diff --git "a/preprocessed (6).csv" "b/preprocessed (6).csv" new file mode 100644--- /dev/null +++ "b/preprocessed (6).csv" @@ -0,0 +1,183518 @@ +query,lang1,lang2 +Level order traversal with direction change after every two levels,"/*JAVA program to print Zig-Zag traversal +in groups of size 2.*/ + +import java.util.*; +class GFG +{ +static final int LEFT = 0; +static final int RIGHT = 1; +static int ChangeDirection(int Dir) +{ +Dir = 1 - Dir; +return Dir; +} +/*A Binary Tree Node*/ + +static class node +{ + int data; + node left, right; +}; +/*Utility function to create a new tree node*/ + +static node newNode(int data) +{ + node temp = new node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/* Function to print the level order of + given binary tree. Direction of printing + level order traversal of binary tree changes + after every two levels */ + +static void modifiedLevelOrder(node root) +{ + if (root == null) + return ; + int dir = LEFT; + node temp; + Queue Q = new LinkedList<>(); + Stack S = new Stack<>(); + S.add(root); +/* Run this while loop till queue got empty*/ + + while (!Q.isEmpty() || !S.isEmpty()) + { + while (!S.isEmpty()) + { + temp = S.peek(); + S.pop(); + System.out.print(temp.data + "" ""); + if (dir == LEFT) + { + if (temp.left != null) + Q.add(temp.left); + if (temp.right != null) + Q.add(temp.right); + } + /* For printing nodes from right to left, + push the nodes to stack + instead of printing them.*/ + + else { + if (temp.right != null) + Q.add(temp.right); + if (temp.left != null) + Q.add(temp.left); + } + } + System.out.println(); +/* for printing the nodes in order + from right to left*/ + + while (!Q.isEmpty()) + { + temp = Q.peek(); + Q.remove(); + System.out.print(temp.data + "" ""); + if (dir == LEFT) { + if (temp.left != null) + S.add(temp.left); + if (temp.right != null) + S.add(temp.right); + } else { + if (temp.right != null) + S.add(temp.right); + if (temp.left != null) + S.add(temp.left); + } + } + System.out.println(); +/* Change the direction of traversal.*/ + + dir = ChangeDirection(dir); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree*/ + + 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.left.left.left = newNode(8); + root.left.left.right = newNode(9); + root.left.right.left = newNode(3); + root.left.right.right = newNode(1); + root.right.left.left = newNode(4); + root.right.left.right = newNode(2); + root.right.right.left = newNode(7); + root.right.right.right = newNode(2); + root.left.right.left.left = newNode(16); + root.left.right.left.right = newNode(17); + root.right.left.right.left = newNode(18); + root.right.right.left.right = newNode(19); + modifiedLevelOrder(root); +} +}", +Smallest of three integers without comparison operators,"/*Java implementation of above approach*/ + +class GFG +{ +static int CHAR_BIT = 8; +/*Function to find minimum of x and y*/ + +static int min(int x, int y) +{ + return y + ((x - y) & ((x - y) >> + ((Integer.SIZE/8) * CHAR_BIT - 1))); +} +/*Function to find minimum of 3 numbers x, y and z*/ + +static int smallest(int x, int y, int z) +{ + return Math.min(x, Math.min(y, z)); +} +/*Driver code*/ + +public static void main (String[] args) +{ + int x = 12, y = 15, z = 5; + System.out.println(""Minimum of 3 numbers is "" + + smallest(x, y, z)); +} +}"," '''Python3 implementation of above approach''' + +CHAR_BIT = 8 + '''Function to find minimum of x and y''' + +def min(x, y): + return y + ((x - y) & \ + ((x - y) >> (32 * CHAR_BIT - 1))) + '''Function to find minimum +of 3 numbers x, y and z''' + +def smallest(x, y, z): + return min(x, min(y, z)) + '''Driver code''' + +x = 12 +y = 15 +z = 5 +print(""Minimum of 3 numbers is "", + smallest(x, y, z))" +Count pairs from two sorted arrays whose sum is equal to a given value x,"/*Java implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value*/ + +import java.io.*; +class GFG { +/* function to count all pairs + from both the sorted arrays + whose sum is equal to a given + value*/ + + static int countPairs(int arr1[], + int arr2[], int m, int n, int x) + { + int count = 0; + int l = 0, r = n - 1; +/* traverse 'arr1[]' from + left to right + traverse 'arr2[]' from + right to left*/ + + while (l < m && r >= 0) + { +/* if this sum is equal + to 'x', then increment 'l', + decrement 'r' and + increment 'count'*/ + + if ((arr1[l] + arr2[r]) == x) + { + l++; r--; + count++; + } +/* if this sum is less + than x, then increment l*/ + + else if ((arr1[l] + arr2[r]) < x) + l++; +/* else decrement 'r'*/ + + else + r--; + } +/* required count of pairs*/ + + return count; + } +/* Driver Code*/ + + public static void main (String[] args) + { + int arr1[] = {1, 3, 5, 7}; + int arr2[] = {2, 3, 5, 8}; + int m = arr1.length; + int n = arr2.length; + int x = 10; + System.out.println( ""Count = "" + + countPairs(arr1, arr2, m, n, x)); + } +}"," '''Python 3 implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value''' + + '''function to count all pairs +from both the sorted arrays +whose sum is equal to a given +value''' + +def countPairs(arr1, arr2, m, n, x): + count, l, r = 0, 0, n - 1 ''' traverse 'arr1[]' from + left to right + traverse 'arr2[]' from + right to left''' + + while (l < m and r >= 0): + ''' if this sum is equal + to 'x', then increment 'l', + decrement 'r' and + increment 'count''' + ''' + if ((arr1[l] + arr2[r]) == x): + l += 1 + r -= 1 + count += 1 + ''' if this sum is less + than x, then increment l''' + + elif ((arr1[l] + arr2[r]) < x): + l += 1 + ''' else decrement 'r''' + ''' + else: + r -= 1 + ''' required count of pairs''' + + return count + '''Driver Code''' + +if __name__ == '__main__': + arr1 = [1, 3, 5, 7] + arr2 = [2, 3, 5, 8] + m = len(arr1) + n = len(arr2) + x = 10 + print(""Count ="", + countPairs(arr1, arr2, + m, n, x))" +Interpolation Search,"/*Java program to implement interpolation +search with recursion*/ + +import java.util.*; +class GFG { +/* If x is present in arr[0..n-1], then returns + index of it, else returns -1.*/ + + public static int interpolationSearch(int arr[], int lo, + int hi, int x) + { + int pos; +/* Since array is sorted, an element + present in array must be in range + defined by corner*/ + + if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { +/* Probing the position with keeping + uniform distribution in mind.*/ + + pos = lo + + (((hi - lo) / (arr[hi] - arr[lo])) + * (x - arr[lo])); +/* Condition of target found*/ + + if (arr[pos] == x) + return pos; +/* If x is larger, x is in right sub array*/ + + if (arr[pos] < x) + return interpolationSearch(arr, pos + 1, hi, + x); +/* If x is smaller, x is in left sub array*/ + + if (arr[pos] > x) + return interpolationSearch(arr, lo, pos - 1, + x); + } + return -1; + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Array of items on which search will + be conducted.*/ + + int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, + 22, 23, 24, 33, 35, 42, 47 }; + int n = arr.length; +/* Element to be searched*/ + + int x = 18; + int index = interpolationSearch(arr, 0, n - 1, x); +/* If element was found*/ + + if (index != -1) + System.out.println(""Element found at index "" + + index); + else + System.out.println(""Element not found.""); + } +}"," '''Python3 program to implement +interpolation search +with recursion''' + + '''If x is present in arr[0..n-1], then +returns index of it, else returns -1.''' + +def interpolationSearch(arr, lo, hi, x): ''' Since array is sorted, an element present + in array must be in range defined by corner''' + + if (lo <= hi and x >= arr[lo] and x <= arr[hi]): + ''' Probing the position with keeping + uniform distribution in mind.''' + + pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * + (x - arr[lo])) + ''' Condition of target found''' + + if arr[pos] == x: + return pos + ''' If x is larger, x is in right subarray''' + + if arr[pos] < x: + return interpolationSearch(arr, pos + 1, + hi, x) + ''' If x is smaller, x is in left subarray''' + + if arr[pos] > x: + return interpolationSearch(arr, lo, + pos - 1, x) + return -1 + '''Driver code''' + '''Array of items in which +search will be conducted''' + +arr = [10, 12, 13, 16, 18, 19, 20, + 21, 22, 23, 24, 33, 35, 42, 47] +n = len(arr) + '''Element to be searched''' + +x = 18 +index = interpolationSearch(arr, 0, n - 1, x) + ''' If element was found''' + +if index != -1: + print(""Element found at index"", index) +else: + print(""Element not found"")" +Check whether Matrix T is a result of one or more 90° rotations of Matrix mat,, +Program to find whether a no is power of two,"/*Java program to efficiently +check for power for 2*/ + +class Test +{ + /* Method to check if x is power of 2*/ + + static boolean isPowerOfTwo (int x) + { + /* First x in the below expression is + for the case when x is 0 */ + + return x!=0 && ((x&(x-1)) == 0); + } +/* Driver method*/ + + public static void main(String[] args) + { + System.out.println(isPowerOfTwo(31) ? ""Yes"" : ""No""); + System.out.println(isPowerOfTwo(64) ? ""Yes"" : ""No""); + } +}"," '''Python program to check if given +number is power of 2 or not''' + + '''Function to check if x is power of 2''' + +def isPowerOfTwo (x): ''' First x in the below expression + is for the case when x is 0''' + + return (x and (not(x & (x - 1))) ) + '''Driver code''' + +if(isPowerOfTwo(31)): + print('Yes') +else: + print('No') +if(isPowerOfTwo(64)): + print('Yes') +else: + print('No')" +Leaders in an array,"/*Java Function to print leaders in an array */ + +class LeadersInArray +{ + void printLeaders(int arr[], int size) + { + for (int i = 0; i < size; i++) + { + int j; + for (j = i + 1; j < size; j++) + { + if (arr[i] <=arr[j]) + break; + }/*the loop didn't break*/ + +if (j == size) + System.out.print(arr[i] + "" ""); + } + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + LeadersInArray lead = new LeadersInArray(); + int arr[] = new int[]{16, 17, 4, 3, 5, 2}; + int n = arr.length; + lead.printLeaders(arr, n); + } +}"," '''Python Function to print leaders in array''' + +def printLeaders(arr,size): + for i in range(0, size): + for j in range(i+1, size): + if arr[i]<=arr[j]: + break + '''If loop didn't break''' + + if j == size-1: + print arr[i], + '''Driver function''' + +arr=[16, 17, 4, 3, 5, 2] +printLeaders(arr, len(arr))" +Convert an Array to a Circular Doubly Linked List,"/*Java program to convert array to +circular doubly linked list*/ + +class GFG +{ + +/*Doubly linked list node*/ + +static class node +{ + int data; + node next; + node prev; +}; + +/*Utility function to create a node in memory*/ + +static node getNode() +{ + return new node(); +} + +/*Function to display the list*/ + +static int displayList( node temp) +{ + node t = temp; + if(temp == null) + return 0; + else + { + System.out.print(""The list is: ""); + + while(temp.next != t) + { + System.out.print(temp.data+"" ""); + temp = temp.next; + } + + System.out.print(temp.data); + + return 1; + } +} + +/*Function to convert array into list*/ + +static node createList(int arr[], int n, node start) +{ +/* Declare newNode and temporary pointer*/ + + node newNode,temp; + int i; + +/* Iterate the loop until array length*/ + + for(i = 0; i < n; i++) + { +/* Create new node*/ + + newNode = getNode(); + +/* Assign the array data*/ + + newNode.data = arr[i]; + +/* If it is first element + Put that node prev and next as start + as it is circular*/ + + if(i == 0) + { + start = newNode; + newNode.prev = start; + newNode.next = start; + } + else + { +/* Find the last node*/ + + temp = (start).prev; + +/* Add the last node to make them + in circular fashion*/ + + temp.next = newNode; + newNode.next = start; + newNode.prev = temp; + temp = start; + temp.prev = newNode; + } + } + return start; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ +/* Array to be converted*/ + + int arr[] = {1,2,3,4,5}; + int n = arr.length; + +/* Start Pointer*/ + + node start = null; + +/* Create the List*/ + + start = createList(arr, n, start); + +/* Display the list*/ + + displayList(start); +} +} + + +"," '''Python3 program to convert array to +circular doubly linked list''' + + + '''Node of the doubly linked list''' + +class Node: + + def __init__(self, data): + self.data = data + self.prev = None + self.next = None + + '''Utility function to create a node in memory''' + +def getNode(): + + return (Node(0)) + + '''Function to display the list''' + +def displayList(temp): + + t = temp + if(temp == None): + return 0 + else: + + print(""The list is: "", end = "" "") + + while(temp.next != t): + + print(temp.data, end = "" "") + temp = temp.next + + print(temp.data) + + return 1 + + '''Function to convert array into list''' + +def createList(arr, n, start): + + ''' Declare newNode and temporary pointer''' + + newNode = None + temp = None + i = 0 + + ''' Iterate the loop until array length''' + + while(i < n): + + ''' Create new node''' + + newNode = getNode() + + ''' Assign the array data''' + + newNode.data = arr[i] + + ''' If it is first element + Put that node prev and next as start + as it is circular''' + + if(i == 0): + + start = newNode + newNode.prev = start + newNode.next = start + + else: + + ''' Find the last node''' + + temp = (start).prev + + ''' Add the last node to make them + in circular fashion''' + + temp.next = newNode + newNode.next = start + newNode.prev = temp + temp = start + temp.prev = newNode + i = i + 1 + return start + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Array to be converted''' + + arr = [1, 2, 3, 4, 5] + n = len(arr) + + ''' Start Pointer''' + + start = None + + ''' Create the List''' + + start = createList(arr, n, start) + + ''' Display the list''' + + displayList(start) + + +" +Deepest left leaf node in a binary tree,"/*A Java program to find +the deepest left leaf +in a binary tree*/ + +/*A Binary Tree node*/ + +class Node +{ + int data; + Node left, right;/* Constructor*/ + + public Node(int data) + { + this.data = data; + left = right = null; + } +} +/*Class to evaluate pass +by reference */ + +class Level +{ +/* maxlevel: gives the + value of level of + maximum left leaf*/ + + int maxlevel = 0; +} +class BinaryTree +{ + Node root; +/* Node to store resultant + node after left traversal*/ + + Node result; +/* A utility function to + find deepest leaf node. + lvl: level of current node. + isLeft: A bool indicate + that this node is left child*/ + + void deepestLeftLeafUtil(Node node, + int lvl, + Level level, + boolean isLeft) + { +/* Base case*/ + + if (node == null) + return; +/* Update result if this node + is left leaf and its level + is more than the maxl level + of the current result*/ + + if (isLeft != false && + node.left == null && + node.right == null && + lvl > level.maxlevel) + { + result = node; + level.maxlevel = lvl; + } +/* Recur for left and right subtrees*/ + + deepestLeftLeafUtil(node.left, lvl + 1, + level, true); + deepestLeftLeafUtil(node.right, lvl + 1, + level, false); + } +/* A wrapper over deepestLeftLeafUtil().*/ + + void deepestLeftLeaf(Node node) + { + Level level = new Level(); + deepestLeftLeafUtil(node, 0, level, false); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.right.left = new Node(5); + tree.root.right.right = new Node(6); + tree.root.right.left.right = new Node(7); + tree.root.right.right.right = new Node(8); + tree.root.right.left.right.left = new Node(9); + tree.root.right.right.right.right = new Node(10); + tree.deepestLeftLeaf(tree.root); + if (tree.result != null) + System.out.println(""The deepest left child""+ + "" is "" + tree.result.data); + else + System.out.println(""There is no left leaf in""+ + "" the given tree""); + } +}"," '''Python program to find the deepest left leaf in a given +Binary tree''' + '''A binary tree node''' + +class Node: + ''' Constructor to create a new node''' + + def __init__(self, val): + self.val = val + self.left = None + self.right = None + '''A utility function to find deepest leaf node. +lvl: level of current node. +maxlvl: pointer to the deepest left leaf node found so far +isLeft: A bool indicate that this node is left child +of its parent +resPtr: Pointer to the result''' + +def deepestLeftLeafUtil(root, lvl, maxlvl, isLeft): + ''' Base CAse''' + + if root is None: + return + ''' Update result if this node is left leaf and its + level is more than the max level of the current result''' + + if(isLeft is True): + if (root.left == None and root.right == None): + if lvl > maxlvl[0] : + deepestLeftLeafUtil.resPtr = root + maxlvl[0] = lvl + return + ''' Recur for left and right subtrees''' + + deepestLeftLeafUtil(root.left, lvl+1, maxlvl, True) + deepestLeftLeafUtil(root.right, lvl+1, maxlvl, False) + '''A wrapper for left and right subtree''' + +def deepestLeftLeaf(root): + maxlvl = [0] + deepestLeftLeafUtil.resPtr = None + deepestLeftLeafUtil(root, 0, maxlvl, False) + return deepestLeftLeafUtil.resPtr + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.right.left = Node(5) +root.right.right = Node(6) +root.right.left.right = Node(7) +root.right.right.right = Node(8) +root.right.left.right.left = Node(9) +root.right.right.right.right= Node(10) +result = deepestLeftLeaf(root) +if result is None: + print ""There is not left leaf in the given tree"" +else: + print ""The deepst left child is"", result.val" +Print unique rows in a given boolean matrix,"/*Given a binary matrix of M X N +of integers, you need to return +only unique rows of binary array */ + +class GFG{ +static int ROW = 4; +static int COL = 5; +/*Function that prints all +unique rows in a given matrix.*/ + +static void findUniqueRows(int M[][]) +{ +/* Traverse through the matrix*/ + + for(int i = 0; i < ROW; i++) + { + int flag = 0; +/* Check if there is similar column + is already printed, i.e if i and + jth column match.*/ + + for(int j = 0; j < i; j++) + { + flag = 1; + for(int k = 0; k < COL; k++) + if (M[i][k] != M[j][k]) + flag = 0; + if (flag == 1) + break; + } +/* If no row is similar*/ + + if (flag == 0) + { +/* Print the row*/ + + for(int j = 0; j < COL; j++) + System.out.print(M[i][j] + "" ""); + System.out.println(); + } + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int M[][] = { { 0, 1, 0, 0, 1 }, + { 1, 0, 1, 1, 0 }, + { 0, 1, 0, 0, 1 }, + { 1, 0, 1, 0, 0 } }; + findUniqueRows(M); +} +}"," '''Given a binary matrix of M X N of +integers, you need to return only +unique rows of binary array''' + +ROW = 4 +COL = 5 + '''The main function that prints +all unique rows in a given matrix.''' + +def findUniqueRows(M): + ''' Traverse through the matrix''' + + for i in range(ROW): + flag = 0 + ''' Check if there is similar column + is already printed, i.e if i and + jth column match.''' + + for j in range(i): + flag = 1 + for k in range(COL): + if (M[i][k] != M[j][k]): + flag = 0 + if (flag == 1): + break + ''' If no row is similar''' + + if (flag == 0): + ''' Print the row''' + + for j in range(COL): + print(M[i][j], end = "" "") + print() + '''Driver Code''' + +if __name__ == '__main__': + M = [ [ 0, 1, 0, 0, 1 ], + [ 1, 0, 1, 1, 0 ], + [ 0, 1, 0, 0, 1 ], + [ 1, 0, 1, 0, 0 ] ] + findUniqueRows(M)" +Delete leaf nodes with value as x,"/*Java code to delete all leaves with given +value. */ + +class GfG { +/*A binary tree node */ + +static class Node { + int data; + Node left, right; +} +/*A utility function to allocate a new node */ + +static Node newNode(int data) +{ + Node newNode = new Node(); + newNode.data = data; + newNode.left = null; + newNode.right = null; + return (newNode); +} + +/*deleteleaves()*/ + +static Node deleteLeaves(Node root, int x) +{ + if (root == null) + return null; + root.left = deleteLeaves(root.left, x); + root.right = deleteLeaves(root.right, x); + if (root.data == x && root.left == null && root.right == null) { + return null; + } + return root; +} /*inorder()*/ + +static void inorder(Node root) +{ + if (root == null) + return; + inorder(root.left); + System.out.print(root.data + "" ""); + inorder(root.right); +} /*Driver program */ + +public static void main(String[] args) +{ + Node root = newNode(10); + root.left = newNode(3); + root.right = newNode(10); + root.left.left = newNode(3); + root.left.right = newNode(1); + root.right.right = newNode(3); + root.right.right.left = newNode(3); + root.right.right.right = newNode(3); + deleteLeaves(root, 3); + System.out.print(""Inorder traversal after deletion : ""); + inorder(root); +} +}"," '''Python3 code to delete all leaves +with given value. ''' + + '''A utility class to allocate a new node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''deleteleaves()''' + +def deleteLeaves(root, x): + if (root == None): + return None + root.left = deleteLeaves(root.left, x) + root.right = deleteLeaves(root.right, x) + if (root.data == x and + root.left == None and + root.right == None): + return None + return root '''inorder()''' + +def inorder(root): + if (root == None): + return + inorder(root.left) + print(root.data, end = "" "") + inorder(root.right) '''Driver Code''' + +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(3) + root.right = newNode(10) + root.left.left = newNode(3) + root.left.right = newNode(1) + root.right.right = newNode(3) + root.right.right.left = newNode(3) + root.right.right.right = newNode(3) + deleteLeaves(root, 3) + print(""Inorder traversal after deletion : "") + inorder(root)" +The Stock Span Problem,"/*Java linear time solution for stock span problem*/ + +import java.util.Stack; +import java.util.Arrays; +public class GFG { +/* A stack based efficient method to calculate + stock span values*/ + + static void calculateSpan(int price[], int n, int S[]) + { +/* Create a stack and push index of first element + to it*/ + + Stack st = new Stack<>(); + st.push(0); +/* Span value of first element is always 1*/ + + S[0] = 1; +/* Calculate span values for rest of the elements*/ + + for (int i = 1; i < n; i++) { +/* Pop elements from stack while stack is not + empty and top of stack is smaller than + price[i]*/ + + while (!st.empty() && price[st.peek()] <= price[i]) + st.pop(); +/* If stack becomes empty, then price[i] is + greater than all elements on left of it, i.e., + price[0], price[1], ..price[i-1]. Else price[i] + is greater than elements after top of stack*/ + + S[i] = (st.empty()) ? (i + 1) : (i - st.peek()); +/* Push this element to stack*/ + + st.push(i); + } + } +/* A utility function to print elements of array*/ + + static void printArray(int arr[]) + { + System.out.print(Arrays.toString(arr)); + } +/* Driver method*/ + + public static void main(String[] args) + { + int price[] = { 10, 4, 5, 90, 120, 80 }; + int n = price.length; + int S[] = new int[n]; +/* Fill the span values in array S[]*/ + + calculateSpan(price, n, S); +/* print the calculated span values*/ + + printArray(S); + } +}"," '''Python linear time solution for stock span problem + ''' '''A stack based efficient method to calculate s''' + +def calculateSpan(price, S): + n = len(price) + ''' Create a stack and push index of fist element to it''' + + st = [] + st.append(0) + ''' Span value of first element is always 1''' + + S[0] = 1 + ''' Calculate span values for rest of the elements''' + + for i in range(1, n): + ''' Pop elements from stack whlie stack is not + empty and top of stack is smaller than price[i]''' + + while( len(st) > 0 and price[st[-1]] <= price[i]): + st.pop() + ''' If stack becomes empty, then price[i] is greater + than all elements on left of it, i.e. price[0], + price[1], ..price[i-1]. Else the price[i] is + greater than elements after top of stack''' + + S[i] = i + 1 if len(st) <= 0 else (i - st[-1]) + ''' Push this element to stack''' + + st.append(i) + '''A utility function to print elements of array''' + +def printArray(arr, n): + for i in range(0, n): + print (arr[i], end ="" "") + '''Driver program to test above function''' + +price = [10, 4, 5, 90, 120, 80] +S = [0 for i in range(len(price)+1)] + '''Fill the span values in array S[]''' + +calculateSpan(price, S) + '''Print the calculated span values''' + +printArray(S, len(price))" +Rotate a matrix by 90 degree in clockwise direction without using any extra space,"import java.io.*; + +class GFG { + +/*rotate function*/ + + + static void rotate(int[][] arr) + { + + int n = arr.length; + /* first rotation + with respect to Secondary diagonal*/ + + 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; + } + } +/* Second rotation + with respect to middle row*/ + + 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; + } + } + } + +/* to print matrix*/ + + static void printMatrix(int arr[][]) + { + int n = arr.length; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + System.out.print(arr[i][j] + "" ""); + System.out.println(); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; + rotate(arr); + printMatrix(arr); + } +} + +", +Find the two numbers with odd occurrences in an unsorted array,, +Game of replacing array elements,"/*Java program for Game of Replacement */ + +import java.util.HashSet; +public class GameOfReplacingArrayElements +{ +/* Function return which player win the game */ + + public static int playGame(int arr[]) + { +/* Create hash that will stores + all distinct element */ + + HashSet set=new HashSet<>(); +/* Traverse an array element */ + + for(int i:arr) + set.add(i); + return (set.size()%2==0)?1:2; + } +/*Driver Function*/ + + public static void main(String args[]) { + int arr[] = { 1, 1, 2, 2, 2, 2 }; + System.out.print(""Player ""+playGame(arr)+"" wins""); + } +}"," '''Python program for Game of Replacement + ''' '''Function return which player win the game ''' + +def playGame(arr, n): + ''' Create hash that will stores + all distinct element ''' + + s = set() + ''' Traverse an array element ''' + + for i in range(n): + s.add(arr[i]) + return 1 if len(s) % 2 == 0 else 2 + '''Driver code''' + +arr = [1, 1, 2, 2, 2, 2] +n = len(arr) +print(""Player"",playGame(arr, n),""Wins"")" +Lowest Common Ancestor in a Binary Tree | Set 1,"/*Java implementation to find lowest common ancestor of +n1 and n2 using one traversal of binary tree*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +public class BinaryTree +{ +/* Root of the Binary Tree*/ + + Node root; + Node findLCA(int n1, int n2) + { + return findLCA(root, n1, n2); + } +/* This function returns pointer to LCA of two given + values n1 and n2. This function assumes that n1 and + n2 are present in Binary Tree*/ + + Node findLCA(Node node, int n1, int n2) + { +/* Base case*/ + + if (node == null) + return null; +/* If either n1 or n2 matches with root's key, report + the presence by returning root (Note that if a key is + ancestor of other, then the ancestor key becomes LCA*/ + + if (node.data == n1 || node.data == n2) + return node; +/* Look for keys in left and right subtrees*/ + + Node left_lca = findLCA(node.left, n1, n2); + Node right_lca = findLCA(node.right, n1, n2); +/* If both of the above calls return Non-NULL, then one key + is present in once subtree and other is present in other, + So this node is the LCA*/ + + if (left_lca!=null && right_lca!=null) + return node; +/* Otherwise check if left subtree or right subtree is LCA*/ + + return (left_lca != null) ? left_lca : right_lca; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + System.out.println(""LCA(4, 5) = "" + + tree.findLCA(4, 5).data); + System.out.println(""LCA(4, 6) = "" + + tree.findLCA(4, 6).data); + System.out.println(""LCA(3, 4) = "" + + tree.findLCA(3, 4).data); + System.out.println(""LCA(2, 4) = "" + + tree.findLCA(2, 4).data); + } +}"," '''Python program to find LCA of n1 and n2 using one +traversal of Binary tree''' + '''A binary tree node''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''This function returns pointer to LCA of two given +values n1 and n2 +This function assumes that n1 and n2 are present in +Binary Tree''' + +def findLCA(root, n1, n2): + ''' Base Case''' + + if root is None: + return None + ''' If either n1 or n2 matches with root's key, report + the presence by returning root (Note that if a key is + ancestor of other, then the ancestor key becomes LCA''' + + if root.key == n1 or root.key == n2: + return root + ''' Look for keys in left and right subtrees''' + + left_lca = findLCA(root.left, n1, n2) + right_lca = findLCA(root.right, n1, n2) + ''' If both of the above calls return Non-NULL, then one key + is present in once subtree and other is present in other, + So this node is the LCA''' + + if left_lca and right_lca: + return root + ''' Otherwise check if left subtree or right subtree is LCA''' + + return left_lca if left_lca is not None else right_lca + '''Driver program to test above function +Let us create a binary tree given in the above example''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) +print ""LCA(4,5) = "", findLCA(root, 4, 5).key +print ""LCA(4,6) = "", findLCA(root, 4, 6).key +print ""LCA(3,4) = "", findLCA(root, 3, 4).key +print ""LCA(2,4) = "", findLCA(root, 2, 4).key" +"Search, insert and delete in a sorted array","/*Java program to insert an +element in a sorted array*/ + +class Main { +/* Inserts a key in arr[] of given + capacity. n is current size of arr[]. + This function returns n+1 if insertion + is successful, else n.*/ + + static int insertSorted(int arr[], int n, int key, int capacity) + { +/* Cannot insert more elements if n is already + more than or equal to capcity*/ + + if (n >= capacity) + return n; + int i; + for (i = n - 1; (i >= 0 && arr[i] > key); i--) + arr[i + 1] = arr[i]; + arr[i + 1] = key; + return (n + 1); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = new int[20]; + arr[0] = 12; + arr[1] = 16; + arr[2] = 20; + arr[3] = 40; + arr[4] = 50; + arr[5] = 70; + int capacity = arr.length; + int n = 6; + int key = 26; + System.out.print(""\nBefore Insertion: ""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); +/* Inserting key*/ + + n = insertSorted(arr, n, key, capacity); + System.out.print(""\nAfter Insertion: ""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +}"," '''Python3 program to implement insert +operation in an sorted array. + ''' '''Inserts a key in arr[] of given capacity. +n is current size of arr[]. This function +returns n+1 if insertion is successful, else n.''' + +def insertSorted(arr, n, key, capacity): + ''' Cannot insert more elements if n is + already more than or equal to capcity''' + + if (n >= capacity): + return n + i = n - 1 + while i >= 0 and arr[i] > key: + arr[i + 1] = arr[i] + i -= 1 + arr[i + 1] = key + return (n + 1) + '''Driver Code''' + +arr = [12, 16, 20, 40, 50, 70] +for i in range(20): + arr.append(0) +capacity = len(arr) +n = 6 +key = 26 +print(""Before Insertion: "", end = "" ""); +for i in range(n): + print(arr[i], end = "" "") + '''Inserting key''' + +n = insertSorted(arr, n, key, capacity) +print(""\nAfter Insertion: "", end = """") +for i in range(n): + print(arr[i], end = "" "")" +Trapping Rain Water,"/*JAVA Code For Trapping Rain Water*/ + +import java.util.*; + +class GFG { + + static int findWater(int arr[], int n) + { +/* initialize output*/ + + int result = 0; + +/* maximum element on left and right*/ + + int left_max = 0, right_max = 0; + +/* indices to traverse the array*/ + + int lo = 0, hi = n - 1; + + while (lo <= hi) { + if (arr[lo] < arr[hi]) { + if (arr[lo] > left_max) + +/* update max in left*/ + + left_max = arr[lo]; + else + +/* water on curr element = + max - curr*/ + + result += left_max - arr[lo]; + lo++; + } + else { + if (arr[hi] > right_max) + +/* update right maximum*/ + + right_max = arr[hi]; + + else + result += right_max - arr[hi]; + hi--; + } + } + + return result; + } + + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = { 0, 1, 0, 2, 1, 0, 1, + 3, 2, 1, 2, 1 }; + int n = arr.length; + + System.out.println(""Maximum water that "" + + ""can be accumulated is "" + + findWater(arr, n)); + } +} + +"," '''Python program to find +maximum amount of water that can +be trapped within given set of bars. +Space Complexity : O(1)''' + + +def findWater(arr, n): + + ''' initialize output''' + + result = 0 + + ''' maximum element on left and right''' + + left_max = 0 + right_max = 0 + + ''' indices to traverse the array''' + + lo = 0 + hi = n-1 + + while(lo <= hi): + + if(arr[lo] < arr[hi]): + + if(arr[lo] > left_max): + + ''' update max in left''' + + left_max = arr[lo] + else: + + ''' water on curr element = max - curr''' + + result += left_max - arr[lo] + lo+= 1 + + else: + + if(arr[hi] > right_max): + ''' update right maximum''' + + right_max = arr[hi] + else: + result += right_max - arr[hi] + hi-= 1 + + return result + + '''Driver program''' + + +arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] +n = len(arr) + +print(""Maximum water that can be accumulated is "", + findWater(arr, n)) + + +" +Custom Tree Problem,"/*Java program to create a custom tree from a given set of links. +The main class that represents tree and has main method*/ + +public class Tree { + private TreeNode root; + /* Returns an array of trees from links input. Links are assumed to + be Strings of the form "" "" where and are starting + and ending points for the link. The returned array is of size 26 + and has non-null values at indexes corresponding to roots of trees + in output */ + + public Tree[] buildFromLinks(String [] links) { +/* Create two arrays for nodes and forest*/ + + TreeNode[] nodes = new TreeNode[26]; + Tree[] forest = new Tree[26]; +/* Process each link */ + + for (String link : links) { +/* Find the two ends of current link*/ + + String[] ends = link.split("" ""); +/*Start node*/ + +int start = (int) (ends[0].charAt(0) - 'a'); +/*End node */ + +int end = (int) (ends[1].charAt(0) - 'a'); +/* If start of link not seen before, add it two both arrays*/ + + if (nodes[start] == null) + { + nodes[start] = new TreeNode((char) (start + 'a')); +/* Note that it may be removed later when this character is + last character of a link. For example, let we first see + a--->b, then c--->a. We first add 'a' to array of trees + and when we see link c--->a, we remove it from trees array.*/ + + forest[start] = new Tree(nodes[start]); + } +/* If end of link is not seen before, add it to the nodes array*/ + + if (nodes[end] == null) + nodes[end] = new TreeNode((char) (end + 'a')); +/* If end of link is seen before, remove it from forest if + it exists there.*/ + + else forest[end] = null; +/* Establish Parent-Child Relationship between Start and End*/ + + nodes[start].addChild(nodes[end], end); + } + return forest; + } +/* Constructor */ + + public Tree(TreeNode root) { this.root = root; } + public static void printForest(String[] links) + { + Tree t = new Tree(new TreeNode('\0')); + for (Tree t1 : t.buildFromLinks(links)) { + if (t1 != null) + { + t1.root.printTreeIdented(""""); + System.out.println(""""); + } + } + } +/* Driver method to test*/ + + public static void main(String[] args) { + String [] links1 = {""a b"", ""b c"", ""b d"", ""a e""}; + System.out.println(""------------ Forest 1 ----------------""); + printForest(links1); + String [] links2 = {""a b"", ""a g"", ""b c"", ""c d"", ""d e"", ""c f"", + ""z y"", ""y x"", ""x w""}; + System.out.println(""------------ Forest 2 ----------------""); + printForest(links2); + } +} +/*Class to represent a tree node*/ + +class TreeNode { + TreeNode []children; + char c; +/* Adds a child 'n' to this node*/ + + public void addChild(TreeNode n, int index) { this.children[index] = n;} +/* Constructor*/ + + public TreeNode(char c) { this.c = c; this.children = new TreeNode[26];} +/* Recursive method to print indented tree rooted with this node.*/ + + public void printTreeIdented(String indent) { + System.out.println(indent + ""-->"" + c); + for (TreeNode child : children) { + if (child != null) + child.printTreeIdented(indent + "" |""); + } + } +}", +Print nodes at k distance from root | Iterative,"/*Java program to print all nodes of level k +iterative approach*/ + +import java.util.*; +class GFG +{ + +/*Node of binary tree*/ + +static class Node +{ + int data; + Node left, right; +} + +/*Function to add a new node*/ + +static Node newNode(int data) +{ + Node newnode = new Node(); + newnode.data = data; + newnode.left = newnode.right = null; + return newnode; +} + +/*Function to print nodes of given level*/ + +static boolean printKDistant(Node root, int klevel) +{ + Queue q = new LinkedList<>(); + int level = 1; + boolean flag = false; + q.add(root); + +/* extra null is added to keep track + of all the nodes to be added before + level is incremented by 1*/ + + q.add(null); + while (q.size() > 0) + { + Node temp = q.peek(); + +/* print when level is equal to k*/ + + if (level == klevel && temp != null) + { + flag = true; + System.out.print( temp.data + "" ""); + } + q.remove(); + if (temp == null) + { + if (q.peek() != null) + q.add(null); + level += 1; + +/* break the loop if level exceeds + the given level number*/ + + if (level > klevel) + break; + } + else + { + if (temp.left != null) + q.add(temp.left); + + if (temp.right != null) + q.add(temp.right); + } + } + System.out.println(); + return flag; +} + +/*Driver code*/ + +public static void main(String srga[]) +{ +/* create a binary tree*/ + + 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); + + System.out.print( ""data at level 1 : ""); + boolean ret = printKDistant(root, 1); + if (ret == false) + System.out.print( ""Number exceeds total "" + + ""number of levels\n""); + + System.out.print(""data at level 2 : ""); + ret = printKDistant(root, 2); + if (ret == false) + System.out.print(""Number exceeds total "" + + ""number of levels\n""); + + System.out.print( ""data at level 3 : ""); + ret = printKDistant(root, 3); + if (ret == false) + System.out.print(""Number exceeds total "" + + ""number of levels\n""); + + System.out.print( ""data at level 6 : ""); + ret = printKDistant(root, 6); + if (ret == false) + System.out.print( ""Number exceeds total"" + + ""number of levels\n""); + +} +} + + +"," '''Python3 program to print all nodes of level k +iterative approach''' + + '''Node of binary tree +Function to add a new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + + '''Function to prnodes of given level''' + +def printKDistant( root, klevel): + + q = [] + level = 1 + flag = False + q.append(root) + + ''' extra None is appended to keep track + of all the nodes to be appended + before level is incremented by 1''' + + q.append(None) + while (len(q)): + temp = q[0] + + ''' prwhen level is equal to k''' + + if (level == klevel and temp != None): + flag = True + print(temp.data, end = "" "") + + q.pop(0) + if (temp == None) : + if (len(q)): + q.append(None) + level += 1 + + ''' break the loop if level exceeds + the given level number''' + + if (level > klevel) : + break + else: + if (temp.left) : + q.append(temp.left) + + if (temp.right) : + q.append(temp.right) + print() + + return flag + + '''Driver Code''' + +if __name__ == '__main__': + + + + ''' create a binary tree''' + + 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) + + print(""data at level 1 : "", end = """") + ret = printKDistant(root, 1) + if (ret == False): + print(""Number exceeds total"", + ""number of levels"") + + print(""data at level 2 : "", end = """") + ret = printKDistant(root, 2) + if (ret == False) : + print(""Number exceeds total"", + ""number of levels"") + + print(""data at level 3 : "", end = """") + ret = printKDistant(root, 3) + if (ret == False) : + print(""Number exceeds total"", + ""number of levels"") + + print(""data at level 6 : "", end = """") + ret = printKDistant(root, 6) + if (ret == False): + print(""Number exceeds total number of levels"")" +Count set bits in an integer,"/*Java implementation for recursive +approach to find the number of set +bits using Brian Kernighan Algorithm*/ + +import java.io.*; +class GFG { +/* recursive function to count set bits*/ + + public static int countSetBits(int n) + { +/* base case*/ + + if (n == 0) + return 0; + else + return 1 + countSetBits(n & (n - 1)); + } +/* Driver function*/ + + public static void main(String[] args) + { +/* get value from user*/ + + int n = 9; +/* function calling*/ + + System.out.println(countSetBits(n)); + } +}"," '''Python3 implementation for +recursive approach to find +the number of set bits using +Brian Kernighan’s Algorithm''' + + '''recursive function to count +set bits''' + +def countSetBits(n): ''' base case''' + + if (n == 0): + return 0 + else: + return 1 + countSetBits(n & (n - 1)) + '''Get value from user''' + +n = 9 + '''function calling''' + +print(countSetBits(n))" +Inorder predecessor and successor for a given key in BST | Iterative Approach,"/*Java program to find predecessor +and successor in a BST*/ + +import java.util.*; +class GFG +{ +/*BST Node*/ + +static class Node +{ + int key; + Node left, right; +}; +static Node pre; +static Node suc; +/*Function that finds predecessor +and successor of key in BST.*/ + +static void findPreSuc(Node root, int key) +{ + if (root == null) + return; +/* Search for given key in BST.*/ + + while (root != null) + { +/* If root is given key.*/ + + if (root.key == key) + { +/* the minimum value in right subtree + is successor.*/ + + if (root.right != null) + { + suc = root.right; + while (suc.left != null) + suc = suc.left; + } +/* the maximum value in left subtree + is predecessor.*/ + + if (root.left != null) + { + pre = root.left; + while (pre.right != null) + pre = pre.right; + } + return; + } +/* If key is greater than root, then + key lies in right subtree. Root + could be predecessor if left + subtree of key is null.*/ + + else if (root.key < key) + { + pre = root; + root = root.right; + } +/* If key is smaller than root, then + key lies in left subtree. Root + could be successor if right + subtree of key is null.*/ + + else + { + suc = root; + root = root.left; + } + } +} +/*A utility function to create a new BST node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.key = item; + temp.left = temp.right = null; + return temp; +} +/*A utility function to insert +a new node with given key in BST*/ + +static Node insert(Node node, int key) +{ + if (node == null) + return newNode(key); + if (key < node.key) + node.left = insert(node.left, key); + else + node.right = insert(node.right, key); + return node; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/*Key to be searched in BST*/ + +int key = 65; + /* Let us create following BST + 50 + / \ + / \ + 30 70 + / \ / \ + / \ / \ + 20 40 60 80 + */ + + Node root = null; + root = insert(root, 50); + insert(root, 30); + insert(root, 20); + insert(root, 40); + insert(root, 70); + insert(root, 60); + insert(root, 80); + findPreSuc(root, key); + if (pre != null) + System.out.println(""Predecessor is "" + + pre.key); + else + System.out.print(""-1""); + if (suc != null) + System.out.print(""Successor is "" + suc.key); + else + System.out.print(""-1""); + } +}"," '''Python3 program to find predecessor +and successor in a BST''' + + '''Function that finds predecessor and +successor of key in BST.''' + +def findPreSuc(root, pre, suc, key): + if root == None: + return + ''' Search for given key in BST.''' + + while root != None: + ''' If root is given key.''' + + if root.key == key: + ''' the minimum value in right + subtree is predecessor.''' + + if root.right: + suc[0] = root.right + while suc[0].left: + suc[0] = suc[0].left + ''' the maximum value in left + subtree is successor.''' + + if root.left: + pre[0] = root.left + while pre[0].right: + pre[0] = pre[0].right + return + ''' If key is greater than root, then + key lies in right subtree. Root + could be predecessor if left + subtree of key is null.''' + + elif root.key < key: + pre[0] = root + root = root.right + ''' If key is smaller than root, then + key lies in left subtree. Root + could be successor if right + subtree of key is null.''' + + else: + suc[0] = root + root = root.left + '''A utility function to create a +new BST node''' + +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + '''A utility function to insert +a new node with given key in BST''' + +def insert(node, key): + if node == None: + return newNode(key) + if key < node.key: + node.left = insert(node.left, key) + else: + node.right = insert(node.right, key) + return node + '''Driver Code''' + +if __name__ == '__main__': + '''Key to be searched in BST''' + + key = 65 + ''' Let us create following BST + 50 + / \ + / \ + 30 70 + / \ / \ + / \ / \ + 20 40 60 80''' + + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + pre, suc = [None], [None] + findPreSuc(root, pre, suc, key) + if pre[0] != None: + print(""Predecessor is"", pre[0].key) + else: + print(""-1"") + if suc[0] != None: + print(""Successor is"", suc[0].key) + else: + print(""-1"")" +Program for nth Catalan Number,"/* A dynamic programming based function to find nth + Catalan number*/ +class GFG { + static int catalanDP(int n) + { +/* Table to store results of subproblems*/ + + int catalan[] = new int[n + 2]; +/* Initialize first two values in table*/ + + catalan[0] = 1; + catalan[1] = 1; +/* Fill entries in catalan[] + using recursive formula*/ + + for (int i = 2; i <= n; i++) { + catalan[i] = 0; + for (int j = 0; j < i; j++) { + catalan[i] + += catalan[j] * catalan[i - j - 1]; + } + } +/* Return last entry*/ + + return catalan[n]; + } +/* Driver code*/ + + public static void main(String[] args) + { + for (int i = 0; i < 10; i++) { + System.out.print(catalanDP(i) + "" ""); + } + } +}"," '''A dynamic programming based function to find nth +Catalan number''' + +def catalan(n): + if (n == 0 or n == 1): + return 1 + ''' Table to store results of subproblems''' + + catalan =[0]*(n+1) + ''' Initialize first two values in table''' + + catalan[0] = 1 + catalan[1] = 1 + ''' Fill entries in catalan[] + using recursive formula''' + + for i in range(2, n + 1): + for j in range(i): + catalan[i] += catalan[j]* catalan[i-j-1] + ''' Return last entry''' + + return catalan[n] + '''Driver code''' + +for i in range(10): + print(catalan(i), end="" "")" +Types of Linked List,"/*Node of a doubly linked list*/ + +static class Node +{ + int data; + Node next; +}; +"," '''structure of Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None +" +Floor and Ceil from a BST,"/*Java program to find ceil of a given value in BST*/ + +/* A binary tree node has key, left child and right child */ + +class Node { + int data; + Node left, right; + Node(int d) + { + data = d; + left = right = null; + } +} +class BinaryTree { + Node root; +/* Function to find ceil of a given input in BST. + If input is more than the max key in BST, + return -1*/ + + int Ceil(Node node, int input) + { +/* Base case*/ + + if (node == null) { + return -1; + } +/* We found equal key*/ + + if (node.data == input) { + return node.data; + } +/* If root's key is smaller, + ceil must be in right subtree*/ + + if (node.data < input) { + return Ceil(node.right, input); + } +/* Else, either left subtree or root + has the ceil value*/ + + int ceil = Ceil(node.left, input); + return (ceil >= input) ? ceil : node.data; + } +/* Driver Code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(8); + tree.root.left = new Node(4); + tree.root.right = new Node(12); + tree.root.left.left = new Node(2); + tree.root.left.right = new Node(6); + tree.root.right.left = new Node(10); + tree.root.right.right = new Node(14); + for (int i = 0; i < 16; i++) { + System.out.println(i + "" "" + tree.Ceil(tree.root, i)); + } + } +}"," '''Python program to find ceil of a given value in BST''' + + '''A Binary tree node''' + +class Node: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + '''Function to find ceil of a given input in BST. If input +is more than the max key in BST, return -1''' + +def ceil(root, inp): + ''' Base Case''' + + if root == None: + return -1 + ''' We found equal key''' + + if root.key == inp : + return root.key + ''' If root's key is smaller, ceil must be in right subtree''' + + if root.key < inp: + return ceil(root.right, inp) + ''' Else, either left subtre or root has the ceil value''' + + val = ceil(root.left, inp) + return val if val >= inp else root.key + '''Driver program to test above function''' + +root = Node(8) +root.left = Node(4) +root.right = Node(12) +root.left.left = Node(2) +root.left.right = Node(6) +root.right.left = Node(10) +root.right.right = Node(14) +for i in range(16): + print ""% d % d"" %(i, ceil(root, i))" +Collect maximum points in a grid using two traversals,"/*A Memoization based program to find maximum collection +using two traversals of a grid*/ + +class GFG +{ +static final int R = 5; +static final int C = 4; +/*checks whether a given input is valid or not*/ + +static boolean isValid(int x, int y1, int y2) +{ + return (x >= 0 && x < R && y1 >=0 && + y1 < C && y2 >=0 && y2 < C); +} +/*Driver function to collect Math.max value*/ + +static int getMaxUtil(int arr[][], int mem[][][], + int x, int y1, int y2) +{ + /*---------- BASE CASES -----------*/ + +/* if P1 or P2 is at an invalid cell*/ + + if (!isValid(x, y1, y2)) return Integer.MIN_VALUE; +/* if both traversals reach their destinations*/ + + if (x == R-1 && y1 == 0 && y2 == C-1) + return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; +/* If both traversals are at last + row but not at their destination*/ + + if (x == R-1) return Integer.MIN_VALUE; +/* If subproblem is already solved*/ + + if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; +/* Initialize answer for this subproblem*/ + + int ans = Integer.MIN_VALUE; +/* this variable is used to store + gain of current cell(s)*/ + + int temp = (y1 == y2)? arr[x][y1]: + arr[x][y1] + arr[x][y2]; + /* Recur for all possible cases, then store + and return the one with max value */ + + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1, y2-1)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1, y2+1)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1, y2)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1-1, y2)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1+1, y2)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); + ans = Math.max(ans, temp + + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); + return (mem[x][y1][y2] = ans); +} +/*This is mainly a wrapper over recursive +function getMaxUtil(). This function +creates a table for memoization and +calls getMaxUtil()*/ + +static int geMaxCollection(int arr[][]) +{ +/* Create a memoization table and + initialize all entries as -1*/ + + int [][][]mem = new int[R][C][C]; + for(int i = 0; i < R; i++) + { + for(int j = 0; j < C; j++) + { + for(int l = 0; l < C; l++) + mem[i][j][l]=-1; + } + } +/* Calculation maximum value using memoization + based function getMaxUtil()*/ + + return getMaxUtil(arr, mem, 0, 0, C-1); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[][] = {{3, 6, 8, 2}, + {5, 2, 4, 3}, + {1, 1, 20, 10}, + {1, 1, 20, 10}, + {1, 1, 20, 10}, + }; + System.out.print(""Maximum collection is "" + + geMaxCollection(arr)); + } +}"," '''A Memoization based program to find maximum collection +using two traversals of a grid''' + +R=5 +C=4 +intmin=-10000000 +intmax=10000000 + '''checks whether a given input is valid or not''' + +def isValid(x,y1,y2): + return ((x >= 0 and x < R and y1 >=0 + and y1 < C and y2 >=0 and y2 < C)) + '''Driver function to collect max value''' + +def getMaxUtil(arr,mem,x,y1,y2): + ''' ---------- BASE CASES -----------''' + + + ''' if P1 or P2 is at an invalid cell''' + + if isValid(x, y1, y2)==False: + return intmin ''' if both traversals reach their destinations''' + + if x == R-1 and y1 == 0 and y2 == C-1: + if y1==y2: + return arr[x][y1] + else: + return arr[x][y1]+arr[x][y2] + ''' If both traversals are at last row + but not at their destination''' + + if x==R-1: + return intmin + ''' If subproblem is already solved''' + + if mem[x][y1][y2] != -1: + return mem[x][y1][y2] + ''' Initialize answer for this subproblem''' + + ans=intmin + ''' this variable is used to store gain of current cell(s)''' + + temp=0 + if y1==y2: + temp=arr[x][y1] + else: + temp=arr[x][y1]+arr[x][y2] + ''' Recur for all possible cases, then store and return the + one with max value''' + + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)) + ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)) + mem[x][y1][y2] = ans + return ans + '''This is mainly a wrapper over recursive +function getMaxUtil(). +This function creates a table for memoization and calls +getMaxUtil()''' + +def geMaxCollection(arr): + ''' Create a memoization table and + initialize all entries as -1''' + + mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)] + ''' Calculation maximum value using + memoization based function + getMaxUtil()''' + + return getMaxUtil(arr, mem, 0, 0, C-1) + '''Driver program to test above functions''' + +if __name__=='__main__': + arr=[[3, 6, 8, 2], + [5, 2, 4, 3], + [1, 1, 20, 10], + [1, 1, 20, 10], + [1, 1, 20, 10], + ] + print('Maximum collection is ', geMaxCollection(arr))" +Insertion Sort for Singly Linked List,"/*Java program to sort link list +using insertion sort*/ + +public class LinkedlistIS +{ + node head; + node sorted; + class node + { + int val; + node next; + public node(int val) + { + this.val = val; + } + } + + /*A utility function to insert a node +at the beginning of linked list*/ + + void push(int val) + {/* allocate node */ + + node newnode = new node(val); + /* link the old list off the new node */ + + newnode.next = head; + /* move the head to point to the new node */ + + head = newnode; + } +/* function to sort a singly linked list using insertion sort*/ + + void insertionSort(node headref) + { +/* Initialize sorted linked list*/ + + sorted = null; + node current = headref; +/* Traverse the given linked list and insert every + node to sorted*/ + + while (current != null) + { +/* Store next for next iteration*/ + + node next = current.next; +/* insert current in sorted linked list*/ + + sortedInsert(current); +/* Update current*/ + + current = next; + } +/* Update head_ref to point to sorted linked list*/ + + head = sorted; + } + /* + * function to insert a new_node in a list. Note that + * this function expects a pointer to head_ref as this + * can modify the head of the input linked list + * (similar to push()) + */ + + void sortedInsert(node newnode) + { + /* Special case for the head end */ + + if (sorted == null || sorted.val >= newnode.val) + { + newnode.next = sorted; + sorted = newnode; + } + else + { + node current = sorted; + /* Locate the node before the point of insertion */ + + while (current.next != null && current.next.val < newnode.val) + { + current = current.next; + } + newnode.next = current.next; + current.next = newnode; + } + } + /* Function to print linked list */ + + void printlist(node head) + { + while (head != null) + { + System.out.print(head.val + "" ""); + head = head.next; + } + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + LinkedlistIS list = new LinkedlistIS(); + list.push(5); + list.push(20); + list.push(4); + list.push(3); + list.push(30); + System.out.println(""Linked List before Sorting..""); + list.printlist(list.head); + list.insertionSort(list.head); + System.out.println(""\nLinkedList After sorting""); + list.printlist(list.head); + } +}"," '''Pyhton implementation of above algorithm''' +class Node: + def __init__(self, data): + self.data = data + self.next = None '''A utility function to insert a node +at the beginning of linked list''' + +def push( head_ref, new_data): + ''' allocate node''' + + new_node = Node(0) + new_node.data = new_data + ''' link the old list off the new node''' + + new_node.next = (head_ref) + ''' move the head to point to the new node''' + + (head_ref) = new_node + return head_ref + '''function to sort a singly linked list using insertion sort''' + +def insertionSort(head_ref): + ''' Initialize sorted linked list''' + + sorted = None + ''' Traverse the given linked list and insert every + node to sorted''' + + current = head_ref + while (current != None): + ''' Store next for next iteration''' + + next = current.next + ''' insert current in sorted linked list''' + + sorted = sortedInsert(sorted, current) + ''' Update current''' + + current = next + ''' Update head_ref to point to sorted linked list''' + + head_ref = sorted + return head_ref + '''function to insert a new_node in a list. Note that this +function expects a pointer to head_ref as this can modify the +head of the input linked list (similar to push())''' + +def sortedInsert(head_ref, new_node): + current = None + ''' Special case for the head end */''' + + if (head_ref == None or (head_ref).data >= new_node.data): + new_node.next = head_ref + head_ref = new_node + else: + current = head_ref ''' Locate the node before the point of insertion''' + + + while (current.next != None and + current.next.data < new_node.data): + current = current.next + new_node.next = current.next + current.next = new_node + return head_ref + '''BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert +Function to print linked list */''' + +def printList(head): + temp = head + while(temp != None): + print( temp.data, end = "" "") + temp = temp.next + '''Driver program to test above functions''' + +a = None +a = push(a, 5) +a = push(a, 20) +a = push(a, 4) +a = push(a, 3) +a = push(a, 30) +print(""Linked List before sorting "") +printList(a) +a = insertionSort(a) +print(""\nLinked List after sorting "") +printList(a)" +Find common elements in three sorted arrays,"/*Java program to find common elements in three arrays*/ + +class FindCommon +{ +/* This function prints common elements in ar1*/ + + void findCommon(int ar1[], int ar2[], int ar3[]) + { +/* Initialize starting indexes for ar1[], ar2[] and ar3[]*/ + + int i = 0, j = 0, k = 0; +/* Iterate through three arrays while all arrays have elements*/ + + while (i < ar1.length && j < ar2.length && k < ar3.length) + { +/* If x = y and y = z, print any of them and move ahead + in all arrays*/ + + if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) + { System.out.print(ar1[i]+"" ""); i++; j++; k++; } +/* x < y*/ + + else if (ar1[i] < ar2[j]) + i++; +/* y < z*/ + + else if (ar2[j] < ar3[k]) + j++; +/* We reach here when x > y and z < y, i.e., z is smallest*/ + + else + k++; + } + } +/* Driver code to test above*/ + + public static void main(String args[]) + { + FindCommon ob = new FindCommon(); + int ar1[] = {1, 5, 10, 20, 40, 80}; + int ar2[] = {6, 7, 20, 80, 100}; + int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}; + System.out.print(""Common elements are ""); + ob.findCommon(ar1, ar2, ar3); + } +}"," '''Python function to print common elements in three sorted arrays''' + '''This function prints common elements in ar1''' + +def findCommon(ar1, ar2, ar3, n1, n2, n3): ''' Initialize starting indexes for ar1[], ar2[] and ar3[]''' + + i, j, k = 0, 0, 0 + ''' Iterate through three arrays while all arrays have elements ''' + + while (i < n1 and j < n2 and k< n3): + ''' If x = y and y = z, print any of them and move ahead + in all arrays''' + + if (ar1[i] == ar2[j] and ar2[j] == ar3[k]): + print ar1[i], + i += 1 + j += 1 + k += 1 + ''' x < y ''' + + elif ar1[i] < ar2[j]: + i += 1 + ''' y < z ''' + + elif ar2[j] < ar3[k]: + j += 1 + ''' We reach here when x > y and z < y, i.e., z is smallest ''' + + else: + k += 1 + '''Driver program to check above function''' + +ar1 = [1, 5, 10, 20, 40, 80] +ar2 = [6, 7, 20, 80, 100] +ar3 = [3, 4, 15, 20, 30, 70, 80, 120] +n1 = len(ar1) +n2 = len(ar2) +n3 = len(ar3) +print ""Common elements are"", +findCommon(ar1, ar2, ar3, n1, n2, n3)" +Rearrange an array in maximum minimum form | Set 1,"/*Java program to rearrange an array in minimum +maximum form*/ + +import java.util.Arrays; +public class GFG +{ +/* Prints max at first position, min at second position + second max at third position, second min at fourth + position and so on.*/ + + static void rearrange(int[] arr, int n) + { +/* Auxiliary array to hold modified array*/ + + int temp[] = arr.clone(); +/* Indexes of smallest and largest elements + from remaining array.*/ + + int small = 0, large = n - 1; +/* To indicate whether we need to copy rmaining + largest or remaining smallest at next position*/ + + boolean flag = true; +/* Store result in temp[]*/ + + for (int i = 0; i < n; i++) { + if (flag) + arr[i] = temp[large--]; + else + arr[i] = temp[small++]; + flag = !flag; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = new int[] { 1, 2, 3, 4, 5, 6 }; + System.out.println(""Original Array ""); + System.out.println(Arrays.toString(arr)); + rearrange(arr, arr.length); + System.out.println(""Modified Array ""); + System.out.println(Arrays.toString(arr)); + } +}"," '''Python program to rearrange an array in minimum +maximum form + ''' '''Prints max at first position, min at second position +second max at third position, second min at fourth +position and so on.''' + +def rearrange(arr, n): + ''' Auxiliary array to hold modified array''' + + temp = n*[None] + ''' Indexes of smallest and largest elements + from remaining array.''' + + small, large = 0, n-1 + ''' To indicate whether we need to copy rmaining + largest or remaining smallest at next position''' + + flag = True + ''' Store result in temp[]''' + + for i in range(n): + if flag is True: + temp[i] = arr[large] + large -= 1 + else: + temp[i] = arr[small] + small += 1 + flag = bool(1-flag) + ''' Copy temp[] to arr[]''' + + for i in range(n): + arr[i] = temp[i] + return arr + '''Driver code''' + +arr = [1, 2, 3, 4, 5, 6] +n = len(arr) +print(""Original Array"") +print(arr) +print(""Modified Array"") +print(rearrange(arr, n))" +Doubly Linked List | Set 1 (Introduction and Insertion),"/*Adding a node at the front of the list*/ + +public void push(int new_data) +{ + /* 1. allocate node + * 2. put in the data */ + + Node new_Node = new Node(new_data); + + /* 3. Make next of new node as head and previous as NULL */ + + new_Node.next = head; + new_Node.prev = null; + + /* 4. change prev of head node to new node */ + + if (head != null) + head.prev = new_Node; + + /* 5. move the head to point to the new node */ + + head = new_Node; +} +"," '''Adding a node at the front of the list''' + +def push(self, new_data): + + ''' 1 & 2: Allocate the Node & Put in the data''' + + new_node = Node(data = new_data) + + ''' 3. Make next of new node as head and previous as NULL''' + + new_node.next = self.head + new_node.prev = None + + ''' 4. change prev of head node to new node''' + + if self.head is not None: + self.head.prev = new_node + + ''' 5. move the head to point to the new node''' + + self.head = new_node + + +" +Level order traversal with direction change after every two levels,"/*Java program to print Zig-Zag traversal +in groups of size 2.*/ + +import java.util.*; +class GFG +{ +/*A Binary Tree Node*/ + +static class Node +{ + Node left; + int data; + Node right; +}; +/* Function to print the level order of +given binary tree. Direction of printing +level order traversal of binary tree changes +after every two levels */ + +static void modifiedLevelOrder(Node node) +{ +/* For null root*/ + + if (node == null) + return; + if (node.left == null && node.right == null) + { + System.out.print(node.data); + return; + } +/* Maintain a queue for normal + level order traversal*/ + + Queue myQueue = new LinkedList<>(); + /* Maintain a stack for + printing nodes in reverse + order after they are popped + out from queue.*/ + + Stack myStack = new Stack<>(); + Node temp = null; +/* sz is used for storing + the count of nodes in a level*/ + + int sz; +/* Used for changing the direction + of level order traversal*/ + + int ct = 0; +/* Used for changing the direction + of level order traversal*/ + + boolean rightToLeft = false; +/* Push root node to the queue*/ + + myQueue.add(node); +/* Run this while loop till queue got empty*/ + + while (!myQueue.isEmpty()) + { + ct++; + sz = myQueue.size(); +/* Do a normal level order traversal*/ + + for (int i = 0; i < sz; i++) + { + temp = myQueue.peek(); + myQueue.remove(); + /*For printing nodes from left to right, + simply print the nodes in the order in which + they are being popped out from the queue.*/ + + if (rightToLeft == false) + System.out.print(temp.data + "" ""); + /* For printing nodes from right to left, + push the nodes to stack instead of printing them.*/ + + else + myStack.push(temp); + if (temp.left != null) + myQueue.add(temp.left); + if (temp.right != null) + myQueue.add(temp.right); + } + if (rightToLeft == true) + { +/* for printing the nodes in order + from right to left*/ + + while (!myStack.isEmpty()) + { + temp = myStack.peek(); + myStack.pop(); + System.out.print(temp.data + "" ""); + } + } + /*Change the direction of printing + nodes after every two levels.*/ + + if (ct == 2) + { + rightToLeft = !rightToLeft; + ct = 0; + } + System.out.print(""\n""); + } +} +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree*/ + + 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.left.left.left = newNode(8); + root.left.left.right = newNode(9); + root.left.right.left = newNode(3); + root.left.right.right = newNode(1); + root.right.left.left = newNode(4); + root.right.left.right = newNode(2); + root.right.right.left = newNode(7); + root.right.right.right = newNode(2); + root.left.right.left.left = newNode(16); + root.left.right.left.right = newNode(17); + root.right.left.right.left = newNode(18); + root.right.right.left.right = newNode(19); + modifiedLevelOrder(root); +} +}"," '''A Binary Tree Node''' + +from collections import deque +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + '''/* Function to prthe level order of + given binary tree. Direction of printing + level order traversal of binary tree changes + after every two levels */''' + +def modifiedLevelOrder(node): + ''' For null root''' + + if (node == None): + return + if (node.left == None and node.right == None): + print(node.data, end = "" "") + return + ''' Maintain a queue for normal + level order traversal''' + + myQueue = deque() + ''' /* Maintain a stack for printing nodes in reverse + order after they are popped out from queue.*/''' + + myStack = [] + temp = None + ''' sz is used for storing the count + of nodes in a level''' + + sz = 0 + ''' Used for changing the direction + of level order traversal''' + + ct = 0 + ''' Used for changing the direction + of level order traversal''' + + rightToLeft = False + ''' Push root node to the queue''' + + myQueue.append(node) + ''' Run this while loop till queue got empty''' + + while (len(myQueue) > 0): + ct += 1 + sz = len(myQueue) + ''' Do a normal level order traversal''' + + for i in range(sz): + temp = myQueue.popleft() + ''' /*For printing nodes from left to right, + simply prthe nodes in the order in which + they are being popped out from the queue.*/''' + + if (rightToLeft == False): + print(temp.data,end="" "") + ''' /* For printing nodes + from right to left, + push the nodes to stack + instead of printing them.*/''' + + else: + myStack.append(temp) + if (temp.left): + myQueue.append(temp.left) + if (temp.right): + myQueue.append(temp.right) + if (rightToLeft == True): + ''' for printing the nodes in order + from right to left''' + + while (len(myStack) > 0): + temp = myStack[-1] + del myStack[-1] + print(temp.data, end = "" "") + ''' /*Change the direction of printing + nodes after every two levels.*/''' + + if (ct == 2): + rightToLeft = not rightToLeft + ct = 0 + print() + '''Driver program to test above functions''' + +if __name__ == '__main__': + ''' Let us create binary tree''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.left.left.left = Node(8) + root.left.left.right = Node(9) + root.left.right.left = Node(3) + root.left.right.right = Node(1) + root.right.left.left = Node(4) + root.right.left.right = Node(2) + root.right.right.left = Node(7) + root.right.right.right = Node(2) + root.left.right.left.left = Node(16) + root.left.right.left.right = Node(17) + root.right.left.right.left = Node(18) + root.right.right.left.right = Node(19) + modifiedLevelOrder(root)" +Find top three repeated in array,"/*Java Program to Find the top three repeated numbers*/ + +import java.io.*; +import java.util.*; +/*User defined Pair class*/ + +class Pair { + int first, second; +} +class GFG { +/* Function to print top three repeated numbers*/ + + static void top3Repeated(int[] arr, int n) + { +/* There should be atleast two elements*/ + + if (n < 3) { + System.out.print(""Invalid Input""); + return; + } +/* Count Frequency of each element*/ + + TreeMap freq = new TreeMap<>(); + for (int i = 0; i < n; i++) + if (freq.containsKey(arr[i])) + freq.put(arr[i], 1 + freq.get(arr[i])); + else + freq.put(arr[i], 1); +/* Initialize first value of each variable + of Pair type is INT_MIN*/ + + Pair x = new Pair(); + Pair y = new Pair(); + Pair z = new Pair(); + x.first = y.first = z.first = Integer.MIN_VALUE; + for (Map.Entry curr : freq.entrySet()) { +/* If frequency of current element + is not zero and greater than + frequency of first largest element*/ + + if (Integer.parseInt(String.valueOf(curr.getValue())) > x.first) { +/* Update second and third largest*/ + + z.first = y.first; + z.second = y.second; + y.first = x.first; + y.second = x.second; +/* Modify values of x Number*/ + + x.first = Integer.parseInt(String.valueOf(curr.getValue())); + x.second = Integer.parseInt(String.valueOf(curr.getKey())); + } +/* If frequency of current element is + not zero and frequency of current + element is less than frequency of + first largest element, but greater + than y element*/ + + else if (Integer.parseInt(String.valueOf(curr.getValue())) > y.first) { +/* Modify values of third largest*/ + + z.first = y.first; + z.second = y.second; +/* Modify values of second largest*/ + + y.first = Integer.parseInt(String.valueOf(curr.getValue())); + y.second = Integer.parseInt(String.valueOf(curr.getKey())); + } +/* If frequency of current element + is not zero and frequency of + current element is less than + frequency of first element and + second largest, but greater than + third largest.*/ + + else if (Integer.parseInt(String.valueOf(curr.getValue())) > z.first) { +/* Modify values of z Number*/ + + z.first = Integer.parseInt(String.valueOf(curr.getValue())); + z.second = Integer.parseInt(String.valueOf(curr.getKey())); + } + } + System.out.print(""Three largest elements are "" + x.second + "" "" + + y.second + "" "" + z.second); + } +/* Driver's Code*/ + + public static void main(String args[]) + { + int[] arr = { 3, 4, 2, 3, 16, 3, 15, + 16, 15, 15, 16, 2, 3 }; + int n = arr.length; + top3Repeated(arr, n); + } +}", +Check if a given array contains duplicate elements within k distance from each other,"/* Java program to Check if a given array contains duplicate + elements within k distance from each other */ + +import java.util.*; +class Main +{ + static boolean checkDuplicatesWithinK(int arr[], int k) + { +/* Creates an empty hashset*/ + + HashSet set = new HashSet<>(); +/* Traverse the input array*/ + + for (int i=0; i= k) + set.remove(arr[i-k]); + } + return false; + } +/* Driver method to test above method*/ + + public static void main (String[] args) + { + int arr[] = {10, 5, 3, 4, 3, 5, 6}; + if (checkDuplicatesWithinK(arr, 3)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python 3 program to Check if a given array +contains duplicate elements within k distance +from each other''' + +def checkDuplicatesWithinK(arr, n, k): + ''' Creates an empty list''' + + myset = [] + ''' Traverse the input array''' + + for i in range(n): + ''' If already present n hash, then we + found a duplicate within k distance''' + + if arr[i] in myset: + return True + ''' Add this item to hashset''' + + myset.append(arr[i]) + ''' Remove the k+1 distant item''' + + if (i >= k): + myset.remove(arr[i - k]) + return False + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [10, 5, 3, 4, 3, 5, 6] + n = len(arr) + if (checkDuplicatesWithinK(arr, n, 3)): + print(""Yes"") + else: + print(""No"")" +Check if given sorted sub-sequence exists in binary search tree,"/*Java program to find if given array +exists as a subsequece in BST */ + +import java.util.*; +class GFG +{ +/*A binary Tree node */ + +static class Node +{ + int data; + Node left, right; +}; +/*structure of int class*/ + +static class INT +{ + int a; +} +/*A utility function to create a new BST node +with key as given num */ + +static Node newNode(int num) +{ + Node temp = new Node(); + temp.data = num; + temp.left = temp.right = null; + return temp; +} +/*A utility function to insert a given key to BST */ + +static Node insert( Node root, int key) +{ + if (root == null) + return newNode(key); + if (root.data > key) + root.left = insert(root.left, key); + else + root.right = insert(root.right, key); + return root; +} +/*function to check if given sorted +sub-sequence exist in BST index -. +iterator for given sorted sub-sequence +seq[] -. given sorted sub-sequence */ + +static void seqExistUtil( Node ptr, int seq[], INT index) +{ + if (ptr == null) + return; +/* We traverse left subtree + first in Inorder */ + + seqExistUtil(ptr.left, seq, index); +/* If current node matches + with se[index] then move + forward in sub-sequence */ + + if (ptr.data == seq[index.a]) + index.a++; +/* We traverse left subtree + in the end in Inorder */ + + seqExistUtil(ptr.right, seq, index); +} +/*A wrapper over seqExistUtil. +It returns true if seq[0..n-1] +exists in tree. */ + +static boolean seqExist( Node root, int seq[], int n) +{ +/* Initialize index in seq[] */ + + INT index = new INT(); + index.a = 0; +/* Do an inorder traversal and find if all + elements of seq[] were present */ + + seqExistUtil(root, seq, index); +/* index would become n if all + elements of seq[] were present */ + + return (index.a == n); +} +/*Driver code */ + +public static void main(String args[]) +{ + Node root = null; + root = insert(root, 8); + root = insert(root, 10); + root = insert(root, 3); + root = insert(root, 6); + root = insert(root, 1); + root = insert(root, 4); + root = insert(root, 7); + root = insert(root, 14); + root = insert(root, 13); + int seq[] = {4, 6, 8, 14}; + int n = seq.length; + if(seqExist(root, seq, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Python3 program to find if given array +exists as a subsequece in BST''' + + ''' Constructor to create a new node ''' +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''A utility function to insert a +given key to BST ''' + +def insert(root, key): + if root == None: + return Node(key) + if root.data > key: + root.left = insert(root.left, key) + else: + root.right = insert(root.right, key) + return root + '''function to check if given sorted +sub-sequence exist in BST index . +iterator for given sorted sub-sequence +seq[] . given sorted sub-sequence ''' + +def seqExistUtil(ptr, seq, index): + if ptr == None: + return + ''' We traverse left subtree + first in Inorder ''' + + seqExistUtil(ptr.left, seq, index) + ''' If current node matches with se[index[0]] + then move forward in sub-sequence ''' + + if ptr.data == seq[index[0]]: + index[0] += 1 + ''' We traverse left subtree in + the end in Inorder ''' + + seqExistUtil(ptr.right, seq, index) + '''A wrapper over seqExistUtil. It returns +true if seq[0..n-1] exists in tree. ''' + +def seqExist(root, seq, n): + ''' Initialize index in seq[] ''' + + index = [0] + ''' Do an inorder traversal and find if + all elements of seq[] were present ''' + + seqExistUtil(root, seq, index) + ''' index would become n if all elements + of seq[] were present ''' + + if index[0] == n: + return True + else: + return False + '''Driver Code''' + +if __name__ == '__main__': + root = None + root = insert(root, 8) + root = insert(root, 10) + root = insert(root, 3) + root = insert(root, 6) + root = insert(root, 1) + root = insert(root, 4) + root = insert(root, 7) + root = insert(root, 14) + root = insert(root, 13) + seq = [4, 6, 8, 14] + n = len(seq) + if seqExist(root, seq, n): + print(""Yes"") + else: + print(""No"")" +Count total set bits in all numbers from 1 to n,"/*A simple program to count set bits +in all numbers from 1 to n.*/ + +class GFG{ +/* Returns count of set bits present + in all numbers from 1 to n*/ + + static int countSetBits( int n) + { +/* initialize the result*/ + + int bitCount = 0; + for (int i = 1; i <= n; i++) + bitCount += countSetBitsUtil(i); + return bitCount; + } +/* A utility function to count set bits + in a number x*/ + + static int countSetBitsUtil( int x) + { + if (x <= 0) + return 0; + return (x % 2 == 0 ? 0 : 1) + + countSetBitsUtil(x / 2); + } +/* Driver program*/ + + public static void main(String[] args) + { + int n = 4; + System.out.print(""Total set bit count is ""); + System.out.print(countSetBits(n)); + } +}"," '''A simple program to count set bits +in all numbers from 1 to n.''' + + '''Returns count of set bits present in all +numbers from 1 to n''' + +def countSetBits(n): ''' initialize the result''' + + bitCount = 0 + for i in range(1, n + 1): + bitCount += countSetBitsUtil(i) + return bitCount + '''A utility function to count set bits +in a number x''' + +def countSetBitsUtil(x): + if (x <= 0): + return 0 + return (0 if int(x % 2) == 0 else 1) + countSetBitsUtil(int(x / 2)) + '''Driver program''' + +if __name__=='__main__': + n = 4 + print(""Total set bit count is"", countSetBits(n))" +Find the maximum sum leaf to root path in a Binary Tree,"/*Java program to find maximum sum leaf to root +path in Binary Tree*/ + +/*A Binary Tree node*/ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +}/*A wrapper class is used so that max_no +can be updated among function calls.*/ + +class Maximum { + int max_no = Integer.MIN_VALUE; +} +class BinaryTree { + Node root; + Maximum max = new Maximum(); + Node target_leaf = null; +/* A utility function that prints all nodes on the + path from root to target_leaf*/ + + boolean printPath(Node node, Node target_leaf) + { +/* base case*/ + + if (node == null) + return false; +/* return true if this node is the target_leaf or + target leaf is present in one of its descendants*/ + + if (node == target_leaf || printPath(node.left, target_leaf) + || printPath(node.right, target_leaf)) { + System.out.print(node.data + "" ""); + return true; + } + return false; + } +/* This function Sets the target_leaf_ref to refer + the leaf node of the maximum path sum. Also, + returns the max_sum using max_sum_ref*/ + + void getTargetLeaf(Node node, Maximum max_sum_ref, + int curr_sum) + { + if (node == null) + return; +/* Update current sum to hold sum of nodes on + path from root to this node*/ + + curr_sum = curr_sum + node.data; +/* If this is a leaf node and path to this node + has maximum sum so far, the n make this node + target_leaf*/ + + if (node.left == null && node.right == null) { + if (curr_sum > max_sum_ref.max_no) { + max_sum_ref.max_no = curr_sum; + target_leaf = node; + } + } +/* If this is not a leaf node, then recur down + to find the target_leaf*/ + + getTargetLeaf(node.left, max_sum_ref, curr_sum); + getTargetLeaf(node.right, max_sum_ref, curr_sum); + } +/* Returns the maximum sum and prints the nodes on + max sum path*/ + + int maxSumPath() + { +/* base case*/ + + if (root == null) + return 0; +/* find the target leaf and maximum sum*/ + + getTargetLeaf(root, max, 0); +/* print the path from root to the target leaf*/ + + printPath(root, target_leaf); +/*return maximum sum*/ + +return max.max_no; + } +/* driver function to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(-2); + tree.root.right = new Node(7); + tree.root.left.left = new Node(8); + tree.root.left.right = new Node(-4); + System.out.println(""Following are the nodes "" + + ""on maximum sum path""); + int sum = tree.maxSumPath(); + System.out.println(""""); + System.out.println(""Sum of nodes is : "" + sum); + } +}"," '''Python3 program to find maximum sum leaf to root +path in Binary Tree''' + + '''A tree node structure ''' + +class node : + def __init__(self): + self.data = 0 + self.left = None + self.right = None '''A utility function that prints all nodes +on the path from root to target_leaf''' + +def printPath( root,target_leaf): + ''' base case''' + + if (root == None): + return False + ''' return True if this node is the target_leaf + or target leaf is present in one of its + descendants''' + + if (root == target_leaf or + printPath(root.left, target_leaf) or + printPath(root.right, target_leaf)) : + print( root.data, end = "" "") + return True + return False +max_sum_ref = 0 +target_leaf_ref = None + '''This function Sets the target_leaf_ref to refer +the leaf node of the maximum path sum. Also, +returns the max_sum using max_sum_ref''' + +def getTargetLeaf(Node, curr_sum): + global max_sum_ref + global target_leaf_ref + if (Node == None): + return + ''' Update current sum to hold sum of nodes on path + from root to this node''' + + curr_sum = curr_sum + Node.data + ''' If this is a leaf node and path to this node has + maximum sum so far, then make this node target_leaf''' + + if (Node.left == None and Node.right == None): + if (curr_sum > max_sum_ref) : + max_sum_ref = curr_sum + target_leaf_ref = Node + ''' If this is not a leaf node, then recur down + to find the target_leaf''' + + getTargetLeaf(Node.left, curr_sum) + getTargetLeaf(Node.right, curr_sum) + '''Returns the maximum sum and prints the nodes on max +sum path''' + +def maxSumPath( Node): + global max_sum_ref + global target_leaf_ref + ''' base case''' + + if (Node == None): + return 0 + target_leaf_ref = None + max_sum_ref = -32676 + ''' find the target leaf and maximum sum''' + + getTargetLeaf(Node, 0) + ''' print the path from root to the target leaf''' + + printPath(Node, target_leaf_ref); + '''return maximum sum''' + + return max_sum_ref; + '''Utility function to create a new Binary Tree node ''' + +def newNode(data): + temp = node(); + temp.data = data; + temp.left = None; + temp.right = None; + return temp; + '''Driver function to test above functions ''' + +root = None; +root = newNode(10); +root.left = newNode(-2); +root.right = newNode(7); +root.left.left = newNode(8); +root.left.right = newNode(-4); +print( ""Following are the nodes on the maximum sum path ""); +sum = maxSumPath(root); +print( ""\nSum of the nodes is "" , sum);" +Program to check if an array is sorted or not (Iterative and Recursive),"/*Recursive approach to check if an +Array is sorted or not*/ + + +class CkeckSorted { +/* Function that returns 0 if a pair + is found unsorted*/ + + static int arraySortedOrNot(int arr[], int n) + { +/* Array has one or no element or the + rest are already checked and approved.*/ + + if (n == 1 || n == 0) + return 1; + +/* Unsorted pair found (Equal values allowed)*/ + + if (arr[n - 1] < arr[n - 2]) + return 0; + +/* Last pair was sorted + Keep on checking*/ + + return arraySortedOrNot(arr, n - 1); + } + +/* main function*/ + + public static void main(String[] args) + { + int arr[] = { 20, 23, 23, 45, 78, 88 }; + int n = arr.length; + if (arraySortedOrNot(arr, n) != 0) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +} +", +Construct Special Binary Tree from given Inorder traversal,"/*Java program to construct tree from inorder traversal*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Recursive function to construct binary of size len from + Inorder traversal inorder[]. Initial values of start and end + should be 0 and len -1. */ + + Node buildTree(int inorder[], int start, int end, Node node) + { + if (start > end) + return null; + /* Find index of the maximum element from Binary Tree */ + + int i = max(inorder, start, end); + /* Pick the maximum value and make it root */ + + node = new Node(inorder[i]); + /* If this is the only element in inorder[start..end], + then return it */ + + if (start == end) + return node; + /* Using index in Inorder traversal, construct left and + right subtress */ + + node.left = buildTree(inorder, start, i - 1, node.left); + node.right = buildTree(inorder, i + 1, end, node.right); + return node; + } + /* Function to find index of the maximum value in arr[start...end] */ + + int max(int arr[], int strt, int end) + { + int i, max = arr[strt], maxind = strt; + for (i = strt + 1; i <= end; i++) + { + if (arr[i] > max) + { + max = arr[i]; + maxind = i; + } + } + return maxind; + } + /* This funtcion is here just to test buildTree() */ + + void printInorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.data + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } +/* Driver code*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* Assume that inorder traversal of following tree is given + 40 + / \ + 10 30 + / \ + 5 28 */ + + int inorder[] = new int[]{5, 10, 40, 30, 28}; + int len = inorder.length; + Node mynode = tree.buildTree(inorder, 0, len - 1, tree.root); + /* Let us test the built tree by printing Inorder traversal */ + + System.out.println(""Inorder traversal of the constructed tree is ""); + tree.printInorder(mynode); + } +}"," '''Python3 program to construct tree from +inorder traversal ''' + '''Recursive function to construct binary of +size len from Inorder traversal inorder[]. +Initial values of start and end should be +0 and len -1. ''' + +def buildTree (inorder, start, end): + if start > end: + return None + ''' Find index of the maximum element + from Binary Tree ''' + + i = Max (inorder, start, end) + ''' Pick the maximum value and make it root ''' + + root = newNode(inorder[i]) + ''' If this is the only element in + inorder[start..end], then return it ''' + + if start == end: + return root + ''' Using index in Inorder traversal, + construct left and right subtress ''' + + root.left = buildTree (inorder, start, i - 1) + root.right = buildTree (inorder, i + 1, end) + return root + '''Function to find index of the maximum +value in arr[start...end] ''' + +def Max(arr, strt, end): + i, Max = 0, arr[strt] + maxind = strt + for i in range(strt + 1, end + 1): + if arr[i] > Max: + Max = arr[i] + maxind = i + return maxind + '''Helper class that allocates a new node +with the given data and None left and +right pointers. ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''This funtcion is here just to test buildTree() ''' + +def printInorder (node): + if node == None: + return + ''' first recur on left child ''' + + printInorder (node.left) + ''' then print the data of node ''' + + print(node.data, end = "" "") + ''' now recur on right child ''' + + printInorder (node.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' Assume that inorder traversal of + following tree is given + 40 + / \ + 10 30 + / \ + 5 28 ''' + + inorder = [5, 10, 40, 30, 28] + Len = len(inorder) + root = buildTree(inorder, 0, Len - 1) + ''' Let us test the built tree by + printing Insorder traversal ''' + + print(""Inorder traversal of the"", + ""constructed tree is "") + printInorder(root)" +Palindrome Partitioning | DP-17,"/*Java Code for Palindrome Partitioning +Problem*/ + +public class GFG +{ + static boolean isPalindrome(String string, int i, int j) + { + while(i < j) + { + if(string.charAt(i) != string.charAt(j)) + return false; + i++; + j--; + } + return true; + } + static int minPalPartion(String string, int i, int j) + { + if( i >= j || isPalindrome(string, i, j) ) + return 0; + int ans = Integer.MAX_VALUE, count; + for(int k = i; k < j; k++) + { + count = minPalPartion(string, i, k) + + minPalPartion(string, k + 1, j) + 1; + ans = Math.min(ans, count); + } + return ans; + } +/* Driver code*/ + + public static void main(String args[]) + { + String str = ""ababbbabbababa""; + System.out.println(""Min cuts needed for "" + + ""Palindrome Partitioning is "" + minPalPartion(str, 0, str.length() - 1)); + } +}"," '''Python code for implementation of Naive Recursive +approach''' + +def isPalindrome(x): + return x == x[::-1] +def minPalPartion(string, i, j): + if i >= j or isPalindrome(string[i:j + 1]): + return 0 + ans = float('inf') + for k in range(i, j): + count = ( + 1 + minPalPartion(string, i, k) + + minPalPartion(string, k + 1, j) + ) + ans = min(ans, count) + return ans + '''Driver code''' + +def main(): + string = ""ababbbabbababa"" + print( + ""Min cuts needed for Palindrome Partitioning is "", + minPalPartion(string, 0, len(string) - 1), + ) +if __name__ == ""__main__"": + main()" +Pair with given product | Set 1 (Find if any pair exists),"/*Java program if there exists a pair for given product*/ + +import java.util.HashSet; +class GFG +{ +/* Returns true if there is a pair in arr[0..n-1] + with product equal to x.*/ + + static boolean isProduct(int arr[], int n, int x) + { +/* Create an empty set and insert first + element into it*/ + + HashSet hset = new HashSet<>(); + if(n < 2) + return false; +/* Traverse remaining elements*/ + + for(int i = 0; i < n; i++) + { +/* 0 case must be handles explicitly as + x % 0 is undefined*/ + + if(arr[i] == 0) + { + if(x == 0) + return true; + else + continue; + } +/* x/arr[i] exists in hash, then we + found a pair*/ + + if(x % arr[i] == 0) + { + if(hset.contains(x / arr[i])) + return true; +/* Insert arr[i]*/ + + hset.add(arr[i]); + } + } + return false; + } +/* driver code*/ + + public static void main(String[] args) + { + int arr[] = {10, 20, 9, 40}; + int x = 400; + int n = arr.length; + if(isProduct(arr, arr.length, x)) + System.out.println(""Yes""); + else + System.out.println(""No""); + x = 190; + if(isProduct(arr, arr.length, x)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 program to find if there +is a pair with the given product. + ''' '''Returns true if there is a pair in +arr[0..n-1] with product equal to x.''' + +def isProduct(arr, n, x): + if n < 2: + return False + ''' Create an empty set and insert + first element into it''' + + s = set() + ''' Traverse remaining elements''' + + for i in range(0, n): + ''' 0 case must be handles explicitly as + x % 0 is undefined behaviour in C++''' + + if arr[i] == 0: + if x == 0: + return True + else: + continue + ''' x/arr[i] exists in hash, then + we found a pair''' + + if x % arr[i] == 0: + if x // arr[i] in s: + return True + ''' Insert arr[i]''' + + s.add(arr[i]) + return False + '''Driver code''' + +if __name__ == ""__main__"": + arr = [10, 20, 9, 40] + x = 400 + n = len(arr) + if isProduct(arr, n, x): + print(""Yes"") + else: + print(""No"") + x = 190 + if isProduct(arr, n, x): + print(""Yes"") + else: + print(""No"")" +Minimize characters to be changed to make the left and right rotation of a string same,"/*Java program of the +above approach*/ + +class GFG{ + +/*Function to find the minimum +characters to be removed from +the string*/ + +public static int getMinimumRemoval(String str) +{ + int n = str.length(); + +/* Initialize answer by N*/ + + int ans = n; + +/* If length is even*/ + + if (n % 2 == 0) + { + +/* Frequency array for odd + and even indices*/ + + int[] freqEven = new int[128]; + int[] freqOdd = new int[128]; + +/* Store the frequency of the + characters at even and odd + indices*/ + + for(int i = 0; i < n; i++) + { + if (i % 2 == 0) + { + freqEven[str.charAt(i)]++; + } + else + { + freqOdd[str.charAt(i)]++; + } + } + +/* Stores the most occuring frequency + for even and odd indices*/ + + int evenMax = 0, oddMax = 0; + + for(char chr = 'a'; chr <= 'z'; chr++) + { + evenMax = Math.max(evenMax, + freqEven[chr]); + oddMax = Math.max(oddMax, + freqOdd[chr]); + } + +/* Update the answer*/ + + ans = ans - evenMax - oddMax; + } + +/* If length is odd*/ + + else + { + +/* Stores the frequency of the + characters of the string*/ + + int[] freq = new int[128]; + for(int i = 0; i < n; i++) + { + freq[str.charAt(i)]++; + } + +/* Stores the most occuring character + in the string*/ + + int strMax = 0; + for(char chr = 'a'; chr <= 'z'; chr++) + { + strMax = Math.max(strMax, freq[chr]); + } + +/* Update the answer*/ + + ans = ans - strMax; + } + return ans; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + String str = ""geeksgeeks""; + + System.out.print(getMinimumRemoval(str)); +} +} + + +"," '''Python3 Program of the +above approach''' + + + '''Function to find the minimum +characters to be removed from +the string''' + +def getMinimumRemoval(str): + + n = len(str) + + ''' Initialize answer by N''' + + ans = n + + ''' If length is even''' + + if(n % 2 == 0): + + ''' Frequency array for odd + and even indices''' + + freqEven = {} + freqOdd = {} + for ch in range(ord('a'), + ord('z') + 1): + freqEven[chr(ch)] = 0 + freqOdd[chr(ch)] = 0 + + ''' Store the frequency of the + characters at even and odd + indices''' + + for i in range(n): + if(i % 2 == 0): + if str[i] in freqEven: + freqEven[str[i]] += 1 + else: + if str[i] in freqOdd: + freqOdd[str[i]] += 1 + + ''' Stores the most occuring + frequency for even and + odd indices''' + + evenMax = 0 + oddMax = 0 + + for ch in range(ord('a'), + ord('z') + 1): + evenMax = max(evenMax, + freqEven[chr(ch)]) + oddMax = max(oddMax, + freqOdd[chr(ch)]) + + ''' Update the answer''' + + ans = ans - evenMax - oddMax + + ''' If length is odd''' + + else: + + ''' Stores the frequency of the + characters of the string''' + + freq = {} + + for ch in range('a','z'): + freq[chr(ch)] = 0 + for i in range(n): + if str[i] in freq: + freq[str[i]] += 1 + + ''' Stores the most occuring + characterin the string''' + + strMax = 0 + + for ch in range('a','z'): + strMax = max(strMax, + freq[chr(ch)]) + + ''' Update the answer''' + + ans = ans - strMax + + return ans + + '''Driver Code''' + +str = ""geeksgeeks"" +print(getMinimumRemoval(str)) + + +" +Difference between highest and least frequencies in an array,"/*Java code to find the difference between highest +and least frequencies*/ + +import java.util.*; +class GFG +{ +static int findDiff(int arr[], int n) +{ +/* Put all elements in a hash map*/ + + Map mp = new HashMap<>(); + for (int i = 0 ; i < n; i++) + { + if(mp.containsKey(arr[i])) + { + mp.put(arr[i], mp.get(arr[i])+1); + } + else + { + mp.put(arr[i], 1); + } + } +/* Find counts of maximum and minimum + frequent elements*/ + + int max_count = 0, min_count = n; + for (Map.Entry x : mp.entrySet()) + { + max_count = Math.max(max_count, x.getValue()); + min_count = Math.min(min_count, x.getValue()); + } + return (max_count - min_count); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; + int n = arr.length; + System.out.println(findDiff(arr, n)); +} +}"," '''Python code to find the difference between highest +and least frequencies''' + +from collections import defaultdict +def findDiff(arr,n): + ''' Put all elements in a hash map''' + + mp = defaultdict(lambda:0) + for i in range(n): + mp[arr[i]]+=1 + ''' Find counts of maximum and minimum + frequent elements''' + + max_count=0;min_count=n + for key,values in mp.items(): + max_count= max(max_count,values) + min_count = min(min_count,values) + return max_count-min_count + '''Driver code''' + +arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5] +n = len(arr) +print(findDiff(arr,n))" +Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed,"/*Java program to find max value of i*arr[i]*/ + +import java.util.Arrays; +class Test +{ + static int arr[] = new int[]{10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; +/* Returns max possible value of i*arr[i]*/ + + static int maxSum() + { +/* Find array sum and i*arr[i] with no rotation +Stores sum of arr[i]*/ + +int arrSum = 0; +/*Stores sum of i*arr[i]*/ + +int currVal = 0; + for (int i=0; i maxVal) + maxVal = currVal; + } +/* Return result*/ + + return maxVal; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.println(""Max sum is "" + maxSum()); + } +}"," '''Python program to find maximum value of Sum(i*arr[i])''' + + '''returns max possible value of Sum(i*arr[i])''' + +def maxSum(arr): + ''' stores sum of arr[i]''' + + arrSum = 0 + ''' stores sum of i*arr[i]''' + + currVal = 0 + n = len(arr) + for i in range(0, n): + arrSum = arrSum + arr[i] + currVal = currVal + (i*arr[i]) + ''' initialize result''' + + maxVal = currVal + ''' try all rotations one by one and find the maximum + rotation sum''' + + for j in range(1, n): + currVal = currVal + arrSum-n*arr[n-j] + if currVal > maxVal: + maxVal = currVal + ''' return result''' + + return maxVal + '''test maxsum(arr) function''' + +arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] +print ""Max sum is: "", maxSum(arr)" +Measure one litre using two vessels and infinite water supply,"/* Sample run of the Algo for V1 with capacity 3 and V2 with capacity 7 +1. Fill V1: V1 = 3, V2 = 0 +2. Transfer from V1 to V2, and fill V1: V1 = 3, V2 = 3 +2. Transfer from V1 to V2, and fill V1: V1 = 3, V2 = 6 +3. Transfer from V1 to V2, and empty V2: V1 = 2, V2 = 0 +4. Transfer from V1 to V2, and fill V1: V1 = 3, V2 = 2 +5. Transfer from V1 to V2, and fill V1: V1 = 3, V2 = 5 +6. Transfer from V1 to V2, and empty V2: V1 = 1, V2 = 0 +7. Stop as V1 now contains 1 litre. +Note that V2 was made empty in steps 3 and 6 because it became full */ + +class GFG +{ +/* A utility function to get GCD of two numbers*/ + + static int gcd(int a, int b) + { + return b > 0 ? gcd(b, a % b) : a; + } +/* Class to represent a Vessel*/ + + static class Vessel + { +/* A vessel has capacity, and + current amount of water in it*/ + + int capacity, current; +/* Constructor: initializes capacity + as given, and current as 0*/ + + public Vessel(int capacity) + { + this.capacity = capacity; + current = 0; + } +/* The main function to fill one litre + in this vessel. Capacity of V2 must be + greater than this vessel and two capacities + must be coprime*/ + + void makeOneLitre(Vessel V2) + { +/* solution exists iff a and b are co-prime*/ + + if (gcd(capacity, V2.capacity) != 1) + return; + while (current != 1) + { +/* fill A (smaller vessel)*/ + + if (current == 0) + current = capacity; + System.out.print(""Vessel 1: "" + current + + "" Vessel 2: "" + V2.current + ""\n""); +/* Transfer water from V1 to V2 and + reduce current of V1 by + the amount equal to transferred water*/ + + current = current - V2.transfer(current); + } +/* Finally, there will be 1 litre in vessel 1*/ + + System.out.print(""Vessel 1: "" + current + + "" Vessel 2: "" + V2.current + ""\n""); + } +/* Fills vessel with given amount and + returns the amount of water + transferred to it. If the vessel + becomes full, then the vessel + is made empty*/ + + int transfer(int amount) + { +/* If the vessel can accommodate the given amount*/ + + if (current + amount < capacity) + { + current += amount; + return amount; + } +/* If the vessel cannot accommodate + the given amount, then store + the amount of water transferred*/ + + int transferred = capacity - current; +/* Since the vessel becomes full, make the vessel + empty so that it can be filled again*/ + + current = 0; + return transferred; + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { +/*a must be smaller than b*/ + +int a = 3, b = 7; +/* Create two vessels of capacities a and b*/ + + Vessel V1 = new Vessel(a); + Vessel V2 = new Vessel(b); +/* Get 1 litre in first vessel*/ + + V1.makeOneLitre(V2); + } +}", +Find a specific pair in Matrix,"/*An efficient method to find maximum value of mat1[d] +- ma[a][b] such that c > a and d > b*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* The function returns maximum value A(c,d) - A(a,b) + over all choices of indexes such that both c > a + and d > b.*/ + + static int findMaxValue(int N,int mat[][]) + { +/* stores maximum value*/ + + int maxValue = Integer.MIN_VALUE; +/* maxArr[i][j] stores max of elements in matrix + from (i, j) to (N-1, N-1)*/ + + int maxArr[][] = new int[N][N]; +/* last element of maxArr will be same's as of + the input matrix*/ + + maxArr[N-1][N-1] = mat[N-1][N-1]; +/* preprocess last row +Initialize max*/ + +int maxv = mat[N-1][N-1]; + for (int j = N - 2; j >= 0; j--) + { + if (mat[N-1][j] > maxv) + maxv = mat[N - 1][j]; + maxArr[N-1][j] = maxv; + } +/* preprocess last column +Initialize max*/ + +maxv = mat[N - 1][N - 1]; + for (int i = N - 2; i >= 0; i--) + { + if (mat[i][N - 1] > maxv) + maxv = mat[i][N - 1]; + maxArr[i][N - 1] = maxv; + } +/* preprocess rest of the matrix from bottom*/ + + for (int i = N-2; i >= 0; i--) + { + for (int j = N-2; j >= 0; j--) + { +/* Update maxValue*/ + + if (maxArr[i+1][j+1] - mat[i][j] > maxValue) + maxValue = maxArr[i + 1][j + 1] - mat[i][j]; +/* set maxArr (i, j)*/ + + maxArr[i][j] = Math.max(mat[i][j], + Math.max(maxArr[i][j + 1], + maxArr[i + 1][j]) ); + } + } + return maxValue; + } +/* Driver code*/ + + public static void main (String[] args) + { + int N = 5; + int mat[][] = { + { 1, 2, -1, -4, -20 }, + { -8, -3, 4, 2, 1 }, + { 3, 8, 6, 1, 3 }, + { -4, -1, 1, 7, -6 }, + { 0, -4, 10, -5, 1 } + }; + System.out.print(""Maximum Value is "" + + findMaxValue(N,mat)); + } +} +"," '''An efficient method to find maximum value +of mat[d] - ma[a][b] such that c > a and d > b''' + +import sys +N = 5 + '''The function returns maximum value +A(c,d) - A(a,b) over all choices of +indexes such that both c > a and d > b.''' + +def findMaxValue(mat): + ''' stores maximum value''' + + maxValue = -sys.maxsize -1 + ''' maxArr[i][j] stores max of elements + in matrix from (i, j) to (N-1, N-1)''' + + maxArr = [[0 for x in range(N)] + for y in range(N)] + ''' last element of maxArr will be + same's as of the input matrix''' + + maxArr[N - 1][N - 1] = mat[N - 1][N - 1] + ''' preprocess last row +Initialize max''' + + maxv = mat[N - 1][N - 1]; + for j in range (N - 2, -1, -1): + if (mat[N - 1][j] > maxv): + maxv = mat[N - 1][j] + maxArr[N - 1][j] = maxv + ''' preprocess last column +Initialize max''' + + maxv = mat[N - 1][N - 1]; + for i in range (N - 2, -1, -1): + if (mat[i][N - 1] > maxv): + maxv = mat[i][N - 1] + maxArr[i][N - 1] = maxv + ''' preprocess rest of the matrix + from bottom''' + + for i in range (N - 2, -1, -1): + for j in range (N - 2, -1, -1): + ''' Update maxValue''' + + if (maxArr[i + 1][j + 1] - + mat[i][j] > maxValue): + maxValue = (maxArr[i + 1][j + 1] - + mat[i][j]) + ''' set maxArr (i, j)''' + + maxArr[i][j] = max(mat[i][j], + max(maxArr[i][j + 1], + maxArr[i + 1][j])) + return maxValue + '''Driver Code''' + +mat = [[ 1, 2, -1, -4, -20 ], + [-8, -3, 4, 2, 1 ], + [ 3, 8, 6, 1, 3 ], + [ -4, -1, 1, 7, -6] , + [0, -4, 10, -5, 1 ]] +print (""Maximum Value is"", + findMaxValue(mat))" +Count zeros in a row wise and column wise sorted matrix,"/*Java program to count number of 0s in the given +row-wise and column-wise sorted binary matrix*/ + +import java.io.*; +class GFG +{ + public static int N = 5; +/* Function to count number of 0s in the given + row-wise and column-wise sorted binary matrix.*/ + + static int countZeroes(int mat[][]) + { +/* start from bottom-left corner of the matrix*/ + + int row = N - 1, col = 0; +/* stores number of zeroes in the matrix*/ + + int count = 0; + while (col < N) + { +/* move up until you find a 0*/ + + while (mat[row][col] > 0) +/* if zero is not found in current column, + we are done*/ + + if (--row < 0) + return count; +/* add 0s present in current column to result*/ + + count += (row + 1); +/* move right to next column*/ + + col++; + } + return count; + } +/* Driver program*/ + + public static void main (String[] args) + { + int mat[][] = { { 0, 0, 0, 0, 1 }, + { 0, 0, 0, 1, 1 }, + { 0, 1, 1, 1, 1 }, + { 1, 1, 1, 1, 1 }, + { 1, 1, 1, 1, 1 } }; + System.out.println(countZeroes(mat)); + } +}"," '''Python program to count number +of 0s in the given row-wise +and column-wise sorted +binary matrix.''' +N = 5; + '''Function to count number +of 0s in the given +row-wise and column-wise +sorted binary matrix.''' + +def countZeroes(mat): ''' start from bottom-left + corner of the matrix''' + + row = N - 1; + col = 0; + ''' stores number of + zeroes in the matrix''' + + count = 0; + while (col < N): + ''' move up until + you find a 0''' + + while (mat[row][col]): + ''' if zero is not found + in current column, we + are done''' + + if (row < 0): + return count; + row = row - 1; + ''' add 0s present in + current column to result''' + + count = count + (row + 1); + ''' move right to + next column''' + + col = col + 1; + return count; + '''Driver Code''' + +mat = [[0, 0, 0, 0, 1], + [0, 0, 0, 1, 1], + [0, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]]; +print( countZeroes(mat));" +"Search, insert and delete in an unsorted array","/*Java program to implement linear +search in unsorted arrays*/ + +class Main +{ +/* Function to implement + search operation*/ + + static int findElement(int arr[], int n, + int key) + { + for (int i = 0; i < n; i++) + if (arr[i] == key) + return i; + return -1; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int arr[] = {12, 34, 10, 6, 40}; + int n = arr.length; +/* Using a last element as search element*/ + + int key = 40; + int position = findElement(arr, n, key); + if (position == - 1) + System.out.println(""Element not found""); + else + System.out.println(""Element Found at Position: "" + + (position + 1)); + } +}"," '''Python program for searching in +unsorted array''' + '''Function to implement + search operation''' + +def findElement(arr, n, key): + for i in range (n): + if (arr[i] == key): + return i + return -1 '''Driver Code''' + +arr = [12, 34, 10, 6, 40] +n = len(arr) + '''Using a last element as search element''' + +key = 40 +index = findElement(arr, n, key) +if index != -1: + print (""element found at position: "" + str(index + 1 )) +else: + print (""element not found"") +" +Reverse a doubly circular linked list,"/*Java implementation to revesre a +doubly circular linked list*/ + +class GFG +{ + +/*structure of a node of linked list*/ + +static class Node +{ + int data; + Node next, prev; +}; + +/*function to create and return a new node*/ + +static Node getNode(int data) +{ + Node newNode = new Node(); + newNode.data = data; + return newNode; +} + +/*Function to insert at the end*/ + +static Node insertEnd(Node head, Node new_node) +{ +/* If the list is empty, create a single node + circular and doubly list*/ + + if (head == null) + { + new_node.next = new_node.prev = new_node; + head = new_node; + return head; + } + +/* If list is not empty*/ + + +/* Find last node /*/ + + Node last = (head).prev; + +/* Start is going to be next of new_node*/ + + new_node.next = head; + +/* Make new node previous of start*/ + + (head).prev = new_node; + +/* Make last preivous of new node*/ + + new_node.prev = last; + +/* Make new node next of old last*/ + + last.next = new_node; + return head; +} + +/*Uitlity function to revesre a +doubly circular linked list*/ + +static Node reverse(Node head) +{ + if (head==null) + return null; + +/* Initialize a new head pointer*/ + + Node new_head = null; + +/* get pointer to the the last node*/ + + Node last = head.prev; + +/* set 'curr' to last node*/ + + Node curr = last, prev; + +/* traverse list in backward direction*/ + + while (curr.prev != last) + { + prev = curr.prev; + +/* insert 'curr' at the end of the list + starting with the 'new_head' pointer*/ + + new_head=insertEnd(new_head, curr); + curr = prev; + } + new_head=insertEnd(new_head, curr); + +/* head pointer of the reversed list*/ + + return new_head; +} + +/*function to display a doubly circular list in +forward and backward direction*/ + +static void display(Node head) +{ + if (head==null) + return; + + Node temp = head; + + System.out.print( ""Forward direction: ""); + while (temp.next != head) + { + System.out.print( temp.data + "" ""); + temp = temp.next; + } + System.out.print( temp.data + "" ""); + + Node last = head.prev; + temp = last; + + System.out.print( ""\nBackward direction: ""); + while (temp.prev != last) + { + System.out.print( temp.data + "" ""); + temp = temp.prev; + } + System.out.print( temp.data + "" ""); +} + +/*Driver code*/ + +public static void main(String args[]) +{ + Node head = null; + + head =insertEnd(head, getNode(1)); + head =insertEnd(head, getNode(2)); + head =insertEnd(head, getNode(3)); + head =insertEnd(head, getNode(4)); + head =insertEnd(head, getNode(5)); + + System.out.print( ""Current list:\n""); + display(head); + + head = reverse(head); + + System.out.print( ""\n\nReversed list:\n""); + display(head); +} +} + + +"," '''Python3 implementation to revesre a +doubly circular linked list''' + +import math + + '''structure of a node of linked list''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''function to create and return a new node''' + +def getNode(data): + newNode = Node(data) + newNode.data = data + return newNode + + '''Function to insert at the end''' + +def insertEnd(head, new_node): + + ''' If the list is empty, create a single node + circular and doubly list''' + + if (head == None) : + new_node.next = new_node + new_node.prev = new_node + head = new_node + return head + + ''' If list is not empty''' + + + ''' Find last node''' + + last = head.prev + + ''' Start is going to be next of new_node''' + + new_node.next = head + + ''' Make new node previous of start''' + + head.prev = new_node + + ''' Make last preivous of new node''' + + new_node.prev = last + + ''' Make new node next of old last''' + + last.next = new_node + return head + + '''Uitlity function to revesre a +doubly circular linked list''' + +def reverse(head): + if (head == None): + return None + + ''' Initialize a new head pointer''' + + new_head = None + + ''' get pointer to the the last node''' + + last = head.prev + + ''' set 'curr' to last node''' + + curr = last + ''' traverse list in backward direction''' + + while (curr.prev != last): + prev = curr.prev + + ''' insert 'curr' at the end of the list + starting with the 'new_head' pointer''' + + new_head = insertEnd(new_head, curr) + curr = prev + + new_head = insertEnd(new_head, curr) + + ''' head pointer of the reversed list''' + + return new_head + + '''function to display a doubly circular list in +forward and backward direction''' + +def display(head): + if (head == None): + return + + temp = head + + print(""Forward direction: "", end = """") + while (temp.next != head): + print(temp.data, end = "" "") + temp = temp.next + + print(temp.data) + + last = head.prev + temp = last + + print(""Backward direction: "", end = """") + while (temp.prev != last): + print(temp.data, end = "" "") + temp = temp.prev + + print(temp.data) + + '''Driver Code''' + +if __name__=='__main__': + + head = None + + head = insertEnd(head, getNode(1)) + head = insertEnd(head, getNode(2)) + head = insertEnd(head, getNode(3)) + head = insertEnd(head, getNode(4)) + head = insertEnd(head, getNode(5)) + + print(""Current list:"") + display(head) + + head = reverse(head) + + print(""\nReversed list:"") + display(head) + + +" +Queries for counts of array elements with values in given range,"/*Simple java program to count +number of elements with +values in given range.*/ + +import java.io.*; +class GFG +{ +/* function to count elements within given range*/ + + static int countInRange(int arr[], int n, int x, int y) + { +/* initialize result*/ + + int count = 0; + for (int i = 0; i < n; i++) { +/* check if element is in range*/ + + if (arr[i] >= x && arr[i] <= y) + count++; + } + return count; + } +/* driver function*/ + + public static void main (String[] args) + { + int arr[] = { 1, 3, 4, 9, 10, 3 }; + int n = arr.length; +/* Answer queries*/ + + int i = 1, j = 4; + System.out.println ( countInRange(arr, n, i, j)) ; + i = 9; + j = 12; + System.out.println ( countInRange(arr, n, i, j)) ; + } +}"," '''function to count elements within given range''' + +def countInRange(arr, n, x, y): + ''' initialize result''' + + count = 0; + for i in range(n): + ''' check if element is in range''' + + if (arr[i] >= x and arr[i] <= y): + count += 1 + return count + '''driver function''' + +arr = [1, 3, 4, 9, 10, 3] +n = len(arr) + '''Answer queries''' + +i = 1 +j = 4 +print(countInRange(arr, n, i, j)) +i = 9 +j = 12 +print(countInRange(arr, n, i, j))" +Find k-cores of an undirected graph,"/*Java program to find K-Cores of a graph*/ + +import java.util.*; +class GFG +{ +/* This class represents a undirected graph using adjacency + list representation*/ + + static class Graph + { +/*No. of vertices*/ + +int V; +/* Pointer to an array containing adjacency lists*/ + + Vector[] adj; + @SuppressWarnings(""unchecked"") + Graph(int V) + { + this.V = V; + this.adj = new Vector[V]; + for (int i = 0; i < V; i++) + adj[i] = new Vector<>(); + } +/* function to add an edge to graph*/ + + void addEdge(int u, int v) + { + this.adj[u].add(v); + this.adj[v].add(u); + } +/* A recursive function to print DFS starting from v. + It returns true if degree of v after processing is less + than k else false + It also updates degree of adjacent if degree of v + is less than k. And if degree of a processed adjacent + becomes less than k, then it reduces of degree of v also,*/ + + boolean DFSUtil(int v, boolean[] visited, int[] vDegree, int k) + { +/* Mark the current node as visited and print it*/ + + visited[v] = true; +/* Recur for all the vertices adjacent to this vertex*/ + + for (int i : adj[v]) + { +/* degree of v is less than k, then degree of adjacent + must be reduced*/ + + if (vDegree[v] < k) + vDegree[i]--; +/* If adjacent is not processed, process it*/ + + if (!visited[i]) + { +/* If degree of adjacent after processing becomes + less than k, then reduce degree of v also.*/ + + DFSUtil(i, visited, vDegree, k); + } + } +/* Return true if degree of v is less than k*/ + + return (vDegree[v] < k); + } +/* Prints k cores of an undirected graph*/ + + void printKCores(int k) + { +/* INITIALIZATION + Mark all the vertices as not visited and not + processed.*/ + + boolean[] visited = new boolean[V]; + boolean[] processed = new boolean[V]; + Arrays.fill(visited, false); + Arrays.fill(processed, false); + int mindeg = Integer.MAX_VALUE; + int startvertex = 0; +/* Store degrees of all vertices*/ + + int[] vDegree = new int[V]; + for (int i = 0; i < V; i++) + { + vDegree[i] = adj[i].size(); + if (vDegree[i] < mindeg) + { + mindeg = vDegree[i]; + startvertex = i; + } + } + DFSUtil(startvertex, visited, vDegree, k); +/* DFS traversal to update degrees of all + vertices.*/ + + for (int i = 0; i < V; i++) + if (!visited[i]) + DFSUtil(i, visited, vDegree, k); +/* PRINTING K CORES*/ + + System.out.println(""K-Cores : ""); + for (int v = 0; v < V; v++) + { +/* Only considering those vertices which have degree + >= K after BFS*/ + + if (vDegree[v] >= k) + { + System.out.printf(""\n[%d]"", v); +/* Traverse adjacency list of v and print only + those adjacent which have vDegree >= k after + BFS.*/ + + for (int i : adj[v]) + if (vDegree[i] >= k) + System.out.printf("" -> %d"", i); + } + } + } + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Create a graph given in the above diagram*/ + + int k = 3; + Graph g1 = new Graph(9); + g1.addEdge(0, 1); + g1.addEdge(0, 2); + g1.addEdge(1, 2); + g1.addEdge(1, 5); + g1.addEdge(2, 3); + g1.addEdge(2, 4); + g1.addEdge(2, 5); + g1.addEdge(2, 6); + g1.addEdge(3, 4); + g1.addEdge(3, 6); + g1.addEdge(3, 7); + g1.addEdge(4, 6); + g1.addEdge(4, 7); + g1.addEdge(5, 6); + g1.addEdge(5, 8); + g1.addEdge(6, 7); + g1.addEdge(6, 8); + g1.printKCores(k); + System.out.println(); + Graph g2 = new Graph(13); + g2.addEdge(0, 1); + g2.addEdge(0, 2); + g2.addEdge(0, 3); + g2.addEdge(1, 4); + g2.addEdge(1, 5); + g2.addEdge(1, 6); + g2.addEdge(2, 7); + g2.addEdge(2, 8); + g2.addEdge(2, 9); + g2.addEdge(3, 10); + g2.addEdge(3, 11); + g2.addEdge(3, 12); + g2.printKCores(k); + } +}"," '''Python program to find K-Cores of a graph''' + +from collections import defaultdict + '''This class represents a undirected graph using adjacency +list representation''' + +class Graph: + def __init__(self,vertices): + '''No. of vertices''' + + self.V= vertices + ''' default dictionary to store graph''' + + self.graph= defaultdict(list) + ''' function to add an edge to undirected graph''' + + def addEdge(self,u,v): + self.graph[u].append(v) + self.graph[v].append(u) + ''' A recursive function to call DFS starting from v. + It returns true if vDegree of v after processing is less + than k else false + It also updates vDegree of adjacent if vDegree of v + is less than k. And if vDegree of a processed adjacent + becomes less than k, then it reduces of vDegree of v also,''' + + def DFSUtil(self,v,visited,vDegree,k): + ''' Mark the current node as visited''' + + visited[v] = True + ''' Recur for all the vertices adjacent to this vertex''' + + for i in self.graph[v]: + ''' vDegree of v is less than k, then vDegree of + adjacent must be reduced''' + + if vDegree[v] < k: + vDegree[i] = vDegree[i] - 1 + ''' If adjacent is not processed, process it''' + + if visited[i]==False: + ''' If vDegree of adjacent after processing becomes + less than k, then reduce vDegree of v also''' + + self.DFSUtil(i,visited,vDegree,k) + ''' Return true if vDegree of v is less than k''' + + return vDegree[v] < k + ''' Prints k cores of an undirected graph''' + + def printKCores(self,k): + ''' INITIALIZATION + Mark all the vertices as not visited''' + + visited = [False]*self.V + ''' Store vDegrees of all vertices''' + + vDegree = [0]*self.V + for i in self.graph: + vDegree[i]=len(self.graph[i]) + self.DFSUtil(0,visited,vDegree,k) ''' DFS traversal to update vDegrees of all + vertices,in case they are unconnected''' + + for i in range(self.V): + if visited[i] ==False: + self.DFSUtil(i,k,vDegree,visited) + ''' PRINTING K CORES''' + + print ""\n K-cores: "" + for v in range(self.V): + ''' Only considering those vertices which have + vDegree >= K after DFS''' + + if vDegree[v] >= k: + print str(""\n [ "") + str(v) + str("" ]""), + ''' Traverse adjacency list of v and print only + those adjacent which have vvDegree >= k + after DFS''' + + for i in self.graph[v]: + if vDegree[i] >= k: + print ""-> "" + str(i), + ''' Driver Code''' + + ''' Create a graph given in the above diagram''' + +k = 3; +g1 = Graph (9); +g1.addEdge(0, 1) +g1.addEdge(0, 2) +g1.addEdge(1, 2) +g1.addEdge(1, 5) +g1.addEdge(2, 3) +g1.addEdge(2, 4) +g1.addEdge(2, 5) +g1.addEdge(2, 6) +g1.addEdge(3, 4) +g1.addEdge(3, 6) +g1.addEdge(3, 7) +g1.addEdge(4, 6) +g1.addEdge(4, 7) +g1.addEdge(5, 6) +g1.addEdge(5, 8) +g1.addEdge(6, 7) +g1.addEdge(6, 8) +g1.printKCores(k) +g2 = Graph(13); +g2.addEdge(0, 1) +g2.addEdge(0, 2) +g2.addEdge(0, 3) +g2.addEdge(1, 4) +g2.addEdge(1, 5) +g2.addEdge(1, 6) +g2.addEdge(2, 7) +g2.addEdge(2, 8) +g2.addEdge(2, 9) +g2.addEdge(3, 10) +g2.addEdge(3, 11) +g2.addEdge(3, 12) +g2.printKCores(k)" +Remove duplicates from an unsorted doubly linked list,"/*Java mplementation to remove duplicates +from an unsorted doubly linked list*/ + +import java.util.*; +class GFG +{ +/*a node of the doubly linked list*/ + +static class Node +{ + int data; + Node next; + Node prev; +}; +/*Function to delete a node in a Doubly Linked List. +head_ref --> pointer to head node pointer. +del --> pointer to node to be deleted.*/ + +static Node deleteNode(Node head_ref, Node del) +{ +/* base case*/ + + if (head_ref == null || del == null) + return null; +/* If node to be deleted is head node*/ + + if (head_ref == del) + head_ref = del.next; +/* Change next only if node to be deleted + is NOT the last node*/ + + if (del.next != null) + del.next.prev = del.prev; +/* Change prev only if node to be deleted + is NOT the first node*/ + + if (del.prev != null) + del.prev.next = del.next; + return head_ref; +} +/*function to remove duplicates from +an unsorted doubly linked list*/ + +static Node removeDuplicates(Node head_ref) +{ +/* if doubly linked list is empty*/ + + if ((head_ref) == null) + return null; +/* unordered_set 'us' implemented as hash table*/ + + HashSet us = new HashSet<>(); + Node current = head_ref, next; +/* traverse up to the end of the list*/ + + while (current != null) + { +/* if current data is seen before*/ + + if (us.contains(current.data)) + { +/* store pointer to the node next to + 'current' node*/ + + next = current.next; +/* delete the node pointed to by 'current'*/ + + head_ref = deleteNode(head_ref, current); +/* update 'current'*/ + + current = next; + } + else + { +/* insert the current data in 'us'*/ + + us.add(current.data); +/* move to the next node*/ + + current = current.next; + } + } + return head_ref; +} +/*Function to insert a node at the +beginning of the Doubly Linked List*/ + +static Node push(Node head_ref, + int new_data) +{ +/* allocate node*/ + + Node new_node = new Node(); +/* put in the data*/ + + new_node.data = new_data; +/* since we are adding at the beginning, + prev is always null*/ + + new_node.prev = null; +/* link the old list off the new node*/ + + new_node.next = (head_ref); +/* change prev of head node to new node*/ + + if ((head_ref) != null) + (head_ref).prev = new_node; +/* move the head to point to the new node*/ + + (head_ref) = new_node; + return head_ref; +} +/*Function to print nodes in a given doubly +linked list*/ + +static void printList(Node head) +{ +/* if list is empty*/ + + if (head == null) + System.out.print(""Doubly Linked list empty""); + while (head != null) + { + System.out.print(head.data + "" ""); + head = head.next; + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node head = null; +/* Create the doubly linked list: + 8<->4<->4<->6<->4<->8<->4<->10<->12<->12*/ + + head = push(head, 12); + head = push(head, 12); + head = push(head, 10); + head = push(head, 4); + head = push(head, 8); + head = push(head, 4); + head = push(head, 6); + head = push(head, 4); + head = push(head, 4); + head = push(head, 8); + System.out.println(""Original Doubly linked list:""); + printList(head); + /* remove duplicate nodes */ + + head = removeDuplicates(head); + System.out.println(""\nDoubly linked list after "" + + ""removing duplicates:""); + printList(head); +} +}"," '''Python3 implementation to remove duplicates +from an unsorted doubly linked list''' + + '''a node of the doubly linked list''' + +class Node: + def __init__(self): + self.data = 0 + self.next = None + self.prev = None '''Function to delete a node in a Doubly Linked List. +head_ref --> pointer to head node pointer. +del --> pointer to node to be deleted.''' + +def deleteNode( head_ref, del_): + ''' base case''' + + if (head_ref == None or del_ == None): + return None + ''' If node to be deleted is head node''' + + if (head_ref == del_): + head_ref = del_.next + ''' Change next only if node to be deleted + is NOT the last node''' + + if (del_.next != None): + del_.next.prev = del_.prev + ''' Change prev only if node to be deleted + is NOT the first node''' + + if (del_.prev != None): + del_.prev.next = del_.next + return head_ref + '''function to remove duplicates from +an unsorted doubly linked list''' + +def removeDuplicates(head_ref): + ''' if doubly linked list is empty''' + + if ((head_ref) == None): + return None + ''' unordered_set 'us' implemented as hash table''' + + us = set() + current = head_ref + next = None + ''' traverse up to the end of the list''' + + while (current != None): + ''' if current data is seen before''' + + if ((current.data) in us): + ''' store pointer to the node next to + 'current' node''' + + next = current.next + ''' delete the node pointed to by 'current''' + ''' + head_ref = deleteNode(head_ref, current) + ''' update 'current''' + ''' + current = next + else: + ''' insert the current data in 'us''' + ''' + us.add(current.data) + ''' move to the next node''' + + current = current.next + return head_ref + '''Function to insert a node at the +beginning of the Doubly Linked List''' + +def push(head_ref,new_data): + ''' allocate node''' + + new_node = Node() + ''' put in the data''' + + new_node.data = new_data + ''' since we are adding at the beginning, + prev is always None''' + + new_node.prev = None + ''' link the old list off the new node''' + + new_node.next = (head_ref) + ''' change prev of head node to new node''' + + if ((head_ref) != None): + (head_ref).prev = new_node + ''' move the head to point to the new node''' + + (head_ref) = new_node + return head_ref + '''Function to print nodes in a given doubly +linked list''' + +def printList( head): + ''' if list is empty''' + + if (head == None): + print(""Doubly Linked list empty"") + while (head != None): + print(head.data , end="" "") + head = head.next + '''Driver Code''' + +head = None + '''Create the doubly linked list: +8<->4<->4<->6<->4<->8<->4<->10<->12<->12''' + +head = push(head, 12) +head = push(head, 12) +head = push(head, 10) +head = push(head, 4) +head = push(head, 8) +head = push(head, 4) +head = push(head, 6) +head = push(head, 4) +head = push(head, 4) +head = push(head, 8) +print(""Original Doubly linked list:"") +printList(head) + '''remove duplicate nodes''' + +head = removeDuplicates(head) +print(""\nDoubly linked list after removing duplicates:"") +printList(head)" +Evaluation of Expression Tree,," '''Python program to evaluate expression tree''' + '''Class to represent the nodes of syntax tree''' + +class node: + def __init__(self, value): + self.left = None + self.data = value + self.right = None + '''This function receives a node of the syntax tree +and recursively evaluate it''' + +def evaluateExpressionTree(root): + ''' empty tree''' + + if root is None: + return 0 + ''' leaf node''' + + if root.left is None and root.right is None: + return int(root.data) + ''' evaluate left tree''' + + left_sum = evaluateExpressionTree(root.left) + ''' evaluate right tree''' + + right_sum = evaluateExpressionTree(root.right) + ''' check which operation to apply''' + + if root.data == '+': + return left_sum + right_sum + elif root.data == '-': + return left_sum - right_sum + elif root.data == '*': + return left_sum * right_sum + else: + return left_sum / right_sum + '''Driver function to test above problem''' + +if __name__=='__main__': + root = node('+') + root.left = node('*') + root.left.left = node('5') + root.left.right = node('4') + root.right = node('-') + root.right.left = node('100') + root.right.right = node('20') + print evaluateExpressionTree(root) + root = None + root = node('+') + root.left = node('*') + root.left.left = node('5') + root.left.right = node('4') + root.right = node('-') + root.right.left = node('100') + root.right.right = node('/') + root.right.right.left = node('20') + root.right.right.right = node('2') + print evaluateExpressionTree(root)" +Find sum of all nodes of the given perfect binary tree,"/*Java program to implement +the above approach*/ + +import java.util.*; +class GFG +{ +/*function to find sum of +all of the nodes of given +perfect binary tree*/ + +static int sumNodes(int l) +{ +/* no of leaf nodes*/ + + int leafNodeCount = (int)Math.pow(2, l - 1); +/* list of vector to store + nodes of all of the levels*/ + + Vector> vec = new Vector>(); +/* initialize*/ + + for (int i = 1; i <= l; i++) + vec.add(new Vector()); +/* store the nodes of last level + i.e., the leaf nodes*/ + + for (int i = 1; + i <= leafNodeCount; i++) + vec.get(l - 1).add(i); +/* store nodes of rest of + the level by moving in + bottom-up manner*/ + + for (int i = l - 2; i >= 0; i--) + { + int k = 0; +/* loop to calculate values + of parent nodes from the + children nodes of lower level*/ + + while (k < vec.get(i + 1).size() - 1) + { +/* store the value of parent + node as sum of children nodes*/ + + vec.get(i).add(vec.get(i + 1).get(k) + + vec.get(i + 1).get(k + 1)); + k += 2; + } + } + int sum = 0; +/* traverse the list of vector + and calculate the sum*/ + + for (int i = 0; i < l; i++) + { + for (int j = 0; + j < vec.get(i).size(); j++) + sum += vec.get(i).get(j); + } + return sum; +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int l = 3; + System.out.println(sumNodes(l)); +} +}"," '''Python3 program to implement the +above approach''' + + '''function to find Sum of all of the +nodes of given perfect binary tree''' + +def SumNodes(l): ''' no of leaf nodes''' + + leafNodeCount = pow(2, l - 1) + ''' list of vector to store nodes of + all of the levels''' + + vec = [[] for i in range(l)] + ''' store the nodes of last level + i.e., the leaf nodes''' + + for i in range(1, leafNodeCount + 1): + vec[l - 1].append(i) + ''' store nodes of rest of the level + by moving in bottom-up manner''' + + for i in range(l - 2, -1, -1): + k = 0 + ''' loop to calculate values of parent nodes + from the children nodes of lower level''' + + while (k < len(vec[i + 1]) - 1): + ''' store the value of parent node as + Sum of children nodes''' + + vec[i].append(vec[i + 1][k] + + vec[i + 1][k + 1]) + k += 2 + Sum = 0 + ''' traverse the list of vector + and calculate the Sum''' + + for i in range(l): + for j in range(len(vec[i])): + Sum += vec[i][j] + return Sum + '''Driver Code''' + +if __name__ == '__main__': + l = 3 + print(SumNodes(l))" +Count subarrays with same even and odd elements,"/*Java program to find total +number of even-odd subarrays +present in given array*/ + +class GFG { +/* function that returns the + count of subarrays that + contain equal number of + odd as well as even numbers*/ + + static int countSubarrays(int[] arr, + int n) { +/* initialize difference + and answer with 0*/ + + int difference = 0; + int ans = 0; +/* create two auxiliary hash + arrays to count frequency + of difference, one array + for non-negative difference + and other array for negative + difference. Size of these + two auxiliary arrays is 'n+1' + because difference can + reach maximum value 'n' as + well as minimum value '-n'*/ + +/* initialize these + auxiliary arrays with 0*/ + + int[] hash_positive = new int[n + 1]; + int[] hash_negative = new int[n + 1];/* since the difference is + initially 0, we have to + initialize hash_positive[0] with 1*/ + + hash_positive[0] = 1; +/* for loop to iterate + through whole array + (zero-based indexing is used)*/ + + for (int i = 0; i < n; i++) { +/* incrementing or decrementing + difference based on + arr[i] being even or odd, + check if arr[i] is odd*/ + + if ((arr[i] & 1) == 1) { + difference++; + } else { + difference--; + } +/* adding hash value of 'difference' + to our answer as all the previous + occurrences of the same difference + value will make even-odd subarray + ending at index 'i'. After that, + we will increment hash array for + that 'difference' value for its + occurrence at index 'i'. if + difference is negative then use + hash_negative*/ + + if (difference < 0) { + ans += hash_negative[-difference]; + hash_negative[-difference]++; +/*else use hash_positive*/ + +} + else { + ans += hash_positive[difference]; + hash_positive[difference]++; + } + } +/* return total number + of even-odd subarrays*/ + + return ans; + } +/* Driver code*/ + + public static void main(String[] args) { + int[] arr = new int[]{3, 4, 6, 8, + 1, 10, 5, 7}; + int n = arr.length; +/* Printing total number + of even-odd subarrays*/ + + System.out.println(""Total Number of Even-Odd"" + + "" subarrays are "" + + countSubarrays(arr, n)); + } +}"," '''Python3 program to find total +number of even-odd subarrays +present in given array''' + + '''function that returns the count +of subarrays that contain equal +number of odd as well as even numbers''' + +def countSubarrays(arr, n): ''' initialize difference and + answer with 0''' + + difference = 0 + ans = 0 + ''' create two auxiliary hash + arrays to count frequency + of difference, one array + for non-negative difference + and other array for negative + difference. Size of these two + auxiliary arrays is 'n+1' + because difference can reach + maximum value 'n' as well as + minimum value -n ''' + + ''' initialize these + auxiliary arrays with 0''' + + hash_positive = [0] * (n + 1) + hash_negative = [0] * (n + 1) ''' since the difference is + initially 0, we have to + initialize hash_positive[0] with 1''' + + hash_positive[0] = 1 + ''' for loop to iterate through + whole array (zero-based + indexing is used)''' + + for i in range(n): + ''' incrementing or decrementing + difference based on arr[i] + being even or odd, check if + arr[i] is odd''' + + if (arr[i] & 1 == 1): + difference = difference + 1 + else: + difference = difference - 1 + ''' adding hash value of 'difference' + to our answer as all the previous + occurrences of the same difference + value will make even-odd subarray + ending at index 'i'. After that, + we will increment hash array for + that 'difference' value for + its occurrence at index 'i'. if + difference is negative then use + hash_negative''' + + if (difference < 0): + ans += hash_negative[-difference] + hash_negative[-difference] = hash_negative[-difference] + 1 + ''' else use hash_positive''' + + else: + ans += hash_positive[difference] + hash_positive[difference] = hash_positive[difference] + 1 + ''' return total number of + even-odd subarrays''' + + return ans + '''Driver code''' + +arr = [3, 4, 6, 8, 1, 10, 5, 7] +n = len(arr) + '''Printing total number +of even-odd subarrays''' + +print(""Total Number of Even-Odd subarrays are "" + + str(countSubarrays(arr, n)))" +Group multiple occurrence of array elements ordered by first occurrence,"/* Java program to group multiple occurrences of individual array elements */ + +import java.util.HashMap; +class Main +{ +/* A hashing based method to group all occurrences of individual elements*/ + + static void orderedGroup(int arr[]) + { +/* Creates an empty hashmap*/ + + HashMap hM = new HashMap(); +/* Traverse the array elements, and store count for every element + in HashMap*/ + + for (int i=0; i queue = new LinkedList(); +/* Do level order traversal starting from root*/ + + queue.add(root); +/*Initialize count of full nodes*/ + +int count=0; + while (!queue.isEmpty()) + { + Node temp = queue.poll(); + if (temp.left!=null && temp.right!=null) + count++; +/* Enqueue left child */ + + if (temp.left != null) + { + queue.add(temp.left); + } +/* Enqueue right child */ + + if (temp.right != null) + { + queue.add(temp.right); + } + } + return count; + } + + /*Driver program */ + + public static void main(String args[]) + {/* 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree as shown + */ + + BinaryTree tree_level = new BinaryTree(); + tree_level.root = new Node(2); + tree_level.root.left = new Node(7); + tree_level.root.right = new Node(5); + tree_level.root.left.right = new Node(6); + tree_level.root.left.right.left = new Node(1); + tree_level.root.left.right.right = new Node(11); + tree_level.root.right.right = new Node(9); + tree_level.root.right.right.left = new Node(4); + System.out.println(tree_level.getfullCount()); + } +}"," '''Python program to count +full nodes in a Binary Tree +using iterative approach''' + + '''A node structure''' + +class Node: + def __init__(self ,key): + self.data = key + self.left = None + self.right = None + '''Iterative Method to count full nodes of binary tree''' + +def getfullCount(root): + ''' Base Case''' + + if root is None: + return 0 + ''' Create an empty queue for level order traversal''' + + queue = [] + ''' Enqueue Root and initialize count''' + + queue.append(root) + '''initialize count for full nodes''' + + count = 0 + while(len(queue) > 0): + node = queue.pop(0) + if node.left is not None and node.right is not None: + count = count+1 ''' Enqueue left child''' + + if node.left is not None: + queue.append(node.left) + ''' Enqueue right child''' + + if node.right is not None: + queue.append(node.right) + return count + '''Driver Program to test above function''' + + ''' 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree as shown + ''' +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) +print ""%d"" %(getfullCount(root))" +Merge k sorted arrays | Set 1,"/*Java program to merge k sorted arrays of size n each.*/ + +import java.io.*; +import java.util.*; +class GFG { +/* This function takes an array of arrays as an argument + and + All arrays are assumed to be sorted. It merges them + together and prints the final sorted output.*/ + + public static void mergeKArrays(int[][] arr, int a, + int[] output) + { + int c = 0; +/* traverse the matrix*/ + + for (int i = 0; i < a; i++) { + for (int j = 0; j < 4; j++) + output[c++] = arr[i][j]; + } +/* sort the array*/ + + Arrays.sort(output); + } +/* A utility function to print array elements*/ + + public static void printArray(int[] arr, int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int[][] arr = { { 2, 6, 12, 34 }, + { 1, 9, 20, 1000 }, + { 23, 34, 90, 2000 } }; + int k = 4; + int n = 3; + int[] output = new int[n * k]; + mergeKArrays(arr, n, output); + System.out.println(""Merged array is ""); + printArray(output, n * k); + } +}", +k-th missing element in sorted array,"/*Java program for above approach*/ + +public class GFG +{ + +/* Function to find + kth missing number*/ + + static int missingK(int[] arr, int k) + { + int n = arr.length; + int l = 0, u = n - 1, mid; + while(l <= u) + { + mid = (l + u)/2; + int numbers_less_than_mid = arr[mid] - + (mid + 1); + +/* If the total missing number + count is equal to k we can iterate + backwards for the first missing number + and that will be the answer.*/ + + if(numbers_less_than_mid == k) + { + +/* To further optimize we check + if the previous element's + missing number count is equal + to k. Eg: arr = [4,5,6,7,8] + If you observe in the example array, + the total count of missing numbers for all + the indices are same, and we are + aiming to narrow down the + search window and achieve O(logn) + time complexity which + otherwise would've been O(n).*/ + + if(mid > 0 && (arr[mid - 1] - (mid)) == k) + { + u = mid - 1; + continue; + } + +/* Else we return arr[mid] - 1.*/ + + return arr[mid] - 1; + } + +/* Here we appropriately + narrow down the search window.*/ + + if(numbers_less_than_mid < k) + { + l = mid + 1; + } + else if(k < numbers_less_than_mid) + { + u = mid - 1; + } + } + +/* In case the upper limit is -ve + it means the missing number set + is 1,2,..,k and hence we directly return k.*/ + + if(u < 0) + return k; + +/* Else we find the residual count + of numbers which we'd then add to + arr[u] and get the missing kth number.*/ + + int less = arr[u] - (u + 1); + k -= less; + +/* Return arr[u] + k*/ + + return arr[u] + k; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int[] arr = {2,3,4,7,11}; + int k = 5; + +/* Function Call*/ + + System.out.println(""Missing kth number = ""+ missingK(arr, k)); + } +} + + +"," '''Python3 program for above approach''' + + + '''Function to find +kth missing number''' + +def missingK(arr, k): + n = len(arr) + l = 0 + u = n - 1 + mid = 0 + while(l <= u): + mid = (l + u)//2; + numbers_less_than_mid = arr[mid] - (mid + 1); + + ''' If the total missing number + count is equal to k we can iterate + backwards for the first missing number + and that will be the answer.''' + + if(numbers_less_than_mid == k): + + ''' To further optimize we check + if the previous element's + missing number count is equal + to k. Eg: arr = [4,5,6,7,8] + If you observe in the example array, + the total count of missing numbers for all + the indices are same, and we are + aiming to narrow down the + search window and achieve O(logn) + time complexity which + otherwise would've been O(n).''' + + if(mid > 0 and (arr[mid - 1] - (mid)) == k): + u = mid - 1; + continue; + + ''' Else we return arr[mid] - 1.''' + + return arr[mid]-1; + + ''' Here we appropriately + narrow down the search window.''' + + if(numbers_less_than_mid < k): + l = mid + 1; + elif(k < numbers_less_than_mid): + u = mid - 1; + + ''' In case the upper limit is -ve + it means the missing number set + is 1,2,..,k and hence we directly return k.''' + + if(u < 0): + return k; + + ''' Else we find the residual count + of numbers which we'd then add to + arr[u] and get the missing kth number.''' + + less = arr[u] - (u + 1); + k -= less; + + ''' Return arr[u] + k''' + + return arr[u] + k; + + '''Driver Code''' + +if __name__=='__main__': + + arr = [2,3,4,7,11]; + k = 5; + + ''' Function Call''' + + print(""Missing kth number = ""+ str(missingK(arr, k))) + + +" +Check if the given array can represent Level Order Traversal of Binary Search Tree,"/*Java implementation to check if the given array +can represent Level Order Traversal of Binary +Search Tree*/ + +import java.util.*; +class Solution +{ +/*to store details of a node like +node's data, 'min' and 'max' to obtain the +range of values where node's left and +right child's should lie*/ + +static class NodeDetails +{ + int data; + int min, max; +}; +/*function to check if the given array +can represent Level Order Traversal +of Binary Search Tree*/ + +static boolean levelOrderIsOfBST(int arr[], int n) +{ +/* if tree is empty*/ + + if (n == 0) + return true; +/* queue to store NodeDetails*/ + + Queue q = new LinkedList(); +/* index variable to access array elements*/ + + int i = 0; +/* node details for the + root of the BST*/ + + NodeDetails newNode=new NodeDetails(); + newNode.data = arr[i++]; + newNode.min = Integer.MIN_VALUE; + newNode.max = Integer.MAX_VALUE; + q.add(newNode); +/* until there are no more elements + in arr[] or queue is not empty*/ + + while (i != n && q.size() > 0) + { +/* extracting NodeDetails of a + node from the queue*/ + + NodeDetails temp = q.peek(); + q.remove(); + newNode = new NodeDetails(); +/* check whether there are more elements + in the arr[] and arr[i] can be left child + of 'temp.data' or not */ + + if (i < n && (arr[i] < (int)temp.data && + arr[i] > (int)temp.min)) + { +/* Create NodeDetails for newNode +and add it to the queue*/ + + newNode.data = arr[i++]; + newNode.min = temp.min; + newNode.max = temp.data; + q.add(newNode); + } + newNode=new NodeDetails(); +/* check whether there are more elements + in the arr[] and arr[i] can be right child + of 'temp.data' or not */ + + if (i < n && (arr[i] > (int)temp.data && + arr[i] < (int)temp.max)) + { +/* Create NodeDetails for newNode +and add it to the queue*/ + + newNode.data = arr[i++]; + newNode.min = temp.data; + newNode.max = temp.max; + q.add(newNode); + } + } +/* given array represents level + order traversal of BST*/ + + if (i == n) + return true; +/* given array do not represent + level order traversal of BST */ + + return false; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}; + int n = arr.length; + if (levelOrderIsOfBST(arr, n)) + System.out.print( ""Yes""); + else + System.out.print( ""No""); +} +}"," '''Python3 implementation to check if the +given array can represent Level Order +Traversal of Binary Search Tree ''' '''To store details of a node like node's +data, 'min' and 'max' to obtain the +range of values where node's left +and right child's should lie ''' + +class NodeDetails: + def __init__(self, data, min, max): + self.data = data + self.min = min + self.max = max + '''function to check if the given array +can represent Level Order Traversal +of Binary Search Tree ''' + +def levelOrderIsOfBST(arr, n): + ''' if tree is empty ''' + + if n == 0: + return True + ''' queue to store NodeDetails ''' + + q = [] + ''' index variable to access array elements ''' + + i = 0 + ''' node details for the root of the BST ''' + + newNode = NodeDetails(arr[i], INT_MIN, INT_MAX) + i += 1 + q.append(newNode) + ''' until there are no more elements + in arr[] or queue is not empty ''' + + while i != n and len(q) != 0: + ''' extracting NodeDetails of a + node from the queue ''' + + temp = q.pop(0) + ''' check whether there are more elements + in the arr[] and arr[i] can be left + child of 'temp.data' or not ''' + + if i < n and (arr[i] < temp.data and + arr[i] > temp.min): + ''' Create NodeDetails for newNode + / and add it to the queue ''' + + newNode = NodeDetails(arr[i], temp.min, temp.data) + i += 1 + q.append(newNode) + ''' check whether there are more elements + in the arr[] and arr[i] can be right + child of 'temp.data' or not ''' + + if i < n and (arr[i] > temp.data and + arr[i] < temp.max): + ''' Create NodeDetails for newNode + / and add it to the queue ''' + + newNode = NodeDetails(arr[i], temp.data, temp.max) + i += 1 + q.append(newNode) + ''' given array represents level + order traversal of BST ''' + + if i == n: + return True + ''' given array do not represent + level order traversal of BST ''' + + return False + '''Driver code''' + +if __name__ == ""__main__"": + arr = [7, 4, 12, 3, 6, 8, 1, 5, 10] + n = len(arr) + if levelOrderIsOfBST(arr, n): + print(""Yes"") + else: + print(""No"")" +Check if an array is stack sortable,"/*Java implementation of above approach.*/ + +import java.util.Stack; +class GFG { +/*Function to check if A[] is +Stack Sortable or Not.*/ + + static boolean check(int A[], int N) { +/* Stack S*/ + + Stack S = new Stack(); +/* Pointer to the end value of array B.*/ + + int B_end = 0; +/* Traversing each element of A[] from starting + Checking if there is a valid operation + that can be performed.*/ + + for (int i = 0; i < N; i++) { +/* If the stack is not empty*/ + + if (!S.empty()) { +/* Top of the Stack.*/ + + int top = S.peek(); +/* If the top of the stack is + Equal to B_end+1, we will pop it + And increment B_end by 1.*/ + + while (top == B_end + 1) { +/* if current top is equal to + B_end+1, we will increment + B_end to B_end+1*/ + + B_end = B_end + 1; +/* Pop the top element.*/ + + S.pop(); +/* If the stack is empty We cannot + further perfom this operation. + Therefore break*/ + + if (S.empty()) { + break; + } +/* Current Top*/ + + top = S.peek(); + } +/* If stack is empty + Push the Current element*/ + + if (S.empty()) { + S.push(A[i]); + } else { + top = S.peek(); +/* If the Current element of the array A[] + if smaller than the top of the stack + We can push it in the Stack.*/ + + if (A[i] < top) { + S.push(A[i]); +/*Else We cannot sort the array Using any valid operations.*/ + +} + else {/* Not Stack Sortable*/ + + return false; + } + } + } else { +/* If the stack is empty push the current + element in the stack.*/ + + S.push(A[i]); + } + } +/* Stack Sortable*/ + + return true; + } +/*Driver's Code*/ + + public static void main(String[] args) { + int A[] = {4, 1, 2, 3}; + int N = A.length; + if (check(A, N)) { + System.out.println(""YES""); + } else { + System.out.println(""NO""); + } + } +}", +Find the two repeating elements in a given array,"/*Java code to Find the +two repeating elements +in a given array*/ + +class RepeatElement +{ + void printRepeating(int arr[], int size) + { + /* Will hold xor of all elements */ + + int xor = arr[0]; + /* Will have only single set bit of xor */ + + int set_bit_no; + int i; + int n = size - 2; + int x = 0, y = 0; + /* Get the xor of all elements in arr[] and {1, 2 .. n} */ + + for (i = 1; i < size; i++) + xor ^= arr[i]; + for (i = 1; i <= n; i++) + xor ^= i; + /* Get the rightmost set bit in set_bit_no */ + + set_bit_no = (xor & ~(xor - 1)); + /* Now divide elements in two sets by comparing rightmost set + bit of xor with bit at same position in each element. */ + + for (i = 0; i < size; i++) { + int a = arr[i] & set_bit_no; + if (a != 0) + x = x ^ arr[i]; /*XOR of first set in arr[] */ + + else + y = y ^ arr[i]; /*XOR of second set in arr[] */ + + } + for (i = 1; i <= n; i++) + { + int a = i & set_bit_no; + if (a != 0) + x = x ^ i; /*XOR of first set in arr[] and {1, 2, ...n }*/ + + else + y = y ^ i; /*XOR of second set in arr[] and {1, 2, ...n } */ + + } + System.out.println(""The two reppeated elements are :""); + System.out.println(x + "" "" + y); + } + /* Driver program to test the above function */ + + public static void main(String[] args) + { + RepeatElement repeat = new RepeatElement(); + int arr[] = {4, 2, 4, 5, 2, 3, 1}; + int arr_size = arr.length; + repeat.printRepeating(arr, arr_size); + } +}"," '''Python3 code to Find the +two repeating elements +in a given array''' + +def printRepeating(arr, size): + ''' Will hold xor + of all elements''' + + xor = arr[0] + + '''Will have only single set bit of xor''' + + n = size - 2 + x = 0 + y = 0 ''' Get the xor of all + elements in arr[] + and 1, 2 .. n''' + + for i in range(1 , size): + xor ^= arr[i] + for i in range(1 , n + 1): + xor ^= i + ''' Get the rightmost set + bit in set_bit_no''' + + set_bit_no = xor & ~(xor-1) + ''' Now divide elements in two + sets by comparing rightmost + set bit of xor with bit at + same position in each element.''' + + for i in range(0, size): + if(arr[i] & set_bit_no): + x = x ^ arr[i] ''' XOR of first + set in arr[]''' + + else: + y = y ^ arr[i] ''' XOR of second + set in arr[]''' + + + for i in range(1 , n + 1): + if(i & set_bit_no): + x = x ^ i ''' XOR of first set + in arr[] and + 1, 2, ...n''' + + else: + y = y ^ i ''' XOR of second set + in arr[] and + 1, 2, ...n''' + + + print(""The two repeating"", + ""elements are"", y, x) + '''Driver code ''' + +arr = [4, 2, 4, + 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size)" +Number of subtrees having odd count of even numbers,"/*Java implementation to find number of +subtrees having odd count of even numbers */ + +import java.util.*; +class GfG { +/* A binary tree Node */ + +static class Node +{ + int data; + Node left, right; +} +/* Helper function that allocates a new Node with the +given data and NULL left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return(node); +} + +static class P +{ + int pcount = 0; +}/*Returns count of subtrees having odd count of +even numbers*/ + +static int countRec(Node root, P p) +{ +/* base condition */ + + if (root == null) + return 0; +/* count even nodes in left subtree */ + + int c = countRec(root.left, p); +/* Add even nodes in right subtree */ + + c += countRec(root.right, p); +/* Check if root data is an even number */ + + if (root.data % 2 == 0) + c += 1; +/* if total count of even numbers + for the subtree is odd */ + + if (c % 2 != 0) + (p.pcount)++; +/* Total count of even nodes of the subtree */ + + return c; +} +/*A wrapper over countRec() */ + +static int countSubtrees(Node root) +{ + P p = new P(); + countRec(root, p); + return p.pcount; +} +/*Driver program to test above */ + +public static void main(String[] args) +{ +/* binary tree formation */ + + Node root = newNode(2); /* 2 */ + + root.left = newNode(1); /* / \ */ + + root.right = newNode(3); /* 1 3 */ + + root.left.left = newNode(4); /* / \ / \ */ + + root.left.right = newNode(10); /* 4 10 8 5 */ + + root.right.left = newNode(8); /* / */ + + root.right.right = newNode(5); /* 6 */ + + root.left.right.left = newNode(6); +System.out.println(""Count = "" + countSubtrees(root)); +} +}"," '''Python3 implementation to find number of +subtrees having odd count of even numbers ''' + '''Helper class that allocates a new Node +with the given data and None left and +right pointers. ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Returns count of subtrees having odd +count of even numbers ''' + +def countRec(root, pcount): + ''' base condition ''' + + if (root == None): + return 0 + ''' count even nodes in left subtree ''' + + c = countRec(root.left, pcount) + ''' Add even nodes in right subtree ''' + + c += countRec(root.right, pcount) + ''' Check if root data is an even number ''' + + if (root.data % 2 == 0): + c += 1 + ''' if total count of even numbers + for the subtree is odd ''' + + if c % 2 != 0: + pcount[0] += 1 + ''' Total count of even nodes of + the subtree ''' + + return c + '''A wrapper over countRec() ''' + +def countSubtrees(root): + count = [0] + pcount = count + countRec(root, pcount) + return count[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree formation + 2 ''' + + root = newNode(2) + ''' / \ ''' + + root.left = newNode(1) + ''' 1 3 ''' + + root.right = newNode(3) + '''/ \ / \ ''' + + root.left.left = newNode(4) + '''4 10 8 5 ''' + + root.left.right = newNode(10) + ''' / ''' + + root.right.left = newNode(8) + ''' 6 ''' + + root.right.right = newNode(5) + root.left.right.left = newNode(6) + print(""Count = "", countSubtrees(root))" +Print Left View of a Binary Tree,"/*Java program to print left view of Binary +Tree*/ + +import java.util.*; + +public class PrintRightView { +/* Binary tree node*/ + + private static class Node { + int data; + Node left, right; + + public Node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } + } + +/* function to print left view of binary tree*/ + + private static void printLeftView(Node root) + { + if (root == null) + return; + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { +/* number of nodes at current level*/ + + int n = queue.size(); + +/* Traverse all nodes of current level*/ + + for (int i = 1; i <= n; i++) { + Node temp = queue.poll(); + +/* Print the left most element at + the level*/ + + if (i == 1) + System.out.print(temp.data + "" ""); + +/* Add left node to queue*/ + + if (temp.left != null) + queue.add(temp.left); + +/* Add right node to queue*/ + + if (temp.right != null) + queue.add(temp.right); + } + } + } + +/* Driver code*/ + + public static void main(String[] args) + { +/* construct binary tree as shown in + above diagram*/ + + Node root = new Node(10); + root.left = new Node(2); + root.right = new Node(3); + root.left.left = new Node(7); + root.left.right = new Node(8); + root.right.right = new Node(15); + root.right.left = new Node(12); + root.right.right.left = new Node(14); + + printLeftView(root); + } +} + + +"," '''Python3 program to print left view of +Binary Tree''' + + + '''Utility function to create a new tree node''' + + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + self.hd = 0 + + '''function to print left view of +binary tree''' + + + +def printRightView(root): + + if (not root): + return + + q = [] + q.append(root) + + while (len(q)): + + ''' number of nodes at current level''' + + n = len(q) + + ''' Traverse all nodes of current level''' + + for i in range(1, n + 1): + temp = q[0] + q.pop(0) + + ''' Print the left most element + at the level''' + + if (i == 1): + print(temp.data, end="" "") + + ''' Add left node to queue''' + + if (temp.left != None): + q.append(temp.left) + + ''' Add right node to queue''' + + if (temp.right != None): + q.append(temp.right) + + + '''Driver Code''' + +if __name__ == '__main__': + + + + ''' construct binary tree as shown in + above diagram''' + + + 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) + printRightView(root)" +Count number of rotated strings which have more number of vowels in the first half than second half,"/*Java implementation of +the approach*/ + +class GFG{ + +/*Function to return the count of +rotated strings which have more +number of vowels in the first +half than the second half*/ + +public static int cntRotations(char s[], + int n) +{ + int lh = 0, rh = 0, i, ans = 0; + +/* Compute the number of + vowels in first-half*/ + + for (i = 0; i < n / 2; ++i) + if (s[i] == 'a' || s[i] == 'e' || + s[i] == 'i' || s[i] == 'o' || + s[i] == 'u') + { + lh++; + } + +/* Compute the number of + vowels in second-half*/ + + for (i = n / 2; i < n; ++i) + if (s[i] == 'a' || s[i] == 'e' || + s[i] == 'i' || s[i] == 'o' || + s[i] == 'u') + { + rh++; + } + +/* Check if first-half + has more vowels*/ + + if (lh > rh) + ans++; + +/* Check for all possible + rotations*/ + + 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 the answer*/ + + return ans; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + char s[] = {'a','b','e','c', + 'i','d','f','t'}; + int n = s.length; + +/* Function call*/ + + System.out.println( + cntRotations(s, n)); +} +} + + +"," '''Python3 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''' + +def cntRotations(s, n): + + lh, rh, ans = 0, 0, 0 + + ''' Compute the number of + vowels in first-half''' + + for i in range (n // 2): + if (s[i] == 'a' or s[i] == 'e' or + s[i] == 'i' or s[i] == 'o' or + s[i] == 'u'): + lh += 1 + + ''' Compute the number of + vowels in second-half''' + + for i in range (n // 2, n): + if (s[i] == 'a' or s[i] == 'e' or + s[i] == 'i' or s[i] == 'o' or + s[i] == 'u'): + rh += 1 + + ''' Check if first-half + has more vowels''' + + if (lh > rh): + ans += 1 + + ''' Check for all possible rotations''' + + for i in range (1, n): + if (s[i - 1] == 'a' or s[i - 1] == 'e' or + s[i - 1] == 'i' or s[i - 1] == 'o' or + s[i - 1] == 'u'): + rh += 1 + lh -= 1 + + if (s[(i - 1 + n // 2) % n] == 'a' or + s[(i - 1 + n // 2) % n] == 'e' or + s[(i - 1 + n // 2) % n] == 'i' or + s[(i - 1 + n // 2) % n] == 'o' or + s[(i - 1 + n // 2) % n] == 'u'): + rh -= 1 + lh += 1 + + if (lh > rh): + ans += 1 + + ''' Return the answer''' + + return ans + + '''Driver code''' + +if __name__ == ""__main__"": + + s = ""abecidft"" + n = len(s) + + ''' Function call''' + + print(cntRotations(s, n)) + + +" +"Write a program to calculate pow(x,n)","/* Function to calculate x raised to the power y in O(logn)*/ + +static int power(int x, int y) +{ + int temp; + if( y == 0) + return 1; + temp = power(x, y / 2); + if (y % 2 == 0) + return temp*temp; + else + return x*temp*temp; +}"," '''Function to calculate x raised to the power y in O(logn)''' + +def power(x,y): + temp = 0 + if( y == 0): + return 1 + temp = power(x, int(y / 2)) + if (y % 2 == 0): + return temp * temp; + else: + return x * temp * temp;" +Count pairs from two linked lists whose sum is equal to a given value,"/*Java implementation to count pairs from both linked +lists whose sum is equal to a given value +Note : here we use java.util.LinkedList for +linked list implementation*/ + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedList; +class GFG +{ +/* method to count all pairs from both the linked lists + whose sum is equal to a given value*/ + + static int countPairs(LinkedList head1, LinkedList head2, int x) + { + int count = 0; +/* traverse the 1st linked list*/ + + Iterator itr1 = head1.iterator(); + while(itr1.hasNext()) + { +/* for each node of 1st list + traverse the 2nd list*/ + + Iterator itr2 = head2.iterator(); + Integer t = itr1.next(); + while(itr2.hasNext()) + { +/* if sum of pair is equal to 'x' + increment count*/ + + if ((t + itr2.next()) == x) + count++; + } + } +/* required count of pairs */ + + return count; + } +/* Driver method*/ + + public static void main(String[] args) + { + Integer arr1[] = {3, 1, 5, 7}; + Integer arr2[] = {8, 2, 5, 3}; + LinkedList head1 = new LinkedList<>(Arrays.asList(arr1)); + LinkedList head2 = new LinkedList<>(Arrays.asList(arr2)); + int x = 10; + System.out.println(""Count = "" + countPairs(head1, head2, x)); + } +}"," '''Python3 implementation to count pairs from both linked +lists whose sum is equal to a given value''' + '''A Linked list node''' + +class Node: + def __init__(self,data): + self.data = data + self.next = None +def push(head_ref,new_data): + new_node=Node(new_data) + new_node.next = head_ref + head_ref = new_node + return head_ref '''function to count all pairs from both the linked lists +whose sum is equal to a given value''' + +def countPairs(head1, head2, x): + count = 0 + ''' traverse the 1st linked list''' + + p1 = head1 + while(p1 != None): + ''' for each node of 1st list + traverse the 2nd list''' + + p2 = head2 + while(p2 != None): + ''' if sum of pair is equal to 'x' + increment count''' + + if ((p1.data + p2.data) == x): + count+=1 + p2 = p2.next + p1 = p1.next + ''' required count of pairs ''' + + return count + '''Driver program to test above''' + +if __name__=='__main__': + head1 = None + head2 = None + head1=push(head1, 7) + head1=push(head1, 5) + head1=push(head1, 1) + head1=push(head1, 3) + head2=push(head2, 3) + head2=push(head2, 5) + head2=push(head2, 2) + head2=push(head2, 8) + x = 10 + print(""Count = "",countPairs(head1, head2, x))" +Binary Tree | Set 1 (Introduction),"/* Class containing left and right child of current + node and key value*/ + + +/* Class containing left and right child +of current node and key value*/ + +class Node +{ + int key; + Node left, right; + public Node(int item) + { + key = item; + left = right = null; + } +}/*Binary Tree*/ + +class BinaryTree +{ + Node root; + + BinaryTree(int key) + { + root = new Node(key); + } + BinaryTree() + { + root = null; + } +/*Driver code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + } +}"," '''Python program to introduce Binary Tree +A class that represents an individual node in a +Binary Tree''' + + '''Class containing left and right child +of current node and key value''' + +class Node: + def __init__(self,key): + self.left = None + self.right = None + self.val = key + '''Driver code''' + +root = Node(1) +root.left = Node(2); +root.right = Node(3); +root.left.left = Node(4); + + + +" +Detect loop in a linked list,"/*Java program to return first node of loop*/ + +class GFG { + static class Node { + int key; + Node next; + }; + static Node newNode(int key) + { + Node temp = new Node(); + temp.key = key; + temp.next = null; + return temp; + } +/* A utility function to print a linked list*/ + + static void printList(Node head) + { + while (head != null) { + System.out.print(head.key + "" ""); + head = head.next; + } + System.out.println(); + } +/* Function to detect first node of loop + in a linked list that may contain loop*/ + + static boolean detectLoop(Node head) + { +/* Create a temporary node*/ + + Node temp = new Node(); + while (head != null) { +/* This condition is for the case + when there is no loop*/ + + if (head.next == null) { + return false; + } +/* Check if next is already + pointing to temp*/ + + if (head.next == temp) { + return true; + } +/* Store the pointer to the next node + in order to get to it in the next step*/ + + Node nex = head.next; +/* Make next point to temp*/ + + head.next = temp; +/* Get to the next node in the list*/ + + head = nex; + } + return false; + } +/* Driver code*/ + + public static void main(String args[]) + { + 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); +/* Create a loop for testing(5 is pointing to 3) /*/ + + head.next.next.next.next.next = head.next.next; + boolean found = detectLoop(head); + if (found) + System.out.println(""Loop Found""); + else + System.out.println(""No Loop""); + } +}"," '''Python3 program to return first node of loop +A binary tree node has data, pointer to +left child and a pointer to right child +Helper function that allocates a new node +with the given data and None left and +right pointers''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''A utility function to pra linked list''' + +def printList(head): + while (head != None): + print(head.key, end="" "") + head = head.next + print() + '''Function to detect first node of loop +in a linked list that may contain loop''' + +def detectLoop(head): + ''' Create a temporary node''' + + temp = """" + while (head != None): + ''' This condition is for the case + when there is no loop''' + + if (head.next == None): + return False + ''' Check if next is already + pointing to temp''' + + if (head.next == temp): + return True + ''' Store the pointer to the next node + in order to get to it in the next step''' + + nex = head.next + ''' Make next poto temp''' + + head.next = temp + ''' Get to the next node in the list''' + + head = nex + return False + '''Driver Code''' + +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) + '''Create a loop for testing(5 is pointing to 3)''' + +head.next.next.next.next.next = head.next.next +found = detectLoop(head) +if (found): + print(""Loop Found"") +else: + print(""No Loop"")" +Level with maximum number of nodes,"/*Java implementation to find the level +having maximum number of Nodes */ + +import java.util.*; +class GfG { +/* A binary tree Node has data, pointer +to left child and a pointer to right +child */ + +static class Node +{ + int data; + Node left; + Node right; +} +/* Helper function that allocates a new node with the +given data and NULL left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return(node); +} +/*function to find the level +having maximum number of Nodes */ + +static int maxNodeLevel(Node root) +{ + if (root == null) + return -1; + Queue q = new LinkedList (); + q.add(root); +/* Current level */ + + int level = 0; +/* Maximum Nodes at same level */ + + int max = Integer.MIN_VALUE; +/* Level having maximum Nodes */ + + int level_no = 0; + while (true) + { +/* Count Nodes in a level */ + + int NodeCount = q.size(); + if (NodeCount == 0) + break; +/* If it is maximum till now + Update level_no to current level */ + + if (NodeCount > max) + { + max = NodeCount; + level_no = level; + } +/* Pop complete current level */ + + while (NodeCount > 0) + { + Node Node = q.peek(); + q.remove(); + if (Node.left != null) + q.add(Node.left); + if (Node.right != null) + q.add(Node.right); + NodeCount--; + } +/* Increment for next level */ + + level++; + } + return level_no; +} +/*Driver program to test above */ + +public static void main(String[] args) +{ +/* binary tree formation */ + + Node root = newNode(2); /* 2 */ + + root.left = newNode(1); /* / \ */ + + root.right = newNode(3); /* 1 3 */ + + root.left.left = newNode(4); /* / \ \ */ + + root.left.right = newNode(6); /* 4 6 8 */ + + root.right.right = newNode(8); /* / */ + + root.left.right.left = newNode(5);/* 5 */ + + System.out.println(""Level having maximum number of Nodes : "" + maxNodeLevel(root)); +} +}"," '''Python3 implementation to find the +level having Maximum number of Nodes +Importing Queue''' + +from queue import Queue + '''Helper class that allocates a new +node with the given data and None +left and right pointers. ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''function to find the level +having Maximum number of Nodes ''' + +def maxNodeLevel(root): + if (root == None): + return -1 + q = Queue() + q.put(root) + ''' Current level ''' + + level = 0 + ''' Maximum Nodes at same level ''' + + Max = -999999999999 + ''' Level having Maximum Nodes ''' + + level_no = 0 + while (1): + ''' Count Nodes in a level ''' + + NodeCount = q.qsize() + if (NodeCount == 0): + break + ''' If it is Maximum till now + Update level_no to current level ''' + + if (NodeCount > Max): + Max = NodeCount + level_no = level + ''' Pop complete current level ''' + + while (NodeCount > 0): + Node = q.queue[0] + q.get() + if (Node.left != None): + q.put(Node.left) + if (Node.right != None): + q.put(Node.right) + NodeCount -= 1 + ''' Increment for next level ''' + + level += 1 + return level_no + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree formation + 2 ''' + + root = newNode(2) + ''' / \ ''' + + root.left = newNode(1) + ''' 1 3 ''' + + root.right = newNode(3) + '''/ \ \ ''' + + root.left.left = newNode(4) + '''4 6 8 ''' + + root.left.right = newNode(6) + ''' / ''' + + root.right.right = newNode(8) + ''' 5 ''' + + root.left.right.left = newNode(5) + print(""Level having Maximum number of Nodes : "", + maxNodeLevel(root))" +Non-Repeating Element,"/*Efficient Java program to find first non- +repeating element.*/ + +import java.util.*; +class GFG { + static int firstNonRepeating(int arr[], int n) + { +/* Insert all array elements in hash + table*/ + + Map m = new HashMap<>(); + for (int i = 0; i < n; i++) { + if (m.containsKey(arr[i])) { + m.put(arr[i], m.get(arr[i]) + 1); + } + else { + m.put(arr[i], 1); + } + } +/* Traverse array again and return + first element with count 1.*/ + + for (int i = 0; i < n; i++) + if (m.get(arr[i]) == 1) + return arr[i]; + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 9, 4, 9, 6, 7, 4 }; + int n = arr.length; + System.out.println(firstNonRepeating(arr, n)); + } +}"," '''Efficient Python3 program to find first +non-repeating element.''' + +from collections import defaultdict +def firstNonRepeating(arr, n): + mp = defaultdict(lambda:0) + ''' Insert all array elements in hash table ''' + + for i in range(n): + mp[arr[i]] += 1 + ''' Traverse array again and return + first element with count 1. ''' + + for i in range(n): + if mp[arr[i]] == 1: + return arr[i] + return -1 + '''Driver Code''' + +arr = [9, 4, 9, 6, 7, 4] +n = len(arr) +print(firstNonRepeating(arr, n))" +Generate all possible sorted arrays from alternate elements of two given sorted arrays,"class GenerateArrays { + + /* Function to generates and prints all sorted arrays from alternate + elements of 'A[i..m-1]' and 'B[j..n-1]' + If 'flag' is true, then current element is to be included from A + otherwise from B. + 'len' is the index in output array C[]. We print output array + each time before including a character from A only if length of + output array is greater than 0. We try than all possible + combinations */ + + void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n, + int len, boolean flag) + { +/*Include valid element from A*/ + +if (flag) + { +/* Print output if there is at least one 'B' in output array 'C'*/ + + if (len != 0) + printArr(C, len + 1); + +/* Recur for all elements of A after current index*/ + + for (int k = i; k < m; k++) + { + if (len == 0) + { + /* this block works for the very first call to include + the first element in the output array */ + + C[len] = A[k]; + +/* don't increment lem as B is included yet*/ + + generateUtil(A, B, C, k + 1, j, m, n, len, !flag); + } + + /* include valid element from A and recur */ + + else if (A[k] > C[len]) + { + C[len + 1] = A[k]; + generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag); + } + } + } + + /* Include valid element from B and recur */ + + else + { + for (int l = j; l < n; l++) + { + if (B[l] > C[len]) + { + C[len + 1] = B[l]; + generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag); + } + } + } + } + + /* Wrapper function */ + + void generate(int A[], int B[], int m, int n) + { + int C[] = new int[m + n]; + + /* output array */ + + generateUtil(A, B, C, 0, 0, m, n, 0, true); + } + +/* A utility function to print an array*/ + + void printArr(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + System.out.println(""""); + } + + + +/*Driver program*/ + + public static void main(String[] args) + { + GenerateArrays generate = new GenerateArrays(); + int A[] = {10, 15, 25}; + int B[] = {5, 20, 30}; + int n = A.length; + int m = B.length; + generate.generate(A, B, n, m); + } +}"," ''' Function to generates and prints all + sorted arrays from alternate elements of + 'A[i..m-1]' and 'B[j..n-1]' + If 'flag' is true, then current element + is to be included from A otherwise + from B. + 'len' is the index in output array C[]. + We print output array each time + before including a character from A + only if length of output array is + greater than 0. We try than all possible combinations ''' + +def generateUtil(A,B,C,i,j,m,n,len,flag): + + '''Include valid element from A''' + + if (flag): + + ''' Print output if there is at + least one 'B' in output array 'C''' + ''' + if (len): + printArr(C, len+1) + + ''' Recur for all elements of + A after current index''' + + for k in range(i,m): + + if ( not len): + + ''' this block works for the + very first call to include + the first element in the output array ''' + + C[len] = A[k] + + ''' don't increment lem + as B is included yet''' + + generateUtil(A, B, C, k+1, j, m, n, len, not flag) + + else: + + ''' include valid element from A and recur''' + + if (A[k] > C[len]): + + C[len+1] = A[k] + generateUtil(A, B, C, k+1, j, m, n, len+1, not flag) + + + else: + + ''' Include valid element from B and recur''' + + for l in range(j,n): + + if (B[l] > C[len]): + + C[len+1] = B[l] + generateUtil(A, B, C, i, l+1, m, n, len+1, not flag) + + + '''Wrapper function''' + +def generate(A,B,m,n): + + '''output array''' + + C=[] + for i in range(m+n+1): + C.append(0) + generateUtil(A, B, C, 0, 0, m, n, 0, True) + + + '''A utility function to print an array''' + +def printArr(arr,n): + + for i in range(n): + print(arr[i] , "" "",end="""") + print() + + '''Driver program''' + + +A = [10, 15, 25] +B = [5, 20, 30] +n = len(A) +m = len(B) + +generate(A, B, n, m) + + +" +Range Query on array whose each element is XOR of index value and previous element,"/*Java Program to solve range query on array +whose each element is XOR of index value +and previous element.*/ + + +import java.io.*; + +class GFG { + +/* function return derived formula value.*/ + + static int fun(int x) + { + int y = (x / 4) * 4; + +/* finding xor value of range [y...x]*/ + + int ans = 0; + + for (int i = y; i <= x; i++) + ans ^= i; + + return ans; + } + +/* function to solve query for l and r.*/ + + static int query(int x) + { + +/* if l or r is 0.*/ + + if (x == 0) + return 0; + + int k = (x + 1) / 2; + +/* finding x is divisible by 2 or not.*/ + + return ((x %= 2) != 0) ? 2 * fun(k) : + ((fun(k - 1) * 2) ^ (k & 1)); + } + + static void allQueries(int q, int l[], int r[]) + { + for (int i = 0; i < q; i++) + System.out.println((query(r[i]) ^ + query(l[i] - 1))) ; + } + +/* Driven Program*/ + + public static void main (String[] args) { + + int q = 3; + int []l = { 2, 2, 5 }; + int []r = { 4, 8, 9 }; + + allQueries(q, l, r); + + } +} + + +"," '''Python3 Program to solve range query +on array whose each element is XOR of +index value and previous element.''' + + + '''function return derived formula value.''' + +def fun(x): + y = (x // 4) * 4 + + ''' finding xor value of range [y...x]''' + + ans = 0 + for i in range(y, x + 1): + ans ^= i + return ans + + '''function to solve query for l and r.''' + +def query(x): + + ''' if l or r is 0.''' + + if (x == 0): + return 0 + + k = (x + 1) // 2 + + ''' finding x is divisible by 2 or not.''' + + if x % 2 == 0: + return((fun(k - 1) * 2) ^ (k & 1)) + else: + return(2 * fun(k)) + +def allQueries(q, l, r): + for i in range(q): + print(query(r[i]) ^ query(l[i] - 1)) + + '''Driver Code''' + +q = 3 +l = [ 2, 2, 5 ] +r = [ 4, 8, 9 ] + +allQueries(q, l, r) + + +" +Find elements larger than half of the elements in an array,"/*Java program to find elements that are +larger than half of the elements in array*/ + +import java.util.*; + +class Gfg +{ +/* Prints elements larger than n/2 element*/ + + static void findLarger(int arr[], int n) + { +/* Sort the array in ascending order*/ + + Arrays.sort(arr); + +/* Print last ceil(n/2) elements*/ + + for (int i = n-1; i >= n/2; i--) + System.out.print(arr[i] + "" ""); + } + +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = {1, 3, 6, 1, 0, 9}; + int n = arr.length; + findLarger(arr, n); + } +} + + +"," '''Python program to find elements that are larger than +half of the elements in array''' + + '''Prints elements larger than n/2 element''' + +def findLarger(arr,n): + ''' Sort the array in ascending order''' + + x = sorted(arr) + + ''' Print last ceil(n/2) elements''' + + for i in range(n/2,n): + print(x[i]), + + '''Driver program''' + +arr = [1, 3, 6, 1, 0, 9] +n = len(arr); +findLarger(arr,n) + + +" +Count smaller elements on right side,, +Find the Rotation Count in Rotated Sorted array,"/*Java program to find number of +rotations in a sorted and rotated +array.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class BinarySearch +{ +/* Returns count of rotations for an array + which is first sorted in ascending order, + then rotated*/ + + static int countRotations(int arr[], int low, + int high) + { +/* This condition is needed to handle + the case when array is not rotated + at all*/ + + if (high < low) + return 0; +/* If there is only one element left*/ + + if (high == low) + return low; +/* Find mid*/ + int mid = low + (high - low)/2; +/* Check if element (mid+1) is minimum + element. Consider the cases like + {3, 4, 5, 1, 2}*/ + + if (mid < high && arr[mid+1] < arr[mid]) + return (mid + 1); +/* Check if mid itself is minimum element*/ + + if (mid > low && arr[mid] < arr[mid - 1]) + return mid; +/* Decide whether we need to go to left + half or right half*/ + + if (arr[high] > arr[mid]) + return countRotations(arr, low, mid - 1); + return countRotations(arr, mid + 1, high); + } +/* Driver program to test above functions*/ + + public static void main (String[] args) + { + int arr[] = {15, 18, 2, 3, 6, 12}; + int n = arr.length; + System.out.println(countRotations(arr, 0, n-1)); + } +}"," '''Binary Search based Python3 +program to find number of +rotations in a sorted and +rotated array.''' + + '''Returns count of rotations for +an array which is first sorted +in ascending order, then rotated''' + +def countRotations(arr,low, high): ''' This condition is needed to + handle the case when array + is not rotated at all''' + + if (high < low): + return 0 + ''' If there is only one + element left''' + + if (high == low): + return low + ''' Find mid''' + + mid = low + (high - low)/2; + mid = int(mid) + ''' Check if element (mid+1) is + minimum element. Consider + the cases like {3, 4, 5, 1, 2}''' + + if (mid < high and arr[mid+1] < arr[mid]): + return (mid+1) + ''' Check if mid itself is + minimum element''' + + if (mid > low and arr[mid] < arr[mid - 1]): + return mid + ''' Decide whether we need to go + to left half or right half''' + + if (arr[high] > arr[mid]): + return countRotations(arr, low, mid-1); + return countRotations(arr, mid+1, high) + '''Driver code''' + +arr = [15, 18, 2, 3, 6, 12] +n = len(arr) +print(countRotations(arr, 0, n-1))" +Print nodes between two given level numbers of a binary tree,"/*Java program to print Nodes level by level between given two levels*/ + +import java.util.LinkedList; +import java.util.Queue; + +/* A binary tree Node has key, pointer to left and right children */ + +class Node +{ + int data; + Node left, right; + + public Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + + /* Given a binary tree, print nodes from level number 'low' to level + number 'high'*/ + + void printLevels(Node node, int low, int high) + { + Queue Q = new LinkedList<>(); + +/*Marker node to indicate end of level*/ + +Node marker = new Node(4); + +/*Initialize level number*/ + +int level = 1; + +/* Enqueue the only first level node and marker node for end of level*/ + + Q.add(node); + Q.add(marker); + +/* Simple level order traversal loop*/ + + while (Q.isEmpty() == false) + { +/* Remove the front item from queue*/ + + Node n = Q.peek(); + Q.remove(); + +/* Check if end of level is reached*/ + + if (n == marker) + { +/* print a new line and increment level number*/ + + System.out.println(""""); + level++; + +/* Check if marker node was last node in queue or + level number is beyond the given upper limit*/ + + if (Q.isEmpty() == true || level > high) + break; + +/* Enqueue the marker for end of next level*/ + + Q.add(marker); + +/* If this is marker, then we don't need print it + and enqueue its children*/ + + continue; + } + +/* If level is equal to or greater than given lower level, + print it*/ + + if (level >= low) + System.out.print( n.data + "" ""); + +/* Enqueue children of non-marker node*/ + + if (n.left != null) + Q.add(n.left); + + if (n.right != null) + Q.add(n.right); + + } + } + +/* Driver program to test for above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(8); + tree.root.right = new Node(22); + + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(12); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(14); + + System.out.print(""Level Order traversal between given two levels is ""); + tree.printLevels(tree.root, 2, 3); + + } +} + + +"," '''Python program to print nodes level by level between +given two levels''' + + + '''A binary tree node''' + +class Node: + + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Given a binary tree, print nodes form level number 'low' +to level number 'high''' + ''' + +def printLevels(root, low, high): + Q = [] + + '''Marker node to indicate end of level''' + + marker = Node(11114) + + + '''Initialize level number''' + + level = 1 + + ''' Enqueue the only first level node and marker node for + end of level''' + + Q.append(root) + Q.append(marker) + + ''' print Q + Simple level order traversal loop''' + + while(len(Q) >0): + ''' Remove the front item from queue''' + + n = Q[0] + Q.pop(0) + ''' print Q + Check if end of level is reached''' + + if n == marker: + ''' print a new line and increment level number''' + + print + level += 1 + + ''' Check if marker node was last node in queue + or level nubmer is beyond the given upper limit''' + + if len(Q) == 0 or level > high: + break + + ''' Enqueue the marker for end of next level''' + + Q.append(marker) + + ''' If this is marker, then we don't need print it + and enqueue its children''' + + continue + + ''' If level is equal to or greater than given lower level, + print it''' + + if level >= low: + print n.key, + ''' Enqueue children of non-marker node''' + + if n.left is not None: + Q.append(n.left) + Q.append(n.right) + + '''Driver program to test the above function''' + +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) + +print ""Level Order Traversal between given two levels is"", +printLevels(root,2,3) + + +" +Direction at last square block,"/*Java program to tell the Current direction in +R x C grid*/ + +import java.io.*; +class GFG { +/* Function which tells the Current direction */ + + static void direction(int R, int C) + { + if (R != C && R % 2 == 0 && C % 2 != 0 && R < C) { + System.out.println(""Left""); + return; + } + if (R != C && R % 2 != 0 && C % 2 == 0 && R > C) { + System.out.println(""Up""); + return; + } + if (R == C && R % 2 != 0 && C % 2 != 0) { + System.out.println(""Right""); + return; + } + if (R == C && R % 2 == 0 && C % 2 == 0) { + System.out.println(""Left""); + return; + } + if (R != C && R % 2 != 0 && C % 2 != 0 && R < C) { + System.out.println(""Right""); + return; + } + if (R != C && R % 2 != 0 && C % 2 != 0 && R > C) { + System.out.println(""Down""); + return; + } + if (R != C && R % 2 == 0 && C % 2 == 0 && R < C) { + System.out.println(""Left""); + return; + } + if (R != C && R % 2 == 0 && C % 2 == 0 && R > C) { + System.out.println(""Up""); + return; + } + if (R != C && R % 2 == 0 && C % 2 != 0 && R > C) { + System.out.println(""Down""); + return; + } + if (R != C && R % 2 != 0 && C % 2 == 0 && R < C) { + System.out.println(""Right""); + return; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int R = 3, C = 1; + direction(R, C); + } +}"," '''Python3 program to tell the Current +direction in R x C grid''' + '''Function which tells the Current direction''' + +def direction(R, C): + if (R != C and R % 2 == 0 and + C % 2 != 0 and R < C): + print(""Left"") + return + if (R != C and R % 2 == 0 and + C % 2 == 0 and R > C): + print(""Up"") + return + if R == C and R % 2 != 0 and C % 2 != 0: + print(""Right"") + return + if R == C and R % 2 == 0 and C % 2 == 0: + print(""Left"") + return + if (R != C and R % 2 != 0 and + C % 2 != 0 and R < C): + print(""Right"") + return + if (R != C and R % 2 != 0 and + C % 2 != 0 and R > C): + print(""Down"") + return + if (R != C and R % 2 == 0 and + C % 2 != 0 and R < C): + print(""Left"") + return + if (R != C and R % 2 == 0 and + C % 2 == 0 and R > C): + print(""Up"") + return + if (R != C and R % 2 != 0 and + C % 2 != 0 and R > C): + print(""Down"") + return + if (R != C and R % 2 != 0 and + C % 2 != 0 and R < C): + print(""Right"") + return + '''Driver code''' + +R = 3; C = 1 +direction(R, C)" +Change a Binary Tree so that every node stores sum of all nodes in left subtree,"/*Java program to store sum of nodes in left subtree in every +node */ + +class GfG { +/*A tree node */ + +static class node +{ + int data; + node left, right; +} +/*Function to modify a Binary Tree so that every node +stores sum of values in its left child including its +own value */ + +static int updatetree(node root) +{ +/* Base cases */ + + if (root == null) + return 0; + if (root.left == null && root.right == null) + return root.data; +/* Update left and right subtrees */ + + int leftsum = updatetree(root.left); + int rightsum = updatetree(root.right); +/* Add leftsum to current node */ + + root.data += leftsum; +/* Return sum of values under root */ + + return root.data + rightsum; +} +/*Utility function to do inorder traversal */ + +static void inorder(node node) +{ + if (node == null) + return; + inorder(node.left); + System.out.print(node.data + "" ""); + inorder(node.right); +} +/*Utility function to create a new node */ + +static node newNode(int data) +{ + node node = new node(); + node.data = data; + node.left = null; + node.right = null; + return(node); +} +/*Driver program */ + +public static void main(String[] args) +{ + /* Let us construct below tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 */ + + node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + root.right.right = newNode(6); + updatetree(root); + System.out.println(""Inorder traversal of the modified tree is""); + inorder(root); +} +}"," '''Python3 program to store sum of nodes +in left subtree in every node +Binary Tree Node +utility that allocates a new Node +with the given key ''' + +class newNode: + ''' Construct to create a new node ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Function to modify a Binary Tree so +that every node stores sum of values +in its left child including its own value ''' + +def updatetree(root): + ''' Base cases ''' + + if (not root): + return 0 + if (root.left == None and + root.right == None) : + return root.data + ''' Update left and right subtrees ''' + + leftsum = updatetree(root.left) + rightsum = updatetree(root.right) + ''' Add leftsum to current node ''' + + root.data += leftsum + ''' Return sum of values under root ''' + + return root.data + rightsum + '''Utility function to do inorder traversal ''' + +def inorder(node) : + if (node == None) : + return + inorder(node.left) + print(node.data, end = "" "") + inorder(node.right) + '''Driver Code ''' + +if __name__ == '__main__': + ''' Let us con below tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 ''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.right = newNode(6) + updatetree(root) + print(""Inorder traversal of the modified tree is"") + inorder(root)" +Find four elements that sum to a given value | Set 2,"/*Java program to find four +elements with the given sum*/ + +import java.util.*; + +class fourElementWithSum { + +/* Function to find 4 elements that add up to + given sum*/ + + public static void fourSum(int X, int[] arr, + Map map) + { + int[] temp = new int[arr.length]; + +/* Iterate from 0 to temp.length*/ + + for (int i = 0; i < temp.length; i++) + temp[i] = 0; + +/* Iterate from 0 to arr.length*/ + + for (int i = 0; i < arr.length - 1; i++) { + +/* Iterate from i + 1 to arr.length*/ + + for (int j = i + 1; j < arr.length; j++) { + +/* Store curr_sum = arr[i] + arr[j]*/ + + int curr_sum = arr[i] + arr[j]; + +/* Check if X - curr_sum if present + in map*/ + + if (map.containsKey(X - curr_sum)) { + +/* Store pair having map value + X - curr_sum*/ + + pair p = map.get(X - curr_sum); + + if (p.first != i && p.sec != i + && p.first != j && p.sec != j + && temp[p.first] == 0 + && temp[p.sec] == 0 && temp[i] == 0 + && temp[j] == 0) { + +/* Print the output*/ + + System.out.printf( + ""%d,%d,%d,%d"", arr[i], arr[j], + arr[p.first], arr[p.sec]); + temp[p.sec] = 1; + temp[i] = 1; + temp[j] = 1; + break; + } + } + } + } + } + +/* Program for two Sum*/ + + public static Map twoSum(int[] nums) + { + Map map = new HashMap<>(); + for (int i = 0; i < nums.length - 1; i++) { + for (int j = i + 1; j < nums.length; j++) { + map.put(nums[i] + nums[j], new pair(i, j)); + } + } + return map; + } + +/* to store indices of two sum pair*/ + + public static class pair { + int first, sec; + + public pair(int first, int sec) + { + this.first = first; + this.sec = sec; + } + } + +/* Driver Code*/ + + public static void main(String args[]) + { + int[] arr = { 10, 20, 30, 40, 1, 2 }; + int n = arr.length; + int X = 91; + Map map = twoSum(arr); + +/* Function call*/ + + fourSum(X, arr, map); + } +} + + +"," '''Python3 program to find four +elements with the given sum''' + + + '''Function to find 4 elements that +add up to given sum''' + +def fourSum(X, arr, Map, N): + + ''' Iterate from 0 to temp.length''' + + + temp = [0 for i in range(N)] + ''' Iterate from 0 to length of arr''' + + for i in range(N - 1): + + ''' Iterate from i + 1 to length of arr''' + + for j in range(i + 1, N): + + ''' Store curr_sum = arr[i] + arr[j]''' + + curr_sum = arr[i] + arr[j] + + ''' Check if X - curr_sum if present + in map''' + + if (X - curr_sum) in Map: + + ''' Store pair having map value + X - curr_sum''' + + p = Map[X - curr_sum] + + if (p[0] != i and p[1] != i and + p[0] != j and p[1] != j and + temp[p[0]] == 0 and temp[p[1]] == 0 and + temp[i] == 0 and temp[j] == 0): + + ''' Print the output''' + + print(arr[i], "","", arr[j], "","", + arr[p[0]], "","", arr[p[1]], + sep = """") + + temp[p[1]] = 1 + temp[i] = 1 + temp[j] = 1 + break + + '''Function for two Sum''' + +def twoSum(nums, N): + + Map = {} + + for i in range(N - 1): + for j in range(i + 1, N): + Map[nums[i] + nums[j]] = [] + Map[nums[i] + nums[j]].append(i) + Map[nums[i] + nums[j]].append(j) + + return Map + + '''Driver code''' + +arr = [ 10, 20, 30, 40, 1, 2 ] +n = len(arr) +X = 91 +Map = twoSum(arr, n) + + '''Function call''' + +fourSum(X, arr, Map, n) + + +" +Range sum queries for anticlockwise rotations of Array by K indices,"/*Java program to calculate range sum +queries for anticlockwise +rotations of array by K*/ + +class GFG{ + +/*Function to execute the queries*/ + +static void rotatedSumQuery(int arr[], int n, + int [][]query, int Q) +{ + +/* Construct a new array + of size 2*N to store + prefix sum of every index*/ + + int []prefix = new int[2 * n]; + +/* Copy elements to the new array*/ + + for(int i = 0; i < n; i++) + { + prefix[i] = arr[i]; + prefix[i + n] = arr[i]; + } + +/* Calculate the prefix sum + for every index*/ + + for(int i = 1; i < 2 * n; i++) + prefix[i] += prefix[i - 1]; + +/* Set start pointer as 0*/ + + int start = 0; + + for(int q = 0; q < Q; q++) + { + +/* Query to perform + anticlockwise rotation*/ + + if (query[q][0] == 1) + { + int k = query[q][1]; + start = (start + k) % n; + } + +/* Query to answer range sum*/ + + else if (query[q][0] == 2) + { + int L, R; + L = query[q][1]; + R = query[q][2]; + +/* If pointing to 1st index*/ + + if (start + L == 0) + +/* Display the sum upto start + R*/ + + System.out.print(prefix[start + R] + ""\n""); + + else + +/* Subtract sum upto start + L - 1 + from sum upto start + R*/ + + System.out.print(prefix[start + R] - + prefix[start + L - 1] + + ""\n""); + } + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 2, 3, 4, 5, 6 }; + +/* Number of query*/ + + int Q = 5; + +/* Store all the queries*/ + + int [][]query = { { 2, 1, 3 }, + { 1, 3 }, + { 2, 0, 3 }, + { 1, 4 }, + { 2, 3, 5 } }; + + int n = arr.length; + rotatedSumQuery(arr, n, query, Q); +} +} + + +"," '''Python3 program to calculate range sum +queries for anticlockwise +rotations of the array by K''' + + + '''Function to execute the queries''' + +def rotatedSumQuery(arr, n, query, Q): + + ''' Construct a new array + of size 2*N to store + prefix sum of every index''' + + prefix = [0] * (2 * n) + + ''' Copy elements to the new array''' + + for i in range(n): + prefix[i] = arr[i] + prefix[i + n] = arr[i] + + ''' Calculate the prefix sum + for every index''' + + for i in range(1, 2 * n): + prefix[i] += prefix[i - 1]; + + ''' Set start pointer as 0''' + + start = 0; + + for q in range(Q): + + ''' Query to perform + anticlockwise rotation''' + + if (query[q][0] == 1): + k = query[q][1] + start = (start + k) % n; + + ''' Query to answer range sum''' + + elif (query[q][0] == 2): + L = query[q][1] + R = query[q][2] + + ''' If pointing to 1st index''' + + if (start + L == 0): + + ''' Display the sum upto start + R''' + + print(prefix[start + R]) + + else: + + ''' Subtract sum upto start + L - 1 + from sum upto start + R''' + + print(prefix[start + R]- + prefix[start + L - 1]) + + '''Driver code''' + +arr = [ 1, 2, 3, 4, 5, 6 ]; + + '''Number of query''' + +Q = 5 + + '''Store all the queries''' + +query= [ [ 2, 1, 3 ], + [ 1, 3 ], + [ 2, 0, 3 ], + [ 1, 4 ], + [ 2, 3, 5 ] ] + +n = len(arr); +rotatedSumQuery(arr, n, query, Q); + + +" +Matrix Chain Multiplication | DP-8,"/* A naive recursive implementation that simply follows + the above optimal substructure property */ + +class MatrixChainMultiplication { +/* Matrix Ai has dimension p[i-1] x p[i] for i = 1..n*/ + + static int MatrixChainOrder(int p[], int i, int j) + { + if (i == j) + return 0; + int min = Integer.MAX_VALUE; +/* place parenthesis at different places between + first and last matrix, recursively calculate + count of multiplications for each parenthesis + placement and return the minimum count*/ + + for (int k = i; k < j; k++) + { + int count = MatrixChainOrder(p, i, k) + + MatrixChainOrder(p, k + 1, j) + + p[i - 1] * p[k] * p[j]; + if (count < min) + min = count; + } +/* Return minimum count*/ + + return min; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = new int[] { 1, 2, 3, 4, 3 }; + int n = arr.length; + System.out.println( + ""Minimum number of multiplications is "" + + MatrixChainOrder(arr, 1, n - 1)); + } +}"," '''A naive recursive implementation that +simply follows the above optimal +substructure property''' + +import sys + '''Matrix A[i] has dimension p[i-1] x p[i] +for i = 1..n''' + +def MatrixChainOrder(p, i, j): + if i == j: + return 0 + _min = sys.maxsize + ''' place parenthesis at different places + between first and last matrix, + recursively calculate count of + multiplications for each parenthesis + placement and return the minimum count''' + + for k in range(i, j): + count = (MatrixChainOrder(p, i, k) + + MatrixChainOrder(p, k + 1, j) + + p[i-1] * p[k] * p[j]) + if count < _min: + _min = count + ''' Return minimum count''' + + return _min + '''Driver code''' + +arr = [1, 2, 3, 4, 3] +n = len(arr) +print(""Minimum number of multiplications is "", + MatrixChainOrder(arr, 1, n-1))" +Maximum product of 4 adjacent elements in matrix,"/*Java implementation of the above approach*/ + +import java.io.*; +class GFG { + public static int maxPro(int[][] a, + int n, int m, + int k) + { + int maxi = 1, mp = 1; + for (int i = 0; i < n; ++i) + { +/* Window Product for each row.*/ + + int wp = 1; + for (int l = 0; l < k; ++l) + { + wp *= a[i][l]; + } +/* Maximum window product for each row*/ + + mp = wp; + for (int j = k; j < m; ++j) + { + wp = wp * a[i][j] / a[i][j - k]; +/* Global maximum + window product*/ + + maxi = Math.max( + maxi, + Math.max(mp, wp)); + } + } + return maxi; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int n = 6, m = 5, k = 4; + int[][] a = new int[][] { + { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 1 }, + { 2, 3, 4, 5, 6 }, { 7, 8, 9, 1, 0 }, + { 9, 6, 4, 2, 3 }, { 1, 1, 2, 1, 1 } + }; +/* Function call*/ + + int maxpro = maxPro(a, n, m, k); + System.out.println(maxpro); + } +}", +Detect if two integers have opposite signs,"/*Java Program to Detect +if two integers have opposite signs.*/ + +class GFG { + +/* Function to detect signs*/ + + static boolean oppositeSigns(int x, int y) + { + return ((x ^ y) < 0); + }/*Driver Code*/ + + public static void main(String[] args) + { + int x = 100, y = -100; + if (oppositeSigns(x, y) == true) + System.out.println(""Signs are opposite""); + else + System.out.println(""Signs are not opposite""); + } +}"," '''Python3 Program to Detect +if two integers have +opposite signs.''' + + + ''' Function to detect signs''' + +def oppositeSigns(x, y): + return ((x ^ y) < 0); '''Driver Code''' + +x = 100 +y = 1 +if (oppositeSigns(x, y) == True): + print ""Signs are opposite"" +else: + print ""Signs are not opposite""" +Longest subsequence such that difference between adjacents is one | Set 2,"/*Java implementation to find longest subsequence +such that difference between adjacents is one*/ + +import java.util.*; +class GFG +{ +/*function to find longest subsequence such +that difference between adjacents is one*/ + +static int longLenSub(int []arr, int n) +{ +/* hash table to map the array element with the + length of the longest subsequence of which + it is a part of and is the last element of + that subsequence*/ + + HashMap um = new HashMap(); +/* to store the longest length subsequence*/ + + int longLen = 0; +/* traverse the array elements*/ + + for (int i = 0; i < n; i++) + { +/* initialize current length + for element arr[i] as 0*/ + + int len = 0; +/* if 'arr[i]-1' is in 'um' and its length + of subsequence is greater than 'len'*/ + + if (um.containsKey(arr[i] - 1) && + len < um.get(arr[i] - 1)) + len = um.get(arr[i] - 1); +/* if 'arr[i]+1' is in 'um' and its length + of subsequence is greater than 'len' */ + + if (um.containsKey(arr[i] + 1) && + len < um.get(arr[i] + 1)) + len = um.get(arr[i] + 1); +/* update arr[i] subsequence length in 'um'*/ + + um. put(arr[i], len + 1); +/* update longest length*/ + + if (longLen < um.get(arr[i])) + longLen = um.get(arr[i]); + } +/* required longest length subsequence*/ + + return longLen; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int[] arr = {1, 2, 3, 4, 5, 3, 2}; + int n = arr.length; + System.out.println(""Longest length subsequence = "" + + longLenSub(arr, n)); +} +}"," '''Python3 implementation to find longest +subsequence such that difference between +adjacents is one''' + +from collections import defaultdict + '''function to find longest subsequence such +that difference between adjacents is one''' + +def longLenSub(arr, n): + ''' hash table to map the array element + with the length of the longest + subsequence of which it is a part of + and is the last element of that subsequence''' + + um = defaultdict(lambda:0) + + ''' to store the longest length subsequence''' + + longLen = 0 ''' traverse the array elements''' + + for i in range(n): ''' / initialize current length + for element arr[i] as 0''' + + len1 = 0 + ''' if 'arr[i]-1' is in 'um' and its length + of subsequence is greater than 'len''' + ''' + if (arr[i - 1] in um and + len1 < um[arr[i] - 1]): + len1 = um[arr[i] - 1] + ''' f 'arr[i]+1' is in 'um' and its length + of subsequence is greater than 'len' ''' + + if (arr[i] + 1 in um and + len1 < um[arr[i] + 1]): + len1 = um[arr[i] + 1] + ''' update arr[i] subsequence + length in 'um' ''' + + um[arr[i]] = len1 + 1 + ''' update longest length''' + + if longLen < um[arr[i]]: + longLen = um[arr[i]] + ''' required longest length + subsequence''' + + return longLen + '''Driver code''' + +arr = [1, 2, 3, 4, 5, 3, 2] +n = len(arr) +print(""Longest length subsequence ="", + longLenSub(arr, n))" +Rotate all odd numbers right and all even numbers left in an Array of 1 to N,"/*Java program to implement +the above approach*/ + + +import java.io.*; +import java.util.*; +import java.lang.*; + +class GFG { + +/* function to left rotate*/ + + static void left_rotate(int[] arr) + { + int last = arr[1]; + for (int i = 3; + i < arr.length; + i = i + 2) { + arr[i - 2] = arr[i]; + } + arr[arr.length - 1] = last; + } + +/* function to right rotate*/ + + static void right_rotate(int[] arr) + { + int start = arr[arr.length - 2]; + for (int i = arr.length - 4; + i >= 0; + i = i - 2) { + arr[i + 2] = arr[i]; + } + arr[0] = start; + } + +/* Function to rotate the array*/ + + public static void rotate(int arr[]) + { + left_rotate(arr); + right_rotate(arr); + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + "" ""); + } + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 2, 3, 4, 5, 6 }; + + rotate(arr); + } +} +"," '''Python3 program for the above approach''' + + + '''Function to left rotate''' + +def left_rotate(arr): + + last = arr[1]; + for i in range(3, len(arr), 2): + arr[i - 2] = arr[i] + + arr[len(arr) - 1] = last + + '''Function to right rotate''' + +def right_rotate(arr): + + start = arr[len(arr) - 2] + for i in range(len(arr) - 4, -1, -2): + arr[i + 2] = arr[i] + + arr[0] = start + + '''Function to rotate the array''' + +def rotate(arr): + + left_rotate(arr) + right_rotate(arr) + for i in range(len(arr)): + print(arr[i], end = "" "") + + '''Driver code''' + +arr = [ 1, 2, 3, 4, 5, 6 ] + +rotate(arr); + + +" +Swap nodes in a linked list without swapping data,"/*Java program to swap two given nodes of a linked list*/ + +class Node { + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } +} +class LinkedList { +/*head of list*/ + +Node head; + /* Function to swap Nodes x and y in linked list by + changing links */ + + public void swapNodes(int x, int y) + { +/* Nothing to do if x and y are same*/ + + if (x == y) + return; +/* Search for x (keep track of prevX and CurrX)*/ + + Node prevX = null, currX = head; + while (currX != null && currX.data != x) { + prevX = currX; + currX = currX.next; + } +/* Search for y (keep track of prevY and currY)*/ + + Node prevY = null, currY = head; + while (currY != null && currY.data != y) { + prevY = currY; + currY = currY.next; + } +/* If either x or y is not present, nothing to do*/ + + if (currX == null || currY == null) + return; +/* If x is not head of linked list*/ + + if (prevX != null) + prevX.next = currY; +/*make y the new head*/ + +else + head = currY; +/* If y is not head of linked list*/ + + if (prevY != null) + prevY.next = currX; +/*make x the new head*/ + +else + head = currX; +/* Swap next pointers*/ + + Node temp = currX.next; + currX.next = currY.next; + currY.next = temp; + } + /* Function to add Node at beginning of list. */ + + public void push(int new_data) + { + /* 1. alloc the Node and put the data */ + + Node new_Node = new Node(new_data); + /* 2. Make next of new Node as head */ + + new_Node.next = head; + /* 3. Move the head to point to new Node */ + + head = new_Node; + } + /* This function prints contents of linked list starting + from the given Node */ + + public void printList() + { + Node tNode = head; + while (tNode != null) { + System.out.print(tNode.data + "" ""); + tNode = tNode.next; + } + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + LinkedList llist = new LinkedList(); + /* The constructed linked list is: + 1->2->3->4->5->6->7 */ + + llist.push(7); + llist.push(6); + llist.push(5); + llist.push(4); + llist.push(3); + llist.push(2); + llist.push(1); + System.out.print( + ""\n Linked list before calling swapNodes() ""); + llist.printList(); + llist.swapNodes(4, 3); + System.out.print( + ""\n Linked list after calling swapNodes() ""); + llist.printList(); + } +}"," '''Python program to swap two given nodes of a linked list''' + +class LinkedList(object): + def __init__(self): + self.head = None + ''' head of list''' + + class Node(object): + def __init__(self, d): + self.data = d + self.next = None + ''' Function to swap Nodes x and y in linked list by + changing links''' + + def swapNodes(self, x, y): + ''' Nothing to do if x and y are same''' + + if x == y: + return + ''' Search for x (keep track of prevX and CurrX)''' + + prevX = None + currX = self.head + while currX != None and currX.data != x: + prevX = currX + currX = currX.next + ''' Search for y (keep track of prevY and currY)''' + + prevY = None + currY = self.head + while currY != None and currY.data != y: + prevY = currY + currY = currY.next + ''' If either x or y is not present, nothing to do''' + + if currX == None or currY == None: + return + ''' If x is not head of linked list''' + + if prevX != None: + prevX.next = currY + '''make y the new head''' + + else: + self.head = currY + ''' If y is not head of linked list''' + + if prevY != None: + prevY.next = currX + '''make x the new head''' + + else: + self.head = currX + ''' Swap next pointers''' + + temp = currX.next + currX.next = currY.next + currY.next = temp + ''' Function to add Node at beginning of list.''' + + def push(self, new_data): + ''' 1. alloc the Node and put the data''' + + new_Node = self.Node(new_data) + ''' 2. Make next of new Node as head''' + + new_Node.next = self.head + ''' 3. Move the head to point to new Node''' + + self.head = new_Node + ''' This function prints contents of linked list starting + from the given Node''' + + def printList(self): + tNode = self.head + while tNode != None: + print tNode.data, + tNode = tNode.next + '''Driver program to test above function''' + +llist = LinkedList() + '''The constructed linked list is: +1->2->3->4->5->6->7''' + +llist.push(7) +llist.push(6) +llist.push(5) +llist.push(4) +llist.push(3) +llist.push(2) +llist.push(1) +print ""Linked list before calling swapNodes() "" +llist.printList() +llist.swapNodes(4, 3) +print ""\nLinked list after calling swapNodes() "" +llist.printList()" +"Given a matrix of ‘O’ and ‘X’, replace 'O' with 'X' if surrounded by 'X'","/*A Java program to replace +all 'O's with 'X''s if +surrounded by 'X'*/ + +import java.io.*; +class GFG +{ + + +/*Size of given matrix is M X N*/ + + static int M = 6; + static int N = 6;/*A recursive function to replace +previous value 'prevV' at '(x, y)' +and all surrounding values of +(x, y) with new value 'newV'.*/ + + static void floodFillUtil(char mat[][], int x, + int y, char prevV, + char newV) + {/* Base cases*/ + + if (x < 0 || x >= M || + y < 0 || y >= N) + return; + if (mat[x][y] != prevV) + return; +/* Replace the color at (x, y)*/ + + mat[x][y] = newV; +/* Recur for north, + east, south and west*/ + + floodFillUtil(mat, x + 1, y, + prevV, newV); + floodFillUtil(mat, x - 1, y, + prevV, newV); + floodFillUtil(mat, x, y + 1, + prevV, newV); + floodFillUtil(mat, x, y - 1, + prevV, newV); + } +/* Returns size of maximum + size subsquare matrix + surrounded by 'X'*/ + + static void replaceSurrounded(char mat[][]) + { +/* Step 1: Replace + all 'O' with '-'*/ + + for (int i = 0; i < M; i++) + for (int j = 0; j < N; j++) + if (mat[i][j] == 'O') + mat[i][j] = '-'; +/* Call floodFill for + all '-' lying on edges +Left side*/ + +for (int i = 0; i < M; i++) + if (mat[i][0] == '-') + floodFillUtil(mat, i, 0, + '-', 'O'); +/*Right side*/ + +for (int i = 0; i < M; i++) + if (mat[i][N - 1] == '-') + floodFillUtil(mat, i, N - 1, + '-', 'O'); +/*Top side*/ + +for (int i = 0; i < N; i++) + if (mat[0][i] == '-') + floodFillUtil(mat, 0, i, + '-', 'O'); +/*Bottom side*/ + +for (int i = 0; i < N; i++) + if (mat[M - 1][i] == '-') + floodFillUtil(mat, M - 1, + i, '-', 'O'); +/* Step 3: Replace + all '-' with 'X'*/ + + for (int i = 0; i < M; i++) + for (int j = 0; j < N; j++) + if (mat[i][j] == '-') + mat[i][j] = 'X'; + } +/* Driver Code*/ + + public static void main (String[] args) + { + char[][] mat = {{'X', 'O', 'X', + 'O', 'X', 'X'}, + {'X', 'O', 'X', + 'X', 'O', 'X'}, + {'X', 'X', 'X', + 'O', 'X', 'X'}, + {'O', 'X', 'X', + 'X', 'X', 'X'}, + {'X', 'X', 'X', + 'O', 'X', 'O'}, + {'O', 'O', 'X', + 'O', 'O', 'O'}}; + replaceSurrounded(mat); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + System.out.print(mat[i][j] + "" ""); + System.out.println(""""); + } + } +}"," '''Python3 program to replace all Os with +Xs if surrounded by X''' + + '''Size of given matrix is M x N''' + +M = 6 +N = 6 '''A recursive function to replace previous +value 'prevV' at '(x, y)' and all surrounding +values of (x, y) with new value 'newV'.''' + +def floodFillUtil(mat, x, y, prevV, newV): + ''' Base Cases''' + + if (x < 0 or x >= M or y < 0 or y >= N): + return + if (mat[x][y] != prevV): + return + ''' Replace the color at (x, y)''' + + mat[x][y] = newV + ''' Recur for north, east, south and west''' + + floodFillUtil(mat, x + 1, y, prevV, newV) + floodFillUtil(mat, x - 1, y, prevV, newV) + floodFillUtil(mat, x, y + 1, prevV, newV) + floodFillUtil(mat, x, y - 1, prevV, newV) + '''Returns size of maximum size subsquare + matrix surrounded by 'X''' + ''' +def replaceSurrounded(mat): + ''' Step 1: Replace all 'O's with '-''' + ''' + for i in range(M): + for j in range(N): + if (mat[i][j] == 'O'): + mat[i][j] = '-' + ''' Call floodFill for all '-' + lying on edges + Left Side''' + + for i in range(M): + if (mat[i][0] == '-'): + floodFillUtil(mat, i, 0, '-', 'O') + ''' Right side''' + + for i in range(M): + if (mat[i][N - 1] == '-'): + floodFillUtil(mat, i, N - 1, '-', 'O') + ''' Top side''' + + for i in range(N): + if (mat[0][i] == '-'): + floodFillUtil(mat, 0, i, '-', 'O') + ''' Bottom side''' + + for i in range(N): + if (mat[M - 1][i] == '-'): + floodFillUtil(mat, M - 1, i, '-', 'O') + ''' Step 3: Replace all '-' with 'X''' + ''' + for i in range(M): + for j in range(N): + if (mat[i][j] == '-'): + mat[i][j] = 'X' + '''Driver code''' + +if __name__ == '__main__': + mat = [ [ 'X', 'O', 'X', 'O', 'X', 'X' ], + [ 'X', 'O', 'X', 'X', 'O', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'X' ], + [ 'O', 'X', 'X', 'X', 'X', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'O' ], + [ 'O', 'O', 'X', 'O', 'O', 'O' ] ]; + replaceSurrounded(mat) + for i in range(M): + print(*mat[i])" +Average of a stream of numbers,"/*Java program to return +Average of a stream of numbers*/ + +class GFG +{ +static int sum, n; +/*Returns the new average +after including x*/ + +static float getAvg(int x) +{ + sum += x; + return (((float)sum) / ++n); +} +/*Prints average of a +stream of numbers*/ + +static void streamAvg(float[] arr, + int n) +{ + float avg = 0; + for (int i = 0; i < n; i++) + { + avg = getAvg((int)arr[i]); + System.out.println(""Average of ""+ (i + 1) + + "" numbers is "" + avg); + } + return; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + float[] arr = new float[]{ 10, 20, 30, + 40, 50, 60 }; + int n = arr.length; + streamAvg(arr, n); +} +}"," '''Returns the new average +after including x''' + +def getAvg(x, n, sum): + sum = sum + x; + return float(sum) / n; + '''Prints average of a +stream of numbers''' + +def streamAvg(arr, n): + avg = 0; + sum = 0; + for i in range(n): + avg = getAvg(arr[i], i + 1, sum); + sum = avg * (i + 1); + print(""Average of "", end = """"); + print(i + 1, end = """"); + print("" numbers is "", end = """"); + print(avg); + return; + '''Driver Code''' + +arr= [ 10, 20, 30, + 40, 50, 60 ]; +n = len(arr); +streamAvg(arr,n);" +Find the two repeating elements in a given array,"class RepeatElement +{ +/* printRepeating function */ + + void printRepeating(int arr[], int size) + { + /* S is for sum of elements in arr[] */ + + int S = 0; + /* P is for product of elements in arr[] */ + + int P = 1; + /* x and y are two repeating elements */ + + int x, y; + /* D is for difference of x and y, i.e., x-y*/ + + int D; + int n = size - 2, i; + /* Calculate Sum and Product of all elements in arr[] */ + + for (i = 0; i < size; i++) + { + S = S + arr[i]; + P = P * arr[i]; + } + /* S is x + y now */ + + S = S - n * (n + 1) / 2; + /* P is x*y now */ + + P = P / fact(n); + /* D is x - y now */ + + D = (int) Math.sqrt(S * S - 4 * P); + x = (D + S) / 2; + y = (S - D) / 2; + System.out.println(""The two repeating elements are :""); + System.out.print(x + "" "" + y); + } + +/*factorial of n*/ + + int fact(int n) + { + return (n == 0) ? 1 : n * fact(n - 1); + }/* driver code*/ + + public static void main(String[] args) { + RepeatElement repeat = new RepeatElement(); + int arr[] = {4, 2, 4, 5, 2, 3, 1}; + int arr_size = arr.length; + repeat.printRepeating(arr, arr_size); + } +}"," '''Python3 code for Find the two repeating +elements in a given array''' + +import math + + ''' printRepeating function''' + +def printRepeating(arr, size) : ''' S is for sum of elements in arr[]''' + + S = 0; + ''' P is for product of elements in arr[]''' + + P = 1; + n = size - 2 + ''' Calculate Sum and Product + of all elements in arr[]''' + + for i in range(0, size) : + S = S + arr[i] + P = P * arr[i] + ''' S is x + y now''' + + S = S - n * (n + 1) // 2 + ''' P is x*y now''' + + P = P // fact(n) + ''' D is x - y now''' + + D = math.sqrt(S * S - 4 * P) + x = (D + S) // 2 + y = (S - D) // 2 + print(""The two Repeating elements are "", + (int)(x),"" & "" ,(int)(y)) + '''factorial of n''' + +def fact(n) : + if(n == 0) : + return 1 + else : + return(n * fact(n - 1)) + '''Driver code''' + +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size)" +Find maximum (or minimum) in Binary Tree,"/*Java code to Find maximum (or minimum) in +Binary Tree*/ + +/*A binary tree node*/ + +class Node { + int data; + Node left, right; +/* Constructor that allocates a new + node with the given data and NULL + left and right pointers. */ + + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree { + Node root;/* Returns the max value in a binary tree*/ + + static int findMax(Node node) + { + + /* Base case*/ + + if (node == null) + return Integer.MIN_VALUE; +/* Return maximum of 3 values: + 1) Root's data 2) Max in Left Subtree + 3) Max in right subtree*/ + + int res = node.data; + int lres = findMax(node.left); + int rres = findMax(node.right); + if (lres > res) + res = lres; + if (rres > res) + res = rres; + return res; + }/* Driver code */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(2); + tree.root.left = new Node(7); + tree.root.right = new Node(5); + tree.root.left.right = new Node(6); + tree.root.left.right.left = new Node(1); + tree.root.left.right.right = new Node(11); + tree.root.right.right = new Node(9); + tree.root.right.right.left = new Node(4); +/* Function call*/ + + System.out.println(""Maximum element is "" + + tree.findMax(tree.root)); + } +}"," '''Python3 program to find maximum +and minimum in a Binary Tree''' + + '''A class to create a new node''' + +class newNode: + ''' Constructor that allocates a new + node with the given data and NULL + left and right pointers. ''' + + def __init__(self, data): + self.data = data + self.left = self.right = None '''Returns maximum value in a +given Binary Tree''' + +def findMax(root): + ''' Base case''' + + if (root == None): + return float('-inf') + ''' Return maximum of 3 values: + 1) Root's data 2) Max in Left Subtree + 3) Max in right subtree''' + + res = root.data + lres = findMax(root.left) + rres = findMax(root.right) + if (lres > res): + res = lres + if (rres > res): + res = rres + return res + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(2) + root.left = newNode(7) + root.right = newNode(5) + root.left.right = newNode(6) + root.left.right.left = newNode(1) + root.left.right.right = newNode(11) + root.right.right = newNode(9) + root.right.right.left = newNode(4) + ''' Function call''' + + print(""Maximum element is"", + findMax(root))" +Insertion Sort for Doubly Linked List,"/*Java implementation for insertion Sort +on a doubly linked list*/ + +class Solution +{ + +/*Node of a doubly linked list*/ + +static class Node +{ + int data; + Node prev, next; +}; + +/*function to create and return a new node +of a doubly linked list*/ + +static Node getNode(int data) +{ +/* allocate node*/ + + Node newNode = new Node(); + +/* put in the data*/ + + newNode.data = data; + newNode.prev = newNode.next = null; + return newNode; +} + +/*function to insert a new node in sorted way in +a sorted doubly linked list*/ + +static Node sortedInsert(Node head_ref, Node newNode) +{ + Node current; + +/* if list is empty*/ + + if (head_ref == null) + head_ref = newNode; + +/* if the node is to be inserted at the beginning + of the doubly linked list*/ + + else if ((head_ref).data >= newNode.data) + { + newNode.next = head_ref; + newNode.next.prev = newNode; + head_ref = newNode; + } + + else + { + current = head_ref; + +/* locate the node after which the new node + is to be inserted*/ + + while (current.next != null && + current.next.data < newNode.data) + current = current.next; + +/* Make the appropriate links /*/ + + + newNode.next = current.next; + +/* if the new node is not inserted + at the end of the list*/ + + if (current.next != null) + newNode.next.prev = newNode; + + current.next = newNode; + newNode.prev = current; + } + return head_ref; +} + +/*function to sort a doubly linked list using insertion sort*/ + +static Node insertionSort(Node head_ref) +{ +/* Initialize 'sorted' - a sorted doubly linked list*/ + + Node sorted = null; + +/* Traverse the given doubly linked list and + insert every node to 'sorted'*/ + + Node current = head_ref; + while (current != null) + { + +/* Store next for next iteration*/ + + Node next = current.next; + +/* removing all the links so as to create 'current' + as a new node for insertion*/ + + current.prev = current.next = null; + +/* insert current in 'sorted' doubly linked list*/ + + sorted=sortedInsert(sorted, current); + +/* Update current*/ + + current = next; + } + +/* Update head_ref to point to sorted doubly linked list*/ + + head_ref = sorted; + + return head_ref; +} + +/*function to print the doubly linked list*/ + +static void printList(Node head) +{ + while (head != null) + { + System.out.print(head.data + "" ""); + head = head.next; + } +} + +/*function to insert a node at the beginning of +the doubly linked list*/ + +static Node push(Node head_ref, int new_data) +{ +/* allocate node /*/ + + Node new_node = new Node(); + +/* put in the data /*/ + + new_node.data = new_data; + +/* Make next of new node as head and previous as null /*/ + + new_node.next = (head_ref); + new_node.prev = null; + +/* change prev of head node to new node /*/ + + if ((head_ref) != null) + (head_ref).prev = new_node; + +/* move the head to point to the new node /*/ + + (head_ref) = new_node; + + return head_ref; +} + +/*Driver code*/ + +public static void main(String args[]) +{ +/* start with the empty doubly linked list /*/ + + Node head = null; + +/* insert the following data*/ + + head=push(head, 9); + head=push(head, 3); + head=push(head, 5); + head=push(head, 10); + head=push(head, 12); + head=push(head, 8); + + System.out.println( ""Doubly Linked List Before Sorting\n""); + printList(head); + + head=insertionSort(head); + + System.out.println(""\nDoubly Linked List After Sorting\n""); + printList(head); + +} +} + + +"," '''Python3 implementation for insertion Sort +on a doubly linked list''' + + + '''Node of a doubly linked list''' + +class Node: + + def __init__(self, data): + self.data = data + self.prev = None + self.next = None + + '''function to create and return a new node +of a doubly linked list''' + +def getNode(data): + + ''' allocate node''' + + newNode = Node(0) + + ''' put in the data''' + + newNode.data = data + newNode.prev = newNode.next = None + return newNode + + '''function to insert a new node in sorted way in +a sorted doubly linked list''' + +def sortedInsert(head_ref, newNode): + + current = None + + ''' if list is empty''' + + if (head_ref == None): + head_ref = newNode + + ''' if the node is to be inserted at the beginning + of the doubly linked list''' + + elif ((head_ref).data >= newNode.data) : + newNode.next = head_ref + newNode.next.prev = newNode + head_ref = newNode + + else : + current = head_ref + + ''' locate the node after which the new node + is to be inserted''' + + while (current.next != None and + current.next.data < newNode.data): + current = current.next + + '''Make the appropriate links ''' + + newNode.next = current.next + + ''' if the new node is not inserted + at the end of the list''' + + if (current.next != None): + newNode.next.prev = newNode + + current.next = newNode + newNode.prev = current + + return head_ref; + + '''function to sort a doubly linked list +using insertion sort''' + +def insertionSort( head_ref): + + ''' Initialize 'sorted' - a sorted + doubly linked list''' + + sorted = None + + ''' Traverse the given doubly linked list + and insert every node to 'sorted''' + ''' + current = head_ref + while (current != None) : + + ''' Store next for next iteration''' + + next = current.next + + ''' removing all the links so as to create + 'current' as a new node for insertion''' + + current.prev = current.next = None + + ''' insert current in 'sorted' doubly linked list''' + + sorted = sortedInsert(sorted, current) + + ''' Update current''' + + current = next + + ''' Update head_ref to point to + sorted doubly linked list''' + + head_ref = sorted + + return head_ref + + '''function to print the doubly linked list''' + +def printList(head): + + while (head != None) : + print( head.data, end = "" "") + head = head.next + + '''function to insert a node at the +beginning of the doubly linked list''' + +def push(head_ref, new_data): + + ''' allocate node ''' + + new_node = Node(0) + + ''' put in the data ''' + + new_node.data = new_data + + ''' Make next of new node as head + and previous as None ''' + + new_node.next = (head_ref) + new_node.prev = None + + ''' change prev of head node to new node ''' + + if ((head_ref) != None): + (head_ref).prev = new_node + + ''' move the head to point to the new node ''' + + (head_ref) = new_node + return head_ref + + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' start with the empty doubly linked list ''' + + head = None + + ''' insert the following data''' + + head = push(head, 9) + head = push(head, 3) + head = push(head, 5) + head = push(head, 10) + head = push(head, 12) + head = push(head, 8) + + print( ""Doubly Linked List Before Sorting"") + printList(head) + + head = insertionSort(head) + + print(""\nDoubly Linked List After Sorting"") + printList(head) + + +" +Linked complete binary tree & its creation,," '''Program for linked implementation +of complete binary tree''' + + '''For Queue Size''' + +SIZE = 50 '''A tree node''' + +class node: + def __init__(self, data): + self.data = data + self.right = None + self.left = None + '''A queue node''' + +class Queue: + def __init__(self): + self.front = None + self.rear = None + self.size = 0 + self.array = [] + '''A utility function to +create a new tree node''' + +def newNode(data): + temp = node(data) + return temp + '''A utility function to +create a new Queue''' + +def createQueue(size): + global queue + queue = Queue(); + queue.front = queue.rear = -1; + queue.size = size; + queue.array = [None for i in range(size)] + return queue; + '''Standard Queue Functions''' + +def isEmpty(queue): + return queue.front == -1 +def isFull(queue): + return queue.rear == queue.size - 1; +def hasOnlyOneItem(queue): + return queue.front == queue.rear; +def Enqueue(root): + if (isFull(queue)): + return; + queue.rear+=1 + queue.array[queue.rear] = root; + if (isEmpty(queue)): + queue.front+=1; +def Dequeue(): + if (isEmpty(queue)): + return None; + temp = queue.array[queue.front]; + if(hasOnlyOneItem(queue)): + queue.front = queue.rear = -1; + else: + queue.front+=1 + return temp; +def getFront(queue): + return queue.array[queue.front]; + '''A utility function to check +if a tree node has both left +and right children''' + +def hasBothChild(temp): + return (temp and temp.left and + temp.right); + '''Function to insert a new +node in complete binary tree''' + +def insert(root, data, queue): + ''' Create a new node for + given data''' + + temp = newNode(data); + ''' If the tree is empty, + initialize the root + with new node.''' + + if not root: + root = temp; + else: + ''' get the front node of + the queue.''' + + front = getFront(queue); + ''' If the left child of this + front node doesn t exist, + set the left child as the + new node''' + + if (not front.left): + front.left = temp; + ''' If the right child of this + front node doesn t exist, set + the right child as the new node''' + + elif (not front.right): + front.right = temp; + ''' If the front node has both the + left child and right child, + Dequeue() it.''' + + if (hasBothChild(front)): + Dequeue(); + ''' Enqueue() the new node for + later insertions''' + + Enqueue(temp); + return root + '''Standard level order +traversal to test above +function''' + +def levelOrder(root): + queue = createQueue(SIZE); + Enqueue(root); + while (not isEmpty(queue)): + temp = Dequeue(); + print(temp.data, end = ' ') + if (temp.left): + Enqueue(temp.left); + if (temp.right): + Enqueue(temp.right); + '''Driver code ''' + +if __name__ == ""__main__"": + root = None + queue = createQueue(SIZE); + for i in range(1, 13): + root=insert(root, i, + queue); + levelOrder(root);" +How to check if a given array represents a Binary Heap?,"/*Java program to check whether a given array +represents a max-heap or not*/ + +class GFG { +/*Returns true if arr[i..n-1] represents a +max-heap*/ + + static boolean isHeap(int arr[], int n) { +/* Start from root and go till the last internal + node*/ + + for (int i = 0; i <= (n - 2) / 2; i++) { +/* If left child is greater, return false*/ + + if (arr[2 * i + 1] > arr[i]) { + return false; + } +/* If right child is greater, return false*/ + + if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) { + return false; + } + } + return true; + } +/*Driver program*/ + + public static void main(String[] args) { + int arr[] = {90, 15, 10, 7, 12, 2, 7, 3}; + int n = arr.length; + if (isHeap(arr, n)) { + System.out.println(""Yes""); + } else { + System.out.println(""No""); + } + } +}"," '''Python3 program to check whether a +given array represents a max-heap or not + ''' '''Returns true if arr[i..n-1] +represents a max-heap''' + +def isHeap(arr, n): + ''' Start from root and go till + the last internal node''' + + for i in range(int((n - 2) / 2) + 1): + ''' If left child is greater, + return false''' + + if arr[2 * i + 1] > arr[i]: + return False + ''' If right child is greater, + return false''' + + if (2 * i + 2 < n and + arr[2 * i + 2] > arr[i]): + return False + return True + '''Driver Code''' + +if __name__ == '__main__': + arr = [90, 15, 10, 7, 12, 2, 7, 3] + n = len(arr) + if isHeap(arr, n): + print(""Yes"") + else: + print(""No"")" +Rotate a matrix by 90 degree in clockwise direction without using any extra space,"import java.io.*; + +class GFG { + + +/*rotate function*/ + + + static void rotate(int[][] arr) { + + int n=arr.length;/* first rotation + with respect to main diagonal*/ + + for(int i=0;i= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; +/* Check for every other element*/ + + for(int i = 1; i < n - 1; i++) + { +/* Check if the neighbors are smaller*/ + + if (arr[i] >= arr[i - 1] && + arr[i] >= arr[i + 1]) + return i; + } + return 0; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 3, 20, 4, 1, 0 }; + int n = arr.length; + System.out.print(""Index of a peak point is "" + + findPeak(arr, n)); +} +}"," '''A Python3 program to find a peak element''' '''Find the peak element in the array''' + +def findPeak(arr, n) : + ''' first or last element is peak element''' + + if (n == 1) : + return 0 + if (arr[0] >= arr[1]) : + return 0 + if (arr[n - 1] >= arr[n - 2]) : + return n - 1 + ''' check for every other element''' + + for i in range(1, n - 1) : + ''' check if the neighbors are smaller''' + + if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) : + return i + '''Driver code.''' + +arr = [ 1, 3, 20, 4, 1, 0 ] +n = len(arr) +print(""Index of a peak point is"", findPeak(arr, n))" +Sorted order printing of a given array that represents a BST,"/*JAVA Code for Sorted order printing of a +given array that represents a BST*/ + +class GFG{ +private static void printSorted(int[] arr, int start, + int end) { + if(start > end) + return; +/* print left subtree*/ + + printSorted(arr, start*2 + 1, end); +/* print root*/ + + System.out.print(arr[start] + "" ""); +/* print right subtree*/ + + printSorted(arr, start*2 + 2, end); + } +/* driver program to test above function*/ + + public static void main(String[] args) { + int arr[] = {4, 2, 5, 1, 3}; + printSorted(arr, 0, arr.length-1); + } +}"," '''Python3 Code for Sorted order printing of a +given array that represents a BST''' + +def printSorted(arr, start, end): + if start > end: + return + ''' print left subtree''' + + printSorted(arr, start * 2 + 1, end) + ''' print root''' + + print(arr[start], end = "" "") + ''' print right subtree''' + + printSorted(arr, start * 2 + 2, end) + '''Driver Code ''' + +if __name__ == '__main__': + arr = [4, 2, 5, 1, 3] + arr_size = len(arr) + printSorted(arr, 0, arr_size - 1)" +Threaded Binary Search Tree | Deletion,"/*Complete Java program to demonstrate deletion +in threaded BST*/ + +import java.util.*; +class solution { + static class Node { + Node left, right; + int info; +/* True if left pointer points to predecessor + in Inorder Traversal*/ + + boolean lthread; +/* True if right pointer points to predecessor + in Inorder Traversal*/ + + boolean rthread; + }; +/* Insert a Node in Binary Threaded Tree*/ + + static Node insert(Node root, int ikey) + { +/* Searching for a Node with given value*/ + + Node ptr = root; +/*Parent of key to be inserted*/ + +Node par = null; + while (ptr != null) { +/* If key already exists, return*/ + + if (ikey == (ptr.info)) { + System.out.printf(""Duplicate Key !\n""); + return root; + } +/*Update parent pointer*/ + +par = ptr; +/* Moving on left subtree.*/ + + if (ikey < ptr.info) { + if (ptr.lthread == false) + ptr = ptr.left; + else + break; + } +/* Moving on right subtree.*/ + + else { + if (ptr.rthread == false) + ptr = ptr.right; + else + break; + } + } +/* Create a new Node*/ + + Node tmp = new Node(); + tmp.info = ikey; + tmp.lthread = true; + tmp.rthread = true; + if (par == null) { + root = tmp; + tmp.left = null; + tmp.right = null; + } + else if (ikey < (par.info)) { + tmp.left = par.left; + tmp.right = par; + par.lthread = false; + par.left = tmp; + } + else { + tmp.left = par; + tmp.right = par.right; + par.rthread = false; + par.right = tmp; + } + return root; + } +/* Returns inorder successor using left + and right children (Used in deletion)*/ + + static Node inSucc(Node ptr) + { + if (ptr.rthread == true) + return ptr.right; + ptr = ptr.right; + while (ptr.lthread == false) + ptr = ptr.left; + return ptr; + } +/* Returns inorder successor using rthread + (Used in inorder)*/ + + static Node inorderSuccessor(Node ptr) + { +/* If rthread is set, we can quickly find*/ + + if (ptr.rthread == true) + return ptr.right; +/* Else return leftmost child of right subtree*/ + + ptr = ptr.right; + while (ptr.lthread == false) + ptr = ptr.left; + return ptr; + } +/* Printing the threaded tree*/ + + static void inorder(Node root) + { + if (root == null) + System.out.printf(""Tree is empty""); +/* Reach leftmost Node*/ + + Node ptr = root; + while (ptr.lthread == false) + ptr = ptr.left; +/* One by one print successors*/ + + while (ptr != null) { + System.out.printf(""%d "", ptr.info); + ptr = inorderSuccessor(ptr); + } + } + static Node inPred(Node ptr) + { + if (ptr.lthread == true) + return ptr.left; + ptr = ptr.left; + while (ptr.rthread == false) + ptr = ptr.right; + return ptr; + } +/* Here 'par' is pointer to parent Node and 'ptr' is + pointer to current Node.*/ + + static Node caseA(Node root, Node par, + Node ptr) + { +/* If Node to be deleted is root*/ + + if (par == null) + root = null; +/* If Node to be deleted is left + of its parent*/ + + else if (ptr == par.left) { + par.lthread = true; + par.left = ptr.left; + } + else { + par.rthread = true; + par.right = ptr.right; + } + return root; + } +/* Here 'par' is pointer to parent Node and 'ptr' is + pointer to current Node.*/ + + static Node caseB(Node root, Node par, + Node ptr) + { + Node child; +/* Initialize child Node to be deleted has + left child.*/ + + if (ptr.lthread == false) + child = ptr.left; +/* Node to be deleted has right child.*/ + + else + child = ptr.right; +/* Node to be deleted is root Node.*/ + + if (par == null) + root = child; +/* Node is left child of its parent.*/ + + else if (ptr == par.left) + par.left = child; + else + par.right = child; +/* Find successor and predecessor*/ + + Node s = inSucc(ptr); + Node p = inPred(ptr); +/* If ptr has left subtree.*/ + + if (ptr.lthread == false) + p.right = s; +/* If ptr has right subtree.*/ + + else { + if (ptr.rthread == false) + s.left = p; + } + return root; + } +/* Here 'par' is pointer to parent Node and 'ptr' is + pointer to current Node.*/ + + static Node caseC(Node root, Node par, + Node ptr) + { +/* Find inorder successor and its parent.*/ + + Node parsucc = ptr; + Node succ = ptr.right; +/* Find leftmost child of successor*/ + + while (succ.lthread == false) { + parsucc = succ; + succ = succ.left; + } + ptr.info = succ.info; + if (succ.lthread == true && succ.rthread == true) + root = caseA(root, parsucc, succ); + else + root = caseB(root, parsucc, succ); + return root; + } +/* Deletes a key from threaded BST with given root and + returns new root of BST.*/ + + static Node delThreadedBST(Node root, int dkey) + { +/* Initialize parent as null and ptrent + Node as root.*/ + + Node par = null, ptr = root; +/* Set true if key is found*/ + + int found = 0; +/* Search key in BST : find Node and its + parent.*/ + + while (ptr != null) { + if (dkey == ptr.info) { + found = 1; + break; + } + par = ptr; + if (dkey < ptr.info) { + if (ptr.lthread == false) + ptr = ptr.left; + else + break; + } + else { + if (ptr.rthread == false) + ptr = ptr.right; + else + break; + } + } + if (found == 0) + System.out.printf(""dkey not present in tree\n""); +/* Two Children*/ + + else if (ptr.lthread == false && ptr.rthread == false) + root = caseC(root, par, ptr); +/* Only Left Child*/ + + else if (ptr.lthread == false) + root = caseB(root, par, ptr); +/* Only Right Child*/ + + else if (ptr.rthread == false) + root = caseB(root, par, ptr); +/* No child*/ + + else + root = caseA(root, par, ptr); + return root; + } +/* Driver Program*/ + + public static void main(String args[]) + { + Node root = null; + root = insert(root, 20); + root = insert(root, 10); + root = insert(root, 30); + root = insert(root, 5); + root = insert(root, 16); + root = insert(root, 14); + root = insert(root, 17); + root = insert(root, 13); + root = delThreadedBST(root, 20); + inorder(root); + } +}", +Program to check if matrix is upper triangular,"/*Java Program to check upper +triangular matrix.*/ + +import java.util.*; +import java.lang.*; +public class GfG +{ + private static final int N = 4; +/* Function to check matrix is in + upper triangular form or not.*/ + + public static Boolean isUpperTriangularMatrix(int mat[][]) + { + for (int i = 1; i < N ; i++) + for (int j = 0; j < i; j++) + if (mat[i][j] != 0) + return false; + return true; + } +/* driver function*/ + + public static void main(String argc[]){ + int[][] mat= { { 1, 3, 5, 3 }, + { 0, 4, 6, 2 }, + { 0, 0, 2, 5 }, + { 0, 0, 0, 6 } }; + if (isUpperTriangularMatrix(mat)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 Program to check upper +triangular matrix. + ''' '''Function to check matrix +is in upper triangular''' + +def isuppertriangular(M): + for i in range(1, len(M)): + for j in range(0, i): + if(M[i][j] != 0): + return False + return True + '''Driver function.''' + +M = [[1,3,5,3], + [0,4,6,2], + [0,0,2,5], + [0,0,0,6]] +if isuppertriangular(M): + print (""Yes"") +else: + print (""No"")" +Print all permutations in sorted (lexicographic) order,," '''An optimized version that uses reverse +instead of sort for finding the next +permutation +A utility function to reverse a +string str[l..h]''' + +def reverse(str, l, h): + while (l < h) : + str[l], str[h] = str[h], str[l] + l += 1 + h -= 1 + return str + +def findCeil(str, c, k, n): + ans = -1 + val = c + for i in range(k, n + 1): + if str[i] > c and str[i] < val: + val = str[i] + ans = i + return ans '''Print all permutations of str in sorted order''' + +def sortedPermutations(str): + ''' Get size of string''' + + size = len(str) + ''' Sort the string in increasing order''' + + str = ''.join(sorted(str)) + ''' Print permutations one by one''' + + isFinished = False + while (not isFinished): + ''' Print this permutation''' + + print(str) + ''' Find the rightmost character which + is smaller than its next character. + Let us call it 'first char' ''' + + for i in range(size - 2, -1, -1): + if (str[i] < str[i + 1]): + break + ''' If there is no such character, all + are sorted in decreasing order, + means we just printed the last + permutation and we are done.''' + + if (i == -1): + isFinished = True + else: + ''' Find the ceil of 'first char' in + right of first character. + Ceil of a character is the + smallest character greater than it''' + + ceilIndex = findCeil(str, str[i], i + 1, + size - 1) + ''' Swap first and second characters''' + + str[i], str[ceilIndex] = str[ceilIndex], str[i] + ''' Reverse the string on right of 'first char''' + ''' + str = reverse(str, i + 1, size - 1)" +Smallest greater elements in whole array,"/*Efficient Java program to +find smallest greater element +in whole array for every element.*/ + +import java.util.*; +class GFG{ + +static void smallestGreater(int arr[], + int n) +{ + HashSet s = new HashSet<>(); + for (int i = 0; i < n; i++) + s.add(arr[i]); + Vector newAr = new Vector<>(); + for (int p : s) + { + newAr.add(p); + } + + for (int i = 0; i < n; i++) + { + int temp = lowerBound(newAr, 0, + newAr.size(), + arr[i]); + if (temp < n) + System.out.print(newAr.get(temp) + "" ""); + else + System.out.print(""_ ""); + } +} + + + +/*lowerbound function*/ + +static int lowerBound(Vector vec, + int low, int high, + int element) +{ + int[] array = new int[vec.size()]; + int k = 0; + for (Integer val : vec) + { + array[k] = val; + k++; + } + while (low < high) + { + int middle = low + + (high - low) / 2; + if (element > array[middle]) + { + low = middle + 1; + } else + { + high = middle; + } + } + + return low+1; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int ar[] = {6, 3, 9, 8, + 10, 2, 1, 15, 7}; + int n = ar.length; + smallestGreater(ar, n); +} +} + + +"," '''Efficient Python3 program to +find smallest greater element +in whole array for every element''' + +def smallestGreater(arr, n): + + s = set() + + for i in range(n): + s.add(arr[i]) + + newAr = [] + + for p in s: + newAr.append(p) + + for i in range(n): + temp = lowerBound(newAr, 0, len(newAr), + arr[i]) + + if (temp < n): + print(newAr[temp], end = "" "") + else: + print(""_ "", end = """") + + + + '''lowerbound function''' + +def lowerBound(vec, low, high, element): + + array = [0] * (len(vec)) + + k = 0 + + for val in vec: + array[k] = val + k += 1 + while (low < high): + middle = low + int((high - low) / 2) + + if (element > array[middle]): + low = middle + 1 + else: + high = middle + + return low + 1 + + '''Driver code''' + +if __name__ == '__main__': + + ar = [ 6, 3, 9, 8, 10, 2, 1, 15, 7 ] + n = len(ar) + + smallestGreater(ar, n) + + +" +Count number of triplets with product equal to given number,"/*Java program to count triplets with given +product m*/ + +import java.util.HashMap; +class GFG { +/* Method to count such triplets*/ + + static int countTriplets(int arr[], int n, int m) + { +/* Store all the elements in a set*/ + + HashMap occ = new HashMap(n); + for (int i = 0; i < n; i++) + occ.put(arr[i], i); + int count = 0; +/* Consider all pairs and check for a + third number so their product is equal to m*/ + + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { +/* Check if current pair divides m or not + If yes, then search for (m / arr[i]*arr[j])*/ + + if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) { + int check = m / (arr[i] * arr[j]); + occ.containsKey(check); +/* Check if the third number is present + in the map and it is not equal to any + other two elements and also check if + this triplet is not counted already + using their indexes*/ + + if (check != arr[i] && check != arr[j] + && occ.containsKey(check) && occ.get(check) > i + && occ.get(check) > j) + count++; + } + } + } +/* Return number of triplets*/ + + return count; + } +/* Driver method*/ + + public static void main(String[] args) + { + int arr[] = { 1, 4, 6, 2, 3, 8 }; + int m = 24; + System.out.println(countTriplets(arr, arr.length, m)); + } +}"," '''Python3 program for the above approach''' + '''Function to find the triplet''' + +def countTriplets(li,product): + flag = 0 + count = 0 + ''' Consider all pairs and check + for a third number so their + product is equal to product''' + + for i in range(len(li)): + ''' Check if current pair + divides product or not + If yes, then search for + (product / li[i]*li[j])''' + + if li[i]!= 0 and product % li[i] == 0: + for j in range(i+1, len(li)): + ''' Check if the third number is present + in the map and it is not equal to any + other two elements and also check if + this triplet is not counted already + using their indexes''' + + if li[j]!= 0 and product % (li[j]*li[i]) == 0: + if product // (li[j]*li[i]) in li: + n = li.index(product//(li[j]*li[i])) + if n > i and n > j: + flag = 1 + count+=1 + print(count) + '''Driver code''' + +li = [ 1, 4, 6, 2, 3, 8 ] +product = 24 +countTriplets(li,product)" +Leaf nodes from Preorder of a Binary Search Tree (Using Recursion),"/*Recursive Java program to find leaf +nodes from given preorder traversal*/ + +class GFG +{ + static int i = 0; +/* Print the leaf node from + the given preorder of BST.*/ + + static boolean isLeaf(int pre[], int n, + int min, int max) + { + if (i >= n) + { + return false; + } + if (pre[i] > min && pre[i] < max) + { + i++; + boolean left = isLeaf(pre, n, min, pre[i - 1]); + boolean right = isLeaf(pre, n, pre[i - 1], max); + if (!left && !right) + { + System.out.print(pre[i - 1] + "" ""); + } + return true; + } + return false; + } + static void printLeaves(int preorder[], int n) + { + isLeaf(preorder, n, Integer.MIN_VALUE, + Integer.MAX_VALUE); + } +/* Driver code*/ + + public static void main(String[] args) + { + int preorder[] = {890, 325, 290, 530, 965}; + int n = preorder.length; + printLeaves(preorder, n); + } +}"," '''Recursive Python program to find leaf +nodes from given preorder traversal''' + + '''Print the leaf node from +the given preorder of BST.''' + +def isLeaf(pre, i, n, Min, Max): + if i[0] >= n: + return False + if pre[i[0]] > Min and pre[i[0]] < Max: + i[0] += 1 + left = isLeaf(pre, i, n, Min, + pre[i[0] - 1]) + right = isLeaf(pre, i, n, + pre[i[0] - 1], Max) + if left == False and right == False: + print(pre[i[0] - 1], end = "" "") + return True + return False +def printLeaves(preorder, n): + i = [0] + INT_MIN, INT_MAX = -999999999999, 999999999999 + isLeaf(preorder, i, n, INT_MIN, INT_MAX) '''Driver code''' + +if __name__ == '__main__': + preorder = [890, 325, 290, 530, 965] + n = len(preorder) + printLeaves(preorder, n)" +Count rotations of N which are Odd and Even,"/*Java implementation of the above approach*/ + + +class Solution { + +/* Function to count of all rotations + which are odd and even*/ + + static 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); + + System.out.println(""Odd = "" + odd_count); + System.out.println(""Even = "" + even_count); + } + +/*Driver Code*/ + + + public static void main(String[] args) + { + int n = 1234; + countOddRotations(n); + } +}"," '''Python implementation of the above approach''' + + + '''Function to count of all rotations +which are odd and even''' + +def countOddRotations(n): + odd_count = 0; even_count = 0 + while n != 0: + digit = n % 10 + if digit % 2 == 0: + odd_count += 1 + else: + even_count += 1 + n = n//10 + print(""Odd ="", odd_count) + print(""Even ="", even_count) + + '''Driver code''' + +n = 1234 +countOddRotations(n) + + +" +Maximum width of a binary tree,"/*Java program to calculate maximum width +of a binary tree using queue*/ + +import java.util.LinkedList; +import java.util.Queue; +public class maxwidthusingqueue +{ + /* A binary tree node has data, pointer to + left child and a pointer to right child */ + + static class node + { + int data; + node left, right; + public node(int data) { this.data = data; } + } +/* Function to find the maximum width of + the tree using level order traversal*/ + + static int maxwidth(node root) + { +/* Base case*/ + + if (root == null) + return 0; +/* Initialize result*/ + + int maxwidth = 0; +/* Do Level order traversal keeping + track of number of nodes at every level*/ + + Queue q = new LinkedList<>(); + q.add(root); + while (!q.isEmpty()) + { +/* Get the size of queue when the level order + traversal for one level finishes*/ + + int count = q.size(); +/* Update the maximum node count value*/ + + maxwidth = Math.max(maxwidth, count); +/* Iterate for all the nodes in + the queue currently*/ + + while (count-- > 0) { +/* Dequeue an node from queue*/ + + node temp = q.remove(); +/* Enqueue left and right children + of dequeued node*/ + + if (temp.left != null) + { + q.add(temp.left); + } + if (temp.right != null) + { + q.add(temp.right); + } + } + } + return maxwidth; + } +/* Driver code*/ + + public static void main(String[] args) + { + 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.right = new node(8); + root.right.right.left = new node(6); + root.right.right.right = new node(7); + /* Constructed Binary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 */ + +/* Function call*/ + + System.out.println(""Maximum width = "" + + maxwidth(root)); + } +}"," '''Python program to find the maximum width of binary +tree using Level Order Traversal with queue.''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to get the maximum width of a binary tree''' + +def getMaxWidth(root): + ''' base case''' + + if root is None: + return 0 + ''' Initialize result''' + + maxWidth = 0 + + ''' Do Level order traversal keeping + track of number of nodes at every level''' + + q = [] + q.insert(0, root) + while (q != []): ''' Get the size of queue when the level order + traversal for one level finishes''' + + count = len(q) + ''' Update the maximum node count value''' + + maxWidth = max(count, maxWidth) + + ''' Iterate for all the nodes in the queue currently''' + + while (count is not 0): + count = count-1 ''' Dequeue an node from queue''' + + temp = q[-1] + q.pop() + if temp.left is not None: + q.insert(0, temp.left) + if temp.right is not None: + q.insert(0, temp.right) + return maxWidth '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) + ''' +Constructed bunary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 + ''' + + '''Function call''' + +print ""Maximum width is %d"" % (getMaxWidth(root))" +Minimum number of swaps required to sort an array,"/*Java program to find +minimum number of swaps +required to sort an array*/ + +import java.util.*; +import java.io.*; +class GfG +{ +/* Return the minimum number + of swaps required to sort the array*/ + + public int minSwaps(int[] arr, int N) + { + int ans = 0; + int[] temp = Arrays.copyOfRange(arr, 0, N); +/* Hashmap which stores the + indexes of the input array*/ + + HashMap h + = new HashMap(); + Arrays.sort(temp); + for (int i = 0; i < N; i++) + { + h.put(arr[i], i); + } + for (int i = 0; i < N; i++) + { +/* This is checking whether + the current element is + at the right place or not*/ + + if (arr[i] != temp[i]) + { + ans++; + int init = arr[i]; +/* If not, swap this element + with the index of the + element which should come here*/ + + swap(arr, i, h.get(temp[i])); +/* Update the indexes in + the hashmap accordingly*/ + + h.put(init, h.get(temp[i])); + h.put(temp[i], i); + } + } + return ans; + } + public void swap(int[] arr, int i, int j) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } +} +/*Driver class*/ + +class Main +{ +/* Driver program to test the above function*/ + + public static void main(String[] args) + throws Exception + { + int[] a + = { 101, 758, 315, 730, 472, + 619, 460, 479 }; + int n = a.length; +/* Output will be 5*/ + + System.out.println(new GfG().minSwaps(a, n)); + } +}"," '''Python3 program to find +minimum number of swaps +required to sort an array + ''' '''Return the minimum number +of swaps required to sort +the array''' + +def minSwap(arr, n): + ans = 0 + temp = arr.copy() + ''' Dictionary which stores the + indexes of the input array''' + + h = {} + temp.sort() + for i in range(n): + h[arr[i]] = i + init = 0 + for i in range(n): ''' This is checking whether + the current element is + at the right place or not''' + + if (arr[i] != temp[i]): + ans += 1 + init = arr[i] + ''' If not, swap this element + with the index of the + element which should come here''' + + arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i] + ''' Update the indexes in + the hashmap accordingly''' + + h[init] = h[temp[i]] + h[temp[i]] = i + return ans + '''Driver code''' + +a = [ 101, 758, 315, 730, + 472, 619, 460, 479 ] +n = len(a) + '''Output will be 5''' + +print(minSwap(a, n))" +Find all elements in array which have at-least two greater elements,"/*Java program to find all +elements in array which +have at-least two greater +elements itself.*/ + +import java.util.*; +import java.io.*; +class GFG +{ +static void findElements(int arr[], + int n) +{ +/* Pick elements one by one + and count greater elements. + If count is more than 2, + print that element.*/ + + for (int i = 0; i < n; i++) + { + int count = 0; + for (int j = 0; j < n; j++) + if (arr[j] > arr[i]) + count++; + if (count >= 2) + System.out.print(arr[i] + "" ""); + } +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = { 2, -6 ,3 , 5, 1}; + int n = arr.length; + findElements(arr, n); +} +}"," '''Python3 program to find +all elements in array +which have at-least two +greater elements itself.''' + +def findElements( arr, n): + ''' Pick elements one by + one and count greater + elements. If count + is more than 2, print + that element.''' + + for i in range(n): + count = 0 + for j in range(0, n): + if arr[j] > arr[i]: + count = count + 1 + if count >= 2 : + print(arr[i], end="" "") + '''Driver code''' + +arr = [ 2, -6 ,3 , 5, 1] +n = len(arr) +findElements(arr, n)" +Recursive selection sort for singly linked list | Swapping node links,"/*Java implementation of recursive selection sort +for singly linked list | Swapping node links*/ + +class GFG +{ + +/*A Linked list node*/ + +static class Node +{ + int data; + Node next; +}; + +/*function to swap nodes 'currX' and 'currY' in a +linked list without swapping data*/ + +static Node swapNodes( Node head_ref, Node currX, + Node currY, Node prevY) +{ +/* make 'currY' as new head*/ + + head_ref = currY; + +/* adjust links*/ + + prevY.next = currX; + +/* Swap next pointers*/ + + Node temp = currY.next; + currY.next = currX.next; + currX.next = temp; + return head_ref; +} + +/*function to sort the linked list using +recursive selection sort technique*/ + +static Node recurSelectionSort( Node head) +{ +/* if there is only a single node*/ + + if (head.next == null) + return head; + +/* 'min' - pointer to store the node having + minimum data value*/ + + Node min = head; + +/* 'beforeMin' - pointer to store node previous + to 'min' node*/ + + Node beforeMin = null; + Node ptr; + +/* traverse the list till the last node*/ + + for (ptr = head; ptr.next != null; ptr = ptr.next) + { + +/* if true, then update 'min' and 'beforeMin'*/ + + if (ptr.next.data < min.data) + { + min = ptr.next; + beforeMin = ptr; + } + } + +/* if 'min' and 'head' are not same, + swap the head node with the 'min' node*/ + + if (min != head) + head = swapNodes(head, head, min, beforeMin); + +/* recursively sort the remaining list*/ + + head.next = recurSelectionSort(head.next); + + return head; +} + +/*function to sort the given linked list*/ + +static Node sort( Node head_ref) +{ +/* if list is empty*/ + + if ((head_ref) == null) + return null; + +/* sort the list using recursive selection + sort technique*/ + + head_ref = recurSelectionSort(head_ref); + return head_ref; +} + +/*function to insert a node at the +beginning of the linked list*/ + +static Node push( Node head_ref, int new_data) +{ +/* allocate node*/ + + Node new_node = new Node(); + +/* put in the data*/ + + new_node.data = new_data; + +/* link the old list to the new node*/ + + new_node.next = (head_ref); + +/* move the head to point to the new node*/ + + (head_ref) = new_node; + return head_ref; +} + +/*function to print the linked list*/ + +static void printList( Node head) +{ + while (head != null) + { + System.out.print( head.data + "" ""); + head = head.next; + } +} + +/*Driver code*/ + +public static void main(String args[]) +{ + Node head = null; + +/* create linked list 10.12.8.4.6*/ + + head = push(head, 6); + head = push(head, 4); + head = push(head, 8); + head = push(head, 12); + head = push(head, 10); + + System.out.println( ""Linked list before sorting:""); + printList(head); + +/* sort the linked list*/ + + head = sort(head); + + System.out.print( ""\nLinked list after sorting:""); + printList(head); +} +} + + +"," '''Python implementation of recursive selection sort +for singly linked list | Swapping node links''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''function to swap nodes 'currX' and 'currY' in a +linked list without swapping data''' + +def swapNodes(head_ref, currX, currY, prevY) : + + ''' make 'currY' as new head''' + + head_ref = currY + + ''' adjust links''' + + prevY.next = currX + + ''' Swap next pointers''' + + temp = currY.next + currY.next = currX.next + currX.next = temp + return head_ref + + '''function to sort the linked list using +recursive selection sort technique''' + +def recurSelectionSort( head) : + + ''' if there is only a single node''' + + if (head.next == None) : + return head + + ''' 'min' - pointer to store the node having + minimum data value''' + + min = head + + ''' 'beforeMin' - pointer to store node previous + to 'min' node''' + + beforeMin = None + ptr = head + + ''' traverse the list till the last node''' + + while ( ptr.next != None ) : + + ''' if true, then update 'min' and 'beforeMin''' + ''' + if (ptr.next.data < min.data) : + + min = ptr.next + beforeMin = ptr + + ptr = ptr.next + + ''' if 'min' and 'head' are not same, + swap the head node with the 'min' node''' + + if (min != head) : + head = swapNodes(head, head, min, beforeMin) + + ''' recursively sort the remaining list''' + + head.next = recurSelectionSort(head.next) + + return head + + '''function to sort the given linked list''' + +def sort( head_ref) : + + ''' if list is empty''' + + if ((head_ref) == None) : + return None + + ''' sort the list using recursive selection + sort technique''' + + head_ref = recurSelectionSort(head_ref) + return head_ref + + '''function to insert a node at the +beginning of the linked list''' + +def push( head_ref, new_data) : + + ''' allocate node''' + + new_node = Node(0) + + ''' put in the data''' + + new_node.data = new_data + + ''' link the old list to the new node''' + + new_node.next = (head_ref) + + ''' move the head to point to the new node''' + + (head_ref) = new_node + return head_ref + + '''function to print the linked list''' + +def printList( head) : + + while (head != None) : + + print( head.data ,end = "" "") + head = head.next + + '''Driver code''' + +head = None + + '''create linked list 10.12.8.4.6''' + +head = push(head, 6) +head = push(head, 4) +head = push(head, 8) +head = push(head, 12) +head = push(head, 10) + +print( ""Linked list before sorting:"") +printList(head) + + '''sort the linked list''' + +head = sort(head) + +print( ""\nLinked list after sorting:"") +printList(head) + + +" +Check given array of size n can represent BST of n levels or not,"/*Java program to Check given array +can represent BST or not*/ + +class GFG +{ +/* structure for Binary Node*/ + + static class Node + { + int key; + Node right, left; + }; + static Node newNode(int num) + { + Node temp = new Node(); + temp.key = num; + temp.left = null; + temp.right = null; + return temp; + } +/* To create a Tree with n levels. We always + insert new node to left if it is less than + previous value.*/ + + static Node createNLevelTree(int arr[], int n) + { + Node root = newNode(arr[0]); + Node temp = root; + for (int i = 1; i < n; i++) + { + if (temp.key > arr[i]) + { + temp.left = newNode(arr[i]); + temp = temp.left; + } + else + { + temp.right = newNode(arr[i]); + temp = temp.right; + } + } + return root; + } +/* Please refer below post for details of this + function. +www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/ +https:*/ + + static boolean isBST(Node root, int min, int max) + { + if (root == null) + { + return true; + } + if (root.key < min || root.key > max) + { + return false; + } +/* Allow only distinct values*/ + + return (isBST(root.left, min, + (root.key) - 1) + && isBST(root.right, + (root.key) + 1, max)); + } +/* Returns tree if given array of size n can + represent a BST of n levels.*/ + + static boolean canRepresentNLevelBST(int arr[], int n) + { + Node root = createNLevelTree(arr, n); + return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {512, 330, 78, 11, 8}; + int n = arr.length; + if (canRepresentNLevelBST(arr, n)) + { + System.out.println(""Yes""); + } + else + { + System.out.println(""No""); + } + } +}"," '''Python program to Check given array +can represent BST or not ''' + + '''A binary tree node has data, +left child and right child ''' + +class newNode(): + def __init__(self, data): + self.key = data + self.left = None + self.right = None '''To create a Tree with n levels. We always +insert new node to left if it is less than +previous value. ''' + +def createNLevelTree(arr, n): + root = newNode(arr[0]) + temp = root + for i in range(1, n): + if (temp.key > arr[i]): + temp.left = newNode(arr[i]) + temp = temp.left + else: + temp.right = newNode(arr[i]) + temp = temp.right + return root + '''Please refer below post for details of this +function. +www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/ +https:''' + +def isBST(root, min, max): + if (root == None): + return True + if (root.key < min or root.key > max): + return False + ''' Allow only distinct values ''' + + return (isBST(root.left, min, (root.key) - 1) and + isBST(root.right,(root.key) + 1, max)) + '''Returns tree if given array of size n can +represent a BST of n levels. ''' + +def canRepresentNLevelBST(arr, n): + root = createNLevelTree(arr, n) + return isBST(root, 0, 2**32) + '''Driver code ''' + +arr = [512, 330, 78, 11, 8] +n = len(arr) +if (canRepresentNLevelBST(arr, n)): + print(""Yes"") +else: + print(""No"")" +Stepping Numbers,"/*A Java program to find all the Stepping Numbers +in range [n, m] using DFS Approach*/ + +import java.util.*; +class Main +{ +/* Method display's all the stepping numbers + in range [n, m]*/ + + public static void dfs(int n,int m,int stepNum) + { +/* If Stepping Number is in the + range [n,m] then display*/ + + if (stepNum <= m && stepNum >= n) + System.out.print(stepNum + "" ""); +/* If Stepping Number is 0 or greater + than m then return*/ + + if (stepNum == 0 || stepNum > m) + return ; +/* Get the last digit of the currently + visited Stepping Number*/ + + int lastDigit = stepNum % 10; +/* There can be 2 cases either digit + to be appended is lastDigit + 1 or + lastDigit - 1*/ + + int stepNumA = stepNum*10 + (lastDigit-1); + int stepNumB = stepNum*10 + (lastDigit+1); +/* If lastDigit is 0 then only possible + digit after 0 can be 1 for a Stepping + Number*/ + + if (lastDigit == 0) + dfs(n, m, stepNumB); +/* If lastDigit is 9 then only possible + digit after 9 can be 8 for a Stepping + Number*/ + + else if(lastDigit == 9) + dfs(n, m, stepNumA); + else + { + dfs(n, m, stepNumA); + dfs(n, m, stepNumB); + } + } +/* Prints all stepping numbers in range [n, m] + using DFS.*/ + + public static void displaySteppingNumbers(int n, int m) + { +/* For every single digit Number 'i' + find all the Stepping Numbers + starting with i*/ + + for (int i = 0 ; i <= 9 ; i++) + dfs(n, m, i); + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 0, m = 21; +/* Display Stepping Numbers in + the range [n,m]*/ + + displaySteppingNumbers(n,m); + } +}"," '''A Python3 program to find all the Stepping Numbers +in range [n, m] using DFS Approach''' + + '''Prints all stepping numbers reachable from num +and in range [n, m]''' + +def dfs(n, m, stepNum) : ''' If Stepping Number is in the + range [n,m] then display''' + + if (stepNum <= m and stepNum >= n) : + print(stepNum, end = "" "") + ''' If Stepping Number is 0 or greater + than m, then return''' + + if (stepNum == 0 or stepNum > m) : + return + ''' Get the last digit of the currently + visited Stepping Number''' + + lastDigit = stepNum % 10 + ''' There can be 2 cases either digit + to be appended is lastDigit + 1 or + lastDigit - 1''' + + stepNumA = stepNum * 10 + (lastDigit - 1) + stepNumB = stepNum * 10 + (lastDigit + 1) + ''' If lastDigit is 0 then only possible + digit after 0 can be 1 for a Stepping + Number''' + + if (lastDigit == 0) : + dfs(n, m, stepNumB) + ''' If lastDigit is 9 then only possible + digit after 9 can be 8 for a Stepping + Number''' + + elif(lastDigit == 9) : + dfs(n, m, stepNumA) + else : + dfs(n, m, stepNumA) + dfs(n, m, stepNumB) + '''Method displays all the stepping +numbers in range [n, m]''' + +def displaySteppingNumbers(n, m) : + ''' For every single digit Number 'i' + find all the Stepping Numbers + starting with i''' + + for i in range(10) : + dfs(n, m, i) + + '''Driver code''' + +n, m = 0, 21 '''Display Stepping Numbers in +the range [n,m]''' + +displaySteppingNumbers(n, m)" +Modify contents of Linked List,"/*Java implementation to modify the +contents of the linked list*/ + +import java.util.*; +class GFG +{ +/* Linked list node*/ + + static class Node + { + int data; + Node next; + }; +/* Function to insert a node at the + beginning of the linked list*/ + + static Node push(Node head_ref, int new_data) + { +/* allocate node*/ + + Node new_node = new Node(); +/* put in the data*/ + + new_node.data = new_data; +/* link the old list at the end of the new node*/ + + new_node.next = head_ref; +/* move the head to point to the new node*/ + + head_ref = new_node; + return head_ref; + } +/* function to print the linked list*/ + + static void printList(Node head) + { + if (head == null) + { + return; + } + while (head.next != null) + { + System.out.print(head.data + ""->""); + head = head.next; + } + System.out.print(head.data + ""\n""); + } +/* Function to middle node of list.*/ + + static Node find_mid(Node head) + { + Node temp = head, slow = head, fast = head; + while (fast != null && fast.next != null) + { +/* Advance 'fast' two nodes, and + advance 'slow' one node*/ + + slow = slow.next; + fast = fast.next.next; + } +/* If number of nodes are odd then update slow + by slow.next;*/ + + if (fast != null) + { + slow = slow.next; + } + return slow; + } +/* function to modify the contents of the linked list.*/ + + static void modifyTheList(Node head, Node slow) + { +/* Create Stack.*/ + + Stack s = new Stack(); + Node temp = head; + while (slow != null) + { + s.add(slow.data); + slow = slow.next; + } +/* Traverse the list by using temp until stack is empty.*/ + + while (!s.empty()) + { + temp.data = temp.data - s.peek(); + temp = temp.next; + s.pop(); + } + } +/* Driver program to test above*/ + + public static void main(String[] args) + { + Node head = null, mid; +/* creating the linked list*/ + + head = push(head, 10); + head = push(head, 7); + head = push(head, 12); + head = push(head, 8); + head = push(head, 9); + head = push(head, 2); +/* Call Function to Find the starting + point of second half of list.*/ + + mid = find_mid(head); +/* Call function to modify + the contents of the linked list.*/ + + modifyTheList(head, mid); +/* print the modified linked list*/ + + System.out.print(""Modified List:"" + ""\n""); + printList(head); + } +}"," '''Python3 implementation to modify the +contents of the linked list''' + '''Linked list node''' + +class Node: + def __init__(self): + self.data = 0 + self.next = None + '''Function to insert a node at the +beginning of the linked list''' + +def append(head_ref, new_data): + ''' Allocate node''' + + new_node = Node() + ''' Put in the data''' + + new_node.data = new_data + ''' Link the old list at the end + of the new node''' + + new_node.next = head_ref + ''' Move the head to point to the new node''' + + head_ref = new_node + return head_ref + '''Function to print the linked list''' + +def printList(head): + if (not head): + return; + while (head.next != None): + print(head.data, end = ' -> ') + head = head.next + print(head.data) + '''Function to middle node of list.''' + +def find_mid(head): + temp = head + slow = head + fast = head + while (fast and fast.next): + ''' Advance 'fast' two nodes, and + advance 'slow' one node''' + + slow = slow.next + fast = fast.next.next + ''' If number of nodes are odd then + update slow by slow.next;''' + + if (fast): + slow = slow.next + return slow + '''Function to modify the contents of +the linked list.''' + +def modifyTheList(head, slow): + ''' Create Stack.''' + + s = [] + temp = head + while (slow): + s.append(slow.data) + slow = slow.next + ''' Traverse the list by using + temp until stack is empty.''' + + while (len(s) != 0): + temp.data = temp.data - s[-1] + temp = temp.next + s.pop() + '''Driver code''' + +if __name__=='__main__': + head = None + ''' creating the linked list''' + + head = append(head, 10) + head = append(head, 7) + head = append(head, 12) + head = append(head, 8) + head = append(head, 9) + head = append(head, 2) + ''' Call Function to Find the + starting point of second half of list.''' + + mid = find_mid(head) + ''' Call function to modify the + contents of the linked list.''' + + modifyTheList( head, mid) + ''' Print the modified linked list''' + + print(""Modified List:"") + printList(head)" +Rearrange a binary string as alternate x and y occurrences,"/*Java program to arrange given string*/ + +import java.io.*; + +class GFG +{ +/* Function which arrange the given string*/ + + static void arrangeString(String str, int x, int y) + { + int count_0 = 0; + int count_1 = 0; + int len = str.length(); + +/* Counting number of 0's and 1's in the + given string.*/ + + for (int i = 0; i < len; i++) + { + if (str.charAt(i) == '0') + count_0++; + else + count_1++; + } + +/* Printing first all 0's x-times + and decrement count of 0's x-times + and do the similar task with '1'*/ + + while (count_0 > 0 || count_1 > 0) + { + for (int j = 0; j < x && count_0 > 0; j++) + { + if (count_0 > 0) + { + System.out.print (""0""); + count_0--; + } + } + for (int j = 0; j < y && count_1 > 0; j++) + { + if (count_1 > 0) + { + System.out.print(""1""); + count_1--; + } + } + } + } + +/* Driver Code*/ + + public static void main (String[] args) + { + String str = ""01101101101101101000000""; + int x = 1; + int y = 2; + arrangeString(str, x, y); + + } +} + + +"," '''Python3 program to arrange given string''' + + + '''Function which arrange the given string''' + +def arrangeString(str1,x,y): + count_0=0 + count_1 =0 + n = len(str1) + + ''' Counting number of 0's and 1's in the + given string.''' + + for i in range(n): + if str1[i] == '0': + count_0 +=1 + else: + count_1 +=1 + + ''' Printing first all 0's x-times + and decrement count of 0's x-times + and do the similar task with '1''' + ''' + while count_0>0 or count_1>0: + for i in range(0,x): + if count_0>0: + print(""0"",end="""") + count_0 -=1 + for j in range(0,y): + if count_1>0: + print(""1"",end="""") + count_1 -=1 + + '''Driver code''' + +if __name__=='__main__': + str1 = ""01101101101101101000000"" + x = 1 + y = 2 + arrangeString(str1, x, y) + + +" +Word Ladder (Length of shortest chain to reach a target word),"/*Java program to find length +of the shortest chain +transformation from source +to target*/ + +import java.util.*; +class GFG +{ +/*Returns length of shortest chain +to reach 'target' from 'start' +using minimum number of adjacent moves. +D is dictionary*/ + +static int shortestChainLen(String start, + String target, + Set D) +{ + if(start == target) + return 0; +/* If the target String is not + present in the dictionary*/ + + if (!D.contains(target)) + return 0; +/* To store the current chain length + and the length of the words*/ + + int level = 0, wordlength = start.length(); +/* Push the starting word into the queue*/ + + Queue Q = new LinkedList<>(); + Q.add(start); +/* While the queue is non-empty*/ + + while (!Q.isEmpty()) + { +/* Increment the chain length*/ + + ++level; +/* Current size of the queue*/ + + int sizeofQ = Q.size(); +/* Since the queue is being updated while + it is being traversed so only the + elements which were already present + in the queue before the start of this + loop will be traversed for now*/ + + for (int i = 0; i < sizeofQ; ++i) + { +/* Remove the first word from the queue*/ + + char []word = Q.peek().toCharArray(); + Q.remove(); +/* For every character of the word*/ + + for (int pos = 0; pos < wordlength; ++pos) + { +/* Retain the original character + at the current position*/ + + char orig_char = word[pos]; +/* Replace the current character with + every possible lowercase alphabet*/ + + for (char c = 'a'; c <= 'z'; ++c) + { + word[pos] = c; +/* If the new word is equal + to the target word*/ + + if (String.valueOf(word).equals(target)) + return level + 1; +/* Remove the word from the set + if it is found in it*/ + + if (!D.contains(String.valueOf(word))) + continue; + D.remove(String.valueOf(word)); +/* And push the newly generated word + which will be a part of the chain*/ + + Q.add(String.valueOf(word)); + } +/* Restore the original character + at the current position*/ + + word[pos] = orig_char; + } + } + } + return 0; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* make dictionary*/ + + Set D = new HashSet(); + D.add(""poon""); + D.add(""plee""); + D.add(""same""); + D.add(""poie""); + D.add(""plie""); + D.add(""poin""); + D.add(""plea""); + String start = ""toon""; + String target = ""plea""; + System.out.print(""Length of shortest chain is: "" + + shortestChainLen(start, target, D)); +} +}"," '''Python3 program to find length of the +shortest chain transformation from source +to target''' + +from collections import deque + '''Returns length of shortest chain +to reach 'target' from 'start' +using minimum number of adjacent +moves. D is dictionary''' + +def shortestChainLen(start, target, D): + if start == target: + return 0 + ''' If the target is not + present in the dictionary''' + + if target not in D: + return 0 + ''' To store the current chain length + and the length of the words''' + + level, wordlength = 0, len(start) + ''' Push the starting word into the queue''' + + Q = deque() + Q.append(start) + ''' While the queue is non-empty''' + + while (len(Q) > 0): + ''' Increment the chain length''' + + level += 1 + ''' Current size of the queue''' + + sizeofQ = len(Q) + ''' Since the queue is being updated while + it is being traversed so only the + elements which were already present + in the queue before the start of this + loop will be traversed for now''' + + for i in range(sizeofQ): + ''' Remove the first word from the queue''' + + word = [j for j in Q.popleft()] ''' + For every character of the word''' + + for pos in range(wordlength): + ''' Retain the original character + at the current position''' + + orig_char = word[pos] + ''' Replace the current character with + every possible lowercase alphabet''' + + for c in range(ord('a'), ord('z')+1): + word[pos] = chr(c) + ''' If the new word is equal + to the target word''' + + if ("""".join(word) == target): + return level + 1 + ''' Remove the word from the set + if it is found in it''' + + if ("""".join(word) not in D): + continue + del D["""".join(word)] + ''' And push the newly generated word + which will be a part of the chain''' + + Q.append("""".join(word)) + ''' Restore the original character + at the current position''' + + word[pos] = orig_char + return 0 + '''Driver code''' + +if __name__ == '__main__': + ''' Make dictionary''' + + D = {} + D[""poon""] = 1 + D[""plee""] = 1 + D[""same""] = 1 + D[""poie""] = 1 + D[""plie""] = 1 + D[""poin""] = 1 + D[""plea""] = 1 + start = ""toon"" + target = ""plea"" + print(""Length of shortest chain is: "", + shortestChainLen(start, target, D))" +Edit Distance | DP-5,"import java.util.*; +class GFG +{ +static int minDis(String s1, String s2, + int n, int m, int[][]dp) +{ +/* If any String is empty, + return the remaining characters of other String*/ + + if(n == 0) + return m; + if(m == 0) + return n; +/* To check if the recursive tree + for given n & m has already been executed*/ + + if(dp[n][m] != -1) + return dp[n][m]; +/* If characters are equal, execute + recursive function for n-1, m-1*/ + + if(s1.charAt(n - 1) == s2.charAt(m - 1)) + { + if(dp[n - 1][m - 1] == -1) + { + return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp); + } + else + return dp[n][m] = dp[n - 1][m - 1]; + } +/* If characters are nt equal, we need to + find the minimum cost out of all 3 operations. */ + + else + { +/*temp variables */ + +int m1, m2, m3; + if(dp[n-1][m] != -1) + { + m1 = dp[n - 1][m]; + } + else + { + m1 = minDis(s1, s2, n - 1, m, dp); + } + if(dp[n][m - 1] != -1) + { + m2 = dp[n][m - 1]; + } + else + { + m2 = minDis(s1, s2, n, m - 1, dp); + } + if(dp[n - 1][m - 1] != -1) + { + m3 = dp[n - 1][m - 1]; + } + else + { + m3 = minDis(s1, s2, n - 1, m - 1, dp); + } + return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3)); + } +} +/*Driver program*/ + +public static void main(String[] args) +{ + String str1 = ""voldemort""; + String str2 = ""dumbledore""; + int n= str1.length(), m = str2.length(); + int[][] dp = new int[n + 1][m + 1]; + for(int i = 0; i < n + 1; i++) + Arrays.fill(dp[i], -1); + System.out.print(minDis(str1, str2, n, m, dp)); +} +}","def minDis(s1, s2, n, m, dp) : + ''' If any string is empty, + return the remaining characters of other string ''' + + if(n == 0) : + return m + if(m == 0) : + return n + ''' To check if the recursive tree + for given n & m has already been executed''' + + if(dp[n][m] != -1) : + return dp[n][m]; + ''' If characters are equal, execute + recursive function for n-1, m-1 ''' + + if(s1[n - 1] == s2[m - 1]) : + if(dp[n - 1][m - 1] == -1) : + dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp) + return dp[n][m] + else : + dp[n][m] = dp[n - 1][m - 1] + return dp[n][m] + ''' If characters are nt equal, we need to + find the minimum cost out of all 3 operations. ''' + + else : + + '''temp variables ''' + + if(dp[n - 1][m] != -1) : + m1 = dp[n - 1][m] + else : + m1 = minDis(s1, s2, n - 1, m, dp) + if(dp[n][m - 1] != -1) : + m2 = dp[n][m - 1] + else : + m2 = minDis(s1, s2, n, m - 1, dp) + if(dp[n - 1][m - 1] != -1) : + m3 = dp[n - 1][m - 1] + else : + m3 = minDis(s1, s2, n - 1, m - 1, dp) + dp[n][m] = 1 + min(m1, min(m2, m3)) + return dp[n][m] ''' Driver code''' + +str1 = ""voldemort"" +str2 = ""dumbledore"" +n = len(str1) +m = len(str2) +dp = [[-1 for i in range(m + 1)] for j in range(n + 1)] +print(minDis(str1, str2, n, m, dp))" +Sum of dependencies in a graph,"/*Java program to find the sum of dependencies*/ + +import java.util.Vector; +class Test +{ +/* To add an edge*/ + + static void addEdge(Vector adj[], int u,int v) + { + adj[u].addElement((v)); + } +/* find the sum of all dependencies*/ + + static int findSum(Vector adj[], int V) + { + int sum = 0; +/* just find the size at each vector's index*/ + + for (int u = 0; u < V; u++) + sum += adj[u].size(); + return sum; + } +/* Driver method*/ + + public static void main(String[] args) + { + int V = 4; + @SuppressWarnings(""unchecked"") + Vector adj[] = new Vector[V]; + for (int i = 0; i < adj.length; i++) { + adj[i] = new Vector<>(); + } + addEdge(adj, 0, 2); + addEdge(adj, 0, 3); + addEdge(adj, 1, 3); + addEdge(adj, 2, 3); + System.out.println(""Sum of dependencies is "" + + findSum(adj, V)); + } +}"," '''Python3 program to find the sum +of dependencies + ''' '''To add an edge''' + +def addEdge(adj, u, v): + adj[u].append(v) + '''Find the sum of all dependencies''' + +def findSum(adj, V): + sum = 0 + ''' Just find the size at each + vector's index''' + + for u in range(V): + sum += len(adj[u]) + return sum + '''Driver code''' + +if __name__=='__main__': + V = 4 + adj = [[] for i in range(V)] + addEdge(adj, 0, 2) + addEdge(adj, 0, 3) + addEdge(adj, 1, 3) + addEdge(adj, 2, 3) + print(""Sum of dependencies is"", + findSum(adj, V))" +"Given an array of size n and a number k, find all elements that appear more than n/k times",," '''Python3 implementation''' + +from collections import Counter + + '''Function to find the number of array +elements with frequency more than n/k times''' + +def printElements(arr, n, k): + + ''' Calculating n/k''' + + x = n//k + + ''' Counting frequency of every + element using Counter''' + + mp = Counter(arr) + + ''' Traverse the map and print all + the elements with occurrence + more than n/k times''' + + for it in mp: + if mp[it] > x: + print(it) + + + '''Driver code''' + +arr = [1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1] +n = len(arr) +k = 4 + +printElements(arr, n, k) + + +" +Deletion at different positions in a Circular Linked List,"/*Java program to delete node at different +poisitions from a circular linked list*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class GFG +{ + +/*structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to insert a node at the end of +a Circular linked list*/ + +static Node Insert(Node head, int data) +{ + Node current = head; + +/* Create a new node*/ + + Node newNode = new Node(); + +/* check node is created or not*/ + + if (newNode == null) + { + System.out.printf(""\nMemory Error\n""); + return null; + } + +/* insert data into newly created node*/ + + newNode.data = data; + +/* check list is empty + if not have any node then + make first node it*/ + + if (head == null) + { + newNode.next = newNode; + head = newNode; + return head; + } + +/* if list have already some node*/ + + else + { + +/* move first node to last node*/ + + while (current.next != head) + { + current = current.next; + } + +/* put first or head node address + in new node link*/ + + newNode.next = head; + +/* put new node address into last + node link(next)*/ + + current.next = newNode; + } + return head; +} + +/*Function print data of list*/ + +static void Display( Node head) +{ + Node current = head; + +/* if list is empty, simply show message*/ + + if (head == null) + { + System.out.printf(""\nDisplay List is empty\n""); + return; + } + +/* traverse first to last node*/ + + else + { + do + { + System.out.printf(""%d "", current.data); + current = current.next; + } while (current != head); + } +} + +/*Function return number of nodes present in list*/ + +static int Length(Node head) +{ + Node current = head; + int count = 0; + +/* if list is empty + simply return length zero*/ + + if (head == null) + { + return 0; + } + +/* traverse forst to last node*/ + + else + { + do + { + current = current.next; + count++; + } while (current != head); + } + return count; +} + +/*Function delete First node of +Circular Linked List*/ + +static Node DeleteFirst(Node head) +{ + Node previous = head, next = head; + +/* check list have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return null; + } + +/* check list have single node + if yes then delete it and return*/ + + if (previous.next == previous) + { + head = null; + return null; + } + +/* traverse second to first*/ + + while (previous.next != head) + { + previous = previous.next; + next = previous.next; + } + +/* now previous is last node and + next is first node of list + first node(next) link address + put in last node(previous) link*/ + + previous.next = next.next; + +/* make second node as head node*/ + + head = previous.next; + + return head; +} + +/*Function to delete last node of +Circular Linked List*/ + +static Node DeleteLast(Node head) +{ + Node current = head, temp = head, previous=null; + +/* check if list doesn't have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return null; + } + +/* check if list have single node + if yes then delete it and return*/ + + if (current.next == current) + { + head = null; + return null; + } + +/* move first node to last + previous*/ + + while (current.next != head) + { + previous = current; + current = current.next; + } + + previous.next = current.next; + head = previous.next; + + return head; +} + +/*Function delete node at a given poisition +of Circular Linked List*/ + +static Node DeleteAtPosition( Node head, int index) +{ +/* Find length of list*/ + + int len = Length(head); + int count = 1; + Node previous = head, next = head; + +/* check list have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nDelete Last List is empty\n""); + return null; + } + +/* given index is in list or not*/ + + if (index >= len || index < 0) + { + System.out.printf(""\nIndex is not Found\n""); + return null; + } + +/* delete first node*/ + + if (index == 0) + { + head = DeleteFirst(head); + return head; + } + +/* traverse first to last node*/ + + while (len > 0) + { + +/* if index found delete that node*/ + + if (index == count) + { + previous.next = next.next; + + return head; + } + previous = previous.next; + next = previous.next; + len--; + count++; + } + return head; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; + head = Insert(head, 99); + head = Insert(head, 11); + head = Insert(head, 22); + head = Insert(head, 33); + head = Insert(head, 44); + head = Insert(head, 55); + head = Insert(head, 66); + +/* Deleting Node at position*/ + + System.out.printf(""Initial List: ""); + Display(head); + System.out.printf(""\nAfter Deleting node at index 4: ""); + head = DeleteAtPosition(head, 4); + Display(head); + +/* Deleting first Node*/ + + System.out.printf(""\n\nInitial List: ""); + Display(head); + System.out.printf(""\nAfter Deleting first node: ""); + head = DeleteFirst(head); + Display(head); + +/* Deleting last Node*/ + + System.out.printf(""\n\nInitial List: ""); + Display(head); + System.out.printf(""\nAfter Deleting last node: ""); + head = DeleteLast(head); + Display(head); +} +} + + +"," '''Python3 program to delete node at different +positions from a circular linked list''' + + + '''A linked list node''' + +class Node: + def __init__(self, new_data): + self.data = new_data + self.next = None + self.prev = None + + '''Function to insert a node at the end of +a Circular linked list''' + +def Insert(head, data): + + current = head + + ''' Create a new node''' + + newNode = Node(0) + + ''' check node is created or not''' + + if (newNode == None): + + print(""\nMemory Error\n"") + return None + + ''' insert data into newly created node''' + + newNode.data = data + + ''' check list is empty + if not have any node then + make first node it''' + + if (head == None) : + newNode.next = newNode + head = newNode + return head + + ''' if list have already some node''' + + else: + + ''' move first node to last node''' + + while (current.next != head): + + current = current.next + + ''' put first or head node address + in new node link''' + + newNode.next = head + + ''' put new node address into last + node link(next)''' + + current.next = newNode + + return head + + '''Function print data of list''' + +def Display(head): + + current = head + + ''' if list is empty, simply show message''' + + if (head == None): + + print(""\nDisplay List is empty\n"") + return + + ''' traverse first to last node''' + + else: + + while(True): + + print( current.data,end="" "") + current = current.next + if (current == head): + break; + + '''Function return number of nodes present in list''' + +def Length(head): + current = head + count = 0 + + ''' if list is empty + simply return length zero''' + + if (head == None): + + return 0 + + ''' traverse forst to last node''' + + else: + + while(True): + + current = current.next + count = count + 1 + if (current == head): + break; + + return count + + '''Function delete First node of +Circular Linked List''' + +def DeleteFirst(head): + previous = head + next = head + + ''' check list have any node + if not then return''' + + if (head == None) : + + print(""\nList is empty"") + return None + + ''' check list have single node + if yes then delete it and return''' + + if (previous.next == previous) : + + head = None + return None + + ''' traverse second to first''' + + while (previous.next != head): + previous = previous.next + next = previous.next + + ''' now previous is last node and + next is first node of list + first node(next) link address + put in last node(previous) link''' + + previous.next = next.next + + ''' make second node as head node''' + + head = previous.next + + return head + + '''Function to delete last node of +Circular Linked List''' + +def DeleteLast(head): + current = head + temp = head + previous = None + + ''' check if list doesn't have any node + if not then return''' + + if (head == None): + print(""\nList is empty"") + return None + + ''' check if list have single node + if yes then delete it and return''' + + if (current.next == current) : + head = None + return None + + ''' move first node to last + previous''' + + while (current.next != head): + previous = current + current = current.next + + previous.next = current.next + head = previous.next + + return head + + '''Function delete node at a given poisition +of Circular Linked List''' + +def DeleteAtPosition(head, index): + + ''' Find length of list''' + + len = Length(head) + count = 1 + previous = head + next = head + + ''' check list have any node + if not then return''' + + if (head == None): + print(""\nDelete Last List is empty"") + return None + + ''' given index is in list or not''' + + if (index >= len or index < 0) : + print(""\nIndex is not Found"") + return None + + ''' delete first node''' + + if (index == 0) : + head = DeleteFirst(head) + return head + + ''' traverse first to last node''' + + while (len > 0): + + ''' if index found delete that node''' + + if (index == count): + previous.next = next.next + + return head + + previous = previous.next + next = previous.next + len = len - 1 + count = count + 1 + + return head + + '''Driver Code''' + + +head = None +head = Insert(head, 99) +head = Insert(head, 11) +head = Insert(head, 22) +head = Insert(head, 33) +head = Insert(head, 44) +head = Insert(head, 55) +head = Insert(head, 66) + + '''Deleting Node at position''' + +print(""Initial List: "") +Display(head) +print(""\nAfter Deleting node at index 4: "") +head = DeleteAtPosition(head, 4) +Display(head) + + '''Deleting first Node''' + +print(""\n\nInitial List: "") +Display(head) +print(""\nAfter Deleting first node: "") +head = DeleteFirst(head) +Display(head) + + '''Deleting last Node''' + +print(""\n\nInitial List: "") +Display(head) +print(""\nAfter Deleting last node: "") +head = DeleteLast(head) +Display(head) + + +" +Find the two repeating elements in a given array,"class RepeatElement +{ + + /*Function to print repeating*/ + + void printRepeating(int arr[], int size) + { + int i; + System.out.println(""The repeating elements are : ""); + for(i = 0; i < size; i++) + { + if(arr[Math.abs(arr[i])] > 0) + arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])]; + else + System.out.print(Math.abs(arr[i]) + "" ""); + } + }/* Driver program to test the above function */ + + public static void main(String[] args) + { + RepeatElement repeat = new RepeatElement(); + int arr[] = {4, 2, 4, 5, 2, 3, 1}; + int arr_size = arr.length; + repeat.printRepeating(arr, arr_size); + } +}"," '''Python3 code for Find the two repeating +elements in a given array''' + + + '''Function to print repeating''' + +def printRepeating(arr, size) : + print("" The repeating elements are"",end="" "") + for i in range(0,size) : + if(arr[abs(arr[i])] > 0) : + arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] + else : + print(abs(arr[i]),end = "" "") '''Driver code''' + +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size)" +Number of local extrema in an array,"/*Java to find +number of extrema*/ + +import java.io.*; + +class GFG { + +/* function to find + local extremum*/ + + static int extrema(int a[], int n) + { + int count = 0; + +/* start loop from + position 1 till n-1*/ + + for (int i = 1; i < n - 1; i++) + { + +/* only one condition + will be true at a + time either a[i] + will be greater than + neighbours or less + than neighbours*/ + + +/* check if a[i] is greater + than both its neighbours + then add 1 to x*/ + + if(a[i] > a[i - 1] && a[i] > a[i + 1]) + count += 1; + +/* check if a[i] is + less than both its + neighbours, then + add 1 to x*/ + + if(a[i] < a[i - 1] && a[i] < a[i + 1]) + count += 1; + } + + return count; + } + +/* driver program*/ + + public static void main(String args[]) + throws IOException + { + int a[] = { 1, 0, 2, 1 }; + int n = a.length; + System.out.println(extrema(a, n)); + } +} + + + +"," '''Python 3 to find +number of extrema''' + + + '''function to find +local extremum''' + +def extrema(a, n): + + count = 0 + ''' start loop from + position 1 till n-1''' + + for i in range(1, n - 1) : + ''' only one condition + will be true + at a time either + a[i] will be greater + than neighbours or + less than neighbours''' + + + ''' check if a[i] if + greater than both its + neighbours, then add + 1 to x''' + + count += (a[i] > a[i - 1] and a[i] > a[i + 1]); + + ''' check if a[i] if + less than both its + neighbours, then + add 1 to x''' + + count += (a[i] < a[i - 1] and a[i] < a[i + 1]); + + return count + + '''driver program''' + +a = [1, 0, 2, 1 ] +n = len(a) +print(extrema(a, n)) + + +" +Decode a string recursively encoded as count followed by substring,"/*Java program to decode a string recursively +encoded as count followed substring*/ + +import java.util.Stack; +class Test +{ +/* Returns decoded string for 'str'*/ + + static String decode(String str) + { + Stack integerstack = new Stack<>(); + Stack stringstack = new Stack<>(); + String temp = """", result = """"; +/* Traversing the string*/ + + for (int i = 0; i < str.length(); i++) + { + int count = 0; +/* If number, convert it into number + and push it into integerstack.*/ + + if (Character.isDigit(str.charAt(i))) + { + while (Character.isDigit(str.charAt(i))) + { + count = count * 10 + str.charAt(i) - '0'; + i++; + } + i--; + integerstack.push(count); + } +/* If closing bracket ']', pop elemment until + '[' opening bracket is not found in the + character stack.*/ + + else if (str.charAt(i) == ']') + { + temp = """"; + count = 0; + if (!integerstack.isEmpty()) + { + count = integerstack.peek(); + integerstack.pop(); + } + while (!stringstack.isEmpty() && stringstack.peek()!='[' ) + { + temp = stringstack.peek() + temp; + stringstack.pop(); + } + if (!stringstack.empty() && stringstack.peek() == '[') + stringstack.pop(); +/* Repeating the popped string 'temo' count + number of times.*/ + + for (int j = 0; j < count; j++) + result = result + temp; +/* Push it in the character stack.*/ + + for (int j = 0; j < result.length(); j++) + stringstack.push(result.charAt(j)); + result = """"; + } +/* If '[' opening bracket, push it into character stack.*/ + + else if (str.charAt(i) == '[') + { + if (Character.isDigit(str.charAt(i-1))) + stringstack.push(str.charAt(i)); + else + { + stringstack.push(str.charAt(i)); + integerstack.push(1); + } + } + else + stringstack.push(str.charAt(i)); + } +/* Pop all the elmenet, make a string and return.*/ + + while (!stringstack.isEmpty()) + { + result = stringstack.peek() + result; + stringstack.pop(); + } + return result; + } +/* Driver method*/ + + public static void main(String args[]) + { + String str = ""3[b2[ca]]""; + System.out.println(decode(str)); + } +}"," '''Python program to decode a string recursively +encoded as count followed substring + ''' '''Returns decoded string for 'str' ''' + +def decode(Str): + integerstack = [] + stringstack = [] + temp = """" + result = """" + i = 0 + ''' Traversing the string ''' + + while i < len(Str): + count = 0 + ''' If number, convert it into number + and push it into integerstack. ''' + + if (Str[i] >= '0' and Str[i] <='9'): + while (Str[i] >= '0' and Str[i] <= '9'): + count = count * 10 + ord(Str[i]) - ord('0') + i += 1 + i -= 1 + integerstack.append(count) + ''' If closing bracket ']', pop elemment until + '[' opening bracket is not found in the + character stack. ''' + + elif (Str[i] == ']'): + temp = """" + count = 0 + if (len(integerstack) != 0): + count = integerstack[-1] + integerstack.pop() + while (len(stringstack) != 0 and stringstack[-1] !='[' ): + temp = stringstack[-1] + temp + stringstack.pop() + if (len(stringstack) != 0 and stringstack[-1] == '['): + stringstack.pop() + ''' Repeating the popped string 'temo' count + number of times.''' + + for j in range(count): + result = result + temp + ''' Push it in the character stack.''' + + for j in range(len(result)): + stringstack.append(result[j]) + result = """" + ''' If '[' opening bracket, push it into character stack. ''' + + elif (Str[i] == '['): + if (Str[i-1] >= '0' and Str[i-1] <= '9'): + stringstack.append(Str[i]) + else: + stringstack.append(Str[i]) + integerstack.append(1) + else: + stringstack.append(Str[i]) + i += 1 + ''' Pop all the elmenet, make a string and return.''' + + while len(stringstack) != 0: + result = stringstack[-1] + result + stringstack.pop() + return result + '''Driven code ''' + +if __name__ == '__main__': + Str = ""3[b2[ca]]"" + print(decode(Str))" +Linear Search,"/*Java program for linear search*/ + +import java.io.*; +class GFG +{ + public static void search(int arr[], int search_Element) + { + int left = 0; + int length = arr.length; + int right = length - 1; + int position = -1; +/* run loop from 0 to right*/ + + for (left = 0; left <= right;) + { +/* if search_element is found with left variable*/ + + if (arr[left] == search_Element) + { + position = left; + System.out.println( + ""Element found in Array at "" + + (position + 1) + "" Position with "" + + (left + 1) + "" Attempt""); + break; + } +/* if search_element is found with right variable*/ + + if (arr[right] == search_Element) + { + position = right; + System.out.println( + ""Element found in Array at "" + + (position + 1) + "" Position with "" + + (length - right) + "" Attempt""); + break; + } + left++; + right--; + } +/* if element not found*/ + + if (position == -1) + System.out.println(""Not found in Array with "" + + left + "" Attempt""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 2, 3, 4, 5 }; + int search_element = 5; +/* Function call*/ + + search(arr,search_element); + } +}"," '''Python3 program for linear search''' + +def search(arr, search_Element): + left = 0 + length = len(arr) + position = -1 + right = length - 1 + ''' Run loop from 0 to right''' + + for left in range(0, right, 1): + ''' If search_element is found with + left variable''' + + if (arr[left] == search_Element): + position = left + print(""Element found in Array at "", position + + 1, "" Position with "", left + 1, "" Attempt"") + break + ''' If search_element is found with + right variable''' + + if (arr[right] == search_Element): + position = right + print(""Element found in Array at "", position + 1, + "" Position with "", length - right, "" Attempt"") + break + left += 1 + right -= 1 + ''' If element not found''' + + if (position == -1): + print(""Not found in Array with "", left, "" Attempt"") + '''Driver code''' + +arr = [1, 2, 3, 4, 5] +search_element = 5 + '''Function call''' + +search(arr, search_element)" +Find subarray with given sum | Set 1 (Nonnegative Numbers),"class SubarraySum { + /* Returns true if the there is +a subarray of arr[] with sum equal to + 'sum' otherwise returns false. +Also, prints the result */ + + int subArraySum(int arr[], int n, int sum) + { + +/* Initialize curr_sum as + value of first element + and starting point as 0 */ + + int curr_sum = arr[0], start = 0, i;/* Pick a starting point*/ + + for (i = 1; i <= n; i++) { +/* If curr_sum exceeds the sum, + then remove the starting elements*/ + + while (curr_sum > sum && start < i - 1) { + curr_sum = curr_sum - arr[start]; + start++; + } +/* If curr_sum becomes equal to sum, + then return true*/ + + if (curr_sum == sum) { + int p = i - 1; + System.out.println( + ""Sum found between indexes "" + start + + "" and "" + p); + return 1; + } +/* Add this element to curr_sum*/ + + if (i < n) + curr_sum = curr_sum + arr[i]; + } + +/* If we reach here, then no subarray*/ + + System.out.println(""No subarray found""); + return 0; + }/*Driver Code*/ + + public static void main(String[] args) + { + SubarraySum arraysum = new SubarraySum(); + int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; + int n = arr.length; + int sum = 23; + arraysum.subArraySum(arr, n, sum); + } +}"," '''An efficient program +to print subarray +with sum as given sum''' + + '''Returns true if the +there is a subarray +of arr[] with sum +equal to 'sum' +otherwise returns +false. Also, prints +the result.''' + +def subArraySum(arr, n, sum_): ''' Initialize curr_sum as + value of first element + and starting point as 0''' + + curr_sum = arr[0] + start = 0 + ''' Add elements one by + one to curr_sum and + if the curr_sum exceeds + the sum, then remove + starting element''' + + i = 1 + while i <= n: + ''' If curr_sum exceeds + the sum, then remove + the starting elements''' + + while curr_sum > sum_ and start < i-1: + curr_sum = curr_sum - arr[start] + start += 1 + ''' If curr_sum becomes + equal to sum, then + return true''' + + if curr_sum == sum_: + print (""Sum found between indexes"") + print (""% d and % d""%(start, i-1)) + return 1 + ''' Add this element + to curr_sum''' + + if i < n: + curr_sum = curr_sum + arr[i] + i += 1 + ''' If we reach here, + then no subarray''' + + print (""No subarray found"") + return 0 + '''Driver program''' + +arr = [15, 2, 4, 8, 9, 5, 10, 23] +n = len(arr) +sum_ = 23 +subArraySum(arr, n, sum_) +" +Count triplets with sum smaller than a given value,"/*A Simple Java program to count triplets with sum smaller +than a given value*/ + + +class Test +{ + static int arr[] = new int[]{5, 1, 3, 4, 7}; + + static int countTriplets(int n, int sum) + { +/* Initialize result*/ + + int ans = 0; + +/* Fix the first element as A[i]*/ + + for (int i = 0; i < n-2; i++) + { +/* Fix the second element as A[j]*/ + + for (int j = i+1; j < n-1; j++) + { +/* Now look for the third number*/ + + for (int k = j+1; k < n; k++) + if (arr[i] + arr[j] + arr[k] < sum) + ans++; + } + } + + return ans; + } + +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + int sum = 12; + System.out.println(countTriplets(arr.length, sum)); + } +} +"," '''A Simple Python 3 program to count triplets with sum smaller +than a given value +include''' + +def countTriplets(arr, n, sum): + + ''' Initialize result''' + + ans = 0 + + ''' Fix the first element as A[i]''' + + for i in range( 0 ,n-2): + + ''' Fix the second element as A[j]''' + + for j in range( i+1 ,n-1): + + ''' Now look for the third number''' + + for k in range( j+1, n): + if (arr[i] + arr[j] + arr[k] < sum): + ans+=1 + + return ans + + '''Driver program''' + +arr = [5, 1, 3, 4, 7] +n = len(arr) +sum = 12 +print(countTriplets(arr, n, sum)) + +" +Maximum and minimum of an array using minimum number of comparisons,"/*Java program of above implementation*/ + +public class GFG { +/* Class Pair is used to return two values from getMinMax() */ + + static class Pair { + int min; + int max; + } + static Pair getMinMax(int arr[], int n) { + Pair minmax = new Pair(); + int i; + /* If array has even number of elements then + initialize the first two elements as minimum and + maximum */ + + if (n % 2 == 0) { + if (arr[0] > arr[1]) { + minmax.max = arr[0]; + minmax.min = arr[1]; + } else { + minmax.min = arr[0]; + minmax.max = arr[1]; + } + + /* set the starting index for loop */ + i = 2; + } /* If array has odd number of elements then + initialize the first element as minimum and + maximum */ + else { + minmax.min = arr[0]; + minmax.max = arr[0]; + + /* set the starting index for loop */ + i = 1; + } + /* In the while loop, pick elements in pair and + compare the pair with max and min so far */ + + while (i < n - 1) { + if (arr[i] > arr[i + 1]) { + if (arr[i] > minmax.max) { + minmax.max = arr[i]; + } + if (arr[i + 1] < minmax.min) { + minmax.min = arr[i + 1]; + } + } else { + if (arr[i + 1] > minmax.max) { + minmax.max = arr[i + 1]; + } + if (arr[i] < minmax.min) { + minmax.min = arr[i]; + } + } + + /* Increment the index by 2 as two + elements are processed in loop */ + i += 2; + } + return minmax; + } + /* Driver program to test above function */ + + public static void main(String args[]) { + int arr[] = {1000, 11, 445, 1, 330, 3000}; + int arr_size = 6; + Pair minmax = getMinMax(arr, arr_size); + System.out.printf(""\nMinimum element is %d"", minmax.min); + System.out.printf(""\nMaximum element is %d"", minmax.max); + } +}"," '''Python3 program of above implementation''' + + + ''' getMinMax()''' + +def getMinMax(arr): + n = len(arr) ''' If array has even number of elements then + initialize the first two elements as minimum + and maximum''' + + if(n % 2 == 0): + mx = max(arr[0], arr[1]) + mn = min(arr[0], arr[1]) + ''' set the starting index for loop''' + + i = 2 + ''' If array has odd number of elements then + initialize the first element as minimum + and maximum''' + + else: + mx = mn = arr[0] + ''' set the starting index for loop''' + + i = 1 + ''' In the while loop, pick elements in pair and + compare the pair with max and min so far''' + + while(i < n - 1): + if arr[i] < arr[i + 1]: + mx = max(mx, arr[i + 1]) + mn = min(mn, arr[i]) + else: + mx = max(mx, arr[i]) + mn = min(mn, arr[i + 1]) + ''' Increment the index by 2 as two + elements are processed in loop''' + + i += 2 + return (mx, mn) + '''Driver Code''' + +if __name__ =='__main__': + arr = [1000, 11, 445, 1, 330, 3000] + mx, mn = getMinMax(arr) + print(""Minimum element is"", mn) + print(""Maximum element is"", mx)" +Find all rectangles filled with 0,," '''Python program to find all +rectangles filled with 0''' + +def findend(i,j,a,output,index): + x = len(a) + y = len(a[0]) + ''' flag to check column edge case, + initializing with 0''' + + flagc = 0 + ''' flag to check row edge case, + initializing with 0''' + + flagr = 0 + for m in range(i,x): + ''' loop breaks where first 1 encounters''' + + if a[m][j] == 1: + '''set the flag''' + + flagr = 1 + break + ''' pass because already processed''' + + if a[m][j] == 5: + pass + for n in range(j, y): + ''' loop breaks where first 1 encounters''' + + if a[m][n] == 1: + '''set the flag''' + + flagc = 1 + break + ''' fill rectangle elements with any + number so that we can exclude + next time''' + + a[m][n] = 5 + if flagr == 1: + output[index].append( m-1) + else: + ''' when end point touch the boundary''' + + output[index].append(m) + if flagc == 1: + output[index].append(n-1) + else: + ''' when end point touch the boundary''' + + output[index].append(n) +def get_rectangle_coordinates(a): + ''' retrieving the column size of array''' + + size_of_array = len(a) + ''' output array where we are going + to store our output''' + + output = [] + ''' It will be used for storing start + and end location in the same index''' + + index = -1 + for i in range(0,size_of_array): + for j in range(0, len(a[0])): + if a[i][j] == 0: + ''' storing initial position + of rectangle''' + + output.append([i, j]) + ''' will be used for the + last position''' + + index = index + 1 + findend(i, j, a, output, index) + print (output) + '''driver code''' + +tests = [ + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 0, 0, 0, 1], + [1, 0, 1, 0, 0, 0, 1], + [1, 0, 1, 1, 1, 1, 1], + [1, 0, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 1, 1] + ] +get_rectangle_coordinates(tests)" +Subtract Two Numbers represented as Linked Lists,"/*Java program to subtract smaller valued +list from larger valued list and return +result as a list.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class LinkedList { +/*head of list*/ + +static Node head; + boolean borrow; + + /* Node Class */ + + static class Node { + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } + } + + +/* A utility function to get length of + linked list */ + + int getLength(Node node) + { + int size = 0; + while (node != null) { + node = node.next; + size++; + } + return size; + } + + /* A Utility that padds zeros in front + of the Node, with the given diff */ + + Node paddZeros(Node sNode, int diff) + { + if (sNode == null) + return null; + + Node zHead = new Node(0); + diff--; + Node temp = zHead; + while ((diff--) != 0) { + temp.next = new Node(0); + temp = temp.next; + } + temp.next = sNode; + return zHead; + } + + /* Subtract LinkedList Helper is a recursive + function, move till the last Node, and + subtract the digits and create the Node and + return the Node. If d1 < d2, we borrow the + number from previous digit. */ + + Node subtractLinkedListHelper(Node l1, Node l2) + { + if (l1 == null && l2 == null && borrow == false) + return null; + + Node previous + = subtractLinkedListHelper( + (l1 != null) ? l1.next + : null, + (l2 != null) ? l2.next : null); + + int d1 = l1.data; + int d2 = l2.data; + int sub = 0; + + /* if you have given the value value to + next digit then reduce the d1 by 1 */ + + if (borrow) { + d1--; + borrow = false; + } + + /* If d1 < d2, then borrow the number from + previous digit. Add 10 to d1 and set + borrow = true; */ + + if (d1 < d2) { + borrow = true; + d1 = d1 + 10; + } + + /* subtract the digits */ + + sub = d1 - d2; + + /* Create a Node with sub value */ + + Node current = new Node(sub); + + /* Set the Next pointer as Previous */ + + current.next = previous; + + return current; + } + + /* This API subtracts two linked lists and + returns the linked list which shall have the + subtracted result. */ + + Node subtractLinkedList(Node l1, Node l2) + { +/* Base Case.*/ + + if (l1 == null && l2 == null) + return null; + +/* In either of the case, get the lengths + of both Linked list.*/ + + int len1 = getLength(l1); + int len2 = getLength(l2); + + Node lNode = null, sNode = null; + + Node temp1 = l1; + Node temp2 = l2; + +/* If lengths differ, calculate the smaller + Node and padd zeros for smaller Node and + ensure both larger Node and smaller Node + has equal length.*/ + + if (len1 != len2) { + lNode = len1 > len2 ? l1 : l2; + sNode = len1 > len2 ? l2 : l1; + sNode = paddZeros(sNode, Math.abs(len1 - len2)); + } + + else { +/* If both list lengths are equal, then + calculate the larger and smaller list. + If 5-6-7 & 5-6-8 are linked list, then + walk through linked list at last Node + as 7 < 8, larger Node is 5-6-8 and + smaller Node is 5-6-7.*/ + + while (l1 != null && l2 != null) { + if (l1.data != l2.data) { + lNode = l1.data > l2.data ? temp1 : temp2; + sNode = l1.data > l2.data ? temp2 : temp1; + break; + } + l1 = l1.next; + l2 = l2.next; + } + } + +/* After calculating larger and smaller Node, + call subtractLinkedListHelper which returns + the subtracted linked list.*/ + + borrow = false; + return subtractLinkedListHelper(lNode, sNode); + } + +/* function to display the linked list*/ + + static void printList(Node head) + { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + "" ""); + temp = temp.next; + } + } + +/* Driver program to test above*/ + + public static void main(String[] args) + { + Node head = new Node(1); + head.next = new Node(0); + head.next.next = new Node(0); + + Node head2 = new Node(1); + + LinkedList ob = new LinkedList(); + Node result = ob.subtractLinkedList(head, head2); + + printList(result); + } +} + + +"," '''Python program to subtract smaller valued list from +larger valued list and return result as a list.''' + + + '''A linked List Node''' + +class Node: + def __init__(self, new_data): + self.data = new_data + self.next = None +def newNode(data): + + temp = Node(0) + temp.data = data + temp.next = None + return temp + + + '''A utility function to get length of linked list''' + +def getLength(Node): + + size = 0 + while (Node != None): + + Node = Node.next + size = size + 1 + + return size + + '''A Utility that padds zeros in front of the +Node, with the given diff''' + +def paddZeros( sNode, diff): + + if (sNode == None): + return None + + zHead = newNode(0) + diff = diff - 1 + temp = zHead + while (diff > 0): + diff = diff - 1 + temp.next = newNode(0) + temp = temp.next + + temp.next = sNode + return zHead + +borrow = True + + '''Subtract LinkedList Helper is a recursive function, +move till the last Node, and subtract the digits and +create the Node and return the Node. If d1 < d2, we +borrow the number from previous digit.''' + +def subtractLinkedListHelper(l1, l2): + + global borrow + + if (l1 == None and l2 == None and not borrow ): + return None + + l3 = None + l4 = None + if(l1 != None): + l3 = l1.next + if(l2 != None): + l4 = l2.next + previous = subtractLinkedListHelper(l3, l4) + + d1 = l1.data + d2 = l2.data + sub = 0 + + ''' if you have given the value value to next digit then + reduce the d1 by 1''' + + if (borrow): + d1 = d1 - 1 + borrow = False + + ''' If d1 < d2, then borrow the number from previous digit. + Add 10 to d1 and set borrow = True''' + + if (d1 < d2): + borrow = True + d1 = d1 + 10 + + ''' subtract the digits''' + + sub = d1 - d2 + + ''' Create a Node with sub value''' + + current = newNode(sub) + + ''' Set the Next pointer as Previous''' + + current.next = previous + + return current + + '''This API subtracts two linked lists and returns the +linked list which shall have the subtracted result.''' + +def subtractLinkedList(l1, l2): + + ''' Base Case.''' + + if (l1 == None and l2 == None): + return None + + ''' In either of the case, get the lengths of both + Linked list.''' + + len1 = getLength(l1) + len2 = getLength(l2) + + lNode = None + sNode = None + + temp1 = l1 + temp2 = l2 + + ''' If lengths differ, calculate the smaller Node + and padd zeros for smaller Node and ensure both + larger Node and smaller Node has equal length.''' + + if (len1 != len2): + if(len1 > len2): + lNode = l1 + else: + lNode = l2 + + if(len1 > len2): + sNode = l2 + else: + sNode = l1 + sNode = paddZeros(sNode, abs(len1 - len2)) + + else: + + ''' If both list lengths are equal, then calculate + the larger and smaller list. If 5-6-7 & 5-6-8 + are linked list, then walk through linked list + at last Node as 7 < 8, larger Node is 5-6-8 + and smaller Node is 5-6-7.''' + + while (l1 != None and l2 != None): + + if (l1.data != l2.data): + if(l1.data > l2.data ): + lNode = temp1 + else: + lNode = temp2 + + if(l1.data > l2.data ): + sNode = temp2 + else: + sNode = temp1 + break + + l1 = l1.next + l2 = l2.next + + global borrow + + ''' After calculating larger and smaller Node, call + subtractLinkedListHelper which returns the subtracted + linked list.''' + + borrow = False + return subtractLinkedListHelper(lNode, sNode) + + '''A utility function to print linked list''' + +def printList(Node): + + while (Node != None): + + print (Node.data, end ="" "") + Node = Node.next + + print("" "") + + + '''Driver program to test above functions''' + + +head1 = newNode(1) +head1.next = newNode(0) +head1.next.next = newNode(0) + +head2 = newNode(1) + +result = subtractLinkedList(head1, head2) + +printList(result) + + +" +Check if a given Binary Tree is height balanced like a Red-Black Tree,"/*Java Program to check if a given Binary +Tree is balanced like a Red-Black Tree */ + +class GFG +{ +static class Node +{ + int key; + Node left, right; + Node(int key) + { + left = null; + right = null; + this.key = key; + } +} +static class INT +{ + static int d; + INT() + { + d = 0; + } +} +/*Returns returns tree if the Binary +tree is balanced like a Red-Black +tree. This function also sets value +in maxh and minh (passed by reference). +maxh and minh are set as maximum and +minimum heights of root.*/ + +static boolean isBalancedUtil(Node root, + INT maxh, INT minh) +{ +/* Base case*/ + + if (root == null) + { + maxh.d = minh.d = 0; + return true; + } +/* To store max and min heights of left subtree*/ + + INT lmxh=new INT(), lmnh=new INT(); +/* To store max and min heights of right subtree*/ + + INT rmxh=new INT(), rmnh=new INT(); +/* Check if left subtree is balanced, + also set lmxh and lmnh*/ + + if (isBalancedUtil(root.left, lmxh, lmnh) == false) + return false; +/* Check if right subtree is balanced, + also set rmxh and rmnh*/ + + if (isBalancedUtil(root.right, rmxh, rmnh) == false) + return false; +/* Set the max and min heights + of this node for the parent call*/ + + maxh.d = Math.max(lmxh.d, rmxh.d) + 1; + minh.d = Math.min(lmnh.d, rmnh.d) + 1; +/* See if this node is balanced*/ + + if (maxh.d <= 2*minh.d) + return true; + return false; +} +/*A wrapper over isBalancedUtil()*/ + +static boolean isBalanced(Node root) +{ + INT maxh=new INT(), minh=new INT(); + return isBalancedUtil(root, maxh, minh); +} +/*Driver code*/ + +public static void main(String args[]) +{ + Node root = new Node(10); + root.left = new Node(5); + root.right = new Node(100); + root.right.left = new Node(50); + root.right.right = new Node(150); + root.right.left.left = new Node(40); + System.out.println(isBalanced(root) ? + ""Balanced"" : ""Not Balanced""); +} +}"," ''' Program to check if a given Binary +Tree is balanced like a Red-Black Tree ''' + + '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Returns returns tree if the Binary +tree is balanced like a Red-Black +tree. This function also sets value +in maxh and minh (passed by +reference). maxh and minh are set +as maximum and minimum heights of root. ''' + +def isBalancedUtil(root, maxh, minh) : + ''' Base case ''' + + if (root == None) : + maxh = minh = 0 + return True + lmxh=0 + ''' To store max and min + heights of left subtree ''' + + lmnh=0 + ''' To store max and min + heights of right subtree''' + + rmxh, rmnh=0,0 + ''' Check if left subtree is balanced, + also set lmxh and lmnh ''' + + if (isBalancedUtil(root.left, lmxh, lmnh) == False) : + return False + ''' Check if right subtree is balanced, + also set rmxh and rmnh ''' + + if (isBalancedUtil(root.right, rmxh, rmnh) == False) : + return False + ''' Set the max and min heights of + this node for the parent call ''' + + maxh = max(lmxh, rmxh) + 1 + minh = min(lmnh, rmnh) + 1 + ''' See if this node is balanced ''' + + if (maxh <= 2 * minh) : + return True + return False + '''A wrapper over isBalancedUtil() ''' + +def isBalanced(root) : + maxh, minh =0,0 + return isBalancedUtil(root, maxh, minh) + '''Driver Code ''' + +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(5) + root.right = newNode(100) + root.right.left = newNode(50) + root.right.right = newNode(150) + root.right.left.left = newNode(40) + if (isBalanced(root)): + print(""Balanced"") + else: + print(""Not Balanced"")" +Perfect Binary Tree Specific Level Order Traversal | Set 2,"/*Java program for special order traversal*/ + +import java.util.*; +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node root; + +/*Function body*/ + + void printSpecificLevelOrderUtil(Node root, Stack s) + { + if (root == null) + return;/* Create a queue and enqueue left and right + children of root*/ + + Queue q = new LinkedList(); + q.add(root.left); + q.add(root.right); +/* We process two nodes at a time, so we + need two variables to store two front + items of queue*/ + + Node first = null, second = null; +/* traversal loop*/ + + while (!q.isEmpty()) + { +/* Pop two items from queue*/ + + first = q.peek(); + q.poll(); + second = q.peek(); + q.poll(); +/* Push first and second node's chilren + in reverse order*/ + + s.push(second.left); + s.push(first.right); + s.push(second.right); + s.push(first.left); +/* If first and second have grandchildren, + enqueue them in specific order*/ + + if (first.left.left != null) + { + q.add(first.right); + q.add(second.left); + q.add(first.left); + q.add(second.right); + } + } + } + /* Given a perfect binary tree, print its nodes in + specific level order */ + + void printSpecificLevelOrder(Node root) + { +/* create a stack and push root*/ + + Stack s = new Stack(); +/* Push level 1 and level 2 nodes in stack*/ + + s.push(root); +/* Since it is perfect Binary Tree, right is + not checked*/ + + if (root.left != null) + { + s.push(root.right); + s.push(root.left); + } +/* Do anything more if there are nodes at next + level in given perfect Binary Tree*/ + + if (root.left.left != null) + printSpecificLevelOrderUtil(root, s); +/* Finally pop all Nodes from stack and prints + them.*/ + + while (!s.empty()) + { + System.out.print(s.peek().data + "" ""); + s.pop(); + } + } +/* Driver program to test the above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + System.out.println(""Specific Level Order Traversal "" + + ""of Binary Tree is ""); + tree.printSpecificLevelOrder(tree.root); + }", +Count rotations divisible by 4,"/*Java program to count +all rotation divisible +by 4.*/ + +import java.io.*; + +class GFG { + +/* Returns count of all + rotations divisible + by 4*/ + + static int countRotations(String n) + { + int len = n.length(); + +/* For single digit number*/ + + if (len == 1) + { + int oneDigit = n.charAt(0)-'0'; + + if (oneDigit % 4 == 0) + return 1; + + return 0; + } + +/* At-least 2 digit + number (considering all + pairs)*/ + + int twoDigit, count = 0; + for (int i = 0; i < (len-1); i++) + { + twoDigit = (n.charAt(i)-'0') * 10 + + (n.charAt(i+1)-'0'); + + if (twoDigit%4 == 0) + count++; + } + +/* Considering the number + formed by the pair of + last digit and 1st digit*/ + + twoDigit = (n.charAt(len-1)-'0') * 10 + + (n.charAt(0)-'0'); + + if (twoDigit%4 == 0) + count++; + + return count; + } + +/* Driver program*/ + + public static void main(String args[]) + { + String n = ""4834""; + System.out.println(""Rotations: "" + + countRotations(n)); + } +} + + +"," '''Python3 program to count +all rotation divisible +by 4.''' + + + '''Returns count of all +rotations divisible +by 4''' + +def countRotations(n) : + + l = len(n) + + ''' For single digit number''' + + if (l == 1) : + oneDigit = (int)(n[0]) + + if (oneDigit % 4 == 0) : + return 1 + return 0 + + + ''' At-least 2 digit number + (considering all pairs)''' + + count = 0 + for i in range(0, l - 1) : + twoDigit = (int)(n[i]) * 10 + (int)(n[i + 1]) + + if (twoDigit % 4 == 0) : + count = count + 1 + + ''' Considering the number + formed by the pair of + last digit and 1st digit''' + + twoDigit = (int)(n[l - 1]) * 10 + (int)(n[0]) + if (twoDigit % 4 == 0) : + count = count + 1 + + return count + + '''Driver program''' + +n = ""4834"" +print(""Rotations: "" , + countRotations(n)) + + +" +Print all nodes that are at distance k from a leaf node,"/*Java program to print all nodes at a distance k from leaf*/ + + + /*A binary tree node*/ + +class Node { + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree { + Node root;/* Given a binary tree and a nuber k, print all nodes that are k + distant from a leaf*/ + + int printKDistantfromLeaf(Node node, int k) + { + if (node == null) + return -1; + int lk = printKDistantfromLeaf(node.left, k); + int rk = printKDistantfromLeaf(node.right, k); + boolean isLeaf = lk == -1 && lk == rk; + if (lk == 0 || rk == 0 || (isLeaf && k == 0)) + System.out.print("" "" + node.data); + if (isLeaf && k > 0) +/*leaf node*/ + +return k - 1; + if (lk > 0 && lk < k) +/*parent of left leaf*/ + +return lk - 1; + if (rk > 0 && rk < k) +/*parent of right leaf*/ + +return rk - 1; + + return -2; + } + +/* Driver program to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + + /* Let us construct the tree shown in above diagram */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.right.left.right = new Node(8); + + System.out.println("" Nodes at distance 2 are :""); + tree.printKDistantfromLeaf(tree.root, 2); + } +} + + +", +Find the minimum number of moves needed to move from one cell of matrix to another,," '''Python3 program to find the minimum numbers +of moves needed to move from source to +destination .''' + +class Graph: + def __init__(self, V): + self.V = V + self.adj = [[] for i in range(V)] + ''' add edge to graph''' + + def addEdge (self, s , d ): + self.adj[s].append(d) + self.adj[d].append(s) + ''' Level BFS function to find minimum + path from source to sink''' + + def BFS(self, s, d): + ''' Base case''' + + if (s == d): + return 0 + ''' make initial distance of all + vertex -1 from source''' + + level = [-1] * self.V + ''' Create a queue for BFS''' + + queue = [] + ''' Mark the source node level[s] = '0''' + level[s] = 0 + queue.append(s) + ''' it will be used to get all adjacent + vertices of a vertex''' + + while (len(queue) != 0): + ''' Dequeue a vertex from queue''' + + s = queue.pop() + ''' Get all adjacent vertices of the + dequeued vertex s. If a adjacent has + not been visited ( level[i] < '0') , + then update level[i] == parent_level[s] + 1 + and enqueue it''' + + i = 0 + while i < len(self.adj[s]): + ''' Else, continue to do BFS''' + + if (level[self.adj[s][i]] < 0 or + level[self.adj[s][i]] > level[s] + 1 ): + level[self.adj[s][i]] = level[s] + 1 + queue.append(self.adj[s][i]) + i += 1 + ''' return minimum moves from source + to sink''' + + return level[d] +def isSafe(i, j, M): + global N + if ((i < 0 or i >= N) or + (j < 0 or j >= N ) or M[i][j] == 0): + return False + return True + '''Returns minimum numbers of moves from a +source (a cell with value 1) to a destination +(a cell with value 2)''' + +def MinimumPath(M): + global N + s , d = None, None + V = N * N + 2 + g = Graph(V) + ''' create graph with n*n node + each cell consider as node + Number of current vertex''' + k = 1 + for i in range(N): + for j in range(N): + if (M[i][j] != 0): + ''' connect all 4 adjacent cell to + current cell''' + + if (isSafe (i , j + 1 , M)): + g.addEdge (k , k + 1) + if (isSafe (i , j - 1 , M)): + g.addEdge (k , k - 1) + if (j < N - 1 and isSafe (i + 1 , j , M)): + g.addEdge (k , k + N) + if (i > 0 and isSafe (i - 1 , j , M)): + g.addEdge (k , k - N) + ''' source index''' + + if(M[i][j] == 1): + s = k + ''' destination index''' + + if (M[i][j] == 2): + d = k + k += 1 + ''' find minimum moves''' + + return g.BFS (s, d) + '''Driver Code''' + +N = 4 +M = [[3 , 3 , 1 , 0 ], [3 , 0 , 3 , 3 ], + [2 , 3 , 0 , 3 ], [0 , 3 , 3 , 3]] +print(MinimumPath(M))" +Root to leaf paths having equal lengths in a Binary Tree,"/*Java program to count root to leaf +paths of different lengths.*/ + +import java.util.HashMap; +import java.util.Map; +class GFG{ +/*A binary tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*Utility that allocates a new node +with the given data and null left +and right pointers.*/ + +static Node newnode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); +} +/*Function to store counts of different +root to leaf path lengths in hash map m.*/ + +static void pathCountUtil(Node node, + HashMap m, int path_len) +{ +/* Base condition*/ + + if (node == null) + return; +/* If leaf node reached, increment count + of path length of this root to leaf path.*/ + + if (node.left == null && node.right == null) + { + if (!m.containsKey(path_len)) + m.put(path_len, 0); + m.put(path_len, m.get(path_len) + 1); + return; + } +/* Recursively call for left and right + subtrees with path lengths more than 1.*/ + + pathCountUtil(node.left, m, path_len + 1); + pathCountUtil(node.right, m, path_len + 1); +} +/*A wrapper over pathCountUtil()*/ + +static void pathCounts(Node root) +{ +/* Create an empty hash table*/ + + HashMap m = new HashMap<>(); +/* Recursively check in left and right subtrees.*/ + + pathCountUtil(root, m, 1); +/* Print all path lenghts and their counts.*/ + + for(Map.Entry entry : m.entrySet()) + { + System.out.printf(""%d paths have length %d\n"", + entry.getValue(), + entry.getKey()); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newnode(8); + root.left = newnode(5); + root.right = newnode(4); + root.left.left = newnode(9); + root.left.right = newnode(7); + root.right.right = newnode(11); + root.right.right.left = newnode(3); + pathCounts(root); +} +}"," '''Python3 program to count root to leaf +paths of different lengths.''' + + + ''' utility that allocates a newNode +with the given key ''' + +class newnode: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Function to store counts of different +root to leaf path lengths in hash map m.''' + +def pathCountUtil(node, m,path_len) : + ''' Base condition''' + + if (node == None) : + return + ''' If leaf node reached, increment count of + path length of this root to leaf path.''' + + if (node.left == None and node.right == None): + if path_len[0] not in m: + m[path_len[0]] = 0 + m[path_len[0]] += 1 + return + ''' Recursively call for left and right + subtrees with path lengths more than 1.''' + + pathCountUtil(node.left, m, [path_len[0] + 1]) + pathCountUtil(node.right, m, [path_len[0] + 1]) + '''A wrapper over pathCountUtil()''' + +def pathCounts(root) : + ''' create an empty hash table''' + + m = {} + path_len = [1] + ''' Recursively check in left and right subtrees.''' + + pathCountUtil(root, m, path_len) + ''' Print all path lenghts and their counts.''' + + for itr in sorted(m, reverse = True): + print(m[itr], "" paths have length "", itr) + '''Driver Code''' + +if __name__ == '__main__': + root = newnode(8) + root.left = newnode(5) + root.right = newnode(4) + root.left.left = newnode(9) + root.left.right = newnode(7) + root.right.right = newnode(11) + root.right.right.left = newnode(3) + pathCounts(root)" +Determine whether a universal sink exists in a directed graph,"/*Java program to find whether a universal sink +exists in a directed graph*/ + +import java.io.*; +import java.util.*; +class Graph +{ + int vertices; + int[][] adjacency_matrix; +/* constructor to initialize number of vertices and + size of adjacency matrix*/ + + public graph(int vertices) + { + this.vertices = vertices; + adjacency_matrix = new int[vertices][vertices]; + } + public void insert(int source, int destination) + { +/* make adjacency_matrix[i][j] = 1 if there is + an edge from i to j*/ + + adjacency_matrix[destination-1] = 1; + } + public boolean issink(int i) + { + for (int j = 0 ; j < vertices ; j++) + { +/* if any element in the row i is 1, it means + that there is an edge emanating from the + vertex, which means it cannot be a sink*/ + + if (adjacency_matrix[i][j] == 1) + return false; +/* if any element other than i in the column + i is 0, it means that there is no edge from + that vertex to the vertex we are testing + and hence it cannot be a sink*/ + + if (adjacency_matrix[j][i] == 0 && j != i) + return false; + } +/* if none of the checks fails, return true*/ + + return true; + } +/* we will eliminate n-1 non sink vertices so that + we have to check for only one vertex instead of + all n vertices*/ + + public int eliminate() + { + int i = 0, j = 0; + while (i < vertices && j < vertices) + { +/* If the index is 1, increment the row we are + checking by 1 + else increment the column*/ + + if (adjacency_matrix[i][j] == 1) + i = i + 1; + else + j = j + 1; + } +/* If i exceeds the number of vertices, it + means that there is no valid vertex in + the given vertices that can be a sink*/ + + if (i > vertices) + return -1; + else if (!issink(i)) + return -1; + else return i; + } +} +public class Sink +{ /*Driver Code*/ +public static void main(String[] args)throws IOException + { + int number_of_vertices = 6; + int number_of_edges = 5; + graph g = new graph(number_of_vertices);/* input set 1 + g.insert(1, 6); + g.insert(2, 6); + g.insert(3, 6); + g.insert(4, 6); + g.insert(5, 6); + input set 2*/ + + g.insert(1, 6); + g.insert(2, 3); + g.insert(2, 4); + g.insert(4, 3); + g.insert(5, 3); + int vertex = g.eliminate(); +/* returns 0 based indexing of vertex. returns + -1 if no sink exits. + returns the vertex number-1 if sink is found*/ + + if (vertex >= 0) + System.out.println(""Sink found at vertex "" + + (vertex + 1)); + else + System.out.println(""No Sink""); + } +}"," '''Python3 program to find whether a +universal sink exists in a directed graph''' + +class Graph: + ''' constructor to initialize number of + vertices and size of adjacency matrix''' + + def __init__(self, vertices): + self.vertices = vertices + self.adjacency_matrix = [[0 for i in range(vertices)] + for j in range(vertices)] + def insert(self, s, destination): + ''' make adjacency_matrix[i][j] = 1 + if there is an edge from i to j''' + + self.adjacency_matrix[s - 1][destination - 1] = 1 + def issink(self, i): + for j in range(self.vertices): + ''' if any element in the row i is 1, it means + that there is an edge emanating from the + vertex, which means it cannot be a sink''' + + if self.adjacency_matrix[i][j] == 1: + return False + ''' if any element other than i in the column + i is 0, it means that there is no edge from + that vertex to the vertex we are testing + and hence it cannot be a sink''' + + if self.adjacency_matrix[j][i] == 0 and j != i: + return False + ''' if none of the checks fails, return true''' + + return True + ''' we will eliminate n-1 non sink vertices so that + we have to check for only one vertex instead of + all n vertices''' + + def eliminate(self): + i = 0 + j = 0 + while i < self.vertices and j < self.vertices: + ''' If the index is 1, increment the row + we are checking by 1 + else increment the column''' + + if self.adjacency_matrix[i][j] == 1: + i += 1 + else: + j += 1 + ''' If i exceeds the number of vertices, it + means that there is no valid vertex in + the given vertices that can be a sink''' + + if i > self.vertices: + return -1 + elif self.issink(i) is False: + return -1 + else: + return i + '''Driver Code''' + +if __name__ == ""__main__"": + number_of_vertices = 6 + number_of_edges = 5 + g = Graph(number_of_vertices) + ''' input set 1 + g.insert(1, 6) + g.insert(2, 6) + g.insert(3, 6) + g.insert(4, 6) + g.insert(5, 6) + input set 2''' + + g.insert(1, 6) + g.insert(2, 3) + g.insert(2, 4) + g.insert(4, 3) + g.insert(5, 3) + vertex = g.eliminate() + ''' returns 0 based indexing of vertex. + returns -1 if no sink exits. + returns the vertex number-1 if sink is found''' + + if vertex >= 0: + print(""Sink found at vertex %d"" % (vertex + 1)) + else: + print(""No Sink"")" +Find if given matrix is Toeplitz or not,"/*Java program to check whether given matrix +is a Toeplitz matrix or not*/ + +import java.io.*; +class GFG +{ + public static int N = 5; + public static int M = 4; +/* Function to check if all elements present in + descending diagonal starting from position + (i, j) in the matrix are all same or not*/ + + static boolean checkDiagonal(int mat[][], int i, int j) + { + int res = mat[i][j]; + while (++i < N && ++j < M) + { +/* mismatch found*/ + + if (mat[i][j] != res) + return false; + } +/* we only reach here when all elements + in given diagonal are same*/ + + return true; + } +/* Function to check whether given matrix is a + Toeplitz matrix or not*/ + + static boolean isToepliz(int mat[][]) + { +/* do for each element in first row*/ + + for (int i = 0; i < M; i++) + { +/* check descending diagonal starting from + position (0, j) in the matrix*/ + + if (!checkDiagonal(mat, 0, i)) + return false; + } +/* do for each element in first column*/ + + for (int i = 1; i < N; i++) + { +/* check descending diagonal starting from + position (i, 0) in the matrix*/ + + if (!checkDiagonal(mat, i, 0)) + return false; + } +/* we only reach here when each descending + diagonal from left to right is same*/ + + return true; + } +/* Driver code*/ + + public static void main(String[] args) + { + int mat[][] = { { 6, 7, 8, 9 }, + { 4, 6, 7, 8 }, + { 1, 4, 6, 7 }, + { 0, 1, 4, 6 }, + { 2, 0, 1, 4 } }; +/* Function call*/ + + if (isToepliz(mat)) + System.out.println(""Matrix is a Toepliz ""); + else + System.out.println(""Matrix is not a Toepliz ""); + } +}"," '''Python3 program to check whether given +matrix is a Toeplitz matrix or not''' + +N = 5 +M = 4 + '''Function to check if all elements present in +descending diagonal starting from position +(i, j) in the matrix are all same or not''' + +def checkDiagonal(mat, i, j): + res = mat[i][j] + i += 1 + j += 1 + while (i < N and j < M): + ''' mismatch found''' + + if (mat[i][j] != res): + return False + i += 1 + j += 1 + ''' we only reach here when all elements + in given diagonal are same''' + + return True + '''Function to check whether given +matrix is a Toeplitz matrix or not''' + +def isToeplitz(mat): + ''' do for each element in first row''' + + for j in range(M): + ''' check descending diagonal starting from + position (0, j) in the matrix''' + + if not(checkDiagonal(mat, 0, j)): + return False + ''' do for each element in first column''' + + for i in range(1, N): + ''' check descending diagonal starting + from position (i, 0) in the matrix''' + + if not(checkDiagonal(mat, i, 0)): + return False + + ''' we only reach here when each descending + diagonal from left to right is same''' + + return True '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[6, 7, 8, 9], + [4, 6, 7, 8], + [1, 4, 6, 7], + [0, 1, 4, 6], + [2, 0, 1, 4]] + ''' Function call''' + + if(isToeplitz(mat)): + print(""Matrix is a Toeplitz"") + else: + print(""Matrix is not a Toeplitz"")" +Check if all leaves are at same level,"/*Java program to check if all leaves are at same level*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class Leaf +{ + int leaflevel=0; +} +class BinaryTree +{ + Node root; + Leaf mylevel = new Leaf();/* Recursive function which checks whether all leaves are at same + level */ + + boolean checkUtil(Node node, int level, Leaf leafLevel) + { +/* Base case*/ + + if (node == null) + return true; +/* If a leaf node is encountered*/ + + if (node.left == null && node.right == null) + { +/* When a leaf node is found first time*/ + + if (leafLevel.leaflevel == 0) + { +/* Set first found leaf's level*/ + + leafLevel.leaflevel = level; + return true; + } +/* If this is not first leaf node, compare its level with + first leaf's level*/ + + return (level == leafLevel.leaflevel); + } +/* If this node is not leaf, recursively check left and right + subtrees*/ + + return checkUtil(node.left, level + 1, leafLevel) + && checkUtil(node.right, level + 1, leafLevel); + } + /* The main function to check if all leafs are at same level. + It mainly uses checkUtil() */ + + boolean check(Node node) + { + int level = 0; + return checkUtil(node, level, mylevel); + } + +/*Driver Code*/ + + public static void main(String args[]) + {/* Let us create the tree as shown in the example*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(12); + tree.root.left = new Node(5); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(9); + tree.root.left.left.left = new Node(1); + tree.root.left.right.left = new Node(1); + if (tree.check(tree.root)) + System.out.println(""Leaves are at same level""); + else + System.out.println(""Leaves are not at same level""); + } +}"," '''Python program to check if all leaves are at same level''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Recursive function which check whether all leaves are at +same level''' + +def checkUtil(root, level): + ''' Base Case''' + + if root is None: + return True + ''' If a tree node is encountered''' + + if root.left is None and root.right is None: + ''' When a leaf node is found first time''' + + if check.leafLevel == 0 : + '''Set first leaf found''' + + check.leafLevel = level + return True + ''' If this is not first leaf node, compare its level + with first leaf's level''' + + return level == check.leafLevel + ''' If this is not first leaf node, compare its level + with first leaf's level''' + + return (checkUtil(root.left, level+1)and + checkUtil(root.right, level+1)) + + ''' The main function to check if all leafs are at same level. + It mainly uses checkUtil() ''' + +def check(root): + level = 0 + check.leafLevel = 0 + return (checkUtil(root, level)) '''Driver program to test above function''' + + ''' Let us create the tree as shown in the example''' + +root = Node(12) +root.left = Node(5) +root.left.left = Node(3) +root.left.right = Node(9) +root.left.left.left = Node(1) +root.left.right.left = Node(2) +if(check(root)): + print ""Leaves are at same level"" +else: + print ""Leaves are not at same level""" +Tarjan's off-line lowest common ancestors algorithm,"/*A Java Program to implement Tarjan Offline LCA Algorithm*/ + +import java.util.Arrays; +class GFG +{ +/*number of nodes in input tree*/ + +static final int V = 5; +/*COLOUR 'WHITE' is assigned value 1*/ + +static final int WHITE = 1; +/*COLOUR 'BLACK' is assigned value 2*/ + +static final int BLACK = 2; + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; + +/* + subset[i].parent-.Holds the parent of node-'i' + subset[i].rank-.Holds the rank of node-'i' + subset[i].ancestor-.Holds the LCA queries answers + subset[i].child-.Holds one of the child of node-'i' + if present, else -'0' + subset[i].sibling-.Holds the right-sibling of node-'i' + if present, else -'0' + subset[i].color-.Holds the colour of node-'i' +*/ + +static class subset +{ + int parent; + int rank; + int ancestor; + int child; + int sibling; + int color; +}; + +/*Structure to represent a query +A query consists of (L,R) and we will process the +queries offline a/c to Tarjan's oflline LCA algorithm*/ + +static class Query +{ + int L, R; + Query(int L, int R) + { + this.L = L; + this.R = R; + } +}; + +/* Helper function that allocates a new node with the + given data and null left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return(node); +} + +/*A utility function to make set*/ + +static void makeSet(subset subsets[], int i) +{ + if (i < 1 || i > V) + return; + subsets[i].color = WHITE; + subsets[i].parent = i; + subsets[i].rank = 0; + return; +} + +/*A utility function to find set of an element i +(uses path compression technique)*/ + +static int findSet(subset subsets[], int i) +{ +/* find root and make root as parent of i (path compression)*/ + + if (subsets[i].parent != i) + subsets[i].parent = findSet (subsets, subsets[i].parent); + + return subsets[i].parent; +} + +/*A function that does union of two sets of x and y +(uses union by rank)*/ + +static void unionSet(subset subsets[], int x, int y) +{ + int xroot = findSet (subsets, x); + int yroot = findSet (subsets, y); + +/* Attach smaller rank tree under root of high rank tree + (Union by Rank)*/ + + if (subsets[xroot].rank < subsets[yroot].rank) + subsets[xroot].parent = yroot; + else if (subsets[xroot].rank > subsets[yroot].rank) + subsets[yroot].parent = xroot; + +/* If ranks are same, then make one as root and increment + its rank by one*/ + + else + { + subsets[yroot].parent = xroot; + (subsets[xroot].rank)++; + } +} + +/*The main function that prints LCAs. u is root's data. +m is size of q[]*/ + +static void lcaWalk(int u, Query q[], int m, + subset subsets[]) +{ + +/* Make Sets*/ + + makeSet(subsets, u); + +/* Initially, each node's ancestor is the node + itself.*/ + + subsets[findSet(subsets, u)].ancestor = u; + int child = subsets[u].child; + +/* This while loop doesn't run for more than 2 times + as there can be at max. two children of a node*/ + + while (child != 0) + { + lcaWalk(child, q, m, subsets); + unionSet (subsets, u, child); + subsets[findSet(subsets, u)].ancestor = u; + child = subsets[child].sibling; + } + + subsets[u].color = BLACK; + for (int i = 0; i < m; i++) + { + if (q[i].L == u) + { + if (subsets[q[i].R].color == BLACK) + { + System.out.printf(""LCA(%d %d)->%d\n"", + q[i].L, + q[i].R, + subsets[findSet(subsets,q[i].R)].ancestor); + } + } + else if (q[i].R == u) + { + if (subsets[q[i].L].color == BLACK) + { + System.out.printf(""LCA(%d %d)->%d\n"", + q[i].L, + q[i].R, + subsets[findSet(subsets,q[i].L)].ancestor); + } + } + } + return; +} + +/*This is basically an inorder traversal and +we preprocess the arrays. child[] +and sibling[] in ""subset"" with +the tree structure using this function.*/ + +static void preprocess(Node node, subset subsets[]) +{ + if (node == null) + return; + +/* Recur on left child*/ + + preprocess(node.left, subsets); + + if (node.left != null && node.right != null) + { + + /* Note that the below two lines can also be this- + subsets[node.data].child = node.right.data; + subsets[node.right.data].sibling = + node.left.data; + + This is because if both left and right children of + node-'i' are present then we can store any of them + in subsets[i].child and correspondingly its sibling*/ + + subsets[node.data].child = node.left.data; + subsets[node.left.data].sibling = + node.right.data; + + } + else if ((node.left != null && node.right == null) + || (node.left == null && node.right != null)) + { + if(node.left != null && node.right == null) + subsets[node.data].child = node.left.data; + else + subsets[node.data].child = node.right.data; + } + +/* Recur on right child*/ + + preprocess (node.right, subsets); +} + +/*A function to initialise prior to pre-processing and +LCA walk*/ + +static void initialise(subset subsets[]) +{ + +/* We colour all nodes WHITE before LCA Walk.*/ + + for (int i = 1; i < subsets.length; i++) + { + subsets[i] = new subset(); + subsets[i].color = WHITE; + } + return; +} + +/*Prints LCAs for given queries q[0..m-1] in a tree +with given root*/ + +static void printLCAs(Node root, Query q[], int m) +{ + +/* Allocate memory for V subsets and nodes*/ + + subset []subsets = new subset[V + 1]; + +/* Creates subsets and colors them WHITE*/ + + initialise(subsets); + +/* Preprocess the tree*/ + + preprocess(root, subsets); + +/* Perform a tree walk to process the LCA queries + offline*/ + + lcaWalk(root.data , q, m, subsets); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + /* + We cona binary tree :- + 1 + / \ + 2 3 + / \ + 4 5 */ + + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + +/* LCA Queries to answer*/ + + Query q[] = new Query[3]; + q[0] = new Query(5, 4); + q[1] = new Query(1, 3); + q[2] = new Query(2, 3); + int m = q.length; + printLCAs(root, q, m); +} +} + + +"," '''A Python3 program to implement Tarjan +Offline LCA Algorithm''' + + + '''Number of nodes in input tree''' + +V = 5 + + '''COLOUR 'WHITE' is assigned value 1''' + +WHITE = 1 + + '''COLOUR 'BLACK' is assigned value 2''' + +BLACK = 2 + + '''A binary tree node has data, pointer +to left child and a pointer to right child''' + +class Node: + + def __init__(self): + + self.data = 0 + self.left = None + self.right = None + + ''' + subset[i].parent-.Holds the parent of node-'i' + subset[i].rank-.Holds the rank of node-'i' + subset[i].ancestor-.Holds the LCA queries answers + subset[i].child-.Holds one of the child of node-'i' + if present, else -'0' + subset[i].sibling-.Holds the right-sibling of node-'i' + if present, else -'0' + subset[i].color-.Holds the colour of node-'i' + ''' + +class subset: + + def __init__(self): + + self.parent = 0 + self.rank = 0 + self.ancestor = 0 + self.child = 0 + self.sibling = 0 + self.color = 0 + + '''Structure to represent a query +A query consists of (L,R) and we +will process the queries offline +a/c to Tarjan's oflline LCA algorithm''' + +class Query: + + def __init__(self, L, R): + + self.L = L + self.R = R + + '''Helper function that allocates a new node +with the given data and None left and +right pointers.''' + +def newNode(data): + + node = Node() + node.data = data + node.left = node.right = None + return (node) + + '''A utility function to make set''' + +def makeSet(subsets, i): + + if (i < 1 or i > V): + return + + subsets[i].color = WHITE + subsets[i].parent = i + subsets[i].rank = 0 + + return + + '''A utility function to find set of an element i +(uses path compression technique)''' + +def findSet(subsets, i): + + ''' Find root and make root as parent + of i (path compression)''' + + if (subsets[i].parent != i): + subsets[i].parent = findSet(subsets, + subsets[i].parent) + + return subsets[i].parent + + '''A function that does union of two sets +of x and y (uses union by rank)''' + +def unionSet(subsets, x, y): + + xroot = findSet(subsets, x) + yroot = findSet(subsets, y) + + ''' Attach smaller rank tree under root of + high rank tree (Union by Rank)''' + + if (subsets[xroot].rank < subsets[yroot].rank): + subsets[xroot].parent = yroot + elif (subsets[xroot].rank > subsets[yroot].rank): + subsets[yroot].parent = xroot + + ''' If ranks are same, then make one as root + and increment its rank by one''' + + else: + subsets[yroot].parent = xroot + (subsets[xroot].rank) += 1 + + '''The main function that prints LCAs. u is +root's data. m is size of q[]''' + +def lcaWalk(u, q, m, subsets): + + ''' Make Sets''' + + makeSet(subsets, u) + + ''' Initially, each node's ancestor is the node + itself.''' + + subsets[findSet(subsets, u)].ancestor = u + + child = subsets[u].child + + ''' This while loop doesn't run for more than 2 times + as there can be at max. two children of a node''' + + while (child != 0): + lcaWalk(child, q, m, subsets) + unionSet(subsets, u, child) + subsets[findSet(subsets, u)].ancestor = u + child = subsets[child].sibling + + subsets[u].color = BLACK + + for i in range(m): + if (q[i].L == u): + if (subsets[q[i].R].color == BLACK): + + print(""LCA(%d %d) -> %d"" % (q[i].L, q[i].R, + subsets[findSet(subsets, q[i].R)].ancestor)) + + elif (q[i].R == u): + if (subsets[q[i].L].color == BLACK): + + print(""LCA(%d %d) -> %d"" % (q[i].L, q[i].R, + subsets[findSet(subsets, q[i].L)].ancestor)) + + return + + '''This is basically an inorder traversal and +we preprocess the arrays. child[] +and sibling[] in ""struct subset"" with +the tree structure using this function.''' + +def preprocess(node, subsets): + + if (node == None): + return + + ''' Recur on left child''' + + preprocess(node.left, subsets) + + if (node.left != None and node.right != None): + + ''' Note that the below two lines can also be this- + subsets[node.data].child = node.right.data; + subsets[node.right.data].sibling = + node.left.data; + + This is because if both left and right children of + node-'i' are present then we can store any of them + in subsets[i].child and correspondingly its sibling''' + + subsets[node.data].child = node.left.data + subsets[node.left.data].sibling = node.right.data + + elif ((node.left != None and node.right == None) + or (node.left == None and node.right != None)): + + if (node.left != None and node.right == None): + subsets[node.data].child = node.left.data + else: + subsets[node.data].child = node.right.data + + ''' Recur on right child''' + + preprocess(node.right, subsets) + + '''A function to initialise prior to pre-processing and +LCA walk''' + +def initialise(subsets): + + ''' Initialising the structure with 0's + memset(subsets, 0, (V+1) * sizeof(struct subset));''' + + for i in range(1, V + 1): + subsets[i].color = WHITE + + return + + '''Prints LCAs for given queries q[0..m-1] in a tree +with given root''' + +def printLCAs(root, q, m): + + ''' Allocate memory for V subsets and nodes''' + + subsets = [subset() for _ in range(V + 1)] + + ''' Creates subsets and colors them WHITE''' + + initialise(subsets) + + ''' Preprocess the tree''' + + preprocess(root, subsets) + + ''' Perform a tree walk to process the LCA queries + offline''' + + lcaWalk(root.data, q, m, subsets) + + '''Driver code''' + +if __name__ == ""__main__"": + + ''' + We construct a binary tree :- + 1 + / \ + 2 3 + / \ + 4 5 ''' + + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + + ''' LCA Queries to answer''' + + q = [Query(5, 4), Query(1, 3), Query(2, 3)] + m = len(q) + + printLCAs(root, q, m) + + +" +"No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x","/*Java program to calculate the number +pairs satisfying th condition*/ + +import java.util.*; + +class GFG +{ + +/*function to calculate the number of pairs*/ + +static int countPairs(int a[], int n, int x, int k) +{ + Arrays.sort(a); + +/* traverse through all elements*/ + + int ans = 0; + for (int i = 0; i < n; i++) + { + +/* current number's divisor*/ + + int d = (a[i] - 1) / x; + +/* use binary search to find the element + after k multiples of x*/ + + int it1 = Arrays.binarySearch(a, + Math.max((d + k) * x, a[i])); + +/* use binary search to find the element + after k+1 multiples of x so that we get + the answer bu subtracting*/ + + int it2 = Arrays.binarySearch(a, + Math.max((d + k + 1) * x, a[i])) ; + +/* the difference of index will be the answer*/ + + ans += it1 - it2; + } + return ans; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int []a = { 1, 3, 5, 7 }; + int n = a.length; + int x = 2, k = 1; + +/* function call to get the number of pairs*/ + + System.out.println(countPairs(a, n, x, k)); +} +} + + +"," '''Python3 program to calculate the number +pairs satisfying th condition''' + + +import bisect + + '''function to calculate the number of pairs''' + +def countPairs(a, n, x, k): + a.sort() + + ''' traverse through all elements''' + + ans = 0 + for i in range(n): + + ''' current number's divisor''' + + d = (a[i] - 1) // x + + ''' use binary search to find the element + after k multiples of x''' + + it1 = bisect.bisect_left(a, max((d + k) * x, a[i])) + + ''' use binary search to find the element + after k+1 multiples of x so that we get + the answer bu subtracting''' + + it2 = bisect.bisect_left(a, max((d + k + 1) * x, a[i])) + + ''' the difference of index will be the answer''' + + ans += it2 - it1 + + return ans + + '''Driver code''' + +if __name__ == ""__main__"": + a = [1, 3, 5, 7] + n = len(a) + x = 2 + k = 1 + + ''' function call to get the number of pairs''' + + print(countPairs(a, n, x, k)) + + +" +Convert a Binary Tree into its Mirror Tree,"/*Java program to convert binary tree into its mirror*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} + + /* Change a tree so that the roles of the left and + right pointers are swapped at every node. +So the tree... + 4 + / \ + 2 5 + / \ +1 3 +is changed to... + 4 + / \ + 5 2 + / \ + 3 1 +*/ + +class BinaryTree +{ + Node root; + void mirror() + { + root = mirror(root); + } + Node mirror(Node node) + { + if (node == null) + return node;/* do the subtrees */ + + Node left = mirror(node.left); + Node right = mirror(node.right); + /* swap the left and right pointers */ + + node.left = right; + node.right = left; + return node; + } + void inOrder() + { + inOrder(root); + } + /* Helper function to test mirror(). Given a binary + search tree, print out its data elements in + increasing sorted order.*/ + + void inOrder(Node node) + { + if (node == null) + return; + inOrder(node.left); + System.out.print(node.data + "" ""); + inOrder(node.right); + } + /* testing for example nodes */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); /* print inorder traversal of the input tree */ + + System.out.println(""Inorder traversal of input tree is :""); + tree.inOrder(); + System.out.println(""""); + /* convert tree to its mirror */ + + tree.mirror(); + /* print inorder traversal of the minor tree */ + + System.out.println(""Inorder traversal of binary tree is : ""); + tree.inOrder(); + } +}"," '''Python3 program to convert a binary +tree to its mirror''' + + '''Utility function to create a new +tree node ''' + +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None ''' Change a tree so that the roles of the + left and right pointers are swapped at + every node. +So the tree... + 4 + / \ + 2 5 + / \ + 1 3 +is changed to... + 4 + / \ + 5 2 + / \ + 3 1 + ''' + +def mirror(node): + if (node == None): + return + else: + temp = node + ''' do the subtrees ''' + + mirror(node.left) + mirror(node.right) + ''' swap the pointers in this node ''' + + temp = node.left + node.left = node.right + node.right = temp + ''' Helper function to print Inorder traversal.''' + +def inOrder(node) : + if (node == None): + return + inOrder(node.left) + print(node.data, end = "" "") + inOrder(node.right) + '''Driver code ''' + +if __name__ ==""__main__"": + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + ''' Print inorder traversal of + the input tree ''' + + print(""Inorder traversal of the"", + ""constructed tree is"") + inOrder(root) + ''' Convert tree to its mirror ''' + + mirror(root) + ''' Print inorder traversal of + the mirror tree ''' + + print(""\nInorder traversal of"", + ""the mirror treeis "") + inOrder(root)" +Probability of a random pair being the maximum weighted pair,"/*Java program to find Probability +of a random pair being the maximum +weighted pair*/ + +import java.io.*; + +class GFG { + +/* Function to return probability*/ + + static double probability(int a[], int b[], + int size1,int size2) + { +/* Count occurrences of maximum + element in A[]*/ + + int max1 = Integer.MIN_VALUE, count1 = 0; + for (int i = 0; i < size1; i++) { + if (a[i] > max1) { + max1 = a[i]; + count1 = 1; + } + else if (a[i] == max1) { + count1++; + } + } + +/* Count occurrences of maximum + element in B[]*/ + + int max2 = Integer.MIN_VALUE, count2 = 0; + for (int i = 0; i < size2; i++) { + if (b[i] > max2) { + max2 = b[i]; + count2 = 1; + } + else if (b[i] == max2) { + count2++; + } + } + +/* Returning probability*/ + + return (double)(count1 * count2) / (size1 * size2); + } + +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 1, 2, 3 }; + int b[] = { 1, 3, 3 }; + + int size1 = a.length; + int size2 = b.length; + + System.out.println(probability(a, b, + size1, size2)); + } +} + + +","import sys + + '''Function to return probability''' + +def probability(a, b, size1, size2): + + ''' Count occurrences of maximum + element in A[]''' + + max1 = -(sys.maxsize - 1) + count1 = 0 + for i in range(size1): + if a[i] > max1: + count1 = 1 + elif a[i] == max1: + count1 += 1 + + ''' Count occurrences of maximum + element in B[]''' + + max2 = -(sys.maxsize - 1) + count2 = 0 + for i in range(size2): + if b[i] > max2: + max2 = b[i] + count2 = 1 + elif b[i] == max2: + count2 += 1 + + ''' Returning probability''' + + return round((count1 * count2) / + (size1 * size2), 6) + + '''Driver code''' + +a = [1, 2, 3] +b = [1, 3, 3] +size1 = len(a) +size2 = len(b) +print(probability(a, b, size1, size2)) + + +" +Print sorted distinct elements of array,"/*Java program to print sorted distinct +elements.*/ + +import java.io.*; +import java.util.*; + +public class GFG { + + static void printRepeating(Integer []arr, int size) + { +/* Create a set using array elements*/ + + SortedSet s = new TreeSet<>(); + Collections.addAll(s, arr); + +/* Print contents of the set.*/ + + System.out.print(s); + } + +/* Driver code*/ + + public static void main(String args[]) + { + Integer []arr = {1, 3, 2, 2, 1}; + int n = arr.length; + printRepeating(arr, n); + } +} + + +"," '''Python3 program to print +sorted distinct elements.''' + + +def printRepeating(arr,size): + + ''' Create a set using array elements''' + + s = set() + for i in range(size): + if arr[i] not in s: + s.add(arr[i]) + + ''' Print contents of the set.''' + + for i in s: + print(i,end="" "") + + '''Driver code''' + +if __name__=='__main__': + arr = [1,3,2,2,1] + size = len(arr) + printRepeating(arr,size) + + +" +Count rotations in sorted and rotated linked list,"/*Program for count number of rotations in +sorted linked list.*/ + +import java.util.*; + +class GFG +{ + +/* Linked list node */ + +static class Node { + int data; + Node next; +}; + +/*Function that count number of +rotation in singly linked list.*/ + +static int countRotation(Node head) +{ + +/* declare count variable and assign it 1.*/ + + int count = 0; + +/* declare a min variable and assign to + data of head node.*/ + + int min = head.data; + +/* check that while head not equal to null.*/ + + while (head != null) { + +/* if min value is greater then head.data + then it breaks the while loop and + return the value of count.*/ + + if (min > head.data) + break; + + count++; + +/* head assign the next value of head.*/ + + head = head.next; + } + return count; +} + +/*Function to push element in linked list.*/ + +static Node push(Node head, int data) +{ +/* Allocate dynamic memory for newNode.*/ + + Node newNode = new Node(); + +/* Assign the data into newNode.*/ + + newNode.data = data; + +/* newNode.next assign the address of + head node.*/ + + newNode.next = (head); + +/* newNode become the headNode.*/ + + (head) = newNode; + return head; +} + +/*Display linked list.*/ + +static void printList(Node node) +{ + while (node != null) { + System.out.printf(""%d "", node.data); + node = node.next; + } +} + +/*Driver functions*/ + +public static void main(String[] args) +{ + +/* Create a node and initialize with null*/ + + Node head = null; + +/* push() insert node in linked list. + 15.18.5.8.11.12*/ + + head = push(head, 12); + head = push(head, 11); + head = push(head, 8); + head = push(head, 5); + head = push(head, 18); + head = push(head, 15); + + printList(head); + System.out.println(); + System.out.print(""Linked list rotated elements: ""); + +/* Function call countRotation()*/ + + System.out.print(countRotation(head) +""\n""); + +} +} + + +"," '''Program for count number of rotations in +sorted linked list.''' + + + '''Linked list node''' + +class Node: + + def __init__(self, data): + + self.data = data + self.next = None + + '''Function that count number of +rotation in singly linked list.''' + +def countRotation(head): + + ''' Declare count variable and assign it 1.''' + + count = 0 + + ''' Declare a min variable and assign to + data of head node.''' + + min = head.data + + ''' Check that while head not equal to None.''' + + while (head != None): + + ''' If min value is greater then head->data + then it breaks the while loop and + return the value of count.''' + + if (min > head.data): + break + + count += 1 + + ''' head assign the next value of head.''' + + head = head.next + + return count + + '''Function to push element in linked list.''' + +def push(head, data): + + ''' Allocate dynamic memory for newNode.''' + + newNode = Node(data) + + ''' Assign the data into newNode.''' + + newNode.data = data + + ''' newNode->next assign the address of + head node.''' + + newNode.next = (head) + + ''' newNode become the headNode.''' + + (head) = newNode + return head + + '''Display linked list.''' + +def printList(node): + + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Create a node and initialize with None''' + + head = None + + ''' push() insert node in linked list. + 15 -> 18 -> 5 -> 8 -> 11 -> 12''' + + head = push(head, 12) + head = push(head, 11) + head = push(head, 8) + head = push(head, 5) + head = push(head, 18) + head = push(head, 15) + + printList(head); + print() + print(""Linked list rotated elements: "", + end = '') + + ''' Function call countRotation()''' + + print(countRotation(head)) + + +" +Find first k natural numbers missing in given array,"/*Java code for +the above approach*/ + +import java.io.*; +import java.util.HashMap; + +class GFG +{ + +/* Program to print first k + missing number*/ + + static void printmissingk(int arr[], int n, int k) + { +/* Creating a hashmap*/ + + HashMap d = new HashMap<>(); + +/* Iterate over array*/ + + for (int i = 0; i < n; i++) + d.put(arr[i], arr[i]); + + int cnt = 1; + int fl = 0; + +/* Iterate to find missing + element*/ + + for (int i = 0; i < (n + k); i++) { + if (!d.containsKey(cnt)) { + fl += 1; + System.out.print(cnt + "" ""); + if (fl == k) + break; + } + cnt += 1; + } + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 4, 3 }; + int n = arr.length; + int k = 3; + printmissingk(arr, n, k); + } +} + + +"," '''Python3 code for above approach''' + + + '''Program to print first k +missing number''' + +def printmissingk(arr,n,k): + + ''' creating a hashmap''' + + d={} + + ''' Iterate over array''' + + for i in range(len(arr)): + d[arr[i]]=arr[i] + + cnt=1 + fl=0 + + ''' Iterate to find missing + element''' + + for i in range(n+k): + if cnt not in d: + fl+=1 + print(cnt,end="" "") + if fl==k: + break + cnt+=1 + print() + + '''Driver Code''' + +arr=[1,4,3] +n=len(arr) +k=3 +printmissingk(arr,n,k) + + +" +Doubly Linked List | Set 1 (Introduction and Insertion),"/*Add a node at the end of the list*/ + +void append(int new_data) +{ + /* 1. allocate node + * 2. put in the data */ + + Node new_node = new Node(new_data); + + Node last = head; /* 3. This new node is going to be the last node, so + * make next of it as NULL*/ + + new_node.next = null; + + /* 4. If the Linked List is empty, then make the new + * node as head */ + + if (head == null) { + new_node.prev = null; + head = new_node; + return; + } + + /* 5. Else traverse till the last node */ + + while (last.next != null) + last = last.next; + + /* 6. Change the next of last node */ + + last.next = new_node; + + /* 7. Make last node as previous of new node */ + + new_node.prev = last; +} +"," '''Add a node at the end of the DLL''' + +def append(self, new_data): + + ''' 1. allocate node 2. put in the data''' + + new_node = Node(data = new_data) + last = self.head + + ''' 3. This new node is going to be the + last node, so make next of it as NULL''' + + new_node.next = None + + ''' 4. If the Linked List is empty, then + make the new node as head''' + + if self.head is None: + new_node.prev = None + self.head = new_node + return + + ''' 5. Else traverse till the last node''' + + while (last.next is not None): + last = last.next + + ''' 6. Change the next of last node''' + + last.next = new_node + ''' 7. Make last node as previous of new node */''' + + new_node.prev = last + + +" +Construction of Longest Increasing Subsequence (N log N),"/*Java implementation to find longest +increasing subsequence in O(n Log n) +time.*/ + +import java.util.Arrays; + +class GFG { + +/* Binary search*/ + + static int GetCeilIndex(int arr[], + int T[], int l, + int r, int key) + { + + while (r - l > 1) { + + int m = l + (r - l) / 2; + if (arr[T[m]] >= key) + r = m; + else + l = m; + } + + return r; + } + + static int LongestIncreasingSubsequence( + int arr[], int n) + { + +/* Add boundary case, when array n is zero + Depend on smart pointers*/ + + + int tailIndices[] = new int[n]; + Arrays.fill(tailIndices, 0); + + int prevIndices[] = new int[n]; + +/* initialized with -1*/ + + Arrays.fill(prevIndices, -1); + +/* it will always point to empty + location*/ + + int len = 1; + + for (int i = 1; i < n; i++) { + if (arr[i] < arr[tailIndices[0]]) + +/* new smallest value*/ + + tailIndices[0] = i; + + else if (arr[i] > arr[tailIndices[len - 1]]) { + +/* arr[i] wants to extend + largest subsequence*/ + + prevIndices[i] = tailIndices[len - 1]; + tailIndices[len++] = i; + } + else { + +/* arr[i] wants to be a potential + condidate of future subsequence + It will replace ceil value in + tailIndices*/ + + int pos = GetCeilIndex(arr, + tailIndices, -1, len - 1, arr[i]); + + prevIndices[i] = tailIndices[pos - 1]; + tailIndices[pos] = i; + } + } + + System.out.println(""LIS of given input""); + + for (int i = tailIndices[len - 1]; i >= 0; + i = prevIndices[i]) + System.out.print(arr[i] + "" ""); + + System.out.println(); + + return len; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 }; + int n = arr.length; + + System.out.print(""LIS size\n"" + LongestIncreasingSubsequence(arr, n)); + } +} + + +"," '''Python implementation to +find longest increasing +subsequence +in O(n Log n) time.''' + + + '''Binary search''' + +def GetCeilIndex(arr, T, l, r, key): + + while (r - l > 1): + + m = l + (r - l)//2 + if (arr[T[m]] >= key): + r = m + else: + l = m + + return r + +def LongestIncreasingSubsequence(arr, n): + + ''' Add boundary case, + when array n is zero + Depend on smart pointers''' + + tailIndices =[0 for i in range(n + 1)] + + ''' Initialized with -1''' + + prevIndices =[-1 for i in range(n + 1)] + + ''' it will always point + to empty location''' + + len = 1 + for i in range(1, n): + + if (arr[i] < arr[tailIndices[0]]): + + ''' new smallest value''' + + tailIndices[0] = i + + elif (arr[i] > arr[tailIndices[len-1]]): + + ''' arr[i] wants to extend + largest subsequence''' + + prevIndices[i] = tailIndices[len-1] + tailIndices[len] = i + len += 1 + + else: + + ''' arr[i] wants to be a + potential condidate of + future subsequence + It will replace ceil + value in tailIndices''' + + pos = GetCeilIndex(arr, tailIndices, -1, + len-1, arr[i]) + + prevIndices[i] = tailIndices[pos-1] + tailIndices[pos] = i + + print(""LIS of given input"") + i = tailIndices[len-1] + while(i >= 0): + print(arr[i], "" "", end ="""") + i = prevIndices[i] + print() + + return len + + '''driver code''' + +arr = [ 2, 5, 3, 7, 11, 8, 10, 13, 6 ] +n = len(arr) + +print(""LIS size\n"", LongestIncreasingSubsequence(arr, n)) + + +" +Program for subtraction of matrices,"/*Java program for subtraction of matrices*/ + +class GFG +{ + static final int N=4; +/* This function subtracts B[][] + from A[][], and stores + the result in C[][]*/ + + static void subtract(int A[][], int B[][], int C[][]) + { + int i, j; + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + C[i][j] = A[i][j] - B[i][j]; + } +/* Driver code*/ + + public static void main (String[] args) + { + int A[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {4, 4, 4, 4}}; + int B[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {4, 4, 4, 4}}; + int C[][]=new int[N][N]; + int i, j; + subtract(A, B, C); + System.out.print(""Result matrix is \n""); + for (i = 0; i < N; i++) + { + for (j = 0; j < N; j++) + System.out.print(C[i][j] + "" ""); + System.out.print(""\n""); + } + } +}"," '''Python 3 program for subtraction +of matrices''' + +N = 4 + '''This function returns 1 +if A[][] and B[][] are identical +otherwise returns 0''' + +def subtract(A, B, C): + for i in range(N): + for j in range(N): + C[i][j] = A[i][j] - B[i][j] + '''Driver Code''' + +A = [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] +B = [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] + +C = A[:][:] +subtract(A, B, C) +print(""Result matrix is"") +for i in range(N): + for j in range(N): + print(C[i][j], "" "", end = '') + print()" +Minimum number of jumps to reach end,"/*Java program to find Minimum +number of jumps to reach end*/ + +import java.util.*; +import java.io.*; +class GFG { +/* Returns minimum number of + jumps to reach arr[h] from arr[l]*/ + + static int minJumps(int arr[], int l, int h) + { +/* Base case: when source + and destination are same*/ + + if (h == l) + return 0; +/* When nothing is reachable + from the given source*/ + + if (arr[l] == 0) + return Integer.MAX_VALUE; +/* Traverse through all the points + reachable from arr[l]. Recursively + get the minimum number of jumps + needed to reach arr[h] from these + reachable points.*/ + + int min = Integer.MAX_VALUE; + for (int i = l + 1; i <= h + && i <= l + arr[l]; + i++) { + int jumps = minJumps(arr, i, h); + if (jumps != Integer.MAX_VALUE && jumps + 1 < min) + min = jumps + 1; + } + return min; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 3, 6, 3, 2, 3, 6, 8, 9, 5 }; + int n = arr.length; + System.out.print(""Minimum number of jumps to reach end is "" + + minJumps(arr, 0, n - 1)); + } +}"," '''Python3 program to find Minimum +number of jumps to reach end''' + '''Returns minimum number of jumps +to reach arr[h] from arr[l]''' + +def minJumps(arr, l, h): + ''' Base case: when source and + destination are same''' + + if (h == l): + return 0 + ''' when nothing is reachable + from the given source''' + + if (arr[l] == 0): + return float('inf') + ''' Traverse through all the points + reachable from arr[l]. Recursively + get the minimum number of jumps + needed to reach arr[h] from + these reachable points.''' + + min = float('inf') + for i in range(l + 1, h + 1): + if (i < l + arr[l] + 1): + jumps = minJumps(arr, i, h) + if (jumps != float('inf') and + jumps + 1 < min): + min = jumps + 1 + return min + '''Driver program to test above function''' + +arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5] +n = len(arr) +print('Minimum number of jumps to reach', + 'end is', minJumps(arr, 0, n-1))" +Count all distinct pairs with difference equal to k,"import java.io.*; +class GFG { + static int BS(int[] arr, int X, int low) { + int high = arr.length - 1; + int ans = arr.length; + while(low <= high) { + int mid = low + (high - low) / 2; + if(arr[mid] >= X) { + ans = mid; + high = mid - 1; + } + else low = mid + 1; + } + return ans; + } static int countPairsWithDiffK(int[] arr, int N, int k) { + int count = 0; + Arrays.sort(arr); + for(int i = 0 ; i < N ; ++i) { + int X = BS(arr, arr[i] + k, i + 1); + if(X != N) { + int Y = BS(arr, arr[i] + k + 1, i + 1); + count += Y - X; + } + } + return count; + } public static void main (String[] args) { + int arr[] = {1, 3, 5, 8, 6, 4, 6}; + int n = arr.length; + int k = 2; + System.out.println(""Count of pairs with given diff is "" + + countPairsWithDiffK(arr, n, k)); + } +}", +"Given a binary tree, print out all of its root-to-leaf paths one per line.","/*Java program to print all root to leaf paths*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Given a binary tree, print out all of its root-to-leaf + paths, one per line. Uses a recursive helper to do the work.*/ + + void printPaths(Node node) + { + int path[] = new int[1000]; + printPathsRecur(node, path, 0); + } + /* Recursive helper function -- given a node, and an array containing + the path from the root node up to but not including this node, + print out all the root-leaf paths. */ + + void printPathsRecur(Node node, int path[], int pathLen) + { + if (node == null) + return; + /* append this node to the path array */ + + path[pathLen] = node.data; + pathLen++; + /* it's a leaf, so print the path that led to here */ + + if (node.left == null && node.right == null) + printArray(path, pathLen); + else + { + /* otherwise try both subtrees */ + + printPathsRecur(node.left, path, pathLen); + printPathsRecur(node.right, path, pathLen); + } + } + /* Utility that prints out an array on a line */ + + void printArray(int ints[], int len) + { + int i; + for (i = 0; i < len; i++) + System.out.print(ints[i] + "" ""); + System.out.println(""""); + } + /* Driver program to test all above functions */ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + /* Print all root-to-leaf paths of the input tree */ + + tree.printPaths(tree.root); + } +}", +Replace two consecutive equal values with one greater,"/*java program to replace two elements +with equal values with one greater.*/ + +public class GFG { + +/* Function to replace consecutive equal + elements*/ + + static void replace_elements(int arr[], int n) + { +/*Index in result*/ + +int pos = 0; + + for (int i = 0; i < n; i++) { + arr[pos++] = arr[i]; + + while (pos > 1 && arr[pos - 2] == + arr[pos - 1]) + { + pos--; + arr[pos - 1]++; + } + } + +/* to print new array*/ + + for (int i = 0; i < pos; i++) + System.out.print( arr[i] + "" ""); + } + +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 6, 4, 3, 4, 3, 3, 5 }; + int n = arr.length; + replace_elements(arr, n); + } +} + + +"," '''python program to replace two elements +with equal values with one greater.''' + +from __future__ import print_function + + '''Function to replace consecutive equal +elements''' + +def replace_elements(arr, n): + + '''Index in result''' + + pos = 0 + for i in range(0, n): + arr[pos] = arr[i] + pos = pos + 1 + while (pos > 1 and arr[pos - 2] + == arr[pos - 1]): + pos -= 1 + arr[pos - 1] += 1 + + ''' to print new array''' + + for i in range(0, pos): + print(arr[i], end="" "") + + '''Driver Code''' + +arr = [ 6, 4, 3, 4, 3, 3, 5 ] +n = len(arr) +replace_elements(arr, n) + + +" +Tree Isomorphism Problem,"/*An iterative java program to solve tree isomorphism problem*/ + +/* A binary tree node has data, pointer to left and right children */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right; + } +} +class BinaryTree +{ + Node root1, root2; + /* Given a binary tree, print its nodes in reverse level order */ + + boolean isIsomorphic(Node n1, Node n2) + { +/* Both roots are NULL, trees isomorphic by definition*/ + + if (n1 == null && n2 == null) + return true; +/* Exactly one of the n1 and n2 is NULL, trees not isomorphic*/ + + if (n1 == null || n2 == null) + return false; + if (n1.data != n2.data) + return false; +/* There are two possible cases for n1 and n2 to be isomorphic + Case 1: The subtrees rooted at these nodes have NOT been + ""Flipped"". + Both of these subtrees have to be isomorphic. + Case 2: The subtrees rooted at these nodes have been ""Flipped""*/ + + return (isIsomorphic(n1.left, n2.left) && + isIsomorphic(n1.right, n2.right)) + || (isIsomorphic(n1.left, n2.right) && + isIsomorphic(n1.right, n2.left)); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); +/* Let us create trees shown in above diagram*/ + + tree.root1 = new Node(1); + tree.root1.left = new Node(2); + tree.root1.right = new Node(3); + tree.root1.left.left = new Node(4); + tree.root1.left.right = new Node(5); + tree.root1.right.left = new Node(6); + tree.root1.left.right.left = new Node(7); + tree.root1.left.right.right = new Node(8); + tree.root2 = new Node(1); + tree.root2.left = new Node(3); + tree.root2.right = new Node(2); + tree.root2.right.left = new Node(4); + tree.root2.right.right = new Node(5); + tree.root2.left.right = new Node(6); + tree.root2.right.right.left = new Node(8); + tree.root2.right.right.right = new Node(7); + if (tree.isIsomorphic(tree.root1, tree.root2) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python program to check if two given trees are isomorphic''' + + '''A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Check if the binary tree is isomorphic or not''' + +def isIsomorphic(n1, n2): + ''' Both roots are None, trees isomorphic by definition''' + + if n1 is None and n2 is None: + return True + ''' Exactly one of the n1 and n2 is None, trees are not + isomorphic''' + + if n1 is None or n2 is None: + return False + if n1.data != n2.data : + return False + ''' There are two possible cases for n1 and n2 to be isomorphic + Case 1: The subtrees rooted at these nodes have NOT + been ""Flipped"". + Both of these subtrees have to be isomorphic, hence the && + Case 2: The subtrees rooted at these nodes have + been ""Flipped""''' + + return ((isIsomorphic(n1.left, n2.left)and + isIsomorphic(n1.right, n2.right)) or + (isIsomorphic(n1.left, n2.right) and + isIsomorphic(n1.right, n2.left)) + ) + '''Driver program to test above function''' + + '''Let us create trees shown in above diagram''' + +n1 = Node(1) +n1.left = Node(2) +n1.right = Node(3) +n1.left.left = Node(4) +n1.left.right = Node(5) +n1.right.left = Node(6) +n1.left.right.left = Node(7) +n1.left.right.right = Node(8) +n2 = Node(1) +n2.left = Node(3) +n2.right = Node(2) +n2.right.left = Node(4) +n2.right.right = Node(5) +n2.left.right = Node(6) +n2.right.right.left = Node(8) +n2.right.right.right = Node(7) +print ""Yes"" if (isIsomorphic(n1, n2) == True) else ""No""" +Convert left-right representation of a binary tree to down-right,"/* Java program to convert left-right to +down-right representation of binary tree */ + +class GFG +{ +/*A Binary Tree Node */ + +static class node +{ + int key; + node left, right; + node(int key) + { + this.key = key; + this.left = null; + this.right = null; + } +} +/*An Iterative level order traversal +based function to convert left-right +to down-right representation. */ + +static void convert(node root) +{ +/* Base Case */ + + if (root == null) return; +/* Recursively convert left + an right subtrees */ + + convert(root.left); + convert(root.right); +/* If left child is NULL, make right + child as left as it is the first child. */ + + if (root.left == null) + root.left = root.right; +/* If left child is NOT NULL, then make + right child as right of left child */ + + else + root.left.right = root.right; +/* Set root's right as NULL */ + + root.right = null; +} +/*A utility function to traverse a +tree stored in down-right form. */ + +static void downRightTraversal(node root) +{ + if (root != null) + { + System.out.print(root.key + "" ""); + downRightTraversal(root.right); + downRightTraversal(root.left); + } +} +/*Utility function to create +a new tree node */ + +static node newNode(int key) +{ + node temp = new node(0); + temp.key = key; + temp.left = null; + temp.right = null; + return temp; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree + shown in above diagram */ + + /* + 1 + / \ + 2 3 + / \ + 4 5 + / / \ + 6 7 8 + */ + + node root = new node(1); + root.left = newNode(2); + root.right = newNode(3); + root.right.left = newNode(4); + root.right.right = newNode(5); + root.right.left.left = newNode(6); + root.right.right.left = newNode(7); + root.right.right.right = newNode(8); + convert(root); + System.out.println(""Traversal of the tree "" + + ""converted to down-right form""); + downRightTraversal(root); +} +}"," '''Python3 program to convert left-right to +down-right representation of binary tree +Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newNode: + ''' Construct to create a new node ''' + + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''An Iterative level order traversal based +function to convert left-right to down-right +representation.''' + +def convert(root): + ''' Base Case''' + + if (root == None): + return + ''' Recursively convert left an + right subtrees''' + + convert(root.left) + convert(root.right) + ''' If left child is None, make right + child as left as it is the first child.''' + + if (root.left == None): + root.left = root.right + ''' If left child is NOT None, then make + right child as right of left child''' + + else: + root.left.right = root.right + ''' Set root's right as None''' + + root.right = None + '''A utility function to traverse a +tree stored in down-right form.''' + +def downRightTraversal(root): + if (root != None): + print( root.key, end = "" "") + downRightTraversal(root.right) + downRightTraversal(root.left) + '''Driver Code ''' + +if __name__ == '__main__': + ''' Let us create binary tree shown + in above diagram''' + + ''' + 1 + / \ + 2 3 + / \ + 4 5 + / / \ + 6 7 8 + ''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.right.left = newNode(4) + root.right.right = newNode(5) + root.right.left.left = newNode(6) + root.right.right.left = newNode(7) + root.right.right.right = newNode(8) + convert(root) + print(""Traversal of the tree converted"", + ""to down-right form"") + downRightTraversal(root)" +Find depth of the deepest odd level leaf node,"/*Java program to find depth of the deepest +odd level leaf node of binary tree*/ + +import java.util.*; +class GFG +{ +/*tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*returns a new tree Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*return max odd number depth of leaf node*/ + +static int maxOddLevelDepth(Node root) +{ + if (root == null) + return 0; +/* create a queue for level order + traversal*/ + + Queue q = new LinkedList<>(); + q.add(root); + int result = Integer.MAX_VALUE; + int level = 0; +/* traverse until the queue is empty*/ + + while (!q.isEmpty()) + { + int size = q.size(); + level += 1; +/* traverse for complete level*/ + + while(size > 0) + { + Node temp = q.peek(); + q.remove(); +/* check if the node is leaf node and + level is odd if level is odd, + then update result*/ + + if(temp.left == null && + temp.right == null && (level % 2 != 0)) + { + result = level; + } +/* check for left child*/ + + if (temp.left != null) + { + q.add(temp.left); + } +/* check for right child*/ + + if (temp.right != null) + { + q.add(temp.right); + } + size -= 1; + } + } + return result; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* construct a tree*/ + + 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(6); + root.right.left.right = newNode(7); + root.right.right.right = newNode(8); + root.right.left.right.left = newNode(9); + root.right.right.right.right = newNode(10); + root.right.right.right.right.left = newNode(11); + int result = maxOddLevelDepth(root); + if (result == Integer.MAX_VALUE) + System.out.println(""No leaf node at odd level""); + else + { + System.out.print(result); + System.out.println("" is the required depth ""); + } +} +}"," '''Python3 program to find depth of the deepest +odd level leaf node of binary tree''' + +INT_MAX = 2**31 + '''tree node returns a new tree Node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''return max odd number depth +of leaf node ''' + +def maxOddLevelDepth(root) : + if (not root): + return 0 + ''' create a queue for level order + traversal ''' + + q = [] + q.append(root) + result = INT_MAX + level = 0 + ''' traverse until the queue is empty ''' + + while (len(q)) : + size = len(q) + level += 1 + ''' traverse for complete level ''' + + while(size > 0) : + temp = q[0] + q.pop(0) + ''' check if the node is leaf node + and level is odd if level is + odd, then update result ''' + + if(not temp.left and not temp.right + and (level % 2 != 0)) : + result = level + ''' check for left child ''' + + if (temp.left) : + q.append(temp.left) + ''' check for right child ''' + + if (temp.right) : + q.append(temp.right) + size -= 1 + return result + '''Driver Code ''' + +if __name__ == '__main__': + '''construct a tree''' + + 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(6) + root.right.left.right = newNode(7) + root.right.right.right = newNode(8) + root.right.left.right.left = newNode(9) + root.right.right.right.right = newNode(10) + root.right.right.right.right.left = newNode(11) + result = maxOddLevelDepth(root) + if (result == INT_MAX) : + print(""No leaf node at odd level"") + else: + print(result, end = """") + print("" is the required depth "")" +Maximum sum of increasing order elements from n arrays,"/*Java program to find +maximum sum by selecting +a element from n arrays*/ + +import java.io.*; + +class GFG +{ + static int M = 4; + static int arr[][] = {{1, 7, 3, 4}, + {4, 2, 5, 1}, + {9, 5, 1, 8}}; + + static void sort(int a[][], + int row, int n) + { + for (int i = 0; i < M - 1; i++) + { + if(a[row][i] > a[row][i + 1]) + { + int temp = a[row][i]; + a[row][i] = a[row][i + 1]; + a[row][i + 1] = temp; + } + } + } + +/* To calculate maximum + sum by selecting element + from each array*/ + + static int maximumSum(int a[][], + int n) + { + +/* Sort each array*/ + + for (int i = 0; i < n; i++) + sort(a, i, n); + +/* Store maximum element + of last array*/ + + int sum = a[n - 1][M - 1]; + int prev = a[n - 1][M - 1]; + int i, j; + +/* Selecting maximum element + from previoulsy selected + element*/ + + for (i = n - 2; i >= 0; i--) + { + for (j = M - 1; j >= 0; j--) + { + if (a[i][j] < prev) + { + prev = a[i][j]; + sum += prev; + break; + } + } + +/* j = -1 means no element + is found in a[i] so + return 0*/ + + if (j == -1) + return 0; + } + return sum; + } + +/* Driver Code*/ + + public static void main(String args[]) + { + int n = arr.length; + System.out.print(maximumSum(arr, n)); + } +} + + +"," '''Python3 program to find +maximum sum by selecting +a element from n arrays''' + +M = 4; + + '''To calculate maximum sum +by selecting element from +each array''' + +def maximumSum(a, n) : + + global M; + + ''' Sort each array''' + + for i in range(0, n) : + a[i].sort(); + + ''' Store maximum element + of last array''' + + sum = a[n - 1][M - 1]; + prev = a[n - 1][M - 1]; + + ''' Selecting maximum + element from previoulsy + selected element''' + + for i in range(n - 2, + -1, -1) : + + for j in range(M - 1, + -1, -1) : + + if (a[i][j] < prev) : + + prev = a[i][j]; + sum += prev; + break; + + ''' j = -1 means no element + is found in a[i] so + return 0''' + + if (j == -1) : + return 0; + return sum; + + '''Driver Code''' + +arr = [[1, 7, 3, 4], + [4, 2, 5, 1], + [9, 5, 1, 8]]; +n = len(arr) ; +print (maximumSum(arr, n)); + + +" +Pairs of Amicable Numbers,"/*Efficient Java program to count +Amicable pairs in an array.*/ + +import java.util.*; +class GFG +{ +/*Calculate the sum +of proper divisors*/ + +static int sumOfDiv(int x) +{ +/* 1 is a proper divisor*/ + + int sum = 1; + for (int i = 2; i <= Math.sqrt(x); i++) + { + if (x % i == 0) + { + sum += i; +/* To handle perfect squares*/ + + if (x / i != i) + sum += x / i; + } + } + return sum; +} +/*Check if pair is amicable*/ + +static boolean isAmicable(int a, int b) +{ + return (sumOfDiv(a) == b && + sumOfDiv(b) == a); +} +/*This function prints count +of amicable pairs present +in the input array*/ + +static int countPairs(int arr[], int n) +{ +/* Map to store the numbers*/ + + HashSet s = new HashSet(); + int count = 0; + for (int i = 0; i < n; i++) + s.add(arr[i]); +/* Iterate through each number, + and find the sum of proper + divisors and check if it's + also present in the array*/ + + for (int i = 0; i < n; i++) + { + if (s.contains(sumOfDiv(arr[i]))) + { +/* It's sum of proper divisors*/ + + int sum = sumOfDiv(arr[i]); + if (isAmicable(arr[i], sum)) + count++; + } + } +/* As the pairs are counted + twice, thus divide by 2*/ + + return count / 2; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr1[] = { 220, 284, 1184, + 1210, 2, 5 }; + int n1 = arr1.length; + System.out.println(countPairs(arr1, n1)); + int arr2[] = { 2620, 2924, 5020, + 5564, 6232, 6368 }; + int n2 = arr2.length; + System.out.println(countPairs(arr2, n2)); +} +}"," '''Efficient Python3 program to count +Amicable pairs in an array.''' + +import math + '''Calculating the sum +of proper divisors''' + +def sumOfDiv(x): + ''' 1 is a proper divisor''' + + sum = 1; + for i in range(2,int(math.sqrt(x))): + if x % i==0: + sum += i + ''' To handle perfect squares''' + + if i != x/i: + sum += x/i + return int(sum); + '''check if pair is ambicle''' + +def isAmbicle(a, b): + return (sumOfDiv(a) == b and + sumOfDiv(b) == a) + '''This function prints count +of amicable pairs present +in the input array''' + +def countPairs(arr,n): + ''' Map to store the numbers''' + + s = set() + count = 0 + for i in range(n): + s.add(arr[i]) + ''' Iterate through each number, + and find the sum of proper + divisors and check if it's + also present in the array''' + + for i in range(n): + if sumOfDiv(arr[i]) in s: + ''' It's sum of proper divisors''' + + sum = sumOfDiv(arr[i]) + if isAmbicle(arr[i], sum): + count += 1 + ''' As the pairs are counted + twice, thus divide by 2''' + + return int(count/2); + '''Driver Code''' + +arr1 = [220, 284, 1184, + 1210, 2, 5] +n1 = len(arr1) +print(countPairs(arr1, n1)) +arr2 = [2620, 2924, 5020, + 5564, 6232, 6368] +n2 = len(arr2) +print(countPairs(arr2, n2))" +Search an element in an array where difference between adjacent elements is 1,"/*Java program to search an element in an +array where difference between all +elements is 1*/ + + +import java.io.*; + +class GFG { + +/* x is the element to be searched + in arr[0..n-1]*/ + + static int search(int arr[], int n, int x) + { + +/* Traverse the given array starting + from leftmost element*/ + + int i = 0; + while (i < n) + { + +/* If x is found at index i*/ + + if (arr[i] == x) + return i; + +/* Jump the difference between current + array element and x*/ + + i = i + Math.abs(arr[i]-x); + } + + System.out.println (""number is not"" + + "" present!""); + + return -1; + } + +/* Driver program to test above function*/ + + public static void main (String[] args) { + + int arr[] = {8 ,7, 6, 7, 6, 5, 4, 3, + 2, 3, 4, 3 }; + int n = arr.length; + int x = 3; + System.out.println(""Element "" + x + + "" is present at index "" + + search(arr,n,3)); + } +} + + +"," '''Python 3 program to search an element +in an array where difference between +all elements is 1''' + + + '''x is the element to be searched in +arr[0..n-1]''' + +def search(arr, n, x): + + ''' Traverse the given array starting + from leftmost element''' + + i = 0 + while (i < n): + + ''' If x is found at index i''' + + if (arr[i] == x): + return i + + ''' Jump the difference between + current array element and x''' + + i = i + abs(arr[i] - x) + + print(""number is not present!"") + return -1 + + '''Driver program to test above function''' + +arr = [8 ,7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3 ] +n = len(arr) +x = 3 +print(""Element"" , x , "" is present at index "", + search(arr,n,3)) + + +" +Reverse Level Order Traversal,"/*A recursive java program to print reverse level order traversal +using stack and queue*/ + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Stack; +/* A binary tree node has data, pointer to left and right children */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right; + } +} +class BinaryTree +{ + Node root; + /* Given a binary tree, print its nodes in reverse level order */ + + void reverseLevelOrder(Node node) + { + Stack S = new Stack(); + Queue Q = new LinkedList(); + Q.add(node); +/* Do something like normal level order traversal order.Following + are the differences with normal level order traversal + 1) Instead of printing a node, we push the node to stack + 2) Right subtree is visited before left subtree*/ + + while (Q.isEmpty() == false) + { + /* Dequeue node and make it root */ + + node = Q.peek(); + Q.remove(); + S.push(node); + /* Enqueue right child */ + + if (node.right != null) +/* NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT*/ + + Q.add(node.right); + /* Enqueue left child */ + + if (node.left != null) + Q.add(node.left); + } +/* Now pop all items from stack one by one and print them*/ + + while (S.empty() == false) + { + node = S.peek(); + System.out.print(node.data + "" ""); + S.pop(); + } + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); +/* Let us create trees shown in above diagram*/ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + System.out.println(""Level Order traversal of binary tree is :""); + tree.reverseLevelOrder(tree.root); + } +}", +Sort the matrix row-wise and column-wise,"/*Java implementation to sort the +matrix row-wise and column-wise*/ + +import java.util.Arrays; +class GFG +{ + static final int MAX_SIZE=10; +/* function to sort each row of the matrix*/ + + static void sortByRow(int mat[][], int n) + { + for (int i = 0; i < n; i++) +/* sorting row number 'i'*/ + + Arrays.sort(mat[i]); + } +/* function to find transpose of the matrix*/ + + static void transpose(int mat[][], int n) + { + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + { +/* swapping element at index (i, j) + by element at index (j, i)*/ + + int temp=mat[i][j]; + mat[i][j]=mat[j][i]; + mat[j][i]=temp; + } + } +/* function to sort the matrix row-wise + and column-wise*/ + + static void sortMatRowAndColWise(int mat[][],int n) + { +/* sort rows of mat[][]*/ + + sortByRow(mat, n); +/* get transpose of mat[][]*/ + + transpose(mat, n); +/* again sort rows of mat[][]*/ + + sortByRow(mat, n); +/* again get transpose of mat[][]*/ + + transpose(mat, n); + } +/* function to print the matrix*/ + + static void printMat(int mat[][], int n) + { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + System.out.print(mat[i][j] + "" ""); + System.out.println(); + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int mat[][] = { { 4, 1, 3 }, + { 9, 6, 8 }, + { 5, 2, 7 } }; + int n = 3; + System.out.print(""Original Matrix:\n""); + printMat(mat, n); + sortMatRowAndColWise(mat, n); + System.out.print(""\nMatrix After Sorting:\n""); + printMat(mat, n); + } +}"," '''Python 3 implementation to +sort the matrix row-wise +and column-wise''' + +MAX_SIZE = 10 + '''function to sort each +row of the matrix''' + +def sortByRow(mat, n): + for i in range (n): + ''' sorting row number 'i''' + ''' + for j in range(n-1): + if mat[i][j] > mat[i][j + 1]: + temp = mat[i][j] + mat[i][j] = mat[i][j + 1] + mat[i][j + 1] = temp + '''function to find +transpose of the matrix''' + +def transpose(mat, n): + for i in range (n): + for j in range(i + 1, n): + ''' swapping element at + index (i, j) by element + at index (j, i)''' + + t = mat[i][j] + mat[i][j] = mat[j][i] + mat[j][i] = t + '''function to sort +the matrix row-wise +and column-wise''' + +def sortMatRowAndColWise(mat, n): + ''' sort rows of mat[][]''' + + sortByRow(mat, n) + ''' get transpose of mat[][]''' + + transpose(mat, n) + ''' again sort rows of mat[][]''' + + sortByRow(mat, n) + ''' again get transpose of mat[][]''' + + transpose(mat, n) + '''function to print the matrix''' + +def printMat(mat, n): + for i in range(n): + for j in range(n): + print(str(mat[i][j] ), end = "" "") + print(); + '''Driver Code''' + +mat = [[ 4, 1, 3 ], + [ 9, 6, 8 ], + [ 5, 2, 7 ]] +n = 3 +print(""Original Matrix:"") +printMat(mat, n) +sortMatRowAndColWise(mat, n) +print(""\nMatrix After Sorting:"") +printMat(mat, n)" +Find all elements in array which have at-least two greater elements,"/*Sorting based Java program to find +all elements in array which have +atleast two greater elements itself.*/ + +import java.util.*; +import java.io.*; +class GFG +{ +static void findElements(int arr[], int n) +{ + Arrays.sort(arr); + for (int i = 0; i < n - 2; i++) + System.out.print(arr[i] + "" ""); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = { 2, -6 ,3 , 5, 1}; + int n = arr.length; + findElements(arr, n); +} +}"," '''Sorting based Python 3 program +to find all elements in array +which have atleast two greater +elements itself.''' + +def findElements(arr, n): + arr.sort() + for i in range(0, n-2): + print(arr[i], end ="" "") + '''Driven source''' + +arr = [2, -6, 3, 5, 1] +n = len(arr) +findElements(arr, n)" +Linked List | Set 2 (Inserting a node),"/* This function is in LinkedList class. +Inserts a new node after the given prev_node. This method is +defined inside LinkedList class shown above */ + +public void insertAfter(Node prev_node, int new_data) +{ + /* 1. Check if the given Node is null */ + + if (prev_node == null) + { + System.out.println(""The given previous node cannot be null""); + return; + } + /* 2. Allocate the Node & + 3. Put in the data*/ + + Node new_node = new Node(new_data); + /* 4. Make next of new Node as next of prev_node */ + + new_node.next = prev_node.next; + /* 5. make next of prev_node as new_node */ + + prev_node.next = new_node; +}"," '''This function is in LinkedList class. +Inserts a new node after the given prev_node. This method is +defined inside LinkedList class shown above */''' + +def insertAfter(self, prev_node, new_data): + ''' 1. check if the given prev_node exists''' + + if prev_node is None: + print ""The given previous node must inLinkedList."" + return + ''' 2. Create new node & + 3. Put in the data''' + + new_node = Node(new_data) + ''' 4. Make next of new Node as next of prev_node''' + + new_node.next = prev_node.next + ''' 5. make next of prev_node as new_node''' + + prev_node.next = new_node" +Create loops of even and odd values in a binary tree,"/*Java implementation to create odd and even loops +in a binary tree*/ + +import java.util.*; +class GFG +{ +/*structure of a node*/ + +static class Node +{ + int data; + Node left, right, abtr; +}; +/*Utility function to create a new node*/ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = node.abtr = null; + return node; +} +static Vector even_ptrs = new Vector<>(); +static Vector odd_ptrs = new Vector<>(); +/*preorder traversal to place the node pointer +in the respective even_ptrs or odd_ptrs list*/ + +static void preorderTraversal(Node root) +{ + if (root == null) + return; +/* place node ptr in even_ptrs list if + node contains even number */ + + if (root.data % 2 == 0) + (even_ptrs).add(root); +/* else place node ptr in odd_ptrs list*/ + + else + (odd_ptrs).add(root); + preorderTraversal(root.left); + preorderTraversal(root.right); +} +/*function to create the even and odd loops*/ + +static void createLoops(Node root) +{ + preorderTraversal(root); + int i; +/* forming even loop*/ + + for (i = 1; i < even_ptrs.size(); i++) + even_ptrs.get(i - 1).abtr = even_ptrs.get(i); +/* for the last element*/ + + even_ptrs.get(i - 1).abtr = even_ptrs.get(0); +/* Similarly forming odd loop*/ + + for (i = 1; i < odd_ptrs.size(); i++) + odd_ptrs.get(i - 1).abtr = odd_ptrs.get(i); + odd_ptrs.get(i - 1).abtr = odd_ptrs.get(0); +} +/*traversing the loop from any random +node in the loop*/ + +static void traverseLoop(Node start) +{ + Node curr = start; + do + { + System.out.print(curr.data + "" ""); + curr = curr.abtr; + } while (curr != start); +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Binary tree formation*/ + + 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); + createLoops(root); /* traversing odd loop from any + random odd node*/ + + System.out.print(""Odd nodes: ""); + traverseLoop(root.right); + System.out.print( ""\nEven nodes: ""); +/* traversing even loop from any + random even node*/ + + traverseLoop(root.left); +} +}"," '''Python3 implementation to create odd and even loops +in a binary tree''' + + '''Utility function to create a new node''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + self.abtr = None +even_ptrs = [] +odd_ptrs = [] '''preorder traversal to place the node pointer +in the respective even_ptrs or odd_ptrs list''' + +def preorderTraversal(root): + global even_ptrs, odd_ptrs + if (not root): + return + ''' place node ptr in even_ptrs list if + node contains even number''' + + if (root.data % 2 == 0): + even_ptrs.append(root) + ''' else place node ptr in odd_ptrs list''' + + else: + odd_ptrs.append(root) + preorderTraversal(root.left) + preorderTraversal(root.right) + '''function to create the even and odd loops''' + +def createLoops(root): + preorderTraversal(root) + ''' forming even loop''' + + i = 1 + while i < len(even_ptrs): + even_ptrs[i - 1].abtr = even_ptrs[i] + i += 1 + ''' for the last element''' + + even_ptrs[i - 1].abtr = even_ptrs[0] + ''' Similarly forming odd loop''' + + i = 1 + while i < len(odd_ptrs): + odd_ptrs[i - 1].abtr = odd_ptrs[i] + i += 1 + odd_ptrs[i - 1].abtr = odd_ptrs[0] + '''traversing the loop from any random +node in the loop''' + +def traverseLoop(start): + curr = start + while True and curr: + print(curr.data, end = "" "") + curr = curr.abtr + if curr == start: + break + print() + '''Driver program to test above''' + +if __name__ == '__main__': + ''' Binary tree formation''' + + root = None + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + createLoops(root) + ''' traversing odd loop from any + random odd node''' + + print(""Odd nodes:"", end = "" "") + traverseLoop(root.right) + print(""Even nodes:"", end = "" "") + ''' traversing even loop from any + random even node''' + + traverseLoop(root.left)" +Doubly Linked List | Set 1 (Introduction and Insertion),"/*Add a node at the end of the list*/ + +void append(int new_data) +{ + /* 1. allocate node + * 2. put in the data */ + + Node new_node = new Node(new_data); + Node last = head; /* 3. This new node is going to be the last node, so + * make next of it as NULL*/ + + new_node.next = null; + /* 4. If the Linked List is empty, then make the new + * node as head */ + + if (head == null) { + new_node.prev = null; + head = new_node; + return; + } + /* 5. Else traverse till the last node */ + + while (last.next != null) + last = last.next; + /* 6. Change the next of last node */ + + last.next = new_node; + /* 7. Make last node as previous of new node */ + + new_node.prev = last; +}"," '''Add a node at the end of the DLL''' + +def append(self, new_data): + ''' 1. allocate node 2. put in the data''' + + new_node = Node(data = new_data) + last = self.head + ''' 3. This new node is going to be the + last node, so make next of it as NULL''' + + new_node.next = None + ''' 4. If the Linked List is empty, then + make the new node as head''' + + if self.head is None: + new_node.prev = None + self.head = new_node + return + ''' 5. Else traverse till the last node''' + + while (last.next is not None): + last = last.next + ''' 6. Change the next of last node''' + + last.next = new_node + ''' 7. Make last node as previous of new node */''' + + new_node.prev = last" +Min Cost Path | DP-6,"/* Java program for Dynamic Programming implementation + of Min Cost Path problem */ + +import java.util.*; +class MinimumCostPath +{ + private static int minCost(int cost[][], int m, int n) + { + int i, j; +/* Instead of following line, we can use int tc[m+1][n+1] or + dynamically allocate memory to save space. The following line is + used to keep the program simple and make it working on all compilers.*/ + + int tc[][]=new int[m+1][n+1]; + tc[0][0] = cost[0][0];/* Initialize first column of total cost(tc) array */ + + for (i = 1; i <= m; i++) + tc[i][0] = tc[i-1][0] + cost[i][0]; + /* Initialize first row of tc array */ + + for (j = 1; j <= n; j++) + tc[0][j] = tc[0][j-1] + cost[0][j]; + /* Construct rest of the tc array */ + + for (i = 1; i <= m; i++) + for (j = 1; j <= n; j++) + tc[i][j] = min(tc[i-1][j-1], + tc[i-1][j], + tc[i][j-1]) + cost[i][j]; + return tc[m][n]; + } + /* A utility function that returns minimum of 3 integers */ + + private static int min(int x, int y, int z) + { + if (x < y) + return (x < z)? x : z; + else + return (y < z)? y : z; + } + + /* Driver program to test above functions */ + + public static void main(String args[]) + { + int cost[][]= {{1, 2, 3}, + {4, 8, 2}, + {1, 5, 3}}; + System.out.println(minCost(cost,2,2)); + } +}"," '''Dynamic Programming Python implementation of Min Cost Path +problem''' + +R = 3 +C = 3 +def minCost(cost, m, n): + ''' Instead of following line, we can use int tc[m+1][n+1] or + dynamically allocate memoery to save space. The following + line is used to keep te program simple and make it working + on all compilers.''' + + tc = [[0 for x in range(C)] for x in range(R)] + tc[0][0] = cost[0][0] + ''' Initialize first column of total cost(tc) array''' + + for i in range(1, m+1): + tc[i][0] = tc[i-1][0] + cost[i][0] + ''' Initialize first row of tc array''' + + for j in range(1, n+1): + tc[0][j] = tc[0][j-1] + cost[0][j] + ''' Construct rest of the tc array''' + + for i in range(1, m+1): + for j in range(1, n+1): + tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j] + return tc[m][n] + '''Driver program to test above functions''' + +cost = [[1, 2, 3], + [4, 8, 2], + [1, 5, 3]] +print(minCost(cost, 2, 2))" +Quickly find multiple left rotations of an array | Set 1,"/*Java implementation of left rotation of +an array K number of times*/ + +class LeftRotate +{ +/* Fills temp[] with two copies of arr[]*/ + + static void preprocess(int arr[], int n, + int temp[]) + { +/* Store arr[] elements at i and i + n*/ + + for (int i = 0; i ((m * n) / 2)); + } +/* Driver Function*/ + + public static void main(String args[]) + { + int array[][] = { { 1, 0, 3 }, + { 0, 0, 4 }, + { 6, 0, 0 } }; + int m = 3, + n = 3; + if (isSparse(array, m, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python 3 code to check +if a matrix is +sparse.''' + +MAX = 100 +def isSparse(array,m, n) : + counter = 0 + ''' Count number of zeros + in the matrix''' + + for i in range(0,m) : + for j in range(0,n) : + if (array[i][j] == 0) : + counter = counter + 1 + return (counter > + ((m * n) // 2)) + '''Driver Function''' + +array = [ [ 1, 0, 3 ], + [ 0, 0, 4 ], + [ 6, 0, 0 ] ] +m = 3 +n = 3 +if (isSparse(array, m, n)) : + print(""Yes"") +else : + print(""No"")" +Check if a Binary Tree contains duplicate subtrees of size 2 or more,"/*Java program to find if there is a duplicate +sub-tree of size 2 or more.*/ + +import java.util.HashSet; +public class Main { + static char MARKER = '$'; +/*A binary tree Node has data, +pointer to left child +and a pointer to right child*/ + +class Node { + int data; + Node left,right; + Node(int data) + { + this.data=data; + } +};/* This function returns empty string if tree + contains a duplicate subtree of size 2 or more.*/ + + public static String dupSubUtil(Node root, HashSet subtrees) + { + String s = """"; +/* If current node is NULL, return marker*/ + + if (root == null) + return s + MARKER; +/* If left subtree has a duplicate subtree.*/ + + String lStr = dupSubUtil(root.left,subtrees); + if (lStr.equals(s)) + return s; +/* Do same for right subtree*/ + + String rStr = dupSubUtil(root.right,subtrees); + if (rStr.equals(s)) + return s; +/* Serialize current subtree*/ + + s = s + root.data + lStr + rStr; +/* If current subtree already exists in hash + table. [Note that size of a serialized tree + with single node is 3 as it has two marker + nodes.*/ + + if (s.length() > 3 && subtrees.contains(s)) + return """"; + subtrees.add(s); + return s; + } +/* Function to find if the Binary Tree contains duplicate + subtrees of size 2 or more*/ + + public static String dupSub(Node root) + { + HashSet subtrees=new HashSet<>(); + return dupSubUtil(root,subtrees); + } + +/*Driver program to test above functions*/ + + public static void main(String args[]) + { + Node root = new Node('A'); + root.left = new Node('B'); + root.right = new Node('C'); + root.left.left = new Node('D'); + root.left.right = new Node('E'); + root.right.right = new Node('B'); + root.right.right.right = new Node('E'); + root.right.right.left= new Node('D'); + String str = dupSub(root); + if(str.equals("""")) + System.out.print("" Yes ""); + else + System.out.print("" No ""); + } +}"," '''Python3 program to find if there is +a duplicate sub-tree of size 2 or more +Separator node''' + +MARKER = '$' + '''Structure for a binary tree node''' + +class Node: + def __init__(self, x): + self.key = x + self.left = None + self.right = None +subtrees = {} + '''This function returns empty if tree +contains a duplicate subtree of size +2 or more.''' + +def dupSubUtil(root): + global subtrees + s = """" + ''' If current node is None, return marker''' + + if (root == None): + return s + MARKER + ''' If left subtree has a duplicate subtree.''' + + lStr = dupSubUtil(root.left) + if (s in lStr): + return s + ''' Do same for right subtree''' + + rStr = dupSubUtil(root.right) + if (s in rStr): + return s + ''' Serialize current subtree''' + + s = s + root.key + lStr + rStr + ''' If current subtree already exists in hash + table. [Note that size of a serialized tree + with single node is 3 as it has two marker + nodes.''' + + if (len(s) > 3 and s in subtrees): + return """" + subtrees[s] = 1 + return s + '''Driver code''' + +if __name__ == '__main__': + root = Node('A') + root.left = Node('B') + root.right = Node('C') + root.left.left = Node('D') + root.left.right = Node('E') + root.right.right = Node('B') + root.right.right.right = Node('E') + root.right.right.left= Node('D') + str = dupSubUtil(root) + if """" in str: + print("" Yes "") + else: + print("" No "")" +Minimum distance between two occurrences of maximum,"/*Java program to find Min distance +of maximum element*/ + +class GFG +{ + +/* function to return min distance*/ + + static int minDistance (int arr[], int n) + { + int maximum_element = arr[0]; + int min_dis = n; + int index = 0; + + for (int i=1; i2->1->3->1 */ + + head = push(head, 1); + head = push(head, 3); + head = push(head, 1); + head = push(head, 2); + head = push(head, 1); + /* Check the count function */ + + System.out.print(""count of 1 is "" + count(head, 1)); + } +}", +Queries to find maximum sum contiguous subarrays of given length in a rotating array,"/*Java program for +the above approach*/ + +class GFG{ + +/*Function to calculate the maximum +sum of length k*/ + +static int MaxSum(int []arr, + int n, int k) +{ + int i, max_sum = 0, sum = 0; + +/* Calculating the max sum for + the first k elements*/ + + for (i = 0; i < k; i++) + { + sum += arr[i]; + } + max_sum = sum; + +/* Find subarray with maximum sum*/ + + while (i < n) + { +/* Update the sum*/ + + sum = sum - arr[i - k] + + arr[i]; + if (max_sum < sum) + { + max_sum = sum; + } + i++; + } + +/* Return maximum sum*/ + + return max_sum; +} + +/*Function to calculate gcd + of the two numbers n1 and n2*/ + +static int gcd(int n1, int n2) +{ +/* Base Case*/ + + if (n2 == 0) + { + return n1; + } + +/* Recursively find the GCD*/ + + else + { + return gcd(n2, n1 % n2); + } +} + +/*Function to rotate the array by Y*/ + +static int []RotateArr(int []arr, + int n, int d) +{ +/* For handling k >= N*/ + + int i = 0, j = 0; + d = d % n; + +/* Dividing the array into + number of sets*/ + + int no_of_sets = gcd(d, n); + + for (i = 0; i < no_of_sets; i++) + { + int temp = arr[i]; + j = i; + +/* Rotate the array by Y*/ + + while (true) + { + int k = j + d; + + if (k >= n) + k = k - n; + + if (k == i) + break; + + arr[j] = arr[k]; + j = k; + } + +/* Update arr[j]*/ + + arr[j] = temp; + } + +/* Return the rotated array*/ + + return arr; +} + +/*Function that performs the queries +on the given array*/ + +static void performQuery(int []arr, + int Q[][], int q) +{ + int N = arr.length; + +/* Traverse each query*/ + + for (int i = 0; i < q; i++) + { +/* If query of type X = 1*/ + + if (Q[i][0] == 1) + { + arr = RotateArr(arr, N, + Q[i][1]); + +/* Print the array*/ + + for (int t : arr) + { + System.out.print(t + "" ""); + } + System.out.print(""\n""); + } + +/* If query of type X = 2*/ + + else + { + System.out.print(MaxSum(arr, N, + Q[i][1]) + ""\n""); + } + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Given array arr[]*/ + + int []arr = {1, 2, 3, 4, 5}; + + int q = 5; + +/* Given Queries*/ + + int Q[][] = {{1, 2}, {2, 3}, + {1, 3}, {1, 1}, + {2, 4}}; + +/* Function Call*/ + + performQuery(arr, Q, q); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Function to calculate the maximum +sum of length k''' + +def MaxSum(arr, n, k): + + i, max_sum = 0, 0 + sum = 0 + + ''' Calculating the max sum for + the first k elements''' + + while i < k: + sum += arr[i] + i += 1 + + max_sum = sum + + ''' Find subarray with maximum sum''' + + while (i < n): + + ''' Update the sum''' + + sum = sum - arr[i - k] + arr[i] + + if (max_sum < sum): + max_sum = sum + + i += 1 + + ''' Return maximum sum''' + + return max_sum + + '''Function to calculate gcd of the +two numbers n1 and n2''' + +def gcd(n1, n2): + + ''' Base Case''' + + if (n2 == 0): + return n1 + + ''' Recursively find the GCD''' + + else: + return gcd(n2, n1 % n2) + + '''Function to rotate the array by Y''' + +def RotateArr(arr, n, d): + + ''' For handling k >= N''' + + i = 0 + j = 0 + d = d % n + + ''' Dividing the array into + number of sets''' + + no_of_sets = gcd(d, n) + + for i in range(no_of_sets): + temp = arr[i] + j = i + + ''' Rotate the array by Y''' + + while (True): + k = j + d + + if (k >= n): + k = k - n + if (k == i): + break + + arr[j] = arr[k] + j = k + + ''' Update arr[j]''' + + arr[j] = temp + + ''' Return the rotated array''' + + return arr + + '''Function that performs the queries +on the given array''' + +def performQuery(arr, Q, q): + + N = len(arr) + + ''' Traverse each query''' + + for i in range(q): + + ''' If query of type X = 1''' + + if (Q[i][0] == 1): + arr = RotateArr(arr, N, Q[i][1]) + + ''' Print the array''' + + for t in arr: + print(t, end = "" "") + + print() + + ''' If query of type X = 2''' + + else: + print(MaxSum(arr, N, Q[i][1])) + + '''Driver Code''' + +if __name__ == '__main__': + + ''' Given array arr[]''' + + arr = [ 1, 2, 3, 4, 5 ] + + q = 5 + + ''' Given Queries''' + + Q = [ [ 1, 2 ], [ 2, 3 ], + [ 1, 3 ], [ 1, 1 ], + [ 2, 4 ] ] + + ''' Function call''' + + performQuery(arr, Q, q) + + +" +Insertion in a Binary Tree in level order,"/*Java program to insert element in binary tree*/ + +import java.util.LinkedList; +import java.util.Queue; +public class GFG { + /* A binary tree node has key, pointer to + left child and a pointer to right child */ + + static class Node { + int key; + Node left, right; +/* constructor*/ + + Node(int key) + { + this.key = key; + left = null; + right = null; + } + } + static Node root; + static Node temp = root; + /* Inorder traversal of a binary tree*/ + + static void inorder(Node temp) + { + if (temp == null) + return; + inorder(temp.left); + System.out.print(temp.key + "" ""); + inorder(temp.right); + } + /*function to insert element in binary tree */ + + static void insert(Node temp, int key) + { + if (temp == null) { + root = new Node(key); + return; + } + Queue q = new LinkedList(); + q.add(temp); +/* Do level order traversal until we find + an empty place.*/ + + while (!q.isEmpty()) { + temp = q.peek(); + q.remove(); + if (temp.left == null) { + temp.left = new Node(key); + break; + } + else + q.add(temp.left); + if (temp.right == null) { + temp.right = new Node(key); + break; + } + else + q.add(temp.right); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + root = new Node(10); + root.left = new Node(11); + root.left.left = new Node(7); + root.right = new Node(9); + root.right.left = new Node(15); + root.right.right = new Node(8); + System.out.print( + ""Inorder traversal before insertion:""); + inorder(root); + int key = 12; + insert(root, key); + System.out.print( + ""\nInorder traversal after insertion:""); + inorder(root); + } +}"," '''Python program to insert element in binary tree''' + + ''' A binary tree node has key, pointer to + left child and a pointer to right child ''' + +class newNode(): + def __init__(self, data): + self.key = data + self.left = None + self.right = None + ''' Inorder traversal of a binary tree''' + +def inorder(temp): + if (not temp): + return + inorder(temp.left) + print(temp.key,end = "" "") + inorder(temp.right) + '''function to insert element in binary tree ''' + +def insert(temp,key): + if not temp: + root = newNode(key) + return + q = [] + q.append(temp) + ''' Do level order traversal until we find + an empty place.''' + + while (len(q)): + temp = q[0] + q.pop(0) + if (not temp.left): + temp.left = newNode(key) + break + else: + q.append(temp.left) + if (not temp.right): + temp.right = newNode(key) + break + else: + q.append(temp.right) + '''Driver code''' + +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(11) + root.left.left = newNode(7) + root.right = newNode(9) + root.right.left = newNode(15) + root.right.right = newNode(8) + print(""Inorder traversal before insertion:"", end = "" "") + inorder(root) + key = 12 + insert(root, key) + print() + print(""Inorder traversal after insertion:"", end = "" "") + inorder(root)" +Average of a stream of numbers,"/*Java program to find average +of a stream of numbers*/ + +class GFG { +/* Returns the new average after including x*/ + + static float getAvg(float prev_avg, float x, int n) + { + return (prev_avg * n + x) / (n + 1); + } +/* Prints average of a stream of numbers*/ + + static void streamAvg(float arr[], int n) + { + float avg = 0; + for (int i = 0; i < n; i++) + { + avg = getAvg(avg, arr[i], i); + System.out.printf(""Average of %d numbers is %f \n"", + i + 1, avg); + } + return; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + float arr[] = { 10, 20, 30, 40, 50, 60 }; + int n = arr.length; + streamAvg(arr, n); + } +}"," '''Returns the new average +after including x''' + +def getAvg(prev_avg, x, n): + return ((prev_avg * + n + x) / + (n + 1)); + '''Prints average of +a stream of numbers''' + +def streamAvg(arr, n): + avg = 0; + for i in range(n): + avg = getAvg(avg, arr[i], i); + print(""Average of "", i + 1, + "" numbers is "", avg); + '''Driver Code''' + +arr = [10, 20, 30, + 40, 50, 60]; +n = len(arr); +streamAvg(arr, n);" +Maximum absolute difference of value and index sums,"/*Java program to calculate the maximum +absolute difference of an array.*/ + +public class MaximumAbsoluteDifference +{ +/* Function to return maximum absolute + difference in linear time.*/ + + private static int maxDistance(int[] array) + { +/* max and min variables as described + in algorithm.*/ + + int max1 = Integer.MIN_VALUE; + int min1 = Integer.MAX_VALUE; + int max2 = Integer.MIN_VALUE; + int min2 = Integer.MAX_VALUE; + + for (int i = 0; i < array.length; i++) + { + +/* Updating max and min variables + as described in algorithm.*/ + + max1 = Math.max(max1, array[i] + i); + min1 = Math.min(min1, array[i] + i); + max2 = Math.max(max2, array[i] - i); + min2 = Math.min(min2, array[i] - i); + } + +/* Calculating maximum absolute difference.*/ + + return Math.max(max1 - min1, max2 - min2); + } + +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int[] array = { -70, -64, -6, -56, 64, + 61, -57, 16, 48, -98 }; + System.out.println(maxDistance(array)); + } +} + + +"," '''Python program to +calculate the maximum +absolute difference +of an array.''' + + + '''Function to return +maximum absolute +difference in linear time.''' + +def maxDistance(array): + + ''' max and min variables as described + in algorithm.''' + + max1 = -2147483648 + min1 = +2147483647 + max2 = -2147483648 + min2 = +2147483647 + + for i in range(len(array)): + + + ''' Updating max and min variables + as described in algorithm.''' + + max1 = max(max1, array[i] + i) + min1 = min(min1, array[i] + i) + max2 = max(max2, array[i] - i) + min2 = min(min2, array[i] - i) + + + ''' Calculating maximum absolute difference.''' + + return max(max1 - min1, max2 - min2) + + + '''Driver program to +test above function''' + + +array = [ -70, -64, -6, -56, 64, + 61, -57, 16, 48, -98 ] + +print(maxDistance(array)) + + +" +Prim's algorithm using priority_queue in STL,"/*If v is not in MST and weight of (u,v) is smaller +than current key of v*/ + +if (inMST[v] == false && key[v] > weight) +{ +/* Updating key of v*/ + + key[v] = weight; + pq.add(new Pair(key[v], v)); + parent[v] = u; +}"," '''If v is not in MST and weight of (u,v) is smaller +than current key of v''' + +if (inMST[v] == False and key[v] > weight) : + ''' Updating key of v''' + + key[v] = weight + pq.append([key[v], v]) + parent[v] = u" +Rotate digits of a given number by K,"/*Java program to implement +the above approach*/ + + +import java.io.*; + +class GFG { + +/* Function to find the count of + digits in N*/ + + static int numberOfDigit(int N) + { + +/* Stores count of + digits in N*/ + + int digit = 0; + +/* Calculate the count + of digits in N*/ + + while (N > 0) { + +/* Update digit*/ + + digit++; + +/* Update N*/ + + N /= 10; + } + return digit; + } + +/* Function to rotate the digits of N by K*/ + + static void rotateNumberByK(int N, int K) + { + +/* Stores count of digits in N*/ + + int X = numberOfDigit(N); + +/* Update K so that only need to + handle left rotation*/ + + K = ((K % X) + X) % X; + +/* Stores first K digits of N*/ + + int left_no = N / (int)(Math.pow(10, + X - K)); + +/* Remove first K digits of N*/ + + N = N % (int)(Math.pow(10, X - K)); + +/* Stores count of digits in left_no*/ + + int left_digit = numberOfDigit(left_no); + +/* Append left_no to the right of + digits of N*/ + + N = (N * (int)(Math.pow(10, left_digit))) + + left_no; + + System.out.println(N); + } + +/* Driver Code*/ + + public static void main(String args[]) + { + + int N = 12345, K = 7; + +/* Function Call*/ + + rotateNumberByK(N, K); + } +} +"," '''Python3 program to implement +the above approach''' + + + '''Function to find the count of +digits in N''' + +def numberOfDigit(N): + + ''' Stores count of + digits in N''' + + digit = 0 + + ''' Calculate the count + of digits in N''' + + while (N > 0): + + ''' Update digit''' + + digit += 1 + + ''' Update N''' + + N //= 10 + return digit + + '''Function to rotate the digits of N by K''' + +def rotateNumberByK(N, K): + + ''' Stores count of digits in N''' + + X = numberOfDigit(N) + + ''' Update K so that only need to + handle left rotation''' + + K = ((K % X) + X) % X + + ''' Stores first K digits of N''' + + left_no = N // pow(10, X - K) + + ''' Remove first K digits of N''' + + N = N % pow(10, X - K) + + ''' Stores count of digits in left_no''' + + left_digit = numberOfDigit(left_no) + + ''' Append left_no to the right of + digits of N''' + + N = N * pow(10, left_digit) + left_no + print(N) + + '''Driver Code''' + +if __name__ == '__main__': + N, K = 12345, 7 + + ''' Function Call''' + + rotateNumberByK(N, K) + + +" +Find largest subtree having identical left and right subtrees,"/*Java program to find the largest subtree +having identical left and right subtree*/ + +class GFG +{ +/* A binary tree node has data, pointer to left +child and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; +/* Helper function that allocates a new node with +the given data and null left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); +} +static class string +{ + String str; +} +static int maxSize; +static Node maxNode; +static class pair +{ + int first; + String second; + pair(int a, String b) + { + first = a; + second = b; + } +} +/*Sets maxSize to size of largest subtree with +identical left and right. maxSize is set with +size of the maximum sized subtree. It returns +size of subtree rooted with current node. This +size is used to keep track of maximum size.*/ + +static pair largestSubtreeUtil(Node root, String str) +{ + if (root == null) + return new pair(0, str); +/* string to store structure of left and + right subtrees*/ + + String left ="""", right=""""; +/* traverse left subtree and finds its size*/ + + pair ls1 = largestSubtreeUtil(root.left, left); + left = ls1.second; + int ls = ls1.first; +/* traverse right subtree and finds its size*/ + + pair rs1 = largestSubtreeUtil(root.right, right); + right = rs1.second; + int rs = rs1.first; +/* if left and right subtrees are similar + update maximum subtree if needed (Note that + left subtree may have a bigger value than + right and vice versa)*/ + + int size = ls + rs + 1; + if (left.equals(right)) + { + if (size > maxSize) + { + maxSize = size; + maxNode = root; + } + } +/* append left subtree data*/ + + str += ""|""+left+""|""; +/* append current node data*/ + + str += ""|""+root.data+""|""; +/* append right subtree data*/ + + str += ""|""+right+""|""; + return new pair(size, str); +} +/*function to find the largest subtree +having identical left and right subtree*/ + +static int largestSubtree(Node node) +{ + maxSize = 0; + largestSubtreeUtil(node,""""); + return maxSize; +} +/* Driver program to test above functions*/ + +public static void main(String args[]) +{ + /* Let us construct the following Tree + 50 + / \ + 10 60 + / \ / \ + 5 20 70 70 + / \ / \ + 65 80 65 80 */ + + Node root = newNode(50); + root.left = newNode(10); + root.right = newNode(60); + root.left.left = newNode(5); + root.left.right = newNode(20); + root.right.left = newNode(70); + root.right.left.left = newNode(65); + root.right.left.right = newNode(80); + root.right.right = newNode(70); + root.right.right.left = newNode(65); + root.right.right.right = newNode(80); + maxNode = null; + maxSize = largestSubtree(root); + System.out.println( ""Largest Subtree is rooted at node "" + + maxNode.data + ""\nand its size is "" + + maxSize); +} +}"," '''Python3 program to find the largest subtree +having identical left and right subtree''' + + '''Helper class that allocates a new node +with the given data and None left and +right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Sets maxSize to size of largest subtree with +identical left and right. maxSize is set with +size of the maximum sized subtree. It returns +size of subtree rooted with current node. This +size is used to keep track of maximum size.''' + +def largestSubtreeUtil(root, Str, + maxSize, maxNode): + if (root == None): + return 0 + ''' string to store structure of left + and right subtrees''' + + left = [""""] + right = [""""] + ''' traverse left subtree and finds its size''' + + ls = largestSubtreeUtil(root.left, left, + maxSize, maxNode) + ''' traverse right subtree and finds its size''' + + rs = largestSubtreeUtil(root.right, right, + maxSize, maxNode) + ''' if left and right subtrees are similar + update maximum subtree if needed (Note + that left subtree may have a bigger + value than right and vice versa)''' + + size = ls + rs + 1 + if (left[0] == right[0]): + if (size > maxSize[0]): + maxSize[0] = size + maxNode[0] = root + ''' append left subtree data''' + + Str[0] = Str[0] + ""|"" + left[0] + ""|"" + ''' append current node data''' + + Str[0] = Str[0] + ""|"" + str(root.data) + ""|"" + ''' append right subtree data''' + + Str[0] = Str[0] + ""|"" + right[0] + ""|"" + return size + '''function to find the largest subtree +having identical left and right subtree''' + +def largestSubtree(node, maxNode): + maxSize = [0] + Str = [""""] + largestSubtreeUtil(node, Str, maxSize, + maxNode) + return maxSize + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us construct the following Tree + 50 + / \ + 10 60 + / \ / \ + 5 20 70 70 + / \ / \ + 65 80 65 80''' + + root = newNode(50) + root.left = newNode(10) + root.right = newNode(60) + root.left.left = newNode(5) + root.left.right = newNode(20) + root.right.left = newNode(70) + root.right.left.left = newNode(65) + root.right.left.right = newNode(80) + root.right.right = newNode(70) + root.right.right.left = newNode(65) + root.right.right.right = newNode(80) + maxNode = [None] + maxSize = largestSubtree(root, maxNode) + print(""Largest Subtree is rooted at node "", + maxNode[0].data) + print(""and its size is "", maxSize)" +Check in binary array the number represented by a subarray is odd or even,"/*java program to find if a subarray +is even or odd.*/ + +import java.io.*; + +class GFG +{ +/* prints if subarray is even or odd*/ + + static void checkEVENodd (int arr[], int n, int l, int r) + { +/* if arr[r] = 1 print odd*/ + + if (arr[r] == 1) + System.out.println( ""odd"") ; + +/* if arr[r] = 0 print even*/ + + else + System.out.println ( ""even"") ; + } + +/* driver code*/ + + public static void main (String[] args) + { + int arr[] = {1, 1, 0, 1}; + int n = arr.length; + checkEVENodd (arr, n, 1, 3); + + + } +} + + +"," '''Python3 program to find if a +subarray is even or odd.''' + + + '''Prints if subarray is even or odd''' + +def checkEVENodd (arr, n, l, r): + + ''' if arr[r] = 1 print odd''' + + if (arr[r] == 1): + print(""odd"") + + ''' if arr[r] = 0 print even''' + + else: + print(""even"") + + '''Driver code''' + +arr = [1, 1, 0, 1] +n = len(arr) +checkEVENodd (arr, n, 1, 3) + + +" +Print cousins of a given node in Binary Tree,"/*Java program to print cousins of a node */ + +class GfG { +/*A Binary Tree Node */ + +static class Node +{ + int data; + Node left, right; +} +/*A utility function to create a new Binary +Tree Node */ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.data = item; + temp.left = null; + temp.right = null; + return temp; +} +/* It returns level of the node if it is present +in tree, otherwise returns 0.*/ + +static int getLevel(Node root, Node node, int level) +{ +/* base cases */ + + if (root == null) + return 0; + if (root == node) + return level; +/* If node is present in left subtree */ + + int downlevel = getLevel(root.left, node, level+1); + if (downlevel != 0) + return downlevel; +/* If node is not present in left subtree */ + + return getLevel(root.right, node, level+1); +} +/* Print nodes at a given level such that sibling of +node is not printed if it exists */ + +static void printGivenLevel(Node root, Node node, int level) +{ +/* Base cases */ + + if (root == null || level < 2) + return; +/* If current node is parent of a node with + given level */ + + if (level == 2) + { + if (root.left == node || root.right == node) + return; + if (root.left != null) + System.out.print(root.left.data + "" ""); + if (root.right != null) + System.out.print(root.right.data + "" ""); + } +/* Recur for left and right subtrees */ + + else if (level > 2) + { + printGivenLevel(root.left, node, level-1); + printGivenLevel(root.right, node, level-1); + } +} +/*This function prints cousins of a given node */ + +static void printCousins(Node root, Node node) +{ +/* Get level of given node */ + + int level = getLevel(root, node, 1); +/* Print nodes of given level. */ + + printGivenLevel(root, node, level); +} +/*Driver Program to test above functions */ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + root.left.right.right = newNode(15); + root.right.left = newNode(6); + root.right.right = newNode(7); + root.right.left.right = newNode(8); + printCousins(root, root.left.right); +} +}"," '''Python3 program to print cousins of a node ''' + + '''A utility function to create a new +Binary Tree Node ''' + +class newNode: + def __init__(self, item): + self.data = item + self.left = self.right = None '''It returns level of the node if it is +present in tree, otherwise returns 0.''' + +def getLevel(root, node, level): + ''' base cases ''' + + if (root == None): + return 0 + if (root == node): + return level + ''' If node is present in left subtree ''' + + downlevel = getLevel(root.left, node, + level + 1) + if (downlevel != 0): + return downlevel + ''' If node is not present in left subtree ''' + + return getLevel(root.right, node, level + 1) + '''Prnodes at a given level such that +sibling of node is not printed if +it exists ''' + +def printGivenLevel(root, node, level): + ''' Base cases ''' + + if (root == None or level < 2): + return + ''' If current node is parent of a + node with given level ''' + + if (level == 2): + if (root.left == node or + root.right == node): + return + if (root.left): + print(root.left.data, end = "" "") + if (root.right): + print(root.right.data, end = "" "") + ''' Recur for left and right subtrees ''' + + elif (level > 2): + printGivenLevel(root.left, node, level - 1) + printGivenLevel(root.right, node, level - 1) + '''This function prints cousins of a given node ''' + +def printCousins(root, node): + ''' Get level of given node ''' + + level = getLevel(root, node, 1) + ''' Prnodes of given level. ''' + + printGivenLevel(root, node, level) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.left.right.right = newNode(15) + root.right.left = newNode(6) + root.right.right = newNode(7) + root.right.left.right = newNode(8) + printCousins(root, root.left.right)" +Smallest power of 2 greater than or equal to n,"/*Java program to find smallest +power of 2 greater than or +equal to n*/ + +import java.io.*; +class GFG +{ +/* Finds next power of two + for n. If n itself is a + power of two then returns n*/ + + static int nextPowerOf2(int n) + { + n--; + n |= n >> 1; + n |= n >> 2; + n |= n >> 4; + n |= n >> 8; + n |= n >> 16; + n++; + return n; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int n = 5; + System.out.println(nextPowerOf2(n)); + } +}"," '''Finds next power of two +for n. If n itself is a +power of two then returns n''' + +def nextPowerOf2(n): + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + n += 1 + return n + '''Driver program to test +above function''' + +n = 5 +print(nextPowerOf2(n))" +Counting Sort,"/*Counting sort which takes negative numbers as well*/ + +import java.util.*; +class GFG { + + +/*The function that sorts the given arr[]*/ + + static void countSort(int[] arr) + { + int max = Arrays.stream(arr).max().getAsInt(); + int min = Arrays.stream(arr).min().getAsInt(); + int range = max - min + 1; + int count[] = new int[range]; + int output[] = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + count[arr[i] - min]++; + } + for (int i = 1; i < count.length; i++) { + count[i] += count[i - 1]; + } + for (int i = arr.length - 1; i >= 0; i--) { + output[count[arr[i] - min] - 1] = arr[i]; + count[arr[i] - min]--; + } + for (int i = 0; i < arr.length; i++) { + arr[i] = output[i]; + } + }/*function to print array*/ + + static void printArray(int[] arr) + { + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + "" ""); + } + System.out.println(""""); + }/* Driver code*/ + + public static void main(String[] args) + { + int[] arr = { -5, -10, 0, -3, 8, 5, -1, 10 }; + countSort(arr); + printArray(arr); + } +}"," '''Python program for counting sort +which takes negative numbers as well''' + + '''The function that sorts the given arr[]''' + +def count_sort(arr): + max_element = int(max(arr)) + min_element = int(min(arr)) + range_of_elements = max_element - min_element + 1 + count_arr = [0 for _ in range(range_of_elements)] + output_arr = [0 for _ in range(len(arr))] + for i in range(0, len(arr)): + count_arr[arr[i]-min_element] += 1 + for i in range(1, len(count_arr)): + count_arr[i] += count_arr[i-1] + for i in range(len(arr)-1, -1, -1): + output_arr[count_arr[arr[i] - min_element] - 1] = arr[i] + count_arr[arr[i] - min_element] -= 1 + for i in range(0, len(arr)): + arr[i] = output_arr[i] + return arr + '''Driver program to test above function''' + +arr = [-5, -10, 0, -3, 8, 5, -1, 10] +ans = count_sort(arr) +print(""Sorted character array is "" + str(ans))" +Lowest Common Ancestor in a Binary Search Tree.,"/*Recursive Java program to print lca of two nodes +A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* Function to find LCA of n1 and n2. +The function assumes that both +n1 and n2 are present in BST */ + +static Node lca(Node root, int n1, int n2) +{ + while (root != null) + { +/* If both n1 and n2 are smaller + than root, then LCA lies in left */ + + if (root.data > n1 && + root.data > n2) + root = root.left; +/* If both n1 and n2 are greater + than root, then LCA lies in right */ + + else if (root.data < n1 && + root.data < n2) + root = root.right; + else break; + } + return root; +} + /* Driver program to test lca() */ + + public static void main(String args[]) + { +/* Let us construct the BST shown in the above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(8); + tree.root.right = new Node(22); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(12); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(14); + int n1 = 10, n2 = 14; + Node t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + n1 = 14; + n2 = 8; + t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + n1 = 10; + n2 = 22; + t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + } +}"," '''A recursive python program to find LCA of two nodes +n1 and n2 +A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to find LCA of n1 and n2. +The function assumes that both + n1 and n2 are present in BST ''' + +def lca(root, n1, n2): + while root: + ''' If both n1 and n2 are smaller than root, + then LCA lies in left''' + + if root.data > n1 and root.data > n2: + root = root.left + ''' If both n1 and n2 are greater than root, + then LCA lies in right''' + + elif root.data < n1 and root.data < n2: + root = root.right + else: + break + return root + '''Driver program to test above function''' '''Let us construct the BST shown in the figure''' + +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) +n1 = 10 ; n2 = 14 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2, t.data) +n1 = 14 ; n2 = 8 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2 , t.data) +n1 = 10 ; n2 = 22 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2, t.data) +" +Range Queries for Longest Correct Bracket Subsequence Set | 2,"/*Java code to answer the query in constant time*/ + +import java.util.*; +class GFG{ +/* +BOP[] stands for ""Balanced open parentheses"" +BCP[] stands for ""Balanced close parentheses"" +*/ + +/*Function for precomputation*/ + +static void constructBlanceArray(int BOP[], int BCP[], + String str, int n) +{ +/* Create a stack and push -1 + as initial index to it.*/ + + Stack stk = new Stack<>();; +/* Traverse all characters of given String*/ + + for(int i = 0; i < n; i++) + { +/* If opening bracket, push index of it*/ + + if (str.charAt(i) == '(') + stk.add(i); +/* If closing bracket, i.e., str[i] = ')'*/ + + else + { +/* If closing bracket, i.e., str[i] = ')' + && stack is not empty then mark both + ""open & close"" bracket indexs as 1 . + Pop the previous opening bracket's index*/ + + if (!stk.isEmpty()) + { + BCP[i] = 1; + BOP[stk.peek()] = 1; + stk.pop(); + } +/* If stack is empty.*/ + + else + BCP[i] = 0; + } + } + for(int i = 1; i < n; i++) + { + BCP[i] += BCP[i - 1]; + BOP[i] += BOP[i - 1]; + } +} +/*Function return output of each query in O(1)*/ + +static int query(int BOP[], int BCP[], + int s, int e) +{ + if (BOP[s - 1] == BOP[s]) + { + return (BCP[e] - BOP[s]) * 2; + } + else + { + return (BCP[e] - BOP[s] + 1) * 2; + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + String str = ""())(())(())(""; + int n = str.length(); + int BCP[] = new int[n + 1]; + int BOP[] = new int[n + 1]; + constructBlanceArray(BOP, BCP, str, n); + int startIndex = 5, endIndex = 11; + System.out.print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + startIndex + "" and "" + endIndex + + "" = "" + query(BOP, BCP, startIndex, + endIndex) + ""\n""); + startIndex = 4; + endIndex = 5; + System.out.print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + startIndex + "" and "" + endIndex + + "" = "" + query(BOP, BCP, startIndex, + endIndex) + ""\n""); + startIndex = 1; + endIndex = 5; + System.out.print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + startIndex + "" and "" + endIndex + + "" = "" + query(BOP, BCP, startIndex, + endIndex) + ""\n""); +} +}"," '''Python3 code to answer the query in constant time''' + + ''' +BOP[] stands for ""Balanced open parentheses"" +BCP[] stands for ""Balanced close parentheses"" ''' + + '''Function for precomputation''' + +def constructBlanceArray(BOP, BCP, str, n): + ''' Create a stack and push -1 + as initial index to it.''' + + stk = [] + ''' Traverse all characters of given String''' + + for i in range(n): + ''' If opening bracket, push index of it''' + + if (str[i] == '('): + stk.append(i); + ''' If closing bracket, i.e., str[i] = ') ''' + else: + ''' If closing bracket, i.e., str[i] = ')' + && stack is not empty then mark both + ""open & close"" bracket indexs as 1 . + Pop the previous opening bracket's index''' + + if (len(stk) != 0): + BCP[i] = 1; + BOP[stk[-1]] = 1; + stk.pop(); + ''' If stack is empty.''' + + else: + BCP[i] = 0; + for i in range(1, n): + BCP[i] += BCP[i - 1]; + BOP[i] += BOP[i - 1]; + '''Function return output of each query in O(1)''' + +def query(BOP, BCP, s, e): + if (BOP[s - 1] == BOP[s]): + return (BCP[e] - BOP[s]) * 2; + else: + return (BCP[e] - BOP[s] + 1) * 2; + '''Driver code''' + +if __name__=='__main__': + string = ""())(())(())(""; + n = len(string) + BCP = [0 for i in range(n + 1)]; + BOP = [0 for i in range(n + 1)]; + constructBlanceArray(BOP, BCP, string, n); + startIndex = 5 + endIndex = 11; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex))); + startIndex = 4; + endIndex = 5; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex))) + startIndex = 1; + endIndex = 5; + print(""Maximum Length Correct "" + + ""Bracket Subsequence between "" + + str(startIndex) + "" and "" + str(endIndex) + + "" = "" + str(query(BOP, BCP, startIndex, + endIndex)));" +Find the two numbers with odd occurrences in an unsorted array,"/*Java program to find two odd +occurring elements*/ + + +import java.util.*; + +class Main +{ + + /* Prints two numbers that occur odd + number of times. The function assumes + that the array size is at least 2 and + there are exactly two numbers occurring + odd number of times. */ + + static void printTwoOdd(int arr[], int size) + { + /* Will hold XOR of two odd occurring elements */ + + int xor2 = arr[0]; + + /* Will have only single set bit of xor2 */ + + int set_bit_no; + int i; + int n = size - 2; + int x = 0, y = 0; + + /* Get the xor of all elements in arr[]. + The xor will basically be xor of two + odd occurring elements */ + + for(i = 1; i < size; i++) + xor2 = xor2 ^ arr[i]; + + /* Get one set bit in the xor2. We get + rightmost set bit in the following + line as it is easy to get */ + + set_bit_no = xor2 & ~(xor2-1); + + /* Now divide elements in two sets: + 1) The elements having the + corresponding bit as 1. + 2) The elements having the + corresponding bit as 0. */ + + for(i = 0; i < size; i++) + { + /* XOR of first set is finally going + to hold one odd occurring number x */ + + if((arr[i] & set_bit_no)>0) + x = x ^ arr[i]; + + /* XOR of second set is finally going + to hold the other odd occurring number y */ + + else + y = y ^ arr[i]; + } + + System.out.println(""The two ODD elements are ""+ + x + "" & "" + y); + } + +/* main function*/ + + public static void main (String[] args) + { + int arr[] = {4, 2, 4, 5, 2, 3, 3, 1}; + int arr_size = arr.length; + printTwoOdd(arr, arr_size); + } +} +"," '''Python3 program to find the +two odd occurring elements''' + + + '''Prints two numbers that occur odd +number of times. The function assumes +that the array size is at least 2 and +there are exactly two numbers occurring +odd number of times.''' + +def printTwoOdd(arr, size): + + ''' Will hold XOR of two odd occurring elements''' + + xor2 = arr[0] + + ''' Will have only single set bit of xor2''' + + set_bit_no = 0 + n = size - 2 + x, y = 0, 0 + + ''' Get the xor of all elements in arr[]. + The xor will basically be xor of two + odd occurring elements''' + + for i in range(1, size): + xor2 = xor2 ^ arr[i] + + ''' Get one set bit in the xor2. We get + rightmost set bit in the following + line as it is easy to get''' + + set_bit_no = xor2 & ~(xor2 - 1) + + ''' Now divide elements in two sets: + 1) The elements having the corresponding bit as 1. + 2) The elements having the corresponding bit as 0.''' + + for i in range(size): + + ''' XOR of first set is finally going to + hold one odd occurring number x''' + + if(arr[i] & set_bit_no): + x = x ^ arr[i] + + ''' XOR of second set is finally going + to hold the other odd occurring number y''' + + else: + y = y ^ arr[i] + + print(""The two ODD elements are"", x, ""&"", y) + + '''Driver Code''' + +arr = [4, 2, 4, 5, 2, 3, 3, 1] +arr_size = len(arr) +printTwoOdd(arr, arr_size) + + +" +Next Greater Element in a Circular Linked List,"/*Java program for the above approach*/ + + +import java.io.*; +import java.util.*; + +class GFG { + static Node head; + +/* Node structure of the circular + Linked list*/ + + static class Node { + int data; + Node next; + +/* Constructor*/ + + public Node(int data) + { + this.data = data; + this.next = null; + } + } + +/* Function to print the elements + of a Linked list*/ + + static void print(Node head) + { + Node temp = head; + +/* Iterate the linked list*/ + + while (temp != null) { + +/* Print the data*/ + + System.out.print( + temp.data + "" ""); + temp = temp.next; + } + } + +/* Function to find the next + greater element for each node*/ + + static void NextGreaterElement(Node head) + { +/* Stores the head of circular + Linked list*/ + + Node H = head; + +/* Stores the head of the + resulting linked list*/ + + Node res = null; + +/* Stores the temporary head of + the resulting Linked list*/ + + Node tempList = null; + +/* Iterate until head + is not equal to H*/ + + do { + +/* Used to iterate over the + circular Linked List*/ + + Node curr = head; + +/* Stores if there exist + any next Greater element*/ + + int Val = -1; + +/* Iterate until head is + not equal to curr*/ + + do { + +/* If the current node + is smaller*/ + + if (head.data < curr.data) { + +/* Update the value + of Val*/ + + Val = curr.data; + break; + } + +/* Update curr*/ + + curr = curr.next; + + } while (curr != head); + +/* If res is Null*/ + + if (res == null) { + +/* Create new Node with + value curr.data*/ + + res = new Node(Val); + +/* Assign address of + res to tempList*/ + + tempList = res; + } + else { + +/* Update tempList*/ + + tempList.next = new Node(Val); + +/* Assign address of the + next node to tempList*/ + + tempList = tempList.next; + } + +/* Update the value of + head node*/ + + head = head.next; + } while (head != H); + +/* Print the resulting + Linked list*/ + + print(res); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + 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); + } +} +", +Check if array contains contiguous integers with duplicates allowed,"/*Java implementation to +check whether the array +contains a set of +contiguous integers*/ + +import java.util.*; +class GFG { +/* function to check + whether the array + contains a set of + contiguous integers*/ + + static boolean areElementsContiguous(int arr[], + int n) + { +/* Find maximum and + minimum elements.*/ + + int max = Integer.MIN_VALUE; + int min = Integer.MAX_VALUE; + for(int i = 0; i < n; i++) + { + max = Math.max(max, arr[i]); + min = Math.min(min, arr[i]); + } + int m = max - min + 1; +/* There should be at least + m elements in aaray to + make them contiguous.*/ + + if (m > n) + return false; +/* Create a visited array + and initialize false.*/ + + boolean visited[] = new boolean[n]; +/* Mark elements as true.*/ + + for (int i = 0; i < n; i++) + visited[arr[i] - min] = true; +/* If any element is not + marked, all elements + are not contiguous.*/ + + for (int i = 0; i < m; i++) + if (visited[i] == false) + return false; + return true; + } + /* Driver program */ + + public static void main(String[] args) + { + int arr[] = { 5, 2, 3, 6, + 4, 4, 6, 6 }; + int n = arr.length; + if (areElementsContiguous(arr, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 implementation to +check whether the array +contains a set of +contiguous integers''' + '''function to check +whether the array +contains a set of +contiguous integers''' + +def areElementsContiguous(arr, n): + ''' Find maximum and + minimum elements.''' + + max1 = max(arr) + min1 = min(arr) + m = max1 - min1 + 1 + ''' There should be at least + m elements in array to + make them contiguous.''' + + if (m > n): + return False + ''' Create a visited array + and initialize fals''' + + visited = [0] * m + ''' Mark elements as true.''' + + for i in range(0,n) : + visited[arr[i] - min1] = True + ''' If any element is not + marked, all elements + are not contiguous.''' + + for i in range(0, m): + if (visited[i] == False): + return False + return True + '''Driver program''' + +arr = [5, 2, 3, 6, 4, 4, 6, 6 ] +n = len(arr) +if (areElementsContiguous(arr, n)): + print(""Yes"") +else: + print(""No"")" +Smallest subarray with sum greater than a given value,"/*O(n) solution for finding smallest subarray with sum +greater than x*/ + +class SmallestSubArraySum { +/* Returns length of smallest subarray with sum greater + than x. If there is no subarray with given sum, then + returns n+1*/ + + static int smallestSubWithSum(int arr[], int n, int x) + { +/* Initialize current sum and minimum length*/ + + int curr_sum = 0, min_len = n + 1; +/* Initialize starting and ending indexes*/ + + int start = 0, end = 0; + while (end < n) { +/* Keep adding array elements while current sum + is smaller than or equal to x*/ + + while (curr_sum <= x && end < n) + curr_sum += arr[end++]; +/* If current sum becomes greater than x.*/ + + while (curr_sum > x && start < n) { +/* Update minimum length if needed*/ + + if (end - start < min_len) + min_len = end - start; +/* remove starting elements*/ + + curr_sum -= arr[start++]; + } + } + return min_len; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int arr1[] = { 1, 4, 45, 6, 10, 19 }; + int x = 51; + int n1 = arr1.length; + int res1 = smallestSubWithSum(arr1, n1, x); + if (res1 == n1 + 1) + System.out.println(""Not Possible""); + else + System.out.println(res1); + int arr2[] = { 1, 10, 5, 2, 7 }; + int n2 = arr2.length; + x = 9; + int res2 = smallestSubWithSum(arr2, n2, x); + if (res2 == n2 + 1) + System.out.println(""Not Possible""); + else + System.out.println(res2); + int arr3[] + = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; + int n3 = arr3.length; + x = 280; + int res3 = smallestSubWithSum(arr3, n3, x); + if (res3 == n3 + 1) + System.out.println(""Not Possible""); + else + System.out.println(res3); + } +}"," '''O(n) solution for finding smallest +subarray with sum greater than x + ''' '''Returns length of smallest subarray +with sum greater than x. If there +is no subarray with given sum, then +returns n + 1''' + +def smallestSubWithSum(arr, n, x): + ''' Initialize current sum and minimum length''' + + curr_sum = 0 + min_len = n + 1 + ''' Initialize starting and ending indexes''' + + start = 0 + end = 0 + while (end < n): + ''' Keep adding array elements while current + sum is smaller than or equal to x''' + + while (curr_sum <= x and end < n): + curr_sum += arr[end] + end += 1 + ''' If current sum becomes greater than x.''' + + while (curr_sum > x and start < n): + ''' Update minimum length if needed''' + + if (end - start < min_len): + min_len = end - start + ''' remove starting elements''' + + curr_sum -= arr[start] + start += 1 + return min_len + '''Driver program''' + +arr1 = [1, 4, 45, 6, 10, 19] +x = 51 +n1 = len(arr1) +res1 = smallestSubWithSum(arr1, n1, x) +print(""Not possible"") if (res1 == n1 + 1) else print(res1) +arr2 = [1, 10, 5, 2, 7] +n2 = len(arr2) +x = 9 +res2 = smallestSubWithSum(arr2, n2, x) +print(""Not possible"") if (res2 == n2 + 1) else print(res2) +arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250] +n3 = len(arr3) +x = 280 +res3 = smallestSubWithSum(arr3, n3, x) +print(""Not possible"") if (res3 == n3 + 1) else print(res3)" +Efficient program to print all prime factors of a given number,"/*Program to print all prime factors*/ + +import java.io.*; +import java.lang.Math; +class GFG +{ +/* A function to print all prime factors + of a given number n*/ + + public static void primeFactors(int n) + { +/* Print the number of 2s that divide n*/ + + while (n%2==0) + { + System.out.print(2 + "" ""); + n /= 2; + } +/* n must be odd at this point. So we can + skip one element (Note i = i +2)*/ + + for (int i = 3; i <= Math.sqrt(n); i+= 2) + { +/* While i divides n, print i and divide n*/ + + while (n%i == 0) + { + System.out.print(i + "" ""); + n /= i; + } + } +/* This condition is to handle the case whien + n is a prime number greater than 2*/ + + if (n > 2) + System.out.print(n); + } +/* Driver code */ + + public static void main (String[] args) + { + int n = 315; + primeFactors(n); + } +}"," '''Python program to print prime factors''' + +import math + '''A function to print all prime factors of +a given number n''' + +def primeFactors(n): + ''' Print the number of two's that divide n''' + + while n % 2 == 0: + print 2, + n = n / 2 + ''' n must be odd at this point + so a skip of 2 ( i = i + 2) can be used''' + + for i in range(3,int(math.sqrt(n))+1,2): + ''' while i divides n , print i ad divide n''' + + while n % i== 0: + print i, + n = n / i + ''' Condition if n is a prime + number greater than 2''' + + if n > 2: + print n + '''Driver Program to test above function''' + +n = 315 +primeFactors(n)" +Birthday Paradox,"/*Java program to approximate number +of people in Birthday Paradox problem*/ + +class GFG { +/* Returns approximate number of people + for a given probability*/ + + static double find(double p) { + return Math.ceil(Math.sqrt(2 * + 365 * Math.log(1 / (1 - p)))); + } +/* Driver code*/ + + public static void main(String[] args) + { + System.out.println(find(0.70)); + } +}"," '''Python3 code to approximate number +of people in Birthday Paradox problem''' + +import math + '''Returns approximate number of +people for a given probability''' + +def find( p ): + return math.ceil(math.sqrt(2 * 365 * + math.log(1/(1-p)))); + '''Driver Code''' + +print(find(0.70))" +Program to check Involutory Matrix,"/*Java Program to implement +involutory matrix.*/ + +import java.io.*; +class GFG { + static int N = 3; +/* Function for matrix multiplication.*/ + + static void multiply(int mat[][], int res[][]) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + res[i][j] = 0; + for (int k = 0; k < N; k++) + res[i][j] += mat[i][k] * mat[k][j]; + } + } + } +/* Function to check involutory matrix.*/ + + static boolean InvolutoryMatrix(int mat[][]) + { + int res[][] = new int[N][N]; +/* multiply function call.*/ + + multiply(mat, res); + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if (i == j && res[i][j] != 1) + return false; + if (i != j && res[i][j] != 0) + return false; + } + } + return true; + } +/* Driver function.*/ + + public static void main (String[] args) + { + int mat[][] = { { 1, 0, 0 }, + { 0, -1, 0 }, + { 0, 0, -1 } }; +/* Function call. If function return + true then if part will execute + otherwise else part will execute.*/ + + if (InvolutoryMatrix(mat)) + System.out.println ( ""Involutory Matrix""); + else + System.out.println ( ""Not Involutory Matrix""); + } +}"," '''Program to implement involutory matrix.''' + +N = 3; + '''Function for matrix multiplication.''' + +def multiply(mat, res): + for i in range(N): + for j in range(N): + res[i][j] = 0; + for k in range(N): + res[i][j] += mat[i][k] * mat[k][j]; + return res; + '''Function to check involutory matrix.''' + +def InvolutoryMatrix(mat): + res=[[0 for i in range(N)] + for j in range(N)]; + ''' multiply function call.''' + + res = multiply(mat, res); + for i in range(N): + for j in range(N): + if (i == j and res[i][j] != 1): + return False; + if (i != j and res[i][j] != 0): + return False; + return True; + '''Driver Code''' + +mat = [[1, 0, 0], [0, -1, 0], [0, 0, -1]]; + '''Function call. If function +return true then if part +will execute otherwise +else part will execute.''' + +if (InvolutoryMatrix(mat)): + print(""Involutory Matrix""); +else: + print(""Not Involutory Matrix"");" +Elements that occurred only once in the array,"/*Java implementation +of above approach*/ + +import java.util.*; + +class GFG +{ + +/*Function to find the elements that +appeared only once in the array*/ + +static void occurredOnce(int arr[], int n) +{ +/* Sort the array*/ + + Arrays.sort(arr); + +/* Check for first element*/ + + if (arr[0] != arr[1]) + System.out.println(arr[0] + "" ""); + +/* Check for all the elements + if it is different + its adjacent elements*/ + + for (int i = 1; i < n - 1; i++) + if (arr[i] != arr[i + 1] && + arr[i] != arr[i - 1]) + System.out.print(arr[i] + "" ""); + +/* Check for the last element*/ + + if (arr[n - 2] != arr[n - 1]) + System.out.print(arr[n - 1] + "" ""); +} + +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {7, 7, 8, 8, 9, + 1, 1, 4, 2, 2}; + int n = arr.length; + + occurredOnce(arr, n); +} +} + + +"," '''Python 3 implementation +of above approach''' + + + '''Function to find the elements +that appeared only once in +the array''' + +def occurredOnce(arr, n): + + ''' Sort the array''' + + arr.sort() + + ''' Check for first element''' + + if arr[0] != arr[1]: + print(arr[0], end = "" "") + + ''' Check for all the elements + if it is different its + adjacent elements''' + + for i in range(1, n - 1): + if (arr[i] != arr[i + 1] and + arr[i] != arr[i - 1]): + print( arr[i], end = "" "") + + ''' Check for the last element''' + + if arr[n - 2] != arr[n - 1]: + print(arr[n - 1], end = "" "") + + '''Driver code''' + +if __name__ == ""__main__"": + + arr = [ 7, 7, 8, 8, 9, + 1, 1, 4, 2, 2 ] + n = len(arr) + occurredOnce(arr, n) + + +" +Find pairs with given sum such that pair elements lie in different BSTs,"/*Java program to find pairs with given sum such +that one element of pair exists in one BST and +other in other BST.*/ + +import java.util.*; +class solution +{ +/*A binary Tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*A utility function to create a new BST node +with key as given num*/ + +static Node newNode(int num) +{ + Node temp = new Node(); + temp.data = num; + temp.left = temp.right = null; + return temp; +} +/*A utility function to insert a given key to BST*/ + +static Node insert(Node root, int key) +{ + if (root == null) + return newNode(key); + if (root.data > key) + root.left = insert(root.left, key); + else + root.right = insert(root.right, key); + return root; +} +/*store storeInorder traversal in auxiliary array*/ + +static void storeInorder(Node ptr, Vector vect) +{ + if (ptr==null) + return; + storeInorder(ptr.left, vect); + vect.add(ptr.data); + storeInorder(ptr.right, vect); +} +/*Function to find pair for given sum in different bst +vect1.get() -. stores storeInorder traversal of first bst +vect2.get() -. stores storeInorder traversal of second bst*/ + +static void pairSumUtil(Vector vect1, Vector vect2, + int sum) +{ +/* Initialize two indexes to two different corners + of two Vectors.*/ + + int left = 0; + int right = vect2.size() - 1; +/* find pair by moving two corners.*/ + + while (left < vect1.size() && right >= 0) + { +/* If we found a pair*/ + + if (vect1.get(left) + vect2.get(right) == sum) + { + System.out.print( ""("" +vect1.get(left) + "", ""+ vect2.get(right) + ""), ""); + left++; + right--; + } +/* If sum is more, move to higher value in + first Vector.*/ + + else if (vect1.get(left) + vect2.get(right) < sum) + left++; +/* If sum is less, move to lower value in + second Vector.*/ + + else + right--; + } +} +/*Prints all pairs with given ""sum"" such that one +element of pair is in tree with root1 and other +node is in tree with root2.*/ + +static void pairSum(Node root1, Node root2, int sum) +{ +/* Store inorder traversals of two BSTs in two + Vectors.*/ + + Vector vect1= new Vector(), vect2= new Vector(); + storeInorder(root1, vect1); + storeInorder(root2, vect2); +/* Now the problem reduces to finding a pair + with given sum such that one element is in + vect1 and other is in vect2.*/ + + pairSumUtil(vect1, vect2, sum); +} +/*Driver program to run the case*/ + +public static void main(String args[]) +{ +/* first BST*/ + + Node root1 = null; + root1 = insert(root1, 8); + root1 = insert(root1, 10); + root1 = insert(root1, 3); + root1 = insert(root1, 6); + root1 = insert(root1, 1); + root1 = insert(root1, 5); + root1 = insert(root1, 7); + root1 = insert(root1, 14); + root1 = insert(root1, 13); +/* second BST*/ + + Node root2 = null; + root2 = insert(root2, 5); + root2 = insert(root2, 18); + root2 = insert(root2, 2); + root2 = insert(root2, 1); + root2 = insert(root2, 3); + root2 = insert(root2, 4); + int sum = 10; + pairSum(root1, root2, sum); +} +}"," '''Python3 program to find pairs with given +sum such that one element of pair exists +in one BST and other in other BST. + ''' '''A utility function to create a new +BST node with key as given num ''' + +class newNode: + ''' Constructor to create a new node ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''A utility function to insert a +given key to BST ''' + +def insert(root, key): + if root == None: + return newNode(key) + if root.data > key: + root.left = insert(root.left, key) + else: + root.right = insert(root.right, key) + return root + '''store storeInorder traversal in +auxiliary array ''' + +def storeInorder(ptr, vect): + if ptr == None: + return + storeInorder(ptr.left, vect) + vect.append(ptr.data) + storeInorder(ptr.right, vect) + '''Function to find pair for given +sum in different bst +vect1[] --> stores storeInorder traversal + of first bst +vect2[] --> stores storeInorder traversal + of second bst ''' + +def pairSumUtil(vect1, vect2, Sum): + ''' Initialize two indexes to two + different corners of two lists. ''' + + left = 0 + right = len(vect2) - 1 + ''' find pair by moving two corners. ''' + + while left < len(vect1) and right >= 0: + ''' If we found a pair ''' + + if vect1[left] + vect2[right] == Sum: + print(""("", vect1[left], "","", + vect2[right], ""),"", end = "" "") + left += 1 + right -= 1 + ''' If sum is more, move to higher + value in first lists. ''' + + elif vect1[left] + vect2[right] < Sum: + left += 1 + ''' If sum is less, move to lower + value in second lists. ''' + + else: + right -= 1 + '''Prints all pairs with given ""sum"" such that one +element of pair is in tree with root1 and other +node is in tree with root2. ''' + +def pairSum(root1, root2, Sum): + ''' Store inorder traversals of + two BSTs in two lists. ''' + + vect1 = [] + vect2 = [] + storeInorder(root1, vect1) + storeInorder(root2, vect2) + ''' Now the problem reduces to finding a + pair with given sum such that one + element is in vect1 and other is in vect2. ''' + + pairSumUtil(vect1, vect2, Sum) + '''Driver Code''' + +if __name__ == '__main__': + ''' first BST ''' + + root1 = None + root1 = insert(root1, 8) + root1 = insert(root1, 10) + root1 = insert(root1, 3) + root1 = insert(root1, 6) + root1 = insert(root1, 1) + root1 = insert(root1, 5) + root1 = insert(root1, 7) + root1 = insert(root1, 14) + root1 = insert(root1, 13) + ''' second BST ''' + + root2 = None + root2 = insert(root2, 5) + root2 = insert(root2, 18) + root2 = insert(root2, 2) + root2 = insert(root2, 1) + root2 = insert(root2, 3) + root2 = insert(root2, 4) + Sum = 10 + pairSum(root1, root2, Sum)" +A Boolean Array Puzzle,"import java.io.*; +class GFG{ +public static void changeToZero(int a[]) +{ + a[a[1]] = a[1 - a[1]]; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int[] arr; + arr = new int[2]; + arr[0] = 1; + arr[1] = 0; + changeToZero(arr); + System.out.println(""arr[0]= "" + arr[0]); + System.out.println(""arr[1]= "" + arr[1]); +} +}","def changeToZero(a): + a[ a[1] ] = a[ not a[1] ] + return a + '''Driver code''' + +if __name__=='__main__': + a = [1, 0] + a = changeToZero(a); + print("" arr[0] = "" + str(a[0])) + print("" arr[1] = "" + str(a[1]))" +Minimum product pair an array of positive Integers,"/*Java program to calculate minimum +product of a pair*/ + +import java.util.*; + +class GFG { + +/* Function to calculate minimum product + of pair*/ + + static int printMinimumProduct(int arr[], int n) + { +/* Initialize first and second + minimums. It is assumed that the + array has at least two elements.*/ + + int first_min = Math.min(arr[0], arr[1]); + int second_min = Math.max(arr[0], arr[1]); + +/* Traverse remaining array and keep + track of two minimum elements (Note + that the two minimum elements may + be same if minimum element appears + more than once) + more than once)*/ + + for (int i = 2; i < n; i++) + { + if (arr[i] < first_min) + { + second_min = first_min; + first_min = arr[i]; + } + else if (arr[i] < second_min) + second_min = arr[i]; + } + + return first_min * second_min; + } + + /* Driver program to test above function */ + + public static void main(String[] args) + { + int a[] = { 11, 8 , 5 , 7 , 5 , 100 }; + int n = a.length; + System.out.print(printMinimumProduct(a,n)); + + } +} + + +"," '''Python program to +calculate minimum +product of a pair''' + + + '''Function to calculate +minimum product +of pair''' + +def printMinimumProduct(arr,n): + + ''' Initialize first and second + minimums. It is assumed that the + array has at least two elements.''' + + first_min = min(arr[0], arr[1]) + second_min = max(arr[0], arr[1]) + + ''' Traverse remaining array and keep + track of two minimum elements (Note + that the two minimum elements may + be same if minimum element appears + more than once) + more than once)''' + + for i in range(2,n): + + if (arr[i] < first_min): + + second_min = first_min + first_min = arr[i] + + elif (arr[i] < second_min): + second_min = arr[i] + + return first_min * second_min + + '''Driver code''' + + +a= [ 11, 8 , 5 , 7 , 5 , 100 ] +n = len(a) + +print(printMinimumProduct(a,n)) + + +" +Count 1's in a sorted binary array,"/*package whatever */ +import java.io.*; + +class GFG +{ + + /* Returns counts of 1's in arr[low..high]. The array is + assumed to be sorted in non-increasing order */ + + +static int countOnes(int arr[], int n) +{ + int ans; + int low = 0, high = n - 1; +/*get the middle index*/ + +while (low <= high) { + int mid = (low + high) / 2; + /* else recur for left side*/ + + if (arr[mid] < 1) + high = mid - 1; + +/* If element is not last 1, recur for right side*/ + + else if (arr[mid] > 1) + low = mid + 1; + else + +/* check if the element at middle index is last 1*/ + + { + if (mid == n - 1 || arr[mid + 1] != 1) + return mid + 1; + else + low = mid + 1; + } + } + return 0; +} + +/* Driver code*/ + + public static void main (String[] args) { + + int arr[] = { 1, 1, 1, 1, 0, 0, 0 }; + int n = arr.length; + + System.out.println(""Count of 1's in given array is ""+ countOnes(arr, n)); + } +} + + +", +Query for ancestor-descendant relationship in a tree,"/*Java program to query whether two node has +ancestor-descendant relationship or not*/ + +import java.util.Vector; +class GFG +{ + static int cnt; +/* Utility dfs method to assign in and out time + to each node*/ + + static void dfs(Vector []g, int u, int parent, + int []timeIn, int []timeOut) + { +/* Assign In-time to node u*/ + + timeIn[u] = cnt++; +/* Call dfs over all neighbors except parent*/ + + for(int i = 0; i < g[u].size(); i++) + { + int v = g[u].get(i); + if (v != parent) + dfs(g, v, u, timeIn, timeOut); + } +/* Assign Out-time to node u*/ + + timeOut[u] = cnt++; + } +/* Method to preprocess all nodes for assigning time*/ + + static void preProcess(int [][]edges, int V, + int []timeIn, int []timeOut) + { + @SuppressWarnings(""unchecked"") + Vector []g = new Vector[V]; + for (int i = 0; i < g.length; i++) + g[i] = new Vector(); +/* Conarray of vector data structure + for tree*/ + + for(int i = 0; i < V - 1; i++) + { + int u = edges[i][0]; + int v = edges[i][1]; + g[u].add(v); + g[v].add(u); + } + cnt = 0; +/* Call dfs method from root*/ + + dfs(g, 0, -1, timeIn, timeOut); + } +/* Method returns ""yes"" if u is a ancestor + node of v*/ + + static String isAncestor(int u, int v, int []timeIn, + int []timeOut) + { + boolean b = (timeIn[u] <= timeIn[v] && + timeOut[v] <= timeOut[u]); + return (b ? ""yes"" : ""no""); + } +/* Driver code */ + + public static void main(String[] args) + { + int edges[][] = { { 0, 1 }, + { 0, 2 }, + { 1, 3 }, + { 1, 4 }, + { 2, 5 }, + { 4, 6 }, + { 5, 7 } }; + int E = edges.length; + int V = E + 1; + int []timeIn = new int[V]; + int []timeOut = new int[V]; + preProcess(edges, V, timeIn, timeOut); + int u = 1; + int v = 6; + System.out.println(isAncestor(u, v, timeIn, + timeOut)); + u = 1; + v = 7; + System.out.println(isAncestor(u, v, timeIn, + timeOut)); + } +}"," '''Python program to query whether two node has +ancestor-descendant relationship or not''' + +cnt = 0 + '''Utility dfs method to assign in and out time +to each node''' + +def dfs(g: list, u: int, parent: int, timeIn: list, timeOut: list): + global cnt + ''' assign In-time to node u''' + + timeIn[u] = cnt + cnt += 1 + ''' call dfs over all neighbors except parent''' + + for i in range(len(g[u])): + v = g[u][i] + if v != parent: + dfs(g, v, u, timeIn, timeOut) + ''' assign Out-time to node u''' + + timeOut[u] = cnt + cnt += 1 + '''method to preprocess all nodes for assigning time''' + +def preProcess(edges: list, V: int, timeIn: list, timeOut: list): + global cnt + g = [[] for i in range(V)] + ''' construct array of vector data structure + for tree''' + + for i in range(V - 1): + u = edges[i][0] + v = edges[i][1] + g[u].append(v) + g[v].append(u) + cnt = 0 + ''' call dfs method from root''' + + dfs(g, 0, -1, timeIn, timeOut) + '''method returns ""yes"" if u is a ancestor +node of v''' + +def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str: + b = timeIn[u] <= timeIn[u] and timeOut[v] <= timeOut[u] + return ""yes"" if b else ""no"" + '''Driver Code''' + +if __name__ == ""__main__"": + edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (4, 6), (5, 7)] + E = len(edges) + V = E + 1 + timeIn = [0] * V + timeOut = [0] * V + preProcess(edges, V, timeIn, timeOut) + u = 1 + v = 6 + print(isAncestor(u, v, timeIn, timeOut)) + u = 1 + v = 7 + print(isAncestor(u, v, timeIn, timeOut))" +Program to check if a matrix is symmetric,"/*Simple java code for check a matrix is +symmetric or not.*/ + +import java.io.*; +class GFG { + static int MAX = 100; +/*Fills transpose of mat[N][N] in tr[N][N]*/ + + static void transpose(int mat[][], int tr[][], int N) +{ + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + tr[i][j] = mat[j][i]; +} +/*Returns true if mat[N][N] is symmetric, else false*/ + + static boolean isSymmetric(int mat[][], int N) +{ + int tr[][] = new int[N][MAX]; + transpose(mat, tr, N); + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + if (mat[i][j] != tr[i][j]) + return false; + return true; +} +/*Driver code*/ + + public static void main (String[] args) + { + int mat[][] = { { 1, 3, 5 }, + { 3, 2, 4 }, + { 5, 4, 1 } }; + if (isSymmetric(mat, 3)) + System.out.println( ""Yes""); + else + System.out.println ( ""No""); + } +}"," '''Simple Python code for check a matrix is +symmetric or not. + ''' '''Fills transpose of mat[N][N] in tr[N][N]''' + +def transpose(mat, tr, N): + for i in range(N): + for j in range(N): + tr[i][j] = mat[j][i] + '''Returns true if mat[N][N] is symmetric, else false''' + +def isSymmetric(mat, N): + tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ] + transpose(mat, tr, N) + for i in range(N): + for j in range(N): + if (mat[i][j] != tr[i][j]): + return False + return True + '''Driver code''' + +mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ] +if (isSymmetric(mat, 3)): + print ""Yes"" +else: + print ""No""" +Print all nodes that are at distance k from a leaf node,"/*Java program to print all nodes at a distance k from leaf +A binary tree node*/ + +class Node { + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree { + Node root; + + /* 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 */ + + void kDistantFromLeafUtil(Node node, int path[], boolean visited[], + int pathLen, int k) + { +/* Base case*/ + + if (node == null) + return; + + /* append this Node to the path array */ + + path[pathLen] = node.data; + visited[pathLen] = false; + pathLen++; + + /* it's a leaf, so print the ancestor at distance k only + if the ancestor is not already printed */ + + if (node.left == null && node.right == null + && pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false) { + System.out.print(path[pathLen - k - 1] + "" ""); + visited[pathLen - k - 1] = true; + return; + } + + /* If not leaf node, recur for left and right subtrees */ + + kDistantFromLeafUtil(node.left, path, visited, pathLen, k); + kDistantFromLeafUtil(node.right, path, visited, pathLen, k); + } + + /* Given a binary tree and a nuber k, print all nodes that are k + distant from a leaf*/ + + void printKDistantfromLeaf(Node node, int k) + { + int path[] = new int[1000]; + boolean visited[] = new boolean[1000]; + kDistantFromLeafUtil(node, path, visited, 0, k); + } + +/* Driver program to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + + /* Let us construct the tree shown in above diagram */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.right.left.right = new Node(8); + + System.out.println("" Nodes at distance 2 are :""); + tree.printKDistantfromLeaf(tree.root, 2); + } +} + + +"," '''utility that allocates a new Node with +the given key''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + + '''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''' + +def kDistantFromLeafUtil(node, path, visited, + pathLen, k): + + ''' Base case''' + + if (node == None): + return + + ''' append this Node to the path array''' + + path[pathLen] = node.key + visited[pathLen] = False + pathLen += 1 + + ''' it's a leaf, so print the ancestor at + distance k only if the ancestor is + not already printed''' + + if (node.left == None and node.right == None and + pathLen - k - 1 >= 0 and + visited[pathLen - k - 1] == False): + print(path[pathLen - k - 1], end = "" "") + visited[pathLen - k - 1] = True + return + + ''' If not leaf node, recur for left + and right subtrees''' + + kDistantFromLeafUtil(node.left, path, + visited, pathLen, k) + kDistantFromLeafUtil(node.right, path, + visited, pathLen, k) + + '''Given a binary tree and a nuber k, +print all nodes that are k distant from a leaf''' + +def printKDistantfromLeaf(node, k): + global MAX_HEIGHT + path = [None] * MAX_HEIGHT + visited = [False] * MAX_HEIGHT + kDistantFromLeafUtil(node, path, visited, 0, k) + + '''Driver Code''' + +MAX_HEIGHT = 10000 + + '''Let us create binary tree given in +the above example''' + +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) + +print(""Nodes at distance 2 are:"", end = "" "") +printKDistantfromLeaf(root, 2) + + +" +Sorting all array elements except one,"/*Java program to sort all elements except +element at index k.*/ + +import java.util.Arrays; + +class GFG { + + static int sortExceptK(int arr[], int k, int n) + { + +/* Move k-th element to end*/ + + int temp = arr[k]; + arr[k] = arr[n-1]; + arr[n-1] = temp; + +/* Sort all elements except last*/ + + Arrays.sort(arr, 0, n-1); + +/* Store last element (originally k-th)*/ + + int last = arr[n-1]; + +/* Move all elements from k-th to one + position ahead.*/ + + for (int i = n-1; i > k; i--) + arr[i] = arr[i-1]; + +/* Restore k-th element*/ + + arr[k] = last; + return 0; + } + +/* Driver code*/ + + public static void main (String[] args) + { + int a[] = {10, 4, 11, 7, 6, 20 }; + int k = 2; + int n = a.length; + + sortExceptK(a, k, n); + + for (int i = 0; i < n; i++) + System.out.print(a[i] + "" ""); + } +} + + +"," '''Python3 program to sort all elements except +element at index k.''' + +def sortExcept(arr, k, n): + + ''' Move k-th element to end''' + + arr[k], arr[-1] = arr[-1], arr[k] + + ''' Sort all elements except last''' + + arr = sorted(arr, key = lambda i: (i is arr[-1], i)) + + ''' Store last element (originally k-th)''' + + last = arr[-1] + + ''' Move all elements from k-th to one + position ahead.''' + + i = n - 1 + while i > k: + arr[i] = arr[i - 1] + i -= 1 + + ''' Restore k-th element''' + + arr[k] = last + return arr + + '''Driver code''' + +if __name__ == '__main__': + a = [10, 4, 11, 7, 6, 20] + k = 2 + n = len(a) + a = sortExcept(a, k, n) + print("" "".join(list(map(str, a)))) + + +" +Count pairs with given sum,"/* Java implementation of simple method to find count of +pairs with given sum*/ + +import java.util.HashMap; +class Test { + static int arr[] = new int[] { 1, 5, 7, -1, 5 }; +/* Returns number of pairs in arr[0..n-1] with sum equal + to 'sum'*/ + + static int getPairsCount(int n, int sum) + { + HashMap hm = new HashMap<>(); +/* Store counts of all elements in map hm*/ + + for (int i = 0; i < n; i++) { +/* initializing value to 0, if key not found*/ + + if (!hm.containsKey(arr[i])) + hm.put(arr[i], 0); + hm.put(arr[i], hm.get(arr[i]) + 1); + } + int twice_count = 0; +/* iterate through each element and increment the + count (Notice that every pair is counted twice)*/ + + for (int i = 0; i < n; i++) { + if (hm.get(sum - arr[i]) != null) + twice_count += hm.get(sum - arr[i]); +/* if (arr[i], arr[i]) pair satisfies the + condition, then we need to ensure that the + count is decreased by one such that the + (arr[i], arr[i]) pair is not considered*/ + + if (sum - arr[i] == arr[i]) + twice_count--; + } +/* return the half of twice_count*/ + + return twice_count / 2; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + int sum = 6; + System.out.println( + ""Count of pairs is "" + + getPairsCount(arr.length, sum)); + } +}"," '''Python 3 implementation of simple method +to find count of pairs with given sum.''' + +import sys + '''Returns number of pairs in arr[0..n-1] +with sum equal to 'sum''' + ''' +def getPairsCount(arr, n, sum): + m = [0] * 1000 + ''' Store counts of all elements in map m''' + + for i in range(0, n): + + ''' initializing value to 0, if key not found''' + + m[arr[i]] += 1 + twice_count = 0 ''' Iterate through each element and increment + the count (Notice that every pair is + counted twice)''' + + for i in range(0, n): + twice_count += m[sum - arr[i]] + ''' if (arr[i], arr[i]) pair satisfies the + condition, then we need to ensure that + the count is decreased by one such + that the (arr[i], arr[i]) pair is not + considered''' + + if (sum - arr[i] == arr[i]): + twice_count -= 1 + ''' return the half of twice_count''' + + return int(twice_count / 2) + '''Driver function''' + +arr = [1, 5, 7, -1, 5] +n = len(arr) +sum = 6 +print(""Count of pairs is"", getPairsCount(arr, + n, sum))" +Binary Search Tree insert with Parent Pointer,"/*Java program to demonstrate insert operation +in binary search tree with parent pointer*/ + +class GfG { +/*Node structure*/ + +static class Node +{ + int key; + Node left, right, parent; +} +/*A utility function to create a new BST Node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.key = item; + temp.left = null; + temp.right = null; + temp.parent = null; + return temp; +} +/*A utility function to do inorder traversal of BST*/ + +static void inorder(Node root) +{ + if (root != null) + { + inorder(root.left); + System.out.print(""Node : ""+ root.key + "" , ""); + if (root.parent == null) + System.out.println(""Parent : NULL""); + else + System.out.println(""Parent : "" + root.parent.key); + inorder(root.right); + } +} +/* A utility function to insert a new Node with +given key in BST */ + +static Node insert(Node node, int key) +{ + /* If the tree is empty, return a new Node */ + + if (node == null) return newNode(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + { + Node lchild = insert(node.left, key); + node.left = lchild; +/* Set parent of root of left subtree*/ + + lchild.parent = node; + } + else if (key > node.key) + { + Node rchild = insert(node.right, key); + node.right = rchild; +/* Set parent of root of right subtree*/ + + rchild.parent = node; + } + /* return the (unchanged) Node pointer */ + + return node; +} +/*Driver Program to test above functions*/ + +public static void main(String[] args) +{ + /* Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80 */ + + Node root = null; + root = insert(root, 50); + insert(root, 30); + insert(root, 20); + insert(root, 40); + insert(root, 70); + insert(root, 60); + insert(root, 80); +/* print iNoder traversal of the BST*/ + + inorder(root); +} +}"," '''Python3 program to demonstrate insert operation +in binary search tree with parent pointer''' + + '''A utility function to create a new BST Node''' + +class newNode: + def __init__(self, item): + self.key = item + self.left = self.right = None + self.parent = None '''A utility function to do inorder +traversal of BST''' + +def inorder(root): + if root != None: + inorder(root.left) + print(""Node :"", root.key, "", "", end = """") + if root.parent == None: + print(""Parent : NULL"") + else: + print(""Parent : "", root.parent.key) + inorder(root.right) + '''A utility function to insert a new +Node with given key in BST''' + +def insert(node, key): + ''' If the tree is empty, return a new Node''' + + if node == None: + return newNode(key) + ''' Otherwise, recur down the tree''' + + if key < node.key: + lchild = insert(node.left, key) + node.left = lchild + ''' Set parent of root of left subtree''' + + lchild.parent = node + elif key > node.key: + rchild = insert(node.right, key) + node.right = rchild + ''' Set parent of root of right subtree''' + + rchild.parent = node + ''' return the (unchanged) Node pointer''' + + return node + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80''' + + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + ''' print iNoder traversal of the BST''' + + inorder(root)" +Check if any two intervals intersects among a given set of intervals,"/*A Java program to check if any two intervals overlap*/ + +class GFG +{ + +/*An interval has start time and end time*/ + +static class Interval +{ + int start; + int end; + public Interval(int start, int end) + { + super(); + this.start = start; + this.end = end; + } +}; + +/*Function to check if any two intervals overlap*/ + +static boolean isIntersect(Interval arr[], int n) +{ + + int max_ele = 0; + +/* Find the overall maximum element*/ + + for (int i = 0; i < n; i++) + { + if (max_ele < arr[i].end) + max_ele = arr[i].end; + } + +/* Initialize an array of size max_ele*/ + + int []aux = new int[max_ele + 1]; + for (int i = 0; i < n; i++) + { + +/* starting point of the interval*/ + + int x = arr[i].start; + +/* end point of the interval*/ + + int y = arr[i].end; + aux[x]++; + aux[y ]--; + } + for (int i = 1; i <= max_ele; i++) + { +/* Calculating the prefix Sum*/ + + aux[i] += aux[i - 1]; + +/* Overlap*/ + + if (aux[i] > 1) + return true; + } + +/* If we reach here, then no Overlap*/ + + return false; +} + +/*Driver program*/ + +public static void main(String[] args) +{ + Interval arr1[] = { new Interval(1, 3), new Interval(7, 9), + new Interval(4, 6), new Interval(10, 13) }; + int n1 = arr1.length; + + if(isIntersect(arr1, n1)) + System.out.print(""Yes\n""); + else + System.out.print(""No\n""); + + Interval arr2[] = { new Interval(6, 8), new Interval(1, 3), + new Interval(2, 4), new Interval(4, 7) }; + int n2 = arr2.length; + if(isIntersect(arr2, n2)) + System.out.print(""Yes\n""); + else + System.out.print(""No\n""); +} +} + + +", +Maximum difference between frequency of two elements such that element having greater frequency is also greater,"/*Efficient Java program to find maximum +difference between frequency of any two +elements such that element with greater +frequency is also greater in value.*/ + +import java.util.*; +class GFG +{ +/* Return the maximum difference between + frequencies of any two elements such that + element with greater frequency is also + greater in value.*/ + + static int maxdiff(int arr[], int n) + { + HashMap freq= new HashMap<>(); + int []dist = new int[n]; +/* Finding the frequency of each element.*/ + + int j = 0; + for (int i = 0; i < n; i++) + { + dist[j++] = arr[i]; + if (!freq.containsKey(arr[i])) + freq.put(arr[i], 1); + else + freq.put(arr[i], freq.get(arr[i]) + 1); + } +/* Sorting the distinct element*/ + + Arrays.sort(dist); + int min_freq = n + 1; +/* Iterate through all sorted distinct elements. + For each distinct element, maintaining the + element with minimum frequency than that + element and also finding the maximum + frequency difference*/ + + int ans = 0; + for (int i = 0; i < j; i++) + { + int cur_freq = freq.get(dist[i]); + ans = Math.max(ans, cur_freq - min_freq); + min_freq = Math.min(min_freq, cur_freq); + } + return ans; + } +/* Driven Program*/ + + public static void main(String[] args) + { + int arr[] = { 3, 1, 3, 2, 3, 2 }; + int n = arr.length; + System.out.print(maxdiff(arr, n) +""\n""); + } +}"," '''Efficient Python3 program to find maximum +difference between frequency of any two +elements such that element with greater +frequency is also greater in value. + ''' '''Return the maximum difference between +frequencies of any two elements such that +element with greater frequency is also +greater in value.''' + +def maxdiff(arr, n): + freq = {} + dist = [0] * n + ''' Finding the frequency of each element.''' + + j = 0 + for i in range(n): + if (arr[i] not in freq): + dist[j] = arr[i] + j += 1 + freq[arr[i]] = 0 + if (arr[i] in freq): + freq[arr[i]] += 1 + dist = dist[:j] + ''' Sorting the distinct element''' + + dist.sort() + min_freq = n + 1 + ''' Iterate through all sorted distinct elements. + For each distinct element, maintaining the + element with minimum frequency than that + element and also finding the maximum + frequency difference''' + + ans = 0 + for i in range(j): + cur_freq = freq[dist[i]] + ans = max(ans, cur_freq - min_freq) + min_freq = min(min_freq, cur_freq) + return ans + '''Driven Program''' + +arr = [3, 1, 3, 2, 3, 2] +n = len(arr) +print(maxdiff(arr, n))" +Find minimum number of coins that make a given value,"/*A Naive recursive JAVA program to find minimum of coins +to make a given change V*/ + +class coin +{ +/* m is size of coins array (number of different coins)*/ + + static int minCoins(int coins[], int m, int V) + { +/* base case*/ + + if (V == 0) return 0; +/* Initialize result*/ + + int res = Integer.MAX_VALUE; +/* Try every coin that has smaller value than V*/ + + for (int i=0; i q = new LinkedList(); + int nc, max; +/* push root to the queue 'q'*/ + + q.add(root); + while (true) + { +/* node count for the current level*/ + + nc = q.size(); +/* if true then all the nodes of + the tree have been traversed*/ + + if (nc == 0) + break; +/* maximum element for the current + level*/ + + max = Integer.MIN_VALUE; + while (nc != 0) + { +/* get the front element from 'q'*/ + + Node front = q.peek(); +/* remove front element from 'q'*/ + + q.remove(); +/* if true, then update 'max'*/ + + if (max < front.data) + max = front.data; +/* if left child exists*/ + + if (front.left != null) + q.add(front.left); +/* if right child exists*/ + + if (front.right != null) + q.add(front.right); + nc--; + } +/* print maximum element of + current level*/ + + System.out.println(max + "" ""); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + /* Construct a Binary Tree + 4 + / \ + 9 2 + / \ \ + 3 5 7 */ + + Node root = null; + root = newNode(4); + root.left = newNode(9); + root.right = newNode(2); + root.left.left = newNode(3); + root.left.right = newNode(5); + root.right.right = newNode(7); +/* Function call*/ + + largestValueInEachLevel(root); + } +}"," '''Python program to print largest value +on each level of binary tree''' + +INT_MIN = -2147483648 + '''Helper function that allocates a new +node with the given data and None left +and right pointers.''' + +class newNode: + def __init__(self, data): + ''' put in the data''' + + self.data = data + self.left = None + self.right = None '''function to find largest values''' + +def largestValueInEachLevel(root): + + ''' if tree is empty''' + + if (not root): + return + q = [] + nc = 10 + max = 0 + ''' push root to the queue 'q' ''' + + q.append(root) + while (1): ''' node count for the current level''' + + nc = len(q) + ''' if true then all the nodes of + the tree have been traversed''' + + if (nc == 0): + break + ''' maximum element for the current + level''' + + max = INT_MIN + while (nc): + ''' get the front element from 'q''' + ''' + front = q[0] + ''' remove front element from 'q''' + ''' + q = q[1:] + ''' if true, then update 'max''' + ''' + if (max < front.data): + max = front.data + ''' if left child exists''' + + if (front.left): + q.append(front.left) + ''' if right child exists''' + + if (front.right != None): + q.append(front.right) + nc -= 1 + ''' print maximum element of + current level''' + + print(max, end="" "") + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us construct the following Tree + 4 + / \ + 9 2 + / \ \ + 3 5 7 ''' + + root = newNode(4) + root.left = newNode(9) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.right = newNode(7) + ''' Function call''' + + largestValueInEachLevel(root) +" +Find sum of all elements in a matrix except the elements in row and/or column of given cell?,"/*An efficient Java program to compute +sum for given array of cell indexes*/ + +class GFG +{ +static int R = 3; +static int C = 3; +/*A structure to represent a cell index*/ + +static class Cell +{ +/*r is row, varies from 0 to R-1*/ + +int r; +/*c is column, varies from 0 to C-1*/ + +int c; + public Cell(int r, int c) + { + this.r = r; + this.c = c; + } +}; +static void printSums(int mat[][], + Cell arr[], int n) +{ + int sum = 0; + int []row = new int[R]; + int []col = new int[C]; +/* Compute sum of all elements, + sum of every row and sum every column*/ + + for (int i = 0; i < R; i++) + { + for (int j = 0; j < C; j++) + { + sum += mat[i][j]; + col[j] += mat[i][j]; + row[i] += mat[i][j]; + } + } +/* Compute the desired sum + for all given cell indexes*/ + + for (int i = 0; i < n; i++) + { + int ro = arr[i].r, co = arr[i].c; + System.out.println(sum - row[ro] - col[co] + + mat[ro][co]); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int mat[][] = {{1, 1, 2}, + {3, 4, 6}, + {5, 3, 2}}; + Cell arr[] = {new Cell(0, 0), + new Cell(1, 1), + new Cell(0, 1)}; + int n = arr.length; + printSums(mat, arr, n); +} +}"," '''Python3 implementation of the approach +A structure to represent a cell index''' + +class Cell: + def __init__(self, r, c): + '''r is row, varies from 0 to R-1''' + + self.r = r + + '''c is column, varies from 0 to C-1''' + + self.c = c +def printSums(mat, arr, n): + Sum = 0 + row, col = [0] * R, [0] * C + ''' Compute sum of all elements, + sum of every row and sum every column''' + + for i in range(0, R): + for j in range(0, C): + Sum += mat[i][j] + row[i] += mat[i][j] + col[j] += mat[i][j] + ''' Compute the desired sum + for all given cell indexes''' + + for i in range(0, n): + r0, c0 = arr[i].r, arr[i].c + print(Sum - row[r0] - col[c0] + mat[r0][c0]) + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] + R = C = 3 + arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] + n = len(arr) + printSums(mat, arr, n)" +Count rotations divisible by 8,"/*Java program to count all +rotations divisible by 8*/ + +import java.io.*; + +class GFG +{ +/* function to count of all + rotations divisible by 8*/ + + static int countRotationsDivBy8(String n) + { + int len = n.length(); + int count = 0; + +/* For single digit number*/ + + if (len == 1) { + int oneDigit = n.charAt(0) - '0'; + if (oneDigit % 8 == 0) + return 1; + return 0; + } + +/* For two-digit numbers + (considering all pairs)*/ + + if (len == 2) { + +/* first pair*/ + + int first = (n.charAt(0) - '0') * + 10 + (n.charAt(1) - '0'); + +/* second pair*/ + + int second = (n.charAt(1) - '0') * + 10 + (n.charAt(0) - '0'); + + if (first % 8 == 0) + count++; + if (second % 8 == 0) + count++; + return count; + } + +/* considering all three-digit sequences*/ + + int threeDigit; + for (int i = 0; i < (len - 2); i++) + { + threeDigit = (n.charAt(i) - '0') * 100 + + (n.charAt(i + 1) - '0') * 10 + + (n.charAt(i + 2) - '0'); + if (threeDigit % 8 == 0) + count++; + } + +/* Considering the number formed by the + last digit and the first two digits*/ + + threeDigit = (n.charAt(len - 1) - '0') * 100 + + (n.charAt(0) - '0') * 10 + + (n.charAt(1) - '0'); + + if (threeDigit % 8 == 0) + count++; + +/* Considering the number formed by the last + two digits and the first digit*/ + + threeDigit = (n.charAt(len - 2) - '0') * 100 + + (n.charAt(len - 1) - '0') * 10 + + (n.charAt(0) - '0'); + if (threeDigit % 8 == 0) + count++; + +/* required count of rotations*/ + + return count; + } + +/* Driver program*/ + + public static void main (String[] args) + { + String n = ""43262488612""; + System.out.println( ""Rotations: "" + +countRotationsDivBy8(n)); + + } +} + + +"," '''Python3 program to count all +rotations divisible by 8''' + + + '''function to count of all +rotations divisible by 8''' + +def countRotationsDivBy8(n): + l = len(n) + count = 0 + + ''' For single digit number''' + + if (l == 1): + oneDigit = int(n[0]) + if (oneDigit % 8 == 0): + return 1 + return 0 + + ''' For two-digit numbers + (considering all pairs)''' + + if (l == 2): + + ''' first pair''' + + first = int(n[0]) * 10 + int(n[1]) + + ''' second pair''' + + second = int(n[1]) * 10 + int(n[0]) + + if (first % 8 == 0): + count+=1 + if (second % 8 == 0): + count+=1 + return count + + ''' considering all + three-digit sequences''' + + threeDigit=0 + for i in range(0,(l - 2)): + threeDigit = (int(n[i]) * 100 + + int(n[i + 1]) * 10 + + int(n[i + 2])) + if (threeDigit % 8 == 0): + count+=1 + + ''' Considering the number + formed by the last digit + and the first two digits''' + + threeDigit = (int(n[l - 1]) * 100 + + int(n[0]) * 10 + + int(n[1])) + + if (threeDigit % 8 == 0): + count+=1 + + ''' Considering the number + formed by the last two + digits and the first digit''' + + threeDigit = (int(n[l - 2]) * 100 + + int(n[l - 1]) * 10 + + int(n[0])) + if (threeDigit % 8 == 0): + count+=1 + + ''' required count + of rotations''' + + return count + + + '''Driver Code''' + +if __name__=='__main__': + n = ""43262488612"" + print(""Rotations:"",countRotationsDivBy8(n)) + + +" +Reverse individual words,"/*Java program to reverse individual +words in a given string using STL list*/ + +import java.io.*; +import java.util.*; +class GFG { +/*reverses individual words of a string*/ + +static void reverseWords(String str) +{ + Stack st=new Stack(); +/* Traverse given string and push all + characters to stack until we see a space.*/ + + for (int i = 0; i < str.length(); ++i) { + if (str.charAt(i) != ' ') + st.push(str.charAt(i)); +/* When we see a space, we print + contents of stack.*/ + + else { + while (st.empty() == false) { + System.out.print(st.pop()); + } + System.out.print("" ""); + } + } +/* Since there may not be space after + last word.*/ + + while (st.empty() == false) { + System.out.print(st.pop()); + } +} +/*Driver program to test above function*/ + +public static void main(String[] args) +{ + String str = ""Geeks for Geeks""; + reverseWords(str); + } +}"," '''Python3 program to reverse individual words +in a given string using STL list + ''' '''reverses individual words of a string''' + +def reverserWords(string): + st = list() + ''' Traverse given string and push all characters + to stack until we see a space.''' + + for i in range(len(string)): + if string[i] != "" "": + st.append(string[i]) + ''' When we see a space, we print + contents of stack.''' + + else: + while len(st) > 0: + print(st[-1], end= """") + st.pop() + print(end = "" "") + ''' Since there may not be space after + last word.''' + + while len(st) > 0: + print(st[-1], end = """") + st.pop() + '''Driver Code''' + +if __name__ == ""__main__"": + string = ""Geeks for Geeks"" + reverserWords(string)" +Number of full binary trees such that each node is product of its children,"/*Java program to find number of full +binary tree such that each node is +product of its children.*/ + +import java.util.Arrays; +class GFG { +/* Return the number of all possible + full binary tree with given product + property.*/ + + static int numoffbt(int arr[], int n) + { +/* Finding the minimum and maximum + values in given array.*/ + + int maxvalue = -2147483647; + int minvalue = 2147483647; + for (int i = 0; i < n; i++) + { + maxvalue = Math.max(maxvalue, arr[i]); + minvalue = Math.min(minvalue, arr[i]); + } + int mark[] = new int[maxvalue + 2]; + int value[] = new int[maxvalue + 2]; + Arrays.fill(mark, 0); + Arrays.fill(value, 0); +/* Marking the presence of each array element + and initialising the number of possible + full binary tree for each integer equal + to 1 because single node will also + contribute as a full binary tree.*/ + + for (int i = 0; i < n; i++) + { + mark[arr[i]] = 1; + value[arr[i]] = 1; + } +/* From minimum value to maximum value of array + finding the number of all possible Full + Binary Trees.*/ + + int ans = 0; + for (int i = minvalue; i <= maxvalue; i++) + { +/* Find if value present in the array*/ + + if (mark[i] != 0) + { +/* For each multiple of i, less than + equal to maximum value of array*/ + + for (int j = i + i; + j <= maxvalue && j/i <= i; j += i) + { +/* If multiple is not present in + the array then continue.*/ + + if (mark[j] == 0) + continue; +/* Finding the number of possible + Full binary trees for multiple + j by multiplying number of + possible Full binary tree from + the number i and number of + possible Full binary tree from i/j.*/ + + value[j] = value[j] + (value[i] + * value[j/i]); +/* Condition for possiblity when + left chid became right child + and vice versa.*/ + + if (i != j / i) + value[j] = value[j] + (value[i] + * value[j/i]); + } + } + ans += value[i]; + } + return ans; + } +/* driver code*/ + + public static void main (String[] args) + { + int arr[] = { 2, 3, 4, 6 }; + int n = arr.length; + System.out.print(numoffbt(arr, n)); + } +}"," '''Python3 program to find number of +full binary tree such that each node +is product of its children.''' + + '''Return the number of all possible full +binary tree with given product property.''' + +def numoffbt(arr, n): ''' Finding the minimum and maximum + values in given array.''' + + maxvalue = -2147483647 + minvalue = 2147483647 + for i in range(n): + maxvalue = max(maxvalue, arr[i]) + minvalue = min(minvalue, arr[i]) + mark = [0 for i in range(maxvalue + 2)] + value = [0 for i in range(maxvalue + 2)] + ''' Marking the presence of each array element + and initialising the number of possible + full binary tree for each integer equal + to 1 because single node will also + contribute as a full binary tree.''' + + for i in range(n): + mark[arr[i]] = 1 + value[arr[i]] = 1 + ''' From minimum value to maximum value + of array finding the number of all + possible Full Binary Trees.''' + + ans = 0 + for i in range(minvalue, maxvalue + 1): + ''' Find if value present in the array''' + + if (mark[i] != 0): + ''' For each multiple of i, less than + equal to maximum value of array''' + + j = i + i + while(j <= maxvalue and j // i <= i): + ''' If multiple is not present in the + array then continue.''' + + if (mark[j] == 0): + continue + ''' Finding the number of possible Full + binary trees for multiple j by + multiplying number of possible Full + binary tree from the number i and + number of possible Full binary tree + from i/j.''' + + value[j] = value[j] + (value[i] * value[j // i]) + ''' Condition for possiblity when left + chid became right child and vice versa.''' + + if (i != j // i): + value[j] = value[j] + (value[i] * value[j // i]) + j += i + ans += value[i] + return ans + '''Driver Code''' + +arr = [ 2, 3, 4, 6 ] +n = len(arr) +print(numoffbt(arr, n))" +Exponential Search,"/*Java program to +find an element x in a +sorted array using +Exponential search.*/ + +import java.util.Arrays; +class GFG +{ +/* Returns position of + first occurrence of + x in array*/ + + static int exponentialSearch(int arr[], + int n, int x) + { +/* If x is present at firt location itself*/ + + if (arr[0] == x) + return 0; +/* Find range for binary search by + repeated doubling*/ + + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; +/* Call binary search for the found range.*/ + + return Arrays.binarySearch(arr, i/2, + Math.min(i, n-1), x); + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = {2, 3, 4, 10, 40}; + int x = 10; + int result = exponentialSearch(arr, + arr.length, x); + System.out.println((result < 0) ? + ""Element is not present in array"" : + ""Element is present at index "" + + result); + } +}"," '''Python program to find an element x +in a sorted array using Exponential Search''' + '''Returns the position of first +occurrence of x in array''' + +def exponentialSearch(arr, n, x): + ''' IF x is present at first + location itself''' + + if arr[0] == x: + return 0 + ''' Find range for binary search + j by repeated doubling''' + + i = 1 + while i < n and arr[i] <= x: + i = i * 2 + ''' Call binary search for the found range''' + + return binarySearch( arr, i / 2, + min(i, n-1), x) + '''A recurssive binary search function returns +location of x in given array arr[l..r] is +present, otherwise -1''' + +def binarySearch( arr, l, r, x): + if r >= l: + mid = l + ( r-l ) / 2 + ''' If the element is present at + the middle itself''' + + if arr[mid] == x: + return mid + ''' If the element is smaller than mid, + then it can only be present in the + left subarray''' + + if arr[mid] > x: + return binarySearch(arr, l, + mid - 1, x) + ''' Else he element can only be + present in the right''' + + return binarySearch(arr, mid + 1, r, x) + ''' We reach here if the element is not present''' + + return -1 + '''Driver Code''' + +arr = [2, 3, 4, 10, 40] +n = len(arr) +x = 10 +result = exponentialSearch(arr, n, x) +if result == -1: + print ""Element not found in thye array"" +else: + print ""Element is present at index %d"" %(result)" +Postorder traversal of Binary Tree without recursion and without stack,"/*Java program or postorder traversal*/ + +class GFG +{ +/* A binary tree node has data, + pointer to left child + and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; + boolean visited; +} +static void postorder( Node head) +{ + Node temp = head; + while (temp != null && + temp.visited == false) + { +/* Visited left subtree*/ + + if (temp.left != null && + temp.left.visited == false) + temp = temp.left; +/* Visited right subtree*/ + + else if (temp.right != null && + temp.right.visited == false) + temp = temp.right; +/* Print node*/ + + else + { + System.out.printf(""%d "", temp.data); + temp.visited = true; + temp = head; + } + } +} +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + node.visited = false; + return (node); +} +/* Driver code*/ + +public static void main(String []args) +{ + Node root = newNode(8); + root.left = newNode(3); + root.right = newNode(10); + root.left.left = newNode(1); + root.left.right = newNode(6); + root.left.right.left = newNode(4); + root.left.right.right = newNode(7); + root.right.right = newNode(14); + root.right.right.left = newNode(13); + postorder(root); +} +}"," '''Python3 program or postorder traversal ''' + + '''A Binary Tree Node +Utility function to create a +new tree node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.visited = False +def postorder(head) : + temp = head + while (temp and temp.visited == False): ''' Visited left subtree''' + + if (temp.left and + temp.left.visited == False): + temp = temp.left + ''' Visited right subtree''' + + elif (temp.right and + temp.right.visited == False): + temp = temp.right + ''' Print node''' + + else: + print(temp.data, end = "" "") + temp.visited = True + temp = head + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(8) + root.left = newNode(3) + root.right = newNode(10) + root.left.left = newNode(1) + root.left.right = newNode(6) + root.left.right.left = newNode(4) + root.left.right.right = newNode(7) + root.right.right = newNode(14) + root.right.right.left = newNode(13) + postorder(root)" +"Find number of pairs (x, y) in an array such that x^y > y^x","/*Java program to finds number of pairs (x, y) +in an array such that x^y > y^x*/ + +import java.util.Arrays; +class Test { +/* Function to return count of pairs with x as one + element of the pair. It mainly looks for all values + in Y[] where x ^ Y[i] > Y[i] ^ x*/ + + static int count(int x, int Y[], int n, int NoOfY[]) + { +/* If x is 0, then there cannot be any value in Y + such that x^Y[i] > Y[i]^x*/ + + if (x == 0) + return 0; +/* If x is 1, then the number of pais is equal to + number of zeroes in Y[]*/ + + if (x == 1) + return NoOfY[0]; +/* Find number of elements in Y[] with values + greater than x getting upperbound of x with + binary search*/ + + int idx = Arrays.binarySearch(Y, x); + int ans; + if (idx < 0) { + idx = Math.abs(idx + 1); + ans = Y.length - idx; + } + else { + while (idx < n && Y[idx] == x) { + idx++; + } + ans = Y.length - idx; + } +/* If we have reached here, then x must be greater + than 1, increase number of pairs for y=0 and y=1*/ + + ans += (NoOfY[0] + NoOfY[1]); +/* Decrease number of pairs for x=2 and (y=4 or y=3)*/ + + if (x == 2) + ans -= (NoOfY[3] + NoOfY[4]); +/* Increase number of pairs for x=3 and y=2*/ + + if (x == 3) + ans += NoOfY[2]; + return ans; + } +/* Function to returns count of pairs (x, y) such that + x belongs to X[], y belongs to Y[] and x^y > y^x*/ + + static long countPairs(int X[], int Y[], int m, int n) + { +/* To store counts of 0, 1, 2, 3 and 4 in array Y*/ + + int NoOfY[] = new int[5]; + for (int i = 0; i < n; i++) + if (Y[i] < 5) + NoOfY[Y[i]]++; +/* Sort Y[] so that we can do binary search in it*/ + + Arrays.sort(Y); +/*Initialize result*/ + +long total_pairs = 0; +/* Take every element of X and count pairs with it*/ + + for (int i = 0; i < m; i++) + total_pairs += count(X[i], Y, n, NoOfY); + return total_pairs; + } +/* Driver method*/ + + public static void main(String args[]) + { + int X[] = { 2, 1, 6 }; + int Y[] = { 1, 5 }; + System.out.println( + ""Total pairs = "" + + countPairs(X, Y, X.length, Y.length)); + } +}"," '''Python3 program to find the number +of pairs (x, y) in an array +such that x^y > y^x''' + +import bisect + '''Function to return count of pairs +with x as one element of the pair. +It mainly looks for all values in Y +where x ^ Y[i] > Y[i] ^ x''' + +def count(x, Y, n, NoOfY): + ''' If x is 0, then there cannot be + any value in Y such that + x^Y[i] > Y[i]^x''' + + if x == 0: + return 0 + ''' If x is 1, then the number of pairs + is equal to number of zeroes in Y''' + + if x == 1: + return NoOfY[0] + ''' Find number of elements in Y[] with + values greater than x, bisect.bisect_right + gets address of first greater element + in Y[0..n-1]''' + + idx = bisect.bisect_right(Y, x) + ans = n - idx + ''' If we have reached here, then x must be greater than 1, + increase number of pairs for y=0 and y=1''' + + ans += NoOfY[0] + NoOfY[1] + ''' Decrease number of pairs + for x=2 and (y=4 or y=3)''' + + if x == 2: + ans -= NoOfY[3] + NoOfY[4] + ''' Increase number of pairs + for x=3 and y=2''' + + if x == 3: + ans += NoOfY[2] + return ans + '''Function to return count of pairs (x, y) +such that x belongs to X, +y belongs to Y and x^y > y^x''' + +def count_pairs(X, Y, m, n): + ''' To store counts of 0, 1, 2, 3, + and 4 in array Y''' + + NoOfY = [0] * 5 + for i in range(n): + if Y[i] < 5: + NoOfY[Y[i]] += 1 + ''' Sort Y so that we can do binary search in it''' + + Y.sort() + '''Initialize result''' + + total_pairs = 0 + ''' Take every element of X and + count pairs with it''' + + for x in X: + total_pairs += count(x, Y, n, NoOfY) + return total_pairs + '''Driver Code''' + +if __name__ == '__main__': + X = [2, 1, 6] + Y = [1, 5] + print(""Total pairs = "", + count_pairs(X, Y, len(X), len(Y)))" +Get maximum left node in binary tree,"/*Java program to print maximum element +in left node. */ + +import java.util.*; +class GfG { +/*A Binary Tree Node */ + +static class Node { + int data; + Node left, right; +} +/*Get max of left element using +Inorder traversal */ + +static int maxOfLeftElement(Node root) +{ + int res = Integer.MIN_VALUE; + if (root == null) + return res; + if (root.left != null) + res = root.left.data; +/* Return maximum of three values + 1) Recursive max in left subtree + 2) Value in left node + 3) Recursive max in right subtree */ + + return Math.max(maxOfLeftElement(root.left), + Math.max(res, maxOfLeftElement(root.right))); +} +/*Utility function to create a new tree node */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} +/*Driver program to test above functions */ + +public static void main(String[] args) +{ +/* Let us create binary tree shown in above diagram */ + + Node root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + /* 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 */ + + System.out.println(maxOfLeftElement(root)); +} +}"," '''Python program to prmaximum element +in left node. ''' + + '''Get max of left element using +Inorder traversal ''' + +def maxOfLeftElement(root): + res = -999999999999 + if (root == None): + return res + if (root.left != None): + res = root.left.data + ''' Return maximum of three values + 1) Recursive max in left subtree + 2) Value in left node + 3) Recursive max in right subtree ''' + + return max({ maxOfLeftElement(root.left), res, + maxOfLeftElement(root.right) }) + '''Utility class to create a +new tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create binary tree shown + in above diagram ''' + + root = newNode(7) + root.left = newNode(6) + root.right = newNode(5) + root.left.left = newNode(4) + root.left.right = newNode(3) + root.right.left = newNode(2) + root.right.right = newNode(1) + ''' 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 ''' + + print(maxOfLeftElement(root))" +Connect Nodes at same Level (Level Order Traversal),"/*Connect nodes at same level using level order +traversal.*/ + +import java.util.LinkedList; +import java.util.Queue; +public class Connect_node_same_level { +/* Node class*/ + + static class Node { + int data; + Node left, right, nextRight; + Node(int data){ + this.data = data; + left = null; + right = null; + nextRight = null; + } + }; +/* Sets nextRight of all nodes of a tree*/ + + static void connect(Node root) + { + Queue q = new LinkedList(); + q.add(root); +/* null marker to represent end of current level*/ + + q.add(null); +/* Do Level order of tree using NULL markers*/ + + while (!q.isEmpty()) { + Node p = q.peek(); + q.remove(); + if (p != null) { +/* next element in queue represents next + node at current Level */ + + p.nextRight = q.peek(); +/* push left and right children of current + node*/ + + if (p.left != null) + q.add(p.left); + if (p.right != null) + q.add(p.right); + } +/* if queue is not empty, push NULL to mark + nodes at this level are visited*/ + + else if (!q.isEmpty()) + q.add(null); + } + } + /* Driver program to test above functions*/ + + public static void main(String args[]) + { + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 90 + */ + + Node root = new Node(10); + root.left = new Node(8); + root.right = new Node(2); + root.left.left = new Node(3); + root.right.right = new Node(90); +/* Populates nextRight pointer in all nodes*/ + + connect(root); +/* Let us check the values of nextRight pointers*/ + + System.out.println(""Following are populated nextRight pointers in \n"" + + ""the tree (-1 is printed if there is no nextRight)""); + System.out.println(""nextRight of ""+ root.data +"" is ""+ + ((root.nextRight != null) ? root.nextRight.data : -1)); + System.out.println(""nextRight of ""+ root.left.data+"" is ""+ + ((root.left.nextRight != null) ? root.left.nextRight.data : -1)); + System.out.println(""nextRight of ""+ root.right.data+"" is ""+ + ((root.right.nextRight != null) ? root.right.nextRight.data : -1)); + System.out.println(""nextRight of ""+ root.left.left.data+"" is ""+ + ((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1)); + System.out.println(""nextRight of ""+ root.right.right.data+"" is ""+ + ((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1)); + } +}"," '''connect nodes at same level using level order traversal''' + +import sys + + ''' Node class''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.nextRight = None + def __str__(self): + return '{}'.format(self.data) ''' set nextRight of all nodes of a tree''' + +def connect(root): + queue = [] + queue.append(root) + ''' null marker to represent end of current level''' + + queue.append(None) + ''' do level order of tree using None markers''' + + while queue: + p = queue.pop(0) + if p: + ''' next element in queue represents + next node at current level''' + + p.nextRight = queue[0] + ''' pus left and right children of current node''' + + if p.left: + queue.append(p.left) + if p.right: + queue.append(p.right) + ''' if queue is not empty, push NULL to mark + nodes at this level are visited''' + + elif queue: + queue.append(None) '''Driver program to test above functions.''' +def main(): ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 90 + ''' + + root = Node(10) + root.left = Node(8) + root.right = Node(2) + root.left.left = Node(3) + root.right.right = Node(90) + ''' Populates nextRight pointer in all nodes''' + + connect(root) + ''' Let us check the values of nextRight pointers''' + + print(""Following are populated nextRight pointers in \n"" + ""the tree (-1 is printed if there is no nextRight) \n"") + if(root.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.data,root.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.data,-1)) + if(root.left.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.left.data,root.left.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.left.data,-1)) + if(root.right.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.right.data,root.right.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.right.data,-1)) + if(root.left.left.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.left.left.data,root.left.left.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.left.left.data,-1)) + if(root.right.right.nextRight != None): + print(""nextRight of %d is %d \n"" %(root.right.right.data,root.right.right.nextRight.data)) + else: + print(""nextRight of %d is %d \n"" %(root.right.right.data,-1)) + print() +if __name__ == ""__main__"": + main() ''' print level by level''' + +def printLevelByLevel(root): + if root: + node = root + while node: + print('{}'.format(node.data), end=' ') + node = node.nextRight + print() + if root.left: + printLevelByLevel(root.left) + else: + printLevelByLevel(root.right) '''print inorder''' +def inorder(root): + if root: + inorder(root.left) + print(root.data, end=' ') + inorder(root.right) +" +Doubly Linked List | Set 1 (Introduction and Insertion),"/*Adding a node at the front of the list*/ + +public void push(int new_data) +{ + /* 1. allocate node + * 2. put in the data */ + + Node new_Node = new Node(new_data); + /* 3. Make next of new node as head and previous as NULL */ + + new_Node.next = head; + new_Node.prev = null; + /* 4. change prev of head node to new node */ + + if (head != null) + head.prev = new_Node; + /* 5. move the head to point to the new node */ + + head = new_Node; +}"," '''Adding a node at the front of the list''' + +def push(self, new_data): + ''' 1 & 2: Allocate the Node & Put in the data''' + + new_node = Node(data = new_data) + ''' 3. Make next of new node as head and previous as NULL''' + + new_node.next = self.head + new_node.prev = None + ''' 4. change prev of head node to new node''' + + if self.head is not None: + self.head.prev = new_node + ''' 5. move the head to point to the new node''' + + self.head = new_node" +K'th Largest element in BST using constant extra space,"/*Java Program for finding K-th largest Node using O(1) +extra memory and reverse Morris traversal.*/ + +class GfG +{ + +/*Node structure*/ + +static class Node +{ + int data; + Node left, right; +}/*helper function to create a new Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.right = null; + temp.left = null; + return temp; +} +static Node KthLargestUsingMorrisTraversal(Node root, int k) +{ + Node curr = root; + Node Klargest = null; +/* count variable to keep count of visited Nodes*/ + + int count = 0; + while (curr != null) + { +/* if right child is NULL*/ + + if (curr.right == null) + { +/* first increment count and check if count = k*/ + + if (++count == k) + Klargest = curr; +/* otherwise move to the left child*/ + + curr = curr.left; + } + else + { +/* find inorder successor of current Node*/ + + Node succ = curr.right; + while (succ.left != null && succ.left != curr) + succ = succ.left; + if (succ.left == null) + { +/* set left child of successor to the + current Node*/ + + succ.left = curr; +/* move current to its right*/ + + curr = curr.right; + } +/* restoring the tree back to original binary + search tree removing threaded links*/ + + else + { + succ.left = null; + if (++count == k) + Klargest = curr; +/* move current to its left child*/ + + curr = curr.left; + } + } + } + return Klargest; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Constructed binary tree is + 4 + / \ + 2 7 + / \ / \ + 1 3 6 10 */ + + Node root = newNode(4); + root.left = newNode(2); + root.right = newNode(7); + root.left.left = newNode(1); + root.left.right = newNode(3); + root.right.left = newNode(6); + root.right.right = newNode(10); + System.out.println(""Finding K-th largest Node in BST : "" + + KthLargestUsingMorrisTraversal(root, 2).data); +} +}"," '''Python3 code for finding K-th largest +Node using O(1) extra memory and +reverse Morris traversal.''' + + '''helper function to create a new Node''' + +class newNode: + def __init__(self, data): + self.data = data + self.right = self.left = None +def KthLargestUsingMorrisTraversal(root, k): + curr = root + Klargest = None ''' count variable to keep count + of visited Nodes''' + + count = 0 + while (curr != None): + ''' if right child is None''' + + if (curr.right == None): + ''' first increment count and + check if count = k''' + + count += 1 + if (count == k): + Klargest = curr + ''' otherwise move to the left child''' + + curr = curr.left + else: + ''' find inorder successor of + current Node''' + + succ = curr.right + while (succ.left != None and + succ.left != curr): + succ = succ.left + if (succ.left == None): + ''' set left child of successor + to the current Node''' + + succ.left = curr + ''' move current to its right''' + + curr = curr.right + ''' restoring the tree back to + original binary search tree + removing threaded links''' + + else: + succ.left = None + count += 1 + if (count == k): + Klargest = curr + ''' move current to its left child''' + + curr = curr.left + return Klargest + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 4 + / \ + 2 7 + / \ / \ + 1 3 6 10''' + + root = newNode(4) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(1) + root.left.right = newNode(3) + root.right.left = newNode(6) + root.right.right = newNode(10) + print(""Finding K-th largest Node in BST : "", + KthLargestUsingMorrisTraversal(root, 2).data)" +Count Strictly Increasing Subarrays,"/*Java program to count number of strictly +increasing subarrays*/ + + + +class Test +{ + static int arr[] = new int[]{1, 2, 2, 4}; + + static int countIncreasing(int n) + { +/*Initialize result*/ + +int cnt = 0; + +/* Initialize length of current increasing + subarray*/ + + int len = 1; + +/* Traverse through the array*/ + + for (int i=0; i < n-1; ++i) + { +/* If arr[i+1] is greater than arr[i], + then increment length*/ + + if (arr[i + 1] > arr[i]) + len++; + +/* Else Update count and reset length*/ + + else + { + cnt += (((len - 1) * len) / 2); + len = 1; + } + } + +/* If last length is more than 1*/ + + if (len > 1) + cnt += (((len - 1) * len) / 2); + + return cnt; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.println(""Count of strictly increasing subarrays is "" + + countIncreasing(arr.length)); + } +} +"," '''Python3 program to count number of +strictlyincreasing subarrays in O(n) time.''' + + +def countIncreasing(arr, n): + '''Initialize result''' + + cnt = 0 + + ''' Initialize length of current + increasing subarray''' + + len = 1 + + ''' Traverse through the array''' + + for i in range(0, n - 1) : + + ''' If arr[i+1] is greater than arr[i], + then increment length''' + + if arr[i + 1] > arr[i] : + len += 1 + + ''' Else Update count and reset length''' + + else: + cnt += (((len - 1) * len) / 2) + len = 1 + + ''' If last length is more than 1''' + + if len > 1: + cnt += (((len - 1) * len) / 2) + + return cnt + + + '''Driver program''' + +arr = [1, 2, 2, 4] +n = len(arr) + +print (""Count of strictly increasing subarrays is"", + int(countIncreasing(arr, n))) + + + +" +Binary Search Tree | Set 1 (Search and Insertion),"/*A utility function to search a given key in BST*/ + +public Node search(Node root, int key) +{ +/* Base Cases: root is null or key is present at root*/ + + if (root==null || root.key==key) + return root; +/* Key is greater than root's key*/ + + if (root.key < key) + return search(root.right, key); +/* Key is smaller than root's key*/ + + return search(root.left, key); +}"," '''A utility function to search a given key in BST''' + +def search(root,key): + ''' Base Cases: root is null or key is present at root''' + + if root is None or root.val == key: + return root + ''' Key is greater than root's key''' + + if root.val < key: + return search(root.right,key) + ''' Key is smaller than root's key''' + + return search(root.left,key)" +Products of ranges in an array,"/*Product in range Queries in O(N)*/ + +import java.io.*; + +class GFG +{ + +/* Function to calculate + Product in the given range.*/ + + static int calculateProduct(int []A, int L, + int R, int P) + { + +/* As our array is 0 based as + and L and R are given as 1 + based index.*/ + + L = L - 1; + R = R - 1; + + int ans = 1; + for (int i = L; i <= R; i++) + { + ans = ans * A[i]; + ans = ans % P; + } + + return ans; + } + +/* Driver code*/ + + static public void main (String[] args) + { + int []A = { 1, 2, 3, 4, 5, 6 }; + int P = 229; + int L = 2, R = 5; + System.out.println( + calculateProduct(A, L, R, P)); + + L = 1; + R = 3; + System.out.println( + calculateProduct(A, L, R, P)); + } +} + + +"," '''Python3 program to find +Product in range Queries in O(N)''' + + + '''Function to calculate Product +in the given range.''' + +def calculateProduct (A, L, R, P): + + ''' As our array is 0 based + and L and R are given as + 1 based index.''' + + L = L - 1 + R = R - 1 + ans = 1 + for i in range(R + 1): + ans = ans * A[i] + ans = ans % P + return ans + + '''Driver code''' + +A = [ 1, 2, 3, 4, 5, 6 ] +P = 229 +L = 2 +R = 5 +print (calculateProduct(A, L, R, P)) +L = 1 +R = 3 +print (calculateProduct(A, L, R, P)) + + +" +Pair with given product | Set 1 (Find if any pair exists),"/*Java program to find if there is a pair +with given product.*/ + +class GFG +{ +/* Returns true if there is a pair in + arr[0..n-1] with product equal to x. */ + + boolean isProduct(int arr[], int n, int x) + { + +/* Consider all possible + pairs and check for + every pair.*/ + + for (int i=0; i edges = new HashSet(); +} +class GFG +{ + static int canPaint(ArrayList nodes, int n, int m) + { +/* Create a visited array of n + nodes, initialized to zero*/ + + ArrayList visited = new ArrayList(); + for(int i = 0; i < n + 1; i++) + { + visited.add(0); + } +/* maxColors used till now are 1 as + all nodes are painted color 1*/ + + int maxColors = 1; +/* Do a full BFS traversal from + all unvisited starting points*/ + + for (int sv = 1; sv <= n; sv++) + { + if (visited.get(sv) > 0) + { + continue; + } +/* If the starting point is unvisited, + mark it visited and push it in queue*/ + + visited.set(sv, 1); + Queue q = new LinkedList<>(); + q.add(sv); +/* BFS Travel starts here*/ + + while(q.size() != 0) + { + int top = q.peek(); + q.remove(); +/* Checking all adjacent nodes + to ""top"" edge in our queue*/ + + for(int it: nodes.get(top).edges) + { +/* IMPORTANT: If the color of the + adjacent node is same, increase it by 1*/ + + if(nodes.get(top).color == nodes.get(it).color) + { + nodes.get(it).color += 1; + } +/* If number of colors used shoots m, return + 0*/ + + maxColors = Math.max(maxColors, + Math.max(nodes.get(top).color, + nodes.get(it).color)); + if (maxColors > m) + return 0; +/* If the adjacent node is not visited, + mark it visited and push it in queue*/ + + if (visited.get(it) == 0) + { + visited.set(it, 1); + q.remove(it); + } + } + } + } + return 1; + } +/* Driver code*/ + + public static void main (String[] args) + { + int n = 4; + int [][] graph = {{ 0, 1, 1, 1 },{ 1, 0, 1, 0 }, + { 1, 1, 0, 1 },{ 1, 0, 1, 0 }}; +/*Number of colors*/ + +int m = 3; +/* Create a vector of n+1 + nodes of type ""node"" + The zeroth position is just + dummy (1 to n to be used)*/ + + ArrayList nodes = new ArrayList(); + for(int i = 0; i < n+ 1; i++) + { + nodes.add(new Node()); + } +/* Add edges to each node as per given input*/ + + for (int i = 0; i < n; i++) + { + for(int j = 0; j < n; j++) + { + if(graph[i][j] > 0) + { +/* Connect the undirected graph*/ + + nodes.get(i).edges.add(i); + nodes.get(j).edges.add(j); + } + } + } +/* Display final answer*/ + + System.out.println(canPaint(nodes, n, m)); + } +}"," '''Python3 program for the above approach''' + +from queue import Queue + + '''A node class which stores the color and the edges + connected to the node''' + +class node: + color = 1 + edges = set() +def canPaint(nodes, n, m): ''' Create a visited array of n + nodes, initialized to zero''' + + visited = [0 for _ in range(n+1)] + ''' maxColors used till now are 1 as + all nodes are painted color 1''' + + maxColors = 1 + ''' Do a full BFS traversal from + all unvisited starting points''' + + for _ in range(1, n + 1): + if visited[_]: + continue + ''' If the starting point is unvisited, + mark it visited and push it in queue''' + + visited[_] = 1 + q = Queue() + q.put(_) + ''' BFS Travel starts here''' + + while not q.empty(): + top = q.get() + ''' Checking all adjacent nodes + to ""top"" edge in our queue''' + + for _ in nodes[top].edges: + ''' IMPORTANT: If the color of the + adjacent node is same, increase it by 1''' + + if nodes[top].color == nodes[_].color: + nodes[_].color += 1 + ''' If number of colors used shoots m, + return 0''' + + maxColors = max(maxColors, max( + nodes[top].color, nodes[_].color)) + if maxColors > m: + print(maxColors) + return 0 + ''' If the adjacent node is not visited, + mark it visited and push it in queue''' + + if not visited[_]: + visited[_] = 1 + q.put(_) + return 1 + '''Driver code''' + +if __name__ == ""__main__"": + n = 4 + graph = [ [ 0, 1, 1, 1 ], + [ 1, 0, 1, 0 ], + [ 1, 1, 0, 1 ], + [ 1, 0, 1, 0 ] ] + ''' Number of colors''' + + m = 3 + ''' Create a vector of n+1 + nodes of type ""node"" + The zeroth position is just + dummy (1 to n to be used)''' + + nodes = [] + for _ in range(n+1): + nodes.append(node()) + ''' Add edges to each node as + per given input''' + + for _ in range(n): + for __ in range(n): + if graph[_][__]: + ''' Connect the undirected graph''' + + nodes[_].edges.add(_) + nodes[__].edges.add(__) + ''' Display final answer''' + + print(canPaint(nodes, n, m))" +Check if array contains contiguous integers with duplicates allowed,"/*Java implementation to check whether the array +contains a set of contiguous integers*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Function to check whether the array + contains a set of contiguous integers*/ + + static Boolean areElementsContiguous(int arr[], int n) + { +/* Storing elements of 'arr[]' in + a hash table 'us'*/ + + HashSet us = new HashSet(); + for (int i = 0; i < n; i++) + us.add(arr[i]); +/* As arr[0] is present in 'us'*/ + + int count = 1; +/* Starting with previous smaller + element of arr[0]*/ + + int curr_ele = arr[0] - 1; +/* If 'curr_ele' is present in 'us'*/ + + while (us.contains(curr_ele) == true) { +/* increment count*/ + + count++; +/* update 'curr_ele""*/ + + curr_ele--; + } +/* Starting with next greater + element of arr[0]*/ + + curr_ele = arr[0] + 1; +/* If 'curr_ele' is present in 'us'*/ + + while (us.contains(curr_ele) == true) { +/* increment count*/ + + count++; +/* update 'curr_ele""*/ + + curr_ele++; + } +/* Returns true if array contains a set of + contiguous integers else returns false*/ + + return (count == (us.size())); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; + int n = arr.length; + if (areElementsContiguous(arr, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python implementation to check whether the array +contains a set of contiguous integers + ''' '''Function to check whether the array +contains a set of contiguous integers''' + +def areElementsContiguous(arr): + ''' Storing elements of 'arr[]' in a hash table 'us''' + ''' + us = set() + for i in arr: us.add(i) + ''' As arr[0] is present in 'us''' + ''' + count = 1 + ''' Starting with previous smaller element of arr[0]''' + + curr_ele = arr[0] - 1 + ''' If 'curr_ele' is present in 'us''' + ''' + while curr_ele in us: + ''' Increment count''' + + count += 1 + ''' Update 'curr_ele""''' + + curr_ele -= 1 + ''' Starting with next greater element of arr[0]''' + + curr_ele = arr[0] + 1 + ''' If 'curr_ele' is present in 'us''' + ''' + while curr_ele in us: + ''' Increment count''' + + count += 1 + ''' Update 'curr_ele""''' + + curr_ele += 1 + ''' Returns true if array contains a set of + contiguous integers else returns false''' + + return (count == len(us)) + '''Driver code''' + +arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ] +if areElementsContiguous(arr): print(""Yes"") +else: print(""No"")" +Maximize count of corresponding same elements in given Arrays by Rotation,"/*Java program of the above approach*/ + +import java.util.*; +class GFG{ + +/*Function that prints maximum +equal elements*/ + +static void maximumEqual(int a[], + int b[], int n) +{ + +/* Vector to store the index + of elements of array b*/ + + int store[] = new int[(int) 1e5]; + +/* Storing the positions of + array B*/ + + for (int i = 0; i < n; i++) + { + store[b[i]] = i + 1; + } + +/* frequency array to keep count + of elements with similar + difference in distances*/ + + int ans[] = new int[(int) 1e5]; + +/* Iterate through all element in arr1[]*/ + + for (int i = 0; i < n; i++) + { + +/* Calculate number of + shift required to + make current element + equal*/ + + int d = Math.abs(store[a[i]] - (i + 1)); + +/* If d is less than 0*/ + + if (store[a[i]] < i + 1) + { + d = n - d; + } + +/* Store the frequency + of current diff*/ + + ans[d]++; + } + + int finalans = 0; + +/* Compute the maximum frequency + stored*/ + + for (int i = 0; i < 1e5; i++) + finalans = Math.max(finalans, + ans[i]); + +/* Printing the maximum number + of equal elements*/ + + System.out.print(finalans + ""\n""); +} + +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Given two arrays*/ + + int A[] = { 6, 7, 3, 9, 5 }; + int B[] = { 7, 3, 9, 5, 6 }; + + int size = A.length; + +/* Function Call*/ + + maximumEqual(A, B, size); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Function that prints maximum +equal elements''' + +def maximumEqual(a, b, n): + + ''' List to store the index + of elements of array b''' + + store = [0] * 10 ** 5 + + ''' Storing the positions of + array B''' + + for i in range(n): + store[b[i]] = i + 1 + + ''' Frequency array to keep count + of elements with similar + difference in distances''' + + ans = [0] * 10 ** 5 + + ''' Iterate through all element + in arr1[]''' + + for i in range(n): + + ''' Calculate number of shift + required to make current + element equal''' + + d = abs(store[a[i]] - (i + 1)) + + ''' If d is less than 0''' + + if (store[a[i]] < i + 1): + d = n - d + + ''' Store the frequency + of current diff''' + + ans[d] += 1 + + finalans = 0 + + ''' Compute the maximum frequency + stored''' + + for i in range(10 ** 5): + finalans = max(finalans, ans[i]) + + ''' Printing the maximum number + of equal elements''' + + print(finalans) + + '''Driver Code''' + +if __name__ == '__main__': + + ''' Given two arrays''' + + A = [ 6, 7, 3, 9, 5 ] + B = [ 7, 3, 9, 5, 6 ] + + size = len(A) + + ''' Function Call''' + + maximumEqual(A, B, size) + + + +" +Dynamic Programming,"/*A recursive solution for subset sum +problem*/ + +class GFG { +/* Returns true if there is a subset + of set[] with sum equal to given sum*/ + + static boolean isSubsetSum(int set[], + int n, int sum) + { +/* Base Cases*/ + + if (sum == 0) + return true; + if (n == 0) + return false; +/* If last element is greater than + sum, then ignore it*/ + + if (set[n - 1] > sum) + return isSubsetSum(set, n - 1, sum); + /* else, check if sum can be obtained + by any of the following + (a) including the last element + (b) excluding the last element */ + + return isSubsetSum(set, n - 1, sum) + || isSubsetSum(set, n - 1, sum - set[n - 1]); + } + /* Driver code */ + + public static void main(String args[]) + { + int set[] = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + int n = set.length; + if (isSubsetSum(set, n, sum) == true) + System.out.println(""Found a subset"" + + "" with given sum""); + else + System.out.println(""No subset with"" + + "" given sum""); + } +}"," '''A recursive solution for subset sum +problem''' + '''Returns true if there is a subset +of set[] with sun equal to given sum''' + +def isSubsetSum(set, n, sum): + ''' Base Cases''' + + if (sum == 0): + return True + if (n == 0): + return False + ''' If last element is greater than + sum, then ignore it''' + + if (set[n - 1] > sum): + return isSubsetSum(set, n - 1, sum) + ''' else, check if sum can be obtained + by any of the following + (a) including the last element + (b) excluding the last element''' + + return isSubsetSum( + set, n-1, sum) or isSubsetSum( + set, n-1, sum-set[n-1]) + '''Driver code''' + +set = [3, 34, 4, 12, 5, 2] +sum = 9 +n = len(set) +if (isSubsetSum(set, n, sum) == True): + print(""Found a subset with given sum"") +else: + print(""No subset with given sum"")" +Maximum absolute difference of value and index sums,"/*Java program to calculate the maximum +absolute difference of an array.*/ + +public class MaximumAbsoluteDifference +{ + private static int calculateDiff(int i, int j, + int[] array) + { +/* Utility function to calculate + the value of absolute difference + for the pair (i, j).*/ + + return Math.abs(array[i] - array[j]) + + Math.abs(i - j); + } + +/* Function to return maximum absolute + difference in brute force.*/ + + private static int maxDistance(int[] array) + { +/* Variable for storing the maximum + absolute distance throughout the + traversal of loops.*/ + + int result = 0; + +/* Iterate through all pairs.*/ + + for (int i = 0; i < array.length; i++) + { + for (int j = i; j < array.length; j++) + { + +/* If the absolute difference of + current pair (i, j) is greater + than the maximum difference + calculated till now, update + the value of result.*/ + + result = Math.max(result, calculateDiff(i, j, array)); + } + } + return result; + } + +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int[] array = { -70, -64, -6, -56, 64, + 61, -57, 16, 48, -98 }; + System.out.println(maxDistance(array)); + } +} + + +"," '''Brute force Python 3 program +to calculate the maximum +absolute difference of an array.''' + + +def calculateDiff(i, j, arr): + + ''' Utility function to calculate + the value of absolute difference + for the pair (i, j).''' + + return abs(arr[i] - arr[j]) + abs(i - j) + + '''Function to return maximum +absolute difference in +brute force.''' + +def maxDistance(arr, n): + + ''' Variable for storing the + maximum absolute distance + throughout the traversal + of loops.''' + + result = 0 + + ''' Iterate through all pairs.''' + + for i in range(0,n): + for j in range(i, n): + + ''' If the absolute difference of + current pair (i, j) is greater + than the maximum difference + calculated till now, update + the value of result.''' + + if (calculateDiff(i, j, arr) > result): + result = calculateDiff(i, j, arr) + + return result + + '''Driver program''' + +arr = [ -70, -64, -6, -56, 64, + 61, -57, 16, 48, -98 ] +n = len(arr) + +print(maxDistance(arr, n)) + + +" +Generate a matrix having sum of secondary diagonal equal to a perfect square,"/*Java program for the above approach*/ + +class GFG { + +/* Function to print the matrix whose sum + of element in secondary diagonal is a + perfect square*/ + + static void diagonalSumPerfectSquare(int[] arr, + int N) + { + +/* Iterate for next N - 1 rows*/ + + for (int i = 0; i < N; i++) + { + +/* Print the current row after + the left shift*/ + + for (int j = 0; j < N; j++) + { + System.out.print(arr[(j + i) % 7] + "" ""); + } + System.out.println(); + } + } + +/* Driver Code*/ + + public static void main(String[] srgs) + { + +/* Given N*/ + + int N = 7; + + int[] arr = new int[N]; + +/* Fill the array with elements + ranging from 1 to N*/ + + for (int i = 0; i < N; i++) + { + arr[i] = i + 1; + } + +/* Function Call*/ + + diagonalSumPerfectSquare(arr, N); + } +} + + +", +Print the path common to the two paths from the root to the two given nodes,"/*Java implementation to print the path common to the +two paths from the root to the two given nodes*/ + +import java.util.ArrayList; +public class PrintCommonPath { +/* Initialize n1 and n2 as not visited*/ + + static boolean v1 = false, v2 = false; +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +}/* This function returns pointer to LCA of two given + values n1 and n2. This function assumes that n1 and + n2 are present in Binary Tree*/ + + static Node findLCAUtil(Node node, int n1, int n2) + { +/* Base case*/ + + if (node == null) + return null; +/* Store result in temp, in case of key match so that we can search for other key also.*/ + + Node temp=null; +/* If either n1 or n2 matches with root's key, report the presence + by setting v1 or v2 as true and return root (Note that if a key + is ancestor of other, then the ancestor key becomes LCA)*/ + + if (node.data == n1) + { + v1 = true; + temp = node; + } + if (node.data == n2) + { + v2 = true; + temp = node; + } +/* Look for keys in left and right subtrees*/ + + Node left_lca = findLCAUtil(node.left, n1, n2); + Node right_lca = findLCAUtil(node.right, n1, n2); + if (temp != null) + return temp; +/* If both of the above calls return Non-NULL, then one key + is present in once subtree and other is present in other, + So this node is the LCA*/ + + if (left_lca != null && right_lca != null) + return node; +/* Otherwise check if left subtree or right subtree is LCA*/ + + return (left_lca != null) ? left_lca : right_lca; + } +/* Returns true if key k is present in tree rooted with root*/ + + static boolean find(Node root, int k) + { +/* Base Case*/ + + if (root == null) + return false; +/* If key k is present at root, or in left subtree + or right subtree, return true*/ + + if (root.data == k || find(root.left, k) || find(root.right, k)) + return true; +/* Else return false*/ + + return false; + } +/* This function returns LCA of n1 and n2 only if both n1 and n2 + are present in tree, otherwise returns null*/ + + static Node findLCA(Node root, int n1, int n2) + { +/* Find lca of n1 and n2*/ + + Node lca = findLCAUtil(root, n1, n2); +/* Return LCA only if both n1 and n2 are present in tree*/ + + if (v1 && v2 || v1 && find(lca, n2) || v2 && find(lca, n1)) + return lca; +/* Else return null*/ + + return null; + } +/* function returns true if + there is a path from root to + the given node. It also populates + 'arr' with the given path*/ + + static boolean hasPath(Node root, ArrayList arr, int x) + { +/* if root is null + there is no path*/ + + if (root==null) + return false; +/* push the node's value in 'arr'*/ + + arr.add(root.data); +/* if it is the required node + return true*/ + + if (root.data == x) + return true; +/* else check whether there the required node lies in the + left subtree or right subtree of the current node*/ + + if (hasPath(root.left, arr, x) || + hasPath(root.right, arr, x)) + return true; +/* required node does not lie either in the + left or right subtree of the current node + Thus, remove current node's value from 'arr' + and then return false; */ + + arr.remove(arr.size()-1); + return false; + } +/* function to print the path common + to the two paths from the root + to the two given nodes if the nodes + lie in the binary tree*/ + + static void printCommonPath(Node root, int n1, int n2) + { +/* ArrayList to store the common path*/ + + ArrayList arr=new ArrayList<>(); +/* LCA of node n1 and n2*/ + + Node lca = findLCA(root, n1, n2); +/* if LCA of both n1 and n2 exists*/ + + if (lca!=null) + { +/* then print the path from root to + LCA node*/ + + if (hasPath(root, arr, lca.data)) + { + for (int i=0; i""); + System.out.print(arr.get(arr.size() - 1)); + } + } +/* LCA is not present in the binary tree + either n1 or n2 or both are not present*/ + + else + System.out.print(""No Common Path""); + } +/* Driver code*/ + + public static void main(String args[]) + { + 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.right.left = new Node(8); + root.right.left.right = new Node(9); + int n1 = 4, n2 = 8; + printCommonPath(root, n1, n2); + } +} +"," '''Python implementation to print the path common to the +two paths from the root to the two given nodes''' + + ''' Initialize n1 and n2 as not visited''' + + v1 = False + v2 = False + '''structure of a node of binary tree''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''This function returns pointer to LCA of two given values n1 and n2. +v1 is set as True by this function if n1 is found +v2 is set as True by this function if n2 is found''' + +def findLCAUtil(root: Node, n1: int, n2: int) -> Node: + global v1, v2 + ''' Base case''' + + if (root is None): + return None + ''' If either n1 or n2 matches with root's data, report the presence + by setting v1 or v2 as True and return root (Note that if a key + is ancestor of other, then the ancestor key becomes LCA)''' + + if (root.data == n1): + v1 = True + return root + if (root.data == n2): + v2 = True + return root + ''' Look for nodes in left and right subtrees''' + + left_lca = findLCAUtil(root.left, n1, n2) + right_lca = findLCAUtil(root.right, n1, n2) + ''' If both of the above calls return Non-None, then one node + is present in one subtree and other is present in other, + So this current node is the LCA''' + + if (left_lca and right_lca): + return root + ''' Otherwise check if left subtree or right subtree is LCA''' + + return left_lca if (left_lca != None) else right_lca + '''Returns True if key k is present in tree rooted with root''' + +def find(root: Node, k: int) -> bool: + ''' Base Case''' + + if (root == None): + return False + ''' If key k is present at root, or in left subtree + or right subtree, return True''' + + if (root.data == k or find(root.left, k) or find(root.right, k)): + return True + ''' Else return False''' + + return False + '''This function returns LCA of n1 and n2 only if both n1 and n2 +are present in tree, otherwise returns None''' + +def findLCA(root: Node, n1: int, n2: int) -> Node: + global v1, v2 + ''' Find lca of n1 and n2''' + + lca = findLCAUtil(root, n1, n2) + ''' Return LCA only if both n1 and n2 are present in tree''' + + if (v1 and v2 or v1 and find(lca, n2) or v2 and find(lca, n1)): + return lca + ''' Else return None''' + + return None + '''function returns True if +there is a path from root to +the given node. It also populates + '''arr' with the given path''' + +def hasPath(root: Node, arr: list, x: int) -> Node: + ''' if root is None + there is no path''' + + if (root is None): + return False + ''' push the node's value in 'arr''' + ''' + arr.append(root.data) + ''' if it is the required node + return True''' + + if (root.data == x): + return True + ''' else check whether there the required node lies in the + left subtree or right subtree of the current node''' + + if (hasPath(root.left, arr, x) or hasPath(root.right, arr, x)): + return True + ''' required node does not lie either in the + left or right subtree of the current node + Thus, remove current node's value from 'arr' + and then return False;''' + + arr.pop() + return False + '''function to print the path common +to the two paths from the root +to the two given nodes if the nodes +lie in the binary tree''' + +def printCommonPath(root: Node, n1: int, n2: int): + ''' vector to store the common path''' + + arr = [] + ''' LCA of node n1 and n2''' + + lca = findLCA(root, n1, n2) + ''' if LCA of both n1 and n2 exists''' + + if (lca): + ''' then print the path from root to + LCA node''' + + if (hasPath(root, arr, lca.data)): + for i in range(len(arr) - 1): + print(arr[i], end=""->"") + print(arr[-1]) + ''' LCA is not present in the binary tree + either n1 or n2 or both are not present''' + + else: + print(""No Common Path"") + '''Driver Code''' + +if __name__ == ""__main__"": + v1 = 0 + v2 = 0 + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.left.right.left = Node(8) + root.right.left.right = Node(9) + n1 = 4 + n2 = 8 + printCommonPath(root, n1, n2)" +Count subtrees that sum up to a given value x only using single recursive function,"/*Java program to find if +there is a subtree with +given sum*/ + +import java.io.*; +/*Node class to create new node*/ + +class Node +{ + int data; + Node left; + Node right; + Node(int data) + { + this.data = data; + } +} +class GFG +{ + static int count = 0; + static Node ptr; +/* Utility function to count subtress that + sum up to a given value x*/ + + int countSubtreesWithSumXUtil(Node root, int x) + { + int l = 0, r = 0; + if(root == null) return 0; + l += countSubtreesWithSumXUtil(root.left, x); + r += countSubtreesWithSumXUtil(root.right, x); + if(l + r + root.data == x) count++; + if(ptr != root) return l + root.data + r; + return count; + } +/* Driver Code*/ + + public static void main(String[] args) + { + /* binary tree creation + 5 + / \ + -10 3 + / \ / \ + 9 8 -4 7 + */ + + Node root = new Node(5); + root.left = new Node(-10); + root.right = new Node(3); + root.left.left = new Node(9); + root.left.right = new Node(8); + root.right.left = new Node(-4); + root.right.right = new Node(7); + int x = 7; + ptr = root; + System.out.println(""Count = "" + + new GFG().countSubtreesWithSumXUtil(root, x)); + } +}"," '''Python3 program to find if there is +a subtree with given sum''' + + '''Structure of a node of binary tree''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to get a new node''' + +def getNode(data): + ''' Allocate space''' + + newNode = Node(data) + return newNode +count = 0 +ptr = None + '''Utility function to count subtress that +sum up to a given value x''' + +def countSubtreesWithSumXUtil(root, x): + global count, ptr + l = 0 + r = 0 + if (root == None): + return 0 + l += countSubtreesWithSumXUtil(root.left, x) + r += countSubtreesWithSumXUtil(root.right, x) + if (l + r + root.data == x): + count += 1 + if (ptr != root): + return l + root.data + r + return count + '''Driver code''' + +if __name__=='__main__': + ''' binary tree creation + 5 + / \ + -10 3 + / \ / \ + 9 8 -4 7 + ''' + + root = getNode(5) + root.left = getNode(-10) + root.right = getNode(3) + root.left.left = getNode(9) + root.left.right = getNode(8) + root.right.left = getNode(-4) + root.right.right = getNode(7) + x = 7 + ptr = root + print(""Count = "" + str(countSubtreesWithSumXUtil( + root, x)))" +Subset Sum | Backtracking-4,, +Find the element that appears once in an array where every other element appears twice,"import java.io.*; +import java.util.Arrays; + +class GFG{ + + +/*singleelement function*/ + + +static int singleelement(int arr[], int n) +{ + int low = 0, high = n - 2; + int mid; + + while (low <= high) + { + mid = (low + high) / 2; + if (arr[mid] == arr[mid ^ 1]) + { + low = mid + 1; + } + else + { + high = mid - 1; + } + } + return arr[low]; +}/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 2, 3, 5, 4, 5, 3, 4 }; + int size = 7; + Arrays.sort(arr); + + System.out.println(singleelement(arr, size)); +} +} + + +"," '''singleelement function''' + +def singleelement(arr, n): + low = 0 + high = n - 2 + mid = 0 + while (low <= high): + mid = (low + high) // 2 + if (arr[mid] == arr[mid ^ 1]): + low = mid + 1 + else: + high = mid - 1 + + return arr[low] + + '''Driver code''' + +arr = [2, 3, 5, 4, 5, 3, 4] +size = len(arr) +arr.sort() +print(singleelement(arr, size)) + + +" +Program to find largest element in an array,"/*Java Program to find maximum in arr[]*/ + +class Test +{ + static int arr[] = {10, 324, 45, 90, 9808}; +/* Method to find maximum in arr[]*/ + + static int largest() + { + int i; +/* Initialize maximum element*/ + + int max = arr[0]; +/* Traverse array elements from second and + compare every element with current max */ + + for (i = 1; i < arr.length; i++) + if (arr[i] > max) + max = arr[i]; + return max; + } +/* Driver method*/ + + public static void main(String[] args) + { + System.out.println(""Largest in given array is "" + largest()); + } + }", +Find sum of all left leaves in a given Binary Tree,"/*Java program to find sum of all left leaves*/ + +import java.util.*; +class GFG +{ +/*A binary tree node*/ + +static class Node +{ + int key; + Node left, right; +/* A constructor to create a new Node*/ + + Node(int key_) + { + this.key = key_; + this.left = null; + this.right = null; + } +}; +/*Return the sum of left leaf nodes*/ + +static int sumOfLeftLeaves(Node root) +{ + if(root == null) + return 0; +/* Using a stack_ for Depth-First + Traversal of the tree*/ + + Stack stack_ = new Stack<>(); + stack_.push(root); +/* sum holds the sum of all the left leaves*/ + + int sum = 0; + while(stack_.size() > 0) + { + Node currentNode = stack_.peek(); + stack_.pop(); + if (currentNode.left != null) + { + stack_.add(currentNode.left); +/* Check if currentNode's left + child is a leaf node*/ + + if(currentNode.left.left == null && + currentNode.left.right == null) + { +/* if currentNode is a leaf, + add its data to the sum*/ + + sum = sum + currentNode.left.key ; + } + } + if (currentNode.right != null) + stack_.add(currentNode.right); + } + return sum; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root = new Node(20); + root.left= new Node(9); + root.right = new Node(49); + root.right.left = new Node(23); + root.right.right= new Node(52); + root.right.right.left = new Node(50); + root.left.left = new Node(5); + root.left.right = new Node(12); + root.left.right.right = new Node(12); + System.out.print(""Sum of left leaves is "" + + sumOfLeftLeaves(root) +""\n""); +} +}"," '''Python3 program to find sum of all left leaves''' '''A binary tree node''' + +class Node: + ''' A constructor to create a new Node''' + + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Return the sum of left leaf nodes''' + +def sumOfLeftLeaves(root): + if(root is None): + return + ''' Using a stack for Depth-First Traversal of the tree''' + + stack = [] + stack.append(root) + ''' sum holds the sum of all the left leaves''' + + sum = 0 + while len(stack) > 0: + currentNode = stack.pop() + if currentNode.left is not None: + stack.append(currentNode.left) + ''' Check if currentNode's left child is a leaf node''' + + if currentNode.left.left is None and currentNode.left.right is None: + ''' if currentNode is a leaf, add its data to the sum ''' + + sum = sum + currentNode.left.data + if currentNode.right is not None: + stack.append(currentNode.right) + return sum + '''Driver Code''' + +root = Tree(20); +root.left= Tree(9); +root.right = Tree(49); +root.right.left = Tree(23); +root.right.right= Tree(52); +root.right.right.left = Tree(50); +root.left.left = Tree(5); +root.left.right = Tree(12); +root.left.right.right = Tree(12); +print('Sum of left leaves is {}'.format(sumOfLeftLeaves(root)))" +Number of paths with exactly k coins,"/*A Dynamic Programming based JAVA program to count paths with +exactly 'k' coins*/ + +class GFG +{ + static final int R = 3; + static final int C = 3; + static final int MAX_K = 100; + static int [][][]dp=new int[R][C][MAX_K]; + static int pathCountDPRecDP(int [][]mat, int m, int n, int k) + { +/* Base cases*/ + + if (m < 0 || n < 0) return 0; + if (m==0 && n==0) return (k == mat[m][n] ? 1 : 0); +/* If this subproblem is already solved*/ + + if (dp[m][n][k] != -1) return dp[m][n][k]; +/* (m, n) can be reached either through (m-1, n) or + through (m, n-1)*/ + + dp[m][n][k] = pathCountDPRecDP(mat, m-1, n, k-mat[m][n]) + + pathCountDPRecDP(mat, m, n-1, k-mat[m][n]); + return dp[m][n][k]; + } +/* This function mainly initializes dp[][][] and calls + pathCountDPRecDP()*/ + + static int pathCountDP(int [][]mat, int k) + { + for(int i=0;i mp = new HashMap<>(); +/* store frequency of each element + in arr[start; end]*/ + + for (int i = start; i <= end; i++) + mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1); +/* Count elements with same frequency + as value*/ + + int count = 0; + for (Map.Entry entry : mp.entrySet()) + if (entry.getKey() == entry.getValue()) + count++; + return count; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int A[] = { 1, 2, 2, 3, 3, 3 }; + int n = A.length; +/* 2D array of queries with 2 columns*/ + + int [][]queries = { { 0, 1 }, + { 1, 1 }, + { 0, 2 }, + { 1, 3 }, + { 3, 5 }, + { 0, 5 } }; +/* calculating number of queries*/ + + int q = queries.length; + for (int i = 0; i < q; i++) + { + int start = queries[i][0]; + int end = queries[i][1]; + System.out.println(""Answer for Query "" + (i + 1) + + "" = "" + solveQuery(start, + end, A)); + } +} +}"," '''Python 3 Program to answer Q queries +to find number of times an element x +appears x times in a Query subarray''' + +import math as mt + '''Returns the count of number x with +frequency x in the subarray from +start to end''' + +def solveQuery(start, end, arr): + ''' map for frequency of elements''' + + frequency = dict() + ''' store frequency of each element + in arr[start end]''' + + for i in range(start, end + 1): + if arr[i] in frequency.keys(): + frequency[arr[i]] += 1 + else: + frequency[arr[i]] = 1 + ''' Count elements with same + frequency as value''' + + count = 0 + for x in frequency: + if x == frequency[x]: + count += 1 + return count + '''Driver code''' + +A = [1, 2, 2, 3, 3, 3 ] +n = len(A) + '''2D array of queries with 2 columns''' + +queries = [[ 0, 1 ], [ 1, 1 ], + [ 0, 2 ], [ 1, 3 ], + [ 3, 5 ], [ 0, 5 ]] + '''calculating number of queries''' + +q = len(queries) +for i in range(q): + start = queries[i][0] + end = queries[i][1] + print(""Answer for Query "", (i + 1), + "" = "", solveQuery(start,end, A))" +Find the maximum element in an array which is first increasing and then decreasing,"/*java program to find maximum +element*/ + + +class Main +{ + static int findMaximum(int arr[], int low, int high) + { +/* Base Case: Only one element is + present in arr[low..high]*/ + + if (low == high) + return arr[low]; + + /* If there are two elements and + first is greater then the first + element is maximum */ + + if ((high == low + 1) && arr[low] >= arr[high]) + return arr[low]; + + /* If there are two elements and + second is greater then the second + element is maximum */ + + if ((high == low + 1) && arr[low] < arr[high]) + return arr[high]; + int mid = (low + high)/2; + + /* If we reach a point where arr[mid] + is greater than both of its adjacent + elements arr[mid-1] and arr[mid+1], + then arr[mid] is the maximum element*/ + + if ( arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) + return arr[mid]; + + /* If arr[mid] is greater than the next + element and smaller than the previous + element then maximum lies on left side + of mid */ + + if (arr[mid] > arr[mid + 1] && arr[mid] < arr[mid - 1]) + return findMaximum(arr, low, mid-1); + + +/*when arr[mid] is greater than arr[mid-1] and smaller than arr[mid+1]*/ + + else + return findMaximum(arr, mid + 1, high); + }/* main function*/ + + public static void main (String[] args) + { + int arr[] = {1, 3, 50, 10, 9, 7, 6}; + int n = arr.length; + System.out.println(""The maximum element is ""+ + findMaximum(arr, 0, n-1)); + } +} +","def findMaximum(arr, low, high): + ''' Base Case: Only one element is present in arr[low..high]*/''' + + if low == high: + return arr[low] + + ''' If there are two elements and first is greater then + the first element is maximum */''' + + if high == low + 1 and arr[low] >= arr[high]: + return arr[low]; + + ''' If there are two elements and second is greater then + the second element is maximum */''' + + if high == low + 1 and arr[low] < arr[high]: + return arr[high] + mid = (low + high)//2 + + ''' If we reach a point where arr[mid] is greater than both of + its adjacent elements arr[mid-1] and arr[mid+1], then arr[mid] + is the maximum element*/''' + + if arr[mid] > arr[mid + 1] and arr[mid] > arr[mid - 1]: + return arr[mid] + + ''' If arr[mid] is greater than the next element and smaller than the previous + element then maximum lies on left side of mid */''' + + if arr[mid] > arr[mid + 1] and arr[mid] < arr[mid - 1]: + return findMaximum(arr, low, mid-1) + '''when arr[mid] is greater than arr[mid-1] and smaller than arr[mid+1]''' + + else: + return findMaximum(arr, mid + 1, high) + + '''Driver program to check above functions */''' + +arr = [1, 3, 50, 10, 9, 7, 6] +n = len(arr) +print (""The maximum element is %d""% findMaximum(arr, 0, n-1)) + + +" +Insertion at Specific Position in a Circular Doubly Linked List,"/*Java program to convert insert +an element at a specific position +in a circular doubly linked listing, +end and middle*/ + +class GFG +{ + +/*Doubly linked list node*/ + +static class node +{ + int data; + node next; + node prev; +}; + +/*Utility function to create a node in memory*/ + +static node getNode() +{ + return new node(); +} + +/*Function to display the list*/ + +static int displayList( node temp) +{ + node t = temp; + if (temp == null) + return 0; + else + { + System.out.println( ""The list is: ""); + + while (temp.next != t) + { + System.out.print( temp.data + "" ""); + temp = temp.next; + } + + System.out.println( temp.data ); + + return 1; + } +} + +/*Function to count nunmber of +elements in the list*/ + +static int countList( node start) +{ +/* Declare temp pointer to + traverse the list*/ + + node temp = start; + +/* Variable to store the count*/ + + int count = 0; + +/* Iterate the list and + increment the count*/ + + while (temp.next != start) + { + temp = temp.next; + count++; + } + +/* As the list is circular, increment + the counter at last*/ + + count++; + + return count; +} + +/*Function to insert a node at +a given position in the +circular doubly linked list*/ + +static node insertAtLocation( node start, + int data, int loc) +{ +/* Declare two pointers*/ + + node temp, newNode; + int i, count; + +/* Create a new node in memory*/ + + newNode = getNode(); + +/* Point temp to start*/ + + temp = start; + +/* count of total elements in the list*/ + + count = countList(start); + +/* If list is empty or the position is + not valid, return false*/ + + if (temp == null || count < loc) + return start; + + else + { +/* Assign the data*/ + + newNode.data = data; + +/* Iterate till the loc*/ + + for (i = 1; i < loc - 1; i++) + { + temp = temp.next; + } + +/* See in Image, circle 1*/ + + newNode.next = temp.next; + +/* See in Image, Circle 2*/ + + (temp.next).prev = newNode; + +/* See in Image, Circle 3*/ + + temp.next = newNode; + +/* See in Image, Circle 4*/ + + newNode.prev = temp; + + return start; + } + +} + +/*Function to create circular doubly +linked list from array elements*/ + +static node createList(int arr[], int n, node start) +{ +/* Declare newNode and temporary pointer*/ + + node newNode, temp; + int i; + +/* Iterate the loop until array length*/ + + for (i = 0; i < n; i++) + { +/* Create new node*/ + + newNode = getNode(); + +/* Assign the array data*/ + + newNode.data = arr[i]; + +/* If it is first element + Put that node prev and next as start + as it is circular*/ + + if (i == 0) + { + start = newNode; + newNode.prev = start; + newNode.next = start; + } + + else + { +/* Find the last node*/ + + temp = (start).prev; + +/* Add the last node to make them + in circular fashion*/ + + temp.next = newNode; + newNode.next = start; + newNode.prev = temp; + temp = start; + temp.prev = newNode; + } + } + return start; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ +/* Array elements to create + circular doubly linked list*/ + + int arr[] = { 1, 2, 3, 4, 5, 6 }; + int n = arr.length; + +/* Start Pointer*/ + + node start = null; + +/* Create the List*/ + + start = createList(arr, n, start); + +/* Display the list before insertion*/ + + displayList(start); + +/* Inserting 8 at 3rd position*/ + + start = insertAtLocation(start, 8, 3); + +/* Display the list after insertion*/ + + displayList(start); +} +} + + +"," '''Python3 program to insert an element +at a specific position in a +circular doubly linked list''' + + + '''Node of the doubly linked list''' + +class Node: + + def __init__(self, data): + self.data = data + self.prev = None + self.next = None + + '''Utility function to create +a node in memory''' + +def getNode(): + + return (Node(0)) + + '''Function to display the list''' + +def displayList(temp): + + t = temp + if (temp == None): + return 0 + else : + print(""The list is: "", end = "" "") + + while (temp.next != t): + print( temp.data, end = "" "") + temp = temp.next + + print(temp.data ) + + return 1 + + '''Function to count nunmber of +elements in the list''' + +def countList( start): + + ''' Declare temp pointer to + traverse the list''' + + temp = start + + ''' Variable to store the count''' + + count = 0 + + ''' Iterate the list and increment the count''' + + while (temp.next != start) : + temp = temp.next + count = count + 1 + + ''' As the list is circular, increment the + counter at last''' + + count = count + 1 + + return count + + '''Function to insert a node at a given position +in the circular doubly linked list''' + +def insertAtLocation(start, data, loc): + + ''' Declare two pointers''' + + temp = None + newNode = None + i = 0 + count = 0 + + ''' Create a new node in memory''' + + newNode = getNode() + + ''' Point temp to start''' + + temp = start + + ''' count of total elements in the list''' + + count = countList(start) + + ''' If list is empty or the position is + not valid, return False''' + + if (temp == None or count < loc): + return start + + else : + + ''' Assign the data''' + + newNode.data = data + + ''' Iterate till the loc''' + + i = 1; + while(i < loc - 1) : + temp = temp.next + i = i + 1 + + ''' See in Image, circle 1''' + + newNode.next = temp.next + + ''' See in Image, Circle 2''' + + (temp.next).prev = newNode + + ''' See in Image, Circle 3''' + + temp.next = newNode + + ''' See in Image, Circle 4''' + + newNode.prev = temp + + return start + + return start + + '''Function to create circular +doubly linked list from array elements''' + +def createList(arr, n, start): + + ''' Declare newNode and temporary pointer''' + + newNode = None + temp = None + i = 0 + + ''' Iterate the loop until array length''' + + while (i < n) : + + ''' Create new node''' + + newNode = getNode() + + ''' Assign the array data''' + + newNode.data = arr[i] + + ''' If it is first element + Put that node prev and next as start + as it is circular''' + + if (i == 0) : + start = newNode + newNode.prev = start + newNode.next = start + + else : + + ''' Find the last node''' + + temp = (start).prev + + ''' Add the last node to make them + in circular fashion''' + + temp.next = newNode + newNode.next = start + newNode.prev = temp + temp = start + temp.prev = newNode + i = i + 1; + + return start + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Array elements to create + circular doubly linked list''' + + arr = [ 1, 2, 3, 4, 5, 6] + n = len(arr) + + ''' Start Pointer''' + + start = None + + ''' Create the List''' + + start = createList(arr, n, start) + + ''' Display the list before insertion''' + + displayList(start) + + ''' Inserting 8 at 3rd position''' + + start = insertAtLocation(start, 8, 3) + + ''' Display the list after insertion''' + + displayList(start) + + +" +Minimum number of subtract operation to make an array decreasing,"/*Java program to make an +array decreasing*/ + +import java.util.*; +import java.lang.*; + +public class GfG{ + +/* Function to count minimum no of operation*/ + + public static int min_noOf_operation(int arr[], + int n, int k) + { + int noOfSubtraction; + int res = 0; + + for (int i = 1; i < n; i++) { + noOfSubtraction = 0; + + if (arr[i] > arr[i - 1]) { + +/* Count how many times + we have to subtract.*/ + + noOfSubtraction = (arr[i] - arr[i - 1]) / k; + +/* Check an additional subtraction + is required or not.*/ + + if ((arr[i] - arr[i - 1]) % k != 0) + noOfSubtraction++; + +/* Modify the value of arr[i]*/ + + arr[i] = arr[i] - k * noOfSubtraction; + } + +/* Count total no of subtraction*/ + + res = res + noOfSubtraction; + } + + return res; + } + +/* driver function*/ + + public static void main(String argc[]){ + int arr = { 1, 1, 2, 3 }; + int N = 4; + int k = 5; + System.out.println(min_noOf_operation(arr, + N, k)); + } + +} + + +"," '''Python program to make an array decreasing''' + + + '''Function to count minimum no of operation''' + +def min_noOf_operation(arr, n, k): + + res = 0 + for i in range(1,n): + noOfSubtraction = 0 + + if (arr[i] > arr[i - 1]): + + ''' Count how many times we have to subtract.''' + + noOfSubtraction = (arr[i] - arr[i - 1]) / k; + + ''' Check an additional subtraction is + required or not.''' + + if ((arr[i] - arr[i - 1]) % k != 0): + noOfSubtraction+=1 + + ''' Modify the value of arr[i].''' + + arr[i] = arr[i] - k * noOfSubtraction + + + ''' Count total no of operation/subtraction .''' + + res = res + noOfSubtraction + + + return int(res) + + + '''Driver Code''' + +arr = [ 1, 1, 2, 3 ] +N = len(arr) +k = 5 +print(min_noOf_operation(arr, N, k)) + + +" +Remove duplicates from an unsorted doubly linked list,"/*Java implementation to remove duplicates +from an unsorted doubly linked list*/ + +class GFG +{ +/*a node of the doubly linked list*/ + +static class Node +{ + int data; + Node next; + Node prev; +} +/*Function to delete a node in a Doubly Linked List. +head_ref -. pointer to head node pointer. +del -. pointer to node to be deleted.*/ + +static Node deleteNode(Node head_ref, Node del) +{ +/* base case*/ + + if (head_ref == null || del == null) + return head_ref; +/* If node to be deleted is head node*/ + + if (head_ref == del) + head_ref = del.next; +/* Change next only if node to be deleted + is NOT the last node*/ + + if (del.next != null) + del.next.prev = del.prev; +/* Change prev only if node to be deleted + is NOT the first node*/ + + if (del.prev != null) + del.prev.next = del.next; + return head_ref; +} +/*function to remove duplicates from +an unsorted doubly linked list*/ + +static Node removeDuplicates(Node head_ref) +{ +/* if DLL is empty or if it contains only + a single node*/ + + if ((head_ref) == null || + (head_ref).next == null) + return head_ref;; + Node ptr1, ptr2; +/* pick elements one by one*/ + + for (ptr1 = head_ref; + ptr1 != null; ptr1 = ptr1.next) + { + ptr2 = ptr1.next; +/* Compare the picked element with the + rest of the elements*/ + + while (ptr2 != null) + { +/* if duplicate, then delete it*/ + + if (ptr1.data == ptr2.data) + { +/* store pointer to the node next to 'ptr2'*/ + + Node next = ptr2.next; +/* delete node pointed to by 'ptr2'*/ + + head_ref = deleteNode(head_ref, ptr2); +/* update 'ptr2'*/ + + ptr2 = next; + } +/* else simply move to the next node*/ + + else + ptr2 = ptr2.next; + } + } + return head_ref; +} +/*Function to insert a node at the beginning +of the Doubly Linked List*/ + +static Node push(Node head_ref, int new_data) +{ +/* allocate node*/ + + Node new_node = new Node(); +/* put in the data*/ + + new_node.data = new_data; +/* since we are adding at the beginning, + prev is always null*/ + + new_node.prev = null; +/* link the old list off the new node*/ + + new_node.next = (head_ref); +/* change prev of head node to new node*/ + + if ((head_ref) != null) + (head_ref).prev = new_node; +/* move the head to point to the new node*/ + + (head_ref) = new_node; + return head_ref; +} +/*Function to print nodes in a +given doubly linked list*/ + +static void printList( Node head) +{ +/* if list is empty*/ + + if (head == null) + System.out.print(""Doubly Linked list empty""); + while (head != null) + { + System.out.print( head.data + "" ""); + head = head.next; + } +} +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; +/* Create the doubly linked list: + 8<.4<.4<.6<.4<.8<.4<.10<.12<.12*/ + + head = push(head, 12); + head = push(head, 12); + head = push(head, 10); + head = push(head, 4); + head = push(head, 8); + head = push(head, 4); + head = push(head, 6); + head = push(head, 4); + head = push(head, 4); + head = push(head, 8); + System.out.print(""Original Doubly linked list:\n""); + printList(head); + /* remove duplicate nodes */ + + head=removeDuplicates(head); + System.out.print(""\nDoubly linked list after"" + + "" removing duplicates:\n""); + printList(head); +} +}"," '''Python implementation to remove duplicates +from an unsorted doubly linked list''' + + '''Node of a linked list''' + +class Node: + def __init__(self, data = None, next = None): + self.next = next + self.data = data '''Function to delete a node in a Doubly Linked List. +head_ref -. pointer to head node pointer. +del -. pointer to node to be deleted.''' + +def deleteNode(head_ref,del_): + ''' base case''' + + if (head_ref == None or del_ == None): + return head_ref + ''' If node to be deleted is head node''' + + if (head_ref == del_): + head_ref = del_.next + ''' Change next only if node to be deleted + is NOT the last node''' + + if (del_.next != None): + del_.next.prev = del_.prev + ''' Change prev only if node to be deleted + is NOT the first node''' + + if (del_.prev != None): + del_.prev.next = del_.next + return head_ref + '''function to remove duplicates from +an unsorted doubly linked list''' + +def removeDuplicates( head_ref): + ''' if DLL is empty or if it contains only + a single node''' + + if ((head_ref) == None or (head_ref).next == None): + return head_ref + ptr1 = head_ref + ptr2 = None + ''' pick elements one by one''' + + while(ptr1 != None) : + ptr2 = ptr1.next + ''' Compare the picked element with the + rest of the elements''' + + while (ptr2 != None): + ''' if duplicate, then delete it''' + + if (ptr1.data == ptr2.data): + ''' store pointer to the node next to 'ptr2''' + ''' + next = ptr2.next + ''' delete node pointed to by 'ptr2''' + ''' + head_ref = deleteNode(head_ref, ptr2) + ''' update 'ptr2''' + ''' + ptr2 = next + ''' else simply move to the next node''' + + else: + ptr2 = ptr2.next + ptr1 = ptr1.next + return head_ref + '''Function to insert a node at the beginning +of the Doubly Linked List''' + +def push( head_ref, new_data): + ''' allocate node''' + + new_node = Node() + ''' put in the data''' + + new_node.data = new_data + ''' since we are adding at the beginning, + prev is always None''' + + new_node.prev = None + ''' link the old list off the new node''' + + new_node.next = (head_ref) + ''' change prev of head node to new node''' + + if ((head_ref) != None): + (head_ref).prev = new_node + ''' move the head to point to the new node''' + + (head_ref) = new_node + return head_ref + '''Function to print nodes in a +given doubly linked list''' + +def printList( head): + ''' if list is empty''' + + if (head == None): + print(""Doubly Linked list empty"") + while (head != None): + print( head.data ,end= "" "") + head = head.next + '''Driver Code''' + +head = None + '''Create the doubly linked list: +8<.4<.4<.6<.4<.8<.4<.10<.12<.12''' + +head = push(head, 12) +head = push(head, 12) +head = push(head, 10) +head = push(head, 4) +head = push(head, 8) +head = push(head, 4) +head = push(head, 6) +head = push(head, 4) +head = push(head, 4) +head = push(head, 8) +print(""Original Doubly linked list:"") +printList(head) + '''remove duplicate nodes */''' + +head=removeDuplicates(head) +print(""\nDoubly linked list after removing duplicates:"") +printList(head)" +Longest subarray having count of 1s one more than count of 0s,"/*Java implementation to find the length of +longest subarray having count of 1's one +more than count of 0's*/ + +import java.util.*; +class GFG +{ +/*function to find the length of longest +subarray having count of 1's one more +than count of 0's*/ + +static int lenOfLongSubarr(int arr[], int n) +{ +/* unordered_map 'um' implemented as + hash table*/ + + HashMap um = new HashMap(); + int sum = 0, maxLen = 0; +/* traverse the given array*/ + + for (int i = 0; i < n; i++) + { +/* consider '0' as '-1'*/ + + sum += arr[i] == 0 ? -1 : 1; +/* when subarray starts form index '0'*/ + + if (sum == 1) + maxLen = i + 1; +/* make an entry for 'sum' if it is + not present in 'um'*/ + + else if (!um.containsKey(sum)) + um. put(sum, i); +/* check if 'sum-1' is present in 'um' + or not*/ + + if (um.containsKey(sum - 1)) + { +/* update maxLength*/ + + if (maxLen < (i - um.get(sum - 1))) + maxLen = i - um.get(sum - 1); + } + } +/* required maximum length*/ + + return maxLen; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = { 0, 1, 1, 0, 0, 1 }; + int n = arr.length; + System.out.println(""Length = "" + + lenOfLongSubarr(arr, n)); +} +}"," '''Python 3 implementation to find the length of +longest subarray having count of 1's one +more than count of 0's + ''' '''function to find the length of longest +subarray having count of 1's one more +than count of 0's''' + +def lenOfLongSubarr(arr, n): + ''' unordered_map 'um' implemented as + hash table''' + + um = {i:0 for i in range(10)} + sum = 0 + maxLen = 0 + ''' traverse the given array''' + + for i in range(n): + ''' consider '0' as '-1''' + ''' + if arr[i] == 0: + sum += -1 + else: + sum += 1 + ''' when subarray starts form index '0''' + ''' + if (sum == 1): + maxLen = i + 1 + ''' make an entry for 'sum' if it is + not present in 'um''' + ''' + elif (sum not in um): + um[sum] = i + ''' check if 'sum-1' is present in 'um' + or not''' + + if ((sum - 1) in um): + ''' update maxLength''' + + if (maxLen < (i - um[sum - 1])): + maxLen = i - um[sum - 1] + ''' required maximum length''' + + return maxLen + '''Driver code''' + +if __name__ == '__main__': + arr = [0, 1, 1, 0, 0, 1] + n = len(arr) + print(""Length ="",lenOfLongSubarr(arr, n))" +Make middle node head in a linked list,"/*Java program to make middle node +as head of Linked list*/ + +public class GFG +{ + /* Link list node */ + + static class Node { + int data; + Node next; + Node(int data){ + this.data = data; + next = null; + } + } + + static Node head; + + /* Function to get the middle and + set at beginning of the linked list*/ + + static void setMiddleHead() + { + if (head == null) + return; + +/* To traverse list nodes one + by one*/ + + Node one_node = head; + +/* To traverse list nodes by + skipping one.*/ + + Node two_node = head; + +/* To keep track of previous of middle*/ + + Node prev = null; + while (two_node != null && + two_node.next != null) { + + /* for previous node of middle node */ + + prev = one_node; + + /* move one node each time*/ + + two_node = two_node.next.next; + + /* move two node each time*/ + + one_node = one_node.next; + } + + /* set middle node at head */ + + prev.next = prev.next.next; + one_node.next = head; + head = one_node; + } + +/* To insert a node at the beginning of + linked list.*/ + + static void push(int new_data) + { + /* allocate node */ + + Node new_node = new Node(new_data); + + /* link the old list off the new node */ + + new_node.next = head; + + /* move the head to point to the new node */ + + head = new_node; + } + +/* A function to print a given linked list*/ + + static void printList(Node ptr) + { + while (ptr != null) { + System.out.print(ptr.data+"" ""); + ptr = ptr.next; + } + System.out.println(); + } + + /* Driver function*/ + + public static void main(String args[]) + { +/* Create a list of 5 nodes*/ + + head = null; + int i; + for (i = 5; i > 0; i--) + push(i); + + System.out.print("" list before: ""); + printList(head); + + setMiddleHead(); + + System.out.print("" list After: ""); + printList(head); + + } +} + +"," '''Python3 program to make middle node +as head of Linked list''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''function to get the middle node +set it as the beginning of the +linked list''' + +def setMiddleHead(head): + if(head == None): + return None + + ''' to traverse nodes + one by one''' + + one_node = head + + ''' to traverse nodes by + skipping one''' + + two_node = head + + ''' to keep track of previous middle''' + + prev = None + + while(two_node != None and + two_node.next != None): + + ''' for previous node of middle node''' + + prev = one_node + + ''' move one node each time''' + + one_node = one_node.next + + ''' move two nodes each time''' + + two_node = two_node.next.next + + ''' set middle node at head''' + + prev.next = prev.next.next + one_node.next = head + head = one_node + return head + + '''To insert a node at the beginning of linked +list.''' + + +def push(head, new_data): + + ''' allocate new node''' + + new_node = Node(new_data) + + ''' link the old list to new node''' + + new_node.next = head + + ''' move the head to point the new node''' + + head = new_node + return head + + '''A function to print a given linked list''' + +def printList(head): + temp = head + while (temp!=None): + + print(str(temp.data), end = "" "") + temp = temp.next + print("""") + + ''' Driver function''' + + '''Create a list of 5 nodes''' + +head = None +for i in range(5, 0, -1): + head = push(head, i) + +print("" list before: "", end = """") +printList(head) + +head = setMiddleHead(head) + +print("" list After: "", end = """") +printList(head) + + +" +"Median of two sorted arrays with different sizes in O(log(min(n, m)))","/*Java code for median with +case of returning double +value when even number of +elements are present in +both array combinely*/ + +import java.io.*; + +class GFG +{ + static int []a = new int[]{900}; + static int []b = new int[]{10, 13, 14}; + +/* Function to find max*/ + + static int maximum(int a, int b) + { + return a > b ? a : b; + } + +/* Function to find minimum*/ + + static int minimum(int a, int b) + { + return a < b ? a : b; + } + +/* Function to find median + of two sorted arrays*/ + + static double findMedianSortedArrays(int n, + int m) + { + + int min_index = 0, + max_index = n, i = 0, + j = 0, median = 0; + + while (min_index <= max_index) + { + i = (min_index + max_index) / 2; + j = ((n + m + 1) / 2) - i; + +/* if i = n, it means that Elements + from a[] in the second half is an + empty set. and if j = 0, it means + that Elements from b[] in the first + half is an empty set. so it is + necessary to check that, because we + compare elements from these two + groups. Searching on right*/ + + if (i < n && j > 0 && b[j - 1] > a[i]) + min_index = i + 1; + +/* if i = 0, it means that Elements + from a[] in the first half is an + empty set and if j = m, it means + that Elements from b[] in the second + half is an empty set. so it is + necessary to check that, because + we compare elements from these two + groups. searching on left*/ + + else if (i > 0 && j < m && b[j] < a[i - 1]) + max_index = i - 1; + +/* we have found the desired halves.*/ + + else + { +/* this condition happens when we + don't have any elements in the + first half from a[] so we + returning the last element in + b[] from the first half.*/ + + if (i == 0) + median = b[j - 1]; + +/* and this condition happens when + we don't have any elements in the + first half from b[] so we + returning the last element in + a[] from the first half.*/ + + else if (j == 0) + median = a[i - 1]; + else + median = maximum(a[i - 1], + b[j - 1]); + break; + } + } + +/* calculating the median. + If number of elements is odd + there is one middle element.*/ + + if ((n + m) % 2 == 1) + return (double)median; + +/* Elements from a[] in the + second half is an empty set.*/ + + if (i == n) + return (median + b[j]) / 2.0; + +/* Elements from b[] in the + second half is an empty set.*/ + + if (j == m) + return (median + a[i]) / 2.0; + + return (median + minimum(a[i], + b[j])) / 2.0; + } + +/* Driver code*/ + + public static void main(String args[]) + { + int n = a.length; + int m = b.length; + +/* we need to define the + smaller array as the + first parameter to + make sure that the + time complexity will + be O(log(min(n,m)))*/ + + if (n < m) + System.out.print(""The median is : "" + + findMedianSortedArrays(n, m)); + else + System.out.print(""The median is : "" + + findMedianSortedArrays(m, n)); + } +} + + +"," '''Python code for median with +case of returning double +value when even number +of elements are present +in both array combinely''' + +median = 0 +i = 0 +j = 0 + + '''def to find max''' + +def maximum(a, b) : + return a if a > b else b + + '''def to find minimum''' + +def minimum(a, b) : + return a if a < b else b + + '''def to find median +of two sorted arrays''' + +def findMedianSortedArrays(a, n, b, m) : + + global median, i, j + min_index = 0 + max_index = n + + while (min_index <= max_index) : + + i = int((min_index + max_index) / 2) + j = int(((n + m + 1) / 2) - i) + + ''' if i = n, it means that + Elements from a[] in the + second half is an empty + set. and if j = 0, it + means that Elements from + b[] in the first half is + an empty set. so it is + necessary to check that, + because we compare elements + from these two groups. + Searching on right''' + + if (i < n and j > 0 and b[j - 1] > a[i]) : + min_index = i + 1 + + ''' if i = 0, it means that + Elements from a[] in the + first half is an empty + set and if j = m, it means + that Elements from b[] in + the second half is an empty + set. so it is necessary to + check that, because we compare + elements from these two groups. + searching on left''' + + elif (i > 0 and j < m and b[j] < a[i - 1]) : + max_index = i - 1 + + ''' we have found the + desired halves.''' + + else : + + ''' this condition happens when + we don't have any elements + in the first half from a[] + so we returning the last + element in b[] from the + first half.''' + + if (i == 0) : + median = b[j - 1] + + ''' and this condition happens + when we don't have any + elements in the first half + from b[] so we returning the + last element in a[] from the + first half.''' + + elif (j == 0) : + median = a[i - 1] + else : + median = maximum(a[i - 1], b[j - 1]) + break + + + + ''' calculating the median. + If number of elements + is odd there is + one middle element.''' + + + if ((n + m) % 2 == 1) : + return median + + ''' Elements from a[] in the + second half is an empty set.''' + + if (i == n) : + return ((median + b[j]) / 2.0) + + ''' Elements from b[] in the + second half is an empty set.''' + + if (j == m) : + return ((median + a[i]) / 2.0) + + return ((median + minimum(a[i], b[j])) / 2.0) + + + '''Driver code''' + +a = [900] +b = [10, 13, 14] +n = len(a) +m = len(b) + + '''we need to define the +smaller array as the +first parameter to make +sure that the time complexity +will be O(log(min(n,m)))''' + +if (n < m) : + print (""The median is : {}"".format(findMedianSortedArrays(a, n, b, m))) +else : + echo (""The median is : {}"".format(findMedianSortedArrays(b, m, a, n))) + + +" +Number of paths with exactly k coins,"/*A Naive Recursive Java program to +count paths with exactly 'k' coins */ + +class GFG { + static final int R = 3; + static final int C = 3; +/*Recursive function to count paths with sum k from +(0, 0) to (m, n)*/ + + static int pathCountRec(int mat[][], int m, int n, int k) { +/* Base cases*/ + + if (m < 0 || n < 0) { + return 0; + } + if (m == 0 && n == 0 && (k == mat[m][n])) { + return 1; + } +/* (m, n) can be reached either through (m-1, n) or + through (m, n-1)*/ + + return pathCountRec(mat, m - 1, n, k - mat[m][n]) + + pathCountRec(mat, m, n - 1, k - mat[m][n]); + } +/*A wrapper over pathCountRec()*/ + + static int pathCount(int mat[][], int k) { + return pathCountRec(mat, R - 1, C - 1, k); + } +/* Driver code*/ + + public static void main(String[] args) { + int k = 12; + int mat[][] = {{1, 2, 3}, + {4, 6, 5}, + {3, 2, 1} + }; + System.out.println(pathCount(mat, k)); + } +}"," '''A Naive Recursive Python program to +count paths with exactly 'k' coins''' + +R = 3 +C = 3 + '''Recursive function to count paths +with sum k from (0, 0) to (m, n)''' + +def pathCountRec(mat, m, n, k): + ''' Base cases''' + + if m < 0 or n < 0: + return 0 + elif m == 0 and n == 0: + return k == mat[m][n] + '''(m, n) can be reached either + + through (m-1, n) or through + (m, n-1)''' + + return (pathCountRec(mat, m-1, n, k-mat[m][n]) + + pathCountRec(mat, m, n-1, k-mat[m][n])) + '''A wrapper over pathCountRec()''' + +def pathCount(mat, k): + return pathCountRec(mat, R-1, C-1, k) + '''Driver Program''' + +k = 12 +mat = [[1, 2, 3], + [4, 6, 5], + [3, 2, 1]] +print(pathCount(mat, k))" +"Sort an array of 0s, 1s and 2s","/*Java program to sort an array of 0, 1 and 2*/ + +import java.io.*; +class countzot { +/* Sort the input array, the array is assumed to + have values in {0, 1, 2}*/ + + static void sort012(int a[], int arr_size) + { + int lo = 0; + int hi = arr_size - 1; + int mid = 0, temp = 0; + while (mid <= hi) { + switch (a[mid]) { + case 0: { + temp = a[lo]; + a[lo] = a[mid]; + a[mid] = temp; + lo++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[hi]; + a[hi] = temp; + hi--; + break; + } + } + } + } + /* Utility function to print array arr[] */ + + static void printArray(int arr[], int arr_size) + { + int i; + for (i = 0; i < arr_size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(""""); + } + /*Driver function to check for above functions*/ + + public static void main(String[] args) + { + int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; + int arr_size = arr.length; + sort012(arr, arr_size); + System.out.println(""Array after seggregation ""); + printArray(arr, arr_size); + } +}"," '''Python program to sort an array with +0, 1 and 2 in a single pass''' + '''Function to sort array''' + +def sort012( a, arr_size): + lo = 0 + hi = arr_size - 1 + mid = 0 + while mid <= hi: + if a[mid] == 0: + a[lo], a[mid] = a[mid], a[lo] + lo = lo + 1 + mid = mid + 1 + elif a[mid] == 1: + mid = mid + 1 + else: + a[mid], a[hi] = a[hi], a[mid] + hi = hi - 1 + return a + '''Function to print array''' + +def printArray( a): + for k in a: + print k, + '''Driver Program''' + +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +arr_size = len(arr) +arr = sort012( arr, arr_size) +print ""Array after segregation :\n"", +printArray(arr) +" +Elements that occurred only once in the array,"/*Java implementation to find elements +that appeared only once*/ + +import java.util.*; +import java.io.*; + +class GFG +{ +/* Function to find the elements that + appeared only once in the array*/ + + static void occurredOnce(int[] arr, int n) + { + HashMap mp = new HashMap<>(); + +/* Store all the elements in the map with + their occurrence*/ + + for (int i = 0; i < n; i++) + { + if (mp.containsKey(arr[i])) + mp.put(arr[i], 1 + mp.get(arr[i])); + else + mp.put(arr[i], 1); + } + +/* Traverse the map and print all the + elements with occurrence 1*/ + + for (Map.Entry entry : mp.entrySet()) + { + if (Integer.parseInt(String.valueOf(entry.getValue())) == 1) + System.out.print(entry.getKey() + "" ""); + } + } + +/* Driver code*/ + + public static void main(String args[]) + { + int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; + int n = arr.length; + + occurredOnce(arr, n); + } +} + + +"," '''Python3 implementation to find elements +that appeared only once''' + +import math as mt + + '''Function to find the elements that +appeared only once in the array''' + +def occurredOnce(arr, n): + + mp = dict() + + ''' Store all the elements in the + map with their occurrence''' + + for i in range(n): + if arr[i] in mp.keys(): + mp[arr[i]] += 1 + else: + mp[arr[i]] = 1 + + ''' Traverse the map and print all + the elements with occurrence 1''' + + for it in mp: + if mp[it] == 1: + print(it, end = "" "") + + '''Driver code''' + +arr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2] +n = len(arr) + +occurredOnce(arr, n) + + +" +Split the array and add the first part to the end,"/*Java program to split array and move first +part to end.*/ + +import java.util.*; +import java.lang.*; +class GFG { +/* Function to spilt array and + move first part to end*/ + + public static void SplitAndAdd(int[] A,int length,int rotation){ +/* make a temporary array with double the size*/ + + int[] tmp = new int[length*2]; +/* copy array element in to new array twice*/ + + System.arraycopy(A, 0, tmp, 0, length); + System.arraycopy(A, 0, tmp, length, length); + for(int i=rotation;i=0) + { +/* If this pair is closer to x than the previously + found closest, then update res_l, res_r and diff*/ + + if (Math.abs(ar1[l] + ar2[r] - x) < diff) + { + res_l = l; + res_r = r; + diff = Math.abs(ar1[l] + ar2[r] - x); + } +/* If sum of this pair is more than x, move to smaller + side*/ + + if (ar1[l] + ar2[r] > x) + r--; +/*move to the greater side*/ + +else + l++; + } +/* Print the result*/ + + System.out.print(""The closest pair is ["" + ar1[res_l] + + "", "" + ar2[res_r] + ""]""); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + ClosestPair ob = new ClosestPair(); + int ar1[] = {1, 4, 5, 7}; + int ar2[] = {10, 20, 30, 40}; + int m = ar1.length; + int n = ar2.length; + int x = 38; + ob.printClosest(ar1, ar2, m, n, x); + } +}"," '''Python3 program to find the pair from +two sorted arays such that the sum +of pair is closest to a given number x''' + +import sys + '''ar1[0..m-1] and ar2[0..n-1] are two +given sorted arrays and x is given +number. This function prints the pair +from both arrays such that the sum +of the pair is closest to x.''' + +def printClosest(ar1, ar2, m, n, x): + ''' Initialize the diff between + pair sum and x.''' + + diff=sys.maxsize + ''' res_l and res_r are result + indexes from ar1[] and ar2[] + respectively.''' + ''' Start from left + side of ar1[] and right side of ar2[]''' + + l = 0 + r = n-1 + while(l < m and r >= 0): ''' If this pair is closer to x than + the previously found closest, + then update res_l, res_r and diff''' + + if abs(ar1[l] + ar2[r] - x) < diff: + res_l = l + res_r = r + diff = abs(ar1[l] + ar2[r] - x) + ''' If sum of this pair is more than x, + move to smaller side''' + + if ar1[l] + ar2[r] > x: + r=r-1 + '''move to the greater side''' + + else: + l=l+1 + ''' Print the result''' + + print(""The closest pair is ["", + ar1[res_l],"","",ar2[res_r],""]"") + '''Driver program to test above functions''' + +ar1 = [1, 4, 5, 7] +ar2 = [10, 20, 30, 40] +m = len(ar1) +n = len(ar2) +x = 38 +printClosest(ar1, ar2, m, n, x)" +Minimum Product Spanning Tree,"/*A Java program for getting minimum product +spanning tree The program is for adjacency matrix +representation of the graph*/ + +import java.util.*; +class GFG { +/* Number of vertices in the graph*/ + + static int V = 5; +/* A utility function to find the vertex with minimum + key value, from the set of vertices not yet included + in MST*/ + + static int minKey(int key[], boolean[] mstSet) + { +/* Initialize min value*/ + + int min = Integer.MAX_VALUE, min_index = 0; + for (int v = 0; v < V; v++) { + if (mstSet[v] == false && key[v] < min) { + min = key[v]; + min_index = v; + } + } + return min_index; + } +/* A utility function to print the constructed MST + stored in parent[] and print Minimum Obtaiable + product*/ + + static void printMST(int parent[], int n, int graph[][]) + { + System.out.printf(""Edge Weight\n""); + int minProduct = 1; + for (int i = 1; i < V; i++) { + System.out.printf(""%d - %d %d \n"", + parent[i], i, graph[i][parent[i]]); + minProduct *= graph[i][parent[i]]; + } + System.out.printf(""Minimum Obtainable product is %d\n"", + minProduct); + } +/* Function to construct and print MST for a graph + represented using adjacency matrix representation + inputGraph is sent for printing actual edges and + logGraph is sent for actual MST operations*/ + + static void primMST(int inputGraph[][], double logGraph[][]) + { +/*Array to store constructed MST*/ + +int[] parent = new int[V]; +/*Key values used to pick minimum*/ + +int[] key = new int[V]; +/* weight edge in cut +To represent set of vertices not*/ + +boolean[] mstSet = new boolean[V]; +/* yet included in MST + Initialize all keys as INFINITE*/ + + for (int i = 0; i < V; i++) { + key[i] = Integer.MAX_VALUE; + mstSet[i] = false; + } +/* Always include first 1st vertex in MST. +Make key 0 so that this vertex is*/ + +key[0] = 0; +/* picked as first vertex +First node is always root of MST*/ + +parent[0] = -1; +/* The MST will have V vertices*/ + + for (int count = 0; count < V - 1; count++) { +/* Pick the minimum key vertex from the set of + vertices not yet included in MST*/ + + int u = minKey(key, mstSet); +/* Add the picked vertex to the MST Set*/ + + mstSet[u] = true; +/* Update key value and parent index of the + adjacent vertices of the picked vertex. + Consider only those vertices which are not yet + included in MST +logGraph[u][v] is non zero only for*/ + +for (int v = 0; v < V; v++) +/* adjacent vertices of m mstSet[v] is false + for vertices not yet included in MST + Update the key only if logGraph[u][v] is + smaller than key[v]*/ + + { + if (logGraph[u][v] > 0 + && mstSet[v] == false + && logGraph[u][v] < key[v]) { + parent[v] = u; + key[v] = (int)logGraph[u][v]; + } + } + } +/* print the constructed MST*/ + + printMST(parent, V, inputGraph); + } +/* Method to get minimum product spanning tree*/ + + static void minimumProductMST(int graph[][]) + { + double[][] logGraph = new double[V][V]; +/* Constructing logGraph from original graph*/ + + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { + if (graph[i][j] > 0) { + logGraph[i][j] = Math.log(graph[i][j]); + } + else { + logGraph[i][j] = 0; + } + } + } +/* Applyting standard Prim's MST algorithm on + Log graph.*/ + + primMST(graph, logGraph); + } +/* Driver code*/ + + public static void main(String[] args) + { + /* Let us create the following graph + 2 3 + (0)--(1)--(2) + | / \ | + 6| 8/ \5 |7 + | / \ | + (3)-------(4) + 9 */ + + int graph[][] = { + { 0, 2, 0, 6, 0 }, + { 2, 0, 3, 8, 5 }, + { 0, 3, 0, 0, 7 }, + { 6, 8, 0, 0, 9 }, + { 0, 5, 7, 9, 0 }, + }; +/* Print the solution*/ + + minimumProductMST(graph); + } +}"," '''A Python3 program for getting minimum +product spanning tree The program is +for adjacency matrix representation +of the graph''' + +import math + '''Number of vertices in the graph''' + +V = 5 + '''A utility function to find the vertex +with minimum key value, from the set +of vertices not yet included in MST''' + +def minKey(key, mstSet): + ''' Initialize min value''' + + min = 10000000 + min_index = 0 + for v in range(V): + if (mstSet[v] == False and + key[v] < min): + min = key[v] + min_index = v + return min_index + '''A utility function to print the constructed +MST stored in parent[] and print Minimum +Obtaiable product''' + +def printMST(parent, n, graph): + print(""Edge Weight"") + minProduct = 1 + for i in range(1, V): + print(""{} - {} {} "".format(parent[i], i, + graph[i][parent[i]])) + minProduct *= graph[i][parent[i]] + print(""Minimum Obtainable product is {}"".format( + minProduct)) + '''Function to construct and print MST for +a graph represented using adjacency +matrix representation inputGraph is +sent for printing actual edges and +logGraph is sent for actual MST +operations''' + +def primMST(inputGraph, logGraph): + ''' Array to store constructed MST''' + + parent = [0 for i in range(V)] + ''' Key values used to pick minimum''' + + key = [10000000 for i in range(V)] + ''' weight edge in cut + To represent set of vertices not''' + + mstSet = [False for i in range(V)] + ''' Always include first 1st vertex in MST + Make key 0 so that this vertex is''' + + key[0] = 0 + ''' Picked as first vertex + First node is always root of MST''' + + parent[0] = -1 + ''' The MST will have V vertices''' + + for count in range(0, V - 1): + ''' Pick the minimum key vertex from + the set of vertices not yet + included in MST''' + + u = minKey(key, mstSet) + ''' Add the picked vertex to the MST Set''' + + mstSet[u] = True + ''' Update key value and parent index + of the adjacent vertices of the + picked vertex. Consider only those + vertices which are not yet + included in MST''' + + for v in range(V): + ''' logGraph[u][v] is non zero only + for adjacent vertices of m + mstSet[v] is false for vertices + not yet included in MST. Update + the key only if logGraph[u][v] is + smaller than key[v]''' + + if (logGraph[u][v] > 0 and + mstSet[v] == False and + logGraph[u][v] < key[v]): + parent[v] = u + key[v] = logGraph[u][v] + ''' Print the constructed MST''' + + printMST(parent, V, inputGraph) + '''Method to get minimum product spanning tree''' + +def minimumProductMST(graph): + logGraph = [[0 for j in range(V)] + for i in range(V)] + ''' Constructing logGraph from + original graph''' + + for i in range(V): + for j in range(V): + if (graph[i][j] > 0): + logGraph[i][j] = math.log(graph[i][j]) + else: + logGraph[i][j] = 0 + ''' Applyting standard Prim's MST algorithm + on Log graph.''' + + primMST(graph, logGraph) + '''Driver code''' + +if __name__=='__main__': + ''' Let us create the following graph + 2 3 + (0)--(1)--(2) + | / \ | + 6| 8/ \5 |7 + | / \ | + (3)-------(4) + 9 ''' + + graph = [ [ 0, 2, 0, 6, 0 ], + [ 2, 0, 3, 8, 5 ], + [ 0, 3, 0, 0, 7 ], + [ 6, 8, 0, 0, 9 ], + [ 0, 5, 7, 9, 0 ], ] + ''' Print the solution''' + + minimumProductMST(graph)" +Pairs of Positive Negative values in an array,"/*Java program to find pairs of positive +and negative values present in an array.*/ + +import java.util.*; +import java.lang.*; +class GFG { +/* Print pair with negative and positive value*/ + + public static void printPairs(int arr[] , int n) + { + Vector v = new Vector(); +/* For each element of array.*/ + + for (int i = 0; i < n; i++) +/* Try to find the negative value of + arr[i] from i + 1 to n*/ + + for (int j = i + 1; j < n; j++) +/* If absolute values are equal + print pair.*/ + + if (Math.abs(arr[i]) == + Math.abs(arr[j])) + v.add(Math.abs(arr[i])); +/* If size of vector is 0, therefore there + is no element with positive negative + value, print ""0""*/ + + if (v.size() == 0) + return; +/* Sort the vector*/ + + Collections.sort(v); +/* Print the pair with negative positive + value.*/ + + for (int i = 0; i < v.size(); i++) + System.out.print(-v.get(i) + "" "" + + v.get(i)); + } +/* Driven Program*/ + + public static void main(String[] args) + { + int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; + int n = arr.length; + printPairs(arr, n); + } +}"," '''Simple Python 3 program to find +pairs of positive and negative +values present in an array. + ''' '''Print pair with negative and +positive value''' + +def printPairs(arr, n): + v = [] + ''' For each element of array.''' + + for i in range(n): + ''' Try to find the negative value + of arr[i] from i + 1 to n''' + + for j in range( i + 1,n) : + ''' If absolute values are + equal print pair.''' + + if (abs(arr[i]) == abs(arr[j])) : + v.append(abs(arr[i])) + ''' If size of vector is 0, therefore + there is no element with positive + negative value, print ""0""''' + + if (len(v) == 0): + return; + ''' Sort the vector''' + + v.sort() + ''' Print the pair with negative + positive value.''' + + for i in range(len( v)): + print(-v[i], """" , v[i], end = "" "") + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ] + n = len(arr) + printPairs(arr, n)" +Practice questions for Linked List and Recursion,"static void fun2(Node head) +{ + if (head == null) + { + return; + } + System.out.print(head.data + "" ""); + if (head.next != null) + { + fun2(head.next.next); + } + System.out.print(head.data + "" ""); +}","def fun2(head): + if(head == None): + return + print(head.data, end = "" "") + if(head.next != None ): + fun2(head.next.next) + print(head.data, end = "" "")" +Center element of matrix equals sums of half diagonals,"/*Java program to find maximum elements +that can be made equal with k updates*/ + +import java.util.Arrays; +public class GFG { + static int MAX = 100; +/* Function to Check center element + is equal to the individual + sum of all the half diagonals*/ + + static boolean HalfDiagonalSums(int mat[][], + int n) + { +/* Find sums of half diagonals*/ + + int diag1_left = 0, diag1_right = 0; + int diag2_left = 0, diag2_right = 0; + for (int i = 0, j = n - 1; i < n; + i++, j--) + { + if (i < n/2) { + diag1_left += mat[i][i]; + diag2_left += mat[j][i]; + } + else if (i > n/2) { + diag1_right += mat[i][i]; + diag2_right += mat[j][i]; + } + } + return (diag1_left == diag2_right && + diag2_right == diag2_left && + diag1_right == diag2_left && + diag2_right == mat[n/2][n/2]); + } +/* Driver code*/ + + public static void main(String args[]) + { + int a[][] = { { 2, 9, 1, 4, -2}, + { 6, 7, 2, 11, 4}, + { 4, 2, 9, 2, 4}, + { 1, 9, 2, 4, 4}, + { 0, 2, 4, 2, 5} }; + System.out.print ( HalfDiagonalSums(a, 5) + ? ""Yes"" : ""No"" ); + } +}"," '''Python 3 Program to check if the center +element is equal to the individual +sum of all the half diagonals''' + +MAX = 100 + '''Function to Check center element +is equal to the individual +sum of all the half diagonals''' + +def HalfDiagonalSums( mat, n): + ''' Find sums of half diagonals''' + + diag1_left = 0 + diag1_right = 0 + diag2_left = 0 + diag2_right = 0 + i = 0 + j = n - 1 + while i < n: + if (i < n//2) : + diag1_left += mat[i][i] + diag2_left += mat[j][i] + elif (i > n//2) : + diag1_right += mat[i][i] + diag2_right += mat[j][i] + i += 1 + j -= 1 + return (diag1_left == diag2_right and + diag2_right == diag2_left and + diag1_right == diag2_left and + diag2_right == mat[n//2][n//2]) + '''Driver code''' + +if __name__ == ""__main__"": + a = [[2, 9, 1, 4, -2], + [6, 7, 2, 11, 4], + [ 4, 2, 9, 2, 4], + [1, 9, 2, 4, 4 ], + [ 0, 2, 4, 2, 5]] + print(""Yes"") if (HalfDiagonalSums(a, 5)) else print(""No"" )" +Find sum of all elements in a matrix except the elements in row and/or column of given cell?,"/*Java implementation of the approach*/ + +class GFG +{ + static int R = 3; + static int C = 3; +/* A structure to represent a cell index*/ + + static class Cell + { +/*r is row, varies from 0 to R-1*/ + +int r; +/*c is column, varies from 0 to C-1*/ + +int c; + +/*Constructor*/ + + public Cell(int r, int c) + { + this.r = r; + this.c = c; + } + };/* A simple solution to find sums for + a given array of cell indexes*/ + + static void printSums(int mat[][], Cell arr[], int n) + { +/* Iterate through all cell indexes*/ + + for (int i = 0; i < n; i++) + { + int sum = 0, r = arr[i].r, c = arr[i].c; +/* Compute sum for current cell index*/ + + for (int j = 0; j < R; j++) + { + for (int k = 0; k < C; k++) + { + if (j != r && k != c) + { + sum += mat[j][k]; + } + } + } + System.out.println(sum); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int mat[][] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; + Cell arr[] = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; + int n = arr.length; + printSums(mat, arr, n); + } +}"," '''Python3 implementation of the approach''' + + '''A structure to represent a cell index''' + +class Cell: + def __init__(self, r, c): '''r is row, varies from 0 to R-1''' + + self.r = r + + '''c is column, varies from 0 to C-1''' + + self.c = c + '''A simple solution to find sums +for a given array of cell indexes''' + +def printSums(mat, arr, n): + ''' Iterate through all cell indexes''' + + for i in range(0, n): + Sum = 0; r = arr[i].r; c = arr[i].c + ''' Compute sum for current cell index''' + + for j in range(0, R): + for k in range(0, C): + if j != r and k != c: + Sum += mat[j][k] + print(Sum) + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] + R = C = 3 + arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] + n = len(arr) + printSums(mat, arr, n)" +Program to find the minimum (or maximum) element of an array,"import java.util.Arrays; + +/*Java program to find minimum (or maximum) element +in an array.*/ + +import java.util.Arrays; + +class GFG { + + static int getMin(int arr[], int n) { + return Arrays.stream(arr).min().getAsInt(); + } + + static int getMax(int arr[], int n) { + return Arrays.stream(arr).max().getAsInt(); + } + +/*Driver code*/ + + public static void main(String[] args) { + int arr[] = {12, 1234, 45, 67, 1}; + int n = arr.length; + System.out.println(""Minimum element of array: "" + getMin(arr, n)); + System.out.println(""Maximum element of array: "" + getMax(arr, n)); + } +} + +"," '''Python3 program to find minimum +(or maximum) element +in an array.''' + +def getMin(arr,n): + return min(arr) + +def getMax(arr,n): + return max(arr) + + '''Driver Code''' + +if __name__=='__main__': + arr = [12,1234,45,67,1] + n = len(arr) + print(""Minimum element of array: "" + ,getMin(arr, n)) + print(""Maximum element of array: "" + ,getMax(arr, n)) + + +" +Check if an array has a majority element,"/*Hashing based Java program +to find if there is a +majority element in input array.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class Gfg +{ +/* Returns true if there is a + majority element in a[]*/ + + static boolean isMajority(int a[], int n) + { +/* Insert all elements + in a hash table*/ + + HashMap mp = new + HashMap(); + for (int i = 0; i < n; i++) + if (mp.containsKey(a[i])) + mp.put(a[i], mp.get(a[i]) + 1); + else mp.put(a[i] , 1); +/* Check if frequency of any + element is n/2 or more.*/ + + for (Map.Entry x : mp.entrySet()) + if (x.getValue() >= n/2) + return true; + return false; + } +/* Driver code*/ + + public static void main (String[] args) + { + int a[] = { 2, 3, 9, 2, 2 }; + int n = a.length; + if (isMajority(a, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Hashing based Python +program to find if +there is a majority +element in input array. + ''' '''Returns true if there +is a majority element +in a[]''' + +def isMajority(a): + ''' Insert all elements + in a hash table''' + + mp = {} + for i in a: + if i in mp: mp[i] += 1 + else: mp[i] = 1 + ''' Check if frequency + of any element is + n/2 or more.''' + + for x in mp: + if mp[x] >= len(a)//2: + return True + return False + '''Driver code''' + +a = [ 2, 3, 9, 2, 2 ] +print(""Yes"" if isMajority(a) else ""No"")" +Count and Toggle Queries on a Binary Array,"/*Java program to implement toggle and +count queries on a binary array.*/ + + +class GFG +{ +static final int MAX = 100000; + +/*segment tree to store count +of 1's within range*/ + +static int tree[] = new int[MAX]; + +/*bool type tree to collect the updates +for toggling the values of 1 and 0 in +given range*/ + +static boolean lazy[] = new boolean[MAX]; + +/*function for collecting updates of toggling +node --> index of current node in segment tree +st --> starting index of current node +en --> ending index of current node +us --> starting index of range update query +ue --> ending index of range update query*/ + +static void toggle(int node, int st, + int en, int us, int ue) +{ +/* If lazy value is non-zero for current + node of segment tree, then there are + some pending updates. So we need + to make sure that the pending updates + are done before making new updates. + Because this value may be used by + parent after recursive calls (See last + line of this function)*/ + + if (lazy[node]) + { + +/* Make pending updates using value + stored in lazy nodes*/ + + lazy[node] = false; + tree[node] = en - st + 1 - tree[node]; + +/* checking if it is not leaf node + because if it is leaf node then + we cannot go further*/ + + if (st < en) + { +/* We can postpone updating children + we don't need their new values now. + Since we are not yet updating children + of 'node', we need to set lazy flags + for the children*/ + + lazy[node << 1] = !lazy[node << 1]; + lazy[1 + (node << 1)] = !lazy[1 + (node << 1)]; + } + } + +/* out of range*/ + + if (st > en || us > en || ue < st) + { + return; + } + +/* Current segment is fully in range*/ + + if (us <= st && en <= ue) + { +/* Add the difference to current node*/ + + tree[node] = en - st + 1 - tree[node]; + +/* same logic for checking leaf node or not*/ + + if (st < en) + { +/* This is where we store values in lazy nodes, + rather than updating the segment tree itelf + Since we don't need these updated values now + we postpone updates by storing values in lazy[]*/ + + lazy[node << 1] = !lazy[node << 1]; + lazy[1 + (node << 1)] = !lazy[1 + (node << 1)]; + } + return; + } + +/* If not completely in rang, + but overlaps, recur for children,*/ + + int mid = (st + en) / 2; + toggle((node << 1), st, mid, us, ue); + toggle((node << 1) + 1, mid + 1, en, us, ue); + +/* And use the result of children + calls to update this node*/ + + if (st < en) + { + tree[node] = tree[node << 1] + + tree[(node << 1) + 1]; + } +} + +/* node --> Index of current node in the segment tree. + Initially 0 is passed as root is always at' + index 0 +st & en --> Starting and ending indexes of the + segment represented by current node, + i.e., tree[node] +qs & qe --> Starting and ending indexes of query + range */ + +/*function to count number of 1's +within given range*/ + +static int countQuery(int node, int st, + int en, int qs, int qe) +{ +/* current node is out of range*/ + + if (st > en || qs > en || qe < st) + { + return 0; + } + +/* If lazy flag is set for current + node of segment tree, then there + are some pending updates. So we + need to make sure that the pending + updates are done before processing + the sub sum query*/ + + if (lazy[node]) + { +/* Make pending updates to this node. + Note that this node represents sum + of elements in arr[st..en] and + all these elements must be increased + by lazy[node]*/ + + lazy[node] = false; + tree[node] = en - st + 1 - tree[node]; + +/* checking if it is not leaf node because if + it is leaf node then we cannot go further*/ + + if (st < en) + { +/* Since we are not yet updating children os si, + we need to set lazy values for the children*/ + + lazy[node << 1] = !lazy[node << 1]; + lazy[(node << 1) + 1] = !lazy[(node << 1) + 1]; + } + } + +/* At this point we are sure that pending + lazy updates are done for current node. + So we can return value If this segment + lies in range*/ + + if (qs <= st && en <= qe) + { + return tree[node]; + } + +/* If a part of this segment overlaps + with the given range*/ + + int mid = (st + en) / 2; + return countQuery((node << 1), st, mid, qs, qe) + + countQuery((node << 1) + 1, mid + 1, en, qs, qe); +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + int n = 5; +/*Toggle 1 2*/ + +toggle(1, 0, n - 1, 1, 2); +/*Toggle 2 4*/ + +toggle(1, 0, n - 1, 2, 4); + +/*Count 2 3*/ + +System.out.println(countQuery(1, 0, n - 1, 2, 3)); + +/*Toggle 2 4*/ + +toggle(1, 0, n - 1, 2, 4); + +/*Count 1 4*/ + +System.out.println(countQuery(1, 0, n - 1, 1, 4)); +} +} + + +"," '''Python program to implement toggle and count +queries on a binary array.''' + +MAX = 100000 + + '''segment tree to store count of 1's within range''' + +tree = [0] * MAX + + '''bool type tree to collect the updates for toggling +the values of 1 and 0 in given range''' + +lazy = [False] * MAX + + '''function for collecting updates of toggling +node --> index of current node in segment tree +st --> starting index of current node +en --> ending index of current node +us --> starting index of range update query +ue --> ending index of range update query''' + +def toggle(node: int, st: int, en: int, us: int, ue: int): + + ''' If lazy value is non-zero for current node of segment + tree, then there are some pending updates. So we need + to make sure that the pending updates are done before + making new updates. Because this value may be used by + parent after recursive calls (See last line of this + function)''' + + if lazy[node]: + + ''' Make pending updates using value stored in lazy nodes''' + + lazy[node] = False + tree[node] = en - st + 1 - tree[node] + + ''' checking if it is not leaf node because if + it is leaf node then we cannot go further''' + + if st < en: + + ''' We can postpone updating children we don't + need their new values now. + Since we are not yet updating children of 'node', + we need to set lazy flags for the children''' + + lazy[node << 1] = not lazy[node << 1] + lazy[1 + (node << 1)] = not lazy[1 + (node << 1)] + + ''' out of range''' + + if st > en or us > en or ue < st: + return + + ''' Current segment is fully in range''' + + if us <= st and en <= ue: + + ''' Add the difference to current node''' + + tree[node] = en - st + 1 - tree[node] + + ''' same logic for checking leaf node or not''' + + if st < en: + + ''' This is where we store values in lazy nodes, + rather than updating the segment tree itelf + Since we don't need these updated values now + we postpone updates by storing values in lazy[]''' + + lazy[node << 1] = not lazy[node << 1] + lazy[1 + (node << 1)] = not lazy[1 + (node << 1)] + return + + ''' If not completely in rang, but overlaps, recur for + children,''' + + mid = (st + en) // 2 + toggle((node << 1), st, mid, us, ue) + toggle((node << 1) + 1, mid + 1, en, us, ue) + + ''' And use the result of children calls to update this node''' + + if st < en: + tree[node] = tree[node << 1] + tree[(node << 1) + 1] + + '''node --> Index of current node in the segment tree. + Initially 0 is passed as root is always at' + index 0 +st & en --> Starting and ending indexes of the + segment represented by current node, + i.e., tree[node] +qs & qe --> Starting and ending indexes of query + range''' + + + '''function to count number of 1's within given range''' + +def countQuery(node: int, st: int, en: int, qs: int, qe: int) -> int: ''' current node is out of range''' + + if st > en or qs > en or qe < st: + return 0 + + ''' If lazy flag is set for current node of segment tree, + then there are some pending updates. So we need to + make sure that the pending updates are done before + processing the sub sum query''' + + if lazy[node]: + + ''' Make pending updates to this node. Note that this + node represents sum of elements in arr[st..en] and + all these elements must be increased by lazy[node]''' + + lazy[node] = False + tree[node] = en - st + 1 - tree[node] + + ''' checking if it is not leaf node because if + it is leaf node then we cannot go further''' + + if st < en: + + ''' Since we are not yet updating children os si, + we need to set lazy values for the children''' + + lazy[node << 1] = not lazy[node << 1] + lazy[(node << 1) + 1] = not lazy[(node << 1) + 1] + + ''' At this point we are sure that pending lazy updates + are done for current node. So we can return value + If this segment lies in range''' + + if qs <= st and en <= qe: + return tree[node] + + ''' If a part of this segment overlaps with the given range''' + + mid = (st + en) // 2 + return countQuery((node << 1), st, mid, qs, qe) + countQuery( + (node << 1) + 1, mid + 1, en, qs, qe) + + '''Driver Code''' + +if __name__ == ""__main__"": + + n = 5 + '''Toggle 1 2''' + +toggle(1, 0, n - 1, 1, 2) + '''Toggle 2 4''' + +toggle(1, 0, n - 1, 2, 4) + + '''count 2 3''' + +print(countQuery(1, 0, n - 1, 2, 3)) + + '''Toggle 2 4''' + +toggle(1, 0, n - 1, 2, 4) + + '''count 1 4''' + +print(countQuery(1, 0, n - 1, 1, 4)) + + +" +Iterative function to check if two trees are identical,"/* Iterative Java program to check if two */ + +import java.util.*; +class GfG { +/*A Binary Tree Node */ + +static class Node +{ + int data; + Node left, right; +} +/*Iterative method to find height of Binary Tree */ + +static boolean areIdentical(Node root1, Node root2) +{ +/* Return true if both trees are empty */ + + if (root1 == null && root2 == null) return true; +/* Return false if one is empty and other is not */ + + if (root1 == null || root2 == null) return false; +/* Create an empty queues for simultaneous traversals */ + + Queue q1 = new LinkedList (); + Queue q2 = new LinkedList (); +/* Enqueue Roots of trees in respective queues */ + + q1.add(root1); + q2.add(root2); + while (!q1.isEmpty() && !q2.isEmpty()) + { +/* Get front nodes and compare them */ + + Node n1 = q1.peek(); + Node n2 = q2.peek(); + if (n1.data != n2.data) + return false; +/* Remove front nodes from queues */ + + q1.remove(); + q2.remove(); + /* Enqueue left children of both nodes */ + + if (n1.left != null && n2.left != null) + { + q1.add(n1.left); + q2.add(n2.left); + } +/* If one left child is empty and other is not */ + + else if (n1.left != null || n2.left != null) + return false; +/* Right child code (Similar to left child code) */ + + if (n1.right != null && n2.right != null) + { + q1.add(n1.right); + q2.add(n2.right); + } + else if (n1.right != null || n2.right != null) + return false; + } + return true; +} +/*Utility function to create a new tree node */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} +/*Driver program to test above functions */ + +public static void main(String[] args) +{ + Node root1 = newNode(1); + root1.left = newNode(2); + root1.right = newNode(3); + root1.left.left = newNode(4); + root1.left.right = newNode(5); + Node root2 = newNode(1); + root2.left = newNode(2); + root2.right = newNode(3); + root2.left.left = newNode(4); + root2.left.right = newNode(5); + if(areIdentical(root1, root2) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Iterative Python3 program to check +if two trees are identical''' + +from queue import Queue + '''Utility function to create a +new tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Iterative method to find height of +Binary Tree ''' + +def areIdentical(root1, root2): + ''' Return true if both trees are empty ''' + + if (root1 and root2): + return True + ''' Return false if one is empty and + other is not ''' + + if (root1 or root2): + return False + ''' Create an empty queues for + simultaneous traversals ''' + + q1 = Queue() + q2 = Queue() + ''' Enqueue Roots of trees in + respective queues ''' + + q1.put(root1) + q2.put(root2) + while (not q1.empty() and not q2.empty()): + ''' Get front nodes and compare them ''' + + n1 = q1.queue[0] + n2 = q2.queue[0] + if (n1.data != n2.data): + return False + ''' Remove front nodes from queues ''' + + q1.get() + q2.get() + ''' Enqueue left children of both nodes ''' + + if (n1.left and n2.left): + q1.put(n1.left) + q2.put(n2.left) + ''' If one left child is empty and + other is not ''' + + elif (n1.left or n2.left): + return False + ''' Right child code (Similar to + left child code) ''' + + if (n1.right and n2.right): + q1.put(n1.right) + q2.put(n2.right) + elif (n1.right or n2.right): + return False + return True + '''Driver Code''' + +if __name__ == '__main__': + root1 = newNode(1) + root1.left = newNode(2) + root1.right = newNode(3) + root1.left.left = newNode(4) + root1.left.right = newNode(5) + root2 = newNode(1) + root2.left = newNode(2) + root2.right = newNode(3) + root2.left.left = newNode(4) + root2.left.right = newNode(5) + if areIdentical(root1, root2): + print(""Yes"") + else: + print(""No"")" +Merge two sorted lists (in-place),"/*Java program to merge two sorted +linked lists in-place.*/ + +class GFG { + + static class Node { + int data; + Node next; + }; + +/* Function to create newNode in a linkedlist*/ + + static Node newNode(int key) + { + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; + } + +/* A utility function to print linked list*/ + + static void printList(Node node) + { + while (node != null) { + System.out.printf(""%d "", node.data); + node = node.next; + } + } + +/* Merges two given lists in-place. This function + mainly compares head nodes and calls mergeUtil()*/ + + static Node merge(Node h1, Node h2) + { + if (h1 == null) + return h2; + if (h2 == null) + return h1; + +/* start with the linked list + whose head data is the least*/ + + if (h1.data < h2.data) { + h1.next = merge(h1.next, h2); + return h1; + } + else { + h2.next = merge(h1, h2.next); + return h2; + } + } + +/* Driver program*/ + + public static void main(String args[]) + { + Node head1 = newNode(1); + head1.next = newNode(3); + head1.next.next = newNode(5); + +/* 1.3.5 LinkedList created*/ + + + Node head2 = newNode(0); + head2.next = newNode(2); + head2.next.next = newNode(4); + +/* 0.2.4 LinkedList created*/ + + + Node mergedhead = merge(head1, head2); + + printList(mergedhead); + } +} + + +"," '''Python3 program to merge two +sorted linked lists in-place.''' + +import math + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to create newNode in a linkedlist''' + +def newNode( key): + temp = Node(key) + temp.data = key + temp.next = None + return temp + + '''A utility function to print linked list''' + +def printList( node): + while (node != None): + print(node.data, end = "" "") + node = node.next + + '''Merges two given lists in-place. +This function mainly compares +head nodes and calls mergeUtil()''' + +def merge( h1, h2): + if (h1 == None): + return h2 + if (h2 == None): + return h1 + + ''' start with the linked list + whose head data is the least''' + + if (h1.data < h2.data): + h1.next = merge(h1.next, h2) + return h1 + + else: + h2.next = merge(h1, h2.next) + return h2 + + '''Driver Code''' + +if __name__=='__main__': + head1 = newNode(1) + head1.next = newNode(3) + head1.next.next = newNode(5) + + ''' 1.3.5 LinkedList created''' + + head2 = newNode(0) + head2.next = newNode(2) + head2.next.next = newNode(4) + + ''' 0.2.4 LinkedList created''' + + mergedhead = merge(head1, head2) + + printList(mergedhead) + + +" +The Knight's tour problem | Backtracking-1,"/*Java program for Knight Tour problem*/ + +class KnightTour { + static int N = 8; + /* A utility function to check if i,j are + valid indexes for N*N chessboard */ + + static boolean isSafe(int x, int y, int sol[][]) + { + return (x >= 0 && x < N && y >= 0 && y < N + && sol[x][y] == -1); + } + /* A utility function to print solution + matrix sol[N][N] */ + + static void printSolution(int sol[][]) + { + for (int x = 0; x < N; x++) { + for (int y = 0; y < N; y++) + System.out.print(sol[x][y] + "" ""); + System.out.println(); + } + } + /* This function solves the Knight Tour problem + using Backtracking. This function mainly + uses solveKTUtil() to solve the problem. It + returns false if no complete tour is possible, + otherwise return true and prints the tour. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions. */ + + static boolean solveKT() + { + int sol[][] = new int[8][8]; + /* Initialization of solution matrix */ + + for (int x = 0; x < N; x++) + for (int y = 0; y < N; y++) + sol[x][y] = -1; + /* xMove[] and yMove[] define next move of Knight. + xMove[] is for next value of x coordinate + yMove[] is for next value of y coordinate */ + + int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; +/* Since the Knight is initially at the first block*/ + + sol[0][0] = 0; + /* Start from 0,0 and explore all tours using + solveKTUtil() */ + + if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { + System.out.println(""Solution does not exist""); + return false; + } + else + printSolution(sol); + return true; + } + /* A recursive utility function to solve Knight + Tour problem */ + + static boolean solveKTUtil(int x, int y, int movei, + int sol[][], int xMove[], + int yMove[]) + { + int k, next_x, next_y; + if (movei == N * N) + return true; + /* Try all next moves from the current coordinate + x, y */ + + for (k = 0; k < 8; k++) { + next_x = x + xMove[k]; + next_y = y + yMove[k]; + if (isSafe(next_x, next_y, sol)) { + sol[next_x][next_y] = movei; + if (solveKTUtil(next_x, next_y, movei + 1, + sol, xMove, yMove)) + return true; + else + +/*backtracking*/ + + sol[next_x][next_y]= -1; + } + } + return false; + } + /* Driver Code */ + + public static void main(String args[]) + { +/* Function Call*/ + + solveKT(); + } +}"," '''Python3 program to solve Knight Tour problem using Backtracking +Chessboard Size''' + +n = 8 + + ''' + A utility function to check if i,j are valid indexes + for N*N chessboard + ''' +def isSafe(x, y, board): + if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1): + return True + return False + + ''' + A utility function to print Chessboard matrix + ''' +def printSolution(n, board): + for i in range(n): + for j in range(n): + print(board[i][j], end=' ') + print() + + ''' + This function solves the Knight Tour problem using + Backtracking. This function mainly uses solveKTUtil() + to solve the problem. It returns false if no complete + tour is possible, otherwise return true and prints the + tour. + Please note that there may be more than one solutions, + this function prints one of the feasible solutions. + ''' +def solveKT(n): + ''' Initialization of Board matrix''' + + board = [[-1 for i in range(n)]for i in range(n)] + ''' move_x and move_y define next move of Knight. + move_x is for next value of x coordinate + move_y is for next value of y coordinate''' + + move_x = [2, 1, -1, -2, -2, -1, 1, 2] + move_y = [1, 2, 2, 1, -1, -2, -2, -1] + ''' Since the Knight is initially at the first block''' + + board[0][0] = 0 + ''' Checking if solution exists or not''' + + pos = 1 + if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)): + print(""Solution does not exist"") + else: + printSolution(n, board) + ''' + A recursive utility function to solve Knight Tour + problem + ''' +def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos): + if(pos == n**2): + return True + ''' Try all next moves from the current coordinate x, y''' + + for i in range(8): + new_x = curr_x + move_x[i] + new_y = curr_y + move_y[i] + if(isSafe(new_x, new_y, board)): + board[new_x][new_y] = pos + if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)): + return True + ''' Backtracking''' + + board[new_x][new_y] = -1 + return False + '''Driver Code''' + +if __name__ == ""__main__"": + ''' Function Call''' + + solveKT(n)" +Shortest path with exactly k edges in a directed and weighted graph,"/*Dynamic Programming based Java program to find shortest path with +exactly k edges*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class ShortestPath +{ +/* Define number of vertices in the graph and inifinite value*/ + + static final int V = 4; + static final int INF = Integer.MAX_VALUE; +/* A Dynamic programming based function to find the shortest path + from u to v with exactly k edges.*/ + + int shortestPath(int graph[][], int u, int v, int k) + { +/* Table to be filled up using DP. The value sp[i][j][e] will + store weight of the shortest path from i to j with exactly + k edges*/ + + int sp[][][] = new int[V][V][k+1]; +/* Loop for number of edges from 0 to k*/ + + for (int e = 0; e <= k; e++) + { +/*for source*/ + +for (int i = 0; i < V; i++) + { +/*for destination*/ + +for (int j = 0; j < V; j++) + { +/* initialize value*/ + + sp[i][j][e] = INF; +/* from base cases*/ + + if (e == 0 && i == j) + sp[i][j][e] = 0; + if (e == 1 && graph[i][j] != INF) + sp[i][j][e] = graph[i][j]; +/* go to adjacent only when number of edges is + more than 1*/ + + if (e > 1) + { + for (int a = 0; a < V; a++) + { +/* There should be an edge from i to a and + a should not be same as either i or j*/ + + if (graph[i][a] != INF && i != a && + j!= a && sp[a][j][e-1] != INF) + sp[i][j][e] = Math.min(sp[i][j][e], + graph[i][a] + sp[a][j][e-1]); + } + } + } + } + } + return sp[u][v][k]; + } + + /*driver program to test above function*/ + + public static void main (String[] args) + {/* Let us create the graph shown in above diagram*/ + + int graph[][] = new int[][]{ {0, 10, 3, 2}, + {INF, 0, INF, 7}, + {INF, INF, 0, 6}, + {INF, INF, INF, 0} + }; + ShortestPath t = new ShortestPath(); + int u = 0, v = 3, k = 2; + System.out.println(""Weight of the shortest path is ""+ + t.shortestPath(graph, u, v, k)); + } +}"," '''Dynamic Programming based Python3 +program to find shortest path with''' + + '''Define number of vertices in +the graph and inifinite value ''' + +V = 4 +INF = 999999999999 '''A Dynamic programming based function +to find the shortest path from u to v +with exactly k edges. ''' + +def shortestPath(graph, u, v, k): + global V, INF ''' Table to be filled up using DP. The + value sp[i][j][e] will store weight + of the shortest path from i to j + with exactly k edges ''' + + sp = [[None] * V for i in range(V)] + for i in range(V): + for j in range(V): + sp[i][j] = [None] * (k + 1) + ''' Loop for number of edges from 0 to k''' + + for e in range(k + 1): + '''for source ''' + + for i in range(V): + '''for destination''' + + for j in range(V): + ''' initialize value ''' + + sp[i][j][e] = INF + ''' from base cases ''' + + if (e == 0 and i == j): + sp[i][j][e] = 0 + if (e == 1 and graph[i][j] != INF): + sp[i][j][e] = graph[i][j] + ''' go to adjacent only when number + of edges is more than 1 ''' + + if (e > 1): + for a in range(V): + ''' There should be an edge from + i to a and a should not be + same as either i or j ''' + + if (graph[i][a] != INF and i != a and + j!= a and sp[a][j][e - 1] != INF): + sp[i][j][e] = min(sp[i][j][e], graph[i][a] + + sp[a][j][e - 1]) + return sp[u][v][k] + '''Driver Code''' + + '''Let us create the graph shown +in above diagram''' + +graph = [[0, 10, 3, 2], + [INF, 0, INF, 7], + [INF, INF, 0, 6], + [INF, INF, INF, 0]] +u = 0 +v = 3 +k = 2 +print(""Weight of the shortest path is"", + shortestPath(graph, u, v, k))" +Count pairs with given sum,"/*Java implementation of simple method to find count of +pairs with given sum.*/ + +public class find { + +/* Prints number of pairs in arr[0..n-1] with sum equal + to 'sum'*/ + + public static void getPairsCount(int[] arr, int sum) + { +/*Initialize result*/ + +int count = 0; +/* Consider all possible pairs and check their sums*/ + + for (int i = 0; i < arr.length; i++) + for (int j = i + 1; j < arr.length; j++) + if ((arr[i] + arr[j]) == sum) + count++; + System.out.printf(""Count of pairs is %d"", count); + } +/*Driver function to test the above function*/ + + public static void main(String args[]) + { + int[] arr = { 1, 5, 7, -1, 5 }; + int sum = 6; + getPairsCount(arr, sum); + } +}"," '''Python3 implementation of simple method +to find count of pairs with given sum. + ''' '''Returns number of pairs in arr[0..n-1] +with sum equal to sum''' +def getPairsCount(arr, n, sum): + '''Initialize result''' + + count = 0 + ''' Consider all possible pairs + and check their sums''' + + for i in range(0, n): + for j in range(i + 1, n): + if arr[i] + arr[j] == sum: + count += 1 + return count + '''Driver function''' + +arr = [1, 5, 7, -1, 5] +n = len(arr) +sum = 6 +print(""Count of pairs is"", + getPairsCount(arr, n, sum))" +Return previous element in an expanding matrix,"/*Java program to return previous element +in an expanding matrix*/ + +import java.io.*; +class GFG +{ +/* Returns left of str in an expanding matrix + of a, b, c and d.*/ + + static StringBuilder findLeft(StringBuilder str) + { + int n = str.length(); +/* Start from rightmost position*/ + + while (n > 0) + { + n--; +/* If the current character is b or d, + change to a or c respectively and + break the loop*/ + + if (str.charAt(n) == 'd') + { + str.setCharAt(n,'c'); + break; + } + if (str.charAt(n) == 'b') + { + str.setCharAt(n,'a'); + break; + } +/* If the current character is a or c, + change it to b or d respectively*/ + + if (str.charAt(n) == 'a') + str.setCharAt(n,'b'); + else if (str.charAt(n) == 'c') + str.setCharAt(n,'d'); + } + return str; + } +/* driver program to test above method*/ + + public static void main (String[] args) + { + StringBuilder str = new StringBuilder(""aacbddc""); + System.out.print(""Left of "" + str + "" is "" + + findLeft(str)); + } +}"," '''Python3 Program to return previous element +in an expanding matrix. + ''' '''Returns left of str in an +expanding matrix of a, b, c, and d.''' + +def findLeft(str): + n = len(str) - 1; + ''' Start from rightmost position''' + + while (n > 0): + ''' If the current character is ‘b’ or ‘d’, + change to ‘a’ or ‘c’ respectively and + break the loop''' + + if (str[n] == 'd'): + str = str[0:n] + 'c' + str[n + 1:]; + break; + if (str[n] == 'b'): + str = str[0:n] + 'a' + str[n + 1:]; + break; + ''' If the current character is ‘a’ or ‘c’, + change it to ‘b’ or ‘d’ respectively''' + + if (str[n] == 'a'): + str = str[0:n] + 'b' + str[n + 1:]; + elif (str[n] == 'c'): + str = str[0:n] + 'd' + str[n + 1:]; + n-=1; + return str; + '''Driver Code''' + +if __name__ == '__main__': + str = ""aacbddc""; + print(""Left of"", str, ""is"", findLeft(str));" +Longest Span with same Sum in two Binary arrays,"/*Java program to find largest subarray +with equal number of 0's and 1's.*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Returns largest common subarray with equal + number of 0s and 1s*/ + + static int longestCommonSum(int[] arr1, int[] arr2, int n) + { +/* Find difference between the two*/ + + int[] arr = new int[n]; + for (int i = 0; i < n; i++) + arr[i] = arr1[i] - arr2[i]; +/* Creates an empty hashMap hM*/ + + HashMap hM = new HashMap<>(); +/*Initialize sum of elements*/ + +int sum = 0; +/*Initialize result*/ + +int max_len = 0; +/* Traverse through the given array*/ + + for (int i = 0; i < n; i++) + { +/* Add current element to sum*/ + + sum += arr[i]; +/* To handle sum=0 at last index*/ + + if (sum == 0) + max_len = i + 1; +/* If this sum is seen before, + then update max_len if required*/ + + if (hM.containsKey(sum)) + max_len = Math.max(max_len, i - hM.get(sum)); +/*Else put this sum in hash table*/ + +else + hM.put(sum, i); + } + return max_len; + } +/* Driver code*/ + + public static void main(String args[]) + { + int[] arr1 = {0, 1, 0, 1, 1, 1, 1}; + int[] arr2 = {1, 1, 1, 1, 1, 0, 1}; + int n = arr1.length; + System.out.println(longestCommonSum(arr1, arr2, n)); + } +}"," '''Python program to find largest subarray +with equal number of 0's and 1's. + ''' '''Returns largest common subarray with equal +number of 0s and 1s''' + +def longestCommonSum(arr1, arr2, n): + ''' Find difference between the two''' + + arr = [0 for i in range(n)] + for i in range(n): + arr[i] = arr1[i] - arr2[i]; + ''' Creates an empty hashMap hM ''' + + hm = {} + '''Initialize sum of elements''' + + sum = 0 + + '''Initialize result''' + + max_len = 0 + ''' Traverse through the given array ''' + + for i in range(n): + ''' Add current element to sum ''' + + sum += arr[i] + ''' To handle sum=0 at last index ''' + + if (sum == 0): + max_len = i + 1 + ''' If this sum is seen before, + then update max_len if required''' + + if sum in hm: + max_len = max(max_len, i - hm[sum]) + '''Else put this sum in hash table''' + + else: + hm[sum] = i + return max_len + '''Driver code''' + +arr1 = [0, 1, 0, 1, 1, 1, 1] +arr2 = [1, 1, 1, 1, 1, 0, 1] +n = len(arr1) +print(longestCommonSum(arr1, arr2, n))" +Maximum and Minimum in a square matrix.,"/*Java program for finding maximum +and minimum in a matrix.*/ + +class GFG +{ + static final int MAX = 100; +/* Finds maximum and minimum + in arr[0..n-1][0..n-1] + using pair wise comparisons*/ + + static void maxMin(int arr[][], int n) + { + int min = +2147483647; + int max = -2147483648; +/* Traverses rows one by one*/ + + for (int i = 0; i < n; i++) + { + for (int j = 0; j <= n/2; j++) + { +/* Compare elements from beginning + and end of current row*/ + + if (arr[i][j] > arr[i][n - j - 1]) + { + if (min > arr[i][n - j - 1]) + min = arr[i][n - j - 1]; + if (max< arr[i][j]) + max = arr[i][j]; + } + else + { + if (min > arr[i][j]) + min = arr[i][j]; + if (max< arr[i][n - j - 1]) + max = arr[i][n - j - 1]; + } + } + } + System.out.print(""Maximum = ""+max+ + "", Minimum = ""+min); + } +/* Driver program*/ + + public static void main (String[] args) + { + int arr[][] = {{5, 9, 11}, + {25, 0, 14}, + {21, 6, 4}}; + maxMin(arr, 3); + } +}"," '''Python3 program for finding +MAXimum and MINimum in a matrix.''' + +MAX = 100 + '''Finds MAXimum and MINimum in arr[0..n-1][0..n-1] +using pair wise comparisons''' + +def MAXMIN(arr, n): + MIN = 10**9 + MAX = -10**9 + ''' Traverses rows one by one''' + + for i in range(n): + for j in range(n // 2 + 1): + ''' Compare elements from beginning + and end of current row''' + + if (arr[i][j] > arr[i][n - j - 1]): + if (MIN > arr[i][n - j - 1]): + MIN = arr[i][n - j - 1] + if (MAX< arr[i][j]): + MAX = arr[i][j] + else: + if (MIN > arr[i][j]): + MIN = arr[i][j] + if (MAX< arr[i][n - j - 1]): + MAX = arr[i][n - j - 1] + print(""MAXimum ="", MAX, "", MINimum ="", MIN) + '''Driver Code''' + +arr = [[5, 9, 11], + [25, 0, 14], + [21, 6, 4]] +MAXMIN(arr, 3)" +Maximum product of 4 adjacent elements in matrix,"/*Java program to find out the +maximum product in the matrix +which four elements are adjacent +to each other in one direction*/ + +class GFG { + static final int n = 5; +/* function to find max product*/ + + static int FindMaxProduct(int arr[][], int n) + { + int max = 0, result; +/* iterate the rows.*/ + + for (int i = 0; i < n; i++) + { +/* iterate the columns.*/ + + for (int j = 0; j < n; j++) + { +/* check the maximum product + in horizontal row.*/ + + if ((j - 3) >= 0) + { + result = arr[i][j] * arr[i][j - 1] + * arr[i][j - 2] + * arr[i][j - 3]; + if (max < result) + max = result; + } +/* check the maximum product + in vertical row.*/ + + if ((i - 3) >= 0) + { + result = arr[i][j] * arr[i - 1][j] + * arr[i - 2][j] + * arr[i - 3][j]; + if (max < result) + max = result; + } +/* check the maximum product in + diagonal (going through down - right)*/ + + if ((i - 3) >= 0 && (j - 3) >= 0) + { + result = arr[i][j] * arr[i - 1][j - 1] + * arr[i - 2][j - 2] + * arr[i - 3][j - 3]; + if (max < result) + max = result; + } +/* check the maximum product in + diagonal (going through up - right)*/ + + if ((i - 3) >= 0 && (j - 1) <= 0) + { + result = arr[i][j] * arr[i - 1][j + 1] + * arr[i - 2][j + 2] + * arr[i - 3][j + 3]; + if (max < result) + max = result; + } + } + } + return max; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[][] = { { 1, 2, 3, 4, 5 }, + { 6, 7, 8, 9, 1 }, + { 2, 3, 4, 5, 6 }, + { 7, 8, 9, 1, 0 }, + { 9, 6, 4, 2, 3 } }; + System.out.print(FindMaxProduct(arr, n)); + } +}"," '''Python3 program to find out the maximum +product in the matrix which four elements +are adjacent to each other in one direction''' + +n = 5 + '''function to find max product''' + +def FindMaxProduct(arr, n): + max = 0 + ''' iterate the rows.''' + + for i in range(n): + ''' iterate the columns.''' + + for j in range( n): + ''' check the maximum product + in horizontal row.''' + + if ((j - 3) >= 0): + result = (arr[i][j] * arr[i][j - 1] * + arr[i][j - 2] * arr[i][j - 3]) + if (max < result): + max = result + ''' check the maximum product + in vertical row.''' + + if ((i - 3) >= 0) : + result = (arr[i][j] * arr[i - 1][j] * + arr[i - 2][j] * arr[i - 3][j]) + if (max < result): + max = result + ''' check the maximum product in + diagonal going through down - right''' + + if ((i - 3) >= 0 and (j - 3) >= 0): + result = (arr[i][j] * arr[i - 1][j - 1] * + arr[i - 2][j - 2] * arr[i - 3][j - 3]) + if (max < result): + max = result + ''' check the maximum product in + diagonal going through up - right''' + + if ((i - 3) >= 0 and (j - 1) <= 0): + result = (arr[i][j] * arr[i - 1][j + 1] * + arr[i - 2][j + 2] * arr[i - 3][j + 3]) + if (max < result): + max = result + return max + '''Driver code''' + +if __name__ == ""__main__"": + arr = [[1, 2, 3, 4, 5], + [6, 7, 8, 9, 1], + [2, 3, 4, 5, 6], + [7, 8, 9, 1, 0], + [9, 6, 4, 2, 3]] + print(FindMaxProduct(arr, n))" +Maximum possible difference of two subsets of an array,"/*java find maximum difference +of subset sum*/ + +import java .io.*; +public class GFG { +/* function for maximum subset diff*/ + + static int maxDiff(int []arr, int n) + { + int SubsetSum_1 = 0, SubsetSum_2 = 0; + for (int i = 0; i <= n - 1; i++) + { + boolean isSingleOccurance = true; + for (int j = i + 1; j <= n - 1; j++) + { +/* if frequency of any element + is two make both equal to + zero*/ + + if (arr[i] == arr[j]) + { + isSingleOccurance = false; + arr[i] = arr[j] = 0; + break; + } + } + if (isSingleOccurance) + { + if (arr[i] > 0) + SubsetSum_1 += arr[i]; + else + SubsetSum_2 += arr[i]; + } + } + return Math.abs(SubsetSum_1 - SubsetSum_2); + } +/* driver program*/ + + static public void main (String[] args) + { + int []arr = { 4, 2, -3, 3, -2, -2, 8 }; + int n = arr.length; + System.out.println(""Maximum Difference = "" + + maxDiff(arr, n)); + } +}"," '''Python3 find maximum difference +of subset sum''' + +import math + '''function for maximum subset diff''' + +def maxDiff(arr, n) : + SubsetSum_1 = 0 + SubsetSum_2 = 0 + for i in range(0, n) : + isSingleOccurance = True + for j in range(i + 1, n) : + ''' if frequency of any element + is two make both equal to + zero''' + + if (arr[i] == arr[j]) : + isSingleOccurance = False + arr[i] = arr[j] = 0 + break + if (isSingleOccurance == True) : + if (arr[i] > 0) : + SubsetSum_1 += arr[i] + else : + SubsetSum_2 += arr[i] + return abs(SubsetSum_1 - SubsetSum_2) + '''Driver Code''' + +arr = [4, 2, -3, 3, -2, -2, 8] +n = len(arr) +print (""Maximum Difference = {}"" + . format(maxDiff(arr, n)))" +"Check if given Preorder, Inorder and Postorder traversals are of same tree","/* Java program to check if all three given +traversals are of the same tree */ + +import java.util.*; +class GfG { + static int preIndex = 0; +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +} +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} +/* Function to find index of value in arr[start...end] +The function assumes that value is present in in[] */ + +static int search(int arr[], int strt, int end, int value) +{ + for (int i = strt; i <= end; i++) + { + if(arr[i] == value) + return i; + } + return -1; +} +/* Recursive function to construct binary tree +of size len from Inorder traversal in[] and +Preorder traversal pre[]. Initial values +of inStrt and inEnd should be 0 and len -1. +The function doesn't do any error checking for +cases where inorder and preorder do not form a +tree */ + +static Node buildTree(int in[], int pre[], int inStrt, int inEnd) +{ + if(inStrt > inEnd) + return null; + /* Pick current node from Preorder traversal + using preIndex and increment preIndex */ + + Node tNode = newNode(pre[preIndex++]); + /* If this node has no children then return */ + + if (inStrt == inEnd) + return tNode; + /* Else find the index of this node in + Inorder traversal */ + + int inIndex = search(in, inStrt, inEnd, tNode.data); + /* Using index in Inorder traversal, + construct left and right subtress */ + + tNode.left = buildTree(in, pre, inStrt, inIndex-1); + tNode.right = buildTree(in, pre, inIndex+1, inEnd); + return tNode; +} +/* function to compare Postorder traversal +on constructed tree and given Postorder */ + +static int checkPostorder(Node node, int postOrder[], int index) +{ + if (node == null) + return index; + /* first recur on left child */ + + index = checkPostorder(node.left,postOrder,index); + /* now recur on right child */ + + index = checkPostorder(node.right,postOrder,index); + /* Compare if data at current index in + both Postorder traversals are same */ + + if (node.data == postOrder[index]) + index++; + else + return -1; + return index; +} +/*Driver program to test above functions*/ + +public static void main(String[] args) +{ + int inOrder[] = {4, 2, 5, 1, 3}; + int preOrder[] = {1, 2, 4, 5, 3}; + int postOrder[] = {4, 5, 2, 3, 1}; + int len = inOrder.length; +/* build tree from given + Inorder and Preorder traversals*/ + + Node root = buildTree(inOrder, preOrder, 0, len - 1); +/* compare postorder traversal on constructed + tree with given Postorder traversal*/ + + int index = checkPostorder(root,postOrder,0); +/* If both postorder traversals are same*/ + + if (index == len) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Python3 program to check if +all three given traversals +are of the same tree''' +preIndex = 0 '''A Binary Tree Node''' + +class node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + + '''Function to find index of value +in arr[start...end]. The function +assumes that value is present in in''' + +def search(arr, strt, end, value): + for i in range(strt, end + 1): + if(arr[i] == value): + return i + '''Recursive function to construct +binary tree of size lenn from +Inorder traversal in and Preorder +traversal pre[]. Initial values +of inStrt and inEnd should be 0 +and lenn -1. The function doesn't +do any error checking for cases +where inorder and preorder do not +form a tree''' + +def buildTree(inn, pre, inStrt, inEnd): + global preIndex + if(inStrt > inEnd): + return None + ''' Pick current node from Preorder + traversal using preIndex and + increment preIndex''' + + tNode = node(pre[preIndex]) + preIndex += 1 + ''' If this node has no children + then return''' + + if (inStrt == inEnd): + return tNode + ''' Else find the index of this + node in Inorder traversal''' + + inIndex = search(inn, inStrt, + inEnd, tNode.data) + ''' Using index in Inorder traversal, + construct left and right subtress''' + + tNode.left = buildTree(inn, pre, inStrt, + inIndex - 1) + tNode.right = buildTree(inn, pre, + inIndex + 1, inEnd) + return tNode + '''function to compare Postorder traversal +on constructed tree and given Postorder''' + +def checkPostorder(node, postOrder, index): + if (node == None): + return index + ''' first recur on left child''' + + index = checkPostorder(node.left, + postOrder, + index) + ''' now recur on right child''' + + index = checkPostorder(node.right, + postOrder, + index) + ''' Compare if data at current index in + both Postorder traversals are same''' + + if (node.data == postOrder[index]): + index += 1 + else: + return - 1 + return index + '''Driver code''' + +if __name__ == '__main__': + inOrder = [4, 2, 5, 1, 3] + preOrder = [1, 2, 4, 5, 3] + postOrder = [4, 5, 2, 3, 1] + lenn = len(inOrder) + ''' build tree from given + Inorder and Preorder traversals''' + + root = buildTree(inOrder, preOrder, + 0, lenn - 1) + ''' compare postorder traversal on + constructed tree with given + Postorder traversal''' + + index = checkPostorder(root, postOrder, 0) + ''' If both postorder traversals are same''' + + if (index == lenn): + print(""Yes"") + else: + print(""No"")" +Flood fill Algorithm,"/*Java code for the above approach*//*Pair class*/ + +class Pair implements Comparable { + int first; + int second; + public Pair(int first, int second) { + this.first = first; + this.second = second; + } + @Override + public int compareTo(Pair o) { + return second - o.second; + } +} +/*Function to check valid coordinate*/ + +class GFG { + public static int validCoord(int x, int y, int n, int m) + { + if (x < 0 || y < 0) { + return 0; + } + if (x >= n || y >= m) { + return 0; + } + return 1; + } +/* Function to run bfs*/ + + public static void bfs(int n, int m, int data[][],int x, int y, int color) + { +/* Visiing array*/ + + int vis[][]=new int[101][101]; +/* Initialing all as zero*/ + + for(int i=0;i<=100;i++){ + for(int j=0;j<=100;j++){ + vis[i][j]=0; + } + } +/* Creating queue for bfs*/ + + Queue obj = new LinkedList<>(); +/* Pushing pair of {x, y}*/ + + Pair pq=new Pair(x,y); + obj.add(pq); +/* Marking {x, y} as visited*/ + + vis[x][y] = 1; +/* Untill queue is emppty*/ + + while (!obj.isEmpty()) + { +/* Extrating front pair*/ + + Pair coord = obj.peek(); + int x1 = coord.first; + int y1 = coord.second; + int preColor = data[x1][y1]; + data[x1][y1] = color; +/* Poping front pair of queue*/ + + obj.remove(); +/* For Upside Pixel or Cell*/ + + if ((validCoord(x1 + 1, y1, n, m)==1) && vis[x1 + 1][y1] == 0 && data[x1 + 1][y1] == preColor) + { + Pair p=new Pair(x1 +1, y1); + obj.add(p); + vis[x1 + 1][y1] = 1; + } +/* For Downside Pixel or Cell*/ + + if ((validCoord(x1 - 1, y1, n, m)==1) && vis[x1 - 1][y1] == 0 && data[x1 - 1][y1] == preColor) + { + Pair p=new Pair(x1-1,y1); + obj.add(p); + vis[x1- 1][y1] = 1; + } +/* For Right side Pixel or Cell*/ + + if ((validCoord(x1, y1 + 1, n, m)==1) && vis[x1][y1 + 1] == 0 && data[x1][y1 + 1] == preColor) + { + Pair p=new Pair(x1,y1 +1); + obj.add(p); + vis[x1][y1 + 1] = 1; + } +/* For Left side Pixel or Cell*/ + + if ((validCoord(x1, y1 - 1, n, m)==1) && vis[x1][y1 - 1] == 0 && data[x1][y1 - 1] == preColor) + { + Pair p=new Pair(x1,y1 -1); + obj.add(p); + vis[x1][y1 - 1] = 1; + } + } +/* Printing The Changed Matrix Of Pixels*/ + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + System.out.print(data[i][j]+"" ""); + } + System.out.println(); + } + System.out.println(); + } + +/*Driver Code*/ + + public static void main (String[] args) { + int nn, mm, xx, yy, colorr; + nn = 8; + mm = 8; + int dataa[][] = {{ 1, 1, 1, 1, 1, 1, 1, 1 }, + { 1, 1, 1, 1, 1, 1, 0, 0 }, + { 1, 0, 0, 1, 1, 0, 1, 1 }, + { 1, 2, 2, 2, 2, 0, 1, 0 }, + { 1, 1, 1, 2, 2, 0, 1, 0 }, + { 1, 1, 1, 2, 2, 2, 2, 0 }, + { 1, 1, 1, 1, 1, 2, 1, 1 }, + { 1, 1, 1, 1, 1, 2, 2, 1 },}; + xx = 4; yy = 4; colorr = 3;/* Function Call*/ + + bfs(nn, mm, dataa, xx, yy, colorr); + } +}", +Find the element that appears once,"/*Java code to find the element +that occur only once*/ + +class GFG { + static final int INT_SIZE = 32; + static int getSingle(int arr[], int n) + {/* Initialize result*/ + + int result = 0; + int x, sum; +/* Iterate through every bit*/ + + for (int i = 0; i < INT_SIZE; i++) { +/* Find sum of set bits at ith position in all + array elements*/ + + sum = 0; + x = (1 << i); + for (int j = 0; j < n; j++) { + if ((arr[j] & x) == 0) + sum++; + } +/* The bits with sum not multiple of 3, are the + bits of element with single occurrence.*/ + + if ((sum % 3) != 0) + result |= x; + } + return result; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 }; + int n = arr.length; + System.out.println(""The element with single occurrence is "" + getSingle(arr, n)); + } +}"," '''Python3 code to find the element +that occur only once''' + +INT_SIZE = 32 +def getSingle(arr, n) : + ''' Initialize result''' + + result = 0 + ''' Iterate through every bit''' + + for i in range(0, INT_SIZE) : + ''' Find sum of set bits + at ith position in all + array elements''' + + sm = 0 + x = (1 << i) + for j in range(0, n) : + if (arr[j] & x) : + sm = sm + 1 + ''' The bits with sum not + multiple of 3, are the + bits of element with + single occurrence.''' + + if ((sm % 3)!= 0) : + result = result | x + return result + '''Driver program''' + +arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7] +n = len(arr) +print(""The element with single occurrence is "", getSingle(arr, n))" +Cutting a Rod | DP-13,"/*A Dynamic Programming solution for Rod cutting problem*/ + +class RodCutting +{ + /* Returns the best obtainable price for a rod of + length n and price[] as prices of different pieces */ + + static int cutRod(int price[],int n) + { + int val[] = new int[n+1]; + val[0] = 0; +/* Build the table val[] in bottom up manner and return + the last entry from the table*/ + + for (int i = 1; i<=n; i++) + { + int max_val = Integer.MIN_VALUE; + for (int j = 0; j < i; j++) + max_val = Math.max(max_val, + price[j] + val[i-j-1]); + val[i] = max_val; + } + return val[n]; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + int arr[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20}; + int size = arr.length; + System.out.println(""Maximum Obtainable Value is "" + + cutRod(arr, size)); + } +}"," '''A Dynamic Programming solution for Rod cutting problem''' + +INT_MIN = -32767 + '''Returns the best obtainable price for a rod of length n and +price[] as prices of different pieces''' + +def cutRod(price, n): + val = [0 for x in range(n+1)] + val[0] = 0 + ''' Build the table val[] in bottom up manner and return + the last entry from the table''' + + for i in range(1, n+1): + max_val = INT_MIN + for j in range(i): + max_val = max(max_val, price[j] + val[i-j-1]) + val[i] = max_val + return val[n] + '''Driver program to test above functions''' + +arr = [1, 5, 8, 9, 10, 17, 17, 20] +size = len(arr) +print(""Maximum Obtainable Value is "" + str(cutRod(arr, size)))" +Maximum width of a binary tree,"/*Java program to calculate width of binary tree*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; + /* Function to get the maximum width of a binary tree*/ + + int getMaxWidth(Node node) + { + int maxWidth = 0; + int width; + int h = height(node); + int i; + /* Get width of each level and compare + the width with maximum width so far */ + + for (i = 1; i <= h; i++) { + width = getWidth(node, i); + if (width > maxWidth) + maxWidth = width; + } + return maxWidth; + } + /* Get width of a given level */ + + int getWidth(Node node, int level) + { + if (node == null) + return 0; + if (level == 1) + return 1; + else if (level > 1) + return getWidth(node.left, level - 1) + + getWidth(node.right, level - 1); + return 0; + } + /* Compute the ""height"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + + int height(Node node) + { + if (node == null) + return 0; + else { + /* compute the height of each subtree */ + + int lHeight = height(node.left); + int rHeight = height(node.right); + /* use the larger one */ + + return (lHeight > rHeight) ? (lHeight + 1) + : (rHeight + 1); + } + } + /* Driver code */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* + Constructed binary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 + */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(8); + tree.root.right.right.left = new Node(6); + tree.root.right.right.right = new Node(7); +/* Function call*/ + + System.out.println(""Maximum width is "" + + tree.getMaxWidth(tree.root)); + } +}"," '''Python program to find the maximum width of +binary tree using Level Order Traversal.''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to get the maximum width of a binary tree''' + +def getMaxWidth(root): + maxWidth = 0 + h = height(root) + ''' Get width of each level and compare the + width with maximum width so far''' + + for i in range(1, h+1): + width = getWidth(root, i) + if (width > maxWidth): + maxWidth = width + return maxWidth + '''Get width of a given level''' + +def getWidth(root, level): + if root is None: + return 0 + if level == 1: + return 1 + elif level > 1: + return (getWidth(root.left, level-1) + + getWidth(root.right, level-1)) + '''Compute the ""height"" of a tree -- the number of +nodes along the longest path from the root node +down to the farthest leaf node.''' + +def height(node): + if node is None: + return 0 + else: + ''' compute the height of each subtree''' + + lHeight = height(node.left) + rHeight = height(node.right) + ''' use the larger one''' + + return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) + '''Driver code''' + + ''' +Constructed binary tree is: + 1 + / \ + 2 3 + / \ \ +4 5 8 + / \ + 6 7 + ''' + + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) '''Function call''' + +print ""Maximum width is %d"" % (getMaxWidth(root))" +Print all possible combinations of r elements in a given array of size n,"/*Java program to print all combination of size r in an array of size n*/ + +import java.io.*; +class Combination { + /* The main function that prints all combinations of size r + in arr[] of size n. This function mainly uses combinationUtil()*/ + + static void printCombination(int arr[], int n, int r) + { +/* A temporary array to store all combination one by one*/ + + int data[]=new int[r]; +/* Print all combination using temprary array 'data[]'*/ + + combinationUtil(arr, n, r, 0, data, 0); + } + /* arr[] ---> Input Array + data[] ---> Temporary array to store current combination + start & end ---> Staring and Ending indexes in arr[] + index ---> Current index in data[] + r ---> Size of a combination to be printed */ + + static void combinationUtil(int arr[], int n, int r, int index, + int data[], int i) + { +/* Current combination is ready to be printed, print it*/ + + if (index == r) + { + for (int j=0; j= n) + return; +/* current is included, put next at next location*/ + + data[index] = arr[i]; + combinationUtil(arr, n, r, index+1, data, i+1); +/* current is excluded, replace it with next (Note that + i+1 is passed, but index is not changed)*/ + + combinationUtil(arr, n, r, index, data, i+1); + } +/*Driver function to check for above function*/ + + public static void main (String[] args) { + int arr[] = {1, 2, 3, 4, 5}; + int r = 3; + int n = arr.length; + printCombination(arr, n, r); + } +}"," '''Program to print all combination +of size r in an array of size n + ''' '''The main function that prints all +combinations of size r in arr[] of +size n. This function mainly uses +combinationUtil()''' + +def printCombination(arr, n, r): + ''' A temporary array to store + all combination one by one''' + + data = [0] * r + ''' Print all combination using + temprary array 'data[]''' + ''' + combinationUtil(arr, n, r, 0, data, 0) + ''' arr[] ---> Input Array +n ---> Size of input array +r ---> Size of a combination to be printed +index ---> Current index in data[] +data[] ---> Temporary array to store + current combination +i ---> index of current element in arr[] ''' + +def combinationUtil(arr, n, r, index, data, i): + ''' Current cobination is ready, + print it''' + + if (index == r): + for j in range(r): + print(data[j], end = "" "") + print() + return + ''' When no more elements are + there to put in data[]''' + + if (i >= n): + return + ''' current is included, put + next at next location''' + + data[index] = arr[i] + combinationUtil(arr, n, r, index + 1, + data, i + 1) + ''' current is excluded, replace it + with next (Note that i+1 is passed, + but index is not changed)''' + + combinationUtil(arr, n, r, index, + data, i + 1) + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 2, 3, 4, 5] + r = 3 + n = len(arr) + printCombination(arr, n, r)" +Program to find largest element in an array,"/*Java program to +find maximum in +arr[] of size n*/ + +import java .io.*; +import java.util.*; +class GFG +{ +/* returns maximum in + arr[] of size n*/ + + static int largest(int []arr, + int n) + { + Arrays.sort(arr); + return arr[n - 1]; + } +/* Driver code*/ + + static public void main (String[] args) + { + int []arr = {10, 324, 45, + 90, 9808}; + int n = arr.length; + System.out.println(largest(arr, n)); + } +}"," '''Python 3 program to find +maximum in arr[] of size n''' + '''returns maximum +in arr[] of size n''' + +def largest(arr, n): + return max(arr) + '''driver code''' + +arr = [10, 324, 45, 90, 9808] +n = len(arr) +print(largest(arr, n))" +Smallest of three integers without comparison operators,"/*Java program to find Smallest +of three integers without +comparison operators*/ + +class GFG { + static int smallest(int x, int y, int z) + { + int c = 0; + while (x != 0 && y != 0 && z != 0) { + x--; + y--; + z--; + c++; + } + return c; + } +/*Driver code*/ + + public static void main(String[] args) + { + int x = 12, y = 15, z = 5; + System.out.printf(""Minimum of 3"" + + "" numbers is %d"", + smallest(x, y, z)); + } +}"," '''Python3 program to find Smallest +of three integers without +comparison operators''' + +def smallest(x, y, z): + c = 0 + while ( x and y and z ): + x = x-1 + y = y-1 + z = z-1 + c = c + 1 + return c + '''Driver Code''' + +x = 12 +y = 15 +z = 5 +print(""Minimum of 3 numbers is"", + smallest(x, y, z))" +Largest Sum Contiguous Subarray,"/*Java program to print largest contiguous +array sum*/ + +import java.io.*; +class GFG { + static int maxSubArraySum(int a[], int size) + { + int max_so_far = a[0]; + int curr_max = a[0]; + for (int i = 1; i < size; i++) + { + curr_max = Math.max(a[i], curr_max+a[i]); + max_so_far = Math.max(max_so_far, curr_max); + } + return max_so_far; + } + /* Driver program to test maxSubArraySum */ + + public static void main(String[] args) + { + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = a.length; + int max_sum = maxSubArraySum(a, n); + System.out.println(""Maximum contiguous sum is "" + + max_sum); + } +}"," '''Python program to find maximum contiguous subarray''' + +def maxSubArraySum(a,size): + max_so_far =a[0] + curr_max = a[0] + for i in range(1,size): + curr_max = max(a[i], curr_max + a[i]) + max_so_far = max(max_so_far,curr_max) + return max_so_far + '''Driver function to check the above function''' + +a = [-2, -3, 4, -1, -2, 1, 5, -3] +print""Maximum contiguous sum is"" , maxSubArraySum(a,len(a))" +How to check if two given sets are disjoint?,"/*Java program to check if two sets are disjoint*/ + +import java.util.Arrays; +public class disjoint1 +{ +/* Returns true if set1[] and set2[] are + disjoint, else false*/ + + boolean aredisjoint(int set1[], int set2[]) + { + int i=0,j=0; +/* Sort the given two sets*/ + + Arrays.sort(set1); + Arrays.sort(set2); +/* Check for same elements using + merge like process*/ + + while(iset2[j]) + j++; + +/* if set1[i] == set2[j] */ + + else + return false; + } + return true; + }/* Driver program to test above function*/ + + public static void main(String[] args) + { + disjoint1 dis = new disjoint1(); + int set1[] = { 12, 34, 11, 9, 3 }; + int set2[] = { 7, 2, 1, 5 }; + boolean result = dis.aredisjoint(set1, set2); + if (result) + System.out.println(""YES""); + else + System.out.println(""NO""); + } +}"," '''A Simple Python 3 program to check +if two sets are disjoint''' + '''Returns true if set1[] and set2[] +are disjoint, else false''' + +def areDisjoint(set1, set2, m, n): + ''' Sort the given two sets''' + + set1.sort() + set2.sort() + ''' Check for same elements + using merge like process''' + + i = 0; j = 0 + while (i < m and j < n): + if (set1[i] < set2[j]): + i += 1 + elif (set2[j] < set1[i]): + j += 1 + '''if set1[i] == set2[j]''' + + else: + return False + return True + '''Driver Code''' + +set1 = [12, 34, 11, 9, 3] +set2 = [7, 2, 1, 5] +m = len(set1) +n = len(set2) +print(""Yes"") if areDisjoint(set1, set2, m, n) else print(""No"")" +Practice questions for Linked List and Recursion,"static class Node +{ + int data; + Node next; +};","class Node: + def __init__(self, data): + self.data = data + self.next = None" +Sort 1 to N by swapping adjacent elements,"/*Java program to test whether an array +can be sorted by swapping adjacent +elements using boolean array*/ +import java.util.Arrays; +class GFG { +/* Return true if array can be + sorted otherwise false*/ + + static boolean sortedAfterSwap(int A[], + boolean B[], int n) + { + int i, j; +/* Check bool array B and sorts + elements for continuous sequence of 1*/ + + for (i = 0; i < n - 1; i++) { + if (B[i]) { + j = i; + while (B[j]) { + j++; + } +/* Sort array A from i to j*/ + + Arrays.sort(A, i, 1 + j); + i = j; + } + } +/* Check if array is sorted or not*/ + + for (i = 0; i < n; i++) { + if (A[i] != i + 1) { + return false; + } + } + return true; + } +/* Driver program to test sortedAfterSwap()*/ + + public static void main(String[] args) + { + int A[] = { 1, 2, 5, 3, 4, 6 }; + boolean B[] = { false, true, true, true, false }; + int n = A.length; + if (sortedAfterSwap(A, B, n)) { + System.out.println(""A can be sorted""); + } + else { + System.out.println(""A can not be sorted""); + } + } +}"," '''Python 3 program to test whether an array +can be sorted by swapping adjacent +elements using a boolean array + ''' '''Return true if array can be +sorted otherwise false''' + +def sortedAfterSwap(A, B, n) : + ''' Check bool array B and sorts + elements for continuous sequence of 1''' + + for i in range(0, n - 1) : + if (B[i]== 1) : + j = i + while (B[j]== 1) : + j = j + 1 + ''' Sort array A from i to j''' + + A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:] + i = j + ''' Check if array is sorted or not''' + + for i in range(0, n) : + if (A[i] != i + 1) : + return False + return True + '''Driver program to test sortedAfterSwap()''' + +A = [ 1, 2, 5, 3, 4, 6 ] +B = [ 0, 1, 1, 1, 0 ] +n = len(A) +if (sortedAfterSwap(A, B, n)) : + print(""A can be sorted"") +else : + print(""A can not be sorted"")" +Two elements whose sum is closest to zero,"/*Java code to find Two elements +whose sum is closest to zero*/ + +import java.util.*; +import java.lang.*; +class Main +{ + static void minAbsSumPair(int arr[], int arr_size) + { + int inv_count = 0; + int l, r, min_sum, sum, min_l, min_r; + /* Array should have at least two elements*/ + + if(arr_size < 2) + { + System.out.println(""Invalid Input""); + return; + } + /* Initialization of values */ + + min_l = 0; + min_r = 1; + min_sum = arr[0] + arr[1]; + for(l = 0; l < arr_size - 1; l++) + { + for(r = l+1; r < arr_size; r++) + { + sum = arr[l] + arr[r]; + if(Math.abs(min_sum) > Math.abs(sum)) + { + min_sum = sum; + min_l = l; + min_r = r; + } + } + } + System.out.println("" The two elements whose ""+ + ""sum is minimum are ""+ + arr[min_l]+ "" and ""+arr[min_r]); + } +/* main function*/ + + public static void main (String[] args) + { + int arr[] = {1, 60, -10, 70, -80, 85}; + minAbsSumPair(arr, 6); + } +}"," '''Python3 code to find Two elements +whose sum is closest to zero''' + +def minAbsSumPair(arr,arr_size): + inv_count = 0 + ''' Array should have at least + two elements''' + + if arr_size < 2: + print(""Invalid Input"") + return + ''' Initialization of values''' + + min_l = 0 + min_r = 1 + min_sum = arr[0] + arr[1] + for l in range (0, arr_size - 1): + for r in range (l + 1, arr_size): + sum = arr[l] + arr[r] + if abs(min_sum) > abs(sum): + min_sum = sum + min_l = l + min_r = r + print(""The two elements whose sum is minimum are"", + arr[min_l], ""and "", arr[min_r]) + '''Driver program to test above function''' + +arr = [1, 60, -10, 70, -80, 85] +minAbsSumPair(arr, 6);" +Majority Element,"/*Java program to find Majority +element in an array*/ + +import java.io.*; +class GFG { +/* Function to find Majority element + in an array*/ + + static void findMajority(int arr[], int n) + { + int maxCount = 0; +/*sentinels*/ + +int index = -1; + for (int i = 0; i < n; i++) { + int count = 0; + for (int j = 0; j < n; j++) { + if (arr[i] == arr[j]) + count++; + } +/* update maxCount if count of + current element is greater*/ + + if (count > maxCount) { + maxCount = count; + index = i; + } + } +/* if maxCount is greater than n/2 + return the corresponding element*/ + + if (maxCount > n / 2) + System.out.println(arr[index]); + else + System.out.println(""No Majority Element""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; + int n = arr.length; +/* Function calling*/ + + findMajority(arr, n); + } + +}"," '''Python3 program to find Majority +element in an array + ''' '''Function to find Majority +element in an array''' + +def findMajority(arr, n): + maxCount = 0 + '''sentinels''' + + index = -1 + for i in range(n): + count = 0 + for j in range(n): + if(arr[i] == arr[j]): + count += 1 + ''' update maxCount if count of + current element is greater''' + + if(count > maxCount): + maxCount = count + index = i + ''' if maxCount is greater than n/2 + return the corresponding element''' + + if (maxCount > n//2): + print(arr[index]) + else: + print(""No Majority Element"") + '''Driver code''' + +if __name__ == ""__main__"": + arr = [1, 1, 2, 1, 3, 5, 1] + n = len(arr) + ''' Function calling''' + + findMajority(arr, n)" +Count all possible groups of size 2 or 3 that have sum as multiple of 3,"/*Java Program to count all possible +groups of size 2 or 3 that have +sum as multiple of 3*/ + +class FindGroups +{ +/* Returns count of all possible groups that can be formed from elements + of a[].*/ + + int findgroups(int arr[], int n) + { +/* Create an array C[3] to store counts of elements with remainder + 0, 1 and 2. c[i] would store count of elements with remainder i*/ + + int c[] = new int[]{0, 0, 0}; + int i; +/*To store the result*/ + +int res = 0; +/* Count elements with remainder 0, 1 and 2*/ + + for (i = 0; i < n; i++) + c[arr[i] % 3]++; +/* Case 3.a: Count groups of size 2 from 0 remainder elements*/ + + res += ((c[0] * (c[0] - 1)) >> 1); +/* Case 3.b: Count groups of size 2 with one element with 1 + remainder and other with 2 remainder*/ + + res += c[1] * c[2]; +/* Case 4.a: Count groups of size 3 with all 0 remainder elements*/ + + res += (c[0] * (c[0] - 1) * (c[0] - 2)) / 6; +/* Case 4.b: Count groups of size 3 with all 1 remainder elements*/ + + res += (c[1] * (c[1] - 1) * (c[1] - 2)) / 6; +/* Case 4.c: Count groups of size 3 with all 2 remainder elements*/ + + res += ((c[2] * (c[2] - 1) * (c[2] - 2)) / 6); +/* Case 4.c: Count groups of size 3 with different remainders*/ + + res += c[0] * c[1] * c[2]; +/* Return total count stored in res*/ + + return res; + } +/*Driver Code*/ + + public static void main(String[] args) + { + FindGroups groups = new FindGroups(); + int arr[] = {3, 6, 7, 2, 9}; + int n = arr.length; + System.out.println(""Required number of groups are "" + + groups.findgroups(arr, n)); + } +}"," '''Python3 Program to Count groups +of size 2 or 3 that have sum +as multiple of 3 + ''' '''Returns count of all possible +groups that can be formed +from elements of a[].''' + +def findgroups(arr, n): + ''' Create an array C[3] to store + counts of elements with + remainder 0, 1 and 2. c[i] + would store count of elements + with remainder i''' + + c = [0, 0, 0] + ''' To store the result''' + + res = 0 + ''' Count elements with remainder + 0, 1 and 2''' + + for i in range(0, n): + c[arr[i] % 3] += 1 + ''' Case 3.a: Count groups of size + 2 from 0 remainder elements''' + + res += ((c[0] * (c[0] - 1)) >> 1) + ''' Case 3.b: Count groups of size + 2 with one element with 1 + remainder and other with 2 remainder''' + + res += c[1] * c[2] + ''' Case 4.a: Count groups of size + 3 with all 0 remainder elements''' + + res += (c[0] * (c[0] - 1) * (c[0] - 2)) / 6 + ''' Case 4.b: Count groups of size 3 + with all 1 remainder elements''' + + res += (c[1] * (c[1] - 1) * (c[1] - 2)) / 6 + ''' Case 4.c: Count groups of size 3 + with all 2 remainder elements''' + + res += ((c[2] * (c[2] - 1) * (c[2] - 2)) / 6) + ''' Case 4.c: Count groups of size 3 + with different remainders''' + + res += c[0] * c[1] * c[2] + ''' Return total count stored in res''' + + return res + '''Driver program''' + +arr = [3, 6, 7, 2, 9] +n = len(arr) +print (""Required number of groups are"", + int(findgroups(arr, n)))" +Minimum number of squares whose sum equals to given number n,"/*Java program for the above approach*/ + +import java.util.*; +import java.awt.Point; +class GFG +{ +/* Function to count minimum + squares that sum to n*/ + + public static int numSquares(int n) + { +/* Creating visited vector + of size n + 1*/ + + int visited[] = new int[n + 1]; +/* Queue of pair to store node + and number of steps*/ + + Queue q = new LinkedList<>(); +/* Initially ans variable is + initialized with inf*/ + + int ans = Integer.MAX_VALUE; +/* Push starting node with 0 + 0 indicate current number + of step to reach n*/ + + q.add(new Point(n, 0)); +/* Mark starting node visited*/ + + visited[n] = 1; + while(q.size() != 0) + { + Point p = q.peek(); + q.poll(); +/* If node reaches its destination + 0 update it with answer*/ + + if(p.x == 0) + ans = Math.min(ans, p.y); +/* Loop for all possible path from + 1 to i*i <= current node(p.first)*/ + + for(int i = 1; i * i <= p.x; i++) + { +/* If we are standing at some node + then next node it can jump to will + be current node- + (some square less than or equal n)*/ + + int path = (p.x - (i * i)); +/* Check if it is valid and + not visited yet*/ + + if(path >= 0 && (visited[path] == 0 || path == 0)) + { +/* Mark visited*/ + + visited[path] = 1; +/* Push it it Queue*/ + + q.add(new Point(path, p.y + 1)); + } + } + } +/* Return ans to calling function*/ + + return ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + System.out.println(numSquares(12)); + } +}"," '''Python3 program for the above approach''' + +import sys + '''Function to count minimum +squares that sum to n''' + +def numSquares(n) : + ''' Creating visited vector + of size n + 1''' + + visited = [0]*(n + 1) + ''' Queue of pair to store node + and number of steps''' + + q = [] + ''' Initially ans variable is + initialized with inf''' + + ans = sys.maxsize + ''' Push starting node with 0 + 0 indicate current number + of step to reach n''' + + q.append([n, 0]) + ''' Mark starting node visited''' + + visited[n] = 1 + while(len(q) > 0) : + p = q[0] + q.pop(0) + ''' If node reaches its destination + 0 update it with answer''' + + if(p[0] == 0) : + ans = min(ans, p[1]) + ''' Loop for all possible path from + 1 to i*i <= current node(p.first)''' + + i = 1 + while i * i <= p[0] : + ''' If we are standing at some node + then next node it can jump to will + be current node- + (some square less than or equal n)''' + + path = p[0] - i * i + ''' Check if it is valid and + not visited yet''' + + if path >= 0 and (visited[path] == 0 or path == 0) : + ''' Mark visited''' + + visited[path] = 1 + ''' Push it it Queue''' + + q.append([path,p[1] + 1]) + i += 1 + ''' Return ans to calling function''' + + return ans + '''Driver code''' + +print(numSquares(12))" +Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2,"/*Java Program for above approach*/ + +public class UniqueNumbers { +/* This function sets the values of + *x and *y to non-repeating elements + in an array arr[] of size n*/ + + public static void UniqueNumbers2(int[] arr,int n) + { + int sum =0; + for(int i = 0;i 0*/ + + if((arr[i]&sum) > 0) + { +/* if result > 0 then arr[i] xored + with the sum1*/ + + sum1 = (sum1^arr[i]); + } + else + { +/* if result == 0 then arr[i] + xored with sum2*/ + + sum2 = (sum2^arr[i]); + } + } +/* print the the two unique numbers*/ + + System.out.println(""The non-repeating elements are ""+ + sum1+"" and ""+sum2); + } +/*Driver Code*/ + + public static void main(String[] args) + { + int[] arr = new int[]{2, 3, 7, 9, 11, 2, 3, 11}; + int n = arr.length; + UniqueNumbers2(arr,n); + } +}"," '''Python3 program for above approach''' + + '''This function sets the values of +*x and *y to non-repeating elements +in an array arr[] of size n''' + +def UniqueNumbers2(arr, n): + sums = 0 + for i in range(0, n): ''' Xor all the elements of the array + all the elements occuring twice will + cancel out each other remaining + two unnique numbers will be xored''' + + sums = (sums ^ arr[i]) + ''' Bitwise & the sum with it's 2's Complement + Bitwise & will give us the sum containing + only the rightmost set bit''' + + sums = (sums & -sums) + ''' sum1 and sum2 will contains 2 unique + elements elements initialized with 0 box + number xored with 0 is number itself''' + + sum1 = 0 + sum2 = 0 + ''' Traversing the array again''' + + for i in range(0, len(arr)): + ''' Bitwise & the arr[i] with the sum + Two possibilities either result == 0 + or result > 0''' + + if (arr[i] & sums) > 0: + ''' If result > 0 then arr[i] xored + with the sum1''' + + sum1 = (sum1 ^ arr[i]) + else: + ''' If result == 0 then arr[i] + xored with sum2''' + + sum2 = (sum2 ^ arr[i]) + ''' Print the the two unique numbers''' + + print(""The non-repeating elements are "", + sum1 ,"" and "", sum2) + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ 2, 3, 7, 9, 11, 2, 3, 11 ] + n = len(arr) + UniqueNumbers2(arr, n)" +Program to count number of set bits in an (big) array,, +Iterative Tower of Hanoi,"/*Java program for iterative +Tower of Hanoi*/ + +class TOH{ +/*A structure to represent a stack*/ + +class Stack +{ + int capacity; + int top; + int array[]; +} +/*Function to create a stack of given capacity.*/ + +Stack createStack(int capacity) +{ + Stack stack = new Stack(); + stack.capacity = capacity; + stack.top = -1; + stack.array = new int[capacity]; + return stack; +} +/*Stack is full when the top is equal +to the last index*/ + +boolean isFull(Stack stack) +{ + return (stack.top == stack.capacity - 1); +} +/*Stack is empty when top is equal to -1*/ + +boolean isEmpty(Stack stack) +{ + return (stack.top == -1); +} +/*Function to add an item to stack.It +increases top by 1*/ + +void push(Stack stack, int item) +{ + if (isFull(stack)) + return; + stack.array[++stack.top] = item; +} +/*Function to remove an item from stack.It +decreases top by 1*/ + +int pop(Stack stack) +{ + if (isEmpty(stack)) + return Integer.MIN_VALUE; + return stack.array[stack.top--]; +} +/*Function to show the movement of disks*/ + +void moveDisk(char fromPeg, char toPeg, int disk) +{ + System.out.println(""Move the disk "" + disk + + "" from "" + fromPeg + + "" to "" + toPeg); +} +/*Function to implement legal movement between +two poles*/ + +void moveDisksBetweenTwoPoles(Stack src, Stack dest, + char s, char d) +{ + int pole1TopDisk = pop(src); + int pole2TopDisk = pop(dest); +/* When pole 1 is empty*/ + + if (pole1TopDisk == Integer.MIN_VALUE) + { + push(src, pole2TopDisk); + moveDisk(d, s, pole2TopDisk); + } +/* When pole2 pole is empty*/ + + else if (pole2TopDisk == Integer.MIN_VALUE) + { + push(dest, pole1TopDisk); + moveDisk(s, d, pole1TopDisk); + } +/* When top disk of pole1 > top disk of pole2*/ + + else if (pole1TopDisk > pole2TopDisk) + { + push(src, pole1TopDisk); + push(src, pole2TopDisk); + moveDisk(d, s, pole2TopDisk); + } +/* When top disk of pole1 < top disk of pole2*/ + + else + { + push(dest, pole2TopDisk); + push(dest, pole1TopDisk); + moveDisk(s, d, pole1TopDisk); + } +} +/*Function to implement TOH puzzle*/ + +void tohIterative(int num_of_disks, Stack + src, Stack aux, Stack dest) +{ + int i, total_num_of_moves; + char s = 'S', d = 'D', a = 'A'; +/* If number of disks is even, then + interchange destination pole and + auxiliary pole*/ + + if (num_of_disks % 2 == 0) + { + char temp = d; + d = a; + a = temp; + } + total_num_of_moves = (int)(Math.pow( + 2, num_of_disks) - 1); +/* Larger disks will be pushed first*/ + + for(i = num_of_disks; i >= 1; i--) + push(src, i); + for(i = 1; i <= total_num_of_moves; i++) + { + if (i % 3 == 1) + moveDisksBetweenTwoPoles(src, dest, s, d); + else if (i % 3 == 2) + moveDisksBetweenTwoPoles(src, aux, s, a); + else if (i % 3 == 0) + moveDisksBetweenTwoPoles(aux, dest, a, d); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Input: number of disks*/ + + int num_of_disks = 3; + TOH ob = new TOH(); + Stack src, dest, aux; +/* Create three stacks of size 'num_of_disks' + to hold the disks*/ + + src = ob.createStack(num_of_disks); + dest = ob.createStack(num_of_disks); + aux = ob.createStack(num_of_disks); + ob.tohIterative(num_of_disks, src, aux, dest); +} +} +", +A program to check if a binary tree is BST or not,"/*Java program to check if a given tree is BST.*/ + +class Sol +{ +/*A binary tree node has data, pointer to +left child && a pointer to right child /*/ + +static class Node +{ + int data; + Node left, right; +}; +/*Returns true if given tree is BST.*/ + +static boolean isBST(Node root, Node l, Node r) +{ +/* Base condition*/ + + if (root == null) + return true; +/* if left node exist then check it has + correct data or not i.e. left node's data + should be less than root's data*/ + + if (l != null && root.data <= l.data) + return false; +/* if right node exist then check it has + correct data or not i.e. right node's data + should be greater than root's data*/ + + if (r != null && root.data >= r.data) + return false; +/* check recursively for every node.*/ + + return isBST(root.left, l, root) && + isBST(root.right, root, r); +} +/*Helper function that allocates a new node with the +given data && null left && right pointers. /*/ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); +} +/*Driver code*/ + +public static void main(String args[]) +{ + Node root = newNode(3); + root.left = newNode(2); + root.right = newNode(5); + root.left.left = newNode(1); + root.left.right = newNode(4); + if (isBST(root,null,null)) + System.out.print(""Is BST""); + else + System.out.print(""Not a BST""); +} +}",""""""" Program to check if a given Binary +Tree is balanced like a Red-Black Tree """""" + +class newNode: + '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Returns true if given tree is BST.''' + +def isBST(root, l = None, r = None): + ''' Base condition''' + + if (root == None) : + return True + ''' if left node exist then check it has + correct data or not i.e. left node's data + should be less than root's data''' + + if (l != None and root.data <= l.data) : + return False + ''' if right node exist then check it has + correct data or not i.e. right node's data + should be greater than root's data''' + + if (r != None and root.data >= r.data) : + return False + ''' check recursively for every node.''' + + + return isBST(root.left, l, root) and \ + isBST(root.right, root, r) + + '''Driver Code''' + + +if __name__ == '__main__': + root = newNode(3) + root.left = newNode(2) + root.right = newNode(5) + root.right.left = newNode(1) + root.right.right = newNode(4) + if (isBST(root,None,None)): + print(""Is BST"") + else: + print(""Not a BST"")" +Print modified array after executing the commands of addition and subtraction,"/*Java program to find modified array +after executing m commands/queries*/ + +import java.util.Arrays; + +class GFG { + +/* Update function for every command*/ + + static void updateQuery(int arr[], int n, + int q, int l, int r, int k) + { + +/* If q == 0, add 'k' and '-k' + to 'l-1' and 'r' index*/ + + if (q == 0){ + arr[l-1] += k; + arr[r] += -k; + } + +/* If q == 1, add '-k' and 'k' + to 'l-1' and 'r' index*/ + + else{ + arr[l-1] += -k; + arr[r] += k; + } + + return; + } + +/* Function to generate the final + array after executing all + commands*/ + + static void generateArray(int arr[], int n) + { +/* Generate final array with the + help of DP concept*/ + + for (int i = 1; i < n; ++i) + arr[i] += arr[i-1]; + + } +/* driver code*/ + + public static void main(String arg[]) + { + int n = 5; + int arr[] = new int[n+1]; + Arrays.fill(arr, 0); + + int q = 0, l = 1, r = 3, k = 2; + updateQuery(arr, n, q, l, r, k); + + q = 1 ; l = 3; r = 5; k = 3; + updateQuery(arr, n, q, l, r, k); + + q = 0 ; l = 2; r = 5; k = 1; + updateQuery(arr, n, q, l, r, k); + + +/* Generate final array*/ + + generateArray(arr, n); + +/* Printing the final modified array*/ + + for (int i = 0; i < n; ++i) + System.out.print(arr[i]+"" ""); + } +} + + +"," '''Python3 program to find modified array +after executing m commands/queries''' + + + '''Update function for every command''' + +def updateQuery(arr, n, q, l, r, k): + + ''' If q == 0, add 'k' and '-k' + to 'l-1' and 'r' index''' + + if (q == 0): + arr[l - 1] += k + arr[r] += -k + + ''' If q == 1, add '-k' and 'k' + to 'l-1' and 'r' index''' + + else: + arr[l - 1] += -k + arr[r] += k + + return + + '''Function to generate the final +array after executing all commands''' + +def generateArray(arr, n): + + ''' Generate final array with the + help of DP concept''' + + for i in range(1, n): + arr[i] += arr[i - 1] + + return + + '''Driver Code''' + +n = 5 +arr = [0 for i in range(n + 1)] + +q = 0; l = 1; r = 3; k = 2 +updateQuery(arr, n, q, l, r, k) + +q, l, r, k = 1, 3, 5, 3 +updateQuery(arr, n, q, l, r, k); + +q, l, r, k = 0, 2, 5, 1 +updateQuery(arr, n, q, l, r, k) '''Generate final array''' + +generateArray(arr, n) + + '''Printing the final modified array''' + +for i in range(n): + print(arr[i], end = "" "") + + + +" +Minimum operations required to make each row and column of matrix equals,"/*Java Program to Find minimum +number of operation required +such that sum of elements on +each row and column becomes same*/ + +import java.io.*; +class GFG { +/* Function to find minimum + operation required + to make sum of each row + and column equals*/ + + static int findMinOpeartion(int matrix[][], + int n) + { +/* Initialize the sumRow[] + and sumCol[] array to 0*/ + + int[] sumRow = new int[n]; + int[] sumCol = new int[n]; +/* Calculate sumRow[] and + sumCol[] array*/ + + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + { + sumRow[i] += matrix[i][j]; + sumCol[j] += matrix[i][j]; + } +/* Find maximum sum value + in either row or in column*/ + + int maxSum = 0; + for (int i = 0; i < n; ++i) + { + maxSum = Math.max(maxSum, sumRow[i]); + maxSum = Math.max(maxSum, sumCol[i]); + } + int count = 0; + for (int i = 0, j = 0; i < n && j < n;) + { +/* Find minimum increment + required in either row + or column*/ + + int diff = Math.min(maxSum - sumRow[i], + maxSum - sumCol[j]); +/* Add difference in + corresponding cell, + sumRow[] and sumCol[] + array*/ + + matrix[i][j] += diff; + sumRow[i] += diff; + sumCol[j] += diff; +/* Update the count + variable*/ + + count += diff; +/* If ith row satisfied, + increment ith value + for next iteration*/ + + if (sumRow[i] == maxSum) + ++i; +/* If jth column satisfied, + increment jth value for + next iteration*/ + + if (sumCol[j] == maxSum) + ++j; + } + return count; + } +/* Utility function to + print matrix*/ + + static void printMatrix(int matrix[][], + int n) + { + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n; ++j) + System.out.print(matrix[i][j] + + "" ""); + System.out.println(); + } + } + /* Driver program */ + + public static void main(String[] args) + { + int matrix[][] = {{1, 2}, + {3, 4}}; + System.out.println(findMinOpeartion(matrix, 2)); + printMatrix(matrix, 2); + } +}"," '''Python 3 Program to Find minimum +number of operation required such +that sum of elements on each row +and column becomes same''' + + '''Function to find minimum operation +required to make sum of each row +and column equals''' + +def findMinOpeartion(matrix, n): ''' Initialize the sumRow[] and sumCol[] + array to 0''' + + sumRow = [0] * n + sumCol = [0] * n + ''' Calculate sumRow[] and sumCol[] array''' + + for i in range(n): + for j in range(n) : + sumRow[i] += matrix[i][j] + sumCol[j] += matrix[i][j] + ''' Find maximum sum value in + either row or in column''' + + maxSum = 0 + for i in range(n) : + maxSum = max(maxSum, sumRow[i]) + maxSum = max(maxSum, sumCol[i]) + count = 0 + i = 0 + j = 0 + while i < n and j < n : + ''' Find minimum increment required + in either row or column''' + + diff = min(maxSum - sumRow[i], + maxSum - sumCol[j]) + ''' Add difference in corresponding + cell, sumRow[] and sumCol[] array''' + + matrix[i][j] += diff + sumRow[i] += diff + sumCol[j] += diff + ''' Update the count variable''' + + count += diff + ''' If ith row satisfied, increment + ith value for next iteration''' + + if (sumRow[i] == maxSum): + i += 1 + ''' If jth column satisfied, increment + jth value for next iteration''' + + if (sumCol[j] == maxSum): + j += 1 + return count + '''Utility function to print matrix''' + +def printMatrix(matrix, n): + for i in range(n) : + for j in range(n): + print(matrix[i][j], end = "" "") + print() + '''Driver code''' + +if __name__ == ""__main__"": + matrix = [[ 1, 2 ], + [ 3, 4 ]] + print(findMinOpeartion(matrix, 2)) + printMatrix(matrix, 2)" +Merge Two Binary Trees by doing Node Sum (Recursive and Iterative),"/*Java program to Merge Two Binary Trees*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + public Node(int data, Node left, Node right) { + this.data = data; + this.left = left; + this.right = right; + } + /* Helper method that allocates a new node with the + given data and NULL left and right pointers. */ + + static Node newNode(int data) + { + return new Node(data, null, null); + } + /* Given a binary tree, print its nodes in inorder*/ + + static void inorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + inorder(node.left); + /* then print the data of node */ + + System.out.printf(""%d "", node.data); + /* now recur on right child */ + + inorder(node.right); + } + /* Method to merge given two binary trees*/ + + static Node MergeTrees(Node t1, Node t2) + { + if (t1 == null) + return t2; + if (t2 == null) + return t1; + t1.data += t2.data; + t1.left = MergeTrees(t1.left, t2.left); + t1.right = MergeTrees(t1.right, t2.right); + return t1; + } +/* Driver method*/ + + public static void main(String[] args) + { + /* Let us construct the first Binary Tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 + */ + + Node root1 = newNode(1); + root1.left = newNode(2); + root1.right = newNode(3); + root1.left.left = newNode(4); + root1.left.right = newNode(5); + root1.right.right = newNode(6); + /* Let us construct the second Binary Tree + 4 + / \ + 1 7 + / / \ + 3 2 6 */ + + Node root2 = newNode(4); + root2.left = newNode(1); + root2.right = newNode(7); + root2.left.left = newNode(3); + root2.right.left = newNode(2); + root2.right.right = newNode(6); + Node root3 = MergeTrees(root1, root2); + System.out.printf(""The Merged Binary Tree is:\n""); + inorder(root3); + } +}"," '''Python3 program to Merge Two Binary Trees''' + + '''Helper class that allocates a new node +with the given data and None left and +right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Given a binary tree, prits nodes +in inorder''' + +def inorder(node): + if (not node): + return + ''' first recur on left child''' + + inorder(node.left) + ''' then print the data of node''' + + print(node.data, end = "" "") + ''' now recur on right child''' + + inorder(node.right) + '''Function to merge given two +binary trees''' + +def MergeTrees(t1, t2): + if (not t1): + return t2 + if (not t2): + return t1 + t1.data += t2.data + t1.left = MergeTrees(t1.left, t2.left) + t1.right = MergeTrees(t1.right, t2.right) + return t1 + '''Driver code''' + +if __name__ == '__main__': + ''' Let us construct the first Binary Tree + 1 + / \ + 2 3 + / \ \ + 4 5 6''' + + root1 = newNode(1) + root1.left = newNode(2) + root1.right = newNode(3) + root1.left.left = newNode(4) + root1.left.right = newNode(5) + root1.right.right = newNode(6) + ''' Let us construct the second Binary Tree + 4 + / \ + 1 7 + / / \ + 3 2 6''' + + root2 = newNode(4) + root2.left = newNode(1) + root2.right = newNode(7) + root2.left.left = newNode(3) + root2.right.left = newNode(2) + root2.right.right = newNode(6) + root3 = MergeTrees(root1, root2) + print(""The Merged Binary Tree is:"") + inorder(root3)" +Palindrome Partitioning | DP-17,"import java.io.*; +class GFG { +/*minCut function*/ + + public static int minCut(String a) + { + int[] cut = new int[a.length()]; + boolean[][] palindrome = new boolean[a.length()][a.length()]; + for (int i = 0; i < a.length(); i++) { + int minCut = i; + for (int j = 0; j <= i; j++) { + if (a.charAt(i) == a.charAt(j) && (i - j < 2 || palindrome[j + 1][i - 1])) { + palindrome[j][i] = true; + minCut = Math.min(minCut, j == 0 ? 0 : (cut[j - 1] + 1)); + } + } + cut[i] = minCut; + } + return cut[a.length() - 1]; + } +/*Driver code*/ + + public static void main(String[] args) + { + System.out.println(minCut(""aab"")); + System.out.println(minCut(""aabababaxx"")); + } +}"," '''minCut function''' + +def minCut(a): + cut = [0 for i in range(len(a))] + palindrome = [[False for i in range(len(a))] for j in range(len(a))] + for i in range(len(a)): + minCut = i; + for j in range(i + 1): + if (a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1])): + palindrome[j][i] = True; + minCut = min(minCut,0 if j == 0 else (cut[j - 1] + 1)); + cut[i] = minCut; + return cut[len(a) - 1]; + '''Driver code''' + +if __name__=='__main__': + print(minCut(""aab"")) + print(minCut(""aabababaxx""))" +Find the repeating and the missing | Added 3 new methods,"/*Java program to find the +repeating and missing elements +using Maps*/ + + +import java.util.*; + +public class Test1 { + + public static void main(String[] args) + { + + int[] arr = { 4, 3, 6, 2, 1, 1 }; + + Map numberMap + = new HashMap<>(); + + int max = arr.length; + + for (Integer i : arr) { + + if (numberMap.get(i) == null) { + numberMap.put(i, true); + } + else { + System.out.println(""Repeating = "" + i); + } + } + for (int i = 1; i <= max; i++) { + if (numberMap.get(i) == null) { + System.out.println(""Missing = "" + i); + } + } + } +} +"," '''Python3 program to find the +repeating and missing elements +using Maps''' + +def main(): + + arr = [ 4, 3, 6, 2, 1, 1 ] + + numberMap = {} + + max = len(arr) + for i in arr: + if not i in numberMap: + numberMap[i] = True + + else: + print(""Repeating ="", i) + + for i in range(1, max + 1): + if not i in numberMap: + print(""Missing ="", i) +main() + + +" +Connect n ropes with minimum cost,"/*Java program to connect n +ropes with minimum cost*/ + +import java.util.*; +class ConnectRopes { + static int minCost(int arr[], int n) + { +/* Create a priority queue*/ + + PriorityQueue pq = new PriorityQueue(); + for (int i = 0; i < n; i++) { + pq.add(arr[i]); + }/* Initialize result*/ + + int res = 0; +/* While size of priority queue + is more than 1*/ + + while (pq.size() > 1) { +/* Extract shortest two ropes from pq*/ + + int first = pq.poll(); + int second = pq.poll(); +/* Connect the ropes: update result + and insert the new rope to pq*/ + + res += first + second; + pq.add(first + second); + } + return res; + } +/* Driver program to test above function*/ + + public static void main(String args[]) + { + int len[] = { 4, 3, 2, 6 }; + int size = len.length; + System.out.println(""Total cost for connecting"" + + "" ropes is "" + minCost(len, size)); + } +}"," '''Python3 program to connect n +ropes with minimum cost''' + +import heapq +def minCost(arr, n): + ''' Create a priority queue out of the + given list''' + + heapq.heapify(arr) + ''' Initializ result''' + + res = 0 + ''' While size of priority queue + is more than 1''' + + while(len(arr) > 1): + ''' Extract shortest two ropes from arr''' + + first = heapq.heappop(arr) + second = heapq.heappop(arr) + ''' Connect the ropes: update result + and insert the new rope to arr''' + + res += first + second + heapq.heappush(arr, first + second) + return res + '''Driver code''' + +if __name__ == '__main__': + lengths = [ 4, 3, 2, 6 ] + size = len(lengths) + print(""Total cost for connecting ropes is "" + + str(minCost(lengths, size)))" +Minimum absolute difference of adjacent elements in a circular array,"/*Java program to find maximum difference +between adjacent elements in a circular +array.*/ + +class GFG { + + static void minAdjDifference(int arr[], int n) + { + if (n < 2) + return; + +/* Checking normal adjacent elements*/ + + int res = Math.abs(arr[1] - arr[0]); + for (int i = 2; i < n; i++) + res = Math.min(res, Math.abs(arr[i] - arr[i - 1])); + +/* Checking circular link*/ + + res = Math.min(res, Math.abs(arr[n - 1] - arr[0])); + + System.out.print(""Min Difference = "" + res); + } + +/* driver code*/ + + public static void main(String arg[]) + { + + int a[] = { 10, 12, 13, 15, 10 }; + int n = a.length; + + minAdjDifference(a, n); + } +} + + +"," '''Python3 program to find maximum +difference between adjacent +elements in a circular array.''' + + +def minAdjDifference(arr, n): + + if (n < 2): return + + ''' Checking normal adjacent elements''' + + res = abs(arr[1] - arr[0]) + + for i in range(2, n): + res = min(res, abs(arr[i] - arr[i - 1])) + + ''' Checking circular link''' + + res = min(res, abs(arr[n - 1] - arr[0])) + + print(""Min Difference = "", res) + + '''Driver Code''' + +a = [10, 12, 13, 15, 10] +n = len(a) +minAdjDifference(a, n) + + +" +Create a matrix with alternating rectangles of O and X,"/*Java code to demonstrate the working.*/ + +import java.io.*; +class GFG { +/*Function to print alternating +rectangles of 0 and X*/ + + static void fill0X(int m, int n) +{ + /* k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator */ + + int i, k = 0, l = 0; +/* Store given number of rows + and columns for later use*/ + + int r = m, c = n; +/* A 2D array to store + the output to be printed*/ + + char a[][] = new char[m][n]; +/* Iniitialize the character + to be stoed in a[][]*/ + + char x = 'X'; +/* Fill characters in a[][] in spiral + form. Every iteration fills + one rectangle of either Xs or Os*/ + + while (k < m && l < n) + { + /* Fill the first row from the remaining rows */ + + for (i = l; i < n; ++i) + a[k][i] = x; + k++; + /* Fill the last column from the remaining columns */ + + for (i = k; i < m; ++i) + a[i][n-1] = x; + n--; + /* Fill the last row from the remaining rows */ + + if (k < m) + { + for (i = n-1; i >= l; --i) + a[m-1][i] = x; + m--; + } + /* Print the first column +/* from the remaining columns */ +*/ + if (l < n) + { + for (i = m-1; i >= k; --i) + a[i][l] = x; + l++; + } +/* Flip character for next iteration*/ + + x = (x == '0')? 'X': '0'; + } +/* Print the filled matrix*/ + + for (i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + System.out.print(a[i][j] + "" ""); + System.out.println(); + } +} +/* Driver program to test above functions */ + +public static void main (String[] args) { + System.out.println(""Output for m = 5, n = 6""); + fill0X(5, 6); + System.out.println(""Output for m = 4, n = 4""); + fill0X(4, 4); + System.out.println(""Output for m = 3, n = 4""); + fill0X(3, 4); + } +}"," '''Python3 program to Create a matrix with +alternating rectangles of O and X''' + + '''Function to pralternating rectangles +of 0 and X''' + +def fill0X(m, n): ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator''' + + i, k, l = 0, 0, 0 + ''' Store given number of rows and + columns for later use''' + + r = m + c = n + ''' A 2D array to store the output + to be printed''' + + a = [[None] * n for i in range(m)] + '''Iniitialize the character to be stoed in a[][]''' + + x = 'X' + ''' Fill characters in a[][] in spiral form. + Every iteration fills one rectangle of + either Xs or Os''' + + while k < m and l < n: + ''' Fill the first row from the + remaining rows''' + + for i in range(l, n): + a[k][i] = x + k += 1 + ''' Fill the last column from + the remaining columns''' + + for i in range(k, m): + a[i][n - 1] = x + n -= 1 + ''' Fill the last row from the + remaining rows''' + + if k < m: + for i in range(n - 1, l - 1, -1): + a[m - 1][i] = x + m -= 1 + ''' Print the first column from + the remaining columns''' + + if l < n: + for i in range(m - 1, k - 1, -1): + a[i][l] = x + l += 1 + ''' Flip character for next iteration''' + + x = 'X' if x == '0' else '0' + ''' Print the filled matrix''' + + for i in range(r): + for j in range(c): + print(a[i][j], end = "" "") + print() + '''Driver Code''' + +if __name__ == '__main__': + print(""Output for m = 5, n = 6"") + fill0X(5, 6) + print(""Output for m = 4, n = 4"") + fill0X(4, 4) + print(""Output for m = 3, n = 4"") + fill0X(3, 4)" +"Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted","/*Java program to find the Minimum length Unsorted Subarray, +sorting which makes the complete array sorted*/ + +class Main +{ + static void printUnsorted(int arr[], int n) + { + int s = 0, e = n-1, i, max, min; +/* step 1(a) of above algo*/ + + for (s = 0; s < n-1; s++) + { + if (arr[s] > arr[s+1]) + break; + } + if (s == n-1) + { + System.out.println(""The complete array is sorted""); + return; + } +/* step 1(b) of above algo*/ + + for(e = n - 1; e > 0; e--) + { + if(arr[e] < arr[e-1]) + break; + } +/* step 2(a) of above algo*/ + + max = arr[s]; min = arr[s]; + for(i = s + 1; i <= e; i++) + { + if(arr[i] > max) + max = arr[i]; + if(arr[i] < min) + min = arr[i]; + } +/* step 2(b) of above algo*/ + + for( i = 0; i < s; i++) + { + if(arr[i] > min) + { + s = i; + break; + } + } +/* step 2(c) of above algo*/ + + for( i = n -1; i >= e+1; i--) + { + if(arr[i] < max) + { + e = i; + break; + } + } +/* step 3 of above algo*/ + + System.out.println("" The unsorted subarray which""+ + "" makes the given array sorted lies""+ + "" between the indices ""+s+"" and ""+e); + return; + } + public static void main(String args[]) + { + int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60}; + int arr_size = arr.length; + printUnsorted(arr, arr_size); + } +}"," '''Python3 program to find the Minimum length Unsorted Subarray, +sorting which makes the complete array sorted''' + +def printUnsorted(arr, n): + e = n-1 + ''' step 1(a) of above algo''' + + for s in range(0,n-1): + if arr[s] > arr[s+1]: + break + if s == n-1: + print (""The complete array is sorted"") + exit() + ''' step 1(b) of above algo''' + + e= n-1 + while e > 0: + if arr[e] < arr[e-1]: + break + e -= 1 + ''' step 2(a) of above algo''' + + max = arr[s] + min = arr[s] + for i in range(s+1,e+1): + if arr[i] > max: + max = arr[i] + if arr[i] < min: + min = arr[i] + ''' step 2(b) of above algo''' + + for i in range(s): + if arr[i] > min: + s = i + break + ''' step 2(c) of above algo''' + + i = n-1 + while i >= e+1: + if arr[i] < max: + e = i + break + i -= 1 + ''' step 3 of above algo''' + + print (""The unsorted subarray which makes the given array"") + print (""sorted lies between the indexes %d and %d""%( s, e)) +arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60] +arr_size = len(arr) +printUnsorted(arr, arr_size)" +Search an element in a sorted and rotated array,"/* Java program to search an element in + sorted and rotated array using + single pass of Binary Search*/ + +class Main { +/* Returns index of key in arr[l..h] + if key is present, otherwise returns -1*/ + + static int search(int arr[], int l, int h, int key) + { + if (l > h) + return -1; + int mid = (l + h) / 2; + if (arr[mid] == key) + return mid; + /* If arr[l...mid] first subarray is sorted */ + + if (arr[l] <= arr[mid]) { + /* As this subarray is sorted, we + can quickly check if key lies in + half or other half */ + + if (key >= arr[l] && key <= arr[mid]) + return search(arr, l, mid - 1, key); + /*If key not lies in first half subarray, + Divide other half into two subarrays, + such that we can quickly check if key lies + in other half */ + + return search(arr, mid + 1, h, key); + } + /* If arr[l..mid] first subarray is not sorted, + then arr[mid... h] must be sorted subarry*/ + + if (key >= arr[mid] && key <= arr[h]) + return search(arr, mid + 1, h, key); + return search(arr, l, mid - 1, key); + } +/* main function*/ + + public static void main(String args[]) + { + int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; + int n = arr.length; + int key = 6; + int i = search(arr, 0, n - 1, key); + if (i != -1) + System.out.println(""Index: "" + i); + else + System.out.println(""Key not found""); + } +}"," '''Search an element in sorted and rotated array using +single pass of Binary Search''' + '''Returns index of key in arr[l..h] if key is present, +otherwise returns -1''' + +def search (arr, l, h, key): + if l > h: + return -1 + mid = (l + h) // 2 + if arr[mid] == key: + return mid + ''' If arr[l...mid] is sorted''' + + if arr[l] <= arr[mid]: + ''' As this subarray is sorted, we can quickly + check if key lies in half or other half''' + + if key >= arr[l] and key <= arr[mid]: + return search(arr, l, mid-1, key) + + '''If key not lies in first half subarray, + Divide other half into two subarrays, + such that we can quickly check if key lies + in other half ''' + + return search(arr, mid + 1, h, key) ''' If arr[l..mid] is not sorted, then arr[mid... r] + must be sorted''' + + if key >= arr[mid] and key <= arr[h]: + return search(a, mid + 1, h, key) + return search(arr, l, mid-1, key) + '''Driver program''' + +arr = [4, 5, 6, 7, 8, 9, 1, 2, 3] +key = 6 +i = search(arr, 0, len(arr)-1, key) +if i != -1: + print (""Index: % d""% i) +else: + print (""Key not found"")" +Recaman's sequence,"/*Java program to print n-th number in Recaman's +sequence*/ + +import java.io.*; +class GFG { +/* Prints first n terms of Recaman sequence*/ + + static void recaman(int n) + { +/* Create an array to store terms*/ + + int arr[] = new int[n]; +/* First term of the sequence is always 0*/ + + arr[0] = 0; + System.out.print(arr[0]+"" ,""); +/* Fill remaining terms using recursive + formula.*/ + + for (int i = 1; i < n; i++) + { + int curr = arr[i - 1] - i; + int j; + for (j = 0; j < i; j++) + { +/* If arr[i-1] - i is negative or + already exists.*/ + + if ((arr[j] == curr) || curr < 0) + { + curr = arr[i - 1] + i; + break; + } + } + arr[i] = curr; + System.out.print(arr[i]+"", ""); + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int n = 17; + recaman(n); + } +}"," '''Python 3 program to print n-th +number in Recaman's sequence''' + '''Prints first n terms of Recaman +sequence''' + +def recaman(n): + ''' Create an array to store terms''' + + arr = [0] * n + ''' First term of the sequence + is always 0''' + + arr[0] = 0 + print(arr[0], end="", "") + ''' Fill remaining terms using + recursive formula.''' + + for i in range(1, n): + curr = arr[i-1] - i + for j in range(0, i): + ''' If arr[i-1] - i is + negative or already + exists.''' + + if ((arr[j] == curr) or curr < 0): + curr = arr[i-1] + i + break + arr[i] = curr + print(arr[i], end="", "") + '''Driver code''' + +n = 17 +recaman(n)" +Density of Binary Tree in One Traversal,"/*Java program to find density of Binary Tree*/ + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +}/*Class to implement pass by reference of size*/ + +class Size +{ + int size = 0; +} +class BinaryTree +{ + Node root;/* Function to compute height and + size of a binary tree*/ + + int heighAndSize(Node node, Size size) + { + if (node == null) + return 0; +/* compute height of each subtree*/ + + int l = heighAndSize(node.left, size); + int r = heighAndSize(node.right, size); +/* increase size by 1*/ + + size.size++; +/* return larger of the two*/ + + return (l > r) ? l + 1 : r + 1; + } +/* function to calculate density of a binary tree*/ + + float density(Node root) + { + Size size = new Size(); + if (root == null) + return 0; +/* Finds height and size*/ + + int _height = heighAndSize(root, size); + return (float) size.size / _height; + } +/* Driver code to test above methods*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + System.out.println(""Density of given Binary Tree is : "" + + tree.density(tree.root)); + } +}"," '''Python3 program to find density +of a binary tree ''' + + '''A binary tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to compute height and +size of a binary tree ''' + +def heighAndSize(node, size): + if (node == None) : + return 0 + ''' compute height of each subtree ''' + + l = heighAndSize(node.left, size) + r = heighAndSize(node.right, size) + ''' increase size by 1 ''' + + size[0] += 1 + ''' return larger of the two ''' + + return l + 1 if(l > r) else r + 1 + '''function to calculate density +of a binary tree ''' + +def density(root): + if (root == None) : + return 0 + '''To store size ''' + + size = [0] + ''' Finds height and size ''' + + _height = heighAndSize(root, size) + return size[0] / _height + '''Driver Code ''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + print(""Density of given binary tree is "", + density(root))" +"Given a sorted and rotated array, find if there is a pair with a given sum","/*Java program to find +number of pairs with +a given sum in a sorted +and rotated array.*/ + +import java.io.*; +class GFG +{ +/*This function returns +count of number of pairs +with sum equals to x.*/ + +static int pairsInSortedRotated(int arr[], + int n, int x) +{ +/* Find the pivot element. + Pivot element is largest + element of array.*/ + + int i; + for (i = 0; i < n - 1; i++) + if (arr[i] > arr[i + 1]) + break; +/* l is index of + smallest element.*/ + + int l = (i + 1) % n; +/* r is index of + largest element.*/ + + int r = i; +/* Variable to store + count of number + of pairs.*/ + + int cnt = 0; +/* Find sum of pair + formed by arr[l] + and arr[r] and + update l, r and + cnt accordingly.*/ + + while (l != r) + { +/* If we find a pair with + sum x, then increment + cnt, move l and r to + next element.*/ + + if (arr[l] + arr[r] == x) + { + cnt++; +/* This condition is required + to be checked, otherwise + l and r will cross each + other and loop will never + terminate.*/ + + if(l == (r - 1 + n) % n) + { + return cnt; + } + l = (l + 1) % n; + r = (r - 1 + n) % n; + } +/* If current pair sum + is less, move to + the higher sum side.*/ + + else if (arr[l] + arr[r] < x) + l = (l + 1) % n; +/* If current pair sum + is greater, move + to the lower sum side.*/ + + else + r = (n + r - 1) % n; + } + return cnt; +} +/*Driver Code*/ + +public static void main (String[] args) +{ + int arr[] = {11, 15, 6, 7, 9, 10}; + int sum = 16; + int n = arr.length; + System.out.println( + pairsInSortedRotated(arr, n, sum)); +} +}"," '''Python program to find +number of pairs with +a given sum in a sorted +and rotated array. + ''' '''This function returns +count of number of pairs +with sum equals to x.''' + +def pairsInSortedRotated(arr, n, x): + ''' Find the pivot element. + Pivot element is largest + element of array.''' + + for i in range(n): + if arr[i] > arr[i + 1]: + break + ''' l is index of + smallest element.''' + + l = (i + 1) % n + ''' r is index of + largest element.''' + + r = i + ''' Variable to store + count of number + of pairs.''' + + cnt = 0 + ''' Find sum of pair + formed by arr[l] + and arr[r] and + update l, r and + cnt accordingly.''' + + while (l != r): + ''' If we find a pair + with sum x, then + increment cnt, move + l and r to next element.''' + + if arr[l] + arr[r] == x: + cnt += 1 + ''' This condition is + required to be checked, + otherwise l and r will + cross each other and + loop will never terminate.''' + + if l == (r - 1 + n) % n: + return cnt + l = (l + 1) % n + r = (r - 1 + n) % n + ''' If current pair sum + is less, move to + the higher sum side.''' + + elif arr[l] + arr[r] < x: + l = (l + 1) % n + ''' If current pair sum + is greater, move to + the lower sum side.''' + + else: + r = (n + r - 1) % n + return cnt + '''Driver Code''' + +arr = [11, 15, 6, 7, 9, 10] +s = 16 +print(pairsInSortedRotated(arr, 6, s))" +Count of all prime weight nodes between given nodes in the given Tree,"/*Java program to count +prime weight nodes +between two nodes +in the given tree*/ + +import java.util.*; +class GFG{ + +static final int MAX = 1000; +static int []weight = + new int[MAX]; +static int []level = + new int[MAX]; +static int []par = + new int[MAX]; +static boolean []prime = + new boolean[MAX + 1]; +static Vector[] graph = + new Vector[MAX]; + +/*Function to perform +Sieve Of Eratosthenes +for prime number*/ + +static void SieveOfEratosthenes() +{ +/* Initialize all entries of + prime it as true a value in + prime[i] will finally be false + if i is Not a prime, else true.*/ + + for (int i = 0; + i < prime.length; i++) + prime[i] = true; + + for (int p = 2; + p * p <= MAX; p++) + { +/* Check if prime[p] + is not changed, + then it is a prime*/ + + if (prime[p] == true) + { +/* Update all multiples + of p greater than or + equal to the square of it + numbers which are multiple + of p and are less than p^2 + are already been marked.*/ + + for (int i = p * p; + i <= MAX; i += p) + prime[i] = false; + } + } +} + +/*Function to perform dfs*/ + +static void dfs(int node, + int parent, int h) +{ +/* Stores parent of each node*/ + + par[node] = parent; + +/* Stores level of each + node from root*/ + + level[node] = h; + + for (int child : graph[node]) + { + if (child == parent) + continue; + dfs(child, node, h + 1); + } +} + +/*Function to perform prime +number between the path*/ + +static int findPrimeOnPath(int u, + int v) +{ + int count = 0; + +/* The node which is present + farthest from the root + node is taken as v + If u is farther from + root node then swap the two*/ + + if (level[u] > level[v]) + { + int temp = v; + v = u; + u = temp; + } + + int d = level[v] - level[u]; + +/* Find the ancestor of v + which is at same level as u*/ + + while (d-- > 0) + { +/* If Weight is prime + increment count*/ + + if (prime[weight[v]]) + count++; + v = par[v]; + } + +/* If u is the ancestor of v + then u is the LCA of u and v + Now check if weigh[v] + is prime or not*/ + + if (v == u) + { + if (prime[weight[v]]) + count++; + return count; + } + +/* When v and u are on the + same level but are in + different subtree. Now + move both u and v up by + 1 till they are not same*/ + + while (v != u) + { + if (prime[weight[v]]) + count++; + + if (prime[weight[u]]) + count++; + + u = par[u]; + v = par[v]; + } + +/* If weight of first + ancestor is prime*/ + + if (prime[weight[v]]) + count++; + return count; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + for (int i = 0; i < graph.length; i++) + graph[i] = new Vector(); + +/* Precompute all the prime + numbers till MAX*/ + + SieveOfEratosthenes(); + +/* Weights of the node*/ + + weight[1] = 5; + weight[2] = 10; + weight[3] = 11; + weight[4] = 8; + weight[5] = 6; + +/* Edges of the tree*/ + + graph[1].add(2); + graph[2].add(3); + graph[2].add(4); + graph[1].add(5); + + dfs(1, -1, 0); + int u = 3, v = 5; + System.out.print(findPrimeOnPath(u, v)); +} +} + + +"," '''Python3 program count prime weight +nodes between two nodes in the given tree''' + +MAX = 1000 + +weight = [0 for i in range(MAX)] +level = [0 for i in range(MAX)] +par = [0 for i in range(MAX)] +prime = [True for i in range(MAX + 1)] +graph = [[] for i in range(MAX)] + + '''Function to perform +Sieve Of Eratosthenes +for prime number''' + +def SieveOfEratosthenes(): + + ''' Initialize all entries of prime it + as true. A value in prime[i] will + finally be false if i is Not a prime, + else true. memset(prime, true, + sizeof(prime))''' + + for p in range(2, MAX + 1): + if p * p > MAX + 1: + break + + ''' Check if prime[p] is not changed, + then it is a prime''' + + if (prime[p] == True): + + ''' Update all multiples + of p greater than or + equal to the square of it + numbers which are multiple + of p and are less than p^2 + are already been marked.''' + + for i in range(p * p, MAX + 1, p): + prime[i] = False + + '''Function to perform dfs''' + +def dfs(node, parent, h): + + ''' Stores parent of each node''' + + par[node] = parent + + ''' Stores level of each node from root''' + + level[node] = h + + for child in graph[node]: + if (child == parent): + continue + + dfs(child, node, h + 1) + + '''Function to perform prime +number between the path''' + +def findPrimeOnPath(u, v): + + count = 0 + + ''' The node which is present farthest + from the root node is taken as v + If u is farther from root node + then swap the two''' + + if (level[u] > level[v]): + u, v = v, u + + d = level[v] - level[u] + + ''' Find the ancestor of v + which is at same level as u''' + + while (d): + + ''' If Weight is prime + increment count''' + + if (prime[weight[v]]): + count += 1 + + v = par[v] + d -= 1 + + ''' If u is the ancestor of v + then u is the LCA of u and v + Now check if weigh[v] + is prime or not''' + + if (v == u): + if (prime[weight[v]]): + count += 1 + + return count + + ''' When v and u are on the same level but + are in different subtree. Now move both + u and v up by 1 till they are not same''' + + while (v != u): + if (prime[weight[v]]): + count += 1 + + if (prime[weight[u]]): + count += 1 + + u = par[u] + v = par[v] + + ''' If weight of first ancestor + is prime''' + + if (prime[weight[v]]): + count += 1 + + return count + + '''Driver code''' + +if __name__ == '__main__': + + ''' Precompute all the prime + numbers till MAX''' + + SieveOfEratosthenes() + + ''' Weights of the node''' + + weight[1] = 5 + weight[2] = 10 + weight[3] = 11 + weight[4] = 8 + weight[5] = 6 + + ''' Edges of the tree''' + + graph[1].append(2) + graph[2].append(3) + graph[2].append(4) + graph[1].append(5) + + dfs(1, -1, 0) + u = 3 + v = 5 + + print(findPrimeOnPath(u, v)) + + +" +Check if a Binary Tree (not BST) has duplicate values,"/*Java Program to check duplicates +in Binary Tree */ + +import java.util.HashSet; +public class CheckDuplicateValues { +/* Function that used HashSet to find presence of duplicate nodes*/ + + public static boolean checkDupUtil(Node root, HashSet s) + { +/* If tree is empty, there are no + duplicates. */ + + if (root == null) + return false; +/* If current node's data is already present. */ + + if (s.contains(root.data)) + return true; +/* Insert current node */ + + s.add(root.data); +/* Recursively check in left and right + subtrees. */ + + return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); + } +/* To check if tree has duplicates */ + + public static boolean checkDup(Node root) + { + HashSet s=new HashSet<>(); + return checkDupUtil(root, s); + } + public static void main(String args[]) { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(2); + root.left.left = new Node(3); + if (checkDup(root)) + System.out.print(""Yes""); + else + System.out.print(""No""); + } +} +/*A binary tree Node has data, +pointer to left child +and a pointer to right child */ + +class Node { + int data; + Node left,right; + Node(int data) + { + this.data=data; + } +};"," ''' Program to check duplicates +in Binary Tree ''' + ''' +Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None +def checkDupUtil( root, s) : + ''' If tree is empty, there are no + duplicates. ''' + + if (root == None) : + return False + ''' If current node's data is already present. ''' + + if root.data in s: + return True + ''' Insert current node ''' + + s.add(root.data) + ''' Recursively check in left and right + subtrees. ''' + + return checkDupUtil(root.left, s) or checkDupUtil(root.right, s) + '''To check if tree has duplicates ''' + +def checkDup( root) : + s=set() + return checkDupUtil(root, s) + '''Driver Code ''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(2) + root.left.left = newNode(3) + if (checkDup(root)): + print(""Yes"") + else: + print(""No"")" +Array range queries for searching an element,"/*Java program to determine if the element +exists for different range queries*/ + +import java.util.*; +class GFG +{ +/*Structure to represent a query range*/ + +static class Query +{ + int L, R, X; + public Query(int L, int R, int X) + { + this.L = L; + this.R = R; + this.X = X; + } +}; +static int maxn = 100; +static int []root = new int[maxn]; +/*Find the root of the group containing +the element at index x*/ + +static int find(int x) +{ + if(x == root[x]) + return x; + else + return root[x] = find(root[x]); +} +/*merge the two groups containing elements +at indices x and y into one group*/ + +static void uni(int x, int y) +{ + int p = find(x), q = find(y); + if (p != q) + { + root[p] = root[q]; + } +} +static void initialize(int a[], int n, + Query q[], int m) +{ +/* make n subsets with every + element as its root*/ + + for (int i = 0; i < n; i++) + root[i] = i; +/* consecutive elements equal in value are + merged into one single group*/ + + for (int i = 1; i < n; i++) + if (a[i] == a[i - 1]) + uni(i, i - 1); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int a[] = { 1, 1, 5, 4, 5 }; + int n = a.length; + Query q[] = { new Query(0, 2, 2 ), + new Query( 1, 4, 1 ), + new Query( 2, 4, 5 ) }; + int m = q.length; + initialize(a, n, q, m); + for (int i = 0; i < m; i++) + { + int flag = 0; + int l = q[i].L, r = q[i].R, x = q[i].X; + int p = r; + while (p >= l) + { +/* check if the current element in + consideration is equal to x or not + if it is equal, then x exists in the range*/ + + if (a[p] == x) + { + flag = 1; + break; + } + p = find(p) - 1; + } +/* Print if x exists or not*/ + + if (flag != 0) + System.out.println(x + "" exists between ["" + + l + "", "" + r + ""] ""); + else + System.out.println(x + "" does not exist between ["" + + l + "", "" + r + ""] ""); + } +} +}"," '''Python3 program to determine if the element +exists for different range queries + ''' '''Structure to represent a query range''' + +class Query: + def __init__(self, L, R, X): + self.L = L + self.R = R + self.X = X +maxn = 100 +root = [0] * maxn + '''Find the root of the group containing +the element at index x''' + +def find(x): + if x == root[x]: + return x + else: + root[x] = find(root[x]) + return root[x] + '''merge the two groups containing elements +at indices x and y into one group''' + +def uni(x, y): + p = find(x) + q = find(y) + if p != q: + root[p] = root[q] +def initialize(a, n, q, m): + ''' make n subsets with every + element as its root''' + + for i in range(n): + root[i] = i + ''' consecutive elements equal in value are + merged into one single group''' + + for i in range(1, n): + if a[i] == a[i - 1]: + uni(i, i - 1) + '''Driver Code''' + +if __name__ == ""__main__"": + a = [1, 1, 5, 4, 5] + n = len(a) + q = [Query(0, 2, 2), + Query(1, 4, 1), + Query(2, 4, 5)] + m = len(q) + initialize(a, n, q, m) + for i in range(m): + flag = False + l = q[i].L + r = q[i].R + x = q[i].X + p = r + while p >= l: + ''' check if the current element in + consideration is equal to x or not + if it is equal, then x exists in the range''' + + if a[p] == x: + flag = True + break + p = find(p) - 1 + ''' Print if x exists or not''' + + if flag: + print(""%d exists between [%d, %d]"" % (x, l, r)) + else: + print(""%d does not exists between [%d, %d]"" % (x, l, r))" +Count ways of choosing a pair with maximum difference,"/*Java Code to find no. of Ways of choosing +a pair with maximum difference*/ + +import java.util.*; + +class GFG { + + static int countPairs(int a[], int n) + { + +/* To find minimum and maximum of + the array*/ + + int mn = Integer.MAX_VALUE; + int mx = Integer.MIN_VALUE; + for (int i = 0; i < n; i++) { + mn = Math.min(mn, a[i]); + mx = Math.max(mx, a[i]); + } + +/* to find the count of minimum and + maximum elements*/ + + int c1 = 0; +/*Count variables*/ + +int c2 = 0; + for (int i = 0; i < n; i++) { + if (a[i] == mn) + c1++; + if (a[i] == mx) + c2++; + } + +/* condition for all elements equal*/ + + if (mn == mx) + return n * (n - 1) / 2; + else + return c1 * c2; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int a[] = { 3, 2, 1, 1, 3 }; + int n = a.length; + System.out.print(countPairs(a, n)); + } +} + + +"," '''Python Code to find no. +of Ways of choosing +a pair with maximum difference''' + + +def countPairs(a, n): + + ''' To find minimum and maximum of + the array''' + + mn = +2147483647 + mx = -2147483648 + for i in range(n): + mn = min(mn, a[i]) + mx = max(mx, a[i]) + + + ''' to find the count of minimum and + maximum elements''' + + c1 = 0 + '''Count variables''' + + c2 = 0 + for i in range(n): + if (a[i] == mn): + c1+= 1 + if (a[i] == mx): + c2+= 1 + + + ''' condition for all elements equal''' + + if (mn == mx): + return n*(n - 1) // 2 + else: + return c1 * c2 + + '''Driver code''' + + +a = [ 3, 2, 1, 1, 3] +n = len(a) + +print(countPairs(a, n)) + + +" +Non-Repeating Element,"/*Java program to find first non-repeating +element.*/ + +class GFG { + static int firstNonRepeating(int arr[], int n) + { + for (int i = 0; i < n; i++) { + int j; + for (j = 0; j < n; j++) + if (i != j && arr[i] == arr[j]) + break; + if (j == n) + return arr[i]; + } + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 9, 4, 9, 6, 7, 4 }; + int n = arr.length; + System.out.print(firstNonRepeating(arr, n)); + } +}"," '''Python3 program to find first +non-repeating element.''' + +def firstNonRepeating(arr, n): + for i in range(n): + j = 0 + while(j < n): + if (i != j and arr[i] == arr[j]): + break + j += 1 + if (j == n): + return arr[i] + return -1 + '''Driver code''' + +arr = [ 9, 4, 9, 6, 7, 4 ] +n = len(arr) +print(firstNonRepeating(arr, n))" +LIFO (Last-In-First-Out) approach in Programming,"/*Java program to demonstrate +working of LIFO +using Stack in Java*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Pushing element on the top of the stack*/ + + static void stack_push(Stack stack) + { + for (int i = 0; i < 5; i++) { + stack.push(i); + } + } +/* Popping element from the top of the stack*/ + + static void stack_pop(Stack stack) + { + System.out.println(""Pop :""); + for (int i = 0; i < 5; i++) { + Integer y = (Integer)stack.pop(); + System.out.println(y); + } + } +/* Displaying element on the top of the stack*/ + + static void stack_peek(Stack stack) + { + Integer element = (Integer)stack.peek(); + System.out.println(""Element on stack top : "" + element); + } +/* Searching element in the stack*/ + + static void stack_search(Stack stack, int element) + { + Integer pos = (Integer)stack.search(element); + if (pos == -1) + System.out.println(""Element not found""); + else + System.out.println(""Element is found at position "" + pos); + } +/*Driver code*/ + + public static void main(String[] args) + { + Stack stack = new Stack(); + stack_push(stack); + stack_pop(stack); + stack_push(stack); + stack_peek(stack); + stack_search(stack, 2); + stack_search(stack, 6); + } +}", +Row-wise vs column-wise traversal of matrix,"/*Java program showing time difference +in row major and column major access*/ + +import java.time.Duration; +import java.time.Instant; +import java.util.*; +class GFG +{ +/*taking MAX 10000 so that time difference +can be shown*/ + +static int MAX= 10000; +static int [][]arr = new int[MAX][MAX]; +static void rowMajor() +{ + int i, j; +/* accessing element row wise*/ + + for (i = 0; i < MAX; i++) + { + for (j = 0; j < MAX; j++) + { + arr[i][j]++; + } + } +} +static void colMajor() +{ + int i, j; +/* accessing element column wise*/ + + for (i = 0; i < MAX; i++) + { + for (j = 0; j < MAX; j++) + { + arr[j][i]++; + } + } +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Time taken by row major order*/ + + Instant start = Instant.now(); + rowMajor(); + Instant end = Instant.now(); + System.out.println(""Row major access time : ""+ + Duration.between(start, end)); +/* Time taken by column major order*/ + + start = Instant.now(); + colMajor(); + end = Instant.now(); + System.out.printf(""Column major access time : ""+ + Duration.between(start, end)); +} +}"," '''Python3 program showing time difference +in row major and column major access + ''' '''taking MAX 10000 so that time difference +can be shown''' + +MAX = 1000 +from time import clock +arr = [[ 0 for i in range(MAX)] for i in range(MAX)] +def rowMajor(): + global arr + ''' accessing element row wise''' + + for i in range(MAX): + for j in range(MAX): + arr[i][j] += 1 +def colMajor(): + global arr + ''' accessing element column wise''' + + for i in range(MAX): + for j in range(MAX): + arr[j][i] += 1 + '''Driver code''' + +if __name__ == '__main__': + ''' Time taken by row major order''' + + t = clock() + rowMajor(); + t = clock() - t + print(""Row major access time :{:.2f} s"".format(t)) + ''' Time taken by column major order''' + + t = clock() + colMajor() + t = clock() - t + print(""Column major access time :{:.2f} s"".format(t))" +Rearrange positive and negative numbers with constant extra space,"/*Java program to Rearrange positive and negative +numbers in a array*/ + +class GFG { + /* Function to print an array */ + + static void printArray(int A[], int size) + { + for (int i = 0; i < size; i++) + System.out.print(A[i] + "" ""); + System.out.println(""""); + ; + } + /* Function to reverse an array. An array can be +reversed in O(n) time and O(1) space. */ + + static void reverse(int arr[], int l, int r) + { + if (l < r) { + arr = swap(arr, l, r); + reverse(arr, ++l, --r); + } + } +/* Merges two subarrays of arr[]. + First subarray is arr[l..m] + Second subarray is arr[m+1..r]*/ + + static void merge(int arr[], int l, int m, int r) + { +/*Initial index of 1st subarray*/ + +int i = l; +/*Initial index of IInd*/ + +int j = m + 1; + while (i <= m && arr[i] < 0) + i++; +/* arr[i..m] is positive*/ + + while (j <= r && arr[j] < 0) + j++; +/* arr[j..r] is positive + reverse positive part of + left sub-array (arr[i..m])*/ + + reverse(arr, i, m); +/* reverse negative part of + right sub-array (arr[m+1..j-1])*/ + + reverse(arr, m + 1, j - 1); +/* reverse arr[i..j-1]*/ + + reverse(arr, i, j - 1); + } +/* Function to Rearrange positive and negative + numbers in a array*/ + + static void RearrangePosNeg(int arr[], int l, int r) + { + if (l < r) { +/* Same as (l+r)/2, but avoids overflow for + large l and h*/ + + int m = l + (r - l) / 2; +/* Sort first and second halves*/ + + RearrangePosNeg(arr, l, m); + RearrangePosNeg(arr, m + 1, r); + merge(arr, l, m, r); + } + } + static int[] swap(int[] arr, int i, int j) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + return arr; + } + /* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; + int arr_size = arr.length; + RearrangePosNeg(arr, 0, arr_size - 1); + printArray(arr, arr_size); + } +}"," '''Python3 program to Rearrange positive +and negative numbers in an array + ''' '''Function to print an array''' + +def printArray(A, size): + for i in range(0, size): + print(A[i], end = "" "") + print() + '''Function to reverse an array. An array can +be reversed in O(n) time and O(1) space.''' + +def reverse(arr, l, r): + if l < r: + arr[l], arr[r] = arr[r], arr[l] + l, r = l + 1, r - 1 + reverse(arr, l, r) + '''Merges two subarrays of arr[]. +First subarray is arr[l..m] +Second subarray is arr[m + 1..r]''' + +def merge(arr, l, m, r): + '''Initial index of 1st subarray''' + + i = l + + '''Initial index of IInd''' + + j = m + 1 + while i <= m and arr[i] < 0: + i += 1 + ''' arr[i..m] is positive''' + + while j <= r and arr[j] < 0: + j += 1 + ''' arr[j..r] is positive + reverse positive part of left + sub-array (arr[i..m])''' + + reverse(arr, i, m) + ''' reverse negative part of right + sub-array (arr[m + 1..j-1])''' + + reverse(arr, m + 1, j - 1) + ''' reverse arr[i..j-1]''' + + reverse(arr, i, j - 1) + '''Function to Rearrange positive +and negative numbers in a array''' + +def RearrangePosNeg(arr, l, r): + if l < r: + ''' Same as (l + r)/2, but avoids + overflow for large l and h''' + + m = l + (r - l) // 2 + ''' Sort first and second halves''' + + RearrangePosNeg(arr, l, m) + RearrangePosNeg(arr, m + 1, r) + merge(arr, l, m, r) + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6] + arr_size = len(arr) + RearrangePosNeg(arr, 0, arr_size - 1) + printArray(arr, arr_size)" +Last duplicate element in a sorted array,"/*Java code to print last duplicate element +and its index in a sorted array*/ + +import java.io.*; + +class GFG +{ + static void dupLastIndex(int arr[], int n) + { +/* if array is null or size is less + than equal to 0 return*/ + + if (arr == null || n <= 0) + return; + +/* compare elements and return last + duplicate and its index*/ + + for (int i = n - 1; i > 0; i--) + { + if (arr[i] == arr[i - 1]) + { + System.out.println(""Last index:"" + i); + System.out.println(""Last duplicate item: "" + + arr[i]); + return; + } + } + +/* If we reach here, then no duplicate + found.*/ + + System.out.print(""no duplicate found""); + } + +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = {1, 5, 5, 6, 6, 7, 9}; + int n = arr.length; + dupLastIndex(arr, n); + + } +} + + +"," '''Python3 code to print last duplicate +element and its index in a sorted array''' + + +def dupLastIndex(arr, n): + + ''' if array is null or size is less + than equal to 0 return''' + + if (arr == None or n <= 0): + return + + ''' compare elements and return last + duplicate and its index''' + + for i in range(n - 1, 0, -1): + + if (arr[i] == arr[i - 1]): + print(""Last index:"", i, ""\nLast"", + ""duplicate item:"",arr[i]) + return + + ''' If we reach here, then no duplicate + found.''' + + print(""no duplicate found"") + + + + '''Driver Code''' + +arr = [1, 5, 5, 6, 6, 7, 9] +n = len(arr) +dupLastIndex(arr, n)" +Number of primes in a subarray (with updates),"/*Java program to find number of prime numbers in a +subarray and performing updates*/ + +import java.io.*; +import java.util.*; + +class GFG +{ + static int MAX = 1000 ; + static void sieveOfEratosthenes(boolean isPrime[]) + { + isPrime[1] = false; + for (int p = 2; p * p <= MAX; p++) + { + +/* If prime[p] is not changed, then + it is a prime*/ + + if (isPrime[p] == true) + { + +/* Update all multiples of p*/ + + for (int i = p * 2; i <= MAX; i += p) + isPrime[i] = false; + } + } + } + +/* A utility function to get the middle index from corner indexes.*/ + + static int getMid(int s, int e) { return s + (e - s) / 2; } + + /* A recursive function to get the number of primes in a given range + of array indexes. The following are parameters for this function. + + st --> Pointer to segment tree + index --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range */ + + + static int queryPrimesUtil(int[] st, int ss, int se, int qs, int qe, int index) + { + +/* If segment of this node is a part of given range, then return + the number of primes in the segment */ + + if (qs <= ss && qe >= se) + return st[index]; + +/* If segment of this node is outside the given range*/ + + if (se < qs || ss > qe) + return 0; + +/* If a part of this segment overlaps with the given range*/ + + int mid = getMid(ss, se); + return queryPrimesUtil(st, ss, mid, qs, qe, 2 * index + 1) + + queryPrimesUtil(st, mid + 1, se, qs, qe, 2 * index + 2); + } + + /* A recursive function to update the nodes which have the given + index in their range. The following are parameters + st, si, ss and se are same as getSumUtil() + i --> index of the element to be updated. This index is + in input array. + diff --> Value to be added to all nodes which have i in range */ + + + static void updateValueUtil(int[] st, int ss, int se, int i, int diff, int si) + { +/* Base Case: If the input index lies outside the range of + this segment*/ + + if (i < ss || i > se) + return; + +/* If the input index is in range of this node, then update + the value of the node and its children*/ + + st[si] = st[si] + diff; + if (se != ss) { + int mid = getMid(ss, se); + updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); + updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); + } + } + +/* The function to update a value in input array and segment tree. + It uses updateValueUtil() to update the value in segment tree*/ + + + static void updateValue(int arr[], int[] st, int n, + int i, int new_val, boolean isPrime[]) + { +/* Check for erroneous input index*/ + + if (i < 0 || i > n - 1) { + System.out.println(""Invalid Input""); + return; + } + int diff = 0; + int oldValue; + + oldValue = arr[i]; + +/* Update the value in array*/ + + arr[i] = new_val; + +/* Case 1: Old and new values both are primes*/ + + if (isPrime[oldValue] && isPrime[new_val]) + return; + +/* Case 2: Old and new values both non primes*/ + + if ((!isPrime[oldValue]) && (!isPrime[new_val])) + return; + +/* Case 3: Old value was prime, new value is non prime*/ + + if (isPrime[oldValue] && !isPrime[new_val]) + { + diff = -1; + } + +/* Case 4: Old value was non prime, new_val is prime*/ + + if (!isPrime[oldValue] && isPrime[new_val]) + { + diff = 1; + } + +/* Update the values of nodes in segment tree*/ + + updateValueUtil(st, 0, n - 1, i, diff, 0); + } + +/* Return number of primes in range from index qs (query start) to + qe (query end). It mainly uses queryPrimesUtil()*/ + + static void queryPrimes(int[] st, int n, int qs, int qe) + { + int primesInRange = queryPrimesUtil(st, 0, n - 1, qs, qe, 0); + System.out.println(""Number of Primes in subarray from "" + + qs + "" to "" + qe + "" = "" + primesInRange); + } + +/* A recursive function that constructs Segment Tree + for array[ss..se]. + si is index of current node in segment tree st*/ + + static int constructSTUtil(int arr[], int ss, int se, + int[] st, int si, boolean isPrime[]) + { +/* If there is one element in array, check if it + is prime then store 1 in the segment tree else + store 0 and return*/ + + if (ss == se) { + +/* if arr[ss] is prime*/ + + if (isPrime[arr[ss]]) + st[si] = 1; + else + st[si] = 0; + + return st[si]; + } + +/* If there are more than one elements, then recur + for left and right subtrees and store the sum + of the two values in this node*/ + + int mid = getMid(ss, se); + st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1, isPrime) + + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, isPrime); + return st[si]; + } + + /* Function to construct segment tree from given array. + This function allocates memory for segment tree and + calls constructSTUtil() to fill the allocated memory */ + + static int[] constructST(int arr[], int n, boolean isPrime[]) + { +/* Allocate memory for segment tree*/ + + +/* Height of segment tree*/ + + int x = (int)(Math.ceil(Math.log(n)/Math.log(2))); + +/* Maximum size of segment tree*/ + + int max_size = 2 * (int)Math.pow(2, x) - 1; + int[] st = new int[max_size]; + +/* Fill the allocated memory st*/ + + constructSTUtil(arr, 0, n - 1, st, 0, isPrime); + +/* Return the constructed segment tree*/ + + return st; + } + +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = { 1, 2, 3, 5, 7, 9 }; + int n = arr.length; + + /* Preprocess all primes till MAX. + Create a boolean array ""isPrime[0..MAX]"". + A value in prime[i] will finally be false + if i is Not a prime, else true. */ + + boolean[] isPrime = new boolean[MAX + 1]; + Arrays.fill(isPrime, Boolean.TRUE); + sieveOfEratosthenes(isPrime); + +/* Build segment tree from given array*/ + + int[] st = constructST(arr, n, isPrime); + +/* Query 1: Query(start = 0, end = 4)*/ + + int start = 0; + int end = 4; + queryPrimes(st, n, start, end); + +/* Query 2: Update(i = 3, x = 6), i.e Update + a[i] to x*/ + + int i = 3; + int x = 6; + updateValue(arr, st, n, i, x, isPrime); + +/* uncomment to see array after update + for(int i = 0; i < n; i++) cout << arr[i] << "" "";*/ + + +/* Query 3: Query(start = 0, end = 4)*/ + + start = 0; + end = 4; + queryPrimes(st, n, start, end); + } +} + + +"," '''Python3 program to find number of prime numbers in a +subarray and performing updates''' + +from math import ceil, floor, log +MAX = 1000 + +def sieveOfEratosthenes(isPrime): + + isPrime[1] = False + + for p in range(2, MAX + 1): + if p * p > MAX: + break + + ''' If prime[p] is not changed, then + it is a prime''' + + if (isPrime[p] == True): + + ''' Update all multiples of p''' + + for i in range(2 * p, MAX + 1, p): + isPrime[i] = False + + '''A utility function to get the middle index from corner indexes.''' + +def getMid(s, e): + return s + (e - s) // 2 + ''' +/* A recursive function to get the number of primes in a given range + of array indexes. The following are parameters for this function. + + st --> Pointer to segment tree + index --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range */''' + +def queryPrimesUtil(st, ss, se, qs, qe, index): + + ''' If segment of this node is a part of given range, then return + the number of primes in the segment''' + + if (qs <= ss and qe >= se): + return st[index] + + ''' If segment of this node is outside the given range''' + + if (se < qs or ss > qe): + return 0 + + ''' If a part of this segment overlaps with the given range''' + + mid = getMid(ss, se) + return queryPrimesUtil(st, ss, mid, qs, qe, 2 * index + 1) + \ + queryPrimesUtil(st, mid + 1, se, qs, qe, 2 * index + 2) + + '''/* A recursive function to update the nodes which have the given +index in their range. The following are parameters + st, si, ss and se are same as getSumUtil() + i --> index of the element to be updated. This index is + in input array. +diff --> Value to be added to all nodes which have i in range */''' + +def updateValueUtil(st, ss, se, i, diff, si): + + ''' Base Case: If the input index lies outside the range of + this segment''' + + if (i < ss or i > se): + return + + ''' If the input index is in range of this node, then update + the value of the node and its children''' + + st[si] = st[si] + diff + if (se != ss): + mid = getMid(ss, se) + updateValueUtil(st, ss, mid, i, diff, 2 * si + 1) + updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2) + + '''The function to update a value in input array and segment tree. +It uses updateValueUtil() to update the value in segment tree''' + +def updateValue(arr,st, n, i, new_val,isPrime): + + ''' Check for erroneous input index''' + + if (i < 0 or i > n - 1): + printf(""Invalid Input"") + return + + diff, oldValue = 0, 0 + + oldValue = arr[i] + + ''' Update the value in array''' + + arr[i] = new_val + + ''' Case 1: Old and new values both are primes''' + + if (isPrime[oldValue] and isPrime[new_val]): + return + + ''' Case 2: Old and new values both non primes''' + + if ((not isPrime[oldValue]) and (not isPrime[new_val])): + return + + ''' Case 3: Old value was prime, new value is non prime''' + + if (isPrime[oldValue] and not isPrime[new_val]): + diff = -1 + + ''' Case 4: Old value was non prime, new_val is prime''' + + if (not isPrime[oldValue] and isPrime[new_val]): + diff = 1 + + ''' Update the values of nodes in segment tree''' + + updateValueUtil(st, 0, n - 1, i, diff, 0) + + '''Return number of primes in range from index qs (query start) to +qe (query end). It mainly uses queryPrimesUtil()''' + +def queryPrimes(st, n, qs, qe): + + primesInRange = queryPrimesUtil(st, 0, n - 1, qs, qe, 0) + + print(""Number of Primes in subarray from "", qs,"" to "", qe,"" = "", primesInRange) + + '''A recursive function that constructs Segment Tree +for array[ss..se]. +si is index of current node in segment tree st''' + +def constructSTUtil(arr, ss, se, st,si,isPrime): + + ''' If there is one element in array, check if it + is prime then store 1 in the segment tree else + store 0 and return''' + + if (ss == se): + + ''' if arr[ss] is prime''' + + if (isPrime[arr[ss]]): + st[si] = 1 + else: + st[si] = 0 + + return st[si] + + ''' If there are more than one elements, then recur + for left and right subtrees and store the sum + of the two values in this node''' + + mid = getMid(ss, se) + st[si] = constructSTUtil(arr, ss, mid, st,si * 2 + 1, isPrime) + \ + constructSTUtil(arr, mid + 1, se, st,si * 2 + 2, isPrime) + return st[si] + + '''/* Function to construct segment tree from given array. +This function allocates memory for segment tree and +calls constructSTUtil() to fill the allocated memory */''' + +def constructST(arr, n, isPrime): + + ''' Allocate memory for segment tree''' + + + ''' Height of segment tree''' + + x = ceil(log(n, 2)) + + ''' Maximum size of segment tree''' + + max_size = 2 * pow(2, x) - 1 + + st = [0]*(max_size) + + ''' Fill the allocated memory st''' + + constructSTUtil(arr, 0, n - 1, st, 0, isPrime) + + ''' Return the constructed segment tree''' + + return st + + '''Driver code''' + +if __name__ == '__main__': + + arr= [ 1, 2, 3, 5, 7, 9] + n = len(arr) + + ''' /* Preprocess all primes till MAX. + Create a boolean array ""isPrime[0..MAX]"". + A value in prime[i] will finally be false + if i is Not a prime, else true. */''' + + + isPrime = [True]*(MAX + 1) + sieveOfEratosthenes(isPrime) + + ''' Build segment tree from given array''' + + st = constructST(arr, n, isPrime) + + ''' Query 1: Query(start = 0, end = 4)''' + + start = 0 + end = 4 + queryPrimes(st, n, start, end) + + ''' Query 2: Update(i = 3, x = 6), i.e Update + a[i] to x''' + + i = 3 + x = 6 + updateValue(arr, st, n, i, x, isPrime) + + ''' uncomment to see array after update + for(i = 0 i < n i++) cout << arr[i] << "" ""''' + + + ''' Query 3: Query(start = 0, end = 4)''' + + start = 0 + end = 4 + queryPrimes(st, n, start, end) + + +" +Maximum determinant of a matrix with every values either 0 or n,"/*Java program to find maximum possible +determinant of 0/n matrix.*/ + +import java.io.*; +public class GFG +{ +/*Function for maximum determinant*/ + +static int maxDet(int n) +{ + return (2 * n * n * n); +} +/*Function to print resulatant matrix*/ + +void resMatrix(int n) +{ + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { +/* three position where 0 appears*/ + + if (i == 0 && j == 2) + System.out.print(""0 ""); + else if (i == 1 && j == 0) + System.out.print(""0 ""); + else if (i == 2 && j == 1) + System.out.print(""0 ""); +/* position where n appears*/ + + else + System.out.print(n +"" ""); + } + System.out.println(""""); + } +} +/* Driver code*/ + + static public void main (String[] args) + { + int n = 15; + GFG geeks=new GFG(); + System.out.println(""Maximum Determinant = "" + + maxDet(n)); + System.out.println(""Resultant Matrix :""); + geeks.resMatrix(n); + } +}"," '''Python 3 program to find maximum +possible determinant of 0/n matrix. + ''' '''Function for maximum determinant''' + +def maxDet(n): + return 2 * n * n * n + '''Function to print resulatant matrix''' + +def resMatrix(n): + for i in range(3): + for j in range(3): + ''' three position where 0 appears''' + + if i == 0 and j == 2: + print(""0"", end = "" "") + elif i == 1 and j == 0: + print(""0"", end = "" "") + elif i == 2 and j == 1: + print(""0"", end = "" "") + ''' position where n appears''' + + else: + print(n, end = "" "") + print(""\n"") + '''Driver code''' + +n = 15 +print(""Maximum Detrminat="", maxDet(n)) +print(""Resultant Matrix:"") +resMatrix(n)" +Check for Majority Element in a sorted array,"/* Java Program to check for majority element in a sorted array */ + +import java.io.*; +class Majority { + /* If x is present in arr[low...high] then returns the index of + first occurrence of x, otherwise returns -1 */ + + static int _binarySearch(int arr[], int low, int high, int x) + { + if (high >= low) + { + int mid = (low + high)/2; /* Check if arr[mid] is the first occurrence of x. + arr[mid] is first occurrence if x is one of the following + is true: + (i) mid == 0 and arr[mid] == x + (ii) arr[mid-1] < x and arr[mid] == x + */ + + if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) ) + return mid; + else if (x > arr[mid]) + return _binarySearch(arr, (mid + 1), high, x); + else + return _binarySearch(arr, low, (mid -1), x); + } + return -1; + } + /* This function returns true if the x is present more than n/2 + times in arr[] of size n */ + + static boolean isMajority(int arr[], int n, int x) + { + /* Find the index of first occurrence of x in arr[] */ + + int i = _binarySearch(arr, 0, n-1, x); + /* If element is not present at all, return false*/ + + if (i == -1) + return false; + /* check if the element is present more than n/2 times */ + + if (((i + n/2) <= (n -1)) && arr[i + n/2] == x) + return true; + else + return false; + } + /*Driver function to check for above functions*/ + + public static void main (String[] args) { + int arr[] = {1, 2, 3, 3, 3, 3, 10}; + int n = arr.length; + int x = 3; + if (isMajority(arr, n, x)==true) + System.out.println(x + "" appears more than ""+ + n/2 + "" times in arr[]""); + else + System.out.println(x + "" does not appear more than "" + + n/2 + "" times in arr[]""); + } +}"," '''Python3 Program to check for majority element in a sorted array''' + + '''If x is present in arr[low...high] then returns the index of +first occurrence of x, otherwise returns -1 */''' + +def _binarySearch(arr, low, high, x): + if high >= low: + mid = (low + high)//2 ''' Check if arr[mid] is the first occurrence of x. + arr[mid] is first occurrence if x is one of the following + is true: + (i) mid == 0 and arr[mid] == x + (ii) arr[mid-1] < x and arr[mid] == x''' + + if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x): + return mid + elif x > arr[mid]: + return _binarySearch(arr, (mid + 1), high, x) + else: + return _binarySearch(arr, low, (mid -1), x) + return -1 + '''This function returns true if the x is present more than n / 2 +times in arr[] of size n */''' + +def isMajority(arr, n, x): + ''' Find the index of first occurrence of x in arr[] */''' + + i = _binarySearch(arr, 0, n-1, x) + ''' If element is not present at all, return false*/''' + + if i == -1: + return False + ''' check if the element is present more than n / 2 times */''' + + if ((i + n//2) <= (n -1)) and arr[i + n//2] == x: + return True + else: + return False +" +A Product Array Puzzle,"class ProductArray { +/* Function to print product array +for a given array arr[] of size n */ + + void productArray(int arr[], int n) + { +/* Base case*/ + + if (n == 1) { + System.out.print(""0""); + return; + } + int i, temp = 1; + /* Allocate memory for the product array */ + + int prod[] = new int[n]; + /* Initialize the product array as 1 */ + + for (int j = 0; j < n; j++) + prod[j] = 1; + /* In this loop, temp variable contains product of + elements on left side excluding arr[i] */ + + for (i = 0; i < n; i++) { + prod[i] = temp; + temp *= arr[i]; + } + /* Initialize temp to 1 for product on right side */ + + temp = 1; + /* In this loop, temp variable contains product of + elements on right side excluding arr[i] */ + + for (i = n - 1; i >= 0; i--) { + prod[i] *= temp; + temp *= arr[i]; + } + /* print the constructed prod array */ + + for (i = 0; i < n; i++) + System.out.print(prod[i] + "" ""); + return; + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + ProductArray pa = new ProductArray(); + int arr[] = { 10, 3, 5, 6, 2 }; + int n = arr.length; + System.out.println(""The product array is : ""); + pa.productArray(arr, n); + } +}"," '''Python3 program for A Product Array Puzzle''' + + '''Function to print product array +for a given array arr[] of size n''' + +def productArray(arr, n): + ''' Base case''' + + if n == 1: + print(0) + return + i, temp = 1, 1 + ''' Allocate memory for the product array''' + + prod = [1 for i in range(n)] + ''' Initialize the product array as 1''' + ''' In this loop, temp variable contains product of + elements on left side excluding arr[i]''' + + for i in range(n): + prod[i] = temp + temp *= arr[i] + ''' Initialize temp to 1 for product on right side''' + + temp = 1 + ''' In this loop, temp variable contains product of + elements on right side excluding arr[i]''' + + for i in range(n - 1, -1, -1): + prod[i] *= temp + temp *= arr[i] + ''' Print the constructed prod array''' + + for i in range(n): + print(prod[i], end = "" "") + return + '''Driver Code''' + +arr = [10, 3, 5, 6, 2] +n = len(arr) +print(""The product array is: n"") +productArray(arr, n)" +Egg Dropping Puzzle | DP-11,"/*A Dynamic Programming based Java +Program for the Egg Dropping Puzzle*/ + +class EggDrop { +/* A utility function to get + maximum of two integers*/ + + static int max(int a, int b) + { + return (a > b) ? a : b; + } + /* Function to get minimum number + of trials needed in worst + case with n eggs and k floors */ + + static int eggDrop(int n, int k) + { + /* A 2D table where entry eggFloor[i][j] + will represent minimum number of trials +needed for i eggs and j floors. */ + + int eggFloor[][] = new int[n + 1][k + 1]; + int res; + int i, j, x; +/* We need one trial for one floor and + 0 trials for 0 floors*/ + + for (i = 1; i <= n; i++) { + eggFloor[i][1] = 1; + eggFloor[i][0] = 0; + } +/* We always need j trials for one egg + and j floors.*/ + + for (j = 1; j <= k; j++) + eggFloor[1][j] = j; +/* Fill rest of the entries in table using + optimal substructure property*/ + + for (i = 2; i <= n; i++) { + for (j = 2; j <= k; j++) { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) { + res = 1 + max( + eggFloor[i - 1][x - 1], + eggFloor[i][j - x]); + if (res < eggFloor[i][j]) + eggFloor[i][j] = res; + } + } + } +/* eggFloor[n][k] holds the result*/ + + return eggFloor[n][k]; + } + /* Driver program to test to pront printDups*/ + + public static void main(String args[]) + { + int n = 2, k = 10; + System.out.println(""Minimum number of trials in worst"" + + "" case with "" + + n + "" eggs and "" + + k + "" floors is "" + eggDrop(n, k)); + } +}"," '''A Dynamic Programming based Python Program for the Egg Dropping Puzzle''' + +INT_MAX = 32767 + '''Function to get minimum number of trials needed in worst +case with n eggs and k floors''' + +def eggDrop(n, k): + ''' A 2D table where entry eggFloor[i][j] will represent minimum + number of trials needed for i eggs and j floors.''' + + eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)] + ''' We need one trial for one floor and0 trials for 0 floors''' + + for i in range(1, n + 1): + eggFloor[i][1] = 1 + eggFloor[i][0] = 0 + ''' We always need j trials for one egg and j floors.''' + + for j in range(1, k + 1): + eggFloor[1][j] = j + ''' Fill rest of the entries in table using optimal substructure + property''' + + for i in range(2, n + 1): + for j in range(2, k + 1): + eggFloor[i][j] = INT_MAX + for x in range(1, j + 1): + res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]) + if res < eggFloor[i][j]: + eggFloor[i][j] = res + ''' eggFloor[n][k] holds the result''' + + return eggFloor[n][k] + '''Driver program to test to pront printDups''' + +n = 2 +k = 36 +print(""Minimum number of trials in worst case with"" + str(n) + ""eggs and "" + + str(k) + "" floors is "" + str(eggDrop(n, k)))" +Program to count leaf nodes in a binary tree,"/*Java implementation to find leaf count of a given Binary tree*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +public class BinaryTree +{ +/* Root of the Binary Tree*/ + + Node root; + /* Function to get the count of leaf nodes in a binary tree*/ + + int getLeafCount() + { + return getLeafCount(root); + } + int getLeafCount(Node node) + { + if (node == null) + return 0; + if (node.left == null && node.right == null) + return 1; + else + return getLeafCount(node.left) + getLeafCount(node.right); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + /* create a tree */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + /* get leaf count of the abve tree */ + + System.out.println(""The leaf count of binary tree is : "" + + tree.getLeafCount()); + } +}"," '''Python program to count leaf nodes in Binary Tree''' + + '''A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to get the count of leaf nodes in binary tree''' + +def getLeafCount(node): + if node is None: + return 0 + if(node.left is None and node.right is None): + return 1 + else: + return getLeafCount(node.left) + getLeafCount(node.right) + '''Driver program to test above function''' + + ''' create a tree ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) ''' get leaf count of the abve tree ''' + +print ""Leaf count of the tree is %d"" %(getLeafCount(root))" +Print path from root to a given node in a binary tree,"/*Java implementation to print the path from root +to a given node in a binary tree */ + +import java.util.ArrayList; +public class PrintPath { +/*A node of binary tree */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + this.data=data; + left=right=null; + } +};/* Returns true if there is a path from root + to the given node. It also populates + 'arr' with the given path */ + + public static boolean hasPath(Node root, ArrayList arr, int x) + { +/* if root is NULL + there is no path */ + + if (root==null) + return false; +/* push the node's value in 'arr' */ + + arr.add(root.data); +/* if it is the required node + return true */ + + if (root.data == x) + return true; +/* else check whether the required node lies + in the left subtree or right subtree of + the current node */ + + if (hasPath(root.left, arr, x) || + hasPath(root.right, arr, x)) + return true; +/* required node does not lie either in the + left or right subtree of the current node + Thus, remove current node's value from + 'arr'and then return false */ + + arr.remove(arr.size()-1); + return false; + } +/* function to print the path from root to the + given node if the node lies in the binary tree */ + + public static void printPath(Node root, int x) + { +/* ArrayList to store the path */ + + ArrayList arr=new ArrayList<>(); +/* if required node 'x' is present + then print the path */ + + if (hasPath(root, arr, x)) + { + for (int i=0; i""); + System.out.print(arr.get(arr.size() - 1)); + } +/* 'x' is not present in the binary tree */ + + else + System.out.print(""No Path""); + } +/*Driver program to test above*/ + + public static void main(String args[]) { + +/* binary tree formation*/ + + 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); + int x=5; + printPath(root, x); + } +}"," '''Python3 implementation to print the path from +root to a given node in a binary tree ''' + + '''Helper Class that allocates a new node +with the given data and None left and +right pointers. ''' + +class getNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Returns true if there is a path from +root to the given node. It also +populates 'arr' with the given path ''' + +def hasPath(root, arr, x): + ''' if root is None there is no path ''' + + if (not root): + return False + ''' push the node's value in 'arr' ''' + + arr.append(root.data) + ''' if it is the required node + return true ''' + + if (root.data == x): + return True + ''' else check whether the required node + lies in the left subtree or right + subtree of the current node ''' + + if (hasPath(root.left, arr, x) or + hasPath(root.right, arr, x)): + return True + ''' required node does not lie either in + the left or right subtree of the current + node. Thus, remove current node's value + from 'arr'and then return false ''' + + arr.pop(-1) + return False + '''function to print the path from root to +the given node if the node lies in +the binary tree ''' + +def printPath(root, x): + ''' vector to store the path ''' + + arr = [] + ''' if required node 'x' is present + then print the path ''' + + if (hasPath(root, arr, x)): + for i in range(len(arr) - 1): + print(arr[i], end = ""->"") + print(arr[len(arr) - 1]) + ''' 'x' is not present in the + binary tree ''' + + else: + print(""No Path"") + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree formation ''' + + root = getNode(1) + root.left = getNode(2) + root.right = getNode(3) + root.left.left = getNode(4) + root.left.right = getNode(5) + root.right.left = getNode(6) + root.right.right = getNode(7) + x = 5 + printPath(root, x)" +Largest Independent Set Problem | DP-26,"/*A naive recursive implementation of +Largest Independent Set problem*/ + +class GFG { +/*A utility function to find +max of two integers*/ + +static int max(int x, int y) +{ + return (x > y) ? x : y; +} +/* A binary tree node has data, +pointer to left child and a +pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; +/*The function returns size of the +largest independent set in a given +binary tree*/ + +static int LISS(Node root) +{ + if (root == null) + return 0; +/* Calculate size excluding the current node*/ + + int size_excl = LISS(root.left) + + LISS(root.right); +/* Calculate size including the current node*/ + + int size_incl = 1; + if (root.left!=null) + size_incl += LISS(root.left.left) + + LISS(root.left.right); + if (root.right!=null) + size_incl += LISS(root.right.left) + + LISS(root.right.right); +/* Return the maximum of two sizes*/ + + return max(size_incl, size_excl); +} +/*A utility function to create a node*/ + +static Node newNode( int data ) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver Code*/ + +public static void main(String args[]) { +/* Let us construct the tree + given in the above diagram*/ + + Node root = newNode(20); + root.left = newNode(8); + root.left.left = newNode(4); + root.left.right = newNode(12); + root.left.right.left = newNode(10); + root.left.right.right = newNode(14); + root.right = newNode(22); + root.right.right = newNode(25); + System.out.println(""Size of the Largest"" + + "" Independent Set is "" + + LISS(root)); + } +}"," '''A naive recursive implementation of +Largest Independent Set problem''' + '''A utility function to find +max of two integers''' + +def max(x, y): + if(x > y): + return x + else: + return y + '''A binary tree node has data, +pointer to left child and a +pointer to right child''' + +class node : + def __init__(self): + self.data = 0 + self.left = self.right = None + '''The function returns size of the +largest independent set in a given +binary tree''' + +def LISS(root): + if (root == None) : + return 0 + ''' Calculate size excluding the current node''' + + size_excl = LISS(root.left) + LISS(root.right) + ''' Calculate size including the current node''' + + size_incl = 1 + if (root.left != None): + size_incl += LISS(root.left.left) + \ + LISS(root.left.right) + if (root.right != None): + size_incl += LISS(root.right.left) + \ + LISS(root.right.right) + ''' Return the maximum of two sizes''' + + return max(size_incl, size_excl) + '''A utility function to create a node''' + +def newNode( data ) : + temp = node() + temp.data = data + temp.left = temp.right = None + return temp + '''Driver Code''' + '''Let us construct the tree +given in the above diagram''' + +root = newNode(20) +root.left = newNode(8) +root.left.left = newNode(4) +root.left.right = newNode(12) +root.left.right.left = newNode(10) +root.left.right.right = newNode(14) +root.right = newNode(22) +root.right.right = newNode(25) +print( ""Size of the Largest"" + , "" Independent Set is "" + , LISS(root) )" +Find the sum of last n nodes of the given Linked List,"/*Java implementation to find the sum of last +'n' nodes of the Linked List*/ + + +class GFG +{ + + +/* A Linked list node */ + +static class Node +{ + int data; + Node next; +}; +static Node head; + +/*function to insert a node at the +beginning of the linked list*/ + +static void push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list to the new node */ + + new_node.next = head_ref; + + /* move the head to point to the new node */ + + head_ref = new_node; + head = head_ref; +} + +/*utility function to find the sum of last 'n' nodes*/ + +static int sumOfLastN_NodesUtil(Node head, int n) +{ +/* if n == 0*/ + + if (n <= 0) + return 0; + + int sum = 0, len = 0; + Node temp = head; + +/* calculate the length of the linked list*/ + + while (temp != null) + { + len++; + temp = temp.next; + } + +/* count of first (len - n) nodes*/ + + int c = len - n; + temp = head; + +/* just traverse the 1st 'c' nodes*/ + + while (temp != null&&c-- >0) + { +/* move to next node*/ + + temp = temp.next; + } + +/* now traverse the last 'n' nodes and add them*/ + + while (temp != null) + { + +/* accumulate node's data to sum*/ + + sum += temp.data; + +/* move to next node*/ + + temp = temp.next; + } + +/* required sum*/ + + return sum; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* create linked list 10.6.8.4.12*/ + + push(head, 12); + push(head, 4); + push(head, 8); + push(head, 6); + push(head, 10); + + int n = 2; + System.out.println(""Sum of last "" + n + "" nodes = "" + + sumOfLastN_NodesUtil(head, n)); +} +} + + +"," '''Python3 implementation to find the sum +of last 'n' Nodes of the Linked List''' + + + '''A Linked list Node''' + +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + +head = None + + '''Function to insert a Node at the +beginning of the linked list''' + +def push(head_ref, new_data): + + ''' Allocate Node''' + + new_Node = Node(new_data) + + ''' Put in the data''' + + new_Node.data = new_data + + ''' Link the old list to the new Node''' + + new_Node.next = head_ref + + ''' Move the head to poto the new Node''' + + head_ref = new_Node + head = head_ref + return head + + '''Utility function to find the sum of +last 'n' Nodes''' + +def sumOfLastN_NodesUtil(head, n): + + ''' If n == 0''' + + if (n <= 0): + return 0 + + sum = 0 + len = 0 + temp = head + + ''' Calculate the length of the linked list''' + + while (temp != None): + len += 1 + temp = temp.next + + ''' Count of first (len - n) Nodes''' + + c = len - n + temp = head + + ''' Just traverse the 1st 'c' Nodes''' + + while (temp != None and c > 0): + + ''' Move to next Node''' + + temp = temp.next + c -= 1 + + ''' Now traverse the last 'n' Nodes + and add them''' + + while (temp != None): + + ''' Accumulate Node's data to sum''' + + sum += temp.data + + ''' Move to next Node''' + + temp = temp.next + + ''' Required sum''' + + return sum + + '''Driver code''' + +if __name__ == '__main__': + + ''' Create linked list 10->6->8->4->12''' + + head = push(head, 12) + head = push(head, 4) + head = push(head, 8) + head = push(head, 6) + head = push(head, 10) + + n = 2 + + print(""Sum of last "", n, "" Nodes = "", + sumOfLastN_NodesUtil(head, n)) + + +" +Maximum sum of pairwise product in an array with negative allowed,"/*Java program for above implementation*/ + +import java.io.*; +import java.util.*; + +class GFG { + +static int Mod = 1000000007; + +/*Function to find the maximum sum*/ + +static long findSum(int arr[], int n) { + long sum = 0; + +/* Sort the array first*/ + + Arrays.sort(arr); + +/* First multiply negative numbers + pairwise and sum up from starting + as to get maximum sum.*/ + + int i = 0; + while (i < n && arr[i] < 0) { + if (i != n - 1 && arr[i + 1] <= 0) { + sum = (sum + (arr[i] * arr[i + 1]) % Mod) % Mod; + i += 2; + } + else + break; + } + +/* Second multiply positive numbers + pairwise and summed up from the + last as to get maximum sum.*/ + + int j = n - 1; + while (j >= 0 && arr[j] > 0) { + if (j != 0 && arr[j - 1] > 0) { + sum = (sum + (arr[j] * arr[j - 1]) % Mod) % Mod; + j -= 2; + } else + break; + } + +/* To handle case if positive and negative + numbers both are odd in counts.*/ + + if (j > i) + sum = (sum + (arr[i] * arr[j]) % Mod) % Mod; + +/* If one of them occurs odd times*/ + + else if (i == j) + sum = (sum + arr[i]) % Mod; + + return sum; +} + +/*Drivers code*/ + +public static void main(String args[]) { + int arr[] = {-1, 9, 4, 5, -4, 7}; + int n = arr.length; + System.out.println(findSum(arr, n)); +} +} + + +"," '''Python3 code for above implementation''' + +Mod= 1000000007 + + '''Function to find the maximum sum''' + +def findSum(arr, n): + sum = 0 + + ''' Sort the array first''' + + arr.sort() + + ''' First multiply negative numbers + pairwise and sum up from starting + as to get maximum sum.''' + + i = 0 + while i < n and arr[i] < 0: + if i != n - 1 and arr[i + 1] <= 0: + sum = (sum + (arr[i] * arr[i + 1]) + % Mod) % Mod + i += 2 + else: + break + + ''' Second multiply positive numbers + pairwise and summed up from the + last as to get maximum sum.''' + + j = n - 1 + while j >= 0 and arr[j] > 0: + if j != 0 and arr[j - 1] > 0: + sum = (sum + (arr[j] * arr[j - 1]) + % Mod) % Mod + j -= 2 + else: + break + + ''' To handle case if positive + and negative numbers both + are odd in counts.''' + + if j > i: + sum = (sum + (arr[i] * arr[j]) % Mod)% Mod + + ''' If one of them occurs odd times''' + + elif i == j: + sum = (sum + arr[i]) % Mod + + return sum + + '''Driver code''' + +arr = [ -1, 9, 4, 5, -4, 7 ] +n = len(arr) +print(findSum(arr, n)) + + +" +Delete last occurrence of an item from linked list,"/*Java program to demonstrate deletion of last +Node in singly linked list*/ + +class GFG +{ + +/*A linked list Node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to delete the last occurrence*/ + +static void deleteLast(Node head, int x) +{ + Node temp = head, ptr = null; + while (temp!=null) + { + +/* If found key, update*/ + + if (temp.data == x) + ptr = temp; + temp = temp.next; + } + +/* If the last occurrence is the last node*/ + + if (ptr != null && ptr.next == null) + { + temp = head; + while (temp.next != ptr) + temp = temp.next; + temp.next = null; + } + +/* If it is not the last node*/ + + if (ptr != null && ptr.next != null) + { + ptr.data = ptr.next.data; + temp = ptr.next; + ptr.next = ptr.next.next; + System.gc(); + } +} + +/* Utility function to create a new node with +given key */ + +static Node newNode(int x) +{ + Node node = new Node(); + node.data = x; + node.next = null; + return node; +} + +/*This function prints contents of linked list +starting from the given Node*/ + +static void display(Node head) +{ + Node temp = head; + if (head == null) + { + System.out.print(""null\n""); + return; + } + while (temp != null) + { + System.out.printf(""%d --> "", temp.data); + temp = temp.next; + } + System.out.print(""null\n""); +} + +/* Driver code*/ + +public static void main(String[] args) +{ + 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(4); + head.next.next.next.next.next.next = newNode(4); + System.out.print(""Created Linked list: ""); + display(head); + deleteLast(head, 4); + System.out.print(""List after deletion of 4: ""); + display(head); +} +} + + +"," '''A Python3 program to demonstrate deletion of last +Node in singly linked list''' + + + '''A linked list Node''' + +class Node: + def __init__(self, new_data): + self.data = new_data + self.next = None + + '''Function to delete the last occurrence''' + +def deleteLast(head, x): + + temp = head + ptr = None + while (temp!=None): + + ''' If found key, update''' + + if (temp.data == x) : + ptr = temp + temp = temp.next + + ''' If the last occurrence is the last node''' + + if (ptr != None and ptr.next == None): + temp = head + while (temp.next != ptr) : + temp = temp.next + temp.next = None + + ''' If it is not the last node''' + + if (ptr != None and ptr.next != None): + ptr.data = ptr.next.data + temp = ptr.next + ptr.next = ptr.next.next + + return head + + '''Utility function to create a new node with +given key''' + +def newNode(x): + + node = Node(0) + node.data = x + node.next = None + return node + + '''This function prints contents of linked list +starting from the given Node''' + +def display( head): + + temp = head + if (head == None): + print(""None\n"") + return + + while (temp != None): + print( temp.data,"" -> "",end="""") + temp = temp.next + + print(""None"") + + '''Driver code''' + + +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(4) +head.next.next.next.next.next.next = newNode(4) +print(""Created Linked list: "") +display(head) +head = deleteLast(head, 4) +print(""List after deletion of 4: "") +display(head) + + +" +Boolean Parenthesization Problem | DP-37,"class GFG { +/* Returns count of all possible + parenthesizations that lead to + result true for a boolean + expression with symbols like true + and false and operators like &, | + and ^ filled between symbols*/ + + static int countParenth(char symb[], + char oper[], + int n) + { + int F[][] = new int[n][n]; + int T[][] = new int[n][n]; +/* Fill diaginal entries first + All diagonal entries in T[i][i] + are 1 if symbol[i] is T (true). + Similarly, all F[i][i] entries + are 1 if symbol[i] is F (False)*/ + + for (int i = 0; i < n; i++) { + F[i][i] = (symb[i] == 'F') ? 1 : 0; + T[i][i] = (symb[i] == 'T') ? 1 : 0; + } +/* Now fill T[i][i+1], T[i][i+2], + T[i][i+3]... in order And F[i][i+1], + F[i][i+2], F[i][i+3]... in order*/ + + for (int gap = 1; gap < n; ++gap) + { + for (int i = 0, + j = gap; j < n; + ++i, ++j) + { + T[i][j] = F[i][j] = 0; + for (int g = 0; g < gap; g++) + { +/* Find place of parenthesization + using current value of gap*/ + + int k = i + g; +/* Store Total[i][k] + and Total[k+1][j]*/ + + int tik = T[i][k] + + F[i][k]; + int tkj = T[k + 1][j] + + F[k + 1][j]; +/* Follow the recursive formulas + according to the current operator*/ + + if (oper[k] == '&') + { + T[i][j] += T[i][k] + * T[k + 1][j]; + F[i][j] + += (tik * tkj + - T[i][k] + * T[k + 1][j]); + } + if (oper[k] == '|') + { + F[i][j] += F[i][k] + * F[k + 1][j]; + T[i][j] + += (tik * tkj + - F[i][k] + * F[k + 1][j]); + } + if (oper[k] == '^') + { + T[i][j] += F[i][k] + * T[k + 1][j] + + T[i][k] + * F[k + 1][j]; + F[i][j] += T[i][k] + * T[k + 1][j] + + F[i][k] + * F[k + 1][j]; + } + } + } + } + return T[0][n - 1]; + } +/* Driver code*/ + + public static void main(String[] args) + { + char symbols[] = ""TTFT"".toCharArray(); + char operators[] = ""|&^"".toCharArray(); + int n = symbols.length; +/* There are 4 ways + ((T|T)&(F^T)), (T|(T&(F^T))), + (((T|T)&F)^T) and (T|((T&F)^T))*/ + + System.out.println( + countParenth(symbols, operators, n)); + } +}"," '''Returns count of all possible +parenthesizations that lead to +result true for a boolean +expression with symbols like +true and false and operators +like &, | and ^ filled between symbols''' + +def countParenth(symb, oper, n): + F = [[0 for i in range(n + 1)] + for i in range(n + 1)] + T = [[0 for i in range(n + 1)] + for i in range(n + 1)] + ''' Fill diaginal entries first + All diagonal entries in + T[i][i] are 1 if symbol[i] + is T (true). Similarly, all + F[i][i] entries are 1 if + symbol[i] is F (False)''' + + for i in range(n): + if symb[i] == 'F': + F[i][i] = 1 + else: + F[i][i] = 0 + if symb[i] == 'T': + T[i][i] = 1 + else: + T[i][i] = 0 + ''' Now fill T[i][i+1], T[i][i+2], + T[i][i+3]... in order And + F[i][i+1], F[i][i+2], + F[i][i+3]... in order''' + + for gap in range(1, n): + i = 0 + for j in range(gap, n): + T[i][j] = F[i][j] = 0 + for g in range(gap): + ''' Find place of parenthesization + using current value of gap''' + + k = i + g + ''' Store Total[i][k] and Total[k+1][j]''' + + tik = T[i][k] + F[i][k] + tkj = T[k + 1][j] + F[k + 1][j] + ''' Follow the recursive formulas + according to the current operator''' + + if oper[k] == '&': + T[i][j] += T[i][k] * T[k + 1][j] + F[i][j] += (tik * tkj - T[i][k] * + T[k + 1][j]) + if oper[k] == '|': + F[i][j] += F[i][k] * F[k + 1][j] + T[i][j] += (tik * tkj - F[i][k] * + F[k + 1][j]) + if oper[k] == '^': + T[i][j] += (F[i][k] * T[k + 1][j] + + T[i][k] * F[k + 1][j]) + F[i][j] += (T[i][k] * T[k + 1][j] + + F[i][k] * F[k + 1][j]) + i += 1 + return T[0][n - 1] + '''Driver Code''' + +symbols = ""TTFT"" +operators = ""|&^"" +n = len(symbols) + '''There are 4 ways +((T|T)&(F^T)), (T|(T&(F^T))), +(((T|T)&F)^T) and (T|((T&F)^T))''' + +print(countParenth(symbols, operators, n))" +Path length having maximum number of bends,"/*Java program to find path length +having maximum number of bends*/ + +import java.util.*; +class GFG +{ +/* structure node*/ + + static class Node + { + int key; + Node left; + Node right; + }; +/* Utility function to create a new node*/ + + static Node newNode(int key) + { + Node node = new Node(); + node.left = null; + node.right = null; + node.key = key; + return node; + } + /* Recursive function to calculate the path +length having maximum number of bends. +The following are parameters for this function. +node -. pointer to the current node +dir -. determines whether the current node +is left or right child of it's parent node +bends -. number of bends so far in the +current path. +maxBends -. maximum number of bends in a +path from root to leaf +soFar -. length of the current path so +far traversed +len -. length of the path having maximum +number of bends +*/ + + static int maxBends; + static int len; + static void findMaxBendsUtil(Node node, + char dir, int bends, + int soFar) + { +/* Base Case*/ + + if (node == null) + return; +/* Leaf node*/ + + if (node.left == null && node.right == null) + { + if (bends > maxBends) + { + maxBends = bends; + len = soFar; + } + } +/* Recurring for both left and right child*/ + + else + { + if (dir == 'l') + { + findMaxBendsUtil(node.left, dir, + bends, + soFar + 1); + findMaxBendsUtil(node.right, 'r', + bends + 1, + soFar + 1); + } + else + { + findMaxBendsUtil(node.right, dir, + bends, + soFar + 1); + findMaxBendsUtil(node.left, 'l', + bends + 1, + soFar + 1); + } + } + } +/* Helper function to call findMaxBendsUtil()*/ + + static int findMaxBends(Node node) + { + if (node == null) + return 0; + len = 0; + maxBends = -1; + int bends = 0; +/* Call for left subtree of the root*/ + + if (node.left != null) + findMaxBendsUtil(node.left, 'l', + bends, 1); +/* Call for right subtree of the root*/ + + if (node.right != null) + findMaxBendsUtil(node.right, 'r', bends, + 1); +/* Include the root node as well in the path length*/ + + len++; + return len; + } +/* Driver code*/ + + public static void main(String[] args) + { + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 + \ + 1 + / + 9 + */ + + Node root = newNode(10); + root.left = newNode(8); + root.right = newNode(2); + root.left.left = newNode(3); + root.left.right = newNode(5); + root.right.left = newNode(2); + root.right.left.right = newNode(1); + root.right.left.right.left = newNode(9); + System.out.print(findMaxBends(root) - 1); + } +}"," '''Python3 program to find path Length +having maximum number of bends''' + '''Utility function to create a new node''' + +class newNode: + def __init__(self, key): + self.left = None + self.right = None + self.key = key + '''Recursive function to calculate the path +Length having maximum number of bends. +The following are parameters for this function. +node -. pointer to the current node +Dir -. determines whether the current node +is left or right child of it's parent node +bends -. number of bends so far in the +current path. +maxBends -. maximum number of bends in a +path from root to leaf +soFar -. Length of the current path so +far traversed +Len -. Length of the path having maximum +number of bends''' + +def findMaxBendsUtil(node, Dir, bends, + maxBends, soFar, Len): + ''' Base Case''' + + if (node == None): + return + ''' Leaf node''' + + if (node.left == None and + node.right == None): + if (bends > maxBends[0]): + maxBends[0] = bends + Len[0] = soFar + ''' Having both left and right child''' + + else: + if (Dir == 'l'): + findMaxBendsUtil(node.left, Dir, bends, + maxBends, soFar + 1, Len) + findMaxBendsUtil(node.right, 'r', bends + 1, + maxBends, soFar + 1, Len) + else: + findMaxBendsUtil(node.right, Dir, bends, + maxBends, soFar + 1, Len) + findMaxBendsUtil(node.left, 'l', bends + 1, + maxBends, soFar + 1, Len) + '''Helper function to call findMaxBendsUtil()''' + +def findMaxBends(node): + if (node == None): + return 0 + Len = [0] + bends = 0 + maxBends = [-1] + ''' Call for left subtree of the root''' + + if (node.left): + findMaxBendsUtil(node.left, 'l', bends, + maxBends, 1, Len) + ''' Call for right subtree of the root''' + + if (node.right): + findMaxBendsUtil(node.right, 'r', bends, + maxBends, 1, Len) + ''' Include the root node as well + in the path Length''' + + Len[0] += 1 + return Len[0] + '''Driver code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 + \ + 1 + / + 9''' + + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.left = newNode(2) + root.right.left.right = newNode(1) + root.right.left.right.left = newNode(9) + print(findMaxBends(root) - 1)" +Flattening a Linked List,"/*Java program for flattening a Linked List*/ + +class LinkedList +{ +/*head of list*/ + +Node head; + + /* Linked list Node*/ + + class Node + { + int data; + Node right, down; + Node(int data) + { + this.data = data; + right = null; + down = null; + } + } + +/* An utility function to merge two sorted linked lists*/ + + Node merge(Node a, Node b) + { +/* if first linked list is empty then second + is the answer*/ + + if (a == null) return b; + +/* if second linked list is empty then first + is the result*/ + + if (b == null) return a; + +/* compare the data members of the two linked lists + and put the larger one in the result*/ + + Node result; + + if (a.data < b.data) + { + result = a; + result.down = merge(a.down, b); + } + + else + { + result = b; + result.down = merge(a, b.down); + } + + result.right = null; + return result; + } + + Node flatten(Node root) + { +/* Base Cases*/ + + if (root == null || root.right == null) + return root; + +/* recur for list on right*/ + + root.right = flatten(root.right); + +/* now merge*/ + + root = merge(root, root.right); + +/* return the root + it will be in turn merged with its left*/ + + return root; + } + + /* Utility function to insert a node at beginning of the + linked list */ + + Node push(Node head_ref, int data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(data); + + /* 3. Make next of new Node as head */ + + new_node.down = head_ref; + + /* 4. Move the head to point to new Node */ + + head_ref = new_node; + + /*5. return to link it back */ + + return head_ref; + } + + void printList() + { + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.down; + } + System.out.println(); + } + + /* Driver program to test above functions */ + + public static void main(String args[]) + { + LinkedList L = new LinkedList(); + + /* Let us create the following linked list + 5 -> 10 -> 19 -> 28 + | | | | + V V V V + 7 20 22 35 + | | | + V V V + 8 50 40 + | | + V V + 30 45 + */ + + + L.head = L.push(L.head, 30); + L.head = L.push(L.head, 8); + L.head = L.push(L.head, 7); + L.head = L.push(L.head, 5); + + L.head.right = L.push(L.head.right, 20); + L.head.right = L.push(L.head.right, 10); + + L.head.right.right = L.push(L.head.right.right, 50); + L.head.right.right = L.push(L.head.right.right, 22); + L.head.right.right = L.push(L.head.right.right, 19); + + L.head.right.right.right = L.push(L.head.right.right.right, 45); + L.head.right.right.right = L.push(L.head.right.right.right, 40); + L.head.right.right.right = L.push(L.head.right.right.right, 35); + L.head.right.right.right = L.push(L.head.right.right.right, 20); + +/* flatten the list*/ + + L.head = L.flatten(L.head); + + L.printList(); + } +} +", +Merge an array of size n into another array of size m+n,"/*Java program to Merge an array of +size n into another array of size m + n*/ + +class MergeArrays { + /* Function to move m + elements at the end of array + * mPlusN[] */ + + void moveToEnd(int mPlusN[], int size) + { + int i, j = size - 1; + for (i = size - 1; i >= 0; i--) { + if (mPlusN[i] != -1) { + mPlusN[j] = mPlusN[i]; + j--; + } + } + } + /* Merges array N[] of + size n into array mPlusN[] + of size m+n*/ + + void merge(int mPlusN[], int N[], int m, int n) + { + int i = n; + /* Current index of i/p part of mPlusN[]*/ + + int j = 0; + /* Current index of N[]*/ + + int k = 0; + /* Current index of output mPlusN[]*/ + + while (k < (m + n)) + { + /* Take an element from mPlusN[] if + a) value of the picked element is smaller and we + have not reached end of it b) We have reached + end of N[] */ + + if ((i < (m + n) && mPlusN[i] <= N[j]) + || (j == n)) { + mPlusN[k] = mPlusN[i]; + k++; + i++; + } +/*Otherwise take element from N[]*/ + +else + { + mPlusN[k] = N[j]; + k++; + j++; + } + } + } + /* Utility that prints out an array on a line */ + + void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(""""); + } +/* Driver Code*/ + + public static void main(String[] args) + { + MergeArrays mergearray = new MergeArrays(); + /* Initialize arrays */ + + int mPlusN[] = { 2, 8, -1, -1, -1, 13, -1, 15, 20 }; + int N[] = { 5, 7, 9, 25 }; + int n = N.length; + int m = mPlusN.length - n; + /*Move the m elements at the end of mPlusN*/ + + mergearray.moveToEnd(mPlusN, m + n); + /*Merge N[] into mPlusN[] */ + + mergearray.merge(mPlusN, N, m, n); + /* Print the resultant mPlusN */ + + mergearray.printArray(mPlusN, m + n); + } +}"," '''Python program to Merge an array of +size n into another array of size m + n''' + +NA = -1 + '''Function to move m elements +at the end of array mPlusN[]''' + +def moveToEnd(mPlusN, size): + i = 0 + j = size - 1 + for i in range(size-1, -1, -1): + if (mPlusN[i] != NA): + mPlusN[j] = mPlusN[i] + j -= 1 + '''Merges array N[] +of size n into array mPlusN[] +of size m+n''' + +def merge(mPlusN, N, m, n): + i = n + '''Current index of i/p part of mPlusN[]''' + + j = 0 + + '''Current index of N[]''' + + k = 0 + '''Current index of output mPlusN[]''' + + + while (k < (m+n)): + ''' Take an element from mPlusN[] if + a) value of the picked + element is smaller and we have + not reached end of it + b) We have reached end of N[] */''' + + if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])): + mPlusN[k] = mPlusN[i] + k += 1 + i += 1 + '''Otherwise take element from N[]''' + + else: + mPlusN[k] = N[j] + k += 1 + j += 1 + '''Utility that prints +out an array on a line''' + +def printArray(arr, size): + for i in range(size): + print(arr[i], "" "", end="""") + print() + '''Driver function to +test above functions''' + '''Initialize arrays''' + +mPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20] +N = [5, 7, 9, 25] +n = len(N) +m = len(mPlusN) - n + '''Move the m elements +at the end of mPlusN''' + +moveToEnd(mPlusN, m+n) + '''Merge N[] into mPlusN[]''' + +merge(mPlusN, N, m, n) + '''Print the resultant mPlusN''' + +printArray(mPlusN, m+n)" +Count Primes in Ranges,"/*Java program to answer queries for +count of primes in given range.*/ + +import java.util.*; + +class GFG { + +static final int MAX = 10000; + +/*prefix[i] is going to store count +of primes till i (including i).*/ + +static int prefix[] = new int[MAX + 1]; + +static void buildPrefix() { + +/* Create a boolean array ""prime[0..n]"". A + value in prime[i] will finally be false + if i is Not a prime, else true.*/ + + boolean prime[] = new boolean[MAX + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= MAX; p++) { + +/* If prime[p] is not changed, then + it is a prime*/ + + if (prime[p] == true) { + +/* Update all multiples of p*/ + + for (int i = p * 2; i <= MAX; i += p) + prime[i] = false; + } + } + +/* Build prefix array*/ + + prefix[0] = prefix[1] = 0; + for (int p = 2; p <= MAX; p++) { + prefix[p] = prefix[p - 1]; + if (prime[p]) + prefix[p]++; + } +} + +/*Returns count of primes in range +from L to R (both inclusive).*/ + +static int query(int L, int R) +{ + return prefix[R] - prefix[L - 1]; +} + +/*Driver code*/ + +public static void main(String[] args) { + + buildPrefix(); + int L = 5, R = 10; + System.out.println(query(L, R)); + + L = 1; R = 10; + System.out.println(query(L, R)); +} +} + + +"," '''Python3 program to answer queries for +count of primes in given range.''' + +MAX = 10000 + + '''prefix[i] is going to +store count of primes +till i (including i).''' + +prefix =[0]*(MAX + 1) + +def buildPrefix(): + + ''' Create a boolean array value in + prime[i] will ""prime[0..n]"". A + finally be false if i is Not a + prime, else true.''' + + prime = [1]*(MAX + 1) + + p = 2 + while(p * p <= MAX): + + ''' If prime[p] is not changed, + then it is a prime''' + + if (prime[p] == 1): + + ''' Update all multiples of p''' + + i = p * 2 + while(i <= MAX): + prime[i] = 0 + i += p + p+=1 + + ''' Build prefix array + prefix[0] = prefix[1] = 0;''' + + for p in range(2,MAX+1): + prefix[p] = prefix[p - 1] + if (prime[p]==1): + prefix[p]+=1 + + '''Returns count of primes +in range from L to +R (both inclusive).''' + +def query(L, R): + return prefix[R]-prefix[L - 1] + + '''Driver code''' + +if __name__=='__main__': + buildPrefix() + + L = 5 + R = 10 + print(query(L, R)) + + L = 1 + R = 10 + print(query(L, R)) + + +" +Program to check diagonal matrix and scalar matrix,"/*Program to check matrix is +diagonal matrix or not.*/ + +import java.io.*; +class GFG { + static int N = 4; +/* Function to check matrix + is diagonal matrix + or not.*/ + + static boolean isDiagonalMatrix(int mat[][]) + { + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) +/* condition to check + other elements + except main diagonal + are zero or not.*/ + + if ((i != j) && + (mat[i][j] != 0)) + return false; + return true; + } +/* Driver function*/ + + public static void main(String args[]) + { + int mat[][] = { { 4, 0, 0, 0 }, + { 0, 7, 0, 0 }, + { 0, 0, 5, 0 }, + { 0, 0, 0, 1 } }; + if (isDiagonalMatrix(mat)) + System.out.println(""Yes""); + else + System.out.println(""No"" ); + } +}"," '''Python3 Program to check if matrix +is diagonal matrix or not.''' + +N = 4 + '''Function to check matrix +is diagonal matrix +or not. ''' + +def isDiagonalMatrix(mat) : + for i in range(0, N): + for j in range(0, N) : + ''' condition to check + other elements + except main diagonal + are zero or not.''' + + if ((i != j) and + (mat[i][j] != 0)) : + return False + return True + '''Driver function''' + +mat = [[ 4, 0, 0, 0 ], + [ 0, 7, 0, 0 ], + [ 0, 0, 5, 0 ], + [ 0, 0, 0, 1 ]] +if (isDiagonalMatrix(mat)) : + print(""Yes"") +else : + print(""No"")" +Minimum product subset of an array,"/*Java program to find maximum product of +a subset.*/ + +class GFG { + + static int minProductSubset(int a[], int n) + { + if (n == 1) + return a[0]; + +/* Find count of negative numbers, + count of zeros, maximum valued + negative number, minimum valued + positive number and product of + non-zero numbers*/ + + int negmax = Integer.MIN_VALUE; + int posmin = Integer.MAX_VALUE; + int count_neg = 0, count_zero = 0; + int product = 1; + + for (int i = 0; i < n; i++) { + +/* if number is zero,count it + but dont multiply*/ + + if (a[i] == 0) { + count_zero++; + continue; + } + +/* count the negative numbers + and find the max negative number*/ + + if (a[i] < 0) { + count_neg++; + negmax = Math.max(negmax, a[i]); + } + +/* find the minimum positive number*/ + + if (a[i] > 0 && a[i] < posmin) + posmin = a[i]; + + product *= a[i]; + } + +/* if there are all zeroes + or zero is present but no + negative number is present*/ + + if (count_zero == n + || (count_neg == 0 && count_zero > 0)) + return 0; + +/* If there are all positive*/ + + if (count_neg == 0) + return posmin; + +/* If there are even number except + zero of negative numbers*/ + + if (count_neg % 2 == 0 && count_neg != 0) { + +/* Otherwise result is product of + all non-zeros divided by maximum + valued negative.*/ + + product = product / negmax; + } + + return product; + } + +/* main function*/ + + public static void main(String[] args) + { + + int a[] = { -1, -1, -2, 4, 3 }; + int n = 5; + + System.out.println(minProductSubset(a, n)); + } +} + + +"," '''def to find maximum +product of a subset''' + + + +def minProductSubset(a, n): + if (n == 1): + return a[0] + + ''' Find count of negative numbers, + count of zeros, maximum valued + negative number, minimum valued + positive number and product + of non-zero numbers''' + + max_neg = float('-inf') + min_pos = float('inf') + count_neg = 0 + count_zero = 0 + prod = 1 + for i in range(0, n): + + ''' If number is 0, we don't + multiply it with product.''' + + if (a[i] == 0): + count_zero = count_zero + 1 + continue + + ''' Count negatives and keep + track of maximum valued + negative.''' + + if (a[i] < 0): + count_neg = count_neg + 1 + max_neg = max(max_neg, a[i]) + + ''' Track minimum positive + number of array''' + + if (a[i] > 0): + min_pos = min(min_pos, a[i]) + + prod = prod * a[i] + + ''' If there are all zeros + or no negative number + present''' + + if (count_zero == n or (count_neg == 0 + and count_zero > 0)): + return 0 + + ''' If there are all positive''' + + if (count_neg == 0): + return min_pos + + ''' If there are even number of + negative numbers and count_neg + not 0''' + + if ((count_neg & 1) == 0 and + count_neg != 0): + + ''' Otherwise result is product of + all non-zeros divided by + maximum valued negative.''' + + prod = int(prod / max_neg) + + return prod + + + '''Driver code''' + +a = [-1, -1, -2, 4, 3] +n = len(a) +print(minProductSubset(a, n)) + +" +Count quadruples from four sorted arrays whose sum is equal to a given value x,"/*Java implementation to count quadruples from +four sorted arrays whose sum is equal to a +given value x*/ + +import java.util.*; +class GFG +{ +/*function to count all quadruples from four sorted +arrays whose sum is equal to a given value x*/ + +static int countQuadruples(int arr1[], int arr2[], int arr3[], + int arr4[], int n, int x) +{ + int count = 0; +/* unordered_map 'um' implemented as hash table + for tuples*/ + + Map m = new HashMap<>(); +/* count frequency of each sum obtained from the + pairs of arr1[] and arr2[] and store them in 'um'*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if(m.containsKey(arr1[i] + arr2[j])) + m.put((arr1[i] + arr2[j]), m.get((arr1[i] + arr2[j]))+1); + else + m.put((arr1[i] + arr2[j]), 1); +/* generate pair from arr3[] and arr4[]*/ + + for (int k = 0; k < n; k++) + for (int l = 0; l < n; l++) + { +/* calculate the sum of elements in + the pair so generated*/ + + int p_sum = arr3[k] + arr4[l]; +/* if 'x-p_sum' is present in 'um' then + add frequency of 'x-p_sum' to 'count'*/ + + if (m.containsKey(x - p_sum)) + count += m.get(x - p_sum); + } +/* required count of quadruples*/ + + return count; +} +/*Driver program to test above*/ + +public static void main(String[] args) +{ +/* four sorted arrays each of size 'n'*/ + + int arr1[] = { 1, 4, 5, 6 }; + int arr2[] = { 2, 3, 7, 8 }; + int arr3[] = { 1, 4, 6, 10 }; + int arr4[] = { 2, 4, 7, 8 }; + int n = arr1.length; + int x = 30; + System.out.println(""Count = "" + + countQuadruples(arr1, arr2, arr3, arr4, n, x)); +} +}"," '''Python implementation to count quadruples from +four sorted arrays whose sum is equal to a +given value x''' + '''function to count all quadruples from four sorted +arrays whose sum is equal to a given value x''' + +def countQuadruples(arr1, arr2, arr3, arr4, n, x): + count = 0 + ''' unordered_map 'um' implemented as hash table + for tuples ''' + + m = {} + ''' count frequency of each sum obtained from the + pairs of arr1[] and arr2[] and store them in 'um''' + ''' + for i in range(n): + for j in range(n): + if (arr1[i] + arr2[j]) in m: + m[arr1[i] + arr2[j]] += 1 + else: + m[arr1[i] + arr2[j]] = 1 + ''' generate pair from arr3[] and arr4[]''' + + for k in range(n): + for l in range(n): + ''' calculate the sum of elements in + the pair so generated''' + + p_sum = arr3[k] + arr4[l] + ''' if 'x-p_sum' is present in 'um' then + add frequency of 'x-p_sum' to 'count'''' + if (x - p_sum) in m: + count += m[x - p_sum] + ''' required count of quadruples''' + + return count + '''Driver program to test above''' + '''four sorted arrays each of size n''' +arr1 = [1, 4, 5, 6] +arr2 = [2, 3, 7, 8 ] +arr3 = [1, 4, 6, 10] +arr4 = [2, 4, 7, 8 ] +n = len(arr1) +x = 30 +print(""Count ="", countQuadruples(arr1, arr2, arr3, arr4, n, x))" +Find distance between two nodes in the given Binary tree for Q queries,"/*Java program to find distance +between two nodes using LCA*/ + +import java.io.*; +import java.util.*; + +class GFG{ + +static final int MAX = 1000; +/*log2(MAX)*/ + +static final int log = 10; + +/*Array to store the level +of each node*/ + +static int[] level = new int[MAX]; + +static int[][] lca = new int[MAX][log]; +static int[][] dist = new int[MAX][log]; + +/*Vector to store tree*/ + +@SuppressWarnings(""unchecked"") +static List > graph = new ArrayList(); + +static void addEdge(int u, int v, int cost) +{ + graph.get(u).add(new int[]{ v, cost }); + graph.get(v).add(new int[]{ u, cost }); +} + +/*Pre-Processing to calculate +values of lca[][], dist[][]*/ + +static void dfs(int node, int parent, + int h, int cost) +{ + +/* Using recursion formula to + calculate the values + of lca[][]*/ + + lca[node][0] = parent; + +/* Storing the level of + each node*/ + + level[node] = h; + + if (parent != -1) + { + dist[node][0] = cost; + } + + for(int i = 1; i < log; i++) + { + if (lca[node][i - 1] != -1) + { + +/* Using recursion formula to + calculate the values of + lca[][] and dist[][]*/ + + lca[node][i] = lca[lca[node][i - 1]][i - 1]; + + dist[node][i] = dist[node][i - 1] + + dist[lca[node][i - 1]][i - 1]; + } + } + + for(int[] i : graph.get(node)) + { + if (i[0] == parent) + continue; + + dfs(i[0], node, h + 1, i[1]); + } +} + +/*Function to find the distance +between given nodes u and v*/ + +static void findDistance(int u, int v) +{ + int ans = 0; + +/* The node which is present + farthest from the root node + is taken as v. If u is + farther from root node + then swap the two*/ + + if (level[u] > level[v]) + { + int temp = u; + u = v; + v = temp; + } + +/* Finding the ancestor of v + which is at same level as u*/ + + for(int i = log - 1; i >= 0; i--) + { + if (lca[v][i] != -1 && + level[lca[v][i]] >= level[u]) + { + +/* Adding distance of node + v till its 2^i-th ancestor*/ + + ans += dist[v][i]; + v = lca[v][i]; + } + } + +/* If u is the ancestor of v + then u is the LCA of u and v*/ + + if (v == u) + { + System.out.println(ans); + } + + else + { + +/* Finding the node closest to the + root which is not the common + ancestor of u and v i.e. a node + x such that x is not the common + ancestor of u and v but lca[x][0] is*/ + + for(int i = log - 1; i >= 0; i--) + { + if (lca[v][i] != lca[u][i]) + { + +/* Adding the distance + of v and u to + its 2^i-th ancestor*/ + + ans += dist[u][i] + dist[v][i]; + + v = lca[v][i]; + u = lca[u][i]; + } + } + +/* Adding the distance of u and v + to its first ancestor*/ + + ans += dist[u][0] + dist[v][0]; + + System.out.println(ans); + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + +/* Number of nodes*/ + + int n = 5; + + for(int i = 0; i < MAX; i++) + { + graph.add(new ArrayList()); + } + +/* Add edges with their cost*/ + + addEdge(1, 2, 2); + addEdge(1, 3, 3); + addEdge(2, 4, 5); + addEdge(2, 5, 7); + +/* Initialising lca and dist values + with -1 and 0 respectively*/ + + for(int i = 1; i <= n; i++) + { + for(int j = 0; j < log; j++) + { + lca[i][j] = -1; + dist[i][j] = 0; + } + } + +/* Perform DFS*/ + + dfs(1, -1, 0, 0); + +/* Query 1: {1, 3}*/ + + findDistance(1, 3); + +/* Query 2: {2, 3}*/ + + findDistance(2, 3); + +/* Query 3: {3, 5}*/ + + findDistance(3, 5); +} +} + + +"," '''Python3 Program to find +distance between two nodes +using LCA''' + +MAX = 1000 + + '''lg2(MAX)''' + +lg = 10 + + '''Array to store the level +of each node''' + +level = [0 for i in range(MAX)] + +lca = [[0 for i in range(lg)] + for j in range(MAX)] +dist = [[0 for i in range(lg)] + for j in range(MAX)] + + '''Vector to store tree''' + +graph = [[] for i in range(MAX)] + +def addEdge(u, v, cost): + + global graph + + graph[u].append([v, cost]) + graph[v].append([u, cost]) + + '''Pre-Processing to calculate +values of lca[][], dist[][]''' + +def dfs(node, parent, h, cost): + + ''' Using recursion formula to + calculate the values + of lca[][]''' + + lca[node][0] = parent + + ''' Storing the level of + each node''' + + level[node] = h + + if (parent != -1): + dist[node][0] = cost + + for i in range(1, lg): + if (lca[node][i - 1] != -1): + + ''' Using recursion formula to + calculate the values of + lca[][] and dist[][]''' + + lca[node][i] = lca[lca[node][i - 1]][i - 1] + + dist[node][i] = (dist[node][i - 1] + + dist[lca[node][i - 1]][i - 1]) + + for i in graph[node]: + if (i[0] == parent): + continue + dfs(i[0], node, h + 1, i[1]) + + '''Function to find the distance +between given nodes u and v''' + +def findDistance(u, v): + + ans = 0 + + ''' The node which is present + farthest from the root node + is taken as v. If u is + farther from root node + then swap the two''' + + if (level[u] > level[v]): + temp = u + u = v + v = temp + + ''' Finding the ancestor of v + which is at same level as u''' + + i = lg - 1 + + while(i >= 0): + if (lca[v][i] != -1 and + level[lca[v][i]] >= level[u]): + + ''' Adding distance of node + v till its 2^i-th ancestor''' + + ans += dist[v][i] + v = lca[v][i] + + i -= 1 + + ''' If u is the ancestor of v + then u is the LCA of u and v''' + + if (v == u): + print(ans) + + else: + ''' Finding the node closest to the + root which is not the common + ancestor of u and v i.e. a node + x such that x is not the common + ancestor of u and v but lca[x][0] is''' + + i = lg - 1 + + while(i >= 0): + if (lca[v][i] != lca[u][i]): + ''' Adding the distance + of v and u to + its 2^i-th ancestor''' + + ans += dist[u][i] + dist[v][i] + + v = lca[v][i] + u = lca[u][i] + i -= 1 + + ''' Adding the distance of u and v + to its first ancestor''' + + ans += (dist[u][0] + + dist[v][0]) + + print(ans) + + '''Driver Code''' + +if __name__ == '__main__': + + ''' Number of nodes''' + + n = 5 + + ''' Add edges with their cost''' + + addEdge(1, 2, 2) + addEdge(1, 3, 3) + addEdge(2, 4, 5) + addEdge(2, 5, 7) + + ''' Initialising lca and dist values + with -1 and 0 respectively''' + + for i in range(1, n + 1): + for j in range(lg): + lca[i][j] = -1 + dist[i][j] = 0 + + ''' Perform DFS''' + + dfs(1, -1, 0, 0) + ''' Query 1: {1, 3}''' + + findDistance(1, 3) + ''' Query 2: {2, 3}''' + + findDistance(2, 3) + ''' Query 3: {3, 5}''' + + findDistance(3, 5) + + +" +Count half nodes in a Binary tree (Iterative and Recursive),"/*Java program to count half nodes in a Binary Tree +using Iterative approach*/ + +import java.util.Queue; +import java.util.LinkedList; +/*Class to represent Tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = null; + right = null; + } +} +/*Class to count half nodes of Tree*/ + +class BinaryTree +{ + Node root; + /* Function to get the count of half Nodes in + a binary tree*/ + + int gethalfCount() + { +/* If tree is empty*/ + + if (root==null) + return 0; +/* Do level order traversal starting from root*/ + + Queue queue = new LinkedList(); + queue.add(root); +/*Initialize count of half nodes*/ + +int count=0; + while (!queue.isEmpty()) + { + Node temp = queue.poll(); + if (temp.left!=null && temp.right==null || + temp.left==null && temp.right!=null) + count++; +/* Enqueue left child*/ + + if (temp.left != null) + queue.add(temp.left); +/* Enqueue right child*/ + + if (temp.right != null) + queue.add(temp.right); + } + return count; + } + + /*Driver Program to test above function */ + public static void main(String args[]) + { + BinaryTree tree_level = new BinaryTree(); + tree_level.root = new Node(2); + tree_level.root.left = new Node(7); + tree_level.root.right = new Node(5); + tree_level.root.left.right = new Node(6); + tree_level.root.left.right.left = new Node(1); + tree_level.root.left.right.right = new Node(11); + tree_level.root.right.right = new Node(9); + tree_level.root.right.right.left = new Node(4); + System.out.println(tree_level.gethalfCount()); + } +}"," '''Python program to count +half nodes in a Binary Tree +using iterative approach''' + + '''A node structure''' + +class Node: + def __init__(self ,key): + self.data = key + self.left = None + self.right = None + '''Iterative Method to count half nodes of binary tree''' + +def gethalfCount(root): + ''' Base Case''' + + if root is None: + return 0 + ''' Create an empty queue for level order traversal''' + + queue = [] + queue.append(root) '''initialize count for half nodes''' + + count = 0 + while(len(queue) > 0): + node = queue.pop(0) + if node.left is not None and node.right is None or node.left is None and node.right is not None: + count = count+1 ''' Enqueue left child''' + + if node.left is not None: + queue.append(node.left) + ''' Enqueue right child''' + + if node.right is not None: + queue.append(node.right) + return count + '''Driver Program to test above function''' + +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) +print ""%d"" %(gethalfCount(root))" +"Find the first, second and third minimum elements in an array","/*Java program to find the first, second +and third minimum element in an array*/ + +import java.util.*; + +public class GFG +{ + static void Print3Smallest(int array[], int n) + { + int firstmin = Integer.MAX_VALUE; + int secmin = Integer.MAX_VALUE; + int thirdmin = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) + { + /* Check if current element is less than + firstmin, then update first, second and + third */ + + if (array[i] < firstmin) + { + thirdmin = secmin; + secmin = firstmin; + firstmin = array[i]; + } + + /* Check if current element is less than + secmin then update second and third */ + + else if (array[i] < secmin) + { + thirdmin = secmin; + secmin = array[i]; + } + + /* Check if current element is less than + then update third */ + + else if (array[i] < thirdmin) + thirdmin = array[i]; + } + + System.out.println(""First min = "" + firstmin ); + System.out.println(""Second min = "" + secmin ); + System.out.println(""Third min = "" + thirdmin ); + } + +/* Driver code*/ + + public static void main(String[] args) + { + int array[] = {4, 9, 1, 32, 12}; + int n = array.length; + Print3Smallest(array, n); + } + +} + + +"," '''A Python program to find the first, +second and third minimum element +in an array''' + + +MAX = 100000 + +def Print3Smallest(arr, n): + firstmin = MAX + secmin = MAX + thirdmin = MAX + + for i in range(0, n): + + ''' Check if current element + is less than firstmin, + then update first,second + and third''' + + + if arr[i] < firstmin: + thirdmin = secmin + secmin = firstmin + firstmin = arr[i] + + ''' Check if current element is + less than secmin then update + second and third''' + + elif arr[i] < secmin: + thirdmin = secmin + secmin = arr[i] + + ''' Check if current element is + less than,then upadte third''' + + elif arr[i] < thirdmin: + thirdmin = arr[i] + + print(""First min = "", firstmin) + print(""Second min = "", secmin) + print(""Third min = "", thirdmin) + + + '''driver program''' + +arr = [4, 9, 1, 32, 12] +n = len(arr) +Print3Smallest(arr, n) + + +" +Foldable Binary Trees,"/*Java program to check foldable binary tree*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; + /* Returns true if the given tree can be folded */ + + boolean IsFoldable(Node node) + { + if (node == null) + return true; + return IsFoldableUtil(node.left, node.right); + } + /* A utility function that checks if trees with roots as + n1 and n2 are mirror of each other */ + + boolean IsFoldableUtil(Node n1, Node n2) + { + /* If both left and right subtrees are NULL, + then return true */ + + if (n1 == null && n2 == null) + return true; + /* If one of the trees is NULL and other is not, + then return false */ + + if (n1 == null || n2 == null) + return false; + /* Otherwise check if left and right subtrees are + mirrors of their counterparts */ + + return IsFoldableUtil(n1.left, n2.right) + && IsFoldableUtil(n1.right, n2.left); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* The constructed binary tree is + 1 + / \ + 2 3 + \ / + 4 5 + */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.right.left = new Node(4); + tree.root.left.right = new Node(5); + if (tree.IsFoldable(tree.root)) + System.out.println(""tree is foldable""); + else + System.out.println(""Tree is not foldable""); + } +}"," '''Python3 program to check +foldable binary tree''' + + '''Utility function to create a new +tree node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Returns true if the given tree can be folded''' + +def IsFoldable(root): + if (root == None): + return True + return IsFoldableUtil(root.left, root.right) + '''A utility function that checks +if trees with roots as n1 and n2 +are mirror of each other''' + +def IsFoldableUtil(n1, n2): + ''' If both left and right subtrees are NULL, + then return true''' + + if n1 == None and n2 == None: + return True + ''' If one of the trees is NULL and other is not, + then return false''' + + if n1 == None or n2 == None: + return False + ''' Otherwise check if left and + right subtrees are mirrors of + their counterparts''' + + d1 = IsFoldableUtil(n1.left, n2.right) + d2 = IsFoldableUtil(n1.right, n2.left) + return d1 and d2 + '''Driver code''' + +if __name__ == ""__main__"": + ''' The constructed binary tree is + 1 + / \ + 2 3 + \ / + 4 5 + ''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.right = newNode(4) + root.right.left = newNode(5) + if IsFoldable(root): + print(""Tree is foldable"") + else: + print(""Tree is not foldable"")" +Maximum distance between two occurrences of same element in array,"/*Java program to find maximum distance between two +same occurrences of a number.*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Function to find maximum distance between equal elements*/ + + static int maxDistance(int[] arr, int n) + { +/* Used to store element to first index mapping*/ + + HashMap map = new HashMap<>(); +/* Traverse elements and find maximum distance between + same occurrences with the help of map.*/ + + int max_dist = 0; + for (int i = 0; i < n; i++) + { +/* If this is first occurrence of element, insert its + index in map*/ + + if (!map.containsKey(arr[i])) + map.put(arr[i], i); +/* Else update max distance*/ + + else + max_dist = Math.max(max_dist, i - map.get(arr[i])); + } + return max_dist; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int[] arr = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; + int n = arr.length; + System.out.println(maxDistance(arr, n)); +} +}"," '''Python program to find maximum distance between two +same occurrences of a number.''' + + '''Function to find maximum distance between equal elements''' + +def maxDistance(arr, n): ''' Used to store element to first index mapping''' + + mp = {} + ''' Traverse elements and find maximum distance between + same occurrences with the help of map.''' + + maxDict = 0 + for i in range(n): + ''' If this is first occurrence of element, insert its + index in map''' + + if arr[i] not in mp.keys(): + mp[arr[i]] = i + ''' Else update max distance''' + + else: + maxDict = max(maxDict, i-mp[arr[i]]) + return maxDict + '''Driver Program''' + +if __name__=='__main__': + arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] + n = len(arr) + print maxDistance(arr, n) +" +Non-recursive program to delete an entire binary tree,"/* Non-recursive program to delete the entire binary tree */ + +import java.util.*; +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Non-recursive function to delete an entire binary tree. */ + + void _deleteTree() + { +/* Base Case*/ + + if (root == null) + return; +/* Create an empty queue for level order traversal*/ + + Queue q = new LinkedList(); +/* Do level order traversal starting from root*/ + + q.add(root); + while (!q.isEmpty()) + { + Node node = q.peek(); + q.poll(); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + } + } + /* Deletes a tree and sets the root as NULL */ + + void deleteTree() + { + _deleteTree(); + root = null; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { +/* create a binary tree*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(15); + tree.root.left = new Node(10); + tree.root.right = new Node(20); + tree.root.left.left = new Node(8); + tree.root.left.right = new Node(12); + tree.root.right.left = new Node(16); + tree.root.right.right = new Node(25); +/* delete entire binary tree*/ + + tree.deleteTree(); + } +}"," '''Python program to delete an entire binary tree +using non-recursive approach''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Non-recursive function to delete an entrie binary tree''' + +def _deleteTree(root): + ''' Base Case''' + + if root is None: + return + ''' Create a empty queue for level order traversal''' + + q = [] + ''' Do level order traversal starting from root''' + + q.append(root) + while(len(q)>0): + node = q.pop(0) + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + node = None + return node + '''Deletes a tree and sets the root as None''' + +def deleteTree(node_ref): + node_ref = _deleteTree(node_ref) + return node_ref + '''Driver program to test above function''' + + '''Create a binary tree''' + +root = Node(15) +root.left = Node(10) +root.right = Node(20) +root.left.left = Node(8) +root.left.right = Node(12) +root.right.left = Node(16) +root.right.right = Node(25) '''delete entire binary tree''' + +root = deleteTree(root)" +Lowest Common Ancestor of the deepest leaves of a Binary Tree,"/*Java program for the above approach*/ + + +/*Node of a Binary Tree*/ + +class Node +{ + Node left = null; + Node right = null; + int data; + + Node(int data) + { + this.data = data; + } +} + +class GFG{ + +/*Function to find the depth +of the Binary Tree*/ + +public static int findDepth(Node root) +{ + +/* If root is not null*/ + + if (root == null) + return 0; + +/* Left recursive subtree*/ + + int left = findDepth(root.left); + +/* Right recursive subtree*/ + + int right = findDepth(root.right); + +/* Returns the maximum depth*/ + + return 1 + Math.max(left, right); +} + +/*Function to perform the depth +first search on the binary tree*/ + +public static Node DFS(Node root, int curr, + int depth) +{ + +/* If root is null*/ + + if (root == null) + return null; + +/* If curr is equal to depth*/ + + if (curr == depth) + return root; + +/* Left recursive subtree*/ + + Node left = DFS(root.left, curr + 1, depth); + +/* Right recursive subtree*/ + + Node right = DFS(root.right, curr + 1, depth); + +/* If left and right are not null*/ + + if (left != null && right != null) + return root; + +/* Return left, if left is not null + Otherwise return right*/ + + return (left != null) ? left : right; +} + +/*Function to find the LCA of the +deepest nodes of the binary tree*/ + +public static Node lcaOfDeepestLeaves(Node root) +{ + +/* If root is null*/ + + if (root == null) + return null; + +/* Stores the deepest depth + of the binary tree*/ + + int depth = findDepth(root) - 1; + +/* Return the LCA of the + nodes at level depth*/ + + return DFS(root, 0, depth); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* Given Binary Tree*/ + + 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.right.left.left = new Node(8); + root.right.left.right = new Node(9); + + System.out.println(lcaOfDeepestLeaves(root).data); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Node of a Binary Tree''' + +class Node: + def __init__(self, d): + self.data = d + self.left = None + self.right = None + + '''Function to find the depth +of the Binary Tree''' + +def finddepth(root): + ''' If root is not null''' + + if (not root): + return 0 + + ''' Left recursive subtree''' + + left = finddepth(root.left) + + ''' Right recursive subtree''' + + right = finddepth(root.right) + + ''' Returns the maximum depth''' + + return 1 + max(left, right) + + '''Function to perform the depth +first search on the binary tree''' + +def dfs(root, curr, depth): + ''' If root is null''' + + if (not root): + return None + + ''' If curr is equal to depth''' + + if (curr == depth): + return root + + ''' Left recursive subtree''' + + left = dfs(root.left, curr + 1, depth) + + ''' Right recursive subtree''' + + right = dfs(root.right, curr + 1, depth) + + ''' If left and right are not null''' + + if (left != None and right != None): + return root + + ''' Return left, if left is not null + Otherwise return right''' + + return left if left else right + + '''Function to find the LCA of the +deepest nodes of the binary tree''' + +def lcaOfDeepestLeaves(root): + + ''' If root is null''' + + if (not root): + return None + + ''' Stores the deepest depth + of the binary tree''' + + depth = finddepth(root) - 1 + + ''' Return the LCA of the + nodes at level depth''' + + return dfs(root, 0, depth) + + '''Driver Code''' + +if __name__ == '__main__': + + ''' Given Binary Tree''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.right.left.left = Node(8) + root.right.left.right = Node(9) + + print(lcaOfDeepestLeaves(root).data) + + +" +Compute sum of digits in all numbers from 1 to n,"/*A Simple JAVA program to compute sum of +digits in numbers from 1 to n*/ + +import java.io.*; +class GFG { +/* Returns sum of all digits in numbers + from 1 to n*/ + + static int sumOfDigitsFrom1ToN(int n) + { +/*initialize result*/ + +int result = 0; +/* One by one compute sum of digits + in every number from 1 to n*/ + + for (int x = 1; x <= n; x++) + result += sumOfDigits(x); + return result; + } +/* A utility function to compute sum + of digits in a given number x*/ + + static int sumOfDigits(int x) + { + int sum = 0; + while (x != 0) + { + sum += x % 10; + x = x / 10; + } + return sum; + } +/* Driver Program*/ + + public static void main(String args[]) + { + int n = 328; + System.out.println(""Sum of digits in numbers"" + +"" from 1 to "" + n + "" is "" + + sumOfDigitsFrom1ToN(n)); + } +}"," '''A Simple Python program to compute sum +of digits in numbers from 1 to n''' + + '''Returns sum of all digits in numbers +from 1 to n''' + +def sumOfDigitsFrom1ToN(n) : '''initialize result''' + + result = 0 + ''' One by one compute sum of digits + in every number from 1 to n''' + + for x in range(1, n+1) : + result = result + sumOfDigits(x) + return result + '''A utility function to compute sum of +digits in a given number x''' + +def sumOfDigits(x) : + sum = 0 + while (x != 0) : + sum = sum + x % 10 + x = x // 10 + return sum + '''Driver Program''' + +n = 328 +print(""Sum of digits in numbers from 1 to"", n, ""is"", sumOfDigitsFrom1ToN(n))" +Lexicographic rank of a string,"/*Java program to find lexicographic rank +of a string*/ + +import java.io.*; +import java.util.*; +class GFG { +/* A utility function to find factorial of n*/ + + static int fact(int n) + { + return (n <= 1) ? 1 : n * fact(n - 1); + } +/* A utility function to count smaller + characters on right of arr[low]*/ + + static int findSmallerInRight(String str, int low, + int high) + { + int countRight = 0, i; + for (i = low + 1; i <= high; ++i) + if (str.charAt(i) < str.charAt(low)) + ++countRight; + return countRight; + } +/* A function to find rank of a string in + all permutations of characters*/ + + static int findRank(String str) + { + int len = str.length(); + int mul = fact(len); + int rank = 1; + int countRight; + for (int i = 0; i < len; ++i) { + mul /= len - i; +/* count number of chars smaller + than str[i] from str[i+1] to + str[len-1]*/ + + countRight = findSmallerInRight(str, i, len - 1); + rank += countRight * mul; + } + return rank; + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + String str = ""string""; + System.out.println(findRank(str)); + } +}"," '''Python program to find lexicographic +rank of a string''' + + '''A utility function to find factorial +of n''' + +def fact(n) : + f = 1 + while n >= 1 : + f = f * n + n = n - 1 + return f '''A utility function to count smaller +characters on right of arr[low]''' + +def findSmallerInRight(st, low, high) : + countRight = 0 + i = low + 1 + while i <= high : + if st[i] < st[low] : + countRight = countRight + 1 + i = i + 1 + return countRight + '''A function to find rank of a string +in all permutations of characters''' + +def findRank (st) : + ln = len(st) + mul = fact(ln) + rank = 1 + i = 0 + while i < ln : + mul = mul / (ln - i) + ''' count number of chars smaller + than str[i] fron str[i + 1] to + str[len-1]''' + + countRight = findSmallerInRight(st, i, ln-1) + rank = rank + countRight * mul + i = i + 1 + return rank + '''Driver program to test above function''' + +st = ""string"" +print (findRank(st))" +Lowest Common Ancestor in a Binary Search Tree.,"/*Recursive Java program to print lca of two nodes +A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Function to find LCA of n1 and n2. The function assumes that both + n1 and n2 are present in BST */ + + Node lca(Node node, int n1, int n2) + { + if (node == null) + return null; +/* If both n1 and n2 are smaller than root, then LCA lies in left*/ + + if (node.data > n1 && node.data > n2) + return lca(node.left, n1, n2); +/* If both n1 and n2 are greater than root, then LCA lies in right*/ + + if (node.data < n1 && node.data < n2) + return lca(node.right, n1, n2); + return node; + } + /* Driver program to test lca() */ + + public static void main(String args[]) + { +/* Let us construct the BST shown in the above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(8); + tree.root.right = new Node(22); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(12); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(14); + int n1 = 10, n2 = 14; + Node t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + n1 = 14; + n2 = 8; + t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + n1 = 10; + n2 = 22; + t = tree.lca(tree.root, n1, n2); + System.out.println(""LCA of "" + n1 + "" and "" + n2 + "" is "" + t.data); + } +}"," '''A recursive python program to find LCA of two nodes +n1 and n2 +A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to find LCA of n1 and n2. The function assumes +that both n1 and n2 are present in BST''' + +def lca(root, n1, n2): + if root is None: + return None ''' If both n1 and n2 are smaller than root, then LCA + lies in left''' + + if(root.data > n1 and root.data > n2): + return lca(root.left, n1, n2) + ''' If both n1 and n2 are greater than root, then LCA + lies in right ''' + + if(root.data < n1 and root.data < n2): + return lca(root.right, n1, n2) + return root + '''Driver program to test above function''' '''Let us construct the BST shown in the figure''' + +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) +n1 = 10 ; n2 = 14 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2, t.data) +n1 = 14 ; n2 = 8 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2 , t.data) +n1 = 10 ; n2 = 22 +t = lca(root, n1, n2) +print ""LCA of %d and %d is %d"" %(n1, n2, t.data)" +"Multiply two integers without using multiplication, division and bitwise operators, and no loops","class GFG { + /* function to multiply two numbers x and y*/ + + static int multiply(int x, int y) { + /* 0 multiplied with anything gives 0 */ + + if (y == 0) + return 0; + /* Add x one by one */ + + if (y > 0) + return (x + multiply(x, y - 1)); + /* the case where y is negative */ + + if (y < 0) + return -multiply(x, -y); + return -1; + } +/* Driver code*/ + + public static void main(String[] args) { + System.out.print(""\n"" + multiply(5, -11)); + } +}"," '''Function to multiply two numbers +x and y''' + +def multiply(x,y): + ''' 0 multiplied with anything + gives 0''' + + if(y == 0): + return 0 + ''' Add x one by one''' + + if(y > 0 ): + return (x + multiply(x, y - 1)) + ''' The case where y is negative''' + + if(y < 0 ): + return -multiply(x, -y) + '''Driver code''' + +print(multiply(5, -11))" +Check if array elements are consecutive | Added Method 3,"class AreConsecutive +{ + /* The function checks if the array elements are consecutive + If elements are consecutive, then returns true, else returns + false */ + + boolean areConsecutive(int arr[], int n) + { + if (n < 1) + return false; + /* 1) Get the minimum element in array */ + + int min = getMin(arr, n); + /* 2) Get the maximum element in array */ + + int max = getMax(arr, n); + /* 3) max - min + 1 is equal to n, then only check all elements */ + + if (max - min + 1 == n) + { + /* Create a temp array to hold visited flag of all elements. + Note that, calloc is used here so that all values are initialized + as false */ + + boolean visited[] = new boolean[n]; + int i; + for (i = 0; i < n; i++) + { + /* If we see an element again, then return false */ + + if (visited[arr[i] - min] != false) + return false; + /* If visited first time, then mark the element as visited */ + + visited[arr[i] - min] = true; + } + /* If all elements occur once, then return true */ + + return true; + } +/*if (max - min + 1 != n)*/ + +return false; + } + /* UTILITY FUNCTIONS */ + + int getMin(int arr[], int n) + { + int min = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + } + return min; + } + int getMax(int arr[], int n) + { + int max = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] > max) + max = arr[i]; + } + return max; + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + AreConsecutive consecutive = new AreConsecutive(); + int arr[] = {5, 4, 2, 3, 1, 6}; + int n = arr.length; + if (consecutive.areConsecutive(arr, n) == true) + System.out.println(""Array elements are consecutive""); + else + System.out.println(""Array elements are not consecutive""); + } +}"," '''Helper functions to get Minimum and +Maximum in an array''' + '''The function checks if the array elements +are consecutive. If elements are consecutive, +then returns true, else returns false''' + +def areConsecutive(arr, n): + if ( n < 1 ): + return False + ''' 1) Get the Minimum element in array */''' + + Min = min(arr) + ''' 2) Get the Maximum element in array */''' + + Max = max(arr) + ''' 3) Max - Min + 1 is equal to n, + then only check all elements */''' + + if (Max - Min + 1 == n): + ''' Create a temp array to hold visited + flag of all elements. Note that, calloc + is used here so that all values are + initialized as false''' + + visited = [False for i in range(n)] + for i in range(n): + ''' If we see an element again, + then return false */''' + + if (visited[arr[i] - Min] != False): + return False + ''' If visited first time, then mark + the element as visited */''' + + visited[arr[i] - Min] = True + ''' If all elements occur once, + then return true */''' + + return True + '''if (Max - Min + 1 != n)''' + + return False + '''Driver Code''' + +arr = [5, 4, 2, 3, 1, 6] +n = len(arr) +if(areConsecutive(arr, n) == True): + print(""Array elements are consecutive "") +else: + print(""Array elements are not consecutive "")" +Sudoku | Backtracking-7,"/*Java program for above approach*/ + +public class Suduko { +/* N is the size of the 2D matrix N*N*/ + + static int N = 9; + /* A utility function to print grid */ + + static void print(int[][] grid) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + System.out.print(grid[i][j] + "" ""); + System.out.println(); + } + } +/* Check whether it will be legal + to assign num to the + given row, col*/ + + static boolean isSafe(int[][] grid, int row, int col, + int num) + { +/* Check if we find the same num + in the similar row , we + return false*/ + + for (int x = 0; x <= 8; x++) + if (grid[row][x] == num) + return false; +/* Check if we find the same num + in the similar column , + we return false*/ + + for (int x = 0; x <= 8; x++) + if (grid[x][col] == num) + return false; +/* Check if we find the same num + in the particular 3*3 + matrix, we return false*/ + + int startRow = row - row % 3, startCol + = col - col % 3; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + if (grid[i + startRow][j + startCol] == num) + return false; + return true; + } +/* Takes a partially filled-in grid and attempts + to assign values to all unassigned locations in + such a way to meet the requirements for + Sudoku solution (non-duplication across rows, + columns, and boxes) */ + + static boolean solveSuduko(int grid[][], int row, + int col) + { + /*if we have reached the 8th + row and 9th column (0 + indexed matrix) , + we are returning true to avoid further + backtracking */ + + if (row == N - 1 && col == N) + return true; +/* Check if column value becomes 9 , + we move to next row + and column start from 0*/ + + if (col == N) { + row++; + col = 0; + } +/* Check if the current position + of the grid already + contains value >0, we iterate + for next column*/ + + if (grid[row][col] != 0) + return solveSuduko(grid, row, col + 1); + for (int num = 1; num < 10; num++) { +/* Check if it is safe to place + the num (1-9) in the + given row ,col ->we move to next column*/ + + if (isSafe(grid, row, col, num)) { + /* assigning the num in the current + (row,col) position of the grid and + assuming our assined num in the position + is correct */ + + grid[row][col] = num; +/* Checking for next + possibility with next column*/ + + if (solveSuduko(grid, row, col + 1)) + return true; + } + /* removing the assigned num , since our + assumption was wrong , and we go for next + assumption with diff num value */ + + grid[row][col] = 0; + } + return false; + } + /* Driver Code*/ + + public static void main(String[] args) + { + int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, + { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, + { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, + { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, + { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, + { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; + if (solveSuduko(grid, 0, 0)) + print(grid); + else + System.out.println(""No Solution exists""); + } + +}"," '''''' '''N is the size of the 2D matrix N*N''' + +N = 9 + '''A utility function to print grid''' + +def printing(arr): + for i in range(N): + for j in range(N): + print(arr[i][j], end = "" "") + print() + '''Checks whether it will be +legal to assign num to the +given row, col''' + +def isSafe(grid, row, col, num): + ''' Check if we find the same num + in the similar row , we + return false''' + + for x in range(9): + if grid[row][x] == num: + return False + ''' Check if we find the same num in + the similar column , we + return false''' + + for x in range(9): + if grid[x][col] == num: + return False + ''' Check if we find the same num in + the particular 3*3 matrix, + we return false''' + + startRow = row - row % 3 + startCol = col - col % 3 + for i in range(3): + for j in range(3): + if grid[i + startRow][j + startCol] == num: + return False + return True + '''Takes a partially filled-in grid and attempts +to assign values to all unassigned locations in +such a way to meet the requirements for +Sudoku solution (non-duplication across rows, +columns, and boxes) */''' + +def solveSuduko(grid, row, col): + ''' Check if we have reached the 8th + row and 9th column (0 + indexed matrix) , we are + returning true to avoid + further backtracking''' + + if (row == N - 1 and col == N): + return True + ''' Check if column value becomes 9 , + we move to next row and + column start from 0''' + + if col == N: + row += 1 + col = 0 + ''' Check if the current position of + the grid already contains + value >0, we iterate for next column''' + + if grid[row][col] > 0: + return solveSuduko(grid, row, col + 1) + for num in range(1, N + 1, 1): + ''' Check if it is safe to place + the num (1-9) in the + given row ,col ->we + move to next column''' + + if isSafe(grid, row, col, num): + ''' Assigning the num in + the current (row,col) + position of the grid + and assuming our assined + num in the position + is correct''' + + grid[row][col] = num + ''' Checking for next possibility with next + column''' + + if solveSuduko(grid, row, col + 1): + return True + ''' Removing the assigned num , + since our assumption + was wrong , and we go for + next assumption with + diff num value''' + + grid[row][col] = 0 + return False + '''Driver Code +0 means unassigned cells''' + +grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0], + [5, 2, 0, 0, 0, 0, 0, 0, 0], + [0, 8, 7, 0, 0, 0, 0, 3, 1], + [0, 0, 3, 0, 1, 0, 0, 8, 0], + [9, 0, 0, 8, 6, 3, 0, 0, 5], + [0, 5, 0, 0, 9, 0, 6, 0, 0], + [1, 3, 0, 0, 0, 0, 2, 5, 0], + [0, 0, 0, 0, 0, 0, 0, 7, 4], + [0, 0, 5, 2, 0, 6, 3, 0, 0]] +if (solveSuduko(grid, 0, 0)): + printing(grid) +else: + print(""no solution exists "")" +Count Inversions of size three in a given array,"/*A O(n^2) Java program to count inversions of size 3*/ + + +class Inversion { + +/* returns count of inversion of size 3*/ + + int getInvCount(int arr[], int n) + { +/*initialize result*/ + +int invcount = 0; + + for (int i=0 ; i< n-1; i++) + { +/* count all smaller elements on right of arr[i]*/ + + int small=0; + for (int j=i+1; j arr[j]) + small++; + +/* count all greater elements on left of arr[i]*/ + + int great = 0; + for (int j=i-1; j>=0; j--) + if (arr[i] < arr[j]) + great++; + +/* update inversion count by adding all inversions + that have arr[i] as middle of three elements*/ + + invcount += great*small; + } + return invcount; + } +/* driver program to test above function*/ + + public static void main(String args[]) + { + Inversion inversion = new Inversion(); + int arr[] = new int[] {8, 4, 2, 1}; + int n = arr.length; + System.out.print(""Inversion count : "" + + inversion.getInvCount(arr, n)); + } +} + + +"," '''A O(n^2) Python3 program to + count inversions of size 3''' + + + '''Returns count of inversions +of size 3''' + +def getInvCount(arr, n): + + ''' Initialize result''' + + invcount = 0 + + for i in range(1,n-1): + + ''' Count all smaller elements + on right of arr[i]''' + + small = 0 + for j in range(i+1 ,n): + if (arr[i] > arr[j]): + small+=1 + + ''' Count all greater elements + on left of arr[i]''' + + great = 0; + for j in range(i-1,-1,-1): + if (arr[i] < arr[j]): + great+=1 + + ''' Update inversion count by + adding all inversions that + have arr[i] as middle of + three elements''' + + invcount += great * small + + return invcount + + '''Driver program to test above function''' + +arr = [8, 4, 2, 1] +n = len(arr) +print(""Inversion Count :"",getInvCount(arr, n)) + +" +Cycle Sort,"/*Java program to implement cycle sort*/ + +import java.util.*; +import java.lang.*; +class GFG { +/* Function sort the array using Cycle sort*/ + + public static void cycleSort(int arr[], int n) + { +/* count number of memory writes*/ + + int writes = 0; +/* traverse array elements and put it to on + the right place*/ + + for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { +/* initialize item as starting point*/ + + int item = arr[cycle_start]; +/* Find position where we put the item. We basically + count all smaller elements on right side of item.*/ + + int pos = cycle_start; + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos++; +/* If item is already in correct position*/ + + if (pos == cycle_start) + continue; +/* ignore all duplicate elements*/ + + while (item == arr[pos]) + pos += 1; +/* put the item to it's right position*/ + + if (pos != cycle_start) { + int temp = item; + item = arr[pos]; + arr[pos] = temp; + writes++; + } +/* Rotate rest of the cycle*/ + + while (pos != cycle_start) { + pos = cycle_start; +/* Find position where we put the element*/ + + for (int i = cycle_start + 1; i < n; i++) + if (arr[i] < item) + pos += 1; +/* ignore all duplicate elements*/ + + while (item == arr[pos]) + pos += 1; +/* put the item to it's right position*/ + + if (item != arr[pos]) { + int temp = item; + item = arr[pos]; + arr[pos] = temp; + writes++; + } + } + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; + int n = arr.length; + cycleSort(arr, n); + System.out.println(""After sort : ""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +} +"," '''Python program to implement cycle sort''' + + ''' Function sort the array using Cycle sort''' + +def cycleSort(array): + + ''' count number of memory writes''' + writes = 0 ''' Loop through the array to find cycles to rotate.''' + + for cycleStart in range(0, len(array) - 1): + + ''' initialize item as starting point''' + + item = array[cycleStart] ''' Find where to put the item.''' + + pos = cycleStart + for i in range(cycleStart + 1, len(array)): + if array[i] < item: + pos += 1 + ''' If the item is already there, this is not a cycle.''' + + if pos == cycleStart: + continue + ''' Otherwise, put the item there or right after any duplicates.''' + + while item == array[pos]: + pos += 1 + ''' put the item to it's right position''' + + array[pos], item = item, array[pos] + writes += 1 + ''' Rotate the rest of the cycle.''' + + while pos != cycleStart: + ''' Find where to put the item.''' + + pos = cycleStart + for i in range(cycleStart + 1, len(array)): + if array[i] < item: + pos += 1 + ''' Put the item there or right after any duplicates.''' + + while item == array[pos]: + pos += 1 + + ''' put the item to it's right position''' + + array[pos], item = item, array[pos] + writes += 1 + return writes '''driver code''' + +arr = [1, 8, 3, 9, 10, 10, 2, 4 ] +n = len(arr) +cycleSort(arr) +print(""After sort : "") +for i in range(0, n) : + print(arr[i], end = ' ') +" +Sort the linked list in the order of elements appearing in the array,"/*Efficient JAVA program to sort given list in order +elements are appearing in an array*/ + +import java.util.*; + +class GFG +{ + +/*Linked list node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to insert a node at the +beginning of the linked list*/ + +static Node 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; + return head_ref; +} + +/*function to print the linked list*/ + +static void printList(Node head) +{ + while (head != null) + { + System.out.print(head.data+ ""->""); + head = head.next; + } +} + +/*Function that sort list in order of apperaing +elements in an array*/ + +static void sortlist(int arr[], int N, Node head) +{ +/* Store frequencies of elements in a + hash table.*/ + + HashMap hash = new HashMap(); + Node temp = head; + while (temp != null) + { + if(hash.containsKey(temp.data)) + hash.put(temp.data,hash.get(temp.data) + 1); + else + hash.put(temp.data,1); + temp = temp.next; + } + + temp = head; + +/* One by one put elements in lis according + to their appearance in array*/ + + for (int i = 0; i < N; i++) + { + +/* Update 'frequency' nodes with value + equal to arr[i]*/ + + int frequency = hash.get(arr[i]); + while (frequency-->0) + { + +/* Modify list data as element + appear in an array*/ + + temp.data = arr[i]; + temp = temp.next; + } + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + Node head = null; + int arr[] = { 5, 1, 3, 2, 8 }; + int N = arr.length; + +/* creating the linked list*/ + + head = push(head, 3); + head = push(head, 2); + head = push(head, 5); + head = push(head, 8); + head = push(head, 5); + head = push(head, 2); + head = push(head, 1); + +/* Function call to sort the list in order + elements are apperaing in an array*/ + + sortlist(arr, N, head); + +/* print the modified linked list*/ + + System.out.print(""Sorted List:"" +""\n""); + printList(head); +} +} + + +"," '''Efficient Python3 program to sort given list in order +elements are appearing in an array''' + + + '''Linked list node''' + +class Node: + def __init__(self): + self.data = 0 + self.next = None + + '''Function to insert a node at the +beginning of the linked list''' + +def push( head_ref, new_data): + + new_node = Node() + new_node.data = new_data + new_node.next = head_ref + head_ref = new_node + return head_ref + + '''function to print the linked list''' + +def printList( head): + + while (head != None): + + print(head.data, end = ""->"") + head = head.next + + '''Function that sort list in order of apperaing +elements in an array''' + +def sortlist( arr, N, head): + + ''' Store frequencies of elements in a + hash table.''' + + hash = dict() + temp = head + while (temp != None) : + + hash[temp.data] = hash.get(temp.data, 0) + 1 + temp = temp.next + + temp = head + + ''' One by one put elements in lis according + to their appearance in array''' + + for i in range(N): + + ''' Update 'frequency' nodes with value + equal to arr[i]''' + + frequency = hash.get(arr[i],0) + + while (frequency > 0) : + + frequency= frequency-1 + ''' Modify list data as element + appear in an array''' + + temp.data = arr[i] + temp = temp.next + + '''Driver Code''' + + +head = None +arr = [5, 1, 3, 2, 8 ] +N = len(arr) + + '''creating the linked list''' + +head = push(head, 3) +head = push(head, 2) +head = push(head, 5) +head = push(head, 8) +head = push(head, 5) +head = push(head, 2) +head = push(head, 1) + + '''Function call to sort the list in order +elements are apperaing in an array''' + +sortlist(arr, N, head) + + '''print the modified linked list''' + +print(""Sorted List:"" ) +printList(head) + + + +" +Find a common element in all rows of a given row-wise sorted matrix,"/*A Java program to find a common +element in all rows of a +row wise sorted array*/ + +class GFG { +/* Specify number of rows and columns*/ + + static final int M = 4; + static final int N = 5; +/* Returns common element in all rows + of mat[M][N]. If there is no + common element, then -1 is + returned*/ + + static int findCommon(int mat[][]) + { +/* An array to store indexes + of current last column*/ + + int column[] = new int[M]; +/* To store index of row whose current + last element is minimum*/ + + int min_row; +/*Initialize current last element of all rows*/ + + int i; + for (i = 0; i < M; i++) + column[i] = N - 1; +/* Initialize min_row as first row*/ + + min_row = 0; +/* Keep finding min_row in current last column, till either + all elements of last column become same or we hit first column.*/ + + while (column[min_row] >= 0) { +/* Find minimum in current last column*/ + + for (i = 0; i < M; i++) { + if (mat[i][column[i]] < mat[min_row][column[min_row]]) + min_row = i; + } +/* eq_count is count of elements equal to minimum in current last + column.*/ + + int eq_count = 0; +/* Traverse current last column elements again to update it*/ + + for (i = 0; i < M; i++) { +/* Decrease last column index of a row whose value is more + than minimum.*/ + + if (mat[i][column[i]] > mat[min_row][column[min_row]]) { + if (column[i] == 0) + return -1; +/* Reduce last column index by 1*/ + + column[i] -= 1; + } + else + eq_count++; + } +/* If equal count becomes M, + return the value*/ + + if (eq_count == M) + return mat[min_row][column[min_row]]; + } + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + int mat[][] = { { 1, 2, 3, 4, 5 }, + { 2, 4, 5, 8, 10 }, + { 3, 5, 7, 9, 11 }, + { 1, 3, 5, 7, 9 } }; + int result = findCommon(mat); + if (result == -1) + System.out.print(""No common element""); + else + System.out.print(""Common element is "" + result); + } +}"," '''Python 3 program to find a common element +in all rows of a row wise sorted array''' + '''Specify number of rows +and columns''' + +M = 4 +N = 5 + '''Returns common element in all rows +of mat[M][N]. If there is no common +element, then -1 is returned''' + +def findCommon(mat): + ''' An array to store indexes of + current last column''' + + column = [N - 1] * M + '''Initialize min_row as first row''' + + min_row = 0 + ''' Keep finding min_row in current last + column, till either all elements of + last column become same or we hit first column.''' + + while (column[min_row] >= 0): + ''' Find minimum in current last column''' + + for i in range(M): + if (mat[i][column[i]] < + mat[min_row][column[min_row]]): + min_row = i + ''' eq_count is count of elements equal + to minimum in current last column.''' + + eq_count = 0 ''' Traverse current last column elements + again to update it''' + + for i in range(M): + ''' Decrease last column index of a row + whose value is more than minimum.''' + + if (mat[i][column[i]] > + mat[min_row][column[min_row]]): + if (column[i] == 0): + return -1 + '''Reduce last column index by 1''' + + column[i] -= 1 + else: + eq_count += 1 ''' If equal count becomes M, return the value''' + + if (eq_count == M): + return mat[min_row][column[min_row]] + return -1 + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[1, 2, 3, 4, 5], + [2, 4, 5, 8, 10], + [3, 5, 7, 9, 11], + [1, 3, 5, 7, 9]] + result = findCommon(mat) + if (result == -1): + print(""No common element"") + else: + print(""Common element is"", result)" +Find k maximum elements of array in original order,"/*Java program to find k maximum +elements of array in original order*/ + +import java.util.Arrays; +import java.util.Collections; + +public class GfG { + +/* Function to print m Maximum elements*/ + + public static void printMax(int arr[], int k, int n) + { +/* Array to store the copy + of the original array*/ + + Integer[] brr = new Integer[n]; + + for (int i = 0; i < n; i++) + brr[i] = arr[i]; + +/* Sorting the array in + descending order*/ + + Arrays.sort(brr, Collections.reverseOrder()); + +/* Traversing through original array and + printing all those elements that are + in first k of sorted array. +goo.gl/uj5RCD +Please refer https: + for details of Arrays.binarySearch()*/ + + for (int i = 0; i < n; ++i) + if (Arrays.binarySearch(brr, arr[i], + Collections.reverseOrder()) >= 0 + && Arrays.binarySearch(brr, arr[i], + Collections.reverseOrder()) < k) + + System.out.print(arr[i]+ "" ""); + } + +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 50, 8, 45, 12, 25, 40, 84 }; + int n = arr.length; + int k = 3; + printMax(arr, k, n); + } +} + + +"," '''Python3 program to find k maximum elements +of array in original order''' + + + '''Function to pr m Maximum elements''' + +def printMax(arr, k, n): + + ''' vector to store the copy of the + original array''' + + brr = arr.copy() + + ''' Sorting the vector in descending + order. Please refer below link for + details''' + + brr.sort(reverse = True) + + ''' Traversing through original array and + pring all those elements that are + in first k of sorted vector.''' + + for i in range(n): + if (arr[i] in brr[0:k]): + print(arr[i], end = "" "") + + '''Driver code''' + +arr = [ 50, 8, 45, 12, 25, 40, 84 ] +n = len(arr) +k = 3 + +printMax(arr, k, n) + + +" +Space and time efficient Binomial Coefficient,"/*Program to calculate C(n, k) in java*/ + +class BinomialCoefficient { +/* Returns value of Binomial Coefficient C(n, k)*/ + + static int binomialCoeff(int n, int k) + { + int res = 1; +/* Since C(n, k) = C(n, n-k)*/ + + if (k > n - k) + k = n - k; +/* Calculate value of + [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]*/ + + for (int i = 0; i < k; ++i) { + res *= (n - i); + res /= (i + 1); + } + return res; + } + /* Driver program to test above function*/ + + public static void main(String[] args) + { + int n = 8; + int k = 2; + System.out.println(""Value of C("" + n + "", "" + k + "") "" + + ""is"" + + "" "" + binomialCoeff(n, k)); + } +} +"," '''Python program to calculate C(n, k)''' + + '''Returns value of Binomial Coefficient +C(n, k)''' + +def binomialCoefficient(n, k): + res = 1 ''' since C(n, k) = C(n, n - k)''' + + if(k > n - k): + k = n - k + ''' Calculate value of + [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]''' + + for i in range(k): + res = res * (n - i) + res = res / (i + 1) + return res + '''Driver program to test above function''' + +n = 8 +k = 2 +res = binomialCoefficient(n, k) +print(""Value of C(% d, % d) is % d"" %(n, k, res))" +Postfix to Infix,"/*Java program to find infix for +a given postfix.*/ + +import java.util.*; +class GFG +{ +static boolean isOperand(char x) +{ + return (x >= 'a' && x <= 'z') || + (x >= 'A' && x <= 'Z'); +} +/*Get Infix for a given postfix +expression*/ + +static String getInfix(String exp) +{ + Stack s = new Stack(); + for (int i = 0; i < exp.length(); i++) + { +/* Push operands*/ + + if (isOperand(exp.charAt(i))) + { + s.push(exp.charAt(i) + """"); + } +/* We assume that input is + a valid postfix and expect + an operator.*/ + + else + { + String op1 = s.peek(); + s.pop(); + String op2 = s.peek(); + s.pop(); + s.push(""("" + op2 + exp.charAt(i) + + op1 + "")""); + } + } +/* There must be a single element + in stack now which is the required + infix.*/ + + return s.peek(); +} +/*Driver code*/ + +public static void main(String args[]) +{ + String exp = ""ab*c+""; + System.out.println( getInfix(exp)); +} +}"," '''Python3 program to find infix for +a given postfix. ''' + +def isOperand(x): + return ((x >= 'a' and x <= 'z') or + (x >= 'A' and x <= 'Z')) + '''Get Infix for a given postfix +expression ''' + +def getInfix(exp) : + s = [] + for i in exp: + ''' Push operands ''' + + if (isOperand(i)) : + s.insert(0, i) + ''' We assume that input is a + valid postfix and expect + an operator. ''' + + else: + op1 = s[0] + s.pop(0) + op2 = s[0] + s.pop(0) + s.insert(0, ""("" + op2 + i + + op1 + "")"") + ''' There must be a single element in + stack now which is the required + infix. ''' + + return s[0] + '''Driver Code ''' + +if __name__ == '__main__': + exp = ""ab*c+"" + print(getInfix(exp.strip()))" +Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts,"/*Java program to find Bitwise OR of two +equal halves of an array after performing +K right circular shifts*/ + +import java.util.*; + +class GFG{ + +static int MAX = 100005; + +/*Array for storing +the segment tree*/ + +static int []seg = new int[4 * MAX]; + +/*Function to build the segment tree*/ + +static void build(int node, int l, + int r, int a[]) +{ + if (l == r) + seg[node] = a[l]; + + else + { + int mid = (l + r) / 2; + + build(2 * node, l, mid, a); + build(2 * node + 1, mid + 1, r, a); + + seg[node] = (seg[2 * node] | + seg[2 * node + 1]); + } +} + +/*Function to return the OR +of elements in the range [l, r]*/ + +static int query(int node, int l, int r, + int start, int end, int a[]) +{ + +/* Check for out of bound condition*/ + + if (l > end || r < start) + return 0; + + if (start <= l && r <= end) + return seg[node]; + +/* Find middle of the range*/ + + int mid = (l + r) / 2; + +/* Recurse for all the elements in array*/ + + return ((query(2 * node, l, mid, + start, end, a)) | + (query(2 * node + 1, mid + 1, + r, start, end, a))); +} + +/*Function to find the OR sum*/ + +static void orsum(int a[], int n, + int q, int k[]) +{ + +/* Function to build the segment Tree*/ + + build(1, 0, n - 1, a); + +/* Loop to handle q queries*/ + + for(int j = 0; j < q; j++) + { + +/* Effective number of + right circular shifts*/ + + int i = k[j] % (n / 2); + +/* Calculating the OR of + the two halves of the + array from the segment tree*/ + + +/* OR of second half of the + array [n/2-i, n-1-i]*/ + + int sec = query(1, 0, n - 1, + n / 2 - i, + n - i - 1, a); + +/* OR of first half of the array + [n-i, n-1]OR[0, n/2-1-i]*/ + + int first = (query(1, 0, n - 1, 0, + n / 2 - 1 - i, a) | + query(1, 0, n - 1, + n - i, n - 1, a)); + + int temp = sec + first; + +/* Print final answer to the query*/ + + System.out.print(temp + ""\n""); + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + + int a[] = { 7, 44, 19, 86, 65, 39, 75, 101 }; + int n = a.length; + int q = 2; + + int k[] = { 4, 2 }; + + orsum(a, n, q, k); +} +} + + +"," '''Python3 program to find Bitwise OR of two +equal halves of an array after performing +K right circular shifts''' + +MAX = 100005 + + '''Array for storing +the segment tree''' + +seg = [0] * (4 * MAX) + + '''Function to build the segment tree''' + +def build(node, l, r, a): + + if (l == r): + seg[node] = a[l] + + else: + mid = (l + r) // 2 + + build(2 * node, l, mid, a) + build(2 * node + 1, mid + 1, r, a) + + seg[node] = (seg[2 * node] | + seg[2 * node + 1]) + + '''Function to return the OR +of elements in the range [l, r]''' + +def query(node, l, r, start, end, a): + + ''' Check for out of bound condition''' + + if (l > end or r < start): + return 0 + + if (start <= l and r <= end): + return seg[node] + + ''' Find middle of the range''' + + mid = (l + r) // 2 + + ''' Recurse for all the elements in array''' + + return ((query(2 * node, l, mid, + start, end, a)) | + (query(2 * node + 1, mid + 1, + r, start, end, a))) + + '''Function to find the OR sum''' + +def orsum(a, n, q, k): + + ''' Function to build the segment Tree''' + + build(1, 0, n - 1, a) + + ''' Loop to handle q queries''' + + for j in range(q): + + ''' Effective number of + right circular shifts''' + + i = k[j] % (n // 2) + + ''' Calculating the OR of + the two halves of the + array from the segment tree''' + + + ''' OR of second half of the + array [n/2-i, n-1-i]''' + + sec = query(1, 0, n - 1, n // 2 - i, + n - i - 1, a) + + ''' OR of first half of the array + [n-i, n-1]OR[0, n/2-1-i]''' + + first = (query(1, 0, n - 1, 0, + n // 2 - + 1 - i, a) | + query(1, 0, n - 1, + n - i, + n - 1, a)) + + temp = sec + first + + ''' Print final answer to the query''' + + print(temp) + + '''Driver Code''' + +if __name__ == ""__main__"": + + a = [ 7, 44, 19, 86, 65, 39, 75, 101 ] + n = len(a) + + q = 2 + k = [ 4, 2 ] + + orsum(a, n, q, k) + + +" +Check for Palindrome after every character replacement Query,," '''Python3 program to find if +string becomes palindrome +after every query. + ''' '''Function to check if string +is Palindrome or Not''' + +def isPalindrome(string: list) -> bool: + n = len(string) + for i in range(n // 2): + if string[i] != string[n - 1 - i]: + return False + return True + '''Takes two inputs for Q queries. +For every query, it prints Yes +if string becomes palindrome +and No if not.''' + +def Query(string: list, Q: int) -> None: + ''' Process all queries one by one''' + + for i in range(Q): + inp = list(input().split()) + i1 = int(inp[0]) + i2 = int(inp[1]) + ch = inp[2] + ''' query 1: i1 = 3 ,i2 = 0, ch = 'e' + query 2: i1 = 0 ,i2 = 2 , ch = 's' + replace character at index + i1 & i2 with new 'ch' ''' + string[i1] = string[i2] = ch + ''' check string is palindrome or not''' + + if isPalindrome(string): + print(""Yes"") + else: + print(""No"") + '''Driver Code''' + +if __name__ == ""__main__"": + string = list(""geeks"") + Q = 2 + Query(string, Q)" +Delete middle element of a stack,"/*Java code to delete middle of a stack +without using additional data structure.*/ + +import java.io.*; +import java.util.*; +public class GFG { +/* Deletes middle of stack of size + n. Curr is current item number*/ + + static void deleteMid(Stack st, + int n, int curr) + { +/* If stack is empty or all items + are traversed*/ + + if (st.empty() || curr == n) + return; +/* Remove current item*/ + + char x = st.pop(); +/* Remove other items*/ + + deleteMid(st, n, curr+1); +/* Put all items back except middle*/ + + if (curr != n/2) + st.push(x); + } +/* Driver function to test above functions*/ + + public static void main(String args[]) + { + Stack st = + new Stack(); +/* push elements into the stack*/ + + st.push('1'); + st.push('2'); + st.push('3'); + st.push('4'); + st.push('5'); + st.push('6'); + st.push('7'); + deleteMid(st, st.size(), 0); +/* Printing stack after deletion + of middle.*/ + + while (!st.empty()) + { + char p=st.pop(); + System.out.print(p + "" ""); + } + } +}"," '''Python3 code to delete middle of a stack +without using additional data structure. + ''' '''Deletes middle of stack of size +n. Curr is current item number''' + +class Stack: + def __init__(self): + self.items = [] + def isEmpty(self): + return self.items == [] + def push(self, item): + self.items.append(item) + def pop(self): + return self.items.pop() + def peek(self): + return self.items[len(self.items)-1] + def size(self): + return len(self.items) +def deleteMid(st, n, curr) : + ''' If stack is empty or all items + are traversed''' + + if (st.isEmpty() or curr == n) : + return + ''' Remove current item''' + + x = st.peek() + st.pop() + ''' Remove other items''' + + deleteMid(st, n, curr+1) + ''' Put all items back except middle''' + + if (curr != int(n/2)) : + st.push(x) + '''Driver function to test above functions''' + +st = Stack() + '''push elements into the stack''' + +st.push('1') +st.push('2') +st.push('3') +st.push('4') +st.push('5') +st.push('6') +st.push('7') +deleteMid(st, st.size(), 0) + '''Printing stack after deletion +of middle.''' + +while (st.isEmpty() == False) : + p = st.peek() + st.pop() + print (str(p) + "" "", end="""")" +Compute the minimum or maximum of two integers without branching,"/*Java program to Compute the minimum +or maximum of two integers without +branching*/ + +public class AWS { + /*Function to find minimum of x and y*/ + + static int min(int x, int y) + { + return y ^ ((x ^ y) & -(x << y)); + } + /*Function to find maximum of x and y*/ + + static int max(int x, int y) + { + return x ^ ((x ^ y) & -(x << y)); + } + /* Driver program to test above functions */ + + public static void main(String[] args) { + int x = 15; + int y = 6; + System.out.print(""Minimum of ""+x+"" and ""+y+"" is ""); + System.out.println(min(x, y)); + System.out.print(""Maximum of ""+x+"" and ""+y+"" is ""); + System.out.println( max(x, y)); + } +}"," '''Python3 program to Compute the minimum +or maximum of two integers without +branching + ''' '''Function to find minimum of x and y''' + +def min(x, y): + return y ^ ((x ^ y) & -(x < y)) + '''Function to find maximum of x and y''' + +def max(x, y): + return x ^ ((x ^ y) & -(x < y)) + '''Driver program to test above functions''' + +x = 15 +y = 6 +print(""Minimum of"", x, ""and"", y, ""is"", end="" "") +print(min(x, y)) +print(""Maximum of"", x, ""and"", y, ""is"", end="" "") +print(max(x, y))" +Count rotations in sorted and rotated linked list,"/*Program for count number of rotations in +sorted linked list.*/ + +import java.util.*; + +class GFG +{ + +/* Linked list node */ + +static class Node { + int data; + Node next; +}; + +/*Function that count number of +rotation in singly linked list.*/ + +static int countRotation(Node head) +{ + +/* declare count variable and assign it 1.*/ + + int count = 0; + +/* declare a min variable and assign to + data of head node.*/ + + int min = head.data; + +/* check that while head not equal to null.*/ + + while (head != null) { + +/* if min value is greater then head.data + then it breaks the while loop and + return the value of count.*/ + + if (min > head.data) + break; + + count++; + +/* head assign the next value of head.*/ + + head = head.next; + } + return count; +} + +/*Function to push element in linked list.*/ + +static Node push(Node head, int data) +{ +/* Allocate dynamic memory for newNode.*/ + + Node newNode = new Node(); + +/* Assign the data into newNode.*/ + + newNode.data = data; + +/* newNode.next assign the address of + head node.*/ + + newNode.next = (head); + +/* newNode become the headNode.*/ + + (head) = newNode; + return head; +} + +/*Display linked list.*/ + +static void printList(Node node) +{ + while (node != null) { + System.out.printf(""%d "", node.data); + node = node.next; + } +} + +/*Driver functions*/ + +public static void main(String[] args) +{ + +/* Create a node and initialize with null*/ + + Node head = null; + +/* push() insert node in linked list. + 15.18.5.8.11.12*/ + + head = push(head, 12); + head = push(head, 11); + head = push(head, 8); + head = push(head, 5); + head = push(head, 18); + head = push(head, 15); + + printList(head); + System.out.println(); + System.out.print(""Linked list rotated elements: ""); + +/* Function call countRotation()*/ + + System.out.print(countRotation(head) +""\n""); + +} +} + + +"," '''Program for count number of rotations in +sorted linked list.''' + + + '''Linked list node''' + +class Node: + + def __init__(self, data): + + self.data = data + self.next = None + + '''Function that count number of +rotation in singly linked list.''' + +def countRotation(head): + + ''' Declare count variable and assign it 1.''' + + count = 0 + + ''' Declare a min variable and assign to + data of head node.''' + + min = head.data + + ''' Check that while head not equal to None.''' + + while (head != None): + + ''' If min value is greater then head->data + then it breaks the while loop and + return the value of count.''' + + if (min > head.data): + break + + count += 1 + + ''' head assign the next value of head.''' + + head = head.next + + return count + + '''Function to push element in linked list.''' + +def push(head, data): + + ''' Allocate dynamic memory for newNode.''' + + newNode = Node(data) + + ''' Assign the data into newNode.''' + + newNode.data = data + + ''' newNode->next assign the address of + head node.''' + + newNode.next = (head) + + ''' newNode become the headNode.''' + + (head) = newNode + return head + + '''Display linked list.''' + +def printList(node): + + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Create a node and initialize with None''' + + head = None + + ''' push() insert node in linked list. + 15 -> 18 -> 5 -> 8 -> 11 -> 12''' + + head = push(head, 12) + head = push(head, 11) + head = push(head, 8) + head = push(head, 5) + head = push(head, 18) + head = push(head, 15) + + printList(head); + print() + print(""Linked list rotated elements: "", + end = '') + + ''' Function call countRotation()''' + + print(countRotation(head)) + + +" +Third largest element in an array of distinct elements,"/*Java program to find third Largest element in an array*/ + +class GFG { + + static void thirdLargest(int arr[], int arr_size) { + /* There should be atleast three elements */ + + if (arr_size < 3) { + System.out.printf("" Invalid Input ""); + return; + } + +/* Initialize first, second and third Largest element*/ + + int first = arr[0], second = Integer.MIN_VALUE, + third = Integer.MIN_VALUE; + +/* Traverse array elements to find the third Largest*/ + + for (int i = 1; i < arr_size; i++) { + /* If current element is greater than first, + then update first, second and third */ + + if (arr[i] > first) { + third = second; + second = first; + first = arr[i]; + } /* If arr[i] is in between first and second */ + + else if (arr[i] > second) { + third = second; + second = arr[i]; + } /* If arr[i] is in between second and third */ + + else if (arr[i] > third) { + third = arr[i]; + } + } + + System.out.printf(""The third Largest element is %d\n"", third); + } + + /* Driver program to test above function */ + + public static void main(String []args) { + int arr[] = {12, 13, 1, 10, 34, 16}; + int n = arr.length; + thirdLargest(arr, n); + } +} + +"," '''Python3 program to find +third Largest element in +an array''' + +import sys +def thirdLargest(arr, arr_size): + + ''' There should be + atleast three elements''' + + if (arr_size < 3): + + print("" Invalid Input "") + return + + ''' Initialize first, second + and third Largest element''' + + first = arr[0] + second = -sys.maxsize + third = -sys.maxsize + + ''' Traverse array elements + to find the third Largest''' + + for i in range(1, arr_size): + + ''' If current element is + greater than first, + then update first, + second and third''' + + if (arr[i] > first): + + third = second + second = first + first = arr[i] + + + ''' If arr[i] is in between + first and second''' + + elif (arr[i] > second): + + third = second + second = arr[i] + + ''' If arr[i] is in between + second and third''' + + elif (arr[i] > third): + third = arr[i] + + print(""The third Largest"" , + ""element is"", third) + + '''Driver Code''' + +arr = [12, 13, 1, + 10, 34, 16] +n = len(arr) +thirdLargest(arr, n) + + +" +Find a triplet that sum to a given value,"/*Java program to find a triplet*/ + +class FindTriplet { +/* returns true if there is triplet with sum equal + to 'sum' present in A[]. Also, prints the triplet*/ + + boolean find3Numbers(int A[], int arr_size, int sum) + { + int l, r; + /* Sort the elements */ + + quickSort(A, 0, arr_size - 1); + /* Now fix the first element one by one and find the + other two elements */ + + for (int i = 0; i < arr_size - 2; i++) { +/* To find the other two elements, start two index variables + from two corners of the array and move them toward each + other +index of the first element in the remaining elements*/ + +l = i + 1; +/*index of the last element*/ + +r = arr_size - 1; + while (l < r) { + if (A[i] + A[l] + A[r] == sum) { + System.out.print(""Triplet is "" + A[i] + "", "" + A[l] + "", "" + A[r]); + return true; + } + else if (A[i] + A[l] + A[r] < sum) + l++; +/*A[i] + A[l] + A[r] > sum*/ + +else + r--; + } + } +/* If we reach here, then no triplet was found*/ + + return false; + } + + /*partition function*/ + + int partition(int A[], int si, int ei) + { + int x = A[ei]; + int i = (si - 1); + int j; + for (j = si; j <= ei - 1; j++) { + if (A[j] <= x) { + i++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } + int temp = A[i + 1]; + A[i + 1] = A[ei]; + A[ei] = temp; + return (i + 1); + }/* Implementation of Quick Sort + A[] --> Array to be sorted + si --> Starting index + ei --> Ending index + */ + + void quickSort(int A[], int si, int ei) + { + int pi; + /* Partitioning index */ + + if (si < ei) { + pi = partition(A, si, ei); + quickSort(A, si, pi - 1); + quickSort(A, pi + 1, ei); + } + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + FindTriplet triplet = new FindTriplet(); + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + triplet.find3Numbers(A, arr_size, sum); + } +}"," '''Python3 program to find a triplet''' + + '''returns true if there is triplet +with sum equal to 'sum' present +in A[]. Also, prints the triplet''' + +def find3Numbers(A, arr_size, sum): ''' Sort the elements ''' + + A.sort() + ''' Now fix the first element + one by one and find the + other two elements ''' + + for i in range(0, arr_size-2): + ''' To find the other two elements, + start two index variables from + two corners of the array and + move them toward each other + index of the first element + in the remaining elements''' + + l = i + 1 + ''' index of the last element''' + + r = arr_size-1 + while (l < r): + if( A[i] + A[l] + A[r] == sum): + print(""Triplet is"", A[i], + ', ', A[l], ', ', A[r]); + return True + elif (A[i] + A[l] + A[r] < sum): + l += 1 + '''A[i] + A[l] + A[r] > sum''' + + else: + r -= 1 + ''' If we reach here, then + no triplet was found''' + + return False + '''Driver program to test above function ''' + +A = [1, 4, 45, 6, 10, 8] +sum = 22 +arr_size = len(A) +find3Numbers(A, arr_size, sum)" +Count of index pairs with equal elements in an array,"/*Java program to count of index pairs with +equal elements in an array.*/ + +import java.util.*; +class GFG { + +/* A method to return number of pairs with + equal values*/ + public static int countPairs(int arr[], int n) + { + HashMap hm = new HashMap<>(); +/* Finding frequency of each number.*/ + + for(int i = 0; i < n; i++) + { + if(hm.containsKey(arr[i])) + hm.put(arr[i],hm.get(arr[i]) + 1); + else + hm.put(arr[i], 1); + } + int ans=0; +/* Calculating count of pairs with equal values*/ + + for(Map.Entry it : hm.entrySet()) + { + int count = it.getValue(); + ans += (count * (count - 1)) / 2; + } + return ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = new int[]{1, 2, 3, 1}; + System.out.println(countPairs(arr,arr.length)); + } +} +"," '''Python3 program to count of index pairs +with equal elements in an array.''' + +import math as mt + '''Return the number of pairs with +equal values.''' + +def countPairs(arr, n): + mp = dict() + ''' Finding frequency of each number.''' + + for i in range(n): + if arr[i] in mp.keys(): + mp[arr[i]] += 1 + else: + mp[arr[i]] = 1 + ''' Calculating pairs of each value.''' + + ans = 0 + for it in mp: + count = mp[it] + ans += (count * (count - 1)) // 2 + return ans + '''Driver Code''' + +arr = [1, 1, 2] +n = len(arr) +print(countPairs(arr, n))" +Noble integers in an array (count of greater elements is equal to value),"/*Java program to find Noble elements +in an array.*/ + +import java.util.ArrayList; + +class GFG { + +/* Returns a Noble integer if present, + else returns -1.*/ + + public static int nobleInteger(int arr[]) + { + int size = arr.length; + for (int i = 0; i < size; i++ ) + { + int count = 0; + for (int j = 0; j < size; j++) + if (arr[i] < arr[j]) + count++; + +/* If count of greater elements + is equal to arr[i]*/ + + if (count == arr[i]) + return arr[i]; + } + return -1; + } + +/* Driver code*/ + + public static void main(String args[]) + { + int [] arr = {10, 3, 20, 40, 2}; + int res = nobleInteger(arr); + if (res != -1) + System.out.println(""The noble "" + + ""integer is ""+ res); + else + System.out.println(""No Noble "" + + ""Integer Found""); + } +} +"," '''Python3 program to find Noble +elements in an array.''' + + + '''Returns a Noble integer if +present, else returns -1.''' + +def nobleInteger(arr, size): + + for i in range(0, size): + + count = 0 + for j in range(0, size): + if (arr[i] < arr[j]): + count += 1 + ''' If count of greater + elements is equal + to arr[i]''' + + if (count == arr[i]): + return arr[i] + + return -1 + + '''Driver code''' + +arr = [10, 3, 20, 40, 2] +size = len(arr) +res = nobleInteger(arr,size) +if (res != -1): + print(""The noble integer is "", + res) +else: + print(""No Noble Integer Found"") + + +" +Find n-th node in Postorder traversal of a Binary Tree,"/*Java program to find n-th node of +Postorder Traversal of Binary Tree */ + +public class NthNodePostOrder { + static int flag = 0; +/* A binary tree node structure */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + this.data=data; + } +};/* function to find the N-th node in the postorder + traversal of a given binary tree */ + + public static void NthPostordernode(Node root, int N) + { + if (root == null) + return; + if (flag <= N) + { +/* left recursion */ + + NthPostordernode(root.left, N); +/* right recursion */ + + NthPostordernode(root.right, N); + flag++; +/* prints the n-th node of preorder traversal */ + + if (flag == N) + System.out.print(root.data); + } + } + +/*driver code*/ + + public static void main(String args[]) { + Node root = new Node(25); + root.left = new Node(20); + root.right = new Node(30); + root.left.left = new Node(18); + root.left.right = new Node(22); + root.right.left = new Node(24); + root.right.right = new Node(32); + int N = 6; /* prints n-th node found */ + + NthPostordernode(root, N); + } +} +"," '''Python3 program to find n-th node of +Postorder Traversal of Binary Tree''' + + '''A Binary Tree Node +Utility function to create a new tree node ''' + +class createNode: + def __init__(self, data): + self.data= data + self.left = None + self.right = None '''function to find the N-th node +in the postorder traversal of +a given binary tree''' + +flag = [0] +def NthPostordernode(root, N): + if (root == None): + return + if (flag[0] <= N[0]): + ''' left recursion ''' + + NthPostordernode(root.left, N) + ''' right recursion ''' + + NthPostordernode(root.right, N) + flag[0] += 1 + ''' prints the n-th node of + preorder traversal ''' + + if (flag[0] == N[0]): + print(root.data) + '''Driver Code''' + +if __name__ == '__main__': + root = createNode(25) + root.left = createNode(20) + root.right = createNode(30) + root.left.left = createNode(18) + root.left.right = createNode(22) + root.right.left = createNode(24) + root.right.right = createNode(32) + N = [6] + ''' prints n-th node found ''' + + NthPostordernode(root, N)" +Iterative method to check if two trees are mirror of each other,"/*Java implementation to check whether the two +binary tress are mirrors of each other or not*/ + +import java.util.*; +class GfG { +/*structure of a node in binary tree */ + +static class Node +{ + int data; + Node left, right; +} +/*Utility function to create and return +a new node for a binary tree */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} +/*function to check whether the two binary trees +are mirrors of each other or not */ + +static String areMirrors(Node root1, Node root2) +{ + Stack st1 = new Stack (); + Stack st2 = new Stack (); + while (true) + { +/* iterative inorder traversal of 1st tree and + reverse inoder traversal of 2nd tree */ + + while (root1 != null && root2 != null) + { +/* if the corresponding nodes in the two traversal + have different data values, then they are not + mirrors of each other. */ + + if (root1.data != root2.data) + return ""No""; + st1.push(root1); + st2.push(root2); + root1 = root1.left; + root2 = root2.right; + } +/* if at any point one root becomes null and + the other root is not null, then they are + not mirrors. This condition verifies that + structures of tree are mirrors of each other. */ + + if (!(root1 == null && root2 == null)) + return ""No""; + if (!st1.isEmpty() && !st2.isEmpty()) + { + root1 = st1.peek(); + root2 = st2.peek(); + st1.pop(); + st2.pop(); + /* we have visited the node and its left subtree. + Now, it's right subtree's turn */ + + root1 = root1.right; + /* we have visited the node and its right subtree. + Now, it's left subtree's turn */ + + root2 = root2.left; + } +/* both the trees have been completely traversed */ + + else + break; + } +/* tress are mirrors of each other */ + + return ""Yes""; +} +/*Driver program to test above */ + +public static void main(String[] args) +{ +/* 1st binary tree formation */ + + Node root1 = newNode(1); /* 1 */ + + root1.left = newNode(3); /* / \ */ + + root1.right = newNode(2); /* 3 2 */ + + root1.right.left = newNode(5); /* / \ */ + + root1.right.right = newNode(4); /* 2nd binary tree formation */ + + Node root2 = newNode(1); /* 1 */ + + root2.left = newNode(2); /* / \ */ + + root2.right = newNode(3); /* 2 3 */ + + root2.left.left = newNode(4); /* / \ */ + + root2.left.right = newNode(5); /* 4 5 */ + + System.out.println(areMirrors(root1, root2)); +} +}"," '''Python3 implementation to check whether +the two binary tress are mirrors of each +other or not ''' + '''Utility function to create and return +a new node for a binary tree ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''function to check whether the two binary +trees are mirrors of each other or not ''' + +def areMirrors(root1, root2): + st1 = [] + st2 = [] + while (1): + ''' iterative inorder traversal of 1st tree + and reverse inoder traversal of 2nd tree ''' + + while (root1 and root2): + ''' if the corresponding nodes in the + two traversal have different data + values, then they are not mirrors + of each other. ''' + + if (root1.data != root2.data): + return ""No"" + st1.append(root1) + st2.append(root2) + root1 = root1.left + root2 = root2.right + ''' if at any point one root becomes None and + the other root is not None, then they are + not mirrors. This condition verifies that + structures of tree are mirrors of each other. ''' + + if (not (root1 == None and root2 == None)): + return ""No"" + if (not len(st1) == 0 and not len(st2) == 0): + root1 = st1[-1] + root2 = st2[-1] + st1.pop(-1) + st2.pop(-1) + ''' we have visited the node and its left + subtree. Now, it's right subtree's turn ''' + + root1 = root1.right + ''' we have visited the node and its right + subtree. Now, it's left subtree's turn ''' + + root2 = root2.left + ''' both the trees have been + completely traversed ''' + + else: + break + ''' tress are mirrors of each other ''' + + return ""Yes"" + '''Driver Code''' + +if __name__ == '__main__': + ''' 1st binary tree formation + 1 ''' + + root1 = newNode(1) + ''' / \ ''' + + root1.left = newNode(3) + ''' 3 2 ''' + + root1.right = newNode(2) + ''' / \ ''' + + root1.right.left = newNode(5) + ''' 5 4 ''' + + root1.right.right = newNode(4) + ''' 2nd binary tree formation + 1 ''' + + root2 = newNode(1) + ''' / \ ''' + + root2.left = newNode(2) + ''' 2 3 ''' + + root2.right = newNode(3) + ''' / \ ''' + + root2.left.left = newNode(4) + '''4 5 ''' + + root2.left.right = newNode(5) + '''function cal''' + + print(areMirrors(root1, root2))" +Find a specific pair in Matrix,"/*A Naive method to find maximum value of mat1[d][e] +- ma[a][b] such that d > a and e > b*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* The function returns maximum value A(d,e) - A(a,b) + over all choices of indexes such that both d > a + and e > b.*/ + + static int findMaxValue(int N,int mat[][]) + { +/* stores maximum value*/ + + int maxValue = Integer.MIN_VALUE; +/* Consider all possible pairs mat[a][b] and + mat1[d][e]*/ + + for (int a = 0; a < N - 1; a++) + for (int b = 0; b < N - 1; b++) + for (int d = a + 1; d < N; d++) + for (int e = b + 1; e < N; e++) + if (maxValue < (mat[d][e] - mat[a][b])) + maxValue = mat[d][e] - mat[a][b]; + return maxValue; + } +/* Driver code*/ + + public static void main (String[] args) + { + int N = 5; + int mat[][] = { + { 1, 2, -1, -4, -20 }, + { -8, -3, 4, 2, 1 }, + { 3, 8, 6, 1, 3 }, + { -4, -1, 1, 7, -6 }, + { 0, -4, 10, -5, 1 } + }; + System.out.print(""Maximum Value is "" + + findMaxValue(N,mat)); + } +}"," '''A Naive method to find maximum +value of mat[d][e] - mat[a][b] +such that d > a and e > b''' + +N = 5 + '''The function returns maximum +value A(d,e) - A(a,b) over +all choices of indexes such +that both d > a and e > b.''' + +def findMaxValue(mat): + ''' stores maximum value''' + + maxValue = 0 + ''' Consider all possible pairs + mat[a][b] and mat[d][e]''' + + for a in range(N - 1): + for b in range(N - 1): + for d in range(a + 1, N): + for e in range(b + 1, N): + if maxValue < int (mat[d][e] - + mat[a][b]): + maxValue = int(mat[d][e] - + mat[a][b]); + return maxValue; + '''Driver Code''' + +mat = [[ 1, 2, -1, -4, -20 ], + [ -8, -3, 4, 2, 1 ], + [ 3, 8, 6, 1, 3 ], + [ -4, -1, 1, 7, -6 ], + [ 0, -4, 10, -5, 1 ]]; +print(""Maximum Value is "" + + str(findMaxValue(mat)))" +Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix,"/*Java implementation of Naive method +to count of negative numbers in +M[n][m]*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG { + static int countNegative(int M[][], int n, + int m) + { + int count = 0; +/* Follow the path shown using + arrows above*/ + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (M[i][j] < 0) + count += 1; +/* no more negative numbers + in this row*/ + + else + break; + } + } + return count; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int M[][] = { { -3, -2, -1, 1 }, + { -2, 2, 3, 4 }, + { 4, 5, 7, 8 } }; + System.out.println(countNegative(M, 3, 4)); + } +}"," '''Python implementation of Naive method to count of +negative numbers in M[n][m]''' + +def countNegative(M, n, m): + count = 0 + ''' Follow the path shown using arrows above''' + + for i in range(n): + for j in range(m): + if M[i][j] < 0: + count += 1 + else: + ''' no more negative numbers in this row''' + + break + return count + '''Driver code''' + +M = [ + [-3, -2, -1, 1], + [-2, 2, 3, 4], + [ 4, 5, 7, 8] + ] +print(countNegative(M, 3, 4))" +Maximum difference between node and its ancestor in Binary Tree,"/* Java program to find maximum difference between node + and its ancestor */ + +/*A binary tree node has key, pointer to left +and right child*/ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +/* Class Res created to implement pass by reference + of 'res' variable */ + +class Res +{ + int r = Integer.MIN_VALUE; +} +public class BinaryTree +{ + Node root; + /* Recursive function to calculate maximum ancestor-node + difference in binary tree. It updates value at 'res' + to store the result. The returned value of this function + is minimum value in subtree rooted with 't' */ + + int maxDiffUtil(Node t, Res res) + { + /* Returning Maximum int value if node is not + there (one child case) */ + + if (t == null) + return Integer.MAX_VALUE; + /* If leaf node then just return node's value */ + + if (t.left == null && t.right == null) + return t.key; + /* Recursively calling left and right subtree + for minimum value */ + + int val = Math.min(maxDiffUtil(t.left, res), + maxDiffUtil(t.right, res)); + /* Updating res if (node value - minimum value + from subtree) is bigger than res */ + + res.r = Math.max(res.r, t.key - val); + /* Returning minimum value got so far */ + + return Math.min(val, t.key); + } + /* This function mainly calls maxDiffUtil() */ + + int maxDiff(Node root) + { +/* Initialising result with minimum int value*/ + + Res res = new Res(); + maxDiffUtil(root, res); + return res.r; + } + /* Helper function to print inorder traversal of + binary tree */ + + void inorder(Node root) + { + if (root != null) + { + inorder(root.left); + System.out.print(root.key + """"); + inorder(root.right); + } + } +/* Driver program to test the above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); +/* Making above given diagram's binary tree*/ + + tree.root = new Node(8); + tree.root.left = new Node(3); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(6); + tree.root.left.right.left = new Node(4); + tree.root.left.right.right = new Node(7); + tree.root.right = new Node(10); + tree.root.right.right = new Node(14); + tree.root.right.right.left = new Node(13); + System.out.println(""Maximum difference between a node and"" + + "" its ancestor is : "" + tree.maxDiff(tree.root)); + } +}"," '''Python3 program to find maximum difference +between node and its ancestor''' + +_MIN = -2147483648 +_MAX = 2147483648 + '''Helper function that allocates a new +node with the given data and None left +and right poers. ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = None + self.right = None ''' +Recursive function to calculate maximum +ancestor-node difference in binary tree. +It updates value at 'res' to store the +result. The returned value of this function +is minimum value in subtree rooted with 't' ''' + +def maxDiffUtil(t, res): + ''' Returning Maximum value if node + is not there (one child case) ''' + + if (t == None): + return _MAX, res + ''' If leaf node then just return + node's value ''' + + if (t.left == None and t.right == None): + return t.key, res + ''' Recursively calling left and right + subtree for minimum value ''' + + a, res = maxDiffUtil(t.left, res) + b, res = maxDiffUtil(t.right, res) + val = min(a, b) + ''' Updating res if (node value - minimum + value from subtree) is bigger than res ''' + + res = max(res, t.key - val) + ''' Returning minimum value got so far ''' + + return min(val, t.key), res + ''' This function mainly calls maxDiffUtil() ''' + +def maxDiff(root): + ''' Initialising result with minimum value''' + + res = _MIN + x, res = maxDiffUtil(root, res) + return res + ''' Helper function to print inorder +traversal of binary tree ''' + +def inorder(root): + if (root): + inorder(root.left) + prf(""%d "", root.key) + inorder(root.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' + Let us create Binary Tree shown + in above example ''' + + root = newNode(8) + root.left = newNode(3) + root.left.left = newNode(1) + root.left.right = newNode(6) + root.left.right.left = newNode(4) + root.left.right.right = newNode(7) + root.right = newNode(10) + root.right.right = newNode(14) + root.right.right.left = newNode(13) + print(""Maximum difference between a node and"", + ""its ancestor is :"", maxDiff(root))" +Program to check if an array is sorted or not (Iterative and Recursive),"/*Java Recursive approach to check if an +Array is sorted or not*/ + +class GFG { + +/* Function that returns true if array is + sorted in non-decreasing order.*/ + + static boolean arraySortedOrNot(int a[], int n) + { +/* base case*/ + + if (n == 1 || n == 0) + return true; + +/* check if present index and index + previous to it are in correct order + and rest of the array is also sorted + if true then return true else return + false*/ + + return a[n - 1] >= a[n - 2] + && arraySortedOrNot(a, n - 1); + } + +/* Driver code*/ + + public static void main(String[] args) + { + + int arr[] = { 20, 23, 23, 45, 78, 88 }; + int n = arr.length; + +/* Function Call*/ + + if (arraySortedOrNot(arr, n)) + System.out.print(""Yes""); + else + System.out.print(""No""); + } +} + + +"," '''Python3 recursive program to check +if an Array is sorted or not''' + + + '''Function that returns true if array +is sorted in non-decreasing order.''' + +def arraySortedOrNot(arr, n): + + ''' Base case''' + + if (n == 0 or n == 1): + return True + + ''' Check if present index and index + previous to it are in correct order + and rest of the array is also sorted + if true then return true else return + false''' + + return (arr[n - 1] >= arr[n - 2] and + arraySortedOrNot(arr, n - 1)) + + '''Driver code''' + +arr = [ 20, 23, 23, 45, 78, 88 ] +n = len(arr) + + '''Function Call''' + +if (arraySortedOrNot(arr, n)): + print(""Yes"") +else: + print(""No"") + + +" +Construct a special tree from given preorder traversal,"/*Java program to construct a binary tree from preorder traversal*/ + + /*A Binary Tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class Index +{ + int index = 0; +} +class BinaryTree +{ + Node root; + Index myindex = new Index();/* A recursive function to create a Binary Tree from given pre[] + preLN[] arrays. The function returns root of tree. index_ptr is used + to update index values in recursive calls. index must be initially + passed as 0 */ + + Node constructTreeUtil(int pre[], char preLN[], Index index_ptr, + int n, Node temp) + { +/* store the current value of index in pre[]*/ + + int index = index_ptr.index; +/* Base Case: All nodes are constructed*/ + + if (index == n) + return null; +/* Allocate memory for this node and increment index for + subsequent recursive calls*/ + + temp = new Node(pre[index]); + (index_ptr.index)++; +/* If this is an internal node, construct left and right subtrees + and link the subtrees*/ + + if (preLN[index] == 'N') + { + temp.left = constructTreeUtil(pre, preLN, index_ptr, n, + temp.left); + temp.right = constructTreeUtil(pre, preLN, index_ptr, n, + temp.right); + } + return temp; + } +/* A wrapper over constructTreeUtil()*/ + + Node constructTree(int pre[], char preLN[], int n, Node node) + { +/* Initialize index as 0. Value of index is used in recursion to + maintain the current index in pre[] and preLN[] arrays.*/ + + int index = 0; + return constructTreeUtil(pre, preLN, myindex, n, node); + } + /* This function is used only for testing */ + + void printInorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.data + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } +/* driver function to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + int pre[] = new int[]{10, 30, 20, 5, 15}; + char preLN[] = new char[]{'N', 'N', 'L', 'L', 'L'}; + int n = pre.length; + Node mynode = tree.constructTree(pre, preLN, n, tree.root); + System.out.println(""Following is Inorder Traversal of the"" + + ""Constructed Binary Tree: ""); + tree.printInorder(mynode); + } +}"," '''A program to construct Binary +Tree from preorder traversal ''' + '''Utility function to create a +new Binary Tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''A recursive function to create a +Binary Tree from given pre[] preLN[] +arrays. The function returns root of +tree. index_ptr is used to update +index values in recursive calls. index +must be initially passed as 0 ''' + +def constructTreeUtil(pre, preLN, index_ptr, n): + '''store the current value ''' + + index = index_ptr[0] + ''' of index in pre[] + Base Case: All nodes are constructed ''' + + if index == n: + return None + ''' Allocate memory for this node and + increment index for subsequent + recursive calls ''' + + temp = newNode(pre[index]) + index_ptr[0] += 1 + ''' If this is an internal node, construct left + and right subtrees and link the subtrees ''' + + if preLN[index] == 'N': + temp.left = constructTreeUtil(pre, preLN, + index_ptr, n) + temp.right = constructTreeUtil(pre, preLN, + index_ptr, n) + return temp + '''A wrapper over constructTreeUtil() ''' + +def constructTree(pre, preLN, n): + ''' Initialize index as 0. Value of index is + used in recursion to maintain the current + index in pre[] and preLN[] arrays. ''' + + index = [0] + return constructTreeUtil(pre, preLN, index, n) + '''This function is used only for testing ''' + +def printInorder (node): + if node == None: + return + ''' first recur on left child''' + + printInorder (node.left) + ''' then print the data of node''' + + print(node.data,end="" "") + ''' now recur on right child ''' + + printInorder (node.right) + '''Driver Code''' + +if __name__ == '__main__': + root = None + pre = [10, 30, 20, 5, 15] + preLN = ['N', 'N', 'L', 'L', 'L'] + n = len(pre) + root = constructTree (pre, preLN, n) + print(""Following is Inorder Traversal of"", + ""the Constructed Binary Tree:"") + printInorder (root)" +"Write a program to calculate pow(x,n)","/*Java program for the above approach*/ + +import java.io.*; +class GFG { + public static int power(int x, int y) + { +/* If x^0 return 1*/ + + if (y == 0) + return 1; +/* If we need to find of 0^y*/ + + if (x == 0) + return 0; +/* For all other cases*/ + + return x * power(x, y - 1); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int x = 2; + int y = 3; + System.out.println(power(x, y)); + } +}"," '''Python3 program for the above approach''' + +def power(x, y): + ''' If x^0 return 1''' + + if (y == 0): + return 1 + ''' If we need to find of 0^y''' + + if (x == 0): + return 0 + ''' For all other cases''' + + return x * power(x, y - 1) + '''Driver Code''' + +x = 2 +y = 3 +print(power(x, y))" +Minimum number of swaps required to sort an array,"/*Java program to find +minimum number of swaps +required to sort an array*/ + +import java.util.*; +import java.io.*; +class GfG +{ +/*swap function*/ + + public void swap(int[] arr, int i, int j) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } +/*indexOf function*/ + + public int indexOf(int[] arr, int ele) + { + for (int i = 0; i < arr.length; i++) + { + if (arr[i] == ele) { + return i; + } + } + return -1; + }/* Return the minimum number + of swaps required to sort the array*/ + + public int minSwaps(int[] arr, int N) + { + int ans = 0; + int[] temp = Arrays.copyOfRange(arr, 0, N); + Arrays.sort(temp); + for (int i = 0; i < N; i++) + { +/* This is checking whether + the current element is + at the right place or not*/ + + if (arr[i] != temp[i]) + { + ans++; +/* Swap the current element + with the right index + so that arr[0] to arr[i] is sorted*/ + + swap(arr, i, indexOf(arr, temp[i])); + } + } + return ans; + } + +} +/*Driver class*/ + +class Main +{ +/* Driver program to test + the above function*/ + + public static void main(String[] args) + throws Exception + { + int[] a + = { 101, 758, 315, 730, 472, + 619, 460, 479 }; + int n = a.length; +/* Output will be 5*/ + + System.out.println(new GfG().minSwaps(a, n)); + } +}"," '''Python3 program to find +minimum number of swaps +required to sort an array''' + '''swap function''' + +def swap(arr, i, j): + temp = arr[i] + arr[i] = arr[j] + arr[j] = temp '''indexOf function''' + +def indexOf(arr, ele): + for i in range(len(arr)): + if (arr[i] == ele): + return i + return -1 '''Return the minimum number +of swaps required to sort +the array''' + +def minSwaps(arr, N): + ans = 0 + temp = arr.copy() + temp.sort() + for i in range(N): + ''' This is checking whether + the current element is + at the right place or not''' + + if (arr[i] != temp[i]): + ans += 1 + ''' Swap the current element + with the right index + so that arr[0] to arr[i] + is sorted''' + + swap(arr, i, + indexOf(arr, temp[i])) + return ans + + + '''Driver code''' + +if __name__ == ""__main__"": + a = [101, 758, 315, 730, + 472, 619, 460, 479] + n = len(a) + ''' Output will be 5''' + + print(minSwaps(a, n))" +"Given a binary tree, how do you remove all the half nodes?","/*Java program to remove half nodes*/ + + +/*Binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +}/*For inorder traversal*/ + +class BinaryTree +{ + Node root; + void printInorder(Node node) + { + if (node != null) + { + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); + } + }/* Removes all nodes with only one child and returns + new root (note that root may change)*/ + + Node RemoveHalfNodes(Node node) + { + if (node == null) + return null; + node.left = RemoveHalfNodes(node.left); + node.right = RemoveHalfNodes(node.right); + if (node.left == null && node.right == null) + return node; + /* if current nodes is a half node with left + child NULL left, then it's right child is + returned and replaces it in the given tree */ + + if (node.left == null) + { + Node new_root = node.right; + return new_root; + } + /* if current nodes is a half node with right + child NULL right, then it's right child is + returned and replaces it in the given tree */ + + if (node.right == null) + { + Node new_root = node.left; + return new_root; + } + return node; + } +/* Driver program*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + Node NewRoot = null; + tree.root = new Node(2); + tree.root.left = new Node(7); + tree.root.right = new Node(5); + tree.root.left.right = new Node(6); + tree.root.left.right.left = new Node(1); + tree.root.left.right.right = new Node(11); + tree.root.right.right = new Node(9); + tree.root.right.right.left = new Node(4); + System.out.println(""the inorder traversal of tree is ""); + tree.printInorder(tree.root); + NewRoot = tree.RemoveHalfNodes(tree.root); + System.out.print(""\nInorder traversal of the modified tree \n""); + tree.printInorder(NewRoot); + } +}"," '''Python program to remove all half nodes''' + + '''A binary tree node''' + +class Node: + def __init__(self , data): + self.data = data + self.left = None + self.right = None + '''For inorder traversal''' + +def printInorder(root): + if root is not None: + printInorder(root.left) + print root.data, + printInorder(root.right) + '''Removes all nodes with only one child and returns +new root(note that root may change)''' + +def RemoveHalfNodes(root): + if root is None: + return None + root.left = RemoveHalfNodes(root.left) + root.right = RemoveHalfNodes(root.right) + if root.left is None and root.right is None: + return root + + ''' If current nodes is a half node with left child + None then it's right child is returned and + replaces it in the given tree''' + + if root.left is None: + new_root = root.right + temp = root + root = None + del(temp) + return new_root + + ''' if current nodes is a half node with right + child NULL right, then it's right child is + returned and replaces it in the given tree ''' + + if root.right is None: + new_root = root.left + temp = root + root = None + del(temp) + return new_root + return root '''Driver Program''' + +root = Node(2) +root.left = Node(7) +root.right = Node(5) +root.left.right = Node(6) +root.left.right.left = Node(1) +root.left.right.right = Node(11) +root.right.right = Node(9) +root.right.right.left = Node(4) +print ""Inorder traversal of given tree"" +printInorder(root) +NewRoot = RemoveHalfNodes(root) +print ""\nInorder traversal of the modified tree"" +printInorder(NewRoot)" +Subarray/Substring vs Subsequence and Programs to Generate them,"/* Java code to generate all possible subsequences. + Time Complexity O(n * 2^n) */ + +import java.math.BigInteger; +class Test +{ + static int arr[] = new int[]{1, 2, 3, 4}; + static void printSubsequences(int n) + { + /* Number of subsequences is (2**n -1)*/ + + int opsize = (int)Math.pow(2, n); + /* Run from counter 000..1 to 111..1*/ + + for (int counter = 1; counter < opsize; counter++) + { + for (int j = 0; j < n; j++) + { + /* Check if jth bit in the counter is set + If set then print jth element from arr[] */ + + if (BigInteger.valueOf(counter).testBit(j)) + System.out.print(arr[j]+"" ""); + } + System.out.println(); + } + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.println(""All Non-empty Subsequences""); + printSubsequences(arr.length); + } +}"," '''Python3 code to generate all +possible subsequences. +Time Complexity O(n * 2 ^ n)''' + +import math +def printSubsequences(arr, n) : + ''' Number of subsequences is (2**n -1)''' + + opsize = math.pow(2, n) + ''' Run from counter 000..1 to 111..1''' + + for counter in range( 1, (int)(opsize)) : + for j in range(0, n) : + ''' Check if jth bit in the counter + is set If set then print jth + element from arr[]''' + + if (counter & (1< 0) + { + Node temp = blockHead; + for (int i = 1; temp.next.next!=null && + i < k - 1; i++) + temp = temp.next; + blockTail.next = blockHead; + tail = temp; + return rotateHelper(blockTail, temp, + d - 1, k); + } + +/* Rotate anti-Clockwise*/ + + if (d < 0) + { + blockTail.next = blockHead; + tail = blockHead; + return rotateHelper(blockHead.next, + blockHead, d + 1, k); + } + return blockHead; +} + +/*Function to rotate the linked list block wise*/ + +static Node rotateByBlocks(Node head, + int k, int d) +{ +/* If length is 0 or 1 return head*/ + + if (head == null || head.next == null) + return head; + +/* if degree of rotation is 0, return head*/ + + if (d == 0) + return head; + + Node temp = head; + tail = null; + +/* Traverse upto last element of this block*/ + + int i; + for (i = 1; temp.next != null && i < k; i++) + temp = temp.next; + +/* storing the first node of next block*/ + + Node nextBlock = temp.next; + +/* If nodes of this block are less than k. + Rotate this block also*/ + + if (i < k) + head = rotateHelper(head, temp, d % k, + i); + else + head = rotateHelper(head, temp, d % k, + k); + +/* Append the new head of next block to + the tail of this block*/ + + tail.next = rotateByBlocks(nextBlock, k, + d % k); + +/* return head of updated Linked List*/ + + return head; +} + +/* UTILITY FUNCTIONS */ + +/* Function to push a node */ + +static Node 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; + return head_ref; + +} + +/* Function to print linked list */ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.next; + } +} + +/* Driver code*/ + +public static void main(String[] args) +{ + + /* Start with the empty list */ + + Node head = null; + +/* create a list 1.2.3.4.5. + 6.7.8.9.null*/ + + for (int i = 9; i > 0; i -= 1) + head = push(head, i); + System.out.print(""Given linked list \n""); + printList(head); + +/* k is block size and d is number of + rotations in every block.*/ + + int k = 3, d = 2; + head = rotateByBlocks(head, k, d); + System.out.print(""\nRotated by blocks Linked list \n""); + printList(head); +} +} + + +"," '''Python3 program to rotate a linked +list block wise''' + + + '''Link list node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Recursive function to rotate one block''' + +def rotateHelper(blockHead, blockTail, + d, tail, k): + if (d == 0): + return blockHead, tail + + ''' Rotate Clockwise''' + + if (d > 0): + temp = blockHead + i = 1 + while temp.next.next != None and i < k - 1: + temp = temp.next + i += 1 + blockTail.next = blockHead + tail = temp + return rotateHelper(blockTail, temp, + d - 1, tail, k) + + ''' Rotate anti-Clockwise''' + + if (d < 0): + blockTail.next = blockHead + tail = blockHead + return rotateHelper(blockHead.next, + blockHead, d + 1, + tail, k) + + '''Function to rotate the linked list block wise''' + +def rotateByBlocks(head, k, d): + + ''' If length is 0 or 1 return head''' + + if (head == None or head.next == None): + return head + + ''' If degree of rotation is 0, return head''' + + if (d == 0): + return head + temp = head + tail = None + + ''' Traverse upto last element of this block''' + + i = 1 + while temp.next != None and i < k: + temp = temp.next + i += 1 + + ''' Storing the first node of next block''' + + nextBlock = temp.next + + ''' If nodes of this block are less than k. + Rotate this block also''' + + if (i < k): + head, tail = rotateHelper(head, temp, d % k, + tail, i) + else: + head, tail = rotateHelper(head, temp, d % k, + tail, k) + + ''' Append the new head of next block to + the tail of this block''' + + tail.next = rotateByBlocks(nextBlock, k, + d % k); + + ''' Return head of updated Linked List''' + + return head; + + '''UTILITY FUNCTIONS''' + + + '''Function to push a node''' + +def push(head_ref, new_data): + + new_node = Node(new_data) + new_node.data = new_data + new_node.next = (head_ref) + (head_ref) = new_node + return head_ref '''Function to print linked list''' + +def printList(node): + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Start with the empty list''' + + head = None + + ''' Create a list 1.2.3.4.5. + 6.7.8.9.None''' + + for i in range(9, 0, -1): + head = push(head, i) + print(""Given linked list "") + printList(head) + + ''' k is block size and d is number of + rotations in every block.''' + + k = 3 + d = 2 + head = rotateByBlocks(head, k, d) + + print(""\nRotated by blocks Linked list "") + printList(head) + + +" +Tracking current Maximum Element in a Stack,"/*Java program to keep track of maximum +element in a stack */ + +import java.util.*; +class GfG { +static class StackWithMax +{ +/* main stack */ + + static Stack mainStack = new Stack (); +/* tack to keep track of max element */ + + static Stack trackStack = new Stack (); +static void push(int x) + { + mainStack.push(x); + if (mainStack.size() == 1) + { + trackStack.push(x); + return; + } +/* If current element is greater than + the top element of track stack, push + the current element to track stack + otherwise push the element at top of + track stack again into it. */ + + if (x > trackStack.peek()) + trackStack.push(x); + else + trackStack.push(trackStack.peek()); + } + static int getMax() + { + return trackStack.peek(); + } + static void pop() + { + mainStack.pop(); + trackStack.pop(); + } +}; +/*Driver program to test above functions */ + +public static void main(String[] args) +{ + StackWithMax s = new StackWithMax(); + s.push(20); + System.out.println(s.getMax()); + s.push(10); + System.out.println(s.getMax()); + s.push(50); + System.out.println(s.getMax()); +} +}"," '''Python3 program to keep track of +maximum element in a stack ''' + +class StackWithMax: + def __init__(self): + ''' main stack ''' + + self.mainStack = [] + ''' tack to keep track of + max element ''' + + self.trackStack = [] + def push(self, x): + self.mainStack.append(x) + if (len(self.mainStack) == 1): + self.trackStack.append(x) + return + ''' If current element is greater than + the top element of track stack, + append the current element to track + stack otherwise append the element + at top of track stack again into it. ''' + + if (x > self.trackStack[-1]): + self.trackStack.append(x) + else: + self.trackStack.append(self.trackStack[-1]) + def getMax(self): + return self.trackStack[-1] + def pop(self): + self.mainStack.pop() + self.trackStack.pop() + '''Driver Code''' + +if __name__ == '__main__': + s = StackWithMax() + s.push(20) + print(s.getMax()) + s.push(10) + print(s.getMax()) + s.push(50) + print(s.getMax())" +The Celebrity Problem,," '''Python3 program to find celebrity +of persons in the party + ''' '''Max ''' + +N = 8 + '''Person with 2 is celebrity''' + +MATRIX = [[0, 0, 1, 0], + [0, 0, 1, 0], + [0, 0, 0, 0], + [0, 0, 1, 0]] +def knows(a, b): + return MATRIX[a][b] + '''Returns -1 if a potential celebrity +is not present. If present, +returns id (value from 0 to n-1).''' + +def findPotentialCelebrity(n): + ''' Base case''' + + if (n == 0): + return 0; + ''' Find the celebrity with n-1 + persons''' + + id_ = findPotentialCelebrity(n - 1) + ''' If there are no celebrities''' + + if (id_ == -1): + return n - 1 + ''' if the id knows the nth person + then the id cannot be a celebrity, but nth person + could be on''' + + elif knows(id_, n - 1): + return n - 1 + ''' if the id knows the nth person + then the id cannot be a celebrity, but nth person + could be one''' + + elif knows(n - 1, id_): + return id_ + ''' If there is no celebrity''' + + return - 1 + '''Returns -1 if celebrity +is not present. If present, +returns id (value from 0 to n-1). +a wrapper over findCelebrity''' + +def Celebrity(n): + ''' Find the celebrity''' + + id_=findPotentialCelebrity(n) + ''' Check if the celebrity found + is really the celebrity''' + + if (id_ == -1): + return id_ + else: + c1=0 + c2=0 + ''' Check the id is really the + celebrity''' + + for i in range(n): + if (i != id_): + c1 += knows(id_, i) + c2 += knows(i, id_) + ''' If the person is known to + everyone.''' + + if (c1 == 0 and c2 == n - 1): + return id_ + return -1 + '''Driver code''' + +if __name__ == '__main__': + n=4 + id_=Celebrity(n) + if id_ == -1: + print(""No celebrity"") + else: + print(""Celebrity ID"", id_)" +Eulerian Path in undirected graph,"/*Efficient Java program to +find out Eulerian path*/ + +import java.util.*; +class GFG +{ +/* Function to find out the path + It takes the adjacency matrix + representation of the graph as input*/ + + static void findpath(int[][] graph, int n) + { + Vector numofadj = new Vector<>(); +/* Find out number of edges each vertex has*/ + + for (int i = 0; i < n; i++) + numofadj.add(accumulate(graph[i], 0)); +/* Find out how many vertex has odd number edges*/ + + int startPoint = 0, numofodd = 0; + for (int i = n - 1; i >= 0; i--) + { + if (numofadj.elementAt(i) % 2 == 1) + { + numofodd++; + startPoint = i; + } + } +/* If number of vertex with odd number of edges + is greater than two return ""No Solution"".*/ + + if (numofodd > 2) + { + System.out.println(""No Solution""); + return; + } +/* If there is a path find the path + Initialize empty stack and path + take the starting current as discussed*/ + + Stack stack = new Stack<>(); + Vector path = new Vector<>(); + int cur = startPoint; +/* Loop will run until there is element in the stack + or current edge has some neighbour.*/ + + while (!stack.isEmpty() || accumulate(graph[cur], 0) != 0) + { +/* If current node has not any neighbour + add it to path and pop stack + set new current to the popped element*/ + + if (accumulate(graph[cur], 0) == 0) + { + path.add(cur); + cur = stack.pop(); +/* If the current vertex has at least one + neighbour add the current vertex to stack, + remove the edge between them and set the + current to its neighbour.*/ + + } + else + { + for (int i = 0; i < n; i++) + { + if (graph[cur][i] == 1) + { + stack.add(cur); + graph[cur][i] = 0; + graph[i][cur] = 0; + cur = i; + break; + } + } + } + } +/* print the path*/ + + for (int ele : path) + System.out.print(ele + "" -> ""); + System.out.println(cur); + } + static int accumulate(int[] arr, int sum) + { + for (int i : arr) + sum += i; + return sum; + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Test case 1*/ + + int[][] graph1 = { { 0, 1, 0, 0, 1 }, + { 1, 0, 1, 1, 0 }, + { 0, 1, 0, 1, 0 }, + { 0, 1, 1, 0, 0 }, + { 1, 0, 0, 0, 0 } }; + int n = graph1.length; + findpath(graph1, n); +/* Test case 2*/ + + int[][] graph2 = { { 0, 1, 0, 1, 1 }, + { 1, 0, 1, 0, 1 }, + { 0, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 0 }, + { 1, 0, 1, 0, 0 } }; + n = graph2.length; + findpath(graph2, n); +/* Test case 3*/ + + int[][] graph3 = { { 0, 1, 0, 0, 1 }, + { 1, 0, 1, 1, 1 }, + { 0, 1, 0, 1, 0 }, + { 0, 1, 1, 0, 1 }, + { 1, 1, 0, 1, 0 } }; + n = graph3.length; + findpath(graph3, n); + } +}"," '''Efficient Python3 program to +find out Eulerian path + ''' '''Function to find out the path +It takes the adjacency matrix +representation of the graph as input''' + +def findpath(graph, n): + numofadj = [] + ''' Find out number of edges each + vertex has''' + + for i in range(n): + numofadj.append(sum(graph[i])) + ''' Find out how many vertex has + odd number edges''' + + startpoint, numofodd = 0, 0 + for i in range(n - 1, -1, -1): + if (numofadj[i] % 2 == 1): + numofodd += 1 + startpoint = i + ''' If number of vertex with odd number of edges + is greater than two return ""No Solution"".''' + + if (numofodd > 2): + print(""No Solution"") + return + ''' If there is a path find the path + Initialize empty stack and path + take the starting current as discussed''' + + stack = [] + path = [] + cur = startpoint + ''' Loop will run until there is element in the + stack or current edge has some neighbour.''' + + while (len(stack) > 0 or sum(graph[cur])!= 0): + ''' If current node has not any neighbour + add it to path and pop stack set new + current to the popped element''' + + if (sum(graph[cur]) == 0): + path.append(cur) + cur = stack[-1] + del stack[-1] + ''' If the current vertex has at least one + neighbour add the current vertex to stack, + remove the edge between them and set the + current to its neighbour.''' + + else: + for i in range(n): + if (graph[cur][i] == 1): + stack.append(cur) + graph[cur][i] = 0 + graph[i][cur] = 0 + cur = i + break + ''' Print the path''' + + for ele in path: + print(ele, end = "" -> "") + print(cur) + '''Driver Code''' + +if __name__ == '__main__': + ''' Test case 1''' + + graph1 = [ [ 0, 1, 0, 0, 1 ], + [ 1, 0, 1, 1, 0 ], + [ 0, 1, 0, 1, 0 ], + [ 0, 1, 1, 0, 0 ], + [ 1, 0, 0, 0, 0 ] ] + n = len(graph1) + findpath(graph1, n) + ''' Test case 2''' + + graph2 = [ [ 0, 1, 0, 1, 1 ], + [ 1, 0, 1, 0, 1 ], + [ 0, 1, 0, 1, 1 ], + [ 1, 1, 1, 0, 0 ], + [ 1, 0, 1, 0, 0 ] ] + n = len(graph2) + findpath(graph2, n) + ''' Test case 3''' + + graph3 = [ [ 0, 1, 0, 0, 1 ], + [ 1, 0, 1, 1, 1 ], + [ 0, 1, 0, 1, 0 ], + [ 0, 1, 1, 0, 1 ], + [ 1, 1, 0, 1, 0 ] ] + n = len(graph3) + findpath(graph3, n)" +Growable array based stack,"/*Java Program to implement growable array based stack +using tight strategy*/ + +class GFG +{ +/*constant amount at which stack is increased*/ + +static final int BOUND = 4; +/*top of the stack*/ + +static int top = -1; +/*length of stack*/ + +static int length = 0; +/*function to create new stack*/ + +static int[] create_new(int[] a) +{ +/* allocate memory for new stack*/ + + int[] new_a = new int[length + BOUND]; +/* copying the content of old stack*/ + + for (int i = 0; i < length; i++) + new_a[i] = a[i]; +/* re-sizing the length*/ + + length += BOUND; + return new_a; +} +/*function to push new element*/ + +static int[] push(int[] a, int element) +{ +/* if stack is full, create new one*/ + + if (top == length - 1) + a = create_new(a); +/* insert element at top of the stack*/ + + a[++top] = element; + return a; +} +/*function to pop an element*/ + +static void pop(int[] a) +{ + top--; +} +/*function to display*/ + +static void display(int[] a) +{ +/* if top is -1, that means stack is empty*/ + + if (top == -1) + System.out.println(""Stack is Empty""); + else + { + System.out.print(""Stack: ""); + for (int i = 0; i <= top; i++) + System.out.print(a[i] + "" ""); + System.out.println(); + } +} +/*Driver Code*/ + +public static void main(String args[]) +{ +/* creating initial stack*/ + + int []a = create_new(new int[length + BOUND]); +/* pushing element to top of stack*/ + + a = push(a, 1); + a = push(a, 2); + a = push(a, 3); + a = push(a, 4); + display(a); +/* pushing more element when stack is full*/ + + a = push(a, 5); + a = push(a, 6); + display(a); + a = push(a, 7); + a = push(a, 8); + display(a); +/* pushing more element so that stack can grow*/ + + a = push(a, 9); + display(a); +} +}"," '''Python3 Program to implement growable array based stack +using tight strategy + ''' '''constant amount at which stack is increased''' + +BOUND = 4 + '''top of the stack''' + +top = -1; +a = [] + '''length of stack''' + +length = 0; + '''function to create new stack''' + +def create_new(): + global length; + ''' allocate memory for new stack''' + + new_a = [0 for i in range(length + BOUND)]; + ''' copying the content of old stack''' + + for i in range(length): + new_a[i] = a[i]; + ''' re-sizing the length''' + + length += BOUND; + return new_a + '''function to push new element''' + +def push( element): + global top, a + ''' if stack is full, create new one''' + + if (top == length - 1): + a = create_new(); + top +=1 + ''' insert element at top of the stack''' + + a[top] = element; + return a; + '''function to pop an element''' + +def pop(): + global top + top -= 1; + '''function to display''' + +def display(): + global top + ''' if top is -1, that means stack is empty''' + + if (top == -1): + print(""Stack is Empty"") + else: + print(""Stack: "", end = '') + for i in range(top + 1): + print(a[i], end = ' ') + print() + '''Driver Code''' + +if __name__=='__main__': + ''' creating initial stack''' + + a = create_new(); + ''' pushing element to top of stack''' + + push(1); + push(2); + push(3); + push(4); + display(); + ''' pushing more element when stack is full''' + + push(5); + push(6); + display(); + push(7); + push(8); + display(); + ''' pushing more element so that stack can grow''' + + push( 9); + display();" +Sort the given matrix,"/*Java implementation to +sort the given matrix*/ + +import java.io.*; +import java.util.*; +class GFG { + static int SIZE = 10; +/* function to sort the given matrix*/ + + static void sortMat(int mat[][], int n) + { +/* temporary matrix of size n^2*/ + + int temp[] = new int[n * n]; + int k = 0; +/* copy the elements of matrix + one by one into temp[]*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + temp[k++] = mat[i][j]; +/* sort temp[]*/ + + Arrays.sort(temp); +/* copy the elements of temp[] + one by one in mat[][]*/ + + k = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + mat[i][j] = temp[k++]; + } +/* function to print the given matrix*/ + + static void printMat(int mat[][], int n) + { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + System.out.print( mat[i][j] + "" ""); + System.out.println(); + } + } +/* Driver program to test above*/ + + public static void main(String args[]) + { + int mat[][] = { { 5, 4, 7 }, + { 1, 3, 8 }, + { 2, 9, 6 } }; + int n = 3; + System.out.println(""Original Matrix:""); + printMat(mat, n); + sortMat(mat, n); + System.out.println(""Matrix After Sorting:""); + printMat(mat, n); + } +}"," '''Python3 implementation to sort +the given matrix''' + +SIZE = 10 + '''Function to sort the given matrix''' + +def sortMat(mat, n) : + ''' Temporary matrix of size n^2''' + + temp = [0] * (n * n) + k = 0 + ''' Copy the elements of matrix + one by one into temp[]''' + + for i in range(0, n) : + for j in range(0, n) : + temp[k] = mat[i][j] + k += 1 + ''' sort temp[]''' + + temp.sort() + ''' copy the elements of temp[] + one by one in mat[][]''' + + k = 0 + for i in range(0, n) : + for j in range(0, n) : + mat[i][j] = temp[k] + k += 1 + '''Function to print the given matrix''' + +def printMat(mat, n) : + for i in range(0, n) : + for j in range( 0, n ) : + print(mat[i][j] , end = "" "") + print() + '''Driver program to test above''' + +mat = [ [ 5, 4, 7 ], + [ 1, 3, 8 ], + [ 2, 9, 6 ] ] +n = 3 +print( ""Original Matrix:"") +printMat(mat, n) +sortMat(mat, n) +print(""\nMatrix After Sorting:"") +printMat(mat, n)" +Delete all odd or even positioned nodes from Circular Linked List,"/*Java program to delete all even and odd position +nodes from Singly Circular Linked list*/ + +class GFG +{ + +/*structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function return number of nodes present in list*/ + +static int Length(Node head) +{ + Node current = head; + int count = 0; + +/* if list is empty simply return length zero*/ + + if (head == null) + { + return 0; + } + +/* traverse forst to last node*/ + + else + { + do + { + current = current.next; + count++; + } while (current != head); + } + return count; +} + +/*Function print data of list*/ + +static void Display( Node head) +{ + Node current = head; + +/* if list is empty simply show message*/ + + if (head == null) + { + System.out.printf(""\nDisplay List is empty\n""); + return; + } + +/* traverse forst to last node*/ + + else + { + do + { + System.out.printf(""%d "", current.data); + current = current.next; + } while (current != head); + } +} + +/* Function to insert a node at the end of +a Circular linked list */ + +static Node Insert(Node head, int data) +{ + Node current = head; +/* Create a new node*/ + + Node newNode = new Node(); + +/* check node is created or not*/ + + if (newNode == null) + { + System.out.printf(""\nMemory Error\n""); + return null; + } + +/* insert data into newly created node*/ + + newNode.data = data; + +/* check list is empty + if not have any node then + make first node it*/ + + if (head == null) + { + newNode.next = newNode; + head = newNode; + return head; + } + +/* if list have already some node*/ + + else + { +/* move firt node to last node*/ + + while (current.next != head) + { + current = current.next; + } + +/* put first or head node address in new node link*/ + + newNode.next = head; + +/* put new node address into last node link(next)*/ + + current.next = newNode; + } + return head; +} + +/*Utitlity function to delete a Node*/ + +static Node deleteNode(Node head_ref, Node del) +{ + Node temp = head_ref; + +/* If node to be deleted is head node*/ + + if (head_ref == del) + { + head_ref = del.next; + } + +/* traverse list till not found + delete node*/ + + while (temp.next != del) + { + temp = temp.next; + } + +/* copy address of node*/ + + temp.next = del.next; + return head_ref; +} + +/*Function to delete First node of +Circular Linked List*/ + +static Node DeleteFirst(Node head) +{ + Node previous = head, next = head; +/* check list have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return head; + } + +/* check list have single node + if yes then delete it and return*/ + + if (previous.next == previous) + { + head = null; + return head; + } + +/* traverse second to first*/ + + while (previous.next != head) + { + previous = previous.next; + next = previous.next; + } + +/* now previous is last node and + next is first node of list + first node(next) link address + put in last node(previous) link*/ + + previous.next = next.next; + +/* make second node as head node*/ + + head = previous.next; + return head; +} + +/*Function to delete odd position nodes*/ + +static Node DeleteAllOddNode(Node head) +{ + int len = Length(head); + int count = 0; + Node previous = head, next = head; + +/* check list have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nDelete Last List is empty\n""); + return null; + } + +/* if list have single node means + odd position then delete it*/ + + if (len == 1) + { + head = DeleteFirst(head); + return head; + } + +/* traverse first to last if + list have more than one node*/ + + while (len > 0) + { +/* delete first position node + which is odd position*/ + + if (count == 0) + { + +/* Function to delete first node*/ + + head = DeleteFirst(head); + } + +/* check position is odd or not + if yes then delete node + Note: Considered 1 based indexing*/ + + if (count % 2 == 0 && count != 0) + { + head = deleteNode(head, previous); + } + + previous = previous.next; + next = previous.next; + + len--; + count++; + } + return head; +} + +/*Function to delete all even position nodes*/ + +static Node DeleteAllEvenNode( Node head) +{ +/* Take size of list*/ + + int len = Length(head); + + int count = 1; + Node previous = head, next = head; + +/* Check list is empty + if empty simply return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return null; + } + +/* if list have single node + then return*/ + + if (len < 2) + { + return null; + } + +/* make first node is previous*/ + + previous = head; + +/* make second node is current*/ + + next = previous.next; + + while (len > 0) + { + +/* check node number is even + if node is even then + delete that node*/ + + if (count % 2 == 0) + { + previous.next = next.next; + previous = next.next; + next = previous.next; + } + + len--; + count++; + } + return head; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; + head = Insert(head, 99); + head = Insert(head, 11); + head = Insert(head, 22); + head = Insert(head, 33); + head = Insert(head, 44); + head = Insert(head, 55); + head = Insert(head, 66); + +/* Deleting Odd positioned nodes*/ + + System.out.printf(""Initial List: ""); + Display(head); + + System.out.printf(""\nAfter deleting Odd position nodes: ""); + head = DeleteAllOddNode(head); + Display(head); + +/* Deleting Even positioned nodes*/ + + System.out.printf(""\n\nInitial List: ""); + Display(head); + + System.out.printf(""\nAfter deleting even position nodes: ""); + head = DeleteAllEvenNode(head); + Display(head); +} +} + + +", +How to check if two given sets are disjoint?,"/*Java program to check if two sets are disjoint*/ + +public class disjoint1 +{ +/* Returns true if set1[] and set2[] are + disjoint, else false*/ + + boolean aredisjoint(int set1[], int set2[]) + { +/* Take every element of set1[] and + search it in set2*/ + + for (int i = 0; i < set1.length; i++) + { + for (int j = 0; j < set2.length; j++) + { + if (set1[i] == set2[j]) + return false; + } + } +/* If no element of set1 is present in set2*/ + + return true; + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + disjoint1 dis = new disjoint1(); + int set1[] = { 12, 34, 11, 9, 3 }; + int set2[] = { 7, 2, 1, 5 }; + boolean result = dis.aredisjoint(set1, set2); + if (result) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''A Simple python 3 program to check +if two sets are disjoint + ''' '''Returns true if set1[] and set2[] are disjoint, else false''' + +def areDisjoint(set1, set2, m, n): + ''' Take every element of set1[] and search it in set2''' + + for i in range(0, m): + for j in range(0, n): + if (set1[i] == set2[j]): + return False + ''' If no element of set1 is present in set2''' + + return True + '''Driver program''' + +set1 = [12, 34, 11, 9, 3] +set2 = [7, 2, 1, 5] +m = len(set1) +n = len(set2) +print(""yes"") if areDisjoint(set1, set2, m, n) else("" No"")" +Count pairs from two sorted arrays whose sum is equal to a given value x,"/*Java implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value*/ + +import java.io.*; +class GFG { +/*function to search 'value' +in the given array 'arr[]' +it uses binary search technique +as 'arr[]' is sorted*/ + +static boolean isPresent(int arr[], int low, + int high, int value) +{ + while (low <= high) + { + int mid = (low + high) / 2; +/* value found*/ + + if (arr[mid] == value) + return true; + else if (arr[mid] > value) + high = mid - 1; + else + low = mid + 1; + } +/* value not found*/ + + return false; +} +/*function to count all pairs +from both the sorted arrays +whose sum is equal to a given +value*/ + +static int countPairs(int arr1[], int arr2[], + int m, int n, int x) +{ + int count = 0; + for (int i = 0; i < m; i++) + { +/* for each arr1[i]*/ + + int value = x - arr1[i]; +/* check if the 'value' + is present in 'arr2[]'*/ + + if (isPresent(arr2, 0, n - 1, value)) + count++; + } +/* required count of pairs*/ + + return count; +} +/* Driver Code*/ + + public static void main (String[] args) + { + int arr1[] = {1, 3, 5, 7}; + int arr2[] = {2, 3, 5, 8}; + int m = arr1.length; + int n = arr2.length; + int x = 10; + System.out.println(""Count = "" + + countPairs(arr1, arr2, m, n, x)); + } +}"," '''Python 3 implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value + ''' '''function to search 'value' +in the given array 'arr[]' +it uses binary search technique +as 'arr[]' is sorted''' + +def isPresent(arr, low, high, value): + while (low <= high): + mid = (low + high) // 2 + ''' value found''' + + if (arr[mid] == value): + return True + elif (arr[mid] > value) : + high = mid - 1 + else: + low = mid + 1 + ''' value not found''' + + return False + '''function to count all pairs +from both the sorted arrays +whose sum is equal to a given +value''' + +def countPairs(arr1, arr2, m, n, x): + count = 0 + for i in range(m): + ''' for each arr1[i]''' + + value = x - arr1[i] + ''' check if the 'value' + is present in 'arr2[]''' + ''' + if (isPresent(arr2, 0, n - 1, value)): + count += 1 + ''' required count of pairs ''' + + return count + '''Driver Code''' + +if __name__ == ""__main__"": + arr1 = [1, 3, 5, 7] + arr2 = [2, 3, 5, 8] + m = len(arr1) + n = len(arr2) + x = 10 + print(""Count = "", + countPairs(arr1, arr2, m, n, x))" +Repeatedly search an element by doubling it after every successful search,"/*Java program to repeatedly search an element by +doubling it after every successful search*/ + +import java.util.Arrays; +public class Test4 { + + static int findElement(int a[], int n, int b) + { +/* Sort the given array so that binary search + can be applied on it*/ + + Arrays.sort(a); + +/*Maximum array element*/ + +int max = a[n - 1]; + + while (b < max) { + +/* search for the element b present or + not in array*/ + + if (Arrays.binarySearch(a, b) > -1) + b *= 2; + else + return b; + } + + return b; + } + +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 1, 2, 3 }; + int n = a.length; + int b = 1; + System.out.println(findElement(a, n, b)); + } +} + +"," '''Python program to repeatedly search an element by +doubling it after every successful search''' + + +def binary_search(a, x, lo = 0, hi = None): + if hi is None: + hi = len(a) + while lo < hi: + mid = (lo + hi)//2 + midval = a[mid] + if midval < x: + lo = mid + 1 + elif midval > x: + hi = mid + else: + return mid + return -1 + +def findElement(a, n, b): + + ''' Sort the given array so that binary search + can be applied on it''' + + a.sort() + + '''Maximum array element''' + + mx = a[n - 1] + while (b < max): + + ''' search for the element b present or + not in array''' + + if (binary_search(a, b, 0, n) != -1): + b *= 2 + else: + return b + return b + + '''Driver code''' + +a = [ 1, 2, 3 ] +n = len(a) +b = 1 +print findElement(a, n, b) + + +" +Lexicographically minimum string rotation | Set 1,"/*A simple Java program to find +lexicographically minimum rotation +of a given String*/ + +import java.util.*; + +class GFG +{ + +/* This functionr return lexicographically + minimum rotation of str*/ + + static String minLexRotation(String str) + { +/* Find length of given String*/ + + int n = str.length(); + +/* Create an array of strings + to store all rotations*/ + + String arr[] = new String[n]; + +/* Create a concatenation of + String with itself*/ + + String concat = str + str; + +/* One by one store all rotations + of str in array. A rotation is + obtained by getting a substring of concat*/ + + for (int i = 0; i < n; i++) + { + arr[i] = concat.substring(i, i + n); + } + +/* Sort all rotations*/ + + Arrays.sort(arr); + +/* Return the first rotation + from the sorted array*/ + + return arr[0]; + } + +/* Driver code*/ + + public static void main(String[] args) + { + System.out.println(minLexRotation(""GEEKSFORGEEKS"")); + System.out.println(minLexRotation(""GEEKSQUIZ"")); + System.out.println(minLexRotation(""BCABDADAB"")); + } +} + + +"," '''A simple Python3 program to find lexicographically +minimum rotation of a given string''' + + + '''This function return lexicographically minimum +rotation of str''' + +def minLexRotation(str_) : + + ''' Find length of given string''' + + n = len(str_) + + ''' Create an array of strings to store all rotations''' + + arr = [0] * n + + ''' Create a concatenation of string with itself''' + + concat = str_ + str_ + + ''' One by one store all rotations of str in array. + A rotation is obtained by getting a substring of concat''' + + for i in range(n) : + arr[i] = concat[i : n + i] + + ''' Sort all rotations''' + + arr.sort() + + ''' Return the first rotation from the sorted array''' + + return arr[0] + + '''Driver Code''' + +print(minLexRotation(""GEEKSFORGEEKS"")) +print(minLexRotation(""GEEKSQUIZ"")) +print(minLexRotation(""BCABDADAB"")) + + +" +Find subarray with given sum | Set 2 (Handles Negative Numbers),"/*Java program to print subarray with sum as given sum*/ + +import java.util.*; +class GFG { + +/*Function to print subarray with sum as given sum*/ + + public static void subArraySum(int[] arr, int n, int sum) {/* cur_sum to keep track of cummulative sum till that point*/ + + int cur_sum = 0; + int start = 0; + int end = -1; + HashMap hashMap = new HashMap<>(); + for (int i = 0; i < n; i++) { + cur_sum = cur_sum + arr[i]; +/* check whether cur_sum - sum = 0, if 0 it means + the sub array is starting from index 0- so stop*/ + + if (cur_sum - sum == 0) { + start = 0; + end = i; + break; + } +/* if hashMap already has the value, means we already + have subarray with the sum - so stop*/ + + if (hashMap.containsKey(cur_sum - sum)) { + start = hashMap.get(cur_sum - sum) + 1; + end = i; + break; + } +/* if value is not present then add to hashmap*/ + + hashMap.put(cur_sum, i); + } +/* if end is -1 : means we have reached end without the sum*/ + + if (end == -1) { + System.out.println(""No subarray with given sum exists""); + } else { + System.out.println(""Sum found between indexes "" + + start + "" to "" + end); + } + } +/* Driver code*/ + + public static void main(String[] args) { + int[] arr = {10, 2, -2, -20, 10}; + int n = arr.length; + int sum = -10; + subArraySum(arr, n, sum); + } +}"," '''Python3 program to print subarray with sum as given sum''' + + '''Function to print subarray with sum as given sum''' + +def subArraySum(arr, n, Sum): ''' create an empty map''' + + Map = {} + curr_sum = 0 + for i in range(0,n): + curr_sum = curr_sum + arr[i] ''' if curr_sum is equal to target sum + we found a subarray starting from index 0 + and ending at index i''' + + if curr_sum == Sum: + print(""Sum found between indexes 0 to"", i) + return + ''' If curr_sum - sum already exists in map + we have found a subarray with target sum''' + + if (curr_sum - Sum) in Map: + print(""Sum found between indexes"", \ + Map[curr_sum - Sum] + 1, ""to"", i) + return + + ''' if value is not present then add to hashmap''' + + Map[curr_sum] = i ''' If we reach here, then no subarray exists''' + + print(""No subarray with given sum exists"") + '''Driver program to test above function''' + +if __name__ == ""__main__"": + arr = [10, 2, -2, -20, 10] + n = len(arr) + Sum = -10 + subArraySum(arr, n, Sum)" +Print Common Nodes in Two Binary Search Trees,"/*Java program of iterative traversal based method to +find common elements in two BSTs.*/ + +import java.util.*; +class GfG { +/*A BST node */ + +static class Node +{ + int key; + Node left, right; +} +/*A utility function to create a new node */ + +static Node newNode(int ele) +{ + Node temp = new Node(); + temp.key = ele; + temp.left = null; + temp.right = null; + return temp; +} +/*Function two print common elements in given two trees */ + +static void printCommon(Node root1, Node root2) +{ + +/* Create two stacks for two inorder traversals*/ + + Stack s1 = new Stack (); + Stack s2 = new Stack (); + while (true) + { /* push the Nodes of first tree in stack s1 */ + + if (root1 != null) + { + s1.push(root1); + root1 = root1.left; + } +/* push the Nodes of second tree in stack s2 */ + + else if (root2 != null) + { + s2.push(root2); + root2 = root2.left; + } +/* Both root1 and root2 are NULL here */ + + else if (!s1.isEmpty() && !s2.isEmpty()) + { + root1 = s1.peek(); + root2 = s2.peek(); +/* If current keys in two trees are same */ + + if (root1.key == root2.key) + { + System.out.print(root1.key + "" ""); + s1.pop(); + s2.pop(); +/* move to the inorder successor */ + + root1 = root1.right; + root2 = root2.right; + } + else if (root1.key < root2.key) + { +/* If Node of first tree is smaller, than that of + second tree, then its obvious that the inorder + successors of current Node can have same value + as that of the second tree Node. Thus, we pop + from s2 */ + + s1.pop(); + root1 = root1.right; +/* root2 is set to NULL, because we need + new Nodes of tree 1 */ + + root2 = null; + } + else if (root1.key > root2.key) + { + s2.pop(); + root2 = root2.right; + root1 = null; + } + } +/* Both roots and both stacks are empty */ + + else break; + } +} +/*A utility function to do inorder traversal */ + +static void inorder(Node root) +{ + if (root != null) + { + inorder(root.left); + System.out.print(root.key + "" ""); + inorder(root.right); + } +} +/* A utility function to insert a new Node with given key in BST */ + +static Node insert(Node node, int key) +{ + /* If the tree is empty, return a new Node */ + + if (node == null) return newNode(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + node.left = insert(node.left, key); + else if (key > node.key) + node.right = insert(node.right, key); + /* return the (unchanged) Node pointer */ + + return node; +} +/*Driver program */ + +public static void main(String[] args) +{ +/* Create first tree as shown in example */ + + Node root1 = null; + root1 = insert(root1, 5); + root1 = insert(root1, 1); + root1 = insert(root1, 10); + root1 = insert(root1, 0); + root1 = insert(root1, 4); + root1 = insert(root1, 7); + root1 = insert(root1, 9); +/* Create second tree as shown in example */ + + Node root2 = null; + root2 = insert(root2, 10); + root2 = insert(root2, 7); + root2 = insert(root2, 20); + root2 = insert(root2, 4); + root2 = insert(root2, 9); + System.out.print(""Tree 1 : "" + ""\n""); + inorder(root1); + System.out.println(); + System.out.print(""Tree 2 : "" + ""\n""); + inorder(root2); + System.out.println(); + System.out.println(""Common Nodes: ""); + printCommon(root1, root2); +} +}"," '''Python3 program of iterative traversal based +method to find common elements in two BSTs. ''' + + '''A utility function to create a new node ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None '''Function two print common elements +in given two trees ''' + +def printCommon(root1, root2): + ''' Create two stacks for two inorder + traversals ''' + + s1 = [] + s2 = [] + while 1: + ''' append the Nodes of first + tree in stack s1 ''' + + if root1: + s1.append(root1) + root1 = root1.left + ''' append the Nodes of second tree + in stack s2 ''' + + elif root2: + s2.append(root2) + root2 = root2.left + ''' Both root1 and root2 are NULL here ''' + + elif len(s1) != 0 and len(s2) != 0: + root1 = s1[-1] + root2 = s2[-1] + ''' If current keys in two trees are same ''' + + if root1.key == root2.key: + print(root1.key, end = "" "") + s1.pop(-1) + s2.pop(-1) + ''' move to the inorder successor ''' + + root1 = root1.right + root2 = root2.right + elif root1.key < root2.key: + ''' If Node of first tree is smaller, than + that of second tree, then its obvious + that the inorder successors of current + Node can have same value as that of the + second tree Node. Thus, we pop from s2 ''' + + s1.pop(-1) + root1 = root1.right + ''' root2 is set to NULL, because we need + new Nodes of tree 1 ''' + + root2 = None + elif root1.key > root2.key: + s2.pop(-1) + root2 = root2.right + root1 = None + ''' Both roots and both stacks are empty ''' + + else: + break + '''A utility function to do inorder traversal ''' + +def inorder(root): + if root: + inorder(root.left) + print(root.key, end = "" "") + inorder(root.right) + '''A utility function to insert a new Node +with given key in BST ''' + +def insert(node, key): + ''' If the tree is empty, return a new Node ''' + + if node == None: + return newNode(key) + ''' Otherwise, recur down the tree ''' + + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + ''' return the (unchanged) Node pointer ''' + + return node + '''Driver Code ''' + +if __name__ == '__main__': + ''' Create first tree as shown in example ''' + + root1 = None + root1 = insert(root1, 5) + root1 = insert(root1, 1) + root1 = insert(root1, 10) + root1 = insert(root1, 0) + root1 = insert(root1, 4) + root1 = insert(root1, 7) + root1 = insert(root1, 9) + ''' Create second tree as shown in example ''' + + root2 = None + root2 = insert(root2, 10) + root2 = insert(root2, 7) + root2 = insert(root2, 20) + root2 = insert(root2, 4) + root2 = insert(root2, 9) + print(""Tree 1 : "") + inorder(root1) + print() + print(""Tree 2 : "") + inorder(root2) + print() + print(""Common Nodes: "") + printCommon(root1, root2)" +Compute sum of digits in all numbers from 1 to n,"/*JAVA program to compute sum of digits +in numbers from 1 to n*/ + +import java.io.*; +import java.math.*; +class GFG{ +/* Function to computer sum of digits in + numbers from 1 to n*/ + static int sumOfDigitsFrom1ToNUtil(int n, int a[]) + { + if (n < 10) + return (n * (n + 1) / 2); + int d = (int)(Math.log10(n)); + int p = (int)(Math.ceil(Math.pow(10, d))); + int msd = n / p; + return (msd * a[d] + (msd * (msd - 1) / 2) * p + + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)); + } + static int sumOfDigitsFrom1ToN(int n) + { + int d = (int)(Math.log10(n)); + int a[] = new int[d+1]; + a[0] = 0; a[1] = 45; + for (int i = 2; i <= d; i++) + a[i] = a[i-1] * 10 + 45 * + (int)(Math.ceil(Math.pow(10, i-1))); + return sumOfDigitsFrom1ToNUtil(n, a); + } + +/* Driver Program*/ + + public static void main(String args[]) + { + int n = 328; + System.out.println(""Sum of digits in numbers "" + + ""from 1 to "" +n + "" is "" + + sumOfDigitsFrom1ToN(n)); + } +}"," '''Python program to compute sum of digits +in numbers from 1 to n''' + +import math + '''Function to computer sum of digits in +numbers from 1 to n''' +def sumOfDigitsFrom1ToNUtil(n, a): + if (n < 10): + return (n * (n + 1)) // 2 + d = int(math.log(n,10)) + p = int(math.ceil(pow(10, d))) + msd = n // p + return (msd * a[d] + (msd * (msd - 1) // 2) * p + + msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a)) +def sumOfDigitsFrom1ToN(n): + d = int(math.log(n, 10)) + a = [0]*(d + 1) + a[0] = 0 + a[1] = 45 + for i in range(2, d + 1): + a[i] = a[i - 1] * 10 + 45 * \ + int(math.ceil(pow(10, i - 1))) + return sumOfDigitsFrom1ToNUtil(n, a) + + '''Driver code''' + +n = 328 +print(""Sum of digits in numbers from 1 to"",n,""is"",sumOfDigitsFrom1ToN(n))" +Print all triplets in sorted array that form AP,"/*Java implementation to print +all the triplets in given array +that form Arithmetic Progression*/ + +import java.io.*; +class GFG +{ +/* Function to print all triplets in + given sorted array that forms AP*/ + + static void findAllTriplets(int arr[], int n) + { + for (int i = 1; i < n - 1; i++) + { +/* Search other two elements + of AP with arr[i] as middle.*/ + + for (int j = i - 1, k = i + 1; j >= 0 && k < n;) + { +/* if a triplet is found*/ + + if (arr[j] + arr[k] == 2 * arr[i]) + { + System.out.println(arr[j] +"" "" + + arr[i]+ "" "" + arr[k]); +/* Since elements are distinct, + arr[k] and arr[j] cannot form + any more triplets with arr[i]*/ + + k++; + j--; + } +/* If middle element is more move to + higher side, else move lower side.*/ + + else if (arr[j] + arr[k] < 2 * arr[i]) + k++; + else + j--; + } + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = { 2, 6, 9, 12, 17, + 22, 31, 32, 35, 42 }; + int n = arr.length; + findAllTriplets(arr, n); + } +}"," '''python 3 program to print all triplets in given +array that form Arithmetic Progression + ''' '''Function to print all triplets in +given sorted array that forms AP''' + +def printAllAPTriplets(arr, n): + for i in range(1, n - 1): + ''' Search other two elements of + AP with arr[i] as middle.''' + + j = i - 1 + k = i + 1 + while(j >= 0 and k < n ): + ''' if a triplet is found''' + + if (arr[j] + arr[k] == 2 * arr[i]): + print(arr[j], """", arr[i], """", arr[k]) + ''' Since elements are distinct, + arr[k] and arr[j] cannot form + any more triplets with arr[i]''' + + k += 1 + j -= 1 + ''' If middle element is more move to + higher side, else move lower side.''' + + elif (arr[j] + arr[k] < 2 * arr[i]): + k += 1 + else: + j -= 1 + '''Driver code''' + +arr = [ 2, 6, 9, 12, 17, + 22, 31, 32, 35, 42 ] +n = len(arr) +printAllAPTriplets(arr, n)" +Length of the longest valid substring,"/*Java program to find length of the longest valid +substring*/ + +import java.util.Stack; +class Test +{ +/* method to get length of the longest valid*/ + + static int findMaxLen(String str) + { + int n = str.length(); +/* Create a stack and push -1 + as initial index to it.*/ + + Stack stk = new Stack<>(); + stk.push(-1); +/* Initialize result*/ + + int result = 0; +/* Traverse all characters of given string*/ + + for (int i = 0; i < n; i++) + { +/* If opening bracket, push index of it*/ + + if (str.charAt(i) == '(') + stk.push(i); +/*If closing bracket, i.e.,str[i] = ')' +*/ + + else + { +/* Pop the previous + opening bracket's index*/ + + if(!stk.empty()) + stk.pop(); +/* Check if this length + formed with base of + current valid substring + is more than max + so far*/ + + if (!stk.empty()) + result + = Math.max(result, + i - stk.peek()); +/* If stack is empty. push + current index as base + for next valid substring (if any)*/ + + else + stk.push(i); + } + } + return result; + } +/* Driver code*/ + + public static void main(String[] args) + { + String str = ""((()()""; +/* Function call*/ + + System.out.println(findMaxLen(str)); + str = ""()(()))))""; +/* Function call*/ + + System.out.println(findMaxLen(str)); + } +}"," '''Python program to find length of the longest valid +substring''' + + + '''method to get length of + the longest valid''' + +def findMaxLen(string): + n = len(string) ''' Create a stack and push -1 + as initial index to it.''' + + stk = [] + stk.append(-1) + ''' Initialize result''' + + result = 0 + ''' Traverse all characters of given string''' + + for i in xrange(n): + ''' If opening bracket, push index of it''' + + if string[i] == '(': + stk.append(i) + ''' If closing bracket''' + else: + ''' Pop the previous opening bracket's index''' + + if len(stk) != 0: + stk.pop() + ''' Check if this length formed with base of + current valid substring is more than max + so far''' + + if len(stk) != 0: + result = max(result, + i - stk[len(stk)-1]) + ''' If stack is empty. push current index as + base for next valid substring (if any)''' + + else: + stk.append(i) + return result + '''Driver code''' + +string = ""((()()"" + '''Function call''' + +print findMaxLen(string) +string = ""()(()))))"" + '''Function call''' + +print findMaxLen(string)" +Row wise sorting in 2D array,"/*Java code to sort 2D matrix row-wise*/ + +import java.io.*; +public class Sort2DMatrix { + static int sortRowWise(int m[][]) + { +/* loop for rows of matrix*/ + + for (int i = 0; i < m.length; i++) { +/* loop for column of matrix*/ + + for (int j = 0; j < m[i].length; j++) { +/* loop for comparison and swapping*/ + + for (int k = 0; k < m[i].length - j - 1; k++) { + if (m[i][k] > m[i][k + 1]) { +/* swapping of elements*/ + + int t = m[i][k]; + m[i][k] = m[i][k + 1]; + m[i][k + 1] = t; + } + } + } + } +/* printing the sorted matrix*/ + + for (int i = 0; i < m.length; i++) { + for (int j = 0; j < m[i].length; j++) + System.out.print(m[i][j] + "" ""); + System.out.println(); + } + return 0; + } +/* driver code*/ + + public static void main(String args[]) + { + int m[][] = { { 9, 8, 7, 1 }, + { 7, 3, 0, 2 }, + { 9, 5, 3, 2 }, + { 6, 3, 1, 2 } }; + sortRowWise(m); + } +}"," '''Python3 code to sort 2D matrix row-wise''' + +def sortRowWise(m): + ''' loop for rows of matrix''' + + for i in range(len(m)): + ''' loop for column of matrix''' + + for j in range(len(m[i])): + ''' loop for comparison and swapping''' + + for k in range(len(m[i]) - j - 1): + if (m[i][k] > m[i][k + 1]): + ''' swapping of elements''' + + t = m[i][k] + m[i][k] = m[i][k + 1] + m[i][k + 1] = t + ''' printing the sorted matrix''' + + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end="" "") + print() + '''Driver code''' + +m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2],[ 6, 3, 1, 2 ]] +sortRowWise(m)" +Find whether a given number is a power of 4 or not,"/*Java program to check +if given number is +power of 4 or not*/ + +import java.io.*; +class GFG +{ + + /*Function to check if x is power of 4*/ + + static int isPowerOfFour(int n) + { + int count = 0;/*Check if there is + only one bit set in n*/ + + int x = n & (n - 1); + if ( n > 0 && x == 0) + { + /* count 0 bits + before set bit */ + + while(n > 1) + { + n >>= 1; + count += 1; + } + /*If count is even + then return true + else false*/ + + return (count % 2 == 0) ? 1 : 0; + } + /* If there are more than + 1 bit set then n is not a + power of 4*/ + + return 0; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int test_no = 64; + if(isPowerOfFour(test_no)>0) + System.out.println(test_no + + "" is a power of 4""); + else + System.out.println(test_no + + "" is not a power of 4""); + } +}"," '''Python3 program to check if given +number is power of 4 or not''' + '''Function to check if x is power of 4''' + +def isPowerOfFour(n): + count = 0 + ''' Check if there is only one + bit set in n''' + + if (n and (not(n & (n - 1)))): + ''' count 0 bits before set bit''' + + while(n > 1): + n >>= 1 + count += 1 + ''' If count is even then return + true else false''' + + if(count % 2 == 0): + return True + else: + return False + '''Driver code''' + +test_no = 64 +if(isPowerOfFour(64)): + print(test_no, 'is a power of 4') +else: + print(test_no, 'is not a power of 4') +" +Construct Tree from given Inorder and Preorder traversals,"/* Java program to construct tree using inorder + and preorder traversals */ + +import java.io.*; +import java.util.*; +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +class Node +{ + char data; + Node left,right; + Node(char item) + { + data = item; + left = right = null; + } +} +class Tree +{ + public static Node root; +/* Store indexes of all items so that we + we can quickly find later*/ + + static HashMap mp = new HashMap<>(); + static int preIndex = 0; + /* Recursive function to construct binary of size + len from Inorder traversal in[] and Preorder traversal + pre[]. Initial values of inStrt and inEnd should be + 0 and len -1. The function doesn't do any error + checking for cases where inorder and preorder + do not form a tree */ + + public static Node buildTree(char[] in, char[] pre, int inStrt, int inEnd) + { + if(inStrt > inEnd) + { + return null; + } + /* Pick current node from Preorder traversal using preIndex + and increment preIndex */ + + char curr = pre[preIndex++]; + Node tNode; + tNode = new Node(curr); + /* If this node has no children then return */ + + if (inStrt == inEnd) + { + return tNode; + } + /* Else find the index of this node in Inorder traversal */ + + int inIndex = mp.get(curr); + /* Using index in Inorder traversal, construct left and + right subtress */ + + tNode.left = buildTree(in, pre, inStrt, inIndex - 1); + tNode.right = buildTree(in, pre, inIndex + 1, inEnd); + return tNode; + } +/* This function mainly creates an unordered_map, then + calls buildTree()*/ + + public static Node buldTreeWrap(char[] in, char[] pre, int len) + { + for(int i = 0; i < len; i++) + { + mp.put(in[i], i); + } + return buildTree(in, pre, 0, len - 1); + } + /* This funtcion is here just to test buildTree() */ + + static void printInorder(Node node) + { + if(node == null) + { + return; + } + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); + } + /* Driver code */ + + public static void main (String[] args) + { + char[] in = {'D', 'B', 'E', 'A', 'F', 'C'}; + char[] pre = {'A', 'B', 'D', 'E', 'C', 'F'}; + int len = in.length; + Tree.root=buldTreeWrap(in, pre, len); + /* Let us test the built tree by printing + Insorder traversal */ + + System.out.println(""Inorder traversal of the constructed tree is""); + printInorder(root); + } +}"," '''Python3 program to construct tree using inorder +and preorder traversals''' + + '''A binary tree node has data, poer to left child +and a poer to right child''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None '''Recursive function to construct binary of size +len from Inorder traversal in[] and Preorder traversal +pre[]. Initial values of inStrt and inEnd should be +0 and len -1. The function doesn't do any error +checking for cases where inorder and preorder +do not form a tree''' + +def buildTree(inn, pre, inStrt, inEnd): + global preIndex, mp + if (inStrt > inEnd): + return None + ''' Pick current node from Preorder traversal + using preIndex and increment preIndex''' + + curr = pre[preIndex] + preIndex += 1 + tNode = Node(curr) + ''' If this node has no children then return''' + + if (inStrt == inEnd): + return tNode + ''' Else find the index of this + node in Inorder traversal''' + + inIndex = mp[curr] + ''' Using index in Inorder traversal, + construct left and right subtress''' + + tNode.left = buildTree(inn, pre, inStrt, + inIndex - 1) + tNode.right = buildTree(inn, pre, inIndex + 1, + inEnd) + return tNode + '''This function mainly creates an +unordered_map, then calls buildTree()''' + +def buldTreeWrap(inn, pre, lenn): + global mp + for i in range(lenn): + mp[inn[i]] = i + return buildTree(inn, pre, 0, lenn - 1) '''This funtcion is here just to test buildTree()''' + +def prInorder(node): + if (node == None): + return + prInorder(node.left) + print(node.data, end = "" "") + prInorder(node.right) + '''Driver code''' + +if __name__ == '__main__': + mp = {} + preIndex = 0 + inn = [ 'D', 'B', 'E', 'A', 'F', 'C' ] + pre = [ 'A', 'B', 'D', 'E', 'C', 'F' ] + lenn = len(inn) + root = buldTreeWrap(inn, pre,lenn) + ''' Let us test the built tree by pring + Insorder traversal''' + + print(""Inorder traversal of "" + ""the constructed tree is"") + prInorder(root)" +Find pairs in array whose sums already exist in array,"/*A simple Java program to find +pair whose sum already exists +in array*/ + +import java.io.*; +public class GFG { +/* Function to find pair whose + sum exists in arr[]*/ + + static void findPair(int[] arr, int n) + { + boolean found = false; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + for (int k = 0; k < n; k++) { + if (arr[i] + arr[j] == arr[k]) { + System.out.println(arr[i] + + "" "" + arr[j]); + found = true; + } + } + } + } + if (found == false) + System.out.println(""Not exist""); + } +/* Driver code*/ + + static public void main(String[] args) + { + int[] arr = {10, 4, 8, 13, 5}; + int n = arr.length; + findPair(arr, n); + } +}"," '''A simple python program to find pair +whose sum already exists in array + ''' '''Function to find pair whose sum +exists in arr[]''' + +def findPair(arr, n): + found = False + for i in range(0, n): + for j in range(i + 1, n): + for k in range(0, n): + if (arr[i] + arr[j] == arr[k]): + print(arr[i], arr[j]) + found = True + if (found == False): + print(""Not exist"") + '''Driver code''' + +if __name__ == '__main__': + arr = [ 10, 4, 8, 13, 5 ] + n = len(arr) + findPair(arr, n)" +Majority Element,"/*Java program to find Majority +element in an array*/ + +import java.io.*; +import java.util.*; +class GFG{ +/*Function to find Majority element +in an array it returns -1 if there +is no majority element */ + +public static int majorityElement(int[] arr, int n) +{ +/* Sort the array in O(nlogn)*/ + + Arrays.sort(arr); + int count = 1, max_ele = -1, + temp = arr[0], ele = 0, + f = 0; + for(int i = 1; i < n; i++) + { +/* Increases the count if the + same element occurs otherwise + starts counting new element*/ + + if (temp == arr[i]) + { + count++; + } + else + { + count = 1; + temp = arr[i]; + } +/* Sets maximum count and stores + maximum occured element so far + if maximum count becomes greater + than n/2 it breaks out setting + the flag*/ + + if (max_ele < count) + { + max_ele = count; + ele = arr[i]; + if (max_ele > (n / 2)) + { + f = 1; + break; + } + } + } +/* Returns maximum occured element + if there is no such element, returns -1*/ + + return (f == 1 ? ele : -1); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; + int n = 7; +/* Function calling*/ + + System.out.println(majorityElement(arr, n)); +} +}"," '''Python3 program to find Majority +element in an array''' + '''Function to find Majority element +in an array +it returns -1 if there is no majority element''' + +def majorityElement(arr, n) : + ''' sort the array in O(nlogn)''' + + arr.sort() + count, max_ele, temp, f = 1, -1, arr[0], 0 + for i in range(1, n) : + ''' increases the count if the same element occurs + otherwise starts counting new element''' + + if(temp == arr[i]) : + count += 1 + else : + count = 1 + temp = arr[i] + ''' sets maximum count + and stores maximum occured element so far + if maximum count becomes greater than n/2 + it breaks out setting the flag''' + + if(max_ele < count) : + max_ele = count + ele = arr[i] + if(max_ele > (n//2)) : + f = 1 + break + ''' returns maximum occured element + if there is no such element, returns -1''' + + if f == 1 : + return ele + else : + return -1 + '''Driver code''' + +arr = [1, 1, 2, 1, 3, 5, 1] +n = len(arr) + '''Function calling''' + +print(majorityElement(arr, n))" +Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array,"/*Java program to find Index of 0 to be replaced with 1 to get +longest continuous sequence of 1s in a binary array*/ + +import java.io.*; +class Binary +{ +/* Returns index of 0 to be replaced with 1 to get longest + continuous sequence of 1s. If there is no 0 in array, then + it returns -1.*/ + + static int maxOnesIndex(int arr[], int n) + { +/*for maximum number of 1 around a zero*/ + +int max_count = 0; +/*for storing result*/ + +int max_index=0; +/*index of previous zero*/ + +int prev_zero = -1; +/*index of previous to previous zero*/ + +int prev_prev_zero = -1; +/* Traverse the input array*/ + + for (int curr=0; curr max_count) + { + max_count = curr - prev_prev_zero; + max_index = prev_zero; + } +/* Update for next iteration*/ + + prev_prev_zero = prev_zero; + prev_zero = curr; + } + } +/* Check for the last encountered zero*/ + + if (n-prev_prev_zero > max_count) + max_index = prev_zero; + return max_index; + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}; + int n = arr.length; + System.out.println(""Index of 0 to be replaced is ""+ + maxOnesIndex(arr, n)); + } +}"," '''Python program to find Index +of 0 to be replaced with 1 to get +longest continuous sequence +of 1s in a binary array + ''' '''Returns index of 0 to be +replaced with 1 to get longest +continuous sequence of 1s. + If there is no 0 in array, then +it returns -1.''' + +def maxOnesIndex(arr,n): + ''' for maximum number of 1 around a zero''' + + max_count = 0 + ''' for storing result ''' + + max_index =0 + ''' index of previous zero''' + + prev_zero = -1 + ''' index of previous to previous zero''' + + prev_prev_zero = -1 + ''' Traverse the input array''' + + for curr in range(n): + ''' If current element is 0, + then calculate the difference + between curr and prev_prev_zero''' + + if (arr[curr] == 0): + ''' Update result if count of + 1s around prev_zero is more''' + + if (curr - prev_prev_zero > max_count): + max_count = curr - prev_prev_zero + max_index = prev_zero + ''' Update for next iteration''' + + prev_prev_zero = prev_zero + prev_zero = curr + ''' Check for the last encountered zero''' + + if (n-prev_prev_zero > max_count): + max_index = prev_zero + return max_index + '''Driver program''' + +arr = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1] +n = len(arr) +print(""Index of 0 to be replaced is "", + maxOnesIndex(arr, n))" +Find sum of non-repeating (distinct) elements in an array,"/*Java Find the sum of all non-repeated +elements in an array*/ +import java.util.Arrays; +public class GFG { +/*Find the sum of all non-repeated elements +in an array*/ + + static int findSum(int arr[], int n) { +/* sort all elements of array*/ + + Arrays.sort(arr); + int sum = arr[0]; + for (int i = 0; i < n-1; i++) { + if (arr[i] != arr[i + 1]) { + sum = sum + arr[i+1]; + } + } + return sum; + } +/*Driver code*/ + + public static void main(String[] args) { + int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; + int n = arr.length; + System.out.println(findSum(arr, n)); + } +}"," '''Python3 Find the sum of all non-repeated +elements in an array''' ''' +Find the sum of all non-repeated elements +in an array''' + +def findSum(arr, n): + ''' sort all elements of array''' + + arr.sort() + sum = arr[0] + for i in range(0,n-1): + if (arr[i] != arr[i+1]): + sum = sum + arr[i+1] + return sum + '''Driver code''' + +def main(): + arr= [1, 2, 3, 1, 1, 4, 5, 6] + n = len(arr) + print(findSum(arr, n)) +if __name__ == '__main__': + main()" +Clockwise rotation of Linked List,"/*Java implementation of the approach*/ + +class GFG +{ + +/* Link list node */ + +static class Node +{ + int data; + Node next; +} + +/* A utility function to push a node */ + +static Node push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list off the new node */ + + new_node.next = (head_ref); + + /* move the head to point to the new node */ + + (head_ref) = new_node; + return head_ref; +} + +/* A utility function to print linked list */ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data + "" -> ""); + node = node.next; + } + System.out.print( ""null""); +} + +/*Function that rotates the given linked list +clockwise by k and returns the updated +head pointer*/ + +static Node rightRotate(Node head, int k) +{ + +/* If the linked list is empty*/ + + if (head == null) + return head; + +/* len is used to store length of the linked list + tmp will point to the last node after this loop*/ + + Node tmp = head; + int len = 1; + while (tmp.next != null) + { + tmp = tmp.next; + len++; + } + +/* If k is greater than the size + of the linked list*/ + + if (k > len) + k = k % len; + +/* Subtract from length to convert + it into left rotation*/ + + k = len - k; + +/* If no rotation needed then + return the head node */ + + if (k == 0 || k == len) + return head; + +/* current will either point to + kth or null after this loop*/ + + Node current = head; + int cnt = 1; + while (cnt < k && current != null) + { + current = current.next; + cnt++; + } + +/* If current is null then k is equal to the + count of nodes in the list + Don't change the list in this case*/ + + if (current == null) + return head; + +/* current points to the kth node*/ + + Node kthnode = current; + +/* Change next of last node to previous head*/ + + tmp.next = head; + +/* Change head to (k+1)th node*/ + + head = kthnode.next; + +/* Change next of kth node to null*/ + + kthnode.next = null; + +/* Return the updated head pointer*/ + + return head; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + + /* The constructed linked list is: + 1.2.3.4.5 */ + + Node head = null; + head = push(head, 5); + head = push(head, 4); + head = push(head, 3); + head = push(head, 2); + head = push(head, 1); + + int k = 2; + +/* Rotate the linked list*/ + + Node updated_head = rightRotate(head, k); + +/* Print the rotated linked list*/ + + printList(updated_head); +} +} + + +"," '''Python3 implementation of the approach''' + + + ''' Link list node ''' + +class Node: + + def __init__(self, data): + self.data = data + self.next = None + + ''' A utility function to push a node ''' + +def push(head_ref, new_data): + + ''' allocate node ''' + + new_node = Node(new_data) + + ''' put in the data ''' + + new_node.data = new_data + + ''' link the old list off the new node ''' + + new_node.next = (head_ref) + + ''' move the head to point to the new node ''' + + (head_ref) = new_node + + return head_ref + + ''' A utility function to print linked list ''' + +def printList(node): + while (node != None): + print(node.data, end=' -> ') + node = node.next + print(""NULL"") + + '''Function that rotates the given linked list +clockwise by k and returns the updated +head pointer''' + +def rightRotate(head, k): + + ''' If the linked list is empty''' + + if (not head): + return head + + ''' len is used to store length of the linked list + tmp will point to the last node after this loop''' + + tmp = head + len = 1 + + while (tmp.next != None): + tmp = tmp.next + len += 1 + + ''' If k is greater than the size + of the linked list''' + + if (k > len): + k = k % len + + ''' Subtract from length to convert + it into left rotation''' + + k = len - k + + ''' If no rotation needed then + return the head node''' + + if (k == 0 or k == len): + return head + + ''' current will either point to + kth or None after this loop''' + + current = head + cnt = 1 + + while (cnt < k and current != None): + current = current.next + cnt += 1 + + ''' If current is None then k is equal to the + count of nodes in the list + Don't change the list in this case''' + + if (current == None): + return head + + ''' current points to the kth node''' + + kthnode = current + + ''' Change next of last node to previous head''' + + tmp.next = head + + ''' Change head to (k+1)th node''' + + head = kthnode.next + + ''' Change next of kth node to None''' + + kthnode.next = None + + ''' Return the updated head pointer''' + + return head + + + '''Driver code''' + +if __name__ == '__main__': + + ''' The constructed linked list is: + 1.2.3.4.5 ''' + + head = None + head = push(head, 5) + head = push(head, 4) + head = push(head, 3) + head = push(head, 2) + head = push(head, 1) + k = 2 + + ''' Rotate the linked list''' + + updated_head = rightRotate(head, k) + + ''' Print the rotated linked list''' + + printList(updated_head) + + +" +Morris traversal for Preorder,"/*Java program to implement Morris preorder traversal +A binary tree node*/ + +class Node { + int data; + Node left, right; + Node(int item) { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; + void morrisTraversalPreorder() + { + morrisTraversalPreorder(root); + } +/* Preorder traversal without recursion and without stack*/ + + void morrisTraversalPreorder(Node node) { + while (node != null) { +/* If left child is null, print the current node data. Move to + right child.*/ + + if (node.left == null) { + System.out.print(node.data + "" ""); + node = node.right; + } else { +/* Find inorder predecessor*/ + + Node current = node.left; + while (current.right != null && current.right != node) { + current = current.right; + } +/* If the right child of inorder predecessor + already points to this node*/ + + if (current.right == node) { + current.right = null; + node = node.right; + } +/* If right child doesn't point to this node, then print + this node and make right child point to this node*/ + + else { + System.out.print(node.data + "" ""); + current.right = node; + node = node.left; + } + } + } + } + void preorder() + { + preorder(root); + } +/* Function for Standard preorder traversal*/ + + void preorder(Node node) { + if (node != null) { + System.out.print(node.data + "" ""); + preorder(node.left); + preorder(node.right); + } + } +/* Driver programs to test above functions*/ + + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.left.left = new Node(8); + tree.root.left.left.right = new Node(9); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(11); + tree.morrisTraversalPreorder(); + System.out.println(""""); + tree.preorder(); + } +}"," '''Python program for Morris Preorder traversal +A binary tree Node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Preorder traversal without +recursion and without stack''' + +def MorrisTraversal(root): + curr = root + while curr: + ''' If left child is null, print the + current node data. And, update + the current pointer to right child.''' + + if curr.left is None: + print(curr.data, end= "" "") + curr = curr.right + else: + ''' Find the inorder predecessor''' + + prev = curr.left + while prev.right is not None and prev.right is not curr: + prev = prev.right + ''' If the right child of inorder + predecessor already points to + the current node, update the + current with it's right child''' + + if prev.right is curr: + prev.right = None + curr = curr.right + ''' else If right child doesn't point + to the current node, then print this + node's data and update the right child + pointer with the current node and update + the current with it's left child''' + + else: + print (curr.data, end="" "") + prev.right = curr + curr = curr.left + '''Function for sStandard preorder traversal''' + +def preorfer(root): + if root : + print(root.data, end = "" "") + preorfer(root.left) + preorfer(root.right) + '''Driver program to test ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left= Node(6) +root.right.right = Node(7) +root.left.left.left = Node(8) +root.left.left.right = Node(9) +root.left.right.left = Node(10) +root.left.right.right = Node(11) +MorrisTraversal(root) +print(""\n"") +preorfer(root)" +Check for star graph,"/*Java program to find whether +given graph is star or not*/ + +import java.io.*; +class GFG +{ +/* define the size of + incidence matrix*/ + + static int size = 4; +/* function to find + star graph*/ + + static boolean checkStar(int mat[][]) + { +/* initialize number of + vertex with deg 1 and n-1*/ + + int vertexD1 = 0, + vertexDn_1 = 0; +/* check for S1*/ + + if (size == 1) + return (mat[0][0] == 0); +/* check for S2*/ + + if (size == 2) + return (mat[0][0] == 0 && + mat[0][1] == 1 && + mat[1][0] == 1 && + mat[1][1] == 0); +/* check for Sn (n>2)*/ + + for (int i = 0; i < size; i++) + { + int degreeI = 0; + for (int j = 0; j < size; j++) + if (mat[i][j] == 1) + degreeI++; + if (degreeI == 1) + vertexD1++; + else if (degreeI == size - 1) + vertexDn_1++; + } + return (vertexD1 == (size - 1) && + vertexDn_1 == 1); + } +/* Driver code*/ + + public static void main(String args[]) + { + int mat[][] = {{0, 1, 1, 1}, + {1, 0, 0, 0}, + {1, 0, 0, 0}, + {1, 0, 0, 0}}; + if (checkStar(mat)) + System.out.print(""Star Graph""); + else + System.out.print(""Not a Star Graph""); + } +}"," '''Python to find whether +given graph is star +or not''' + + '''define the size +of incidence matrix''' + +size = 4 '''def to +find star graph''' + +def checkStar(mat) : + global size + ''' initialize number of + vertex with deg 1 and n-1''' + + vertexD1 = 0 + vertexDn_1 = 0 + ''' check for S1''' + + if (size == 1) : + return (mat[0][0] == 0) + ''' check for S2''' + + if (size == 2) : + return (mat[0][0] == 0 and + mat[0][1] == 1 and + mat[1][0] == 1 and + mat[1][1] == 0) + ''' check for Sn (n>2)''' + + for i in range(0, size) : + degreeI = 0 + for j in range(0, size) : + if (mat[i][j]) : + degreeI = degreeI + 1 + if (degreeI == 1) : + vertexD1 = vertexD1 + 1 + elif (degreeI == size - 1): + vertexDn_1 = vertexDn_1 + 1 + return (vertexD1 == (size - 1) and + vertexDn_1 == 1) + '''Driver code''' + +mat = [[0, 1, 1, 1], + [1, 0, 0, 0], + [1, 0, 0, 0], + [1, 0, 0, 0]] +if(checkStar(mat)) : + print (""Star Graph"") +else : + print (""Not a Star Graph"")" +Print uncommon elements from two sorted arrays,"/*Java program to find uncommon elements +of two sorted arrays*/ + +import java.io.*; + +class GFG { + + static void printUncommon(int arr1[], + int arr2[], int n1, int n2) + { + + int i = 0, j = 0, k = 0; + while (i < n1 && j < n2) { + +/* If not common, print smaller*/ + + if (arr1[i] < arr2[j]) { + System.out.print(arr1[i] + "" ""); + i++; + k++; + } + else if (arr2[j] < arr1[i]) { + System.out.print(arr2[j] + "" ""); + k++; + j++; + } + +/* Skip common element*/ + + else { + i++; + j++; + } + } + +/* printing remaining elements*/ + + while (i < n1) { + System.out.print(arr1[i] + "" ""); + i++; + k++; + } + while (j < n2) { + System.out.print(arr2[j] + "" ""); + j++; + k++; + } + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr1[] = { 10, 20, 30 }; + int arr2[] = { 20, 25, 30, 40, 50 }; + + int n1 = arr1.length; + int n2 = arr2.length; + + printUncommon(arr1, arr2, n1, n2); + } +} + + +"," '''Python 3 program to find uncommon +elements of two sorted arrays''' + + + +def printUncommon(arr1, arr2, n1, n2) : + + i = 0 + j = 0 + k = 0 + while (i < n1 and j < n2) : + + ''' If not common, print smaller''' + + if (arr1[i] < arr2[j]) : + print( arr1[i] , end= "" "") + i = i + 1 + k = k + 1 + + elif (arr2[j] < arr1[i]) : + print( arr2[j] , end= "" "") + k = k + 1 + j = j + 1 + + ''' Skip common element''' + + else : + i = i + 1 + j = j + 1 + + ''' printing remaining elements''' + + while (i < n1) : + print( arr1[i] , end= "" "") + i = i + 1 + k = k + 1 + + while (j < n2) : + print( arr2[j] , end= "" "") + j = j + 1 + k = k + 1 + + + '''Driver code''' + +arr1 = [10, 20, 30] +arr2 = [20, 25, 30, 40, 50] + +n1 = len(arr1) +n2 = len(arr2) + +printUncommon(arr1, arr2, n1, n2) + + + + +" +Search in a row wise and column wise sorted matrix,"/*JAVA Code for Search in a row wise and +column wise sorted matrix*/ + +class GFG { + /* Searches the element x in mat[][]. If the + element is found, then prints its position + and returns true, otherwise prints ""not found"" + and returns false */ + + private static void search(int[][] mat, + int n, int x) + { +/* set indexes for top right element*/ + int i = 0, j = n - 1; + while (i < n && j >= 0) + { + if (mat[i][j] == x) + { + System.out.print(""n Found at "" + + i + "" "" + j); + return; + } + if (mat[i][j] > x) + j--; + + +/*if mat[i][j] < x*/ + +else + i++; + } + System.out.print(""n Element not found""); +/*if ( i==n || j== -1 )*/ + +return; + } +/* driver program to test above function*/ + + public static void main(String[] args) + { + int mat[][] = { { 10, 20, 30, 40 }, + { 15, 25, 35, 45 }, + { 27, 29, 37, 48 }, + { 32, 33, 39, 50 } }; + search(mat, 4, 29); + } +}"," '''Python3 program to search an element +in row-wise and column-wise sorted matrix''' + + '''Searches the element x in mat[][]. If the +element is found, then prints its position +and returns true, otherwise prints ""not found"" +and returns false''' + +def search(mat, n, x): + i = 0 ''' set indexes for top right element''' + + j = n - 1 + while ( i < n and j >= 0 ): + if (mat[i][j] == x ): + print(""n Found at "", i, "", "", j) + return 1 + if (mat[i][j] > x ): + j -= 1 + ''' if mat[i][j] < x''' + + else: + i += 1 + print(""Element not found"") + '''if (i == n || j == -1 )''' + + return 0 + '''Driver Code''' + +mat = [ [10, 20, 30, 40], + [15, 25, 35, 45], + [27, 29, 37, 48], + [32, 33, 39, 50] ] +search(mat, 4, 29)" +Count frequencies of all elements in array in O(1) extra space and O(n) time,"class CountFrequency +{ +/* Function to find counts of all elements present in + arr[0..n-1]. The array elements must be range from + 1 to n*/ + + void printfrequency(int arr[], int n) + { +/* Subtract 1 from every element so that the elements + become in range from 0 to n-1*/ + + for (int j = 0; j < n; j++) + arr[j] = arr[j] - 1; + +/* Use every element arr[i] as index and add 'n' to + element present at arr[i]%n to keep track of count of + occurrences of arr[i]*/ + + for (int i = 0; i < n; i++) + arr[arr[i] % n] = arr[arr[i] % n] + n; + +/* To print counts, simply print the number of times n + was added at index corresponding to every element*/ + + for (int i = 0; i < n; i++) + System.out.println(i + 1 + ""->"" + arr[i] / n); + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + CountFrequency count = new CountFrequency(); + int arr[] = {2, 3, 3, 2, 5}; + int n = arr.length; + count.printfrequency(arr, n); + } +} + + +"," '''Python 3 program to print frequencies +of all array elements in O(1) extra +space and O(n) time''' + + + '''Function to find counts of all elements +present in arr[0..n-1]. The array +elements must be range from 1 to n''' + +def printfrequency(arr, n): + + ''' Subtract 1 from every element so that + the elements become in range from 0 to n-1''' + + for j in range(n): + arr[j] = arr[j] - 1 + + ''' Use every element arr[i] as index + and add 'n' to element present at + arr[i]%n to keep track of count of + occurrences of arr[i]''' + + for i in range(n): + arr[arr[i] % n] = arr[arr[i] % n] + n + + ''' To print counts, simply print the + number of times n was added at index + corresponding to every element''' + + for i in range(n): + print(i + 1, ""->"", arr[i] // n) + + '''Driver code''' + +arr = [2, 3, 3, 2, 5] +n = len(arr) +printfrequency(arr, n) + + +" +"Write a program to calculate pow(x,n)","/* Java code for extended version of power function +that can work for float x and negative y */ + +class GFG { + static float power(float x, int y) + { + float temp; + if( y == 0) + return 1; + temp = power(x, y/2); + if (y%2 == 0) + return temp*temp; + else + { + if(y > 0) + return x * temp * temp; + else + return (temp * temp) / x; + } + } + /* Program to test function power */ + + public static void main(String[] args) + { + float x = 2; + int y = -3; + System.out.printf(""%f"", power(x, y)); + } +}"," '''Python3 code for extended version +of power function that can work +for float x and negative y''' + +def power(x, y): + if(y == 0): return 1 + temp = power(x, int(y / 2)) + if (y % 2 == 0): + return temp * temp + else: + if(y > 0): return x * temp * temp + else: return (temp * temp) / x + '''Driver Code''' + +x, y = 2, -3 +print('%.6f' %(power(x, y)))" +Find the sum of last n nodes of the given Linked List,"/*Java implementation to find the sum of +last 'n' nodes of the Linked List*/ + +import java.util.*; + +class GFG +{ + +/* A Linked list node */ + +static class Node +{ + int data; + Node next; +}; +static Node head; +static int n, sum; + +/*function to insert a node at the +beginning of the linked list*/ + +static void push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list to the new node */ + + new_node.next = head_ref; + + /* move the head to point to the new node */ + + head_ref = new_node; + head = head_ref; +} + +/*function to recursively find the sum of last +'n' nodes of the given linked list*/ + +static void sumOfLastN_Nodes(Node head) +{ +/* if head = NULL*/ + + if (head == null) + return; + +/* recursively traverse the remaining nodes*/ + + sumOfLastN_Nodes(head.next); + +/* if node count 'n' is greater than 0*/ + + if (n > 0) + { + +/* accumulate sum*/ + + sum = sum + head.data; + +/* reduce node count 'n' by 1*/ + + --n; + } +} + +/*utility function to find the sum of last 'n' nodes*/ + +static int sumOfLastN_NodesUtil(Node head, int n) +{ +/* if n == 0*/ + + if (n <= 0) + return 0; + + sum = 0; + +/* find the sum of last 'n' nodes*/ + + sumOfLastN_Nodes(head); + +/* required sum*/ + + return sum; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + head = null; + +/* create linked list 10.6.8.4.12*/ + + push(head, 12); + push(head, 4); + push(head, 8); + push(head, 6); + push(head, 10); + + n = 2; + System.out.print(""Sum of last "" + n + + "" nodes = "" + + sumOfLastN_NodesUtil(head, n)); +} +} + + +"," '''Python3 implementation to find the sum of +last 'n' nodes of the Linked List''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + +head = None +n = 0 +sum = 0 + + '''function to insert a node at the +beginning of the linked list''' + +def push(head_ref, new_data): + global head + + ''' allocate node''' + + new_node = Node(0) + + ''' put in the data''' + + new_node.data = new_data + + ''' link the old list to the new node''' + + new_node.next = head_ref + + ''' move the head to point to the new node''' + + head_ref = new_node + head = head_ref + + '''function to recursively find the sum of last + '''n' nodes of the given linked list''' + +def sumOfLastN_Nodes(head): + + global sum + global n + + ''' if head = None''' + + if (head == None): + return + + ''' recursively traverse the remaining nodes''' + + sumOfLastN_Nodes(head.next) + + ''' if node count 'n' is greater than 0''' + + if (n > 0) : + + ''' accumulate sum''' + + sum = sum + head.data + + ''' reduce node count 'n' by 1''' + + n = n - 1 + + '''utility function to find the sum of last 'n' nodes''' + +def sumOfLastN_NodesUtil(head, n): + + global sum + + ''' if n == 0''' + + if (n <= 0): + return 0 + + sum = 0 + + ''' find the sum of last 'n' nodes''' + + sumOfLastN_Nodes(head) + + ''' required sum''' + + return sum + + '''Driver Code''' + +head = None + + '''create linked list 10.6.8.4.12''' + +push(head, 12) +push(head, 4) +push(head, 8) +push(head, 6) +push(head, 10) + +n = 2 +print(""Sum of last "" , n , + "" nodes = "", sumOfLastN_NodesUtil(head, n)) + + +" +Point arbit pointer to greatest value right side node in a linked list,"/*Java program to point arbit pointers to highest +value on its right*/ + +class GfG +{ + +/* Link list node */ + +static class Node +{ + int data; + Node next, arbit; +} + +/* Function to reverse the linked list */ + +static Node reverse(Node head) +{ + Node prev = null, current = head, next = null; + while (current != null) + { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + return prev; +} + +/*This function populates arbit pointer in every +node to the greatest value to its right.*/ + +static Node populateArbit(Node head) +{ +/* Reverse given linked list*/ + + head = reverse(head); + +/* Initialize pointer to maximum value node*/ + + Node max = head; + +/* Traverse the reversed list*/ + + Node temp = head.next; + while (temp != null) + { +/* Connect max through arbit pointer*/ + + temp.arbit = max; + +/* Update max if required*/ + + if (max.data < temp.data) + max = temp; + +/* Move ahead in reversed list*/ + + temp = temp.next; + } + +/* Reverse modified linked list and return + head.*/ + + return reverse(head); +} + +/*Utility function to print result linked list*/ + +static void printNextArbitPointers(Node node) +{ + System.out.println(""Node\tNext Pointer\tArbit Pointer""); + while (node != null) + { + System.out.print(node.data + ""\t\t""); + + if (node.next != null) + System.out.print(node.next.data + ""\t\t""); + else + System.out.print(""NULL"" +""\t\t""); + + if (node.arbit != null) + System.out.print(node.arbit.data); + else + System.out.print(""NULL""); + + System.out.println(); + node = node.next; + } +} + +/* Function to create a new node with given data */ + +static Node newNode(int data) +{ + Node new_node = new Node(); + new_node.data = data; + new_node.next = null; + return new_node; +} + +/* Driver code*/ + +public static void main(String[] args) +{ + Node head = newNode(5); + head.next = newNode(10); + head.next.next = newNode(2); + head.next.next.next = newNode(3); + + head = populateArbit(head); + + System.out.println(""Resultant Linked List is: ""); + printNextArbitPointers(head); + +} +} + + +"," '''Python Program to point arbit pointers to highest +value on its right''' + + + '''Node class''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.arbit = None + + '''Function to reverse the linked list''' + +def reverse(head): + + prev = None + current = head + next = None + while (current != None): + + next = current.next + current.next = prev + prev = current + current = next + + return prev + + '''This function populates arbit pointer in every +node to the greatest value to its right.''' + +def populateArbit(head): + + ''' Reverse given linked list''' + + head = reverse(head) + + ''' Initialize pointer to maximum value node''' + + max = head + + ''' Traverse the reversed list''' + + temp = head.next + while (temp != None): + + ''' Connect max through arbit pointer''' + + temp.arbit = max + + ''' Update max if required''' + + if (max.data < temp.data): + max = temp + + ''' Move ahead in reversed list''' + + temp = temp.next + + ''' Reverse modified linked list and return + head.''' + + return reverse(head) + + '''Utility function to print result linked list''' + +def printNextArbitPointers(node): + + print(""Node\tNext Pointer\tArbit Pointer\n"") + while (node != None): + + print( node.data , ""\t\t"",end = """") + + if (node.next != None): + print( node.next.data , ""\t\t"",end = """") + else : + print( ""None"" , ""\t\t"",end = """") + + if (node.arbit != None): + print( node.arbit.data,end = """") + else : + print( ""None"",end = """") + + print(""\n"") + node = node.next + + '''Function to create a new node with given data''' + +def newNode(data): + + new_node = Node(0) + new_node.data = data + new_node.next = None + return new_node + + '''Driver code''' + + +head = newNode(5) +head.next = newNode(10) +head.next.next = newNode(2) +head.next.next.next = newNode(3) + +head = populateArbit(head) + +print(""Resultant Linked List is: \n"") +printNextArbitPointers(head) + + +" +Iteratively Reverse a linked list using only 2 pointers (An Interesting Method),," '''Python3 program to reverse a linked list using two pointers.''' + + + '''A linked list node''' + +class Node : + def __init__(self): + self.data = 0 + self.next = None + + '''Function to reverse the linked list using 2 pointers''' + +def reverse(head_ref): + + current = head_ref + next= None + while (current.next != None) : + next = current.next + current.next = next.next + next.next = (head_ref) + head_ref = next + + return head_ref + + '''Function to push a node''' + +def push( head_ref, new_data): + + new_node = Node() + new_node.data = new_data + new_node.next = (head_ref) + (head_ref) = new_node + return head_ref + + '''Function to print linked list''' + +def printList( head): + + temp = head + while (temp != None) : + print( temp.data, end="" "") + temp = temp.next + + '''Driver code''' + + + '''Start with the empty list''' + +head = None + +head = push(head, 20) +head = push(head, 4) +head = push(head, 15) +head = push(head, 85) + +print(""Given linked list"") +printList(head) +head = reverse(head) +print(""\nReversed Linked list "") +printList(head) + + +" +Boyer Moore Algorithm for Pattern Searching,"/* Java Program for Bad Character Heuristic of Boyer +Moore String Matching Algorithm */ + +class AWQ{ + static int NO_OF_CHARS = 256; +/* A utility function to get maximum of two integers*/ + + static int max (int a, int b) { return (a > b)? a: b; } +/* The preprocessing function for Boyer Moore's + bad character heuristic*/ + + static void badCharHeuristic( char []str, int size,int badchar[]) + { +/* Initialize all occurrences as -1*/ + + for (int i = 0; i < NO_OF_CHARS; i++) + badchar[i] = -1; +/* Fill the actual value of last occurrence + of a character (indeces of table are ascii and values are index of occurence)*/ + + for (i = 0; i < size; i++) + badchar[(int) str[i]] = i; + } + /* A pattern searching function that uses Bad + Character Heuristic of Boyer Moore Algorithm */ + + static void search( char txt[], char pat[]) + { + int m = pat.length; + int n = txt.length; + int badchar[] = new int[NO_OF_CHARS]; + /* Fill the bad character array by calling + the preprocessing function badCharHeuristic() + for given pattern */ + + badCharHeuristic(pat, m, badchar); +/*s is shift of the pattern with respect to text*/ + +int s = 0; +/*there are n-m+1 potential allignments*/ + + while(s <= (n - m)) + { + int j = m-1; + /* Keep reducing index j of pattern while + characters of pattern and text are + matching at this shift s */ + + while(j >= 0 && pat[j] == txt[s+j]) + j--; + /* If the pattern is present at current + shift, then index j will become -1 after + the above loop */ + + if (j < 0) + { + System.out.println(""Patterns occur at shift = "" + s); + /* Shift the pattern so that the next + character in text aligns with the last + occurrence of it in pattern. + The condition s+m < n is necessary for + the case when pattern occurs at the end + of text txt[s+m] is character after the pattern in text*/ + + s += (s+m < n)? m-badchar[txt[s+m]] : 1; + } + else + +/* Shift the pattern so that the bad character + in text aligns with the last occurrence of + it in pattern. The max function is used to + make sure that we get a positive shift. + We may get a negative shift if the last + occurrence of bad character in pattern + is on the right side of the current + character. */ + + s += max(1, j - badchar[txt[s+j]]); + } + } + /* Driver program to test above function */ + + public static void main(String []args) { + char txt[] = ""ABAAABCD"".toCharArray(); + char pat[] = ""ABC"".toCharArray(); + search(txt, pat); + } +}"," '''Python3 Program for Bad Character Heuristic +of Boyer Moore String Matching Algorithm''' + +NO_OF_CHARS = 256 + + ''' + The preprocessing function for + Boyer Moore's bad character heuristic + ''' + +def badCharHeuristic(string, size): ''' Initialize all occurrence as -1''' + + badChar = [-1]*NO_OF_CHARS + ''' Fill the actual value of last occurrence''' + + for i in range(size): + badChar[ord(string[i])] = i; + return badChar ''' + A pattern searching function that uses Bad Character + Heuristic of Boyer Moore Algorithm + ''' +def search(txt, pat): + m = len(pat) + n = len(txt) + ''' create the bad character list by calling + the preprocessing function badCharHeuristic() + for given pattern''' + + badChar = badCharHeuristic(pat, m) + ''' s is shift of the pattern with respect to text''' + + s = 0 + + '''there are n-m+1 potential allignments''' + + while(s <= n-m): + j = m-1 ''' Keep reducing index j of pattern while + characters of pattern and text are matching + at this shift s''' + + while j>=0 and pat[j] == txt[s+j]: + j -= 1 + ''' If the pattern is present at current shift, + then index j will become -1 after the above loop''' + + if j<0: + print(""Pattern occur at shift = {}"".format(s)) + ''' + Shift the pattern so that the next character in text + aligns with the last occurrence of it in pattern. + The condition s+m < n is necessary for the case when + pattern occurs at the end of text + ''' + + s += (m-badChar[ord(txt[s+m])] if s+m graph[], + boolean visited[], int x) +{ + for (int i = 0; i < graph[x].size(); i++) + { + if (!visited[graph[x].get(i)]) + { +/* Incrementing the number of node in + a connected component.*/ + + (k)++; + visited[graph[x].get(i)] = true; + dfs(graph, visited, graph[x].get(i)); + } + } +} +/*Return the number of count of non-accessible cells.*/ + +static int countNonAccessible(Vector graph[], int N) +{ + boolean []visited = new boolean[N * N + N]; + int ans = 0; + for (int i = 1; i <= N * N; i++) + { + if (!visited[i]) + { + visited[i] = true; +/* Initialize count of connected + vertices found by DFS starting + from i.*/ + + int k = 1; + dfs(graph, visited, i); +/* Update result*/ + + ans += k * (N * N - k); + } + } + return ans; +} +/*Inserting the edge between edge.*/ + +static void insertpath(Vector graph[], + int N, int x1, int y1, + int x2, int y2) +{ +/* Mapping the cell coordinate into node number.*/ + + int a = (x1 - 1) * N + y1; + int b = (x2 - 1) * N + y2; +/* Inserting the edge.*/ + + graph[a].add(b); + graph[b].add(a); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int N = 2; + Vector[] graph = new Vector[N * N + 1]; + for (int i = 1; i <= N * N; i++) + graph[i] = new Vector(); + insertpath(graph, N, 1, 1, 1, 2); + insertpath(graph, N, 1, 2, 2, 2); + System.out.println(countNonAccessible(graph, N)); +} +}"," '''Python3 program to count number of pair of +positions in matrix which are not accessible''' + + '''Counts number of vertices connected in a +component containing x. Stores the count in k. ''' + +def dfs(graph,visited, x, k): + for i in range(len(graph[x])): + if (not visited[graph[x][i]]): ''' Incrementing the number of node + in a connected component. ''' + + k[0] += 1 + visited[graph[x][i]] = True + dfs(graph, visited, graph[x][i], k) + '''Return the number of count of +non-accessible cells. ''' + +def countNonAccessible(graph, N): + visited = [False] * (N * N + N) + ans = 0 + for i in range(1, N * N + 1): + if (not visited[i]): + visited[i] = True + ''' Initialize count of connected + vertices found by DFS starting + from i. ''' + + k = [1] + dfs(graph, visited, i, k) + ''' Update result ''' + + ans += k[0] * (N * N - k[0]) + return ans + '''Inserting the edge between edge. ''' + +def insertpath(graph, N, x1, y1, x2, y2): + ''' Mapping the cell coordinate + into node number. ''' + + a = (x1 - 1) * N + y1 + b = (x2 - 1) * N + y2 + ''' Inserting the edge. ''' + + graph[a].append(b) + graph[b].append(a) + '''Driver Code''' + +if __name__ == '__main__': + N = 2 + graph = [[] for i in range(N*N + 1)] + insertpath(graph, N, 1, 1, 1, 2) + insertpath(graph, N, 1, 2, 2, 2) + print(countNonAccessible(graph, N))" +Total numbers with no repeated digits in a range,"/*Java implementation of above idea*/ + +import java.util.*; +class GFG +{ +/* Maximum*/ + + static int MAX = 100; +/* Prefix Array*/ + + static Vector Prefix = new Vector<>(); +/* Function to check if the given + number has repeated digit or not*/ + + static int repeated_digit(int n) + { + HashSet a = new HashSet<>(); + int d; +/* Traversing through each digit*/ + + while (n != 0) + { + d = n % 10; +/* if the digit is present + more than once in the + number*/ + + if (a.contains(d)) +/* return 0 if the number + has repeated digit*/ + + return 0; + a.add(d); + n /= 10; + } +/* return 1 if the number has no + repeated digit*/ + + return 1; + } +/* Function to pre calculate + the Prefix array*/ + + static void pre_calculations() + { + Prefix.add(0); + Prefix.add(repeated_digit(1)); +/* Traversing through the numbers + from 2 to MAX*/ + + for (int i = 2; i < MAX + 1; i++) +/* Generating the Prefix array*/ + + Prefix.add(repeated_digit(i) + Prefix.elementAt(i - 1)); + } +/* Calclute Function*/ + + static int calculate(int L, int R) + { +/* Answer*/ + + return Prefix.elementAt(R) - Prefix.elementAt(L - 1); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int L = 1, R = 100; +/* Pre-calculating the Prefix array.*/ + + pre_calculations(); +/* Calling the calculate function + to find the total number of number + which has no repeated digit*/ + + System.out.println(calculate(L, R)); + } +}"," '''Maximum ''' + +MAX = 1000 + '''Prefix Array''' + +Prefix = [0] + '''Function to check if +the given number has +repeated digit or not ''' + +def repeated_digit(n): + a = [] + ''' Traversing through each digit''' + + while n != 0: + d = n%10 + ''' if the digit is present + more than once in the + number''' + + if d in a: + ''' return 0 if the number + has repeated digit''' + + return 0 + a.append(d) + n = n//10 + ''' return 1 if the number has no + repeated digit''' + + return 1 + '''Function to pre calculate +the Prefix array''' + +def pre_calculation(MAX): + global Prefix + Prefix.append(repeated_digit(1)) ''' Traversing through the numbers + from 2 to MAX''' + + for i in range(2,MAX+1): + ''' Generating the Prefix array ''' + + Prefix.append( repeated_digit(i) + + Prefix[i-1] ) + '''Calclute Function''' + +def calculate(L,R): + ''' Answer''' + + return Prefix[R]-Prefix[L-1] + '''Pre-calculating the Prefix array.''' + +pre_calculation(MAX) +L=1 +R=100 '''Calling the calculate function +to find the total number of number +which has no repeated digit''' + +print(calculate(L, R))" +Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space,"/*Java program to shuffle an array in +the form of a1, b1, a2, b2,...*/ + +import java.io.*; + +class GFG { + +/* function to rearrange the array*/ + + public static void rearrange(int[] arr) { + +/* if size is null or odd return because it + is not possible to rearrange*/ + + if (arr == null || arr.length % 2 == 1) + return; + +/* start from the middle index*/ + + int currIdx = (arr.length - 1) / 2; + +/* each time we will set two elements from the + start to the valid position by swapping*/ + + while (currIdx > 0) { + int count = currIdx, swapIdx = currIdx; + + while (count-- > 0) { + int temp = arr[swapIdx + 1]; + arr[swapIdx + 1] = arr[swapIdx]; + arr[swapIdx] = temp; + swapIdx++; + } + currIdx--; + } + } + + /*Driver Program*/ + + + public static void main(String[] args) { + int arr[] = {1, 3, 5, 2, 4, 6}; + rearrange(arr); + for (int i = 0; i < arr.length; i++) + System.out.print("" "" + arr[i]); + } +}"," '''Python program to shuffle +an array in the form +of a1, b1, a2, b2,...''' + + +arr = [1, 3, 5, 2, 4, 6] + + '''function to +rearrange the array''' + +def rearrange(n) : + + global arr + + ''' if size is null or + odd return because + it is not possible + to rearrange''' + + if (n % 2 == 1) : + return + + ''' start from the + middle index''' + + currIdx = int((n - 1) / 2) + + ''' each time we will set + two elements from the + start to the valid + position by swapping''' + + while (currIdx > 0) : + + count = currIdx + swapIdx = currIdx + + while (count > 0) : + + temp = arr[swapIdx + 1] + arr[swapIdx + 1] = arr[swapIdx] + arr[swapIdx] = temp + swapIdx = swapIdx + 1 + count = count - 1 + + currIdx = currIdx - 1 + + '''Driver Code''' + +n = len(arr) +rearrange(n) +for i in range(0, n) : + print (""{} "" . format(arr[i]), + end = """") + + +" +How to check if an instance of 8 puzzle is solvable?,"/*Java program to check if a given +instance of 8 puzzle is solvable or not*/ + +class GFG +{ +/*A utility function to count +inversions in given array 'arr[]'*/ + +static int getInvCount(int[][] arr) +{ + int inv_count = 0; + for (int i = 0; i < 3 - 1; i++) + for (int j = i + 1; j < 3; j++) +/* Value 0 is used for empty space*/ + + if (arr[j][i] > 0 && + arr[j][i] > arr[i][j]) + inv_count++; + return inv_count; +} +/*This function returns true +if given 8 puzzle is solvable.*/ + +static boolean isSolvable(int[][] puzzle) +{ +/* Count inversions in given 8 puzzle*/ + + int invCount = getInvCount(puzzle); +/* return true if inversion count is even.*/ + + return (invCount % 2 == 0); +} +/* Driver code */ + +public static void main (String[] args) +{ + int[][] puzzle = {{1, 8, 2},{0, 4, 3},{7, 6, 5}}; + if(isSolvable(puzzle)) + System.out.println(""Solvable""); + else + System.out.println(""Not Solvable""); +} +}"," '''Python3 program to check if a given +instance of 8 puzzle is solvable or not''' + + '''A utility function to count +inversions in given array 'arr[]' ''' +def getInvCount(arr) : + inv_count = 0 + for i in range(0, 2) : + for j in range(i + 1, 3) : ''' Value 0 is used for empty space''' + + if (arr[j][i] > 0 and arr[j][i] > arr[i][j]) : + inv_count += 1 + return inv_count + '''This function returns true +if given 8 puzzle is solvable.''' + +def isSolvable(puzzle) : + ''' Count inversions in given 8 puzzle''' + + invCount = getInvCount(puzzle) + ''' return true if inversion count is even.''' + + return (invCount % 2 == 0) + ''' Driver code''' + +puzzle = [[1, 8, 2],[0, 4, 3],[7, 6, 5]] +if(isSolvable(puzzle)) : + print(""Solvable"") +else : + print(""Not Solvable"")" +Rotate a Linked List,"/*Java program to rotate +a linked list counter clock wise*/ + +import java.util.*; + +class GFG{ + +/* Link list node */ + +static class Node { + + int data; + Node next; +}; +static Node head = null; + +/*This function rotates a linked list +counter-clockwise and updates the +head. The function assumes that k is +smaller than size of linked list.*/ + +static void rotate( int k) +{ + if (k == 0) + return; + +/* Let us understand the below + code for example k = 4 and + list = 10.20.30.40.50.60.*/ + + Node current = head; + +/* Traverse till the end.*/ + + while (current.next != null) + current = current.next; + + current.next = head; + current = head; + +/* traverse the linked list to k-1 position which + will be last element for rotated array.*/ + + for (int i = 0; i < k - 1; i++) + current = current.next; + +/* update the head_ref and last element pointer to null*/ + + head = current.next; + current.next = null; +} + +/* UTILITY FUNCTIONS */ + +/* Function to push a node */ + +static void push(int new_data) +{ + + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list off the new node */ + + new_node.next = head; + + /* move the head to point to the new node */ + + head = new_node; +} + +/* Function to print linked list */ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.next; + } +} + +/* Driver code*/ + +public static void main(String[] args) +{ + /* Start with the empty list */ + + + +/* create a list 10.20.30.40.50.60*/ + + for (int i = 60; i > 0; i -= 10) + push( i); + + System.out.print(""Given linked list \n""); + printList(head); + rotate( 4); + + System.out.print(""\nRotated Linked list \n""); + printList(head); +} +} + + + +"," '''Python3 program to rotate +a linked list counter clock wise''' + + + '''Link list node''' + +class Node: + + def __init__(self): + + self.data = 0 + self.next = None + + '''This function rotates a linked list +counter-clockwise and updates the +head. The function assumes that k is +smaller than size of linked list.''' + +def rotate(head_ref, k): + + if (k == 0): + return + + ''' Let us understand the below + code for example k = 4 and + list = 10.20.30.40.50.60.''' + + current = head_ref + + ''' Traverse till the end.''' + + while (current.next != None): + current = current.next + + current.next = head_ref + current = head_ref + + ''' Traverse the linked list to k-1 + position which will be last element + for rotated array.''' + + for i in range(k - 1): + current = current.next + + ''' Update the head_ref and last + element pointer to None''' + + head_ref = current.next + current.next = None + return head_ref + + '''UTILITY FUNCTIONS''' + + '''Function to push a node''' + +def push(head_ref, new_data): + ''' Allocate node''' + + new_node = Node() + + ''' Put in the data''' + + new_node.data = new_data + + ''' Link the old list off + the new node''' + + new_node.next = (head_ref) + + ''' Move the head to point + to the new node''' + + (head_ref) = new_node + return head_ref + + '''Function to print linked list''' + +def printList(node): + + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Start with the empty list''' + + head = None + + ''' Create a list 10.20.30.40.50.60''' + + for i in range(60, 0, -10): + head = push(head, i) + + print(""Given linked list "") + printList(head) + head = rotate(head, 4) + + print(""\nRotated Linked list "") + printList(head) + + +" +Find smallest range containing elements from k lists,"/*Java program to finds out smallest range that includes +elements from each of the given sorted lists.*/ + +class GFG { + static final int N = 5; +/* array for storing the current index of list i*/ + + static int ptr[] = new int[501]; +/* This function takes an k sorted lists in the form of + 2D array as an argument. It finds out smallest range + that includes elements from each of the k lists.*/ + + static void findSmallestRange(int arr[][], int n, int k) + { + int i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; +/* initializing to 0 index;*/ + + for (i = 0; i <= k; i++) { + ptr[i] = 0; + } + minrange = Integer.MAX_VALUE; + while (true) { +/* for maintaining the index of list containing the minimum element*/ + + minind = -1; + minval = Integer.MAX_VALUE; + maxval = Integer.MIN_VALUE; + flag = 0; +/* iterating over all the list*/ + + for (i = 0; i < k; i++) { +/* if every element of list[i] is traversed then break the loop*/ + + if (ptr[i] == n) { + flag = 1; + break; + } +/* find minimum value among all the list elements pointing by the ptr[] array*/ + + if (ptr[i] < n && arr[i][ptr[i]] < minval) { +/*update the index of the list*/ + +minind = i; + minval = arr[i][ptr[i]]; + } +/* find maximum value among all the list elements pointing by the ptr[] array*/ + + if (ptr[i] < n && arr[i][ptr[i]] > maxval) { + maxval = arr[i][ptr[i]]; + } + } +/* if any list exhaust we will not get any better answer, so break the while loop*/ + + if (flag == 1) { + break; + } + ptr[minind]++; +/* updating the minrange*/ + + if ((maxval - minval) < minrange) { + minel = minval; + maxel = maxval; + minrange = maxel - minel; + } + } + System.out.printf(""The smallest range is [%d, %d]\n"", minel, maxel); + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[][] = { + { 4, 7, 9, 12, 15 }, + { 0, 8, 10, 14, 20 }, + { 6, 12, 16, 30, 50 } + }; + int k = arr.length; + findSmallestRange(arr, N, k); + } +}"," '''Python3 program to finds out +smallest range that includes +elements from each of the +given sorted lists.''' + +N = 5 + '''array for storing the +current index of list i''' + +ptr = [0 for i in range(501)] + '''This function takes an k sorted +lists in the form of 2D array as +an argument. It finds out smallest +range that includes elements from +each of the k lists.''' + +def findSmallestRange(arr, n, k): + i, minval, maxval, minrange, minel, maxel, flag, minind = 0, 0, 0, 0, 0, 0, 0, 0 + ''' initializing to 0 index''' + + for i in range(k + 1): + ptr[i] = 0 + minrange = 10**9 + while(1): + ''' for maintaining the index of list + containing the minimum element''' + + minind = -1 + minval = 10**9 + maxval = -10**9 + flag = 0 + ''' iterating over all the list''' + + for i in range(k): + ''' if every element of list[i] is + traversed then break the loop''' + + if(ptr[i] == n): + flag = 1 + break + ''' find minimum value among all the list + elements pointing by the ptr[] array''' + + if(ptr[i] < n and arr[i][ptr[i]] < minval): + '''update the index of the list''' + + minind = i + minval = arr[i][ptr[i]] + ''' find maximum value among all the + list elements pointing by the ptr[] array''' + + if(ptr[i] < n and arr[i][ptr[i]] > maxval): + maxval = arr[i][ptr[i]] + ''' if any list exhaust we will + not get any better answer, + so break the while loop''' + + if(flag): + break + ptr[minind] += 1 + ''' updating the minrange''' + + if((maxval-minval) < minrange): + minel = minval + maxel = maxval + minrange = maxel - minel + print(""The smallest range is ["", minel, maxel, ""]"") + '''Driver code''' + +arr = [ + [4, 7, 9, 12, 15], + [0, 8, 10, 14, 20], + [6, 12, 16, 30, 50] + ] +k = len(arr) +findSmallestRange(arr, N, k)" +Check horizontal and vertical symmetry in binary matrix,"/*Java program to find if +a matrix is symmetric.*/ + +import java.io.*; +public class GFG { + static void checkHV(int[][] arr, int N, + int M) + { +/* Initializing as both horizontal + and vertical symmetric.*/ + + boolean horizontal = true; + boolean vertical = true; +/* Checking for Horizontal Symmetry. + We compare first row with last + row, second row with second + last row and so on.*/ + + for (int i = 0, k = N - 1; + i < N / 2; i++, k--) { +/* Checking each cell of a column.*/ + + for (int j = 0; j < M; j++) { +/* check if every cell is identical*/ + + if (arr[i][j] != arr[k][j]) { + horizontal = false; + break; + } + } + } +/* Checking for Vertical Symmetry. We compare + first column with last column, second xolumn + with second last column and so on.*/ + + for (int i = 0, k = M - 1; + i < M / 2; i++, k--) { +/* Checking each cell of a row.*/ + + for (int j = 0; j < N; j++) { +/* check if every cell is identical*/ + + if (arr[i][j] != arr[k][j]) { + horizontal = false; + break; + } + } + } + if (!horizontal && !vertical) + System.out.println(""NO""); + else if (horizontal && !vertical) + System.out.println(""HORIZONTAL""); + else if (vertical && !horizontal) + System.out.println(""VERTICAL""); + else + System.out.println(""BOTH""); + } +/* Driver Code*/ + + static public void main(String[] args) + { + int[][] mat = { { 1, 0, 1 }, + { 0, 0, 0 }, + { 1, 0, 1 } }; + checkHV(mat, 3, 3); + } +}"," '''Python3 program to find if a matrix is symmetric.''' + +MAX = 1000 +def checkHV(arr, N, M): + ''' Initializing as both horizontal and vertical + symmetric.''' + + horizontal = True + vertical = True + ''' Checking for Horizontal Symmetry. We compare + first row with last row, second row with second + last row and so on.''' + + i = 0 + k = N - 1 + while(i < N // 2): + ''' Checking each cell of a column.''' + + for j in range(M): + ''' check if every cell is identical''' + + if (arr[i][j] != arr[k][j]): + horizontal = False + break + i += 1 + k -= 1 + ''' Checking for Vertical Symmetry. We compare + first column with last column, second xolumn + with second last column and so on.''' + + i = 0 + k = M - 1 + while(i < M // 2): + ''' Checking each cell of a row.''' + + for j in range(N): + ''' check if every cell is identical''' + + if (arr[i][j] != arr[k][j]): + vertical = False + break + i += 1 + k -= 1 + if (not horizontal and not vertical): + print(""NO"") + elif (horizontal and not vertical): + print(""HORIZONTAL"") + elif (vertical and not horizontal): + print(""VERTICAL"") + else: + print(""BOTH"") + '''Driver code''' + +mat = [[1, 0, 1],[ 0, 0, 0],[1, 0, 1]] +checkHV(mat, 3, 3)" +Find the element that appears once in an array where every other element appears twice,"/*Java program to find the array +element that appears only once*/ + +class MaxSum +{ +/* Return the maximum Sum of difference + between consecutive elements.*/ + + static int findSingle(int ar[], int ar_size) + { +/* Do XOR of all elements and return*/ + + int res = ar[0]; + for (int i = 1; i < ar_size; i++) + res = res ^ ar[i]; + return res; + } +/* Driver code*/ + + public static void main (String[] args) + { + int ar[] = {2, 3, 5, 4, 5, 3, 4}; + int n = ar.length; + System.out.println(""Element occurring once is "" + + findSingle(ar, n) + "" ""); + } +}"," '''function to find the once +appearing element in array''' + +def findSingle( ar, n): + res = ar[0] + ''' Do XOR of all elements and return''' + + for i in range(1,n): + res = res ^ ar[i] + return res + '''Driver code''' + +ar = [2, 3, 5, 4, 5, 3, 4] +print ""Element occurring once is"", findSingle(ar, len(ar))" +Compute the minimum or maximum of two integers without branching,"/*Java program for the above approach*/ + +import java.io.*; +class GFG { +/*absbit32 function*/ + + public static int absbit32(int x, int y){ + int sub = x - y; + int mask = (sub >> 31); + return (sub ^ mask) - mask; + }/*max function*/ + + public static int max(int x, int y){ + int abs = absbit32(x,y); + return (x + y + abs)/2; + }/*min function*/ + + public static int min(int x, int y){ + int abs = absbit32(x,y); + return (x + y - abs)/2; + }/*Driver code*/ + public static void main(String []args){ +System.out.println( max(2,3) ); +System.out.println( max(2,-3) ); +System.out.println( max(-2,-3) ); +System.out.println( min(2,3) ); +System.out.println( min(2,-3) ); +System.out.println( min(-2,-3) ); + } +}"," '''Python3 program for the above approach''' + '''absbit32 function''' + +def absbit32( x, y): + sub = x - y + mask = (sub >> 31) + return (sub ^ mask) - mask '''max function''' + +def max(x, y): + abs = absbit32(x,y) + return (x + y + abs)//2 '''min function''' + +def min(x, y): + abs = absbit32(x,y) + return (x + y - abs)//2 '''Driver code''' + +print( max(2,3) ) +print( max(2,-3) ) +print( max(-2,-3) ) +print( min(2,3) ) +print( min(2,-3) ) +print( min(-2,-3) )" +Count sub-matrices having sum divisible 'k',"/*Java implementation to count +sub-matrices having sum +divisible by the value 'k'*/ + +import java.util.*; +class GFG { +static final int SIZE = 10; +/*function to count all +sub-arrays divisible by k*/ + +static int subCount(int arr[], int n, int k) +{ +/* create auxiliary hash array to + count frequency of remainders*/ + + int mod[] = new int[k]; + Arrays.fill(mod, 0); +/* Traverse original array and compute cumulative + sum take remainder of this current cumulative + sum and increase count by 1 for this remainder + in mod[] array*/ + + int cumSum = 0; + for (int i = 0; i < n; i++) { + cumSum += arr[i]; +/* as the sum can be negative, + taking modulo twice*/ + + mod[((cumSum % k) + k) % k]++; + } +/* Initialize result*/ + + int result = 0; +/* Traverse mod[]*/ + + for (int i = 0; i < k; i++) +/* If there are more than one prefix subarrays + with a particular mod value.*/ + + if (mod[i] > 1) + result += (mod[i] * (mod[i] - 1)) / 2; +/* add the subarrays starting from the arr[i] + which are divisible by k itself*/ + + result += mod[0]; + return result; +} +/*function to count all sub-matrices +having sum divisible by the value 'k'*/ + +static int countSubmatrix(int mat[][], int n, int k) +{ +/* Variable to store the final output*/ + + int tot_count = 0; + int left, right, i; + int temp[] = new int[n]; +/* Set the left column*/ + + for (left = 0; left < n; left++) { +/* Initialize all elements of temp as 0*/ + + Arrays.fill(temp, 0); +/* Set the right column for the left column + set by outer loop*/ + + for (right = left; right < n; right++) { +/* Calculate sum between current left + and right for every row 'i'*/ + + for (i = 0; i < n; ++i) + temp[i] += mat[i][right]; +/* Count number of subarrays in temp[] + having sum divisible by 'k' and then + add it to 'tot_count'*/ + + tot_count += subCount(temp, n, k); + } + } +/* required count of sub-matrices having sum + divisible by 'k'*/ + + return tot_count; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int mat[][] = {{5, -1, 6}, + {-2, 3, 8}, + {7, 4, -9}}; + int n = 3, k = 4; + System.out.print(""Count = "" + + countSubmatrix(mat, n, k)); +} +}"," '''Python implementation to +count sub-matrices having +sum divisible by the +value k''' + '''function to count all +sub-arrays divisible by k''' + +def subCount(arr, n, k) : + ''' create auxiliary hash + array to count frequency + of remainders''' + + mod = [0] * k; + ''' Traverse original array + and compute cumulative + sum take remainder of + this current cumulative + sum and increase count + by 1 for this remainder + in mod array''' + + cumSum = 0; + for i in range(0, n) : + cumSum = cumSum + arr[i]; + ''' as the sum can be + negative, taking + modulo twice''' + + mod[((cumSum % k) + k) % k] = mod[ + ((cumSum % k) + k) % k] + 1; + '''Initialize result''' + + result = 0; + ''' Traverse mod''' + + for i in range(0, k) : + ''' If there are more than + one prefix subarrays + with a particular mod value.''' + + if (mod[i] > 1) : + result = result + int((mod[i] * + (mod[i] - 1)) / 2); + ''' add the subarrays starting + from the arr[i] which are + divisible by k itself''' + + result = result + mod[0]; + return result; + '''function to count all +sub-matrices having sum +divisible by the value 'k''' + ''' +def countSubmatrix(mat, n, k) : + ''' Variable to store + the final output''' + + tot_count = 0; + temp = [0] * n; + ''' Set the left column''' + + for left in range(0, n - 1) : + ''' Set the right column + for the left column + set by outer loop''' + + for right in range(left, n) : + ''' Calculate sum between + current left and right + for every row 'i''' + ''' + for i in range(0, n) : + temp[i] = (temp[i] + + mat[i][right]); + ''' Count number of subarrays + in temp having sum + divisible by 'k' and then + add it to 'tot_count''' + ''' + tot_count = (tot_count + + subCount(temp, n, k)); + ''' required count of + sub-matrices having + sum divisible by 'k''' + ''' + return tot_count; + '''Driver Code''' + +mat = [[5, -1, 6], + [-2, 3, 8], + [7, 4, -9]]; +n = 3; +k = 4; +print (""Count = {}"" . format( + countSubmatrix(mat, n, k)));" +Number of indexes with equal elements in given range,"/*Java program to count +the number of indexes +in range L R such that +Ai=Ai+1*/ + +class GFG { +public static int N = 1000; +/*Array to store count +of index from 0 to +i that obey condition*/ + +static int prefixans[] = new int[1000]; +/*precomputing prefixans[] array*/ + +public static void countIndex(int a[], int n) +{ +/* traverse to compute + the prefixans[] array*/ + + for (int i = 0; i < n; i++) { + if (i + 1 < n && a[i] == a[i + 1]) + prefixans[i] = 1; + if (i != 0) + prefixans[i] += prefixans[i - 1]; + } +} +/*function that answers +every query in O(1)*/ + +public static int answer_query(int l, int r) +{ + if (l == 0) + return prefixans[r - 1]; + else + return prefixans[r - 1] - + prefixans[l - 1]; +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int a[] = {1, 2, 2, 2, 3, 3, 4, 4, 4}; + int n = 9; +/* pre-computation*/ + + countIndex(a, n); + int L, R; +/* 1-st query*/ + + L = 1; + R = 8; + System.out.println(answer_query(L, R)); +/* 2nd query*/ + + L = 0; + R = 4; + System.out.println(answer_query(L, R)); +} +}"," '''Python program to count +the number of indexes in +range L R such that Ai=Ai+1''' + +N = 1000 + '''array to store count +of index from 0 to +i that obey condition''' + +prefixans = [0] * N; + '''precomputing +prefixans[] array''' + +def countIndex(a, n) : + global N, prefixans + ''' traverse to compute + the prefixans[] array''' + + for i in range(0, n - 1) : + if (a[i] == a[i + 1]) : + prefixans[i] = 1 + if (i != 0) : + prefixans[i] = (prefixans[i] + + prefixans[i - 1]) + '''def that answers +every query in O(1)''' + +def answer_query(l, r) : + global N, prefixans + if (l == 0) : + return prefixans[r - 1] + else : + return (prefixans[r - 1] - + prefixans[l - 1]) + '''Driver Code''' + +a = [1, 2, 2, 2, + 3, 3, 4, 4, 4] +n = len(a) + '''pre-computation''' + +countIndex(a, n) + '''1-st query''' + +L = 1 +R = 8 +print (answer_query(L, R)) + '''2nd query''' + +L = 0 +R = 4 +print (answer_query(L, R))" +K maximum sums of overlapping contiguous sub-arrays,," '''Python program to find out k maximum sum of +overlapping sub-arrays''' + + '''Function to compute prefix-sum of the input array''' + +def prefix_sum(arr, n): + pre_sum = list() + pre_sum.append(arr[0]) + for i in range(1, n): + pre_sum.append(pre_sum[i-1] + arr[i]) + return pre_sum '''Update maxi by k maximum values from maxi and cand''' + +def maxMerge(maxi, cand): + ''' Here cand and maxi arrays are in non-increasing + order beforehand. Now, j is the index of the + next cand element and i is the index of next + maxi element. Traverse through maxi array. + If cand[j] > maxi[i] insert cand[j] at the ith + position in the maxi array and remove the minimum + element of the maxi array i.e. the last element + and increase j by 1 i.e. take the next element + from cand.''' + + k = len(maxi) + j = 0 + for i in range(k): + if (cand[j] > maxi[i]): + maxi.insert(i, cand[j]) + del maxi[-1] + j += 1 + '''Insert prefix_sum[i] to mini array if needed''' + +def insertMini(mini, pre_sum): + ''' Traverse the mini array from left to right. + If prefix_sum[i] is less than any element + then insert prefix_sum[i] at that position + and delete maximum element of the mini array + i.e. the rightmost element from the array.''' + + k = len(mini) + for i in range(k): + if (pre_sum < mini[i]): + mini.insert(i, pre_sum) + del mini[-1] + break + '''Function to compute k maximum overlapping sub-array sums''' + +def kMaxOvSubArray(arr, k): + n = len(arr) + ''' Compute the prefix sum of the input array.''' + + pre_sum = prefix_sum(arr, n) + ''' Set all the elements of mini as + infinite + except 0th. Set the 0th element as 0.''' + + mini = [float('inf') for i in range(k)] + mini[0] = 0 + ''' Set all the elements of maxi as -infinite.''' + + maxi = [-float('inf') for i in range(k)] + ''' Initialize cand array.''' + + cand = [0 for i in range(k)] + ''' For each element of the prefix_sum array do: + compute the cand array. + take k maximum values from maxi and cand + using maxmerge function. + insert prefix_sum[i] to mini array if needed + using insertMini function.''' + + for i in range(n): + for j in range(k): + cand[j] = pre_sum[i] - mini[j] + maxMerge(maxi, cand) + insertMini(mini, pre_sum[i]) + ''' Elements of maxi array is the k + maximum overlapping sub-array sums. + Print out the elements of maxi array.''' + + for ele in maxi: + print(ele, end = ' ') + print('') + '''Driver Program''' + + '''Test case 1''' + +arr1 = [4, -8, 9, -4, 1, -8, -1, 6] +k1 = 4 +kMaxOvSubArray(arr1, k1) '''Test case 2''' + +arr2 = [-2, -3, 4, -1, -2, 1, 5, -3] +k2 = 3 +kMaxOvSubArray(arr2, k2)" +Find postorder traversal of BST from preorder traversal,"/*Java program for finding postorder +traversal of BST from preorder traversal*/ + +import java.util.*; +class Solution { + static class INT { + int data; + INT(int d) { data = d; } + } +/* Function to find postorder traversal from + preorder traversal.*/ + + static void findPostOrderUtil(int pre[], int n, + int minval, int maxval, + INT preIndex) + { +/* If entire preorder array is traversed then + return as no more element is left to be + added to post order array.*/ + + if (preIndex.data == n) + return; +/* If array element does not lie in range specified, + then it is not part of current subtree.*/ + + if (pre[preIndex.data] < minval + || pre[preIndex.data] > maxval) { + return; + } +/* Store current value, to be printed later, after + printing left and right subtrees. Increment + preIndex to find left and right subtrees, + and pass this updated value to recursive calls.*/ + + int val = pre[preIndex.data]; + preIndex.data++; +/* All elements with value between minval and val + lie in left subtree.*/ + + findPostOrderUtil(pre, n, minval, val, preIndex); +/* All elements with value between val and maxval + lie in right subtree.*/ + + findPostOrderUtil(pre, n, val, maxval, preIndex); + System.out.print(val + "" ""); + } +/* Function to find postorder traversal.*/ + + static void findPostOrder(int pre[], int n) + { +/* To store index of element to be + traversed next in preorder array. + This is passed by reference to + utility function.*/ + + INT preIndex = new INT(0); + findPostOrderUtil(pre, n, Integer.MIN_VALUE, + Integer.MAX_VALUE, preIndex); + } +/* Driver code*/ + + public static void main(String args[]) + { + int pre[] = { 40, 30, 35, 80, 100 }; + int n = pre.length; +/* Calling function*/ + + findPostOrder(pre, n); + } +}"," '''Python3 program for finding postorder +traversal of BST from preorder traversal''' + +INT_MIN = -2**31 +INT_MAX = 2**31 + '''Function to find postorder traversal +from preorder traversal.''' + +def findPostOrderUtil(pre, n, minval, + maxval, preIndex): + ''' If entire preorder array is traversed + then return as no more element is left + to be added to post order array.''' + + if (preIndex[0] == n): + return + ''' If array element does not lie in + range specified, then it is not + part of current subtree.''' + + if (pre[preIndex[0]] < minval or + pre[preIndex[0]] > maxval): + return + ''' Store current value, to be printed later, + after printing left and right subtrees. + Increment preIndex to find left and right + subtrees, and pass this updated value to + recursive calls.''' + + val = pre[preIndex[0]] + preIndex[0] += 1 + ''' All elements with value between minval + and val lie in left subtree.''' + + findPostOrderUtil(pre, n, minval, + val, preIndex) + ''' All elements with value between val + and maxval lie in right subtree.''' + + findPostOrderUtil(pre, n, val, + maxval, preIndex) + print(val, end="" "") + '''Function to find postorder traversal.''' + +def findPostOrder(pre, n): + ''' To store index of element to be + traversed next in preorder array. + This is passed by reference to + utility function.''' + + preIndex = [0] + findPostOrderUtil(pre, n, INT_MIN, + INT_MAX, preIndex) + '''Driver Code''' + +if __name__ == '__main__': + pre = [40, 30, 35, 80, 100] + n = len(pre) + ''' Calling function''' + + findPostOrder(pre, n)" +Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer),"import java.util.HashMap; +import java.util.Map; +/*Java program to find lowest common ancestor using parent pointer +A tree node*/ + +class Node +{ + int key; + Node left, right, parent; + Node(int key) + { + this.key = key; + left = right = parent = null; + } +} +class BinaryTree +{ + Node root, n1, n2, lca; + /* A utility function to insert a new node with + given key in Binary Search Tree */ + + Node insert(Node node, int key) + { + /* If the tree is empty, return a new node */ + + if (node == null) + return new Node(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + { + node.left = insert(node.left, key); + node.left.parent = node; + } + else if (key > node.key) + { + node.right = insert(node.right, key); + node.right.parent = node; + } + /* return the (unchanged) node pointer */ + + return node; + } +/* A utility function to find depth of a node + (distance of it from root)*/ + + int depth(Node node) + { + int d = -1; + while (node != null) + { + ++d; + node = node.parent; + } + return d; + } +/* To find LCA of nodes n1 and n2 in Binary Tree*/ + + Node LCA(Node n1, Node n2) + { +/* Find depths of two nodes and differences*/ + + int d1 = depth(n1), d2 = depth(n2); + int diff = d1 - d2; +/* If n2 is deeper, swap n1 and n2*/ + + if (diff < 0) + { + Node temp = n1; + n1 = n2; + n2 = temp; + diff = -diff; + } +/* Move n1 up until it reaches the same level as n2*/ + + while (diff-- != 0) + n1 = n1.parent; +/* Now n1 and n2 are at same levels*/ + + while (n1 != null && n2 != null) + { + if (n1 == n2) + return n1; + n1 = n1.parent; + n2 = n2.parent; + } + return null; + } +/* Driver method to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = tree.insert(tree.root, 20); + tree.root = tree.insert(tree.root, 8); + tree.root = tree.insert(tree.root, 22); + tree.root = tree.insert(tree.root, 4); + tree.root = tree.insert(tree.root, 12); + tree.root = tree.insert(tree.root, 10); + tree.root = tree.insert(tree.root, 14); + tree.n1 = tree.root.left.right.left; + tree.n2 = tree.root.right; + tree.lca = tree.LCA(tree.n1, tree.n2); + System.out.println(""LCA of "" + tree.n1.key + "" and "" + tree.n2.key + + "" is "" + tree.lca.key); + } +}", +Maximum Subarray Sum Excluding Certain Elements,"/*Java Program to find max subarray +sum excluding some elements*/ + +import java.io.*; +class GFG { +/* Function to check the element + present in array B*/ + + static boolean isPresent(int B[], int m, int x) + { + for (int i = 0; i < m; i++) + if (B[i] == x) + return true; + return false; + } +/* Utility function for findMaxSubarraySum() + with the following parameters + A => Array A, + B => Array B, + n => Number of elements in Array A, + m => Number of elements in Array B*/ + + static int findMaxSubarraySumUtil(int A[], int B[], + int n, int m) + { +/* set max_so_far to INT_MIN*/ + + int max_so_far = -2147483648, curr_max = 0; + for (int i = 0; i < n; i++) + { +/* if the element is present in B, + set current max to 0 and move to + the next element*/ + + if (isPresent(B, m, A[i])) + { + curr_max = 0; + continue; + } +/* Proceed as in Kadane's Algorithm*/ + + curr_max = Math.max(A[i], curr_max + A[i]); + max_so_far = Math.max(max_so_far, curr_max); + } + return max_so_far; + } +/* Wrapper for findMaxSubarraySumUtil()*/ + + static void findMaxSubarraySum(int A[], int B[], int n, + int m) + { + int maxSubarraySum + = findMaxSubarraySumUtil(A, B, n, m); +/* This case will occour when all + elements of A are present + in B, thus no subarray can be formed*/ + + if (maxSubarraySum == -2147483648) + { + System.out.println(""Maximum Subarray Sum"" + + "" "" + + ""can't be found""); + } + else { + System.out.println(""The Maximum Subarray Sum = "" + + maxSubarraySum); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int A[] = { 3, 4, 5, -4, 6 }; + int B[] = { 1, 8, 5 }; + int n = A.length; + int m = B.length; +/* Function call*/ + + findMaxSubarraySum(A, B, n, m); + } +}"," '''Python Program to find max +subarray sum excluding some +elements''' + + '''Function to check the element +present in array B''' + +INT_MIN = -2147483648 +def isPresent(B, m, x): + for i in range(0, m): + if B[i] == x: + return True + return False '''Utility function for findMaxSubarraySum() +with the following parameters +A => Array A, +B => Array B, +n => Number of elements in Array A, +m => Number of elements in Array B''' + +def findMaxSubarraySumUtil(A, B, n, m): + ''' set max_so_far to INT_MIN''' + + max_so_far = INT_MIN + curr_max = 0 + for i in range(0, n): + '''if the element is present in B, + set current max to 0 and move to + the next element''' + + if isPresent(B, m, A[i]) == True: + curr_max = 0 + continue + ''' Proceed as in Kadane's Algorithm''' + + curr_max = max(A[i], curr_max + A[i]) + max_so_far = max(max_so_far, curr_max) + return max_so_far + '''Wrapper for findMaxSubarraySumUtil()''' + +def findMaxSubarraySum(A, B, n, m): + maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m) + ''' This case will occour when all + elements of A are present + in B, thus no subarray can be + formed''' + + if maxSubarraySum == INT_MIN: + print('Maximum Subarray Sum cant be found') + else: + print('The Maximum Subarray Sum =', + maxSubarraySum) + '''Driver code''' + +A = [3, 4, 5, -4, 6] +B = [1, 8, 5] +n = len(A) +m = len(B) + '''Function call''' + +findMaxSubarraySum(A, B, n, m)" +Length of the largest subarray with contiguous elements | Set 1,"class LargestSubArray2 +{ +/* Utility functions to find minimum and maximum of + two elements*/ + + int min(int x, int y) + { + return (x < y) ? x : y; + } + int max(int x, int y) + { + return (x > y) ? x : y; + } +/* Returns length of the longest contiguous subarray*/ + + int findLength(int arr[], int n) + { +/*Initialize result*/ + +int max_len = 1; + for (int i = 0; i < n - 1; i++) + { +/* Initialize min and max for all subarrays starting with i*/ + + int mn = arr[i], mx = arr[i]; +/* Consider all subarrays starting with i and ending with j*/ + + for (int j = i + 1; j < n; j++) + { +/* Update min and max in this subarray if needed*/ + + mn = min(mn, arr[j]); + mx = max(mx, arr[j]); +/* If current subarray has all contiguous elements*/ + + if ((mx - mn) == j - i) + max_len = max(max_len, mx - mn + 1); + } + } +/*Return result*/ + +return max_len; + } +/*Driver Code*/ + + public static void main(String[] args) + { + LargestSubArray2 large = new LargestSubArray2(); + int arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; + int n = arr.length; + System.out.println(""Length of the longest contiguous subarray is "" + + large.findLength(arr, n)); + } +}"," '''Python3 program to find length +of the longest subarray''' + '''Utility functions to find minimum +and maximum of two elements''' + +def min(x, y): + return x if(x < y) else y +def max(x, y): + return x if(x > y) else y + '''Returns length of the longest +contiguous subarray''' + +def findLength(arr, n): + ''' Initialize result''' + + max_len = 1 + for i in range(n - 1): + ''' Initialize min and max for + all subarrays starting with i''' + + mn = arr[i] + mx = arr[i] + ''' Consider all subarrays starting + with i and ending with j''' + + for j in range(i + 1, n): + ''' Update min and max in + this subarray if needed''' + + mn = min(mn, arr[j]) + mx = max(mx, arr[j]) + ''' If current subarray has + all contiguous elements''' + + if ((mx - mn) == j - i): + max_len = max(max_len, mx - mn + 1) + + '''Return result''' + + return max_len '''Driver Code''' + +arr = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45] +n = len(arr) +print(""Length of the longest contiguous subarray is "", + findLength(arr, n))" +Find Union and Intersection of two unsorted arrays,"/*Java program for the above approach*/ + +import java.io.*; +import java.util.*; +class GFG{ +static void printUnion(int[] a, int n, + int[] b, int m) +{ +/* Defining map container mp*/ + + Map mp = new HashMap(); +/* Inserting array elements in mp*/ + + for(int i = 0; i < n; i++) + { + mp.put(a[i], i); + } + for(int i = 0; i < m; i++) + { + mp.put(b[i], i); + } + System.out.println(""The union set of both arrays is :""); + for(Map.Entry mapElement : mp.entrySet()) + { + System.out.print(mapElement.getKey() + "" ""); + + } +}/*Driver Code*/ + +public static void main (String[] args) +{ + int a[] = { 1, 2, 5, 6, 2, 3, 5 }; + int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; + printUnion(a, 7, b, 9); +} +}", +Practice questions for Linked List and Recursion,"/*Java code implementation for above approach*/ + +class GFG +{ + /* A linked list node */ + + static class Node + { + int data; + Node next; + }; + /* Prints a linked list in reverse manner */ + + static void fun1(Node head) + { + if (head == null) + { + return; + } + fun1(head.next); + System.out.print(head.data + "" ""); + } + /* prints alternate nodes of a Linked List, first + from head to end, and then from end to head. */ + + static void fun2(Node start) + { + if (start == null) + { + return; + } + System.out.print(start.data + "" ""); + if (start.next != null) + { + fun2(start.next.next); + } + System.out.print(start.data + "" ""); + } + /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */ + + /* 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. */ + + static Node push(Node head_ref, int new_data) + { + /* allocate node */ + + Node new_node = new Node(); + /* put in the data */ + + new_node.data = new_data; + /* link the old list off the new node */ + + new_node.next = (head_ref); + /* move the head to point to the new node */ + + (head_ref) = new_node; + return head_ref; + } + /* Driver code */ + + public static void main(String[] args) + { + /* Start with the empty list */ + + Node head = null; + /* Using push() to conbelow list + 1->2->3->4->5 */ + + head = push(head, 5); + head = push(head, 4); + head = push(head, 3); + head = push(head, 2); + head = push(head, 1); + System.out.print(""Output of fun1() for "" + + ""list 1->2->3->4->5 \n""); + fun1(head); + System.out.print(""\nOutput of fun2() for "" + + ""list 1->2->3->4->5 \n""); + fun2(head); + } +}"," ''' A linked list node ''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + ''' Prints a linked list in reverse manner ''' + +def fun1(head): + if(head == None): + return + fun1(head.next) + print(head.data, end = "" "") + ''' prints alternate nodes of a Linked List, first +from head to end, and then from end to head. ''' + +def fun2(start): + if(start == None): + return + print(start.data, end = "" "") + if(start.next != None ): + fun2(start.next.next) + print(start.data, end = "" "") + ''' UTILITY FUNCTIONS TO TEST fun1() and fun2() ''' + + ''' 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. ''' + +def push( head, new_data): + ''' put in the data ''' + + new_node = Node(new_data) + ''' link the old list off the new node ''' + + new_node.next = head + ''' move the head to poto the new node ''' + + head = new_node + return head + ''' Driver code ''' + + ''' Start with the empty list ''' + +head = None + ''' Using push() to construct below list + 1.2.3.4.5 ''' + +head = Node(5) +head = push(head, 4) +head = push(head, 3) +head = push(head, 2) +head = push(head, 1) +print(""Output of fun1() for list 1->2->3->4->5"") +fun1(head) +print(""\nOutput of fun2() for list 1->2->3->4->5"") +fun2(head)" +Print Left View of a Binary Tree,"/*Java program to print left view of binary tree*/ + + +/* Class containing left and right child of current +node and key value*/ + +class Node { + int data; + Node left, right; + + public Node(int item) + { + data = item; + left = right = null; + } +} + +/* Class to print the left view */ + +class BinaryTree { + Node root; + static int max_level = 0; + +/* recursive function to print left view*/ + + void leftViewUtil(Node node, int level) + { +/* Base Case*/ + + if (node == null) + return; + +/* If this is the first node of its level*/ + + if (max_level < level) { + System.out.print("" "" + node.data); + max_level = level; + } + +/* Recur for left and right subtrees*/ + + leftViewUtil(node.left, level + 1); + leftViewUtil(node.right, level + 1); + } + +/* A wrapper over leftViewUtil()*/ + + void leftView() + { + leftViewUtil(root, 1); + } + + /* testing for example nodes */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(12); + tree.root.left = new Node(10); + tree.root.right = new Node(30); + tree.root.right.left = new Node(25); + tree.root.right.right = new Node(40); + + tree.leftView(); + } +} + "," '''Python program to print left view of Binary Tree''' + + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + '''Recursive function pritn left view of a binary tree''' + +def leftViewUtil(root, level, max_level): + + ''' Base Case''' + + if root is None: + return + + ''' If this is the first node of its level''' + + if (max_level[0] < level): + print ""% d\t"" %(root.data), + max_level[0] = level + + ''' Recur for left and right subtree''' + + leftViewUtil(root.left, level + 1, max_level) + leftViewUtil(root.right, level + 1, max_level) + + + '''A wrapper over leftViewUtil()''' + +def leftView(root): + max_level = [0] + leftViewUtil(root, 1, max_level) + + + '''Driver program to test above function''' + +root = Node(12) +root.left = Node(10) +root.right = Node(20) +root.right.left = Node(25) +root.right.right = Node(40) + +leftView(root) + + +" +Segregate even and odd numbers | Set 3,"/*java code to segregate even odd +numbers in an array*/ + +public class GFG { +/* Function to segregate even + odd numbers*/ + + static void arrayEvenAndOdd( + int arr[], int n) + { + int i = -1, j = 0; + while (j != n) { + if (arr[j] % 2 == 0) + { + i++; +/* Swapping even and + odd numbers*/ + + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + j++; + } +/* Printing segregated array*/ + + for (int k = 0; k < n; k++) + System.out.print(arr[k] + "" ""); + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 3, 2, 4, 7, + 6, 9, 10 }; + int n = arr.length; + arrayEvenAndOdd(arr, n); + } +}"," '''Python3 code to segregate even odd +numbers in an array + ''' '''Function to segregate even odd numbers''' + +def arrayEvenAndOdd(arr,n): + i = -1 + j= 0 + while (j!=n): + if (arr[j] % 2 ==0): + i = i+1 + ''' Swapping even and odd numbers''' + + arr[i],arr[j] = arr[j],arr[i] + j = j+1 + ''' Printing segregated array''' + + for i in arr: + print (str(i) + "" "" ,end='') + '''Driver Code''' + +if __name__=='__main__': + arr = [ 1 ,3, 2, 4, 7, 6, 9, 10] + n = len(arr) + arrayEvenAndOdd(arr,n)" +Find the closest leaf in a Binary Tree,"/*Java program to find closest leaf of a given key in Binary Tree*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* A utility function to find minimum of x and y*/ + + int getMin(int x, int y) + { + return (x < y) ? x : y; + } +/* A utility function to find distance of closest leaf of the tree + rooted under given root*/ + + int closestDown(Node node) + { +/* Base cases*/ + + if (node == null) + return Integer.MAX_VALUE; + if (node.left == null && node.right == null) + return 0; +/* Return minimum of left and right, plus one*/ + + return 1 + getMin(closestDown(node.left), closestDown(node.right)); + } +/* Returns distance of the cloest leaf to a given key 'k'. The array + ancestors is used to keep track of ancestors of current node and + 'index' is used to keep track of curremt index in 'ancestors[]'*/ + + int findClosestUtil(Node node, char k, Node ancestors[], int index) + { +/* Base case*/ + + if (node == null) + return Integer.MAX_VALUE; +/* If key found*/ + + if (node.data == k) + { +/* Find the cloest leaf under the subtree rooted with given key*/ + + int res = closestDown(node); +/* Traverse all ancestors and update result if any parent node + gives smaller distance*/ + + for (int i = index - 1; i >= 0; i--) + res = getMin(res, index - i + closestDown(ancestors[i])); + return res; + } +/* If key node found, store current node and recur for left and + right childrens*/ + + ancestors[index] = node; + return getMin(findClosestUtil(node.left, k, ancestors, index + 1), + findClosestUtil(node.right, k, ancestors, index + 1)); + } +/* The main function that returns distance of the closest key to 'k'. It + mainly uses recursive function findClosestUtil() to find the closes + distance.*/ + + int findClosest(Node node, char k) + { +/* Create an array to store ancestors + Assumptiom: Maximum height of tree is 100*/ + + Node ancestors[] = new Node[100]; + return findClosestUtil(node, k, ancestors, 0); + } +/* Driver program to test for above functions*/ + + public static void main(String args[]) + { +/* Let us construct the BST shown in the above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node('A'); + tree.root.left = new Node('B'); + tree.root.right = new Node('C'); + tree.root.right.left = new Node('E'); + tree.root.right.right = new Node('F'); + tree.root.right.left.left = new Node('G'); + tree.root.right.left.left.left = new Node('I'); + tree.root.right.left.left.right = new Node('J'); + tree.root.right.right.right = new Node('H'); + tree.root.right.right.right.left = new Node('H'); + char k = 'H'; + System.out.println(""Distance of the closest key from "" + k + "" is "" + + tree.findClosest(tree.root, k)); + k = 'C'; + System.out.println(""Distance of the closest key from "" + k + "" is "" + + tree.findClosest(tree.root, k)); + k = 'E'; + System.out.println(""Distance of the closest key from "" + k + "" is "" + + tree.findClosest(tree.root, k)); + k = 'B'; + System.out.println(""Distance of the closest key from "" + k + "" is "" + + tree.findClosest(tree.root, k)); + } +}"," '''Python program to find closest leaf of a +given key in binary tree''' + +INT_MAX = 2**32 + '''A binary tree node''' + +class Node: + def __init__(self ,key): + self.key = key + self.left = None + self.right = None ''' A utility function to find distance of closest leaf of the tree + rooted under given root''' + +def closestDown(root): + ''' Base Case''' + + if root is None: + return INT_MAX + if root.left is None and root.right is None: + return 0 + ''' Return minum of left and right plus one''' + + return 1 + min(closestDown(root.left), + closestDown(root.right)) + '''Returns destance of the closes leaf to a given key k +The array ancestors us used to keep track of ancestors +of current node and 'index' is used to keep track of +current index in 'ancestors[i]''' + ''' +def findClosestUtil(root, k, ancestors, index): + ''' Base Case ''' + + if root is None: + return INT_MAX + ''' if key found''' + + if root.key == k: + ''' Find closest leaf under the subtree rooted + with given key''' + + res = closestDown(root) + ''' Traverse ll ancestors and update result if any + parent node gives smaller distance''' + + for i in reversed(range(0,index)): + res = min(res, index-i+closestDown(ancestors[i])) + return res + ''' if key node found, store current node and recur for left + and right childrens''' + + ancestors[index] = root + return min( + findClosestUtil(root.left, k,ancestors, index+1), + findClosestUtil(root.right, k, ancestors, index+1)) + '''The main function that return distance of the clses key to + '''key'. It mainly uses recursive function findClosestUtil() +to find the closes distance''' + +def findClosest(root, k): + ''' Create an arrray to store ancestors + Assumption: Maximum height of tree is 100''' + + ancestors = [None for i in range(100)] + return findClosestUtil(root, k, ancestors, 0) + '''Driver program to test above function''' + + ''' Let us construct the BST shown in the above figure''' + +root = Node('A') +root.left = Node('B') +root.right = Node('C'); +root.right.left = Node('E'); +root.right.right = Node('F'); +root.right.left.left = Node('G'); +root.right.left.left.left = Node('I'); +root.right.left.left.right = Node('J'); +root.right.right.right = Node('H'); +root.right.right.right.left = Node('K'); +k = 'H'; +print ""Distance of the closest key from ""+ k + "" is"", +print findClosest(root, k) +k = 'C' +print ""Distance of the closest key from "" + k + "" is"", +print findClosest(root, k) +k = 'E' +print ""Distance of the closest key from "" + k + "" is"", +print findClosest(root, k) +k = 'B' +print ""Distance of the closest key from "" + k + "" is"", +print findClosest(root, k)" +"Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)","/*Java implementation of the approach*/ + +public class GFG { +/* Linearly search x in arr[]. If x is present then + return the index, otherwise return -1*/ + + static int search(int arr[], int n, int x) + { + int i; + for (i = 0; i < n; i++) { + if (arr[i] == x) { + return i; + } + } + return -1; + } + /* Driver program to test above functions*/ + + public static void main(String[] args) + { + int arr[] = { 1, 10, 30, 15 }; + int x = 30; + int n = arr.length; + System.out.printf(""%d is present at index %d"", x, + search(arr, n, x)); + } +}"," '''Python 3 implementation of the approach + ''' '''Linearly search x in arr[]. If x is present +then return the index, otherwise return -1''' + +def search(arr, x): + for index, value in enumerate(arr): + if value == x: + return index + return -1 + '''Driver Code''' + +arr = [1, 10, 30, 15] +x = 30 +print(x, ""is present at index"", + search(arr, x))" +C Program To Check whether Matrix is Skew Symmetric or not,"/*java program to check +whether given matrix +is skew-symmetric or not*/ + +import java.io.*; +class GFG { +static int ROW =3; +static int COL =3; +/*Utility function to create transpose matrix*/ + + static void transpose(int transpose_matrix[][], + int matrix[][]) +{ +for (int i = 0; i < ROW; i++) + for (int j = 0; j < COL; j++) + transpose_matrix[j][i] = matrix[i][j]; +} +/*Utility function to check skew - symmetric +matrix condition*/ + + static boolean check(int transpose_matrix[][], + int matrix[][]) +{ + for (int i = 0; i < ROW; i++) + for (int j = 0; j < COL; j++) + if (matrix[i][j] != -transpose_matrix[i][j]) + return false; + return true; +} +/*Utility function to print a matrix*/ + + static void printMatrix(int matrix[][]) +{ + for (int i = 0; i < ROW; i++) + { + for (int j = 0; j < COL; j++) + System.out.print(matrix[i][j] + "" ""); + System.out.println(); + } +} +/*Driver program to test above functions*/ + +public static void main (String[] args) { + int matrix[][] = { + {0, 5, -4}, + {-5, 0, 1}, + {4, -1, 0}, + }; + int transpose_matrix[][] = new int[ROW][COL]; +/* Function create transpose matrix*/ + + transpose(transpose_matrix, matrix); + System.out.println (""Transpose matrix: ""); + printMatrix(transpose_matrix); +/* Check whether matrix is skew-symmetric or not*/ + + if (check(transpose_matrix, matrix)) + System.out.println(""Skew Symmetric Matrix""); + else + System.out.println(""Not Skew Symmetric Matrix""); + } +}"," '''Python 3 program to check +whether given matrix +is skew-symmetric or not''' + +ROW=3 +COL=3 + '''Utility function to +create transpose matrix''' + +def transpose(transpose_matrix,matrix): + for i in range (ROW): + for j in range(COL): + transpose_matrix[j][i] = matrix[i][j] + '''Utility function to +check skew - symmetric +matrix condition''' + +def check(transpose_matrix,matrix): + for i in range(ROW): + for j in range(COL): + if (matrix[i][j] != -transpose_matrix[i][j]): + return False + return True + '''Utility function to print a matrix''' + +def printMatrix(matrix): + for i in range (ROW): + for j in range(COL): + print(matrix[i][j],"" "",end="""") + print() + '''Driver program to test above functions''' + +matrix= [ + [0, 5, -4], + [-5, 0, 1], + [4, -1, 0], + ] +transpose_matrix=[[0 for i in range(3)] for j in range(3)] + '''Function create transpose matrix''' + +transpose(transpose_matrix, matrix) +print(""Transpose matrix:"") +printMatrix(transpose_matrix) + '''Check whether matrix is +skew-symmetric or not''' + +if (check(transpose_matrix, matrix)): + print(""Skew Symmetric Matrix"") +else: + print(""Not Skew Symmetric Matrix"")" +Program to check if an array is sorted or not (Iterative and Recursive),"/*Recursive approach to check if an +Array is sorted or not*/ + +class GFG { + +/* Function that returns true if array is + sorted in non-decreasing order.*/ + + static boolean arraySortedOrNot(int arr[], int n) + { + +/* Array has one or no element*/ + + if (n == 0 || n == 1) + return true; + + for (int i = 1; i < n; i++) + +/* Unsorted pair found*/ + + if (arr[i - 1] > arr[i]) + return false; + +/* No unsorted pair found*/ + + return true; + } + +/* driver code*/ + + public static void main(String[] args) + { + + int arr[] = { 20, 23, 23, 45, 78, 88 }; + int n = arr.length; + + if (arraySortedOrNot(arr, n)) + System.out.print(""Yes\n""); + else + System.out.print(""No\n""); + } +} + + +"," '''Python3 program to check if an +Array is sorted or not''' + + + '''Function that returns true if array is +sorted in non-decreasing order.''' + +def arraySortedOrNot(arr, n): + + ''' Array has one or no element''' + + if (n == 0 or n == 1): + return True + + for i in range(1, n): + + ''' Unsorted pair found''' + + if (arr[i-1] > arr[i]): + return False + + ''' No unsorted pair found''' + + return True + + + '''Driver code''' + +arr = [20, 23, 23, 45, 78, 88] +n = len(arr) +if (arraySortedOrNot(arr, n)): + print(""Yes"") +else: + print(""No"") + + +" +Number of pairs with maximum sum,"/*Java program to count pairs +with maximum sum.*/ + +import java.io.*; +class GFG { + +/*function to find the number +of maximum pair sums*/ + +static int sum(int a[], int n) +{ +/* Find maximum and second maximum + elements. Also find their counts.*/ + + int maxVal = a[0], maxCount = 1; + int secondMax = Integer.MIN_VALUE, + secondMaxCount = 0; + for (int i = 1; i < n; i++) { + if (a[i] == maxVal) + maxCount++; + else if (a[i] > maxVal) { + secondMax = maxVal; + secondMaxCount = maxCount; + maxVal = a[i]; + maxCount = 1; + } + else if (a[i] == secondMax) { + secondMax = a[i]; + secondMaxCount++; + } + else if (a[i] > secondMax) { + secondMax = a[i]; + secondMaxCount = 1; + } + } + +/* If maximum element appears + more than once.*/ + + if (maxCount > 1) + return maxCount * (maxCount - 1) / 2; + +/* If maximum element appears + only once.*/ + + return secondMaxCount; +} + +/*driver program*/ + +public static void main(String[] args) +{ + int array[] = { 1, 1, 1, 2, 2, 2, 3 }; + int n = array.length; + System.out.println(sum(array, n)); +} +} + + +"," '''Python 3 program to count +pairs with maximum sum.''' + +import sys + + '''Function to find the number +of maximum pair sums''' + +def sum(a, n): + + ''' Find maximum and second maximum elements. + Also find their counts.''' + + maxVal = a[0]; maxCount = 1 + secondMax = sys.maxsize + + for i in range(1, n) : + + if (a[i] == maxVal) : + maxCount += 1 + + elif (a[i] > maxVal) : + secondMax = maxVal + secondMaxCount = maxCount + maxVal = a[i] + maxCount = 1 + + elif (a[i] == secondMax) : + secondMax = a[i] + secondMaxCount += 1 + + elif (a[i] > secondMax) : + secondMax = a[i] + secondMaxCount = 1 + + ''' If maximum element appears more than once.''' + + if (maxCount > 1): + return maxCount * (maxCount - 1) / 2 + + ''' If maximum element appears only once.''' + + return secondMaxCount + + '''Driver Code''' + +array = [1, 1, 1, 2, 2, 2, 3] +n = len(array) +print(sum(array, n)) + + + +" +Maximum sum of nodes in Binary tree such that no two are adjacent,"/*Java program to find maximum sum from a subset of +nodes of binary tree*/ + +import java.util.HashMap; +public class FindSumOfNotAdjacentNodes { +/* A binary tree node structure */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + this.data=data; + left=right=null; + } +};/* method returns maximum sum possible from subtrees rooted + at grandChildrens of node 'node'*/ + + public static int sumOfGrandChildren(Node node, HashMap mp) + { + int sum = 0; +/* call for children of left child only if it is not NULL*/ + + if (node.left!=null) + sum += getMaxSumUtil(node.left.left, mp) + + getMaxSumUtil(node.left.right, mp); +/* call for children of right child only if it is not NULL*/ + + if (node.right!=null) + sum += getMaxSumUtil(node.right.left, mp) + + getMaxSumUtil(node.right.right, mp); + return sum; + } +/* Utility method to return maximum sum rooted at node 'node'*/ + + public static int getMaxSumUtil(Node node, HashMap mp) + { + if (node == null) + return 0; +/* If node is already processed then return calculated + value from map*/ + + if(mp.containsKey(node)) + return mp.get(node); +/* take current node value and call for all grand children*/ + + int incl = node.data + sumOfGrandChildren(node, mp); +/* don't take current node value and call for all children*/ + + int excl = getMaxSumUtil(node.left, mp) + + getMaxSumUtil(node.right, mp); +/* choose maximum from both above calls and store that in map*/ + + mp.put(node,Math.max(incl, excl)); + return mp.get(node); + } +/* Returns maximum sum from subset of nodes + of binary tree under given constraints*/ + + public static int getMaxSum(Node node) + { + if (node == null) + return 0; + HashMap mp=new HashMap<>(); + return getMaxSumUtil(node, mp); + } + +/* Driver code to test above methods*/ + + public static void main(String args[]) + { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.right.left = new Node(4); + root.right.right = new Node(5); + root.left.left = new Node(1); + System.out.print(getMaxSum(root)); + } +}"," '''Python3 program to find +maximum sum from a subset +of nodes of binary tree''' + + '''A binary tree node structure''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Utility function to create +a new Binary Tree node''' + +def newNode(data): + temp = Node(data) + return temp; + '''method returns maximum sum +possible from subtrees rooted +at grandChildrens of node''' +def sumOfGrandChildren(node, mp): + sum = 0; + ''' call for children of left + child only if it is not NULL''' + + if (node.left): + sum += (getMaxSumUtil(node.left.left, mp) + + getMaxSumUtil(node.left.right, mp)); + ''' call for children of right + child only if it is not NULL''' + + if (node.right): + sum += (getMaxSumUtil(node.right.left, mp) + + getMaxSumUtil(node.right.right, mp)); + return sum; + '''Utility method to return +maximum sum rooted at node + ''' +def getMaxSumUtil(node, mp): + if (node == None): + return 0; + ''' If node is already processed + then return calculated + value from map''' + + if node in mp: + return mp[node]; + ''' take current node value + and call for all grand children''' + + incl = (node.data + + sumOfGrandChildren(node, mp)); + ''' don't take current node + value and call for all children''' + + excl = (getMaxSumUtil(node.left, mp) + + getMaxSumUtil(node.right, mp)); + ''' choose maximum from both + above calls and store that + in map''' + + mp[node] = max(incl, excl); + return mp[node]; + '''Returns maximum sum from +subset of nodes of binary +tree under given constraints''' + +def getMaxSum(node): + if (node == None): + return 0; + mp = dict() + return getMaxSumUtil(node, mp); + '''Driver code''' + +if __name__==""__main__"": + root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.right.left = newNode(4); + root.right.right = newNode(5); + root.left.left = newNode(1); + print(getMaxSum(root))" +Word Wrap Problem | DP-19,"/*A Dynamic programming solution for +Word Wrap Problem in Java*/ + +public class WordWrap +{ + final int MAX = Integer.MAX_VALUE; +/* A utility function to print the solution*/ + + int printSolution (int p[], int n) + { + int k; + if (p[n] == 1) + k = 1; + else + k = printSolution (p, p[n]-1) + 1; + System.out.println(""Line number"" + "" "" + k + "": "" + + ""From word no."" +"" ""+ p[n] + "" "" + ""to"" + "" "" + n); + return k; + } +/*l[] represents lengths of different words in input sequence. +For example, l[] = {3, 2, 2, 5} is for a sentence like +""aaa bb cc ddddd"". n is size of l[] and M is line width +(maximum no. of characters that can fit in a line)*/ + + void solveWordWrap (int l[], int n, int M) + { +/* For simplicity, 1 extra space is used in all below arrays + extras[i][j] will have number of extra spaces if words from i + to j are put in a single line*/ + + int extras[][] = new int[n+1][n+1]; +/* lc[i][j] will have cost of a line which has words from + i to j*/ + + int lc[][]= new int[n+1][n+1]; +/* c[i] will have total cost of optimal arrangement of words + from 1 to i*/ + + int c[] = new int[n+1]; +/* p[] is used to print the solution.*/ + + int p[] =new int[n+1]; +/* calculate extra spaces in a single line. The value extra[i][j] + indicates extra spaces if words from word number i to j are + placed in a single line*/ + + for (int i = 1; i <= n; i++) + { + extras[i][i] = M - l[i-1]; + for (int j = i+1; j <= n; j++) + extras[i][j] = extras[i][j-1] - l[j-1] - 1; + } +/* Calculate line cost corresponding to the above calculated extra + spaces. The value lc[i][j] indicates cost of putting words from + word number i to j in a single line*/ + + for (int i = 1; i <= n; i++) + { + for (int j = i; j <= n; j++) + { + if (extras[i][j] < 0) + lc[i][j] = MAX; + else if (j == n && extras[i][j] >= 0) + lc[i][j] = 0; + else + lc[i][j] = extras[i][j]*extras[i][j]; + } + } +/* Calculate minimum cost and find minimum cost arrangement. + The value c[j] indicates optimized cost to arrange words + from word number 1 to j.*/ + + c[0] = 0; + for (int j = 1; j <= n; j++) + { + c[j] = MAX; + for (int i = 1; i <= j; i++) + { + if (c[i-1] != MAX && lc[i][j] != MAX && + (c[i-1] + lc[i][j] < c[j])) + { + c[j] = c[i-1] + lc[i][j]; + p[j] = i; + } + } + } + printSolution(p, n); + } +/* Driver code*/ + + public static void main(String args[]) + { + WordWrap w = new WordWrap(); + int l[] = {3, 2, 2, 5}; + int n = l.length; + int M = 6; + w.solveWordWrap (l, n, M); + } +}"," '''A Dynamic programming solution +for Word Wrap Problem''' +INF = 2147483647 + '''A utility function to print +the solution''' + +def printSolution(p, n): + k = 0 + if p[n] == 1: + k = 1 + else: + k = printSolution(p, p[n] - 1) + 1 + print('Line number ', k, ': From word no. ', + p[n], 'to ', n) + return k '''l[] represents lengths of different +words in input sequence. For example, +l[] = {3, 2, 2, 5} is for a sentence +like ""aaa bb cc ddddd"". n is size of +l[] and M is line width (maximum no. +of characters that can fit in a line)''' + +def solveWordWrap (l, n, M): ''' For simplicity, 1 extra space is + used in all below arrays + extras[i][j] will have number + of extra spaces if words from i + to j are put in a single line''' + + extras = [[0 for i in range(n + 1)] + for i in range(n + 1)] + ''' lc[i][j] will have cost of a line + which has words from i to j''' + + lc = [[0 for i in range(n + 1)] + for i in range(n + 1)] + ''' c[i] will have total cost of + optimal arrangement of words + from 1 to i''' + + c = [0 for i in range(n + 1)] + ''' p[] is used to print the solution.''' + + p = [0 for i in range(n + 1)] + ''' calculate extra spaces in a single + line. The value extra[i][j] indicates + extra spaces if words from word number + i to j are placed in a single line''' + + for i in range(n + 1): + extras[i][i] = M - l[i - 1] + for j in range(i + 1, n + 1): + extras[i][j] = (extras[i][j - 1] - + l[j - 1] - 1) + ''' Calculate line cost corresponding + to the above calculated extra + spaces. The value lc[i][j] indicates + cost of putting words from word number + i to j in a single line''' + + for i in range(n + 1): + for j in range(i, n + 1): + if extras[i][j] < 0: + lc[i][j] = INF; + elif j == n and extras[i][j] >= 0: + lc[i][j] = 0 + else: + lc[i][j] = (extras[i][j] * + extras[i][j]) + ''' Calculate minimum cost and find + minimum cost arrangement. The value + c[j] indicates optimized cost to + arrange words from word number 1 to j.''' + + c[0] = 0 + for j in range(1, n + 1): + c[j] = INF + for i in range(1, j + 1): + if (c[i - 1] != INF and + lc[i][j] != INF and + ((c[i - 1] + lc[i][j]) < c[j])): + c[j] = c[i-1] + lc[i][j] + p[j] = i + printSolution(p, n) + '''Driver Code''' + +l = [3, 2, 2, 5] +n = len(l) +M = 6 +solveWordWrap(l, n, M)" +Minimum Index Sum for Common Elements of Two Lists,"import java.util.*; +class GFG +{ +/*Function to print common Strings with minimum index sum*/ + +static void find(Vector list1, Vector list2) +{ +/*resultant list*/ + +Vector res = new Vector<>(); + int max_possible_sum = list1.size() + list2.size() - 2; +/* iterating over sum in ascending order*/ + + for (int sum = 0; sum <= max_possible_sum ; sum++) + { +/* iterating over one list and check index + (Corresponding to given sum) in other list*/ + + for (int i = 0; i <= sum; i++) +/* put common Strings in resultant list*/ + + if (i < list1.size() && + (sum - i) < list2.size() && + list1.get(i) == list2.get(sum - i)) + res.add(list1.get(i)); +/* if common String found then break as we are + considering index sums in increasing order.*/ + + if (res.size() > 0) + break; + } +/* print the resultant list*/ + + for (int i = 0; i < res.size(); i++) + System.out.print(res.get(i)+"" ""); +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Creating list1*/ + + Vector list1 = new Vector<>(); + list1.add(""GeeksforGeeks""); + list1.add(""Udemy""); + list1.add(""Coursera""); + list1.add(""edX""); +/* Creating list2*/ + + Vector list2= new Vector<>(); + list2.add(""Codecademy""); + list2.add(""Khan Academy""); + list2.add(""GeeksforGeeks""); + find(list1, list2); +} +}"," '''Function to print common strings +with minimum index sum''' + +def find(list1, list2): + '''resultant list''' + + res = [] + max_possible_sum = len(list1) + len(list2) - 2 + ''' iterating over sum in ascending order''' + + for sum in range(max_possible_sum + 1): + ''' iterating over one list and check index + (Corresponding to given sum) in other list''' + + for i in range(sum + 1): + ''' put common strings in resultant list''' + + if (i < len(list1) and + (sum - i) < len(list2) and + list1[i] == list2[sum - i]): + res.append(list1[i]) + ''' if common string found then break as we are + considering index sums in increasing order.''' + + if (len(res) > 0): + break + ''' print the resultant list''' + + for i in range(len(res)): + print(res[i], end = "" "") + '''Driver code''' + + '''Creating list1''' + +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") '''Creating list2''' + +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") +find(list1, list2)" +ShellSort,"/*Java implementation of ShellSort*/ + +class ShellSort +{ + /* An utility function to print array of size n*/ + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i 0; gap /= 2) + { +/* Do a gapped insertion sort for this gap size. + The first gap elements a[0..gap-1] are already + in gapped order keep adding one more element + until the entire array is gap sorted*/ + + for (int i = gap; i < n; i += 1) + { +/* add a[i] to the elements that have been gap + sorted save a[i] in temp and make a hole at + position i*/ + + int temp = arr[i]; +/* shift earlier gap-sorted elements up until + the correct location for a[i] is found*/ + + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; +/* put temp (the original a[i]) in its correct + location*/ + + arr[j] = temp; + } + } + return 0; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = {12, 34, 54, 2, 3}; + System.out.println(""Array before sorting""); + printArray(arr); + ShellSort ob = new ShellSort(); + ob.sort(arr); + System.out.println(""Array after sorting""); + printArray(arr); + } +}", +Largest Rectangular Area in a Histogram | Set 2,"/*Java program to find maximum rectangular area in linear time*/ + +import java.util.Stack; +public class RectArea +{ +/* The main function to find the maximum rectangular area under given + histogram with n bars*/ + + static int getMaxArea(int hist[], int n) + { +/* Create an empty stack. The stack holds indexes of hist[] array + The bars stored in stack are always in increasing order of their + heights.*/ + + Stack s = new Stack<>(); +/*Initialize max area*/ + +int max_area = 0; +/*To store top of stack*/ + +int tp; +/*To store area with top bar as the smallest bar*/ + +int area_with_top; +/* Run through all bars of given histogram*/ + + int i = 0; + while (i < n) + { +/* If this bar is higher than the bar on top stack, push it to stack*/ + + if (s.empty() || hist[s.peek()] <= hist[i]) + s.push(i++); +/* If this bar is lower than top of stack, then calculate area of rectangle + with stack top as the smallest (or minimum height) bar. 'i' is + 'right index' for the top and element before top in stack is 'left index'*/ + + else + { +/*store the top index*/ + +tp = s.peek(); +/*pop the top*/ + +s.pop(); +/* Calculate the area with hist[tp] stack as smallest bar*/ + + area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1); +/* update max area, if needed*/ + + if (max_area < area_with_top) + max_area = area_with_top; + } + } +/* Now pop the remaining bars from stack and calculate area with every + popped bar as the smallest bar*/ + + while (s.empty() == false) + { + tp = s.peek(); + s.pop(); + area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1); + if (max_area < area_with_top) + max_area = area_with_top; + } + return max_area; + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int hist[] = { 6, 2, 5, 4, 5, 1, 6 }; + System.out.println(""Maximum area is "" + getMaxArea(hist, hist.length)); + } +} +", +Find if an array of strings can be chained to form a circle | Set 2,," '''Python3 code to check if +cyclic order is possible +among strings under given +constrainsts''' + +M = 26 + '''Utility method for a depth +first search among vertices''' + +def dfs(g, u, visit): + visit[u] = True + for i in range(len(g[u])): + if(not visit[g[u][i]]): + dfs(g, g[u][i], visit) + '''Returns true if all vertices +are strongly connected i.e. +can be made as loop''' + +def isConnected(g, mark, s): + ''' Initialize all vertices + as not visited''' + + visit = [False for i in range(M)] + ''' Perform a dfs from s''' + + dfs(g, s, visit) + ''' Now loop through + all characters''' + + for i in range(M): + ''' I character is marked + (i.e. it was first or last + character of some string) + then it should be visited + in last dfs (as for looping, + graph should be strongly + connected) */''' + + if(mark[i] and (not visit[i])): + return False + ''' If we reach that means + graph is connected''' + + return True + '''return true if an order among +strings is possible''' + +def possibleOrderAmongString(arr, N): + ''' Create an empty graph''' + + g = {} + ''' Initialize all vertices + as not marked''' + + mark = [False for i in range(M)] + ''' Initialize indegree and + outdegree of every + vertex as 0.''' + + In = [0 for i in range(M)] + out = [0 for i in range(M)] + ''' Process all strings + one by one''' + + for i in range(N): + ''' Find first and last + characters''' + + f = (ord(arr[i][0]) - + ord('a')) + l = (ord(arr[i][-1]) - + ord('a')) + ''' Mark the characters''' + + mark[f] = True + mark[l] = True + ''' Increase indegree + and outdegree count''' + + In[l] += 1 + out[f] += 1 + if f not in g: + g[f] = [] + ''' Add an edge in graph''' + + g[f].append(l) + ''' If for any character + indegree is not equal to + outdegree then ordering + is not possible''' + + for i in range(M): + if(In[i] != out[i]): + return False + return isConnected(g, mark, + ord(arr[0][0]) - + ord('a')) + '''Driver code''' + +arr = [""ab"", ""bc"", + ""cd"", ""de"", + ""ed"", ""da""] +N = len(arr) +if(possibleOrderAmongString(arr, N) == + False): + print(""Ordering not possible"") +else: + print(""Ordering is possible"")" +"Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n","/*An efficient Java program to +find different (x, y) pairs +that satisfy x*x + y*y < n.*/ + +import java.io.*; +class GFG +{ +/* This function counts number + of pairs (x, y) that satisfy + the inequality x*x + y*y < n.*/ + + static int countSolutions(int n) + { + int x = 0, yCount, res = 0; +/* Find the count of different + y values for x = 0.*/ + + for (yCount = 0; yCount * yCount < n; yCount++) ; +/* One by one increase value of x, + and find yCount forcurrent x. If + yCount becomes 0, then we have reached + maximum possible value of x.*/ + + while (yCount != 0) + { +/* Add yCount (count of different possible + values of y for current x) to result*/ + + res += yCount; +/* Increment x*/ + + x++; +/* Update yCount for current x. Keep reducing + yCount while the inequality is not satisfied.*/ + + while (yCount != 0 && (x * x + (yCount - 1) + * (yCount - 1) >= n)) + yCount--; + } + return res; + } +/* Driver program*/ + + public static void main(String args[]) + { + System.out.println ( ""Total Number of distinct Non-Negative pairs is "" + +countSolutions(6)) ; + } +}"," '''An efficient python program to +find different (x, y) pairs +that satisfy x*x + y*y < n.''' + '''This function counts number of +pairs (x, y) that satisfy the +inequality x*x + y*y < n.''' + +def countSolutions(n): + x = 0 + res = 0 + yCount = 0 + ''' Find the count of different + y values for x = 0.''' + + while(yCount * yCount < n): + yCount = yCount + 1 + ''' One by one increase value of + x, and find yCount for current + x. If yCount becomes 0, then + we have reached maximum + possible value of x.''' + + while (yCount != 0): + ''' Add yCount (count of + different possible values + of y for current x) to + result''' + + res = res + yCount + ''' Increment x''' + + x = x + 1 + ''' Update yCount for current + x. Keep reducing yCount + while the inequality is + not satisfied.''' + + while (yCount != 0 and (x * x + + (yCount - 1) * + (yCount - 1) >= n)): + yCount = yCount - 1 + return res + '''Driver program to test +above function''' + +print (""Total Number of distinct "", + ""Non-Negative pairs is "" + , countSolutions(6))" +Maximum consecutive numbers present in an array,"/*Java program to find largest consecutive +numbers present in arr[].*/ + +import java.util.*; +class GFG +{ +static int findLongestConseqSubseq(int arr[], int n) +{ + /* We insert all the array elements into + unordered set. */ + + HashSet S = new HashSet(); + for (int i = 0; i < n; i++) + S.add(arr[i]); +/* check each possible sequence from the start + then update optimal length*/ + + int ans = 0; + for (int i = 0; i < n; i++) + { +/* if current element is the starting + element of a sequence*/ + + if(S.contains(arr[i])) + { +/* Then check for next elements in the + sequence*/ + + int j = arr[i]; +/* increment the value of array element + and repeat search in the set*/ + + while (S.contains(j)) + j++; +/* Update optimal length if this length + is more. To get the length as it is + incremented one by one*/ + + ans = Math.max(ans, j - arr[i]); + } + } + return ans; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {1, 94, 93, 1000, 5, 92, 78}; + int n = arr.length; + System.out.println(findLongestConseqSubseq(arr, n)); +} +}"," '''Python3 program to find largest consecutive +numbers present in arr.''' + +def findLongestConseqSubseq(arr, n): + '''We insert all the array elements into unordered set.''' + + S = set(); + for i in range(n): + S.add(arr[i]); + ''' check each possible sequence from the start + then update optimal length''' + + ans = 0; + for i in range(n): + ''' if current element is the starting + element of a sequence''' + + if S.__contains__(arr[i]): + ''' Then check for next elements in the + sequence''' + + j = arr[i]; + ''' increment the value of array element + and repeat search in the set''' + + while(S.__contains__(j)): + j += 1; + ''' Update optimal length if this length + is more. To get the length as it is + incremented one by one''' + + ans = max(ans, j - arr[i]); + return ans; + '''Driver code''' + +if __name__ == '__main__': + arr = [ 1, 94, 93, 1000, 5, 92, 78 ]; + n = len(arr); + print(findLongestConseqSubseq(arr, n));" +Find the minimum element in a sorted and rotated array,"/*Java program to find minimum element in a sorted and rotated array*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class Minimum +{ + static int findMin(int arr[], int low, int high) + { +/* This condition is needed to handle the case when array + is not rotated at all*/ + + if (high < low) return arr[0]; +/* If there is only one element left*/ + + if (high == low) return arr[low]; +/* Find mid*/ + + int mid = low + (high - low)/2; /* Check if element (mid+1) is minimum element. Consider + the cases like {3, 4, 5, 1, 2}*/ + + if (mid < high && arr[mid+1] < arr[mid]) + return arr[mid+1]; +/* Check if mid itself is minimum element*/ + + if (mid > low && arr[mid] < arr[mid - 1]) + return arr[mid]; +/* Decide whether we need to go to left half or right half*/ + + if (arr[high] > arr[mid]) + return findMin(arr, low, mid-1); + return findMin(arr, mid+1, high); + } +/* Driver Program*/ + + public static void main (String[] args) + { + int arr1[] = {5, 6, 1, 2, 3, 4}; + int n1 = arr1.length; + System.out.println(""The minimum element is ""+ findMin(arr1, 0, n1-1)); + int arr2[] = {1, 2, 3, 4}; + int n2 = arr2.length; + System.out.println(""The minimum element is ""+ findMin(arr2, 0, n2-1)); + int arr3[] = {1}; + int n3 = arr3.length; + System.out.println(""The minimum element is ""+ findMin(arr3, 0, n3-1)); + int arr4[] = {1, 2}; + int n4 = arr4.length; + System.out.println(""The minimum element is ""+ findMin(arr4, 0, n4-1)); + int arr5[] = {2, 1}; + int n5 = arr5.length; + System.out.println(""The minimum element is ""+ findMin(arr5, 0, n5-1)); + int arr6[] = {5, 6, 7, 1, 2, 3, 4}; + int n6 = arr6.length; + System.out.println(""The minimum element is ""+ findMin(arr6, 0, n6-1)); + int arr7[] = {1, 2, 3, 4, 5, 6, 7}; + int n7 = arr7.length; + System.out.println(""The minimum element is ""+ findMin(arr7, 0, n7-1)); + int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; + int n8 = arr8.length; + System.out.println(""The minimum element is ""+ findMin(arr8, 0, n8-1)); + int arr9[] = {3, 4, 5, 1, 2}; + int n9 = arr9.length; + System.out.println(""The minimum element is ""+ findMin(arr9, 0, n9-1)); + } +}"," '''Python program to find minimum element +in a sorted and rotated array''' + +def findMin(arr, low, high): + ''' This condition is needed to handle the case when array is not + rotated at all''' + + if high < low: + return arr[0] + ''' If there is only one element left''' + + if high == low: + return arr[low] + ''' Find mid''' + + mid = int((low + high)/2) + ''' Check if element (mid+1) is minimum element. Consider + the cases like [3, 4, 5, 1, 2]''' + + if mid < high and arr[mid+1] < arr[mid]: + return arr[mid+1] + ''' Check if mid itself is minimum element''' + + if mid > low and arr[mid] < arr[mid - 1]: + return arr[mid] + ''' Decide whether we need to go to left half or right half''' + + if arr[high] > arr[mid]: + return findMin(arr, low, mid-1) + return findMin(arr, mid+1, high) + '''Driver program to test above functions''' + +arr1 = [5, 6, 1, 2, 3, 4] +n1 = len(arr1) +print(""The minimum element is "" + str(findMin(arr1, 0, n1-1))) +arr2 = [1, 2, 3, 4] +n2 = len(arr2) +print(""The minimum element is "" + str(findMin(arr2, 0, n2-1))) +arr3 = [1] +n3 = len(arr3) +print(""The minimum element is "" + str(findMin(arr3, 0, n3-1))) +arr4 = [1, 2] +n4 = len(arr4) +print(""The minimum element is "" + str(findMin(arr4, 0, n4-1))) +arr5 = [2, 1] +n5 = len(arr5) +print(""The minimum element is "" + str(findMin(arr5, 0, n5-1))) +arr6 = [5, 6, 7, 1, 2, 3, 4] +n6 = len(arr6) +print(""The minimum element is "" + str(findMin(arr6, 0, n6-1))) +arr7 = [1, 2, 3, 4, 5, 6, 7] +n7 = len(arr7) +print(""The minimum element is "" + str(findMin(arr7, 0, n7-1))) +arr8 = [2, 3, 4, 5, 6, 7, 8, 1] +n8 = len(arr8) +print(""The minimum element is "" + str(findMin(arr8, 0, n8-1))) +arr9 = [3, 4, 5, 1, 2] +n9 = len(arr9) +print(""The minimum element is "" + str(findMin(arr9, 0, n9-1)))" +Find number of pairs in an array such that their XOR is 0,"/*Java program to find number +of pairs in an array such +that their XOR is 0*/ + +import java.util.*; +class GFG +{ +/* Function to calculate + the count*/ + + static int calculate(int a[], int n) + { +/* Sorting the list using + built in function*/ + + Arrays.sort(a); + int count = 1; + int answer = 0; +/* Traversing through the + elements*/ + + for (int i = 1; i < n; i++) + { + if (a[i] == a[i - 1]) + { +/* Counting frequency of each + elements*/ + + count += 1; + } + else + { +/* Adding the contribution of + the frequency to the answer*/ + + answer = answer + (count * (count - 1)) / 2; + count = 1; + } + } + answer = answer + (count * (count - 1)) / 2; + return answer; + } +/* Driver Code*/ + + public static void main (String[] args) + { + int a[] = { 1, 2, 1, 2, 4 }; + int n = a.length; +/* Print the count*/ + + System.out.println(calculate(a, n)); + } +}"," '''Python3 program to find number of pairs +in an array such that their XOR is 0 + ''' '''Function to calculate the count''' + +def calculate(a) : + ''' Sorting the list using + built in function''' + + a.sort() + count = 1 + answer = 0 + ''' Traversing through the elements''' + + for i in range(1, len(a)) : + if a[i] == a[i - 1] : + ''' Counting frequncy of each elements''' + + count += 1 + else : + ''' Adding the contribution of + the frequency to the answer''' + + answer = answer + count * (count - 1) // 2 + count = 1 + answer = answer + count * (count - 1) // 2 + return answer + '''Driver Code''' + +if __name__ == '__main__': + a = [1, 2, 1, 2, 4] + ''' Print the count''' + + print(calculate(a))" +Bottom View of a Binary Tree,"/*Java program to print Bottom View of Binary Tree*/ + +import java.io.*; +import java.lang.*; +import java.util.*; +class GFG{ +/*Tree node class*/ + +static class Node +{ +/* Data of the node*/ + + int data; +/* Horizontal distance of the node*/ + + int hd; +/* Left and right references*/ + + Node left, right; +/* Constructor of tree node*/ + + public Node(int key) + { + data = key; + hd = Integer.MAX_VALUE; + left = right = null; + } +} +/*printBottomViewUtil function*/ + +static void printBottomViewUtil(Node root, int curr, int hd, + TreeMap m) +{ +/* Base case*/ + + if (root == null) + return; +/* If node for a particular + horizontal distance is not + present, add to the map.*/ + + if (!m.containsKey(hd)) + { + m.put(hd, new int[]{ root.data, curr }); + } +/* Compare height for already + present node at similar horizontal + distance*/ + + else + { + int[] p = m.get(hd); + if (p[1] <= curr) + { + p[1] = curr; + p[0] = root.data; + } + m.put(hd, p); + } +/* Recur for left subtree*/ + + printBottomViewUtil(root.left, curr + 1, + hd - 1, m); +/* Recur for right subtree*/ + + printBottomViewUtil(root.right, curr + 1, + hd + 1, m); +} +/*printBottomView function*/ + + +static void printBottomView(Node root) +{/* Map to store Horizontal Distance, + Height and Data.*/ + + TreeMap m = new TreeMap<>(); + printBottomViewUtil(root, 0, 0, m); +/* Prints the values stored by printBottomViewUtil()*/ + + for(int val[] : m.values()) + { + System.out.print(val[0] + "" ""); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root = new Node(20); + root.left = new Node(8); + root.right = new Node(22); + root.left.left = new Node(5); + root.left.right = new Node(3); + root.right.left = new Node(4); + root.right.right = new Node(25); + root.left.right.left = new Node(10); + root.left.right.right = new Node(14); + System.out.println( + ""Bottom view of the given binary tree:""); + printBottomView(root); +} +}"," '''Python3 program to print Bottom +View of Binary Tree''' + + + '''Tree node class''' + +class Node: + '''Constructor of tree node''' + + def __init__(self, key = None, + left = None, + right = None): + self.data = key + self.left = left + self.right = right '''printBottomViewUtil function''' + +def printBottomViewUtil(root, d, hd, level): ''' Base case''' + + if root is None: + return + ''' If current level is more than or equal + to maximum level seen so far for the + same horizontal distance or horizontal + distance is seen for the first time, + update the dictionary''' + + if hd in d: + if level >= d[hd][1]: + d[hd] = [root.data, level] + else: + d[hd] = [root.data, level] + ''' recur for left subtree by decreasing + horizontal distance and increasing + level by 1''' + + printBottomViewUtil(root.left, d, hd - 1, + level + 1) + ''' recur for right subtree by increasing + horizontal distance and increasing + level by 1''' + + printBottomViewUtil(root.right, d, hd + 1, + level + 1) + '''printBottomView function''' + + +def printBottomView(root): ''' Create a dictionary where + key -> relative horizontal distance + of the node from root node and + value -> pair containing node's + value and its level''' + + d = dict() + printBottomViewUtil(root, d, 0, 0) + ''' Traverse the dictionary in sorted + order of their keys and print + the bottom view''' + + for i in sorted(d.keys()): + print(d[i][0], end = "" "") + '''Driver Code ''' + +if __name__ == '__main__': + root = Node(20) + root.left = Node(8) + root.right = Node(22) + root.left.left = Node(5) + root.left.right = Node(3) + root.right.left = Node(4) + root.right.right = Node(25) + root.left.right.left = Node(10) + root.left.right.right = Node(14) + print(""Bottom view of the given binary tree :"") + printBottomView(root)" +Maximum sum from a tree with adjacent levels not allowed,"/*Java code for max sum with adjacent levels +not allowed*/ + +import java.util.*; +public class Main { +/* Tree node class for Binary Tree + representation*/ + + static class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } + } +/* Recursive function to find the maximum + sum returned for a root node and its + grandchildren*/ + + public static int getSumAlternate(Node root) + { + if (root == null) + return 0; + int sum = root.data; + if (root.left != null) { + sum += getSum(root.left.left); + sum += getSum(root.left.right); + } + if (root.right != null) { + sum += getSum(root.right.left); + sum += getSum(root.right.right); + } + return sum; + } +/* Returns maximum sum with adjacent + levels not allowed. This function + mainly uses getSumAlternate()*/ + + public static int getSum(Node root) + { + if (root == null) + return 0; +/* We compute sum of alternate levels + starting first level and from second + level. + And return maximum of two values.*/ + + return Math.max(getSumAlternate(root), + (getSumAlternate(root.left) + + getSumAlternate(root.right))); + } +/* Driver function*/ + + public static void main(String[] args) + { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.right.left = new Node(4); + root.right.left.right = new Node(5); + root.right.left.right.left = new Node(6); + System.out.println(getSum(root)); + } +}"," '''Python3 code for max sum with adjacent +levels not allowed''' + +from collections import deque as queue + '''A BST node''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + '''Recursive function to find the maximum +sum returned for a root node and its +grandchildren''' + +def getSumAlternate(root): + if (root == None): + return 0 + sum = root.data + if (root.left != None): + sum += getSum(root.left.left) + sum += getSum(root.left.right) + if (root.right != None): + sum += getSum(root.right.left) + sum += getSum(root.right.right) + return sum + '''Returns maximum sum with adjacent +levels not allowed. This function +mainly uses getSumAlternate()''' + +def getSum(root): + if (root == None): + return 0 + ''' We compute sum of alternate levels + starting first level and from second + level. + And return maximum of two values.''' + + return max(getSumAlternate(root), + (getSumAlternate(root.left) + + getSumAlternate(root.right))) + '''Driver code''' + +if __name__ == '__main__': + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.right.left = Node(4) + root.right.left.right = Node(5) + root.right.left.right.left = Node(6) + print(getSum(root))" +Optimal Binary Search Tree | DP-24,"/*Dynamic Programming Java code for Optimal Binary Search +Tree Problem*/ + +public class Optimal_BST2 { + /* A utility function to get sum of array elements + freq[i] to freq[j]*/ + + static int sum(int freq[], int i, int j) { + int s = 0; + for (int k = i; k <= j; k++) { + if (k >= freq.length) + continue; + s += freq[k]; + } + return s; + }/* A Dynamic Programming based function that calculates + minimum cost of a Binary Search Tree. */ + + static int optimalSearchTree(int keys[], int freq[], int n) { + /* Create an auxiliary 2D matrix to store results of + subproblems */ + + int cost[][] = new int[n + 1][n + 1]; + /* cost[i][j] = Optimal cost of binary search tree that + can be formed from keys[i] to keys[j]. cost[0][n-1] + will store the resultant cost */ + +/* For a single key, cost is equal to frequency of the key*/ + + for (int i = 0; i < n; i++) + cost[i][i] = freq[i]; +/* Now we need to consider chains of length 2, 3, ... . + L is chain length.*/ + + for (int L = 2; L <= n; L++) { +/* i is row number in cost[][]*/ + + for (int i = 0; i <= n - L + 1; i++) { +/* Get column number j from row number i and + chain length L*/ + + int j = i + L - 1; + cost[i][j] = Integer.MAX_VALUE; +/* Try making all keys in interval keys[i..j] as root*/ + + for (int r = i; r <= j; r++) { +/* c = cost when keys[r] becomes root of this subtree*/ + + int c = ((r > i) ? cost[i][r - 1] : 0) + + ((r < j) ? cost[r + 1][j] : 0) + sum(freq, i, j); + if (c < cost[i][j]) + cost[i][j] = c; + } + } + } + return cost[0][n - 1]; + } +/*Driver program to test above functions*/ + + public static void main(String[] args) { + int keys[] = { 10, 12, 20 }; + int freq[] = { 34, 8, 50 }; + int n = keys.length; + System.out.println(""Cost of Optimal BST is "" + + optimalSearchTree(keys, freq, n)); + } +}"," '''Dynamic Programming code for Optimal Binary Search +Tree Problem''' + +INT_MAX = 2147483647 + '''A utility function to get sum of +array elements freq[i] to freq[j]''' + +def sum(freq, i, j): + s = 0 + for k in range(i, j + 1): + s += freq[k] + return s + ''' A Dynamic Programming based function that +calculates minimum cost of a Binary Search Tree. ''' + +def optimalSearchTree(keys, freq, n): + ''' Create an auxiliary 2D matrix to store + results of subproblems ''' + + cost = [[0 for x in range(n)] + for y in range(n)] + ''' cost[i][j] = Optimal cost of binary search + tree that can be formed from keys[i] to keys[j]. + cost[0][n-1] will store the resultant cost ''' + + ''' For a single key, cost is equal to + frequency of the key''' + + for i in range(n): + cost[i][i] = freq[i] + ''' Now we need to consider chains of + length 2, 3, ... . L is chain length.''' + + for L in range(2, n + 1): + ''' i is row number in cost''' + + for i in range(n - L + 2): + ''' Get column number j from row number + i and chain length L''' + + j = i + L - 1 + if i >= n or j >= n: + break + cost[i][j] = INT_MAX + ''' Try making all keys in interval + keys[i..j] as root''' + + for r in range(i, j + 1): + ''' c = cost when keys[r] becomes root + of this subtree''' + + c = 0 + if (r > i): + c += cost[i][r - 1] + if (r < j): + c += cost[r + 1][j] + c += sum(freq, i, j) + if (c < cost[i][j]): + cost[i][j] = c + return cost[0][n - 1] + '''Driver Code''' + +if __name__ == '__main__': + keys = [10, 12, 20] + freq = [34, 8, 50] + n = len(keys) + print(""Cost of Optimal BST is"", + optimalSearchTree(keys, freq, n))" +Minimum rotations required to get the same string,"/*Java program to determine minimum number +of rotations required to yield same +string. */ + + +import java.util.*; + +class GFG +{ +/* Returns count of rotations to get the + same string back. */ + + static int findRotations(String str) + { +/* tmp is the concatenated string. */ + + String tmp = str + str; + int n = str.length(); + + for (int i = 1; i <= n; i++) + { + +/* substring from i index of original + string size. */ + + + String substring = tmp.substring( + i, i+str.length()); + +/* if substring matches with original string + then we will come out of the loop. */ + + if (str.equals(substring)) + return i; + } + return n; + } + +/* Driver Method */ + + public static void main(String[] args) + { + String str = ""aaaa""; + System.out.println(findRotations(str)); + } +} + +"," '''Python 3 program to determine minimum +number of rotations required to yield +same string.''' + + + '''Returns count of rotations to get the +same string back.''' + +def findRotations(str): + + ''' tmp is the concatenated string.''' + + tmp = str + str + n = len(str) + + for i in range(1, n + 1): + + ''' substring from i index of + original string size.''' + + substring = tmp[i: i+n] + + ''' if substring matches with + original string then we will + come out of the loop.''' + + if (str == substring): + return i + return n + + '''Driver code''' + +if __name__ == '__main__': + + str = ""abc"" + print(findRotations(str)) + + +" +Ceiling in a sorted array,"class Main +{ + /* Function to get index of ceiling + of x in arr[low..high] */ + + static int ceilSearch(int arr[], int low, int high, int x) + { + int i; + /* If x is smaller than or equal to first + element,then return the first element */ + + if(x <= arr[low]) + return low; + /* Otherwise, linearly search for ceil value */ + + for(i = low; i < high; i++) + { + if(arr[i] == x) + return i; + /* if x lies between arr[i] and arr[i+1] + including arr[i+1], then return arr[i+1] */ + + if(arr[i] < x && arr[i+1] >= x) + return i+1; + } + /* If we reach here then x is greater than the + last element of the array, return -1 in this case */ + + return -1; + } + /* Driver program to check above functions */ + + public static void main (String[] args) + { + int arr[] = {1, 2, 8, 10, 10, 12, 19}; + int n = arr.length; + int x = 3; + int index = ceilSearch(arr, 0, n-1, x); + if(index == -1) + System.out.println(""Ceiling of ""+x+"" doesn't exist in array""); + else + System.out.println(""ceiling of ""+x+"" is ""+arr[index]); + } +}"," '''''' '''Function to get index of ceiling of x in arr[low..high] */''' + +def ceilSearch(arr, low, high, x): + ''' If x is smaller than or equal to first element, + then return the first element */''' + + if x <= arr[low]: + return low + ''' Otherwise, linearly search for ceil value */''' + + i = low + for i in range(high): + if arr[i] == x: + return i + ''' if x lies between arr[i] and arr[i+1] including + arr[i+1], then return arr[i+1] */''' + + if arr[i] < x and arr[i+1] >= x: + return i+1 + ''' If we reach here then x is greater than the last element + of the array, return -1 in this case */''' + + return -1 + '''Driver program to check above functions */''' + +arr = [1, 2, 8, 10, 10, 12, 19] +n = len(arr) +x = 3 +index = ceilSearch(arr, 0, n-1, x); +if index == -1: + print (""Ceiling of %d doesn't exist in array ""% x) +else: + print (""ceiling of %d is %d""%(x, arr[index]))" +Check if two BSTs contain same set of elements,"/*JAVA program to check if two BSTs contains +same set of elements*/ + +import java.util.*; +class GFG +{ +/*BST Node*/ + +static class Node +{ + int data; + Node left; + Node right; +}; +/*Utility function to create new Node*/ + +static Node newNode(int val) +{ + Node temp = new Node(); + temp.data = val; + temp.left = temp.right = null; + return temp; +} +/*function to insert elements of the +tree to map m*/ + +static void insertToHash(Node root, HashSet s) +{ + if (root == null) + return; + insertToHash(root.left, s); + s.add(root.data); + insertToHash(root.right, s); +} +/*function to check if the two BSTs contain +same set of elements*/ + +static boolean checkBSTs(Node root1, Node root2) +{ +/* Base cases*/ + + if (root1 != null && root2 != null) + return true; + if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) + return false; +/* Create two hash sets and store + elements both BSTs in them.*/ + + HashSet s1 = new HashSet(); + HashSet s2 = new HashSet(); + insertToHash(root1, s1); + insertToHash(root2, s2); +/* Return true if both hash sets + contain same elements.*/ + + return (s1.equals(s2)); +} +/*Driver program to check above functions*/ + +public static void main(String[] args) +{ +/* First BST*/ + + Node root1 = newNode(15); + root1.left = newNode(10); + root1.right = newNode(20); + root1.left.left = newNode(5); + root1.left.right = newNode(12); + root1.right.right = newNode(25); +/* Second BST*/ + + Node root2 = newNode(15); + root2.left = newNode(12); + root2.right = newNode(20); + root2.left.left = newNode(5); + root2.left.left.right = newNode(10); + root2.right.right = newNode(25); +/* check if two BSTs have same set of elements*/ + + if (checkBSTs(root1, root2)) + System.out.print(""YES""); + else + System.out.print(""NO""); +} +}"," '''Python3 program to check if two BSTs contains +same set of elements''' + + '''BST Node''' + +class Node: + def __init__(self): + self.val = 0 + self.left = None + self.right = None '''Utility function to create Node''' + +def Node_(val1): + temp = Node() + temp.val = val1 + temp.left = temp.right = None + return temp +s = {} + '''function to insert elements of the +tree to map m''' + +def insertToHash(root): + if (root == None): + return + insertToHash(root.left) + s.add(root.data) + insertToHash(root.right) + '''function to check if the two BSTs contain +same set of elements''' + +def checkBSTs(root1, root2): + ''' Base cases''' + + if (root1 != None and root2 != None) : + return True + if ((root1 == None and root2 != None) or + (root1 != None and root2 == None)): + return False + ''' Create two hash sets and store + elements both BSTs in them.''' + + s1 = {} + s2 = {} + s = s1 + insertToHash(root1) + s1 = s + s = s2 + insertToHash(root2) + s2 = s + ''' Return True if both hash sets + contain same elements.''' + + return (s1 == (s2)) + '''Driver code''' + + '''First BST''' + +root1 = Node_(15) +root1.left = Node_(10) +root1.right = Node_(20) +root1.left.left = Node_(5) +root1.left.right = Node_(12) +root1.right.right = Node_(25) '''Second BST''' + +root2 = Node_(15) +root2.left = Node_(12) +root2.right = Node_(20) +root2.left.left = Node_(5) +root2.left.left.right = Node_(10) +root2.right.right = Node_(25) + '''check if two BSTs have same set of elements''' + +if (checkBSTs(root1, root2)): + print(""YES"") +else: + print(""NO"")" +Closest leaf to a given node in Binary Tree,"/*Java program to find closest leaf to given node x in a tree*/ + +/*A binary tree node*/ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +class Distance +{ + int minDis = Integer.MAX_VALUE; +} +class BinaryTree +{ + Node root;/* This function finds closest leaf to root. This distance + is stored at *minDist.*/ + + void findLeafDown(Node root, int lev, Distance minDist) + { +/* base case*/ + + if (root == null) + return; +/* If this is a leaf node, then check if it is closer + than the closest so far*/ + + if (root.left == null && root.right == null) + { + if (lev < (minDist.minDis)) + minDist.minDis = lev; + return; + } +/* Recur for left and right subtrees*/ + + findLeafDown(root.left, lev + 1, minDist); + findLeafDown(root.right, lev + 1, minDist); + } +/* This function finds if there is closer leaf to x through + parent node.*/ + + int findThroughParent(Node root, Node x, Distance minDist) + { +/* Base cases*/ + + if (root == null) + return -1; + if (root == x) + return 0; +/* Search x in left subtree of root*/ + + int l = findThroughParent(root.left, x, minDist); +/* If left subtree has x*/ + + if (l != -1) + { +/* Find closest leaf in right subtree*/ + + findLeafDown(root.right, l + 2, minDist); + return l + 1; + } +/* Search x in right subtree of root*/ + + int r = findThroughParent(root.right, x, minDist); +/* If right subtree has x*/ + + if (r != -1) + { +/* Find closest leaf in left subtree*/ + + findLeafDown(root.left, r + 2, minDist); + return r + 1; + } + return -1; + } +/* Returns minimum distance of a leaf from given node x*/ + + int minimumDistance(Node root, Node x) + { +/* Initialize result (minimum distance from a leaf)*/ + + Distance d = new Distance(); +/* Find closest leaf down to x*/ + + findLeafDown(x, 0, d); +/* See if there is a closer leaf through parent*/ + + findThroughParent(root, x, d); + return d.minDis; + } +/* Driver program*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); +/* Let us create Binary Tree shown in above example*/ + + tree.root = new Node(1); + tree.root.left = new Node(12); + tree.root.right = new Node(13); + tree.root.right.left = new Node(14); + tree.root.right.right = new Node(15); + tree.root.right.left.left = new Node(21); + tree.root.right.left.right = new Node(22); + tree.root.right.right.left = new Node(23); + tree.root.right.right.right = new Node(24); + tree.root.right.left.left.left = new Node(1); + tree.root.right.left.left.right = new Node(2); + tree.root.right.left.right.left = new Node(3); + tree.root.right.left.right.right = new Node(4); + tree.root.right.right.left.left = new Node(5); + tree.root.right.right.left.right = new Node(6); + tree.root.right.right.right.left = new Node(7); + tree.root.right.right.right.right = new Node(8); + Node x = tree.root.right; + System.out.println(""The closest leaf to node with value "" + + x.key + "" is at a distance of "" + + tree.minimumDistance(tree.root, x)); + } +}"," '''Find closest leaf to the given +node x in a tree''' + '''Utility class to create a new node''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + '''This function finds closest leaf to +root. This distance is stored at *minDist.''' + +def findLeafDown(root, lev, minDist): + ''' base case''' + + if (root == None): + return + ''' If this is a leaf node, then check if + it is closer than the closest so far''' + + if (root.left == None and + root.right == None): + if (lev < (minDist[0])): + minDist[0] = lev + return + ''' Recur for left and right subtrees''' + + findLeafDown(root.left, lev + 1, minDist) + findLeafDown(root.right, lev + 1, minDist) + '''This function finds if there is +closer leaf to x through parent node.''' + +def findThroughParent(root, x, minDist): + ''' Base cases''' + + if (root == None): + return -1 + if (root == x): + return 0 + ''' Search x in left subtree of root''' + + l = findThroughParent(root.left, x, + minDist) + ''' If left subtree has x''' + + if (l != -1): + ''' Find closest leaf in right subtree''' + + findLeafDown(root.right, l + 2, minDist) + return l + 1 + ''' Search x in right subtree of root''' + + r = findThroughParent(root.right, x, minDist) + ''' If right subtree has x''' + + if (r != -1): + ''' Find closest leaf in left subtree''' + + findLeafDown(root.left, r + 2, minDist) + return r + 1 + return -1 + '''Returns minimum distance of a leaf +from given node x''' + +def minimumDistance(root, x): + ''' Initialize result (minimum + distance from a leaf)''' + + minDist = [999999999999] + ''' Find closest leaf down to x''' + + findLeafDown(x, 0, minDist) + ''' See if there is a closer leaf + through parent''' + + findThroughParent(root, x, minDist) + return minDist[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create Binary Tree shown + in above example''' + + root = newNode(1) + root.left = newNode(12) + root.right = newNode(13) + root.right.left = newNode(14) + root.right.right = newNode(15) + root.right.left.left = newNode(21) + root.right.left.right = newNode(22) + root.right.right.left = newNode(23) + root.right.right.right = newNode(24) + root.right.left.left.left = newNode(1) + root.right.left.left.right = newNode(2) + root.right.left.right.left = newNode(3) + root.right.left.right.right = newNode(4) + root.right.right.left.left = newNode(5) + root.right.right.left.right = newNode(6) + root.right.right.right.left = newNode(7) + root.right.right.right.right = newNode(8) + x = root.right + print(""The closest leaf to the node with value"", + x.key, ""is at a distance of"", + minimumDistance(root, x))" +Print all increasing sequences of length k from first n natural numbers,"/*Java program to print all +increasing sequences of +length 'k' such that the +elements in every sequence +are from first 'n' +natural numbers.*/ + +class GFG { +/* A utility function to print + contents of arr[0..k-1]*/ + + static void printArr(int[] arr, int k) + { + for (int i = 0; i < k; i++) + System.out.print(arr[i] + "" ""); + System.out.print(""\n""); + } +/* A recursive function to print + all increasing sequences + of first n natural numbers. + Every sequence should be + length k. The array arr[] is + used to store current sequence*/ + + static void printSeqUtil(int n, int k, + int len, int[] arr) + { +/* If length of current increasing + sequence becomes k, print it*/ + + if (len == k) + { + printArr(arr, k); + return; + } +/* Decide the starting number + to put at current position: + If length is 0, then there + are no previous elements + in arr[]. So start putting + new numbers with 1. + If length is not 0, + then start from value of + previous element plus 1.*/ + + int i = (len == 0) ? 1 : arr[len - 1] + 1; +/* Increase length*/ + + len++; +/* Put all numbers (which are + greater than the previous + element) at new position.*/ + + while (i <= n) + { + arr[len - 1] = i; + printSeqUtil(n, k, len, arr); + i++; + } +/* This is important. The + variable 'len' is shared among + all function calls in recursion + tree. Its value must be + brought back before next + iteration of while loop*/ + + len--; + } +/* This function prints all + increasing sequences of + first n natural numbers. + The length of every sequence + must be k. This function + mainly uses printSeqUtil()*/ + + static void printSeq(int n, int k) + { +/* An array to store + individual sequences*/ + + int[] arr = new int[k]; +/* Initial length of + current sequence*/ + + int len = 0; + printSeqUtil(n, k, len, arr); + } +/* Driver Code*/ + + static public void main (String[] args) + { + int k = 3, n = 7; + printSeq(n, k); + } +}"," '''Python3 program to print all +increasing sequences of length + '''k' such that the elements in +every sequence are from first + '''n' natural numbers.''' + + '''A utility function to +print contents of arr[0..k-1]''' + +def printArr(arr, k): + for i in range(k): + print(arr[i], end = "" ""); + print(); '''A recursive function to print +all increasing sequences of +first n natural numbers. Every +sequence should be length k. +The array arr[] is used to +store current sequence.''' + +def printSeqUtil(n, k,len1, arr): + ''' If length of current + increasing sequence + becomes k, print it''' + + if (len1 == k): + printArr(arr, k); + return; + ''' Decide the starting number + to put at current position: + If length is 0, then there + are no previous elements + in arr[]. So start putting + new numbers with 1. If length + is not 0, then start from value + of previous element plus 1.''' + + i = 1 if(len1 == 0) else (arr[len1 - 1] + 1); + ''' Increase length''' + + len1 += 1; + ''' Put all numbers (which are greater + than the previous element) at + new position.''' + + while (i <= n): + arr[len1 - 1] = i; + printSeqUtil(n, k, len1, arr); + i += 1; + ''' This is important. The variable + 'len' is shared among all function + calls in recursion tree. Its value + must be brought back before next + iteration of while loop''' + + len1 -= 1; + '''This function prints all increasing +sequences of first n natural numbers. +The length of every sequence must be +k. This function mainly uses printSeqUtil()''' + +def printSeq(n, k): + '''An array to store individual sequences''' + + arr = [0] * k; + + ''' +Initial length of current sequence''' + + len1 = 0; + printSeqUtil(n, k, len1, arr); '''Driver Code''' + +k = 3; +n = 7; +printSeq(n, k);" +"Count frequency of k in a matrix of size n where matrix(i, j) = i+j","/*Java program to find the +frequency of k in matrix +in matrix where m(i, j)=i+j*/ + +import java.util.*; +import java.lang.*; +public class GfG{ + public static int find(int n, int k) + { + if (n + 1 >= k) + return (k - 1); + else + return (2 * n + 1 - k); + } +/* Driver function*/ + + public static void main(String argc[]) + { + int n = 4, k = 7; + int freq = find(n, k); + if (freq < 0) + System.out.print("" element"" + + "" not exist \n ""); + else + System.out.print("" Frequency"" + + "" of "" + k + "" is "" + + freq + ""\n""); + } +}"," '''Python program to find +the frequency of k +in matrix where +m(i, j)=i+j''' + +import math +def find( n, k): + if (n + 1 >= k): + return (k - 1) + else: + return (2 * n + 1 - k) + '''Driver Code''' + +n = 4 +k = 7 +freq = find(n, k) +if (freq < 0): + print ( "" element not exist"") +else: + print("" Frequency of "" , k ,"" is "" , freq )" +Array range queries over range queries,"/*Java program to perform range queries over range +queries.*/ + +public class GFG { + static final int max = 10000; +/*For prefix sum array*/ + + static void update(int arr[], int l) { + arr[l] += arr[l - 1]; + } +/*This function is used to apply square root +decomposition in the record array*/ + + static void record_func(int block_size, int block[], + int record[], int l, int r, int value) { +/* traversing first block in range*/ + + while (l < r && l % block_size != 0 && l != 0) { + record[l] += value; + l++; + } +/* traversing completely overlapped blocks in range*/ + + while (l + block_size <= r + 1) { + block[l / block_size] += value; + l += block_size; + } +/* traversing last block in range*/ + + while (l <= r) { + record[l] += value; + l++; + } + } +/*Function to print the resultant array*/ + + static void print(int arr[], int n) { + for (int i = 0; i < n; i++) { + System.out.print(arr[i] + "" ""); + } + } +/*Driver code*/ + + public static void main(String[] args) { + int n = 5, m = 5; + int arr[] = new int[n], record[] = new int[m]; + int block_size = (int) Math.sqrt(m); + int block[] = new int[max]; + int command[][] = {{1, 1, 2}, {1, 4, 5}, + {2, 1, 2}, {2, 1, 3}, + {2, 3, 4}}; + for (int i = m - 1; i >= 0; i--) { +/* If query is of type 2 then function + call to record_func*/ + + if (command[i][0] == 2) { + int x = i / (block_size); + record_func(block_size, block, record, + command[i][1] - 1, command[i][2] - 1, + (block[x] + record[i] + 1)); +/*If query is of type 1 then simply add1 to the record array*/ + +} + else { + record[i]++; + } + }/* Merging the value of the block in the record array*/ + + for (int i = 0; i < m; i++) { + int check = (i / block_size); + record[i] += block[check]; + } + for (int i = 0; i < m; i++) { +/* If query is of type 1 then the array + elements are over-written by the record + array*/ + + if (command[i][0] == 1) { + arr[command[i][1] - 1] += record[i]; + if ((command[i][2] - 1) < n - 1) { + arr[(command[i][2])] -= record[i]; + } + } + } +/* The prefix sum of the array*/ + + for (int i = 1; i < n; i++) { + update(arr, i); + } +/* Printing the resultant array*/ + + print(arr, n); + } +}"," '''Python3 program to perform range +queries over range queries.''' + +import math +max = 10000 + '''For prefix sum array''' + +def update(arr, l): + arr[l] += arr[l - 1] + '''This function is used to apply square root +decomposition in the record array''' + +def record_func(block_size, block, + record, l, r, value): + ''' Traversing first block in range''' + + while (l < r and + l % block_size != 0 and + l != 0): + record[l] += value + l += 1 + ''' Traversing completely overlapped + blocks in range''' + + while (l + block_size <= r + 1): + block[l // block_size] += value + l += block_size + ''' Traversing last block in range''' + + while (l <= r): + record[l] += value + l += 1 + '''Function to print the resultant array''' + +def print_array(arr, n): + for i in range(n): + print(arr[i], end = "" "") + '''Driver code''' + +if __name__ == ""__main__"": + n = 5 + m = 5 + arr = [0] * n + record = [0] * m + block_size = (int)(math.sqrt(m)) + block = [0] * max + command = [ [ 1, 1, 2 ], + [ 1, 4, 5 ], + [ 2, 1, 2 ], + [ 2, 1, 3 ], + [ 2, 3, 4 ] ] + for i in range(m - 1, -1, -1): + ''' If query is of type 2 then function + call to record_func''' + + if (command[i][0] == 2): + x = i // (block_size) + record_func(block_size, block, + record, command[i][1] - 1, + command[i][2] - 1, + (block[x] + record[i] + 1)) + ''' If query is of type 1 then simply add + 1 to the record array''' + + else: + record[i] += 1 + ''' Merging the value of the block + in the record array''' + + for i in range(m): + check = (i // block_size) + record[i] += block[check] + for i in range(m): + ''' If query is of type 1 then the array + elements are over-written by the record + array''' + + if (command[i][0] == 1): + arr[command[i][1] - 1] += record[i] + if ((command[i][2] - 1) < n - 1): + arr[(command[i][2])] -= record[i] + ''' The prefix sum of the array''' + + for i in range(1, n): + update(arr, i) + ''' Printing the resultant array''' + + print_array(arr, n)" +"Given an array of pairs, find all symmetric pairs in it","/*A Java program to find all symmetric pairs in a given array of pairs*/ + +import java.util.HashMap; +class SymmetricPairs { +/* Print all pairs that have a symmetric counterpart*/ + + static void findSymPairs(int arr[][]) + { +/* Creates an empty hashMap hM*/ + + HashMap hM = new HashMap(); +/* Traverse through the given array*/ + + for (int i = 0; i < arr.length; i++) + { +/* First and second elements of current pair*/ + + int first = arr[i][0]; + int sec = arr[i][1]; +/* Look for second element of this pair in hash*/ + + Integer val = hM.get(sec); +/* If found and value in hash matches with first + element of this pair, we found symmetry*/ + + if (val != null && val == first) + System.out.println(""("" + sec + "", "" + first + "")""); +/*Else put sec element of this pair in hash*/ + +else + hM.put(first, sec); + } + } +/* Driver method*/ + + public static void main(String arg[]) + { + int arr[][] = new int[5][2]; + arr[0][0] = 11; arr[0][1] = 20; + arr[1][0] = 30; arr[1][1] = 40; + arr[2][0] = 5; arr[2][1] = 10; + arr[3][0] = 40; arr[3][1] = 30; + arr[4][0] = 10; arr[4][1] = 5; + findSymPairs(arr); + } +}"," '''A Python3 program to find all symmetric +pairs in a given array of pairs.''' + '''Print all pairs that have +a symmetric counterpart''' + +def findSymPairs(arr, row): + ''' Creates an empty hashMap hM''' + + hM = dict() + ''' Traverse through the given array''' + + for i in range(row): + ''' First and second elements + of current pair''' + + first = arr[i][0] + sec = arr[i][1] + ''' If found and value in hash matches with first + element of this pair, we found symmetry''' + + if (sec in hM.keys() and hM[sec] == first): + print(""("", sec,"","", first, "")"") + '''Else put sec element of this pair in hash''' + + else: + hM[first] = sec + '''Driver Code''' + +if __name__ == '__main__': + arr = [[0 for i in range(2)] + for i in range(5)] + arr[0][0], arr[0][1] = 11, 20 + arr[1][0], arr[1][1] = 30, 40 + arr[2][0], arr[2][1] = 5, 10 + arr[3][0], arr[3][1] = 40, 30 + arr[4][0], arr[4][1] = 10, 5 + findSymPairs(arr, 5)" +Maximum sum of i*arr[i] among all rotations of a given array,"/*A Naive Java program to find +maximum sum rotation*/ + +import java.util.*; +import java.io.*; +class GFG { +/*Returns maximum value of i*arr[i]*/ + +static int maxSum(int arr[], int n) +{ +/*Initialize result*/ + +int res = Integer.MIN_VALUE; +/*Consider rotation beginning with i +for all possible values of i.*/ + +for (int i = 0; i < n; i++) +{ +/* Initialize sum of current rotation*/ + + int curr_sum = 0; +/* Compute sum of all values. We don't + actually rotation the array, but compute + sum by finding ndexes when arr[i] is + first element*/ + + for (int j = 0; j < n; j++) + { + int index = (i + j) % n; + curr_sum += j * arr[index]; + } +/* Update result if required*/ + + res = Math.max(res, curr_sum); +} +return res; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {8, 3, 1, 2}; + int n = arr.length; + System.out.println(maxSum(arr, n)); +} +}"," '''A Naive Python3 program to find +maximum sum rotation''' + +import sys + '''Returns maximum value of i * arr[i]''' + +def maxSum(arr, n): + ''' Initialize result''' + + res = -sys.maxsize + ''' Consider rotation beginning with i + for all possible values of i.''' + + for i in range(0, n): + ''' Initialize sum of current rotation''' + + curr_sum = 0 + ''' Compute sum of all values. We don't + acutally rotation the array, but + compute sum by finding ndexes when + arr[i] is first element''' + + for j in range(0, n): + index = int((i + j)% n) + curr_sum += j * arr[index] + ''' Update result if required''' + + res = max(res, curr_sum) + return res + '''Driver code''' + +arr = [8, 3, 1, 2] +n = len(arr) +print(maxSum(arr, n))" +Maximum circular subarray sum,"import java.io.*; + +class GFG { +/*The function returns maximum +circular contiguous sum in a[]*/ + + public static int maxCircularSum(int a[], int n) + { +/* Corner Case*/ + + if (n == 1) + return a[0]; + +/* Initialize sum variable which store total sum of + the array.*/ + + int sum = 0; + for (int i = 0; i < n; i++) { + sum += a[i]; + } + +/* Initialize every variable with first value of + array.*/ + + int curr_max = a[0], max_so_far = a[0], + curr_min = a[0], min_so_far = a[0]; + +/* Concept of Kadane's Algorithm*/ + + for (int i = 1; i < n; i++) + { + +/* Kadane's Algorithm to find Maximum subarray + sum.*/ + + curr_max = Math.max(curr_max + a[i], a[i]); + max_so_far = Math.max(max_so_far, curr_max); + +/* Kadane's Algorithm to find Minimum subarray + sum.*/ + + curr_min = Math.min(curr_min + a[i], a[i]); + min_so_far = Math.min(min_so_far, curr_min); + } + if (min_so_far == sum) { + return max_so_far; + } + +/* returning the maximum value*/ + + return Math.max(max_so_far, sum - min_so_far); + } + +/* Driver code*/ + + public static void main(String[] args) + { + int a[] = { 11, 10, -20, 5, -3, -5, 8, -13, 10 }; + int n = 9; + System.out.println(""Maximum circular sum is "" + + maxCircularSum(a, n)); + } +} + + +"," '''Python program for maximum contiguous circular sum problem''' + + + '''The function returns maximum +circular contiguous sum in a[]''' + +def maxCircularSum(a, n): + + ''' Corner Case''' + + if (n == 1): + return a[0] + + ''' Initialize sum variable which + store total sum of the array.''' + + sum = 0 + for i in range(n): + sum += a[i] + + ''' Initialize every variable + with first value of array.''' + + curr_max = a[0] + max_so_far = a[0] + curr_min = a[0] + min_so_far = a[0] + + ''' Concept of Kadane's Algorithm''' + + for i in range(1, n): + + ''' Kadane's Algorithm to find Maximum subarray sum.''' + + curr_max = max(curr_max + a[i], a[i]) + max_so_far = max(max_so_far, curr_max) + + ''' Kadane's Algorithm to find Minimum subarray sum.''' + + curr_min = min(curr_min + a[i], a[i]) + min_so_far = min(min_so_far, curr_min) + if (min_so_far == sum): + return max_so_far + + ''' returning the maximum value''' + + return max(max_so_far, sum - min_so_far) + + '''Driver code''' + +a = [11, 10, -20, 5, -3, -5, 8, -13, 10] +n = len(a) +print(""Maximum circular sum is"", maxCircularSum(a, n)) + +" +Find the Deepest Node in a Binary Tree,"/*A Java program to find value of the +deepest node in a given binary tree*/ + +class GFG +{ +/*A tree node with constructor*/ + +static class Node +{ + int data; + Node left, right; + Node(int key) + { + data = key; + left = null; + right = null; + } +}; +/*Utility function to find height +of a tree, rooted at 'root'.*/ + +static int height(Node root) +{ + if(root == null) return 0; + int leftHt = height(root.left); + int rightHt = height(root.right); + return Math.max(leftHt, rightHt) + 1; +} +/*levels : current Level +Utility function to print all +nodes at a given level.*/ + +static void deepestNode(Node root, + int levels) +{ + if(root == null) return; + if(levels == 1) + System.out.print(root.data + "" ""); + else if(levels > 1) + { + deepestNode(root.left, levels - 1); + deepestNode(root.right, levels - 1); + } +} +/*Driver Codede*/ + +public static void main(String args[]) +{ + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.left.left = new Node(4); + root.right.left = new Node(5); + root.right.right = new Node(6); + root.right.left.right = new Node(7); + root.right.right.right = new Node(8); + root.right.left.right.left = new Node(9); +/* Calculating height of tree*/ + + int levels = height(root); +/* Printing the deepest node*/ + + deepestNode(root, levels); +} +}"," '''A Python3 program to find value of the +deepest node in a given binary tree''' + + '''A tree node with constructor''' + +class new_Node: + def __init__(self, key): + self.data = key + self.left = self.right = None '''Utility function to find height +of a tree, rooted at 'root'.''' + +def height(root): + if(not root): + return 0 + leftHt = height(root.left) + rightHt = height(root.right) + return max(leftHt, rightHt) + 1 + '''levels : current Level +Utility function to print all +nodes at a given level.''' + +def deepestNode(root, levels): + if(not root): + return + if(levels == 1): + print(root.data) + elif(levels > 1): + deepestNode(root.left, levels - 1) + deepestNode(root.right, levels - 1) + '''Driver Code''' + +if __name__ == '__main__': + root = new_Node(1) + root.left = new_Node(2) + root.right = new_Node(3) + root.left.left = new_Node(4) + root.right.left = new_Node(5) + root.right.right = new_Node(6) + root.right.left.right = new_Node(7) + root.right.right.right = new_Node(8) + root.right.left.right.left = new_Node(9) + ''' Calculating height of tree''' + + levels = height(root) + ''' Printing the deepest node''' + + deepestNode(root, levels)" +Products of ranges in an array,"/*Java program to find Product +in range Queries in O(1)*/ + +class GFG +{ + +static int MAX = 100; +int pre_product[] = new int[MAX]; +int inverse_product[] = new int[MAX]; + +/*Returns modulo inverse of a +with respect to m using extended +Euclid Algorithm Assumption: a +and m are coprimes, +i.e., gcd(a, m) = 1*/ + +int modInverse(int a, int m) +{ + int m0 = m, t, q; + int x0 = 0, x1 = 1; + + if (m == 1) + return 0; + + while (a > 1) + { + +/* q is quotient*/ + + q = a / m; + + t = m; + +/* m is remainder now, + process same as + Euclid's algo*/ + + m = a % m; + a = t; + + t = x0; + + x0 = x1 - q * x0; + + x1 = t; + } + +/* Make x1 positive*/ + + if (x1 < 0) + x1 += m0; + + return x1; +} + +/*calculating pre_product array*/ + +void calculate_Pre_Product(int A[], + int N, int P) +{ + pre_product[0] = A[0]; + + for (int i = 1; i < N; i++) + { + pre_product[i] = pre_product[i - 1] * + A[i]; + pre_product[i] = pre_product[i] % P; + } +} + +/*Cacluating inverse_product array.*/ + +void calculate_inverse_product(int A[], + int N, int P) +{ + inverse_product[0] = modInverse(pre_product[0], + P); + + for (int i = 1; i < N; i++) + inverse_product[i] = modInverse(pre_product[i], + P); +} + +/*Function to calculate Product +in the given range.*/ + +int calculateProduct(int A[], int L, + int R, int P) +{ +/* As our array is 0 based as and + L and R are given as 1 based index.*/ + + L = L - 1; + R = R - 1; + int ans; + + if (L == 0) + ans = pre_product[R]; + else + ans = pre_product[R] * + inverse_product[L - 1]; + + return ans; +} + +/*Driver code*/ + +public static void main(String[] s) +{ + GFG d = new GFG(); + +/* Array*/ + + int A[] = { 1, 2, 3, 4, 5, 6 }; + +/* Prime P*/ + + int P = 113; + +/* Calculating PreProduct and + InverseProduct*/ + + d.calculate_Pre_Product(A, A.length, P); + d.calculate_inverse_product(A, A.length, + P); + +/* Range [L, R] in 1 base index*/ + + int L = 2, R = 5; + System.out.println(d.calculateProduct(A, L, + R, P)); + L = 1; + R = 3; + System.out.println(d.calculateProduct(A, L, + R, P)); + +} +} + + +"," '''Python3 implementation of the +above approach''' + + + '''Returns modulo inverse of a with +respect to m using extended Euclid +Algorithm. Assumption: a and m are +coprimes, i.e., gcd(a, m) = 1''' + +def modInverse(a, m): + + m0, x0, x1 = m, 0, 1 + + if m == 1: + return 0 + + while a > 1: + + ''' q is quotient''' + + q = a // m + t = m + + ''' m is remainder now, process + same as Euclid's algo''' + + m, a = a % m, t + t = x0 + x0 = x1 - q * x0 + x1 = t + + ''' Make x1 positive''' + + if x1 < 0: + x1 += m0 + + return x1 + + '''calculating pre_product array''' + +def calculate_Pre_Product(A, N, P): + + pre_product[0] = A[0] + + for i in range(1, N): + + pre_product[i] = pre_product[i - 1] * A[i] + pre_product[i] = pre_product[i] % P + + '''Cacluating inverse_product +array.''' + +def calculate_inverse_product(A, N, P): + + inverse_product[0] = modInverse(pre_product[0], P) + + for i in range(1, N): + inverse_product[i] = modInverse(pre_product[i], P) + + '''Function to calculate +Product in the given range.''' + +def calculateProduct(A, L, R, P): + + ''' As our array is 0 based as + and L and R are given as 1 + based index.''' + + L = L - 1 + R = R - 1 + ans = 0 + + if L == 0: + ans = pre_product[R] + else: + ans = pre_product[R] * inverse_product[L - 1] + + return ans + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Array''' + + A = [1, 2, 3, 4, 5, 6] + N = len(A) + + ''' Prime P''' + + P = 113 + MAX = 100 + + pre_product = [None] * (MAX) + inverse_product = [None] * (MAX) + + ''' Calculating PreProduct + and InverseProduct''' + + calculate_Pre_Product(A, N, P) + calculate_inverse_product(A, N, P) + + ''' Range [L, R] in 1 base index''' + + L, R = 2, 5 + print(calculateProduct(A, L, R, P)) + + L, R = 1, 3 + print(calculateProduct(A, L, R, P)) + + +" +Check whether Arithmetic Progression can be formed from the given array,," '''Python3 program to check if a given array +can form arithmetic progression''' + + + '''Returns true if a permutation of arr[0..n-1] +can form arithmetic progression''' + +def checkIsAP(arr, n): + + hm = {} + smallest = float('inf') + second_smallest = float('inf') + + for i in range(n): + + ''' Find the smallest and and + update second smallest''' + + if (arr[i] < smallest): + second_smallest = smallest + smallest = arr[i] + + ''' Find second smallest''' + + elif (arr[i] != smallest and + arr[i] < second_smallest): + second_smallest = arr[i] + + ''' Check if the duplicate element found or not''' + + if arr[i] not in hm: + hm[arr[i]] = 1 + + ''' If duplicate found then return false''' + + else: + return False + + ''' Find the difference between smallest + and second smallest''' + + diff = second_smallest - smallest + + ''' As we have used smallest and + second smallest,so we + should now only check for n-2 elements''' + + for i in range(n-1): + if (second_smallest) not in hm: + return False + + second_smallest += diff + + return True + + '''Driver code''' + +arr = [ 20, 15, 5, 0, 10 ] +n = len(arr) + +if (checkIsAP(arr, n)): + print(""Yes"") +else: + print(""No"") + + +" +Convert a Binary Tree into its Mirror Tree,"/*Iterative Java program to convert a Binary +Tree to its mirror*/ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, pointer to +left child and a pointer to right child */ + +static class Node +{ + int data; + Node left; + Node right; +}; +/* Helper function that allocates a new node +with the given data and null left and right +pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return(node); +} +/* Change a tree so that the roles of the left and + right pointers are swapped at every node. +So the tree... + 4 + / \ + 2 5 + / \ +1 3 +is changed to... + 4 + / \ + 5 2 + / \ + 3 1 +*/ + +static void mirror(Node root) +{ + if (root == null) + return; + Queue q = new LinkedList<>(); + q.add(root); +/* Do BFS. While doing BFS, keep swapping + left and right children*/ + + while (q.size() > 0) + { +/* pop top node from queue*/ + + Node curr = q.peek(); + q.remove(); +/* swap left child with right child*/ + + Node temp = curr.left; + curr.left = curr.right; + curr.right = temp;; +/* push left and right children*/ + + if (curr.left != null) + q.add(curr.left); + if (curr.right != null) + q.add(curr.right); + } +} +/* Helper function to print Inorder traversal.*/ + +static void inOrder( Node node) +{ + if (node == null) + return; + inOrder(node.left); + System.out.print( node.data + "" ""); + inOrder(node.right); +} +/* Driver code */ + +public static void main(String args[]) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + /* Print inorder traversal of the input tree */ + + System.out.print( ""\n Inorder traversal of the"" + +"" coned tree is \n""); + inOrder(root); + /* Convert tree to its mirror */ + + mirror(root); + /* Print inorder traversal of the mirror tree */ + + System.out.print( ""\n Inorder traversal of the ""+ + ""mirror tree is \n""); + inOrder(root); +} +}"," '''Python3 program to convert a Binary +Tree to its mirror''' + + '''A binary tree node has data, pointer to +left child and a pointer to right child +Helper function that allocates a new node +with the given data and None left and +right pointers ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None ''' Change a tree so that the roles of the left + and right pointers are swapped at every node. + So the tree... + 4 + / \ + 2 5 + / \ + 1 3 + is changed to... + 4 + / \ + 5 2 + / \ + 3 1 + ''' + +def mirror( root): + if (root == None): + return + q = [] + q.append(root) + ''' Do BFS. While doing BFS, keep swapping + left and right children''' + + while (len(q)): + ''' pop top node from queue''' + + curr = q[0] + q.pop(0) + ''' swap left child with right child''' + + curr.left, curr.right = curr.right, curr.left + ''' append left and right children''' + + if (curr.left): + q.append(curr.left) + if (curr.right): + q.append(curr.right) + ''' Helper function to print Inorder traversal.''' + +def inOrder( node): + if (node == None): + return + inOrder(node.left) + print(node.data, end = "" "") + inOrder(node.right) + '''Driver code''' + +root = newNode(1) +root.left = newNode(2) +root.right = newNode(3) +root.left.left = newNode(4) +root.left.right = newNode(5) + ''' Print inorder traversal of the input tree ''' + +print(""Inorder traversal of the constructed tree is"") +inOrder(root) + ''' Convert tree to its mirror ''' + +mirror(root) + ''' Print inorder traversal of the mirror tree ''' + +print(""\nInorder traversal of the mirror tree is"") +inOrder(root)" +Check if two nodes are cousins in a Binary Tree,"/*Java program to check if two binary tree are cousins*/ + + +/*A Binary Tree Node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* Recursive function to check if two Nodes are + siblings*/ + + boolean isSibling(Node node, Node a, Node b) + { +/* Base case*/ + + if (node == null) + return false; + return ((node.left == a && node.right == b) || + (node.left == b && node.right == a) || + isSibling(node.left, a, b) || + isSibling(node.right, a, b)); + } +/* Recursive function to find level of Node 'ptr' in + a binary tree*/ + + int level(Node node, Node ptr, int lev) + { +/* base cases*/ + + if (node == null) + return 0; + if (node == ptr) + return lev; +/* Return level if Node is present in left subtree*/ + + int l = level(node.left, ptr, lev + 1); + if (l != 0) + return l; +/* Else search in right subtree*/ + + return level(node.right, ptr, lev + 1); + } +/* Returns 1 if a and b are cousins, otherwise 0*/ + + boolean isCousin(Node node, Node a, Node b) + { +/* 1. The two Nodes should be on the same level + in the binary tree. + 2. The two Nodes should not be siblings (means + that they should not have the same parent + Node).*/ + + return ((level(node, a, 1) == level(node, b, 1)) && + (!isSibling(node, a, b))); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.left.right.right = new Node(15); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.right.left.right = new Node(8); + Node Node1, Node2; + Node1 = tree.root.left.left; + Node2 = tree.root.right.right; + if (tree.isCousin(tree.root, Node1, Node2)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python program to check if two nodes in a binary +tree are cousins''' + + '''A Binary Tree Node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + ''' Recursive function to check if two Nodes are + siblings''' + +def isSibling(root, a , b): ''' Base Case''' + + if root is None: + return 0 + return ((root.left == a and root.right ==b) or + (root.left == b and root.right == a)or + isSibling(root.left, a, b) or + isSibling(root.right, a, b)) + '''Recursive function to find level of Node 'ptr' in +a binary tree''' + +def level(root, ptr, lev): + ''' Base Case ''' + + if root is None : + return 0 + if root == ptr: + return lev + ''' Return level if Node is present in left subtree''' + + l = level(root.left, ptr, lev+1) + if l != 0: + return l + ''' Else search in right subtree''' + + return level(root.right, ptr, lev+1) + '''Returns 1 if a and b are cousins, otherwise 0''' + +def isCousin(root,a, b): + ''' 1. The two nodes should be on the same level in + the binary tree + The two nodes should not be siblings(means that + they should not have the smae parent node''' + + if ((level(root,a,1) == level(root, b, 1)) and + not (isSibling(root, a, b))): + return 1 + else: + return 0 + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.left.right.right = Node(15) +root.right.left = Node(6) +root.right.right = Node(7) +root.right.left.right = Node(8) +node1 = root.left.right +node2 = root.right.right +print ""Yes"" if isCousin(root, node1, node2) == 1 else ""No""" +A Product Array Puzzle,"/*Java program for the above approach*/ + +import java.io.*; +import java.util.*; +class Solution { + public static long[] productExceptSelf(int a[], int n) + { + long prod = 1; + long flag = 0; +/* product of all elements*/ + + for (int i = 0; i < n; i++) { +/* counting number of elements + which have value + 0*/ + + if (a[i] == 0) + flag++; + else + prod *= a[i]; + } +/* creating a new array of size n*/ + + long arr[] = new long[n]; + for (int i = 0; i < n; i++) { +/* if number of elements in + array with value 0 + is more than 1 than each + value in new array + will be equal to 0*/ + + if (flag > 1) { + arr[i] = 0; + } +/* if no element having value + 0 than we will + insert product/a[i] in new array*/ + + else if (flag == 0) + arr[i] = (prod / a[i]); +/* if 1 element of array having + value 0 than all + the elements except that index + value , will be + equal to 0*/ + + else if (flag == 1 && a[i] != 0) { + arr[i] = 0; + } +/* if(flag == 1 && a[i] == 0)*/ + + else + arr[i] = prod; + } + return arr; + } +/* Driver Code*/ + + public static void main(String args[]) + throws IOException + { + int n = 5; + int[] array = { 10, 3, 5, 6, 2 }; + Solution ob = new Solution(); + long[] ans = new long[n]; + ans = ob.productExceptSelf(array, n); + for (int i = 0; i < n; i++) { + System.out.print(ans[i] + "" ""); + } + } +}", +LCA for general or n-ary trees (Sparse Matrix DP approach ),"/* Program to find LCA of n1 and n2 using one DFS on +the Tree */ + + +import java.util.*; + +class GFG +{ + +/* Maximum number of nodes is 100000 and nodes are + numbered from 1 to 100000*/ + + static final int MAXN = 100001; + + static Vector[] tree = new Vector[MAXN]; +/*storing root to node path*/ + +static int[][] path = new int[3][MAXN]; + static boolean flag; + +/* storing the path from root to node*/ + + static void dfs(int cur, int prev, int pathNumber, int ptr, int node) + { + for (int i = 0; i < tree[cur].size(); i++) + { + if (tree[cur].get(i) != prev && !flag) + { +/* pushing current node into the path*/ + + path[pathNumber][ptr] = tree[cur].get(i); + if (tree[cur].get(i) == node) + { +/* node found*/ + + flag = true; + +/* terminating the path*/ + + path[pathNumber][ptr + 1] = -1; + return; + } + dfs(tree[cur].get(i), cur, pathNumber, ptr + 1, node); + } + } + } + +/* This Function compares the path from root to 'a' & root + to 'b' and returns LCA of a and b. Time Complexity : O(n)*/ + + static int LCA(int a, int b) + { +/* trivial case*/ + + if (a == b) + return a; + +/* setting root to be first element in path*/ + + path[1][0] = path[2][0] = 1; + +/* calculating path from root to a*/ + + flag = false; + dfs(1, 0, 1, 1, a); + +/* calculating path from root to b*/ + + flag = false; + dfs(1, 0, 2, 1, b); + +/* runs till path 1 & path 2 mathches*/ + + int i = 0; + while (i < MAXN && path[1][i] == path[2][i]) + i++; + +/* returns the last matching node in the paths*/ + + return path[1][i - 1]; + } + + static void addEdge(int a, int b) + { + tree[a].add(b); + tree[b].add(a); + } + +/* Driver code*/ + + public static void main(String[] args) + { + for (int i = 0; i < MAXN; i++) + tree[i] = new Vector(); + +/* Number of nodes*/ + + addEdge(1, 2); + addEdge(1, 3); + addEdge(2, 4); + addEdge(2, 5); + addEdge(2, 6); + addEdge(3, 7); + addEdge(3, 8); + + System.out.print(""LCA(4, 7) = "" + LCA(4, 7) + ""\n""); + System.out.print(""LCA(4, 6) = "" + LCA(4, 6) + ""\n""); + } +} + + +"," '''Python3 program to find LCA of n1 and +n2 using one DFS on the Tree''' + + + '''Maximum number of nodes is 100000 and +nodes are numbered from 1 to 100000''' + +MAXN = 100001 + +tree = [0] * MAXN +for i in range(MAXN): + tree[i] = [] + + '''Storing root to node path''' + +path = [0] * 3 +for i in range(3): + path[i] = [0] * MAXN + +flag = False + + '''Storing the path from root to node''' + +def dfs(cur: int, prev: int, pathNumber: int, + ptr: int, node: int) -> None: + + global tree, path, flag + + for i in range(len(tree[cur])): + if (tree[cur][i] != prev and not flag): + + ''' Pushing current node into the path''' + + path[pathNumber][ptr] = tree[cur][i] + + if (tree[cur][i] == node): + + ''' Node found''' + + flag = True + + ''' Terminating the path''' + + path[pathNumber][ptr + 1] = -1 + return + + dfs(tree[cur][i], cur, pathNumber, + ptr + 1, node) + + '''This Function compares the path from root +to 'a' & root to 'b' and returns LCA of +a and b. Time Complexity : O(n)''' + +def LCA(a: int, b: int) -> int: + + global flag + + ''' Trivial case''' + + if (a == b): + return a + + ''' Setting root to be first element + in path''' + + path[1][0] = path[2][0] = 1 + + ''' Calculating path from root to a''' + + flag = False + dfs(1, 0, 1, 1, a) + + ''' Calculating path from root to b''' + + flag = False + dfs(1, 0, 2, 1, b) + + ''' Runs till path 1 & path 2 mathches''' + + i = 0 + while (path[1][i] == path[2][i]): + i += 1 + + ''' Returns the last matching + node in the paths''' + + return path[1][i - 1] + +def addEdge(a: int, b: int) -> None: + + tree[a].append(b) + tree[b].append(a) + + '''Driver code''' + +if __name__ == ""__main__"": + + n = 8 + + ''' Number of nodes''' + + addEdge(1, 2) + addEdge(1, 3) + addEdge(2, 4) + addEdge(2, 5) + addEdge(2, 6) + addEdge(3, 7) + addEdge(3, 8) + + print(""LCA(4, 7) = {}"".format(LCA(4, 7))) + print(""LCA(4, 6) = {}"".format(LCA(4, 6))) + + +" +Insert a node after the n-th node from the end,"/*Java implementation to +insert a node after the +nth node from the end*/ + +class GfG +{ + +/*structure of a node*/ + +static class Node +{ + int data; + Node next; +} + +/*function to get a new node*/ + +static Node getNode(int data) +{ +/* allocate memory for the node*/ + + Node newNode = new Node(); + +/* put in the data*/ + + newNode.data = data; + newNode.next = null; + return newNode; +} + +/*function to insert a node after +the nth node from the end*/ + +static void insertAfterNthNode(Node head, + int n, int x) +{ +/* if list is empty*/ + + if (head == null) + return; + +/* get a new node for the value 'x'*/ + + Node newNode = getNode(x); + +/* Initializing the slow + and fast pointers*/ + + Node slow_ptr = head; + Node fast_ptr = head; + +/* move 'fast_ptr' to point to the + nth node from the beginning*/ + + for (int i = 1; i <= n - 1; i++) + fast_ptr = fast_ptr.next; + +/* iterate until 'fast_ptr' points + to the last node*/ + + while (fast_ptr.next != null) + { + +/* move both the pointers to the + respective next nodes*/ + + slow_ptr = slow_ptr.next; + fast_ptr = fast_ptr.next; + } + +/* insert the 'newNode' by making the + necessary adjustment in the links*/ + + newNode.next = slow_ptr.next; + slow_ptr.next = newNode; +} + +/*function to print the list*/ + +static void printList(Node head) +{ + while (head != null) + { + System.out.print(head.data + "" ""); + head = head.next; + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ +/* Creating list 1->3->4->5*/ + + Node head = getNode(1); + head.next = getNode(3); + head.next.next = getNode(4); + head.next.next.next = getNode(5); + + int n = 4, x = 2; + System.out.println(""Original Linked List: ""); + printList(head); + + insertAfterNthNode(head, n, x); + System.out.println(); + System.out.println(""Linked List After Insertion: ""); + printList(head); +} +} + + +"," '''Python3 implementation to insert a +node after the nth node from the end''' + + + '''Structure of a node''' + +class Node: + + def __init__(self, data): + + self.data = data + self.next = None + + '''Function to get a new node''' + +def getNode(data): + + ''' Allocate memory for the node''' + + newNode = Node(data) + return newNode + + '''Function to insert a node after the +nth node from the end''' + +def insertAfterNthNode(head, n, x): + + ''' If list is empty''' + + if (head == None): + return + + ''' Get a new node for the value 'x''' + ''' + newNode = getNode(x) + + ''' Initializing the slow and fast pointers''' + + slow_ptr = head + fast_ptr = head + + ''' Move 'fast_ptr' to point to the nth + node from the beginning''' + + for i in range(1, n): + fast_ptr = fast_ptr.next + + ''' Iterate until 'fast_ptr' points to the + last node''' + + while (fast_ptr.next != None): + + ''' Move both the pointers to the + respective next nodes''' + + slow_ptr = slow_ptr.next + fast_ptr = fast_ptr.next + + ''' Insert the 'newNode' by making the + necessary adjustment in the links''' + + newNode.next = slow_ptr.next + slow_ptr.next = newNode + + '''Function to print the list''' + +def printList(head): + + while (head != None): + print(head.data, end = ' ') + head = head.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Creating list 1.3.4.5''' + + head = getNode(1) + head.next = getNode(3) + head.next.next = getNode(4) + head.next.next.next = getNode(5) + + n = 4 + x = 2 + + print(""Original Linked List: "", end = '') + printList(head) + + insertAfterNthNode(head, n, x) + + print(""\nLinked List After Insertion: "", end = '') + printList(head) + + +" +Check whether a given graph is Bipartite or not,"import java.util.*; +public class GFG{ + static class Pair{ + int first, second; + Pair(int f, int s){ + first = f; + second = s; + } + } + static boolean isBipartite(int V, ArrayList> adj) + { +/* vector to store colour of vertex + assiging all to -1 i.e. uncoloured + colours are either 0 or 1 + for understanding take 0 as red and 1 as blue*/ + + int col[] = new int[V]; + Arrays.fill(col, -1); +/* queue for BFS storing {vertex , colour}*/ + + Queue q = new LinkedList(); +/* loop incase graph is not connected*/ + + for (int i = 0; i < V; i++) { +/* if not coloured*/ + + if (col[i] == -1) { +/* colouring with 0 i.e. red*/ + + q.add(new Pair(i, 0)); + col[i] = 0; + while (!q.isEmpty()) { + Pair p = q.peek(); + q.poll(); +/* current vertex*/ + + int v = p.first; +/* colour of current vertex*/ + + int c = p.second; +/* traversing vertexes connected to current vertex*/ + + for (int j : adj.get(v)) + { +/* if already coloured with parent vertex color + then bipartite graph is not possible*/ + + if (col[j] == c) + return false; +/* if uncooloured*/ + + if (col[j] == -1) + { +/* colouring with opposite color to that of parent*/ + + col[j] = (c==1) ? 0 : 1; + q.add(new Pair(j, col[j])); + } + } + } + } + } +/* if all vertexes are coloured such that + no two connected vertex have same colours*/ + + return true; + } +/* Driver Code Starts.*/ + + public static void main(String args[]) + { + int V, E; + V = 4 ; + E = 8; +/* adjacency list for storing graph*/ + + ArrayList> adj = new ArrayList>(); + for(int i = 0; i < V; i++){ + adj.add(new ArrayList()); + } + adj.get(0).add(1); + adj.get(0).add(3); + adj.get(1).add(0); + adj.get(1).add(2); + adj.get(2).add(1); + adj.get(2).add(3); + adj.get(3).add(0); + adj.get(3).add(2); + boolean ans = isBipartite(V, adj); +/* returns 1 if bipatite graph is possible*/ + + if (ans) + System.out.println(""Yes""); +/* returns 0 if bipartite graph is not possible*/ + + else + System.out.println(""No""); + } +}", +Count pairs whose products exist in array,"/*Java program to count pairs +whose product exist in array*/ + +import java.io.*; +class GFG +{ +/*Returns count of pairs +whose product exists in arr[]*/ + +static int countPairs(int arr[], + int n) +{ + int result = 0; + for (int i = 0; i < n ; i++) + { + for (int j = i + 1 ; j < n ; j++) + { + int product = arr[i] * arr[j] ; +/* find product + in an array*/ + + for (int k = 0; k < n; k++) + { +/* if product found + increment counter*/ + + if (arr[k] == product) + { + result++; + break; + } + } + } + } +/* return Count of all pair + whose product exist in array*/ + + return result; +} +/*Driver Code*/ + +public static void main (String[] args) +{ +int arr[] = {6, 2, 4, 12, 5, 3} ; +int n = arr.length; +System.out.println(countPairs(arr, n)); +} +}"," '''Python program to count pairs whose +product exist in array + ''' '''Returns count of pairs whose +product exists in arr[]''' + +def countPairs(arr, n): + result = 0; + for i in range (0, n): + for j in range(i + 1, n): + product = arr[i] * arr[j] ; + ''' find product in an array''' + + for k in range (0, n): + ''' if product found increment counter''' + + if (arr[k] == product): + result = result + 1; + break; + ''' return Count of all pair whose + product exist in array''' + + return result; + '''Driver program''' + +arr = [6, 2, 4, 12, 5, 3] ; +n = len(arr); +print(countPairs(arr, n));" +Swap Kth node from beginning with Kth node from end in a Linked List,"/*A Java program to swap kth +node from the beginning with +kth node from the end*/ + + /*A Linked List node*/ + +class Node { + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } +} +class LinkedList { + Node head;/* Utility function to insert + a node at the beginning */ + + void push(int new_data) + { + Node new_node = new Node(new_data); + new_node.next = head; + head = new_node; + } + /* Utility function for displaying linked list */ + + void printList() + { + Node node = head; + while (node != null) { + System.out.print(node.data + "" ""); + node = node.next; + } + System.out.println(""""); + } + /* Utility function for calculating + length of linked list */ + + int countNodes() + { + int count = 0; + Node s = head; + while (s != null) { + count++; + s = s.next; + } + return count; + } + /* Function for swapping kth nodes from + both ends of linked list */ + + void swapKth(int k) + { +/* Count nodes in linked list*/ + + int n = countNodes(); +/* Check if k is valid*/ + + if (n < k) + return; +/* If x (kth node from start) and + y(kth node from end) are same*/ + + if (2 * k - 1 == n) + return; +/* Find the kth node from beginning of linked list. + We also find previous of kth node because we need + to update next pointer of the previous.*/ + + Node x = head; + Node x_prev = null; + for (int i = 1; i < k; i++) { + x_prev = x; + x = x.next; + } +/* Similarly, find the kth node from end and its + previous. kth node from end is (n-k+1)th node + from beginning*/ + + Node y = head; + Node y_prev = null; + for (int i = 1; i < n - k + 1; i++) { + y_prev = y; + y = y.next; + } +/* If x_prev exists, then new next of it will be y. + Consider the case when y->next is x, in this case, + x_prev and y are same. So the statement + ""x_prev->next = y"" creates a self loop. This self + loop will be broken when we change y->next.*/ + + if (x_prev != null) + x_prev.next = y; +/* Same thing applies to y_prev*/ + + if (y_prev != null) + y_prev.next = x; +/* Swap next pointers of x and y. These statements + also break self loop if x->next is y or y->next + is x*/ + + Node temp = x.next; + x.next = y.next; + y.next = temp; +/* Change head pointers when k is 1 or n*/ + + if (k == 1) + head = y; + if (k == n) + head = x; + } +/* Driver code to test above*/ + + public static void main(String[] args) + { + LinkedList llist = new LinkedList(); + for (int i = 8; i >= 1; i--) + llist.push(i); + System.out.print(""Original linked list: ""); + llist.printList(); + System.out.println(""""); + for (int i = 1; i < 9; i++) { + llist.swapKth(i); + System.out.println(""Modified List for k = "" + i); + llist.printList(); + System.out.println(""""); + } + } +}"," ''' +A Python3 program to swap kth node from +the beginning with kth node from the end + ''' + + '''A Linked List node''' + +class Node: + def __init__(self, data, next = None): + self.data = data + self.next = next +class LinkedList: + def __init__(self, *args, **kwargs): + self.head = Node(None) ''' + Utility function to insert a node at the beginning + @args: + data: value of node + ''' + + def push(self, data): + node = Node(data) + node.next = self.head + self.head = node + ''' Print linked list''' + + def printList(self): + node = self.head + while node.next is not None: + print(node.data, end = "" "") + node = node.next + ''' count number of node in linked list''' + + def countNodes(self): + count = 0 + node = self.head + while node.next is not None: + count += 1 + node = node.next + return count + ''' + Function for swapping kth nodes from + both ends of linked list + ''' + + def swapKth(self, k): + ''' Count nodes in linked list''' + + n = self.countNodes() + ''' check if k is valid''' + + if nnext is x, in this case, + x_prev and y are same. So the statement + ""x_prev->next = y"" creates a self loop. This self + loop will be broken when we change y->next. + ''' + + if x_prev is not None: + x_prev.next = y + ''' Same thing applies to y_prev''' + + if y_prev is not None: + y_prev.next = x + ''' + Swap next pointers of x and y. These statements + also break self loop if x->next is y or y->next + is x + ''' + + temp = x.next + x.next = y.next + y.next = temp + ''' Change head pointers when k is 1 or n''' + + if k == 1: + self.head = y + if k == n: + self.head = x + '''Driver Code''' + +llist = LinkedList() +for i in range(8, 0, -1): + llist.push(i) +llist.printList() +for i in range(1, 9): + llist.swapKth(i) + print(""Modified List for k = "", i) + llist.printList() + print(""\n"")" +Pascal's Triangle,"/*Java code for Pascal's Triangle*/ + +import java.io.*; +class GFG { +/*binomialCoeff*/ + + + static int binomialCoeff(int n, int k) + { + int res = 1; + if (k > n - k) + k = n - k; + for (int i = 0; i < k; ++i) + { + res *= (n - i); + res /= (i + 1); + } + return res; + } +/* Function to print first + n lines of Pascal's Triangle*/ + + static void printPascal(int n) + { +/* Iterate through every line + and print entries in it*/ + + for (int line = 0; line < n; line++) + { +/* Every line has number of + integers equal to line number*/ + + for (int i = 0; i <= line; i++) + System.out.print(binomialCoeff + (line, i)+"" ""); + System.out.println(); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 7; + printPascal(n); + } +}"," '''Python 3 code for Pascal's Triangle''' + + '''binomialCoeff''' + +def binomialCoeff(n, k) : + res = 1 + if (k > n - k) : + k = n - k + for i in range(0 , k) : + res = res * (n - i) + res = res // (i + 1) + return res + '''A simple O(n^3) +program for +Pascal's Triangle +Function to print +first n lines of +Pascal's Triangle''' + +def printPascal(n) : ''' Iterate through every line + and print entries in it''' + + for line in range(0, n) : + ''' Every line has number of + integers equal to line + number''' + + for i in range(0, line + 1) : + print(binomialCoeff(line, i), + "" "", end = """") + print() + '''Driver program''' + +n = 7 +printPascal(n)" +Minimum Index Sum for Common Elements of Two Lists,"/*Hashing based Java program to find common elements +with minimum index sum.*/ + +import java.util.*; +class GFG +{ +/* Function to print common Strings with minimum index sum*/ + + static void find(Vector list1, Vector list2) + { +/* mapping Strings to their indices*/ + + Map map = new HashMap<>(); + for (int i = 0; i < list1.size(); i++) + map.put(list1.get(i), i); +/*resultant list*/ + +Vector res = new Vector(); + int minsum = Integer.MAX_VALUE; + for (int j = 0; j < list2.size(); j++) + { + if (map.containsKey(list2.get(j))) + { +/* If current sum is smaller than minsum*/ + + int sum = j + map.get(list2.get(j)); + if (sum < minsum) + { + minsum = sum; + res.clear(); + res.add(list2.get(j)); + } +/* if index sum is same then put this + String in resultant list as well*/ + + else if (sum == minsum) + res.add(list2.get(j)); + } + } +/* Print result*/ + + for (int i = 0; i < res.size(); i++) + System.out.print(res.get(i) + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { +/* Creating list1*/ + + Vector list1 = new Vector(); + list1.add(""GeeksforGeeks""); + list1.add(""Udemy""); + list1.add(""Coursera""); + list1.add(""edX""); +/* Creating list2*/ + + Vector list2 = new Vector(); + list2.add(""Codecademy""); + list2.add(""Khan Academy""); + list2.add(""GeeksforGeeks""); + find(list1, list2); + } +}"," '''Hashing based Python3 program to find +common elements with minimum index sum''' + +import sys + '''Function to print common strings +with minimum index sum''' + +def find(list1, list2): + ''' Mapping strings to their indices''' + + Map = {} + for i in range(len(list1)): + Map[list1[i]] = i + ''' Resultant list''' + + res = [] + minsum = sys.maxsize + for j in range(len(list2)): + if list2[j] in Map: + ''' If current sum is smaller + than minsum''' + + Sum = j + Map[list2[j]] + if (Sum < minsum): + minsum = Sum + res.clear() + res.append(list2[j]) + ''' If index sum is same then put this + string in resultant list as well ''' + + elif (Sum == minsum): + res.append(list2[j]) + ''' Print result''' + + print(*res, sep = "" "") + '''Driver code''' + '''Creating list1''' + +list1 = [] +list1.append(""GeeksforGeeks"") +list1.append(""Udemy"") +list1.append(""Coursera"") +list1.append(""edX"") + '''Creating list2''' + +list2 = [] +list2.append(""Codecademy"") +list2.append(""Khan Academy"") +list2.append(""GeeksforGeeks"") +find(list1, list2)" +Creating a tree with Left-Child Right-Sibling Representation,"/*Java program to create a tree with left child +right sibling representation.*/ + +import java.util.*; +class GFG +{ + static class Node + { + int data; + Node next; + Node child; + }; +/* Creating new Node*/ + + static Node newNode(int data) + { + Node newNode = new Node(); + newNode.next = newNode.child = null; + newNode.data = data; + return newNode; + } +/* Adds a sibling to a list with starting with n*/ + + static Node addSibling(Node n, int data) + { + if (n == null) + return null; + while (n.next != null) + n = n.next; + return (n.next = newNode(data)); + } +/* Add child Node to a Node*/ + + static Node addChild(Node n, int data) + { + if (n == null) + return null; +/* Check if child list is not empty.*/ + + if (n.child != null) + return addSibling(n.child, data); + else + return (n.child = newNode(data)); + } +/* Traverses tree in level order*/ + + static void traverseTree(Node root) + { +/* Corner cases*/ + + if (root == null) + return; + System.out.print(root.data+ "" ""); + if (root.child == null) + return; +/* Create a queue and enque root*/ + + Queue q = new LinkedList<>(); + Node curr = root.child; + q.add(curr); + while (!q.isEmpty()) + { +/* Take out an item from the queue*/ + + curr = q.peek(); + q.remove(); +/* Print next level of taken out item and enque + next level's children*/ + + while (curr != null) + { + System.out.print(curr.data + "" ""); + if (curr.child != null) + { + q.add(curr.child); + } + curr = curr.next; + } + } + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = newNode(10); + Node n1 = addChild(root, 2); + Node n2 = addChild(root, 3); + Node n3 = addChild(root, 4); + Node n4 = addChild(n3, 6); + Node n5 = addChild(root, 5); + Node n6 = addChild(n5, 7); + Node n7 = addChild(n5, 8); + Node n8 = addChild(n5, 9); + traverseTree(root); + } +}"," '''Python3 program to create a tree with +left child right sibling representation''' + +from collections import deque + + '''Creating new Node''' + +class Node: + def __init__(self, x): + self.data = x + self.next = None + self.child = None '''Adds a sibling to a list with +starting with n''' + +def addSibling(n, data): + if (n == None): + return None + while (n.next): + n = n.next + n.next = Node(data) + return n + '''Add child Node to a Node''' + +def addChild(n, data): + if (n == None): + return None + ''' Check if child list is not empty''' + + if (n.child): + return addSibling(n.child, data) + else: + n.child = Node(data) + return n + '''Traverses tree in level order''' + +def traverseTree(root): + ''' Corner cases''' + + if (root == None): + return + print(root.data, end = "" "") + if (root.child == None): + return + ''' Create a queue and enque root''' + + q = deque() + curr = root.child + q.append(curr) + while (len(q) > 0): + ''' Take out an item from the queue''' + + curr = q.popleft() + ''' Print next level of taken out + item and enque next level's children''' + + while (curr != None): + print(curr.data, end = "" "") + if (curr.child != None): + q.append(curr.child) + curr = curr.next + '''Driver code''' + +if __name__ == '__main__': + root = Node(10) + n1 = addChild(root, 2) + n2 = addChild(root, 3) + n3 = addChild(root, 4) + n4 = addChild(n3, 6) + n5 = addChild(root, 5) + n6 = addChild(n5, 7) + n7 = addChild(n5, 8) + n8 = addChild(n5, 9) + traverseTree(root)" +Construct a Binary Tree from Postorder and Inorder,"/* Java program to contree using inorder and +postorder traversals */ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, pointer to left +child and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; +/*Utility function to create a new node*/ + +/* Recursive function to conbinary of size n +from Inorder traversal in[] and Postorder traversal +post[]. Initial values of inStrt and inEnd should +be 0 and n -1. The function doesn't do any error +checking for cases where inorder and postorder +do not form a tree */ + +static Node buildUtil(int in[], int post[], + int inStrt, int inEnd) +{ +/* Base case*/ + + if (inStrt > inEnd) + return null; + /* Pick current node from Postorder traversal + using postIndex and decrement postIndex */ + + int curr = post[index]; + Node node = newNode(curr); + (index)--; + /* If this node has no children then return */ + + if (inStrt == inEnd) + return node; + /* Else find the index of this node in Inorder + traversal */ + + int iIndex = mp.get(curr); + /* Using index in Inorder traversal, con + left and right subtress */ + + node.right = buildUtil(in, post, iIndex + 1, + inEnd); + node.left = buildUtil(in, post, inStrt, + iIndex - 1); + return node; +} +static HashMap mp = new HashMap(); +static int index; +/*This function mainly creates an unordered_map, then +calls buildTreeUtil()*/ + +static Node buildTree(int in[], int post[], int len) +{ +/* Store indexes of all items so that we + we can quickly find later*/ + + for (int i = 0; i < len; i++) + mp.put(in[i], i); +/*Index in postorder*/ + +index = len - 1; + return buildUtil(in, post, 0, len - 1 ); +} +/* Helper function that allocates a new node */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); +} +/* This funtcion is here just to test */ + +static void preOrder(Node node) +{ + if (node == null) + return; + System.out.printf(""%d "", node.data); + preOrder(node.left); + preOrder(node.right); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; + int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; + int n = in.length; + Node root = buildTree(in, post, n); + System.out.print(""Preorder of the constructed tree : \n""); + preOrder(root); +} +}"," '''Python3 program to construct tree using inorder +and postorder traversals''' + + '''A binary tree node has data, pointer to left +child and a pointer to right child''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None '''Recursive function to construct binary of size n +from Inorder traversal in[] and Postorder traversal +post[]. Initial values of inStrt and inEnd should +be 0 and n -1. The function doesn't do any error +checking for cases where inorder and postorder +do not form a tree''' + +def buildUtil(inn, post, innStrt, innEnd): + global mp, index + ''' Base case''' + + if (innStrt > innEnd): + return None + ''' Pick current node from Postorder traversal + using postIndex and decrement postIndex''' + + curr = post[index] + node = Node(curr) + index -= 1 + ''' If this node has no children then return''' + + if (innStrt == innEnd): + return node + ''' Else finnd the inndex of this node inn + Inorder traversal''' + + iIndex = mp[curr] + ''' Using inndex inn Inorder traversal, + construct left and right subtress''' + + node.right = buildUtil(inn, post, + iIndex + 1, innEnd) + node.left = buildUtil(inn, post, innStrt, + iIndex - 1) + return node + '''This function mainly creates an unordered_map, +then calls buildTreeUtil()''' + +def buildTree(inn, post, lenn): + global index + ''' Store indexes of all items so that we + we can quickly find later''' + + for i in range(lenn): + mp[inn[i]] = i + ''' Index in postorder''' + + index = lenn - 1 + return buildUtil(inn, post, 0, lenn - 1) + '''This funtcion is here just to test''' + +def preOrder(node): + if (node == None): + return + print(node.data, end = "" "") + preOrder(node.left) + preOrder(node.right) + '''Driver Code''' + +if __name__ == '__main__': + inn = [ 4, 8, 2, 5, 1, 6, 3, 7 ] + post = [ 8, 4, 5, 2, 6, 7, 3, 1 ] + n = len(inn) + mp, index = {}, 0 + root = buildTree(inn, post, n) + print(""Preorder of the constructed tree :"") + preOrder(root)" +Merge two sorted arrays with O(1) extra space,"/*Java program program to merge two +sorted arrays with O(1) extra space.*/ + +import java.util.Arrays; +class Test +{ + +/*Merge ar1[] and ar2[] with O(1) extra space*/ + + static int arr1[] = new int[]{1, 5, 9, 10, 15, 20}; + static int arr2[] = new int[]{2, 3, 8, 13}; + static void merge(int m, int n) + {/* Iterate through all elements of ar2[] starting from + the last element*/ + + for (int i=n-1; i>=0; i--) + { + /* Find the smallest element greater than ar2[i]. Move all + elements one position ahead till the smallest greater + element is not found */ + + int j, last = arr1[m-1]; + for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) + arr1[j+1] = arr1[j]; +/* If there was a greater element*/ + + if (j != m-2 || last > arr2[i]) + { + arr1[j+1] = arr2[i]; + arr2[i] = last; + } + } + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + merge(arr1.length,arr2.length); + System.out.print(""After Merging nFirst Array: ""); + System.out.println(Arrays.toString(arr1)); + System.out.print(""Second Array: ""); + System.out.println(Arrays.toString(arr2)); + } +}"," '''Python program to merge +two sorted arrays +with O(1) extra space.''' '''Merge ar1[] and ar2[] +with O(1) extra space''' + +def merge(ar1, ar2, m, n): + ''' Iterate through all + elements of ar2[] starting from + the last element''' + + for i in range(n-1, -1, -1): + ''' Find the smallest element + greater than ar2[i]. Move all + elements one position ahead + till the smallest greater + element is not found''' + + last = ar1[m-1] + j=m-2 + while(j >= 0 and ar1[j] > ar2[i]): + ar1[j+1] = ar1[j] + j-=1 + ''' If there was a greater element''' + + if (j != m-2 or last > ar2[i]): + ar1[j+1] = ar2[i] + ar2[i] = last + '''Driver program''' + +ar1 = [1, 5, 9, 10, 15, 20] +ar2 = [2, 3, 8, 13] +m = len(ar1) +n = len(ar2) +merge(ar1, ar2, m, n) +print(""After Merging \nFirst Array:"", end="""") +for i in range(m): + print(ar1[i] , "" "", end="""") +print(""\nSecond Array: "", end="""") +for i in range(n): + print(ar2[i] , "" "", end="""")" +Smallest value in each level of Binary Tree,"/*Java program to print smallest element +in each level of binary tree.*/ + +import java.util.Arrays; +class GFG +{ +static int INT_MAX = (int) 10e6; +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*return height of tree*/ + +static int heightoftree(Node root) +{ + if (root == null) + return 0; + int left = heightoftree(root.left); + int right = heightoftree(root.right); + return ((left > right ? left : right) + 1); +} +/*Inorder Traversal +Search minimum element in each level and +store it into vector array.*/ + +static void printPerLevelMinimum(Node root, + int []res, int level) +{ + if (root != null) + { + printPerLevelMinimum(root.left, + res, level + 1); + if (root.data < res[level]) + res[level] = root.data; + printPerLevelMinimum(root.right, + res, level + 1); + } +} +static void perLevelMinimumUtility(Node root) +{ +/* height of tree for the size of + vector array*/ + + int n = heightoftree(root), i; +/* vector for store all minimum of + every level*/ + + int []res = new int[n]; + Arrays.fill(res, INT_MAX); +/* save every level minimum using + inorder traversal*/ + + printPerLevelMinimum(root, res, 0); +/* print every level minimum*/ + + System.out.print(""Every level minimum is\n""); + for (i = 0; i < n; i++) + { + System.out.print(""level "" + i + + "" min is = "" + + res[i] + ""\n""); + } +} +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree shown + in above diagram*/ + + Node root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + /* 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 */ + + perLevelMinimumUtility(root); +} +}"," '''Python3 program to print +smallest element in each +level of binary tree.''' + +INT_MAX = 1000006 + '''A Binary Tree Node''' + +class Node: + def __init__(self, + data): + self.data = data + self.left = None + self.right = None + '''return height of tree''' + +def heightoftree(root): + if (root == None): + return 0; + left = heightoftree(root.left); + right = heightoftree(root.right); + return ((left if left > right + else right) + 1); + '''Inorder Traversal +Search minimum element in +each level and store it +into vector array.''' + +def printPerLevelMinimum(root, + res, level): + if (root != None): + res = printPerLevelMinimum(root.left, + res, level + 1); + if (root.data < res[level]): + res[level] = root.data; + res = printPerLevelMinimum(root.right, + res, level + 1); + return res +def perLevelMinimumUtility(root): + ''' height of tree for the + size of vector array''' + + n = heightoftree(root) + i = 0 + ''' vector for store all + minimum of every level''' + + res = [INT_MAX for i in range(n)] + ''' save every level minimum + using inorder traversal''' + + res = printPerLevelMinimum(root, + res, 0); + ''' print every level minimum''' + + print(""Every level minimum is"") + for i in range(n): + print('level ' + str(i) + + ' min is = ' + str(res[i])) + '''Utility function to create +a new tree node''' + +def newNode(data): + temp = Node(data) + return temp; + '''Driver code''' + +if __name__ == ""__main__"": + ''' Let us create binary + tree shown in below + diagram''' + + root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + ''' 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 ''' + + perLevelMinimumUtility(root);" +Program to find the minimum (or maximum) element of an array,"/*Java program to find minimum +(or maximum) element +in an array.*/ + +class GFG +{ + +static int getMin(int arr[], int i, int n) +{ +/* If there is single element, return it. + Else return minimum of first element and + minimum of remaining array.*/ + + return (n == 1) ? arr[i] : Math.min(arr[i], + getMin(arr,i + 1 , n - 1)); +} + +static int getMax(int arr[], int i, int n) +{ +/* If there is single element, return it. + Else return maximum of first element and + maximum of remaining array.*/ + + return (n == 1) ? arr[i] : Math.max(arr[i], + getMax(arr ,i + 1, n - 1)); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 12, 1234, 45, 67, 1 }; + int n = arr.length; + System.out.print(""Minimum element of array: "" + + getMin(arr, 0, n) + ""\n""); + System.out.println(""Maximum element of array: "" + + getMax(arr, 0, n)); + } +} + + +"," '''Python3 program to find minimum +(or maximum) element in an array.''' + +def getMin(arr, n): + if(n==1): + return arr[0] + ''' If there is single element, return it. + Else return minimum of first element + and minimum of remaining array.''' + + else: + return min(getMin(arr[1:], n-1), arr[0]) +def getMax(arr, n): + if(n==1): + return arr[0] + ''' If there is single element, return it. + Else return maximum of first element + and maximum of remaining array.''' + + else: + return max(getMax(arr[1:], n-1), arr[0]) + + '''Driver code''' + +arr = [12, 1234, 45, 67, 1] +n = len(arr) +print(""Minimum element of array: "", + getMin(arr, n)); +print(""Maximum element of array: "", + getMax(arr, n)); + + +" +Move all negative elements to end in order with extra space allowed,"/*Java program to Move All -ve Element At End +Without changing order Of Array Element*/ + +import java.util.Arrays; +class GFG { +/* Moves all -ve element to end of array in + same order.*/ + + static void segregateElements(int arr[], int n) + { +/* Create an empty array to store result*/ + + int temp[] = new int[n]; +/* Traversal array and store +ve element in + temp array +index of temp*/ + +int j = 0; + for (int i = 0; i < n; i++) + if (arr[i] >= 0) + temp[j++] = arr[i]; +/* If array contains all positive or all + negative.*/ + + if (j == n || j == 0) + return; +/* Store -ve element in temp array*/ + + for (int i = 0; i < n; i++) + if (arr[i] < 0) + temp[j++] = arr[i]; +/* Copy contents of temp[] to arr[]*/ + + for (int i = 0; i < n; i++) + arr[i] = temp[i]; + } +/* Driver code*/ + + public static void main(String arg[]) + { + int arr[] = { 1, -1, -3, -2, 7, 5, 11, 6 }; + int n = arr.length; + segregateElements(arr, n); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +}"," '''Python program to Move All -ve Element At End +Without changing order Of Array Element''' + + '''Moves all -ve element to end of array in +same order.''' + +def segregateElements(arr, n): ''' Create an empty array to store result''' + + temp = [0 for k in range(n)] + ''' Traversal array and store +ve element in + temp array +index of temp''' + + j = 0 + for i in range(n): + if (arr[i] >= 0 ): + temp[j] = arr[i] + j +=1 + ''' If array contains all positive or all negative.''' + + if (j == n or j == 0): + return + ''' Store -ve element in temp array''' + + for i in range(n): + if (arr[i] < 0): + temp[j] = arr[i] + j +=1 + ''' Copy contents of temp[] to arr[]''' + + for k in range(n): + arr[k] = temp[k] + '''Driver program''' + +arr = [1 ,-1 ,-3 , -2, 7, 5, 11, 6 ] +n = len(arr) +segregateElements(arr, n); +for i in range(n): + print arr[i], +" +Tug of War,"/*Java program for Tug of war*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class TugOfWar +{ + public int min_diff; +/* function that tries every possible solution + by calling itself recursively*/ + + void TOWUtil(int arr[], int n, boolean curr_elements[], + int no_of_selected_elements, boolean soln[], + int sum, int curr_sum, int curr_position) + { +/* checks whether the it is going out of bound*/ + + if (curr_position == n) + return; +/* checks that the numbers of elements left + are not less than the number of elements + required to form the solution*/ + + if ((n / 2 - no_of_selected_elements) > + (n - curr_position)) + return; +/* consider the cases when current element + is not included in the solution*/ + + TOWUtil(arr, n, curr_elements, + no_of_selected_elements, soln, sum, + curr_sum, curr_position+1); +/* add the current element to the solution*/ + + no_of_selected_elements++; + curr_sum = curr_sum + arr[curr_position]; + curr_elements[curr_position] = true; +/* checks if a solution is formed*/ + + if (no_of_selected_elements == n / 2) + { +/* checks if the solution formed is + better than the best solution so + far*/ + + if (Math.abs(sum / 2 - curr_sum) < + min_diff) + { + min_diff = Math.abs(sum / 2 - + curr_sum); + for (int i = 0; i < n; i++) + soln[i] = curr_elements[i]; + } + } + else + { +/* consider the cases where current + element is included in the + solution*/ + + TOWUtil(arr, n, curr_elements, + no_of_selected_elements, + soln, sum, curr_sum, + curr_position + 1); + } +/* removes current element before + returning to the caller of this + function*/ + + curr_elements[curr_position] = false; + } +/* main function that generate an arr*/ + + void tugOfWar(int arr[]) + { + int n = arr.length; +/* the boolean array that contains the + inclusion and exclusion of an element + in current set. The number excluded + automatically form the other set*/ + + boolean[] curr_elements = new boolean[n]; +/* The inclusion/exclusion array for + final solution*/ + + boolean[] soln = new boolean[n]; + min_diff = Integer.MAX_VALUE; + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += arr[i]; + curr_elements[i] = soln[i] = false; + } +/* Find the solution using recursive + function TOWUtil()*/ + + TOWUtil(arr, n, curr_elements, 0, + soln, sum, 0, 0); +/* Print the solution*/ + + System.out.print(""The first subset is: ""); + for (int i = 0; i < n; i++) + { + if (soln[i] == true) + System.out.print(arr[i] + "" ""); + } + System.out.print(""\nThe second subset is: ""); + for (int i = 0; i < n; i++) + { + if (soln[i] == false) + System.out.print(arr[i] + "" ""); + } + } +/* Driver program to test above functions*/ + + public static void main (String[] args) + { + int arr[] = {23, 45, -34, 12, 0, 98, + -99, 4, 189, -1, 4}; + TugOfWar a = new TugOfWar(); + a.tugOfWar(arr); + } +}"," '''Python3 program for above approach''' + + '''function that tries every possible +solution by calling itself recursively ''' + +def TOWUtil(arr, n, curr_elements, no_of_selected_elements, + soln, min_diff, Sum, curr_sum, curr_position): ''' checks whether the it is going + out of bound ''' + + if (curr_position == n): + return + ''' checks that the numbers of elements + left are not less than the number of + elements required to form the solution ''' + + if ((int(n / 2) - no_of_selected_elements) > + (n - curr_position)): + return + ''' consider the cases when current element + is not included in the solution ''' + + TOWUtil(arr, n, curr_elements, no_of_selected_elements, + soln, min_diff, Sum, curr_sum, curr_position + 1) + ''' add the current element to the solution ''' + + no_of_selected_elements += 1 + curr_sum = curr_sum + arr[curr_position] + curr_elements[curr_position] = True + ''' checks if a solution is formed ''' + + if (no_of_selected_elements == int(n / 2)): + ''' checks if the solution formed is better + than the best solution so far ''' + + if (abs(int(Sum / 2) - curr_sum) < min_diff[0]): + min_diff[0] = abs(int(Sum / 2) - curr_sum) + for i in range(n): + soln[i] = curr_elements[i] + else: + ''' consider the cases where current + element is included in the solution ''' + + TOWUtil(arr, n, curr_elements, no_of_selected_elements, + soln, min_diff, Sum, curr_sum, curr_position + 1) + ''' removes current element before returning + to the caller of this function ''' + + curr_elements[curr_position] = False + '''main function that generate an arr ''' + +def tugOfWar(arr, n): + ''' the boolean array that contains the + inclusion and exclusion of an element + in current set. The number excluded + automatically form the other set ''' + + curr_elements = [None] * n + ''' The inclusion/exclusion array + for final solution ''' + + soln = [None] * n + min_diff = [999999999999] + Sum = 0 + for i in range(n): + Sum += arr[i] + curr_elements[i] = soln[i] = False + ''' Find the solution using recursive + function TOWUtil() ''' + + TOWUtil(arr, n, curr_elements, 0, + soln, min_diff, Sum, 0, 0) + ''' Print the solution ''' + + print(""The first subset is: "") + for i in range(n): + if (soln[i] == True): + print(arr[i], end = "" "") + print() + print(""The second subset is: "") + for i in range(n): + if (soln[i] == False): + print(arr[i], end = "" "") + '''Driver Code''' + +if __name__ == '__main__': + arr = [23, 45, -34, 12, 0, 98, + -99, 4, 189, -1, 4] + n = len(arr) + tugOfWar(arr, n)" +Graph representations using set and hash,"/*A Java program to demonstrate adjacency +list using HashMap and TreeSet +representation of graphs using sets*/ + +import java.util.*; +class Graph{ +/*TreeSet is used to get clear +understand of graph.*/ + +HashMap> graph; +static int v; +public Graph() +{ + graph = new HashMap<>(); + for(int i = 0; i < v; i++) + { + graph.put(i, new TreeSet<>()); + } +} + +/*Adds an edge to an undirected graph*/ + +public void addEdge(int src, int dest) +{ +/* Add an edge from src to dest into the set*/ + + graph.get(src).add(dest); +/* Since graph is undirected, add an edge + from dest to src into the set*/ + + graph.get(dest).add(src); +} +/*A utility function to print the graph*/ + +public void printGraph() +{ + for(int i = 0; i < v; i++) + { + System.out.println(""Adjacency list of vertex "" + i); + Iterator set = graph.get(i).iterator(); + while (set.hasNext()) + System.out.print(set.next() + "" ""); + System.out.println(); + System.out.println(); + } +} +/*Searches for a given edge in the graph*/ + +public void searchEdge(int src, int dest) +{ + Iterator set = graph.get(src).iterator(); + if (graph.get(src).contains(dest)) + System.out.println(""Edge from "" + src + "" to "" + + dest + "" found""); + else + System.out.println(""Edge from "" + src + "" to "" + + dest + "" not found""); + System.out.println(); +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Create the graph given in the above figure*/ + + v = 5; + Graph graph = new Graph(); + graph.addEdge(0, 1); + graph.addEdge(0, 4); + graph.addEdge(1, 2); + graph.addEdge(1, 3); + graph.addEdge(1, 4); + graph.addEdge(2, 3); + graph.addEdge(3, 4); +/* Print the adjacency list representation of + the above graph*/ + + graph.printGraph(); +/* Search the given edge in the graph*/ + + graph.searchEdge(2, 1); + graph.searchEdge(0, 3); +} +}"," '''Python3 program to represent adjacency +list using dictionary''' + +class graph(object): + def __init__(self, v): + self.v = v + self.graph = dict() + ''' Adds an edge to undirected graph''' + + def addEdge(self, source, destination): + ''' Add an edge from source to destination. + A new element is inserted to adjacent + list of source.''' + + if source not in self.graph: + self.graph = {destination} + else: + self.graph.add(destination) + ''' Add an dge from destination to source. + A new element is inserted to adjacent + list of destination.''' + + if destination not in self.graph: + self.graph[destination] = {source} + else: + self.graph[destination].add(source) + ''' A utility function to print the adjacency + list representation of graph''' + + def print(self): + for i, adjlist in sorted(self.graph.items()): + print(""Adjacency list of vertex "", i) + for j in sorted(adjlist, reverse = True): + print(j, end = "" "") + print('\n') + ''' Search for a given edge in graph''' + + def searchEdge(self,source,destination): + if source in self.graph: + if destination in self.graph: + print(""Edge from {0} to {1} found.\n"".format( + source, destination)) + else: + print(""Edge from {0} to {1} not found.\n"".format( + source, destination)) + else: + print(""Source vertex {} is not present in graph.\n"".format( + source)) + '''Driver code''' + +if __name__==""__main__"": + + ''' Create the graph given in the above figure''' + + g = graph(5) + g.addEdge(0, 1) + g.addEdge(0, 4) + g.addEdge(1, 2) + g.addEdge(1, 3) + g.addEdge(1, 4) + g.addEdge(2, 3) + g.addEdge(3, 4) ''' Print adjacenecy list + representation of graph''' + + g.print() + ''' Search the given edge in a graph''' + + g.searchEdge(2, 1) + g.searchEdge(0, 3)" +Inorder Successor of a node in Binary Tree,"/*Java program to find inorder successor of a node */ + +class Solution +{ +/*A Binary Tree Node */ + + static class Node +{ + int data; + Node left, right; +} +/*Temporary node for case 2 */ + +static Node temp = new Node(); +/*Utility function to create a new tree node */ + +static Node newNode(int data) + { + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*function to find left most node in a tree */ + +static Node leftMostNode(Node node) + { + while (node != null && node.left != null) + node = node.left; + return node; +} +/*function to find right most node in a tree */ + +static Node rightMostNode(Node node) + { + while (node != null && node.right != null) + node = node.right; + return node; +} +/*recursive function to find the Inorder Scuccessor +when the right child of node x is null */ + +static Node findInorderRecursive(Node root, Node x ) + { + if (root==null) + return null; + if (root==x || (temp = findInorderRecursive(root.left,x))!=null || + (temp = findInorderRecursive(root.right,x))!=null) + { + if (temp!=null) + { + if (root.left == temp) + { + System.out.print( ""Inorder Successor of ""+x.data); + System.out.print( "" is ""+ root.data + ""\n""); + return null; + } + } + return root; + } + return null; +} +/*function to find inorder successor of +a node */ + +static void inorderSuccesor(Node root, Node x) + { +/* Case1: If right child is not null */ + + if (x.right != null) + { + Node inorderSucc = leftMostNode(x.right); + System.out.print(""Inorder Successor of ""+x.data+"" is ""); + System.out.print(inorderSucc.data+""\n""); + } +/* Case2: If right child is null */ + + if (x.right == null) + { + int f = 0; + Node rightMost = rightMostNode(root); +/* case3: If x is the right most node */ + + if (rightMost == x) + System.out.print(""No inorder successor! Right most node.\n""); + else + findInorderRecursive(root, x); + } +} +/*Driver program to test above functions */ + +public static void main(String args[]) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + root.right.right = newNode(6); /* Case 1 */ + + inorderSuccesor(root, root.right); +/* case 2 */ + + inorderSuccesor(root, root.left.left); +/* case 3 */ + + inorderSuccesor(root, root.right.right); +} +}"," ''' Python3 code for inorder succesor +and predecessor of tree ''' + + '''A Binary Tree Node +Utility function to create a new tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''function to find left most node in a tree ''' + +def leftMostNode(node): + while (node != None and node.left != None): + node = node.left + return node + '''function to find right most node in a tree ''' + +def rightMostNode(node): + while (node != None and node.right != None): + node = node.right + return node + '''recursive function to find the Inorder Scuccessor +when the right child of node x is None ''' + +def findInorderRecursive(root, x ): + if (not root): + return None + if (root == x or (findInorderRecursive(root.left, x)) or + (findInorderRecursive(root.right, x))): + if findInorderRecursive(root.right, x): + temp=findInorderRecursive(root.right, x) + else: + temp=findInorderRecursive(root.left, x) + if (temp): + if (root.left == temp): + print(""Inorder Successor of"", + x.data, end = """") + print("" is"", root.data) + return None + return root + return None + '''function to find inorder successor +of a node ''' + +def inorderSuccesor(root, x): + ''' Case1: If right child is not None ''' + + if (x.right != None) : + inorderSucc = leftMostNode(x.right) + print(""Inorder Successor of"", x.data, + ""is"", end = "" "") + print(inorderSucc.data) + ''' Case2: If right child is None ''' + + if (x.right == None): + f = 0 + rightMost = rightMostNode(root) + ''' case3: If x is the right most node ''' + + if (rightMost == x): + print(""No inorder successor!"", + ""Right most node."") + else: + findInorderRecursive(root, x) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.right = newNode(6) + ''' Case 1 ''' + + inorderSuccesor(root, root.right) + ''' case 2 ''' + + inorderSuccesor(root, root.left.left) + ''' case 3 ''' + + inorderSuccesor(root, root.right.right)" +Delete an element from array (Using two traversals and one traversal),"/*Java program to remove a given element from an array*/ + +import java.io.*; + +class Deletion { + +/* This function removes an element x from arr[] and + returns new size after removal (size is reduced only + when x is present in arr[]*/ + + static int deleteElement(int arr[], int n, int x) + { +/* Search x in array*/ + + int i; + for (i=0; i mp1 = new HashMap<>(); + HashMap mp2 = new HashMap<>(); + + for (int i = 0; i < n; i++) + { + mp1.put(perm1[i], i); + } + for (int j = 0; j < n; j++) + { + mp2.put(perm2[j], j); + } + + for (int i = 0; i < n; i++) + { +/* idx1 is index of element + in first permutation + idx2 is index of element + in second permutation*/ + + int idx2 = mp2.get(perm1[i]); + int idx1 = i; + + if (idx1 == idx2) + { +/* If element if present on same + index on both permutations then + distance is zero*/ + + left[i] = 0; + right[i] = 0; + } + else if (idx1 < idx2) + { +/* Calculate distance from left + and right side*/ + + left[i] = (n - (idx2 - idx1)); + right[i] = (idx2 - idx1); + } + else + { +/* Calculate distance from left + and right side*/ + + left[i] = (idx1 - idx2); + right[i] = (n - (idx1 - idx2)); + } + } + +/* Maps to store frequencies of elements + present in left and right arrays*/ + + HashMap freq1 = new HashMap<>(); + HashMap freq2 = new HashMap<>(); + + for (int i = 0; i < n; i++) + { + if(freq1.containsKey(left[i])) + freq1.put(left[i], + freq1.get(left[i]) + 1); + else + freq1.put(left[i], 1); + if(freq2.containsKey(right[i])) + freq2.put(right[i], + freq2.get(right[i]) + 1); + else + freq2.put(right[i], 1); + } + + int ans = 0; + + for (int i = 0; i < n; i++) + { +/* Find maximum frequency*/ + + ans = Math.max(ans, + Math.max(freq1.get(left[i]), + freq2.get(right[i]))); + } + +/* Return the result*/ + + return ans; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Given permutations P1 and P2*/ + + int P1[] = {5, 4, 3, 2, 1}; + int P2[] = {1, 2, 3, 4, 5}; + int n = P1.length; + +/* Function Call*/ + + System.out.print(maximumMatchingPairs(P1, P2, n)); +} +} + + +"," '''Python3 program for the above approach''' + +from collections import defaultdict + + '''Function to maximize the matching +pairs between two permutation +using left and right rotation''' + +def maximumMatchingPairs(perm1, perm2, n): + + ''' Left array store distance of element + from left side and right array store + distance of element from right side''' + + left = [0] * n + right = [0] * n + + ''' Map to store index of elements''' + + mp1 = {} + mp2 = {} + for i in range (n): + mp1[perm1[i]] = i + + for j in range (n): + mp2[perm2[j]] = j + + for i in range (n): + + ''' idx1 is index of element + in first permutation idx2 is index of element + in second permutation''' + + idx2 = mp2[perm1[i]] + idx1 = i + + if (idx1 == idx2): + + + ''' If element if present on same + index on both permutations then + distance is zero''' + + left[i] = 0 + right[i] = 0 + + elif (idx1 < idx2): + + ''' Calculate distance from left + and right side''' + + left[i] = (n - (idx2 - idx1)) + right[i] = (idx2 - idx1) + + else : + + ''' Calculate distance from left + and right side''' + + left[i] = (idx1 - idx2) + right[i] = (n - (idx1 - idx2)) + + ''' Maps to store frequencies of elements + present in left and right arrays''' + + freq1 = defaultdict (int) + freq2 = defaultdict (int) + for i in range (n): + freq1[left[i]] += 1 + freq2[right[i]] += 1 + + ans = 0 + + for i in range( n): + + ''' Find maximum frequency''' + + ans = max(ans, max(freq1[left[i]], + freq2[right[i]])) + + ''' Return the result''' + + return ans + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Given permutations P1 and P2''' + + P1 = [ 5, 4, 3, 2, 1 ] + P2 = [ 1, 2, 3, 4, 5 ] + n = len(P1) + + ''' Function Call''' + + print(maximumMatchingPairs(P1, P2, n)) + + +" +Maximum equlibrium sum in an array,"/*java program to find maximum +equilibrium sum.*/ + +import java.io.*; +class GFG { +/* Function to find maximum + equilibrium sum.*/ + + static int findMaxSum(int []arr, int n) + { + int res = Integer.MIN_VALUE; + for (int i = 0; i < n; i++) + { + int prefix_sum = arr[i]; + for (int j = 0; j < i; j++) + prefix_sum += arr[j]; + int suffix_sum = arr[i]; + for (int j = n - 1; j > i; j--) + suffix_sum += arr[j]; + if (prefix_sum == suffix_sum) + res = Math.max(res, prefix_sum); + } + return res; + } +/* Driver Code*/ + + public static void main (String[] args) + { + int arr[] = {-2, 5, 3, 1, 2, 6, -4, 2 }; + int n = arr.length; + System.out.println(findMaxSum(arr, n)); + } +}"," '''Python 3 program to find maximum +equilibrium sum.''' + +import sys + '''Function to find maximum equilibrium sum.''' + +def findMaxSum(arr, n): + res = -sys.maxsize - 1 + for i in range(n): + prefix_sum = arr[i] + for j in range(i): + prefix_sum += arr[j] + suffix_sum = arr[i] + j = n - 1 + while(j > i): + suffix_sum += arr[j] + j -= 1 + if (prefix_sum == suffix_sum): + res = max(res, prefix_sum) + return res + '''Driver Code''' + +if __name__ == '__main__': + arr = [-2, 5, 3, 1, 2, 6, -4, 2] + n = len(arr) + print(findMaxSum(arr, n))" +Maximum XOR value in matrix,"/*Java program to Find maximum XOR value in +matrix either row / column wise*/ + +class GFG { + static final int MAX = 1000;/* function return the maximum xor value + that is either row or column wise*/ + + static int maxXOR(int mat[][], int N) + { +/* for row xor and column xor*/ + + int r_xor, c_xor; + int max_xor = 0; +/* traverse matrix*/ + + for (int i = 0 ; i < N ; i++) + { + r_xor = 0; c_xor = 0; + for (int j = 0 ; j < N ; j++) + { +/* xor row element*/ + + r_xor = r_xor^mat[i][j]; +/* for each column : j is act as row & i + act as column xor column element*/ + + c_xor = c_xor^mat[j][i]; + } +/* update maximum between r_xor , c_xor*/ + + if (max_xor < Math.max(r_xor, c_xor)) + max_xor = Math.max(r_xor, c_xor); + } +/* return maximum xor value*/ + + return max_xor; + } +/* driver code*/ + + public static void main (String[] args) + { + int N = 3; + int mat[][] = { {1, 5, 4}, + {3, 7, 2}, + {5, 9, 10}}; + System.out.print(""maximum XOR value : "" + + maxXOR(mat, N)); + } +}"," '''Python3 program to Find maximum +XOR value in matrix either row / column wise +maximum number of row and column''' + +MAX = 1000 + '''Function return the maximum +xor value that is either row +or column wise''' + +def maxXOR(mat, N): + ''' For row xor and column xor''' + + max_xor = 0 + ''' Traverse matrix''' + + for i in range(N): + r_xor = 0 + c_xor = 0 + for j in range(N): + ''' xor row element''' + + r_xor = r_xor ^ mat[i][j] + ''' for each column : j is act as row & i + act as column xor column element''' + + c_xor = c_xor ^ mat[j][i] + ''' update maximum between r_xor , c_xor''' + + if (max_xor < max(r_xor, c_xor)): + max_xor = max(r_xor, c_xor) + ''' return maximum xor value''' + + return max_xor + '''Driver Code''' + +N = 3 +mat= [[1 , 5, 4], + [3 , 7, 2 ], + [5 , 9, 10]] +print(""maximum XOR value : "", + maxXOR(mat, N))" +Flood fill Algorithm,"/*Java program to implement flood fill algorithm*/ + +class GFG +{ +/*Dimentions of paint screen*/ + +static int M = 8; +static int N = 8; +/*A recursive function to replace previous color 'prevC' at '(x, y)' +and all surrounding pixels of (x, y) with new color 'newC' and*/ + +static void floodFillUtil(int screen[][], int x, int y, + int prevC, int newC) +{ +/* Base cases*/ + + if (x < 0 || x >= M || y < 0 || y >= N) + return; + if (screen[x][y] != prevC) + return; +/* Replace the color at (x, y)*/ + + screen[x][y] = newC; +/* Recur for north, east, south and west*/ + + floodFillUtil(screen, x+1, y, prevC, newC); + floodFillUtil(screen, x-1, y, prevC, newC); + floodFillUtil(screen, x, y+1, prevC, newC); + floodFillUtil(screen, x, y-1, prevC, newC); +} +/*It mainly finds the previous color on (x, y) and +calls floodFillUtil()*/ + +static void floodFill(int screen[][], int x, int y, int newC) +{ + int prevC = screen[x][y]; + floodFillUtil(screen, x, y, prevC, newC); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int screen[][] = {{1, 1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1, 1, 0, 0}, + {1, 0, 0, 1, 1, 0, 1, 1}, + {1, 2, 2, 2, 2, 0, 1, 0}, + {1, 1, 1, 2, 2, 0, 1, 0}, + {1, 1, 1, 2, 2, 2, 2, 0}, + {1, 1, 1, 1, 1, 2, 1, 1}, + {1, 1, 1, 1, 1, 2, 2, 1}, + }; + int x = 4, y = 4, newC = 3; + floodFill(screen, x, y, newC); + System.out.println(""Updated screen after call to floodFill: ""); + for (int i = 0; i < M; i++) + { + for (int j = 0; j < N; j++) + System.out.print(screen[i][j] + "" ""); + System.out.println(); + } + } +}"," '''Python3 program to implement +flood fill algorithm + ''' '''Dimentions of paint screen''' + +M = 8 +N = 8 + '''A recursive function to replace +previous color 'prevC' at '(x, y)' +and all surrounding pixels of (x, y) +with new color 'newC' and''' + +def floodFillUtil(screen, x, y, prevC, newC): + ''' Base cases''' + + if (x < 0 or x >= M or y < 0 or + y >= N or screen[x][y] != prevC or + screen[x][y] == newC): + return + ''' Replace the color at (x, y)''' + + screen[x][y] = newC + ''' Recur for north, east, south and west''' + + floodFillUtil(screen, x + 1, y, prevC, newC) + floodFillUtil(screen, x - 1, y, prevC, newC) + floodFillUtil(screen, x, y + 1, prevC, newC) + floodFillUtil(screen, x, y - 1, prevC, newC) + '''It mainly finds the previous color on (x, y) and +calls floodFillUtil()''' + +def floodFill(screen, x, y, newC): + prevC = screen[x][y] + floodFillUtil(screen, x, y, prevC, newC) + '''Driver Code''' + +screen = [[1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 0, 0], + [1, 0, 0, 1, 1, 0, 1, 1], + [1, 2, 2, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 0, 1, 0], + [1, 1, 1, 2, 2, 2, 2, 0], + [1, 1, 1, 1, 1, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 1]] +x = 4 +y = 4 +newC = 3 +floodFill(screen, x, y, newC) +print (""Updated screen after call to floodFill:"") +for i in range(M): + for j in range(N): + print(screen[i][j], end = ' ') + print()" +"Sort a linked list of 0s, 1s and 2s","/*Java program to sort a linked list of 0, 1 and 2*/ + +class LinkedList +{ +/*head of list*/ + +Node head; + + /* Linked list Node*/ + + class Node + { + int data; + Node next; + Node(int d) {data = d; next = null; } + } + + void sortList() + { +/* initialise count of 0 1 and 2 as 0*/ + + int count[] = {0, 0, 0}; + + Node ptr = head; + + /* count total number of '0', '1' and '2' + * count[0] will store total number of '0's + * count[1] will store total number of '1's + * count[2] will store total number of '2's */ + + while (ptr != null) + { + count[ptr.data]++; + ptr = ptr.next; + } + + int i = 0; + ptr = head; + + /* Let say count[0] = n1, count[1] = n2 and count[2] = n3 + * now start traversing list from head node, + * 1) fill the list with 0, till n1 > 0 + * 2) fill the list with 1, till n2 > 0 + * 3) fill the list with 2, till n3 > 0 */ + + while (ptr != null) + { + if (count[i] == 0) + i++; + else + { + ptr.data= i; + --count[i]; + ptr = ptr.next; + } + } + } + + + /* Inserts a new Node at front of the list. */ + + public void push(int new_data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + + /* 3. Make next of new Node as head */ + + new_node.next = head; + + /* 4. Move the head to point to new Node */ + + head = new_node; + } + + /* Function to print linked list */ + + void printList() + { + Node temp = head; + while (temp != null) + { + System.out.print(temp.data+"" ""); + temp = temp.next; + } + System.out.println(); + } + + /* Driver program to test above functions */ + + public static void main(String args[]) + { + LinkedList llist = new LinkedList(); + + /* Constructed Linked List is 1->2->3->4->5->6->7-> + 8->8->9->null */ + + llist.push(0); + llist.push(1); + llist.push(0); + llist.push(2); + llist.push(1); + llist.push(1); + llist.push(2); + llist.push(1); + llist.push(2); + + System.out.println(""Linked List before sorting""); + llist.printList(); + + llist.sortList(); + + System.out.println(""Linked List after sorting""); + llist.printList(); + } +} + +"," '''Python program to sort a linked list of 0, 1 and 2''' + +class LinkedList(object): + def __init__(self): + + ''' head of list''' + + self.head = None + + ''' Linked list Node''' + + class Node(object): + def __init__(self, d): + self.data = d + self.next = None + + def sortList(self): + + ''' initialise count of 0 1 and 2 as 0''' + + count = [0, 0, 0] + + ptr = self.head + + ''' count total number of '0', '1' and '2' + * count[0] will store total number of '0's + * count[1] will store total number of '1's + * count[2] will store total number of '2's ''' + + while ptr != None: + count[ptr.data]+=1 + ptr = ptr.next + + i = 0 + ptr = self.head + + ''' Let say count[0] = n1, count[1] = n2 and count[2] = n3 + * now start traversing list from head node, + * 1) fill the list with 0, till n1 > 0 + * 2) fill the list with 1, till n2 > 0 + * 3) fill the list with 2, till n3 > 0 ''' + + while ptr != None: + if count[i] == 0: + i+=1 + else: + ptr.data = i + count[i]-=1 + ptr = ptr.next + + + ''' Inserts a new Node at front of the list.''' + + def push(self, new_data): + + ''' 1 & 2: Allocate the Node & + Put in the data''' + + new_node = self.Node(new_data) + + ''' 3. Make next of new Node as head''' + + new_node.next = self.head + + ''' 4. Move the head to point to new Node''' + + self.head = new_node + + ''' Function to print linked list''' + + def printList(self): + temp = self.head + while temp != None: + print str(temp.data), + temp = temp.next + print '' + + '''Driver program to test above functions''' + + + + + ''' Constructed Linked List is 1->2->3->4->5->6->7-> + 8->8->9->null ''' + +llist = LinkedList() +llist.push(0) +llist.push(1) +llist.push(0) +llist.push(2) +llist.push(1) +llist.push(1) +llist.push(2) +llist.push(1) +llist.push(2) + +print ""Linked List before sorting"" +llist.printList() + +llist.sortList() + +print ""Linked List after sorting"" +llist.printList()" +Smallest power of 2 greater than or equal to n,"/*Java program to find smallest +power of 2 greater than or +equal to n*/ + +import java.io.*; +class GFG +{ + static int nextPowerOf2(int n) + { + int p = 1; + if (n > 0 && (n & (n - 1)) == 0) + return n; + while (p < n) + p <<= 1; + return p; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int n = 5; + System.out.println(nextPowerOf2(n)); + } +}","def nextPowerOf2(n): + p = 1 + if (n and not(n & (n - 1))): + return n + while (p < n) : + p <<= 1 + return p; + '''Driver Code''' + +n = 5 +print(nextPowerOf2(n));" +Check given matrix is magic square or not,"/*JAVA program to check whether a given +matrix is magic matrix or not*/ + +import java.io.*; +class GFG { + static int N = 3; +/* Returns true if mat[][] is magic + square, else returns false.*/ + + static boolean isMagicSquare(int mat[][]) + { +/* calculate the sum of + the prime diagonal*/ + + int sum = 0,sum2=0; + for (int i = 0; i < N; i++) + sum = sum + mat[i][i]; +/* the secondary diagonal*/ + + for (int i = 0; i < N; i++) + sum2 = sum2 + mat[i][N-1-i]; + if(sum!=sum2) + return false; +/* For sums of Rows*/ + + for (int i = 0; i < N; i++) { + int rowSum = 0; + for (int j = 0; j < N; j++) + rowSum += mat[i][j]; +/* check if every row sum is + equal to prime diagonal sum*/ + + if (rowSum != sum) + return false; + } +/* For sums of Columns*/ + + for (int i = 0; i < N; i++) { + int colSum = 0; + for (int j = 0; j < N; j++) + colSum += mat[j][i]; +/* check if every column sum is + equal to prime diagonal sum*/ + + if (sum != colSum) + return false; + } + return true; + } +/* driver program to + test above function*/ + + public static void main(String[] args) + { + int mat[][] = {{ 2, 7, 6 }, + { 9, 5, 1 }, + { 4, 3, 8 }}; + if (isMagicSquare(mat)) + System.out.println(""Magic Square""); + else + System.out.println(""Not a magic"" + + "" Square""); + } +}"," '''Python3 program to check whether a given +matrix is magic matrix or not''' + +N = 3 + '''Returns true if mat[][] is magic +square, else returns false.''' + +def isMagicSquare( mat) : + ''' calculate the sum of + the prime diagonal''' + + s = 0 + for i in range(0, N) : + s = s + mat[i][i] + ''' the secondary diagonal''' + + s2 = 0 + for i in range(0, N) : + s2 = s2 + mat[i][N-i-1] + if(s!=s2) : + return False + ''' For sums of Rows''' + + for i in range(0, N) : + rowSum = 0; + for j in range(0, N) : + rowSum += mat[i][j] + ''' check if every row sum is + equal to prime diagonal sum''' + + if (rowSum != s) : + return False + ''' For sums of Columns''' + + for i in range(0, N): + colSum = 0 + for j in range(0, N) : + colSum += mat[j][i] + ''' check if every column sum is + equal to prime diagonal sum''' + + if (s != colSum) : + return False + return True + '''Driver Code''' + +mat = [ [ 2, 7, 6 ], + [ 9, 5, 1 ], + [ 4, 3, 8 ] ] +if (isMagicSquare(mat)) : + print( ""Magic Square"") +else : + print( ""Not a magic Square"")" +Find Height of Binary Tree represented by Parent array,"/*Java program to find height using parent array*/ + +class BinaryTree { +/* This function fills depth of i'th element in parent[]. The depth is + filled in depth[i].*/ + + void fillDepth(int parent[], int i, int depth[]) { +/* If depth[i] is already filled*/ + + if (depth[i] != 0) { + return; + } +/* If node at index i is root*/ + + if (parent[i] == -1) { + depth[i] = 1; + return; + } +/* If depth of parent is not evaluated before, then evaluate + depth of parent first*/ + + if (depth[parent[i]] == 0) { + fillDepth(parent, parent[i], depth); + } +/* Depth of this node is depth of parent plus 1*/ + + depth[i] = depth[parent[i]] + 1; + } +/* This function returns height of binary tree represented by + parent array*/ + + int findHeight(int parent[], int n) { +/* Create an array to store depth of all nodes/ and + initialize depth of every node as 0 (an invalid + value). Depth of root is 1*/ + + int depth[] = new int[n]; + for (int i = 0; i < n; i++) { + depth[i] = 0; + } +/* fill depth of all nodes*/ + + for (int i = 0; i < n; i++) { + fillDepth(parent, i, depth); + } +/* The height of binary tree is maximum of all depths. + Find the maximum value in depth[] and assign it to ht.*/ + + int ht = depth[0]; + for (int i = 1; i < n; i++) { + if (ht < depth[i]) { + ht = depth[i]; + } + } + return ht; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); +/* int parent[] = {1, 5, 5, 2, 2, -1, 3};*/ + + int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5}; + int n = parent.length; + System.out.println(""Height is "" + tree.findHeight(parent, n)); + } +}"," '''Python program to find height using parent array''' + '''This functio fills depth of i'th element in parent[] +The depth is filled in depth[i]''' + +def fillDepth(parent, i , depth): + ''' If depth[i] is already filled''' + + if depth[i] != 0: + return + ''' If node at index i is root''' + + if parent[i] == -1: + depth[i] = 1 + return + ''' If depth of parent is not evaluated before, + then evaluate depth of parent first''' + + if depth[parent[i]] == 0: + fillDepth(parent, parent[i] , depth) + ''' Depth of this node is depth of parent plus 1''' + + depth[i] = depth[parent[i]] + 1 + '''This function reutns height of binary tree represented +by parent array''' + +def findHeight(parent): + n = len(parent) + ''' Create an array to store depth of all nodes and + initialize depth of every node as 0 + Depth of root is 1''' + + depth = [0 for i in range(n)] + ''' fill depth of all nodes''' + + for i in range(n): + fillDepth(parent, i, depth) + ''' The height of binary tree is maximum of all + depths. Find the maximum in depth[] and assign + it to ht''' + + ht = depth[0] + for i in range(1,n): + ht = max(ht, depth[i]) + return ht + '''Driver program to test above function''' + + '''int parent[] = {1, 5, 5, 2, 2, -1, 3};''' + +parent = [-1 , 0 , 0 , 1 , 1 , 3 , 5] +print ""Height is %d"" %(findHeight(parent))" +Interchange elements of first and last rows in matrix,"/*Java code to swap the element of first +and last row and display the result*/ + +import java.io.*; +public class Interchange { + static void interchangeFirstLast(int m[][]) + { + int rows = m.length; +/* swapping of element between first + and last rows*/ + + for (int i = 0; i < m[0].length; i++) { + int t = m[0][i]; + m[0][i] = m[rows-1][i]; + m[rows-1][i] = t; + } + } +/* Driver code*/ + + public static void main(String args[]) throws IOException + { +/* input in the array*/ + + int m[][] = { { 8, 9, 7, 6 }, + { 4, 7, 6, 5 }, + { 3, 2, 1, 8 }, + { 9, 9, 7, 7 } }; + interchangeFirstLast(m); +/* printing the interchanged matrix*/ + + for (int i = 0; i < m.length; i++) { + for (int j = 0; j < m[0].length; j++) + System.out.print(m[i][j] + "" ""); + System.out.println(); + } + } +}"," '''Python code to swap the element +of first and last row and display +the result''' + +def interchangeFirstLast(mat, n, m): + rows = n + ''' swapping of element between + first and last rows''' + + for i in range(n): + t = mat[0][i] + mat[0][i] = mat[rows-1][i] + mat[rows-1][i] = t + '''Driver Program''' '''input in the array''' + +mat = [[8, 9, 7, 6], + [4, 7, 6, 5], + [3, 2, 1, 8], + [9, 9, 7, 7]] +n = 4 +m = 4 +interchangeFirstLast(mat, n, m) + '''printing the interchanged matrix''' + +for i in range(n): + for j in range(m): + print(mat[i][j], end = "" "") + print(""\n"")" +Binary Indexed Tree : Range Updates and Point Queries,"/* Java code to demonstrate Range Update and +* Point Queries on a Binary Index Tree. +* This method only works when all array +* values are initially 0.*/ + +class GFG +{ +/* Max tree size*/ + + final static int MAX = 1000; + static int BITree[] = new int[MAX]; +/* Updates a node in Binary Index + Tree (BITree) at given index + in BITree. The given value 'val' + is added to BITree[i] and + all of its ancestors in tree.*/ + + public static void updateBIT(int n, + int index, + int val) + { +/* index in BITree[] is 1 + more than the index in arr[]*/ + + index = index + 1; +/* Traverse all ancestors + and add 'val'*/ + + while (index <= n) + { +/* Add 'val' to current + node of BITree*/ + + BITree[index] += val; +/* Update index to that + of parent in update View*/ + + index += index & (-index); + } + } +/* Constructs Binary Indexed Tree + for given array of size n.*/ + + public static void constructBITree(int arr[], + int n) + { +/* Initialize BITree[] as 0*/ + + for(int i = 1; i <= n; i++) + BITree[i] = 0; +/* Store the actual values + in BITree[] using update()*/ + + for(int i = 0; i < n; i++) + updateBIT(n, i, arr[i]); + + } +/* SERVES THE PURPOSE OF getElement() + Returns sum of arr[0..index]. This + function assumes that the array is + preprocessed and partial sums of + array elements are stored in BITree[]*/ + + public static int getSum(int index) + { +/*Initialize result*/ + +int sum = 0; +/* index in BITree[] is 1 more + than the index in arr[]*/ + + index = index + 1; +/* Traverse ancestors + of BITree[index]*/ + + while (index > 0) + { +/* Add current element + of BITree to sum*/ + + sum += BITree[index]; +/* Move index to parent + node in getSum View*/ + + index -= index & (-index); + } +/* Return the sum*/ + + return sum; + } +/* Updates such that getElement() + gets an increased value when + queried from l to r.*/ + + public static void update(int l, int r, + int n, int val) + { +/* Increase value at + 'l' by 'val'*/ + + updateBIT(n, l, val); +/* Decrease value at + 'r+1' by 'val'*/ + + updateBIT(n, r + 1, -val); + } +/* Driver Code*/ + + public static void main(String args[]) + { + int arr[] = {0, 0, 0, 0, 0}; + int n = arr.length; + constructBITree(arr,n); +/* Add 2 to all the + element from [2,4]*/ + + int l = 2, r = 4, val = 2; + update(l, r, n, val); + +/* Find the element at Index 4*/ + + int index = 4; + System.out.println(""Element at index ""+ + index + "" is ""+ + getSum(index));/* Add 2 to all the + element from [0,3]*/ + + l = 0; r = 3; val = 4; + update(l, r, n, val); +/* Find the element + at Index 3*/ + + index = 3; + System.out.println(""Element at index ""+ + index + "" is ""+ + getSum(index)); + } +}"," '''Python3 code to demonstrate Range Update and +PoQueries on a Binary Index Tree''' + '''Updates a node in Binary Index Tree (BITree) at given index +in BITree. The given value 'val' is added to BITree[i] and +all of its ancestors in tree.''' + +def updateBIT(BITree, n, index, val): + ''' index in BITree[] is 1 more than the index in arr[]''' + + index = index + 1 + ''' Traverse all ancestors and add 'val''' + ''' + while (index <= n): + ''' Add 'val' to current node of BI Tree''' + + BITree[index] += val + ''' Update index to that of parent in update View''' + + index += index & (-index) + '''Constructs and returns a Binary Indexed Tree for given +array of size n.''' + +def constructBITree(arr, n): + ''' Create and initialize BITree[] as 0''' + + BITree = [0]*(n+1) + ''' Store the actual values in BITree[] using update()''' + + for i in range(n): + updateBIT(BITree, n, i, arr[i]) + return BITree + '''SERVES THE PURPOSE OF getElement() +Returns sum of arr[0..index]. This function assumes +that the array is preprocessed and partial sums of +array elements are stored in BITree[]''' + +def getSum(BITree, index): + '''Iniialize result''' + + sum = 0 + ''' index in BITree[] is 1 more than the index in arr[]''' + + index = index + 1 + ''' Traverse ancestors of BITree[index]''' + + while (index > 0): + ''' Add current element of BITree to sum''' + + sum += BITree[index] + ''' Move index to parent node in getSum View''' + + index -= index & (-index) + + ''' Return the sum ''' + + return sum '''Updates such that getElement() gets an increased +value when queried from l to r.''' + +def update(BITree, l, r, n, val): + ''' Increase value at 'l' by 'val''' + ''' + updateBIT(BITree, n, l, val) + ''' Decrease value at 'r+1' by 'val''' + ''' + updateBIT(BITree, n, r+1, -val) + '''Driver code''' + +arr = [0, 0, 0, 0, 0] +n = len(arr) +BITree = constructBITree(arr, n) + '''Add 2 to all the element from [2,4]''' + +l = 2 +r = 4 +val = 2 +update(BITree, l, r, n, val) + '''Find the element at Index 4''' + +index = 4 +print(""Element at index"", index, ""is"", getSum(BITree, index)) + '''Add 2 to all the element from [0,3]''' + +l = 0 +r = 3 +val = 4 +update(BITree, l, r, n, val) + '''Find the element at Index 3''' + +index = 3 +print(""Element at index"", index, ""is"", getSum(BITree,index))" +Sum of heights of all individual nodes in a binary tree,"/*Java program to find sum of heights of all +nodes in a binary tree*/ + +class GfG { +/* A binary tree Node has data, pointer to + left child and a pointer to right child */ + +static class Node { + int data; + Node left; + Node right; +} +/* Compute the ""maxHeight"" of a particular Node*/ + +static int getHeight(Node Node) +{ + if (Node == null) + return 0; + else { + /* compute the height of each subtree */ + + int lHeight = getHeight(Node.left); + int rHeight = getHeight(Node.right); + /* use the larger one */ + + if (lHeight > rHeight) + return (lHeight + 1); + else + return (rHeight + 1); + } +} +/* Helper function that allocates a new Node with the +given data and NULL left and right pointers. */ + +static Node newNode(int data) +{ + Node Node = new Node(); + Node.data = data; + Node.left = null; + Node.right = null; + return (Node); +} +/* Function to sum of heights of individual Nodes +Uses Inorder traversal */ + +static int getTotalHeight( Node root) +{ + if (root == null) + return 0; + return getTotalHeight(root.left) + getHeight(root) + getTotalHeight(root.right); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + System.out.println(""Sum of heights of all Nodes = "" + getTotalHeight(root)); +} +}"," '''Python3 program to find sum of heights +of all nodes in a binary tree''' + + '''Compute the ""maxHeight"" of a +particular Node''' + +def getHeight(Node): + if (Node == None): + return 0 + else: + ''' compute the height of each subtree''' + + lHeight = getHeight(Node.left) + rHeight = getHeight(Node.right) + ''' use the larger one''' + + if (lHeight > rHeight): + return (lHeight + 1) + else: + return (rHeight + 1) + '''Helper class that allocates a new Node +with the given data and None left and +right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to sum of heights of +individual Nodes Uses Inorder traversal''' + +def getTotalHeight(root): + if (root == None): + return 0 + return (getTotalHeight(root.left) + + getHeight(root) + + getTotalHeight(root.right)) + '''Driver code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) +print(""Sum of heights of all Nodes ="", + getTotalHeight(root))" +Count frequencies of all elements in array in O(1) extra space and O(n) time,"/*Java program to print frequencies of all array +elements in O(n) extra space and O(n) time*/ + +import java.util.*; + +class GFG{ + +/*Function to find counts of all elements +present in arr[0..n-1]. The array elements +must be range from 1 to n*/ + +public static void findCounts(int arr[], int n) +{ + +/* Hashmap*/ + + int hash[] = new int[n]; + Arrays.fill(hash, 0); + +/* Traverse all array elements*/ + + int i = 0; + + while (i < n) + { + +/* Update the frequency of array[i]*/ + + hash[arr[i] - 1]++; + +/* Increase the index*/ + + i++; + } + System.out.println(""\nBelow are counts "" + + ""of all elements""); + for(i = 0; i < n; i++) + { + System.out.println((i + 1) + "" -> "" + + hash[i]); + } +} + +/*Driver code*/ + +public static void main(String []args) +{ + int arr[] = { 2, 3, 3, 2, 5 }; + findCounts(arr, arr.length); + + int arr1[] = {1}; + findCounts(arr1, arr1.length); + + int arr3[] = { 4, 4, 4, 4 }; + findCounts(arr3, arr3.length); + + int arr2[] = { 1, 3, 5, 7, 9, + 1, 3, 5, 7, 9, 1 }; + findCounts(arr2, arr2.length); + + int arr4[] = { 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3 }; + findCounts(arr4, arr4.length); + + int arr5[] = { 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11 }; + findCounts(arr5, arr5.length); + + int arr6[] = { 11, 10, 9, 8, 7, + 6, 5, 4, 3, 2, 1 }; + findCounts(arr6, arr6.length); +} +} + + +"," '''Python3 program to print frequencies +of all array elements in O(n) extra +space and O(n) time''' + + + '''Function to find counts of all +elements present in arr[0..n-1]. +The array elements must be range +from 1 to n''' + +def findCounts(arr, n): + + ''' Hashmap''' + + hash = [0 for i in range(n)] + + ''' Traverse all array elements''' + + i = 0 + + while (i < n): + + ''' Update the frequency of array[i]''' + + hash[arr[i] - 1] += 1 + + ''' Increase the index''' + + i += 1 + + print(""Below are counts of all elements"") + for i in range(n): + print(i + 1, ""->"", hash[i], end = "" "") + print() + + '''Driver code''' + +arr = [ 2, 3, 3, 2, 5 ] +findCounts(arr, len(arr)) + +arr1 = [1] +findCounts(arr1, len(arr1)) + +arr3 = [ 4, 4, 4, 4 ] +findCounts(arr3, len(arr3)) + +arr2 = [ 1, 3, 5, 7, 9, + 1, 3, 5, 7, 9, 1 ] +findCounts(arr2, len(arr2)) + +arr4 = [ 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3 ] +findCounts(arr4, len(arr4)) + +arr5 = [ 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11 ] +findCounts(arr5, len(arr5)) + +arr6 = [ 11, 10, 9, 8, 7, + 6, 5, 4, 3, 2, 1 ] +findCounts(arr6, len(arr6)) + + +" +Print left rotation of array in O(n) time and O(1) space,"/*JAVA implementation of left rotation +of an array K number of times*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class arr_rot { +/* Function to leftRotate array multiple + times*/ + + static void leftRotate(int arr[], int n, int k) + { + /* To get the starting point of + rotated array */ + + int mod = k % n; +/* Prints the rotated array from + start position*/ + + for (int i = 0; i < n; ++i) + System.out.print(arr[(i + mod) % n] + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 5, 7, 9 }; + int n = arr.length; + int k = 2; +/* Function Call*/ + + leftRotate(arr, n, k); + k = 3; +/* Function Call*/ + + leftRotate(arr, n, k); + k = 4; +/* Function Call*/ + + leftRotate(arr, n, k); + } +}"," '''Python implementation of left rotation of +an array K number of times + ''' '''Function to leftRotate array multiple times''' + +def leftRotate(arr, n, k): + ''' To get the starting point of rotated array''' + + mod = k % n + s = """" + ''' Prints the rotated array from start position''' + + for i in range(n): + print str(arr[(mod + i) % n]), + print + return + '''Driver code''' + +arr = [1, 3, 5, 7, 9] +n = len(arr) +k = 2 + '''Function Call''' + +leftRotate(arr, n, k) +k = 3 + '''Function Call''' + +leftRotate(arr, n, k) +k = 4 + '''Function Call''' + +leftRotate(arr, n, k)" +Find sum of all left leaves in a given Binary Tree,"/*Java program to find sum of all left leaves*/ + + +/* A binary tree Node has key, pointer to left and right + children */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* A utility function to check if a given node is leaf or not*/ + + boolean isLeaf(Node node) + { + if (node == null) + return false; + if (node.left == null && node.right == null) + return true; + return false; + } +/* This function returns sum of all left leaves in a given + binary tree*/ + + int leftLeavesSum(Node node) + { +/* Initialize result*/ + + int res = 0; +/* Update result if root is not NULL*/ + + if (node != null) + { +/* If left of root is NULL, then add key of + left child*/ + + if (isLeaf(node.left)) + res += node.left.data; +/*Else recur for left child of root*/ + +else + res += leftLeavesSum(node.left); +/* Recur for right child of root and update res*/ + + res += leftLeavesSum(node.right); + } +/* return result*/ + + return res; + } +/* Driver program*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(9); + tree.root.right = new Node(49); + tree.root.left.right = new Node(12); + tree.root.left.left = new Node(5); + tree.root.right.left = new Node(23); + tree.root.right.right = new Node(52); + tree.root.left.right.right = new Node(12); + tree.root.right.right.left = new Node(50); + System.out.println(""The sum of leaves is "" + + tree.leftLeavesSum(tree.root)); + } +}"," '''Python program to find sum of all left leaves''' + + '''A Binary tree node''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''A utility function to check if a given node is leaf or not''' + +def isLeaf(node): + if node is None: + return False + if node.left is None and node.right is None: + return True + return False + '''This function return sum of all left leaves in a +given binary tree''' + +def leftLeavesSum(root): + ''' Initialize result''' + + res = 0 + ''' Update result if root is not None''' + + if root is not None: + ''' If left of root is None, then add key of + left child''' + + if isLeaf(root.left): + res += root.left.key + else: + ''' Else recur for left child of root''' + + res += leftLeavesSum(root.left) + ''' Recur for right child of root and update res''' + + res += leftLeavesSum(root.right) + + ''' return result''' + + return res '''Driver program to test above function''' + +root = Node(20) +root.left = Node(9) +root.right = Node(49) +root.right.left = Node(23) +root.right.right = Node(52) +root.right.right.left = Node(50) +root.left.left = Node(5) +root.left.right = Node(12) +root.left.right.right = Node(12) +print ""Sum of left leaves is"", leftLeavesSum(root)" +Smallest subarray with all occurrences of a most frequent element,"/*Java implementation to find smallest +subarray with all occurrences of +a most frequent element*/ + +import java.io.*; +import java.util.*; +class GfG { + static void smallestSubsegment(int a[], int n) + { +/* To store left most occurrence of elements*/ + + HashMap left= new HashMap(); +/* To store counts of elements*/ + + HashMap count= new HashMap(); +/* To store maximum frequency*/ + + int mx = 0; +/* To store length and starting index of + smallest result window*/ + + int mn = -1, strindex = -1; + for (int i = 0; i < n; i++) + { + int x = a[i]; +/* First occurrence of an element, + store the index*/ + + if (count.get(x) == null) + { + left.put(x, i) ; + count.put(x, 1); + } +/* increase the frequency of elements*/ + + else + count.put(x, count.get(x) + 1); +/* Find maximum repeated element and + store its last occurrence and first + occurrence*/ + + if (count.get(x) > mx) + { + mx = count.get(x); +/* length of subsegment*/ + + mn = i - left.get(x) + 1; + strindex = left.get(x); + } +/* select subsegment of smallest size*/ + + else if ((count.get(x) == mx) && + (i - left.get(x) + 1 < mn)) + { + mn = i - left.get(x) + 1; + strindex = left.get(x); + } + } +/* Print the subsegment with all occurrences of + a most frequent element*/ + + for (int i = strindex; i < strindex + mn; i++) + System.out.print(a[i] + "" ""); + } +/* Driver program*/ + + public static void main (String[] args) + { + int A[] = { 1, 2, 2, 2, 1 }; + int n = A.length; + smallestSubsegment(A, n); + } +}"," '''Python3 implementation to find smallest +subarray with all occurrences of +a most frequent element''' + +def smallestSubsegment(a, n): + ''' To store left most occurrence of elements''' + + left = dict() + ''' To store counts of elements''' + + count = dict() + ''' To store maximum frequency''' + + mx = 0 + ''' To store length and starting index of + smallest result window''' + + mn, strindex = 0, 0 + for i in range(n): + x = a[i] + ''' First occurrence of an element, + store the index''' + + if (x not in count.keys()): + left[x] = i + count[x] = 1 + ''' increase the frequency of elements''' + + else: + count[x] += 1 + ''' Find maximum repeated element and + store its last occurrence and first + occurrence''' + + if (count[x] > mx): + mx = count[x] + '''length of subsegment''' + + mn = i - left[x] + 1 + strindex = left[x] + ''' select subsegment of smallest size''' + + elif (count[x] == mx and + i - left[x] + 1 < mn): + mn = i - left[x] + 1 + strindex = left[x] + ''' Print the subsegment with all occurrences of + a most frequent element''' + + for i in range(strindex, strindex + mn): + print(a[i], end = "" "") + '''Driver code''' + +A = [1, 2, 2, 2, 1] +n = len(A) +smallestSubsegment(A, n)" +Top three elements in binary tree,"/*Java program to find largest three elements +in a binary tree.*/ + +import java.util.*; +class GFG +{ +static class Node +{ + int data; + Node left; + Node right; +}; +static int first, second, third; +/* Helper function that allocates +a new Node with the given data and +null left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*function to find three largest element*/ + +static void threelargest(Node root) +{ +if (root == null) + return; +/*if data is greater than first large number +update the top three list*/ + +if (root.data > first) +{ + third = second; + second = first; + first = root.data; +} +/*if data is greater than second large number +and not equal to first update the bottom +two list*/ + +else if (root.data > second && + root.data != first) +{ + third = second; + second = root.data; +} +/*if data is greater than third large number +and not equal to first & second update the +third highest list*/ + +else if (root.data > third && + root.data != first && + root.data != second) + third = root.data; +threelargest(root.left); +threelargest(root.right); +} +/*driver function*/ + +public static void main(String[] args) +{ + 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(4); + root.right.right = newNode(5); + first = 0; second = 0; third = 0; + threelargest(root); + System.out.print(""three largest elements are "" + + first + "" "" + second + "" "" + third); +} +}"," '''Python3 program to find largest three +elements in a binary tree.''' + + '''Helper function that allocates a new +Node with the given data and None +left and right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''function to find three largest element''' + +def threelargest(root, first, second, third): + if (root == None): + return + ''' if data is greater than first large + number update the top three list''' + + if (root.data > first[0]): + third[0] = second[0] + second[0] = first[0] + first[0] = root.data + ''' if data is greater than second large + number and not equal to first update + the bottom two list''' + + elif (root.data > second[0] and + root.data != first[0]): + third[0] = second[0] + second[0] = root.data + ''' if data is greater than third large + number and not equal to first & second + update the third highest list''' + + elif (root.data > third[0] and + root.data != first[0] and + root.data != second[0]): + third[0] = root.data + threelargest(root.left, first, + second, third) + threelargest(root.right, first, + second, third) + '''Driver Code''' + +if __name__ == '__main__': + 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(4) + root.right.right = newNode(5) + first = [0] + second = [0] + third = [0] + threelargest(root, first, second, third) + print(""three largest elements are"", + first[0], second[0], third[0])" +Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction,"/*Java program for the above approach*/ + +import java.io.*; +import java.lang.*; +import java.util.*; + +public class GFG { + +/* Function to print the matrix*/ + + static void print(int mat[][]) + { +/* Iterate over the rows*/ + + for (int i = 0; i < mat.length; i++) { + +/* Iterate over the columns*/ + + for (int j = 0; j < mat[0].length; j++) + +/* Print the value*/ + + System.out.print(mat[i][j] + "" ""); + + System.out.println(); + } + } + +/* Function to perform the swapping of + matrix elements in clockwise manner*/ + + static void performSwap(int mat[][], int i, int j) + { + int N = mat.length; + +/* Stores the last row*/ + + int ei = N - 1 - i; + +/* Stores the last column*/ + + int ej = N - 1 - j; + +/* Perform the swaps*/ + + int temp = mat[i][j]; + mat[i][j] = mat[ej][i]; + mat[ej][i] = mat[ei][ej]; + mat[ei][ej] = mat[j][ei]; + mat[j][ei] = temp; + } + +/* Function to rotate non - diagonal + elements of the matrix K times in + clockwise direction*/ + + static void rotate(int mat[][], int N, int K) + { +/* Update K to K % 4*/ + + K = K % 4; + +/* Iterate until K is positive*/ + + while (K-- > 0) { + +/* Iterate each up to N/2-th row*/ + + for (int i = 0; i < N / 2; i++) { + +/* Iterate each column + from i to N - i - 1*/ + + for (int j = i; j < N - i - 1; j++) { + +/* Check if the element + at i, j is not a + diagonal element*/ + + if (i != j && (i + j) != N - 1) { + +/* Perform the swapping*/ + + performSwap(mat, i, j); + } + } + } + } + +/* Print the matrix*/ + + print(mat); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + + int K = 5; + int mat[][] = { + { 1, 2, 3, 4 }, + { 6, 7, 8, 9 }, + { 11, 12, 13, 14 }, + { 16, 17, 18, 19 }, + }; + + int N = mat.length; + rotate(mat, N, K); + } +} + + +"," '''Python3 program for the above approach''' + + + '''Function to print the matrix''' + +def printMat(mat): + + ''' Iterate over the rows''' + + for i in range(len(mat)): + + ''' Iterate over the columns''' + + for j in range(len(mat[0])): + + ''' Print the value''' + + print(mat[i][j], end = "" "") + + print() + + '''Function to perform the swapping of +matrix elements in clockwise manner''' + +def performSwap(mat, i, j): + + N = len(mat) + + ''' Stores the last row''' + + ei = N - 1 - i + + ''' Stores the last column''' + + ej = N - 1 - j + + ''' Perform the swaps''' + + temp = mat[i][j] + mat[i][j] = mat[ej][i] + mat[ej][i] = mat[ei][ej] + mat[ei][ej] = mat[j][ei] + mat[j][ei] = temp + + '''Function to rotate non - diagonal +elements of the matrix K times in +clockwise direction''' + +def rotate(mat, N, K): + + ''' Update K to K % 4''' + + K = K % 4 + + ''' Iterate until K is positive''' + + while (K > 0): + + ''' Iterate each up to N/2-th row''' + + for i in range(int(N / 2)): + + ''' Iterate each column + from i to N - i - 1''' + + for j in range(i, N - i - 1): + + ''' Check if the element + at i, j is not a + diagonal element''' + + if (i != j and (i + j) != N - 1): + + ''' Perform the swapping''' + + performSwap(mat, i, j) + + K -= 1 + + ''' Print the matrix''' + + printMat(mat) + + '''Driver Code''' + +K = 5 +mat = [ [ 1, 2, 3, 4 ], + [ 6, 7, 8, 9 ], + [ 11, 12, 13, 14 ], + [ 16, 17, 18, 19 ] ] +N = len(mat) + +rotate(mat, N, K) + + +" +Print matrix in antispiral form,"/*Java Code for Print matrix in antispiral form*/ + +import java.util.*; +class GFG { + public static void antiSpiralTraversal(int m, int n, + int a[][]) + { + int i, k = 0, l = 0; + /* k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator */ + + Stack stk=new Stack(); + while (k <= m && l <= n) + { + /* Print the first row from the remaining + rows */ + + for (i = l; i <= n; ++i) + stk.push(a[k][i]); + k++; + /* Print the last column from the remaining + columns */ + + for (i = k; i <= m; ++i) + stk.push(a[i][n]); + n--; + /* Print the last row from the remaining + rows */ + + if ( k <= m) + { + for (i = n; i >= l; --i) + stk.push(a[m][i]); + m--; + } + /* Print the first column from the remaining + columns */ + + if (l <= n) + { + for (i = m; i >= k; --i) + stk.push(a[i][l]); + l++; + } + } + while (!stk.empty()) + { + System.out.print(stk.peek() + "" ""); + stk.pop(); + } + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int mat[][] = + { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 10}, + {11, 12, 13, 14, 15}, + {16, 17, 18, 19, 20} + }; + antiSpiralTraversal(mat.length - 1, mat[0].length - 1, + mat); + } + }"," '''Python 3 program to print +matrix in anti-spiral form''' + +R = 4 +C = 5 +def antiSpiralTraversal(m, n, a): + k = 0 + l = 0 + ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator''' + + stk = [] + while (k <= m and l <= n): + ''' Print the first row + from the remaining rows''' + + for i in range(l, n + 1): + stk.append(a[k][i]) + k += 1 + ''' Print the last column + from the remaining columns''' + + for i in range(k, m + 1): + stk.append(a[i][n]) + n -= 1 + ''' Print the last row + from the remaining rows''' + + if ( k <= m): + for i in range(n, l - 1, -1): + stk.append(a[m][i]) + m -= 1 + ''' Print the first column + from the remaining columns''' + + if (l <= n): + for i in range(m, k - 1, -1): + stk.append(a[i][l]) + l += 1 + while len(stk) != 0: + print(str(stk[-1]), end = "" "") + stk.pop() + '''Driver Code''' + +mat = [[1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20]]; +antiSpiralTraversal(R - 1, C - 1, mat)" +Print the longest leaf to leaf path in a Binary tree,"/*Java program to print the longest leaf to leaf +path*/ + +import java.io.*; +/*Tree node structure used in the program*/ + +class Node +{ + int data; + Node left, right; + Node(int val) + { + data = val; + left = right = null; + } +} +class GFG +{ + static int ans, lh, rh, f; + static Node k; + public static Node Root; +/* Function to find height of a tree*/ + + static int height(Node root) + { + if (root == null) + return 0; + int left_height = height(root.left); + int right_height = height(root.right); +/* update the answer, because diameter of a + tree is nothing but maximum value of + (left_height + right_height + 1) for each node*/ + + if (ans < 1 + left_height + right_height) + { + ans = 1 + left_height + right_height; +/* save the root, this will help us finding the + left and the right part of the diameter*/ + + k = root; +/* save the height of left & right subtree as well.*/ + + lh = left_height; + rh = right_height; + } + return 1 + Math.max(left_height, right_height); + } +/* prints the root to leaf path*/ + + static void printArray(int[] ints, int len) + { + int i; +/* print left part of the path in reverse order*/ + + if(f == 0) + { + for(i = len - 1; i >= 0; i--) + { + System.out.print(ints[i] + "" ""); + } + } + else if(f == 1) + { + for (i = 0; i < len; i++) + { + System.out.print(ints[i] + "" ""); + } + } + } +/* this function finds out all the root to leaf paths*/ + + static void printPathsRecur(Node node, int[] path, + int pathLen, int max) + { + if (node == null) + return; +/* append this node to the path array*/ + + path[pathLen] = node.data; + pathLen++; +/* If it's a leaf, so print the path that led to here*/ + + if (node.left == null && node.right == null) + { +/* print only one path which is equal to the + height of the tree.*/ + + if (pathLen == max && (f == 0 || f == 1)) + { + printArray(path, pathLen); + f = 2; + } + } + else + { +/* otherwise try both subtrees*/ + + printPathsRecur(node.left, path, pathLen, max); + printPathsRecur(node.right, path, pathLen, max); + } + } +/* Computes the diameter of a binary tree with given root.*/ + + static void diameter(Node root) + { + if (root == null) + return; +/* lh will store height of left subtree + rh will store height of right subtree*/ + + ans = Integer.MIN_VALUE; + lh = 0; + rh = 0; +/* f is a flag whose value helps in printing + left & right part of the diameter only once*/ + + f = 0; + int height_of_tree = height(root); + int[] lPath = new int[100]; + int pathlen = 0; +/* print the left part of the diameter*/ + + printPathsRecur(k.left, lPath, pathlen, lh); + System.out.print(k.data+"" ""); + int[] rPath = new int[100]; + f = 1; +/* print the right part of the diameter*/ + + printPathsRecur(k.right, rPath, pathlen, rh); + } +/* Driver code*/ + + public static void main (String[] args) + { +/* Enter the binary tree ... + 1 + / \ + 2 3 + / \ + 4 5 + \ / \ + 8 6 7 + / + 9*/ + + GFG.Root = new Node(1); + GFG.Root.left = new Node(2); + GFG.Root.right = new Node(3); + GFG.Root.left.left = new Node(4); + GFG.Root.left.right = new Node(5); + GFG.Root.left.right.left = new Node(6); + GFG.Root.left.right.right = new Node(7); + GFG.Root.left.left.right = new Node(8); + GFG.Root.left.left.right.left = new Node(9); + diameter(Root); + } +}"," '''Python3 program to print the longest +leaf to leaf path''' + + '''Tree node structure used in the program''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None '''Function to find height of a tree''' + +def height(root): + global ans, k, lh, rh, f + if (root == None): + return 0 + left_height = height(root.left) + right_height = height(root.right) + ''' Update the answer, because diameter of a + tree is nothing but maximum value of + (left_height + right_height + 1) for each node''' + + if (ans < 1 + left_height + right_height): + ans = 1 + left_height + right_height + ''' Save the root, this will help us finding the + left and the right part of the diameter''' + + k = root + ''' Save the height of left & right + subtree as well.''' + + lh = left_height + rh = right_height + return 1 + max(left_height, right_height) + '''Prints the root to leaf path''' + +def printArray(ints, lenn, f): + ''' Print left part of the path + in reverse order''' + + if (f == 0): + for i in range(lenn - 1, -1, -1): + print(ints[i], end = "" "") + elif (f == 1): + for i in range(lenn): + print(ints[i], end = "" "") + '''This function finds out all the +root to leaf paths''' + +def printPathsRecur(node, path, maxm, pathlen): + global f + if (node == None): + return + ''' Append this node to the path array''' + + path[pathlen] = node.data + pathlen += 1 + ''' If it's a leaf, so print the + path that led to here''' + + if (node.left == None and node.right == None): + ''' Print only one path which is equal to the + height of the tree. + print(pathlen,""---"",maxm)''' + + if (pathlen == maxm and (f == 0 or f == 1)): + printArray(path, pathlen,f) + f = 2 + else: ''' Otherwise try both subtrees''' + + printPathsRecur(node.left, path, maxm, pathlen) + printPathsRecur(node.right, path, maxm, pathlen) + '''Computes the diameter of a binary +tree with given root.''' + +def diameter(root): + if (root == None): + return + ''' lh will store height of left subtree + rh will store height of right subtree''' + + global ans, lh, rh ''' f is a flag whose value helps in printing + left & right part of the diameter only once''' + global f, k, pathLen + height_of_tree = height(root) + lPath = [0 for i in range(100)] + '''Print the left part of the diameter''' + + printPathsRecur(k.left, lPath, lh, 0); + print(k.data, end = "" "") + rPath = [0 for i in range(100)] + f = 1 + ''' Print the right part of the diameter''' + + printPathsRecur(k.right, rPath, rh, 0) + '''Driver code''' + +if __name__ == '__main__': + k, lh, rh, f, ans, pathLen = None, 0, 0, 0, 0 - 10 ** 19, 0 + ''' Enter the binary tree ... + 1 + / \ + 2 3 + / \ + 4 5 + \ / \ + 8 6 7 + / + 9''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.left.right.left = Node(6) + root.left.right.right = Node(7) + root.left.left.right = Node(8) + root.left.left.right.left = Node(9) + diameter(root)" +Binary representation of a given number,"public class GFG +{ + +/*bin function*/ + + static void bin(long n) + { + long i; + System.out.print(""0""); + for (i = 1 << 30; i > 0; i = i / 2) + { + if((n & i) != 0) + { + System.out.print(""1""); + } + else + { + System.out.print(""0""); + } + } + }/* Driver code*/ + + public static void main(String[] args) + { + bin(7); + System.out.println(); + bin(4); + } +}"," '''bin function''' + +def bin(n) : + i = 1 << 31 + while(i > 0) : + if((n & i) != 0) : + print(""1"", end = """") + else : + print(""0"", end = """") + i = i // 2 + '''Driver Code''' + +bin(7) +print() +bin(4)" +Query to find the maximum and minimum weight between two nodes in the given tree using LCA.,"/*Java Program to find the maximum and +minimum weight between two nodes +in the given tree using LCA*/ + +import java.util.*; +class GFG{ + +static final int MAX = 1000; + +/*Math.log(MAX)*/ + +static final int log = 10 ; + +/*Array to store the +level of each node*/ + +static int []level = + new int[MAX]; + +static int [][]lca = + new int[MAX][log]; +static int [][]minWeight = + new int[MAX][log]; +static int [][]maxWeight = + new int[MAX][log]; + +/*Vector to store tree*/ + +static Vector []graph = + new Vector[MAX]; + +/*Array to store +weight of nodes*/ + +static int []weight = + new int[MAX]; + +private static void swap(int x, + int y) +{ + int temp = x; + x = y; + y = temp; +} + +static void addEdge(int u, + int v) +{ + graph[u].add(v); + graph[v].add(u); +} + +/*Pre-Processing to +calculate values of +lca[][], MinWeight[][] +and MaxWeight[][]*/ + +static void dfs(int node, + int parent, int h) +{ +/* Using recursion formula to + calculate the values + of lca[][]*/ + + lca[node][0] = parent; + +/* Storing the level of + each node*/ + + level[node] = h; + + if (parent != -1) + { + minWeight[node][0] = Math.min(weight[node], + weight[parent]); + maxWeight[node][0] = Math.max(weight[node], + weight[parent]); + } + + for (int i = 1; i < log; i++) + { + if (lca[node][i - 1] != -1) + { +/* Using recursion formula to + calculate the values of lca[][], + MinWeight[][] and MaxWeight[][]*/ + + lca[node][i] = + lca[lca[node][i - 1]][i - 1]; + + minWeight[node][i] = + Math.min(minWeight[node][i - 1], + minWeight[lca[node][i - 1]][i - 1]); + maxWeight[node][i] = + Math.max(maxWeight[node][i - 1], + maxWeight[lca[node][i - 1]][i - 1]); + } + } + + for (int i : graph[node]) + { + if (i == parent) + continue; + dfs(i, node, h + 1); + } +} + +/*Function to find the minimum and +maximum weights in the given range*/ + +static void findMinMaxWeight(int u, + int v) +{ + int minWei = Integer.MAX_VALUE; + int maxWei = Integer.MIN_VALUE; + +/* The node which is present + farthest from the root node + is taken as v If u is + farther from root node + then swap the two*/ + + if (level[u] > level[v]) + swap(u, v); + +/* Finding the ancestor of v + which is at same level as u*/ + + for (int i = log - 1; i >= 0; i--) + { + if (lca[v][i] != -1 && + level[lca[v][i]] >= level[u]) + { +/* Calculating Minimum and + Maximum Weight of node + v till its 2^i-th ancestor*/ + + minWei = Math.min(minWei, + minWeight[v][i]); + maxWei = Math.max(maxWei, + maxWeight[v][i]); + v = lca[v][i]; + } + } + +/* If u is the ancestor of v + then u is the LCA of u and v*/ + + if (v == u) + { + System.out.print(minWei + "" "" + + maxWei + ""\n""); + } + else + { +/* Finding the node closest to the + root which is not the common + ancestor of u and v i.e. a node + x such that x is not the common + ancestor of u and v but lca[x][0] is*/ + + for (int i = log - 1; i >= 0; i--) + { + if(v == -1) + v++; + if (lca[v][i] != lca[u][i]) + { +/* Calculating the minimum of + MinWeight of v to its 2^i-th + ancestor and MinWeight of u + to its 2^i-th ancestor*/ + + minWei = Math.min(minWei, + Math.min(minWeight[v][i], + minWeight[u][i])); + +/* Calculating the maximum of + MaxWeight of v to its 2^i-th + ancestor and MaxWeight of u + to its 2^i-th ancestor*/ + + maxWei = Math.max(maxWei, + Math.max(maxWeight[v][i], + maxWeight[u][i])); + + v = lca[v][i]; + u = lca[u][i]; + } + } + +/* Calculating the Minimum of + first ancestor of u and v*/ + + if(u == -1) + u++; + minWei = Math.min(minWei, + Math.min(minWeight[v][0], + minWeight[u][0])); + +/* Calculating the maximum of + first ancestor of u and v*/ + + maxWei = Math.max(maxWei, + Math.max(maxWeight[v][0], + maxWeight[u][0])); + + System.out.print(minWei + "" "" + + maxWei + ""\n""); + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Number of nodes*/ + + int n = 5; + + for (int i = 0; i < graph.length; i++) + graph[i] = new Vector(); + +/* Add edges*/ + + addEdge(1, 2); + addEdge(1, 5); + addEdge(2, 4); + addEdge(2, 3); + + weight[1] = -1; + weight[2] = 5; + weight[3] = -1; + weight[4] = 3; + weight[5] = -2; + +/* Initialising lca values with -1 + Initialising MinWeight values + with Integer.MAX_VALUE + Initialising MaxWeight values + with Integer.MIN_VALUE*/ + + for (int i = 1; i <= n; i++) + { + for (int j = 0; j < log; j++) + { + lca[i][j] = -1; + minWeight[i][j] = Integer.MAX_VALUE; + maxWeight[i][j] = Integer.MIN_VALUE; + } + } + +/* Perform DFS*/ + + dfs(1, -1, 0); + +/* Query 1: {1, 3}*/ + + findMinMaxWeight(1, 3); + +/* Query 2: {2, 4}*/ + + findMinMaxWeight(2, 4); + +/* Query 3: {3, 5}*/ + + findMinMaxWeight(3, 5); +} +} + + +"," '''Python3 Program to find the +maximum and minimum weight +between two nodes in the +given tree using LCA''' + +import sys +MAX = 1000 + + '''log2(MAX)''' + +log = 10 + + '''Array to store the level +of each node''' + +level = [0 for i in range(MAX)]; +lca = [[-1 for j in range(log)] + for i in range(MAX)] +minWeight = [[sys.maxsize for j in range(log)] + for i in range(MAX)] +maxWeight = [[-sys.maxsize for j in range(log)] + for i in range(MAX)] + + '''Vector to store tree''' + +graph = [[] for i in range(MAX)] + + '''Array to store weight of nodes''' + +weight = [0 for i in range(MAX)] + +def addEdge(u, v): + + graph[u].append(v); + graph[v].append(u); + + '''Pre-Processing to calculate +values of lca[][], MinWeight[][] +and MaxWeight[][]''' + +def dfs(node, parent, h): + + ''' Using recursion formula to + calculate the values + of lca[][]''' + + lca[node][0] = parent; + + ''' Storing the level of + each node''' + + level[node] = h; + + if (parent != -1): + minWeight[node][0] = (min(weight[node], + weight[parent])); + maxWeight[node][0] = (max(weight[node], + weight[parent])); + + for i in range(1, log): + if (lca[node][i - 1] != -1): + + ''' Using recursion formula to + calculate the values of lca[][], + MinWeight[][] and MaxWeight[][]''' + + lca[node][i] = lca[lca[node][i - 1]][i - 1]; + minWeight[node][i] = min(minWeight[node][i - 1], + minWeight[lca[node][i - 1]][i - 1]); + maxWeight[node][i] = max(maxWeight[node][i - 1], + maxWeight[lca[node][i - 1]][i - 1]); + + for i in graph[node]: + if (i == parent): + continue; + dfs(i, node, h + 1); + + '''Function to find the minimum +and maximum weights in the +given range''' + +def findMinMaxWeight(u, v): + + minWei = sys.maxsize + maxWei = -sys.maxsize + + ''' The node which is present + farthest from the root node + is taken as v If u is + farther from root node + then swap the two''' + + if (level[u] > level[v]): + u, v = v, u + + ''' Finding the ancestor of v + which is at same level as u''' + + for i in range(log - 1, -1, -1): + + if (lca[v][i] != -1 and + level[lca[v][i]] >= + level[u]): + + ''' Calculating Minimum and + Maximum Weight of node + v till its 2^i-th ancestor''' + + minWei = min(minWei, + minWeight[v][i]); + maxWei = max(maxWei, + maxWeight[v][i]); + v = lca[v][i]; + + ''' If u is the ancestor of v + then u is the LCA of u and v''' + + if (v == u): + print(str(minWei) + ' ' + + str(maxWei)) + + else: + + ''' Finding the node closest to the + root which is not the common + ancestor of u and v i.e. a node + x such that x is not the common + ancestor of u and v but lca[x][0] is''' + + for i in range(log - 1, -1, -1): + + if (lca[v][i] != lca[u][i]): + + ''' Calculating the minimum of + MinWeight of v to its 2^i-th + ancestor and MinWeight of u + to its 2^i-th ancestor''' + + minWei = (min(minWei, + min(minWeight[v][i], + minWeight[u][i]))); + + ''' Calculating the maximum of + MaxWeight of v to its 2^i-th + ancestor and MaxWeight of u + to its 2^i-th ancestor''' + + maxWei = max(maxWei, + max(maxWeight[v][i], + maxWeight[u][i])); + + v = lca[v][i]; + u = lca[u][i]; + + ''' Calculating the Minimum of + first ancestor of u and v''' + + minWei = min(minWei, + min(minWeight[v][0], + minWeight[u][0])); + + ''' Calculating the maximum of + first ancestor of u and v''' + + maxWei = max(maxWei, + max(maxWeight[v][0], + maxWeight[u][0])); + + print(str(minWei) + ' ' + + str(maxWei)) + + '''Driver code''' + +if __name__ == ""__main__"": + + ''' Number of nodes''' + + n = 5; + + ''' Add edges''' + + addEdge(1, 2); + addEdge(1, 5); + addEdge(2, 4); + addEdge(2, 3); + + weight[1] = -1; + weight[2] = 5; + weight[3] = -1; + weight[4] = 3; + weight[5] = -2; + + + ''' Perform DFS''' + + dfs(1, -1, 0); + + ''' Query 1: {1, 3}''' + + findMinMaxWeight(1, 3); + + ''' Query 2: {2, 4}''' + + findMinMaxWeight(2, 4); + + ''' Query 3: {3, 5}''' + + findMinMaxWeight(3, 5); + + +" +Radix Sort,"/*Radix sort Java implementation*/ + +import java.io.*; +import java.util.*; +class Radix { +/* A utility function to get maximum value in arr[]*/ + + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } +/* A function to do counting sort of arr[] according to + the digit represented by exp.*/ + + static void countSort(int arr[], int n, int exp) + { +/*output array*/ + +int output[] = new int[n]; + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); +/* Store count of occurrences in count[]*/ + + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; +/* Change count[i] so that count[i] now contains + actual position of this digit in output[]*/ + + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; +/* Build the output array*/ + + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } +/* Copy the output array to arr[], so that arr[] now + contains sorted numbers according to current digit*/ + + for (i = 0; i < n; i++) + arr[i] = output[i]; + } +/* The main function to that sorts arr[] of size n using + Radix Sort*/ + + static void radixsort(int arr[], int n) + { +/* Find the maximum number to know number of digits*/ + + int m = getMax(arr, n); +/* Do counting sort for every digit. Note that + instead of passing digit number, exp is passed. + exp is 10^i where i is current digit number*/ + + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } +/* A utility function to print an array*/ + + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } + /*Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; +/* Function Call*/ + + radixsort(arr, n); + print(arr, n); + } +}"," '''Python program for implementation of Radix Sort''' + '''A function to do counting sort of arr[] according to +the digit represented by exp.''' + +def countingSort(arr, exp1): + n = len(arr) + ''' The output array elements that will have sorted arr''' + + output = [0] * (n) + ''' initialize count array as 0''' + + count = [0] * (10) + ''' Store count of occurrences in count[]''' + + for i in range(0, n): + index = (arr[i] / exp1) + count[int(index % 10)] += 1 + ''' Change count[i] so that count[i] now contains actual + position of this digit in output array''' + + for i in range(1, 10): + count[i] += count[i - 1] + ''' Build the output array''' + + i = n - 1 + while i >= 0: + index = (arr[i] / exp1) + output[count[int(index % 10)] - 1] = arr[i] + count[int(index % 10)] -= 1 + i -= 1 + ''' Copying the output array to arr[], + so that arr now contains sorted numbers''' + + i = 0 + for i in range(0, len(arr)): + arr[i] = output[i] + '''Method to do Radix Sort''' + +def radixSort(arr): + ''' Find the maximum number to know number of digits''' + + max1 = max(arr) + ''' Do counting sort for every digit. Note that instead + of passing digit number, exp is passed. exp is 10^i + where i is current digit number''' + + exp = 1 + while max1 / exp > 0: + countingSort(arr, exp) + exp *= 10 + '''Driver code''' + +arr = [170, 45, 75, 90, 802, 24, 2, 66] + '''Function Call''' + +radixSort(arr) +for i in range(len(arr)): + print(arr[i])" +Boundary elements of a Matrix,"/*JAVA Code for Finding sum of boundary elements*/ + +class GFG { + public static long getBoundarySum(int a[][], int m, + int n) + { + long sum = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i == 0) + sum += a[i][j]; + else if (i == m - 1) + sum += a[i][j]; + else if (j == 0) + sum += a[i][j]; + else if (j == n - 1) + sum += a[i][j]; + } + } + return sum; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; + long sum = getBoundarySum(a, 4, 4); + System.out.println(""Sum of boundary elements"" + + "" is "" + sum); + } +}"," '''Python program to print boundary element +of the matrix.''' + +MAX = 100 +def printBoundary(a, m, n): + sum = 0 + for i in range(m): + for j in range(n): + if (i == 0): + sum += a[i][j] + elif (i == m-1): + sum += a[i][j] + elif (j == 0): + sum += a[i][j] + elif (j == n-1): + sum += a[i][j] + return sum + '''Driver code''' + +a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] +sum = printBoundary(a, 4, 4) +print ""Sum of boundary elements is"", sum" +Count total set bits in all numbers from 1 to n,"public class GFG { + static int countSetBits(int n) + { + int i = 0;/* ans store sum of set bits from 0 to n*/ + + int ans = 0; +/* while n greater than equal to 2^i*/ + + while ((1 << i) <= n) { +/* This k will get flipped after + 2^i iterations*/ + + boolean k = false; +/* change is iterator from 2^i to 1*/ + + int change = 1 << i; +/* This will loop from 0 to n for + every bit position*/ + + for (int j = 0; j <= n; j++) { + if (k == true) + ans += 1; + else + ans += 0; + if (change == 1) { +/* When change = 1 flip the bit*/ + + k = !k; +/* again set change to 2^i*/ + + change = 1 << i; + } + else { + change--; + } + } +/* increment the position*/ + + i++; + } + return ans; + } +/* Driver program*/ + + public static void main(String[] args) + { + int n = 17; + System.out.println(countSetBits(n)); + } +}"," '''Function which counts set bits from 0 to n''' + +def countSetBits(n) : + i = 0 + ''' ans store sum of set bits from 0 to n ''' + + ans = 0 + ''' while n greater than equal to 2^i''' + + while ((1 << i) <= n) : + ''' This k will get flipped after + 2^i iterations''' + + k = 0 + ''' change is iterator from 2^i to 1''' + + change = 1 << i + ''' This will loop from 0 to n for + every bit position''' + + for j in range(0, n+1) : + ans += k + if change == 1 : + ''' When change = 1 flip the bit''' + + k = not k + ''' again set change to 2^i''' + + change = 1 << i + else : + change -= 1 + ''' increment the position''' + + i += 1 + return ans + '''Driver code''' + +if __name__ == ""__main__"" : + n = 17 + print(countSetBits(n))" +Shortest path with exactly k edges in a directed and weighted graph,"/*Dynamic Programming based Java program to find shortest path +with exactly k edges*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class ShortestPath +{ +/* Define number of vertices in the graph and inifinite value*/ + + static final int V = 4; + static final int INF = Integer.MAX_VALUE; +/* A naive recursive function to count walks from u to v + with k edges*/ + + int shortestPath(int graph[][], int u, int v, int k) + { +/* Base cases*/ + + if (k == 0 && u == v) return 0; + if (k == 1 && graph[u][v] != INF) return graph[u][v]; + if (k <= 0) return INF; +/* Initialize result*/ + + int res = INF; +/* Go to all adjacents of u and recur*/ + + for (int i = 0; i < V; i++) + { + if (graph[u][i] != INF && u != i && v != i) + { + int rec_res = shortestPath(graph, i, v, k-1); + if (rec_res != INF) + res = Math.min(res, graph[u][i] + rec_res); + } + } + return res; + } + + /*driver program to test above function*/ + + public static void main (String[] args) + {/* Let us create the graph shown in above diagram*/ + + int graph[][] = new int[][]{ {0, 10, 3, 2}, + {INF, 0, INF, 7}, + {INF, INF, 0, 6}, + {INF, INF, INF, 0} + }; + ShortestPath t = new ShortestPath(); + int u = 0, v = 3, k = 2; + System.out.println(""Weight of the shortest path is ""+ + t.shortestPath(graph, u, v, k)); + } +}"," '''Python3 program to find shortest path +with exactly k edges ''' + + + + '''Define number of vertices in the graph +and inifinite value''' +V = 4 +INF = 999999999999 '''A naive recursive function to count +walks from u to v with k edges ''' + +def shortestPath(graph, u, v, k): ''' Base cases ''' + + if k == 0 and u == v: + return 0 + if k == 1 and graph[u][v] != INF: + return graph[u][v] + if k <= 0: + return INF + '''Initialize result ''' + + res = INF + '''Go to all adjacents of u and recur''' + + for i in range(V): + if graph[u][i] != INF and u != i and v != i: + rec_res = shortestPath(graph, i, v, k - 1) + if rec_res != INF: + res = min(res, graph[u][i] + rec_res) + return res + '''Driver Code''' + +if __name__ == '__main__': + INF = 999999999999 + ''' Let us create the graph shown + in above diagram''' + + graph = [[0, 10, 3, 2], + [INF, 0, INF, 7], + [INF, INF, 0, 6], + [INF, INF, INF, 0]] + u = 0 + v = 3 + k = 2 + print(""Weight of the shortest path is"", + shortestPath(graph, u, v, k))" +Iterative Preorder Traversal,"import java.util.Stack; +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree{ +Node root; +void preorderIterative() +{ + preorderIterative(root); +} +/*Iterative function to do Preorder +traversal of the tree*/ + +void preorderIterative(Node node) +{ + if (node == null) + { + return; + } + Stack st = new Stack(); +/* Start from root node (set curr + node to root node)*/ + + Node curr = node; +/* Run till stack is not empty or + current is not NULL*/ + + while (curr != null || !st.isEmpty()) + { +/* Print left children while exist + and keep pushing right into the + stack.*/ + + while (curr != null) + { + System.out.print(curr.data + "" ""); + if (curr.right != null) + st.push(curr.right); + curr = curr.left; + } +/* We reach when curr is NULL, so We + take out a right child from stack*/ + + if (!st.isEmpty()) + { + curr = st.pop(); + } + } +} +/*Driver code*/ + +public static void main(String args[]) +{ + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(20); + tree.root.right = new Node(30); + tree.root.left.left = new Node(40); + tree.root.left.left.left = new Node(70); + tree.root.left.right = new Node(50); + tree.root.right.left = new Node(60); + tree.root.left.left.right = new Node(80); + tree.preorderIterative(); +} +}"," '''Tree Node''' + +class Node: + def __init__(self, data = 0): + self.data = data + self.left = None + self.right = None + '''Iterative function to do Preorder traversal of the tree''' + +def preorderIterative(root): + if (root == None): + return + st = [] + ''' start from root node (set current node to root node)''' + + curr = root + ''' run till stack is not empty or current is + not NULL''' + + while (len(st) or curr != None): + ''' Print left children while exist + and keep appending right into the + stack.''' + + while (curr != None): + print(curr.data, end = "" "") + if (curr.right != None): + st.append(curr.right) + curr = curr.left + ''' We reach when curr is NULL, so We + take out a right child from stack''' + + if (len(st) > 0): + curr = st[-1] + st.pop() + '''Driver Code''' + +root = Node(10) +root.left = Node(20) +root.right = Node(30) +root.left.left = Node(40) +root.left.left.left = Node(70) +root.left.right = Node(50) +root.right.left = Node(60) +root.left.left.right = Node(80) +preorderIterative(root)" +Total number of non-decreasing numbers with n digits,"class NDN +{ + static int countNonDecreasing(int n) + { +/* dp[i][j] contains total count of non decreasing + numbers ending with digit i and of length j*/ + + int dp[][] = new int[10][n+1]; +/* Fill table for non decreasing numbers of length 1 + Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9*/ + + for (int i = 0; i < 10; i++) + dp[i][1] = 1; +/* Fill the table in bottom-up manner*/ + + for (int digit = 0; digit <= 9; digit++) + { +/* Compute total numbers of non decreasing + numbers of length 'len'*/ + + for (int len = 2; len <= n; len++) + { +/* sum of all numbers of length of len-1 + in which last digit x is <= 'digit'*/ + + for (int x = 0; x <= digit; x++) + dp[digit][len] += dp[x][len-1]; + } + } + int count = 0; +/* There total nondecreasing numbers of length n + wiint be dp[0][n] + dp[1][n] ..+ dp[9][n]*/ + + for (int i = 0; i < 10; i++) + count += dp[i][n]; + return count; + } +/*Driver program*/ + + public static void main(String args[]) + { + int n = 3; + System.out.println(countNonDecreasing(n)); + } +}"," '''Python3 program to count +non-decreasing number with n digits''' + +def countNonDecreasing(n): + ''' dp[i][j] contains total count + of non decreasing numbers ending + with digit i and of length j''' + + dp = [[0 for i in range(n + 1)] + for i in range(10)] + ''' Fill table for non decreasing + numbers of length 1. + Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9''' + + for i in range(10): + dp[i][1] = 1 + ''' Fill the table in bottom-up manner''' + + for digit in range(10): + ''' Compute total numbers of non + decreasing numbers of length 'len''' + ''' + for len in range(2, n + 1): + ''' sum of all numbers of length + of len-1 in which last + digit x is <= 'digit''' + ''' + for x in range(digit + 1): + dp[digit][len] += dp[x][len - 1] + count = 0 + ''' There total nondecreasing numbers + of length n won't be dp[0][n] + + dp[1][n] ..+ dp[9][n]''' + + for i in range(10): + count += dp[i][n] + return count + '''Driver Code''' + +n = 3 +print(countNonDecreasing(n))" +Maximizing Unique Pairs from two arrays,"/*Java implementation of above approach*/ + +import java.util.*; + +class solution +{ + +/*Returns count of maximum pairs that caan +be formed from a[] and b[] under given +constraints.*/ + +static int findMaxPairs(int a[], int b[], int n, int k) +{ +/*Sorting the first array.*/ + +Arrays.sort(a); +/*Sorting the second array.*/ + +Arrays.sort(b); + +/* To keep track of visited elements of b[]*/ + + boolean []flag = new boolean[n]; + Arrays.fill(flag,false); + +/* For every element of a[], find a pair + for it and break as soon as a pair is + found.*/ + + int result = 0; + for (int i=0; i inEnd) + return null; + /* Pick current node from Preorder traversal using preIndex + and increment preIndex */ + + Node tNode = new Node(pre[preIndex++]); + /* If this node has no children then return */ + + if (inStrt == inEnd) + return tNode; + /* Else find the index of this node in Inorder traversal */ + + int inIndex = search(in, inStrt, inEnd, tNode.data); + /* Using index in Inorder traversal, construct left and + right subtress */ + + tNode.left = buildTree(in, pre, inStrt, inIndex - 1); + tNode.right = buildTree(in, pre, inIndex + 1, inEnd); + return tNode; + } + /* UTILITY FUNCTIONS */ + + /* Function to find index of value in arr[start...end] + The function assumes that value is present in in[] */ + + int search(char arr[], int strt, int end, char value) + { + int i; + for (i = strt; i <= end; i++) { + if (arr[i] == value) + return i; + } + return i; + } + /* This funtcion is here just to test buildTree() */ + + void printInorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.data + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } +/* driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + char in[] = new char[] { 'D', 'B', 'E', 'A', 'F', 'C' }; + char pre[] = new char[] { 'A', 'B', 'D', 'E', 'C', 'F' }; + int len = in.length; + Node root = tree.buildTree(in, pre, 0, len - 1); +/* building the tree by printing inorder traversal*/ + + System.out.println(""Inorder traversal of constructed tree is : ""); + tree.printInorder(root); + } +}"," '''Python program to construct tree using inorder and +preorder traversals''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Recursive function to construct binary of size len from + Inorder traversal in[] and Preorder traversal pre[]. Initial values + of inStrt and inEnd should be 0 and len -1. The function doesn't + do any error checking for cases where inorder and preorder + do not form a tree ''' + +def buildTree(inOrder, preOrder, inStrt, inEnd): + if (inStrt > inEnd): + return None + ''' Pich current node from Preorder traversal using + preIndex and increment preIndex''' + + tNode = Node(preOrder[buildTree.preIndex]) + buildTree.preIndex += 1 + ''' If this node has no children then return''' + + if inStrt == inEnd : + return tNode + ''' Else find the index of this node in Inorder traversal''' + + inIndex = search(inOrder, inStrt, inEnd, tNode.data) + ''' Using index in Inorder Traversal, construct left + and right subtrees''' + + tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex-1) + tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd) + return tNode + '''UTILITY FUNCTIONS''' + + '''Function to find index of value in arr[start...end] +The function assumes that value is rpesent in inOrder[]''' + +def search(arr, start, end, value): + for i in range(start, end + 1): + if arr[i] == value: + return i + ''' This funtcion is here just to test buildTree() ''' + +def printInorder(node): + if node is None: + return + ''' first recur on left child''' + + printInorder(node.left) ''' then print the data of node''' + + print node.data, + ''' now recur on right child''' + + printInorder(node.right) + '''Driver program to test above function''' + +inOrder = ['D', 'B', 'E', 'A', 'F', 'C'] +preOrder = ['A', 'B', 'D', 'E', 'C', 'F'] +buildTree.preIndex = 0 +root = buildTree(inOrder, preOrder, 0, len(inOrder)-1) + '''Let us test the build tree by priting Inorder traversal''' + +print ""Inorder traversal of the constructed tree is"" +printInorder(root)" +Generating numbers that are divisor of their right-rotations,"/*Java program to Generating numbers that +are divisor of their right-rotations */ + + +public class GFG { + +/* Function to check if N is a + divisor of its right-rotation*/ + + static boolean rightRotationDivisor(int N) + { + int lastDigit = N % 10; + int rightRotation = (int)(lastDigit * Math.pow(10 ,(int)(Math.log10(N))) + + Math.floor(N / 10)); + return (rightRotation % N == 0); + } + +/* Function to generate m-digit + numbers which are divisor of + their right-rotation */ + + static void generateNumbers(int m) + { + for (int i= (int)Math.pow(10,(m - 1)); i < Math.pow(10 , m);i++) + if (rightRotationDivisor(i)) + System.out.println(i); + } + + +/* Driver code*/ + + public static void main(String args[]) + { + int m = 3; + generateNumbers(m); + + } + +} + +"," '''Python program to Generating numbers that are +divisor of their right-rotations''' + + +from math import log10 + + '''Function to check if N is a +divisor of its right-rotation''' + +def rightRotationDivisor(N): + lastDigit = N % 10 + rightRotation = (lastDigit * 10 ** int(log10(N)) + + N // 10) + return rightRotation % N == 0 + + '''Function to generate m-digit +numbers which are divisor of +their right-rotation''' + +def generateNumbers(m): + for i in range(10 ** (m - 1), 10 ** m): + if rightRotationDivisor(i): + print(i) + + '''Driver code''' + +m = 3 +generateNumbers(m) +" +Minimum number of squares whose sum equals to given number n,"/*A naive recursive JAVA +program to find minimum +number of squares whose +sum is equal to a given number*/ + +class squares +{ +/* Returns count of minimum + squares that sum to n*/ + + static int getMinSquares(int n) + { +/* base cases*/ + + if (n <= 3) + return n; +/* getMinSquares rest of the + table using recursive + formula + Maximum squares required is*/ + + int res = n; +/* n (1*1 + 1*1 + ..) + Go through all smaller numbers + to recursively find minimum*/ + + for (int x = 1; x <= n; x++) + { + int temp = x * x; + if (temp > n) + break; + else + res = Math.min(res, 1 + + getMinSquares(n - temp)); + } + return res; + } +/* Driver code*/ + + public static void main(String args[]) + { + System.out.println(getMinSquares(6)); + } +}"," '''A naive recursive Python program to +find minimum number of squares whose +sum is equal to a given number + ''' '''Returns count of minimum squares +that sum to n''' + +def getMinSquares(n): + ''' base cases''' + + if n <= 3: + return n; + ''' getMinSquares rest of the table + using recursive formula + Maximum squares required + is n (1 * 1 + 1 * 1 + ..)''' + + res = n + ''' Go through all smaller numbers + to recursively find minimum''' + + for x in range(1, n + 1): + temp = x * x; + if temp > n: + break + else: + res = min(res, 1 + getMinSquares(n + - temp)) + return res; + '''Driver code''' + +print(getMinSquares(6))" +Heap Sort for decreasing order using min heap,"/*Java program for implementation of Heap Sort*/ + +import java.io.*; +class GFG { +/* To heapify a subtree rooted with node i which is + an index in arr[]. n is size of heap*/ + + static void heapify(int arr[], int n, int i) + { +/*Initialize smalles as root*/ + +int smallest = i; +/*left = 2*i + 1*/ + +int l = 2 * i + 1; +/*right = 2*i + 2*/ + +int r = 2 * i + 2; +/* If left child is smaller than root*/ + + if (l < n && arr[l] < arr[smallest]) + smallest = l; +/* If right child is smaller than smallest so far*/ + + if (r < n && arr[r] < arr[smallest]) + smallest = r; +/* If smallest is not root*/ + + if (smallest != i) { + int temp = arr[i]; + arr[i] = arr[smallest]; + arr[smallest] = temp; +/* Recursively heapify the affected sub-tree*/ + + heapify(arr, n, smallest); + } + } +/* main function to do heap sort*/ + + static void heapSort(int arr[], int n) + { +/* Build heap (rearrange array)*/ + + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); +/* One by one extract an element from heap*/ + + for (int i = n - 1; i >= 0; i--) { +/* Move current root to end*/ + + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; +/* call max heapify on the reduced heap*/ + + heapify(arr, i, 0); + } + } + /* A utility function to print array of size n */ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = { 4, 6, 3, 2, 9 }; + int n = arr.length; + heapSort(arr, n); + System.out.println(""Sorted array is ""); + printArray(arr, n); + } +}"," '''Python3 program for implementation +of Heap Sort + ''' '''To heapify a subtree rooted with +node i which is an index in arr[]. +n is size of heap''' + +def heapify(arr, n, i): + '''Initialize smalles as root''' + + smallest = i + + '''left = 2*i + 1''' + + l = 2 * i + 1 + + '''right = 2*i + 2''' + + r = 2 * i + 2 + ''' If left child is smaller than root''' + + if l < n and arr[l] < arr[smallest]: + smallest = l + ''' If right child is smaller than + smallest so far''' + + if r < n and arr[r] < arr[smallest]: + smallest = r + ''' If smallest is not root''' + + if smallest != i: + (arr[i], + arr[smallest]) = (arr[smallest], + arr[i]) + ''' Recursively heapify the affected + sub-tree''' + + heapify(arr, n, smallest) + '''main function to do heap sort''' + +def heapSort(arr, n): + ''' Build heap (rearrange array)''' + + for i in range(int(n / 2) - 1, -1, -1): + heapify(arr, n, i) + ''' One by one extract an element + from heap''' + + for i in range(n-1, -1, -1): + ''' +Move current root to end ''' + + arr[0], arr[i] = arr[i], arr[0] + ''' call max heapify on the reduced heap''' + + heapify(arr, i, 0) + '''A utility function to print +array of size n''' + +def printArray(arr, n): + for i in range(n): + print(arr[i], end = "" "") + print() + '''Driver Code''' + +if __name__ == '__main__': + arr = [4, 6, 3, 2, 9] + n = len(arr) + heapSort(arr, n) + print(""Sorted array is "") + printArray(arr, n)" +Find sum of all nodes of the given perfect binary tree,"/*Java code to find sum of all nodes +of the given perfect binary tree*/ + +import java.io.*; +import java.lang.Math; +class GFG { +/* function to find sum of + all of the nodes of given + perfect binary tree*/ + + static double sumNodes(int l) + { +/* no of leaf nodes*/ + + double leafNodeCount = Math.pow(2, l - 1); + double sumLastLevel = 0; +/* sum of nodes at last level*/ + + sumLastLevel = (leafNodeCount * + (leafNodeCount + 1)) / 2; +/* sum of all nodes*/ + + double sum = sumLastLevel * l; + return sum; + } +/* Driver Code*/ + + public static void main (String[] args) { + int l = 3; + System.out.println(sumNodes(l)); + } +}"," '''function to find sum of all of the nodes +of given perfect binary tree''' + +import math + + '''function to find sum of + all of the nodes of given + perfect binary tree''' + +def sumNodes(l): ''' no of leaf nodes''' + + leafNodeCount = math.pow(2, l - 1); + sumLastLevel = 0; + ''' sum of nodes at last level''' + + sumLastLevel = ((leafNodeCount * + (leafNodeCount + 1)) / 2); + ''' sum of all nodes''' + + sum = sumLastLevel * l; + return int(sum); + '''Driver Code''' + +l = 3; +print (sumNodes(l));" +Three numbers in a BST that adds upto zero,"/*A Java program to check if there +is a triplet with sum equal to 0 in +a given BST*/ + +import java.util.*; +class GFG +{ +/* A BST node has key, and left and right pointers*/ + + static class node + { + int key; + node left; + node right; + }; + static node head; + static node tail; +/* A function to convert given BST to Doubly + Linked List. left pointer is used + as previous pointer and right pointer + is used as next pointer. The function + sets *head to point to first and *tail + to point to last node of converted DLL*/ + + static void convertBSTtoDLL(node root) + { +/* Base case*/ + + if (root == null) + return; +/* First convert the left subtree*/ + + if (root.left != null) + convertBSTtoDLL(root.left); +/* Then change left of current root + as last node of left subtree*/ + + root.left = tail; +/* If tail is not null, then set right + of tail as root, else current + node is head*/ + + if (tail != null) + (tail).right = root; + else + head = root; +/* Update tail*/ + + tail = root; +/* Finally, convert right subtree*/ + + if (root.right != null) + convertBSTtoDLL(root.right); + } +/* This function returns true if there + is pair in DLL with sum equal to given + sum. The algorithm is similar to hasArrayTwoCandidates() +tinyurl.com/dy6palr +in method 1 of http:*/ + + static boolean isPresentInDLL(node head, node tail, int sum) + { + while (head != tail) + { + int curr = head.key + tail.key; + if (curr == sum) + return true; + else if (curr > sum) + tail = tail.left; + else + head = head.right; + } + return false; + } +/* The main function that returns + true if there is a 0 sum triplet in + BST otherwise returns false*/ + + static boolean isTripletPresent(node root) + { +/* Check if the given BST is empty*/ + + if (root == null) + return false; +/* Convert given BST to doubly linked list. head and tail store the + pointers to first and last nodes in DLLL*/ + + head = null; + tail = null; + convertBSTtoDLL(root); +/* Now iterate through every node and + find if there is a pair with sum + equal to -1 * heaf.key where head is current node*/ + + while ((head.right != tail) && (head.key < 0)) + { +/* If there is a pair with sum + equal to -1*head.key, then return + true else move forward*/ + + if (isPresentInDLL(head.right, tail, -1*head.key)) + return true; + else + head = head.right; + } +/* If we reach here, then + there was no 0 sum triplet*/ + + return false; + } +/* A utility function to create + a new BST node with key as given num*/ + + static node newNode(int num) + { + node temp = new node(); + temp.key = num; + temp.left = temp.right = null; + return temp; + } +/* A utility function to insert a given key to BST*/ + + static node insert(node root, int key) + { + if (root == null) + return newNode(key); + if (root.key > key) + root.left = insert(root.left, key); + else + root.right = insert(root.right, key); + return root; + } +/* Driver code*/ + + public static void main(String[] args) + { + node root = null; + root = insert(root, 6); + root = insert(root, -13); + root = insert(root, 14); + root = insert(root, -8); + root = insert(root, 15); + root = insert(root, 13); + root = insert(root, 7); + if (isTripletPresent(root)) + System.out.print(""Present""); + else + System.out.print(""Not Present""); + } +}", +How to handle duplicates in Binary Search Tree?,"/*Java program to implement basic operations +(search, insert and delete) on a BST that +handles duplicates by storing count with +every node*/ + +class GFG +{ +static class node +{ + int key; + int count; + node left, right; +}; +/*A utility function to create a new BST node*/ + +static node newNode(int item) +{ + node temp = new node(); + temp.key = item; + temp.left = temp.right = null; + temp.count = 1; + return temp; +} +/*A utility function to do inorder traversal of BST*/ + +static void inorder(node root) +{ + if (root != null) + { + inorder(root.left); + System.out.print(root.key + ""("" + + root.count + "") ""); + inorder(root.right); + } +} +/* A utility function to insert a new +node with given key in BST */ + +static node insert(node node, int key) +{ + /* If the tree is empty, return a new node */ + + if (node == null) return newNode(key); +/* If key already exists in BST, + increment count and return*/ + + if (key == node.key) + { + (node.count)++; + return node; + } + /* Otherwise, recur down the tree */ + + if (key < node.key) + node.left = insert(node.left, key); + else + node.right = insert(node.right, key); + /* return the (unchanged) node pointer */ + + return node; +} +/* Given a non-empty binary search tree, return +the node with minimum key value found in that +tree. Note that the entire tree does not need +to be searched. */ + +static node minValueNode(node node) +{ + node current = node; + /* loop down to find the leftmost leaf */ + + while (current.left != null) + current = current.left; + return current; +} +/* Given a binary search tree and a key, +this function deletes a given key and +returns root of modified tree */ + +static node deleteNode(node root, int key) +{ +/* base case*/ + + if (root == null) return root; +/* If the key to be deleted is smaller than the + root's key, then it lies in left subtree*/ + + if (key < root.key) + root.left = deleteNode(root.left, key); +/* If the key to be deleted is greater than + the root's key, then it lies in right subtree*/ + + else if (key > root.key) + root.right = deleteNode(root.right, key); +/* if key is same as root's key*/ + + else + { +/* If key is present more than once, + simply decrement count and return*/ + + if (root.count > 1) + { + (root.count)--; + return root; + } +/* ElSE, delete the node + node with only one child or no child*/ + + if (root.left == null) + { + node temp = root.right; + root=null; + return temp; + } + else if (root.right == null) + { + node temp = root.left; + root = null; + return temp; + } +/* node with two children: Get the inorder + successor (smallest in the right subtree)*/ + + node temp = minValueNode(root.right); +/* Copy the inorder successor's + content to this node*/ + + root.key = temp.key; +/* Delete the inorder successor*/ + + root.right = deleteNode(root.right, + temp.key); + } + return root; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + /* Let us create following BST + 12(3) + / \ + 10(2) 20(1) + / \ + 9(1) 11(1) */ + + node root = null; + root = insert(root, 12); + root = insert(root, 10); + root = insert(root, 20); + root = insert(root, 9); + root = insert(root, 11); + root = insert(root, 10); + root = insert(root, 12); + root = insert(root, 12); + System.out.print(""Inorder traversal of "" + + ""the given tree "" + ""\n""); + inorder(root); + System.out.print(""\nDelete 20\n""); + root = deleteNode(root, 20); + System.out.print(""Inorder traversal of "" + + ""the modified tree \n""); + inorder(root); + System.out.print(""\nDelete 12\n""); + root = deleteNode(root, 12); + System.out.print(""Inorder traversal of "" + + ""the modified tree \n""); + inorder(root); + System.out.print(""\nDelete 9\n""); + root = deleteNode(root, 9); + System.out.print(""Inorder traversal of "" + + ""the modified tree \n""); + inorder(root); +} +}"," '''Python3 program to implement basic operations +(search, insert and delete) on a BST that handles +duplicates by storing count with every node''' + + '''A utility function to create a new BST node''' + +class newNode: + def __init__(self, data): + self.key = data + self.count = 1 + self.left = None + self.right = None + '''A utility function to do inorder +traversal of BST''' + +def inorder(root): + if root != None: + inorder(root.left) + print(root.key,""("", root.count,"")"", + end = "" "") + inorder(root.right) + '''A utility function to insert a new node +with given key in BST''' + +def insert(node, key): + ''' If the tree is empty, return a new node''' + + if node == None: + k = newNode(key) + return k + ''' If key already exists in BST, increment + count and return''' + + if key == node.key: + (node.count) += 1 + return node + ''' Otherwise, recur down the tree''' + + if key < node.key: + node.left = insert(node.left, key) + else: + node.right = insert(node.right, key) + ''' return the (unchanged) node pointer''' + + return node + '''Given a non-empty binary search tree, return +the node with minimum key value found in that +tree. Note that the entire tree does not need +to be searched.''' + +def minValueNode(node): + current = node + ''' loop down to find the leftmost leaf''' + + while current.left != None: + current = current.left + return current + '''Given a binary search tree and a key, +this function deletes a given key and +returns root of modified tree''' + +def deleteNode(root, key): + ''' base case''' + + if root == None: + return root + ''' If the key to be deleted is smaller than the + root's key, then it lies in left subtree''' + + if key < root.key: + root.left = deleteNode(root.left, key) + ''' If the key to be deleted is greater than + the root's key, then it lies in right subtree''' + + elif key > root.key: + root.right = deleteNode(root.right, key) + ''' if key is same as root's key''' + + else: + ''' If key is present more than once, + simply decrement count and return''' + + if root.count > 1: + root.count -= 1 + return root + ''' ElSE, delete the node node with + only one child or no child''' + + if root.left == None: + temp = root.right + return temp + elif root.right == None: + temp = root.left + return temp + ''' node with two children: Get the inorder + successor (smallest in the right subtree)''' + + temp = minValueNode(root.right) + ''' Copy the inorder successor's content + to this node''' + + root.key = temp.key + ''' Delete the inorder successor''' + + root.right = deleteNode(root.right, temp.key) + return root + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create following BST + 12(3) + / \ + 10(2) 20(1) + / \ + 9(1) 11(1)''' + + root = None + root = insert(root, 12) + root = insert(root, 10) + root = insert(root, 20) + root = insert(root, 9) + root = insert(root, 11) + root = insert(root, 10) + root = insert(root, 12) + root = insert(root, 12) + print(""Inorder traversal of the given tree"") + inorder(root) + print() + print(""Delete 20"") + root = deleteNode(root, 20) + print(""Inorder traversal of the modified tree"") + inorder(root) + print() + print(""Delete 12"") + root = deleteNode(root, 12) + print(""Inorder traversal of the modified tree"") + inorder(root) + print() + print(""Delete 9"") + root = deleteNode(root, 9) + print(""Inorder traversal of the modified tree"") + inorder(root)" +"Given a sorted array and a number x, find the pair in array whose sum is closest to x","/*Java program to find pair with sum closest to x*/ + +import java.io.*; +import java.util.*; +import java.lang.Math; +class CloseSum { +/* Prints the pair with sum cloest to x*/ + + static void printClosest(int arr[], int n, int x) + { +/*To store indexes of result pair*/ + +int res_l=0, res_r=0; +/* Initialize left and right indexes and difference between + pair sum and x*/ + + int l = 0, r = n-1, diff = Integer.MAX_VALUE; +/* While there are elements between l and r*/ + + while (r > l) + { +/* Check if this pair is closer than the closest pair so far*/ + + if (Math.abs(arr[l] + arr[r] - x) < diff) + { + res_l = l; + res_r = r; + diff = Math.abs(arr[l] + arr[r] - x); + } +/* If this pair has more sum, move to smaller values.*/ + + if (arr[l] + arr[r] > x) + r--; +/*Move to larger values*/ + +else + l++; + } + System.out.println("" The closest pair is ""+arr[res_l]+"" and ""+ arr[res_r]); +} +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; + int n = arr.length; + printClosest(arr, n, x); + } +}"," '''Python3 program to find the pair +with sum +closest to a given no. +A sufficiently large value greater +than any +element in the input array''' + +MAX_VAL = 1000000000 + '''Prints the pair with sum closest to x''' + +def printClosest(arr, n, x): + ''' To store indexes of result pair''' + + res_l, res_r = 0, 0 + ''' Initialize left and right indexes + and difference between + pair sum and x''' + + l, r, diff = 0, n-1, MAX_VAL + ''' While there are elements between l and r''' + + while r > l: + ''' Check if this pair is closer than the + closest pair so far''' + + if abs(arr[l] + arr[r] - x) < diff: + res_l = l + res_r = r + diff = abs(arr[l] + arr[r] - x) + if arr[l] + arr[r] > x: + ''' If this pair has more sum, move to + smaller values.''' + + r -= 1 + else: + ''' Move to larger values''' + + l += 1 + print('The closest pair is {} and {}' + .format(arr[res_l], arr[res_r])) + '''Driver code to test above''' + +if __name__ == ""__main__"": + arr = [10, 22, 28, 29, 30, 40] + n = len(arr) + x=54 + printClosest(arr, n, x)" +LCA for general or n-ary trees (Sparse Matrix DP approach ),"/*Sparse Matrix DP approach to find LCA of two nodes*/ + +import java.util.*; + +class GFG +{ + static final int MAXN = 100000; + static final int level = 18; + + @SuppressWarnings(""unchecked"") + static Vector[] tree = new Vector[MAXN]; + static int[] depth = new int[MAXN]; + static int[][] parent = new int[MAXN][level]; + +/* pre-compute the depth for each node and their + first parent(2^0th parent) + time complexity : O(n)*/ + + static void dfs(int cur, int prev) + { + depth[cur] = depth[prev] + 1; + parent[cur][0] = prev; + for (int i = 0; i < tree[cur].size(); i++) + { + if (tree[cur].get(i) != prev) + dfs(tree[cur].get(i), cur); + } + } + +/* Dynamic Programming Sparse Matrix Approach + populating 2^i parent for each node + Time complexity : O(nlogn)*/ + + static void precomputeSparseMatrix(int n) + { + for (int i = 1; i < level; i++) + { + for (int node = 1; node <= n; node++) + { + if (parent[node][i - 1] != -1) + parent[node][i] = parent[parent[node][i - 1]][i - 1]; + } + } + } + +/* Returning the LCA of u and v + Time complexity : O(log n)*/ + + static int lca(int u, int v) + { + if (depth[v] < depth[u]) + { + u = u + v; + v = u - v; + u = u - v; + } + + int diff = depth[v] - depth[u]; + +/* Step 1 of the pseudocode*/ + + for (int i = 0; i < level; i++) + if (((diff >> i) & 1) == 1) + v = parent[v][i]; + +/* now depth[u] == depth[v]*/ + + if (u == v) + return u; + +/* Step 2 of the pseudocode*/ + + for (int i = level - 1; i >= 0; i--) + if (parent[u][i] != parent[v][i]) + { + u = parent[u][i]; + v = parent[v][i]; + } + + return parent[u][0]; + } + + static void addEdge(int u, int v) + { + tree[u].add(v); + tree[v].add(u); + } + + static void memset(int value) + { + for (int i = 0; i < MAXN; i++) + { + for (int j = 0; j < level; j++) + { + parent[i][j] = -1; + } + } + } + +/* driver function*/ + + public static void main(String[] args) + { + memset(-1); + for (int i = 0; i < MAXN; i++) + tree[i] = new Vector(); + int n = 8; + addEdge(1, 2); + addEdge(1, 3); + addEdge(2, 4); + addEdge(2, 5); + addEdge(2, 6); + addEdge(3, 7); + addEdge(3, 8); + depth[0] = 0; + +/* running dfs and precalculating depth + of each node.*/ + + dfs(1, 0); + +/* Precomputing the 2^i th ancestor for evey node*/ + + precomputeSparseMatrix(n); + +/* calling the LCA function*/ + + System.out.print(""LCA(4, 7) = "" + lca(4, 7) + ""\n""); + System.out.print(""LCA(4, 6) = "" + lca(4, 6) + ""\n""); + } +} + + +", +Height of binary tree considering even level leaves only,"/* Java Program to find height of the tree considering +only even level leaves. */ + +class GfG { +/* A binary tree node has data, pointer to +left child and a pointer to right child */ + +static class Node { + int data; + Node left; + Node right; +} +static int heightOfTreeUtil(Node root, boolean isEven) +{ +/* Base Case */ + + if (root == null) + return 0; + if (root.left == null && root.right == null) { + if (isEven == true) + return 1; + else + return 0; + } + /*left stores the result of left subtree, + and right stores the result of right subtree*/ + + int left = heightOfTreeUtil(root.left, !isEven); + int right = heightOfTreeUtil(root.right, !isEven); + /*If both left and right returns 0, it means + there is no valid path till leaf node*/ + + if (left == 0 && right == 0) + return 0; + return (1 + Math.max(left, right)); +} +/* Helper function that allocates a new node with the +given data and NULL left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +static int heightOfTree(Node root) +{ + return heightOfTreeUtil(root, false); +} +/* Driver program to test above functions*/ + +public static void main(String[] args) +{ +/* Let us create binary tree shown in above diagram */ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + root.left.right.left = newNode(6); + System.out.println(""Height of tree is "" + heightOfTree(root)); +} +}"," '''Program to find height of the tree considering +only even level leaves.''' + + ''' A binary tree node has data, pointer to +left child and a pointer to right child ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None +def heightOfTreeUtil(root, isEven): ''' Base Case ''' + + if (not root): + return 0 + if (not root.left and not root.right): + if (isEven): + return 1 + else: + return 0 + ''' left stores the result of left subtree, + and right stores the result of right subtree''' + + left = heightOfTreeUtil(root.left, not isEven) + right = heightOfTreeUtil(root.right, not isEven) + ''' If both left and right returns 0, it means + there is no valid path till leaf node''' + + if (left == 0 and right == 0): + return 0 + return (1 + max(left, right)) +def heightOfTree(root): + return heightOfTreeUtil(root, False) + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create binary tree shown + in above diagram ''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.left.right.left = newNode(6) + print(""Height of tree is"", + heightOfTree(root))" +How to swap two numbers without using a temporary variable?,"/*Java Program to swap two numbers +without using temporary variable*/ + +import java.io.*; +class GFG { + public static void main(String[] args) + { + int x = 10; + int y = 5; +/* Code to swap 'x' and 'y' +x now becomes 50*/ + +x = x * y; +/*y becomes 10*/ + +y = x / y; +/*x becomes 5*/ + +x = x / y; + System.out.println(""After swaping:"" + + "" x = "" + x + "", y = "" + y); + } +}"," '''Python3 program to +swap two numbers +without using +temporary variable''' + +x = 10 +y = 5 + '''code to swap + '''x' and 'y' +x now becomes 50''' + +x = x * y + '''y becomes 10''' + +y = x // y; + '''x becomes 5''' + +x = x // y; +print(""After Swapping: x ="", + x, "" y ="", y);" +First negative integer in every window of size k,"/*Java implementation to find the +first negative integer in +every window of size k*/ + +import java.util.*; +class GFG +{ +/*function to find the first negative +integer in every window of size k*/ + +static void printFirstNegativeInteger(int arr[], + int n, int k) +{ +/* A Double Ended Queue, Di that will + store indexes of useful array elements + for the current window of size k. + The useful elements are all negative integers.*/ + + LinkedList Di = new LinkedList<>(); +/* Process first k (or first window) + elements of array*/ + + int i; + for (i = 0; i < k; i++) +/* Add current element at the rear of Di + if it is a negative integer*/ + + if (arr[i] < 0) + Di.add(i); +/* Process rest of the elements, + i.e., from arr[k] to arr[n-1]*/ + + for ( ; i < n; i++) + { +/* if Di is not empty then the element + at the front of the queue is the first + negative integer of the previous window*/ + + if (!Di.isEmpty()) + System.out.print(arr[Di.peek()] + "" ""); +/* else the window does not have a + negative integer*/ + + else + System.out.print(""0"" + "" ""); +/* Remove the elements which are + out of this window*/ + + while ((!Di.isEmpty()) && + Di.peek() < (i - k + 1)) +/*Remove from front of queue*/ + +Di.remove(); +/* Add current element at the rear of Di + if it is a negative integer*/ + + if (arr[i] < 0) + Di.add(i); + } +/* Print the first negative + integer of last window*/ + + if (!Di.isEmpty()) + System.out.print(arr[Di.peek()] + "" ""); + else + System.out.print(""0"" + "" ""); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = {12, -1, -7, 8, -15, 30, 16, 28}; + int n = arr.length; + int k = 3; + printFirstNegativeInteger(arr, n, k); +} +}"," '''Python3 implementation to find the +first negative integer in every window +of size k import deque() from collections''' + +from collections import deque + '''function to find the first negative +integer in every window of size k''' + +def printFirstNegativeInteger(arr, n, k): + ''' A Double Ended Queue, Di that will store + indexes of useful array elements for the + current window of size k. The useful + elements are all negative integers.''' + + Di = deque() + ''' Process first k (or first window) + elements of array''' + + for i in range(k): + ''' Add current element at the rear of Di + if it is a negative integer''' + + if (arr[i] < 0): + Di.append(i); + ''' Process rest of the elements, i.e., + from arr[k] to arr[n-1]''' + + for i in range(k, n): + ''' if the window does not have + a negative integer''' + + if (not Di): + print(0, end = ' ') + ''' if Di is not empty then the element + at the front of the queue is the first + negative integer of the previous window''' + + else: + print(arr[Di[0]], end = ' '); + ''' Remove the elements which are + out of this window''' + + while Di and Di[0] <= (i - k): + '''Remove from front of queue''' + + Di.popleft() + ''' Add current element at the rear of Di + if it is a negative integer''' + + if (arr[i] < 0): + Di.append(i); + ''' Print the first negative + integer of last window''' + + if not Di: + print(0) + else: + print(arr[Di[0]], end = "" "") + '''Driver Code''' + +if __name__ ==""__main__"": + arr = [12, -1, -7, 8, -15, 30, 16, 28] + n = len(arr) + k = 3 + printFirstNegativeInteger(arr, n, k);" +Convert a given Binary Tree to Doubly Linked List | Set 3,"/*A Java program for in-place conversion of Binary Tree to DLL*/ + +/*A binary tree node has data, left pointers and right pointers*/ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* head --> Pointer to head node of created doubly linked list*/ + + Node head; +/* A simple recursive function to convert a given Binary tree + to Doubly Linked List + root --> Root of Binary Tree*/ + + void BinaryTree2DoubleLinkedList(Node root) + { +/* Base case*/ + + if (root == null) + return; +/* Initialize previously visited node as NULL. This is + static so that the same value is accessible in all recursive + calls*/ + + static Node prev = null; +/* Recursively convert left subtree*/ + + BinaryTree2DoubleLinkedList(root.left); +/* Now convert this node*/ + + if (prev == null) + head = root; + else + { + root.left = prev; + prev.right = root; + } + prev = root; +/* Finally convert right subtree*/ + + BinaryTree2DoubleLinkedList(root.right); + } + /* Function to print nodes in a given doubly linked list */ + + void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.right; + } + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { +/* Let us create the tree as shown in above diagram*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(12); + tree.root.right = new Node(15); + tree.root.left.left = new Node(25); + tree.root.left.right = new Node(30); + tree.root.right.left = new Node(36); +/* convert to DLL*/ + + tree.BinaryTree2DoubleLinkedList(tree.root); +/* Print the converted List*/ + + tree.printList(tree.head); + } +}", +Minimum operations required to set all elements of binary matrix,"/*Java program to find minimum operations required +to set all the element of binary matrix*/ + +class GFG { + static final int N = 5; + static final int M = 5; +/*Return minimum operation required to make all 1s.*/ + + static int minOperation(boolean arr[][]) + { + int ans = 0; + for (int i = N - 1; i >= 0; i--) + { + for (int j = M - 1; j >= 0; j--) + { +/* check if this cell equals 0*/ + + if (arr[i][j] == false) + { +/* increase the number of moves*/ + + ans++; +/* flip from this cell to the start point*/ + + for (int k = 0; k <= i; k++) + { + for (int h = 0; h <= j; h++) + { +/* flip the cell*/ + + if (arr[k][h] == true) + { + arr[k][h] = false; + } else { + arr[k][h] = true; + } + } + } + } + } + } + return ans; + } +/*Driven Program*/ + + public static void main(String[] args) { + boolean mat[][] + = { + {false, false, true, true, true}, + {false, false, false, true, true}, + {false, false, false, true, true}, + {true, true, true, true, true}, + {true, true, true, true, true} + }; + System.out.println(minOperation(mat)); + } +}"," '''Python 3 program to find +minimum operations required +to set all the element of +binary matrix + ''' '''Return minimum operation +required to make all 1s.''' + +def minOperation(arr): + ans = 0 + for i in range(N - 1, -1, -1): + for j in range(M - 1, -1, -1): + ''' check if this + cell equals 0''' + + if(arr[i][j] == 0): + ''' increase the + number of moves''' + + ans += 1 + ''' flip from this cell + to the start point''' + + for k in range(i + 1): + for h in range(j + 1): + ''' flip the cell''' + + if (arr[k][h] == 1): + arr[k][h] = 0 + else: + arr[k][h] = 1 + return ans + '''Driver Code''' + +mat = [[ 0, 0, 1, 1, 1], + [0, 0, 0, 1, 1], + [0, 0, 0, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1]] +M = 5 +N = 5 +print(minOperation(mat))" +Maximum equlibrium sum in an array,"/*Java program to find maximum equilibrium sum.*/ + +import java.io.*; +public class GFG { +/* Function to find maximum + equilibrium sum.*/ + + static int findMaxSum(int []arr, int n) + { +/* Array to store prefix sum.*/ + + int []preSum = new int[n]; +/* Array to store suffix sum.*/ + + int []suffSum = new int[n]; +/* Variable to store maximum sum.*/ + + int ans = Integer.MIN_VALUE; +/* Calculate prefix sum.*/ + + preSum[0] = arr[0]; + for (int i = 1; i < n; i++) + preSum[i] = preSum[i - 1] + arr[i]; +/* Calculate suffix sum and compare + it with prefix sum. Update ans + accordingly.*/ + + suffSum[n - 1] = arr[n - 1]; + if (preSum[n - 1] == suffSum[n - 1]) + ans = Math.max(ans, preSum[n - 1]); + for (int i = n - 2; i >= 0; i--) + { + suffSum[i] = suffSum[i + 1] + arr[i]; + if (suffSum[i] == preSum[i]) + ans = Math.max(ans, preSum[i]); + } + return ans; + } +/* Driver Code*/ + + static public void main (String[] args) + { + int []arr = { -2, 5, 3, 1, 2, 6, -4, 2 }; + int n = arr.length; + System.out.println( findMaxSum(arr, n)); + } +}"," '''Python3 program to find +maximum equilibrium sum. + ''' '''Function to find maximum +equilibrium sum.''' + +def findMaxSum(arr, n): + ''' Array to store prefix sum.''' + + preSum = [0 for i in range(n)] + ''' Array to store suffix sum.''' + + suffSum = [0 for i in range(n)] + ''' Variable to store maximum sum.''' + + ans = -10000000 + ''' Calculate prefix sum.''' + + preSum[0] = arr[0] + for i in range(1, n): + preSum[i] = preSum[i - 1] + arr[i] + ''' Calculate suffix sum and compare + it with prefix sum. Update ans + accordingly.''' + + suffSum[n - 1] = arr[n - 1] + if (preSum[n - 1] == suffSum[n - 1]): + ans = max(ans, preSum[n - 1]) + for i in range(n - 2, -1, -1): + suffSum[i] = suffSum[i + 1] + arr[i] + if (suffSum[i] == preSum[i]): + ans = max(ans, preSum[i]) + return ans + '''Driver Code''' + +if __name__=='__main__': + arr = [-2, 5, 3, 1,2, 6, -4, 2] + n = len(arr) + print(findMaxSum(arr, n))" +Diameter of a Binary Tree in O(n) [A new method],"/*Simple Java program to find diameter +of a binary tree.*/ + +class GfG { +/* Tree node structure used in the program */ + +static class Node +{ + int data; + Node left, right; +} +static class A +{ + int ans = Integer.MIN_VALUE; +} +/* Function to find height of a tree */ + +static int height(Node root, A a) +{ + if (root == null) + return 0; + int left_height = height(root.left, a); + int right_height = height(root.right, a); +/* update the answer, because diameter of a + tree is nothing but maximum value of + (left_height + right_height + 1) for each node*/ + + a.ans = Math.max(a.ans, 1 + left_height + + right_height); + return 1 + Math.max(left_height, right_height); +} +/* Computes the diameter of binary +tree with given root. */ + +static int diameter(Node root) +{ + if (root == null) + return 0; +/* This will store the final answer*/ + + A a = new A(); + int height_of_tree = height(root, a); + return a.ans; +} +/*A utility function to +create a new Binary Tree Node*/ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + System.out.println(""Diameter is "" + diameter(root)); +} +}"," '''Simple Python3 program to find diameter +of a binary tree.''' + + + ''' Tree node structure used in the program ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to find height of a tree''' + +def height(root, ans): + if (root == None): + return 0 + left_height = height(root.left, ans) + right_height = height(root.right, ans) + ''' update the answer, because diameter + of a tree is nothing but maximum + value of (left_height + right_height + 1) + for each node''' + + ans[0] = max(ans[0], 1 + left_height + + right_height) + return 1 + max(left_height, + right_height) + '''Computes the diameter of binary +tree with given root.''' + +def diameter(root): + if (root == None): + return 0 + '''This will storethe final answer''' + + + ans = [-999999999999] + height_of_tree = height(root, ans) + return ans[0] '''Driver code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + print(""Diameter is"", diameter(root))" +Block swap algorithm for array rotation,"import java.util.*; +class GFG +{ +/* Wrapper over the recursive function leftRotateRec() + It left rotates arr[] by d.*/ + + public static void leftRotate(int arr[], int d, + int n) + { + leftRotateRec(arr, 0, d, n); + } + public static void leftRotateRec(int arr[], int i, + int d, int n) + { + /* Return If number of elements to be rotated + is zero or equal to array size */ + + if(d == 0 || d == n) + return; + /*If number of elements to be rotated + is exactly half of array size */ + + if(n - d == d) + { + swap(arr, i, n - d + i, d); + return; + } + /* If A is shorter*/ + + if(d < n - d) + { + swap(arr, i, n - d + i, d); + leftRotateRec(arr, i, d, n - d); + } +/* If B is shorter*/ + else + { + swap(arr, i, d, n - d); + leftRotateRec(arr, n - d + i, 2 * d - n, d); + } + }/* function to print an array */ + +public static void printArray(int arr[], int size) +{ + int i; + for(i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); +} +/*This function swaps d elements +starting at index fi with d elements +starting at index si */ + +public static void swap(int arr[], int fi, + int si, int d) +{ + int i, temp; + for(i = 0; i < d; i++) + { + temp = arr[fi + i]; + arr[fi + i] = arr[si + i]; + arr[si + i] = temp; + } +} +/*Driver Code*/ + +public static void main (String[] args) +{ + int arr[] = {1, 2, 3, 4, 5, 6, 7}; + leftRotate(arr, 2, 7); + printArray(arr, 7); +} +}"," '''Wrapper over the recursive function leftRotateRec() +It left rotates arr by d.''' + +def leftRotate(arr, d, n): + leftRotateRec(arr, 0, d, n); +def leftRotateRec(arr, i, d, n): + ''' + * Return If number of elements to be + rotated is zero or equal to array size + ''' + + if (d == 0 or d == n): + return; + ''' + * If number of elements to be rotated + is exactly half of array size + ''' + + if (n - d == d): + swap(arr, i, n - d + i, d); + return; + ''' If A is shorter ''' + + if (d < n - d): + swap(arr, i, n - d + i, d); + leftRotateRec(arr, i, d, n - d); + ''' If B is shorter ''' + + else: + swap(arr, i, d, n - d); + leftRotateRec(arr, n - d + i, 2 * d - n, d); ''' function to pran array ''' + +def printArray(arr, size): + for i in range(size): + print(arr[i], end = "" ""); + print(); + ''' + * This function swaps d elements starting at + * index fi with d elements starting at index si + ''' + +def swap(arr, fi, si, d): + for i in range(d): + temp = arr[fi + i]; + arr[fi + i] = arr[si + i]; + arr[si + i] = temp; + '''Driver Code''' + +if __name__ == '__main__': + arr = [1, 2, 3, 4, 5, 6, 7]; + leftRotate(arr, 2, 7); + printArray(arr, 7);" +Check loop in array according to given constraints,"/*Java program to check if +a given array is cyclic or not*/ + +import java.util.Vector; +class GFG +{ +/*A simple Graph DFS based recursive function to check if +there is cycle in graph with vertex v as root of DFS. +Refer below article for details. +https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ +*/ + + static boolean isCycleRec(int v, Vector[] adj, + Vector visited, + Vector recur) + { + visited.set(v, true); + recur.set(v, true); + for (int i = 0; i < adj[v].size(); i++) + { + if (visited.elementAt(adj[v].elementAt(i)) == false) + { + if (isCycleRec(adj[v].elementAt(i), + adj, visited, recur)) + return true; + } +/* There is a cycle if an adjacent is visited + and present in recursion call stack recur[]*/ + + else if (visited.elementAt(adj[v].elementAt(i)) == true && + recur.elementAt(adj[v].elementAt(i)) == true) + return true; + } + recur.set(v, false); + return false; + } +/* Returns true if arr[] has cycle*/ + + @SuppressWarnings(""unchecked"") + static boolean isCycle(int[] arr, int n) + { +/* Create a graph using given moves in arr[]*/ + + Vector[] adj = new Vector[n]; + for (int i = 0; i < n; i++) + if (i != (i + arr[i] + n) % n && + adj[i] != null) + adj[i].add((i + arr[i] + n) % n); +/* Do DFS traversal of graph to detect cycle*/ + + Vector visited = new Vector<>(); + for (int i = 0; i < n; i++) + visited.add(true); + Vector recur = new Vector<>(); + for (int i = 0; i < n; i++) + recur.add(true); + for (int i = 0; i < n; i++) + if (visited.elementAt(i) == false) + if (isCycleRec(i, adj, visited, recur)) + return true; + return true; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 2, -1, 1, 2, 2 }; + int n = arr.length; + if (isCycle(arr, n) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 program to check if a +given array is cyclic or not''' + + '''A simple Graph DFS based recursive +function to check if there is cycle +in graph with vertex v as root of DFS. +Refer below article for details. +https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ + ''' + +def isCycleRec(v, adj, visited, recur): + visited[v] = True + recur[v] = True + for i in range(len(adj[v])): + if (visited[adj[v][i]] == False): + if (isCycleRec(adj[v][i], adj, + visited, recur)): + return True ''' There is a cycle if an adjacent is visited + and present in recursion call stack recur[]''' + + elif (visited[adj[v][i]] == True and + recur[adj[v][i]] == True): + return True + recur[v] = False + return False + '''Returns true if arr[] has cycle''' + +def isCycle(arr, n): + ''' Create a graph using given + moves in arr[]''' + + adj = [[] for i in range(n)] + for i in range(n): + if (i != (i + arr[i] + n) % n): + adj[i].append((i + arr[i] + n) % n) + ''' Do DFS traversal of graph + to detect cycle ''' + + visited = [False] * n + recur = [False] * n + for i in range(n): + if (visited[i] == False): + if (isCycleRec(i, adj, + visited, recur)): + return True + return True + '''Driver code''' + +if __name__ == '__main__': + arr = [2, -1, 1, 2, 2] + n = len(arr) + if (isCycle(arr, n)): + print(""Yes"") + else: + print(""No"")" +Check if reversing a sub array make the array sorted,"/*Java program to check whether reversing a +sub array make the array sorted or not*/ + + +import java.util.Arrays; + +class GFG { + +/*Return true, if reversing the subarray will +sort the array, else return false.*/ + + static boolean checkReverse(int arr[], int n) { +/* Copying the array.*/ + + int temp[] = new int[n]; + for (int i = 0; i < n; i++) { + temp[i] = arr[i]; + } + +/* Sort the copied array.*/ + + Arrays.sort(temp); + +/* Finding the first mismatch.*/ + + int front; + for (front = 0; front < n; front++) { + if (temp[front] != arr[front]) { + break; + } + } + +/* Finding the last mismatch.*/ + + int back; + for (back = n - 1; back >= 0; back--) { + if (temp[back] != arr[back]) { + break; + } + } + +/* If whole array is sorted*/ + + if (front >= back) { + return true; + } + +/* Checking subarray is decreasing or not.*/ + + do { + front++; + if (arr[front - 1] < arr[front]) { + return false; + } + } while (front != back); + + return true; + } + +/*Driven Program*/ + + public static void main(String[] args) { + + int arr[] = {1, 2, 5, 4, 3}; + int n = arr.length; + + if (checkReverse(arr, n)) { + System.out.print(""Yes""); + } else { + System.out.print(""No""); + } + } + +} + +"," '''Python3 program to check whether +reversing a sub array make the +array sorted or not''' + + + '''Return true, if reversing the +subarray will sort the array, +else return false.''' + +def checkReverse(arr, n): + + ''' Copying the array''' + + temp = [0] * n + for i in range(n): + temp[i] = arr[i] + + ''' Sort the copied array.''' + + temp.sort() + + ''' Finding the first mismatch.''' + + for front in range(n): + if temp[front] != arr[front]: + break + + ''' Finding the last mismatch.''' + + for back in range(n - 1, -1, -1): + if temp[back] != arr[back]: + break + + ''' If whole array is sorted''' + + if front >= back: + return True + + + ''' Checking subarray is decreasing or not.''' + + while front != back: + front += 1 + if arr[front - 1] < arr[front]: + return False + return True '''Driver code''' + +arr = [1, 2, 5, 4, 3] +n = len(arr) +if checkReverse(arr, n) == True: + print(""Yes"") +else: + print(""No"") + + +" +Number of turns to reach from one node to other in binary tree,"/*A Java Program to count number of turns +in a Binary Tree.*/ + +public class Turns_to_reach_another_node { + static int Count;/* A Binary Tree Node*/ + + static class Node { + Node left, right; + int key; +/* Constructor*/ + + Node(int key) { + this.key = key; + left = null; + right = null; + } + } +/* Utility function to find the LCA of + two given values n1 and n2.*/ + + static Node findLCA(Node root, int n1, int n2) { +/* Base case*/ + + if (root == null) + return null; +/* If either n1 or n2 matches with + root's key, report the presence by + returning root (Note that if a key + is ancestor of other, then the + ancestor key becomes LCA*/ + + if (root.key == n1 || root.key == n2) + return root; +/* Look for keys in left and right subtrees*/ + + Node left_lca = findLCA(root.left, n1, n2); + Node right_lca = findLCA(root.right, n1, n2); +/* If both of the above calls return + Non-NULL, then one key is present + in once subtree and other is present + in other, So this node is the LCA*/ + + if (left_lca != null && right_lca != null) + return root; +/* Otherwise check if left subtree or right + subtree is LCA*/ + + return (left_lca != null) ? left_lca : right_lca; + } +/* function count number of turn need to reach + given node from it's LCA we have two way to*/ + + static boolean CountTurn(Node root, int key, boolean turn) { + if (root == null) + return false; +/* if found the key value in tree*/ + + if (root.key == key) + return true; +/* Case 1:*/ + + if (turn == true) { + if (CountTurn(root.left, key, turn)) + return true; + if (CountTurn(root.right, key, !turn)) { + Count += 1; + return true; + } +/*Case 2:*/ + +} else + { + if (CountTurn(root.right, key, turn)) + return true; + if (CountTurn(root.left, key, !turn)) { + Count += 1; + return true; + } + } + return false; + } +/* Function to find nodes common to given two nodes*/ + + static int NumberOfTurn(Node root, int first, int second) { + Node LCA = findLCA(root, first, second); +/* there is no path between these two node*/ + + if (LCA == null) + return -1; + Count = 0; +/* case 1:*/ + + if (LCA.key != first && LCA.key != second) { +/* count number of turns needs to reached + the second node from LCA*/ + + if (CountTurn(LCA.right, second, false) + || CountTurn(LCA.left, second, true)) + ; +/* count number of turns needs to reached + the first node from LCA*/ + + if (CountTurn(LCA.left, first, true) + || CountTurn(LCA.right, first, false)) + ; + return Count + 1; + } +/* case 2:*/ + + if (LCA.key == first) { +/* count number of turns needs to reached + the second node from LCA*/ + + CountTurn(LCA.right, second, false); + CountTurn(LCA.left, second, true); + return Count; + } else { +/* count number of turns needs to reached + the first node from LCA1*/ + + CountTurn(LCA.right, first, false); + CountTurn(LCA.left, first, true); + return Count; + } + } +/* Driver program to test above functions*/ + + public static void main(String[] args) { +/* Let us create binary tree given in the above + example*/ + + 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.right.left.left = new Node(9); + root.right.left.right = new Node(10); + int turn = 0; + if ((turn = NumberOfTurn(root, 5, 10)) != 0) + System.out.println(turn); + else + System.out.println(""Not Possible""); + } +}"," '''Python Program to count number of turns +in a Binary Tree.''' + '''A Binary Tree Node''' + +class Node: + def __init__(self): + self.key = 0 + self.left = None + self.right = None + '''Utility function to create a new +tree Node''' + +def newNode(key: int) -> Node: + temp = Node() + temp.key = key + temp.left = None + temp.right = None + return temp + '''Utility function to find the LCA of +two given values n1 and n2.''' + +def findLCA(root: Node, n1: int, n2: int) -> Node: + ''' Base case''' + + if root is None: + return None + ''' If either n1 or n2 matches with + root's key, report the presence by + returning root (Note that if a key + is ancestor of other, then the + ancestor key becomes LCA''' + + if root.key == n1 or root.key == n2: + return root + ''' Look for keys in left and right subtrees''' + + left_lca = findLCA(root.left, n1, n2) + right_lca = findLCA(root.right, n1, n2) + ''' If both of the above calls return + Non-NULL, then one key is present + in once subtree and other is present + in other, So this node is the LCA''' + + if left_lca and right_lca: + return root + ''' Otherwise check if left subtree or right + subtree is LCA''' + + return (left_lca if left_lca is not None else right_lca) + '''function count number of turn need to reach +given node from it's LCA we have two way to''' + +def countTurn(root: Node, key: int, turn: bool) -> bool: + global count + if root is None: + return False + ''' if found the key value in tree''' + + if root.key == key: + return True + ''' Case 1:''' + + if turn is True: + if countTurn(root.left, key, turn): + return True + if countTurn(root.right, key, not turn): + count += 1 + return True + ''' Case 2:''' + + else: + if countTurn(root.right, key, turn): + return True + if countTurn(root.left, key, not turn): + count += 1 + return True + return False + '''Function to find nodes common to given two nodes''' + +def numberOfTurn(root: Node, first: int, second: int) -> int: + global count + LCA = findLCA(root, first, second) + ''' there is no path between these two node''' + + if LCA is None: + return -1 + count = 0 + ''' case 1:''' + + if LCA.key != first and LCA.key != second: + ''' count number of turns needs to reached + the second node from LCA''' + + if countTurn(LCA.right, second, False) or countTurn( + LCA.left, second, True): + pass + ''' count number of turns needs to reached + the first node from LCA''' + + if countTurn(LCA.left, first, True) or countTurn( + LCA.right, first, False): + pass + return count + 1 + ''' case 2:''' + + if LCA.key == first: + ''' count number of turns needs to reached + the second node from LCA''' + + countTurn(LCA.right, second, False) + countTurn(LCA.left, second, True) + return count + else: + ''' count number of turns needs to reached + the first node from LCA1''' + + countTurn(LCA.right, first, False) + countTurn(LCA.left, first, True) + return count + '''Driver Code''' + +if __name__ == ""__main__"": + count = 0 + ''' Let us create binary tree given in the above + example''' + + root = 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.left.left.left = newNode(8) + root.right.left.left = newNode(9) + root.right.left.right = newNode(10) + turn = numberOfTurn(root, 5, 10) + if turn: + print(turn) + else: + print(""Not possible"")" +Check if X can give change to every person in the Queue,"/*Java program to check +whether X can give +change to every person +in the Queue*/ + +import java.io.*; +class GFG +{ +/*Function to check if +every person will +get the change from X*/ + +static int isChangeable(int notes[], + int n) +{ +/* To count the 5$ + and 10& notes*/ + + int fiveCount = 0; + int tenCount = 0; +/* Serve the customer + in order*/ + + for (int i = 0; i < n; i++) + { +/* Increase the number + of 5$ note by one*/ + + if (notes[i] == 5) + fiveCount++; + else if (notes[i] == 10) + { +/* decrease the number + of note 5$ and + increase 10$ note by one*/ + + if (fiveCount > 0) + { + fiveCount--; + tenCount++; + } + else + return 0; + } + else + { +/* decrease 5$ and + 10$ note by one*/ + + if (fiveCount > 0 && + tenCount > 0) + { + fiveCount--; + tenCount--; + } +/* decrease 5$ + note by three*/ + + else if (fiveCount >= 3) + { + fiveCount -= 3; + } + else + return 0; + } + } + return 1; +} +/*Driver Code*/ + +public static void main (String[] args) +{ +/*queue of customers +with available notes.*/ + +int a[] = {5, 5, 5, 10, 20}; +int n = a.length; +/*Calling function*/ + +if (isChangeable(a, n) > 0) + System.out.print(""YES""); +else + System.out.print(""NO""); +} +}"," '''Python program to check whether X can +give change to every person in the Queue''' + + '''Function to check if every person +will get the change from X''' + +def isChangeable(notes, n): ''' To count the 5$ and 10& notes''' + + fiveCount = 0 + tenCount = 0 + ''' Serve the customer in order''' + + for i in range(n): + ''' Increase the number of 5$ note by one''' + + if (notes[i] == 5): + fiveCount += 1 + elif(notes[i] == 10): + ''' decrease the number of note 5$ + and increase 10$ note by one''' + + if (fiveCount > 0): + fiveCount -= 1 + tenCount += 1 + else: + return 0 + else: + ''' decrease 5$ and 10$ note by one''' + + if (fiveCount > 0 and tenCount > 0): + fiveCount -= 1 + tenCount -= 1 + ''' decrease 5$ note by three''' + + elif (fiveCount >= 3): + fiveCount -= 3 + else: + return 0 + return 1 + '''Driver Code''' + + '''queue of customers with available notes.''' + +a = [5, 5, 5, 10, 20 ] +n = len(a) '''Calling function''' + +if (isChangeable(a, n)): + print(""YES"") +else: + print(""NO"")" +Ropes left after every removal of smallest,"/*Java program to print how many +Ropes are Left After Every Cut*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class GFG { + +/* function print how many Ropes are Left After + Every Cutting operation*/ + + public static void cuttringRopes(int Ropes[], int n) + { +/* sort all Ropes in increasing + order of their length*/ + + Arrays.sort(Ropes); + + int singleOperation = 0; + +/* min length rope*/ + + int cuttingLenght = Ropes[0]; + +/* now traverse through the given Ropes in + increase order of length*/ + + for (int i = 1; i < n; i++) + { +/* After cutting if current rope length + is greater than '0' that mean all + ropes to it's right side are also + greater than 0*/ + + if (Ropes[i] - cuttingLenght > 0) + { + System.out.print(n - i + "" ""); + +/* now current rope become + min length rope*/ + + cuttingLenght = Ropes[i]; + + singleOperation++; + } + } + +/* after first operation all ropes + length become zero*/ + + if (singleOperation == 0) + System.out.print(""0""); + } + + /* Driver Code*/ + + + public static void main(String[] arg) + { + int[] Ropes = { 5, 1, 1, 2, 3, 5 }; + int n = Ropes.length; + cuttringRopes(Ropes, n); + } +}", +Construct a graph from given degrees of all vertices,"/*Java program to generate a graph for a +given fixed degrees*/ + +import java.util.*; +class GFG +{ +/*A function to print the adjacency matrix.*/ + +static void printMat(int degseq[], int n) +{ +/* n is number of vertices*/ + + int [][]mat = new int[n][n]; + for (int i = 0; i < n; i++) + { + for (int j = i + 1; j < n; j++) + { +/* For each pair of vertex decrement + the degree of both vertex.*/ + + if (degseq[i] > 0 && degseq[j] > 0) + { + degseq[i]--; + degseq[j]--; + mat[i][j] = 1; + mat[j][i] = 1; + } + } + } +/* Print the result in specified format*/ + + System.out.print(""\n"" + setw(3) + "" ""); + for (int i = 0; i < n; i++) + System.out.print(setw(3) + ""("" + i + "")""); + System.out.print(""\n\n""); + for (int i = 0; i < n; i++) + { + System.out.print(setw(4) + ""("" + i + "")""); + for (int j = 0; j < n; j++) + System.out.print(setw(5) + mat[i][j]); + System.out.print(""\n""); + } +} +static String setw(int n) +{ + String space = """"; + while(n-- > 0) + space += "" ""; + return space; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int degseq[] = { 2, 2, 1, 1, 1 }; + int n = degseq.length; + printMat(degseq, n); +} +}"," '''Python3 program to generate a graph +for a given fixed degrees + ''' '''A function to print the adjacency matrix. ''' + +def printMat(degseq, n): + ''' n is number of vertices ''' + + mat = [[0] * n for i in range(n)] + for i in range(n): + for j in range(i + 1, n): + ''' For each pair of vertex decrement + the degree of both vertex. ''' + + if (degseq[i] > 0 and degseq[j] > 0): + degseq[i] -= 1 + degseq[j] -= 1 + mat[i][j] = 1 + mat[j][i] = 1 + ''' Print the result in specified form''' + + print("" "", end = "" "") + for i in range(n): + print("" "", ""("", i, "")"", end = """") + print() + print() + for i in range(n): + print("" "", ""("", i, "")"", end = """") + for j in range(n): + print("" "", mat[i][j], end = """") + print() + '''Driver Code''' + +if __name__ == '__main__': + degseq = [2, 2, 1, 1, 1] + n = len(degseq) + printMat(degseq, n)" +Linear Search,"/*Java code for linearly searching x in arr[]. If x +is present then return its location, otherwise +return -1*/ + +class GFG +{ + public static int search(int arr[], int x) + { + int n = arr.length; + for (int i = 0; i < n; i++) + { + if (arr[i] == x) + return i; + } + return -1; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 2, 3, 4, 10, 40 }; + int x = 10; +/* Function call*/ + + int result = search(arr, x); + if (result == -1) + System.out.print( + ""Element is not present in array""); + else + System.out.print(""Element is present at index "" + + result); + } +}"," '''Python3 code to linearly search x in arr[]. +If x is present then return its location, +otherwise return -1''' + +def search(arr, n, x): + for i in range(0, n): + if (arr[i] == x): + return i + return -1 + '''Driver Code''' + +arr = [2, 3, 4, 10, 40] +x = 10 +n = len(arr) + '''Function call''' + +result = search(arr, n, x) +if(result == -1): + print(""Element is not present in array"") +else: + print(""Element is present at index"", result)" +Find modular node in a linked list,"/*A Java program to find modular node in a linked list*/ + +public class GFG +{ +/* A Linkedlist node*/ + + static class Node{ + int data; + Node next; + Node(int data){ + this.data = data; + } + } +/* Function to find modular node in the linked list*/ + + static Node modularNode(Node head, int k) + { +/* Corner cases*/ + + if (k <= 0 || head == null) + return null; +/* Traverse the given list*/ + + int i = 1; + Node modularNode = null; + for (Node temp = head; temp != null; temp = temp.next) { + if (i % k == 0) + modularNode = temp; + i++; + } + return modularNode; + } +/* Driver code to test above function*/ + + public static void main(String[] args) + { + Node head = new Node(1); + head.next = new Node(2); + head.next.next = new Node(3); + head.next.next.next = new Node(4); + head.next.next.next.next = new Node(5); + int k = 2; + Node answer = modularNode(head, k); + System.out.print(""Modular node is ""); + if (answer != null) + System.out.println(answer.data); + else + System.out.println(""null""); + } +}"," '''Python3 program to find modular node +in a linked list''' + +import math + '''Linked list node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + '''Function to create a new node +with given data''' + +def newNode(data): + new_node = Node(data) + new_node.data = data + new_node.next = None + return new_node + '''Function to find modular node +in the linked list''' + +def modularNode(head, k): + ''' Corner cases''' + + if (k <= 0 or head == None): + return None + ''' Traverse the given list''' + + i = 1 + modularNode = None + temp = head + while (temp != None): + if (i % k == 0): + modularNode = temp + i = i + 1 + temp = temp.next + return modularNode + '''Driver Code''' + +if __name__ == '__main__': + 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) + k = 2 + answer = modularNode(head, k) + print(""Modular node is"", end = ' ') + if (answer != None): + print(answer.data, end = ' ') + else: + print(""None"")" +Activity Selection Problem | Greedy Algo-1,"/*The following implementation assumes that the activities +are already sorted according to their finish time*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class ActivitySelection +{ +/* Prints a maximum set of activities that can be done by a single + person, one at a time. + n --> Total number of activities + s[] --> An array that contains start time of all activities + f[] --> An array that contains finish time of all activities*/ + + public static void printMaxActivities(int s[], int f[], int n) + { + int i, j; + System.out.print(""Following activities are selected : n""); +/* The first activity always gets selected*/ + + i = 0; + System.out.print(i+"" ""); +/* Consider rest of the activities*/ + + for (j = 1; j < n; j++) + { +/* If this activity has start time greater than or + equal to the finish time of previously selected + activity, then select it*/ + + if (s[j] >= f[i]) + { + System.out.print(j+"" ""); + i = j; + } + } + } +/* driver program to test above function*/ + + public static void main(String[] args) + { + int s[] = {1, 3, 0, 5, 8, 5}; + int f[] = {2, 4, 6, 7, 9, 9}; + int n = s.length; + printMaxActivities(s, f, n); + } +}"," '''The following implementation assumes that the activities +are already sorted according to their finish time''' + + '''Prints a maximum set of activities that can be done by a +single person, one at a time +n --> Total number of activities +s[]--> An array that contains start time of all activities +f[] --> An array that contains finish time of all activities''' + +def printMaxActivities(s , f ): + n = len(f) + print ""The following activities are selected"" + + ''' The first activity is always selected''' + + i = 0 + print i, + ''' Consider rest of the activities''' + + for j in xrange(n): + ''' If this activity has start time greater than + or equal to the finish time of previously + selected activity, then select it''' + + if s[j] >= f[i]: + print j, + i = j + '''Driver program to test above function''' + +s = [1 , 3 , 0 , 5 , 8 , 5] +f = [2 , 4 , 6 , 7 , 9 , 9] +printMaxActivities(s , f)" +Rabin-Karp Algorithm for Pattern Searching,"/*Following program is a Java implementation +of Rabin Karp Algorithm given in the CLRS book*/ + +public class Main +{ +/* d is the number of characters in the input alphabet*/ + + public final static int d = 256; + /* pat -> pattern + txt -> text + q -> A prime number + */ + + static void search(String pat, String txt, int q) + { + int M = pat.length(); + int N = txt.length(); + int i, j; +/*hash value for pattern*/ + +int p = 0; +/*hash value for txt*/ + +int t = 0; + int h = 1; +/* The value of h would be ""pow(d, M-1)%q""*/ + + for (i = 0; i < M-1; i++) + h = (h*d)%q; +/* Calculate the hash value of pattern and first + window of text*/ + + for (i = 0; i < M; i++) + { + p = (d*p + pat.charAt(i))%q; + t = (d*t + txt.charAt(i))%q; + } +/* Slide the pattern over text one by one*/ + + for (i = 0; i <= N - M; i++) + { +/* Check the hash values of current window of text + and pattern. If the hash values match then only + check for characters on by one*/ + + if ( p == t ) + { + /* Check for characters one by one */ + + for (j = 0; j < M; j++) + { + if (txt.charAt(i+j) != pat.charAt(j)) + break; + } +/* if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]*/ + + if (j == M) + System.out.println(""Pattern found at index "" + i); + } +/* Calculate hash value for next window of text: Remove + leading digit, add trailing digit*/ + + if ( i < N-M ) + { + t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; +/* We might get negative value of t, converting it + to positive*/ + + if (t < 0) + t = (t + q); + } + } + } + /* Driver Code */ + + public static void main(String[] args) + { + String txt = ""GEEKS FOR GEEKS""; + String pat = ""GEEK""; +/* A prime number*/ + + int q = 101; +/* Function Call*/ + + search(pat, txt, q); + } +}"," '''Following program is the python implementation of +Rabin Karp Algorithm given in CLRS book + ''' '''d is the number of characters in the input alphabet''' + +d = 256 + '''pat -> pattern +txt -> text +q -> A prime number''' + +def search(pat, txt, q): + M = len(pat) + N = len(txt) + i = 0 + j = 0 + '''hash value for pattern''' + + p = 0 + + '''hash value for txt''' + + t = 0 + h = 1 + ''' The value of h would be ""pow(d, M-1)%q""''' + + for i in xrange(M-1): + h = (h*d)%q + ''' Calculate the hash value of pattern and first window + of text''' + + for i in xrange(M): + p = (d*p + ord(pat[i]))%q + t = (d*t + ord(txt[i]))%q + ''' Slide the pattern over text one by one''' + + for i in xrange(N-M+1): + ''' Check the hash values of current window of text and + pattern if the hash values match then only check + for characters on by one''' + + if p==t: + ''' Check for characters one by one''' + + for j in xrange(M): + if txt[i+j] != pat[j]: + break + else: j+=1 + ''' if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]''' + + if j==M: + print ""Pattern found at index "" + str(i) + ''' Calculate hash value for next window of text: Remove + leading digit, add trailing digit''' + + if i < N-M: + t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%q + ''' We might get negative values of t, converting it to + positive''' + + if t < 0: + t = t+q + '''Driver Code''' + +txt = ""GEEKS FOR GEEKS"" +pat = ""GEEK"" + '''A prime number''' + +q = 101 + '''Function Call''' + +search(pat,txt,q)" +Reversing a queue using recursion,"/*Java program to reverse a Queue by recursion*/ + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Stack; +public class Queue_reverse { + static Queue queue;/* Utility function to print the queue*/ + + static void Print() + { + while (!queue.isEmpty()) + { + System.out.print(queue.peek() + "" ""); + queue.remove(); + } + } +/*Recurrsive function to reverse the queue*/ + +static Queue reverseQueue(Queue q) +{ +/* Base case*/ + + if (q.isEmpty()) + return q; +/* Dequeue current item (from front) */ + + int data = q.peek(); + q.remove(); +/* Reverse remaining queue */ + + q = reverseQueue(q); +/* Enqueue current item (to rear) */ + + q.add(data); + return q; +} +/*Driver code*/ + +public static void main(String args[]) +{ + queue = new LinkedList(); + queue.add(56); + queue.add(27); + queue.add(30); + queue.add(45); + queue.add(85); + queue.add(92); + queue.add(58); + queue.add(80); + queue.add(90); + queue.add(100); + queue = reverseQueue(queue); + Print(); +} +}", +How to print maximum number of A's using given four keys,"/* A recursive Java program to print + maximum number of A's using + following four keys */ + +import java.io.*; +class GFG { +/* A recursive function that returns + the optimal length string for N keystrokes*/ + + static int findoptimal(int N) + { +/* The optimal string length is N + when N is smaller than 7*/ + + if (N <= 6) + return N; +/* Initialize result*/ + + int max = 0; +/* TRY ALL POSSIBLE BREAK-POINTS + For any keystroke N, we need to + loop from N-3 keystrokes back to + 1 keystroke to find a breakpoint + 'b' after which we will have Ctrl-A, + Ctrl-C and then only Ctrl-V all the way.*/ + + int b; + for (b = N - 3; b >= 1; b--) { +/* If the breakpoint is s at b'th + keystroke then the optimal string + would have length + (n-b-1)*screen[b-1];*/ + + int curr = (N - b - 1) * findoptimal(b); + if (curr > max) + max = curr; + } + return max; + } +/* Driver program*/ + + public static void main(String[] args) + { + int N; +/* for the rest of the array we + will rely on the previous + entries to compute new ones*/ + + for (N = 1; N <= 20; N++) + System.out.println(""Maximum Number of A's with keystrokes is "" + N + findoptimal(N)); + } +}"," '''A recursive Python3 program to print maximum +number of A's using following four keys''' '''A recursive function that returns +the optimal length string for N keystrokes''' + +def findoptimal(N): + ''' The optimal string length is + N when N is smaller than''' + + if N<= 6: + return N + ''' Initialize result''' + + maxi = 0 + ''' TRY ALL POSSIBLE BREAK-POINTS + For any keystroke N, we need + to loop from N-3 keystrokes + back to 1 keystroke to find + a breakpoint 'b' after which we + will have Ctrl-A, Ctrl-C and then + only Ctrl-V all the way.''' + + for b in range(N-3, 0, -1): + + '''If the breakpoint is s at b'th + keystroke then the optimal string + would have length + (n-b-1)*screen[b-1];''' + + curr =(N-b-1)*findoptimal(b) + if curr>maxi: + maxi = curr + return maxi '''Driver program''' + +if __name__=='__main__': + '''for the rest of the array we will +rely on the previous +entries to compute new ones''' + + for n in range(1, 21): + print('Maximum Number of As with ', n, 'keystrokes is ', findoptimal(n)) +" +Find root of the tree where children id sum for every node is given,"/*Find root of tree where children +sum for every node id is given.*/ + +class GFG +{ + static class pair + { + int first, second; + public pair(int first, int second) + { + this.first = first; + this.second = second; + } + } + static int findRoot(pair arr[], int n) + { +/* Every node appears once as an id, and + every node except for the root appears + once in a sum. So if we subtract all + the sums from all the ids, we're left + with the root id.*/ + + int root = 0; + for (int i = 0; i < n; i++) + { + root += (arr[i].first - arr[i].second); + } + return root; + } +/* Driver code*/ + + public static void main(String[] args) + { + pair arr[] = {new pair(1, 5), new pair(2, 0), + new pair(3, 0), new pair(4, 0), + new pair(5, 5), new pair(6, 5)}; + int n = arr.length; + System.out.printf(""%d\n"", findRoot(arr, n)); + } +}"," '''Find root of tree where children +sum for every node id is given''' + +def findRoot(arr, n) : + ''' Every node appears once as an id, and + every node except for the root appears + once in a sum. So if we subtract all + the sums from all the ids, we're left + with the root id.''' + + root = 0 + for i in range(n): + root += (arr[i][0] - arr[i][1]) + return root + '''Driver Code''' + +if __name__ == '__main__': + arr = [[1, 5], [2, 0], + [3, 0], [4, 0], + [5, 5], [6, 5]] + n = len(arr) + print(findRoot(arr, n))" +Count of n digit numbers whose sum of digits equals to given sum,"/*Java program to Count of n digit numbers +whose sum of digits equals to given sum*/ + +public class GFG { + private static void findCount(int n, int sum) { +/* in case n = 2 start is 10 and end is (100-1) = 99*/ + + int start = (int) Math.pow(10, n-1); + int end = (int) Math.pow(10, n)-1; + int count = 0; + int i = start; + while(i < end) { + int cur = 0; + int temp = i; + while( temp != 0) { + cur += temp % 10; + temp = temp / 10; + } + if(cur == sum) { + count++; + i += 9; + }else + i++; + } + System.out.println(count); + + } +/*Driver Code*/ + + public static void main(String[] args) { + int n = 3; + int sum = 5; + findCount(n,sum); + } +}"," '''Python3 program to Count of n digit numbers +whose sum of digits equals to given sum''' + +import math +def findCount(n, sum): ''' in case n = 2 start is 10 and + end is (100-1) = 99''' + + start = math.pow(10, n - 1); + end = math.pow(10, n) - 1; + count = 0; + i = start; + while(i <= end): + cur = 0; + temp = i; + while(temp != 0): + cur += temp % 10; + temp = temp // 10; + if(cur == sum): + count = count + 1; + i += 9; + else: + i = i + 1; + print(count); + '''Driver Code''' + +n = 3; +sum = 5; +findCount(n, sum);" +Space optimization using bit manipulations,"/*Java code to for marking multiples*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* index >> 5 corresponds to dividing index by 32 + index & 31 corresponds to modulo operation of + index by 32 + Function to check value of bit position whether + it is zero or one*/ + + static boolean checkbit(int array[], int index) + { + int val = array[index >> 5] & (1 << (index & 31)); + if (val == 0) + return false; + return true; + } +/* Sets value of bit for corresponding index*/ + + static void setbit(int array[], int index) + { + array[index >> 5] |= (1 << (index & 31)); + } +/* Driver code*/ + + public static void main(String args[]) + { + int a = 2, b = 10; + int size = Math.abs(b-a); +/* Size that will be used is actual_size/32 + ceil is used to initialize the array with + positive number*/ + + size = (int)Math.ceil((double)size / 32); +/* Array is dynamically initialized as + we are calculating size at run time*/ + + int[] array = new int[size]; +/* Iterate through every index from a to b and + call setbit() if it is a multiple of 2 or 5*/ + + for (int i = a; i <= b; i++) + if (i % 2 == 0 || i % 5 == 0) + setbit(array, i - a); + System.out.println(""MULTIPLES of 2 and 5:""); + for (int i = a; i <= b; i++) + if (checkbit(array, i - a)) + System.out.print(i + "" ""); + } +}"," '''Python3 code to for marking multiples''' + +import math + '''index >> 5 corresponds to dividing index by 32 +index & 31 corresponds to modulo operation of +index by 32 +Function to check value of bit position whether +it is zero or one''' + +def checkbit( array, index): + return array[index >> 5] & (1 << (index & 31)) + '''Sets value of bit for corresponding index''' + +def setbit( array, index): + array[index >> 5] |= (1 << (index & 31)) + '''Driver code''' + +a = 2 +b = 10 +size = abs(b - a) + '''Size that will be used is actual_size/32 +ceil is used to initialize the array with +positive number''' + +size = math.ceil(size / 32) + '''Array is dynamically initialized as +we are calculating size at run time''' + +array = [0 for i in range(size)] + '''Iterate through every index from a to b and +call setbit() if it is a multiple of 2 or 5''' + +for i in range(a, b + 1): + if (i % 2 == 0 or i % 5 == 0): + setbit(array, i - a) +print(""MULTIPLES of 2 and 5:"") +for i in range(a, b + 1): + if (checkbit(array, i - a)): + print(i, end = "" "")" +Check whether a given binary tree is perfect or not,"/*Java program to check whether a given +Binary Tree is Perfect or not */ + +class GfG { +/* Tree node structure */ + +static class Node +{ + int key; + Node left, right; +} +/*Returns depth of leftmost leaf. */ + +static int findADepth(Node node) +{ +int d = 0; +while (node != null) +{ + d++; + node = node.left; +} +return d; +} +/* This function tests if a binary tree is perfect +or not. It basically checks for two things : +1) All leaves are at same level +2) All internal nodes have two children */ + +static boolean isPerfectRec(Node root, int d, int level) +{ +/* An empty tree is perfect */ + + if (root == null) + return true; +/* If leaf node, then its depth must be same as + depth of all other leaves. */ + + if (root.left == null && root.right == null) + return (d == level+1); +/* If internal node and one child is empty */ + + if (root.left == null || root.right == null) + return false; +/* Left and right subtrees must be perfect. */ + + return isPerfectRec(root.left, d, level+1) && isPerfectRec(root.right, d, level+1); +} +/*Wrapper over isPerfectRec() */ + +static boolean isPerfect(Node root) +{ +int d = findADepth(root); +return isPerfectRec(root, d, 0); +} +/* Helper function that allocates a new node with the +given key and NULL left and right pointer. */ + +static Node newNode(int k) +{ + Node node = new Node(); + node.key = k; + node.right = null; + node.left = null; + return node; +} +/*Driver Program */ + +public static void main(String args[]) +{ + Node root = null; + root = newNode(10); + root.left = newNode(20); + root.right = newNode(30); + root.left.left = newNode(40); + root.left.right = newNode(50); + root.right.left = newNode(60); + root.right.right = newNode(70); + if (isPerfect(root) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Python3 program to check whether a +given Binary Tree is Perfect or not''' + + '''Returns depth of leftmost leaf. ''' + +def findADepth(node): + d = 0 + while (node != None): + d += 1 + node = node.left + return d + '''This function tests if a binary tree +is perfect or not. It basically checks +for two things : +1) All leaves are at same level +2) All internal nodes have two children ''' + +def isPerfectRec(root, d, level = 0): + ''' An empty tree is perfect ''' + + if (root == None): + return True + ''' If leaf node, then its depth must + be same as depth of all other leaves. ''' + + if (root.left == None and root.right == None): + return (d == level + 1) + ''' If internal node and one child is empty ''' + + if (root.left == None or root.right == None): + return False + ''' Left and right subtrees must be perfect. ''' + + return (isPerfectRec(root.left, d, level + 1) and + isPerfectRec(root.right, d, level + 1)) + '''Wrapper over isPerfectRec() ''' + +def isPerfect(root): + d = findADepth(root) + return isPerfectRec(root, d) + '''Helper class that allocates a new +node with the given key and None +left and right pointer. ''' + +class newNode: + def __init__(self, k): + self.key = k + self.right = self.left = None '''Driver Code ''' + +if __name__ == '__main__': + root = None + root = newNode(10) + root.left = newNode(20) + root.right = newNode(30) + root.left.left = newNode(40) + root.left.right = newNode(50) + root.right.left = newNode(60) + root.right.right = newNode(70) + if (isPerfect(root)): + print(""Yes"") + else: + print(""No"")" +Find largest d in array such that a + b + c = d,"/*A hashing based Java program to find largest d +such that a + b + c = d.*/ + +import java.util.HashMap; +import java.lang.Math; +/*To store and retrieve indices pair i & j*/ + +class Indexes +{ + int i, j; + Indexes(int i, int j) + { + this.i = i; + this.j = j; + } + int getI() + { + return i; + } + int getJ() + { + return j; + } +} +class GFG { +/* The function finds four elements with given sum X*/ + + static int findFourElements(int[] arr, int n) + { + HashMap map = new HashMap<>(); +/* Store sums (a+b) of all pairs (a,b) in a + hash table*/ + + for (int i = 0; i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { + map.put(arr[i] + arr[j], new Indexes(i, j)); + } + } + int d = Integer.MIN_VALUE; +/* Traverse through all pairs and find (d -c) + is present in hash table*/ + + for (int i = 0; i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { + int abs_diff = Math.abs(arr[i] - arr[j]); +/* If d - c is present in hash table,*/ + + if (map.containsKey(abs_diff)) + { + Indexes indexes = map.get(abs_diff); +/* Making sure that all elements are + distinct array elements and an element + is not considered more than once.*/ + + if (indexes.getI() != i && indexes.getI() != j && + indexes.getJ() != i && indexes.getJ() != j) + { + d = Math.max(d, Math.max(arr[i], arr[j])); + } + } + } + } + return d; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 2, 3, 5, 7, 12 }; + int n = arr.length; + int res = findFourElements(arr, n); + if (res == Integer.MIN_VALUE) + System.out.println(""No Solution""); + else + System.out.println(res); + } +}"," '''A hashing based Python3 program to find +largest d, such that a + b + c = d.''' + + '''The function finds four elements +with given sum X''' + +def findFourElements(arr, n): + mp = dict() ''' Store sums (a+b) of all pairs (a,b) in a + hash table''' + + + for i in range(n - 1): + for j in range(i + 1, n): + mp[arr[i] + arr[j]] =(i, j) + ''' Traverse through all pairs and find (d -c) + is present in hash table''' + + d = -10**9 + for i in range(n - 1): + for j in range(i + 1, n): + abs_diff = abs(arr[i] - arr[j]) + ''' If d - c is present in hash table,''' + + if abs_diff in mp.keys(): + ''' Making sure that all elements are + distinct array elements and an element + is not considered more than once.''' + + p = mp[abs_diff] + if (p[0] != i and p[0] != j and + p[1] != i and p[1] != j): + d = max(d, max(arr[i], arr[j])) + return d + '''Driver Code''' + +arr = [2, 3, 5, 7, 12] +n = len(arr) +res = findFourElements(arr, n) +if (res == -10**9): + print(""No Solution."") +else: + print(res)" +Find minimum number of merge operations to make an array palindrome,"/*Java program to find number of operations +to make an array palindrome*/ + +class GFG +{ +/* Returns minimum number of count operations + required to make arr[] palindrome*/ + + static int findMinOps(int[] arr, int n) + { +/*Initialize result*/ + +int ans = 0; +/* Start from two corners*/ + + for (int i=0,j=n-1; i<=j;) + { +/* If corner elements are same, + problem reduces arr[i+1..j-1]*/ + + if (arr[i] == arr[j]) + { + i++; + j--; + } +/* If left element is greater, then + we merge right two elements*/ + + else if (arr[i] > arr[j]) + { +/* need to merge from tail.*/ + + j--; + arr[j] += arr[j+1] ; + ans++; + } +/* Else we merge left two elements*/ + + else + { + i++; + arr[i] += arr[i-1]; + ans++; + } + } + return ans; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + int arr[] = new int[]{1, 4, 5, 9, 1} ; + System.out.println(""Count of minimum operations is ""+ + findMinOps(arr, arr.length)); + } +}"," '''Python program to find number of operations +to make an array palindrome + ''' '''Returns minimum number of count operations +required to make arr[] palindrome''' + +def findMinOps(arr, n): + '''Initialize result''' + + ans = 0 ''' Start from two corners''' + + i,j = 0,n-1 + while i<=j: + ''' If corner elements are same, + problem reduces arr[i+1..j-1]''' + + if arr[i] == arr[j]: + i += 1 + j -= 1 + ''' If left element is greater, then + we merge right two elements''' + + elif arr[i] > arr[j]: + ''' need to merge from tail.''' + + j -= 1 + arr[j] += arr[j+1] + ans += 1 + ''' Else we merge left two elements''' + + else: + i += 1 + arr[i] += arr[i-1] + ans += 1 + return ans + '''Driver program to test above''' + +arr = [1, 4, 5, 9, 1] +n = len(arr) +print(""Count of minimum operations is "" + str(findMinOps(arr, n)))" +Boundary elements of a Matrix,"/*JAVA Code for Boundary elements of a Matrix*/ + +class GFG { + public static void printBoundary(int a[][], int m, + int n) + { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i == 0) + System.out.print(a[i][j] + "" ""); + else if (i == m - 1) + System.out.print(a[i][j] + "" ""); + else if (j == 0) + System.out.print(a[i][j] + "" ""); + else if (j == n - 1) + System.out.print(a[i][j] + "" ""); + else + System.out.print("" ""); + } + System.out.println(""""); + } + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; + printBoundary(a, 4, 4); + } +}"," '''Python program to print boundary element +of the matrix.''' + +MAX = 100 +def printBoundary(a, m, n): + for i in range(m): + for j in range(n): + if (i == 0): + print a[i][j], + elif (i == m-1): + print a[i][j], + elif (j == 0): + print a[i][j], + elif (j == n-1): + print a[i][j], + else: + print "" "", + print + '''Driver code''' + +a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ] +printBoundary(a, 4, 4)" +Inorder Successor of a node in Binary Tree,"/*Java program to find inorder successor of a node.*/ + +/*structure of a Binary Node.*/ + +class Node { + int data; + Node left, right; + Node(int data) { + this.data = data; + left = null; right = null; + } +} +/*class to find inorder successor of +a node */ + +class InorderSuccessor { + Node root; +/* to change previous node*/ + + static class PreviousNode { + Node pNode; + PreviousNode() { + pNode = null; + } + } +/* function to find inorder successor of + a node */ + + private void inOrderSuccessorOfBinaryTree(Node root, + PreviousNode pre, int searchNode) + { +/* Case1: If right child is not NULL */ + + if(root.right != null) + inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); +/* Case2: If root data is equal to search node*/ + + if(root.data == searchNode) + System.out.println(""inorder successor of "" + searchNode + "" is: "" + + (pre.pNode != null ? pre.pNode.data : ""null"")); + pre.pNode = root; + if(root.left != null) + inOrderSuccessorOfBinaryTree(root.left, pre, searchNode); + } +/* Driver program to test above functions */ + + public static void main(String[] args) + { + InorderSuccessor tree = new InorderSuccessor(); +/* Let's construct the binary tree + as shown in above diagram */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(6); +/* Case 1*/ + + tree.inOrderSuccessorOfBinaryTree(tree.root, + new PreviousNode(), 3); +/* Case 2*/ + + tree.inOrderSuccessorOfBinaryTree(tree.root, + new PreviousNode(), 4); +/* Case 3*/ + + tree.inOrderSuccessorOfBinaryTree(tree.root, + new PreviousNode(), 6); + } +}"," '''Python3 program to find inorder successor.''' + '''A Binary Tree Node ''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to create a new Node.''' + +def newNode(val): + temp = Node(0) + temp.data = val + temp.left = None + temp.right = None + return temp + '''function that prints the inorder successor +of a target node. next will point the last +tracked node, which will be the answer.''' + +def inorderSuccessor(root, target_node): + global next + ''' if root is None then return''' + + if(root == None): + return + inorderSuccessor(root.right, target_node) + ''' if target node found, then + enter this condition''' + + if(root.data == target_node.data): + if(next == None): + print (""inorder successor of"", + root.data , "" is: None"") + else: + print ( ""inorder successor of"", + root.data , ""is:"", next.data) + next = root + inorderSuccessor(root.left, target_node) +next = None '''Driver Code''' + +if __name__ == '__main__': + ''' Let's construct the binary tree + as shown in above diagram.''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.right.right = newNode(6) + ''' Case 1 ''' + + next = None + inorderSuccessor(root, root.right) + ''' case 2 ''' + + next = None + inorderSuccessor(root, root.left.left) + ''' case 3 ''' + + next = None + inorderSuccessor(root, root.right.right)" +Count subtrees that sum up to a given value x only using single recursive function,"/*Java program to find if +there is a subtree with +given sum*/ + +import java.util.*; +class GFG +{ +/*structure of a node +of binary tree*/ + +static class Node +{ + int data; + Node left, right; +} +static class INT +{ + int v; + INT(int a) + { + v = a; + } +} +/*function to get a new node*/ + +static Node getNode(int data) +{ +/* allocate space*/ + + Node newNode = new Node(); +/* put in the data*/ + + newNode.data = data; + newNode.left = newNode.right = null; + return newNode; +} +/*function to count subtress that +sum up to a given value x*/ + +static int countSubtreesWithSumX(Node root, + INT count, int x) +{ +/* if tree is empty*/ + + if (root == null) + return 0; +/* sum of nodes in the left subtree*/ + + int ls = countSubtreesWithSumX(root.left, + count, x); +/* sum of nodes in the right subtree*/ + + int rs = countSubtreesWithSumX(root.right, + count, x); +/* sum of nodes in the subtree + rooted with 'root.data'*/ + + int sum = ls + rs + root.data; +/* if true*/ + + if (sum == x) + count.v++; +/* return subtree's nodes sum*/ + + return sum; +} +/*utility function to +count subtress that +sum up to a given value x*/ + +static int countSubtreesWithSumXUtil(Node root, + int x) +{ +/* if tree is empty*/ + + if (root == null) + return 0; + INT count = new INT(0); +/* sum of nodes in the left subtree*/ + + int ls = countSubtreesWithSumX(root.left, + count, x); +/* sum of nodes in the right subtree*/ + + int rs = countSubtreesWithSumX(root.right, + count, x); +/* if tree's nodes sum == x*/ + + if ((ls + rs + root.data) == x) + count.v++; +/* required count of subtrees*/ + + return count.v; +} +/*Driver Code*/ + +public static void main(String args[]) +{ + /* binary tree creation + 5 + / \ + -10 3 + / \ / \ + 9 8 -4 7 + */ + + Node root = getNode(5); + root.left = getNode(-10); + root.right = getNode(3); + root.left.left = getNode(9); + root.left.right = getNode(8); + root.right.left = getNode(-4); + root.right.right = getNode(7); + int x = 7; + System.out.println(""Count = "" + + countSubtreesWithSumXUtil(root, x)); +} +}"," '''Python3 implementation to count subtress +that Sum up to a given value x''' + + '''class to get a new node''' + +class getNode: + def __init__(self, data): ''' put in the data''' + + self.data = data + self.left = self.right = None + '''function to count subtress that +Sum up to a given value x''' + +def countSubtreesWithSumX(root, count, x): + ''' if tree is empty''' + + if (not root): + return 0 + ''' Sum of nodes in the left subtree''' + + ls = countSubtreesWithSumX(root.left, + count, x) + ''' Sum of nodes in the right subtree''' + + rs = countSubtreesWithSumX(root.right, + count, x) + ''' Sum of nodes in the subtree + rooted with 'root.data''' + ''' + Sum = ls + rs + root.data + ''' if true''' + + if (Sum == x): + count[0] += 1 + ''' return subtree's nodes Sum''' + + return Sum + '''utility function to count subtress +that Sum up to a given value x''' + +def countSubtreesWithSumXUtil(root, x): + ''' if tree is empty''' + + if (not root): + return 0 + count = [0] + ''' Sum of nodes in the left subtree''' + + ls = countSubtreesWithSumX(root.left, + count, x) + ''' Sum of nodes in the right subtree''' + + rs = countSubtreesWithSumX(root.right, + count, x) + ''' if tree's nodes Sum == x''' + + if ((ls + rs + root.data) == x): + count[0] += 1 + ''' required count of subtrees''' + + return count[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree creation + 5 + / \ + -10 3 + / \ / \ + 9 8 -4 7''' + + root = getNode(5) + root.left = getNode(-10) + root.right = getNode(3) + root.left.left = getNode(9) + root.left.right = getNode(8) + root.right.left = getNode(-4) + root.right.right = getNode(7) + x = 7 + print(""Count ="", + countSubtreesWithSumXUtil(root, x))" +Subarray with no pair sum divisible by K,"/*Java Program to find the subarray with +no pair sum divisible by K*/ + +import java.io.*; +import java.util.*; +public class GFG { +/* function to find the subarray with + no pair sum divisible by k*/ + + static void subarrayDivisibleByK(int []arr, + int n, int k) + { +/* hash table to store the remainders + obtained on dividing by K*/ + + int []mp = new int[1000]; +/* s : starting index of the + current subarray, e : ending + index of the current subarray, maxs : + starting index of the maximum + size subarray so far, maxe : ending + index of the maximum size subarray + so far*/ + + int s = 0, e = 0, maxs = 0, maxe = 0; +/* insert the first element in the set*/ + + mp[arr[0] % k]++; + for (int i = 1; i < n; i++) + { + int mod = arr[i] % k; +/* Removing starting elements of current + subarray while there is an element in + set which makes a pair with mod[i] such + that the pair sum is divisible.*/ + + while (mp[k - mod] != 0 || + (mod == 0 && mp[mod] != 0)) + { + mp[arr[s] % k]--; + s++; + } +/* include the current element in + the current subarray the ending + index of the current subarray + increments by one*/ + + mp[mod]++; + e++; +/* compare the size of the current + subarray with the maximum size so + far*/ + + if ((e - s) > (maxe - maxs)) + { + maxe = e; + maxs = s; + } + } + System.out.print(""The maximum size is "" + + (maxe - maxs + 1) + + "" and the subarray is as follows\n""); + for (int i = maxs; i <= maxe; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver Code*/ + + public static void main(String args[]) + { + int k = 3; + int []arr = {5, 10, 15, 20, 25}; + int n = arr.length; + subarrayDivisibleByK(arr, n, k); + } +}"," '''Python3 Program to find the subarray with +no pair sum divisible by K''' + + '''function to find the subarray with +no pair sum divisible by k''' + +def subarrayDivisibleByK(arr, n, k) : ''' hash table to store the remainders + obtained on dividing by K''' + + mp = [0] * 1000 + ''' s : starting index of the + current subarray, e : ending + index of the current subarray, maxs : + starting index of the maximum + size subarray so far, maxe : ending + index of the maximum size subarray + so far''' + + s = 0; e = 0; maxs = 0; maxe = 0; + ''' insert the first element in the set''' + + mp[arr[0] % k] = mp[arr[0] % k] + 1; + for i in range(1, n): + mod = arr[i] % k + ''' Removing starting elements of current + subarray while there is an element in + set which makes a pair with mod[i] such + that the pair sum is divisible.''' + + while (mp[k - mod] != 0 or (mod == 0 + and mp[mod] != 0)) : + mp[arr[s] % k] = mp[arr[s] % k] - 1 + s = s + 1 + ''' include the current element in + the current subarray the ending + index of the current subarray + increments by one''' + + mp[mod] = mp[mod] + 1 + e = e + 1 + ''' compare the size of the current + subarray with the maximum size so + far''' + + if ((e - s) > (maxe - maxs)) : + maxe = e + maxs = s + print (""The maximum size is {} and the "" + "" subarray is as follows"" + .format((maxe - maxs + 1))) + for i in range(maxs, maxe + 1) : + print (""{} "".format(arr[i]), end="""") + '''Driver Code''' + +k = 3 +arr = [5, 10, 15, 20, 25] +n = len(arr) +subarrayDivisibleByK(arr, n, k)" +A program to check if a binary tree is BST or not,," '''Python3 program to check +if a given tree is BST.''' + +import math + '''A binary tree node has data, +pointer to left child and +a pointer to right child''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None +def isBSTUtil(root, prev): + ''' traverse the tree in inorder fashion + and keep track of prev node''' + + if (root != None): + if (isBSTUtil(root.left, prev) == True): + return False + ''' Allows only distinct valued nodes''' + + if (prev != None and + root.data <= prev.data): + return False + prev = root + return isBSTUtil(root.right, prev) + return True +def isBST(root): + prev = None + return isBSTUtil(root, prev) + '''Driver Code''' + +if __name__ == '__main__': + root = Node(3) + root.left = Node(2) + root.right = Node(5) + root.right.left = Node(1) + root.right.right = Node(4) + if (isBST(root) == None): + print(""Is BST"") + else: + print(""Not a BST"")" +Boolean Parenthesization Problem | DP-37,"import java.io.*; +import java.util.*; +class GFG { +/*CountWays function*/ + + public static int countWays(int N, String S) + { + int dp[][][] = new int[N + 1][N + 1][2]; + for (int row[][] : dp) + for (int col[] : row) + Arrays.fill(col, -1); + return parenthesis_count(S, 0, N - 1, 1, dp); + } +/* Base Condition*/ + + public static int parenthesis_count(String str, int i, + int j, int isTrue, + int[][][] dp) + { + if (i > j) + return 0; + if (i == j) + { + if (isTrue == 1) + { + return (str.charAt(i) == 'T') ? 1 : 0; + } + else + { + return (str.charAt(i) == 'F') ? 1 : 0; + } + } + if (dp[i][j][isTrue] != -1) + return dp[i][j][isTrue]; + int temp_ans = 0; + int leftTrue, rightTrue, leftFalse, rightFalse; + for (int k = i + 1; k <= j - 1; k = k + 2) + { + if (dp[i][k - 1][1] != -1) + leftTrue = dp[i][k - 1][1]; + else + { +/* Count number of True in left Partition*/ + + leftTrue = parenthesis_count(str, i, k - 1, + 1, dp); + } + if (dp[i][k - 1][0] != -1) + leftFalse = dp[i][k - 1][0]; + else + { +/* Count number of False in left Partition*/ + + leftFalse = parenthesis_count(str, i, k - 1, + 0, dp); + } + if (dp[k + 1][j][1] != -1) + rightTrue = dp[k + 1][j][1]; + else + { +/* Count number of True in right Partition*/ + + rightTrue = parenthesis_count(str, k + 1, j, + 1, dp); + } + if (dp[k + 1][j][0] != -1) + rightFalse = dp[k + 1][j][0]; + else + { +/* Count number of False in right Partition*/ + + rightFalse = parenthesis_count(str, k + 1, + j, 0, dp); + } +/* Evaluate AND operation*/ + + if (str.charAt(k) == '&') + { + if (isTrue == 1) + { + temp_ans + = temp_ans + leftTrue * rightTrue; + } + else + { + temp_ans = temp_ans + + leftTrue * rightFalse + + leftFalse * rightTrue + + leftFalse * rightFalse; + } + } +/* Evaluate OR operation*/ + + else if (str.charAt(k) == '|') + { + if (isTrue == 1) + { + temp_ans = temp_ans + + leftTrue * rightTrue + + leftTrue * rightFalse + + leftFalse * rightTrue; + } + else + { + temp_ans + = temp_ans + leftFalse * rightFalse; + } + } +/* Evaluate XOR operation*/ + + else if (str.charAt(k) == '^') + { + if (isTrue == 1) + { + temp_ans = temp_ans + + leftTrue * rightFalse + + leftFalse * rightTrue; + } + else + { + temp_ans = temp_ans + + leftTrue * rightTrue + + leftFalse * rightFalse; + } + } + dp[i][j][isTrue] = temp_ans; + } + return temp_ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + String symbols = ""TTFT""; + String operators = ""|&^""; + StringBuilder S = new StringBuilder(); + int j = 0; + for (int i = 0; i < symbols.length(); i++) + { + S.append(symbols.charAt(i)); + if (j < operators.length()) + S.append(operators.charAt(j++)); + } +/* We obtain the string T|T&F^T*/ + + int N = S.length(); +/* There are 4 ways + ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and + (T|((T&F)^T))*/ + + System.out.println(countWays(N, S.toString())); + } +}"," '''CountWays function''' + +def countWays(N, S) : + dp = [[[-1 for k in range(2)] for i in range(N + 1)] for j in range(N + 1)] + return parenthesis_count(S, 0, N - 1, 1, dp) + ''' Base Condition''' + +def parenthesis_count(Str, i, j, isTrue, dp) : + if (i > j) : + return 0 + if (i == j) : + if (isTrue == 1) : + return 1 if Str[i] == 'T' else 0 + else : + return 1 if Str[i] == 'F' else 0 + if (dp[i][j][isTrue] != -1) : + return dp[i][j][isTrue] + temp_ans = 0 + for k in range(i + 1, j, 2) : + if (dp[i][k - 1][1] != -1) : + leftTrue = dp[i][k - 1][1] + else : + ''' Count number of True in left Partition''' + + leftTrue = parenthesis_count(Str, i, k - 1, 1, dp) + if (dp[i][k - 1][0] != -1) : + leftFalse = dp[i][k - 1][0] + else : + ''' Count number of False in left Partition''' + + leftFalse = parenthesis_count(Str, i, k - 1, 0, dp) + if (dp[k + 1][j][1] != -1) : + rightTrue = dp[k + 1][j][1] + else : + ''' Count number of True in right Partition''' + + rightTrue = parenthesis_count(Str, k + 1, j, 1, dp) + if (dp[k + 1][j][0] != -1) : + rightFalse = dp[k + 1][j][0] + else : + ''' Count number of False in right Partition''' + + rightFalse = parenthesis_count(Str, k + 1, j, 0, dp) + ''' Evaluate AND operation''' + + if (Str[k] == '&') : + if (isTrue == 1) : + temp_ans = temp_ans + leftTrue * rightTrue + else : + temp_ans = temp_ans + leftTrue * rightFalse + leftFalse * rightTrue + leftFalse * rightFalse + ''' Evaluate OR operation''' + + elif (Str[k] == '|') : + if (isTrue == 1) : + temp_ans = temp_ans + leftTrue * rightTrue + leftTrue * rightFalse + leftFalse * rightTrue + else : + temp_ans = temp_ans + leftFalse * rightFalse + ''' Evaluate XOR operation''' + + elif (Str[k] == '^') : + if (isTrue == 1) : + temp_ans = temp_ans + leftTrue * rightFalse + leftFalse * rightTrue + else : + temp_ans = temp_ans + leftTrue * rightTrue + leftFalse * rightFalse + dp[i][j][isTrue] = temp_ans + return temp_ans + ''' Driver code''' + +symbols = ""TTFT"" +operators = ""|&^"" +S = """" +j = 0 +for i in range(len(symbols)) : + S = S + symbols[i] + if (j < len(operators)) : + S = S + operators[j] + j += 1 + '''We obtain the string T|T&F^T''' + +N = len(S) + '''There are 4 ways +((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and +(T|((T&F)^T))''' + +print(countWays(N, S))" +Find first non matching leaves in two binary trees,"/*Java program to find first leaves that are +not same. */ + +import java.util.*; +class GfG { +/*Tree node */ + +static class Node +{ + int data; + Node left, right; +} +/*Utility method to create a new node */ + +static Node newNode(int x) +{ + Node temp = new Node(); + temp.data = x; + temp.left = null; + temp.right = null; + return temp; +} +static boolean isLeaf(Node t) +{ + return ((t.left == null) && (t.right == null)); +} +/*Prints the first non-matching leaf node in +two trees if it exists, else prints nothing. */ + +static void findFirstUnmatch(Node root1, Node root2) +{ +/* If any of the tree is empty */ + + if (root1 == null || root2 == null) + return; +/* Create two stacks for preorder traversals */ + + Stack s1 = new Stack (); + Stack s2 = new Stack (); + s1.push(root1); + s2.push(root2); + while (!s1.isEmpty() || !s2.isEmpty()) + { +/* If traversal of one tree is over + and other tree still has nodes. */ + + if (s1.isEmpty() || s2.isEmpty() ) + return; +/* Do iterative traversal of first tree + and find first lead node in it as ""temp1"" */ + + Node temp1 = s1.peek(); + s1.pop(); + while (temp1 != null && isLeaf(temp1) != true) + { +/* pushing right childfirst so that + left child comes first while popping. */ + + s1.push(temp1.right); + s1.push(temp1.left); + temp1 = s1.peek(); + s1.pop(); + } +/* Do iterative traversal of second tree + and find first lead node in it as ""temp2"" */ + + Node temp2 = s2.peek(); + s2.pop(); + while (temp2 != null && isLeaf(temp2) != true) + { + s2.push(temp2.right); + s2.push(temp2.left); + temp2 = s2.peek(); + s2.pop(); + } +/* If we found leaves in both trees */ + + if (temp1 != null && temp2 != null ) + { + if (temp1.data != temp2.data ) + { + System.out.println(temp1.data+"" ""+temp2.data); + return; + } + } + } +} +/*Driver code */ + +public static void main(String[] args) +{ + Node root1 = newNode(5); + root1.left = newNode(2); + root1.right = newNode(7); + root1.left.left = newNode(10); + root1.left.right = newNode(11); + Node root2 = newNode(6); + root2.left = newNode(10); + root2.right = newNode(15); + findFirstUnmatch(root1,root2); +} +}"," '''Python3 program to find first leaves +that are not same.''' + '''Utility function to create a +new tree Node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None +def isLeaf(t): + return ((t.left == None) and + (t.right == None)) + '''Prints the first non-matching leaf node in +two trees if it exists, else prints nothing. ''' + +def findFirstUnmatch(root1, root2) : + ''' If any of the tree is empty ''' + + if (root1 == None or root2 == None) : + return + ''' Create two stacks for preorder + traversals ''' + + s1 = [] + s2 = [] + s1.insert(0, root1) + s2.insert(0, root2) + while (len(s1) or len(s2)) : + ''' If traversal of one tree is over + and other tree still has nodes. ''' + + if (len(s1) == 0 or len(s2) == 0) : + return + ''' Do iterative traversal of first + tree and find first lead node + in it as ""temp1"" ''' + + temp1 = s1[0] + s1.pop(0) + while (temp1 and not isLeaf(temp1)) : + ''' pushing right childfirst so that + left child comes first while popping. ''' + + s1.insert(0, temp1.right) + s1.insert(0, temp1.left) + temp1 = s1[0] + s1.pop(0) + ''' Do iterative traversal of second tree + and find first lead node in it as ""temp2"" ''' + + temp2 = s2[0] + s2.pop(0) + while (temp2 and not isLeaf(temp2)) : + s2.insert(0, temp2.right) + s2.insert(0, temp2.left) + temp2 = s2[0] + s2.pop(0) + ''' If we found leaves in both trees ''' + + if (temp1 != None and temp2 != None ) : + if (temp1.data != temp2.data ) : + print(""First non matching leaves :"", + temp1.data, """", temp2.data ) + return + '''Driver Code ''' + +if __name__ == '__main__': + root1 = newNode(5) + root1.left = newNode(2) + root1.right = newNode(7) + root1.left.left = newNode(10) + root1.left.right = newNode(11) + root2 = newNode(6) + root2.left = newNode(10) + root2.right = newNode(15) + findFirstUnmatch(root1,root2)" +Iterative Search for a key 'x' in Binary Tree,"/*Iterative level order traversal +based method to search in Binary Tree */ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, +left child and right child */ + +static class node +{ + int data; + node left; + node right; + /* Constructor that allocates a new node with the + given data and null left and right pointers. */ + + node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } +}; +/*An iterative process to search +an element x in a given binary tree */ + +static boolean iterativeSearch(node root, int x) +{ +/* Base Case */ + + if (root == null) + return false; +/* Create an empty queue for + level order traversal */ + + Queue q = new LinkedList(); +/* Enqueue Root and initialize height */ + + q.add(root); +/* Queue based level order traversal */ + + while (q.size() > 0) + { +/* See if current node is same as x */ + + node node = q.peek(); + if (node.data == x) + return true; +/* Remove current node and enqueue its children */ + + q.remove(); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + } + return false; +} +/*Driver code */ + +public static void main(String ags[]) +{ + node NewRoot = null; + node root = new node(2); + root.left = new node(7); + root.right = new node(5); + root.left.right = new node(6); + root.left.right.left = new node(1); + root.left.right.right = new node(11); + root.right.right = new node(9); + root.right.right.left = new node(4); + System.out.print((iterativeSearch(root, 6)? + ""Found\n"": ""Not Found\n"")); + System.out.print((iterativeSearch(root, 12)? + ""Found\n"": ""Not Found\n"")); +} +}"," '''Iterative level order traversal based +method to search in Binary Tree +importing Queue''' + +from queue import Queue + '''Helper function that allocates a +new node with the given data and +None left and right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''An iterative process to search an +element x in a given binary tree ''' + +def iterativeSearch(root, x): + ''' Base Case ''' + + if (root == None): + return False + ''' Create an empty queue for level + order traversal ''' + + q = Queue() + ''' Enqueue Root and initialize height ''' + + q.put(root) + ''' Queue based level order traversal ''' + + while (q.empty() == False): + ''' See if current node is same as x ''' + + node = q.queue[0] + if (node.data == x): + return True + ''' Remove current node and + enqueue its children ''' + + q.get() + if (node.left != None): + q.put(node.left) + if (node.right != None): + q.put(node.right) + return False + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(2) + root.left = newNode(7) + root.right = newNode(5) + root.left.right = newNode(6) + root.left.right.left = newNode(1) + root.left.right.right = newNode(11) + root.right.right = newNode(9) + root.right.right.left = newNode(4) + if iterativeSearch(root, 6): + print(""Found"") + else: + print(""Not Found"") + if iterativeSearch(root, 12): + print(""Found"") + else: + print(""Not Found"")" +Minimum number of elements to add to make median equals x,"/*Java program to find minimum number +of elements to add so that its +median equals x.*/ + +import java.util.*; +import java.lang.*; + +class GFG { + + public static int minNumber(int a[], + int n, int x) + { + int l = 0, h = 0, e = 0; + for (int i = 0; i < n; i++) + { + +/* no. of elements equals to + x, that is, e.*/ + + if (a[i] == x) + e++; + +/* no. of elements greater + than x, that is, h.*/ + + else if (a[i] > x) + h++; + +/* no. of elements smaller + than x, that is, l.*/ + + else if (a[i] < x) + l++; + } + + int ans = 0; + if (l > h) + ans = l - h; + else if (l < h) + ans = h - l - 1; + +/* subtract the no. of elements + that are equal to x.*/ + + return ans + 1 - e; + } + +/* Driven Program*/ + + public static void main(String[] args) + { + int x = 10; + int a[] = { 10, 20, 30 }; + int n = a.length; + System.out.println( + minNumber(a, n, x)); + } +} + + +"," '''Python3 program to find minimum number +of elements to add so that its median +equals x.''' + + +def minNumber (a, n, x): + l = 0 + h = 0 + e = 0 + for i in range(n): + + ''' no. of elements equals to x, + that is, e.''' + + if a[i] == x: + e+=1 + + ''' no. of elements greater than x, + that is, h.''' + + elif a[i] > x: + h+=1 + + ''' no. of elements smaller than x, + that is, l.''' + + elif a[i] < x: + l+=1 + + ans = 0; + if l > h: + ans = l - h + elif l < h: + ans = h - l - 1; + + ''' subtract the no. of elements + that are equal to x.''' + + return ans + 1 - e + + '''Driver code''' + +x = 10 +a = [10, 20, 30] +n = len(a) +print(minNumber(a, n, x)) + + +" +Iterative method to find ancestors of a given binary tree,"/*Java program to print all +ancestors of a given key */ + +import java.util.*; +class GfG +{ +/*Structure for a tree node */ + +static class Node +{ + int data; + Node left, right; +} +/*A utility function to +create a new tree node */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return node; +} +/*Iterative Function to print +all ancestors of a given key */ + +static void printAncestors(Node root, int key) +{ + if (root == null) + return; +/* Create a stack to hold ancestors */ + + Stack st = new Stack (); +/* Traverse the complete tree in + postorder way till we find the key */ + + while (1 == 1) + { +/* Traverse the left side. While + traversing, push the nodes into + the stack so that their right + subtrees can be traversed later */ + + while (root != null && root.data != key) + { +/*push current node */ + +st.push(root); +/*move to next node */ + +root = root.left; + } +/* If the node whose ancestors + are to be printed is found, + then break the while loop. */ + + if (root != null && root.data == key) + break; +/* Check if right sub-tree exists + for the node at top If not then + pop that node because we don't + need this node any more. */ + + if (st.peek().right == null) + { + root = st.peek(); + st.pop(); +/* If the popped node is right child of top, + then remove the top as well. Left child of + the top must have processed before. */ + + while (!st.isEmpty() && st.peek().right == root) + { + root = st.peek(); + st.pop(); + } + } +/* if stack is not empty then simply + set the root as right child of + top and start traversing right + sub-tree. */ + + root = st.isEmpty() ? null : st.peek().right; + } +/* If stack is not empty, print contents of stack + Here assumption is that the key is there in tree */ + + while (!st.isEmpty()) + { + System.out.print(st.peek().data + "" ""); + st.pop(); + } +} +/*Driver code */ + +public static void main(String[] args) +{ +/* Let us construct a binary tree */ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(7); + root.left.left = newNode(3); + root.left.right = newNode(5); + root.right.left = newNode(8); + root.right.right = newNode(9); + root.left.left.left = newNode(4); + root.left.right.right = newNode(6); + root.right.right.left = newNode(10); + int key = 6; + printAncestors(root, key); +} +}"," '''Python program to print all ancestors of a given key''' + + '''A class to create a new tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Iterative Function to print all ancestors of a +given key ''' + +def printAncestors(root, key): + if (root == None): + return + ''' Create a stack to hold ancestors ''' + + st = [] + ''' Traverse the complete tree in postorder way till + we find the key ''' + + while (1): + ''' Traverse the left side. While traversing, push + the nodes into the stack so that their right + subtrees can be traversed later ''' + + while (root and root.data != key): + '''push current node ''' + + st.append(root) + + '''move to next node''' + + root = root.left + ''' If the node whose ancestors are to be printed + is found, then break the while loop. ''' + + if (root and root.data == key): + break + ''' Check if right sub-tree exists for the node at top + If not then pop that node because we don't need + this node any more. ''' + + if (st[-1].right == None): + root = st[-1] + st.pop() + ''' If the popped node is right child of top, + then remove the top as well. Left child of + the top must have processed before. ''' + + while (len(st) != 0 and st[-1].right == root): + root = st[-1] + st.pop() + ''' if stack is not empty then simply set the root + as right child of top and start traversing right + sub-tree. ''' + + root = None if len(st) == 0 else st[-1].right + ''' If stack is not empty, print contents of stack + Here assumption is that the key is there in tree ''' + + while (len(st) != 0): + print(st[-1].data,end = "" "") + st.pop() + '''Driver code''' + +if __name__ == '__main__': + ''' Let us construct a binary tree ''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.left = newNode(8) + root.right.right = newNode(9) + root.left.left.left = newNode(4) + root.left.right.right = newNode(6) + root.right.right.left = newNode(10) + key = 6 + printAncestors(root, key)" +Longest Consecutive Subsequence,"/*Java program to find longest +contiguous subsequence*/ + +import java.io.*; +import java.util.*; +class GFG +{ + +/*Returns length of the longest +contiguous subsequence*/ + + static int findLongestConseqSubseq(int arr[], + int n) + {/* Sort the array*/ + + Arrays.sort(arr); + int ans = 0, count = 0; + ArrayList v = new ArrayList(); + v.add(10); +/* Insert repeated elements + only once in the vector*/ + + for (int i = 1; i < n; i++) + { + if (arr[i] != arr[i - 1]) + v.add(arr[i]); + } +/* Find the maximum length + by traversing the array*/ + + for (int i = 0; i < v.size(); i++) + { +/* Check if the current element is + equal to previous element +1*/ + + if (i > 0 &&v.get(i) == v.get(i - 1) + 1) + count++; + else + count = 1; +/* Update the maximum*/ + + ans = Math.max(ans, count); + } + return ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; + int n = arr.length; + System.out.println( + ""Length of the Longest "" + + ""contiguous subsequence is "" + + findLongestConseqSubseq(arr, n)); + } +}"," '''Python3 program to find longest +contiguous subsequence''' + + '''Returns length of the longest +contiguous subsequence''' + +def findLongestConseqSubseq(arr, n): + ans = 0 + count = 0 ''' Sort the array''' + + arr.sort() + v = [] + v.append(arr[0]) + ''' Insert repeated elements only + once in the vector''' + + for i in range(1, n): + if (arr[i] != arr[i - 1]): + v.append(arr[i]) + ''' Find the maximum length + by traversing the array''' + + for i in range(len(v)): + ''' Check if the current element is + equal to previous element +1''' + + if (i > 0 and v[i] == v[i - 1] + 1): + count += 1 + else: + count = 1 ''' Update the maximum''' + + ans = max(ans, count) + return ans + '''Driver code''' + +arr = [ 1, 2, 2, 3 ] +n = len(arr) +print(""Length of the Longest contiguous subsequence is"", + findLongestConseqSubseq(arr, n))" +"Search, insert and delete in a sorted array","/*Java program to implement binary +search in a sorted array*/ + +class Main { +/* function to implement + binary search*/ + + static int binarySearch(int arr[], int low, int high, int key) + { + if (high < low) + return -1; + /*low + (high - low)/2;*/ + + int mid = (low + high) / 2; + if (key == arr[mid]) + return mid; + if (key > arr[mid]) + return binarySearch(arr, (mid + 1), high, key); + return binarySearch(arr, low, (mid - 1), key); + } + /* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 5, 6, 7, 8, 9, 10 }; + int n, key; + n = arr.length - 1; + key = 10; + System.out.println(""Index: "" + binarySearch(arr, 0, n, key)); + } +}"," '''python 3 program to implement +binary search in sorted array''' + '''function to implement + binary search''' + +def binarySearch(arr, low, high, key): ''' low + (high - low)/2''' + + mid = (low + high)/2 + if (key == arr[int(mid)]): + return mid + if (key > arr[int(mid)]): + return binarySearch(arr, + (mid + 1), high, key) + if (key < arr[int(mid)]): + return binarySearch(arr,low, (mid-1), key) + return 0 + '''Driver program to check above functions +Let us search 3 in below array''' + +arr = [5, 6, 7, 8, 9, 10] +n = len(arr) +key = 10 +print(""Index:"", int(binarySearch(arr, 0, n-1, key) ))" +Product of maximum in first array and minimum in second,"/*Java program to calculate the +product of max element of first +array and min element of second array*/ + +import java.util.*; +import java.lang.*; +class GfG +{ +/* Function to calculate the product*/ + + public static int minMaxProduct(int arr1[], + int arr2[], + int n1, + int n2) + { +/* Initialize max of + first array*/ + + int max = arr1[0]; +/* initialize min of + second array*/ + + int min = arr2[0]; + int i; + for (i = 1; i < n1 && i < n2; ++i) + { +/* To find the maximum + element in first array*/ + + if (arr1[i] > max) + max = arr1[i]; +/* To find the minimum element + in second array*/ + + if (arr2[i] < min) + min = arr2[i]; + } +/* Process remaining elements*/ + + while (i < n1) + { + if (arr1[i] > max) + max = arr1[i]; + i++; + } + while (i < n2) + { + if (arr2[i] < min) + min = arr2[i]; + i++; + } + return max * min; + } +/* Driver Code*/ + + public static void main(String argc[]) + { + int [] arr1= new int []{ 10, 2, 3, + 6, 4, 1 }; + int [] arr2 = new int []{ 5, 1, 4, + 2, 6, 9 }; + int n1 = 6; + int n2 = 6; + System.out.println(minMaxProduct(arr1, arr2, + n1, n2)); + } +}"," '''Python3 program to find the to +calculate the product of +max element of first array +and min element of second array + ''' '''Function to calculate the product''' + +def minMaxProduct(arr1, arr2, + n1, n2) : + ''' Initialize max of first array''' + + max = arr1[0] + ''' initialize min of second array''' + + min = arr2[0] + i = 1 + while (i < n1 and i < n2) : + ''' To find the maximum + element in first array''' + + if (arr1[i] > max) : + max = arr1[i] + ''' To find the minimum + element in second array''' + + if (arr2[i] < min) : + min = arr2[i] + i += 1 + ''' Process remaining elements''' + + while (i < n1) : + if (arr1[i] > max) : + max = arr1[i] + i += 1 + while (i < n2): + if (arr2[i] < min) : + min = arr2[i] + i += 1 + return max * min + '''Driver code''' + +arr1 = [10, 2, 3, 6, 4, 1 ] +arr2 = [5, 1, 4, 2, 6, 9 ] +n1 = len(arr1) +n2 = len(arr1) +print(minMaxProduct(arr1, arr2, n1, n2))" +k-th missing element in increasing sequence which is not present in a given sequence,"/*Java program to find the k-th missing element +in a given sequence*/ + +import java.util.*; +class GFG +{ +/*Returns k-th missing element. It returns -1 if +no k is more than number of missing elements.*/ + +static int find(int a[], int b[], int k, int n1, int n2) +{ +/* Insert all elements of givens sequence b[].*/ + + LinkedHashSet s = new LinkedHashSet<>(); + for (int i = 0; i < n2; i++) + s.add(b[i]); +/* Traverse through increasing sequence and + keep track of count of missing numbers.*/ + + int missing = 0; + for (int i = 0; i < n1; i++) + { + if(!s.contains(a[i]) ) + missing++; + if (missing == k) + return a[i]; + } + return -1; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int a[] = { 0, 2, 4, 6, 8, 10, 12, 14, 15 }; + int b[] = { 4, 10, 6, 8, 12 }; + int n1 = a.length; + int n2 = b.length; + int k = 3; + System.out.println(find(a, b, k, n1, n2)); +} +}"," '''Python3 program to find the k-th +missing element in a given sequence + ''' '''Returns k-th missing element. It returns -1 if +no k is more than number of missing elements.''' + +def find(a, b, k, n1, n2): + ''' insert all elements of + given sequence b[].''' + + s = set() + for i in range(n2): + s.add(b[i]) + ''' Traverse through increasing sequence and + keep track of count of missing numbers.''' + + missing = 0 + for i in range(n1): + if a[i] not in s: + missing += 1 + if missing == k: + return a[i] + return -1 + '''Driver code''' + +a = [0, 2, 4, 6, 8, 10, 12, 14, 15] +b = [4, 10, 6, 8, 12] +n1 = len(a) +n2 = len(b) +k = 3 +print(find(a, b, k, n1, n2))" +Shortest path in a Binary Maze,"/*Java program to find the shortest +path between a given source cell +to a destination cell.*/ + +import java.util.*; +class GFG +{ +static int ROW = 9; +static int COL = 10; +/*To store matrix cell cordinates*/ + +static class Point +{ + int x; + int y; + public Point(int x, int y) + { + this.x = x; + this.y = y; + } +}; +/*A Data Structure for queue used in BFS*/ + +static class queueNode +{ +/*The cordinates of a cell*/ + +Point pt; +/*cell's distance of from the source*/ + +int dist; + public queueNode(Point pt, int dist) + { + this.pt = pt; + this.dist = dist; + } +}; +/*check whether given cell (row, col) +is a valid cell or not.*/ + +static boolean isValid(int row, int col) +{ +/* return true if row number and + column number is in range*/ + + return (row >= 0) && (row < ROW) && + (col >= 0) && (col < COL); +} +/*These arrays are used to get row and column +numbers of 4 neighbours of a given cell*/ + +static int rowNum[] = {-1, 0, 0, 1}; +static int colNum[] = {0, -1, 1, 0}; +/*function to find the shortest path between +a given source cell to a destination cell.*/ + +static int BFS(int mat[][], Point src, + Point dest) +{ +/* check source and destination cell + of the matrix have value 1*/ + + if (mat[src.x][src.y] != 1 || + mat[dest.x][dest.y] != 1) + return -1; + boolean [][]visited = new boolean[ROW][COL]; +/* Mark the source cell as visited*/ + + visited[src.x][src.y] = true; +/* Create a queue for BFS*/ + + Queue q = new LinkedList<>(); +/* Distance of source cell is 0*/ + + queueNode s = new queueNode(src, 0); +/*Enqueue source cell*/ + +q.add(s); +/* Do a BFS starting from source cell*/ + + while (!q.isEmpty()) + { + queueNode curr = q.peek(); + Point pt = curr.pt; +/* If we have reached the destination cell, + we are done*/ + + if (pt.x == dest.x && pt.y == dest.y) + return curr.dist; +/* Otherwise dequeue the front cell + in the queue and enqueue + its adjacent cells*/ + + q.remove(); + for (int i = 0; i < 4; i++) + { + int row = pt.x + rowNum[i]; + int col = pt.y + colNum[i]; +/* if adjacent cell is valid, has path + and not visited yet, enqueue it.*/ + + if (isValid(row, col) && + mat[row][col] == 1 && + !visited[row][col]) + { +/* mark cell as visited and enqueue it*/ + + visited[row][col] = true; + queueNode Adjcell = new queueNode + (new Point(row, col), + curr.dist + 1 ); + q.add(Adjcell); + } + } + } +/* Return -1 if destination cannot be reached*/ + + return -1; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int mat[][] = {{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, + { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, + { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, + { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; + Point source = new Point(0, 0); + Point dest = new Point(3, 4); + int dist = BFS(mat, source, dest); + if (dist != -1) + System.out.println(""Shortest Path is "" + dist); + else + System.out.println(""Shortest Path doesn't exist""); + } +}"," '''Python program to find the shortest +path between a given source cell +to a destination cell.''' +from collections import deque +ROW = 9 +COL = 10 '''To store matrix cell cordinates''' + +class Point: + def __init__(self,x: int, y: int): + self.x = x + self.y = y + '''A data structure for queue used in BFS''' + +class queueNode: + def __init__(self,pt: Point, dist: int): + '''The cordinates of the cell''' + + self.pt = pt + '''Cell's distance from the source''' + + self.dist = dist + '''Check whether given cell(row,col) +is a valid cell or not''' + +def isValid(row: int, col: int): + + '''return true if row number and + column number is in range''' + + return (row >= 0) and (row < ROW) and(col >= 0) and (col < COL) '''These arrays are used to get row and column +numbers of 4 neighbours of a given cell''' + +rowNum = [-1, 0, 0, 1] +colNum = [0, -1, 1, 0] + '''Function to find the shortest path between +a given source cell to a destination cell.''' + +def BFS(mat, src: Point, dest: Point): + ''' check source and destination cell + of the matrix have value 1''' + + if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1: + return -1 + visited = [[False for i in range(COL)] + for j in range(ROW)] + ''' Mark the source cell as visited''' + + visited[src.x][src.y] = True + ''' Create a queue for BFS''' + + q = deque() + ''' Distance of source cell is 0''' + + s = queueNode(src,0) + ''' Enqueue source cell''' + + q.append(s) + ''' Do a BFS starting from source cell''' + + while q: + curr = q.popleft() + pt = curr.pt ''' If we have reached the destination cell, + we are done''' + + if pt.x == dest.x and pt.y == dest.y: + return curr.dist + ''' Otherwise enqueue its adjacent cells''' + + for i in range(4): + row = pt.x + rowNum[i] + col = pt.y + colNum[i] + ''' if adjacent cell is valid, has path + and not visited yet, enqueue it.''' + + if (isValid(row,col) and + mat[row][col] == 1 and + not visited[row][col]): + + '''mark cell as visited and enqueue it''' + + visited[row][col] = True + Adjcell = queueNode(Point(row,col), + curr.dist+1) + q.append(Adjcell) ''' Return -1 if destination cannot be reached''' + + return -1 + '''Driver code''' + +def main(): + mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], + [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], + [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], + [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], + [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ], + [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], + [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ], + [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], + [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]] + source = Point(0,0) + dest = Point(3,4) + dist = BFS(mat,source,dest) + if dist!=-1: + print(""Shortest Path is"",dist) + else: + print(""Shortest Path doesn't exist"") +main()" +Hierholzer's Algorithm for directed graph,," '''Python3 program to print Eulerian circuit in given +directed graph using Hierholzer algorithm''' + +def printCircuit(adj): + ''' adj represents the adjacency list of + the directed graph + edge_count represents the number of edges + emerging from a vertex''' + + edge_count = dict() + for i in range(len(adj)): + ''' find the count of edges to keep track + of unused edges''' + + edge_count[i] = len(adj[i]) + if len(adj) == 0: + return ''' empty graph + Maintain a stack to keep vertices''' + + curr_path = [] + ''' vector to store final circuit''' + + circuit = [] + ''' start from any vertex''' + + curr_path.append(0) + curr_v = 0 ''' Current vertex''' + + while len(curr_path): + ''' If there's remaining edge''' + + if edge_count[curr_v]: + ''' Push the vertex''' + + curr_path.append(curr_v) + ''' Find the next vertex using an edge''' + + next_v = adj[curr_v][-1] + ''' and remove that edge''' + + edge_count[curr_v] -= 1 + adj[curr_v].pop() + ''' Move to next vertex''' + + curr_v = next_v + ''' back-track to find remaining circuit''' + + else: + circuit.append(curr_v) + ''' Back-tracking''' + + curr_v = curr_path[-1] + curr_path.pop() + ''' we've got the circuit, now print it in reverse''' + + for i in range(len(circuit) - 1, -1, -1): + print(circuit[i], end = """") + if i: + print("" -> "", end = """") + '''Driver Code''' + +if __name__ == ""__main__"": + ''' Input Graph 1''' + + adj1 = [0] * 3 + for i in range(3): + adj1[i] = [] + ''' Build the edges''' + + adj1[0].append(1) + adj1[1].append(2) + adj1[2].append(0) + printCircuit(adj1) + print() + ''' Input Graph 2''' + + adj2 = [0] * 7 + for i in range(7): + adj2[i] = [] + adj2[0].append(1) + adj2[0].append(6) + adj2[1].append(2) + adj2[2].append(0) + adj2[2].append(3) + adj2[3].append(4) + adj2[4].append(2) + adj2[4].append(5) + adj2[5].append(0) + adj2[6].append(4) + printCircuit(adj2) + print()" +Remove all the Even Digit Sum Nodes from a Circular Singly Linked List,"/*Java program to remove all +the Even Digit Sum Nodes from a +circular singly linked list*/ + +import java.util.*; + +class GFG{ + +/*Structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to insert a node at the beginning +of a Circular linked list*/ + +static Node push(Node head_ref, int data) +{ + +/* Create a new node and make head + as next of it.*/ + + Node ptr1 = new Node(); + + Node temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + +/* If linked list is not null then + set the next of last node*/ + + if (head_ref != null) + { + +/* Find the node before head + and update next of it.*/ + + while (temp.next != head_ref) + temp = temp.next; + + temp.next = ptr1; + } + else + +/* Point for the first node*/ + + ptr1.next = ptr1; + + head_ref = ptr1; + return head_ref; +} + +/*Function to delete the node from a +Circular Linked list*/ + +static void deleteNode(Node head_ref, Node del) +{ + Node temp = head_ref; + +/* If node to be deleted is head node*/ + + if (head_ref == del) + head_ref = del.next; + +/* Traverse list till not found + delete node*/ + + while (temp.next != del) + { + temp = temp.next; + } + +/* Copy the address of the node*/ + + temp.next = del.next; + +/* Finally, free the memory + occupied by del*/ + + del = null; + + return; +} + +/*Function to find the digit sum +for a number*/ + +static int digitSum(int num) +{ + int sum = 0; + + while (num > 0) + { + sum += (num % 10); + num /= 10; + } + return sum; +} + +/*Function to delete all the Even Digit +Sum Nodes from the singly circular +linked list*/ + +static void deleteEvenDigitSumNodes(Node head) +{ + Node ptr = head; + Node next; + +/* Traverse the list till the end*/ + + do + { + +/* If the node's data is Fibonacci, + delete node 'ptr'*/ + + if (!(digitSum(ptr.data) % 2 == 1)) + deleteNode(head, ptr); + +/* Point to the next node*/ + + next = ptr.next; + ptr = next; + } while (ptr != head); +} + +/*Function to print nodes in a +given Circular linked list*/ + +static void printList(Node head) +{ + Node temp = head; + if (head != null) + { + do + { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } while (temp != head); + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* Initialize lists as empty*/ + + Node head = null; + +/* Created linked list will be + 9.11.34.6.13.21*/ + + head = push(head, 21); + head = push(head, 13); + head = push(head, 6); + head = push(head, 34); + head = push(head, 11); + head = push(head, 9); + + deleteEvenDigitSumNodes(head); + + printList(head); +} +} + + +"," '''Python3 program to remove all +the Even Digit Sum Nodes from a +circular singly linked list''' + + + '''Structure for a node''' + +class Node: + + def __init__(self, data): + + self.data = data + self.next = None + + '''Function to insert a node at the beginning +of a Circular linked list''' + +def push(head_ref, data): + + ''' Create a new node and make head as next + of it.''' + + ptr1 = Node(data) + + temp = head_ref + ptr1.data = data + ptr1.next = head_ref + + ''' If linked list is not None then + set the next of last node''' + + if (head_ref != None): + + ''' Find the node before head + and update next of it.''' + + while (temp.next != head_ref): + temp = temp.next + + temp.next = ptr1 + + else: + + ''' Point for the first node''' + + ptr1.next = ptr1 + + head_ref = ptr1 + + return head_ref + + '''Function to deltete the node from a +Circular Linked list''' + +def delteteNode(head_ref, delt): + + temp = head_ref + + ''' If node to be delteted is head node''' + + if (head_ref == delt): + head_ref = delt.next + + ''' Traverse list till not found + deltete node''' + + while (temp.next != delt): + temp = temp.next + + ''' Copy the address of the node''' + + temp.next = delt.next + + ''' Finally, free the memory + occupied by delt''' + + del (delt) + + return + + '''Function to find the digit sum +for a number''' + +def digitSum(num): + + sum = 0 + + while (num != 0): + sum += (num % 10) + num //= 10 + + return sum + + '''Function to deltete all the Even Digit +Sum Nodes from the singly circular linked list''' + +def delteteEvenDigitSumNodes(head): + + ptr = head + next = None + + ''' Traverse the list till the end''' + + while True: + + ''' If the node's data is Fibonacci, + deltete node 'ptr''' + ''' + if (not (digitSum(ptr.data) & 1)): + delteteNode(head, ptr) + + ''' Point to the next node''' + + next = ptr.next + ptr = next + + if (ptr == head): + break + + '''Function to print nodes in a +given Circular linked list''' + +def printList(head): + + temp = head + + if (head != None): + while True: + print(temp.data, end = ' ') + temp = temp.next + + if (temp == head): + break + + '''Driver code''' + +if __name__=='__main__': + + ''' Initialize lists as empty''' + + head = None + + ''' Created linked list will be + 9.11.34.6.13.21''' + + head = push(head, 21) + head = push(head, 13) + head = push(head, 6) + head = push(head, 34) + head = push(head, 11) + head = push(head, 9) + + delteteEvenDigitSumNodes(head) + + printList(head) + + +" +Find elements which are present in first array and not in second,"/*Java simple program to +find elements which are +not present in second array*/ + +class GFG +{ +/* Function for finding elements + which are there in a[] but not + in b[].*/ + + static void findMissing(int a[], int b[], + int n, int m) + { + for (int i = 0; i < n; i++) + { + int j; + for (j = 0; j < m; j++) + if (a[i] == b[j]) + break; + if (j == m) + System.out.print(a[i] + "" ""); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = { 1, 2, 6, 3, 4, 5 }; + int b[] = { 2, 4, 3, 1, 0 }; + int n = a.length; + int m = b.length; + findMissing(a, b, n, m); + } +}"," '''Python 3 simple program to find elements +which are not present in second array + ''' '''Function for finding elements which +are there in a[] but not in b[].''' + +def findMissing(a, b, n, m): + for i in range(n): + for j in range(m): + if (a[i] == b[j]): + break + if (j == m - 1): + print(a[i], end = "" "") + '''Driver code''' + +if __name__ == ""__main__"": + a = [ 1, 2, 6, 3, 4, 5 ] + b = [ 2, 4, 3, 1, 0 ] + n = len(a) + m = len(b) + findMissing(a, b, n, m)" +Block swap algorithm for array rotation,"/*Java code for above implementation*/ + +static void leftRotate(int arr[], int d, int n) +{ +int i, j; +if(d == 0 || d == n) + return; +i = d; +j = n - d; +while (i != j) +{ +/*A is shorter*/ + if(i < j) + { + swap(arr, d-i, d+j-i, i); + j -= i; + } +/*B is shorter*/ + else + { + swap(arr, d-i, d, j); + i -= j; + } +}/*Finally, block swap A and B*/ + +swap(arr, d-i, d, i); +}"," '''Python3 code for above implementation''' + +def leftRotate(arr, d, n): + if(d == 0 or d == n): + return; + i = d + j = n - d + while (i != j): + '''A is shorter''' + + if(i < j): + swap(arr, d - i, d + j - i, i) + j -= i + '''B is shorter''' + + else: + swap(arr, d - i, d, j) + i -= j + '''Finally, block swap A and B''' + + swap(arr, d - i, d, i)" +Find the smallest positive number missing from an unsorted array | Set 1,"/*Java program to find the smallest +positive missing number*/ + +import java.util.*; + +class Main { + + /* Utility function that puts all non-positive + (0 and negative) numbers on left side of + arr[] and return count of such numbers */ + + static int segregate(int arr[], int size) + { + int j = 0, i; + for (i = 0; i < size; i++) { + if (arr[i] <= 0) { + int temp; + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +/* increment count of non-positive + integers*/ + + j++; + } + } + + return j; + } + + /* Find the smallest positive missing + number in an array that contains + all positive integers */ + + static int findMissingPositive(int arr[], int size) + { + int i; + +/* Mark arr[i] as visited by making + arr[arr[i] - 1] negative. Note that + 1 is subtracted because index start + from 0 and positive numbers start from 1*/ + + for (i = 0; i < size; i++) { + int x = Math.abs(arr[i]); + if (x - 1 < size && arr[x - 1] > 0) + arr[x - 1] = -arr[x - 1]; + } + +/* Return the first index value at which + is positive*/ + + for (i = 0; i < size; i++) + if (arr[i] > 0) +/*1 is added becuase indexes*/ + +return i + 1; + return size + 1; + } +/* Find the smallest positive missing + number in an array that contains + both positive and negative integers */ + + static int findMissing(int arr[], int size) + { +/* First separate positive and + negative numbers*/ + + int shift = segregate(arr, size); + int arr2[] = new int[size - shift]; + int j = 0; + for (int i = shift; i < size; i++) { + arr2[j] = arr[i]; + j++; + } +/* Shift the array and call + findMissingPositive for + positive part*/ + + return findMissingPositive(arr2, j); + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 0, 10, 2, -10, -20 }; + int arr_size = arr.length; + int missing = findMissing(arr, arr_size); + System.out.println(""The smallest positive missing number is "" + missing); + } +} +"," ''' Python3 program to find the +smallest positive missing number ''' + + + ''' Utility function that puts all +non-positive (0 and negative) numbers on left +side of arr[] and return count of such numbers ''' + +def segregate(arr, size): + j = 0 + for i in range(size): + if (arr[i] <= 0): + arr[i], arr[j] = arr[j], arr[i] + '''increment count of non-positive integers''' + + j += 1 + return j + + + ''' Find the smallest positive missing number +in an array that contains all positive integers ''' + +def findMissingPositive(arr, size): + + ''' Mark arr[i] as visited by + making arr[arr[i] - 1] negative. + Note that 1 is subtracted + because index start + from 0 and positive numbers start from 1''' + + for i in range(size): + if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0): + arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] + + ''' Return the first index value at which is positive''' + + for i in range(size): + if (arr[i] > 0): + + ''' 1 is added because indexes start from 0''' + + return i + 1 + return size + 1 + + ''' Find the smallest positive missing +number in an array that contains +both positive and negative integers ''' + +def findMissing(arr, size): + + ''' First separate positive and negative numbers''' + + shift = segregate(arr, size) + + ''' Shift the array and call findMissingPositive for + positive part''' + + return findMissingPositive(arr[shift:], size - shift) + + '''Driver code''' + +arr = [ 0, 10, 2, -10, -20 ] +arr_size = len(arr) +missing = findMissing(arr, arr_size) +print(""The smallest positive missing number is "", missing) + + +" +Find minimum difference between any two elements,"/*Java implementation of simple method to find +minimum difference between any pair*/ + +class GFG +{ +/* Returns minimum difference between any pair*/ + + static int findMinDiff(int[] arr, int n) + { +/* Initialize difference as infinite*/ + + int diff = Integer.MAX_VALUE; +/* Find the min diff by comparing difference + of all possible pairs in given array*/ + + for (int i=0; i arr[i]*/ + +import java.util.*; +class GFG{ + +public static void main(String[] args) +{ + int []v = {34, 8, 10, 3, 2, + 80, 30, 33, 1}; + int n = v.length; + int []maxFromEnd = new int[n + 1]; + Arrays.fill(maxFromEnd, Integer.MIN_VALUE); + +/* Create an array maxfromEnd*/ + + for (int i = v.length - 1; i >= 0; i--) + { + maxFromEnd[i] = Math.max(maxFromEnd[i + 1], + v[i]); + } + + int result = 0; + + for (int i = 0; i < v.length; i++) + { + int low = i + 1, high = v.length - 1, + ans = i; + + while (low <= high) + { + int mid = (low + high) / 2; + + if (v[i] <= maxFromEnd[mid]) + { +/* We store this as current + answer and look for further + larger number to the right side*/ + + ans = Math.max(ans, mid); + low = mid + 1; + } + else + { + high = mid - 1; + } + } + +/* Keeping a track of the + maximum difference in indices*/ + + result = Math.max(result, ans - i); + } + System.out.print(result + ""\n""); +} +} + + +"," '''Python3 program to implement +the above approach''' + + + '''For a given array arr, +calculates the maximum j – i +such that arr[j] > arr[i]''' + + +if __name__ == '__main__': + + v = [34, 8, 10, 3, + 2, 80, 30, 33, 1]; + n = len(v); + maxFromEnd = [-38749432] * (n + 1); + ''' Create an array maxfromEnd''' + + for i in range(n - 1, 0, -1): + maxFromEnd[i] = max(maxFromEnd[i + 1], + v[i]); + + result = 0; + + for i in range(0, n): + low = i + 1; high = n - 1; ans = i; + + while (low <= high): + mid = int((low + high) / 2); + + if (v[i] <= maxFromEnd[mid]): + + ''' We store this as current + answer and look for further + larger number to the right side''' + + ans = max(ans, mid); + low = mid + 1; + else: + high = mid - 1; + + ''' Keeping a track of the + maximum difference in indices''' + + result = max(result, ans - i); + + print(result, end = """"); + + +" +Depth of the deepest odd level node in Binary Tree,"/*Java program to find depth of the deepest +odd level node */ + +class GfG { +/*A Tree node */ + +static class Node +{ + int key; + Node left, right; +} +/*Utility function to create a new node */ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.key = key; + temp.left = null; + temp.right = null; + return (temp); +} +/*Utility function which +returns whether the current node +is a leaf or not */ + +static boolean isleaf(Node curr_node) +{ + return (curr_node.left == null && curr_node.right == null); +} +/*function to return the longest +odd level depth if it exists +otherwise 0 */ + +static int deepestOddLevelDepthUtil(Node curr_node, int curr_level) +{ +/* Base case + return from here */ + + if ( curr_node == null) + return 0; +/* increment current level */ + + curr_level += 1; +/* if curr_level is odd + and its a leaf node */ + + if ( curr_level % 2 != 0 && isleaf(curr_node)) + return curr_level; + return Math.max(deepestOddLevelDepthUtil(curr_node.left,curr_level), + deepestOddLevelDepthUtil(curr_node.right,curr_level)); +} +/*A wrapper over deepestOddLevelDepth() */ + +static int deepestOddLevelDepth(Node curr_node) +{ + return deepestOddLevelDepthUtil(curr_node, 0); +} +public static void main(String[] args) +{ + /* 10 + / \ + 28 13 + / \ + 14 15 + / \ + 23 24 + Let us create Binary Tree shown in above example */ + + Node root = newNode(10); + root.left = newNode(28); + root.right = newNode(13); + root.right.left = newNode(14); + root.right.right = newNode(15); + root.right.right.left = newNode(23); + root.right.right.right = newNode(24); + System.out.println(deepestOddLevelDepth(root)); +} +}"," '''Python3 program to find depth of +the deepest odd level node +Helper function that allocates a +new node with the given data and +None left and right poers. ''' + +class newNode: + ''' Constructor to create a new node ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Utility function which returns +whether the current node is a +leaf or not ''' + +def isleaf(curr_node) : + return (curr_node.left == None and + curr_node.right == None) + '''function to return the longest +odd level depth if it exists +otherwise 0 ''' + +def deepestOddLevelDepthUtil(curr_node, + curr_level) : + ''' Base case + return from here ''' + + if (curr_node == None) : + return 0 + ''' increment current level ''' + + curr_level += 1 + ''' if curr_level is odd and + its a leaf node ''' + + if (curr_level % 2 != 0 and + isleaf(curr_node)) : + return curr_level + return max(deepestOddLevelDepthUtil(curr_node.left, + curr_level), + deepestOddLevelDepthUtil(curr_node.right, + curr_level)) + '''A wrapper over deepestOddLevelDepth() ''' + +def deepestOddLevelDepth(curr_node) : + return deepestOddLevelDepthUtil(curr_node, 0) + '''Driver Code ''' + +if __name__ == '__main__': + ''' 10 + / \ + 28 13 + / \ + 14 15 + / \ + 23 24 + Let us create Binary Tree shown in + above example ''' + + root = newNode(10) + root.left = newNode(28) + root.right = newNode(13) + root.right.left = newNode(14) + root.right.right = newNode(15) + root.right.right.left = newNode(23) + root.right.right.right = newNode(24) + print(deepestOddLevelDepth(root))" +Group words with same set of characters,"/*Java program to print all words that have +the same unique character set*/ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map.Entry; +public class GFG { + static final int MAX_CHAR = 26; +/* Generates a key from given string. The key + contains all unique characters of given string + in sorted order consisting of only distinct elements.*/ + + static String getKey(String str) + { + boolean[] visited = new boolean[MAX_CHAR]; + Arrays.fill(visited, false); +/* store all unique characters of current + word in key*/ + + for (int j = 0; j < str.length(); j++) + visited[str.charAt(j) - 'a'] = true ; + String key = """"; + for (int j=0; j < MAX_CHAR; j++) + if (visited[j]) + key = key + (char)('a'+j); + return key; + } +/* Print all words together with same character sets.*/ + + static void wordsWithSameCharSet(String words[], int n) + { +/* Stores indexes of all words that have same + set of unique characters. + unordered_map > Hash;*/ + + HashMap> Hash = new HashMap<>(); +/* Traverse all words*/ + + for (int i=0; i get_al = Hash.get(key); + get_al.add(i); + Hash.put(key, get_al); + } +/* if key is not present in the map + then create a new list and add + both key and the list*/ + + else + { + ArrayList new_al = new ArrayList<>(); + new_al.add(i); + Hash.put(key, new_al); + } + } +/* print all words that have the same unique character set*/ + + for (Entry> it : Hash.entrySet()) + { + ArrayList get =it.getValue(); + for (Integer v:get) + System.out.print( words[v] + "", ""); + System.out.println(); + } + } +/* Driver program to test above function*/ + + public static void main(String args[]) + { + String words[] = { ""may"", ""student"", ""students"", ""dog"", + ""studentssess"", ""god"", ""cat"", ""act"", ""tab"", + ""bat"", ""flow"", ""wolf"", ""lambs"", ""amy"", ""yam"", + ""balms"", ""looped"", ""poodle""}; + int n = words.length; + wordsWithSameCharSet(words, n); + } +}", +Find the first repeating element in an array of integers,"/* Java program to find first +repeating element in arr[] */ + +public class GFG +{ +/* This function prints the + first repeating element in arr[]*/ + + static void printFirstRepeating(int[] arr, int n) + { +/* This will set k=1, if any + repeating element found*/ + + int k = 0; +/* max = maximum from (all elements & n)*/ + + int max = n; + for (int i = 0; i < n; i++) + if (max < arr[i]) + max = arr[i]; +/* Array a is for storing + 1st time occurence of element + initialized by 0*/ + + int[] a = new int[max + 1]; +/* Store 1 in array b + if element is duplicate + initialized by 0*/ + + int[] b = new int[max + 1]; + for (int i = 0; i < n; i++) + { +/* Duplicate element found*/ + + if (a[arr[i]] != 0) + { + b[arr[i]] = 1; + k = 1; + continue; + } + else +/* storing 1st occurence of arr[i]*/ + + a[arr[i]] = i; + } + if (k == 0) + System.out.println(""No repeating element found""); + else + { + int min = max + 1; +/* trace array a & find repeating element + with min index*/ + + for (int i = 0; i < max + 1; i++) + if (a[i] != 0 && min > a[i] && b[i] != 0) + min = a[i]; + System.out.print(arr[min]); + } + System.out.println(); + } +/* Driver code*/ + + public static void main(String[] args) + { + int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; + int n = arr.length; + printFirstRepeating(arr, n); + } +}"," '''Python3 program to find first +repeating element in arr[] + ''' '''This function prints the +first repeating element in arr[]''' + +def printFirstRepeating(arr, n): + ''' This will set k=1, if any + repeating element found''' + + k = 0 + ''' max = maximum from (all elements & n)''' + + max = n + for i in range(n): + if (max < arr[i]): + max = arr[i] + ''' Array a is for storing + 1st time occurence of element + initialized by 0''' + + a = [0 for i in range(max + 1)] + ''' Store 1 in array b + if element is duplicate + initialized by 0''' + + b = [0 for i in range(max + 1)] + for i in range(n): + ''' Duplicate element found''' + + if (a[arr[i]]): + b[arr[i]] = 1 + k = 1 + continue + else: + ''' Storing 1st occurence of arr[i]''' + + a[arr[i]] = i + if (k == 0): + print(""No repeating element found"") + else: + min = max + 1 + for i in range(max + 1): + ''' Trace array a & find repeating + element with min index''' + + if (a[i] and (min > (a[i])) and b[i]): + min = a[i] + print(arr[min]) + '''Driver code''' + +arr = [ 10, 5, 3, 4, 3, 5, 6 ] +n = len(arr) +printFirstRepeating(arr, n)" +Two elements whose sum is closest to zero,"/*Java implementation using STL*/ + +import java.io.*; +class GFG{ +/*Modified to sort by abolute values*/ + +static void findMinSum(int[] arr, int n) +{ + for(int i = 1; i < n; i++) + { + if (!(Math.abs(arr[i - 1]) < + Math.abs(arr[i]))) + { + int temp = arr[i - 1]; + arr[i - 1] = arr[i]; + arr[i] = temp; + } + } + int min = Integer.MAX_VALUE; + int x = 0, y = 0; + for(int i = 1; i < n; i++) + { +/* Absolute value shows how close + it is to zero*/ + + if (Math.abs(arr[i - 1] + arr[i]) <= min) + { +/* If found an even close value + update min and store the index*/ + + min = Math.abs(arr[i - 1] + arr[i]); + x = i - 1; + y = i; + } + } + System.out.println(""The two elements whose "" + + ""sum is minimum are "" + + arr[x] + "" and "" + arr[y]); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int[] arr = { 1, 60, -10, 70, -80, 85 }; + int n = arr.length; + findMinSum(arr, n); +} +}"," '''Python3 implementation using STL''' + +import sys +def findMinSum(arr, n): + for i in range(1, n): + ''' Modified to sort by abolute values''' + + if (not abs(arr[i - 1]) < abs(arr[i])): + arr[i - 1], arr[i] = arr[i], arr[i - 1] + Min = sys.maxsize + x = 0 + y = 0 + for i in range(1, n): + ''' Absolute value shows how + close it is to zero''' + + if (abs(arr[i - 1] + arr[i]) <= Min): + ''' If found an even close value + update min and store the index''' + + Min = abs(arr[i - 1] + arr[i]) + x = i - 1 + y = i + print(""The two elements whose sum is minimum are"", + arr[x], ""and"", arr[y]) + '''Driver code''' + +arr = [ 1, 60, -10, 70, -80, 85 ] +n = len(arr) +findMinSum(arr, n)" +Delete an element from array (Using two traversals and one traversal),"/*Java program to remove a given element from an array*/ + +import java.io.*; + +class Deletion +{ +/* This function removes an element x from arr[] and + returns new size after removal. + Returned size is n-1 when element is present. + Otherwise 0 is returned to indicate failure.*/ + + static int deleteElement(int arr[], int n, int x) + { +/* If x is last element, nothing to do*/ + + if (arr[n-1] == x) + return (n-1); + +/* Start from rightmost element and keep moving + elements one position ahead.*/ + + int prev = arr[n-1], i; + for (i=n-2; i>=0 && arr[i]!=x; i--) + { + int curr = arr[i]; + arr[i] = prev; + prev = curr; + } + +/* If element was not found*/ + + if (i < 0) + return 0; + +/* Else move the next element in place of x*/ + + arr[i] = prev; + + return (n-1); + } + +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = {11, 15, 6, 8, 9, 10}; + int n = arr.length; + int x = 6; + +/* Delete x from arr[]*/ + + n = deleteElement(arr, n, x); + + System.out.println(""Modified array is""); + for (int i = 0; i < n; i++) + System.out.print(arr[i]+"" ""); + + } +} + +"," '''python program to remove a given element from an array''' + + + + '''This function removes an element x from arr[] and +returns new size after removal. +Returned size is n-1 when element is present. +Otherwise 0 is returned to indicate failure.''' + +def deleteElement(arr,n,x): + + ''' If x is last element, nothing to do''' + + if arr[n-1]==x: + return n-1 + + ''' Start from rightmost element and keep moving + elements one position ahead.''' + + + prev = arr[n-1] + for i in range(n-2,1,-1): + if arr[i]!=x: + curr = arr[i] + arr[i] = prev + prev = curr + + ''' If element was not found''' + + if i<0: + return 0 + + ''' Else move the next element in place of x''' + + arr[i] = prev + return n-1 + + + '''Driver code''' + +arr = [11,15,6,8,9,10] +n = len(arr) +x = 6 + + + + ''' Delete x from arr[]''' + +n = deleteElement(arr,n,x) +print(""Modified array is"") +for i in range(n): + print(arr[i],end="" "")" +"Possible edges of a tree for given diameter, height and vertices","/*Java program to construct tree for given count +width and height.*/ + +class GfG { +/*Function to construct the tree*/ + +static void constructTree(int n, int d, int h) +{ + if (d == 1) { +/* Special case when d == 2, only one edge*/ + + if (n == 2 && h == 1) { + System.out.println(""1 2""); + return; + } +/*Tree is not possible*/ + +System.out.println(""-1""); + return; + } + if (d > 2 * h) { + System.out.println(""-1""); + return; + } +/* Satisfy the height condition by add + edges up to h*/ + + for (int i = 1; i <= h; i++) + System.out.println(i + "" "" + (i + 1)); + if (d > h) { +/* Add d - h edges from 1 to + satisfy diameter condition*/ + + System.out.println(""1"" + "" "" + (h + 2)); + for (int i = h + 2; i <= d; i++) { + System.out.println(i + "" "" + (i + 1)); + } + } +/* Remaining edges at vertex 1 or 2(d == h)*/ + + for (int i = d + 1; i < n; i++) + { + int k = 1; + if (d == h) + k = 2; + System.out.println(k + "" "" + (i + 1)); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int n = 5, d = 3, h = 2; + constructTree(n, d, h); +} +}"," '''Python3 code to construct tree for given count +width and height.''' + + '''Function to construct the tree''' + +def constructTree(n, d, h): + if d == 1: ''' Special case when d == 2, only one edge''' + + if n == 2 and h == 1: + print(""1 2"") + return 0 + '''Tree is not possible''' + + print(""-1"") + return 0 + if d > 2 * h: + print(""-1"") + return 0 + ''' Satisfy the height condition by add + edges up to h''' + + for i in range(1, h+1): + print(i,"" "" , i + 1) + if d > h: + ''' Add d - h edges from 1 to + satisfy diameter condition''' + + print(1,"" "", h + 2) + for i in range(h+2, d+1): + print(i, "" "" , i + 1) + ''' Remaining edges at vertex 1 or 2(d == h)''' + + for i in range(d+1, n): + k = 1 + if d == h: + k = 2 + print(k ,"" "" , i + 1) + '''Driver Code''' + +n = 5 +d = 3 +h = 2 +constructTree(n, d, h)" +Minimum adjacent swaps to move maximum and minimum to corners,"/*Java program to count Minimum number +of swaps so that the largest element +is at beginning and the +smallest element is at last*/ + +import java.io.*; +class GFG { +/* Function performing calculations*/ + + public static void minimumSwaps(int a[], int n) + { + int maxx = -1, minn = a[0], l = 0, r = 0; + for (int i = 0; i < n; i++) { +/* Index of leftmost largest element*/ + + if (a[i] > maxx) { + maxx = a[i]; + l = i; + } +/* Index of rightmost smallest element*/ + + if (a[i] <= minn) { + minn = a[i]; + r = i; + } + } + if (r < l) + System.out.println(l + (n - r - 2)); + else + System.out.println(l + (n - r - 1)); + } +/* Driver Code*/ + + public static void main(String args[]) throws IOException + { + int a[] = { 5, 6, 1, 3 }; + int n = a.length; + minimumSwaps(a, n); + } +}"," '''Python3 program to count +Minimum number of adjacent +swaps so that the largest +element is at beginning and +the smallest element is at last.''' + + + '''Function that returns + the minimum swaps''' +def minSwaps(arr): + n = len(arr) + maxx, minn, l, r = -1, arr[0], 0, 0 + for i in range(n): + ''' Index of leftmost + largest element''' + + if arr[i] > maxx: + maxx = arr[i] + l = i + ''' Index of rightmost + smallest element''' + + if arr[i] <= minn: + minn = arr[i] + r = i + if r < l: + print(l + (n - r - 2)) + else: + print(l + (n - r - 1)) + '''Driver code''' + +arr = [5, 6, 1, 3] +minSwaps(arr)" +Program for nth Catalan Number,"import java.util.*; +class GFG +{ +/*Function to print the number*/ + +static void catalan(int n) +{ + int cat_ = 1; +/* For the first number +C(0)*/ + +System.out.print(cat_+"" ""); +/* Iterate till N*/ + + for (int i = 1; i < n; i++) + { +/* Calculate the number + and print it*/ + + cat_ *= (4 * i - 2); + cat_ /= (i + 1); + System.out.print(cat_+"" ""); + } +} +/*Driver code*/ + +public static void main(String args[]) +{ + int n = 5; +/* Function call*/ + + catalan(n); +} +}"," '''Function to print the number''' + +def catalan(n): + cat_ = 1 + ''' For the first number +C(0)''' + + print(cat_, "" "", end = '') + ''' Iterate till N''' + + for i in range(1, n): + ''' Calculate the number + and print it''' + + cat_ *= (4 * i - 2); + cat_ //= (i + 1); + print(cat_, "" "", end = '') + '''Driver code''' + +n = 5 + '''Function call''' + +catalan(n)" +Check if two expressions with brackets are same,"/*Java program to check if two expressions +evaluate to same.*/ + +import java.io.*; +import java.util.*; +class GFG +{ + static final int MAX_CHAR = 26; +/* Return local sign of the operand. For example, + in the expr a-b-(c), local signs of the operands + are +a, -b, +c*/ + + static boolean adjSign(String s, int i) + { + if (i == 0) + return true; + if (s.charAt(i - 1) == '-') + return false; + return true; + }; +/* Evaluate expressions into the count vector of + the 26 alphabets.If add is true, then add count + to the count vector of the alphabets, else remove + count from the count vector.*/ + + static void eval(String s, int[] v, boolean add) + { +/* stack stores the global sign + for operands.*/ + + Stack stk = new Stack<>(); + stk.push(true); +/* + means true + global sign is positive initially*/ + + int i = 0; + while (i < s.length()) + { + if (s.charAt(i) == '+' || s.charAt(i) == '-') + { + i++; + continue; + } + if (s.charAt(i) == '(') + { +/* global sign for the bracket is + pushed to the stack*/ + + if (adjSign(s, i)) + stk.push(stk.peek()); + else + stk.push(!stk.peek()); + } +/* global sign is popped out which + was pushed in for the last bracket*/ + + else if (s.charAt(i) == ')') + stk.pop(); + else + { +/* global sign is positive (we use different + values in two calls of functions so that + we finally check if all vector elements + are 0.*/ + + if (stk.peek()) + v[s.charAt(i) - 'a'] += (adjSign(s, i) ? + add ? 1 : -1 : add ? -1 : 1); +/* global sign is negative here*/ + + else + v[s.charAt(i) - 'a'] += (adjSign(s, i) ? + add ? -1 : 1 : add ? 1 : -1); + } + i++; + } + }; +/* Returns true if expr1 and expr2 represent + same expressions*/ + + static boolean areSame(String expr1, String expr2) + { +/* Create a vector for all operands and + initialize the vector as 0.*/ + + int[] v = new int[MAX_CHAR]; +/* Put signs of all operands in expr1*/ + + eval(expr1, v, true); +/* Subtract signs of operands in expr2*/ + + eval(expr2, v, false); +/* If expressions are same, vector must + be 0.*/ + + for (int i = 0; i < MAX_CHAR; i++) + if (v[i] != 0) + return false; + return true; + } +/* Driver Code*/ + + public static void main(String[] args) + { + String expr1 = ""-(a+b+c)"", expr2 = ""-a-b-c""; + if (areSame(expr1, expr2)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 program to check if two expressions +evaluate to same.''' + +MAX_CHAR = 26; + '''Return local sign of the operand. For example, +in the expr a-b-(c), local signs of the operands +are +a, -b, +c''' + +def adjSign(s, i): + if (i == 0): + return True; + if (s[i - 1] == '-'): + return False; + return True; + '''Evaluate expressions into the count vector of +the 26 alphabets.If add is True, then add count +to the count vector of the alphabets, else remove +count from the count vector.''' + +def eval(s, v, add): + ''' stack stores the global sign + for operands.''' + + stk = [] + stk.append(True); + ''' + means True + global sign is positive initially''' + + i = 0; + while (i < len(s)): + if (s[i] == '+' or s[i] == '-'): + i += 1 + continue; + if (s[i] == '('): + ''' global sign for the bracket is + pushed to the stack''' + + if (adjSign(s, i)): + stk.append(stk[-1]); + else: + stk.append(not stk[-1]); + ''' global sign is popped out which + was pushed in for the last bracket''' + + elif (s[i] == ')'): + stk.pop(); + else: + ''' global sign is positive (we use different + values in two calls of functions so that + we finally check if all vector elements + are 0.''' + + if (stk[-1]): + v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1) + ''' global sign is negative here''' + + else: + v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1) + i += 1 + '''Returns True if expr1 and expr2 represent +same expressions''' + +def areSame(expr1, expr2): + ''' Create a vector for all operands and + initialize the vector as 0.''' + + v = [0 for i in range(MAX_CHAR)]; + ''' Put signs of all operands in expr1''' + + eval(expr1, v, True); + ''' Subtract signs of operands in expr2''' + + eval(expr2, v, False); + ''' If expressions are same, vector must + be 0.''' + + for i in range(MAX_CHAR): + if (v[i] != 0): + return False; + return True; + '''Driver Code''' + +if __name__=='__main__': + expr1 = ""-(a+b+c)"" + expr2 = ""-a-b-c""; + if (areSame(expr1, expr2)): + print(""Yes""); + else: + print(""No"");" +Dynamic Programming,"/*A Dynamic Programming solution for subset +sum problem*/ + +class GFG { +/* Returns true if there is a subset of + set[] with sun equal to given sum*/ + + static boolean isSubsetSum(int set[], + int n, int sum) + { +/* The value of subset[i][j] will be + true if there is a subset of + set[0..j-1] with sum equal to i*/ + + boolean subset[][] = new boolean[sum + 1][n + 1]; +/* If sum is 0, then answer is true*/ + + for (int i = 0; i <= n; i++) + subset[0][i] = true; +/* If sum is not 0 and set is empty, + then answer is false*/ + + for (int i = 1; i <= sum; i++) + subset[i][0] = false; +/* Fill the subset table in botton + up manner*/ + + for (int i = 1; i <= sum; i++) { + for (int j = 1; j <= n; j++) { + subset[i][j] = subset[i][j - 1]; + if (i >= set[j - 1]) + subset[i][j] = subset[i][j] + || subset[i - set[j - 1]][j - 1]; + } + } +/*print table*/ + + for (int i = 0; i <= sum; i++) + { + for (int j = 0; j <= n; j++) + System.out.println (subset[i][j]); + } + return subset[sum][n]; + }/* Driver code*/ + + public static void main(String args[]) + { + int set[] = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + int n = set.length; + if (isSubsetSum(set, n, sum) == true) + System.out.println(""Found a subset"" + + "" with given sum""); + else + System.out.println(""No subset with"" + + "" given sum""); + } +}"," '''A Dynamic Programming solution for subset +sum problem''' + ''' Returns true if there is a subset of set[] +with sun equal to given sum''' + +def isSubsetSum(set, n, sum): ''' The value of subset[i][j] will be + true if there is a + subset of set[0..j-1] with sum equal to i''' + + subset =([[False for i in range(sum + 1)] + for i in range(n + 1)]) + ''' If sum is 0, then answer is true''' + + for i in range(n + 1): + subset[i][0] = True + ''' If sum is not 0 and set is empty, + then answer is false''' + + for i in range(1, sum + 1): + subset[0][i]= False + ''' Fill the subset table in botton up manner''' + + for i in range(1, n + 1): + for j in range(1, sum + 1): + if j= set[i-1]: + subset[i][j] = (subset[i-1][j] or + subset[i - 1][j-set[i-1]]) + ''' print table''' + + for i in range(n + 1): + for j in range(sum + 1): + print (subset[i][j], end ="" "") + print() + + return subset[n][sum] + '''Driver code''' + +if __name__=='__main__': + set = [3, 34, 4, 12, 5, 2] + sum = 9 + n = len(set) + if (isSubsetSum(set, n, sum) == True): + print(""Found a subset with given sum"") + else: + print(""No subset with given sum"")" +Iterative HeapSort,"/*Java implementation of Iterative Heap Sort */ + +public class HeapSort { +/* function build Max Heap where value + of each child is always smaller + than value of their parent*/ + + static void buildMaxHeap(int arr[], int n) + { + for (int i = 1; i < n; i++) + { +/* if child is bigger than parent*/ + + if (arr[i] > arr[(i - 1) / 2]) + { + int j = i; +/* swap child and parent until + parent is smaller*/ + + while (arr[j] > arr[(j - 1) / 2]) + { + swap(arr, j, (j - 1) / 2); + j = (j - 1) / 2; + } + } + } + } + static void heapSort(int arr[], int n) + { + buildMaxHeap(arr, n); + for (int i = n - 1; i > 0; i--) + { +/* swap value of first indexed + with last indexed*/ + + swap(arr, 0, i); +/* maintaining heap property + after each swapping*/ + + int j = 0, index; + do + { + index = (2 * j + 1); +/* if left child is smaller than + right child point index variable + to right child*/ + + if (index < (i - 1) && arr[index] < arr[index + 1]) + index++; +/* if parent is smaller than child + then swapping parent with child + having higher value*/ + + if (index < i && arr[j] < arr[index]) + swap(arr, j, index); + j = index; + } while (index < i); + } + } + public static void swap(int[] a, int i, int j) { + int temp = a[i]; + a[i]=a[j]; + a[j] = temp; + } + /* A utility function to print array of size n */ + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver program*/ + + public static void main(String args[]) + { + int arr[] = {10, 20, 15, 17, 9, 21}; + int n = arr.length; + System.out.print(""Given array: ""); + printArray(arr); + heapSort(arr, n); + System.out.print(""Sorted array: ""); + printArray(arr); + } +}"," '''Python3 program for implementation +of Iterative Heap Sort + ''' '''function build Max Heap where value +of each child is always smaller +than value of their parent ''' + +def buildMaxHeap(arr, n): + for i in range(n): + ''' if child is bigger than parent ''' + + if arr[i] > arr[int((i - 1) / 2)]: + j = i + ''' swap child and parent until + parent is smaller ''' + + while arr[j] > arr[int((j - 1) / 2)]: + (arr[j], + arr[int((j - 1) / 2)]) = (arr[int((j - 1) / 2)], + arr[j]) + j = int((j - 1) / 2) +def heapSort(arr, n): + buildMaxHeap(arr, n) + for i in range(n - 1, 0, -1): + ''' swap value of first indexed + with last indexed ''' + + arr[0], arr[i] = arr[i], arr[0] + ''' maintaining heap property + after each swapping ''' + + j, index = 0, 0 + while True: + index = 2 * j + 1 + ''' if left child is smaller than + right child point index variable + to right child ''' + + if (index < (i - 1) and + arr[index] < arr[index + 1]): + index += 1 + ''' if parent is smaller than child + then swapping parent with child + having higher value ''' + + if index < i and arr[j] < arr[index]: + arr[j], arr[index] = arr[index], arr[j] + j = index + if index >= i: + break + '''Driver Code''' + +if __name__ == '__main__': + arr = [10, 20, 15, 17, 9, 21] + n = len(arr) + print(""Given array: "") + for i in range(n): + print(arr[i], end = "" "") + print() + heapSort(arr, n) + print(""Sorted array: "") + for i in range(n): + print(arr[i], end = "" "")" +Sum of matrix in which each element is absolute difference of its row and column numbers,"/*Java program to find sum of matrix in which +each element is absolute difference of its +corresponding row and column number row.*/ + +import java.io.*; +public class GFG { +/*Retuen the sum of matrix in which each element +is absolute difference of its corresponding +row and column number row*/ + +static int findSum(int n) +{ + n--; + int sum = 0; + sum += (n * (n + 1)) / 2; + sum += (n * (n + 1) * (2 * n + 1)) / 6; + return sum; +} +/* Driver Code*/ + + static public void main (String[] args) + { + int n = 3; + System.out.println(findSum(n)); + } +}"," '''Python 3 program to find sum of matrix +in which each element is absolute +difference of its corresponding row +and column number row.''' + '''Return the sum of matrix in which +each element is absolute difference +of its corresponding row and column +number row''' + +def findSum(n): + n -= 1 + sum = 0 + sum += (n * (n + 1)) / 2 + sum += (n * (n + 1) * (2 * n + 1)) / 6 + return int(sum) '''Driver Code''' + +n = 3 +print(findSum(n))" +Rearrange an array such that arr[i] = i,"/*Java program for above approach*/ + +class GFG{ +/*Function to tranform the array*/ + +public static void fixArray(int ar[], int n) +{ + int i, j, temp; +/* Iterate over the array*/ + + for(i = 0; i < n; i++) + { + for(j = 0; j < n; j++) + { +/* Checf is any ar[j] + exists such that + ar[j] is equal to i*/ + + if (ar[j] == i) + { + temp = ar[j]; + ar[j] = ar[i]; + ar[i] = temp; + break; + } + } + } +/* Iterate over array*/ + + for(i = 0; i < n; i++) + { +/* If not present*/ + + if (ar[i] != i) + { + ar[i] = -1; + } + } +/* Print the output*/ + + System.out.println(""Array after Rearranging""); + for(i = 0; i < n; i++) + { + System.out.print(ar[i] + "" ""); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int n, ar[] = { -1, -1, 6, 1, 9, + 3, 2, -1, 4, -1 }; + n = ar.length; +/* Function Call*/ + + fixArray(ar, n); +} +}"," '''Python3 program for above approach''' + '''Function to tranform the array''' + +def fixArray(ar, n): + ''' Iterate over the array''' + + for i in range(n): + for j in range(n): + ''' Check is any ar[j] + exists such that + ar[j] is equal to i''' + + if (ar[j] == i): + ar[j], ar[i] = ar[i], ar[j] + ''' Iterate over array''' + + for i in range(n): + ''' If not present''' + + if (ar[i] != i): + ar[i] = -1 + ''' Print the output''' + + print(""Array after Rearranging"") + for i in range(n): + print(ar[i], end = "" "") + '''Driver Code''' + +ar = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ] +n = len(ar) + '''Function Call''' + +fixArray(ar, n);" +Reorder an array according to given indexes,"/*Java to find positions of zeroes flipping which +produces maximum number of consecutive 1's*/ + +import java.util.Arrays; +class Test +{ + static int arr[] = new int[]{50, 40, 70, 60, 90}; + static int index[] = new int[]{3, 0, 4, 1, 2}; +/* Method to reorder elements of arr[] according + to index[]*/ + + static void reorder() + { + int temp[] = new int[arr.length]; +/* arr[i] should be present at index[i] index*/ + + for (int i=0; i s) +{ +/* Transfer elements of s to aux.*/ + + Stack aux = new Stack (); + while (!s.isEmpty()) { + aux.push(s.peek()); + s.pop(); + } +/* Traverse aux and see if + elements are pairwise + consecutive or not. We also + need to make sure that original + content is retained.*/ + + boolean result = true; + while (aux.size() > 1) { +/* Fetch current top two + elements of aux and check + if they are consecutive.*/ + + int x = aux.peek(); + aux.pop(); + int y = aux.peek(); + aux.pop(); + if (Math.abs(x - y) != 1) + result = false; +/* Push the elements to original + stack.*/ + + s.push(x); + s.push(y); + } + if (aux.size() == 1) + s.push(aux.peek()); + return result; +} +/*Driver program*/ + +public static void main(String[] args) +{ + Stack s = new Stack (); + s.push(4); + s.push(5); + s.push(-2); + s.push(-3); + s.push(11); + s.push(10); + s.push(5); + s.push(6); + s.push(20); + if (pairWiseConsecutive(s)) + System.out.println(""Yes""); + else + System.out.println(""No""); + System.out.println(""Stack content (from top) after function call""); + while (s.isEmpty() == false) + { + System.out.print(s.peek() + "" ""); + s.pop(); + } +} +}"," '''Python3 program to check if successive +pair of numbers in the stack are +consecutive or not + ''' '''Function to check if elements are +pairwise consecutive in stack''' + +def pairWiseConsecutive(s): + ''' Transfer elements of s to aux.''' + + aux = [] + while (len(s) != 0): + aux.append(s[-1]) + s.pop() + ''' Traverse aux and see if elements + are pairwise consecutive or not. + We also need to make sure that + original content is retained.''' + + result = True + while (len(aux) > 1): + ''' Fetch current top two + elements of aux and check + if they are consecutive.''' + + x = aux[-1] + aux.pop() + y = aux[-1] + aux.pop() + if (abs(x - y) != 1): + result = False + ''' append the elements to + original stack.''' + + s.append(x) + s.append(y) + if (len(aux) == 1): + s.append(aux[-1]) + return result + '''Driver Code''' + +if __name__ == '__main__': + s = [] + s.append(4) + s.append(5) + s.append(-2) + s.append(-3) + s.append(11) + s.append(10) + s.append(5) + s.append(6) + s.append(20) + if (pairWiseConsecutive(s)): + print(""Yes"") + else: + print(""No"") + print(""Stack content (from top)"", + ""after function call"") + while (len(s) != 0): + print(s[-1], end = "" "") + s.pop()" +Remove every k-th node of the linked list,"/*Java program to delete every k-th Node +of a singly linked list.*/ + +class GFG +{ + +/* Linked list Node */ + +static class Node +{ + int data; + Node next; +} + +/*To remove complete list (Needed for +case when k is 1)*/ + +static Node freeList(Node node) +{ + while (node != null) + { + Node next = node.next; + node = next; + } + return node; +} + +/*Deletes every k-th node and +returns head of modified list.*/ + +static Node deleteKthNode(Node head, int k) +{ +/* If linked list is empty*/ + + if (head == null) + return null; + + if (k == 1) + { + head = freeList(head); + return null; + } + +/* Initialize ptr and prev before + starting traversal.*/ + + Node ptr = head, prev = null; + +/* Traverse list and delete + every k-th node*/ + + int count = 0; + while (ptr != null) + { +/* increment Node count*/ + + count++; + +/* check if count is equal to k + if yes, then delete current Node*/ + + if (k == count) + { +/* put the next of current Node in + the next of previous Node*/ + + prev.next = ptr.next; + +/* set count = 0 to reach further + k-th Node*/ + + count = 0; + } + +/* update prev if count is not 0*/ + + if (count != 0) + prev = ptr; + + ptr = prev.next; + } + return head; +} + +/* Function to print linked list */ + +static void displayList(Node head) +{ + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } +} + +/*Utility function to create a new node.*/ + +static Node newNode(int x) +{ + Node temp = new Node(); + temp.data = x; + temp.next = null; + return temp; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + /* Start with the empty list */ + + 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); +} +} + + +"," '''Python3 program to delete every k-th Node +of a singly linked list.''' + +import math + + '''Linked list Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''To remove complete list (Needed for +case when k is 1)''' + +def freeList(node): + while (node != None): + next = node.next + node = next + return node + + '''Deletes every k-th node and +returns head of modified list.''' + +def deleteKthNode(head, k): + + ''' If linked list is empty''' + + if (head == None): + return None + + if (k == 1): + freeList(head) + return None + + ''' Initialize ptr and prev before + starting traversal.''' + + ptr = head + prev = None + + ''' Traverse list and delete every k-th node''' + + count = 0 + while (ptr != None): + + ''' increment Node count''' + + count = count + 1 + + ''' check if count is equal to k + if yes, then delete current Node''' + + if (k == count): + + ''' put the next of current Node in + the next of previous Node + delete(prev.next)''' + + prev.next = ptr.next + + ''' set count = 0 to reach further + k-th Node''' + + count = 0 + + ''' update prev if count is not 0''' + + if (count != 0): + prev = ptr + + ptr = prev.next + + return head + + '''Function to print linked list''' + +def displayList(head): + temp = head + while (temp != None): + print(temp.data, end = ' ') + temp = temp.next + + '''Utility function to create a new node.''' + +def newNode( x): + temp = Node(x) + temp.data = x + temp.next = None + return temp + + '''Driver Code''' + +if __name__=='__main__': + + ''' Start with the empty list''' + + 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) + + k = 3 + head = deleteKthNode(head, k) + + displayList(head) + + +" +Program to find whether a no is power of two,"/*Java program to find whether +a no is power of two*/ + +import java.io.*; +class GFG { +/* Function to check if + x is power of 2*/ + + static boolean isPowerOfTwo(int n) + { + if (n == 0) + return false; + while (n != 1) + { + if (n % 2 != 0) + return false; + n = n / 2; + } + return true; + } +/* Driver program*/ + + public static void main(String args[]) + { + if (isPowerOfTwo(31)) + System.out.println(""Yes""); + else + System.out.println(""No""); + if (isPowerOfTwo(64)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python program to check if given +number is power of 2 or not''' + + '''Function to check if x is power of 2''' + +def isPowerOfTwo(n): + if (n == 0): + return False + while (n != 1): + if (n % 2 != 0): + return False + n = n // 2 + return True '''Driver code''' + +if(isPowerOfTwo(31)): + print('Yes') +else: + print('No') +if(isPowerOfTwo(64)): + print('Yes') +else: + print('No')" +Count of n digit numbers whose sum of digits equals to given sum,"/*A Java memoization based recursive program to count +numbers with sum of n as given 'sum'*/ + +class sum_dig +{ +/* A lookup table used for memoization*/ + + static int lookup[][] = new int[101][501]; +/* Memoization based implementation of recursive + function*/ + + static int countRec(int n, int sum) + { +/* Base case*/ + + if (n == 0) + return sum == 0 ? 1 : 0; +/* If this subproblem is already evaluated, + return the evaluated value*/ + + if (lookup[n][sum] != -1) + return lookup[n][sum]; +/* Initialize answer*/ + + int ans = 0; +/* Traverse through every digit and + recursively count numbers beginning + with it*/ + + for (int i=0; i<10; i++) + if (sum-i >= 0) + ans += countRec(n-1, sum-i); + return lookup[n][sum] = ans; + } +/* This is mainly a wrapper over countRec. It + explicitly handles leading digit and calls + countRec() for remaining n.*/ + + static int finalCount(int n, int sum) + { +/* Initialize all entries of lookup table*/ + + for(int i = 0; i <= 100; ++i){ + for(int j = 0; j <= 500; ++j){ + lookup[i][j] = -1; + } + } +/* Initialize final answer*/ + + int ans = 0; +/* Traverse through every digit from 1 to + 9 and count numbers beginning with it*/ + + for (int i = 1; i <= 9; i++) + if (sum-i >= 0) + ans += countRec(n-1, sum-i); + return ans; + } + /* Driver program to test above function */ + + public static void main (String args[]) + { + int n = 3, sum = 5; + System.out.println(finalCount(n, sum)); + } +}"," '''A Python3 memoization based recursive +program to count numbers with Sum of n +as given 'Sum' ''' + '''A lookup table used for memoization''' + +lookup = [[-1 for i in range(501)] + for i in range(101)] + '''Memoization based implementation +of recursive function''' + +def countRec(n, Sum): + ''' Base case''' + + if (n == 0): + return Sum == 0 + ''' If this subproblem is already evaluated, + return the evaluated value''' + + if (lookup[n][Sum] != -1): + return lookup[n][Sum] + ''' Initialize answer''' + + ans = 0 + ''' Traverse through every digit and + recursively count numbers beginning + with it''' + + for i in range(10): + if (Sum-i >= 0): + ans += countRec(n - 1, Sum-i) + lookup[n][Sum] = ans + return lookup[n][Sum] + '''This is mainly a wrapper over countRec. It +explicitly handles leading digit and calls +countRec() for remaining n.''' + +def finalCount(n, Sum): + ''' Initialize final answer''' + + ans = 0 + ''' Traverse through every digit from 1 to + 9 and count numbers beginning with it''' + + for i in range(1, 10): + if (Sum - i >= 0): + ans += countRec(n - 1, Sum - i) + return ans + '''Driver Code''' + +n, Sum = 3, 5 +print(finalCount(n, Sum))" +Minimum De-arrangements present in array of AP (Arithmetic Progression),"/*Java code for counting minimum +de-arrangements present in an array.*/ + +import java.util.*; +import java.lang.*; +import java.util.Arrays; + +public class GeeksforGeeks{ + +/* function to count Dearrangement*/ + + public static int countDe(int arr[], int n){ + int v[] = new int[n]; + +/* create a copy of original array*/ + + for(int i = 0; i < n; i++) + v[i] = arr[i]; + +/* sort the array*/ + + Arrays.sort(arr); + +/* traverse sorted array for + counting mismatches*/ + + int count1 = 0; + for (int i = 0; i < n; i++) + if (arr[i] != v[i]) + count1++; + +/* reverse the sorted array*/ + + Collections.reverse(Arrays.asList(arr)); + +/* traverse reverse sorted array + for counting mismatches*/ + + int count2 = 0; + for (int i = 0; i < n; i++) + if (arr[i] != v[i]) + count2++; + +/* return minimum mismatch count*/ + + return (Math.min (count1, count2)); + } + +/* driver code*/ + + public static void main(String argc[]){ + int arr[] = {5, 9, 21, 17, 13}; + int n = 5; + System.out.println(""Minimum Dearrangement = ""+ + countDe(arr, n)); + } +} + + +"," '''Python3 code for counting minimum +de-arrangements present in an array.''' + + + '''function to count Dearrangement''' + +def countDe(arr, n): + + i = 0 + + ''' create a copy of + original array''' + + v = arr.copy() + + ''' sort the array''' + + arr.sort() + + ''' traverse sorted array for + counting mismatches''' + + count1 = 0 + i = 0 + while( i < n ): + if (arr[i] != v[i]): + count1 = count1 + 1 + i = i + 1 + + ''' reverse the sorted array''' + + arr.sort(reverse=True) + + ''' traverse reverse sorted array + for counting mismatches''' + + count2 = 0 + i = 0 + while( i < n ): + if (arr[i] != v[i]): + count2 = count2 + 1 + i = i + 1 + + ''' return minimum mismatch count''' + + return (min (count1, count2)) + + '''Driven code''' + +arr = [5, 9, 21, 17, 13] +n = 5 +print (""Minimum Dearrangement ="",countDe(arr, n)) + + +" +Iterative program to count leaf nodes in a Binary Tree,"/*Java program to count leaf nodes +in a Binary Tree*/ + +import java.util.*; +class GFG +{ + /* A binary tree Node has data, + pointer to left child and + a pointer to right child */ + + static class Node + { + int data; + Node left, right; + } + /* Function to get the count of + leaf Nodes in a binary tree*/ + + static int getLeafCount(Node node) + { +/* If tree is empty*/ + + if (node == null) + { + return 0; + } +/* Initialize empty queue.*/ + + Queue q = new LinkedList<>(); +/* Do level order traversal starting from root +Initialize count of leaves*/ + +int count = 0; + q.add(node); + while (!q.isEmpty()) + { + Node temp = q.peek(); + q.poll(); + if (temp.left != null) + { + q.add(temp.left); + } + if (temp.right != null) + { + q.add(temp.right); + } + if (temp.left == null && + temp.right == null) + { + count++; + } + } + return count; + } + /* Helper function that allocates + a new Node with the given data + and null left and right pointers. */ + + static Node newNode(int data) + { + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); + } +/* Driver Code*/ + + public static void main(String[] args) + { + { + /* 1 + / \ + 2 3 + / \ + 4 5 + Let us create Binary Tree shown in + above example */ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + /* get leaf count of the above created tree */ + + System.out.println(getLeafCount(root)); + } + } +}"," '''Python3 program to count leaf nodes +in a Binary Tree''' + +from queue import Queue + '''Helper function that allocates a new +Node with the given data and None +left and right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Function to get the count of leaf +Nodes in a binary tree''' + +def getLeafCount(node): + ''' If tree is empty''' + + if (not node): + return 0 + ''' Initialize empty queue.''' + + q = Queue() + ''' Do level order traversal + starting from root +Initialize count of leaves''' + + count = 0 + q.put(node) + while (not q.empty()): + temp = q.queue[0] + q.get() + if (temp.left != None): + q.put(temp.left) + if (temp.right != None): + q.put(temp.right) + if (temp.left == None and + temp.right == None): + count += 1 + return count + '''Driver Code''' + +if __name__ == '__main__': + ''' 1 + / \ + 2 3 + / \ + 4 5 + Let us create Binary Tree shown + in above example''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + ''' get leaf count of the above + created tree''' + + print(getLeafCount(root))" +Root to leaf path sum equal to a given number,"/*Java program to print to print +root to leaf path sum +equal to a given number*/ + +/* A binary tree node has data, + pointer to left child + and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; + /* + Given a tree and a sum, + return true if there is a path + from the root down to a leaf, + such that adding up all + the values along the path + equals the given sum. + Strategy: subtract the node + value from the sum when + recurring down, and check to + see if the sum is 0 when + you run out of tree. + */ + + boolean hasPathSum(Node node, int sum) + { + if (node == null) + return sum == 0; + return hasPathSum(node.left, sum - node.data) + || hasPathSum(node.right, sum - node.data); + } +/* Driver Code*/ + + public static void main(String args[]) + { + int sum = 21; + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 + */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(2); + if (tree.haspathSum(tree.root, sum)) + System.out.println( + ""There is a root to leaf path with sum "" + + sum); + else + System.out.println( + ""There is no root to leaf path with sum "" + + sum); + } +}"," '''Python program to find if +there is a root to sum path''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + ''' + Given a tree and a sum, return + true if there is a path from the root + down to a leaf, such that + adding up all the values along the path + equals the given sum. + Strategy: subtract the node + value from the sum when recurring down, + and check to see if the sum + is 0 when you run out of tree. +s is the sum''' + +def hasPathSum(node, s): + + if node is None: + return (s == 0) + else: + ans = 0 + subSum = s - node.data + if(subSum == 0 and node.left == None and node.right == None): + return True + if node.left is not None: + ans = ans or hasPathSum(node.left, subSum) + if node.right is not None: + ans = ans or hasPathSum(node.right, subSum) + return ans + + '''Driver Code''' + ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 + ''' + +s = 21 +root = Node(10) +root.left = Node(8) +root.right = Node(2) +root.left.right = Node(5) +root.left.left = Node(3) +root.right.left = Node(2) +if hasPathSum(root, s): + print ""There is a root-to-leaf path with sum %d"" % (s) +else: + print ""There is no root-to-leaf path with sum %d"" % (s)" +Maximum product of indexes of next greater on left and right,"/*Java program to find the +max LRproduct[i] among all i*/ + +import java.io.*; +import java.util.*; +class GFG +{ + static int MAX = 1000; +/* function to find just next + greater element in left side*/ + + static int[] nextGreaterInLeft(int []a, + int n) + { + int []left_index = new int[MAX]; + Stack s = new Stack(); + for (int i = n - 1; i >= 0; i--) + { +/* checking if current + element is greater than top*/ + + while (s.size() != 0 && + a[i] > a[s.peek() - 1]) + { + int r = s.peek(); + s.pop(); +/* on index of top store + the current element + index which is just + greater than top element*/ + + left_index[r - 1] = i + 1; + } +/* else push the current + element in stack*/ + + s.push(i + 1); + } + return left_index; + } +/* function to find just next + greater element in right side*/ + + static int[] nextGreaterInRight(int []a, + int n) + { + int []right_index = new int[MAX]; + Stack s = new Stack(); + for (int i = 0; i < n; ++i) { +/* checking if current element + is greater than top*/ + + while (s.size() != 0 && + a[i] > a[s.peek() - 1]) + { + int r = s.peek(); + s.pop(); +/* on index of top store + the current element index + which is just greater than + top element stored index + should be start with 1*/ + + right_index[r - 1] = i + 1; + } +/* else push the current + element in stack*/ + + s.push(i + 1); + } + return right_index; + } +/* Function to find + maximum LR product*/ + + static int LRProduct(int []arr, int n) + { +/* for each element storing + the index of just greater + element in left side*/ + + int []left = nextGreaterInLeft(arr, n); +/* for each element storing + the index of just greater + element in right side*/ + + int []right = nextGreaterInRight(arr, n); + int ans = -1; + for (int i = 1; i <= n; i++) + { +/* finding the max + index product*/ + + ans = Math.max(ans, left[i] * + right[i]); + } + return ans; + } +/* Driver code*/ + + public static void main(String args[]) + { + int []arr = new int[]{ 5, 4, 3, 4, 5 }; + int n = arr.length; + System.out.print(LRProduct(arr, n)); + } +}"," '''Python3 program to find the +max LRproduct[i] among all i''' + '''Method to find the next greater +value in left side''' + +def nextGreaterInLeft(a): + left_index = [0] * len(a) + s = [] + for i in range(len(a)): ''' Checking if current + element is greater than top''' + + while len(s) != 0 and a[i] >= a[s[-1]]: + s.pop() ''' Pop the element till we can't + get the larger value then + the current value''' + + if len(s) != 0: + left_index[i] = s[-1] + else: + left_index[i] = 0 + ''' Else push the element in the stack''' + + s.append(i) + return left_index + '''Method to find the next +greater value in right''' + +def nextGreaterInRight(a): + right_index = [0] * len(a) + s = [] + for i in range(len(a) - 1, -1, -1): + ''' Checking if current element + is greater than top''' + + while len(s) != 0 and a[i] >= a[s[-1]]: + s.pop() ''' Pop the element till we can't + get the larger value then + the current value''' + + + if len(s) != 0: + right_index[i] = s[-1] + else: + right_index[i] = 0 + ''' Else push the element in the stack''' + + s.append(i) + return right_index +def LRProduct(arr): + ''' For each element storing + the index of just greater + element in left side''' + + left = nextGreaterInLeft(arr) + ''' For each element storing + the index of just greater + element in right side''' + + right = nextGreaterInRight(arr) + ans = -1 + for i in range(1, len(left) - 1): + if left[i] == 0 or right[i] == 0: ''' Finding the max index product''' + ans = max(ans, 0) + else: + temp = (left[i] + 1) * (right[i] + 1) + ans = max(ans, temp) + return ans + '''Driver Code''' + +arr = [ 5, 4, 3, 4, 5 ] +print(LRProduct(arr))" +Print the nodes at odd levels of a tree,"/*Iterative Java program to print odd level nodes*/ + +import java.util.*; +class GfG { +static class Node { + int data; + Node left, right; +} +/*Iterative method to do level order traversal line by line*/ + +static void printOddNodes(Node root) +{ +/* Base Case*/ + + if (root == null) return; +/* Create an empty queue for level + order traversal*/ + + Queue q = new LinkedList (); +/* Enqueue root and initialize level as odd*/ + + q.add(root); + boolean isOdd = true; + while (true) + { +/* nodeCount (queue size) indicates + number of nodes at current level.*/ + + int nodeCount = q.size(); + if (nodeCount == 0) + break; +/* Dequeue all nodes of current level + and Enqueue all nodes of next level*/ + + while (nodeCount > 0) + { + Node node = q.peek(); + if (isOdd == true) + System.out.print(node.data + "" ""); + q.remove(); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + nodeCount--; + } + isOdd = !isOdd; + } +} +/*Utility method to create a node*/ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + printOddNodes(root); +} +}"," '''Iterative Python3 program to prodd +level nodes +A Binary Tree Node +Utility function to create a +new tree Node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Iterative method to do level order +traversal line by line''' + +def printOddNodes(root) : + ''' Base Case''' + + if (root == None): + return + ''' Create an empty queue for + level order traversal''' + + q = [] + ''' Enqueue root and initialize + level as odd''' + + q.append(root) + isOdd = True + while (1) : + ''' nodeCount (queue size) indicates + number of nodes at current level.''' + + nodeCount = len(q) + if (nodeCount == 0) : + break + ''' Dequeue all nodes of current level + and Enqueue all nodes of next level''' + + while (nodeCount > 0): + node = q[0] + if (isOdd): + print(node.data, end = "" "") + q.pop(0) + if (node.left != None) : + q.append(node.left) + if (node.right != None) : + q.append(node.right) + nodeCount -= 1 + isOdd = not isOdd + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + printOddNodes(root)" +Minimum cost to connect all cities,"/*Java code to find out minimum cost +path to connect all the cities*/ + +import java.util.*; +class GFG{ +/*Function to find out minimum valued node +among the nodes which are not yet included +in MST*/ + +static int minnode(int n, int keyval[], + boolean mstset[]) +{ + int mini = Integer.MAX_VALUE; + int mini_index = 0; +/* Loop through all the values of the nodes + which are not yet included in MST and find + the minimum valued one.*/ + + for(int i = 0; i < n; i++) + { + if (mstset[i] == false && + keyval[i] < mini) + { + mini = keyval[i]; + mini_index = i; + } + } + return mini_index; +} +/*Function to find out the MST and +the cost of the MST.*/ + +static void findcost(int n, int city[][]) +{ +/* Array to store the parent node of a + particular node.*/ + + int parent[] = new int[n]; +/* Array to store key value of each node.*/ + + int keyval[] = new int[n]; +/* Boolean Array to hold bool values whether + a node is included in MST or not.*/ + + boolean mstset[] = new boolean[n]; +/* Set all the key values to infinite and + none of the nodes is included in MST.*/ + + for(int i = 0; i < n; i++) + { + keyval[i] = Integer.MAX_VALUE; + mstset[i] = false; + } +/* Start to find the MST from node 0. + Parent of node 0 is none so set -1. + key value or minimum cost to reach + 0th node from 0th node is 0.*/ + + parent[0] = -1; + keyval[0] = 0; +/* Find the rest n-1 nodes of MST.*/ + + for(int i = 0; i < n - 1; i++) + { +/* First find out the minimum node + among the nodes which are not yet + included in MST.*/ + + int u = minnode(n, keyval, mstset); +/* Now the uth node is included in MST.*/ + + mstset[u] = true; +/* Update the values of neighbor + nodes of u which are not yet + included in MST.*/ + + for(int v = 0; v < n; v++) + { + if (city[u][v] > 0 && + mstset[v] == false && + city[u][v] < keyval[v]) + { + keyval[v] = city[u][v]; + parent[v] = u; + } + } + } +/* Find out the cost by adding + the edge values of MST.*/ + + int cost = 0; + for(int i = 1; i < n; i++) + cost += city[parent[i]][i]; + System.out.println(cost); +} +/*Driver code*/ + +public static void main(String args[]) +{ +/* Input 1*/ + + int n1 = 5; + int city1[][] = { { 0, 1, 2, 3, 4 }, + { 1, 0, 5, 0, 7 }, + { 2, 5, 0, 6, 0 }, + { 3, 0, 6, 0, 0 }, + { 4, 7, 0, 0, 0 } }; + findcost(n1, city1); +/* Input 2*/ + + int n2 = 6; + int city2[][] = { { 0, 1, 1, 100, 0, 0 }, + { 1, 0, 1, 0, 0, 0 }, + { 1, 1, 0, 0, 0, 0 }, + { 100, 0, 0, 0, 2, 2 }, + { 0, 0, 0, 2, 0, 2 }, + { 0, 0, 0, 2, 2, 0 } }; + findcost(n2, city2); +} +}"," '''Python3 code to find out minimum cost +path to connect all the cities''' + '''Function to find out minimum valued +node among the nodes which are not +yet included in MST''' + +def minnode(n, keyval, mstset): + mini = 999999999999 + mini_index = None + ''' Loop through all the values of + the nodes which are not yet + included in MST and find the + minimum valued one.''' + + for i in range(n): + if (mstset[i] == False and + keyval[i] < mini): + mini = keyval[i] + mini_index = i + return mini_index + '''Function to find out the MST and +the cost of the MST.''' + +def findcost(n, city): + ''' Array to store the parent + node of a particular node.''' + + parent = [None] * n + ''' Array to store key value + of each node.''' + + keyval = [None] * n + ''' Boolean Array to hold bool + values whether a node is + included in MST or not.''' + + mstset = [None] * n + ''' Set all the key values to infinite and + none of the nodes is included in MST.''' + + for i in range(n): + keyval[i] = 9999999999999 + mstset[i] = False + ''' Start to find the MST from node 0. + Parent of node 0 is none so set -1. + key value or minimum cost to reach + 0th node from 0th node is 0.''' + + parent[0] = -1 + keyval[0] = 0 + ''' Find the rest n-1 nodes of MST.''' + + for i in range(n - 1): + ''' First find out the minimum node + among the nodes which are not yet + included in MST.''' + + u = minnode(n, keyval, mstset) + ''' Now the uth node is included in MST.''' + + mstset[u] = True + ''' Update the values of neighbor + nodes of u which are not yet + included in MST.''' + + for v in range(n): + if (city[u][v] and mstset[v] == False and + city[u][v] < keyval[v]): + keyval[v] = city[u][v] + parent[v] = u + ''' Find out the cost by adding + the edge values of MST.''' + + cost = 0 + for i in range(1, n): + cost += city[parent[i]][i] + print(cost) + '''Driver Code''' + +if __name__ == '__main__': + ''' Input 1''' + + n1 = 5 + city1 = [[0, 1, 2, 3, 4], + [1, 0, 5, 0, 7], + [2, 5, 0, 6, 0], + [3, 0, 6, 0, 0], + [4, 7, 0, 0, 0]] + findcost(n1, city1) + ''' Input 2''' + + n2 = 6 + city2 = [[0, 1, 1, 100, 0, 0], + [1, 0, 1, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [100, 0, 0, 0, 2, 2], + [0, 0, 0, 2, 0, 2], + [0, 0, 0, 2, 2, 0]] + findcost(n2, city2)" +How to print maximum number of A's using given four keys,"/* A Dynamic Programming based C + program to find maximum number + of A's that can be printed using + four keys */ + +import java.io.*; +class GFG { +/* this function returns the optimal + length string for N keystrokes*/ + + static int findoptimal(int N) + { +/* The optimal string length is N + when N is smaller than 7*/ + + if (N <= 6) + return N; +/* An array to store result + of subproblems*/ + + int screen[] = new int[N]; +/*To pick a breakpoint*/ + +int b; +/* Initializing the optimal lengths + array for uptil 6 input strokes*/ + + int n; + for (n = 1; n <= 6; n++) + screen[n - 1] = n; +/* Solve all subproblems in bottom manner*/ + + for (n = 7; n <= N; n++) { +/* Initialize length of optimal + string for n keystrokes*/ + + screen[n - 1] = 0; +/* For any keystroke n, we need + to loop from n-3 keystrokes + back to 1 keystroke to find + a breakpoint 'b' after which we + will have ctrl-a, ctrl-c and + then only ctrl-v all the way.*/ + + for (b = n - 3; b >= 1; b--) { +/* if the breakpoint is + at b'th keystroke then + the optimal string would + have length + (n-b-1)*screen[b-1];*/ + + int curr = (n - b - 1) * screen[b - 1]; + if (curr > screen[n - 1]) + screen[n - 1] = curr; + } + } + return screen[N - 1]; + } +/* Driver program*/ + + public static void main(String[] args) + { + int N; +/* for the rest of the array we will rely on the previous + entries to compute new ones*/ + + for (N = 1; N <= 20; N++) + System.out.println(""Maximum Number of A's with keystrokes is "" + N + findoptimal(N)); + } +}"," '''A Dynamic Programming based Python program +to find maximum number of A's +that can be printed using four keys''' + '''this function returns the optimal +length string for N keystrokes''' + +def findoptimal(N): + ''' The optimal string length is + N when N is smaller than 7''' + + if (N <= 6): + return N + ''' An array to store result of + subproblems''' + + screen = [0]*N + ''' Initializing the optimal lengths + array for uptil 6 input + strokes.''' + + for n in range(1, 7): + screen[n-1] = n + ''' Solve all subproblems in bottom manner''' + + for n in range(7, N + 1): + ''' Initialize length of optimal + string for n keystrokes''' + + screen[n-1] = 0 + ''' For any keystroke n, we need to + loop from n-3 keystrokes + back to 1 keystroke to find a breakpoint + 'b' after which we + will have ctrl-a, ctrl-c and then only + ctrl-v all the way.''' + + for b in range(n-3, 0, -1): + ''' if the breakpoint is at b'th keystroke then + the optimal string would have length + (n-b-1)*screen[b-1];''' + + curr = (n-b-1)*screen[b-1] + if (curr > screen[n-1]): + screen[n-1] = curr + return screen[N-1] + '''Driver program''' + +if __name__ == ""__main__"": + ''' for the rest of the array we + will rely on the previous + entries to compute new ones''' + + for N in range(1, 21): + print(""Maximum Number of A's with "", N, "" keystrokes is "", + findoptimal(N))" +"Find four elements a, b, c and d in an array such that a+b = c+d","/*Java Program to find four different elements a,b,c and d of +array such that a+b = c+d*/ + +import java.io.*; +import java.util.*; +class ArrayElements +{ +/* Class to represent a pair*/ + + class pair + { + int first, second; + pair(int f,int s) + { + first = f; second = s; + } + }; +/*function to find a, b, c, d such that +(a + b) = (c + d)*/ + + boolean findPairs(int arr[]) + { +/* Create an empty Hash to store mapping from sum to + pair indexes*/ + + HashMap map = new HashMap(); + int n=arr.length; +/* Traverse through all possible pairs of arr[]*/ + + for (int i=0; i= 0; i--) + { + if (arr[i] > maxRight) + maxRight = arr[i]; + else + { + int diff = maxRight - arr[i]; + if (diff > maxDiff) + { + maxDiff = diff; + } + } + } + return maxDiff; +} + +/* Driver program to test above function */ + + public static void main (String[] args) { + int arr[] = {1, 2, 90, 10, 110}; + int n = arr.length; + +/*Function calling*/ + + System.out.println (""Maximum difference is "" + maxDiff(arr, n)); + } + +} +"," '''Python3 program to find Maximum difference +between two elements such that larger +element appears after the smaller number''' + + + '''The function assumes that there are +at least two elements in array. The +function returns a negative value if the +array is sorted in decreasing order and +returns 0 if elements are equal''' + +def maxDiff(arr, n): + + ''' Initialize Result''' + + maxDiff = -1 + + ''' Initialize max element from + right side''' + + maxRight = arr[n - 1] + + for i in range(n - 2, -1, -1): + if (arr[i] > maxRight): + maxRight = arr[i] + else: + diff = maxRight - arr[i] + if (diff > maxDiff): + maxDiff = diff + return maxDiff + + '''Driver Code''' + +if __name__ == '__main__': + arr = [1, 2, 90, 10, 110] + n = len(arr) + + ''' Function calling''' + + print(""Maximum difference is"", + maxDiff(arr, n)) + + +" +Rearrange characters in a string such that no two adjacent are same,"/*Java program to rearrange characters in a string +so that no two adjacent characters are same.*/ + +import java.io.*; +import java.util.*; +class KeyComparator implements Comparator { +/* Overriding compare()method of Comparator*/ + + public int compare(Key k1, Key k2) + { + if (k1.freq < k2.freq) + return 1; + else if (k1.freq > k2.freq) + return -1; + return 0; + } +} +class Key { +/*store frequency of character*/ + +int freq; + char ch; + Key(int val, char c) + { + freq = val; + ch = c; + } +} +class GFG { + static int MAX_CHAR = 26; +/* Function to rearrange character of a string + so that no char repeat twice*/ + + static void rearrangeString(String str) + { + int n = str.length(); +/* Store frequencies of all characters in string*/ + + int[] count = new int[MAX_CHAR]; + for (int i = 0; i < n; i++) + count[str.charAt(i) - 'a']++; +/* Insert all characters with their frequencies + into a priority_queue*/ + + PriorityQueue pq + = new PriorityQueue<>(new KeyComparator()); + for (char c = 'a'; c <= 'z'; c++) { + int val = c - 'a'; + if (count[val] > 0) + pq.add(new Key(count[val], c)); + } +/* 'str' that will store resultant value*/ + + str = """"; +/* work as the previous visited element + initial previous element be. ( '#' and + it's frequency '-1' )*/ + + Key prev = new Key(-1, '#'); +/* traverse queue*/ + + while (pq.size() != 0) { +/* pop top element from queue and add it + to string.*/ + + Key k = pq.peek(); + pq.poll(); + str = str + k.ch; +/* If frequency of previous character is less + than zero that means it is useless, we + need not to push it*/ + + if (prev.freq > 0) + pq.add(prev); +/* make current character as the previous 'char' + decrease frequency by 'one'*/ + + (k.freq)--; + prev = k; + } +/* If length of the resultant string and original + string is not same then string is not valid*/ + + if (n != str.length()) + System.out.println("" Not valid String ""); + +/*valid string*/ + + else + System.out.println(str); + }/* Driver program to test above function*/ + + public static void main(String args[]) + { + String str = ""bbbaa""; + rearrangeString(str); + } +}", +Maximize sum of diagonal of a matrix by rotating all rows or all columns,"/*Java program to implement +the above approach*/ + +import java.util.*; + +class GFG{ + +static int N = 3; + +/*Function to find maximum sum of +diagonal elements of matrix by +rotating either rows or columns*/ + +static int findMaximumDiagonalSumOMatrixf(int A[][]) +{ + +/* Stores maximum diagonal sum of elements + of matrix by rotating rows or columns*/ + + int maxDiagonalSum = Integer.MIN_VALUE; + +/* Rotate all the columns by an integer + in the range [0, N - 1]*/ + + for(int i = 0; i < N; i++) + { + +/* Stores sum of diagonal elements + of the matrix*/ + + int curr = 0; + +/* Calculate sum of diagonal + elements of the matrix*/ + + for(int j = 0; j < N; j++) + { + +/* Update curr*/ + + curr += A[j][(i + j) % N]; + } + +/* Update maxDiagonalSum*/ + + maxDiagonalSum = Math.max(maxDiagonalSum, + curr); + } + +/* Rotate all the rows by an integer + in the range [0, N - 1]*/ + + for(int i = 0; i < N; i++) + { + +/* Stores sum of diagonal elements + of the matrix*/ + + int curr = 0; + +/* Calculate sum of diagonal + elements of the matrix*/ + + for(int j = 0; j < N; j++) + { + +/* Update curr*/ + + curr += A[(i + j) % N][j]; + } + +/* Update maxDiagonalSum*/ + + maxDiagonalSum = Math.max(maxDiagonalSum, + curr); + } + return maxDiagonalSum; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int[][] mat = { { 1, 1, 2 }, + { 2, 1, 2 }, + { 1, 2, 2 } }; + + System.out.println( + findMaximumDiagonalSumOMatrixf(mat)); +} +} + + +"," '''Python3 program to implement +the above approach''' + +import sys + +N = 3 + + '''Function to find maximum sum of diagonal +elements of matrix by rotating either +rows or columns''' + +def findMaximumDiagonalSumOMatrixf(A): + + ''' Stores maximum diagonal sum of elements + of matrix by rotating rows or columns''' + + maxDiagonalSum = -sys.maxsize - 1 + + ''' Rotate all the columns by an integer + in the range [0, N - 1]''' + + for i in range(N): + + ''' Stores sum of diagonal elements + of the matrix''' + + curr = 0 + + ''' Calculate sum of diagonal + elements of the matrix''' + + for j in range(N): + + ''' Update curr''' + + curr += A[j][(i + j) % N] + + ''' Update maxDiagonalSum''' + + maxDiagonalSum = max(maxDiagonalSum, + curr) + + ''' Rotate all the rows by an integer + in the range [0, N - 1]''' + + for i in range(N): + + ''' Stores sum of diagonal elements + of the matrix''' + + curr = 0 + + ''' Calculate sum of diagonal + elements of the matrix''' + + for j in range(N): + + ''' Update curr''' + + curr += A[(i + j) % N][j] + + ''' Update maxDiagonalSum''' + + maxDiagonalSum = max(maxDiagonalSum, + curr) + + return maxDiagonalSum + + '''Driver code''' + +if __name__ == ""__main__"": + + mat = [ [ 1, 1, 2 ], + [ 2, 1, 2 ], + [ 1, 2, 2 ] ] + + print(findMaximumDiagonalSumOMatrixf(mat)) + + +" +Bucket Sort,"/*Java program to sort an array +using bucket sort*/ + +import java.util.*; +import java.util.Collections; +class GFG { +/* Function to sort arr[] of size n + using bucket sort*/ + + static void bucketSort(float arr[], int n) + { + if (n <= 0) + return; +/* 1) Create n empty buckets*/ + + @SuppressWarnings(""unchecked"") + Vector[] buckets = new Vector[n]; + for (int i = 0; i < n; i++) { + buckets[i] = new Vector(); + } +/* 2) Put array elements in different buckets*/ + + for (int i = 0; i < n; i++) { + float idx = arr[i] * n; + buckets[(int)idx].add(arr[i]); + } +/* 3) Sort individual buckets*/ + + for (int i = 0; i < n; i++) { + Collections.sort(buckets[i]); + } +/* 4) Concatenate all buckets into arr[]*/ + + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < buckets[i].size(); j++) { + arr[index++] = buckets[i].get(j); + } + } + } +/* Driver code*/ + + public static void main(String args[]) + { + float arr[] = { (float)0.897, (float)0.565, + (float)0.656, (float)0.1234, + (float)0.665, (float)0.3434 }; + int n = arr.length; + bucketSort(arr, n); + System.out.println(""Sorted array is ""); + for (float el : arr) { + System.out.print(el + "" ""); + } + } +}", +Maximum sum of nodes in Binary tree such that no two are adjacent,"/*Java program to find maximum sum in Binary Tree +such that no two nodes are adjacent.*/ + +public class FindSumOfNotAdjacentNodes { +/* A binary tree node structure */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + this.data=data; + left=right=null; + } +}; +/*maxSumHelper function */ + + public static Pair maxSumHelper(Node root) + { + if (root==null) + { + Pair sum=new Pair(0, 0); + return sum; + } + Pair sum1 = maxSumHelper(root.left); + Pair sum2 = maxSumHelper(root.right); + Pair sum=new Pair(0,0); +/* This node is included (Left and right children + are not included)*/ + + sum.first = sum1.second + sum2.second + root.data; +/* This node is excluded (Either left or right + child is included)*/ + + sum.second = Math.max(sum1.first, sum1.second) + + Math.max(sum2.first, sum2.second); + return sum; + } +/* Returns maximum sum from subset of nodes + of binary tree under given constraints*/ + + public static int maxSum(Node root) + { + Pair res=maxSumHelper(root); + return Math.max(res.first, res.second); + } + +/*Driver code*/ + + public static void main(String args[]) { + Node root= new Node(10); + root.left= new Node(1); + root.left.left= new Node(2); + root.left.left.left= new Node(1); + root.left.right= new Node(3); + root.left.right.left= new Node(4); + root.left.right.right= new Node(5); + System.out.print(maxSum(root)); + } +}/* Pair class */ + +class Pair +{ + int first,second; + Pair(int first,int second) + { + this.first=first; + this.second=second; + } +}", +Sum of minimum absolute difference of each array element,"/*java implementation to find the sum +of minimum absolute difference of +each array element*/ + +import java.*; +import java.util.Arrays; + +public class GFG { + +/* function to find the sum of + minimum absolute difference*/ + + static int sumOfMinAbsDifferences( + int arr[] ,int n) + { + +/* sort the given array*/ + + Arrays.sort(arr); + +/* initialize sum*/ + + int sum = 0; + +/* min absolute difference for + the 1st array element*/ + + sum += Math.abs(arr[0] - arr[1]); + +/* min absolute difference for + the last array element*/ + + sum += Math.abs(arr[n-1] - arr[n-2]); + +/* find min absolute difference for + rest of the array elements and + add them to sum*/ + + for (int i = 1; i < n - 1; i++) + sum += + Math.min(Math.abs(arr[i] - arr[i-1]), + Math.abs(arr[i] - arr[i+1])); + +/* required sum*/ + + return sum; + } + +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = {5, 10, 1, 4, 8, 7}; + int n = arr.length; + + System.out.println( ""Sum = "" + + sumOfMinAbsDifferences(arr, n)); + } +} + + +"," '''Python implementation to find the +sum of minimum absolute difference +of each array element''' + + + '''function to find the sum of +minimum absolute difference''' + + +def sumOfMinAbsDifferences(arr,n): + ''' sort the given array''' + + arr.sort() + ''' initialize sum''' + + sum = 0 + + ''' min absolute difference for + the 1st array element''' + + sum += abs(arr[0] - arr[1]); + + ''' min absolute difference for + the last array element''' + + sum += abs(arr[n - 1] - arr[n - 2]); + + ''' find min absolute difference for + rest of the array elements and + add them to sum''' + + for i in range(1, n - 1): + sum += min(abs(arr[i] - arr[i - 1]), + abs(arr[i] - arr[i + 1])) + + ''' required sum''' + + return sum; + + + '''Driver code''' + +arr = [5, 10, 1, 4, 8, 7] +n = len(arr) +print( ""Sum = "", sumOfMinAbsDifferences(arr, n)) + + + +" +Find next right node of a given key | Set 2,"/* Java program to find next right of a given key +using preorder traversal */ + +import java.util.*; +class GfG { +/*A Binary Tree Node*/ + +static class Node { + Node left, right; + int key; +} +/*Utility function to create a new tree node*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.key = key; + temp.left = null; + temp.right = null; + return temp; +} +/*Function to find next node for given node +in same level in a binary tree by using +pre-order traversal*/ + +static Node nextRightNode(Node root, int k, int level, int[] value) +{ +/* return null if tree is empty*/ + + if (root == null) + return null; +/* if desired node is found, set value[0] + to current level*/ + + if (root.key == k) { + value[0] = level; + return null; + } +/* if value[0] is already set, then current + node is the next right node*/ + + else if (value[0] != 0) { + if (level == value[0]) + return root; + } +/* recurse for left subtree by increasing level by 1*/ + + Node leftNode = nextRightNode(root.left, k, level + 1, value); +/* if node is found in left subtree, return it*/ + + if (leftNode != null) + return leftNode; +/* recurse for right subtree by increasing level by 1*/ + + return nextRightNode(root.right, k, level + 1, value); +} +/*Function to find next node of given node in the +same level in given binary tree*/ + +static Node nextRightNodeUtil(Node root, int k) +{ + int[] v = new int[1]; + v[0] = 0; + return nextRightNode(root, k, 1, v); +} +/*A utility function to test above functions*/ + +static void test(Node root, int k) +{ + Node nr = nextRightNodeUtil(root, k); + if (nr != null) + System.out.println(""Next Right of "" + k + "" is ""+ nr.key); + else + System.out.println(""No next right node found for "" + k); +} +/*Driver program to test above functions*/ + +public static void main(String[] args) +{ +/* Let us create binary tree given in the + above example*/ + + Node root = newNode(10); + root.left = newNode(2); + root.right = newNode(6); + root.right.right = newNode(5); + root.left.left = newNode(8); + root.left.right = newNode(4); + test(root, 10); + test(root, 2); + test(root, 6); + test(root, 5); + test(root, 8); + test(root, 4); +} +}"," '''Python3 program to find next right of a +given key using preorder traversal''' + + '''class to create a new tree node''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None '''Function to find next node for given node +in same level in a binary tree by using +pre-order traversal''' + +def nextRightNode(root, k, level, value_level): + ''' return None if tree is empty''' + + if (root == None): + return None + ''' if desired node is found, set + value_level to current level''' + + if (root.key == k): + value_level[0] = level + return None + ''' if value_level is already set, then + current node is the next right node''' + + elif (value_level[0]): + if (level == value_level[0]): + return root + ''' recurse for left subtree by increasing + level by 1''' + + leftNode = nextRightNode(root.left, k, + level + 1, value_level) + ''' if node is found in left subtree, + return it''' + + if (leftNode): + return leftNode + ''' recurse for right subtree by + increasing level by 1''' + + return nextRightNode(root.right, k, + level + 1, value_level) + '''Function to find next node of given node +in the same level in given binary tree''' + +def nextRightNodeUtil(root, k): + value_level = [0] + return nextRightNode(root, k, 1, value_level) + '''A utility function to test above functions''' + +def test(root, k): + nr = nextRightNodeUtil(root, k) + if (nr != None): + print(""Next Right of"", k, ""is"", nr.key) + else: + print(""No next right node found for"", k) + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create binary tree given in the + above example''' + + root = newNode(10) + root.left = newNode(2) + root.right = newNode(6) + root.right.right = newNode(5) + root.left.left = newNode(8) + root.left.right = newNode(4) + test(root, 10) + test(root, 2) + test(root, 6) + test(root, 5) + test(root, 8) + test(root, 4)" +Print the nodes at odd levels of a tree,"/*Recursive Java program to print odd level nodes*/ + +class GfG { +static class Node { + int data; + Node left, right; +} +static void printOddNodes(Node root, boolean isOdd) +{ +/* If empty tree*/ + + if (root == null) + return; +/* If current node is of odd level*/ + + if (isOdd == true) + System.out.print(root.data + "" ""); +/* Recur for children with isOdd + switched.*/ + + printOddNodes(root.left, !isOdd); + printOddNodes(root.right, !isOdd); +} +/*Utility method to create a node*/ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + printOddNodes(root, true); +} +}"," '''Recursive Python3 program to print +odd level nodes +Utility method to create a node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None +def printOddNodes(root, isOdd = True): + ''' If empty tree''' + + if (root == None): + return + ''' If current node is of odd level''' + + if (isOdd): + print(root.data, end = "" "") + ''' Recur for children with isOdd + switched.''' + + printOddNodes(root.left, not isOdd) + printOddNodes(root.right, not isOdd) + '''Driver code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + printOddNodes(root)" +Check if reversing a sub array make the array sorted,"/*Java program to check whether reversing a sub array +make the array sorted or not*/ + + +class GFG { + +/*Return true, if reversing the subarray will sort t +he array, else return false.*/ + + static boolean checkReverse(int arr[], int n) { + if (n == 1) { + return true; + } + +/* Find first increasing part*/ + + int i; + for (i = 1; arr[i - 1] < arr[i] && i < n; i++); + if (i == n) { + return true; + } + +/* Find reversed part*/ + + int j = i; + while (j < n && arr[j] < arr[j - 1]) { + if (i > 1 && arr[j] < arr[i - 2]) { + return false; + } + j++; + } + + if (j == n) { + return true; + } + +/* Find last increasing part*/ + + int k = j; + +/* To handle cases like {1,2,3,4,20,9,16,17}*/ + + if (arr[k] < arr[i - 1]) { + return false; + } + + while (k > 1 && k < n) { + if (arr[k] < arr[k - 1]) { + return false; + } + k++; + } + return true; + } + +/*Driven Program*/ + + public static void main(String[] args) { + + int arr[] = {1, 3, 4, 10, 9, 8}; + int n = arr.length; + + if (checkReverse(arr, n)) { + System.out.print(""Yes""); + } else { + System.out.print(""No""); + } + } + +} + + +"," '''Python3 program to check whether reversing +a sub array make the array sorted or not''' + +import math as mt + + '''Return True, if reversing the subarray +will sort the array, else return False.''' + +def checkReverse(arr, n): + + if (n == 1): + return True + + ''' Find first increasing part''' + + i = 1 + for i in range(1, n): + if arr[i - 1] < arr[i] : + if (i == n): + return True + + else: + break + + ''' Find reversed part''' + + j = i + while (j < n and arr[j] < arr[j - 1]): + + if (i > 1 and arr[j] < arr[i - 2]): + return False + j += 1 + + if (j == n): + return True + + ''' Find last increasing part''' + + k = j + + ''' To handle cases like 1,2,3,4,20,9,16,17''' + + if (arr[k] < arr[i - 1]): + return False + + while (k > 1 and k < n): + + if (arr[k] < arr[k - 1]): + return False + k += 1 + + return True + + '''Driver Code''' + +arr = [ 1, 3, 4, 10, 9, 8] +n = len(arr) +if checkReverse(arr, n): + print(""Yes"") +else: + print(""No"") + + +" +Count all sorted rows in a matrix,"/*Java program to find number of sorted rows*/ + +class GFG { + static int MAX = 100; +/* Function to count all sorted rows in a matrix*/ + + static int sortedCount(int mat[][], int r, int c) + { +/*Initialize result*/ + +int result = 0; +/* Start from left side of matrix to + count increasing order rows*/ + + for (int i = 0; i < r; i++) { +/* Check if there is any pair ofs element + that are not in increasing order.*/ + + int j; + for (j = 0; j < c - 1; j++) + if (mat[i][j + 1] <= mat[i][j]) + break; +/* If the loop didn't break (All elements + of current row were in increasing order)*/ + + if (j == c - 1) + result++; + } +/* Start from right side of matrix to + count increasing order rows ( reference + to left these are in decreasing order )*/ + + for (int i = 0; i < r; i++) { +/* Check if there is any pair ofs element + that are not in decreasing order.*/ + + int j; + for (j = c - 1; j > 0; j--) + if (mat[i][j - 1] <= mat[i][j]) + break; +/* Note c > 1 condition is required to make + sure that a single column row is not counted + twice (Note that a single column row is sorted + both in increasing and decreasing order)*/ + + if (c > 1 && j == 0) + result++; + } + return result; + } +/* Driver code*/ + + public static void main(String arg[]) + { + int m = 4, n = 5; + int mat[][] = { { 1, 2, 3, 4, 5 }, + { 4, 3, 1, 2, 6 }, + { 8, 7, 6, 5, 4 }, + { 5, 7, 8, 9, 10 } }; + System.out.print(sortedCount(mat, m, n)); + } +}"," '''Python3 program to find number +of sorted rows''' + + + '''Function to count all sorted rows in a matrix''' + +def sortedCount(mat, r, c): + '''Initialize result''' + + result = 0 ''' Start from left side of matrix to + count increasing order rows''' + + for i in range(r): + ''' Check if there is any pair ofs element + that are not in increasing order.''' + + j = 0 + for j in range(c - 1): + if mat[i][j + 1] <= mat[i][j]: + break + ''' If the loop didn't break (All elements + of current row were in increasing order)''' + + if j == c - 2: + result += 1 + ''' Start from right side of matrix to + count increasing order rows ( reference + to left these are in decreasing order )''' + + for i in range(0, r): + ''' Check if there is any pair ofs element + that are not in decreasing order.''' + + j = 0 + for j in range(c - 1, 0, -1): + if mat[i][j - 1] <= mat[i][j]: + break + ''' Note c > 1 condition is required to + make sure that a single column row + is not counted twice (Note that a + single column row is sorted both + in increasing and decreasing order)''' + + if c > 1 and j == 1: + result += 1 + return result + '''Driver code''' + +m, n = 4, 5 +mat = [[1, 2, 3, 4, 5], + [4, 3, 1, 2, 6], + [8, 7, 6, 5, 4], + [5, 7, 8, 9, 10]] +print(sortedCount(mat, m, n))" +Reorder an array according to given indexes,"/*A O(n) time and O(1) extra space Java program to +sort an array according to given indexes*/ + +import java.util.Arrays; +class Test +{ + static int arr[] = new int[]{50, 40, 70, 60, 90}; + static int index[] = new int[]{3, 0, 4, 1, 2}; +/* Method to reorder elements of arr[] according + to index[]*/ + + static void reorder() + { +/* Fix all elements one by one*/ + + for (int i=0; i n) + return 0; + if (k == 0 || k == n) + return 1; +/* Recur*/ + + return binomialCoeff(n - 1, k - 1) + + binomialCoeff(n - 1, k); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int n = 5, k = 2; + System.out.printf(""Value of C(%d, %d) is %d "", n, k, + binomialCoeff(n, k)); + } +}"," '''A naive recursive Python implementation''' + + ''' Returns value of Binomial + Coefficient C(n, k)''' + +def binomialCoeff(n, k): ''' Base Cases''' + + if k > n: + return 0 + if k == 0 or k == n: + return 1 + ''' Recursive Call''' + + return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k) + '''Driver Program to test ht above function''' + +n = 5 +k = 2 +print ""Value of C(%d,%d) is (%d)"" % (n, k, + binomialCoeff(n, k))" +Inorder predecessor and successor for a given key in BST,," ''' Python3 code for inorder successor +and predecessor of tree ''' + + '''A Binary Tree Node +Utility function to create a new tree node''' + +class getnode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None ''' +since inorder traversal results in +ascendingorder visit to node , we +can store the values of the largest +o which is smaller than a (predecessor) +and smallest no which is large than +a (successor) using inorder traversal + ''' + +def find_p_s(root, a, p, q): + ''' If root is None return''' + + if(not root): + return + ''' traverse the left subtree ''' + + find_p_s(root.left, a, p, q) + ''' root data is greater than a''' + + if(root and root.data > a): + ''' q stores the node whose data is greater + than a and is smaller than the previously + stored data in *q which is successor''' + + if((not q[0]) or q[0] and + q[0].data > root.data): + q[0] = root + ''' if the root data is smaller than + store it in p which is predecessor''' + + elif(root and root.data < a): + p[0]= root + ''' traverse the right subtree''' + + find_p_s(root.right, a, p, q) + '''Driver Code''' + +if __name__ == '__main__': + root1 = getnode(50) + root1.left = getnode(20) + root1.right = getnode(60) + root1.left.left = getnode(10) + root1.left.right = getnode(30) + root1.right.left = getnode(55) + root1.right.right = getnode(70) + p = [None] + q = [None] + find_p_s(root1, 55, p, q) + if(p[0]) : + print(p[0].data, end = """") + if(q[0]) : + print("""", q[0].data)" +Find Second largest element in an array,"/*Java program to find second largest +element in an array*/ + +class GFG{ +/*Function to print the second largest elements*/ + +static void print2largest(int arr[], int arr_size) +{ + int i, first, second; +/* There should be atleast two elements*/ + + if (arr_size < 2) + { + System.out.printf("" Invalid Input ""); + return; + } + int largest = second = Integer.MIN_VALUE; +/* Find the largest element*/ + + for(i = 0; i < arr_size; i++) + { + largest = Math.max(largest, arr[i]); + } +/* Find the second largest element*/ + + for(i = 0; i < arr_size; i++) + { + if (arr[i] != largest) + second = Math.max(second, arr[i]); + } + if (second == Integer.MIN_VALUE) + System.out.printf(""There is no second "" + + ""largest element\n""); + else + System.out.printf(""The second largest "" + + ""element is %d\n"", second); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 12, 35, 1, 10, 34, 1 }; + int n = arr.length; + print2largest(arr, n); +} +}"," '''Python3 program to find +second largest element +in an array''' + + '''Function to print +second largest elements''' + +def print2largest(arr, arr_size): ''' There should be atleast + two elements''' + + if (arr_size < 2): + print("" Invalid Input ""); + return; + largest = second = -2454635434; + ''' Find the largest element''' + + for i in range(0, arr_size): + largest = max(largest, arr[i]); + ''' Find the second largest element''' + + for i in range(0, arr_size): + if (arr[i] != largest): + second = max(second, arr[i]); + if (second == -2454635434): + print(""There is no second "" + + ""largest element""); + else: + print(""The second largest "" + + ""element is \n"", second); + '''Driver code''' + +if __name__ == '__main__': + arr = [12, 35, 1, + 10, 34, 1]; + n = len(arr); + print2largest(arr, n);" +Efficient program to calculate e^x,"/*Java efficient program to calculate +e raise to the power x*/ + +import java.io.*; +class GFG +{ +/* Function returns approximate value of e^x + using sum of first n terms of Taylor Series*/ + + static float exponential(int n, float x) + { +/* initialize sum of series*/ + + float sum = 1; + for (int i = n - 1; i > 0; --i ) + sum = 1 + x * sum / i; + return sum; + } +/* driver program*/ + + public static void main (String[] args) + { + int n = 10; + float x = 1; + System.out.println(""e^x = ""+exponential(n,x)); + } +} +"," '''Python program to calculate +e raise to the power x''' + + '''Function to calculate value +using sum of first n terms of +Taylor Series''' + +def exponential(n, x): ''' initialize sum of series''' + + sum = 1.0 + for i in range(n, 0, -1): + sum = 1 + x * sum / i + print (""e^x ="", sum) + '''Driver program to test above function''' + +n = 10 +x = 1.0 +exponential(n, x)" +Level order traversal line by line | Set 3 (Using One Queue),"/*Java program to do level order +traversal line by line*/ + +import java.util.LinkedList; +import java.util.Queue; +public class GFG { +/*A Binary Tree Node*/ + + static class Node { + int data; + Node left; + Node right; + Node(int data) { + this.data = data; + left = null; + right = null; + } + } +/* Prints level order traversal line + by line using two queues.*/ + + static void levelOrder(Node root) { + if (root == null) + return; + +/* Create an empty queue for + level order traversal*/ + + Queue q = new LinkedList<>();/* Pushing root node into the queue.*/ + + q.add(root); +/* Pushing delimiter into the queue.*/ + + q.add(null); +/* Executing loop till queue becomes + empty*/ + + while (!q.isEmpty()) { + Node curr = q.poll(); +/* condition to check the + occurence of next level*/ + + if (curr == null) { + if (!q.isEmpty()) { + q.add(null); + System.out.println(); + } + } else { +/* Pushing left child current node*/ + + if (curr.left != null) + q.add(curr.left); +/* Pushing right child current node*/ + + if (curr.right != null) + q.add(curr.right); + System.out.print(curr.data + "" ""); + } + } + } +/* Driver function*/ + + public static void main(String[] args) { + +/* Let us create binary tree + shown above*/ + + 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.right = new Node(6); + levelOrder(root); + } +}"," '''Python3 program to print levels +line by line ''' + +from collections import deque as queue + '''A Binary Tree Node''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Function to do level order +traversal line by line''' + +def levelOrder(root): + if (root == None): + return + ''' Create an empty queue for + level order traversal''' + + q = queue() + ''' Pushing root node into the queue.''' + + q.append(root) + + ''' Pushing delimiter into the queue.''' + + q.append(None) + ''' Condition to check + occurrence of next + level.''' + while (len(q) > 1): + curr = q.popleft() + + ''' Pushing left child of + current node.''' + if (curr == None): + q.append(None) + print() + else: + + ''' Pushing left child current node''' + + if (curr.left): + q.append(curr.left) ''' Pushing right child of + current node.''' + + if (curr.right): + q.append(curr.right) + print(curr.data, end = "" "") + '''Driver code''' + +if __name__ == '__main__': + ''' Let us create binary tree + shown above''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.right = Node(6) + levelOrder(root)" +Modify a string by performing given shift operations,"/*Java implementataion +of above approach*/ + +import java.io.*; +class GFG +{ + +/* Function to find the string obtained + after performing given shift operations*/ + + static void stringShift(String s, int[][] shift) + { + int val = 0; + for (int i = 0; i < shift.length; ++i) + +/* If shift[i][0] = 0, then left shift + Otherwise, right shift*/ + + if (shift[i][0] == 0) + val -= shift[i][1]; + else + val += shift[i][1]; + +/* Stores length of the string*/ + + int len = s.length(); + +/* Effective shift calculation*/ + + val = val % len; + +/* Stores modified string*/ + + String result = """"; + +/* Right rotation*/ + + if (val > 0) + result = s.substring(len - val, (len - val) + val) + + s.substring(0, len - val); + +/* Left rotation*/ + + else + result = s.substring(-val, len + val) + + s.substring(0, -val); + + System.out.println(result); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + String s = ""abc""; + int[][] shift + = new int[][] {{ 0, 1 }, { 1, 2 }}; + + stringShift(s, shift); + } +} + + +", +Diagonal Sum of a Binary Tree,"/*Java Program to calculate the +sum of diagonal nodes.*/ + +import java.util.*; +class GFG +{ +/*Node Structure*/ + +static class Node +{ + int data; + Node left, right; +}; +/*to map the node with level - index*/ + +static HashMap grid = new HashMap<>(); +/*Function to create new node*/ + +static Node newNode(int data) +{ + Node Node = new Node(); + Node.data = data; + Node.left = Node.right = null; + return Node; +} +/*recursvise function to calculate sum of elements +where level - index is same.*/ + +static void addConsideringGrid(Node root, int level, int index) +{ +/* if there is no child then return*/ + + if (root == null) + return; +/* add the element in the group of node + whose level - index is equal*/ + + if(grid.containsKey(level-index)) + grid.put(level - index,grid.get(level-index) + (root.data)); + else + grid.put(level-index, root.data); +/* left child call*/ + + addConsideringGrid(root.left, level + 1, index - 1); +/* right child call*/ + + addConsideringGrid(root.right, level + 1, index + 1); +} +static Vector diagonalSum(Node root) +{ + grid.clear(); +/* Function call*/ + + addConsideringGrid(root, 0, 0); + Vector ans = new Vector<>(); +/* for different values of level - index + add te sum of those node to answer*/ + + for (Map.Entry x : grid.entrySet()) + { + ans.add(x.getValue()); + } + return ans; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* build binary tree*/ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(9); + root.left.right = newNode(6); + root.right.left = newNode(4); + root.right.right = newNode(5); + root.right.left.right = newNode(7); + root.right.left.left = newNode(12); + root.left.right.left = newNode(11); + root.left.left.right = newNode(10); +/* Function Call*/ + + Vector v = diagonalSum(root); +/* print the daigonal sums*/ + + for (int i = 0; i < v.size(); i++) + System.out.print(v.get(i) + "" ""); + } +}"," '''Python3 program calculate the +sum of diagonal nodes.''' + +from collections import deque + '''A binary tree node structure''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''To map the node with level - index''' + +grid = {} + '''Recursvise function to calculate +sum of elements where level - index +is same''' + +def addConsideringGrid(root, level, index): + global grid + ''' If there is no child then return''' + + if (root == None): + return + ''' Add the element in the group of node + whose level - index is equal''' + + grid[level - index] = (grid.get(level - index, 0) + + root.data) + ''' Left child call''' + + addConsideringGrid(root.left, level + 1, + index - 1) + ''' Right child call''' + + addConsideringGrid(root.right, level + 1, + index + 1) +def diagonalSum(root): + '''Function call''' + + addConsideringGrid(root, 0, 0) + ans = [] + ''' For different values of level - index + add te sum of those node to answer''' + + for x in grid: + ans.append(grid[x]) + return ans + '''Driver code''' + +if __name__ == '__main__': + ''' Build binary tree''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(9) + root.left.right = Node(6) + root.right.left = Node(4) + root.right.right = Node(5) + root.right.left.right = Node(7) + root.right.left.left = Node(12) + root.left.right.left = Node(11) + root.left.left.right = Node(10) + ''' Function Call''' + + v = diagonalSum(root) + ''' Print the daigonal sums''' + + for i in v: + print(i, end = "" "")" +Difference between sums of odd level and even level nodes of a Binary Tree,"/*A recursive java program to find difference between sum of nodes at +odd level and sum at even level*/ + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right; + } +} +class BinaryTree +{/* The main function that return difference between odd and even level + nodes*/ + + Node root; + int getLevelDiff(Node node) + { +/* Base case*/ + + if (node == null) + return 0; +/* Difference for root is root's data - difference for + left subtree - difference for right subtree*/ + + return node.data - getLevelDiff(node.left) - + getLevelDiff(node.right); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(5); + tree.root.left = new Node(2); + tree.root.right = new Node(6); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(4); + tree.root.left.right.left = new Node(3); + tree.root.right.right = new Node(8); + tree.root.right.right.right = new Node(9); + tree.root.right.right.left = new Node(7); + System.out.println(tree.getLevelDiff(tree.root) + + "" is the required difference""); + } +}"," '''A recursive program to find difference between sum of nodes +at odd level and sum at even level''' + + '''A Binary Tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''The main function that returns difference between odd and +even level nodes''' + +def getLevelDiff(root): + ''' Base Case ''' + + if root is None: + return 0 + ''' Difference for root is root's data - difference for + left subtree - difference for right subtree''' + + return (root.data - getLevelDiff(root.left)- + getLevelDiff(root.right)) + '''Driver program to test above function''' + +root = Node(5) +root.left = Node(2) +root.right = Node(6) +root.left.left = Node(1) +root.left.right = Node(4) +root.left.right.left = Node(3) +root.right.right = Node(8) +root.right.right.right = Node(9) +root.right.right.left = Node(7) +print ""%d is the required difference"" %(getLevelDiff(root))" +Find missing elements of a range,"/*A hashing based Java program to find missing +elements from an array*/ + +import java.util.Arrays; +import java.util.HashSet; +public class Print { +/* Print all elements of range [low, high] that + are not present in arr[0..n-1]*/ + + static void printMissing(int ar[], int low, int high) + { + HashSet hs = new HashSet<>(); +/* Insert all elements of arr[] in set*/ + + for (int i = 0; i < ar.length; i++) + hs.add(ar[i]); +/* Traverse throught the range an print all + missing elements*/ + + for (int i = low; i <= high; i++) { + if (!hs.contains(i)) { + System.out.print(i + "" ""); + } + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 5, 4 }; + int low = 1, high = 10; + printMissing(arr, low, high); + } +}"," '''A hashing based Python3 program to +find missing elements from an array + ''' '''Print all elements of range +[low, high] that are not +present in arr[0..n-1]''' + +def printMissing(arr, n, low, high): + ''' Insert all elements of + arr[] in set''' + + s = set(arr) + ''' Traverse through the range + and print all missing elements''' + + for x in range(low, high + 1): + if x not in s: + print(x, end = ' ') + '''Driver Code''' + +arr = [1, 3, 5, 4] +n = len(arr) +low, high = 1, 10 +printMissing(arr, n, low, high)" +Rearrange a linked list such that all even and odd positioned nodes are together,"/*Java program to rearrange a linked list +in such a way that all odd positioned +node are stored before all even positioned nodes*/ + +class GfG +{ + +/*Linked List Node*/ + +static class Node +{ + int data; + Node next; +} + +/*A utility function to create a new node*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; +} + +/*Rearranges given linked list +such that all even positioned +nodes are before odd positioned. +Returns new head of linked List.*/ + +static Node rearrangeEvenOdd(Node head) +{ +/* Corner case*/ + + if (head == null) + return null; + +/* Initialize first nodes of even and + odd lists*/ + + Node odd = head; + Node even = head.next; + +/* Remember the first node of even list so + that we can connect the even list at the + end of odd list.*/ + + Node evenFirst = even; + + while (1 == 1) + { +/* If there are no more nodes, + then connect first node of even + list to the last node of odd list*/ + + if (odd == null || even == null || + (even.next) == null) + { + odd.next = evenFirst; + break; + } + +/* Connecting odd nodes*/ + + odd.next = even.next; + odd = even.next; + +/* If there are NO more even nodes + after current odd.*/ + + if (odd.next == null) + { + even.next = null; + odd.next = evenFirst; + break; + } + +/* Connecting even nodes*/ + + even.next = odd.next; + even = odd.next; + } + return head; +} + +/*A utility function to print a linked list*/ + +static void printlist(Node node) +{ + while (node != null) + { + System.out.print(node.data + ""->""); + node = node.next; + } + System.out.println(""NULL"") ; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + 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); + + System.out.println(""Given Linked List""); + printlist(head); + + head = rearrangeEvenOdd(head); + + System.out.println(""Modified Linked List""); + printlist(head); +} +} + + +"," '''Python3 program to rearrange a linked list +in such a way that all odd positioned +node are stored before all even positioned nodes''' + + + '''Linked List Node''' + +class Node: + def __init__(self, d): + self.data = d + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + + ''' A utility function to create + a new node''' + + def newNode(self, key): + temp = Node(key) + self.next = None + return temp + + ''' Rearranges given linked list + such that all even positioned + nodes are before odd positioned. + Returns new head of linked List.''' + + def rearrangeEvenOdd(self, head): + + ''' Corner case''' + + if (self.head == None): + return None + + ''' Initialize first nodes of + even and odd lists''' + + odd = self.head + even = self.head.next + + ''' Remember the first node of even list so + that we can connect the even list at the + end of odd list.''' + + evenFirst = even + + while (1 == 1): + + ''' If there are no more nodes, + then connect first node of even + list to the last node of odd list''' + + if (odd == None or even == None or + (even.next) == None): + odd.next = evenFirst + break + + ''' Connecting odd nodes''' + + odd.next = even.next + odd = even.next + + ''' If there are NO more even nodes + after current odd.''' + + if (odd.next == None): + even.next = None + odd.next = evenFirst + break + + ''' Connecting even nodes''' + + even.next = odd.next + even = odd.next + return head + + ''' A utility function to print a linked list''' + + def printlist(self, node): + while (node != None): + print(node.data, end = """") + print(""->"", end = """") + node = node.next + print (""NULL"") + + ''' Function to insert a new node + at the beginning''' + + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + '''Driver code''' + +ll = LinkedList() +ll.push(5) +ll.push(4) +ll.push(3) +ll.push(2) +ll.push(1) +print (""Given Linked List"") +ll.printlist(ll.head) + +start = ll.rearrangeEvenOdd(ll.head) + +print (""\nModified Linked List"") +ll.printlist(start) + + +" +Find the first repeating element in an array of integers,"/* Java program to find first repeating element in arr[] */ + +import java.util.*; +class Main +{ +/* This function prints the first repeating element in arr[]*/ + + static void printFirstRepeating(int arr[]) + { +/* Initialize index of first repeating element*/ + + int min = -1; +/* Creates an empty hashset*/ + + HashSet set = new HashSet<>(); +/* Traverse the input array from right to left*/ + + for (int i=arr.length-1; i>=0; i--) + { +/* If element is already in hash set, update min*/ + + if (set.contains(arr[i])) + min = i; +/*Else add element to hash set*/ + +else + set.add(arr[i]); + } +/* Print the result*/ + + if (min != -1) + System.out.println(""The first repeating element is "" + arr[min]); + else + System.out.println(""There are no repeating elements""); + } +/* Driver method to test above method*/ + + public static void main (String[] args) throws java.lang.Exception + { + int arr[] = {10, 5, 3, 4, 3, 5, 6}; + printFirstRepeating(arr); + } +}"," '''Python3 program to find first repeating +element in arr[] + ''' '''This function prints the first repeating +element in arr[]''' + +def printFirstRepeating(arr, n): + ''' Initialize index of first repeating element''' + + Min = -1 + ''' Creates an empty hashset''' + + myset = dict() + ''' Traverse the input array from right to left''' + + for i in range(n - 1, -1, -1): + ''' If element is already in hash set, + update Min''' + + if arr[i] in myset.keys(): + Min = i + '''Else add element to hash set''' + + else: + myset[arr[i]] = 1 + ''' Print the result''' + + if (Min != -1): + print(""The first repeating element is"", + arr[Min]) + else: + print(""There are no repeating elements"") + '''Driver Code''' + +arr = [10, 5, 3, 4, 3, 5, 6] +n = len(arr) +printFirstRepeating(arr, n)" +Sum of matrix in which each element is absolute difference of its row and column numbers,"/*Java program to find sum of matrix in which +each element is absolute difference of its +corresponding row and column number row.*/ + +import java.io.*; +class GFG { +/*Retuen the sum of matrix in which each +element is absolute difference of its +corresponding row and column number row*/ + +static int findSum(int n) +{ + int sum = 0; + for (int i = 0; i < n; i++) + sum += i * (n - i); + return 2 * sum; +} +/* Driver Code*/ + + static public void main(String[] args) + { + int n = 3; + System.out.println(findSum(n)); + } +}"," '''Python 3 program to find sum +of matrix in which each element +is absolute difference of its +corresponding row and column +number row.''' + + '''Return the sum of matrix in +which each element is absolute +difference of its corresponding +row and column number row''' + +def findSum(n): + sum = 0 + for i in range(n): + sum += i * (n - i) + return 2 * sum '''Driver code''' + +n = 3 +print(findSum(n))" +Maximum difference between group of k-elements and rest of the array.,"/*java to find maximum group difference*/ + +import java.util.Arrays; + +public class GFG { + +/* utility function for array sum*/ + + static long arraySum(int arr[], int n) + { + long sum = 0; + for (int i = 0; i < n; i++) + sum = sum + arr[i]; + + return sum; + } + +/* function for finding maximum group + difference of array*/ + + static long maxDiff (int arr[], int n, int k) + { + +/* sort the array*/ + + Arrays.sort(arr); + +/* find array sum*/ + + long arraysum = arraySum(arr, n); + +/* difference for k-smallest + diff1 = (arraysum-k_smallest)-k_smallest*/ + + long diff1 = Math.abs(arraysum - + 2 * arraySum(arr, k)); + +/* reverse array for finding sum of + 1st k-largest*/ + + int end = arr.length - 1; + int start = 0; + while (start < end) + { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + +/* difference for k-largest + diff2 = (arraysum-k_largest)-k_largest*/ + + long diff2 = Math.abs(arraysum - + 2 * arraySum(arr, k)); + +/* return maximum difference value*/ + + return(Math.max(diff1, diff2)); + + } + + + /*driver program*/ + + + public static void main(String args[]) { + int arr[] = {1, 7, 4, 8, -1, 5, 2, 1}; + int n = arr.length; + int k = 3; + + System.out.println(""Maximum Difference = "" + + maxDiff(arr, n, k)); + + } +} + "," '''Python3 to find maximum group difference''' + + + '''utility function for array sum''' + +def arraySum(arr, n): + + sum = 0 + for i in range(n): + sum = sum + arr[i] + return sum + + '''function for finding +maximum group difference of array''' + +def maxDiff (arr, n, k): + + ''' sort the array''' + + arr.sort() + + ''' find array sum''' + + arraysum = arraySum(arr, n) + + ''' difference for k-smallest + diff1 = (arraysum-k_smallest)-k_smallest''' + + diff1 = abs(arraysum - 2 * arraySum(arr, k)) + + ''' reverse array for finding sum + 0f 1st k-largest''' + + arr.reverse() + + ''' difference for k-largest + diff2 = (arraysum-k_largest)-k_largest''' + + diff2 = abs(arraysum - 2 * arraySum(arr, k)) + + ''' return maximum difference value''' + + return(max(diff1, diff2)) + + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 7, 4, 8, -1, 5, 2, 1] + n = len(arr) + k = 3 + print (""Maximum Difference ="", + maxDiff(arr, n, k)) + + +" +Minimum no. of iterations to pass information to all nodes in the tree,"/*Java program to find minimum number of +iterations to pass information from +root to all nodes in an n-ary tree*/ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +class GFG +{ +/* No. of nodes*/ + + private static int N; +/* Adjacency list containing + list of children*/ + + private static List> adj; + GFG(int N) + { + this.N = N; + adj = new ArrayList<>(N); + for (int i = 0; i < N; i++) + adj.add(new ArrayList<>()); + } +/* function to add a child w to v*/ + + void addChild(int v, int w) + { + adj.get(v).add(w); + } +/* Main function to find the + minimum iterations*/ + + private int getMinIteration() + { +/* Base case : if height = 0 or 1;*/ + + if (N == 0 || N == 1) + return 0; + int[] mintItr = new int[N]; +/* Start Post Order Traversal from Root*/ + + getMinIterUtil(0, mintItr); + return mintItr[0]; + } + /* A recursive function to used by getMinIter(). + This function mainly does postorder traversal + and get minimum iteration of all children + of parent node, sort them in decreasing order + and then get minimum iteration of parent node + 1. Get minItr(B) of all children (B) of a node (A) + 2. Sort all minItr(B) in descending order + 3. Get minItr of A based on all minItr(B) + minItr(A) = child(A) -->> child(A) + is children count of node A + For children B from i = 0 to child(A) + minItr(A) = max (minItr(A), + minItr(B) + i + 1) + Base cases would be: + If node is leaf, minItr = 0 + If node's height is 1, minItr = children count + */ + + private void getMinIterUtil(int u, int[] minItr) + { +/* Base case : Leaf node*/ + + if (adj.get(u).size() == 0) + return; + minItr[u] = adj.get(u).size(); + Integer[] minItrTemp = new Integer[minItr[u]]; + int k = 0; + Iterator itr = adj.get(u).iterator(); + while (itr.hasNext()) + { + int currentChild = (int) itr.next(); + getMinIterUtil(currentChild, minItr); + minItrTemp[k++] = minItr[currentChild]; + } + Arrays.sort(minItrTemp, Collections.reverseOrder()); + for (k = 0; k < adj.get(u).size(); k++) + { + int temp = minItrTemp[k] + k + 1; + minItr[u] = Math.max(minItr[u], temp); + } + } +/* Driver Code*/ + + public static void main(String args[]) + { +/* TestCase1*/ + + GFG testCase1 = new GFG(17); + testCase1.addChild(0, 1); + testCase1.addChild(0, 2); + testCase1.addChild(0, 3); + testCase1.addChild(0, 4); + testCase1.addChild(0, 5); + testCase1.addChild(0, 6); + testCase1.addChild(1, 7); + testCase1.addChild(1, 8); + testCase1.addChild(1, 9); + testCase1.addChild(4, 10); + testCase1.addChild(4, 11); + testCase1.addChild(6, 12); + testCase1.addChild(7, 13); + testCase1.addChild(7, 14); + testCase1.addChild(10, 15); + testCase1.addChild(11, 16); + System.out.println(""TestCase 1 - Minimum Iteration: "" + + testCase1.getMinIteration()); +/* TestCase2*/ + + GFG testCase2 = new GFG(3); + testCase2.addChild(0, 1); + testCase2.addChild(0, 2); + System.out.println(""TestCase 2 - Minimum Iteration: "" + + testCase2.getMinIteration()); +/* TestCase3*/ + + GFG testCase3 = new GFG(1); + System.out.println(""TestCase 3 - Minimum Iteration: "" + + testCase3.getMinIteration()); +/* TestCase4*/ + + GFG testCase4 = new GFG(6); + testCase4.addChild(0, 1); + testCase4.addChild(1, 2); + testCase4.addChild(2, 3); + testCase4.addChild(3, 4); + testCase4.addChild(4, 5); + System.out.println(""TestCase 4 - Minimum Iteration: "" + + testCase4.getMinIteration()); +/* TestCase 5*/ + + GFG testCase5 = new GFG(6); + testCase5.addChild(0, 1); + testCase5.addChild(0, 2); + testCase5.addChild(2, 3); + testCase5.addChild(2, 4); + testCase5.addChild(2, 5); + System.out.println(""TestCase 5 - Minimum Iteration: "" + + testCase5.getMinIteration()); +/* TestCase 6*/ + + GFG testCase6 = new GFG(6); + testCase6.addChild(0, 1); + testCase6.addChild(0, 2); + testCase6.addChild(2, 3); + testCase6.addChild(2, 4); + testCase6.addChild(3, 5); + System.out.println(""TestCase 6 - Minimum Iteration: "" + + testCase6.getMinIteration()); +/* TestCase 7*/ + + GFG testCase7 = new GFG(14); + testCase7.addChild(0, 1); + testCase7.addChild(0, 2); + testCase7.addChild(0, 3); + testCase7.addChild(1, 4); + testCase7.addChild(2, 5); + testCase7.addChild(2, 6); + testCase7.addChild(4, 7); + testCase7.addChild(5, 8); + testCase7.addChild(5, 9); + testCase7.addChild(7, 10); + testCase7.addChild(8, 11); + testCase7.addChild(8, 12); + testCase7.addChild(10, 13); + System.out.println(""TestCase 7 - Minimum Iteration: "" + + testCase7.getMinIteration()); +/* TestCase 8*/ + + GFG testCase8 = new GFG(14); + testCase8.addChild(0, 1); + testCase8.addChild(0, 2); + testCase8.addChild(0, 3); + testCase8.addChild(0, 4); + testCase8.addChild(0, 5); + testCase8.addChild(1, 6); + testCase8.addChild(2, 7); + testCase8.addChild(3, 8); + testCase8.addChild(4, 9); + testCase8.addChild(6, 10); + testCase8.addChild(7, 11); + testCase8.addChild(8, 12); + testCase8.addChild(9, 13); + System.out.println(""TestCase 8 - Minimum Iteration: "" + + testCase8.getMinIteration()); +/* TestCase 9*/ + + GFG testCase9 = new GFG(25); + testCase9.addChild(0, 1); + testCase9.addChild(0, 2); + testCase9.addChild(0, 3); + testCase9.addChild(0, 4); + testCase9.addChild(0, 5); + testCase9.addChild(0, 6); + testCase9.addChild(1, 7); + testCase9.addChild(2, 8); + testCase9.addChild(3, 9); + testCase9.addChild(4, 10); + testCase9.addChild(5, 11); + testCase9.addChild(6, 12); + testCase9.addChild(7, 13); + testCase9.addChild(8, 14); + testCase9.addChild(9, 15); + testCase9.addChild(10, 16); + testCase9.addChild(11, 17); + testCase9.addChild(12, 18); + testCase9.addChild(13, 19); + testCase9.addChild(14, 20); + testCase9.addChild(15, 21); + testCase9.addChild(16, 22); + testCase9.addChild(17, 23); + testCase9.addChild(19, 24); + System.out.println(""TestCase 9 - Minimum Iteration: "" + + testCase9.getMinIteration()); + } +}", +Program to Print Matrix in Z form,"/*Java program to print a +square matrix in Z form*/ + +import java.lang.*; +import java.io.*; +class GFG { + public static void diag(int arr[][], int n) + { + int i = 0, j, k; + for(i = 0;i < n;i++){ + for(j = 0;j < n;j++){ + if(i == 0){ + System.out.print(arr[i][j]+"" ""); + } else if(i == j){ + System.out.print(arr[i][j]+"" ""); + } else if(i == n-1){ + System.out.print(arr[i][j]+"" ""); + } + } + } + } +/*Driver code*/ + + public static void main(String[] args) + { + int a[][] = { { 4, 5, 6, 8 }, + { 1, 2, 3, 1 }, + { 7, 8, 9, 4 }, + { 1, 8, 7, 5 } }; + diag(a, 4); + } +}"," '''Python3 program to pra +square matrix in Z form''' + +def diag(arr, n): + for i in range(n): + for j in range(n): + if(i == 0): + print(arr[i][j], end = "" "") + elif(i == j): + print(arr[i][j], end = "" "") + elif(i == n - 1): + print(arr[i][j], end = "" "") + '''Driver code''' + +if __name__ == '__main__': + a= [ [ 4, 5, 6, 8 ], + [ 1, 2, 3, 1 ], + [ 7, 8, 9, 4 ], + [ 1, 8, 7, 5 ] ] + diag(a, 4)" +Edit Distance | DP-5,"/*A Space efficient Dynamic Programming +based Java program to find minimum +number operations to convert str1 to str2*/ + +import java.util.*; +class GFG +{ +static void EditDistDP(String str1, String str2) +{ + int len1 = str1.length(); + int len2 = str2.length(); +/* Create a DP array to memoize result + of previous computations*/ + + int [][]DP = new int[2][len1 + 1]; +/* Base condition when second String + is empty then we remove all characters*/ + + for (int i = 0; i <= len1; i++) + DP[0][i] = i; +/* Start filling the DP + This loop run for every + character in second String*/ + + for (int i = 1; i <= len2; i++) + { +/* This loop compares the char from + second String with first String + characters*/ + + for (int j = 0; j <= len1; j++) + { +/* if first String is empty then + we have to perform add character + operation to get second String*/ + + if (j == 0) + DP[i % 2][j] = i; +/* if character from both String + is same then we do not perform any + operation . here i % 2 is for bound + the row number.*/ + + else if (str1.charAt(j - 1) == str2.charAt(i - 1)) { + DP[i % 2][j] = DP[(i - 1) % 2][j - 1]; + } +/* if character from both String is + not same then we take the minimum + from three specified operation*/ + + else { + DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j], + Math.min(DP[i % 2][j - 1], + DP[(i - 1) % 2][j - 1])); + } + } + } +/* after complete fill the DP array + if the len2 is even then we end + up in the 0th row else we end up + in the 1th row so we take len2 % 2 + to get row*/ + + System.out.print(DP[len2 % 2][len1] +""\n""); +} +/*Driver program*/ + +public static void main(String[] args) +{ + String str1 = ""food""; + String str2 = ""money""; + EditDistDP(str1, str2); +} +}"," '''A Space efficient Dynamic Programming +based Python3 program to find minimum +number operations to convert str1 to str2''' + +def EditDistDP(str1, str2): + len1 = len(str1) + len2 = len(str2) + ''' Create a DP array to memoize result + of previous computations''' + + DP = [[0 for i in range(len1 + 1)] + for j in range(2)]; + ''' Base condition when second String + is empty then we remove all characters''' + + for i in range(0, len1 + 1): + DP[0][i] = i + ''' Start filling the DP + This loop run for every + character in second String''' + + for i in range(1, len2 + 1): + ''' This loop compares the char from + second String with first String + characters''' + + for j in range(0, len1 + 1): + ''' If first String is empty then + we have to perform add character + operation to get second String''' + + if (j == 0): + DP[i % 2][j] = i + ''' If character from both String + is same then we do not perform any + operation . here i % 2 is for bound + the row number.''' + + elif(str1[j - 1] == str2[i-1]): + DP[i % 2][j] = DP[(i - 1) % 2][j - 1] + ''' If character from both String is + not same then we take the minimum + from three specified operation''' + + else: + DP[i % 2][j] = (1 + min(DP[(i - 1) % 2][j], + min(DP[i % 2][j - 1], + DP[(i - 1) % 2][j - 1]))) + ''' After complete fill the DP array + if the len2 is even then we end + up in the 0th row else we end up + in the 1th row so we take len2 % 2 + to get row''' + + print(DP[len2 % 2][len1], """") + '''Driver code''' + +if __name__ == '__main__': + str1 = ""food"" + str2 = ""money"" + EditDistDP(str1, str2)" +Minimum swaps required to bring all elements less than or equal to k together,"/*Java program to find minimum +swaps required to club all +elements less than or equals +to k together*/ + +import java.lang.*; +class GFG { +/*Utility function to find minimum swaps +required to club all elements less than +or equals to k together*/ + +static int minSwap(int arr[], int n, int k) { +/* Find count of elements which are + less than equals to k*/ + + int count = 0; + for (int i = 0; i < n; ++i) + if (arr[i] <= k) + ++count; +/* Find unwanted elements in current + window of size 'count'*/ + + int bad = 0; + for (int i = 0; i < count; ++i) + if (arr[i] > k) + ++bad; +/* Initialize answer with 'bad' value of + current window*/ + + int ans = bad; + for (int i = 0, j = count; j < n; ++i, ++j) { +/* Decrement count of previous window*/ + + if (arr[i] > k) + --bad; +/* Increment count of current window*/ + + if (arr[j] > k) + ++bad; +/* Update ans if count of 'bad' + is less in current window*/ + + ans = Math.min(ans, bad); + } + return ans; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {2, 1, 5, 6, 3}; + int n = arr.length; + int k = 3; + System.out.print(minSwap(arr, n, k) + ""\n""); + int arr1[] = {2, 7, 9, 5, 8, 7, 4}; + n = arr1.length; + k = 5; + System.out.print(minSwap(arr1, n, k)); +} +}"," '''Python3 program to find +minimum swaps required +to club all elements less +than or equals to k together + ''' '''Utility function to find +minimum swaps required to +club all elements less than +or equals to k together''' + +def minSwap(arr, n, k) : + ''' Find count of elements + which are less than + equals to k''' + + count = 0 + for i in range(0, n) : + if (arr[i] <= k) : + count = count + 1 + ''' Find unwanted elements + in current window of + size 'count''' + ''' + bad = 0 + for i in range(0, count) : + if (arr[i] > k) : + bad = bad + 1 + ''' Initialize answer with + 'bad' value of current + window''' + + ans = bad + j = count + for i in range(0, n) : + if(j == n) : + break + ''' Decrement count of + previous window''' + + if (arr[i] > k) : + bad = bad - 1 + ''' Increment count of + current window''' + + if (arr[j] > k) : + bad = bad + 1 + ''' Update ans if count + of 'bad' is less in + current window''' + + ans = min(ans, bad) + j = j + 1 + return ans + '''Driver code''' + +arr = [2, 1, 5, 6, 3] +n = len(arr) +k = 3 +print (minSwap(arr, n, k)) +arr1 = [2, 7, 9, 5, 8, 7, 4] +n = len(arr1) +k = 5 +print (minSwap(arr1, n, k))" +Find pairs with given sum in doubly linked list,"/*Java program to find a +pair with given sum x.*/ + +class GFG +{ +/*structure of node of +doubly linked list*/ + +static class Node +{ + int data; + Node next, prev; +}; +/*Function to find pair whose +sum equal to given value x.*/ + +static void pairSum( Node head, int x) +{ +/* Set two pointers, first + to the beginning of DLL + and second to the end of DLL.*/ + + Node first = head; + Node second = head; + while (second.next != null) + second = second.next; +/* To track if we find a pair or not*/ + + boolean found = false; +/* The loop terminates when + they cross each other (second.next + == first), or they become same + (first == second)*/ + + while ( first != second && second.next != first) + { +/* pair found*/ + + if ((first.data + second.data) == x) + { + found = true; + System.out.println( ""("" + first.data + + "", ""+ second.data + "")"" ); +/* move first in forward direction*/ + + first = first.next; +/* move second in backward direction*/ + + second = second.prev; + } + else + { + if ((first.data + second.data) < x) + first = first.next; + else + second = second.prev; + } + } +/* if pair is not present*/ + + if (found == false) + System.out.println(""No pair found""); +} +/*A utility function to insert +a new node at the beginning +of doubly linked list*/ + +static Node insert(Node head, int data) +{ + Node temp = new Node(); + temp.data = data; + temp.next = temp.prev = null; + if (head == null) + (head) = temp; + else + { + temp.next = head; + (head).prev = temp; + (head) = temp; + } + return temp; +} +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; + head = insert(head, 9); + head = insert(head, 8); + head = insert(head, 6); + head = insert(head, 5); + head = insert(head, 4); + head = insert(head, 2); + head = insert(head, 1); + int x = 7; + pairSum(head, x); +} +}"," '''Python3 program to find a pair with +given sum x.''' + '''Structure of node of doubly linked list''' + +class Node: + def __init__(self, x): + self.data = x + self.next = None + self.prev = None + '''Function to find pair whose sum +equal to given value x.''' + +def pairSum(head, x): + ''' Set two pointers, first to the + beginning of DLL and second to + the end of DLL.''' + + first = head + second = head + while (second.next != None): + second = second.next + ''' To track if we find a pair or not''' + + found = False + ''' The loop terminates when they + cross each other (second.next == + first), or they become same + (first == second)''' + + while (first != second and second.next != first): + ''' Pair found''' + + if ((first.data + second.data) == x): + found = True + print(""("", first.data, "","", + second.data, "")"") + ''' Move first in forward direction''' + + first = first.next + ''' Move second in backward direction''' + + second = second.prev + else: + if ((first.data + second.data) < x): + first = first.next + else: + second = second.prev + ''' If pair is not present''' + + if (found == False): + print(""No pair found"") + '''A utility function to insert a new node +at the beginning of doubly linked list''' + +def insert(head, data): + temp = Node(data) + if not head: + head = temp + else: + temp.next = head + head.prev = temp + head = temp + return head + '''Driver code''' + +if __name__ == '__main__': + head = None + head = insert(head, 9) + head = insert(head, 8) + head = insert(head, 6) + head = insert(head, 5) + head = insert(head, 4) + head = insert(head, 2) + head = insert(head, 1) + x = 7 + pairSum(head, x)" +Distance of nearest cell having 1 in a binary matrix,"/*Java program to find distance of nearest +cell having 1 in a binary matrix.*/ + +import java.io.*; +class GFG { + static int N = 3; + static int M = 4; +/* Print the distance of nearest cell + having 1 for each cell.*/ + + static void printDistance(int mat[][]) + { + int ans[][] = new int[N][M]; +/* Initialize the answer matrix with INT_MAX.*/ + + for (int i = 0; i < N; i++) + for (int j = 0; j < M; j++) + ans[i][j] = Integer.MAX_VALUE; +/* For each cell*/ + + for (int i = 0; i < N; i++) + for (int j = 0; j < M; j++) + { +/* Traversing the whole matrix + to find the minimum distance.*/ + + for (int k = 0; k < N; k++) + for (int l = 0; l < M; l++) + { +/* If cell contain 1, check + for minimum distance.*/ + + if (mat[k][l] == 1) + ans[i][j] = + Math.min(ans[i][j], + Math.abs(i-k) + + Math.abs(j-l)); + } + } +/* Printing the answer.*/ + + for (int i = 0; i < N; i++) + { + for (int j = 0; j < M; j++) + System.out.print( ans[i][j] + "" ""); + System.out.println(); + } + } +/* Driven Program*/ + + public static void main (String[] args) + { + int mat[][] = { {0, 0, 0, 1}, + {0, 0, 1, 1}, + {0, 1, 1, 0} }; + printDistance(mat); + } +}"," '''Python3 program to find distance of +nearest cell having 1 in a binary matrix.''' + '''Prthe distance of nearest cell +having 1 for each cell.''' + +def printDistance(mat): + global N, M + ans = [[None] * M for i in range(N)] ''' Initialize the answer matrix + with INT_MAX.''' + + for i in range(N): + for j in range(M): + ans[i][j] = 999999999999 + ''' For each cell''' + + for i in range(N): + for j in range(M): + ''' Traversing the whole matrix + to find the minimum distance.''' + + for k in range(N): + for l in range(M): + ''' If cell contain 1, check + for minimum distance.''' + + if (mat[k][l] == 1): + ans[i][j] = min(ans[i][j], + abs(i - k) + abs(j - l)) + ''' Printing the answer.''' + + for i in range(N): + for j in range(M): + print(ans[i][j], end = "" "") + print() + '''Driver Code''' + +N = 3 +M = 4 +mat = [[0, 0, 0, 1], + [0, 0, 1, 1], + [0, 1, 1, 0]] +printDistance(mat)" +Two Clique Problem (Check if Graph can be divided in two Cliques),"/*Java program to find out whether a given graph can be +converted to two Cliques or not.*/ + +import java.util.ArrayDeque; +import java.util.Deque; +class GFG { +static int V = 5; +/*This function returns true if subgraph reachable from +src is Bipartite or not.*/ + +static boolean isBipartiteUtil(int G[][], int src, int colorArr[]) +{ + colorArr[src] = 1; +/* Create a queue (FIFO) of vertex numbers and enqueue + source vertex for BFS traversal*/ + + Deque q = new ArrayDeque<>(); + q.push(src); +/* Run while there are vertices in queue (Similar to BFS)*/ + + while (!q.isEmpty()) + { +/* Dequeue a vertex from queue*/ + + int u = q.peek(); + q.pop(); +/* Find all non-colored adjacent vertices*/ + + for (int v = 0; v < V; ++v) + { +/* An edge from u to v exists and destination + v is not colored*/ + + if (G[u][v] == -1 && colorArr[v] == -1) + { +/* Assign alternate color to this adjacent + v of u*/ + + colorArr[v] = 1 - colorArr[u]; + q.push(v); + } +/* An edge from u to v exists and destination + v is colored with same color as u*/ + + else if (G[u][v] == colorArr[u] && colorArr[v] == colorArr[u]) + return false; + } + } +/* If we reach here, then all adjacent vertices can + be colored with alternate color*/ + + return true; +} +/*Returns true if a Graph G[][] is Bipartite or not. Note +that G may not be connected.*/ + +static boolean isBipartite(int G[][]) +{ +/* Create a color array to store colors assigned + to all veritces. Vertex number is used as index in + this array. The value '-1' of colorArr[i] + is used to indicate that no color is assigned to + vertex 'i'. The value 1 is used to indicate first + color is assigned and value 0 indicates + second color is assigned.*/ + + int colorArr[]=new int[V]; + for (int i = 0; i < V; ++i) + colorArr[i] = -1; +/* One by one check all not yet colored vertices.*/ + + for (int i = 0; i < V; i++) + if (colorArr[i] == -1) + if (isBipartiteUtil(G, i, colorArr) == false) + return false; + return true; +} +/*Returns true if G can be divided into +two Cliques, else false.*/ + +static boolean canBeDividedinTwoCliques(int G[][]) +{ +/* Find complement of G[][] + All values are complemented except + diagonal ones*/ + + int GC[][]=new int[V][V]; + for (int i=0; i= k,"/*Java program to remove all nodes which donot +lie on path having sum>= k*/ + +/*Class representing binary tree node*/ + +class Node { + int data; + Node left; + Node right; + public Node(int data) { + this.data = data; + left = null; + right = null; + } +} +/* for print traversal*/ + + public void print(Node root) { + if (root == null) + return; + print(root.left); + System.out.print(root.data + "" ""); + print(root.right); + } +}/*class to truncate binary tree recursive method to truncate binary tree*/ + +class BinaryTree { + Node root; + public Node prune(Node root, int sum) {/* base case*/ + + if (root == null) + return null; +/* recur for left and right subtree*/ + + root.left = prune(root.left, sum - root.data); + root.right = prune(root.right, sum - root.data); +/* if node is a leaf node whose data is smaller + than the sum we delete the leaf.An important + thing to note is a non-leaf node can become + leaf when its children are deleted.*/ + + if (isLeaf(root)) { + if (sum > root.data) + root = null; + } + return root; + } +/* utility method to check if node is leaf*/ + + public boolean isLeaf(Node root) { + if (root == null) + return false; + if (root.left == null && root.right == null) + return true; + return false; + } +/*Driver class to test above function*/ + +public class GFG { + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.left.left = new Node(8); + tree.root.left.left.right = new Node(9); + tree.root.left.right.left = new Node(12); + tree.root.right.right.left = new Node(10); + tree.root.right.right.left.right = new Node(11); + tree.root.left.left.right.left = new Node(13); + tree.root.left.left.right.right = new Node(14); + tree.root.left.left.right.right.left = new Node(15); + System.out.println(""Tree before truncation""); + tree.print(tree.root); + tree.prune(tree.root, 45); + System.out.println(""\nTree after truncation""); + tree.print(tree.root); + } +}"," ''' +Python program to remove all nodes which don’t +lie in any path with sum>= k + ''' + + '''binary tree node contains data field , left +and right pointer''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''inorder traversal''' + +def inorder(root): + if root is None: + return + inorder(root.left) + print(root.data, """", end="""") + inorder(root.right) + '''Function to remove all nodes which do not +lie in th sum path''' + +def prune(root, sum): + ''' Base case''' + + if root is None: + return None + ''' Recur for left and right subtree''' + + root.left = prune(root.left, sum - root.data) + root.right = prune(root.right, sum - root.data) + ''' if node is leaf and sum is found greater + than data than remove node An important + thing to remember is that a non-leaf node + can become a leaf when its children are + removed''' + + if root.left is None and root.right is None: + if sum > root.data: + return None + return root + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) +root.left.left.left = Node(8) +root.left.left.right = Node(9) +root.left.right.left = Node(12) +root.right.right.left = Node(10) +root.right.right.left.right = Node(11) +root.left.left.right.left = Node(13) +root.left.left.right.right = Node(14) +root.left.left.right.right.left = Node(15) +print(""Tree before truncation"") +inorder(root) +prune(root, 45) +print(""\nTree after truncation"") +inorder(root)" +Find if a 2-D array is completely traversed or not by following the cell values,"/* Java program to Find a 2-D array is completely +traversed or not by following the cell values */ + +import java.io.*; +class Cell { + int x; + int y; +/* Cell class constructor*/ + + Cell(int x, int y) + { + this.x = x; + this.y = y; + } +} +public class MoveCellPerCellValue { +/* function which tells all cells are visited or not*/ + + public boolean isAllCellTraversed(Cell grid[][]) + { + boolean[][] visited = + new boolean[grid.length][grid[0].length]; + int total = grid.length * grid[0].length; +/* starting cell values*/ + + int startx = grid[0][0].x; + int starty = grid[0][0].y; + for (int i = 0; i < total - 2; i++) { +/* if we get null before the end of loop + then returns false. Because it means we + didn't traverse all the cells*/ + + if (grid[startx][starty] == null) + return false; +/* If found cycle then return false*/ + + if (visited[startx][starty] == true) + return false; + visited[startx][starty] = true; + int x = grid[startx][starty].x; + int y = grid[startx][starty].y; +/* Update startx and starty values to next + cell values*/ + + startx = x; + starty = y; + } +/* finally if we reach our goal then returns true*/ + + if (grid[startx][starty] == null) + return true; + return false; + } + /* Driver program to test above function */ + + public static void main(String args[]) + { + Cell cell[][] = new Cell[3][2]; + cell[0][0] = new Cell(0, 1); + cell[0][1] = new Cell(2, 0); + cell[1][0] = null; + cell[1][1] = new Cell(1, 0); + cell[2][0] = new Cell(2, 1); + cell[2][1] = new Cell(1, 1); + MoveCellPerCellValue mcp = new MoveCellPerCellValue(); + System.out.println(mcp.isAllCellTraversed(cell)); + } +}", +Deepest right leaf node in a binary tree | Iterative approach,"/*Java program to find deepest right leaf +node of binary tree*/ + +import java.util.*; +class GFG +{ +/*tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*returns a new tree Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*return the deepest right leaf node +of binary tree*/ + +static Node getDeepestRightLeafNode(Node root) +{ + if (root == null) + return null; +/* create a queue for level order traversal*/ + + Queue q = new LinkedList<>(); + q.add(root); + Node result = null; +/* traverse until the queue is empty*/ + + while (!q.isEmpty()) + { + Node temp = q.peek(); + q.poll(); + if (temp.left != null) + { + q.add(temp.left); + } +/* Since we go level by level, the last + stored right leaf node is deepest one */ + + if (temp.right != null) + { + q.add(temp.right); + if (temp.right.left == null && temp.right.right == null) + result = temp.right; + } + } + return result; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* construct a tree*/ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.right = newNode(4); + root.right.left = newNode(5); + root.right.right = newNode(6); + root.right.left.right = newNode(7); + root.right.right.right = newNode(8); + root.right.left.right.left = newNode(9); + root.right.right.right.right = newNode(10); + Node result = getDeepestRightLeafNode(root); + if (result != null) + System.out.println(""Deepest Right Leaf Node :: "" + + result.data); + else + System.out.println(""No result, right leaf not found\n""); + } +}"," '''Python3 program to find closest +value in Binary search Tree''' '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newnode: + ''' Constructor to create a new node ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''utility function to return level +of given node''' + +def getDeepestRightLeafNode(root) : + if (not root): + return None + ''' create a queue for level + order traversal ''' + + q = [] + q.append(root) + result = None + ''' traverse until the queue is empty ''' + + while (len(q)): + temp = q[0] + q.pop(0) + if (temp.left): + q.append(temp.left) + ''' Since we go level by level, the last + stored right leaf node is deepest one ''' + + if (temp.right): + q.append(temp.right) + if (not temp.right.left and + not temp.right.right): + result = temp.right + return result + '''Driver Code ''' + +if __name__ == '__main__': + ''' create a binary tree ''' + + root = newnode(1) + root.left = newnode(2) + root.right = newnode(3) + root.left.right = newnode(4) + root.right.left = newnode(5) + root.right.right = newnode(6) + root.right.left.right = newnode(7) + root.right.right.right = newnode(8) + root.right.left.right.left = newnode(9) + root.right.right.right.right = newnode(10) + result = getDeepestRightLeafNode(root) + if result: + print(""Deepest Right Leaf Node ::"", + result.data) + else: + print(""No result, right leaf not found"")" +Find all elements in array which have at-least two greater elements,"/*Java program to find all elements +in array which have atleast +two greater elements itself.*/ + +import java.util.*; +import java.io.*; +class GFG +{ +static void findElements(int arr[], int n) +{ + int first = Integer.MIN_VALUE; + int second = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) + { +/* If current element is smaller + than first then update both + first and second*/ + + if (arr[i] > first) + { + second = first; + first = arr[i]; + } + /* If arr[i] is in between + first and second + then update second */ + + else if (arr[i] > second) + second = arr[i]; + } + for (int i = 0; i < n; i++) + if (arr[i] < second) + System.out.print(arr[i] + "" "") ; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = { 2, -6, 3, 5, 1}; + int n = arr.length; + findElements(arr, n); +} +}"," '''Python3 program to find all elements +in array which have atleast two +greater elements itself.''' + +import sys +def findElements(arr, n): + first = -sys.maxsize + second = -sys.maxsize + for i in range(0, n): + ''' If current element is smaller + than first then update both + first and second''' + + if (arr[i] > first): + second = first + first = arr[i] + ''' If arr[i] is in between first + and second then update second''' + + elif (arr[i] > second): + second = arr[i] + for i in range(0, n): + if (arr[i] < second): + print(arr[i], end ="" "") + '''Driver code''' + +arr = [2, -6, 3, 5, 1] +n = len(arr) +findElements(arr, n)" +Check if two trees are Mirror,"/*Java program to see if two trees +are mirror of each other*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node a, b;/* Given two trees, return true if they are + mirror of each other */ + + boolean areMirror(Node a, Node b) + { + /* Base case : Both empty */ + + if (a == null && b == null) + return true; +/* If only one is empty*/ + + if (a == null || b == null) + return false; + /* Both non-empty, compare them recursively + Note that in recursive calls, we pass left + of one tree and right of other tree */ + + return a.data == b.data + && areMirror(a.left, b.right) + && areMirror(a.right, b.left); + } +/* Driver code to test above methods*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + Node a = new Node(1); + Node b = new Node(1); + a.left = new Node(2); + a.right = new Node(3); + a.left.left = new Node(4); + a.left.right = new Node(5); + b.left = new Node(3); + b.right = new Node(2); + b.right.left = new Node(5); + b.right.right = new Node(4); + if (tree.areMirror(a, b) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 program to check if two +trees are mirror of each other''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Given two trees, return true +if they are mirror of each other''' + +def areMirror(a, b): + ''' Base case : Both empty''' + + if a is None and b is None: + return True + ''' If only one is empty''' + + if a is None or b is None: + return False + ''' Both non-empty, compare them + recursively. Note that in + recursive calls, we pass left + of one tree and right of other tree''' + + return (a.data == b.data and + areMirror(a.left, b.right) and + areMirror(a.right , b.left)) + '''Driver code''' + +root1 = Node(1) +root2 = Node(1) +root1.left = Node(2) +root1.right = Node(3) +root1.left.left = Node(4) +root1.left.right = Node(5) +root2.left = Node(3) +root2.right = Node(2) +root2.right.left = Node(5) +root2.right.right = Node(4) +if areMirror(root1, root2): + print (""Yes"") +else: + print (""No"")" +Check if a string can be obtained by rotating another string 2 places,"/*Java program to check if a string is two time +rotation of another string.*/ + + +class Test +{ +/* Method to check if string2 is obtained by + string 1*/ + + static boolean isRotated(String str1, String str2) + { + if (str1.length() != str2.length()) + return false; + if(str1.length() < 2) + { + return str1.equals(str2); + } + + String clock_rot = """"; + String anticlock_rot = """"; + int len = str2.length(); + +/* Initialize string as anti-clockwise rotation*/ + + anticlock_rot = anticlock_rot + + str2.substring(len-2, len) + + str2.substring(0, len-2) ; + +/* Initialize string as clock wise rotation*/ + + clock_rot = clock_rot + + str2.substring(2) + + str2.substring(0, 2) ; + +/* check if any of them is equal to string1*/ + + return (str1.equals(clock_rot) || + str1.equals(anticlock_rot)); + } + +/* Driver method*/ + + public static void main(String[] args) + { + String str1 = ""geeks""; + String str2 = ""eksge""; + + System.out.println(isRotated(str1, str2) ? ""Yes"" + : ""No""); + } +} +"," '''Python 3 program to check if a string +is two time rotation of another string.''' + + + '''Function to check if string2 is +obtained by string 1''' + +def isRotated(str1, str2): + + if (len(str1) != len(str2)): + return False + + if(len(str1) < 2): + return str1 == str2 + clock_rot = """" + anticlock_rot = """" + l = len(str2) + + ''' Initialize string as anti-clockwise rotation''' + + anticlock_rot = (anticlock_rot + str2[l - 2:] + + str2[0: l - 2]) + + ''' Initialize string as clock wise rotation''' + + clock_rot = clock_rot + str2[2:] + str2[0:2] + + ''' check if any of them is equal to string1''' + + return (str1 == clock_rot or + str1 == anticlock_rot) + + '''Driver code''' + +if __name__ == ""__main__"": + + str1 = ""geeks"" + str2 = ""eksge"" +if isRotated(str1, str2): + print(""Yes"") +else: + print(""No"") + + +" +Remove all even parity nodes from a Doubly and Circular Singly Linked List,"/*Java program to remove all +the Even Parity Nodes from a +circular singly linked list*/ + +class GFG{ + +/*Structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to insert a node at +the beginning of a Circular +linked list*/ + +static Node push(Node head_ref, int data) +{ + +/* Create a new node + and make head as next + of it.*/ + + Node ptr1 = new Node(); + + Node temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + +/* If linked list is not null then + set the next of last node*/ + + if (head_ref != null) + { + +/* Find the node before head + and update next of it.*/ + + while (temp.next != head_ref) + temp = temp.next; + + temp.next = ptr1; + } + else + +/* Point for the first node*/ + + ptr1.next = ptr1; + + head_ref = ptr1; + return head_ref; +} + +/*Function to delete the node +from a Circular Linked list*/ + +static void deleteNode(Node head_ref, + Node del) +{ + +/* If node to be deleted is + head node*/ + + if (head_ref == del) + head_ref = del.next; + + Node temp = head_ref; + +/* Traverse list till not found + delete node*/ + + while (temp.next != del) + { + temp = temp.next; + } + +/* Copy the address of the node*/ + + temp.next = del.next; + +/* Finally, free the memory + occupied by del*/ + + System.gc(); + + return; +} + +/*Function that returns true if count +of set bits in x is even*/ + +static boolean isEvenParity(int x) +{ + +/* Parity will store the + count of set bits*/ + + int parity = 0; + + while (x != 0) + { + if ((x & 1) != 0) + parity++; + + x = x >> 1; + } + + if (parity % 2 == 0) + return true; + else + return false; +} + +/*Function to delete all the +Even Parity Nodes from the +singly circular linked list*/ + +static void deleteEvenParityNodes(Node head) +{ + if (head == null) + return; + + if (head == head.next) + { + if (isEvenParity(head.data)) + head = null; + + return; + } + + Node ptr = head; + Node next; + +/* Traverse the list till the end*/ + + do + { + next = ptr.next; + +/* If the node's data has + even parity, delete node 'ptr'*/ + + if (isEvenParity(ptr.data)) + deleteNode(head, ptr); + +/* Point to the next node*/ + + ptr = next; + + } while (ptr != head); + + if (head == head.next) + { + if (isEvenParity(head.data)) + head = null; + + return; + } +} + +/*Function to print nodes in a +given Circular linked list*/ + +static void printList(Node head) +{ + if (head == null) + { + System.out.print(""Empty List\n""); + return; + } + + Node temp = head; + if (head != null) + { + do + { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } while (temp != head); + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* Initialize lists as empty*/ + + Node head = null; + +/* Created linked list will be + 11.9.34.6.13.21*/ + + head = push(head, 21); + head = push(head, 13); + head = push(head, 6); + head = push(head, 34); + head = push(head, 9); + head = push(head, 11); + + deleteEvenParityNodes(head); + + printList(head); +} +} + + +"," '''Python3 program to remove all +the Even Parity Nodes from a +circular singly linked list''' + + + '''Structure for a node''' + +class Node: + + def __init__(self): + + self.data = 0 + self.next = None + + '''Function to insert a node at the beginning +of a Circular linked list''' + +def push(head_ref, data): + + ''' Create a new node + and make head as next + of it.''' + + ptr1 = Node() + + temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + + ''' If linked list is not None then + set the next of last node''' + + if (head_ref != None): + + ''' Find the node before head + and update next of it.''' + + while (temp.next != head_ref): + temp = temp.next; + + temp.next = ptr1; + + else: + + ''' Pofor the first node''' + + ptr1.next = ptr1; + + head_ref = ptr1; + + return head_ref + + '''Function to deltete the node from a +Circular Linked list''' + +def delteteNode( head_ref, delt): + + ''' If node to be delteted is head node''' + + if (head_ref == delt): + head_ref = delt.next; + + temp = head_ref; + + ''' Traverse list till not found + deltete node''' + + while (temp.next != delt): + temp = temp.next; + + ''' Copy the address of the node''' + + temp.next = delt.next; + + ''' Finally, free the memory + occupied by delt''' + + del(delt); + + return head_ref; + + '''Function that returns true if count +of set bits in x is even''' + +def isEvenParity(x): + + ''' parity will store the + count of set bits''' + + parity = 0; + while (x != 0): + if (x & 1) != 0: + parity += 1 + x = x >> 1; + + if (parity % 2 == 0): + return True; + else: + return False; + + '''Function to deltete all +the Even Parity Nodes +from the singly circular linked list''' + +def delteteEvenParityNodes(head): + + if (head == None): + return head; + + if (head == head.next): + if (isEvenParity(head.data)): + head = None; + return head; + + ptr = head; + + next = None + + ''' Traverse the list till the end''' + + while True: + + next = ptr.next; + + ''' If the node's data has even parity, + deltete node 'ptr''' + ''' + if (isEvenParity(ptr.data)): + head=delteteNode(head, ptr); + + ''' Poto the next node''' + + ptr = next; + + if(ptr == head): + break + + if (head == head.next): + if (isEvenParity(head.data)): + head = None; + return head; + + return head; + + '''Function to prnodes in a +given Circular linked list''' + +def printList(head): + + if (head == None): + print(""Empty List"") + return; + + temp = head; + + if (head != None): + while True: + print(temp.data, end=' ') + temp = temp.next + + if temp == head: + break + + '''Driver code''' + +if __name__=='__main__': + + ''' Initialize lists as empty''' + + head = None; + + ''' Created linked list will be + 11.9.34.6.13.21''' + + head=push(head, 21); + head=push(head, 13); + head=push(head, 6); + head=push(head, 34); + head=push(head, 9); + head=push(head, 11); + + head=delteteEvenParityNodes(head); + + printList(head); + + +" +Sorting array using Stacks,"/*Java program to sort an +array using stack*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* This function return + the sorted stack*/ + + static Stack sortStack(Stack input) + { + Stack tmpStack = + new Stack(); + while (!input.empty()) + { +/* pop out the + first element*/ + + int tmp = input.peek(); + input.pop(); +/* while temporary stack is + not empty and top of stack + is smaller than temp*/ + + while (!tmpStack.empty() && + tmpStack.peek() < tmp) + { +/* pop from temporary + stack and push it + to the input stack*/ + + input.push(tmpStack.peek()); + tmpStack.pop(); + } +/* push temp in + tempory of stack*/ + + tmpStack.push(tmp); + } + return tmpStack; + } + static void sortArrayUsingStacks(int []arr, + int n) + { +/* push array elements + to stack*/ + + Stack input = + new Stack(); + for (int i = 0; i < n; i++) + input.push(arr[i]); +/* Sort the temporary stack*/ + + Stack tmpStack = + sortStack(input); +/* Put stack elements + in arrp[]*/ + + for (int i = 0; i < n; i++) + { + arr[i] = tmpStack.peek(); + tmpStack.pop(); + } + } +/* Driver Code*/ + + public static void main(String args[]) + { + int []arr = {10, 5, 15, 45}; + int n = arr.length; + sortArrayUsingStacks(arr, n); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +}"," '''Python3 program to sort an array using stack + ''' '''This function return the sorted stack''' + +def sortStack(input): + tmpStack = [] + while (len(input) > 0): + ''' pop out the first element''' + + tmp = input[-1] + input.pop() + ''' while temporary stack is not empty + and top of stack is smaller than temp''' + + while (len(tmpStack) > 0 and tmpStack[-1] < tmp): + ''' pop from temporary stack and + append it to the input stack''' + + input.append(tmpStack[-1]) + tmpStack.pop() + ''' append temp in tempory of stack''' + + tmpStack.append(tmp) + return tmpStack +def sortArrayUsingStacks(arr, n): + ''' append array elements to stack''' + + input = [] + i = 0 + while ( i < n ): + input.append(arr[i]) + i = i + 1 + ''' Sort the temporary stack''' + + tmpStack = sortStack(input) + i = 0 + ''' Put stack elements in arrp[]''' + + while (i < n): + arr[i] = tmpStack[-1] + tmpStack.pop() + i = i + 1 + return arr + '''Driver code''' + +arr = [10, 5, 15, 45] +n = len(arr) +arr = sortArrayUsingStacks(arr, n) +i = 0 +while (i < n): + print(arr[i] ,end= "" "") + i = i + 1" +Sort an array in wave form,"/*A O(n) Java program to sort an input array in wave form*/ + +class SortWave +{ +/* A utility method to swap two numbers.*/ + + void swap(int arr[], int a, int b) + { + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + } +/* This function sorts arr[0..n-1] in wave form, i.e., + arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]....*/ + + void sortInWave(int arr[], int n) + { +/* Traverse all even elements*/ + + for (int i = 0; i < n; i+=2) + { +/* If current even element is smaller + than previous*/ + + if (i>0 && arr[i-1] > arr[i] ) + swap(arr, i-1, i); +/* If current even element is smaller + than next*/ + + if (i= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]''' + +def sortInWave(arr, n): + ''' Traverse all even elements''' + + for i in range(0, n, 2): + ''' If current even element is smaller than previous''' + + if (i> 0 and arr[i] < arr[i-1]): + arr[i],arr[i-1] = arr[i-1],arr[i] + ''' If current even element is smaller than next''' + + if (i < n-1 and arr[i] < arr[i+1]): + arr[i],arr[i+1] = arr[i+1],arr[i] + '''Driver program''' + +arr = [10, 90, 49, 2, 1, 5, 23] +sortInWave(arr, len(arr)) +for i in range(0,len(arr)): + print arr[i]," +Convert a given tree to its Sum Tree,"/*Java program to convert a tree into its sum tree*/ + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* Convert a given tree to a tree where every node contains sum of + values of nodes in left and right subtrees in the original tree*/ + + int toSumTree(Node node) + { +/* Base case*/ + + if (node == null) + return 0; +/* Store the old value*/ + + int old_val = node.data; +/* Recursively call for left and right subtrees and store the sum + as new value of this node*/ + + node.data = toSumTree(node.left) + toSumTree(node.right); +/* Return the sum of values of nodes in left and right subtrees + and old_value of this node*/ + + return node.data + old_val; + } +/* A utility function to print inorder traversal of a Binary Tree*/ + + void printInorder(Node node) + { + if (node == null) + return; + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); + } + /* Driver function to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* Constructing tree given in the above figure */ + + tree.root = new Node(10); + tree.root.left = new Node(-2); + tree.root.right = new Node(6); + tree.root.left.left = new Node(8); + tree.root.left.right = new Node(-4); + tree.root.right.left = new Node(7); + tree.root.right.right = new Node(5); + tree.toSumTree(tree.root); +/* Print inorder traversal of the converted tree to test result + of toSumTree()*/ + + System.out.println(""Inorder Traversal of the resultant tree is:""); + tree.printInorder(tree.root); + } +}"," '''Python3 program to convert a tree +into its sum tree ''' + + '''Node defintion ''' + +class node: + def __init__(self, data): + self.left = None + self.right = None + self.data = data '''Convert a given tree to a tree where +every node contains sum of values of +nodes in left and right subtrees +in the original tree ''' + +def toSumTree(Node) : + ''' Base case ''' + + if(Node == None) : + return 0 + ''' Store the old value ''' + + old_val = Node.data + ''' Recursively call for left and + right subtrees and store the sum as + new value of this node ''' + + Node.data = toSumTree(Node.left) + \ + toSumTree(Node.right) + ''' Return the sum of values of nodes + in left and right subtrees and + old_value of this node ''' + + return Node.data + old_val + '''A utility function to print +inorder traversal of a Binary Tree ''' + +def printInorder(Node) : + if (Node == None) : + return + printInorder(Node.left) + print(Node.data, end = "" "") + printInorder(Node.right) + '''Utility function to create a new Binary Tree node ''' + +def newNode(data) : + temp = node(0) + temp.data = data + temp.left = None + temp.right = None + return temp + '''Driver Code ''' + +if __name__ == ""__main__"": + root = None + x = 0 + ''' Constructing tree given in the above figure ''' + + root = newNode(10) + root.left = newNode(-2) + root.right = newNode(6) + root.left.left = newNode(8) + root.left.right = newNode(-4) + root.right.left = newNode(7) + root.right.right = newNode(5) + toSumTree(root) + ''' Print inorder traversal of the converted + tree to test result of toSumTree() ''' + + print(""Inorder Traversal of the resultant tree is: "") + printInorder(root)" +Lexicographic rank of a string,"/*A O(n) solution for finding rank of string*/ + +class GFG { + static int MAX_CHAR = 256; +/* all elements of count[] are initialized with 0*/ + + int count[] = new int[MAX_CHAR]; +/* A utility function to find factorial of n*/ + + static int fact(int n) + { + return (n <= 1) ? 1 : n * fact(n - 1); + } +/* Construct a count array where value at every index + contains count of smaller characters in whole string*/ + + static void populateAndIncreaseCount(int[] count, char[] str) + { + int i; + for (i = 0; i < str.length; ++i) + ++count[str[i]]; + for (i = 1; i < MAX_CHAR; ++i) + count[i] += count[i - 1]; + } +/* Removes a character ch from count[] array + constructed by populateAndIncreaseCount()*/ + + static void updatecount(int[] count, char ch) + { + int i; + for (i = ch; i < MAX_CHAR; ++i) + --count[i]; + } +/* A function to find rank of a string in all permutations + of characters*/ + + static int findRank(char[] str) + { + int len = str.length; + int mul = fact(len); + int rank = 1, i; +/* Populate the count array such that count[i] + contains count of characters which are present + in str and are smaller than i*/ + + populateAndIncreaseCount(count, str); + for (i = 0; i < len; ++i) { + mul /= len - i; +/* count number of chars smaller than str[i] + fron str[i+1] to str[len-1]*/ + + rank += count[str[i] - 1] * mul; +/* Reduce count of characters greater than str[i]*/ + + updatecount(count, str[i]); + } + return rank; + } +/* Driver code*/ + + public static void main(String args[]) + { + char str[] = ""string"".toCharArray(); + System.out.println(findRank(str)); + } +}"," '''A O(n) solution for finding rank of string''' + +MAX_CHAR=256; + '''all elements of count[] are initialized with 0''' + +count=[0]*(MAX_CHAR + 1); + '''A utility function to find factorial of n''' + +def fact(n): + return 1 if(n <= 1) else (n * fact(n - 1)); + '''Construct a count array where value at every index +contains count of smaller characters in whole string''' + +def populateAndIncreaseCount(str): + for i in range(len(str)): + count[ord(str[i])]+=1; + for i in range(1,MAX_CHAR): + count[i] += count[i - 1]; + '''Removes a character ch from count[] array +constructed by populateAndIncreaseCount()''' + +def updatecount(ch): + for i in range(ord(ch),MAX_CHAR): + count[i]-=1; + '''A function to find rank of a string in all permutations +of characters''' + +def findRank(str): + len1 = len(str); + mul = fact(len1); + rank = 1; + ''' Populate the count array such that count[i] + contains count of characters which are present + in str and are smaller than i''' + + populateAndIncreaseCount(str); + for i in range(len1): + mul = mul//(len1 - i); + ''' count number of chars smaller than str[i] + fron str[i+1] to str[len-1]''' + + rank += count[ord(str[i]) - 1] * mul; + ''' Reduce count of characters greater than str[i]''' + + updatecount(str[i]); + return rank; + '''Driver code''' + +str = ""string""; +print(findRank(str));" +Print matrix in diagonal pattern,"/*Java program to print matrix in diagonal order*/ + +public class MatrixDiag { + +/* Driver code*/ + + public static void main(String[] args) + {/* Initialize matrix*/ + + int[][] mat = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; +/* n - size + mode - switch to derive up/down traversal + it - iterator count - increases until it + reaches n and then decreases*/ + + int n = 4, mode = 0, it = 0, lower = 0; +/* 2n will be the number of iterations*/ + + for (int t = 0; t < (2 * n - 1); t++) { + int t1 = t; + if (t1 >= n) { + mode++; + t1 = n - 1; + it--; + lower++; + } + else { + lower = 0; + it++; + } + for (int i = t1; i >= lower; i--) { + if ((t1 + mode) % 2 == 0) { + System.out.println(mat[i][t1 + lower - i]); + } + else { + System.out.println(mat[t1 + lower - i][i]); + } + } + } + } +}"," '''Python3 program to prmatrix in diagonal order''' + + '''Driver Code''' '''Initialize matrix''' + +mat = [[ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 9, 10, 11, 12 ], + [ 13, 14, 15, 16 ]]; '''n - size +mode - switch to derive up/down traversal +it - iterator count - increases until it +reaches n and then decreases''' + +n = 4 +mode = 0 +it = 0 +lower = 0 + '''2n will be the number of iterations''' + +for t in range(2 * n - 1): + t1 = t + if (t1 >= n): + mode += 1 + t1 = n - 1 + it -= 1 + lower += 1 + else: + lower = 0 + it += 1 + for i in range(t1, lower - 1, -1): + if ((t1 + mode) % 2 == 0): + print((mat[i][t1 + lower - i])) + else: + print(mat[t1 + lower - i][i])" +First negative integer in every window of size k,"/*Java code for First negative integer +in every window of size k*/ + +import java.util.*; +class GFG{ +static void printFirstNegativeInteger(int arr[], + int k, int n) +{ + int firstNegativeIndex = 0; + int firstNegativeElement; + for(int i = k - 1; i < n; i++) + { +/* Skip out of window and positive elements*/ + + while ((firstNegativeIndex < i ) && + (firstNegativeIndex <= i - k || + arr[firstNegativeIndex] > 0)) + { + firstNegativeIndex ++; + } +/* Check if a negative element is + found, otherwise use 0*/ + + if (arr[firstNegativeIndex] < 0) + { + firstNegativeElement = arr[firstNegativeIndex]; + } + else + { + firstNegativeElement = 0; + } + System.out.print(firstNegativeElement + "" ""); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 12, -1, -7, 8, -15, 30, 16, 28 }; + int n = arr.length; + int k = 3; + printFirstNegativeInteger(arr, k, n); +} +}"," '''Python3 code for First negative integer +in every window of size k''' + +def printFirstNegativeInteger(arr, k): + firstNegativeIndex = 0 + for i in range(k - 1, len(arr)): + ''' skip out of window and positive elements''' + + while firstNegativeIndex < i and (firstNegativeIndex <= i - k or arr[firstNegativeIndex] > 0): + firstNegativeIndex += 1 + ''' check if a negative element is found, otherwise use 0''' + + firstNegativeElement = arr[firstNegativeIndex] if arr[firstNegativeIndex] < 0 else 0 + print(firstNegativeElement, end=' ') + '''Driver code''' + +if __name__ == ""__main__"": + arr = [12, -1, -7, 8, -15, 30, 16, 28] + k = 3 + printFirstNegativeInteger(arr, k)" +Binary representation of a given number,"/*Java implementation of the approach*/ + +class GFG { +/* Function to convert decimal + to binary number*/ + + static void bin(Integer n) + { + if (n > 1) + bin(n >> 1); + System.out.printf(""%d"", n & 1); + } +/* Driver code*/ + + public static void main(String[] args) + { + bin(131); + System.out.printf(""\n""); + bin(3); + } +}"," '''Python 3 implementation of above approach + ''' '''Function to convert decimal to +binary number''' + +def bin(n): + if (n > 1): + bin(n >> 1) + print(n & 1, end="""") + '''Driver code''' + +bin(131) +print() +bin(3)" +Find Excel column name from a given column number,"import java.util.*; +class GFG{ +static void printString(int n) +{ + int []arr = new int[10000]; + int i = 0; +/* Step 1: Converting to number + assuming 0 in number system*/ + + while (n > 0) + { + arr[i] = n % 26; + n = n / 26; + i++; + } +/* Step 2: Getting rid of 0, as 0 is + not part of number system*/ + + for(int j = 0; j < i - 1; j++) + { + if (arr[j] <= 0) + { + arr[j] += 26; + arr[j + 1] = arr[j + 1] - 1; + } + } + for(int j = i; j >= 0; j--) + { + if (arr[j] > 0) + System.out.print( + (char)('A' + arr[j] - 1)); + } + System.out.println(); +} +/*Driver code*/ + +public static void main(String[] args) +{ + printString(26); + printString(51); + printString(52); + printString(80); + printString(676); + printString(702); + printString(705); +} +}","def printString(n): + arr = [0] * 10000 + i = 0 + ''' Step 1: Converting to number + assuming 0 in number system''' + + while (n > 0): + arr[i] = n % 26 + n = int(n // 26) + i += 1 + ''' Step 2: Getting rid of 0, as 0 is + not part of number system''' + + for j in range(0, i - 1): + if (arr[j] <= 0): + arr[j] += 26 + arr[j + 1] = arr[j + 1] - 1 + for j in range(i, -1, -1): + if (arr[j] > 0): + print(chr(ord('A') + + (arr[j] - 1)), end = """"); + print(); + '''Driver code''' + +if __name__ == '__main__': + printString(26); + printString(51); + printString(52); + printString(80); + printString(676); + printString(702); + printString(705);" +Find Union and Intersection of two unsorted arrays,"/*Java code to find intersection when +elements may not be distinct*/ + +import java.io.*; +import java.util.Arrays; +class GFG { +/* Function to find intersection*/ + + static void intersection(int a[], int b[], int n, int m) + { + int i = 0, j = 0; + while (i < n && j < m) { + if (a[i] > b[j]) { + j++; + } + else if (b[j] > a[i]) { + i++; + } + else { +/* when both are equal*/ + + System.out.print(a[i] + "" ""); + i++; + j++; + } + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 }; + int b[] = { 3, 3, 5 }; + int n = a.length; + int m = b.length; +/* sort*/ + + Arrays.sort(a); + Arrays.sort(b); +/* Function call*/ + + intersection(a, b, n, m); + } +}"," '''Python 3 code to find intersection +when elements may not be distinct + ''' '''Function to find intersection''' + +def intersection(a, b, n, m): + i = 0 + j = 0 + while (i < n and j < m): + if (a[i] > b[j]): + j += 1 + else: + if (b[j] > a[i]): + i += 1 + else: + ''' when both are equal''' + + print(a[i], end="" "") + i += 1 + j += 1 + '''Driver Code''' + +if __name__ == ""__main__"": + a = [1, 3, 2, 3, 4, 5, 5, 6] + b = [3, 3, 5] + n = len(a) + m = len(b) + ''' sort''' + + a.sort() + b.sort() + ''' function call''' + + intersection(a, b, n, m)" +Remove duplicates from a sorted linked list,"/*Java program for the above approach*/ + +import java.io.*; +import java.util.*; +class Node +{ + int data; + Node next; + Node() + { + data = 0; + next = null; + } +} +class GFG +{ + /* Function to insert a node at + the beginging of the linked + * list */ + + static Node push(Node head_ref, int new_data) + { + /* allocate node */ + + Node new_node = new Node(); + /* put in the data */ + + new_node.data = new_data; + /* link the old list off + the new node */ + + new_node.next = (head_ref); + /* move the head to point + to the new node */ + + head_ref = new_node; + return head_ref; + } + /* Function to print nodes + in a given linked list */ + + static void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.next; + } + } +/* Function to remove duplicates*/ + + static void removeDuplicates(Node head) + { + HashMap track = new HashMap<>(); + Node temp = head; + while(temp != null) + { + if(!track.containsKey(temp.data)) + { + System.out.print(temp.data + "" ""); + } + track.put(temp.data , true); + temp = temp.next; + } + } +/* Driver Code*/ + + public static void main (String[] args) + { + Node head = null; + /* Created linked list will be + 11->11->11->13->13->20 */ + + head = push(head, 20); + head = push(head, 13); + head = push(head, 13); + head = push(head, 11); + head = push(head, 11); + head = push(head, 11); + System.out.print(""Linked list before duplicate removal ""); + printList(head); + System.out.print(""\nLinked list after duplicate removal ""); + removeDuplicates(head); + } +}", +Number of NGEs to the right,"import java.util.*; +class GFG{ +static Vector no_NGN(int arr[], int n) +{ + Vector nxt = new Vector<>(); +/* use of stl stack in Java*/ + + Stack s = new Stack<>(); + nxt.add(0); +/* push the (n-1)th index to the stack*/ + + s.add(n - 1); +/* traverse in reverse order*/ + + for (int i = n - 2; i >= 0; i--) + { + while (!s.isEmpty() && arr[i] >= arr[s.peek()]) + s.pop(); +/* if no element is greater than arr[i] the + number of NGEs to right is 0*/ + + if (s.isEmpty()) + nxt.add(0); + else +/* number of NGEs to right of arr[i] is + one greater than the number of NGEs to right + of higher number to its right*/ + + nxt.add(nxt.get(n - s.peek() - 1 ) + 1); + s.add(i); + } +/* reverse again because values are in reverse order*/ + + Collections.reverse(nxt); +/* returns the vector of number of next + greater elements to the right of each index.*/ + + return nxt; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 8; + int arr[] = { 3, 4, 2, 7, 5, 8, 10, 6 }; + Vector nxt = no_NGN(arr, n); +/* query 1 answered*/ + + System.out.print(nxt.get(3) +""\n""); +/* query 2 answered*/ + + System.out.print(nxt.get(6) +""\n""); +/* query 3 answered*/ + + System.out.print(nxt.get(1) +""\n""); +} +}", +Segregate 0s and 1s in an array,"/*Java code to Segregate 0s and 1s in an array*/ + +class GFG { + +/* function to segregate 0s and 1s*/ + + static void segregate0and1(int arr[], int n) + { +/*counts the no of zeros in arr*/ + +int count = 0; + + for (int i = 0; i < n; i++) { + if (arr[i] == 0) + count++; + } + +/* loop fills the arr with 0 until count*/ + + for (int i = 0; i < count; i++) + arr[i] = 0; + +/* loop fills remaining arr space with 1*/ + + for (int i = count; i < n; i++) + arr[i] = 1; + } + +/* function to print segregated array*/ + + static void print(int arr[], int n) + { + System.out.print(""Array after segregation is ""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } + +/* driver function*/ + + public static void main(String[] args) + { + int arr[] = new int[]{ 0, 1, 0, 1, 1, 1 }; + int n = arr.length; + + segregate0and1(arr, n); + print(arr, n); + + } +} + + +"," '''Python 3 code to Segregate +0s and 1s in an array''' + + + '''Function to segregate 0s and 1s''' + +def segregate0and1(arr, n) : + + ''' Counts the no of zeros in arr''' + + count = 0 + + for i in range(0, n) : + if (arr[i] == 0) : + count = count + 1 + + ''' Loop fills the arr with 0 until count''' + + for i in range(0, count) : + arr[i] = 0 + + ''' Loop fills remaining arr space with 1''' + + for i in range(count, n) : + arr[i] = 1 + + + '''Function to print segregated array''' + +def print_arr(arr , n) : + print( ""Array after segregation is "",end = """") + + for i in range(0, n) : + print(arr[i] , end = "" "") + + + '''Driver function''' + +arr = [ 0, 1, 0, 1, 1, 1 ] +n = len(arr) + +segregate0and1(arr, n) +print_arr(arr, n) + + + + +" +Closest numbers from a list of unsorted integers,"/*Java program to find minimum +difference an unsorted array.*/ + +import java.util.*; + +class GFG +{ + +/* Returns minimum difference between + any two pair in arr[0..n-1]*/ + + static void printMinDiffPairs(int arr[], int n) + { + if (n <= 1) + return; + +/* Sort array elements*/ + + Arrays.sort(arr); + +/* Compare differences of adjacent + pairs to find the minimum difference.*/ + + int minDiff = arr[1] - arr[0]; + for (int i = 2; i < n; i++) + minDiff = Math.min(minDiff, arr[i] - arr[i-1]); + +/* Traverse array again and print all pairs + with difference as minDiff.*/ + + for ( int i = 1; i < n; i++) + { + if ((arr[i] - arr[i-1]) == minDiff) + { + System.out.print(""("" + arr[i-1] + "", "" + + arr[i] + ""),"" ); + } + } + } + +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = {5, 3, 2, 4, 1}; + int n = arr.length; + printMinDiffPairs(arr, n); + } +} + + +"," '''Python3 program to find minimum +difference in an unsorted array.''' + + + '''Returns minimum difference between +any two pair in arr[0..n-1]''' + +def printMinDiffPairs(arr , n): + if n <= 1: return + + ''' Sort array elements''' + + arr.sort() + + ''' Compare differences of adjacent + pairs to find the minimum difference.''' + + minDiff = arr[1] - arr[0] + for i in range(2 , n): + minDiff = min(minDiff, arr[i] - arr[i-1]) + + ''' Traverse array again and print all + pairs with difference as minDiff.''' + + for i in range(1 , n): + if (arr[i] - arr[i-1]) == minDiff: + print( ""("" + str(arr[i-1]) + "", "" + + str(arr[i]) + ""), "", end = '') + + '''Driver code''' + +arr = [5, 3, 2, 4, 1] +n = len(arr) +printMinDiffPairs(arr , n) + + +" +Check whether a given graph is Bipartite or not,"/*Java program to find out whether +a given graph is Bipartite or not. +Using recursion.*/ + +class GFG +{ + static final int V = 4; + static boolean colorGraph(int G[][], + int color[], + int pos, int c) + { + if (color[pos] != -1 && + color[pos] != c) + return false; +/* color this pos as c and + all its neighbours as 1-c*/ + + color[pos] = c; + boolean ans = true; + for (int i = 0; i < V; i++) + { + if (G[pos][i] == 1) + { + if (color[i] == -1) + ans &= colorGraph(G, color, i, 1 - c); + if (color[i] != -1 && color[i] != 1 - c) + return false; + } + if (!ans) + return false; + } + return true; + } + static boolean isBipartite(int G[][]) + { + int[] color = new int[V]; + for (int i = 0; i < V; i++) + color[i] = -1; +/* start is vertex 0;*/ + + int pos = 0; +/* two colors 1 and 0*/ + + return colorGraph(G, color, pos, 1); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int G[][] = { { 0, 1, 0, 1 }, + { 1, 0, 1, 0 }, + { 0, 1, 0, 1 }, + { 1, 0, 1, 0 } }; + if (isBipartite(G)) + System.out.print(""Yes""); + else + System.out.print(""No""); + } +}"," '''Python3 program to find out whether a given +graph is Bipartite or not using recursion.''' + +V = 4 +def colorGraph(G, color, pos, c): + if color[pos] != -1 and color[pos] != c: + return False ''' color this pos as c and all its neighbours and 1-c''' + + color[pos] = c + ans = True + for i in range(0, V): + if G[pos][i]: + if color[i] == -1: + ans &= colorGraph(G, color, i, 1-c) + if color[i] !=-1 and color[i] != 1-c: + return False + if not ans: + return False + return True +def isBipartite(G): + color = [-1] * V + ''' start is vertex 0''' + + pos = 0 + ''' two colors 1 and 0''' + + return colorGraph(G, color, pos, 1) + '''Driver Code''' + +if __name__ == ""__main__"": + G = [[0, 1, 0, 1], + [1, 0, 1, 0], + [0, 1, 0, 1], + [1, 0, 1, 0]] + if isBipartite(G): print(""Yes"") + else: print(""No"")" +AVL with duplicate keys,"/*Java program of AVL tree that handles duplicates*/ + +import java.util.*; +class solution { +/* An AVL tree node*/ + + static class node { + int key; + node left; + node right; + int height; + int count; + } +/* A utility function to get height of the tree*/ + + static int height(node N) + { + if (N == null) + return 0; + return N.height; + } +/* A utility function to get maximum of two integers*/ + + static int max(int a, int b) + { + return (a > b) ? a : b; + } + /* Helper function that allocates a new node with the given key and + null left and right pointers. */ + + static node newNode(int key) + { + node node = new node(); + node.key = key; + node.left = null; + node.right = null; +/*new node is initially added at leaf*/ + +node.height = 1; + node.count = 1; + return (node); + } +/* A utility function to right rotate subtree rooted with y + See the diagram given above.*/ + + static node rightRotate(node y) + { + node x = y.left; + node T2 = x.right; +/* Perform rotation*/ + + x.right = y; + y.left = T2; +/* Update heights*/ + + y.height = max(height(y.left), height(y.right)) + 1; + x.height = max(height(x.left), height(x.right)) + 1; +/* Return new root*/ + + return x; + } +/* A utility function to left rotate subtree rooted with x + See the diagram given above.*/ + + static node leftRotate(node x) + { + node y = x.right; + node T2 = y.left; +/* Perform rotation*/ + + y.left = x; + x.right = T2; +/* Update heights*/ + + x.height = max(height(x.left), height(x.right)) + 1; + y.height = max(height(y.left), height(y.right)) + 1; +/* Return new root*/ + + return y; + } +/* Get Balance factor of node N*/ + + static int getBalance(node N) + { + if (N == null) + return 0; + return height(N.left) - height(N.right); + } + static node insert(node node, int key) + { + /*1. Perform the normal BST rotation */ + + if (node == null) + return (newNode(key)); +/* If key already exists in BST, increment count and return*/ + + if (key == node.key) { + (node.count)++; + return node; + } + /* Otherwise, recur down the tree */ + + if (key < node.key) + node.left = insert(node.left, key); + else + node.right = insert(node.right, key); + /* 2. Update height of this ancestor node */ + + node.height = max(height(node.left), height(node.right)) + 1; + /* 3. Get the balance factor of this ancestor node to check whether + this node became unbalanced */ + + int balance = getBalance(node); +/* If this node becomes unbalanced, then there are 4 cases + Left Left Case*/ + + if (balance > 1 && key < node.left.key) + return rightRotate(node); +/* Right Right Case*/ + + if (balance < -1 && key > node.right.key) + return leftRotate(node); +/* Left Right Case*/ + + if (balance > 1 && key > node.left.key) { + node.left = leftRotate(node.left); + return rightRotate(node); + } +/* Right Left Case*/ + + if (balance < -1 && key < node.right.key) { + node.right = rightRotate(node.right); + return leftRotate(node); + } + /* return the (unchanged) node pointer */ + + return node; + } + /* Given a non-empty binary search tree, return the node with minimum + key value found in that tree. Note that the entire tree does not + need to be searched. */ + + static node minValueNode(node node) + { + node current = node; + /* loop down to find the leftmost leaf */ + + while (current.left != null) + current = current.left; + return current; + } + static node deleteNode(node root, int key) + { +/* STEP 1: PERFORM STANDARD BST DELETE*/ + + if (root == null) + return root; +/* If the key to be deleted is smaller than the root's key, + then it lies in left subtree*/ + + if (key < root.key) + root.left = deleteNode(root.left, key); +/* If the key to be deleted is greater than the root's key, + then it lies in right subtree*/ + + else if (key > root.key) + root.right = deleteNode(root.right, key); +/* if key is same as root's key, then This is the node + to be deleted*/ + + else { +/* If key is present more than once, simply decrement + count and return*/ + + if (root.count > 1) { + (root.count)--; + return null; + } +/* ElSE, delete the node + node with only one child or no child*/ + + if ((root.left == null) || (root.right == null)) { + node temp = root.left != null ? root.left : root.right; +/* No child case*/ + + if (temp == null) { + temp = root; + root = null; + } +/*One child case*/ + +else +/*Copy the contents of the non-empty child*/ + +root = temp; + } + else { +/* node with two children: Get the inorder successor (smallest + in the right subtree)*/ + + node temp = minValueNode(root.right); +/* Copy the inorder successor's data to this node and update the count*/ + + root.key = temp.key; + root.count = temp.count; + temp.count = 1; +/* Delete the inorder successor*/ + + root.right = deleteNode(root.right, temp.key); + } + } +/* If the tree had only one node then return*/ + + if (root == null) + return root; +/* STEP 2: UPDATE HEIGHT OF THE CURRENT NODE*/ + + root.height = max(height(root.left), height(root.right)) + 1; +/* STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether + this node became unbalanced)*/ + + int balance = getBalance(root); +/* If this node becomes unbalanced, then there are 4 cases + Left Left Case*/ + + if (balance > 1 && getBalance(root.left) >= 0) + return rightRotate(root); +/* Left Right Case*/ + + if (balance > 1 && getBalance(root.left) < 0) { + root.left = leftRotate(root.left); + return rightRotate(root); + } +/* Right Right Case*/ + + if (balance < -1 && getBalance(root.right) <= 0) + return leftRotate(root); +/* Right Left Case*/ + + if (balance < -1 && getBalance(root.right) > 0) { + root.right = rightRotate(root.right); + return leftRotate(root); + } + return root; + } +/* A utility function to print preorder traversal of the tree. + The function also prints height of every node*/ + + static void preOrder(node root) + { + if (root != null) { + System.out.printf(""%d(%d) "", root.key, root.count); + preOrder(root.left); + preOrder(root.right); + } + } + /* Driver program to test above function*/ + + public static void main(String args[]) + { + node root = null; + /* Coning tree given in the above figure */ + + root = insert(root, 9); + root = insert(root, 5); + root = insert(root, 10); + root = insert(root, 5); + root = insert(root, 9); + root = insert(root, 7); + root = insert(root, 17); + System.out.printf(""Pre order traversal of the constructed AVL tree is \n""); + preOrder(root); + deleteNode(root, 9); + System.out.printf(""\nPre order traversal after deletion of 9 \n""); + preOrder(root); + } +}", +Smallest Derangement of Sequence,"/*Java program to generate +smallest derangement +using priority queue.*/ + +import java.util.*; +class GFG{ +static void generate_derangement(int N) +{ +/* Generate Sequence and insert + into a priority queue.*/ + + int []S = new int[N + 1]; + PriorityQueue PQ = + new PriorityQueue <>(); + for (int i = 1; i <= N; i++) + { + S[i] = i; + PQ.add(S[i]); + } +/* Generate Least Derangement*/ + + int []D = new int[N + 1]; + for (int i = 1; i <= N; i++) + { + int d = PQ.peek(); + PQ.remove(); + if (d != S[i] || i == N) + { + D[i] = d; + } + else + { + D[i] = PQ.peek(); + PQ.remove(); + PQ.add(d); + } + } + if (D[N] == S[N]) + { + int t = D[N - 1]; + D[N - 1] = D[N]; + D[N] = t; + } +/* Print Derangement*/ + + for (int i = 1; i <= N; i++) + System.out.printf(""%d "", D[i]); + System.out.printf(""\n""); +} +/*Driver code*/ + +public static void main(String[] args) +{ + generate_derangement(10); +} +}"," '''Python3 program to generate +smallest derangement +using priority queue.''' + +def generate_derangement(N) : ''' Generate Sequence and insert + into a priority queue.''' + + S = [i for i in range(N + 1)] + PQ = [] + for i in range(1, N + 1) : + PQ.append(S[i]) + ''' Generate Least Derangement''' + + D = [0] * (N + 1) + PQ.sort() + for i in range(1, N + 1) : + PQ.sort() + d = PQ[0] + del PQ[0] + if (d != S[i]) or (i == N) : + D[i] = d + else : + PQ.sort() + D[i] = PQ[0] + del PQ[0] + PQ.append(d) + if D[N] == S[N] : + t = D[N - 1] + D[N - 1] = D[N] + D[N] = t + ''' Print Derangement''' + + for i in range(1, N + 1) : + print(D[i], end = "" "") + print() + '''Driver code''' + +generate_derangement(10)" +Bubble Sort,"/*Optimized java implementation +of Bubble sort*/ + +import java.io.*; +class GFG +{ +/* An optimized version of Bubble Sort*/ + + static void bubbleSort(int arr[], int n) + { + int i, j, temp; + boolean swapped; + for (i = 0; i < n - 1; i++) + { + swapped = false; + for (j = 0; j < n - i - 1; j++) + { + if (arr[j] > arr[j + 1]) + { +/* swap arr[j] and arr[j+1]*/ + + temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + swapped = true; + } + } +/* IF no two elements were + swapped by inner loop, then break*/ + + if (swapped == false) + break; + } + } +/* Function to print an array*/ + + static void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver program*/ + + public static void main(String args[]) + { + int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; + int n = arr.length; + bubbleSort(arr, n); + System.out.println(""Sorted array: ""); + printArray(arr, n); + } +}"," '''Python3 Optimized implementation +of Bubble sort + ''' '''An optimized version of Bubble Sort''' + +def bubbleSort(arr): + n = len(arr) + for i in range(n): + swapped = False + for j in range(0, n-i-1): + if arr[j] > arr[j+1] : ''' traverse the array from 0 to + n-i-1. Swap if the element + found is greater than the + next element''' + + arr[j], arr[j+1] = arr[j+1], arr[j] + swapped = True + ''' IF no two elements were swapped + by inner loop, then break''' + + if swapped == False: + break + '''Driver code to test above''' + +arr = [64, 34, 25, 12, 22, 11, 90] +bubbleSort(arr) +print (""Sorted array :"") +for i in range(len(arr)): + print (""%d"" %arr[i],end="" "")" +Sort n numbers in range from 0 to n^2,"/*Java program to sort an array of size n where elements are +in range from 0 to n^2 – 1.*/ + +class Sort1ToN2 +{ +/* A function to do counting sort of arr[] according to + the digit represented by exp.*/ + + void countSort(int arr[], int n, int exp) + { +/*output array*/ + +int output[] = new int[n]; + int i, count[] = new int[n] ; + for (i=0; i < n; i++) + count[i] = 0; +/* Store count of occurrences in count[]*/ + + for (i = 0; i < n; i++) + count[ (arr[i]/exp)%n ]++; +/* Change count[i] so that count[i] now contains actual + position of this digit in output[]*/ + + for (i = 1; i < n; i++) + count[i] += count[i - 1]; +/* Build the output array*/ + + for (i = n - 1; i >= 0; i--) + { + output[count[ (arr[i]/exp)%n] - 1] = arr[i]; + count[(arr[i]/exp)%n]--; + } +/* Copy the output array to arr[], so that arr[] now + contains sorted numbers according to current digit*/ + + for (i = 0; i < n; i++) + arr[i] = output[i]; + } +/* The main function to that sorts arr[] of size n using Radix Sort*/ + + void sort(int arr[], int n) + { +/* Do counting sort for first digit in base n. Note that + instead of passing digit number, exp (n^0 = 1) is passed.*/ + + countSort(arr, n, 1); +/* Do counting sort for second digit in base n. Note that + instead of passing digit number, exp (n^1 = n) is passed.*/ + + countSort(arr, n, n); + } +/* A utility function to print an array*/ + + void printArr(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i]+"" ""); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + Sort1ToN2 ob = new Sort1ToN2(); +/* Since array size is 7, elements should be from 0 to 48*/ + + int arr[] = {40, 12, 45, 32, 33, 1, 22}; + int n = arr.length; + System.out.println(""Given array""); + ob.printArr(arr, n); + ob.sort(arr, n); + System.out.println(""Sorted array""); + ob.printArr(arr, n); + } +}"," '''Python3 the implementation to sort an +array of size n''' + '''A function to do counting sort of arr[] +according to the digit represented by exp.''' + +def countSort(arr, n, exp): + '''output array''' + + output = [0] * n + count = [0] * n + for i in range(n): + count[i] = 0 + ''' Store count of occurrences in count[]''' + + for i in range(n): + count[ (arr[i] // exp) % n ] += 1 + ''' Change count[i] so that count[i] now contains + actual position of this digit in output[]''' + + for i in range(1, n): + count[i] += count[i - 1] + ''' Build the output array''' + + for i in range(n - 1, -1, -1): + output[count[ (arr[i] // exp) % n] - 1] = arr[i] + count[(arr[i] // exp) % n] -= 1 + ''' Copy the output array to arr[], so that + arr[] now contains sorted numbers according + to current digit''' + + for i in range(n): + arr[i] = output[i] + '''The main function to that sorts arr[] of +size n using Radix Sort''' + +def sort(arr, n) : + ''' Do counting sort for first digit in base n. + Note that instead of passing digit number, + exp (n^0 = 1) is passed.''' + + countSort(arr, n, 1) + ''' Do counting sort for second digit in base n. + Note that instead of passing digit number, + exp (n^1 = n) is passed.''' + + countSort(arr, n, n) + '''Driver Code''' + +if __name__ ==""__main__"": + ''' Since array size is 7, elements should + be from 0 to 48''' + + arr = [40, 12, 45, 32, 33, 1, 22] + n = len(arr) + print(""Given array is"") + print(*arr) + sort(arr, n) + print(""Sorted array is"") + print(*arr) +" +Detect loop in a linked list,"/*Java program to detect loop in a linked list*/ + +class LinkedList { +/*head of list*/ + +Node head; + /* Linked list Node*/ + + class Node { + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } + } + /* Inserts a new Node at front of the list. */ + + public void push(int new_data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + /* 3. Make next of new Node as head */ + + new_node.next = head; + /* 4. Move the head to point to new Node */ + + head = new_node; + } + void detectLoop() + { + Node slow_p = head, fast_p = head; + int flag = 0; + while (slow_p != null && fast_p != null + && fast_p.next != null) { + slow_p = slow_p.next; + fast_p = fast_p.next.next; + if (slow_p == fast_p) { + flag = 1; + break; + } + } + if (flag == 1) + System.out.println(""Loop found""); + else + System.out.println(""Loop not found""); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + /* Start with the empty list */ + + LinkedList llist = new LinkedList(); + llist.push(20); + llist.push(4); + llist.push(15); + llist.push(10);/*Create loop for testing */ + + llist.head.next.next.next.next = llist.head; + llist.detectLoop(); + } +}", +Count ways to form minimum product triplets,"/*Java program to count number of ways we can +form triplets with minimum product.*/ + +import java.util.Arrays; + +class GFG { + +/* function to calculate number of triples*/ + + static long noOfTriples(long arr[], int n) + { + +/* Sort the array*/ + + Arrays.sort(arr); + +/* Count occurrences of third element*/ + + long count = 0; + for (int i = 0; i < n; i++) + if (arr[i] == arr[2]) + count++; + +/* If all three elements are same (minimum + element appears at least 3 times). Answer + is nC3.*/ + + if (arr[0] == arr[2]) + return (count - 2) * (count - 1) * + (count) / 6; + +/* If minimum element appears once. + Answer is nC2.*/ + + else if (arr[1] == arr[2]) + return (count - 1) * (count) / 2; + +/* Minimum two elements are distinct. + Answer is nC1.*/ + + return count; + } + +/* driver code*/ + + public static void main(String arg[]) + { + + long arr[] = { 1, 3, 3, 4 }; + int n = arr.length; + + System.out.print(noOfTriples(arr, n)); + } +} + + +"," '''Python3 program to count number +of ways we can form triplets +with minimum product.''' + + + '''function to calculate number of triples''' + +def noOfTriples (arr, n): + + ''' Sort the array''' + + arr.sort() + + ''' Count occurrences of third element''' + + count = 0 + for i in range(n): + if arr[i] == arr[2]: + count+=1 + + ''' If all three elements are same + (minimum element appears at l + east 3 times). Answer is nC3.''' + + if arr[0] == arr[2]: + return (count - 2) * (count - 1) * (count) / 6 + + ''' If minimum element appears once. + Answer is nC2.''' + + elif arr[1] == arr[2]: + return (count - 1) * (count) / 2 + + ''' Minimum two elements are distinct. + Answer is nC1.''' + + return count + + '''Driver code''' + +arr = [1, 3, 3, 4] +n = len(arr) +print (noOfTriples(arr, n)) + + +" +Find missing elements of a range,"/*A sorting based Java program to find missing +elements from an array*/ + +import java.util.Arrays; +public class PrintMissing { +/* Print all elements of range [low, high] that + are not present in arr[0..n-1]*/ + + static void printMissing(int ar[], int low, int high) + { + Arrays.sort(ar); +/* Do binary search for 'low' in sorted + array and find index of first element + which either equal to or greater than + low.*/ + + int index = ceilindex(ar, low, 0, ar.length - 1); + int x = low; +/* Start from the found index and linearly + search every range element x after this + index in arr[]*/ + + while (index < ar.length && x <= high) { +/* If x doesn't math with current element + print it*/ + + if (ar[index] != x) { + System.out.print(x + "" ""); + } +/* If x matches, move to next element in arr[]*/ + + else + index++; +/* Move to next element in range [low, high]*/ + + x++; + } +/* Print range elements thar are greater than the + last element of sorted array.*/ + + while (x <= high) { + System.out.print(x + "" ""); + x++; + } + } +/* Utility function to find ceil index of given element*/ + + static int ceilindex(int ar[], int val, int low, int high) + { + if (val < ar[0]) + return 0; + if (val > ar[ar.length - 1]) + return ar.length; + int mid = (low + high) / 2; + if (ar[mid] == val) + return mid; + if (ar[mid] < val) { + if (mid + 1 < high && ar[mid + 1] >= val) + return mid + 1; + return ceilindex(ar, val, mid + 1, high); + } + else { + if (mid - 1 >= low && ar[mid - 1] < val) + return mid; + return ceilindex(ar, val, low, mid - 1); + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 5, 4 }; + int low = 1, high = 10; + printMissing(arr, low, high); + } +}"," '''Python library for binary search''' + +from bisect import bisect_left + '''Print all elements of range [low, high] that +are not present in arr[0..n-1]''' + +def printMissing(arr, n, low, high): + arr.sort() ''' Do binary search for 'low' in sorted + array and find index of first element + which either equal to or greater than + low.''' + + ptr = bisect_left(arr, low) + index = ptr + ''' Start from the found index and linearly + search every range element x after this + index in arr[]''' + + i = index + x = low + while (i < n and x <= high): + ''' If x doesn't math with current element + print it''' + + if(arr[i] != x): + print(x, end ="" "") + ''' If x matches, move to next element in arr[]''' + + else: + i = i + 1 + ''' Move to next element in range [low, high]''' + + x = x + 1 + ''' Print range elements thar are greater than the + last element of sorted array.''' + + while (x <= high): + print(x, end ="" "") + x = x + 1 + '''Driver code''' + +arr = [1, 3, 5, 4] +n = len(arr) +low = 1 +high = 10 +printMissing(arr, n, low, high);" +Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1,"/*Java program for kth largest element in a 2d +array sorted row-wise and column-wise*/ + +class GFG{ +/*A structure to store entry of heap. +The entry contains value from 2D array, +row and column numbers of the value*/ + +static class HeapNode +{ +/* Value to be stored*/ + + int val; +/* Row number of value in 2D array*/ + + int r; +/* Column number of value in 2D array*/ + + int c; + HeapNode(int val, int r, int c) + { + this.val = val; + this.c = c; + this.r = r; + } +} +/*A utility function to swap two HeapNode items.*/ + +static void swap(int i, int min, HeapNode[] arr) +{ + HeapNode temp = arr[i]; + arr[i] = arr[min]; + arr[min] = temp; +} +/*A utility function to minheapify the node +harr[i] of a heap stored in harr[]*/ + +static void minHeapify(HeapNode harr[], + int i, int heap_size) +{ + int l = 2 * i + 1; + int r = 2 * i + 2; + int min = i; + if (l < heap_size && + harr[l].val < harr[min].val) + { + min = l; + } + if (r < heap_size && + harr[r].val = 0) + { + minHeapify(harr, i, n); + i--; + } +} +/*This function returns kth smallest +element in a 2D array mat[][]*/ + +public static int kthSmallest(int[][] mat, + int n, int k) +{ +/* k must be greater than 0 and + smaller than n*n*/ + + if (k > 0 && k < n * n) + { + return Integer.MAX_VALUE; + } +/* Create a min heap of elements + from first row of 2D array*/ + + HeapNode harr[] = new HeapNode[n]; + for(int i = 0; i < n; i++) + { + harr[i] = new HeapNode(mat[0][i], 0, i); + } + HeapNode hr = new HeapNode(0, 0, 0); + for(int i = 1; i <= k; i++) + { +/* Get current heap root*/ + + hr = harr[0]; +/* Get next value from column of root's + value. If the value stored at root was + last value in its column, then assign + INFINITE as next value*/ + + int nextVal = hr.r < n - 1 ? + mat[hr.r + 1][hr.c] : + Integer.MAX_VALUE; +/* Update heap root with next value*/ + + harr[0] = new HeapNode(nextVal, + hr.r + 1, hr.c); +/* Heapify root*/ + + minHeapify(harr, 0, n); + } +/* Return the value at last extracted root*/ + + return hr.val; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int mat[][] = { { 10, 20, 30, 40 }, + { 15, 25, 35, 45 }, + { 25, 29, 37, 48 }, + { 32, 33, 39, 50 } }; + int res = kthSmallest(mat, 4, 7); + System.out.print(""7th smallest element is ""+ res); +} +}","Program for kth largest element in a 2d array +sorted row-wise and column-wise''' + +from sys import maxsize '''A structure to store an entry of heap. +The entry contains a value from 2D array, +row and column numbers of the value''' + +class HeapNode: + def __init__(self, val, r, c): + '''value to be stored''' + +self.val = val + '''Row number of value in 2D array''' + +self.r = r + '''Column number of value in 2D array''' + +self.c = c + '''A utility function to minheapify the node harr[i] +of a heap stored in harr[]''' + +def minHeapify(harr, i, heap_size): + l = i * 2 + 1 + r = i * 2 + 2 + smallest = i + if l < heap_size and harr[l].val < harr[i].val: + smallest = l + if r < heap_size and harr[r].val = 0: + minHeapify(harr, i, n) + i -= 1 + '''This function returns kth smallest element +in a 2D array mat[][]''' + +def kthSmallest(mat, n, k): + ''' k must be greater than 0 and smaller than n*n''' + + if k n * n: + return maxsize + ''' Create a min heap of elements from + first row of 2D array''' + + harr = [0] * n + for i in range(n): + harr[i] = HeapNode(mat[0][i], 0, i) + buildHeap(harr, n) + hr = HeapNode(0, 0, 0) + for i in range(k): + ''' Get current heap root''' + + hr = harr[0] + ''' Get next value from column of root's value. + If the value stored at root was last value + in its column, then assign INFINITE as next value''' + + nextval = mat[hr.r + 1][hr.c] + if (hr.r < n - 1) else maxsize + ''' Update heap root with next value''' + + harr[0] = HeapNode(nextval, hr.r + 1, hr.c) + ''' Heapify root''' + + minHeapify(harr, 0, n) + ''' Return the value at last extracted root''' + + return hr.val + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[10, 20, 30, 40], + [15, 25, 35, 45], + [25, 29, 37, 48], + [32, 33, 39, 50]] + print(""7th smallest element is"", + kthSmallest(mat, 4, 7))" +Iterative Preorder Traversal,"/*Java program to implement iterative preorder traversal*/ + +import java.util.Stack; +/*A binary tree node*/ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} + +/* An iterative process to print preorder traversal of Binary tree*/ +class BinaryTree { + Node root; + void iterativePreorder() + { + iterativePreorder(root); + } + void iterativePreorder(Node node) + { +/* Base Case*/ + + if (node == null) { + return; + } +/* Create an empty stack and push root to it*/ + + Stack nodeStack = new Stack(); + nodeStack.push(root); + /* Pop all items one by one. Do following for every popped item + a) print it + b) push its right child + c) push its left child + Note that right child is pushed first so that left is processed first */ + + while (nodeStack.empty() == false) { +/* Pop the top item from stack and print it*/ + + Node mynode = nodeStack.peek(); + System.out.print(mynode.data + "" ""); + nodeStack.pop(); +/* Push right and left children of the popped node to stack*/ + + if (mynode.right != null) { + nodeStack.push(mynode.right); + } + if (mynode.left != null) { + nodeStack.push(mynode.left); + } + } + } +/* driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(2); + tree.iterativePreorder(); + } +}"," '''Python program to perform iterative preorder traversal''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''An iterative process to print preorder traveral of BT''' + +def iterativePreorder(root): + ''' Base CAse''' + + if root is None: + return + ''' create an empty stack and push root to it''' + + nodeStack = [] + nodeStack.append(root) + ''' Pop all items one by one. Do following for every popped item + a) print it + b) push its right child + c) push its left child + Note that right child is pushed first so that left + is processed first */''' + + while(len(nodeStack) > 0): + ''' Pop the top item from stack and print it''' + + node = nodeStack.pop() + print (node.data, end="" "") + ''' Push right and left children of the popped node + to stack''' + + if node.right is not None: + nodeStack.append(node.right) + if node.left is not None: + nodeStack.append(node.left) + '''Driver program to test above function''' + +root = Node(10) +root.left = Node(8) +root.right = Node(2) +root.left.left = Node(3) +root.left.right = Node(5) +root.right.left = Node(2) +iterativePreorder(root)" +Count of rotations required to generate a sorted array,"/*Java Program to implement +the above approach*/ + + +public class GFG { + +/* Function to return the + count of rotations*/ + + public static int countRotation(int[] arr, + int low, + int high) + { +/* If array is not rotated*/ + + if (low > high) { + return 0; + } + + int mid = low + (high - low) / 2; + +/* Check if current element is + greater than the next + element*/ + + + if (mid < high + && arr[mid] > arr[mid + 1]) { +/* the next element is + the smallest*/ + + return mid + 1; + } + +/* Check if current element is + smaller than it's previous + element*/ + + if (mid > low + && arr[mid] < arr[mid - 1]) { +/* Current element is + the smallest*/ + + return mid; + } + +/* Check if current element is + greater than lower bound*/ + + + if (arr[mid] > arr[low]) { +/* The sequence is increasing + so far + Search for smallest + element on the right + subarray*/ + + return countRotation(arr, + mid + 1, + high); + } + + if (arr[mid] < arr[high]) { +/* Smallest element lies on the + left subarray*/ + + return countRotation(arr, + low, + mid - 1); + } + + else { +/* Search for the smallest + element on both subarrays*/ + + int rightIndex = countRotation(arr, + mid + 1, + high); + int leftIndex = countRotation(arr, + low, + mid - 1); + + if (rightIndex == 0) { + return leftIndex; + } + + return rightIndex; + } + } + +/* Driver Program*/ + + public static void main(String[] args) + { + int[] arr1 = { 4, 5, 1, 2, 3 }; + + System.out.println( + countRotation( + arr1, + 0, arr1.length + - 1)); + } +} +"," '''Python3 program to implement the +above approach''' + + + '''Function to return the +count of rotations''' + +def countRotation(arr, low, high): + + ''' If array is not rotated''' + + if (low > high): + return 0 + + mid = low + (high - low) // 2 + + ''' Check if current element is + greater than the next + element''' + + if (mid < high and arr[mid] > arr[mid + 1]): + + ''' The next element is + the smallest''' + + return mid + 1 + + ''' Check if current element is + smaller than it's previous + element''' + + if (mid > low and arr[mid] < arr[mid - 1]): + + ''' Current element is + the smallest''' + + return mid + + ''' Check if current element is + greater than lower bound''' + + if (arr[mid] > arr[low]): + + ''' The sequence is increasing + so far + Search for smallest + element on the right + subarray''' + + return countRotation(arr, mid + 1, high) + + if (arr[mid] < arr[high]): + + ''' Smallest element lies on the + left subarray''' + + return countRotation(arr, low, mid - 1) + + else: + + ''' Search for the smallest + element on both subarrays''' + + rightIndex = countRotation(arr, + mid + 1, + high) + leftIndex = countRotation(arr, low, + mid - 1) + + if (rightIndex == 0): + return leftIndex + + return rightIndex + + '''Driver code''' + +if __name__ == '__main__': + + arr1 = [ 4, 5, 1, 2, 3 ] + N = len(arr1) + + print(countRotation(arr1, 0, N - 1)) + + +" +Construct Full Binary Tree from given preorder and postorder traversals,"/*Java program for construction +of full binary tree*/ + +public class fullbinarytreepostpre +{ + static int preindex;/* A binary tree node has data, pointer to left child +and a pointer to right child */ + + static class node + { + int data; + node left, right; + public node(int data) + { + this.data = data; + } + } +/* A recursive function to construct Full + from pre[] and post[]. preIndex is used + to keep track of index in pre[]. l is + low index and h is high index for the + current subarray in post[]*/ + + static node constructTreeUtil(int pre[], int post[], int l, + int h, int size) + { +/* Base case*/ + + if (preindex >= size || l > h) + return null; +/* The first node in preorder traversal is + root. So take the node at preIndex from + preorder and make it root, and increment + preIndex*/ + + node root = new node(pre[preindex]); + preindex++; +/* If the current subarry has only one + element, no need to recur or + preIndex > size after incrementing*/ + + if (l == h || preindex >= size) + return root; + int i; +/* Search the next element of pre[] in post[]*/ + + for (i = l; i <= h; i++) + { + if (post[i] == pre[preindex]) + break; + } +/* Use the index of element found in + postorder to divide postorder array + in two parts. Left subtree and right subtree*/ + + if (i <= h) + { + root.left = constructTreeUtil(pre, post, l, i, size); + root.right = constructTreeUtil(pre, post, i + 1, h, size); + } + return root; + } +/* The main function to construct Full + Binary Tree from given preorder and + postorder traversals. This function + mainly uses constructTreeUtil()*/ + + static node constructTree(int pre[], int post[], int size) + { + preindex = 0; + return constructTreeUtil(pre, post, 0, size - 1, size); + } +/*A utility function to print inorder traversal of a Binary Tree*/ + + static void printInorder(node root) + { + if (root == null) + return; + printInorder(root.left); + System.out.print(root.data + "" ""); + printInorder(root.right); + } +/*Driver program to test above functions*/ + + public static void main(String[] args) + { + int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; + int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 }; + int size = pre.length; + node root = constructTree(pre, post, size); + System.out.println(""Inorder traversal of the constructed tree:""); + printInorder(root); + } +}"," '''Python3 program for construction of +full binary tree''' + + '''A binary tree node has data, pointer +to left child and a pointer to right child''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''A recursive function to construct +Full from pre[] and post[]. +preIndex is used to keep track +of index in pre[]. l is low index +and h is high index for the +current subarray in post[]''' + +def constructTreeUtil(pre: list, post: list, + l: int, h: int, + size: int) -> Node: + global preIndex + ''' Base case''' + + if (preIndex >= size or l > h): + return None + ''' The first node in preorder traversal + is root. So take the node at preIndex + from preorder and make it root, and + increment preIndex''' + + root = Node(pre[preIndex]) + preIndex += 1 + ''' If the current subarry has only + one element, no need to recur''' + + if (l == h or preIndex >= size): + return root + ''' Search the next element + of pre[] in post[]''' + + i = l + while i <= h: + if (pre[preIndex] == post[i]): + break + i += 1 + ''' Use the index of element + found in postorder to divide + postorder array in two parts. + Left subtree and right subtree''' + + if (i <= h): + root.left = constructTreeUtil(pre, post, + l, i, size) + root.right = constructTreeUtil(pre, post, + i + 1, h, + size) + return root + '''The main function to construct +Full Binary Tree from given +preorder and postorder traversals. +This function mainly uses constructTreeUtil()''' + +def constructTree(pre: list, + post: list, + size: int) -> Node: + global preIndex + return constructTreeUtil(pre, post, 0, + size - 1, size) + '''A utility function to print +inorder traversal of a Binary Tree''' + +def printInorder(node: Node) -> None: + if (node is None): + return + printInorder(node.left) + print(node.data, end = "" "") + printInorder(node.right) + '''Driver code''' + +if __name__ == ""__main__"": + pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ] + post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ] + size = len(pre) + preIndex = 0 + root = constructTree(pre, post, size) + print(""Inorder traversal of "" + ""the constructed tree: "") + printInorder(root)" +Closest Pair of Points using Divide and Conquer algorithm,," '''A divide and conquer program in Python3 +to find the smallest distance from a +given set of points.''' + +import math +import copy + '''A class to represent a Point in 2D plane''' + +class Point(): + def __init__(self, x, y): + self.x = x + self.y = y + '''A utility function to find the +distance between two points''' + +def dist(p1, p2): + return math.sqrt((p1.x - p2.x) * + (p1.x - p2.x) + + (p1.y - p2.y) * + (p1.y - p2.y)) + '''A Brute Force method to return the +smallest distance between two points +in P[] of size n''' + +def bruteForce(P, n): + min_val = float('inf') + for i in range(n): + for j in range(i + 1, n): + if dist(P[i], P[j]) < min_val: + min_val = dist(P[i], P[j]) + return min_val + '''A utility function to find the +distance beween the closest points of +strip of given size. All points in +strip[] are sorted accordint to +y coordinate. They all have an upper +bound on minimum distance as d. +Note that this method seems to be +a O(n^2) method, but it's a O(n) +method as the inner loop runs at most 6 times''' + +def stripClosest(strip, size, d): + ''' Initialize the minimum distance as d''' + + min_val = d + ''' Pick all points one by one and + try the next points till the difference + between y coordinates is smaller than d. + This is a proven fact that this loop + runs at most 6 times''' + + for i in range(size): + j = i + 1 + while j < size and (strip[j].y - + strip[i].y) < min_val: + min_val = dist(strip[i], strip[j]) + j += 1 + return min_val + '''A recursive function to find the +smallest distance. The array P contains +all points sorted according to x coordinate''' + +def closestUtil(P, Q, n): + ''' If there are 2 or 3 points, + then use brute force''' + + if n <= 3: + return bruteForce(P, n) + ''' Find the middle point''' + + mid = n // 2 + midPoint = P[mid] + ''' keep a copy of left and right branch''' + + Pl = P[:mid] + Pr = P[mid:] + ''' Consider the vertical line passing + through the middle point calculate + the smallest distance dl on left + of middle point and dr on right side''' + + dl = closestUtil(Pl, Q, mid) + dr = closestUtil(Pr, Q, n - mid) + ''' Find the smaller of two distances''' + + d = min(dl, dr) + ''' Build an array strip[] that contains + points close (closer than d) + to the line passing through the middle point''' + + stripP = [] + stripQ = [] + lr = Pl + Pr + for i in range(n): + if abs(lr[i].x - midPoint.x) < d: + stripP.append(lr[i]) + if abs(Q[i].x - midPoint.x) < d: + stripQ.append(Q[i]) + '''<-- REQUIRED''' + + stripP.sort(key = lambda point: point.y) + min_a = min(d, stripClosest(stripP, len(stripP), d)) + min_b = min(d, stripClosest(stripQ, len(stripQ), d)) + ''' Find the self.closest points in strip. + Return the minimum of d and self.closest + distance is strip[]''' + + return min(min_a,min_b) + '''The main function that finds +the smallest distance. +This method mainly uses closestUtil()''' + +def closest(P, n): + P.sort(key = lambda point: point.x) + Q = copy.deepcopy(P) + Q.sort(key = lambda point: point.y) + ''' Use recursive function closestUtil() + to find the smallest distance''' + + return closestUtil(P, Q, n) + '''Driver code''' + +P = [Point(2, 3), Point(12, 30), + Point(40, 50), Point(5, 1), + Point(12, 10), Point(3, 4)] +n = len(P) +print(""The smallest distance is"", + closest(P, n))" +Longest Span with same Sum in two Binary arrays,"/*A Simple Java program to find longest common +subarray of two binary arrays with same sum*/ + +class Test +{ + static int arr1[] = new int[]{0, 1, 0, 1, 1, 1, 1}; + static int arr2[] = new int[]{1, 1, 1, 1, 1, 0, 1}; +/* Returns length of the longest common sum in arr1[] + and arr2[]. Both are of same size n.*/ + + static int longestCommonSum(int n) + { +/* Initialize result*/ + + int maxLen = 0; +/* One by one pick all possible starting points + of subarrays*/ + + for (int i=0; i maxLen) + maxLen = len; + } + } + } + return maxLen; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.print(""Length of the longest common span with same sum is ""); + System.out.println(longestCommonSum(arr1.length)); + } +}"," '''A Simple python program to find longest common +subarray of two binary arrays with same sum + ''' '''Returns length of the longest common subarray +with same sum''' + +def longestCommonSum(arr1, arr2, n): + ''' Initialize result''' + + maxLen = 0 + ''' One by one pick all possible starting points + of subarrays''' + + for i in range(0,n): + ''' Initialize sums of current subarrays''' + + sum1 = 0 + sum2 = 0 + ''' Conider all points for starting with arr[i]''' + + for j in range(i,n): + ''' Update sums''' + + sum1 += arr1[j] + sum2 += arr2[j] + ''' If sums are same and current length is + more than maxLen, update maxLen''' + + if (sum1 == sum2): + len = j-i+1 + if (len > maxLen): + maxLen = len + return maxLen + '''Driver program to test above function''' + +arr1 = [0, 1, 0, 1, 1, 1, 1] +arr2 = [1, 1, 1, 1, 1, 0, 1] +n = len(arr1) +print(""Length of the longest common span with same "" + ""sum is"",longestCommonSum(arr1, arr2, n))" +"Given a sorted array and a number x, find the pair in array whose sum is closest to x","/*Java program to find pair with sum closest to x*/ + +import java.io.*; +import java.util.*; +import java.lang.Math; + +class CloseSum { + +/* Prints the pair with sum cloest to x*/ + + static void printClosest(int arr[], int n, int x) + { +/*To store indexes of result pair*/ + +int res_l=0, res_r=0; + +/* Initialize left and right indexes and difference between + pair sum and x*/ + + int l = 0, r = n-1, diff = Integer.MAX_VALUE; + +/* While there are elements between l and r*/ + + while (r > l) + { +/* Check if this pair is closer than the closest pair so far*/ + + if (Math.abs(arr[l] + arr[r] - x) < diff) + { + res_l = l; + res_r = r; + diff = Math.abs(arr[l] + arr[r] - x); + } + +/* If this pair has more sum, move to smaller values.*/ + + if (arr[l] + arr[r] > x) + r--; +/*Move to larger values*/ + +else + l++; + } + + System.out.println("" The closest pair is ""+arr[res_l]+"" and ""+ arr[res_r]); +} + + +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; + int n = arr.length; + printClosest(arr, n, x); + } +} + +"," '''Python3 program to find the pair +with sum +closest to a given no.''' + + + '''A sufficiently large value greater +than any +element in the input array''' + +MAX_VAL = 1000000000 + + + '''Prints the pair with sum closest to x''' + + +def printClosest(arr, n, x): + + ''' To store indexes of result pair''' + + res_l, res_r = 0, 0 + + ''' Initialize left and right indexes + and difference between + pair sum and x''' + + l, r, diff = 0, n-1, MAX_VAL + + ''' While there are elements between l and r''' + + while r > l: + ''' Check if this pair is closer than the + closest pair so far''' + + if abs(arr[l] + arr[r] - x) < diff: + res_l = l + res_r = r + diff = abs(arr[l] + arr[r] - x) + + if arr[l] + arr[r] > x: + ''' If this pair has more sum, move to + smaller values.''' + + r -= 1 + else: + ''' Move to larger values''' + + l += 1 + + print('The closest pair is {} and {}' + .format(arr[res_l], arr[res_r])) + + + '''Driver code to test above''' + +if __name__ == ""__main__"": + arr = [10, 22, 28, 29, 30, 40] + n = len(arr) + x=54 + printClosest(arr, n, x) + + +" +Number of sink nodes in a graph,"/*Java program to count number if sink nodes*/ + +import java.util.*; +class GFG +{ +/*Return the number of Sink NOdes.*/ + +static int countSink(int n, int m, + int edgeFrom[], int edgeTo[]) +{ +/* Array for marking the non-sink node.*/ + + int []mark = new int[n + 1]; +/* Marking the non-sink node.*/ + + for (int i = 0; i < m; i++) + mark[edgeFrom[i]] = 1; +/* Counting the sink nodes.*/ + + int count = 0; + for (int i = 1; i <= n ; i++) + if (mark[i] == 0) + count++; + return count; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int n = 4, m = 2; + int edgeFrom[] = { 2, 4 }; + int edgeTo[] = { 3, 3 }; + System.out.println(countSink(n, m, + edgeFrom, edgeTo)); +} +}"," '''Python3 program to count number if sink nodes + ''' '''Return the number of Sink NOdes. ''' + +def countSink(n, m, edgeFrom, edgeTo): + ''' Array for marking the non-sink node. ''' + + mark = [0] * (n + 1) + ''' Marking the non-sink node.''' + + for i in range(m): + mark[edgeFrom[i]] = 1 + ''' Counting the sink nodes. ''' + + count = 0 + for i in range(1, n + 1): + if (not mark[i]): + count += 1 + return count + '''Driver Code''' + +if __name__ == '__main__': + n = 4 + m = 2 + edgeFrom = [2, 4] + edgeTo = [3, 3] + print(countSink(n, m, edgeFrom, edgeTo))" +Find the smallest positive integer value that cannot be represented as sum of any subset of a given array,"/*Java program to find the smallest positive value that cannot be +represented as sum of subsets of a given sorted array*/ + +class FindSmallestInteger +{ +/* Returns the smallest number that cannot be represented as sum + of subset of elements from set represented by sorted array arr[0..n-1]*/ + + int findSmallest(int arr[], int n) + { +/*Initialize result*/ + +int res = 1; +/* Traverse the array and increment 'res' if arr[i] is + smaller than or equal to 'res'.*/ + + for (int i = 0; i < n && arr[i] <= res; i++) + res = res + arr[i]; + return res; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + FindSmallestInteger small = new FindSmallestInteger(); + int arr1[] = {1, 3, 4, 5}; + int n1 = arr1.length; + System.out.println(small.findSmallest(arr1, n1)); + int arr2[] = {1, 2, 6, 10, 11, 15}; + int n2 = arr2.length; + System.out.println(small.findSmallest(arr2, n2)); + int arr3[] = {1, 1, 1, 1}; + int n3 = arr3.length; + System.out.println(small.findSmallest(arr3, n3)); + int arr4[] = {1, 1, 3, 4}; + int n4 = arr4.length; + System.out.println(small.findSmallest(arr4, n4)); + } +}"," '''Python3 program to find the smallest +positive value that cannot be +represented as sum of subsets +of a given sorted array + ''' '''Returns the smallest number +that cannot be represented as sum +of subset of elements from set +represented by sorted array arr[0..n-1]''' + +def findSmallest(arr, n): + '''Initialize result''' + + res = 1 + ''' Traverse the array and increment + 'res' if arr[i] is smaller than + or equal to 'res'.''' + + for i in range (0, n ): + if arr[i] <= res: + res = res + arr[i] + else: + break + return res + '''Driver program to test above function''' + +arr1 = [1, 3, 4, 5] +n1 = len(arr1) +print(findSmallest(arr1, n1)) +arr2= [1, 2, 6, 10, 11, 15] +n2 = len(arr2) +print(findSmallest(arr2, n2)) +arr3= [1, 1, 1, 1] +n3 = len(arr3) +print(findSmallest(arr3, n3)) +arr4 = [1, 1, 3, 4] +n4 = len(arr4) +print(findSmallest(arr4, n4))" +Check for Children Sum Property in a Binary Tree,"/*Java program to check children sum property*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + public Node(int d) + { + data = d; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* returns 1 if children sum property holds for the given + node and both of its children*/ + + int isSumProperty(Node node) + { + /* left_data is left child data and right_data is for right + child data*/ + + int left_data = 0, right_data = 0; + /* If node is NULL or it's a leaf node then + return true */ + + if (node == null + || (node.left == null && node.right == null)) + return 1; + else + { + /* If left child is not present then 0 is used + as data of left child */ + + if (node.left != null) + left_data = node.left.data; + /* If right child is not present then 0 is used + as data of right child */ + + if (node.right != null) + right_data = node.right.data; + /* if the node and both of its children satisfy the + property return 1 else 0*/ + + if ((node.data == left_data + right_data) + && (isSumProperty(node.left)!=0) + && isSumProperty(node.right)!=0) + return 1; + else + return 0; + } + } + /* driver program to test the above functions */ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(2); + if (tree.isSumProperty(tree.root) != 0) + System.out.println(""The given tree satisfies children"" + + "" sum property""); + else + System.out.println(""The given tree does not satisfy children"" + + "" sum property""); + } +}"," '''Python3 program to check children +sum property ''' + + '''returns 1 if children sum property +holds for the given node and both +of its children''' + +def isSumProperty(node): + ''' left_data is left child data and + right_data is for right child data''' + + left_data = 0 + right_data = 0 + ''' If node is None or it's a leaf + node then return true ''' + + if(node == None or (node.left == None and + node.right == None)): + return 1 + else: + ''' If left child is not present then + 0 is used as data of left child ''' + + if(node.left != None): + left_data = node.left.data + ''' If right child is not present then + 0 is used as data of right child ''' + + if(node.right != None): + right_data = node.right.data + ''' if the node and both of its children + satisfy the property return 1 else 0''' + + if((node.data == left_data + right_data) and + isSumProperty(node.left) and + isSumProperty(node.right)): + return 1 + else: + return 0 + '''Helper class that allocates a new +node with the given data and None +left and right pointers. ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Driver Code''' + +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.right = newNode(2) + if(isSumProperty(root)): + print(""The given tree satisfies the"", + ""children sum property "") + else: + print(""The given tree does not satisfy"", + ""the children sum property "")" +"Given an n x n square matrix, find sum of all sub-squares of size k x k","/*A simple Java program to find sum of all +subsquares of size k x k*/ + +class GFG +{ +/* Size of given matrix*/ + + static final int n = 5; +/* A simple function to find sum of all + sub-squares of size k x k in a given + square matrix of size n x n*/ + + static void printSumSimple(int mat[][], int k) + { +/* k must be smaller than or + equal to n*/ + + if (k > n) return; +/* row number of first cell in + current sub-square of size k x k*/ + + for (int i = 0; i < n-k+1; i++) + { +/* column of first cell in current + sub-square of size k x k*/ + + for (int j = 0; j < n-k+1; j++) + { +/* Calculate and print sum of + current sub-square*/ + + int sum = 0; + for (int p = i; p < k+i; p++) + for (int q = j; q < k+j; q++) + sum += mat[p][q]; + System.out.print(sum+ "" ""); + } +/* Line separator for sub-squares + starting with next row*/ + + System.out.println(); + } + } +/* Driver Program to test above function*/ + + public static void main(String arg[]) + { + int mat[][] = {{1, 1, 1, 1, 1}, + {2, 2, 2, 2, 2}, + {3, 3, 3, 3, 3}, + {4, 4, 4, 4, 4}, + {5, 5, 5, 5, 5}}; + int k = 3; + printSumSimple(mat, k); + } +}"," '''A simple Python 3 program to find sum +of all subsquares of ''' '''size k x k +Size of given matrix''' + +n = 5 + '''A simple function to find sum of all +sub-squares of size k x k in a given +square matrix of size n x n''' + +def printSumSimple(mat, k): + ''' k must be smaller than or equal to n''' + + if (k > n): + return + ''' row number of first cell in current + sub-square of size k x k''' + + for i in range(n - k + 1): + ''' column of first cell in current + sub-square of size k x k''' + + for j in range(n - k + 1): + ''' Calculate and print sum of + current sub-square''' + + sum = 0 + for p in range(i, k + i): + for q in range(j, k + j): + sum += mat[p][q] + print(sum, end = "" "") + ''' Line separator for sub-squares + starting with next row''' + + print() + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5]] + k = 3 + printSumSimple(mat, k)" +Ford-Fulkerson Algorithm for Maximum Flow Problem,"/*Java program for implementation of Ford Fulkerson +algorithm*/ + +import java.io.*; +import java.lang.*; +import java.util.*; +import java.util.LinkedList; +class MaxFlow { +/*Number of vertices in graph*/ + +static final int V = 6; + /* Returns true if there is a path from source 's' to + sink 't' in residual graph. Also fills parent[] to + store the path */ + + boolean bfs(int rGraph[][], int s, int t, int parent[]) + { +/* Create a visited array and mark all vertices as + not visited*/ + + boolean visited[] = new boolean[V]; + for (int i = 0; i < V; ++i) + visited[i] = false; +/* Create a queue, enqueue source vertex and mark + source vertex as visited*/ + + LinkedList queue + = new LinkedList(); + queue.add(s); + visited[s] = true; + parent[s] = -1; +/* Standard BFS Loop*/ + + while (queue.size() != 0) { + int u = queue.poll(); + for (int v = 0; v < V; v++) { + if (visited[v] == false + && rGraph[u][v] > 0) { +/* If we find a connection to the sink + node, then there is no point in BFS + anymore We just have to set its parent + and can return true*/ + + if (v == t) { + parent[v] = u; + return true; + } + queue.add(v); + parent[v] = u; + visited[v] = true; + } + } + } +/* We didn't reach sink in BFS starting from source, + so return false*/ + + return false; + } +/* Returns tne maximum flow from s to t in the given + graph*/ + + int fordFulkerson(int graph[][], int s, int t) + { + int u, v; +/* Create a residual graph and fill the residual + graph with given capacities in the original graph + as residual capacities in residual graph + Residual graph where rGraph[i][j] indicates + residual capacity of edge from i to j (if there + is an edge. If rGraph[i][j] is 0, then there is + not)*/ + + int rGraph[][] = new int[V][V]; + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; +/* This array is filled by BFS and to store path*/ + + int parent[] = new int[V]; +/*There is no flow initially*/ + +int max_flow = 0; +/* Augment the flow while tere is path from source + to sink*/ + + while (bfs(rGraph, s, t, parent)) { +/* Find minimum residual capacity of the edhes + along the path filled by BFS. Or we can say + find the maximum flow through the path found.*/ + + int path_flow = Integer.MAX_VALUE; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + path_flow + = Math.min(path_flow, rGraph[u][v]); + } +/* update residual capacities of the edges and + reverse edges along the path*/ + + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } +/* Add path flow to overall flow*/ + + max_flow += path_flow; + } +/* Return the overall flow*/ + + return max_flow; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + throws java.lang.Exception + { +/* Let us create a graph shown in the above example*/ + + int graph[][] = new int[][] { + { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, + { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, + { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } + }; + MaxFlow m = new MaxFlow(); + System.out.println(""The maximum possible flow is "" + + m.fordFulkerson(graph, 0, 5)); + } +}"," '''Python program for implementation +of Ford Fulkerson algorithm''' + +from collections import defaultdict + '''Returns true if there is a path from source 's' to sink 't' in + residual graph. Also fills parent[] to store the path ''' + + def BFS(self, s, t, parent): + ''' Mark all the vertices as not visited''' + + visited = [False]*(self.ROW) + ''' Create a queue for BFS''' + + queue = [] + queue.append(s) + visited[s] = True ''' Standard BFS Loop''' + + while queue: + u = queue.pop(0) + for ind, val in enumerate(self.graph[u]): + if visited[ind] == False and val > 0: ''' If we find a connection to the sink node, + then there is no point in BFS anymore + We just have to set its parent and can return true''' + + if ind == t: + visited[ind] = True + return True + queue.append(ind) + visited[ind] = True + parent[ind] = u + ''' We didn't reach sink in BFS starting + from source, so return false''' + + return False + ''' Returns tne maximum flow from s to t in the given graph''' + + def FordFulkerson(self, source, sink): + '''This class represents a directed graph +using adjacency matrix representation''' + +class Graph: + def __init__(self, graph): + self.graph = graph + self. ROW = len(graph) ''' This array is filled by BFS and to store path''' + + parent = [-1]*(self.ROW) + '''There is no flow initially''' + +max_flow = 0 + ''' Augment the flow while there is path from source to sink''' + + while self.BFS(source, sink, parent) : + ''' Find minimum residual capacity of the edges along the + path filled by BFS. Or we can say find the maximum flow + through the path found.''' + + path_flow = float(""Inf"") + s = sink + while(s != source): + path_flow = min (path_flow, self.graph[parent[s]][s]) + s = parent[s] + ''' update residual capacities of the edges and reverse edges + along the path''' + + v = sink + while(v != source): + u = parent[v] + self.graph[u][v] -= path_flow + self.graph[v][u] += path_flow + v = parent[v] + + ''' Add path flow to overall flow''' + + max_flow += path_flow + '''Return the overall flow''' + + return max_flow '''Create a graph given in the above diagram''' + +graph = [[0, 16, 13, 0, 0, 0], + [0, 0, 10, 12, 0, 0], + [0, 4, 0, 0, 14, 0], + [0, 0, 9, 0, 0, 20], + [0, 0, 0, 7, 0, 4], + [0, 0, 0, 0, 0, 0]] +g = Graph(graph) +source = 0; sink = 5 +print (""The maximum possible flow is %d "" % g.FordFulkerson(source, sink)) + + + " +Form minimum number from given sequence,"/*Java program to print minimum number that can be formed +from a given sequence of Is and Ds*/ + +import java.io.*; +import java.util.*; +public class GFG { + static void printLeast(String arr) + { +/* min_avail represents the minimum number which is + still available for inserting in the output vector. + pos_of_I keeps track of the most recent index + where 'I' was encountered w.r.t the output vector*/ + + int min_avail = 1, pos_of_I = 0; +/* vector to store the output*/ + + ArrayList al = new ArrayList<>(); +/* cover the base cases*/ + + if (arr.charAt(0) == 'I') + { + al.add(1); + al.add(2); + min_avail = 3; + pos_of_I = 1; + } + else + { + al.add(2); + al.add(1); + min_avail = 3; + pos_of_I = 0; + } +/* Traverse rest of the input*/ + + for (int i = 1; i < arr.length(); i++) + { + if (arr.charAt(i) == 'I') + { + al.add(min_avail); + min_avail++; + pos_of_I = i + 1; + } + else + { + al.add(al.get(i)); + for (int j = pos_of_I; j <= i; j++) + al.set(j, al.get(j) + 1); + min_avail++; + } + } +/* print the number*/ + + for (int i = 0; i < al.size(); i++) + System.out.print(al.get(i) + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String args[]) + { + printLeast(""IDID""); + printLeast(""I""); + printLeast(""DD""); + printLeast(""II""); + printLeast(""DIDI""); + printLeast(""IIDDD""); + printLeast(""DDIDDIID""); + } +}"," '''Python3 program to print minimum number +that can be formed from a given sequence +of Is and Ds''' + +def printLeast(arr): + ''' min_avail represents the minimum + number which is still available + for inserting in the output vector. + pos_of_I keeps track of the most + recent index where 'I' was + encountered w.r.t the output vector''' + + min_avail = 1 + pos_of_I = 0 + ''' Vector to store the output''' + + v = [] + ''' Cover the base cases''' + + if (arr[0] == 'I'): + v.append(1) + v.append(2) + min_avail = 3 + pos_of_I = 1 + else: + v.append(2) + v.append(1) + min_avail = 3 + pos_of_I = 0 + ''' Traverse rest of the input''' + + for i in range(1, len(arr)): + if (arr[i] == 'I'): + v.append(min_avail) + min_avail += 1 + pos_of_I = i + 1 + else: + v.append(v[i]) + for j in range(pos_of_I, i + 1): + v[j] += 1 + min_avail += 1 + ''' Print the number''' + + print(*v, sep = ' ') + '''Driver code''' + +printLeast(""IDID"") +printLeast(""I"") +printLeast(""DD"") +printLeast(""II"") +printLeast(""DIDI"") +printLeast(""IIDDD"") +printLeast(""DDIDDIID"")" +Range Minimum Query (Square Root Decomposition and Sparse Table),"/*Java program to do range minimum query +in O(1) time with O(n*n) extra space +and O(n*n) preprocessing time.*/ + +import java.util.*; +class GFG { + static int MAX = 500; +/* lookup[i][j] is going to store index of + minimum value in arr[i..j]*/ + + static int[][] lookup = new int[MAX][MAX]; +/* Structure to represent a query range*/ + + static class Query { + int L, R; + public Query(int L, int R) + { + this.L = L; + this.R = R; + } + }; +/* Fills lookup array lookup[n][n] for + all possible values of query ranges*/ + + static void preprocess(int arr[], int n) + { +/* Initialize lookup[][] for + the intervals with length 1*/ + + for (int i = 0; i < n; i++) + lookup[i][i] = i; +/* Fill rest of the entries in bottom up manner*/ + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) +/* To find minimum of [0,4], + we compare minimum of + arr[lookup[0][3]] with arr[4].*/ + + if (arr[lookup[i][j - 1]] < arr[j]) + lookup[i][j] = lookup[i][j - 1]; + else + lookup[i][j] = j; + } + } +/* Prints minimum of given m query + ranges in arr[0..n-1]*/ + + static void RMQ(int arr[], int n, Query q[], int m) + { +/* Fill lookup table for + all possible input queries*/ + + preprocess(arr, n); +/* One by one compute sum of all queries*/ + + for (int i = 0; i < m; i++) { +/* Left and right boundaries + of current range*/ + + int L = q[i].L, R = q[i].R; +/* Print sum of current query range*/ + + System.out.println(""Minimum of ["" + L + "", "" + R + + ""] is "" + + arr[lookup[L][R]]); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; + int n = a.length; + Query q[] = { new Query(0, 4), new Query(4, 7), + new Query(7, 8) }; + int m = q.length; + RMQ(a, n, q, m); + } +}"," '''Python3 program to do range +minimum query in O(1) time with +O(n*n) extra space and O(n*n) +preprocessing time.''' + +MAX = 500 + '''lookup[i][j] is going to store +index of minimum value in +arr[i..j]''' + +lookup = [[0 for j in range(MAX)] + for i in range(MAX)] + '''Structure to represent +a query range''' + +class Query: + def __init__(self, L, R): + self.L = L + self.R = R + '''Fills lookup array lookup[n][n] +for all possible values +of query ranges''' + +def preprocess(arr, n): + ''' Initialize lookup[][] for the + intervals with length 1''' + + for i in range(n): + lookup[i][i] = i; + ''' Fill rest of the entries in + bottom up manner''' + + for i in range(n): + for j in range(i + 1, n): + ''' To find minimum of [0,4], + we compare minimum + of arr[lookup[0][3]] with arr[4].''' + + if (arr[lookup[i][j - 1]] < arr[j]): + lookup[i][j] = lookup[i][j - 1]; + else: + lookup[i][j] = j; + '''Prints minimum of given m +query ranges in arr[0..n-1]''' + +def RMQ(arr, n, q, m): + ''' Fill lookup table for + all possible input queries''' + + preprocess(arr, n); + ''' One by one compute sum of + all queries''' + + for i in range(m): + ''' Left and right boundaries + of current range''' + + L = q[i].L + R = q[i].R; + ''' Print sum of current query range''' + + print(""Minimum of ["" + str(L) + "", "" + + str(R) + ""] is "" + + str(arr[lookup[L][R]])) + '''Driver code''' + +if __name__ == ""__main__"": + a = [7, 2, 3, 0, 5, + 10, 3, 12, 18] + n = len(a) + q = [Query(0, 4), + Query(4, 7), + Query(7, 8)] + m = len(q) + RMQ(a, n, q, m);" +Maximum Product Subarray,"/*Java program to find maximum product subarray*/ + +import java.io.*; + +class GFG { + /* Returns the product of max product subarray.*/ + + static int maxSubarrayProduct(int arr[]) + { +/* Initializing result*/ + + int result = arr[0]; + int n = arr.length; + + for (int i = 0; i < n; i++) + { + int mul = arr[i]; +/* traversing in current subarray*/ + + for (int j = i + 1; j < n; j++) + { +/* updating result every time + to keep an eye over the + maximum product*/ + + result = Math.max(result, mul); + mul *= arr[j]; + } +/* updating the result for (n-1)th index.*/ + + result = Math.max(result, mul); + } + return result; + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; + System.out.println(""Maximum Sub array product is "" + + maxSubarrayProduct(arr)); + } +} + + +"," '''Python3 program to find Maximum Product Subarray''' + + + '''Returns the product of max product subarray.''' + +def maxSubarrayProduct(arr, n): + + ''' Initializing result''' + + result = arr[0] + + for i in range(n): + + mul = arr[i] + + ''' traversing in current subarray''' + + for j in range(i + 1, n): + + ''' updating result every time + to keep an eye over the maximum product''' + + result = max(result, mul) + mul *= arr[j] + + ''' updating the result for (n-1)th index.''' + + result = max(result, mul) + + return result + + '''Driver code''' + +arr = [ 1, -2, -3, 0, 7, -8, -2 ] +n = len(arr) +print(""Maximum Sub array product is"" , maxSubarrayProduct(arr, n)) + + +" +Function to check if a singly linked list is palindrome,"/* Java program to check if linked list is palindrome */ + +class LinkedList { +/* Linked list Node*/ + + class Node { + char data; + Node next; + Node(char d) + { + data = d; + next = null; + } + } + /*head of list*/ + +Node head; + Node slow_ptr, fast_ptr, second_half; + /* Function to check if given linked list is + palindrome or not */ + + boolean isPalindrome(Node head) + { + slow_ptr = head; + fast_ptr = head; + Node prev_of_slow_ptr = head; +/*To handle odd size list*/ + +Node midnode = null; +/*initialize result*/ + +boolean res = true; + if (head != null && head.next != null) { + /* Get the middle of the list. Move slow_ptr by 1 + and fast_ptrr by 2, slow_ptr will have the middle + node */ + + while (fast_ptr != null && fast_ptr.next != null) { + fast_ptr = fast_ptr.next.next; + /*We need previous of the slow_ptr for + linked lists with odd elements */ + + prev_of_slow_ptr = slow_ptr; + slow_ptr = slow_ptr.next; + } + /* fast_ptr would become NULL when there are even elements + in the list and not NULL for odd elements. We need to skip + the middle node for odd case and store it somewhere so that + we can restore the original list */ + + if (fast_ptr != null) { + midnode = slow_ptr; + slow_ptr = slow_ptr.next; + } +/* Now reverse the second half and compare it with first half*/ + + second_half = slow_ptr; +/*NULL terminate first half*/ + +prev_of_slow_ptr.next = null; +/*Reverse the second half*/ + +reverse(); +/*compare*/ + +res = compareLists(head, second_half); + /* Construct the original list back */ + +/*Reverse the second half again*/ + +reverse(); + if (midnode != null) { +/* If there was a mid node (odd size case) which + was not part of either first half or second half.*/ + + prev_of_slow_ptr.next = midnode; + midnode.next = second_half; + } + else + prev_of_slow_ptr.next = second_half; + } + return res; + } + /* Function to reverse the linked list Note that this + function may change the head */ + + void reverse() + { + Node prev = null; + Node current = second_half; + Node next; + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + second_half = prev; + } + /* Function to check if two input lists have same data*/ + + boolean compareLists(Node head1, Node head2) + { + Node temp1 = head1; + Node temp2 = head2; + while (temp1 != null && temp2 != null) { + if (temp1.data == temp2.data) { + temp1 = temp1.next; + temp2 = temp2.next; + } + else + return false; + } + /* Both are empty reurn 1*/ + + if (temp1 == null && temp2 == null) + return true; + /* Will reach here when one is NULL + and other is not */ + + return false; + } + /* Push a node to linked list. Note that this function + changes the head */ + + public void push(char new_data) + { + /* Allocate the Node & + Put in the data */ + + Node new_node = new Node(new_data); + /* link the old list off the new one */ + + new_node.next = head; + /* Move the head to point to new Node */ + + head = new_node; + } +/* A utility function to print a given linked list*/ + + void printList(Node ptr) + { + while (ptr != null) { + System.out.print(ptr.data + ""->""); + ptr = ptr.next; + } + System.out.println(""NULL""); + } + /* Driver program to test the above functions */ + + public static void main(String[] args) + { + /* Start with the empty list */ + + LinkedList llist = new LinkedList(); + char str[] = { 'a', 'b', 'a', 'c', 'a', 'b', 'a' }; + String string = new String(str); + for (int i = 0; i < 7; i++) { + llist.push(str[i]); + llist.printList(llist.head); + if (llist.isPalindrome(llist.head) != false) { + System.out.println(""Is Palindrome""); + System.out.println(""""); + } + else { + System.out.println(""Not Palindrome""); + System.out.println(""""); + } + } + } +}"," '''Python3 program to check if +linked list is palindrome''' + '''Node class''' +class Node: + def __init__(self, data): + self.data = data + self.next = None +class LinkedList: + ''' Function to initialize head''' + + def __init__(self): + self.head = None + ''' Function to check if given + linked list is pallindrome or not''' + + def isPalindrome(self, head): + slow_ptr = head + fast_ptr = head + prev_of_slow_ptr = head + ''' To handle odd size list''' + + midnode = None + ''' Initialize result''' + + res = True + if (head != None and head.next != None): + ''' Get the middle of the list. + Move slow_ptr by 1 and + fast_ptrr by 2, slow_ptr + will have the middle node''' + + while (fast_ptr != None and + fast_ptr.next != None): + ''' We need previous of the slow_ptr + for linked lists with odd + elements''' + + fast_ptr = fast_ptr.next.next + prev_of_slow_ptr = slow_ptr + slow_ptr = slow_ptr.next + ''' fast_ptr would become NULL when + there are even elements in the + list and not NULL for odd elements. + We need to skip the middle node for + odd case and store it somewhere so + that we can restore the original list''' + + if (fast_ptr != None): + midnode = slow_ptr + slow_ptr = slow_ptr.next + ''' Now reverse the second half + and compare it with first half''' + + second_half = slow_ptr + ''' NULL terminate first half''' + + prev_of_slow_ptr.next = None + ''' Reverse the second half''' + + second_half = self.reverse(second_half) + ''' Compare''' + + res = self.compareLists(head, second_half) + ''' Construct the original list back''' + '''Reverse the second half again''' + + second_half = self.reverse(second_half) + if (midnode != None): + ''' If there was a mid node (odd size + case) which was not part of either + first half or second half.''' + + prev_of_slow_ptr.next = midnode + midnode.next = second_half + else: + prev_of_slow_ptr.next = second_half + return res + ''' Function to reverse the linked list + Note that this function may change + the head''' + + def reverse(self, second_half): + prev = None + current = second_half + next = None + while current != None: + next = current.next + current.next = prev + prev = current + current = next + second_half = prev + return second_half + ''' Function to check if two input + lists have same data''' + + def compareLists(self, head1, head2): + temp1 = head1 + temp2 = head2 + while (temp1 and temp2): + if (temp1.data == temp2.data): + temp1 = temp1.next + temp2 = temp2.next + else: + return 0 + ''' Both are empty return 1''' + + if (temp1 == None and temp2 == None): + return 1 + ''' Will reach here when one is NULL + and other is not''' + + return 0 + ''' Function to insert a new node + at the beginning''' + + def push(self, new_data): + ''' Allocate the Node & + Put in the data''' + + new_node = Node(new_data) + ''' Link the old list off the new one''' + + new_node.next = self.head + ''' Move the head to point to new Node''' + + self.head = new_node + ''' A utility function to print + a given linked list''' + + def printList(self): + temp = self.head + while(temp): + print(temp.data, end = ""->"") + temp = temp.next + print(""NULL"") + '''Driver code''' + +if __name__ == '__main__': + '''Start with the empty list ''' + + l = LinkedList() + s = [ 'a', 'b', 'a', 'c', 'a', 'b', 'a' ] + for i in range(7): + l.push(s[i]) + l.printList() + if (l.isPalindrome(l.head) != False): + print(""Is Palindrome\n"") + else: + print(""Not Palindrome\n"") + print()" +Maximum sum such that no two elements are adjacent,"class MaximumSum +{ + /*Function to return max sum such that no two elements + are adjacent */ + + int FindMaxSum(int arr[], int n) + { + int incl = arr[0]; + int excl = 0; + int excl_new; + int i; + for (i = 1; i < n; i++) + { + /* current max excluding i */ + + excl_new = (incl > excl) ? incl : excl; + /* current max including i */ + + incl = excl + arr[i]; + excl = excl_new; + } + /* return max of incl and excl */ + + return ((incl > excl) ? incl : excl); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + MaximumSum sum = new MaximumSum(); + int arr[] = new int[]{5, 5, 10, 100, 10, 5}; + System.out.println(sum.FindMaxSum(arr, arr.length)); + } +}"," '''''' '''Function to return max sum such that +no two elements are adjacent''' + +def find_max_sum(arr): + incl = 0 + excl = 0 + for i in arr: + ''' Current max excluding i (No ternary in + Python)''' + + new_excl = excl if excl>incl else incl + ''' Current max including i''' + + incl = excl + i + excl = new_excl + ''' return max of incl and excl''' + + return (excl if excl>incl else incl) + '''Driver program to test above function''' + +arr = [5, 5, 10, 100, 10, 5] +print find_max_sum(arr)" +Largest Sum Contiguous Subarray,"static int maxSubArraySum(int a[],int size) +{ + int max_so_far = a[0], max_ending_here = 0; + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_ending_here < 0) + max_ending_here = 0; + /* Do not compare for all + elements. Compare only + when max_ending_here > 0 */ + + else if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + } + return max_so_far; +}","def maxSubArraySum(a,size): + max_so_far = a[0] + max_ending_here = 0 + for i in range(0, size): + max_ending_here = max_ending_here + a[i] + if max_ending_here < 0: + max_ending_here = 0 + ''' Do not compare for all elements. Compare only + when max_ending_here > 0''' + + elif (max_so_far < max_ending_here): + max_so_far = max_ending_here + return max_so_far" +Iterative Search for a key 'x' in Binary Tree,"/*An iterative method to search an item in Binary Tree*/ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, +left child and right child */ + +static class node +{ + int data; + node left, right; +}; +/* Helper function that allocates a +new node with the given data and +null left and right pointers.*/ + +static node newNode(int data) +{ + node node = new node(); + node.data = data; + node.left = node.right = null; + return(node); +} +/*iterative process to search +an element x in a given binary tree*/ + +static boolean iterativeSearch(node root, int x) +{ +/* Base Case*/ + + if (root == null) + return false; +/* Create an empty stack and push root to it*/ + + Stack nodeStack = new Stack(); + nodeStack.push(root); +/* Do iterative preorder traversal to search x*/ + + while (nodeStack.empty() == false) + { +/* See the top item from stack and + check if it is same as x*/ + + node node = nodeStack.peek(); + if (node.data == x) + return true; + nodeStack.pop(); +/* Push right and left children + of the popped node to stack*/ + + if (node.right != null) + nodeStack.push(node.right); + if (node.left != null) + nodeStack.push(node.left); + } + return false; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + node NewRoot = null; + node root = newNode(2); + root.left = newNode(7); + root.right = newNode(5); + root.left.right = newNode(6); + root.left.right.left = newNode(1); + root.left.right.right = newNode(11); + root.right.right = newNode(9); + root.right.right.left = newNode(4); + if(iterativeSearch(root, 6)) + System.out.println(""Found""); + else + System.out.println(""Not Found""); + if(iterativeSearch(root, 12)) + System.out.println(""Found""); + else + System.out.println(""Not Found""); +} +}"," '''An iterative Python3 code to search +an item in Binary Tree''' + + ''' A binary tree node has data, +left child and right child ''' + +class newNode: + ''' Construct to create a newNode ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''iterative process to search an element x +in a given binary tree''' + +def iterativeSearch(root,x): + ''' Base Case''' + + if (root == None): + return False + ''' Create an empty stack and + append root to it''' + + nodeStack = [] + nodeStack.append(root) + ''' Do iterative preorder traversal to search x''' + + while (len(nodeStack)): + ''' See the top item from stack and + check if it is same as x''' + + node = nodeStack[0] + if (node.data == x): + return True + nodeStack.pop(0) + ''' append right and left children + of the popped node to stack''' + + if (node.right): + nodeStack.append(node.right) + if (node.left): + nodeStack.append(node.left) + return False + '''Driver Code''' + +root = newNode(2) +root.left = newNode(7) +root.right = newNode(5) +root.left.right = newNode(6) +root.left.right.left = newNode(1) +root.left.right.right = newNode(11) +root.right.right = newNode(9) +root.right.right.left = newNode(4) +if iterativeSearch(root, 6): + print(""Found"") +else: + print(""Not Found"") +if iterativeSearch(root, 12): + print(""Found"") +else: + print(""Not Found"")" +Find Excel column name from a given column number,"/*Java program to find Excel +column name from a given +column number*/ + +public class ExcelColumnTitle { +/* Function to print Excel column + name for a given column number*/ + + private static void printString(int columnNumber) + { +/* To store result (Excel column name)*/ + + StringBuilder columnName = new StringBuilder(); + while (columnNumber > 0) { +/* Find remainder*/ + + int rem = columnNumber % 26; +/* If remainder is 0, then a + 'Z' must be there in output*/ + + if (rem == 0) { + columnName.append(""Z""); + columnNumber = (columnNumber / 26) - 1; + } +/*If remainder is non-zero*/ + +else + { + columnName.append((char)((rem - 1) + 'A')); + columnNumber = columnNumber / 26; + } + } +/* Reverse the string and print result*/ + + System.out.println(columnName.reverse()); + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + printString(26); + printString(51); + printString(52); + printString(80); + printString(676); + printString(702); + printString(705); + } +}"," '''Python program to find Excel column name from a +given column number''' + +MAX = 50 + '''Function to print Excel column name +for a given column number''' + +def printString(n): + ''' To store current index in str which is result''' + string = [""\0""] * MAX + i = 0 + while n > 0: + ''' Find remainder''' + + rem = n % 26 + ''' if remainder is 0, then a + 'Z' must be there in output''' + + if rem == 0: + string[i] = 'Z' + i += 1 + n = (n / 26) - 1 + + '''If remainder is non-zero''' + + else: + string[i] = chr((rem - 1) + ord('A')) + i += 1 + n = n / 26 + string[i] = '\0' ''' Reverse the string and print result''' + + string = string[::-1] + print """".join(string) + '''Driver program to test the above Function''' + +printString(26) +printString(51) +printString(52) +printString(80) +printString(676) +printString(702) +printString(705)" +Comb Sort,"/*Java program for implementation of Comb Sort*/ + +class CombSort +{ +/* To find gap between elements*/ + + int getNextGap(int gap) + { +/* Shrink gap by Shrink factor*/ + + gap = (gap*10)/13; + if (gap < 1) + return 1; + return gap; + } +/* Function to sort arr[] using Comb Sort*/ + + void sort(int arr[]) + { + int n = arr.length; +/* initialize gap*/ + + int gap = n; +/* Initialize swapped as true to make sure that + loop runs*/ + + boolean swapped = true; +/* Keep running while gap is more than 1 and last + iteration caused a swap*/ + + while (gap != 1 || swapped == true) + { +/* Find next gap*/ + + gap = getNextGap(gap); +/* Initialize swapped as false so that we can + check if swap happened or not*/ + + swapped = false; +/* Compare all elements with current gap*/ + + for (int i=0; i arr[i+gap]) + { +/* Swap arr[i] and arr[i+gap]*/ + + int temp = arr[i]; + arr[i] = arr[i+gap]; + arr[i+gap] = temp; +/* Set swapped*/ + + swapped = true; + } + } + } + } +/* Driver method*/ + + public static void main(String args[]) + { + CombSort ob = new CombSort(); + int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; + ob.sort(arr); + System.out.println(""sorted array""); + for (int i=0; i arr[i + gap]: + +/* Swap arr[i] and arr[i+gap]*/ + + arr[i], arr[i + gap]=arr[i + gap], arr[i] +/* Set swapped*/ + + swapped = True '''Driver code to test above''' + +arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0] +combSort(arr) +print (""Sorted array:"") +for i in range(len(arr)): + print (arr[i])," +Number of subarrays having sum exactly equal to k,"/*Java program for +the above approach*/ + +import java.util.*; +class Solution { + public static void main(String[] args) + { + int arr[] = { 10, 2, -2, -20, 10 }; + int k = -10; + int n = arr.length; + int res = 0; +/* calculate all subarrays*/ + + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = i; j < n; j++) { +/* calculate required sum*/ + + sum += arr[j]; +/* check if sum is equal to + required sum*/ + + if (sum == k) + res++; + } + } + System.out.println(res); + } +}"," '''Python3 program for +the above approach''' + +arr = [ 10, 2, -2, -20, 10 ] +n = len(arr) +k = -10 +res = 0 + '''Calculate all subarrays''' + +for i in range(n): + summ = 0 + for j in range(i, n): + ''' Calculate required sum''' + + summ += arr[j] + ''' Check if sum is equal to + required sum''' + + if summ == k: + res += 1 +print(res)" +Find missing elements of a range,"/*An array based Java program +to find missing elements from +an array*/ + +import java.util.Arrays; +public class Print { +/* Print all elements of range + [low, high] that are not present + in arr[0..n-1]*/ + + static void printMissing( + int arr[], int low, + int high) + { +/* Create boolean array of + size high-low+1, each index i + representing wether (i+low)th + element found or not.*/ + + boolean[] points_of_range = new boolean + [high - low + 1]; + for (int i = 0; i < arr.length; i++) { +/* if ith element of arr is in + range low to high then mark + corresponding index as true in array*/ + + if (low <= arr[i] && arr[i] <= high) + points_of_range[arr[i] - low] = true; + } +/* Traverse through the range and print all + elements whose value is false*/ + + for (int x = 0; x <= high - low; x++) { + if (points_of_range[x] == false) + System.out.print((low + x) + "" ""); + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 5, 4 }; + int low = 1, high = 10; + printMissing(arr, low, high); + } +}"," '''An array-based Python3 program to +find missing elements from an array + ''' '''Print all elements of range +[low, high] that are not +present in arr[0..n-1]''' + +def printMissing(arr, n, low, high): + ''' Create boolean list of size + high-low+1, each index i + representing wether (i+low)th + element found or not.''' + + points_of_range = [False] * (high-low+1) + for i in range(n) : + ''' if ith element of arr is in range + low to high then mark corresponding + index as true in array''' + + if ( low <= arr[i] and arr[i] <= high ) : + points_of_range[arr[i]-low] = True + ''' Traverse through the range + and print all elements whose value + is false''' + + for x in range(high-low+1) : + if (points_of_range[x]==False) : + print(low+x, end = "" "") + '''Driver Code''' + +arr = [1, 3, 5, 4] +n = len(arr) +low, high = 1, 10 +printMissing(arr, n, low, high)" +Majority Element,"/* Program for finding out majority element in an array */ + +class MajorityElement { + /* Function to find the candidate for Majority */ + + int findCandidate(int a[], int size) + { + int maj_index = 0, count = 1; + int i; + for (i = 1; i < size; i++) { + if (a[maj_index] == a[i]) + count++; + else + count--; + if (count == 0) { + maj_index = i; + count = 1; + } + } + return a[maj_index]; + } + /* Function to check if the candidate occurs more + than n/2 times */ + + boolean isMajority(int a[], int size, int cand) + { + int i, count = 0; + for (i = 0; i < size; i++) { + if (a[i] == cand) + count++; + } + if (count > size / 2) + return true; + else + return false; + } + /* Function to print Majority Element */ + + void printMajority(int a[], int size) + { + /* Find the candidate for Majority*/ + + int cand = findCandidate(a, size); + /* Print the candidate if it is Majority*/ + + if (isMajority(a, size, cand)) + System.out.println("" "" + cand + "" ""); + else + System.out.println(""No Majority Element""); + } + /* Driver code */ + + public static void main(String[] args) + { + MajorityElement majorelement + = new MajorityElement(); + int a[] = new int[] { 1, 3, 3, 1, 2 }; +/* Function call*/ + + int size = a.length; + majorelement.printMajority(a, size); + } +}"," '''Program for finding out majority element in an array + ''' '''Function to find the candidate for Majority''' + +def findCandidate(A): + maj_index = 0 + count = 1 + for i in range(len(A)): + if A[maj_index] == A[i]: + count += 1 + else: + count -= 1 + if count == 0: + maj_index = i + count = 1 + return A[maj_index] + '''Function to check if the candidate occurs more than n/2 times''' + +def isMajority(A, cand): + count = 0 + for i in range(len(A)): + if A[i] == cand: + count += 1 + if count > len(A)/2: + return True + else: + return False + '''Function to print Majority Element''' + +def printMajority(A): + ''' Find the candidate for Majority''' + + cand = findCandidate(A) + ''' Print the candidate if it is Majority''' + + if isMajority(A, cand) == True: + print(cand) + else: + print(""No Majority Element"") + '''Driver code''' + +A = [1, 3, 3, 1, 2] + '''Function call''' + +printMajority(A)" +Reverse Level Order Traversal,"/*A recursive java program to print reverse level order traversal*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right; + } +} +class BinaryTree +{ + Node root;/* Function to print REVERSE level order traversal a tree*/ + + void reverseLevelOrder(Node node) + { + int h = height(node); + int i; + for (i = h; i >= 1; i--) + { + printGivenLevel(node, i); + } + }/* Print nodes at a given level */ + + void printGivenLevel(Node node, int level) + { + if (node == null) + return; + if (level == 1) + System.out.print(node.data + "" ""); + else if (level > 1) + { + printGivenLevel(node.left, level - 1); + printGivenLevel(node.right, level - 1); + } + } + /* Compute the ""height"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + + int height(Node node) + { + if (node == null) + return 0; + else + { + /* compute the height of each subtree */ + + int lheight = height(node.left); + int rheight = height(node.right); + /* use the larger one */ + + if (lheight > rheight) + return (lheight + 1); + else + return (rheight + 1); + } + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); +/* Let us create trees shown in above diagram*/ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println(""Level Order traversal of binary tree is : ""); + tree.reverseLevelOrder(tree.root); + } +}"," '''A recursive Python program to print REVERSE level order traversal''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to print reverse level order traversal''' + +def reverseLevelOrder(root): + h = height(root) + for i in reversed(range(1, h+1)): + printGivenLevel(root,i) + '''Print nodes at a given level''' + +def printGivenLevel(root, level): + if root is None: + return + if level ==1 : + print root.data, + elif level>1: + printGivenLevel(root.left, level-1) + printGivenLevel(root.right, level-1) + '''Compute the height of a tree-- the number of +nodes along the longest path from the root node +down to the farthest leaf node''' + +def height(node): + if node is None: + return 0 + else: + ''' Compute the height of each subtree''' + + lheight = height(node.left) + rheight = height(node.right) + ''' Use the larger one''' + + if lheight > rheight : + return lheight + 1 + else: + return rheight + 1 + '''Driver program to test above function''' ''' Let us create trees shown + in above diagram ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +print ""Level Order traversal of binary tree is"" +reverseLevelOrder(root)" +Lucky alive person in a circle | Code Solution to sword puzzle,"/*Java code to find the luckiest person*/ + +class GFG +{ + +/*Node structure*/ + +static class Node +{ + int data; + Node next; +}; + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.next = null; + return node; +} + +/*Function to find the luckiest person*/ + +static int alivesol(int Num) +{ + if (Num == 1) + return 1; + +/* Create a single node circular + linked list.*/ + + Node last = newNode(1); + last.next = last; + + for (int i = 2; i <= Num; i++) + { + Node temp = newNode(i); + temp.next = last.next; + last.next = temp; + last = temp; + } + +/* Starting from first soldier.*/ + + Node curr = last.next; + +/* condition for evaluating the existence + of single soldier who is not killed.*/ + + Node temp = new Node(); + while (curr.next != curr) + { + temp = curr; + curr = curr.next; + temp.next = curr.next; + +/* deleting soldier from the circular + list who is killed in the fight.*/ + + temp = temp.next; + curr = temp; + } + +/* Returning the Luckiest soldier who + remains alive.*/ + + int res = temp.data; + + return res; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + int N = 100; + System.out.println( alivesol(N) ); +} +} + + +"," '''Python3 code to find the luckiest person''' + + + '''Node structure''' + +class Node: + + def __init__(self, data): + self.data = data + self.next = None + +def newNode(data): + node = Node(data) + return node + + '''Function to find the luckiest person''' + +def alivesol( Num): + if (Num == 1): + return 1; + + ''' Create a single node circular + linked list.''' + + last = newNode(1); + last.next = last; + + for i in range(2, Num + 1): + temp = newNode(i); + temp.next = last.next; + last.next = temp; + last = temp; + + ''' Starting from first soldier.''' + + curr = last.next; + + ''' condition for evaluating the existence + of single soldier who is not killed.''' + + temp = None + + while (curr.next != curr): + temp = curr; + curr = curr.next; + temp.next = curr.next; + + ''' deleting soldier from the circular + list who is killed in the fight.''' + + del curr; + temp = temp.next; + curr = temp; + + ''' Returning the Luckiest soldier who + remains alive.''' + + res = temp.data; + del temp; + return res; + + '''Driver code''' + +if __name__=='__main__': + + N = 100; + print(alivesol(N)) + + +" +Find a peak element,"/*A Java program to find a peak +element using divide and conquer*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class PeakElement { +/* A binary search based function + that returns index of a peak element*/ + + static int findPeakUtil( + int arr[], int low, int high, int n) + { +/* Find index of middle element + (low + high)/2*/ + + int mid = low + (high - low) / 2; +/* Compare middle element with its + neighbours (if neighbours exist)*/ + + if ((mid == 0 || arr[mid - 1] <= arr[mid]) + && (mid == n - 1 || arr[mid + 1] <= arr[mid])) + return mid; +/* If middle element is not peak + and its left neighbor is + greater than it, then left half + must have a peak element*/ + + else if (mid > 0 && arr[mid - 1] > arr[mid]) + return findPeakUtil(arr, low, (mid - 1), n); +/* If middle element is not peak + and its right neighbor + is greater than it, then right + half must have a peak + element*/ + + else + return findPeakUtil( + arr, (mid + 1), high, n); + } +/* A wrapper over recursive function + findPeakUtil()*/ + + static int findPeak(int arr[], int n) + { + return findPeakUtil(arr, 0, n - 1, n); + } +/* Driver method*/ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 20, 4, 1, 0 }; + int n = arr.length; + System.out.println( + ""Index of a peak point is "" + findPeak(arr, n)); + } +}"," '''A python3 program to find a peak +element element using divide and conquer''' + '''A binary search based function +that returns index of a peak element''' + +def findPeakUtil(arr, low, high, n): + ''' Find index of middle element + (low + high)/2''' + + mid = low + (high - low)/2 + mid = int(mid) + ''' Compare middle element with its + neighbours (if neighbours exist)''' + + if ((mid == 0 or arr[mid - 1] <= arr[mid]) and + (mid == n - 1 or arr[mid + 1] <= arr[mid])): + return mid + ''' If middle element is not peak and + its left neighbour is greater + than it, then left half must + have a peak element''' + + elif (mid > 0 and arr[mid - 1] > arr[mid]): + return findPeakUtil(arr, low, (mid - 1), n) + ''' If middle element is not peak and + its right neighbour is greater + than it, then right half must + have a peak element''' + + else: + return findPeakUtil(arr, (mid + 1), high, n) + '''A wrapper over recursive +function findPeakUtil()''' + +def findPeak(arr, n): + return findPeakUtil(arr, 0, n - 1, n) + '''Driver code''' + +arr = [1, 3, 20, 4, 1, 0] +n = len(arr) +print(""Index of a peak point is"", findPeak(arr, n))" +Find four elements that sum to a given value | Set 1 (n^3 solution),"class FindFourElements +{ + + /* A naive solution to print all combination of 4 elements in A[] + with sum equal to X */ + + void findFourElements(int A[], int n, int X) + { +/* Fix the first element and find other three*/ + + for (int i = 0; i < n - 3; i++) + { +/* Fix the second element and find other two*/ + + for (int j = i + 1; j < n - 2; j++) + { +/* Fix the third element and find the fourth*/ + + for (int k = j + 1; k < n - 1; k++) + { +/* find the fourth*/ + + for (int l = k + 1; l < n; l++) + { + if (A[i] + A[j] + A[k] + A[l] == X) + System.out.print(A[i]+"" ""+A[j]+"" ""+A[k] + +"" ""+A[l]); + } + } + } + } + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + FindFourElements findfour = new FindFourElements(); + int A[] = {10, 20, 30, 40, 1, 2}; + int n = A.length; + int X = 91; + findfour.findFourElements(A, n, X); + } +} +"," '''A naive solution to print all combination +of 4 elements in A[] with sum equal to X''' + +def findFourElements(A, n, X): + + ''' Fix the first element and find + other three''' + + for i in range(0,n-3): + + ''' Fix the second element and + find other two''' + + for j in range(i+1,n-2): + + ''' Fix the third element + and find the fourth''' + + for k in range(j+1,n-1): + + ''' find the fourth''' + + for l in range(k+1,n): + + if A[i] + A[j] + A[k] + A[l] == X: + print (""%d, %d, %d, %d"" + %( A[i], A[j], A[k], A[l])) + + '''Driver program to test above function''' + +A = [10, 2, 3, 4, 5, 9, 7, 8] +n = len(A) +X = 23 +findFourElements (A, n, X) + + +" +Rotate a Linked List,"/*Java program to rotate +a linked list counter clock wise*/ + +import java.util.*; + +class GFG{ + +/* Link list node */ + +static class Node { + + int data; + Node next; +}; +static Node head = null; + +/*This function rotates a linked list +counter-clockwise and updates the +head. The function assumes that k is +smaller than size of linked list.*/ + +static void rotate( int k) +{ + if (k == 0) + return; + +/* Let us understand the below + code for example k = 4 and + list = 10.20.30.40.50.60.*/ + + Node current = head; + +/* Traverse till the end.*/ + + while (current.next != null) + current = current.next; + + current.next = head; + current = head; + +/* traverse the linked list to k-1 position which + will be last element for rotated array.*/ + + for (int i = 0; i < k - 1; i++) + current = current.next; + +/* update the head_ref and last element pointer to null*/ + + head = current.next; + current.next = null; +} + +/* UTILITY FUNCTIONS */ + +/* Function to push a node */ + +static void push(int new_data) +{ + + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list off the new node */ + + new_node.next = head; + + /* move the head to point to the new node */ + + head = new_node; +} + +/* Function to print linked list */ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.next; + } +} + +/* Driver code*/ + +public static void main(String[] args) +{ + /* Start with the empty list */ + + + +/* create a list 10.20.30.40.50.60*/ + + for (int i = 60; i > 0; i -= 10) + push( i); + + System.out.print(""Given linked list \n""); + printList(head); + rotate( 4); + + System.out.print(""\nRotated Linked list \n""); + printList(head); +} +} + + + +"," '''Python3 program to rotate +a linked list counter clock wise''' + + + '''Link list node''' + +class Node: + + def __init__(self): + + self.data = 0 + self.next = None + + '''This function rotates a linked list +counter-clockwise and updates the +head. The function assumes that k is +smaller than size of linked list.''' + +def rotate(head_ref, k): + + if (k == 0): + return + + ''' Let us understand the below + code for example k = 4 and + list = 10.20.30.40.50.60.''' + + current = head_ref + + ''' Traverse till the end.''' + + while (current.next != None): + current = current.next + + current.next = head_ref + current = head_ref + + ''' Traverse the linked list to k-1 + position which will be last element + for rotated array.''' + + for i in range(k - 1): + current = current.next + + ''' Update the head_ref and last + element pointer to None''' + + head_ref = current.next + current.next = None + return head_ref + + '''UTILITY FUNCTIONS''' + + + '''Function to push a node''' + +def push(head_ref, new_data): ''' Allocate node''' + + new_node = Node() + + ''' Put in the data''' + + new_node.data = new_data + + ''' Link the old list off + the new node''' + + new_node.next = (head_ref) + + ''' Move the head to point + to the new node''' + + (head_ref) = new_node + return head_ref + + '''Function to print linked list''' + +def printList(node): + + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Start with the empty list''' + + head = None + + ''' Create a list 10.20.30.40.50.60''' + + for i in range(60, 0, -10): + head = push(head, i) + + print(""Given linked list "") + printList(head) + head = rotate(head, 4) + + print(""\nRotated Linked list "") + printList(head) + + +" +Closest greater element for every array element from another array,"/*Java to find result from target array +for closest element*/ + +import java.util.*; + +class GFG +{ + +/* Function for printing resultant array*/ + + static void closestResult(Integer[] a, + int[] b, int n) + { + +/* change arr[] to Set*/ + + TreeSet vect = new TreeSet<>(Arrays.asList(a)); + +/* vector for result*/ + + Vector c = new Vector<>(); + +/* calculate resultant array*/ + + for (int i = 0; i < n; i++) + { + +/* check upper bound element*/ + + Integer up = vect.higher(b[i]); + +/* if no element found push -1*/ + + if (up == null) + c.add(-1); + +/* Else push the element*/ + + else +/*add to resultant*/ + +c.add(up); + } + + System.out.print(""Result = ""); + for (int i : c) + System.out.print(i + "" ""); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + Integer[] a = { 2, 5, 6, 1, 8, 9 }; + int[] b = { 2, 1, 0, 5, 4, 9 }; + int n = a.length; + + closestResult(a, b, n); + } +} + + +"," '''Python implementation to find result +from target array for closest element''' + + +import bisect + + '''Function for printing resultant array''' + +def closestResult(a, b, n): + + ''' sort list for ease''' + + a.sort() + + ''' list for result''' + + c = [] + + ''' calculate resultant array''' + + for i in range(n): + + ''' check location of upper bound element''' + + up = bisect.bisect_right(a, b[i]) + + ''' if no element found push -1''' + + if up == n: + c.append(-1) + + ''' else puch the element''' + + else: + '''add to resultant''' + + c.append(a[up]) + print(""Result = "", end = """") + for i in c: + print(i, end = "" "") + + + '''Driver code''' + +if __name__ == ""__main__"": + a = [2,5,6,1,8,9] + b = [2,1,0,5,4,9] + n = len(a) + closestResult(a, b, n) + + +" +Perfect Binary Tree Specific Level Order Traversal | Set 2,"/*Java program for special order traversal*/ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, +pointer to left child and +a pointer to right child */ + +static class Node +{ + int data; + Node left; + Node right; + /* Helper function that allocates + a new node with the given data and + null left and right pointers. */ + + Node(int value) + { + data = value; + left = null; + right = null; + } +}; +/* Given a perfect binary tree, +print its nodes in specific level order */ + +static void specific_level_order_traversal(Node root) +{ +/* for level order traversal*/ + + Queue q= new LinkedList<>(); +/* Stack to print reverse*/ + + Stack > s = new Stack>(); + q.add(root); + int sz; + while(q.size() > 0) + { +/* vector to store the level*/ + + Vector v = new Vector(); +/*considering size of the level*/ + +sz = q.size(); + for(int i = 0; i < sz; ++i) + { + Node temp = q.peek(); + q.remove(); +/* push data of the node of a + particular level to vector*/ + + v.add(temp.data); + if(temp.left != null) + q.add(temp.left); + if(temp.right != null) + q.add(temp.right); + } +/* push vector containing a level in Stack*/ + + s.push(v); + } +/* print the Stack*/ + + while(s.size() > 0) + { +/* Finally pop all Nodes from Stack + and prints them.*/ + + Vector v = s.peek(); + s.pop(); + for(int i = 0, j = v.size() - 1; i < j; ++i) + { + System.out.print(v.get(i) + "" "" + + v.get(j) + "" ""); + j--; + } + } +/* finally print root;*/ + + System.out.println(root.data); +} +/*Driver code*/ + +public static void main(String args[]) +{ + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); System.out.println(""Specific Level Order traversal"" + + "" of binary tree is""); + specific_level_order_traversal(root); +} +} + "," '''Python program for special order traversal''' + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Given a perfect binary tree, +print its nodes in specific level order''' + +def specific_level_order_traversal(root) : + ''' for level order traversal''' + + q = [] + ''' Stack to print reverse''' + + s = [] + q.append(root) + sz = 0 + while(len(q) > 0) : + ''' vector to store the level''' + + v = [] + '''considering size of the level''' + + sz = len(q) + i = 0 + while( i < sz) : + temp = q[0] + q.pop(0) + ''' push data of the node of a + particular level to vector''' + + v.append(temp.data) + if(temp.left != None) : + q.append(temp.left) + if(temp.right != None) : + q.append(temp.right) + i = i + 1 + ''' push vector containing a level in Stack''' + + s.append(v) + ''' print the Stack''' + + while(len(s) > 0) : + ''' Finally pop all Nodes from Stack + and prints them.''' + + v = s[-1] + s.pop() + i = 0 + j = len(v) - 1 + while( i < j) : + print(v[i] , "" "" , v[j] ,end= "" "") + j = j - 1 + i = i + 1 + ''' finally print root''' + + print(root.data) + '''Driver code''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +print(""Specific Level Order traversal of binary tree is"") +specific_level_order_traversal(root)" +"Design a data structure that supports insert, delete, search and getRandom in constant time","/* Java program to design a data structure that support following operations + in Theta(n) time + a) Insert + b) Delete + c) Search + d) getRandom */ + +import java.util.*; +/*class to represent the required data structure*/ + +class MyDS +{ +/* Constructor (creates arr[] and hash)*/ + + public MyDS() + { + arr = new ArrayList(); + hash = new HashMap(); + } +/*A resizable array*/ + +ArrayList arr; +/* A hash where keys are array elements and values are + indexes in arr[]*/ + + HashMap hash; +/* A Theta(1) function to add an element to MyDS + data structure*/ + + void add(int x) + { +/* If element is already present, then nothing to do*/ + + if (hash.get(x) != null) + return; +/* Else put element at the end of arr[]*/ + + int s = arr.size(); + arr.add(x); +/* And put in hash also*/ + + hash.put(x, s); + } +/* A Theta(1) function to remove an element from MyDS + data structure*/ + + void remove(int x) + { +/* Check if element is present*/ + + Integer index = hash.get(x); + if (index == null) + return; +/* If present, then remove element from hash*/ + + hash.remove(x); +/* Swap element with last element so that remove from + arr[] can be done in O(1) time*/ + + int size = arr.size(); + Integer last = arr.get(size-1); + Collections.swap(arr, index, size-1); +/* Remove last element (This is O(1))*/ + + arr.remove(size-1); +/* Update hash table for new index of last element*/ + + hash.put(last, index); + } +/* Returns a random element from MyDS*/ + + int getRandom() + { +/* Find a random index from 0 to size - 1 +Choose a different seed*/ + +Random rand = new Random(); + int index = rand.nextInt(arr.size()); +/* Return element at randomly picked index*/ + + return arr.get(index); + } +/* Returns index of element if element is present, otherwise null*/ + + Integer search(int x) + { + return hash.get(x); + } +} +/*Driver class*/ + +class Main +{ + public static void main (String[] args) + { + MyDS ds = new MyDS(); + ds.add(10); + ds.add(20); + ds.add(30); + ds.add(40); + System.out.println(ds.search(30)); + ds.remove(20); + ds.add(50); + System.out.println(ds.search(50)); + System.out.println(ds.getRandom()); + } +}"," ''' +Python program to design a DS that +supports following operations +in Theta(n) time: +a) Insert +b) Delete +c) Search +d) getRandom + ''' + +import random + '''Class to represent the required +data structure''' + +class MyDS: + ''' Constructor (creates a list and a hash)''' + + def __init__(self): + ''' A resizable array''' + + self.arr = [] + ''' A hash where keys are lists elements + and values are indexes of the list''' + + self.hashd = {} + ''' A Theta(1) function to add an element + to MyDS data structure''' + + def add(self, x): + ''' If element is already present, + then nothing has to be done''' + + if x in self.hashd: + return + ''' Else put element at + the end of the list''' + + s = len(self.arr) + self.arr.append(x) + ''' Also put it into hash''' + + self.hashd[x] = s + ''' A Theta(1) function to remove an element + from MyDS data structure''' + + def remove(self, x): + ''' Check if element is present''' + + index = self.hashd.get(x, None) + if index == None: + return + ''' If present, then remove + element from hash''' + + del self.hashd[x] + ''' Swap element with last element + so that removal from the list + can be done in O(1) time''' + + size = len(self.arr) + last = self.arr[size - 1] + self.arr[index], \ + self.arr[size - 1] = self.arr[size - 1], \ + self.arr[index] + ''' Remove last element (This is O(1))''' + + del self.arr[-1] + ''' Update hash table for + new index of last element''' + + self.hashd[last] = index + ''' Returns a random element from MyDS''' + + def getRandom(self): + ''' Find a random index from 0 to size - 1''' + + index = random.randrange(0, len(self.arr)) + ''' Return element at randomly picked index''' + + return self.arr[index] + ''' Returns index of element + if element is present, + otherwise none''' + + def search(self, x): + return self.hashd.get(x, None) + '''Driver Code''' + +if __name__==""__main__"": + ds = MyDS() + ds.add(10) + ds.add(20) + ds.add(30) + ds.add(40) + print(ds.search(30)) + ds.remove(20) + ds.add(50) + print(ds.search(50)) + print(ds.getRandom())" +Find whether a given number is a power of 4 or not,"/*Java program to check +if given number is +power of 4 or not*/ + +import java.util.*; +class GFG{ +static double logn(int n, + int r) +{ + return Math.log(n) / + Math.log(r); +} +static boolean isPowerOfFour(int n) +{ +/* 0 is not considered + as a power of 4*/ + + if (n == 0) + return false; + return Math.floor(logn(n, 4)) == + Math.ceil(logn(n, 4)); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int test_no = 64; + if (isPowerOfFour(test_no)) + System.out.print(test_no + + "" is a power of 4""); + else + System.out.print(test_no + + "" is not a power of 4""); +} +}"," '''Python3 program to check +if given number is +power of 4 or not''' + +import math +def logn(n, r): + return math.log(n) / math.log(r) +def isPowerOfFour(n): + ''' 0 is not considered + as a power of 4''' + + if (n == 0): + return False + return (math.floor(logn(n, 4)) == + math.ceil(logn(n, 4))) + '''Driver code''' + +if __name__ == '__main__': + test_no = 64 + if (isPowerOfFour(test_no)): + print(test_no, "" is a power of 4"") + else: + print(test_no, "" is not a power of 4"")" +Rearrange a Linked List in Zig-Zag fashion,"/*Java program for the above approach*/ + +import java.io.*; + +/*Node class*/ + +class Node { + int data; + Node next; + Node(int data) { this.data = data; } +} + +public class GFG { + + private Node head; + +/* Print Linked List*/ + + public void printLL() + { + Node t = head; + while (t != null) { + System.out.print(t.data + "" ->""); + t = t.next; + } + System.out.println(); + } + +/* Swap both nodes*/ + + public void swap(Node a, Node b) + { + if (a == null || b == null) + return; + int temp = a.data; + a.data = b.data; + b.data = temp; + } + +/* Rearrange the linked list + in zig zag way*/ + + public Node zigZag(Node node, int flag) + { + if (node == null || node.next == null) { + return node; + } + if (flag == 0) { + if (node.data > node.next.data) { + swap(node, node.next); + } + return zigZag(node.next, 1); + } + else { + if (node.data < node.next.data) { + swap(node, node.next); + } + return zigZag(node.next, 0); + } + } + +/* Driver Code*/ + + public static void main(String[] args) + { + GFG lobj = new GFG(); + lobj.head = new Node(11); + lobj.head.next = new Node(15); + lobj.head.next.next = new Node(20); + lobj.head.next.next.next = new Node(5); + lobj.head.next.next.next.next = new Node(10); + lobj.printLL(); + +/* 0 means the current element + should be smaller than the next*/ + + int flag = 0; + lobj.zigZag(lobj.head, flag); + System.out.println(""LL in zig zag fashion : ""); + lobj.printLL(); + } +} +", +Karp's minimum mean (or average) weight cycle algorithm,"/*Java program to find minimum average +weight of a cycle in connected and +directed graph.*/ + +import java.io.*; +import java.util.*; +class GFG +{ +static int V = 4; +/*a struct to represent edges*/ + +static class Edge +{ + int from, weight; + Edge(int from, int weight) + { + this.from = from; + this.weight = weight; + } +} +/*vector to store edges +@SuppressWarnings(""unchecked"")*/ + +static Vector[] edges = new Vector[V]; +static +{ + for (int i = 0; i < V; i++) + edges[i] = new Vector<>(); +} +static void addedge(int u, int v, int w) +{ + edges[v].add(new Edge(u, w)); +} +/*calculates the shortest path*/ + +static void shortestpath(int[][] dp) +{ +/* initializing all distances as -1*/ + + for (int i = 0; i <= V; i++) + for (int j = 0; j < V; j++) + dp[i][j] = -1; +/* shortest distance from first vertex + to in tself consisting of 0 edges*/ + + dp[0][0] = 0; +/* filling up the dp table*/ + + for (int i = 1; i <= V; i++) + { + for (int j = 0; j < V; j++) + { + for (int k = 0; k < edges[j].size(); k++) + { + if (dp[i - 1][edges[j].elementAt(k).from] != -1) + { + int curr_wt = dp[i - 1][edges[j].elementAt(k).from] + + edges[j].elementAt(k).weight; + if (dp[i][j] == -1) + dp[i][j] = curr_wt; + else + dp[i][j] = Math.min(dp[i][j], curr_wt); + } + } + } + } +} +/*Returns minimum value of average weight +of a cycle in graph.*/ + +static double minAvgWeight() +{ + int[][] dp = new int[V + 1][V]; + shortestpath(dp); +/* array to store the avg values*/ + + double[] avg = new double[V]; + for (int i = 0; i < V; i++) + avg[i] = -1; +/* Compute average values for all vertices using + weights of shortest paths store in dp.*/ + + for (int i = 0; i < V; i++) + { + if (dp[V][i] != -1) + { + for (int j = 0; j < V; j++) + if (dp[j][i] != -1) + avg[i] = Math.max(avg[i], + ((double) dp[V][i] - + dp[j][i]) / (V - j)); + } + } +/* Find minimum value in avg[]*/ + + double result = avg[0]; + for (int i = 0; i < V; i++) + if (avg[i] != -1 && avg[i] < result) + result = avg[i]; + return result; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + addedge(0, 1, 1); + addedge(0, 2, 10); + addedge(1, 2, 3); + addedge(2, 3, 2); + addedge(3, 1, 0); + addedge(3, 0, 8); + System.out.printf(""%.5f"", minAvgWeight()); +} +}"," '''Python3 program to find minimum +average weight of a cycle in +connected and directed graph.''' '''a struct to represent edges''' + +class edge: + def __init__(self, u, w): + self.From = u + self.weight = w +def addedge(u, v, w): + edges[v].append(edge(u, w)) + '''vector to store edges +@SuppressWarnings(""unchecked"")''' + +V = 4 +edges = [[] for i in range(V)] '''calculates the shortest path''' + +def shortestpath(dp): + ''' initializing all distances as -1''' + + for i in range(V + 1): + for j in range(V): + dp[i][j] = -1 + ''' shortest distance From first vertex + to in tself consisting of 0 edges''' + + dp[0][0] = 0 + ''' filling up the dp table''' + + for i in range(1, V + 1): + for j in range(V): + for k in range(len(edges[j])): + if (dp[i - 1][edges[j][k].From] != -1): + curr_wt = (dp[i - 1][edges[j][k].From] + + edges[j][k].weight) + if (dp[i][j] == -1): + dp[i][j] = curr_wt + else: + dp[i][j] = min(dp[i][j], curr_wt) + '''Returns minimum value of average +weight of a cycle in graph.''' + +def minAvgWeight(): + dp = [[None] * V for i in range(V + 1)] + shortestpath(dp) + ''' array to store the avg values''' + + avg = [-1] * V + ''' Compute average values for all + vertices using weights of + shortest paths store in dp.''' + + for i in range(V): + if (dp[V][i] != -1): + for j in range(V): + if (dp[j][i] != -1): + avg[i] = max(avg[i], (dp[V][i] - + dp[j][i]) / (V - j)) + ''' Find minimum value in avg[]''' + + result = avg[0] + for i in range(V): + if (avg[i] != -1 and avg[i] < result): + result = avg[i] + return result + '''Driver Code''' + + +addedge(0, 1, 1) +addedge(0, 2, 10) +addedge(1, 2, 3) +addedge(2, 3, 2) +addedge(3, 1, 0) +addedge(3, 0, 8) +print(minAvgWeight())" +Minimum increment by k operations to make all elements equal,"/*Program to make all array equal*/ + +import java.io.*; +import java.util.Arrays; +class GFG { +/* function for calculating min operations*/ + + static int minOps(int arr[], int n, int k) + { +/* max elements of array*/ + + Arrays.sort(arr); + int max = arr[arr.length - 1]; + int res = 0; +/* iterate for all elements*/ + + for (int i = 0; i < n; i++) { +/* check if element can make equal to + max or not if not then return -1*/ + + if ((max - arr[i]) % k != 0) + return -1; +/* else update res for required operations*/ + + else + res += (max - arr[i]) / k; + } +/* return result*/ + + return res; + } +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = { 21, 33, 9, 45, 63 }; + int n = arr.length; + int k = 6; + System.out.println(minOps(arr, n, k)); + } +}"," '''Python3 Program to make all array equal + ''' '''function for calculating min operations''' + +def minOps(arr, n, k): + ''' max elements of array''' + + max1 = max(arr) + res = 0 + ''' iterate for all elements''' + + for i in range(0, n): + ''' check if element can make equal to + max or not if not then return -1''' + + if ((max1 - arr[i]) % k != 0): + return -1 + ''' else update res fo + required operations''' + + else: + res += (max1 - arr[i]) / k + ''' return result''' + + return int(res) + '''driver program''' + +arr = [21, 33, 9, 45, 63] +n = len(arr) +k = 6 +print(minOps(arr, n, k))" +"Given a Boolean Matrix, find k such that all elements in k'th row are 0 and k'th column are 1.","/*Java program to find i such that all entries in i'th row are 0 +and all entries in i't column are 1*/ + +class GFG { + static int n = 5; + static int find(boolean arr[][]) { +/* Start from top-most rightmost corner + (We could start from other corners also)*/ + + int i = 0, j = n - 1; +/* Initialize result*/ + + int res = -1; +/* Find the index (This loop runs at most 2n times, we either + increment row number or decrement column number)*/ + + while (i < n && j >= 0) { +/* If current element is false, then this row may be a solution*/ + + if (arr[i][j] == false) { +/* Check for all elements in this row*/ + + while (j >= 0 && (arr[i][j] == false || i == j)) { + j--; + } +/* If all values are false, then store this row as result*/ + + if (j == -1) { + res = i; + break; +/*We reach here if we found a 1 in current row, so this row cannot be a solution, increment row number*/ + +} + else { + i++; + }/*If current element is 1*/ + +} else + { +/* Check for all elements in this column*/ + + while (i < n && (arr[i][j] == true || i == j)) { + i++; + } +/* If all elements are 1*/ + + if (i == n) { + res = j; + break; +/*We reach here if we found a 0 in current column, so this column cannot be a solution, increment column number*/ + +} + else { + j--; + } + } + }/* If we could not find result in above loop, then result doesn't exist*/ + + if (res == -1) { + return res; + } +/* Check if above computed res is valid*/ + + for (int k = 0; k < n; k++) { + if (res != k && arr[k][res] != true) { + return -1; + } + } + for (int l = 0; l < n; l++) { + if (res != l && arr[res][l] != false) { + return -1; + } + } + return res; + } + /* Driver program to test above functions */ + + public static void main(String[] args) { + boolean mat[][] = {{false, false, true, true, false}, + {false, false, false, true, false}, + {true, true, true, true, false}, + {false, false, false, false, false}, + {true, true, true, true, true}}; + System.out.println(find(mat)); + } +}"," ''' Python program to find k such that all elements in k'th row + are 0 and k'th column are 1''' + +def find(arr): + n = len(arr) ''' start from top right-most corner ''' + + i = 0 + j = n - 1 + ''' initialise result''' + + res = -1 + ''' find the index (This loop runs at most 2n times, we + either increment row number or decrement column number)''' + + while i < n and j >= 0: + ''' if the current element is 0, then this row may be a solution''' + + if arr[i][j] == 0: + ''' check for all the elements in this row''' + + while j >= 0 and (arr[i][j] == 0 or i == j): + j -= 1 + ''' if all values are 0, update result as row number ''' + + if j == -1: + res = i + break + ''' if found a 1 in current row, the row can't be a + solution, increment row number''' + + else: i += 1 + ''' if the current element is 1''' + + else: + ''' check for all the elements in this column''' + + while i < n and (arr[i][j] == 1 or i == j): + i +=1 + ''' if all elements are 1, update result as col number''' + + if i == n: + res = j + break + ''' if found a 0 in current column, the column can't be a + solution, decrement column number''' + + else: j -= 1 + ''' if we couldn't find result in above loop, result doesn't exist''' + + if res == -1: + return res + ''' check if the above computed res value is valid''' + + for i in range(0, n): + if res != i and arr[i][res] != 1: + return -1 + for j in range(0, j): + if res != j and arr[res][j] != 0: + return -1; + return res; + '''test find(arr) function''' + +arr = [ [0,0,1,1,0], + [0,0,0,1,0], + [1,1,1,1,0], + [0,0,0,0,0], + [1,1,1,1,1] ] +print find(arr)" +Difference between highest and least frequencies in an array,"/*JAVA Code for Difference between +highest and least frequencies +in an array*/ + +import java.util.*; +class GFG { + static int findDiff(int arr[], int n) + { +/* sort the array*/ + + Arrays.sort(arr); + int count = 0, max_count = 0, + min_count = n; + for (int i = 0; i < (n - 1); i++) { +/* checking consecutive elements*/ + + if (arr[i] == arr[i + 1]) { + count += 1; + continue; + } + else { + max_count = Math.max(max_count, + count); + min_count = Math.min(min_count, + count); + count = 0; + } + } + return (max_count - min_count); + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int arr[] = { 7, 8, 4, 5, 4, 1, + 1, 7, 7, 2, 5 }; + int n = arr.length; + System.out.println(findDiff(arr, n)); + } +}"," '''Python3 code to find the difference +between highest nd least frequencies''' + +def findDiff(arr, n): + ''' sort the array''' + + arr.sort() + count = 0; max_count = 0; min_count = n + for i in range(0, (n-1)): + ''' checking consecutive elements''' + + if arr[i] == arr[i + 1]: + count += 1 + continue + else: + max_count = max(max_count, count) + min_count = min(min_count, count) + count = 0 + return max_count - min_count + '''Driver Code''' + +arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ] +n = len(arr) +print (findDiff(arr, n))" +Replace every element with the greatest element on right side,"/*Java Program to replace every element with the +greatest element on right side*/ + +import java.io.*; + +class NextGreatest +{ + /* Function to replace every element with the + next greatest element */ + + static void nextGreatest(int arr[]) + { + int size = arr.length; + +/* Initialize the next greatest element*/ + + int max_from_right = arr[size-1]; + +/* The next greatest element for the rightmost + element is always -1*/ + + arr[size-1] = -1; + +/* Replace all other elements with the next greatest*/ + + for (int i = size-2; i >= 0; i--) + { +/* Store the current element (needed later for + updating the next greatest element)*/ + + int temp = arr[i]; + +/* Replace current element with the next greatest*/ + + arr[i] = max_from_right; + +/* Update the greatest element, if needed*/ + + if(max_from_right < temp) + max_from_right = temp; + } + } + + /* A utility Function that prints an array */ + + static void printArray(int arr[]) + { + for (int i=0; i < arr.length; i++) + System.out.print(arr[i]+"" ""); + } + + + +/*Driver Code*/ + + public static void main (String[] args) + { + int arr[] = {16, 17, 4, 3, 5, 2}; + nextGreatest (arr); + System.out.println(""The modified array:""); + printArray (arr); + } +}"," '''Python Program to replace every element with the +greatest element on right side''' + + + '''Function to replace every element with the next greatest +element''' + +def nextGreatest(arr): + + size = len(arr) + + ''' Initialize the next greatest element''' + + max_from_right = arr[size-1] + + ''' The next greatest element for the rightmost element + is always -1''' + + arr[size-1] = -1 + + ''' Replace all other elements with the next greatest''' + + for i in range(size-2,-1,-1): + + ''' Store the current element (needed later for updating + the next greatest element)''' + + temp = arr[i] + + ''' Replace current element with the next greatest''' + + arr[i]=max_from_right + + ''' Update the greatest element, if needed''' + + if max_from_right< temp: + max_from_right=temp + + '''Utility function to print an array''' + +def printArray(arr): + for i in range(0,len(arr)): + print arr[i], + + '''Driver function to test above function''' + +arr = [16, 17, 4, 3, 5, 2] +nextGreatest(arr) +print ""Modified array is"" +printArray(arr) + +" +Queries for counts of array elements with values in given range,"/*Efficient C++ program to count number +of elements with values in given range.*/ + +import java.io.*; +import java.util.Arrays; +class GFG +{ +/* function to find first index >= x*/ + + static int lowerIndex(int arr[], int n, int x) + { + int l = 0, h = n - 1; + while (l <= h) + { + int mid = (l + h) / 2; + if (arr[mid] >= x) + h = mid - 1; + else + l = mid + 1; + } + return l; + } +/* function to find last index <= y*/ + + static int upperIndex(int arr[], int n, int y) + { + int l = 0, h = n - 1; + while (l <= h) + { + int mid = (l + h) / 2; + if (arr[mid] <= y) + l = mid + 1; + else + h = mid - 1; + } + return h; + } +/* function to count elements within given range*/ + + static int countInRange(int arr[], int n, int x, int y) + { +/* initialize result*/ + + int count = 0; + count = upperIndex(arr, n, y) - + lowerIndex(arr, n, x) + 1; + return count; + } +/* Driver function*/ + + public static void main (String[] args) + { + int arr[] = { 1, 4, 4, 9, 10, 3 }; + int n = arr.length; +/* Preprocess array*/ + + Arrays.sort(arr); +/* Answer queries*/ + + int i = 1, j = 4; + System.out.println( countInRange(arr, n, i, j)); ; + i = 9; + j = 12; + System.out.println( countInRange(arr, n, i, j)); + } +}"," '''function to find first index >= x''' + +def lowerIndex(arr, n, x): + l = 0 + h = n-1 + while (l <= h): + mid = int((l + h)/2) + if (arr[mid] >= x): + h = mid - 1 + else: + l = mid + 1 + return l + '''function to find last index <= x''' + +def upperIndex(arr, n, x): + l = 0 + h = n-1 + while (l <= h): + mid = int((l + h)/2) + if (arr[mid] <= x): + l = mid + 1 + else: + h = mid - 1 + return h + '''function to count elements within given range''' + +def countInRange(arr, n, x, y): + ''' initialize result''' + + count = 0; + count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; + return count + '''driver function''' + +arr = [1, 3, 4, 9, 10, 3] +n = len(arr) '''Preprocess array''' + +arr.sort() + + '''Answer queries''' + +i = 1 +j = 4 +print(countInRange(arr, n, i, j)) +i = 9 +j = 12 +print(countInRange(arr, n, i, j))" +Maximum product of two non-intersecting paths in a tree,"/*Java program to find maximum product +of two non-intersecting paths*/ + +import java.util.*; +class GFG{ +static int curMax; +/*Returns maximum length path in +subtree rooted at u after +removing edge connecting u and v*/ + +static int dfs(Vector g[], + int u, int v) +{ +/* To find lengths of first and + second maximum in subtrees. + currMax is to store overall + maximum.*/ + + int max1 = 0, max2 = 0, total = 0; +/* Loop through all neighbors of u*/ + + for(int i = 0; i < g[u].size(); i++) + { +/* If neighbor is v, then skip it*/ + + if (g[u].get(i) == v) + continue; +/* Call recursively with current + neighbor as root*/ + + total = Math.max(total, dfs( + g, g[u].get(i), u)); +/* Get max from one side and update*/ + + if (curMax > max1) + { + max2 = max1; + max1 = curMax; + } + else + max2 = Math.max(max2, curMax); + } +/* Store total length by adding max + and second max*/ + + total = Math.max(total, max1 + max2); +/* Update current max by adding 1, i.e. + current node is included*/ + + curMax = max1 + 1; + return total; +} +/*Method returns maximum product of +length of two non-intersecting paths*/ + +static int maxProductOfTwoPaths(Vector g[], + int N) +{ + int res = Integer.MIN_VALUE; + int path1, path2; +/* One by one removing all edges and + calling dfs on both subtrees*/ + + for(int i = 1; i < N + 2; i++) + { + for(int j = 0; j < g[i].size(); j++) + { +/* Calling dfs on subtree rooted at + g[i][j], excluding edge from g[i][j] + to i.*/ + + curMax = 0; + path1 = dfs(g, g[i].get(j), i); +/* Calling dfs on subtree rooted at + i, edge from i to g[i][j]*/ + + curMax = 0; + path2 = dfs(g,i, g[i].get(j)); + res = Math.max(res, path1 * path2); + } + } + return res; +} +/*Utility function to add an +undirected edge (u,v)*/ + +static void addEdge(Vector g[], + int u, int v) +{ + g[u].add(v); + g[v].add(u); +} +/* Driver code*/ + +public static void main(String[] args) +{ + int edges[][] = { { 1, 8 }, { 2, 6 }, + { 3, 1 }, { 5, 3 }, + { 7, 8 }, { 8, 4 }, + { 8, 6 } }; + int N = edges.length; +/* There are N edges, so +1 for nodes + and +1 for 1-based indexing*/ + + @SuppressWarnings(""unchecked"") + Vector []g = new Vector[N + 2]; + for(int i = 0; i < g.length; i++) + g[i] = new Vector(); + for(int i = 0; i < N; i++) + addEdge(g, edges[i][0], edges[i][1]); + System.out.print(maxProductOfTwoPaths(g, N) + ""\n""); +} +}"," '''Python3 program to find maximum product of two +non-intersecting paths''' + + '''Returns maximum length path in subtree rooted +at u after removing edge connecting u and v''' + +def dfs(g, curMax, u, v): ''' To find lengths of first and second maximum + in subtrees. currMax is to store overall + maximum.''' + + max1 = 0 + max2 = 0 + total = 0 + ''' loop through all neighbors of u''' + + for i in range(len(g[u])): + ''' if neighbor is v, then skip it''' + + if (g[u][i] == v): + continue + ''' call recursively with current neighbor as root''' + + total = max(total, dfs(g, curMax, g[u][i], u)) + ''' get max from one side and update''' + + if (curMax[0] > max1): + max2 = max1 + max1 = curMax[0] + else: + max2 = max(max2, curMax[0]) + ''' store total length by adding max + and second max''' + + total = max(total, max1 + max2) + ''' update current max by adding 1, i.e. + current node is included''' + + curMax[0] = max1 + 1 + return total + '''method returns maximum product of length of +two non-intersecting paths''' + +def maxProductOfTwoPaths(g, N): + res = -999999999999 + path1, path2 = None, None + ''' one by one removing all edges and calling + dfs on both subtrees''' + + for i in range(N): + for j in range(len(g[i])): + ''' calling dfs on subtree rooted at + g[i][j], excluding edge from g[i][j] + to i.''' + + curMax = [0] + path1 = dfs(g, curMax, g[i][j], i) + ''' calling dfs on subtree rooted at + i, edge from i to g[i][j]''' + + curMax = [0] + path2 = dfs(g, curMax, i, g[i][j]) + res = max(res, path1 * path2) + return res + '''Utility function to add an undirected edge (u,v)''' + +def addEdge(g, u, v): + g[u].append(v) + g[v].append(u) + '''Driver code ''' + +if __name__ == '__main__': + edges = [[1, 8], [2, 6], [3, 1], [5, 3], [7, 8], [8, 4], [8, 6]] + N = len(edges) + ''' there are N edges, so +1 for nodes and +1 + for 1-based indexing''' + + g = [[] for i in range(N + 2)] + for i in range(N): + addEdge(g, edges[i][0], edges[i][1]) + print(maxProductOfTwoPaths(g, N))" +Count subarrays having total distinct elements same as original array,"/*Java program Count total number of sub-arrays +having total distinct elements same as that +original array.*/ + +import java.util.HashMap; +class Test +{ +/* Method to calculate distinct sub-array*/ + + static int countDistictSubarray(int arr[], int n) + { +/* Count distinct elements in whole array*/ + + HashMap vis = new HashMap(){ + @Override + public Integer get(Object key) { + if(!containsKey(key)) + return 0; + return super.get(key); + } + }; + for (int i = 0; i < n; ++i) + vis.put(arr[i], 1); + int k = vis.size(); +/* Reset the container by removing all elements*/ + + vis.clear(); +/* Use sliding window concept to find + count of subarrays having k distinct + elements.*/ + + int ans = 0, right = 0, window = 0; + for (int left = 0; left < n; ++left) + { + while (right < n && window < k) + { + vis.put(arr[right], vis.get(arr[right]) + 1); + if (vis.get(arr[right])== 1) + ++window; + ++right; + } +/* If window size equals to array distinct + element size, then update answer*/ + + if (window == k) + ans += (n - right + 1); +/* Decrease the frequency of previous element + for next sliding window*/ + + vis.put(arr[left], vis.get(arr[left]) - 1); +/* If frequency is zero then decrease the + window size*/ + + if (vis.get(arr[left]) == 0) + --window; + } + return ans; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = {2, 1, 3, 2, 3}; + System.out.println(countDistictSubarray(arr, arr.length)); + } +}"," '''Python3 program Count total number of +sub-arrays having total distinct elements +same as that original array. + ''' '''Function to calculate distinct sub-array''' + +def countDistictSubarray(arr, n): + ''' Count distinct elements in whole array''' + + vis = dict() + for i in range(n): + vis[arr[i]] = 1 + k = len(vis) + ''' Reset the container by removing + all elements''' + + vid = dict() + ''' Use sliding window concept to find + count of subarrays having k distinct + elements.''' + + ans = 0 + right = 0 + window = 0 + for left in range(n): + while (right < n and window < k): + if arr[right] in vid.keys(): + vid[ arr[right] ] += 1 + else: + vid[ arr[right] ] = 1 + if (vid[ arr[right] ] == 1): + window += 1 + right += 1 + ''' If window size equals to array distinct + element size, then update answer''' + + if (window == k): + ans += (n - right + 1) + ''' Decrease the frequency of previous + element for next sliding window''' + + vid[ arr[left] ] -= 1 + ''' If frequency is zero then decrease + the window size''' + + if (vid[ arr[left] ] == 0): + window -= 1 + return ans + '''Driver code''' + +arr = [2, 1, 3, 2, 3] +n = len(arr) +print(countDistictSubarray(arr, n))" +Modify contents of Linked List,"/*Java implementation to modify the contents +of the linked list*/ + +class GFG +{ +/* Linked list node */ + +static class Node +{ + int data; + Node next; +}; +/* Function to insert a node at the beginning +of the linked list */ + +static Node push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node =new Node(); + /* put in the data */ + + new_node.data = new_data; + /* link the old list at the end + of the new node */ + + new_node.next = head_ref; + /* move the head to point to the new node */ + + head_ref = new_node; + return head_ref; +} +static Node front,back; +/* Split the nodes of the given list +into front and back halves, +and return the two lists +using the reference parameters. +Uses the fast/slow pointer strategy. */ + +static void frontAndBackSplit( Node head) +{ + Node slow, fast; + slow = head; + fast = head.next; + /* Advance 'fast' two nodes, and + advance 'slow' one node */ + + while (fast != null) + { + fast = fast.next; + if (fast != null) + { + slow = slow.next; + fast = fast.next; + } + } + /* 'slow' is before the midpoint in the list, + so split it in two at that point. */ + + front = head; + back = slow.next; + slow.next = null; +} +/* Function to reverse the linked list */ + +static Node reverseList( Node head_ref) +{ + 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; + return head_ref; +} +/*perfrom the required subtraction operation +on the 1st half of the linked list*/ + +static void modifyTheContentsOf1stHalf() +{ + Node front1 = front, back1 = back; +/* traversing both the lists simultaneously*/ + + while (back1 != null) + { +/* subtraction operation and node data + modification*/ + + front1.data = front1.data - back1.data; + front1 = front1.next; + back1 = back1.next; + } +} +/*function to concatenate the 2nd(back) list +at the end of the 1st(front) list and +returns the head of the new list*/ + +static Node concatFrontAndBackList(Node front, + Node back) +{ + Node head = front; + if(front == null)return back; + while (front.next != null) + front = front.next; + front.next = back; + return head; +} +/*function to modify the contents of the linked list*/ + +static Node modifyTheList( Node head) +{ +/* if list is empty or contains only single node*/ + + if (head == null || head.next == null) + return head; + front = null; back = null; +/* split the list into two halves + front and back lists*/ + + frontAndBackSplit(head); +/* reverse the 2nd(back) list*/ + + back = reverseList(back); +/* modify the contents of 1st half*/ + + modifyTheContentsOf1stHalf(); +/* agains reverse the 2nd(back) list*/ + + back = reverseList(back); +/* concatenating the 2nd list back to the + end of the 1st list*/ + + head = concatFrontAndBackList(front, back); +/* pointer to the modified list*/ + + return head; +} +/*function to print the linked list*/ + +static void printList( Node head) +{ + if (head == null) + return; + while (head.next != null) + { + System.out.print(head.data + "" -> ""); + head = head.next; + } + System.out.println(head.data ); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; +/* creating the linked list*/ + + head = push(head, 10); + head = push(head, 7); + head = push(head, 12); + head = push(head, 8); + head = push(head, 9); + head = push(head, 2); +/* modify the linked list*/ + + head = modifyTheList(head); +/* print the modified linked list*/ + + System.out.println( ""Modified List:"" ); + printList(head); +} +}"," '''Python3 implementation to modify the contents +of the linked list''' + + '''Linked list node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None '''Function to insert a node at the beginning +of the linked list''' + +def push(head_ref, new_data): + ''' allocate node''' + + new_node =Node(0) + ''' put in the data''' + + new_node.data = new_data + ''' link the old list at the end + of the new node''' + + new_node.next = head_ref + ''' move the head to point to the new node''' + + head_ref = new_node + return head_ref +front = None +back = None + '''Split the nodes of the given list +into front and back halves, +and return the two lists +using the reference parameters. +Uses the fast/slow pointer strategy.''' + +def frontAndBackSplit( head): + global front + global back + slow = None + fast = None + slow = head + fast = head.next + ''' Advance 'fast' two nodes, and + advance 'slow' one node''' + + while (fast != None): + fast = fast.next + if (fast != None): + slow = slow.next + fast = fast.next + ''' 'slow' is before the midpoint in the list, + so split it in two at that point.''' + + front = head + back = slow.next + slow.next = None + return head + '''Function to reverse the linked list''' + +def reverseList( head_ref): + current = None + prev = None + next = None + current = head_ref + prev = None + while (current != None): + next = current.next + current.next = prev + prev = current + current = next + head_ref = prev + return head_ref + '''perfrom the required subtraction operation +on the 1st half of the linked list''' + +def modifyTheContentsOf1stHalf(): + global front + global back + front1 = front + back1 = back + ''' traversing both the lists simultaneously''' + + while (back1 != None): + ''' subtraction operation and node data + modification''' + + front1.data = front1.data - back1.data + front1 = front1.next + back1 = back1.next + '''function to concatenate the 2nd(back) list +at the end of the 1st(front) list and +returns the head of the new list''' + +def concatFrontAndBackList( front, back): + head = front + if(front == None): + return back + while (front.next != None): + front = front.next + front.next = back + return head + '''function to modify the contents of the linked list''' + +def modifyTheList( head): + global front + global back + ''' if list is empty or contains only single node''' + + if (head == None or head.next == None): + return head + front = None + back = None + ''' split the list into two halves + front and back lists''' + + frontAndBackSplit(head) + ''' reverse the 2nd(back) list''' + + back = reverseList(back) + ''' modify the contents of 1st half''' + + modifyTheContentsOf1stHalf() + ''' agains reverse the 2nd(back) list''' + + back = reverseList(back) + ''' concatenating the 2nd list back to the + end of the 1st list''' + + head = concatFrontAndBackList(front, back) + ''' pointer to the modified list''' + + return head + '''function to print the linked list''' + +def printList( head): + if (head == None): + return + while (head.next != None): + print(head.data , "" -> "",end="""") + head = head.next + print(head.data ) + '''Driver Code''' + +head = None + '''creating the linked list''' + +head = push(head, 10) +head = push(head, 7) +head = push(head, 12) +head = push(head, 8) +head = push(head, 9) +head = push(head, 2) + '''modify the linked list''' + +head = modifyTheList(head) + '''print the modified linked list''' + +print( ""Modified List:"" ) +printList(head)" +Babylonian method for square root,"class GFG { + /*Returns the square root of n. + Note that the function */ + + static float squareRoot(float n) + { + /*We are using n itself as + initial approximation This + can definitely be improved */ + + float x = n; + float y = 1; +/* e decides the accuracy level*/ + + double e = 0.000001; + while (x - y > e) { + x = (x + y) / 2; + y = n / x; + } + return x; + } + /* Driver program to test + above function*/ + + public static void main(String[] args) + { + int n = 50; + System.out.printf(""Square root of "" + + n + "" is "" + squareRoot(n)); + } +} +"," '''Returns the square root of n. +Note that the function''' + +def squareRoot(n): + ''' We are using n itself as + initial approximation This + can definitely be improved''' + + x = n + y = 1 + ''' e decides the accuracy level''' + + e = 0.000001 + while(x - y > e): + x = (x + y)/2 + y = n / x + return x + '''Driver program to test +above function''' + +n = 50 +print(""Square root of"", n, ""is"", + round(squareRoot(n), 6))" +Types of Linked List,," '''structure of Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None +" +Count trailing zeroes in factorial of a number,"/*Java program to count +trailing 0s in n!*/ + +import java.io.*; +class GFG +{ +/* Function to return trailing + 0s in factorial of n*/ + + static int findTrailingZeros(int n) + { +/* Initialize result*/ + + int count = 0; +/* Keep dividing n by powers + of 5 and update count*/ + + for (int i = 5; n / i >= 1; i *= 5) + count += n / i; + return count; + } +/* Driver Code*/ + + public static void main (String[] args) + { + int n = 100; + System.out.println(""Count of trailing 0s in "" + + n +""! is "" + + findTrailingZeros(n)); + } +}"," '''Python3 program to +count trailing 0s +in n! + ''' '''Function to return +trailing 0s in +factorial of n''' + +def findTrailingZeros(n): + ''' Initialize result''' + + count = 0 + ''' Keep dividing n by + 5 & update Count''' + + while(n >= 5): + n //= 5 + count += n + return count + '''Driver program''' + +n = 100 +print(""Count of trailing 0s "" + + ""in 100! is"", findTrailingZeros(n))" +Minimum number of edges between two vertices of a Graph,"/*Java program to find minimum edge +between given two vertex of Graph*/ + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Vector; +class Test +{ +/* Method for finding minimum no. of edge + using BFS*/ + + static int minEdgeBFS(Vector edges[], int u, + int v, int n) + { +/* visited[n] for keeping track of visited + node in BFS*/ + + Vector visited = new Vector(n); + for (int i = 0; i < n; i++) { + visited.addElement(false); + } +/* Initialize distances as 0*/ + + Vector distance = new Vector(n); + for (int i = 0; i < n; i++) { + distance.addElement(0); + } +/* queue to do BFS.*/ + + Queue Q = new LinkedList<>(); + distance.setElementAt(0, u); + Q.add(u); + visited.setElementAt(true, u); + while (!Q.isEmpty()) + { + int x = Q.peek(); + Q.poll(); + for (int i=0; i edges[], int u, int v) + { + edges[u].add(v); + edges[v].add(u); + } +/* Driver method*/ + + public static void main(String args[]) + { +/* To store adjacency list of graph*/ + + int n = 9; + Vector edges[] = new Vector[9]; + for (int i = 0; i < edges.length; i++) { + edges[i] = new Vector<>(); + } + addEdge(edges, 0, 1); + addEdge(edges, 0, 7); + addEdge(edges, 1, 7); + addEdge(edges, 1, 2); + addEdge(edges, 2, 3); + addEdge(edges, 2, 5); + addEdge(edges, 2, 8); + addEdge(edges, 3, 4); + addEdge(edges, 3, 5); + addEdge(edges, 4, 5); + addEdge(edges, 5, 6); + addEdge(edges, 6, 7); + addEdge(edges, 7, 8); + int u = 0; + int v = 5; + System.out.println(minEdgeBFS(edges, u, v, n)); + } +}"," '''Python3 program to find minimum edge +between given two vertex of Graph''' + +import queue + '''function for finding minimum +no. of edge using BFS''' + +def minEdgeBFS(edges, u, v, n): + ''' visited[n] for keeping track + of visited node in BFS''' + + visited = [0] * n + ''' Initialize distances as 0''' + + distance = [0] * n + ''' queue to do BFS.''' + + Q = queue.Queue() + distance[u] = 0 + Q.put(u) + visited[u] = True + while (not Q.empty()): + x = Q.get() + for i in range(len(edges[x])): + if (visited[edges[x][i]]): + continue + ''' update distance for i''' + + distance[edges[x][i]] = distance[x] + 1 + Q.put(edges[x][i]) + visited[edges[x][i]] = 1 + return distance[v] + '''function for addition of edge''' + +def addEdge(edges, u, v): + edges[u].append(v) + edges[v].append(u) + '''Driver Code''' + +if __name__ == '__main__': + ''' To store adjacency list of graph''' + + n = 9 + edges = [[] for i in range(n)] + addEdge(edges, 0, 1) + addEdge(edges, 0, 7) + addEdge(edges, 1, 7) + addEdge(edges, 1, 2) + addEdge(edges, 2, 3) + addEdge(edges, 2, 5) + addEdge(edges, 2, 8) + addEdge(edges, 3, 4) + addEdge(edges, 3, 5) + addEdge(edges, 4, 5) + addEdge(edges, 5, 6) + addEdge(edges, 6, 7) + addEdge(edges, 7, 8) + u = 0 + v = 5 + print(minEdgeBFS(edges, u, v, n))" +Move all occurrences of an element to end in a linked list,"/*Java code to remove key element to end of linked list*/ + +import java.util.*; + +/*Node class*/ + +class Node { + int data; + Node next; + + public Node(int data) + { + this.data = data; + this.next = null; + } +} + +class gfg { + + static Node root; + +/* Function to remove key to end*/ + + public static Node keyToEnd(Node head, int key) + { + +/* Node to keep pointing to tail*/ + + Node tail = head; + + if (head == null) { + return null; + } + + while (tail.next != null) { + tail = tail.next; + } + +/* Node to point to last of linked list*/ + + Node last = tail; + + Node current = head; + Node prev = null; + +/* Node prev2 to point to previous when head.data!=key*/ + + Node prev2 = null; + +/* loop to perform operations to remove key to end*/ + + 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; + } + +/* Function to display linked list*/ + + public static void display(Node root) + { + while (root != null) { + System.out.print(root.data + "" ""); + root = root.next; + } + } + +/* Driver Code*/ + + public static void main(String args[]) + { + root = new Node(5); + root.next = new Node(2); + root.next.next = new Node(2); + root.next.next.next = new Node(7); + root.next.next.next.next = new Node(2); + root.next.next.next.next.next = new Node(2); + root.next.next.next.next.next.next = new Node(2); + + int key = 2; + System.out.println(""Linked List before operations :""); + display(root); + System.out.println(""\nLinked List after operations :""); + root = keyToEnd(root, key); + display(root); + } +} +"," '''Python3 code to remove key element to +end of linked list''' + + + '''A Linked list Node''' + +class Node: + + def __init__(self, data): + + self.data = data + self.next = None +def newNode(x): + + temp = Node(x) + return temp + + '''Function to remove key to end''' + +def keyToEnd(head, key): + + ''' Node to keep pointing to tail''' + + tail = head + + if (head == None): + return None + + while (tail.next != None): + tail = tail.next + + ''' Node to point to last of linked list''' + + last = tail + current = head + prev = None + + ''' Node prev2 to point to previous + when head.data!=key''' + + prev2 = None + + ''' Loop to perform operations to + remove key to end''' + + while (current != tail): + if (current.data == key and prev2 == None): + prev = current + current = current.next + head = current + last.next = prev + last = last.next + last.next = None + prev = None + + else: + if (current.data == key and prev2 != None): + prev = current + current = current.next + prev2.next = current + last.next = prev + last = last.next + last.next = None + + elif (current != tail): + prev2 = current + current = current.next + + return head + + '''Function to display linked list''' + +def printList(head): + + temp = head + + while (temp != None): + print(temp.data, end = ' ') + temp = temp.next + + print() + + '''Driver Code''' + +if __name__=='__main__': + + 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) + + key = 2 + print(""Linked List before operations :"") + printList(root) + print(""Linked List after operations :"") + root = keyToEnd(root, key) + + printList(root) + + +" +Alternate Odd and Even Nodes in a Singly Linked List,"/*Java program to rearrange nodes +as alternate odd even nodes in +a Singly Linked List*/ + +import java.util.*; + +class GFG +{ + +/*class node*/ + +static class Node +{ + int data; + Node next; +} + +/*A utility function to print +linked list*/ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data +"" ""); + node = node.next; + } + System.out.println(); +} + +/*Function to create newNode +in a linkedlist*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; +} + +/*Function to insert at beginning*/ + +static Node insertBeg(Node head, int val) +{ + Node temp = newNode(val); + temp.next = head; + head = temp; + return head; +} + +/*Function to rearrange the +odd and even nodes*/ + +static void rearrangeOddEven(Node head) +{ + Stack odd=new Stack(); + Stack even=new Stack(); + int i = 1; + + while (head != null) { + + if (head.data % 2 != 0 && i % 2 == 0) + { + +/* Odd Value in Even Position + Add pointer to current node + in odd stack*/ + + odd.push(head); + } + + else if (head.data % 2 == 0 && i % 2 != 0) + { + +/* Even Value in Odd Position + Add pointer to current node + in even stack*/ + + even.push(head); + } + + head = head.next; + i++; + } + + while (odd.size() > 0 && even.size() > 0) + { + +/* Swap Data at the top of two stacks*/ + + int k=odd.peek().data; + odd.peek().data=even.peek().data; + even.peek().data=k; + odd.pop(); + even.pop(); + } +} + +/*Driver code*/ + +public static void main(String args[]) +{ + Node head = newNode(8); + head = insertBeg(head, 7); + head = insertBeg(head, 6); + head = insertBeg(head, 5); + head = insertBeg(head, 3); + head = insertBeg(head, 2); + head = insertBeg(head, 1); + + System.out.println( ""Linked List:"" ); + printList(head); + rearrangeOddEven(head); + + System.out.println( ""Linked List after ""+ + ""Rearranging:"" ); + printList(head); +} +} + + +"," '''Python program to rearrange nodes +as alternate odd even nodes in +a Singly Linked List''' + + + '''Link list node''' + +class Node: + + def __init__(self, data): + self.data = data + self.next = next + + '''A utility function to print +linked list''' + +def printList( node): + + while (node != None) : + print(node.data , end="" "") + node = node.next + + print(""\n"") + + '''Function to create newNode +in a linkedlist''' + +def newNode(key): + + temp = Node(0) + temp.data = key + temp.next = None + return temp + + '''Function to insert at beginning''' + +def insertBeg(head, val): + + temp = newNode(val) + temp.next = head + head = temp + return head + + '''Function to rearrange the +odd and even nodes''' + +def rearrangeOddEven( head): + + odd = [] + even = [] + i = 1 + + while (head != None): + + if (head.data % 2 != 0 and i % 2 == 0): + + ''' Odd Value in Even Position + Add pointer to current node + in odd stack''' + + odd.append(head) + + elif (head.data % 2 == 0 and i % 2 != 0): + + ''' Even Value in Odd Position + Add pointer to current node + in even stack''' + + even.append(head) + + head = head.next + i = i + 1 + + while (len(odd) != 0 and len(even) != 0) : + + ''' Swap Data at the top of two stacks''' + + odd[-1].data, even[-1].data = even[-1].data, odd[-1].data + odd.pop() + even.pop() + + return head + + '''Driver code''' + + +head = newNode(8) +head = insertBeg(head, 7) +head = insertBeg(head, 6) +head = insertBeg(head, 5) +head = insertBeg(head, 3) +head = insertBeg(head, 2) +head = insertBeg(head, 1) + +print( ""Linked List:"" ) +printList(head) +rearrangeOddEven(head) + +print( ""Linked List after "", ""Rearranging:"" ) +printList(head) + + +" +Find duplicates in a given array when elements are not limited to a range,"/*Java implementation of the +above approach*/ + +import java.util.ArrayList; +public class GFG { +/* Function to find the Duplicates, + if duplicate occurs 2 times or + more than 2 times in + array so, it will print duplicate + value only once at output*/ + + static void findDuplicates( + int arr[], int len) + { +/* initialize ifPresent as false*/ + + boolean ifPresent = false; +/* ArrayList to store the output*/ + + ArrayList al = new ArrayList(); + for (int i = 0; i < len - 1; i++) { + for (int j = i + 1; j < len; j++) { + if (arr[i] == arr[j]) { +/* checking if element is + present in the ArrayList + or not if present then break*/ + + if (al.contains(arr[i])) { + break; + } +/* if element is not present in the + ArrayList then add it to ArrayList + and make ifPresent at true*/ + + else { + al.add(arr[i]); + ifPresent = true; + } + } + } + } +/* if duplicates is present + then print ArrayList*/ + + if (ifPresent == true) { + System.out.print(al + "" ""); + } + else { + System.out.print( + ""No duplicates present in arrays""); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 }; + int n = arr.length; + findDuplicates(arr, n); + } +}"," '''Python3 implementation of the +above approach + ''' '''Function to find the Duplicates, +if duplicate occurs 2 times or +more than 2 times in array so, +it will print duplicate value +only once at output''' + +def findDuplicates(arr, Len): + ''' Initialize ifPresent as false''' + + ifPresent = False + ''' ArrayList to store the output''' + + a1 = [] + for i in range(Len - 1): + for j in range(i + 1, Len): + ''' Checking if element is + present in the ArrayList + or not if present then break''' + + if (arr[i] == arr[j]): + if arr[i] in a1: + break + ''' If element is not present in the + ArrayList then add it to ArrayList + and make ifPresent at true''' + + else: + a1.append(arr[i]) + ifPresent = True + ''' If duplicates is present + then print ArrayList''' + + if (ifPresent): + print(a1, end = "" "") + else: + print(""No duplicates present in arrays"") + '''Driver Code''' + +arr = [ 12, 11, 40, 12, 5, 6, 5, 12, 11 ] +n = len(arr) +findDuplicates(arr, n)" +Count pairs from two sorted arrays whose sum is equal to a given value x,"/*Java implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value*/ +import java.util.*; +class GFG +{ +/*function to count all pairs +from both the sorted arrays +whose sum is equal to a given +value*/ + +static int countPairs(int arr1[], int arr2[], + int m, int n, int x) +{ + int count = 0; + HashSet us = new HashSet(); +/* insert all the elements + of 1st array in the hash + table(unordered_set 'us')*/ + + for (int i = 0; i < m; i++) + us.add(arr1[i]); +/* for each element of 'arr2[]*/ + + for (int j = 0; j < n; j++) +/* find (x - arr2[j]) in 'us'*/ + + if (us.contains(x - arr2[j])) + count++; +/* required count of pairs*/ + + return count; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr1[] = {1, 3, 5, 7}; + int arr2[] = {2, 3, 5, 8}; + int m = arr1.length; + int n = arr2.length; + int x = 10; + System.out.print(""Count = "" + + countPairs(arr1, arr2, m, n, x)); +} +}"," '''Python3 implementation to count +pairs from both sorted arrays +whose sum is equal to a given value + ''' '''function to count all pairs from +both the sorted arrays whose sum +is equal to a given value''' + +def countPairs(arr1, arr2, m, n, x): + count = 0 + us = set() + ''' insert all the elements + of 1st array in the hash + table(unordered_set 'us')''' + + for i in range(m): + us.add(arr1[i]) + ''' or each element of 'arr2[]''' + + for j in range(n): + ''' find (x - arr2[j]) in 'us''' + ''' + if x - arr2[j] in us: + count += 1 + ''' required count of pairs''' + + return count + '''Driver code''' + +arr1 = [1, 3, 5, 7] +arr2 = [2, 3, 5, 8] +m = len(arr1) +n = len(arr2) +x = 10 +print(""Count ="", + countPairs(arr1, arr2, m, n, x))" +Construct Binary Tree from given Parent Array representation,"/*Java program to construct a binary tree from parent array*/ +/*A binary tree node*/ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* Creates a node with key as 'i'. If i is root, then it changes + root. If parent of i is not created, then it creates parent first*/ + + void createNode(int parent[], int i, Node created[]) + { +/* If this node is already created*/ + + if (created[i] != null) + return; +/* Create a new node and set created[i]*/ + + created[i] = new Node(i); +/* If 'i' is root, change root pointer and return*/ + + if (parent[i] == -1) + { + root = created[i]; + return; + } +/* If parent is not created, then create parent first*/ + + if (created[parent[i]] == null) + createNode(parent, parent[i], created); +/* Find parent pointer*/ + + Node p = created[parent[i]]; +/* If this is first child of parent*/ + + if (p.left == null) + p.left = created[i]; +/*If second child*/ + +else + p.right = created[i]; + } + /* Creates tree from parent[0..n-1] and returns root of + the created tree */ + + Node createTree(int parent[], int n) + { +/* Create an array created[] to keep track + of created nodes, initialize all entries + as NULL*/ + + Node[] created = new Node[n]; + for (int i = 0; i < n; i++) + created[i] = null; + for (int i = 0; i < n; i++) + createNode(parent, i, created); + return root; + } +/* For adding new line in a program*/ + + void newLine() + { + System.out.println(""""); + } +/* Utility function to do inorder traversal*/ + + void inorder(Node node) + { + if (node != null) + { + inorder(node.left); + System.out.print(node.key + "" ""); + inorder(node.right); + } + } +/* Driver method*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5}; + int n = parent.length; + Node node = tree.createTree(parent, n); + System.out.println(""Inorder traversal of constructed tree ""); + tree.inorder(node); + tree.newLine(); + } +}"," '''Python implementation to construct a Binary Tree from +parent array''' + + '''A node structure''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + ''' Creates a node with key as 'i'. If i is root,then + it changes root. If parent of i is not created, then + it creates parent first + ''' + +def createNode(parent, i, created, root): + ''' If this node is already created''' + + if created[i] is not None: + return + ''' Create a new node and set created[i]''' + + created[i] = Node(i) + ''' If 'i' is root, change root pointer and return''' + + if parent[i] == -1: + root[0] = created[i] + return ''' If parent is not created, then create parent first''' + + if created[parent[i]] is None: + createNode(parent, parent[i], created, root ) + ''' Find parent pointer''' + + p = created[parent[i]] + ''' If this is first child of parent''' + + if p.left is None: + p.left = created[i] + ''' If second child''' + + else: + p.right = created[i] + '''Creates tree from parent[0..n-1] and returns root of the +created tree''' + +def createTree(parent): + n = len(parent) + ''' Create and array created[] to keep track + of created nodes, initialize all entries as None''' + + created = [None for i in range(n+1)] + root = [None] + for i in range(n): + createNode(parent, i, created, root) + return root[0] + '''Inorder traversal of tree''' + +def inorder(root): + if root is not None: + inorder(root.left) + print root.key, + inorder(root.right) + '''Driver Method''' + +parent = [-1, 0, 0, 1, 1, 3, 5] +root = createTree(parent) +print ""Inorder Traversal of constructed tree"" +inorder(root)" +Find k-th smallest element in BST (Order Statistics in BST),"/*A simple inorder traversal based Java program +to find k-th smallest element in a BST.*/ + +import java.io.*; +/*A BST node*/ + +class Node { + int data; + Node left, right; + Node(int x) + { + data = x; + left = right = null; + } +} +class GFG { + static int count = 0; +/* Recursive function to insert an key into BST*/ + + public static Node insert(Node root, int x) + { + if (root == null) + return new Node(x); + if (x < root.data) + root.left = insert(root.left, x); + else if (x > root.data) + root.right = insert(root.right, x); + return root; + } +/* Function to find k'th largest element in BST + Here count denotes the number + of nodes processed so far*/ + + public static Node kthSmallest(Node root, int k) + { +/* base case*/ + + if (root == null) + return null; +/* search in left subtree*/ + + Node left = kthSmallest(root.left, k); +/* if k'th smallest is found in left subtree, return it*/ + + if (left != null) + return left; +/* if current element is k'th smallest, return it*/ + + count++; + if (count == k) + return root; +/* else search in right subtree*/ + + return kthSmallest(root.right, k); + } +/* Function to find k'th largest element in BST*/ + + public static void printKthSmallest(Node root, int k) + { +/* maintain an index to count number of + nodes processed so far*/ + + count = 0; + Node res = kthSmallest(root, k); + if (res == null) + System.out.println(""There are less "" + + ""than k nodes in the BST""); + else + System.out.println(""K-th Smallest"" + + "" Element is "" + res.data); + } +/*Driver code*/ + + public static void main (String[] args) { + Node root = null; + int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; + for (int x : keys) + root = insert(root, x); + int k = 3; + printKthSmallest(root, k); + } +}"," '''A simple inorder traversal based Python3 +program to find k-th smallest element +in a BST.''' + + '''A BST node''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Recursive function to insert an key into BST''' + +def insert(root, x): + if (root == None): + return Node(x) + if (x < root.data): + root.left = insert(root.left, x) + elif (x > root.data): + root.right = insert(root.right, x) + return root + '''Function to find k'th largest element +in BST. Here count denotes the number +of nodes processed so far''' + +def kthSmallest(root): + global k + ''' Base case''' + + if (root == None): + return None + ''' Search in left subtree''' + + left = kthSmallest(root.left) + ''' If k'th smallest is found in + left subtree, return it''' + + if (left != None): + return left + ''' If current element is k'th + smallest, return it''' + + k -= 1 + if (k == 0): + return root + ''' Else search in right subtree''' + + return kthSmallest(root.right) + '''Function to find k'th largest element in BST''' + +def printKthSmallest(root): + ''' Maintain index to count number + of nodes processed so far''' + + count = 0 + res = kthSmallest(root) + if (res == None): + print(""There are less than k nodes in the BST"") + else: + print(""K-th Smallest Element is "", res.data) + '''Driver code''' + +if __name__ == '__main__': + root = None + keys = [ 20, 8, 22, 4, 12, 10, 14 ] + for x in keys: + root = insert(root, x) + k = 3 + printKthSmallest(root)" +Union-Find Algorithm | Set 2 (Union By Rank and Path Compression),"/*Naive implementation of find*/ + +static int find(int parent[], int i) +{ + if (parent[i] == -1) + return i; + return find(parent, parent[i]); +} +/*Naive implementation of union()*/ + +static void Union(int parent[], int x, int y) +{ + int xset = find(parent, x); + int yset = find(parent, y); + parent[xset] = yset; +}"," '''Naive implementation of find''' + +def find(parent, i): + if (parent[i] == -1): + return i + return find(parent, parent[i]) + '''Naive implementation of union()''' + +def Union(parent, x, y): + xset = find(parent, x) + yset = find(parent, y) + parent[xset] = yset" +0-1 Knapsack Problem | DP-10,"/*A Dynamic Programming based solution +for 0-1 Knapsack problem*/ + +class Knapsack { +/* A utility function that returns + maximum of two integers*/ + + static int max(int a, int b) + { + return (a > b) ? a : b; + } +/* Returns the maximum value that can + be put in a knapsack of capacity W*/ + + static int knapSack(int W, int wt[], + int val[], int n) + { + int i, w; + int K[][] = new int[n + 1][W + 1]; +/* Build table K[][] in bottom up manner*/ + + for (i = 0; i <= n; i++) + { + for (w = 0; w <= W; w++) + { + if (i == 0 || w == 0) + K[i][w] = 0; + else if (wt[i - 1] <= w) + K[i][w] + = max(val[i - 1] + + K[i - 1][w - wt[i - 1]], + K[i - 1][w]); + else + K[i][w] = K[i - 1][w]; + } + } + return K[n][W]; + } +/* Driver code*/ + + public static void main(String args[]) + { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +}"," '''A Dynamic Programming based Python +Program for 0-1 Knapsack problem''' + + '''Returns the maximum value that can +be put in a knapsack of capacity W''' + +def knapSack(W, wt, val, n): + K = [[0 for x in range(W + 1)] for x in range(n + 1)] ''' Build table K[][] in bottom up manner''' + + for i in range(n + 1): + for w in range(W + 1): + if i == 0 or w == 0: + K[i][w] = 0 + elif wt[i-1] <= w: + K[i][w] = max(val[i-1] + + K[i-1][w-wt[i-1]], + K[i-1][w]) + else: + K[i][w] = K[i-1][w] + return K[n][W] + '''Driver code''' + +val = [60, 100, 120] +wt = [10, 20, 30] +W = 50 +n = len(val) +print(knapSack(W, wt, val, n))" +Maximum number of edges to be added to a tree so that it stays a Bipartite graph,"/*Java code to print maximum edges such that +Tree remains a Bipartite graph*/ + +import java.util.*; +class GFG +{ +/*To store counts of nodes with two colors*/ + +static long []count_color = new long[2]; +static void dfs(Vector adj[], int node, + int parent, boolean color) +{ +/* Increment count of nodes with current + color*/ + + count_color[color == false ? 0 : 1]++; +/* Traversing adjacent nodes*/ + + for (int i = 0; i < adj[node].size(); i++) + { +/* Not recurring for the parent node*/ + + if (adj[node].get(i) != parent) + dfs(adj, adj[node].get(i), node, !color); + } +} +/*Finds maximum number of edges that can be added +without violating Bipartite property.*/ + +static int findMaxEdges(Vector adj[], int n) +{ +/* Do a DFS to count number of nodes + of each color*/ + + dfs(adj, 1, 0, false); + return (int) (count_color[0] * + count_color[1] - (n - 1)); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 5; + Vector[] adj = new Vector[n + 1]; + for (int i = 0; i < n + 1; i++) + adj[i] = new Vector(); + adj[1].add(2); + adj[1].add(3); + adj[2].add(4); + adj[3].add(5); + System.out.println(findMaxEdges(adj, n)); +} +}"," '''Python 3 code to print maximum edges such +that Tree remains a Bipartite graph ''' + + '''To store counts of nodes with two colors''' + +def dfs(adj, node, parent, color): + ''' Increment count of nodes with + current color ''' + + count_color[color] += 1 + ''' Traversing adjacent nodes''' + + for i in range(len(adj[node])): + ''' Not recurring for the parent node ''' + + if (adj[node][i] != parent): + dfs(adj, adj[node][i], + node, not color) + '''Finds maximum number of edges that +can be added without violating +Bipartite property. ''' + +def findMaxEdges(adj, n): + ''' Do a DFS to count number of + nodes of each color ''' + + dfs(adj, 1, 0, 0) + return (count_color[0] * + count_color[1] - (n - 1)) + '''Driver code +To store counts of nodes with +two colors ''' + +count_color = [0, 0] +n = 5 +adj = [[] for i in range(n + 1)] +adj[1].append(2) +adj[1].append(3) +adj[2].append(4) +adj[3].append(5) +print(findMaxEdges(adj, n))" +Graph implementation using STL for competitive programming | Set 2 (Weighted graph),," '''Python3 program to represent undirected +and weighted graph. The program basically +prints adjacency list representation of graph''' + + '''To add an edge''' + +def addEdge(adj, u, v, wt): + adj[u].append([v, wt]) + adj[v].append([u, wt]) + return adj '''Print adjacency list representaion ot graph''' + +def printGraph(adj, V): + v, w = 0, 0 + for u in range(V): + print(""Node"", u, ""makes an edge with"") + for it in adj[u]: + v = it[0] + w = it[1] + print(""\tNode"", v, ""with edge weight ="", w) + print() + '''Driver code''' + +if __name__ == '__main__': + V = 5 + adj = [[] for i in range(V)] + adj = addEdge(adj, 0, 1, 10) + adj = addEdge(adj, 0, 4, 20) + adj = addEdge(adj, 1, 2, 30) + adj = addEdge(adj, 1, 3, 40) + adj = addEdge(adj, 1, 4, 50) + adj = addEdge(adj, 2, 3, 60) + adj = addEdge(adj, 3, 4, 70) + printGraph(adj, V)" +Find if given matrix is Toeplitz or not,"/*JAVA program to check whether given matrix +is a Toeplitz matrix or not*/ + +import java.util.*; +class GFG { + static boolean isToeplitz(int[][] matrix) + { +/* row = number of rows + col = number of columns*/ + + int row = matrix.length; + int col = matrix[0].length; +/* HashMap to store key,value pairs*/ + + HashMap map + = new HashMap(); + for (int i = 0; i < row; i++) + { + for (int j = 0; j < col; j++) + { + int key = i - j; +/* if key value exists in the hashmap,*/ + + if (map.containsKey(key)) + { +/* we check whether the current value + stored in this key matches to element + at current index or not. If not, + return false*/ + + if (map.get(key) != matrix[i][j]) + return false; + } +/* else we put key,value pair in hashmap*/ + + else { + map.put(i - j, matrix[i][j]); + } + } + } + return true; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[][] matrix = { { 12, 23, -32 }, + { -20, 12, 23 }, + { 56, -20, 12 }, + { 38, 56, -20 } }; +/* Function call*/ + + String result = (isToeplitz(matrix)) ? ""Yes"" : ""No""; + System.out.println(result); + } +}"," '''Python3 program to check whether given matrix +is a Toeplitz matrix or not''' + +def isToeplitz(matrix): + ''' row = number of rows + col = number of columns''' + + row = len(matrix) + col = len(matrix[0]) + ''' dictionary to store key,value pairs''' + + map = {} + for i in range(row): + for j in range(col): + key = i-j + ''' if key value exists in the map,''' + + if (key in map): + ''' we check whether the current value stored + in this key matches to element at current + index or not. If not, return false''' + + if (map[key] != matrix[i][j]): + return False + ''' else we put key,value pair in map''' + + else: + map[key] = matrix[i][j] + return True + '''Driver Code''' + +if __name__ == ""__main__"": + matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]] + ''' Function call''' + + if (isToeplitz(matrix)): + print(""Yes"") + else: + print(""No"")" +Two Pointers Technique,"import java.io.*; +class GFG +{ +/* Two pointer technique based solution to find + if there is a pair in A[0..N-1] with a given sum.*/ + + public static int isPairSum(int A[], int N, int X) + { +/* represents first pointer*/ + + int i = 0; +/* represents second pointer*/ + + int j = N - 1; + while (i < j) { +/* If we find a pair*/ + + if (A[i] + A[j] == X) + return 1; +/* If sum of elements at current + pointers is less, we move towards + higher values by doing i++*/ + + else if (A[i] + A[j] < X) + i++; +/* If sum of elements at current + pointers is more, we move towards + lower values by doing j--*/ + + else + j--; + } + return 0; + } +/* Driver code*/ + + public static void main(String[] args) + { +/* array declaration*/ + + int arr[] = { 3, 5, 9, 2, 8, 10, 11 }; +/* value to search*/ + + int val = 17; +/* size of the array*/ + + int arrSize = arr.length; +/* Function call*/ + + System.out.println(isPairSum(arr, arrSize, val)); + } +}"," '''Two pointer technique based solution to find +if there is a pair in A[0..N-1] with a given sum.''' + +def isPairSum(A, N, X): + ''' represents first pointer''' + + i = 0 + ''' represents second pointer''' + + j = N - 1 + while(i < j): + ''' If we find a pair''' + + if (A[i] + A[j] == X): + return True + ''' If sum of elements at current + pointers is less, we move towards + higher values by doing i += 1''' + + elif(A[i] + A[j] < X): + i += 1 + ''' If sum of elements at current + pointers is more, we move towards + lower values by doing j -= 1''' + + else: + j -= 1 + return 0 + '''array declaration''' + +arr = [3, 5, 9, 2, 8, 10, 11] + '''value to search''' + +val = 17 + ''' Function call''' + +print(isPairSum(arr, len(arr), val))" +Maximum difference between two elements such that larger element appears after the smaller number,"/*Java program to find Maximum difference +between two elements such that larger +element appears after the smaller number*/ + +class MaximumDiffrence +{ + /* The function assumes that there are at least two + elements in array. + The function returns a negative value if the array is + sorted in decreasing order. + Returns 0 if elements are equal */ + + int maxDiff(int arr[], int arr_size) + { + int max_diff = arr[1] - arr[0]; + int i, j; + for (i = 0; i < arr_size; i++) + { + for (j = i + 1; j < arr_size; j++) + { + if (arr[j] - arr[i] > max_diff) + max_diff = arr[j] - arr[i]; + } + } + return max_diff; + } + + /* Driver program to test above functions */ + + public static void main(String[] args) + { + MaximumDifference maxdif = new MaximumDifference(); + int arr[] = {1, 2, 90, 10, 110}; + + + +/* Function calling*/ + + System.out.println(""Maximum difference is "" + + maxdif.maxDiff(arr, 5)); + } +}"," '''Python 3 code to find Maximum difference +between two elements such that larger +element appears after the smaller number''' + + + '''The function assumes that there are at +least two elements in array. The function +returns a negative value if the array is +sorted in decreasing order. Returns 0 +if elements are equal''' + +def maxDiff(arr, arr_size): + max_diff = arr[1] - arr[0] + + for i in range( 0, arr_size ): + for j in range( i+1, arr_size ): + if(arr[j] - arr[i] > max_diff): + max_diff = arr[j] - arr[i] + + return max_diff + + '''Driver program to test above function''' + +arr = [1, 2, 90, 10, 110] +size = len(arr) + + + ''' Function calling''' + + +print (""Maximum difference is"", maxDiff(arr, size))" +Print nodes at k distance from root,"/*Java program to print nodes at k distance from root*/ + + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + + void printKDistant(Node node, int k) + { + if (node == null|| k < 0 ) + return; + if (k == 0) + { + System.out.print(node.data + "" ""); + return; + } + printKDistant(node.left, k - 1); + printKDistant(node.right, k - 1); + + } +/* Driver program to test above functions */ + + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); + + /* Constructed binary tree is + 1 + / \ + 2 3 + / \ / + 4 5 8 + */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(8); + + tree.printKDistant(tree.root, 2); + } +} + + +"," '''Python program to find the nodes at k distance from root''' + + + '''A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + +def printKDistant(root, k): + + if root is None: + return + if k == 0: + print root.data, + else: + printKDistant(root.left, k-1) + printKDistant(root.right, k-1) + + '''Driver program to test above function''' + + ''' + Constructed binary tree is + 1 + / \ + 2 3 + / \ / + 4 5 8 + ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(8) + +printKDistant(root, 2) + + +" +Range sum queries without updates,"/*Java program to find sum between two indexes +when there is no update.*/ + + +import java.util.*; +import java.lang.*; + +class GFG { + public static void preCompute(int arr[], int n, + int pre[]) + { + pre[0] = arr[0]; + for (int i = 1; i < n; i++) + pre[i] = arr[i] + pre[i - 1]; + } + +/* Returns sum of elements in arr[i..j] + It is assumed that i <= j*/ + + public static int rangeSum(int i, int j, int pre[]) + { + if (i == 0) + return pre[j]; + + return pre[j] - pre[i - 1]; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 2, 3, 4, 5 }; + int n = arr.length; + + int pre[] = new int[n]; + + +/*Function call*/ + + + preCompute(arr, n, pre); + System.out.println(rangeSum(1, 3, pre)); + System.out.println(rangeSum(2, 4, pre)); + } +}", +Minimum sum of absolute difference of pairs of two arrays,"/*Java program to find minimum sum of +absolute differences of two arrays.*/ + +import java.util.Arrays; + +class MinSum +{ +/* Returns minimum possible pairwise + absolute difference of two arrays.*/ + + static long findMinSum(long a[], long b[], long n) + { +/* Sort both arrays*/ + + Arrays.sort(a); + Arrays.sort(b); + +/* Find sum of absolute differences*/ + + long sum = 0 ; + for (int i = 0; i < n; i++) + sum = sum + Math.abs(a[i] - b[i]); + + return sum; + } + +/* Driver code*/ + + public static void main(String[] args) + { +/* Both a[] and b[] must be of same size.*/ + + long a[] = {4, 1, 8, 7}; + long b[] = {2, 3, 6, 5}; + int n = a.length; + System.out.println(findMinSum(a, b, n)); + } +} + + +"," '''Python3 program to find minimum sum +of absolute differences of two arrays.''' + +def findMinSum(a, b, n): + + ''' Sort both arrays''' + + a.sort() + b.sort() + + ''' Find sum of absolute differences''' + + sum = 0 + + for i in range(n): + sum = sum + abs(a[i] - b[i]) + + return sum + + '''Driver program''' + + + '''Both a[] and b[] must be of same size.''' + +a = [4, 1, 8, 7] +b = [2, 3, 6, 5] +n = len(a) + +print(findMinSum(a, b, n)) + + +" +Find position of the only set bit,"/*Java program to find position of only set bit in a given number*/ + +class GFG { +/* A utility function to check whether n is a power of 2 or not. +goo.gl/17Arj +See http:*/ + + static boolean isPowerOfTwo(int n) + { + return (n > 0 && ((n & (n - 1)) == 0)) ? true : false; + } +/* Returns position of the only set bit in 'n'*/ + + static int findPosition(int n) + { + if (!isPowerOfTwo(n)) + return -1; + int i = 1, pos = 1; +/* Iterate through bits of n till we find a set bit + i&n will be non-zero only when 'i' and 'n' have a set bit + at same position*/ + + while ((i & n) == 0) { +/* Unset current bit and set the next bit in 'i'*/ + + i = i << 1; +/* increment position*/ + + ++pos; + } + return pos; + } +/* Driver code*/ + + public static void main(String[] args) + { + int n = 16; + int pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + n = 12; + pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + n = 128; + pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + } +}"," '''Python3 program to find position of +only set bit in a given number''' ''' +A utility function to check +whether n is power of 2 or +not.''' + +def isPowerOfTwo(n): + return (True if(n > 0 and + ((n & (n - 1)) > 0)) + else False); + '''Returns position of the +only set bit in 'n''' + ''' +def findPosition(n): + if (isPowerOfTwo(n) == True): + return -1; + i = 1; + pos = 1; + ''' Iterate through bits of n + till we find a set bit i&n + will be non-zero only when + 'i' and 'n' have a set bit + at same position''' + + while ((i & n) == 0): + ''' Unset current bit and + set the next bit in 'i''' + ''' + i = i << 1; + ''' increment position''' + + pos += 1; + return pos; + '''Driver Code''' + +n = 16; +pos = findPosition(n); +if (pos == -1): + print(""n ="", n, "", Invalid number""); +else: + print(""n ="", n, "", Position "", pos); +n = 12; +pos = findPosition(n); +if (pos == -1): + print(""n ="", n, "", Invalid number""); +else: + print(""n ="", n, "", Position "", pos); +n = 128; +pos = findPosition(n); +if (pos == -1): + print(""n ="", n, "", Invalid number""); +else: + print(""n ="", n, "", Position "", pos);" +Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression),"/*Java program to implement Union-Find with union +by rank and path compression*/ + +import java.util.*; +class GFG +{ +static int MAX_VERTEX = 101; +/*Arr to represent parent of index i*/ + +static int []Arr = new int[MAX_VERTEX]; +/*Size to represent the number of nodes +in subgxrph rooted at index i*/ + +static int []size = new int[MAX_VERTEX]; +/*set parent of every node to itself and +size of node to one*/ + +static void initialize(int n) +{ + for (int i = 0; i <= n; i++) + { + Arr[i] = i; + size[i] = 1; + } +} +/*Each time we follow a path, find function +compresses it further until the path length +is greater than or equal to 1.*/ + +static int find(int i) +{ +/* while we reach a node whose parent is + equal to itself*/ + + while (Arr[i] != i) + { +/*Skip one level*/ + +Arr[i] = Arr[Arr[i]]; +/*Move to the new level*/ + +i = Arr[i]; + } + return i; +} +/*A function that does union of two nodes x and y +where xr is root node of x and yr is root node of y*/ + +static void _union(int xr, int yr) +{ +/*Make yr parent of xr*/ + +if (size[xr] < size[yr]) + { + Arr[xr] = Arr[yr]; + size[yr] += size[xr]; + } +/*Make xr parent of yr*/ + +else + { + Arr[yr] = Arr[xr]; + size[xr] += size[yr]; + } +} +/*The main function to check whether a given +gxrph contains cycle or not*/ + +static int isCycle(Vector adj[], int V) +{ +/* Itexrte through all edges of gxrph, + find nodes connecting them. + If root nodes of both are same, + then there is cycle in gxrph.*/ + + for (int i = 0; i < V; i++) + { + for (int j = 0; j < adj[i].size(); j++) + { +/*find root of i*/ + +int x = find(i); +/* find root of adj[i][j]*/ + + int y = find(adj[i].get(j)); + if (x == y) +/*If same parent*/ + +return 1; +/*Make them connect*/ + +_union(x, y); + } + } + return 0; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int V = 3; +/* Initialize the values for arxry Arr and Size*/ + + initialize(V); + /* Let us create following gxrph + 0 + | \ + | \ + 1-----2 */ + +/* Adjacency list for graph*/ + + Vector []adj = new Vector[V]; + for(int i = 0; i < V; i++) + adj[i] = new Vector(); + adj[0].add(1); + adj[0].add(2); + adj[1].add(2); +/* call is_cycle to check if it contains cycle*/ + + if (isCycle(adj, V) == 1) + System.out.print(""Graph contains Cycle.\n""); + else + System.out.print(""Graph does not contain Cycle.\n""); + } +}"," '''Python3 program to implement Union-Find +with union by rank and path compression.''' +MAX_VERTEX = 101 + '''Arr to represent parent of index i ''' + +Arr = [None] * MAX_VERTEX + '''Size to represent the number of nodes +in subgxrph rooted at index i ''' + +size = [None] * MAX_VERTEX + + '''set parent of every node to itself +and size of node to one ''' + +def initialize(n): + global Arr, size + for i in range(n + 1): + Arr[i] = i + size[i] = 1 '''Each time we follow a path, find +function compresses it further +until the path length is greater +than or equal to 1. ''' + +def find(i): + global Arr, size + ''' while we reach a node whose + parent is equal to itself ''' + + while (Arr[i] != i): + '''Skip one level ''' + + Arr[i] = Arr[Arr[i]] + '''Move to the new level''' + + i = Arr[i] + return i + '''A function that does union of two +nodes x and y where xr is root node +of x and yr is root node of y ''' + +def _union(xr, yr): + global Arr, size + '''Make yr parent of xr ''' + +if (size[xr] < size[yr]): + Arr[xr] = Arr[yr] + size[yr] += size[xr] + '''Make xr parent of yr''' + +else: + Arr[yr] = Arr[xr] + size[xr] += size[yr] + '''The main function to check whether +a given graph contains cycle or not ''' + +def isCycle(adj, V): + global Arr, size + ''' Itexrte through all edges of gxrph, + find nodes connecting them. + If root nodes of both are same, + then there is cycle in gxrph.''' + + for i in range(V): + for j in range(len(adj[i])): + '''find root of i ''' + +x = find(i) + '''find root of adj[i][j] ''' + +y = find(adj[i][j]) + if (x == y): + '''If same parent ''' + +return 1 + '''Make them connect''' + +_union(x, y) + return 0 + '''Driver Code''' +V = 3 + + '''Initialize the values for arxry +Arr and Size ''' + +initialize(V) + '''Let us create following gxrph + 0 +| \ +| \ +1-----2 ''' + + '''Adjacency list for graph ''' + +adj = [[] for i in range(V)] +adj[0].append(1) +adj[0].append(2) +adj[1].append(2) '''call is_cycle to check if it +contains cycle ''' + +if (isCycle(adj, V)): + print(""Graph contains Cycle."") +else: + print(""Graph does not contain Cycle."")" +Inorder Successor in Binary Search Tree,"/*Java program to find minimum +value node in Binary Search Tree*/ + + /*A binary tree node*/ + +class Node { + int data; + Node left, right, parent; + Node(int d) + { + data = d; + left = right = parent = null; + } +} +class BinaryTree { + static Node head;/* Given a binary search tree and a number, + inserts a new node with the given number in + the correct place in the tree. Returns the new + root pointer which the caller should then use + (the standard trick to avoid using reference + parameters). */ + + Node insert(Node node, int data) + { + /* 1. If the tree is empty, return a new, + single node */ + + if (node == null) { + return (new Node(data)); + } + else { + Node temp = null; + /* 2. Otherwise, recur down the tree */ + + if (data <= node.data) { + temp = insert(node.left, data); + node.left = temp; + temp.parent = node; + } + else { + temp = insert(node.right, data); + node.right = temp; + temp.parent = node; + } + /* return the (unchanged) node pointer */ + + return node; + } + } + Node inOrderSuccessor(Node root, Node n) + { +/* step 1 of the above algorithm*/ + + if (n.right != null) { + return minValue(n.right); + } +/* step 2 of the above algorithm*/ + + Node p = n.parent; + while (p != null && n == p.right) { + n = p; + p = p.parent; + } + return p; + } + /* Given a non-empty binary search + tree, return the minimum data + value found in that tree. Note that + the entire tree does not need + to be searched. */ + + Node minValue(Node node) + { + Node current = node; + /* loop down to find the leftmost leaf */ + + while (current.left != null) { + current = current.left; + } + return current; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + Node root = null, temp = null, suc = null, min = null; + root = tree.insert(root, 20); + root = tree.insert(root, 8); + root = tree.insert(root, 22); + root = tree.insert(root, 4); + root = tree.insert(root, 12); + root = tree.insert(root, 10); + root = tree.insert(root, 14); + temp = root.left.right.right; + suc = tree.inOrderSuccessor(root, temp); + if (suc != null) { + System.out.println( + ""Inorder successor of "" + + temp.data + "" is "" + suc.data); + } + else { + System.out.println( + ""Inorder successor does not exist""); + } + } +}"," '''Python program to find the inroder successor in a BST''' + + '''A binary tree node''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + '''Given a binary search tree and a number, inserts a +new node with the given number in the correct place +in the tree. Returns the new root pointer which the +caller should then use( the standard trick to avoid +using reference parameters)''' + +def insert( node, data): + ''' 1) If tree is empty then return a new singly node''' + + if node is None: + return Node(data) + else: + ''' 2) Otherwise, recur down the tree''' + + if data <= node.data: + temp = insert(node.left, data) + node.left = temp + temp.parent = node + else: + temp = insert(node.right, data) + node.right = temp + temp.parent = node + ''' return the unchanged node pointer''' + + return node +def inOrderSuccessor(n): ''' Step 1 of the above algorithm''' + + if n.right is not None: + return minValue(n.right) + ''' Step 2 of the above algorithm''' + + p = n.parent + while( p is not None): + if n != p.right : + break + n = p + p = p.parent + return p + '''Given a non-empty binary search tree, return the +minimum data value found in that tree. Note that the +entire tree doesn't need to be searched''' + +def minValue(node): + current = node + ''' loop down to find the leftmost leaf''' + + while(current is not None): + if current.left is None: + break + current = current.left + return current + '''Driver progam to test above function''' + +root = None +root = insert(root, 20) +root = insert(root, 8); +root = insert(root, 22); +root = insert(root, 4); +root = insert(root, 12); +root = insert(root, 10); +root = insert(root, 14); +temp = root.left.right.right +succ = inOrderSuccessor( root, temp) +if succ is not None: + print ""\nInorder Successor of % d is % d "" \ + %(temp.data, succ.data) +else: + print ""\nInorder Successor doesn't exist""" +Rotate Linked List block wise,"/*Java program to rotate a linked list block wise*/ + +import java.util.*; +class GFG +{ + +/* Link list node */ + +static class Node +{ + int data; + Node next; +}; +static Node tail; + +/*Recursive function to rotate one block*/ + +static Node rotateHelper(Node blockHead, + Node blockTail, + int d, + int k) +{ + if (d == 0) + return blockHead; + +/* Rotate Clockwise*/ + + if (d > 0) + { + Node temp = blockHead; + for (int i = 1; temp.next.next!=null && + i < k - 1; i++) + temp = temp.next; + blockTail.next = blockHead; + tail = temp; + return rotateHelper(blockTail, temp, + d - 1, k); + } + +/* Rotate anti-Clockwise*/ + + if (d < 0) + { + blockTail.next = blockHead; + tail = blockHead; + return rotateHelper(blockHead.next, + blockHead, d + 1, k); + } + return blockHead; +} + +/*Function to rotate the linked list block wise*/ + +static Node rotateByBlocks(Node head, + int k, int d) +{ +/* If length is 0 or 1 return head*/ + + if (head == null || head.next == null) + return head; + +/* if degree of rotation is 0, return head*/ + + if (d == 0) + return head; + + Node temp = head; + tail = null; + +/* Traverse upto last element of this block*/ + + int i; + for (i = 1; temp.next != null && i < k; i++) + temp = temp.next; + +/* storing the first node of next block*/ + + Node nextBlock = temp.next; + +/* If nodes of this block are less than k. + Rotate this block also*/ + + if (i < k) + head = rotateHelper(head, temp, d % k, + i); + else + head = rotateHelper(head, temp, d % k, + k); + +/* Append the new head of next block to + the tail of this block*/ + + tail.next = rotateByBlocks(nextBlock, k, + d % k); + +/* return head of updated Linked List*/ + + return head; +} + +/* UTILITY FUNCTIONS */ + +/* Function to push a node */ + +static Node 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; + return head_ref; + +} + +/* Function to print linked list */ + +static void printList(Node node) +{ + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.next; + } +} + +/* Driver code*/ + +public static void main(String[] args) +{ + + /* Start with the empty list */ + + Node head = null; + +/* create a list 1.2.3.4.5. + 6.7.8.9.null*/ + + for (int i = 9; i > 0; i -= 1) + head = push(head, i); + System.out.print(""Given linked list \n""); + printList(head); + +/* k is block size and d is number of + rotations in every block.*/ + + int k = 3, d = 2; + head = rotateByBlocks(head, k, d); + System.out.print(""\nRotated by blocks Linked list \n""); + printList(head); +} +} + + +"," '''Python3 program to rotate a linked +list block wise''' + + + '''Link list node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Recursive function to rotate one block''' + +def rotateHelper(blockHead, blockTail, + d, tail, k): + if (d == 0): + return blockHead, tail + + ''' Rotate Clockwise''' + + if (d > 0): + temp = blockHead + i = 1 + while temp.next.next != None and i < k - 1: + temp = temp.next + i += 1 + blockTail.next = blockHead + tail = temp + return rotateHelper(blockTail, temp, + d - 1, tail, k) + + ''' Rotate anti-Clockwise''' + + if (d < 0): + blockTail.next = blockHead + tail = blockHead + return rotateHelper(blockHead.next, + blockHead, d + 1, + tail, k) + + '''Function to rotate the linked list block wise''' + +def rotateByBlocks(head, k, d): + + ''' If length is 0 or 1 return head''' + + if (head == None or head.next == None): + return head + + ''' If degree of rotation is 0, return head''' + + if (d == 0): + return head + temp = head + tail = None + + ''' Traverse upto last element of this block''' + + i = 1 + while temp.next != None and i < k: + temp = temp.next + i += 1 + + ''' Storing the first node of next block''' + + nextBlock = temp.next + + ''' If nodes of this block are less than k. + Rotate this block also''' + + if (i < k): + head, tail = rotateHelper(head, temp, d % k, + tail, i) + else: + head, tail = rotateHelper(head, temp, d % k, + tail, k) + + ''' Append the new head of next block to + the tail of this block''' + + tail.next = rotateByBlocks(nextBlock, k, + d % k); + + ''' Return head of updated Linked List''' + + return head; + + '''UTILITY FUNCTIONS''' + + + '''Function to push a node''' + +def push(head_ref, new_data): + + new_node = Node(new_data) + new_node.data = new_data + new_node.next = (head_ref) + (head_ref) = new_node + return head_ref '''Function to print linked list''' + +def printList(node): + while (node != None): + print(node.data, end = ' ') + node = node.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Start with the empty list''' + + head = None + + ''' Create a list 1.2.3.4.5. + 6.7.8.9.None''' + + for i in range(9, 0, -1): + head = push(head, i) + print(""Given linked list "") + printList(head) + + ''' k is block size and d is number of + rotations in every block.''' + + k = 3 + d = 2 + head = rotateByBlocks(head, k, d) + + print(""\nRotated by blocks Linked list "") + printList(head) + + +" +Replace node with depth in a binary tree,"/*Java program to replace every key value +with its depth. */ + +class GfG { +/* A tree node structure */ + +static class Node +{ + int data; + Node left, right; +} +/* Utility function to create a +new Binary Tree node */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} +/*Helper function replaces the data with depth +Note : Default value of level is 0 for root. */ + +static void replaceNode(Node node, int level) +{ +/* Base Case */ + + if (node == null) + return; +/* Replace data with current depth */ + + node.data = level; + replaceNode(node.left, level+1); + replaceNode(node.right, level+1); +} +/*A utility function to print inorder +traversal of a Binary Tree */ + +static void printInorder(Node node) +{ + if (node == null) + return; + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); +} +/* Driver function to test above functions */ + +public static void main(String[] args) +{ + Node root = new Node(); + /* Constructing tree given in + the above figure */ + + root = newNode(3); + root.left = newNode(2); + root.right = newNode(5); + root.left.left = newNode(1); + root.left.right = newNode(4); + System.out.println(""Before Replacing Nodes""); + printInorder(root); + replaceNode(root, 0); + System.out.println(); + System.out.println(""After Replacing Nodes""); + printInorder(root); +} +}"," '''Python3 program to replace every key +value with its depth. ''' + + ''' A tree node structure ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Helper function replaces the data with depth +Note : Default value of level is 0 for root. ''' + +def replaceNode(node, level = 0): + ''' Base Case ''' + + if (node == None): + return + ''' Replace data with current depth ''' + + node.data = level + replaceNode(node.left, level + 1) + replaceNode(node.right, level + 1) + '''A utility function to prinorder +traversal of a Binary Tree ''' + +def printInorder(node): + if (node == None): + return + printInorder(node.left) + print(node.data, end = "" "") + printInorder(node.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructing tree given in + the above figure ''' + + root = newNode(3) + root.left = newNode(2) + root.right = newNode(5) + root.left.left = newNode(1) + root.left.right = newNode(4) + print(""Before Replacing Nodes"") + printInorder(root) + replaceNode(root) + print() + print(""After Replacing Nodes"") + printInorder(root)" +Split the array and add the first part to the end,"/*Java program to split array and move first +part to end.*/ + +import java.util.*; +import java.lang.*; +class GFG { + public static void splitArr(int arr[], int n, int k) + { + for (int i = 0; i < k; i++) { +/* Rotate array by 1.*/ + + int x = arr[0]; + for (int j = 0; j < n - 1; ++j) + arr[j] = arr[j + 1]; + arr[n - 1] = x; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 12, 10, 5, 6, 52, 36 }; + int n = arr.length; + int position = 2; + splitArr(arr, 6, position); + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + "" ""); + } +} +"," '''Python program to split array and move first +part to end.''' + +def splitArr(arr, n, k): + for i in range(0, k): + + '''Rotate array by 1.''' + + x = arr[0] + for j in range(0, n-1): + arr[j] = arr[j + 1] + arr[n-1] = x '''main''' + +arr = [12, 10, 5, 6, 52, 36] +n = len(arr) +position = 2 +splitArr(arr, n, position) +for i in range(0, n): + print(arr[i], end = ' ') +" +Check a given sentence for a given set of simple grammer rules,"/*Java program to validate a given sentence +for a set of rules*/ + +class GFG +{ +/* Method to check a given sentence for given rules*/ + + static boolean checkSentence(char[] str) + { +/* Calculate the length of the string.*/ + + int len = str.length; +/* Check that the first character lies in [A-Z]. + Otherwise return false.*/ + + if (str[0] < 'A' || str[0] > 'Z') + return false; +/* If the last character is not a full stop(.) + no need to check further.*/ + + if (str[len - 1] != '.') + return false; +/* Maintain 2 states. Previous and current state + based on which vertex state you are. + Initialise both with 0 = start state.*/ + + int prev_state = 0, curr_state = 0; +/* Keep the index to the next character in the string.*/ + + int index = 1; +/* Loop to go over the string.*/ + + while (index <= str.length) + { +/* Set states according to the input characters + in the string and the rule defined in the description. + If current character is [A-Z]. Set current state as 0.*/ + + if (str[index] >= 'A' && str[index] <= 'Z') + curr_state = 0; +/* If current character is a space. + Set current state as 1.*/ + + else if (str[index] == ' ') + curr_state = 1; +/* If current character is [a-z]. + Set current state as 2.*/ + + else if (str[index] >= 'a' && str[index] <= 'z') + curr_state = 2; +/* If current state is a dot(.). + Set current state as 3.*/ + + else if (str[index] == '.') + curr_state = 3; +/* Validates all current state with previous state + for the rules in the description of the problem.*/ + + if (prev_state == curr_state && curr_state != 2) + return false; + if (prev_state == 2 && curr_state == 0) + return false; +/* If we have reached last state and previous state + is not 1, then check next character. If next character + is '\0', then return true, else false*/ + + if (curr_state == 3 && prev_state != 1) + return (index + 1 == str.length); + index++; +/* Set previous state as current state + before going over to the next character.*/ + + prev_state = curr_state; + } + return false; + } +/* Driver Code*/ + + public static void main(String[] args) + { + String[] str = { ""I love cinema."", ""The vertex is S."", + ""I am single."", ""My name is KG."", + ""I lovE cinema."", ""GeeksQuiz. is a quiz site."", + ""I love Geeksquiz and Geeksforgeeks."", + "" You are my friend."", ""I love cinema"" }; + int str_size = str.length; + int i = 0; + for (i = 0; i < str_size; i++) + { + if (checkSentence(str[i].toCharArray())) + System.out.println(""\"""" + str[i] + + ""\"""" + "" is correct""); + else + System.out.println(""\"""" + str[i] + + ""\"""" + "" is incorrect""); + } + } +}"," '''Python program to validate a given sentence for a set of rules + ''' '''Method to check a given sentence for given rules''' + +def checkSentence(string): + ''' Calculate the length of the string.''' + + length = len(string) + ''' Check that the first character lies in [A-Z]. + Otherwise return false.''' + + if string[0] < 'A' or string[0] > 'Z': + return False + ''' If the last character is not a full stop(.) no + need to check further.''' + + if string[length-1] != '.': + return False + ''' Maintain 2 states. Previous and current state based + on which vertex state you are. Initialise both with + 0 = start state.''' + + prev_state = 0 + curr_state = 0 + ''' Keep the index to the next character in the string.''' + + index = 1 + ''' Loop to go over the string.''' + + while (string[index]): + ''' Set states according to the input characters in the + string and the rule defined in the description. + If current character is [A-Z]. Set current state as 0.''' + + if string[index] >= 'A' and string[index] <= 'Z': + curr_state = 0 + ''' If current character is a space. Set current state as 1.''' + + elif string[index] == ' ': + curr_state = 1 + ''' If current character is a space. Set current state as 2.''' + + elif string[index] >= 'a' and string[index] <= 'z': + curr_state = 2 + ''' If current character is a space. Set current state as 3.''' + + elif string[index] == '.': + curr_state = 3 + ''' Validates all current state with previous state for the + rules in the description of the problem.''' + + if prev_state == curr_state and curr_state != 2: + return False + ''' If we have reached last state and previous state is not 1, + then check next character. If next character is '\0', then + return true, else false''' + + if prev_state == 2 and curr_state == 0: + return False + ''' Set previous state as current state before going over + to the next character.''' + + if curr_state == 3 and prev_state != 1: + return True + index += 1 + prev_state = curr_state + return False + '''Driver program''' + +string = [""I love cinema."", ""The vertex is S."", + ""I am single."", ""My name is KG."", + ""I lovE cinema."", ""GeeksQuiz. is a quiz site."", + ""I love Geeksquiz and Geeksforgeeks."", + "" You are my friend."", ""I love cinema""] +string_size = len(string) +for i in xrange(string_size): + if checkSentence(string[i]): + print ""\"""" + string[i] + ""\"" is correct"" + else: + print ""\"""" + string[i] + ""\"" is incorrect""" +Iterative Quick Sort,"/*Java program for implementation of QuickSort*/ + +import java.util.*; +class QuickSort { + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + + static int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + int i = (low - 1); + for (int j = low; j <= high - 1; j++) { + if (arr[j] <= pivot) { + i++; + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return i + 1; + } + +/* The main function that implements QuickSort() + arr[] --> Array to be sorted, + low --> Starting index, + high --> Ending index */ + + static void qSort(int arr[], int low, int high) + { + if (low < high) { + /* pi is partitioning index, arr[pi] is + now at right place */ + + int pi = partition(arr, low, high); + qSort(arr, low, pi - 1); + qSort(arr, pi + 1, high); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 5; + int arr[] = { 4, 2, 6, 9, 2 }; + qSort(arr, 0, n - 1); + for (int i = 0; i < n; i++) { + System.out.print(arr[i] + "" ""); + } + } +}"," '''A typical recursive Python +implementation of QuickSort''' + + '''Function takes last element as pivot, +places the pivot element at its correct +position in sorted array, and places all +smaller (smaller than pivot) to left of +pivot and all greater elements to right +of pivot''' + +def partition(arr, low, high): + i = (low - 1) + pivot = arr[high] + for j in range(low, high): + if arr[j] <= pivot: + i += 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1], arr[high] = arr[high], arr[i + 1] + return (i + 1) + '''The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index +Function to do Quick sort''' + +def quickSort(arr, low, high): + if low < high: + ''' pi is partitioning index, arr[p] is now + at right place''' + + pi = partition(arr, low, high) + quickSort(arr, low, pi-1) + quickSort(arr, pi + 1, high) + '''Driver Code''' + +if __name__ == '__main__' : + arr = [4, 2, 6, 9, 2] + n = len(arr) + quickSort(arr, 0, n - 1) + for i in range(n): + print(arr[i], end = "" "") +" +Find a Fixed Point (Value equal to index) in a given array,"/*Java program to check fixed point +in an array using linear search*/ + +class Main +{ + static int linearSearch(int arr[], int n) + { + int i; + for(i = 0; i < n; i++) + { + if(arr[i] == i) + return i; + } + /* If no fixed point present + then return -1 */ + + return -1; + } +/* main function*/ + + public static void main(String args[]) + { + int arr[] = {-10, -1, 0, 3, 10, 11, 30, 50, 100}; + int n = arr.length; + System.out.println(""Fixed Point is "" + + linearSearch(arr, n)); + } +}"," '''Python program to check fixed point +in an array using linear search''' + +def linearSearch(arr, n): + for i in range(n): + if arr[i] is i: + return i + ''' If no fixed point present then return -1''' + + return -1 + '''Driver program to check above functions''' + +arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100] +n = len(arr) +print(""Fixed Point is "" + str(linearSearch(arr,n)))" +Modify a binary tree to get preorder traversal using right pointers only,"/*Java code to modify binary tree for +traversal using only right pointer */ + +import java.util.*; +class GfG { +/*A binary tree node has data, +left child and right child */ + +static class Node { + int data; + Node left; + Node right; +} +/*Helper function that allocates a new +node with the given data and NULL +left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*An iterative process to set the right +pointer of Binary tree */ + +static void modifytree(Node root) +{ +/* Base Case */ + + if (root == null) + return; +/* Create an empty stack and push root to it */ + + Stack nodeStack = new Stack (); + nodeStack.push(root); + /* Pop all items one by one. + Do following for every popped item + a) print it + b) push its right child + c) push its left child + Note that right child is pushed first + so that left is processed first */ + + Node pre = null; + while (nodeStack.isEmpty() == false) { +/* Pop the top item from stack */ + + Node node = nodeStack.peek(); + nodeStack.pop(); +/* Push right and left children of + the popped node to stack */ + + if (node.right != null) + nodeStack.push(node.right); + if (node.left != null) + nodeStack.push(node.left); +/* check if some previous node exists */ + + if (pre != null) { +/* set the right pointer of + previous node to currrent */ + + pre.right = node; + } +/* set previous node as current node */ + + pre = node; + } +} +/*printing using right pointer only */ + +static void printpre(Node root) +{ + while (root != null) { + System.out.print(root.data + "" ""); + root = root.right; + } +} +/*Driver code */ + +public static void main(String[] args) +{ + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 5 +*/ + + Node root = newNode(10); + root.left = newNode(8); + root.right = newNode(2); + root.left.left = newNode(3); + root.left.right = newNode(5); + modifytree(root); + printpre(root); +} +}"," '''Python code to modify binary tree for +traversal using only right pointer ''' + + '''A binary tree node has data, +left child and right child ''' + +class newNode(): + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''An iterative process to set the right +pointer of Binary tree ''' + +def modifytree( root): + ''' Base Case ''' + + if (root == None): + return + ''' Create an empty stack and append root to it ''' + + nodeStack = [] + nodeStack.append(root) + ''' Pop all items one by one. + Do following for every popped item + a) prit + b) append its right child + c) append its left child + Note that right child is appended first + so that left is processed first ''' + + pre = None + while (len(nodeStack)): + ''' Pop the top item from stack ''' + + node = nodeStack[-1] + nodeStack.pop() + ''' append right and left children of + the popped node to stack ''' + + if (node.right): + nodeStack.append(node.right) + if (node.left): + nodeStack.append(node.left) + ''' check if some previous node exists ''' + + if (pre != None): + ''' set the right pointer of + previous node to currrent ''' + + pre.right = node + ''' set previous node as current node ''' + + pre = node + '''printing using right pointer only ''' + +def printpre( root): + while (root != None): + print(root.data, end = "" "") + root = root.right + '''Driver code ''' + + ''' Constructed binary tree is + 10 + / \ + 8 2 +/ \ +3 5 + ''' + +root = newNode(10) +root.left = newNode(8) +root.right = newNode(2) +root.left.left = newNode(3) +root.left.right = newNode(5) +modifytree(root) +printpre(root)" +Check if removing an edge can divide a Binary Tree in two halves,"/*Java program to check if there exist an edge whose +removal creates two trees of same size*/ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* To calculate size of tree with given root*/ + + int count(Node node) + { + if (node == null) + return 0; + return count(node.left) + count(node.right) + 1; + } +/* This function returns true if there is an edge + whose removal can divide the tree in two halves + n is size of tree*/ + + boolean checkRec(Node node, int n) + { +/* Base cases*/ + + if (node == null) + return false; +/* Check for root*/ + + if (count(node) == n - count(node)) + return true; +/* Check for rest of the nodes*/ + + return checkRec(node.left, n) + || checkRec(node.right, n); + } +/* This function mainly uses checkRec()*/ + + boolean check(Node node) + { +/* Count total nodes in given tree*/ + + int n = count(node); +/* Now recursively check all nodes*/ + + return checkRec(node, n); + } +/* Driver code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(5); + tree.root.left = new Node(1); + tree.root.right = new Node(6); + tree.root.left.left = new Node(3); + tree.root.right.left = new Node(7); + tree.root.right.right = new Node(4); + if(tree.check(tree.root)==true) + System.out.println(""YES""); + else + System.out.println(""NO""); + } +}"," '''Python3 program to check if there +exist an edge whose removal creates +two trees of same size +utility function to create a new node''' + +class newNode: + def __init__(self, x): + self.data = x + self.left = self.right = None + '''To calculate size of tree +with given root''' + +def count(root): + if (root == None): + return 0 + return (count(root.left) + + count(root.right) + 1) + '''This function returns true if there +is an edge whose removal can divide +the tree in two halves n is size of tree''' + +def checkRec(root, n): + ''' Base cases''' + + if (root == None): + return False + ''' Check for root''' + + if (count(root) == n - count(root)): + return True + ''' Check for rest of the nodes''' + + return (checkRec(root.left, n) or + checkRec(root.right, n)) + '''This function mainly uses checkRec()''' + +def check(root): + ''' Count total nodes in given tree''' + + n = count(root) + ''' Now recursively check all nodes''' + + return checkRec(root, n) + '''Driver code''' + +if __name__ == '__main__': + root = newNode(5) + root.left = newNode(1) + root.right = newNode(6) + root.left.left = newNode(3) + root.right.left = newNode(7) + root.right.right = newNode(4) + if check(root): + print(""YES"") + else: + print(""NO"")" +Rank of all elements in an array,"/*Java Code to find rank of elements*/ + +public class GfG { + +/* Function to print m Maximum elements*/ + + public static void rankify(int A[], int n) + { +/* Rank Vector*/ + + float R[] = new float[n]; + +/* Sweep through all elements in A + for each element count the number + of less than and equal elements + separately in r and s*/ + + for (int i = 0; i < n; i++) { + int r = 1, s = 1; + + for (int j = 0; j < n; j++) + { + if (j != i && A[j] < A[i]) + r += 1; + + if (j != i && A[j] == A[i]) + s += 1; + } + +/* Use formula to obtain rank*/ + + R[i] = r + (float)(s - 1) / (float) 2; + + } + + for (int i = 0; i < n; i++) + System.out.print(R[i] + "" ""); + + } + +/* Driver code*/ + + public static void main(String args[]) + { + int A[] = {1, 2, 5, 2, 1, 25, 2}; + int n = A.length; + + for (int i = 0; i < n; i++) + System.out.print(A[i] + "" ""); + System.out.println(); + rankify(A, n); + } +} + + +"," '''Python Code to find +rank of elements''' + +def rankify(A): + + ''' Rank Vector''' + + R = [0 for x in range(len(A))] + + ''' Sweep through all elements + in A for each element count + the number of less than and + equal elements separately + in r and s.''' + + for i in range(len(A)): + (r, s) = (1, 1) + for j in range(len(A)): + if j != i and A[j] < A[i]: + r += 1 + if j != i and A[j] == A[i]: + s += 1 + + ''' Use formula to obtain rank''' + + R[i] = r + (s - 1) / 2 + return R + + ''' Driver code''' + + +if __name__ == ""__main__"": + A = [1, 2, 5, 2, 1, 25, 2] + print(A) + print(rankify(A)) +" +Diagonal Traversal of Binary Tree,"/*Java program for diagonal +traversal of Binary Tree*/ + +import java.util.HashMap; +import java.util.Map.Entry; +import java.util.Vector; +public class DiagonalTraversalBTree +{ +/* Tree node*/ + + static class Node + { + int data; + Node left; + Node right; + Node(int data) + { + this.data=data; + left = null; + right =null; + } + }/* root - root of the binary tree + d - distance of current line from rightmost + -topmost slope. + diagonalPrint - HashMap to store Diagonal + elements (Passed by Reference) */ + + static void diagonalPrintUtil(Node root,int d, + HashMap> diagonalPrint) + { +/* Base case*/ + + if (root == null) + return; +/* Store all nodes of same line + together as a vector*/ + + Vector k = diagonalPrint.get(d); + if (k == null) + { + k = new Vector<>(); + k.add(root.data); + } + else + { + k.add(root.data); + } + diagonalPrint.put(d,k);/* Increase the vertical distance + if left child*/ + + diagonalPrintUtil(root.left, + d + 1, diagonalPrint); +/* Vertical distance remains + same for right child*/ + + diagonalPrintUtil(root.right, + d, diagonalPrint); + } +/* Print diagonal traversal + of given binary tree*/ + + static void diagonalPrint(Node root) + { +/* create a map of vectors + to store Diagonal elements*/ + + HashMap> + diagonalPrint = new HashMap<>(); + diagonalPrintUtil(root, 0, diagonalPrint); + System.out.println(""Diagonal Traversal + of Binnary Tree""); + for (Entry> entry : + diagonalPrint.entrySet()) + { + System.out.println(entry.getValue()); + } + } +/* Driver program*/ + + public static void main(String[] args) + { + Node root = new Node(8); + root.left = new Node(3); + root.right = new Node(10); + root.left.left = new Node(1); + root.left.right = new Node(6); + root.right.right = new Node(14); + root.right.right.left = new Node(13); + root.left.right.left = new Node(4); + root.left.right.right = new Node(7); + diagonalPrint(root); + } +}"," '''Python program for diagonal +traversal of Binary Tree''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + ''' root - root of the binary tree + d - distance of current line from rightmost + -topmost slope. + diagonalPrint - multimap to store Diagonal + elements (Passed by Reference) ''' + +def diagonalPrintUtil(root, d, diagonalPrintMap): + ''' Base Case''' + + if root is None: + return + ''' Store all nodes of same line + together as a vector''' + + try : + diagonalPrintMap[d].append(root.data) + except KeyError: + diagonalPrintMap[d] = [root.data] + ''' Increase the vertical distance + if left child''' + + diagonalPrintUtil(root.left, + d+1, diagonalPrintMap) + ''' Vertical distance remains + same for right child''' + + diagonalPrintUtil(root.right, + d, diagonalPrintMap) + '''Print diagonal traversal of given binary tree''' + +def diagonalPrint(root): + ''' Create a dict to store diagnoal elements''' + + diagonalPrintMap = dict() + diagonalPrintUtil(root, 0, diagonalPrintMap) + print ""Diagonal Traversal of binary tree : "" + for i in diagonalPrintMap: + for j in diagonalPrintMap[i]: + print j, + print """" '''Driver Program''' + +root = Node(8) +root.left = Node(3) +root.right = Node(10) +root.left.left = Node(1) +root.left.right = Node(6) +root.right.right = Node(14) +root.right.right.left = Node(13) +root.left.right.left = Node(4) +root.left.right.right = Node(7) +diagonalPrint(root)" +Smallest greater elements in whole array,"/*Simple Java program to find +smallest greater element in +whole array for every element.*/ + +import java.io.*; + +class GFG +{ +static void smallestGreater(int arr[], + int n) +{ + for (int i = 0; i < n; i++) + { + +/* Find the closest greater + element for arr[j] in + the entire array.*/ + + int diff = Integer.MAX_VALUE; + int closest = -1; + for (int j = 0; j < n; j++) + { + if (arr[i] < arr[j] && + arr[j] - arr[i] < diff) + { + diff = arr[j] - arr[i]; + closest = j; + } + } + +/* Check if arr[i] is largest*/ + + if(closest == -1) + System.out.print( ""_ "" ); + else + System.out.print(arr[closest] + "" ""); + } +} + +/*Driver code*/ + +public static void main (String[] args) +{ + int ar[] = {6, 3, 9, 8, 10, + 2, 1, 15, 7}; + int n = ar.length; + smallestGreater(ar, n); +} +} + + +"," '''Simple Python3 program to find smallest +greater element in whole array for +every element.''' + +def smallestGreater(arr, n) : + for i in range(0, n) : + + ''' Find the closest greater element + for arr[j] in the entire array.''' + + diff = 1000; + closest = -1; + for j in range(0, n) : + if ( arr[i] < arr[j] and + arr[j] - arr[i] < diff) : + diff = arr[j] - arr[i]; + closest = j; + + ''' Check if arr[i] is largest''' + + if (closest == -1) : + print (""_ "", end = """"); + else : + print (""{} "".format(arr[closest]), + end = """"); + + '''Driver code''' + +ar = [6, 3, 9, 8, 10, 2, 1, 15, 7]; +n = len(ar) ; +smallestGreater(ar, n); + + +" +Efficiently compute sums of diagonals of a matrix,"/*A simple java program to find +sum of diagonals*/ + +import java.io.*; +public class GFG { + static void printDiagonalSums(int [][]mat, + int n) + { + int principal = 0, secondary = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { +/* Condition for principal + diagonal*/ + + if (i == j) + principal += mat[i][j]; +/* Condition for secondary + diagonal*/ + + if ((i + j) == (n - 1)) + secondary += mat[i][j]; + } + } + System.out.println(""Principal Diagonal:"" + + principal); + System.out.println(""Secondary Diagonal:"" + + secondary); + } +/* Driver code*/ + + static public void main (String[] args) + { + int [][]a = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 1, 2, 3, 4 }, + { 5, 6, 7, 8 } }; + printDiagonalSums(a, 4); + } +}"," '''A simple Python program to +find sum of diagonals''' + +MAX = 100 +def printDiagonalSums(mat, n): + principal = 0 + secondary = 0; + for i in range(0, n): + for j in range(0, n): + ''' Condition for principal diagonal''' + + if (i == j): + principal += mat[i][j] + ''' Condition for secondary diagonal''' + + if ((i + j) == (n - 1)): + secondary += mat[i][j] + print(""Principal Diagonal:"", principal) + print(""Secondary Diagonal:"", secondary) + '''Driver code''' + +a = [[ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ]] +printDiagonalSums(a, 4)" +Program to find whether a no is power of two,"/*Java program for +the above approach*/ + +import java.util.*; +class GFG{ +/*Function which checks +whether a number is a +power of 2*/ + +static boolean powerOf2(int n) +{ +/* base cases + '1' is the only odd number + which is a power of 2(2^0)*/ + + if (n == 1) + return true; +/* all other odd numbers are + not powers of 2*/ + + else if (n % 2 != 0 || + n ==0) + return false; +/* recursive function call*/ + + return powerOf2(n / 2); +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* True*/ + + int n = 64; +/* False*/ + + int m = 12; + if (powerOf2(n) == true) + System.out.print(""True"" + ""\n""); + else System.out.print(""False"" + ""\n""); + if (powerOf2(m) == true) + System.out.print(""True"" + ""\n""); + else + System.out.print(""False"" + ""\n""); +} +}"," '''Python program for above approach''' + + '''function which checks whether a +number is a power of 2''' + +def powerof2(n): ''' base cases + '1' is the only odd number + which is a power of 2(2^0)''' + + if n == 1: + return True + ''' all other odd numbers are not powers of 2''' + + elif n%2 != 0 or n == 0: + return False + ''' recursive function call''' + + return powerof2(n/2) + '''Driver Code''' + +if __name__ == ""__main__"": + '''True''' + + print(powerof2(64)) + + '''False''' + + print(powerof2(12))" +Find index of closing bracket for a given opening bracket in an expression,"/*Java program to find index of closing +bracket for given opening bracket. */ + +import java.util.Stack; +class GFG { +/*Function to find index of closing +bracket for given opening bracket. */ + + static void test(String expression, int index) { + int i; +/* If index given is invalid and is + not an opening bracket. */ + + if (expression.charAt(index) != '[') { + System.out.print(expression + "", "" + + index + "": -1\n""); + return; + } +/* Stack to store opening brackets. */ + + Stack st = new Stack<>(); +/* Traverse through string starting from + given index. */ + + for (i = index; i < expression.length(); i++) { +/* If current character is an + opening bracket push it in stack. */ + + if (expression.charAt(i) == '[') { + st.push((int) expression.charAt(i)); +} /*If current character is a closing bracket, pop from stack. If stack + is empty, then this closing + bracket is required bracket. */ + + else if (expression.charAt(i) == ']') { + st.pop(); + if (st.empty()) { + System.out.print(expression + "", "" + + index + "": "" + i + ""\n""); + return; + } + } + } + + +/* If no matching closing bracket + is found. */ + + System.out.print(expression + "", "" + + index + "": -1\n""); + } +/*Driver Code */ + + public static void main(String[] args) { +/*should be 8 */ + +test(""[ABC[23]][89]"", 0); +/*should be 7 */ + +test(""[ABC[23]][89]"", 4); +/*should be 12 */ + +test(""[ABC[23]][89]"", 9); +/*No matching bracket */ + +test(""[ABC[23]][89]"", 1); + } + +}"," '''Python program to find index of closing +bracket for a given opening bracket.''' + +from collections import deque + + '''Function to find index of closing +bracket for given opening bracket.''' + +def getIndex(s, i): ''' If input is invalid.''' + + if s[i] != '[': + return -1 + ''' Create a deque to use it as a stack.''' + + d = deque() + ''' Traverse through all elements + starting from i.''' + + for k in range(i, len(s)): + ''' Push all starting brackets''' + + if s[k] == '[': + d.append(s[i]) + ''' Pop a starting bracket + for every closing bracket''' + + elif s[k] == ']': + d.popleft() + if not d: + return k ''' If deque becomes empty''' + + + return -1 + '''test function''' +def test(s, i): + matching_index = getIndex(s, i) + print(s + "", "" + str(i) + "": "" + str(matching_index)) '''Driver code to test above method.''' + + +def main(): + '''should be 8''' + + test(""[ABC[23]][89]"", 0) + + '''should be 7''' + + test(""[ABC[23]][89]"", 4) + + '''should be 12''' + + test(""[ABC[23]][89]"", 9) + + '''No matching bracket''' + + test(""[ABC[23]][89]"", 1) + '''execution''' +if __name__ == ""__main__"": + main()" +Finding minimum vertex cover size of a graph using binary search,"/*A Java program to find size of minimum vertex +cover using Binary Search*/ + +class GFG +{ +static final int maxn = 25; +/*Global array to store the graph +Note: since the array is global, all the +elements are 0 initially*/ + +static boolean [][]gr = new boolean[maxn][maxn]; +/*Returns true if there is a possible subset +of size 'k' that can be a vertex cover*/ + +static boolean isCover(int V, int k, int E) +{ +/* Set has first 'k' bits high initially*/ + + int set = (1 << k) - 1; + int limit = (1 << V); +/* to mark the edges covered in each subset + of size 'k'*/ + + boolean [][]vis = new boolean[maxn][maxn];; + while (set < limit) + { +/* Reset visited array for every subset + of vertices*/ + + for(int i = 0; i < maxn; i++) + { + for(int j = 0; j < maxn; j++) + { + vis[i][j] = false; + } + } +/* set counter for number of edges covered + from this subset of vertices to zero*/ + + int cnt = 0; +/* selected vertex cover is the indices + where 'set' has its bit high*/ + + for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) + { + if ((set & j) != 0) + { +/* Mark all edges emerging out of this + vertex visited*/ + + for (int co = 1 ; co <= V ; co++) + { + if (gr[v][co] && !vis[v][co]) + { + vis[v][co] = true; + vis[co][v] = true; + cnt++; + } + } + } + } +/* If the current subset covers all the edges*/ + + if (cnt == E) + return true; +/* Generate previous combination with k bits high + set & -set = (1 << last bit high in set)*/ + + int co = set & -set; + int ro = set + co; + set = (((ro^set) >> 2) / co) | ro; + } + return false; +} +/*Returns answer to graph stored in gr[][]*/ + +static int findMinCover(int n, int m) +{ +/* Binary search the answer*/ + + int left = 1, right = n; + while (right > left) + { + int mid = (left + right) >> 1; + if (isCover(n, mid, m) == false) + left = mid + 1; + else + right = mid; + } +/* at the end of while loop both left and + right will be equal,/ as when they are + not, the while loop won't exit the minimum + size vertex cover = left = right*/ + + return left; +} +/*Inserts an edge in the graph*/ + +static void insertEdge(int u, int v) +{ + gr[u][v] = true; +/*Undirected graph*/ + +gr[v][u] = true; +} +/*Driver code*/ + +public static void main(String[] args) +{ + /* + 6 + / + 1 ----- 5 vertex cover = {1, 2} + /|\ + 3 | \ + \ | \ + 2 4 */ + + int V = 6, E = 6; + insertEdge(1, 2); + insertEdge(2, 3); + insertEdge(1, 3); + insertEdge(1, 4); + insertEdge(1, 5); + insertEdge(1, 6); + System.out.print(""Minimum size of a vertex cover = "" + + findMinCover(V, E) +""\n""); +/* Let us create another graph*/ + + for(int i = 0; i < maxn; i++) + { + for(int j = 0; j < maxn; j++) + { + gr[i][j] = false; + } + } + /* + 2 ---- 4 ---- 6 + /| | + 1 | | vertex cover = {2, 3, 4} + \ | | + 3 ---- 5 */ + + V = 6; + E = 7; + insertEdge(1, 2); + insertEdge(1, 3); + insertEdge(2, 3); + insertEdge(2, 4); + insertEdge(3, 5); + insertEdge(4, 5); + insertEdge(4, 6); + System.out.print(""Minimum size of a vertex cover = "" + + findMinCover(V, E) +""\n""); +} +}"," '''A Python3 program to find size of minimum +vertex cover using Binary Search''' + +maxn = 25 + '''Global array to store the graph +Note: since the array is global, +all the elements are 0 initially ''' + +gr = [[None] * maxn for i in range(maxn)] + '''Returns true if there is a possible subSet +of size 'k' that can be a vertex cover ''' + +def isCover(V, k, E): ''' Set has first 'k' bits high initially ''' + + Set = (1 << k) - 1 + limit = (1 << V) + ''' to mark the edges covered in each + subSet of size 'k' ''' + + vis = [[None] * maxn for i in range(maxn)] + while (Set < limit): + ''' ReSet visited array for every + subSet of vertices ''' + + vis = [[0] * maxn for i in range(maxn)] + ''' Set counter for number of edges covered + from this subSet of vertices to zero ''' + + cnt = 0 + ''' selected vertex cover is the + indices where 'Set' has its bit high''' + + j = 1 + v = 1 + while(j < limit): + if (Set & j): + ''' Mark all edges emerging out of + this vertex visited''' + + for k in range(1, V + 1): + if (gr[v][k] and not vis[v][k]): + vis[v][k] = 1 + vis[k][v] = 1 + cnt += 1 + j = j << 1 + v += 1 + ''' If the current subSet covers all the edges ''' + + if (cnt == E): + return True + ''' Generate previous combination with k bits high + Set & -Set = (1 << last bit high in Set) ''' + + c = Set & -Set + r = Set + c + Set = (((r ^ Set) >> 2) // c) | r + return False + '''Returns answer to graph stored in gr[][] ''' + +def findMinCover(n, m): + ''' Binary search the answer ''' + + left = 1 + right = n + while (right > left): + mid = (left + right) >> 1 + if (isCover(n, mid, m) == False): + left = mid + 1 + else: + right = mid + ''' at the end of while loop both left and + right will be equal,/ as when they are + not, the while loop won't exit the + minimum size vertex cover = left = right ''' + + return left + '''Inserts an edge in the graph ''' + +def insertEdge(u, v): + gr[u][v] = 1 + '''Undirected graph''' + + gr[v][u] = 1 + '''Driver code ''' + + ''' + 6 + / + 1 ----- 5 vertex cover = {1, 2} + /|\ +3 | \ +\ | \ + 2 4 ''' + +V = 6 +E = 6 +insertEdge(1, 2) +insertEdge(2, 3) +insertEdge(1, 3) +insertEdge(1, 4) +insertEdge(1, 5) +insertEdge(1, 6) +print(""Minimum size of a vertex cover = "", + findMinCover(V, E)) + '''Let us create another graph ''' + +gr = [[0] * maxn for i in range(maxn)] + ''' + 2 ---- 4 ---- 6 + /| | +1 | | vertex cover = {2, 3, 4} + \ | | + 3 ---- 5 ''' + +V = 6 +E = 7 +insertEdge(1, 2) +insertEdge(1, 3) +insertEdge(2, 3) +insertEdge(2, 4) +insertEdge(3, 5) +insertEdge(4, 5) +insertEdge(4, 6) +print(""Minimum size of a vertex cover = "", + findMinCover(V, E))" +Find the node with minimum value in a Binary Search Tree,"/*Java program to find minimum value node in Binary Search Tree*/ +/*A binary tree node*/ + +class Node { + int data; + Node left, right; + Node(int d) { + data = d; + left = right = null; + } +} +class BinaryTree { + static Node head; + /* Given a binary search tree and a number, + inserts a new node with the given number in + the correct place in the tree. Returns the new + root pointer which the caller should then use + (the standard trick to avoid using reference + parameters). */ + + Node insert(Node node, int data) { + /* 1. If the tree is empty, return a new, + single node */ + + if (node == null) { + return (new Node(data)); + } else { + /* 2. Otherwise, recur down the tree */ + + if (data <= node.data) { + node.left = insert(node.left, data); + } else { + node.right = insert(node.right, data); + } + /* return the (unchanged) node pointer */ + + return node; + } + } + /* Given a non-empty binary search tree, + return the minimum data value found in that + tree. Note that the entire tree does not need + to be searched. */ + + int minvalue(Node node) { + Node current = node; + /* loop down to find the leftmost leaf */ + + while (current.left != null) { + current = current.left; + } + return (current.data); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) { + BinaryTree tree = new BinaryTree(); + Node root = null; + root = tree.insert(root, 4); + tree.insert(root, 2); + tree.insert(root, 1); + tree.insert(root, 3); + tree.insert(root, 6); + tree.insert(root, 5); + System.out.println(""Minimum value of BST is "" + tree.minvalue(root)); + } +}"," '''Python program to find the node with minimum value in bst''' + + '''A binary tree node''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None ''' Give a binary search tree and a number, +inserts a new node with the given number in +the correct place in the tree. Returns the new +root pointer which the caller should then use +(the standard trick to avoid using reference +parameters). ''' + +def insert(node, data): + ''' 1. If the tree is empty, return a new, + single node''' + + if node is None: + return (Node(data)) + else: + ''' 2. Otherwise, recur down the tree''' + + if data <= node.data: + node.left = insert(node.left, data) + else: + node.right = insert(node.right, data) + ''' Return the (unchanged) node pointer''' + + return node + ''' Given a non-empty binary search tree, +return the minimum data value found in that +tree. Note that the entire tree does not need +to be searched. ''' + +def minValue(node): + current = node + ''' loop down to find the lefmost leaf''' + + while(current.left is not None): + current = current.left + return current.data + '''Driver program''' + +root = None +root = insert(root,4) +insert(root,2) +insert(root,1) +insert(root,3) +insert(root,6) +insert(root,5) +print ""\nMinimum value in BST is %d"" %(minValue(root))" +Count set bits in an integer,"/*java program to demonstrate +__builtin_popcount()*/ + +import java.io.*; +class GFG { +/* Driver code*/ + + public static void main(String[] args) + { + System.out.println(Integer.bitCount(4)); + System.out.println(Integer.bitCount(15)); + } +}"," '''Python3 program to demonstrate __builtin_popcount()''' + + + ''' Driver code''' + +print(bin(4).count('1')); +print(bin(15).count('1'));" +Merge Sort for Linked Lists,"/*Java program for the above approach*/ + +import java.io.*; +import java.lang.*; +import java.util.*; +/*Node Class*/ + +class Node { + int data; + Node next; + Node(int key) + { + this.data = key; + next = null; + } +} +class GFG { +/* Function to merge sort*/ + + static Node mergeSort(Node head) + { + if (head.next == null) + return head; + Node mid = findMid(head); + Node head2 = mid.next; + mid.next = null; + Node newHead1 = mergeSort(head); + Node newHead2 = mergeSort(head2); + Node finalHead = merge(newHead1, newHead2); + return finalHead; + } +/* Function to merge two linked lists*/ + + static Node merge(Node head1, Node head2) + { + Node merged = new Node(-1); + Node temp = merged; +/* While head1 is not null and head2 + is not null*/ + + while (head1 != null && head2 != null) { + if (head1.data < head2.data) { + temp.next = head1; + head1 = head1.next; + } + else { + temp.next = head2; + head2 = head2.next; + } + temp = temp.next; + } +/* While head1 is not null*/ + + while (head1 != null) { + temp.next = head1; + head1 = head1.next; + temp = temp.next; + } +/* While head2 is not null*/ + + while (head2 != null) { + temp.next = head2; + head2 = head2.next; + temp = temp.next; + } + return merged.next; + } +/* Find mid using The Tortoise and The Hare approach*/ + + static Node findMid(Node head) + { + Node slow = head, fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + return slow; + } +/* Function to print list*/ + + static void printList(Node head) + { + while (head != null) { + System.out.print(head.data + "" ""); + head = head.next; + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + Node head = new Node(7); + Node temp = head; + temp.next = new Node(10); + temp = temp.next; + temp.next = new Node(5); + temp = temp.next; + temp.next = new Node(20); + temp = temp.next; + temp.next = new Node(3); + temp = temp.next; + temp.next = new Node(2); + temp = temp.next; +/* Apply merge Sort*/ + + head = mergeSort(head); + System.out.print(""\nSorted Linked List is: \n""); + printList(head); + } +}", +Delete all odd nodes of a Circular Linked List,"/*Java program to delete all prime +node from a Circular singly linked list*/ + +class GFG { + +/* Structure for a node*/ + + static class Node { + int data; + Node next; + }; + +/* Function to insert a node at the beginning + of a Circular linked list*/ + + static Node push(Node head_ref, int data) + { + Node ptr1 = new Node(); + Node temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + +/* If linked list is not null then + set the next of last node*/ + + if (head_ref != null) { + while (temp.next != head_ref) + temp = temp.next; + temp.next = ptr1; + return head_ref; + } + else +/*For the first node*/ + + ptr1.next = ptr1; + + head_ref = ptr1; + return head_ref; + } + +/* Delete the node if it is odd*/ + + static Node deleteNode(Node head_ref, Node del) + { + Node temp = head_ref; +/* If node to be deleted is head node*/ + + + if (head_ref == del) + head_ref = del.next; + +/* Traverse list till not found + delete node*/ + + while (temp.next != del) { + temp = temp.next; + } + +/* Copy address of node*/ + + temp.next = del.next; + + return head_ref; + } + +/* Function to delete all odd nodes + from the singly circular linked list*/ + + static Node deleteoddNodes(Node head) + { + Node ptr = head; + + Node next; + +/* Traverse list till the end + if the node is odd then delete it*/ + + do { +/* If node is odd*/ + + if (ptr.data % 2 == 1) + deleteNode(head, ptr); + +/* point to next node*/ + + next = ptr.next; + ptr = next; + } while (ptr != head); + return head; + } + +/* Function to print nodes*/ + + static void printList(Node head) + { + Node temp = head; + if (head != null) { + do { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } while (temp != head); + } + } + +/* Driver code*/ + + public static void main(String args[]) + { +/* Initialize lists as empty*/ + + Node head = null; + +/* Created linked list will be 56->61->57->11->12->2*/ + + head = push(head, 2); + head = push(head, 12); + head = push(head, 11); + head = push(head, 57); + head = push(head, 61); + head = push(head, 56); + + System.out.println(""\nList after deletion : ""); + head = deleteoddNodes(head); + printList(head); + } +} +"," '''Python3 program to delete all odd +node from a Circular singly linked list''' + +import math + + '''Structure for a node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to insert a node at the beginning +of a Circular linked list''' + +def push(head_ref, data): + ptr1 = Node(data) + temp = head_ref + ptr1.data = data + ptr1.next = head_ref + + ''' If linked list is not None then + set the next of last node''' + + if (head_ref != None): + while (temp.next != head_ref): + temp = temp.next + temp.next = ptr1 + + else: + '''For the first node''' + + ptr1.next = ptr1 + + head_ref = ptr1 + return head_ref + + '''Delete the node if it is odd''' + +def deleteNode(head_ref, delete): + temp = head_ref + + ''' If node to be deleted is head node''' + + if (head_ref == delete): + head_ref = delete.next + + ''' Traverse list till not found + delete node''' + + while (temp.next != delete): + temp = temp.next + + ''' Copy address of node''' + + temp.next = delete.next + + + '''Function to delete all odd nodes +from the singly circular linked list''' + +def deleteoddNodes(head): + ptr = head + next = None + + ''' Traverse list till the end + if the node is odd then delete it''' + + ''' if node is odd''' + + next = ptr.next + ptr = next + while (ptr != head): + if (ptr.data % 2 == 1): + deleteNode(head, ptr) + ''' po to next node''' + + next = ptr.next + ptr = next + return head + + '''Function to pr nodes''' + +def prList(head): + temp = head + if (head != None): + print(temp.data, end = "" "") + temp = temp.next + while (temp != head): + print(temp.data, end = "" "") + temp = temp.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Initialize lists as empty''' + + head = None + + ''' Created linked list will be 56->61->57->11->12->2 ''' + + head = push(head, 2) + head = push(head, 12) + head = push(head, 11) + head = push(head, 57) + head = push(head, 61) + head = push(head, 56) + + print(""List after deletion : "", end = """") + head = deleteoddNodes(head) + prList(head) +" +Check if there exist two elements in an array whose sum is equal to the sum of rest of the array,"/*Java program to find whether two elements exist +whose sum is equal to sum of rest of the elements.*/ + +import java.util.*; + +class GFG +{ + +/* Function to check whether two elements exist + whose sum is equal to sum of rest of the elements.*/ + + static boolean checkPair(int arr[], int n) + { +/* Find sum of whole array*/ + + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += arr[i]; + } + +/* If sum of array is not even than we can not + divide it into two part*/ + + if (sum % 2 != 0) + { + return false; + } + + sum = sum / 2; + +/* For each element arr[i], see if there is + another element with vaalue sum - arr[i]*/ + + HashSet s = new HashSet(); + for (int i = 0; i < n; i++) + { + int val = sum - arr[i]; + +/* If element exist than return the pair*/ + + if (s.contains(val) && + val == (int) s.toArray()[s.size() - 1]) + { + System.out.printf(""Pair elements are %d and %d\n"", + arr[i], val); + return true; + } + s.add(arr[i]); + } + return false; + } + +/* Driver program.*/ + + public static void main(String[] args) + { + int arr[] = {2, 11, 5, 1, 4, 7}; + int n = arr.length; + if (checkPair(arr, n) == false) + { + System.out.printf(""No pair found""); + } + } +} + + +"," '''Python3 program to find whether +two elements exist whose sum is +equal to sum of rest of the elements.''' + + + '''Function to check whether two +elements exist whose sum is equal +to sum of rest of the elements.''' + +def checkPair(arr, n): + s = set() + sum = 0 + + ''' Find sum of whole array''' + + for i in range(n): + sum += arr[i] + + ''' / If sum of array is not + even than we can not + divide it into two part''' + + if sum % 2 != 0: + return False + sum = sum / 2 + + ''' For each element arr[i], see if + there is another element with + value sum - arr[i]''' + + for i in range(n): + val = sum - arr[i] + if arr[i] not in s: + s.add(arr[i]) + + ''' If element exist than + return the pair''' + + if val in s: + print(""Pair elements are"", + arr[i], ""and"", int(val)) + + '''Driver Code''' + +arr = [2, 11, 5, 1, 4, 7] +n = len(arr) +if checkPair(arr, n) == False: + print(""No pair found"") + + +" +Rearrange an array such that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' | Set 1,"/*A simple JAVA program to rearrange +contents of arr[] such that arr[j] +becomes j if arr[i] is j*/ + +class GFG { +/* A simple method to rearrange + 'arr[0..n-1]' so that 'arr[j]' + becomes 'i' if 'arr[i]' is 'j'*/ + + static void rearrange(int arr[], int n) + { + for (int i = 0; i < n; i++) { +/* retrieving old value and + storing with the new one*/ + + arr[arr[i] % n] += i * n; + } + for (int i = 0; i < n; i++) { +/* retrieving new value*/ + + arr[i] /= n; + } + } +/* A utility function to print + contents of arr[0..n-1]*/ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) { + System.out.print(arr[i] + "" ""); + } + System.out.println(); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 2, 0, 1, 4, 5, 3 }; + int n = arr.length; + System.out.println(""Given array is : ""); + printArray(arr, n); + rearrange(arr, n); + System.out.println(""Modified array is :""); + printArray(arr, n); + } +}"," '''A simple Python3 program to rearrange +contents of arr[] such that arr[j] +becomes j if arr[i] is j''' ''' +A simple method to rearrange + '''arr[0..n-1]' so that 'arr[j]' +becomes 'i' if 'arr[i]' is 'j''' + ''' +def rearrange(arr, n): + for i in range(n): + ''' Retrieving old value and + storing with the new one''' + + arr[arr[i] % n] += i * n + for i in range(n): + ''' Retrieving new value''' + + arr[i] //= n + '''A utility function to pr +contents of arr[0..n-1]''' + +def prArray(arr, n): + for i in range(n): + print(arr[i], end = "" "") + print() + '''Driver code''' + +arr = [2, 0, 1, 4, 5, 3] +n = len(arr) +print(""Given array is : "") +prArray(arr, n) +rearrange(arr, n) +print(""Modified array is :"") +prArray(arr, n)" +Insert node into the middle of the linked list,"/*Java implementation to insert node +at the middle of the linked list*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class LinkedList +{ +/*head of list*/ + +static Node head; + + /* Node Class */ + + static class Node { + int data; + Node next; + + Node(int d) { + data = d; + next = null; + } + } + +/* function to insert node at the + middle of the linked list*/ + + static void insertAtMid(int x) + { +/* if list is empty*/ + + if (head == null) + head = new Node(x); + + else { +/* get a new node*/ + + Node newNode = new Node(x); + +/* assign values to the slow + and fast pointers*/ + + Node slow = head; + Node fast = head.next; + + while (fast != null && fast.next + != null) + { +/* move slow pointer to next node*/ + + slow = slow.next; + +/* move fast pointer two nodes + at a time*/ + + fast = fast.next.next; + } + +/* insert the 'newNode' and adjust + the required links*/ + + newNode.next = slow.next; + slow.next = newNode; + } + } + +/* function to display the linked list*/ + + static void display() + { + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } + } + +/* Driver program to test above*/ + + public static void main (String[] args) + { +/* Creating the list 1.2.4.5*/ + + head = null; + head = new Node(1); + head.next = new Node(2); + head.next.next = new Node(4); + head.next.next.next = new Node(5); + + System.out.println(""Linked list before""+ + "" insertion: ""); + display(); + + int x = 3; + insertAtMid(x); + + System.out.println(""\nLinked list after""+ + "" insertion: ""); + display(); + } +} + + +", +Iterative program to Calculate Size of a tree,"/*Java programn to calculate +Size of a tree*/ + +import java.util.LinkedList; +import java.util.Queue; + +/*Node Structure*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +}/*return size of tree*/ + +class BinaryTree +{ + Node root; + public int size() + { + +/* if tree is empty it will + return 0*/ + + if (root == null) + return 0;/* Using level order Traversal.*/ + + Queue q = new LinkedList(); + q.offer(root); + int count = 1; + while (!q.isEmpty()) + { + Node tmp = q.poll(); +/* when the queue is empty: + the poll() method returns null.*/ + + if (tmp != null) + { + if (tmp.left != null) + { +/* Increment count*/ + + count++; +/* Enqueue left child */ + + q.offer(tmp.left); + } + if (tmp.right != null) + { +/* Increment count*/ + + count++; +/* Enqueue right child */ + + q.offer(tmp.right); + } + } + } + return count; + } +/* Driver code*/ + + public static void main(String args[]) + { + /* creating a binary tree and entering + the nodes */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println(""The size of binary tree"" + + "" is : "" + tree.size()); + } +}"," '''Python Program to calculate size of the tree iteratively''' + + '''Node Structure''' + +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None '''Return size of tree''' + +def sizeoftree(root): + ''' if tree is empty it will + return 0''' + + if root == None: + return 0 + + ''' Using level order Traversal.''' + + q = [] + q.append(root) + count = 1 + while(len(q) != 0): + root = q.pop(0) ''' when the queue is empty: + the pop() method returns null.''' + + if(root.left): + ''' Increment count''' + + + count += 1 + ''' Enqueue left child''' + + q.append(root.left) + if(root.right): ''' Increment count''' + + count += 1 + ''' Enqueue right child ''' + + q.append(root.right) + return count '''Driver Program''' + ''' creating a binary tree and entering + the nodes''' + +root = newNode(1) +root.left = newNode(2) +root.right = newNode(3) +root.left.left = newNode(4) +root.left.right = newNode(5) +print(sizeoftree(root))" +Binomial Coefficient | DP-9,"/*JAVA program for the above approach*/ + +import java.util.*; +class GFG +{ +/*Function to find binomial +coefficient*/ + +static int binomialCoeff(int n, int r) +{ + if (r > n) + return 0; + long m = 1000000007; + long inv[] = new long[r + 1]; + inv[0] = 1; + if(r+1>=2) + inv[1] = 1; +/* Getting the modular inversion + for all the numbers + from 2 to r with respect to m + here m = 1000000007*/ + + for (int i = 2; i <= r; i++) { + inv[i] = m - (m / i) * inv[(int) (m % i)] % m; + } + int ans = 1; +/* for 1/(r!) part*/ + + for (int i = 2; i <= r; i++) { + ans = (int) (((ans % m) * (inv[i] % m)) % m); + } +/* for (n)*(n-1)*(n-2)*...*(n-r+1) part*/ + + for (int i = n; i >= (n - r + 1); i--) { + ans = (int) (((ans % m) * (i % m)) % m); + } + return ans; +} +/* Driver code*/ + +public static void main(String[] args) +{ + int n = 5, r = 2; + System.out.print(""Value of C("" + n+ "", "" + r+ "") is "" + +binomialCoeff(n, r) +""\n""); +} +}"," '''Python3 program for the above approach + ''' '''Function to find binomial +coefficient''' + +def binomialCoeff(n, r): + if (r > n): + return 0 + m = 1000000007 + inv = [0 for i in range(r + 1)] + inv[0] = 1 + if(r+1>=2): + inv[1] = 1 + ''' Getting the modular inversion + for all the numbers + from 2 to r with respect to m + here m = 1000000007''' + + for i in range(2, r + 1): + inv[i] = m - (m // i) * inv[m % i] % m + ans = 1 + ''' for 1/(r!) part''' + + for i in range(2, r + 1): + ans = ((ans % m) * (inv[i] % m)) % m + ''' for (n)*(n-1)*(n-2)*...*(n-r+1) part''' + + for i in range(n, n - r, -1): + ans = ((ans % m) * (i % m)) % m + return ans + '''Driver code''' + +n = 5 +r = 2 +print(""Value of C("" ,n , "", "" , r , + "") is "",binomialCoeff(n, r))" +Find Second largest element in an array,"/*Java program to find second largest +element in an array*/ + +import java.util.*; +class GFG{ +/*Function to print the +second largest elements*/ + +static void print2largest(int arr[], + int arr_size) +{ + int i, first, second; +/* There should be + atleast two elements*/ + + if (arr_size < 2) + { + System.out.printf("" Invalid Input ""); + return; + } +/* Sort the array*/ + + Arrays.sort(arr); +/* Start from second last element + as the largest element is at last*/ + + for (i = arr_size - 2; i >= 0; i--) + { +/* If the element is not + equal to largest element*/ + + if (arr[i] != arr[arr_size - 1]) + { + System.out.printf(""The second largest "" + + ""element is %d\n"", arr[i]); + return; + } + } + System.out.printf(""There is no second "" + + ""largest element\n""); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {12, 35, 1, 10, 34, 1}; + int n = arr.length; + print2largest(arr, n); +} +}"," '''Python3 program to find second +largest element in an array + ''' '''Function to print the +second largest elements''' + +def print2largest(arr, + arr_size): + ''' There should be + atleast two elements''' + + if (arr_size < 2): + print("" Invalid Input "") + return + ''' Sort the array''' + + arr.sort + ''' Start from second last + element as the largest + element is at last''' + + for i in range(arr_size-2, + -1, -1): + ''' If the element is not + equal to largest element''' + + if (arr[i] != arr[arr_size - 1]) : + print(""The second largest element is"", + arr[i]) + return + print(""There is no second largest element"") + '''Driver code''' + +arr = [12, 35, 1, 10, 34, 1] +n = len(arr) +print2largest(arr, n)" +"Given two strings, find if first string is a subsequence of second","/*Recursive Java program to check if a string +is subsequence of another string*/ + +import java.io.*; +class SubSequence { +/* Returns true if str1[] is a subsequence of str2[] + m is length of str1 and n is length of str2*/ + + static boolean isSubSequence(String str1, String str2, + int m, int n) + { +/* Base Cases*/ + + if (m == 0) + return true; + if (n == 0) + return false; +/* If last characters of two strings are matching*/ + + if (str1.charAt(m - 1) == str2.charAt(n - 1)) + return isSubSequence(str1, str2, m - 1, n - 1); +/* If last characters are not matching*/ + + return isSubSequence(str1, str2, m, n - 1); + } +/* Driver program*/ + + public static void main(String[] args) + { + String str1 = ""gksrek""; + String str2 = ""geeksforgeeks""; + int m = str1.length(); + int n = str2.length(); + boolean res = isSubSequence(str1, str2, m, n); + if (res) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +} +"," '''Recursive Python program to check +if a string is subsequence +of another string''' + + '''Returns true if str1[] is a +subsequence of str2[].''' + +def isSubSequence(string1, string2, m, n): ''' Base Cases''' + + if m == 0: + return True + if n == 0: + return False + ''' If last characters of two + strings are matching''' + + if string1[m-1] == string2[n-1]: + return isSubSequence(string1, string2, m-1, n-1) + ''' If last characters are not matching''' + + return isSubSequence(string1, string2, m, n-1) + '''Driver program to test the above function''' + +string1 = ""gksrek"" +string2 = ""geeksforgeeks"" +if isSubSequence(string1, string2, len(string1), len(string2)): + print ""Yes"" +else: + print ""No""" +Longest Increasing Subsequence | DP-3,"/* Dynamic Programming Java implementation + of LIS problem */ + +class LIS { + /* lis() returns the length of the longest + increasing subsequence in arr[] of size n */ + + static int lis(int arr[], int n) + { + int lis[] = new int[n]; + int i, j, max = 0; + /* Initialize LIS values for all indexes */ + + for (i = 0; i < n; i++) + lis[i] = 1; + /* Compute optimized LIS values in + bottom up manner */ + + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + /* Pick maximum of all LIS values */ + + for (i = 0; i < n; i++) + if (max < lis[i]) + max = lis[i]; + return max; + } + /*Driver code*/ + +public static void main(String args[]) + { + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = arr.length; + System.out.println(""Length of lis is "" + lis(arr, n) + + ""\n""); + } +}"," '''Dynamic programming Python implementation +of LIS problem + ''' '''lis returns length of the longest +increasing subsequence in arr of size n''' + +def lis(arr): + n = len(arr) + ''' Declare the list (array) for LIS and + initialize LIS values for all indexes''' + + lis = [1]*n + ''' Compute optimized LIS values in bottom up manner''' + + for i in range(1, n): + for j in range(0, i): + if arr[i] > arr[j] and lis[i] < lis[j] + 1: + lis[i] = lis[j]+1 + ''' Initialize maximum to 0 to get + the maximum of all LIS''' + + maximum = 0 + ''' Pick maximum of all LIS values''' + + for i in range(n): + maximum = max(maximum, lis[i]) + return maximum + '''Driver program to test above function''' + +arr = [10, 22, 9, 33, 21, 50, 41, 60] +print ""Length of lis is"", lis(arr)" +Find element at given index after a number of rotations,"/*Java code to rotate an array +and answer the index query*/ + +import java.util.*; +class GFG +{ +/* Function to compute the element at + given index*/ + + static int findElement(int[] arr, int[][] ranges, + int rotations, int index) + { + for (int i = rotations - 1; i >= 0; i--) { +/* Range[left...right]*/ + + int left = ranges[i][0]; + int right = ranges[i][1]; +/* Rotation will not have any effect*/ + + if (left <= index && right >= index) { + if (index == left) + index = right; + else + index--; + } + } +/* Returning new element*/ + + return arr[index]; + } +/* Driver*/ + + public static void main (String[] args) { + int[] arr = { 1, 2, 3, 4, 5 }; +/* No. of rotations*/ + + int rotations = 2; +/* Ranges according to 0-based indexing*/ + + int[][] ranges = { { 0, 2 }, { 0, 3 } }; + int index = 1; + System.out.println(findElement(arr, ranges, + rotations, index)); + } +}"," '''Python 3 code to rotate an array +and answer the index query + ''' '''Function to compute the element +at given index''' + +def findElement(arr, ranges, rotations, index) : + for i in range(rotations - 1, -1, -1 ) : + ''' Range[left...right]''' + + left = ranges[i][0] + right = ranges[i][1] + ''' Rotation will not have + any effect''' + + if (left <= index and right >= index) : + if (index == left) : + index = right + else : + index = index - 1 + ''' Returning new element''' + + return arr[index] + '''Driver Code''' + +arr = [ 1, 2, 3, 4, 5 ] + '''No. of rotations''' + +rotations = 2 + '''Ranges according to +0-based indexing''' + +ranges = [ [ 0, 2 ], [ 0, 3 ] ] +index = 1 +print(findElement(arr, ranges, rotations, index))" +Find the number of Islands | Set 2 (Using Disjoint Set),"/*Java program to find number of islands using Disjoint +Set data structure.*/ + +import java.io.*; +import java.util.*; +public class Main +{ + +/*Class to represent Disjoint Set Data structure*/ + +class DisjointUnionSets +{ + int[] rank, parent; + int n; + public DisjointUnionSets(int n) + { + rank = new int[n]; + parent = new int[n]; + this.n = n; + makeSet(); + } + void makeSet() + { +/* Initially, all elements are in their + own set.*/ + + for (int i=0; i= 0 && a[j-1][k]==1) + dus.union(j*(m)+k, (j-1)*(m)+k); + if (k+1 < m && a[j][k+1]==1) + dus.union(j*(m)+k, (j)*(m)+k+1); + if (k-1 >= 0 && a[j][k-1]==1) + dus.union(j*(m)+k, (j)*(m)+k-1); + if (j+1=0 && a[j+1][k-1]==1) + dus.union(j*m+k, (j+1)*(m)+k-1); + if (j-1>=0 && k+1=0 && k-1>=0 && a[j-1][k-1]==1) + dus.union(j*m+k, (j-1)*m+k-1); + } + } +/* Array to note down frequency of each set*/ + + int[] c = new int[n*m]; + int numberOfIslands = 0; + for (int j=0; j= 0 and a[j - 1][k] == 1: + dus.Union(j * (m) + k, + (j - 1) * (m) + k) + if k + 1 < m and a[j][k + 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k + 1) + if k - 1 >= 0 and a[j][k - 1] == 1: + dus.Union(j * (m) + k, + (j) * (m) + k - 1) + if (j + 1 < n and k + 1 < m and + a[j + 1][k + 1] == 1): + dus.Union(j * (m) + k, (j + 1) * + (m) + k + 1) + if (j + 1 < n and k - 1 >= 0 and + a[j + 1][k - 1] == 1): + dus.Union(j * m + k, (j + 1) * + (m) + k - 1) + if (j - 1 >= 0 and k + 1 < m and + a[j - 1][k + 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k + 1) + if (j - 1 >= 0 and k - 1 >= 0 and + a[j - 1][k - 1] == 1): + dus.Union(j * m + k, (j - 1) * + m + k - 1) + ''' Array to note down frequency of each set''' + + c = [0] * (n * m) + numberOfIslands = 0 + for j in range(n): + for k in range(n): + if a[j][k] == 1: + x = dus.find(j * m + k) + ''' If frequency of set is 0, + increment numberOfIslands''' + + if c[x] == 0: + numberOfIslands += 1 + c[x] += 1 + else: + c[x] += 1 + return numberOfIslands + '''Driver Code''' + +a = [[1, 1, 0, 0, 0], + [0, 1, 0, 0, 1], + [1, 0, 0, 1, 1], + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 1]] +print(""Number of Islands is:"", countIslands(a))" +Program to check if matrix is lower triangular,"/*Java Program to check for +a lower triangular matrix.*/ + +import java.io.*; +class Lower_triangular +{ + int N = 4; +/* Function to check matrix is + in lower triangular form or not.*/ + + boolean isLowerTriangularMatrix(int mat[][]) + { + for (int i = 0; i < N; i++) + for (int j = i + 1; j < N; j++) + if (mat[i][j] != 0) + return false; + return true; + } +/* Driver function.*/ + + public static void main(String args[]) + { + Lower_triangular ob = new Lower_triangular(); + int mat[][] = { { 1, 0, 0, 0 }, + { 1, 4, 0, 0 }, + { 4, 6, 2, 0 }, + { 0, 4, 7, 6 } }; +/* Function call*/ + + if (ob.isLowerTriangularMatrix(mat)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 Program to check +lower triangular matrix.''' + + '''Function to check matrix +is in lower triangular''' + +def islowertriangular(M): + for i in range(0, len(M)): + for j in range(i + 1, len(M)): + if(M[i][j] != 0): + return False + return True '''Driver function.''' + +M = [[1,0,0,0], + [1,4,0,0], + [4,6,2,0], + [0,4,7,6]] + '''Function call''' + +if islowertriangular(M): + print (""Yes"") +else: + print (""No"")" +Find row number of a binary matrix having maximum number of 1s,"/*Java program to find row with maximum 1 +in row sorted binary matrix*/ + +class GFG { + static final int N = 4; +/* function for finding row with maximum 1*/ + + static void findMax(int arr[][]) { + int row = 0, i, j; + for (i = 0, j = N - 1; i < N; i++) { +/* find left most position of 1 in + a row find 1st zero in a row*/ + + while (j >= 0 && arr[i][j] == 1) { + row = i; + j--; + } + } + System.out.print(""Row number = "" + + (row + 1)); + System.out.print("", MaxCount = "" + + (N - 1 - j)); + } +/* Driver code*/ + + public static void main(String[] args) { + int arr[][] = {{0, 0, 0, 1}, + {0, 0, 0, 1}, + {0, 0, 0, 0}, + {0, 1, 1, 1}}; + findMax(arr); + } +}"," '''python program to find row with +maximum 1 in row sorted binary +matrix''' + +N = 4 + '''function for finding row with +maximum 1''' + +def findMax (arr): + row = 0 + j = N - 1 + for i in range(0, N): + ''' find left most position + of 1 in a row find 1st + zero in a row''' + + while (arr[i][j] == 1 + and j >= 0): + row = i + j -= 1 + print(""Row number = "" , row + 1, + "", MaxCount = "", N - 1 - j) + '''driver program''' + +arr = [ [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 0], + [0, 1, 1, 1] ] +findMax(arr)" +Creating a tree with Left-Child Right-Sibling Representation,"/*Java program to create a tree with left child +right sibling representation.*/ + +class GFG { +/*Creating new Node*/ + + static class NodeTemp + { + int data; + NodeTemp next, child; + public NodeTemp(int data) + { + this.data = data; + next = child = null; + } + } +/* Adds a sibling to a list with starting with n*/ + + static public NodeTemp addSibling(NodeTemp node, int data) + { + if(node == null) + return null; + while(node.next != null) + node = node.next; + return(node.next = new NodeTemp(data)); + } +/* Add child Node to a Node*/ + + static public NodeTemp addChild(NodeTemp node,int data) + { + if(node == null) + return null; +/* Check if child is not empty.*/ + + if(node.child != null) + return(addSibling(node.child,data)); + else + return(node.child = new NodeTemp(data)); + } +/* Traverses tree in depth first order*/ + + static public void traverseTree(NodeTemp root) + { + if(root == null) + return; + while(root != null) + { + System.out.print(root.data + "" ""); + if(root.child != null) + traverseTree(root.child); + root = root.next; + } + } +/* Driver code*/ + + public static void main(String args[]) + { + NodeTemp root = new NodeTemp(10); + NodeTemp n1 = addChild(root,2); + NodeTemp n2 = addChild(root,3); + NodeTemp n3 = addChild(root,4); + NodeTemp n4 = addChild(n3,6); + NodeTemp n5 = addChild(root,5); + NodeTemp n6 = addChild(n5,7); + NodeTemp n7 = addChild(n5,8); + NodeTemp n8 = addChild(n5,9); + traverseTree(root); + } +}"," '''Python3 program to create a tree with +left child right sibling representation.''' + + '''Creating new Node''' + +class newNode: + def __init__(self, data): + self.Next = self.child = None + self.data = data '''Adds a sibling to a list with +starting with n''' + +def addSibling(n, data): + if (n == None): + return None + while (n.Next): + n = n.Next + n.Next = newNode(data) + return n.Next + '''Add child Node to a Node''' + +def addChild(n, data): + if (n == None): + return None + ''' Check if child list is not empty.''' + + if (n.child): + return addSibling(n.child, data) + else: + n.child = newNode(data) + return n.child + '''Traverses tree in depth first order''' + +def traverseTree(root): + if (root == None): + return + while (root): + print(root.data, end = "" "") + if (root.child): + traverseTree(root.child) + root = root.Next + '''Driver code''' + +if __name__ == '__main__': + root = newNode(10) + n1 = addChild(root, 2) + n2 = addChild(root, 3) + n3 = addChild(root, 4) + n4 = addChild(n3, 6) + n5 = addChild(root, 5) + n6 = addChild(n5, 7) + n7 = addChild(n5, 8) + n8 = addChild(n5, 9) + traverseTree(root)" +Check if all leaves are at same level,"/*Java program to check if all leaf nodes are at +same level of binary tree*/ + +import java.util.*; +/*User defined node class*/ + +class Node { + int data; + Node left, right; +/* Constructor to create a new tree node*/ + + Node(int key) { + int data = key; + left = right = null; + } +} +class GFG { +/* return true if all leaf nodes are + at same level, else false*/ + + static boolean checkLevelLeafNode(Node root) + { + if (root == null) + return true; +/* create a queue for level order traversal*/ + + Queue q = new LinkedList<>(); + q.add(root); + int result = Integer.MAX_VALUE; + int level = 0; +/* traverse until the queue is empty*/ + + while (q.size() != 0) { + int size = q.size(); + level++; +/* traverse for complete level*/ + + while (size > 0) { + Node temp = q.remove(); +/* check for left child*/ + + if (temp.left != null) { + q.add(temp.left); +/* if its leaf node*/ + + if (temp.left.left == null && temp.left.right == null) { +/* if it's first leaf node, then update result*/ + + if (result == Integer.MAX_VALUE) + result = level; +/* if it's not first leaf node, then compare + the level with level of previous leaf node.*/ + + else if (result != level) + return false; + } + } +/* check for right child*/ + + if (temp.right != null) { + q.add(temp.right); +/* if its leaf node*/ + + if (temp.right.left == null && temp.right.right == null) { +/* if it's first leaf node, then update result*/ + + if (result == Integer.MAX_VALUE) + result = level; +/* if it's not first leaf node, then compare + the level with level of previous leaf node.*/ + + else if (result != level) + return false; + } + } + size--; + } + } + return true; + } +/* Driver code*/ + + public static void main(String args[]) + { +/* construct a tree*/ + + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.left.right = new Node(4); + root.right.left = new Node(5); + root.right.right = new Node(6); + boolean result = checkLevelLeafNode(root); + if (result == true) + System.out.println(""All leaf nodes are at same level""); + else + System.out.println(""Leaf nodes not at same level""); + } +}"," '''Python3 program to check if all leaf nodes +are at same level of binary tree''' + +INT_MAX = 2**31 +INT_MIN = -2**31 + '''Tree Node +returns a new tree Node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''return true if all leaf nodes are +at same level, else false''' + +def checkLevelLeafNode(root) : + if (not root) : + return 1 + ''' create a queue for level + order traversal''' + + q = [] + q.append(root) + result = INT_MAX + level = 0 + ''' traverse until the queue is empty''' + + while (len(q)): + size = len(q) + level += 1 + ''' traverse for complete level''' + + while(size > 0 or len(q)): + temp = q[0] + q.pop(0) + ''' check for left child''' + + if (temp.left) : + q.append(temp.left) + ''' if its leaf node''' + + if(not temp.left.right and + not temp.left.left): + ''' if it's first leaf node, + then update result''' + + if (result == INT_MAX): + result = level + ''' if it's not first leaf node, + then compare the level with + level of previous leaf node''' + + elif (result != level): + return 0 + ''' check for right child''' + + if (temp.right) : + q.append(temp.right) + ''' if it's leaf node''' + + if (not temp.right.left and + not temp.right.right): + ''' if it's first leaf node till now, + then update the result''' + + if (result == INT_MAX): + result = level + ''' if it is not the first leaf node, + then compare the level with level + of previous leaf node''' + + elif(result != level): + return 0 + size -= 1 + return 1 + '''Driver Code''' + +if __name__ == '__main__': + ''' construct a tree''' + + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.right = newNode(4) + root.right.left = newNode(5) + root.right.right = newNode(6) + result = checkLevelLeafNode(root) + if (result) : + print(""All leaf nodes are at same level"") + else: + print(""Leaf nodes not at same level"")" +Median of two sorted arrays of same size,"/*A Java program to divide and conquer based +efficient solution to find +median of two sorted arrays +of same size.*/ + +import java.util.*; +class GfG { + /* This function returns median + of ar1[] and ar2[]. + Assumptions in this function: + Both ar1[] and ar2[] are + sorted arrays + Both have n elements */ + + static int getMedian( + int[] a, int[] b, int startA, + int startB, int endA, int endB) + { + if (endA - startA == 1) { + return ( + Math.max(a[startA], + b[startB]) + + Math.min(a[endA], b[endB])) + / 2; + } + /* get the median of + the first array */ + + int m1 = median(a, startA, endA); + /* get the median of + the second array */ + + int m2 = median(b, startB, endB); + /* If medians are equal then + return either m1 or m2 */ + + if (m1 == m2) { + return m1; + } + /* if m1 < m2 then median must + exist in ar1[m1....] and + ar2[....m2] */ + + else if (m1 < m2) { + return getMedian( + a, b, (endA + startA + 1) / 2, + startB, endA, + (endB + startB + 1) / 2); + } + /* if m1 > m2 then median must + exist in ar1[....m1] and + ar2[m2...] */ + + else { + return getMedian( + a, b, startA, + (endB + startB + 1) / 2, + (endA + startA + 1) / 2, endB); + } + } + /* Function to get median + of a sorted array */ + + static int median( + int[] arr, int start, int end) + { + int n = end - start + 1; + if (n % 2 == 0) { + return ( + arr[start + (n / 2)] + + arr[start + (n / 2 - 1)]) + / 2; + } + else { + return arr[start + n / 2]; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int ar1[] = { 1, 2, 3, 6 }; + int ar2[] = { 4, 6, 8, 10 }; + int n1 = ar1.length; + int n2 = ar2.length; + if (n1 != n2) { + System.out.println( + ""Doesn't work for arrays "" + + ""of unequal size""); + } + else if (n1 == 0) { + System.out.println(""Arrays are empty.""); + } + else if (n1 == 1) { + System.out.println((ar1[0] + ar2[0]) / 2); + } + else { + System.out.println( + ""Median is "" + + getMedian( + ar1, ar2, 0, 0, + ar1.length - 1, ar2.length - 1)); + } + } +}", +Ceiling in a sorted array,"class Main +{ + /* Function to get index of + ceiling of x in arr[low..high]*/ + + static int ceilSearch(int arr[], int low, int high, int x) + { + int mid; + /* If x is smaller than or equal to the + first element, then return the first element */ + + if(x <= arr[low]) + return low; + /* If x is greater than the last + element, then return -1 */ + + if(x > arr[high]) + return -1; + /* get the index of middle element + of arr[low..high]*/ + + mid = (low + high)/2; /* If x is same as middle element, + then return mid */ + + if(arr[mid] == x) + return mid; + /* If x is greater than arr[mid], then + either arr[mid + 1] is ceiling of x or + ceiling lies in arr[mid+1...high] */ + + else if(arr[mid] < x) + { + if(mid + 1 <= high && x <= arr[mid+1]) + return mid + 1; + else + return ceilSearch(arr, mid+1, high, x); + } + /* If x is smaller than arr[mid], + then either arr[mid] is ceiling of x + or ceiling lies in arr[low...mid-1] */ + + else + { + if(mid - 1 >= low && x > arr[mid-1]) + return mid; + else + return ceilSearch(arr, low, mid - 1, x); + } + } + /* Driver program to check above functions */ + + public static void main (String[] args) + { + int arr[] = {1, 2, 8, 10, 10, 12, 19}; + int n = arr.length; + int x = 8; + int index = ceilSearch(arr, 0, n-1, x); + if(index == -1) + System.out.println(""Ceiling of ""+x+"" doesn't exist in array""); + else + System.out.println(""ceiling of ""+x+"" is ""+arr[index]); + } +}"," '''''' '''Function to get index of ceiling of x in arr[low..high]*/''' + +def ceilSearch(arr, low, high, x): + ''' If x is smaller than or equal to the first element, + then return the first element */''' + + if x <= arr[low]: + return low + ''' If x is greater than the last element, then return -1 */''' + + if x > arr[high]: + return -1 + ''' get the index of middle element of arr[low..high]*/ +low + (high - low)/2 */''' + + mid = (low + high)/2; + ''' If x is same as middle element, then return mid */''' + + if arr[mid] == x: + return mid + ''' If x is greater than arr[mid], then either arr[mid + 1] + is ceiling of x or ceiling lies in arr[mid+1...high] */''' + + elif arr[mid] < x: + if mid + 1 <= high and x <= arr[mid+1]: + return mid + 1 + else: + return ceilSearch(arr, mid+1, high, x) + ''' If x is smaller than arr[mid], then either arr[mid] + is ceiling of x or ceiling lies in arr[low...mid-1] */ ''' + + else: + if mid - 1 >= low and x > arr[mid-1]: + return mid + else: + return ceilSearch(arr, low, mid - 1, x) + '''Driver program to check above functions */''' + +arr = [1, 2, 8, 10, 10, 12, 19] +n = len(arr) +x = 20 +index = ceilSearch(arr, 0, n-1, x); +if index == -1: + print (""Ceiling of %d doesn't exist in array ""% x) +else: + print (""ceiling of %d is %d""%(x, arr[index]))" +Find next Smaller of next Greater in an array,"/*Java Program to find Right smaller element of next +greater element*/ + +import java.util.Stack; +public class Main { +/* function find Next greater element*/ + + public static void nextGreater(int arr[], int next[], char order) + { +/* create empty stack*/ + + Stack stack=new Stack<>(); +/* Traverse all array elements in reverse order + order == 'G' we compute next greater elements of + every element + order == 'S' we compute right smaller element of + every element*/ + + for (int i=arr.length-1; i>=0; i--) + { +/* Keep removing top element from S while the top + element is smaller then or equal to arr[i] (if Key is G) + element is greater then or equal to arr[i] (if order is S)*/ + + while (!stack.isEmpty() && ((order=='G')? arr[stack.peek()] <= arr[i]:arr[stack.peek()] >= arr[i])) + stack.pop(); +/* store the next greater element of current element*/ + + if (!stack.isEmpty()) + next[i] = stack.peek(); +/* If all elements in S were smaller than arr[i]*/ + + else + next[i] = -1; +/* Push this element*/ + + stack.push(i); + } + } +/* Function to find Right smaller element of next greater + element*/ + + public static void nextSmallerOfNextGreater(int arr[]) + { +/*stores indexes of next greater elements*/ + +int NG[]=new int[arr.length]; +/*stores indexes of right smaller elements*/ + +int RS[]=new int[arr.length]; +/* Find next greater element + Here G indicate next greater element*/ + + nextGreater(arr, NG, 'G'); +/* Find right smaller element + using same function nextGreater() + Here S indicate right smaller elements*/ + + nextGreater(arr, RS, 'S'); +/* If NG[i] == -1 then there is no smaller element + on right side. We can find Right smaller of next + greater by arr[RS[NG[i]]]*/ + + for (int i=0; i< arr.length; i++) + { + if (NG[i] != -1 && RS[NG[i]] != -1) + System.out.print(arr[RS[NG[i]]]+"" ""); + else + System.out.print(""-1 ""); + } + } +/* Driver code*/ + + public static void main(String args[]) { + int arr[] = {5, 1, 9, 2, 5, 1, 7}; + nextSmallerOfNextGreater(arr); + } +}"," '''Python 3 Program to find Right smaller element of next +greater element''' + '''function find Next greater element''' + +def nextGreater(arr, n, next, order): + + '''create empty stack''' + + S = [] ''' Traverse all array elements in reverse order + order == 'G' we compute next greater elements of + every element + order == 'S' we compute right smaller element of + every element''' + + for i in range(n-1,-1,-1): + ''' Keep removing top element from S while the top + element is smaller then or equal to arr[i] (if Key is G) + element is greater then or equal to arr[i] (if order is S)''' + + while (S!=[] and (arr[S[len(S)-1]] <= arr[i] + if (order=='G') else arr[S[len(S)-1]] >= arr[i] )): + S.pop() + ''' store the next greater element of current element''' + + if (S!=[]): + next[i] = S[len(S)-1] + ''' If all elements in S were smaller than arr[i]''' + + else: + next[i] = -1 + ''' Push this element''' + + S.append(i) + '''Function to find Right smaller element of next greater +element''' + +def nextSmallerOfNextGreater(arr, n): + ''' stores indexes of next greater elements''' + + NG = [None]*n + + '''stores indexes of right smaller elements''' + + RS = [None]*n + ''' Find next greater element + Here G indicate next greater element''' + + nextGreater(arr, n, NG, 'G') + ''' Find right smaller element + using same function nextGreater() + Here S indicate right smaller elements''' + + nextGreater(arr, n, RS, 'S') + ''' If NG[i] == -1 then there is no smaller element + on right side. We can find Right smaller of next + greater by arr[RS[NG[i]]]''' + + for i in range(n): + if (NG[i] != -1 and RS[NG[i]] != -1): + print(arr[RS[NG[i]]],end="" "") + else: + print(""-1"",end="" "") + '''Driver program''' + +if __name__==""__main__"": + arr = [5, 1, 9, 2, 5, 1, 7] + n = len(arr) + nextSmallerOfNextGreater(arr, n)" +Find the element that appears once in an array where every other element appears twice,"/*Java program to find the array +element that appears only once*/ + +class MaxSum +{ +/* Return the maximum Sum of difference + between consecutive elements.*/ + + static int findSingle(int ar[], int ar_size) + { +/* Do XOR of all elements and return*/ + + int res = ar[0]; + for (int i = 1; i < ar_size; i++) + res = res ^ ar[i]; + + return res; + } + +/* Driver code*/ + + public static void main (String[] args) + { + int ar[] = {2, 3, 5, 4, 5, 3, 4}; + int n = ar.length; + System.out.println(""Element occurring once is "" + + findSingle(ar, n) + "" ""); + } +} + +"," '''function to find the once +appearing element in array''' + +def findSingle( ar, n): + + + + ''' Do XOR of all elements and return''' + res = ar[0] + for i in range(1,n): + res = res ^ ar[i] + + return res + + '''Driver code''' + +ar = [2, 3, 5, 4, 5, 3, 4] +print ""Element occurring once is"", findSingle(ar, len(ar)) + + +" +Print all nodes at distance k from a given node,"/*Java program to print all nodes at a distance k from given node*/ + + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + /* Recursive function to print all the nodes at distance k in + tree (or subtree) rooted with given root. */ + + + void printkdistanceNodeDown(Node node, int k) + { +/* Base Case*/ + + if (node == null || k < 0) + return; + +/* If we reach a k distant node, print it*/ + + if (k == 0) + { + System.out.print(node.data); + System.out.println(""""); + return; + } + +/* Recur for left and right subtrees*/ + + printkdistanceNodeDown(node.left, k - 1); + printkdistanceNodeDown(node.right, k - 1); + } + +/* 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.*/ + + int printkdistanceNode(Node node, Node target, int k) + { +/* Base Case 1: If tree is empty, return -1*/ + + if (node == null) + 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*/ + + if (node == target) + { + printkdistanceNodeDown(node, k); + return 0; + } + +/* Recur for left subtree*/ + + int dl = printkdistanceNode(node.left, target, k); + +/* Check if target node was found in left subtree*/ + + if (dl != -1) + { + +/* If root is at distance k from target, print root + Note that dl is Distance of root's left child from + target*/ + + if (dl + 1 == k) + { + System.out.print(node.data); + System.out.println(""""); + } + +/* 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*/ + + else + printkdistanceNodeDown(node.right, k - dl - 2); + +/* Add 1 to the distance and return value for parent calls*/ + + return 1 + dl; + } + +/* MIRROR OF ABOVE CODE FOR RIGHT SUBTREE + Note that we reach here only when node was not found in left + subtree*/ + + int dr = printkdistanceNode(node.right, target, k); + if (dr != -1) + { + if (dr + 1 == k) + { + System.out.print(node.data); + System.out.println(""""); + } + else + printkdistanceNodeDown(node.left, k - dr - 2); + return 1 + dr; + } + +/* If target was neither present in left nor in right subtree*/ + + return -1; + } + +/* Driver program to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + + /* Let us construct the tree shown in above diagram */ + + tree.root = new Node(20); + tree.root.left = new Node(8); + tree.root.right = new Node(22); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(12); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(14); + Node target = tree.root.left.right; + tree.printkdistanceNode(tree.root, target, 2); + } +} + + +"," '''Python program to print nodes at distance k from a given node''' + + + '''A binary tree node''' + +class Node: + + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Recursive function to print all the nodes at distance k +int the tree(or subtree) rooted with given root. See''' + +def printkDistanceNodeDown(root, k): + + ''' Base Case''' + + if root is None or k< 0 : + return + + ''' If we reach a k distant node, print it''' + + if k == 0 : + print root.data + return + + ''' Recur for left and right subtee''' + + printkDistanceNodeDown(root.left, k-1) + printkDistanceNodeDown(root.right, k-1) + + + '''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''' + +def printkDistanceNode(root, target, k): + + ''' Base Case 1 : IF tree is empty return -1''' + + if root is None: + 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''' + + if root == target: + printkDistanceNodeDown(root, k) + return 0 + + ''' Recur for left subtree''' + + dl = printkDistanceNode(root.left, target, k) + + ''' Check if target node was found in left subtree''' + + if dl != -1: + + ''' If root is at distance k from target, print root + Note: dl is distance of root's left child + from target''' + + if dl +1 == k : + print root.data + + ''' Else go to right subtreee and print all k-dl-2 + distant nodes + Note: that the right child is 2 edges away from + left chlid''' + + else: + printkDistanceNodeDown(root.right, k-dl-2) + + ''' Add 1 to the distance and return value for + for parent calls''' + + return 1 + dl + + ''' MIRROR OF ABOVE CODE FOR RIGHT SUBTREE + Note that we reach here only when node was not found + in left subtree''' + + dr = printkDistanceNode(root.right, target, k) + if dr != -1: + if (dr+1 == k): + print root.data + else: + printkDistanceNodeDown(root.left, k-dr-2) + return 1 + dr + + ''' If target was neither present in left nor in right subtree''' + + return -1 + + '''Driver program to test above function''' + + + '''Let us construct the tree shown in above diagram ''' + +root = Node(20) +root.left = Node(8) +root.right = Node(22) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) +target = root.left.right +printkDistanceNode(root, target, 2) + " +Print all possible strings that can be made by placing spaces,"/*Java program to print permutations +of a given string with +spaces*/ + +import java.io.*; +class Permutation +{ +/* Function recursively prints + the strings having space + pattern i and j are indices in 'String str' and + 'buf[]' respectively*/ + + static void printPatternUtil(String str, char buf[], + int i, int j, int n) + { + if (i == n) + { + buf[j] = '\0'; + System.out.println(buf); + return; + } +/* Either put the character*/ + + buf[j] = str.charAt(i); + printPatternUtil(str, buf, i + 1, + j + 1, n); +/* Or put a space followed + by next character*/ + + buf[j] = ' '; + buf[j + 1] = str.charAt(i); + printPatternUtil(str, buf, i + 1, + j + 2, n); + } +/* Function creates buf[] to + store individual output + string and uses printPatternUtil() + to print all + permutations*/ + + static void printPattern(String str) + { + int len = str.length(); +/* Buffer to hold the string + containing spaces + 2n-1 characters and 1 + string terminator*/ + + char[] buf = new char[2 * len]; +/* Copy the first character as it is, since it will + be always at first position*/ + + buf[0] = str.charAt(0); + printPatternUtil(str, buf, 1, 1, len); + } +/* Driver program*/ + + public static void main(String[] args) + { + String str = ""ABCD""; + printPattern(str); + } +}", +Find the largest rectangle of 1's with swapping of columns allowed,"/*Java program to find the largest rectangle of +1's with swapping of columns allowed.*/ + +class GFG { + static final int R = 3; + static final int C = 5; +/* Returns area of the largest rectangle of 1's*/ + + static int maxArea(int mat[][]) + { +/* An auxiliary array to store count of consecutive 1's + in every column.*/ + + int hist[][] = new int[R + 1][C + 1]; +/* Step 1: Fill the auxiliary array hist[][]*/ + + for (int i = 0; i < C; i++) + { +/* First row in hist[][] is copy of first row in mat[][]*/ + + hist[0][i] = mat[0][i]; +/* Fill remaining rows of hist[][]*/ + + for (int j = 1; j < R; j++) + { + hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1; + } + } +/* Step 2: Sort rows of hist[][] in non-increasing order*/ + + for (int i = 0; i < R; i++) + { + int count[] = new int[R + 1]; +/* counting occurrence*/ + + for (int j = 0; j < C; j++) + { + count[hist[i][j]]++; + } +/* Traverse the count array from right side*/ + + int col_no = 0; + for (int j = R; j >= 0; j--) + { + if (count[j] > 0) + { + for (int k = 0; k < count[j]; k++) + { + hist[i][col_no] = j; + col_no++; + } + } + } + } +/* Step 3: Traverse the sorted hist[][] to find maximum area*/ + + int curr_area, max_area = 0; + for (int i = 0; i < R; i++) + { + for (int j = 0; j < C; j++) + { +/* Since values are in decreasing order, + The area ending with cell (i, j) can + be obtained by multiplying column number + with value of hist[i][j]*/ + + curr_area = (j + 1) * hist[i][j]; + if (curr_area > max_area) + { + max_area = curr_area; + } + } + } + return max_area; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int mat[][] = {{0, 1, 0, 1, 0}, + {0, 1, 0, 1, 1}, + {1, 1, 0, 1, 0}}; + System.out.println(""Area of the largest rectangle is "" + maxArea(mat)); + } +}"," '''Python 3 program to find the largest +rectangle of 1's with swapping +of columns allowed.''' + +R = 3 +C = 5 + '''Returns area of the largest +rectangle of 1's''' + +def maxArea(mat): + ''' An auxiliary array to store count + of consecutive 1's in every column.''' + + hist = [[0 for i in range(C + 1)] + for i in range(R + 1)] + ''' Step 1: Fill the auxiliary array hist[][]''' + + for i in range(0, C, 1): + ''' First row in hist[][] is copy of + first row in mat[][]''' + + hist[0][i] = mat[0][i] + ''' Fill remaining rows of hist[][]''' + + for j in range(1, R, 1): + if ((mat[j][i] == 0)): + hist[j][i] = 0 + else: + hist[j][i] = hist[j - 1][i] + 1 + ''' Step 2: Sort rows of hist[][] in + non-increasing order''' + + for i in range(0, R, 1): + count = [0 for i in range(R + 1)] + ''' counting occurrence''' + + for j in range(0, C, 1): + count[hist[i][j]] += 1 + ''' Traverse the count array from + right side''' + + col_no = 0 + j = R + while(j >= 0): + if (count[j] > 0): + for k in range(0, count[j], 1): + hist[i][col_no] = j + col_no += 1 + j -= 1 + ''' Step 3: Traverse the sorted hist[][] + to find maximum area''' + + max_area = 0 + for i in range(0, R, 1): + for j in range(0, C, 1): + ''' Since values are in decreasing order, + The area ending with cell (i, j) can + be obtained by multiplying column number + with value of hist[i][j]''' + + curr_area = (j + 1) * hist[i][j] + if (curr_area > max_area): + max_area = curr_area + return max_area + '''Driver Code''' + +if __name__ == '__main__': + mat = [[0, 1, 0, 1, 0], + [0, 1, 0, 1, 1], + [1, 1, 0, 1, 0]] + print(""Area of the largest rectangle is"", + maxArea(mat))" +Program for nth Catalan Number,"class CatalnNumber { +/* A recursive function to find nth catalan number*/ + + int catalan(int n) + { + +/* Base case*/ + + if (n <= 1) + { + return 1; + } +/* catalan(n) is sum of + catalan(i)*catalan(n-i-1)*/ + + int res = 0; + for (int i = 0; i < n; i++) + { + res += catalan(i) + * catalan(n - i - 1); + } + return res; + } +/* Driver Code*/ + + public static void main(String[] args) + { + CatalnNumber cn = new CatalnNumber(); + for (int i = 0; i < 10; i++) + { + System.out.print(cn.catalan(i) + "" ""); + } + } +}"," '''A recursive function to +find nth catalan number''' + +def catalan(n): + ''' Base Case''' + + if n <= 1: + return 1 + ''' Catalan(n) is the sum + of catalan(i)*catalan(n-i-1)''' + + res = 0 + for i in range(n): + res += catalan(i) * catalan(n-i-1) + return res + '''Driver Code''' + +for i in range(10): + print catalan(i)," +Construct the full k-ary tree from its preorder traversal,"/*Java program to build full k-ary tree from +its preorder traversal and to print the +postorder traversal of the tree.*/ + +import java.util.*; +class GFG +{ +/*Structure of a node of an n-ary tree*/ + +static class Node +{ + int key; + Vector child; +}; +/*Utility function to create a new tree +node with k children*/ + +static Node newNode(int value) +{ + Node nNode = new Node(); + nNode.key = value; + nNode.child= new Vector(); + return nNode; +} +static int ind; +/*Function to build full k-ary tree*/ + +static Node BuildKaryTree(int A[], int n, + int k, int h) +{ +/* For null tree*/ + + if (n <= 0) + return null; + Node nNode = newNode(A[ind]); + if (nNode == null) + { + System.out.println(""Memory error"" ); + return null; + } +/* For adding k children to a node*/ + + for (int i = 0; i < k; i++) + { +/* Check if ind is in range of array + Check if height of the tree is greater than 1*/ + + if (ind < n - 1 && h > 1) + { + ind++; +/* Recursively add each child*/ + + nNode.child.add(BuildKaryTree(A, n, k, h - 1)); + } + else + { + nNode.child.add(null); + } + } + return nNode; +} +/*Function to find the height of the tree*/ + +static Node BuildKaryTree_1(int[] A, int n, int k, int in) +{ + int height = (int)Math.ceil(Math.log((double)n * (k - 1) + 1) / + Math.log((double)k)); + ind = in; + return BuildKaryTree(A, n, k, height); +} +/*Function to print postorder traversal of the tree*/ + +static void postord(Node root, int k) +{ + if (root == null) + return; + for (int i = 0; i < k; i++) + postord(root.child.get(i), k); + System.out.print(root.key + "" ""); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int ind = 0; + int k = 3, n = 10; + int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; + Node root = BuildKaryTree_1(preorder, n, k, ind); + System.out.println(""Postorder traversal of "" + + ""constructed full k-ary tree is: ""); + postord(root, k); + System.out.println(); +} +}"," '''Python3 program to build full k-ary tree +from its preorder traversal and to print the +postorder traversal of the tree. ''' + +from math import ceil, log + '''Utility function to create a new +tree node with k children ''' + +class newNode: + def __init__(self, value): + self.key = value + self.child = [] + '''Function to build full k-ary tree ''' + +def BuildkaryTree(A, n, k, h, ind): + ''' For None tree ''' + + if (n <= 0): + return None + nNode = newNode(A[ind[0]]) + if (nNode == None): + print(""Memory error"") + return None + ''' For adding k children to a node''' + + for i in range(k): + ''' Check if ind is in range of array + Check if height of the tree is + greater than 1 ''' + + if (ind[0] < n - 1 and h > 1): + ind[0] += 1 + ''' Recursively add each child ''' + + nNode.child.append(BuildkaryTree(A, n, k, + h - 1, ind)) + else: + nNode.child.append(None) + return nNode + '''Function to find the height of the tree ''' + +def BuildKaryTree(A, n, k, ind): + height = int(ceil(log(float(n) * (k - 1) + 1) / + log(float(k)))) + return BuildkaryTree(A, n, k, height, ind) + '''Function to prpostorder traversal +of the tree ''' + +def postord(root, k): + if (root == None): + return + for i in range(k): + postord(root.child[i], k) + print(root.key, end = "" "") + '''Driver Code''' + +if __name__ == '__main__': + ind = [0] + k = 3 + n = 10 + preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4] + root = BuildKaryTree(preorder, n, k, ind) + print(""Postorder traversal of constructed"", + ""full k-ary tree is: "") + postord(root, k)" +Trapping Rain Water,"/*Java implementation of the approach*/ + +import java.util.*; + +class GFG +{ + + static int maxWater(int[] arr, int n) + { + +/* indices to traverse the array*/ + + int left = 0; + int right = n - 1; + +/* To store Left max and right max + for two pointers left and right*/ + + int l_max = 0; + int r_max = 0; + +/* To store the total amount + of rain water trapped*/ + + int result = 0; + while (left <= right) + { + +/* We need check for minimum of left + and right max for each element*/ + + if(r_max <= l_max) + { + +/* Add the difference between + current value and right max at index r*/ + + result += Math.max(0, r_max-arr[right]); + +/* Update right max*/ + + r_max = Math.max(r_max, arr[right]); + +/* Update right pointer*/ + + right -= 1; + } + else + { + +/* Add the difference between + current value and left max at index l*/ + + result += Math.max(0, l_max-arr[left]); + +/* Update left max*/ + + l_max = Math.max(l_max, arr[left]); + +/* Update left pointer*/ + + left += 1; + } + } + return result; + } + +/* Driver code*/ + + public static void main(String []args) + { + int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; + int n = arr.length; + System.out.print(maxWater(arr, n)); + } +} + + +"," '''Function to return the maximum +water that can be stored''' + + + +def maxWater(arr, n): + ''' indices to traverse the array''' + + left = 0 + right = n-1 + + ''' To store Left max and right max + for two pointers left and right''' + + l_max = 0 + r_max = 0 + + ''' To store the total amount + of rain water trapped''' + + result = 0 + while (left <= right): + + ''' We need check for minimum of left + and right max for each element''' + + if r_max <= l_max: + + ''' Add the difference between + current value and right max at index r''' + + result += max(0, r_max-arr[right]) + + ''' Update right max''' + + r_max = max(r_max, arr[right]) + + ''' Update right pointer''' + + right -= 1 + else: + + ''' Add the difference between + current value and left max at index l''' + + result += max(0, l_max-arr[left]) + + ''' Update left max''' + + l_max = max(l_max, arr[left]) + + ''' Update left pointer''' + + left += 1 + return result + + + '''Driver code''' + +arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] +n = len(arr) +print(maxWater(arr, n)) + + +" +Position of rightmost set bit,"/*Java program to find the +first rightmost set bit +using XOR operator*/ + +class GFG { +/* function to find + the rightmost set bit*/ + + static int PositionRightmostSetbit(int n) + { +/* Position variable initialize + with 1 m variable is used to + check the set bit*/ + + int position = 1; + int m = 1; + while ((n & m) == 0) { +/* left shift*/ + + m = m << 1; + position++; + } + return position; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int n = 16; +/* function call*/ + + System.out.println(PositionRightmostSetbit(n)); + } +}"," '''Python3 program to find +the first rightmost set +bit using XOR operator''' + + '''function to find the +rightmost set bit''' + +def PositionRightmostSetbit(n): ''' Position variable initialize + with 1 m variable is used + to check the set bit''' + + position = 1 + m = 1 + while (not(n & m)) : + ''' left shift''' + + m = m << 1 + position += 1 + return position + '''Driver Code''' + +n = 16 + '''function call''' + +print(PositionRightmostSetbit(n))" +Form minimum number from given sequence,"/*Java program to print minimum number that can be formed +from a given sequence of Is and Ds*/ + +class GFG +{ +/* Prints the minimum number that can be formed from + input sequence of I's and D's*/ + + static void PrintMinNumberForPattern(String arr) + { +/* Initialize current_max (to make sure that + we don't use repeated character*/ + + int curr_max = 0; +/* Initialize last_entry (Keeps track for + last printed digit)*/ + + int last_entry = 0; + int j; +/* Iterate over input array*/ + + for (int i = 0; i < arr.length(); i++) + { +/* Initialize 'noOfNextD' to get count of + next D's available*/ + + int noOfNextD = 0; + switch (arr.charAt(i)) + { + case 'I': +/* If letter is 'I' + Calculate number of next consecutive D's + available*/ + + j = i + 1; + while (j < arr.length() && arr.charAt(j) == 'D') + { + noOfNextD++; + j++; + } + if (i == 0) + { + curr_max = noOfNextD + 2; +/* If 'I' is first letter, print incremented + sequence from 1*/ + + System.out.print("" "" + ++last_entry); + System.out.print("" "" + curr_max); +/* Set max digit reached*/ + + last_entry = curr_max; + } + else + { +/* If not first letter + Get next digit to print*/ + + curr_max = curr_max + noOfNextD + 1; +/* Print digit for I*/ + + last_entry = curr_max; + System.out.print("" "" + last_entry); + } +/* For all next consecutive 'D' print + decremented sequence*/ + + for (int k = 0; k < noOfNextD; k++) + { + System.out.print("" "" + --last_entry); + i++; + } + break; +/* If letter is 'D'*/ + + case 'D': + if (i == 0) + { +/* If 'D' is first letter in sequence + Find number of Next D's available*/ + + j = i + 1; + while (j < arr.length()&&arr.charAt(j) == 'D') + { + noOfNextD++; + j++; + } +/* Calculate first digit to print based on + number of consecutive D's*/ + + curr_max = noOfNextD + 2; +/* Print twice for the first time*/ + + System.out.print("" "" + curr_max + "" "" + (curr_max - 1)); +/* Store last entry*/ + + last_entry = curr_max - 1; + } + else + { +/* If current 'D' is not first letter + Decrement last_entry*/ + + System.out.print("" "" + (last_entry - 1)); + last_entry--; + } + break; + } + } + System.out.println(); + } +/* Driver code*/ + + public static void main(String[] args) + { + PrintMinNumberForPattern(""IDID""); + PrintMinNumberForPattern(""I""); + PrintMinNumberForPattern(""DD""); + PrintMinNumberForPattern(""II""); + PrintMinNumberForPattern(""DIDI""); + PrintMinNumberForPattern(""IIDDD""); + PrintMinNumberForPattern(""DDIDDIID""); + } +}"," '''Python3 program to print minimum number that +can be formed from a given sequence of Is and Ds + ''' '''Prints the minimum number that can be formed from +input sequence of I's and D's''' + +def PrintMinNumberForPattern(arr): + ''' Initialize current_max (to make sure that + we don't use repeated character''' + + curr_max = 0 + ''' Initialize last_entry (Keeps track for + last printed digit)''' + + last_entry = 0 + i = 0 + ''' Iterate over input array''' + + while i < len(arr): + ''' Initialize 'noOfNextD' to get count of + next D's available''' + + noOfNextD = 0 + if arr[i] == ""I"": + ''' If letter is 'I' + Calculate number of next consecutive D's + available''' + + j = i + 1 + while j < len(arr) and arr[j] == ""D"": + noOfNextD += 1 + j += 1 + if i == 0: + curr_max = noOfNextD + 2 + last_entry += 1 + ''' If 'I' is first letter, print incremented + sequence from 1''' + + print("""", last_entry, end = """") + print("""", curr_max, end = """") + ''' Set max digit reached''' + + last_entry = curr_max + else: + ''' If not first letter + Get next digit to print''' + + curr_max += noOfNextD + 1 + ''' Print digit for I''' + + last_entry = curr_max + print("""", last_entry, end = """") + ''' For all next consecutive 'D' print + decremented sequence''' + + for k in range(noOfNextD): + last_entry -= 1 + print("""", last_entry, end = """") + i += 1 + ''' If letter is 'D''' + ''' + elif arr[i] == ""D"": + if i == 0: + ''' If 'D' is first letter in sequence + Find number of Next D's available''' + + j = i + 1 + while j < len(arr) and arr[j] == ""D"": + noOfNextD += 1 + j += 1 + ''' Calculate first digit to print based on + number of consecutive D's''' + + curr_max = noOfNextD + 2 + ''' Print twice for the first time''' + + print("""", curr_max, curr_max - 1, end = """") + ''' Store last entry''' + + last_entry = curr_max - 1 + else: + ''' If current 'D' is not first letter + Decrement last_entry''' + + print("""", last_entry - 1, end = """") + last_entry -= 1 + i += 1 + print() + '''Driver code''' + +if __name__ == ""__main__"": + PrintMinNumberForPattern(""IDID"") + PrintMinNumberForPattern(""I"") + PrintMinNumberForPattern(""DD"") + PrintMinNumberForPattern(""II"") + PrintMinNumberForPattern(""DIDI"") + PrintMinNumberForPattern(""IIDDD"") + PrintMinNumberForPattern(""DDIDDIID"")" +Count number of occurrences (or frequency) in a sorted array,"/*Java program to count occurrences +of an element*/ + + +class Main +{ +/* Returns number of times x occurs in arr[0..n-1]*/ + + static int countOccurrences(int arr[], int n, int x) + { + int res = 0; + for (int i=0; i 0) + res = res - aux[tli-1][rbj]; +/* Remove elements between (0, 0) + and (rbi, tlj-1)*/ + + if (tlj > 0) + res = res - aux[rbi][tlj-1]; +/* Add aux[tli-1][tlj-1] as elements + between (0, 0) and (tli-1, tlj-1) + are subtracted twice*/ + + if (tli > 0 && tlj > 0) + res = res + aux[tli-1][tlj-1]; + return res; + } +/* Driver code*/ + + public static void main (String[] args) + { + int mat[][] = {{1, 2, 3, 4, 6}, + {5, 3, 8, 1, 2}, + {4, 6, 7, 5, 5}, + {2, 4, 8, 9, 4}}; + int aux[][] = new int[M][N]; + preProcess(mat, aux); + int tli = 2, tlj = 2, rbi = 3, rbj = 4; + System.out.print(""\nQuery1: "" + + sumQuery(aux, tli, tlj, rbi, rbj)); + tli = 0; tlj = 0; rbi = 1; rbj = 1; + System.out.print(""\nQuery2: "" + + sumQuery(aux, tli, tlj, rbi, rbj)); + tli = 1; tlj = 2; rbi = 3; rbj = 3; + System.out.print(""\nQuery3: "" + + sumQuery(aux, tli, tlj, rbi, rbj)); + } +}"," '''Python 3 program to compute submatrix +query sum in O(1) time''' + +M = 4 +N = 5 + '''Function to preprcess input mat[M][N]. +This function mainly fills aux[M][N] +such that aux[i][j] stores sum +of elements from (0,0) to (i,j)''' + +def preProcess(mat, aux): + ''' Copy first row of mat[][] to aux[][]''' + + for i in range(0, N, 1): + aux[0][i] = mat[0][i] + ''' Do column wise sum''' + + for i in range(1, M, 1): + for j in range(0, N, 1): + aux[i][j] = mat[i][j] + aux[i - 1][j] + ''' Do row wise sum''' + + for i in range(0, M, 1): + for j in range(1, N, 1): + aux[i][j] += aux[i][j - 1] + '''A O(1) time function to compute sum of submatrix +between (tli, tlj) and (rbi, rbj) using aux[][] +which is built by the preprocess function''' + +def sumQuery(aux, tli, tlj, rbi, rbj): + ''' result is now sum of elements + between (0, 0) and (rbi, rbj)''' + + res = aux[rbi][rbj] + ''' Remove elements between (0, 0) + and (tli-1, rbj)''' + + if (tli > 0): + res = res - aux[tli - 1][rbj] + ''' Remove elements between (0, 0) + and (rbi, tlj-1)''' + + if (tlj > 0): + res = res - aux[rbi][tlj - 1] + ''' Add aux[tli-1][tlj-1] as elements + between (0, 0) and (tli-1, tlj-1) + are subtracted twice''' + + if (tli > 0 and tlj > 0): + res = res + aux[tli - 1][tlj - 1] + return res + '''Driver Code''' + +if __name__ == '__main__': + mat = [[1, 2, 3, 4, 6], + [5, 3, 8, 1, 2], + [4, 6, 7, 5, 5], + [2, 4, 8, 9, 4]] +aux = [[0 for i in range(N)] + for j in range(M)] +preProcess(mat, aux) +tli = 2 +tlj = 2 +rbi = 3 +rbj = 4 +print(""Query1:"", sumQuery(aux, tli, tlj, rbi, rbj)) +tli = 0 +tlj = 0 +rbi = 1 +rbj = 1 +print(""Query2:"", sumQuery(aux, tli, tlj, rbi, rbj)) +tli = 1 +tlj = 2 +rbi = 3 +rbj = 3 +print(""Query3:"", sumQuery(aux, tli, tlj, rbi, rbj))" +Find the Deepest Node in a Binary Tree,"/*Java program to find value of the deepest node +in a given binary tree*/ + +class GFG +{ +/* A tree node*/ + + static class Node + { + int data; + Node left, right; + Node(int key) + { + data = key; + left = null; + right = null; + } + } + static int maxLevel = -1; + static int res = -1; +/* maxLevel : keeps track of maximum level seen so far. + res : Value of deepest node so far. + level : Level of root*/ + + static void find(Node root, int level) + { + if (root != null) + { + find(root.left, ++level); +/* Update level and resue*/ + + if (level > maxLevel) + { + res = root.data; + maxLevel = level; + } + find(root.right, level); + } + } +/* Returns value of deepest node*/ + + static int deepestNode(Node root) + { +/* Initialze result and max level*/ + + int res = -1; + int maxLevel = -1; /* Updates value ""res"" and ""maxLevel"" + Note that res and maxLen are passed + by reference.*/ + + find(root, 0); + return res; + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.left.left = new Node(4); + root.right.left = new Node(5); + root.right.right = new Node(6); + root.right.left.right = new Node(7); + root.right.right.right = new Node(8); + root.right.left.right.left = new Node(9); + System.out.println(deepestNode(root)); + } +}"," '''Python3 program to find value of the +deepest node in a given binary tree''' + + '''A Binary Tree Node +Utility function to create a +new tree node''' + +class newNode: + def __init__(self, data): + self.data= data + self.left = None + self.right = None + self.visited = False '''maxLevel : keeps track of maximum +level seen so far. +res : Value of deepest node so far. +level : Level of root''' + +def find(root, level, maxLevel, res): + if (root != None): + level += 1 + find(root.left, level, maxLevel, res) + ''' Update level and resue''' + + if (level > maxLevel[0]): + res[0] = root.data + maxLevel[0] = level + find(root.right, level, maxLevel, res) + '''Returns value of deepest node''' + +def deepestNode(root) : + ''' Initialze result and max level''' + + res = [-1] + maxLevel = [-1] + ''' Updates value ""res"" and ""maxLevel"" + Note that res and maxLen are passed + by reference.''' + + find(root, 0, maxLevel, res) + return res[0] + '''Driver Code''' + +if __name__ == '__main__': + 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(6) + root.right.left.right = newNode(7) + root.right.right.right = newNode(8) + root.right.left.right.left = newNode(9) + print(deepestNode(root))" +Sparse Table,"/*Java program to do range minimum query +using sparse table*/ + +import java.io.*; +class GFG { + static int MAX =500; +/* lookup[i][j] is going to store minimum + value in arr[i..j]. Ideally lookup table + size should not be fixed and should be + determined using n Log n. It is kept + constant to keep code simple.*/ + + static int [][]lookup = new int[MAX][MAX]; +/* Fills lookup array lookup[][] in bottom up manner.*/ + + static void buildSparseTable(int arr[], int n) + { +/* Initialize M for the intervals with length 1*/ + + for (int i = 0; i < n; i++) + lookup[i][0] = arr[i]; +/* Compute values from smaller to bigger intervals*/ + + for (int j = 1; (1 << j) <= n; j++) { +/* Compute minimum value for all intervals with + size 2^j*/ + + for (int i = 0; (i + (1 << j) - 1) < n; i++) { +/* For arr[2][10], we compare arr[lookup[0][7]] + and arr[lookup[3][10]]*/ + + if (lookup[i][j - 1] < + lookup[i + (1 << (j - 1))][j - 1]) + lookup[i][j] = lookup[i][j - 1]; + else + lookup[i][j] = + lookup[i + (1 << (j - 1))][j - 1]; + } + } + } +/* Returns minimum of arr[L..R]*/ + + static int query(int L, int R) + { +/* Find highest power of 2 that is smaller + than or equal to count of elements in given + range. For [2, 10], j = 3*/ + + int j = (int)Math.log(R - L + 1); +/* Compute minimum of last 2^j elements with first + 2^j elements in range. + For [2, 10], we compare arr[lookup[0][3]] and + arr[lookup[3][3]],*/ + + if (lookup[L][j] <= lookup[R - (1 << j) + 1][j]) + return lookup[L][j]; + else + return lookup[R - (1 << j) + 1][j]; + } +/* Driver program*/ + + public static void main (String[] args) + { + int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; + int n = a.length; + buildSparseTable(a, n); + System.out.println(query(0, 4)); + System.out.println(query(4, 7)); + System.out.println(query(7, 8)); + } +}"," '''Python3 program to do range minimum +query using sparse table''' + +import math + ''' lookup[i][j] is going to store minimum + value in arr[i..j]. Ideally lookup table + size should not be fixed and should be + determined using n Log n. It is kept + constant to keep code simple.''' + + '''Fills lookup array lookup[][] in +bottom up manner.''' + +def buildSparseTable(arr, n): + ''' Initialize M for the intervals + with length 1''' + + for i in range(0, n): + lookup[i][0] = arr[i] + j = 1 + ''' Compute values from smaller to + bigger intervals''' + + while (1 << j) <= n: + ''' Compute minimum value for all + intervals with size 2^j''' + + i = 0 + while (i + (1 << j) - 1) < n: + ''' For arr[2][10], we compare arr[lookup[0][7]] + and arr[lookup[3][10]]''' + + if (lookup[i][j - 1] < + lookup[i + (1 << (j - 1))][j - 1]): + lookup[i][j] = lookup[i][j - 1] + else: + lookup[i][j] = \ + lookup[i + (1 << (j - 1))][j - 1] + i += 1 + j += 1 + '''Returns minimum of arr[L..R]''' + +def query(L, R): + ''' Find highest power of 2 that is smaller + than or equal to count of elements in + given range. For [2, 10], j = 3''' + + j = int(math.log2(R - L + 1)) + ''' Compute minimum of last 2^j elements + with first 2^j elements in range. + For [2, 10], we compare arr[lookup[0][3]] + and arr[lookup[3][3]],''' + + if lookup[L][j] <= lookup[R - (1 << j) + 1][j]: + return lookup[L][j] + else: + return lookup[R - (1 << j) + 1][j] + '''Driver Code''' + +if __name__ == ""__main__"": + a = [7, 2, 3, 0, 5, 10, 3, 12, 18] + n = len(a) + MAX = 500 + lookup = [[0 for i in range(MAX)] + for j in range(MAX)] + buildSparseTable(a, n) + print(query(0, 4)) + print(query(4, 7)) + print(query(7, 8))" +How to print maximum number of A's using given four keys,"/*A Dynamic Programming based Java program +to find maximum number of A's that +can be printed using four keys*/ + +class GFG +{ +/*This function returns the optimal length +string for N keystrokes*/ + +static int findoptimal(int N) +{ +/* The optimal string length is N + when N is smaller than 7*/ + + if (N <= 6) + return N; +/* An array to store result of subproblems*/ + + int []screen = new int[N]; +/*To pick a breakpoint*/ + +int b; +/* Initializing the optimal lengths array + for uptil 6 input strokes.*/ + + int n; + for (n = 1; n <= 6; n++) + screen[n - 1] = n; +/* Solve all subproblems in bottom-up manner*/ + + for (n = 7; n <= N; n++) + { +/* for any keystroke n, we will need to choose between:- + 1. pressing Ctrl-V once after copying the + A's obtained by n-3 keystrokes. + 2. pressing Ctrl-V twice after copying the A's + obtained by n-4 keystrokes. + 3. pressing Ctrl-V thrice after copying the A's + obtained by n-5 keystrokes.*/ + + screen[n - 1] = Math.max(2 * screen[n - 4], + Math.max(3 * screen[n - 5], + 4 * screen[n - 6])); + } + return screen[N - 1]; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int N; +/* for the rest of the array we will rely + on the previous entries to compute new ones*/ + + for (N = 1; N <= 20; N++) + System.out.printf(""Maximum Number of A's with"" + + "" %d keystrokes is %d\n"", + N, findoptimal(N)); + } +}"," '''A Dynamic Programming based Python3 program +to find maximum number of A's +that can be printed using four keys''' + + '''this function returns the optimal +length string for N keystrokes''' + +def findoptimal(N): ''' The optimal string length is + N when N is smaller than 7''' + + if (N <= 6): + return N + ''' An array to store result of + subproblems''' + + screen = [0] * N + ''' Initializing the optimal lengths + array for uptil 6 input + strokes.''' + + for n in range(1, 7): + screen[n - 1] = n + ''' Solve all subproblems in bottom manner''' + + for n in range(7, N + 1): + ''' for any keystroke n, we will need to choose between:- + 1. pressing Ctrl-V once after copying the + A's obtained by n-3 keystrokes. + 2. pressing Ctrl-V twice after copying the A's + obtained by n-4 keystrokes. + 3. pressing Ctrl-V thrice after copying the A's + obtained by n-5 keystrokes.''' + + screen[n - 1] = max(2 * screen[n - 4], + max(3 * screen[n - 5], + 4 * screen[n - 6])); + return screen[N - 1] + '''Driver Code''' + +if __name__ == ""__main__"": + ''' for the rest of the array we + will rely on the previous + entries to compute new ones''' + + for N in range(1, 21): + print(""Maximum Number of A's with "", N, + "" keystrokes is "", findoptimal(N))" +Multiply a given Integer with 3.5,"/*Java Program to multiply +a number with 3.5*/ + +class GFG { + static int multiplyWith3Point5(int x) + { + return (x<<1) + x + (x>>1); + } + /* Driver program to test above functions*/ + + public static void main(String[] args) + { + int x = 2; + System.out.println(multiplyWith3Point5(x)); + } +}"," '''Python 3 program to multiply +a number with 3.5''' + +def multiplyWith3Point5(x): + return (x<<1) + x + (x>>1) + '''Driver program to +test above functions''' + +x = 4 +print(multiplyWith3Point5(x))" +Find the Mth element of the Array after K left rotations,"/*Java program for the above approach */ + +import java.util.*; +class GFG{ + +/*Function to return Mth element of +array after k left rotations */ + +public static int getFirstElement(int[] a, int N, + int K, int M) +{ + +/* The array comes to original state + after N rotations */ + + K %= N; + +/* Mth element after k left rotations + is (K+M-1)%N th element of the + original array */ + + int index = (K + M - 1) % N; + + int result = a[index]; + +/* Return the result */ + + return result; +} + +/*Driver code */ + +public static void main(String[] args) +{ + +/* Array initialization */ + + int a[] = { 3, 4, 5, 23 }; + +/* Size of the array */ + + int N = a.length; + +/* Given K rotation and Mth element + to be found after K rotation */ + + int K = 2, M = 1; + +/* Function call */ + + System.out.println(getFirstElement(a, N, K, M)); +} +} + + +"," '''Python3 program for the above approach ''' + + + '''Function to return Mth element of +array after k left rotations ''' + +def getFirstElement(a, N, K, M): + + ''' The array comes to original state + after N rotations ''' + + K %= N + + ''' Mth element after k left rotations + is (K+M-1)%N th element of the + original array ''' + + index = (K + M - 1) % N + + result = a[index] + + ''' Return the result ''' + + return result + + '''Driver Code ''' + +if __name__ == '__main__': + + ''' Array initialization ''' + + a = [ 3, 4, 5, 23 ] + + ''' Size of the array ''' + + N = len(a) + + ''' Given K rotation and Mth element + to be found after K rotation ''' + + K = 2 + M = 1 + + ''' Function call ''' + + print(getFirstElement(a, N, K, M)) + + +" +Remove all occurrences of duplicates from a sorted Linked List,"/*Java program to remove all occurrences of +duplicates from a sorted linked list*/ + + +/*class to create Linked lIst*/ + +class LinkedList{ +Node head = null; +class Node +{ + int val; + Node next; + Node(int v) + { + val = v; + next = null; + } +} + + + +/*Function to insert data nodes into +the Linked List at the front*/ + +public void insert(int data) +{ + Node new_node = new Node(data); + new_node.next = head; + head = new_node; +} + +/*Function to remove all occurrences +of duplicate elements*/ + +public void removeAllDuplicates() +{ + +/* Create a dummy node that acts like a fake + head of list pointing to the original head*/ + + Node dummy = new Node(0); + +/* Dummy node points to the original head*/ + + dummy.next = head; + Node prev = dummy; + Node current = head; + + while (current != null) + { +/* Until the current and previous values + are same, keep updating current*/ + + while (current.next != null && + prev.next.val == current.next.val) + current = current.next; + +/* If current has unique value i.e current + is not updated, Move the prev pointer + to next node*/ + + if (prev.next == current) + prev = prev.next; + +/* When current is updated to the last + duplicate value of that segment, make + prev the next of current*/ +*/ + else + prev.next = current.next; + + current = current.next; + } + +/* Update original head to the next of dummy + node*/ + + head = dummy.next; +} + +/*Function to print the list elements*/ + +public void printList() +{ + Node trav = head; + if (head == null) + System.out.print("" List is empty"" ); + + while (trav != null) + { + System.out.print(trav.val + "" ""); + trav = trav.next; + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + LinkedList ll = new LinkedList(); + ll.insert(53); + ll.insert(53); + ll.insert(49); + ll.insert(49); + ll.insert(35); + ll.insert(28); + ll.insert(28); + ll.insert(23); + + System.out.println(""Before removal of duplicates""); + ll.printList(); + + ll.removeAllDuplicates(); + + System.out.println(""\nAfter removal of duplicates""); + ll.printList(); +} +} +", +Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient),"/* Java program to convert a Binary Tree to + Threaded Tree */ + +import java.util.*; +class solution +{ +/* structure of a node in threaded binary tree */ + +static class Node +{ + int key; + Node left, right; +/* Used to indicate whether the right pointer + is a normal right pointer or a pointer + to inorder successor.*/ + + boolean isThreaded; +}; +/*Converts tree with given root to threaded +binary tree. +This function returns rightmost child of +root.*/ + +static Node createThreaded(Node root) +{ +/* Base cases : Tree is empty or has single + node*/ + + if (root == null) + return null; + if (root.left == null && + root.right == null) + return root; +/* Find predecessor if it exists*/ + + if (root.left != null) + { +/* Find predecessor of root (Rightmost + child in left subtree)*/ + + Node l = createThreaded(root.left); +/* Link a thread from predecessor to + root.*/ + + l.right = root; + l.isThreaded = true; + } +/* If current node is rightmost child*/ + + if (root.right == null) + return root; +/* Recur for right subtree.*/ + + return createThreaded(root.right); +} +/*A utility function to find leftmost node +in a binary tree rooted with 'root'. +This function is used in inOrder()*/ + +static Node leftMost(Node root) +{ + while (root != null && root.left != null) + root = root.left; + return root; +} +/*Function to do inorder traversal of a threadded +binary tree*/ + +static void inOrder(Node root) +{ + if (root == null) return; +/* Find the leftmost node in Binary Tree*/ + + Node cur = leftMost(root); + while (cur != null) + { + System.out.print(cur.key + "" ""); +/* If this Node is a thread Node, then go to + inorder successor*/ + + if (cur.isThreaded) + cur = cur.right; +/*Else go to the leftmost child in right subtree*/ + +else + cur = leftMost(cur.right); + } +} +/*A utility function to create a new node*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.left = temp.right = null; + temp.key = key; + return temp; +} +/*Driver program to test above functions*/ + +public static void main(String args[]) +{ + /* 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 */ + + 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); + createThreaded(root); + System.out.println(""Inorder traversal of created ""+""threaded tree is\n""); + inOrder(root); +} +}"," '''Python3 program to convert a Binary Tree to +Threaded Tree''' + + '''Converts tree with given root to threaded +binary tree. +This function returns rightmost child of +root.''' + +def createThreaded(root): + ''' Base cases : Tree is empty or has + single node''' + + if root == None: + return None + if root.left == None and root.right == None: + return root + ''' Find predecessor if it exists''' + + if root.left != None: + ''' Find predecessor of root (Rightmost + child in left subtree)''' + + l = createThreaded(root.left) + ''' Link a thread from predecessor + to root.''' + + l.right = root + l.isThreaded = True + ''' If current node is rightmost child''' + + if root.right == None: + return root + ''' Recur for right subtree.''' + + return createThreaded(root.right) + '''A utility function to find leftmost node +in a binary tree rooted with 'root'. +This function is used in inOrder()''' + +def leftMost(root): + while root != None and root.left != None: + root = root.left + return root + '''Function to do inorder traversal of a +threaded binary tree''' + +def inOrder(root): + if root == None: + return + ''' Find the leftmost node in Binary Tree''' + + cur = leftMost(root) + while cur != None: + print(cur.key, end = "" "") + ''' If this Node is a thread Node, then + go to inorder successor''' + + if cur.isThreaded: + cur = cur.right + '''Else go to the leftmost child in right subtree''' + + else: + cur = leftMost(cur.right) '''A utility function to create a new node''' + +class newNode: + def __init__(self, key): + self.left = self.right = None + self.key = key + self.isThreaded = None '''Driver Code''' + +if __name__ == '__main__': + ''' 1 + / \ + 2 3 + / \ / \ + 4 5 6 7''' + + 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) + createThreaded(root) + print(""Inorder traversal of created"", + ""threaded tree is"") + inOrder(root)" +Write a function that generates one of 3 numbers according to given probabilities,,"import random + '''This function generates 'x' with probability px/100, 'y' with +probability py/100 and 'z' with probability pz/100: +Assumption: px + py + pz = 100 where px, py and pz lie +between 0 to 100''' + +def random(x, y, z, px, py, pz): + ''' Generate a number from 1 to 100''' + + r = random.randint(1, 100) + ''' r is smaller than px with probability px/100''' + + if (r <= px): + return x + ''' r is greater than px and smaller than + or equal to px+py with probability py/100''' + + if (r <= (px+py)): + return y + ''' r is greater than px+py and smaller than + or equal to 100 with probability pz/100''' + + else: + return z" +Check given array of size n can represent BST of n levels or not,"/*Java program to Check given array +can represent BST or not */ + +class Solution +{ +/*Driver code */ + +public static void main(String args[]) +{ + int arr[] = { 5123, 3300, 783, 1111, 890 }; + int n = arr.length; + int max = Integer.MAX_VALUE; + int min = Integer.MIN_VALUE; + boolean flag = true; + for (int i = 1; i < n; i++) { +/* This element can be inserted to the right + of the previous element, only if it is greater + than the previous element and in the range. */ + + if (arr[i] > arr[i - 1] && arr[i] > min && arr[i] < max) { +/* max remains same, update min */ + + min = arr[i - 1]; + } +/* This element can be inserted to the left + of the previous element, only if it is lesser + than the previous element and in the range. */ + + else if (arr[i] < arr[i - 1] && arr[i] > min && arr[i] < max) { +/* min remains same, update max */ + + max = arr[i - 1]; + } + else { + flag = false; + break; + } + } + if (flag) { + System.out.println(""Yes""); + } + else { +/* if the loop completed successfully without encountering else condition */ + + System.out.println(""No""); + } +} +}"," '''Python3 program to Check given array +can represent BST or not + ''' '''Driver Code ''' + +if __name__ == '__main__': + arr = [5123, 3300, 783, 1111, 890] + n = len(arr) + max = 2147483647 + min = -2147483648 + flag = True + for i in range(1,n): ''' This element can be inserted to the + right of the previous element, only + if it is greater than the previous + element and in the range. ''' + + if (arr[i] > arr[i - 1] and + arr[i] > min and arr[i] < max): + ''' max remains same, update min ''' + + min = arr[i - 1] + ''' This element can be inserted to the + left of the previous element, only + if it is lesser than the previous + element and in the range. ''' + + elif (arr[i] < arr[i - 1] and + arr[i] > min and arr[i] < max): + ''' min remains same, update max ''' + + max = arr[i - 1] + else : + flag = False + break + if (flag): + print(""Yes"") + else: + ''' if the loop completed successfully + without encountering else condition ''' + + print(""No"")" +Minimum cost to sort a matrix of numbers from 0 to n^2,"/*Java implementation to find +the total energy required +to rearrange the numbers*/ + +import java.util.*; +import java.lang.*; +public class GfG{ + private final static int SIZE = 100; +/* function to find the total energy + required to rearrange the numbers*/ + + public static int calculateEnergy(int mat[][], + int n) + { + int i_des, j_des, q; + int tot_energy = 0; +/* nested loops to access the elements + of the given matrix*/ + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { +/* store quotient*/ + + q = mat[i][j] / n; +/* final destination location + (i_des, j_des) of + the element mat[i][j] is + being calculated*/ + + i_des = q; + j_des = mat[i][j] - (n * q); +/* energy required for the + movement of the + element mat[i][j] is + calculated and then + accumulated in the 'tot_energy'*/ + + tot_energy += Math.abs(i_des - i) + + Math.abs(j_des - j); + } + } +/* required total energy*/ + + return tot_energy; + } +/* Driver function*/ + + public static void main(String argc[]){ + int[][] mat = new int[][] {{ 4, 7, 0, 3 }, + { 8, 5, 6, 1 }, + { 9, 11, 10, 2 }, + { 15, 13, 14, 12 }}; + int n = 4; + System.out.println(""Total energy required = "" + + calculateEnergy(mat, n) + "" units""); + } +}"," '''implementation to find the total +energy required to rearrange the +numbers''' + +n = 4 + '''function to find the total energy +required to rearrange the numbers''' + +def calculateEnergy(mat,n): + tot_energy = 0 + ''' nested loops to access the + elements of the given matrix''' + + for i in range(n): + for j in range(n): + ''' store quotient''' + + q = mat[i][j]//n + ''' final destination location + (i_des, j_des) of the + element mat[i][j] is being + calculated''' + + i_des = q + j_des = mat[i][j]- (n*q) + ''' energy required for the + movement of the element + mat[i][j] is calculated + and then accumulated in + the 'tot_energy''' + ''' + tot_energy += (abs(i_des-i) + + abs(j_des-j)) + ''' required total energy''' + + return tot_energy + '''Driver Program''' + +mat = [[4, 7, 0, 3], + [8, 5, 6, 1], + [9, 11, 10, 2], + [15, 13, 14, 12]] +print(""Total energy required = "", + calculateEnergy(mat,n), ""units"")" +Sum of both diagonals of a spiral odd-order square matrix,"/*Java program to find sum of +diagonals of spiral matrix*/ + +class GFG +{ +/* function returns sum of diagonals*/ + + static int spiralDiaSum(int n) + { + if (n == 1) + return 1; +/* as order should be only odd + we should pass only odd-integers*/ + + return (4 * n * n - 6 * n + 6 + + spiralDiaSum(n - 2)); + } +/* Driver program to test*/ + + public static void main (String[] args) + { + int n = 7; + System.out.print(spiralDiaSum(n)); + } +}"," '''Python3 program to find sum of +diagonals of spiral matrix + ''' '''function returns sum of diagonals''' + +def spiralDiaSum(n): + if n == 1: + return 1 + ''' as order should be only odd + we should pass only odd + integers''' + + return (4 * n*n - 6 * n + 6 + + spiralDiaSum(n-2)) + '''Driver program''' + +n = 7; +print(spiralDiaSum(n))" +Subset Sum | Backtracking-4,, +"Given a matrix of 'O' and 'X', find the largest subsquare surrounded by 'X'","/*Size of given matrix is N X N*/ + +class GFG +{ + static int N = 6; + static int maximumSubSquare(int[][] arr) + { + int[][][] dp = new int[51][51][2]; + int[][] maxside = new int[51][51]; +/* Initialize maxside with 0*/ + + for (int[] row : maxside) + Arrays.fill(row, 10); + int x = 0, y = 0;/* Fill the dp matrix horizontally. + for contiguous 'X' increment the value of x, + otherwise make it 0*/ + + for (int i = 0; i < N; i++) + { + x = 0; + for (int j = 0; j < N; j++) + { + if (arr[i][j] == 'X') + x += 1; + else + x = 0; + dp[i][j][0] = x; + } + } +/* Fill the dp matrix vertically. + For contiguous 'X' increment the value of y, + otherwise make it 0*/ + + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + if (arr[j][i] == 'X') + y += 1; + else + y = 0; + dp[j][i][1] = y; + } + } +/* Now check , for every value of (i, j) if sub-square + is possible, + traverse back horizontally by value val, and check if + vertical contiguous + 'X'enfing at (i , j-val+1) is greater than equal to + val. + Similarly, check if traversing back vertically, the + horizontal contiguous + 'X'ending at (i-val+1, j) is greater than equal to + val.*/ + + int maxval = 0, val = 0; + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + val = Math.min(dp[i][j][0], dp[i][j][1]); + if (dp[i][j - val + 1][1] >= val + && dp[i - val + 1][j][0] >= val) + maxside[i][j] = val; + else + maxside[i][j] = 0; +/* store the final answer in maxval*/ + + maxval = Math.max(maxval, maxside[i][j]); + } + } +/* return the final answe.*/ + + return maxval; + } +/* Driver code*/ + + public static void main (String[] args) + { + int mat[][] = { + { 'X', 'O', 'X', 'X', 'X', 'X' }, + { 'X', 'O', 'X', 'X', 'O', 'X' }, + { 'X', 'X', 'X', 'O', 'O', 'X' }, + { 'O', 'X', 'X', 'X', 'X', 'X' }, + { 'X', 'X', 'X', 'O', 'X', 'O' }, + { 'O', 'O', 'X', 'O', 'O', 'O' }, + }; +/* Function call*/ + + System.out.println(maximumSubSquare(mat)); + } +}"," '''Python3 program to find the largest +subsquare surrounded by X in a given +matrix of O and X''' + + '''Size of given matrix is N X N''' + +N = 6 +def maximumSubSquare(arr): + dp = [[[-1, -1] for i in range(51)] + for j in range(51)] ''' Initialize maxside with 0''' + + maxside = [[0 for i in range(51)] + for j in range(51)] + x = 0 + y = 0 + ''' Fill the dp matrix horizontally. + for contiguous 'X' increment the + value of x, otherwise make it 0''' + + for i in range(N): + x = 0 + for j in range(N): + if (arr[i][j] == 'X'): + x += 1 + else: + x = 0 + dp[i][j][0] = x + ''' Fill the dp matrix vertically. + For contiguous 'X' increment + the value of y, otherwise + make it 0''' + + for i in range(N): + for j in range(N): + if (arr[j][i] == 'X'): + y += 1 + else: + y = 0 + dp[j][i][1] = y + ''' Now check , for every value of (i, j) if sub-square + is possible, + traverse back horizontally by value val, and check if + vertical contiguous + 'X'enfing at (i , j-val+1) is greater than equal to + val. + Similarly, check if traversing back vertically, the + horizontal contiguous + 'X'ending at (i-val+1, j) is greater than equal to + val.''' + + maxval = 0 + val = 0 + for i in range(N): + for j in range(N): + val = min(dp[i][j][0], + dp[i][j][1]) + if (dp[i][j - val + 1][1] >= val and + dp[i - val + 1][j][0] >= val): + maxside[i][j] = val + else: + maxside[i][j] = 0 + ''' Store the final answer in maxval''' + + maxval = max(maxval, maxside[i][j]) + ''' Return the final answe.''' + + return maxval + '''Driver code''' + +mat = [ [ 'X', 'O', 'X', 'X', 'X', 'X' ], + [ 'X', 'O', 'X', 'X', 'O', 'X' ], + [ 'X', 'X', 'X', 'O', 'O', 'X' ], + [ 'O', 'X', 'X', 'X', 'X', 'X' ], + [ 'X', 'X', 'X', 'O', 'X', 'O' ], + [ 'O', 'O', 'X', 'O', 'O', 'O' ] ] + '''Function call''' + +print(maximumSubSquare(mat))" +Write you own Power without using multiplication(*) and division(/) operators,"import java.io.*; +class GFG { + /* A recursive function to get x*y */ + + static int multiply(int x, int y) + { + if (y > 0) + return (x + multiply(x, y - 1)); + else + return 0; + } + /* A recursive function to get a^b + Works only if a >= 0 and b >= 0 */ + + static int pow(int a, int b) + { + if (b > 0) + return multiply(a, pow(a, b - 1)); + else + return 1; + } + /* driver program to test above functions */ + + public static void main(String[] args) + { + System.out.println(pow(5, 3)); + } +}"," '''A recursive function to get x*y *''' + +def multiply(x, y): + if (y): + return (x + multiply(x, y-1)); + else: + return 0; +def pow(a,b): + if(b): + return multiply(a, pow(a, b-1)); + else: + return 1; + '''driver program to test above functions *''' + +print(pow(5, 3));" +Find Union and Intersection of two unsorted arrays,"/*A Java program to print union and intersection +of two unsorted arrays*/ + +import java.util.Arrays; +class UnionAndIntersection { +/* Prints union of arr1[0..m-1] and arr2[0..n-1]*/ + + void printUnion(int arr1[], int arr2[], int m, int n) + { +/* Before finding union, make sure arr1[0..m-1] + is smaller*/ + + if (m > n) { + int tempp[] = arr1; + arr1 = arr2; + arr2 = tempp; + int temp = m; + m = n; + n = temp; + } +/* Now arr1[] is smaller + Sort the first array and print its elements + (these two steps can be swapped as order in + output is not important)*/ + + Arrays.sort(arr1); + for (int i = 0; i < m; i++) + System.out.print(arr1[i] + "" ""); +/* Search every element of bigger array in smaller + array and print the element if not found*/ + + for (int i = 0; i < n; i++) { + if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) + System.out.print(arr2[i] + "" ""); + } + } +/* Prints intersection of arr1[0..m-1] and arr2[0..n-1]*/ + + void printIntersection(int arr1[], int arr2[], int m, + int n) + { +/* Before finding intersection, make sure + arr1[0..m-1] is smaller*/ + + if (m > n) { + int tempp[] = arr1; + arr1 = arr2; + arr2 = tempp; + int temp = m; + m = n; + n = temp; + } +/* Now arr1[] is smaller + Sort smaller array arr1[0..m-1]*/ + + Arrays.sort(arr1); +/* Search every element of bigger array in smaller + array and print the element if found*/ + + for (int i = 0; i < n; i++) { + if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) + System.out.print(arr2[i] + "" ""); + } + } +/* A recursive binary search function. It returns + location of x in given array arr[l..r] is present, + otherwise -1*/ + + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) { + int mid = l + (r - l) / 2; +/* If the element is present at the middle + itself*/ + + if (arr[mid] == x) + return mid; +/* If element is smaller than mid, then it can + only be present in left subarray*/ + + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); +/* Else the element can only be present in right + subarray*/ + + return binarySearch(arr, mid + 1, r, x); + } +/* We reach here when element is not present in + array*/ + + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + UnionAndIntersection u_i + = new UnionAndIntersection(); + int arr1[] = { 7, 1, 5, 2, 3, 6 }; + int arr2[] = { 3, 8, 6, 20, 7 }; + int m = arr1.length; + int n = arr2.length; +/* Function call*/ + + System.out.println(""Union of two arrays is ""); + u_i.printUnion(arr1, arr2, m, n); + System.out.println(""""); + System.out.println( + ""Intersection of two arrays is ""); + u_i.printIntersection(arr1, arr2, m, n); + } +}"," '''A Python3 program to print union and intersection +of two unsorted arrays + ''' '''Prints union of arr1[0..m-1] and arr2[0..n-1]''' + +def printUnion(arr1, arr2, m, n): + ''' Before finding union, make sure arr1[0..m-1] + is smaller''' + + if (m > n): + tempp = arr1 + arr1 = arr2 + arr2 = tempp + temp = m + m = n + n = temp + ''' Now arr1[] is smaller + Sort the first array and print its elements (these two + steps can be swapped as order in output is not important)''' + + arr1.sort() + for i in range(0, m): + print(arr1[i], end="" "") + ''' Search every element of bigger array in smaller array + and print the element if not found''' + + for i in range(0, n): + if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): + print(arr2[i], end="" "") + '''Prints intersection of arr1[0..m-1] and arr2[0..n-1]''' + +def printIntersection(arr1, arr2, m, n): + ''' Before finding intersection, make sure arr1[0..m-1] + is smaller''' + + if (m > n): + tempp = arr1 + arr1 = arr2 + arr2 = tempp + temp = m + m = n + n = temp + ''' Now arr1[] is smaller + Sort smaller array arr1[0..m-1]''' + + arr1.sort() + ''' Search every element of bigger array in smaller + array and print the element if found''' + + for i in range(0, n): + if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1): + print(arr2[i], end="" "") + '''A recursive binary search function. It returns +location of x in given array arr[l..r] is present, +otherwise -1''' + +def binarySearch(arr, l, r, x): + if (r >= l): + mid = int(l + (r - l)/2) + ''' If the element is present at the middle itself''' + + if (arr[mid] == x): + return mid + ''' If element is smaller than mid, then it can only + be presen in left subarray''' + + if (arr[mid] > x): + return binarySearch(arr, l, mid - 1, x) + ''' Else the element can only be present in right subarray''' + + return binarySearch(arr, mid + 1, r, x) + ''' We reach here when element is not present in array''' + + return -1 + '''Driver code''' + +arr1 = [7, 1, 5, 2, 3, 6] +arr2 = [3, 8, 6, 20, 7] +m = len(arr1) +n = len(arr2) + '''Function call''' + +print(""Union of two arrays is "") +printUnion(arr1, arr2, m, n) +print(""\nIntersection of two arrays is "") +printIntersection(arr1, arr2, m, n)" +Identical Linked Lists,"/*An iterative Java program to check if two linked lists +are identical or not*/ + + +/* Linked list Node*/ + + class Node + { + int data; + Node next; + Node(int d) { data = d; next = null; } + } + + /*head of list*/ +class LinkedList +{ +Node head; + + /* Returns true if linked lists a and b are identical, + otherwise false */ + + boolean areIdentical(LinkedList listb) + { + Node a = this.head, b = listb.head; + while (a != null && b != null) + { + if (a.data != b.data) + return false; + + /* If we reach here, then a and b are not null + and their data is same, so move to next nodes + in both lists */ + + a = a.next; + b = b.next; + } + +/* If linked lists are identical, then 'a' and 'b' must + be null at this point.*/ + + return (a == null && b == null); + } + + /* UTILITY FUNCTIONS TO TEST fun1() and fun2() */ + + /* 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. */ + + + void push(int new_data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + + /* 3. Make next of new Node as head */ + + new_node.next = head; + + /* 4. Move the head to point to new Node */ + + head = new_node; + } + + + /* Driver program to test above functions */ + + public static void main(String args[]) + { + LinkedList llist1 = new LinkedList(); + LinkedList llist2 = new LinkedList(); + + /* The constructed linked lists are : + llist1: 3->2->1 + llist2: 3->2->1 */ + + + llist1.push(1); + llist1.push(2); + llist1.push(3); + + llist2.push(1); + llist2.push(2); + llist2.push(3); + + if (llist1.areIdentical(llist2) == true) + System.out.println(""Identical ""); + else + System.out.println(""Not identical ""); + + } +} +"," '''An iterative Java program to check if +two linked lists are identical or not''' + + + '''Linked list Node''' + +class Node: + def __init__(self, d): + self.data = d + self.next = None + + '''head of list''' + +class LinkedList: + def __init__(self): + self.head = None + + ''' Returns true if linked lists a and b + are identical, otherwise false''' + + def areIdentical(self, listb): + a = self.head + b = listb.head + while (a != None and b != None): + if (a.data != b.data): + return False + + ''' If we reach here, then a and b + are not null and their data is + same, so move to next nodes + in both lists''' + + a = a.next + b = b.next + + ''' If linked lists are identical, + then 'a' and 'b' must be null + at this point.''' + + return (a == None and b == None) + + ''' UTILITY FUNCTIONS TO TEST fun1() and fun2()''' + + + '''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.''' + + + def push(self, new_data): ''' 1 & 2: Allocate the Node & + Put in the data''' + + new_node = Node(new_data) + + ''' 3. Make next of new Node as head''' + + new_node.next = self.head + + ''' 4. Move the head to point to new Node''' + + self.head = new_node + + '''Driver Code''' + +llist1 = LinkedList() +llist2 = LinkedList() + + '''The constructed linked lists are : +llist1: 3->2->1 +llist2: 3->2->1''' + +llist1.push(1) +llist1.push(2) +llist1.push(3) +llist2.push(1) +llist2.push(2) +llist2.push(3) + +if (llist1.areIdentical(llist2) == True): + print(""Identical "") +else: + print(""Not identical "") + + +" +Change the array into a permutation of numbers from 1 to n,"/*Java program to make a permutation of numbers +from 1 to n using minimum changes.*/ + +import java.util.*; +class GFG +{ +static void makePermutation(int []a, int n) +{ +/* Store counts of all elements.*/ + + HashMap count = new HashMap(); + for (int i = 0; i < n; i++) + { + if(count.containsKey(a[i])) + { + count.put(a[i], count.get(a[i]) + 1); + } + else + { + count.put(a[i], 1); + } + } + int next_missing = 1; + for (int i = 0; i < n; i++) + { + if (count.containsKey(a[i]) && + count.get(a[i]) != 1 || + a[i] > n || a[i] < 1) + { + count.put(a[i], count.get(a[i]) - 1); +/* Find next missing element to put + in place of current element.*/ + + while (count.containsKey(next_missing)) + next_missing++; +/* Replace with next missing and insert + the missing element in hash.*/ + + a[i] = next_missing; + count. put(next_missing, 1); + } + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int A[] = { 2, 2, 3, 3 }; + int n = A.length; + makePermutation(A, n); + for (int i = 0; i < n; i++) + System.out.print(A[i] + "" ""); + } +}"," '''Python3 code to make a permutation +of numbers from 1 to n using +minimum changes.''' + +def makePermutation (a, n): + ''' Store counts of all elements.''' + + count = dict() + for i in range(n): + if count.get(a[i]): + count[a[i]] += 1 + else: + count[a[i]] = 1; + next_missing = 1 + for i in range(n): + if count[a[i]] != 1 or a[i] > n or a[i] < 1: + count[a[i]] -= 1 + ''' Find next missing element to put + in place of current element.''' + + while count.get(next_missing): + next_missing+=1 + ''' Replace with next missing and + insert the missing element in hash.''' + + a[i] = next_missing + count[next_missing] = 1 + '''Driver Code''' + +A = [ 2, 2, 3, 3 ] +n = len(A) +makePermutation(A, n) +for i in range(n): + print(A[i], end = "" "")" +Rearrange a given linked list in-place.,"/*Java implementation*/ + +import java.io.*; + +/*Creating the structure for node*/ + +class Node { + int data; + Node next; + Node(int key) + { + data = key; + next = null; + } +} + + + +class GFG { + + Node left = null; + +/* Function to print the list*/ + + void printlist(Node head) + { + while (head != null) { + System.out.print(head.data + "" ""); + if (head.next != null) { + System.out.print(""->""); + } + head = head.next; + } + System.out.println(); + } + +/* Function to rearrange*/ + + void rearrange(Node head) + { + + if (head != null) { + left = head; + reorderListUtil(left); + } + } + + void reorderListUtil(Node right) + { + + if (right == null) { + return; + } + + reorderListUtil(right.next); + +/* we set left = null, when we reach stop condition, + so no processing required after that*/ + + if (left == null) { + return; + } + +/* Stop condition: odd case : left = right, even + case : left.next = right*/ + + if (left != right && left.next != right) { + Node temp = left.next; + left.next = right; + right.next = temp; + left = temp; + } +/*stop condition , set null to left nodes*/ + +else { + if (left.next == right) { +/*even case*/ + +left.next.next = null; + left = null; + } + else { +/*odd case*/ + +left.next = null; + left = null; + } + } + } + +/* Drivers Code*/ + + public static void main(String[] args) + { + + Node head = new Node(1); + head.next = new Node(2); + head.next.next = new Node(3); + head.next.next.next = new Node(4); + head.next.next.next.next = new Node(5); + + GFG gfg = new GFG(); + +/* Print original list*/ + + gfg.printlist(head); + +/* Modify the list*/ + + gfg.rearrange(head); + +/* Print modified list*/ + + gfg.printlist(head); + } +} + + +"," '''Python3 implementation''' + +class Node: + + def __init__(self, key): + + self.data = key + self.next = None + + + +left = None '''Function to print the list''' + +def printlist(head): + + while (head != None): + print(head.data, end = "" "") + if (head.next != None): + print(""->"", end = """") + + head = head.next + + print() + + '''Function to rearrange''' + +def rearrange(head): + + global left + if (head != None): + left = head + reorderListUtil(left) + +def reorderListUtil(right): + + global left + if (right == None): + return + + reorderListUtil(right.next) + + ''' We set left = null, when we reach stop + condition, so no processing required + after that''' + + if (left == None): + return + + ''' Stop condition: odd case : left = right, even + case : left.next = right''' + + if (left != right and left.next != right): + temp = left.next + left.next = right + right.next = temp + left = temp + else: + + ''' Stop condition , set null to left nodes''' + + if (left.next == right): + + ''' Even case''' + + left.next.next = None + left = None + else: + + ''' Odd case''' + + left.next = None + left = None + + '''Driver code''' + +head = Node(1) +head.next = Node(2) +head.next.next = Node(3) +head.next.next.next = Node(4) +head.next.next.next.next = Node(5) + + '''Print original list''' + +printlist(head) + + ''' Modify the list''' + +rearrange(head) + + '''Print modified list''' + +printlist(head) + + +" +Flip Binary Tree,"/*Java program to flip a binary tree*/ + +import java.util.*; +class GFG +{ +/*A binary tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*Utility function to create +a new Binary Tree Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*method to flip the binary tree*/ + +static Node flipBinaryTree(Node root) +{ +/* Initialization of pointers*/ + + Node curr = root; + Node next = null; + Node temp = null; + Node prev = null; +/* Iterate through all left nodes*/ + + while(curr != null) + { + next = curr.left; +/* Swapping nodes now, need + temp to keep the previous + right child + Making prev's right + as curr's left child*/ + + curr.left = temp; +/* Storing curr's right child*/ + + temp = curr.right; +/* Making prev as curr's + right child*/ + + curr.right = prev; + prev = curr; + curr = next; + } + return prev; +} +/*Iterative method to do +level order traversal +line by line*/ + +static void printLevelOrder(Node root) +{ +/* Base Case*/ + + if (root == null) return; +/* Create an empty queue for + level order traversal*/ + + Queue q = new LinkedList(); +/* Enqueue Root and + initialize height*/ + + q.add(root); + while (true) + { +/* nodeCount (queue size) + indicates number of nodes + at current lelvel.*/ + + int nodeCount = q.size(); + if (nodeCount == 0) + break; +/* Dequeue all nodes of current + level and Enqueue all nodes + of next level*/ + + while (nodeCount > 0) + { + Node node = q.peek(); + System.out.print(node.data + "" ""); + q.remove(); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + nodeCount--; + } + System.out.println(); + } +} +/*Driver code*/ + +public static void main(String args[]) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.right.left = newNode(4); + root.right.right = newNode(5); + System.out.print(""Level order traversal "" + + ""of given tree\n""); + printLevelOrder(root); + root = flipBinaryTree(root); + System.out.print(""\nLevel order traversal "" + + ""of the flipped tree\n""); + printLevelOrder(root); +} +}"," '''Python3 program to flip +a binary tree''' + +from collections import deque + '''A binary tree node structure''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''method to flip the +binary tree''' + +def flipBinaryTree(root): + ''' Initialization of + pointers''' + + curr = root + next = None + temp = None + prev = None + ''' Iterate through all + left nodes''' + + while(curr): + next = curr.left + ''' Swapping nodes now, need temp + to keep the previous right child + Making prev's right as curr's + left child''' + + curr.left = temp + ''' Storing curr's right child''' + + temp = curr.right + ''' Making prev as curr's right + child''' + + curr.right = prev + prev = curr + curr = next + return prev + '''Iterative method to do level +order traversal line by line''' + +def printLevelOrder(root): + ''' Base Case''' + + if (root == None): + return + ''' Create an empty queue for + level order traversal''' + + q = deque() + ''' Enqueue Root and initialize + height''' + + q.append(root) + while (1): + ''' nodeCount (queue size) indicates + number of nodes at current level.''' + + nodeCount = len(q) + if (nodeCount == 0): + break + ''' Dequeue all nodes of current + level and Enqueue all nodes + of next level''' + + while (nodeCount > 0): + node = q.popleft() + print(node.data, end = "" "") + if (node.left != None): + q.append(node.left) + if (node.right != None): + q.append(node.right) + nodeCount -= 1 + print() + '''Driver code''' + +if __name__ == '__main__': + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.right.left = Node(4) + root.right.right = Node(5) + print(""Level order traversal of given tree"") + printLevelOrder(root) + root = flipBinaryTree(root) + print(""\nLevel order traversal of the flipped"" + "" tree"") + printLevelOrder(root)" +Magical Indices in an array,"/*Java program to find number of magical +indices in the given array.*/ + +import java.io.*; +import java.util.*; +public class GFG { +/* Function to count number of magical + indices.*/ + + static int solve(int []A, int n) + { + int i, cnt = 0, j; +/* Array to store parent node of + traversal.*/ + + int []parent = new int[n + 1]; +/* Array to determine whether current node + is already counted in the cycle.*/ + + int []vis = new int[n + 1]; +/* Initialize the arrays.*/ + + for (i = 0; i < n+1; i++) { + parent[i] = -1; + vis[i] = 0; + } + for (i = 0; i < n; i++) { + j = i; +/* Check if current node is already + traversed or not. If node is not + traversed yet then parent value + will be -1.*/ + + if (parent[j] == -1) { +/* Traverse the graph until an + already visited node is not + found.*/ + + while (parent[j] == -1) { + parent[j] = i; + j = (j + A[j] + 1) % n; + } +/* Check parent value to ensure + a cycle is present.*/ + + if (parent[j] == i) { +/* Count number of nodes in + the cycle.*/ + + while (vis[j]==0) { + vis[j] = 1; + cnt++; + j = (j + A[j] + 1) % n; + } + } + } + } + return cnt; + } +/* Driver code */ + + public static void main(String args[]) + { + int []A = { 0, 0, 0, 2 }; + int n = A.length; + System.out.print(solve(A, n)); + } +}"," '''Python3 program to find number of magical +indices in the given array.''' + + '''Function to count number of magical +indices.''' + +def solve(A, n) : + cnt = 0 ''' Array to store parent node of + traversal.''' + + parent = [None] * (n + 1) + ''' Array to determine whether current node + is already counted in the cycle.''' + + vis = [None] * (n + 1) + ''' Initialize the arrays.''' + + for i in range(0, n+1): + parent[i] = -1 + vis[i] = 0 + for i in range(0, n): + j = i + ''' Check if current node is already + traversed or not. If node is not + traversed yet then parent value + will be -1.''' + + if (parent[j] == -1) : + ''' Traverse the graph until an + already visited node is not + found.''' + + while (parent[j] == -1) : + parent[j] = i + j = (j + A[j] + 1) % n + ''' Check parent value to ensure + a cycle is present.''' + + if (parent[j] == i) : + ''' Count number of nodes in + the cycle.''' + + while (vis[j]==0) : + vis[j] = 1 + cnt = cnt + 1 + j = (j + A[j] + 1) % n + return cnt + '''Driver code ''' + +A = [ 0, 0, 0, 2 ] +n = len(A) +print (solve(A, n))" +Find four elements that sum to a given value | Set 2,"/*A hashing based Java program to find +if there are four elements with given sum.*/ + +import java.util.HashMap; +class GFG { + static class pair { + int first, second; + public pair(int first, int second) + { + this.first = first; + this.second = second; + } + } + +/* The function finds four elements + with given sum X*/ + + static void findFourElements(int arr[], int n, int X) + { +/* Store sums of all pairs in a hash table*/ + + HashMap mp + = new HashMap(); + for (int i = 0; i < n - 1; i++) + for (int j = i + 1; j < n; j++) + mp.put(arr[i] + arr[j], new pair(i, j)); + +/* Traverse through all pairs and search + for X - (current pair sum).*/ + + for (int i = 0; i < n - 1; i++) { + for (int j = i + 1; j < n; j++) { + int sum = arr[i] + arr[j]; + +/* If X - sum is present in hash table,*/ + + if (mp.containsKey(X - sum)) { + +/* Making sure that all elements are + distinct array elements and an + element is not considered more than + once.*/ + + pair p = mp.get(X - sum); + if (p.first != i && p.first != j + && p.second != i && p.second != j) { + System.out.print( + arr[i] + "", "" + arr[j] + "", "" + + arr[p.first] + "", "" + + arr[p.second]); + return; + } + } + } + } + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 10, 20, 30, 40, 1, 2 }; + int n = arr.length; + int X = 91; + +/* Function call*/ + + findFourElements(arr, n, X); + } +} + + +"," '''A hashing based Python program to find if there are +four elements with given summ.''' + + + '''The function finds four elements with given summ X''' + + + +def findFourElements(arr, n, X): + + ''' Store summs of all pairs in a hash table''' + + mp = {} + for i in range(n - 1): + for j in range(i + 1, n): + mp[arr[i] + arr[j]] = [i, j] + + ''' Traverse through all pairs and search + for X - (current pair summ).''' + + for i in range(n - 1): + for j in range(i + 1, n): + summ = arr[i] + arr[j] + + ''' If X - summ is present in hash table,''' + + if (X - summ) in mp: + + ''' Making sure that all elements are + distinct array elements and an element + is not considered more than once.''' + + p = mp[X - summ] + if (p[0] != i and p[0] != j and p[1] != i and p[1] != j): + print(arr[i], "", "", arr[j], "", "", + arr[p[0]], "", "", arr[p[1]], sep="""") + return + + + '''Driver code''' + +arr = [10, 20, 30, 40, 1, 2] +n = len(arr) +X = 91 + + '''Function call''' + +findFourElements(arr, n, X) + + +" +Expression Evaluation,"/* A Java program to evaluate a + given expression where tokens + are separated by space. +*/ + +import java.util.Stack; +public class EvaluateString +{ + +/* Returns true if 'op2' has higher + or same precedence as 'op1', + otherwise returns false.*/ + + public static boolean hasPrecedence( + char op1, char op2) + { + if (op2 == '(' || op2 == ')') + return false; + if ((op1 == '*' || op1 == '/') && + (op2 == '+' || op2 == '-')) + return false; + else + return true; + } +/* A utility method to apply an + operator 'op' on operands 'a' + and 'b'. Return the result.*/ + + public static int applyOp(char op, + int b, int a) + { + switch (op) + { + case '+': + return a + b; + case '-': + return a - b; + case '*': + return a * b; + case '/': + if (b == 0) + throw new + UnsupportedOperationException( + ""Cannot divide by zero""); + return a / b; + } + return 0; + } +/*Function that returns value of +expression after evaluation.*/ + + public static int evaluate(String expression) + { + char[] tokens = expression.toCharArray();/* Stack for numbers: 'values'*/ + + Stack values = new + Stack(); +/* Stack for Operators: 'ops'*/ + + Stack ops = new + Stack(); + for (int i = 0; i < tokens.length; i++) + { +/* Current token is a + whitespace, skip it*/ + + if (tokens[i] == ' ') + continue; +/* Current token is an opening brace, + push it to 'ops'*/ + + else if (tokens[i] == '(') + ops.push(tokens[i]); +/* Current token is a number, + push it to stack for numbers*/ + + if (tokens[i] >= '0' && + tokens[i] <= '9') + { + StringBuffer sbuf = new + StringBuffer(); +/* There may be more than one + digits in number*/ + + while (i < tokens.length && + tokens[i] >= '0' && + tokens[i] <= '9') + sbuf.append(tokens[i++]); + values.push(Integer.parseInt(sbuf. + toString())); +/* right now the i points to + the character next to the digit, + since the for loop also increases + the i, we would skip one + token position; we need to + decrease the value of i by 1 to + correct the offset.*/ + + i--; + } +/* Closing brace encountered, + solve entire brace*/ + + else if (tokens[i] == ')') + { + while (ops.peek() != '(') + values.push(applyOp(ops.pop(), + values.pop(), + values.pop())); + ops.pop(); + } +/* Current token is an operator.*/ + + else if (tokens[i] == '+' || + tokens[i] == '-' || + tokens[i] == '*' || + tokens[i] == '/') + { +/* While top of 'ops' has same + or greater precedence to current + token, which is an operator. + Apply operator on top of 'ops' + to top two elements in values stack*/ + + while (!ops.empty() && + hasPrecedence(tokens[i], + ops.peek())) + values.push(applyOp(ops.pop(), + values.pop(), + values.pop())); +/* Push current token to 'ops'.*/ + + ops.push(tokens[i]); + } + } +/* Entire expression has been + parsed at this point, apply remaining + ops to remaining values*/ + + while (!ops.empty()) + values.push(applyOp(ops.pop(), + values.pop(), + values.pop())); +/* Top of 'values' contains + result, return it*/ + + return values.pop(); + } +/* Driver method to test above methods*/ + + public static void main(String[] args) + { + System.out.println(EvaluateString. + evaluate(""10 + 2 * 6"")); + System.out.println(EvaluateString. + evaluate(""100 * 2 + 12"")); + System.out.println(EvaluateString. + evaluate(""100 * ( 2 + 12 )"")); + System.out.println(EvaluateString. + evaluate(""100 * ( 2 + 12 ) / 14"")); + } +}"," '''Python3 program to evaluate a given +expression where tokens are +separated by space.''' + + '''Function to find precedence +of operators.''' + +def precedence(op): + if op == '+' or op == '-': + return 1 + if op == '*' or op == '/': + return 2 + return 0 '''Function to perform arithmetic +operations.''' + +def applyOp(a, b, op): + if op == '+': return a + b + if op == '-': return a - b + if op == '*': return a * b + if op == '/': return a // b + '''Function that returns value of +expression after evaluation.''' + +def evaluate(tokens): + ''' stack to store integer values.''' + + values = [] + ''' stack to store operators.''' + + ops = [] + i = 0 + while i < len(tokens): + ''' Current token is a whitespace, + skip it.''' + + if tokens[i] == ' ': + i += 1 + continue + ''' Current token is an opening + brace, push it to 'ops''' + ''' + elif tokens[i] == '(': + ops.append(tokens[i]) + ''' Current token is a number, push + it to stack for numbers.''' + + elif tokens[i].isdigit(): + val = 0 + ''' There may be more than one + digits in the number.''' + + while (i < len(tokens) and + tokens[i].isdigit()): + val = (val * 10) + int(tokens[i]) + i += 1 + values.append(val) + ''' right now the i points to + the character next to the digit, + since the for loop also increases + the i, we would skip one + token position; we need to + decrease the value of i by 1 to + correct the offset.''' + + i-=1 + ''' Closing brace encountered, + solve entire brace.''' + + elif tokens[i] == ')': + while len(ops) != 0 and ops[-1] != '(': + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + values.append(applyOp(val1, val2, op)) + ''' pop opening brace.''' + + ops.pop() + ''' Current token is an operator.''' + + else: + ''' While top of 'ops' has same or + greater precedence to current + token, which is an operator. + Apply operator on top of 'ops' + to top two elements in values stack.''' + + while (len(ops) != 0 and + precedence(ops[-1]) >= + precedence(tokens[i])): + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + values.append(applyOp(val1, val2, op)) + ''' Push current token to 'ops'.''' + + ops.append(tokens[i]) + i += 1 + ''' Entire expression has been parsed + at this point, apply remaining ops + to remaining values.''' + + while len(ops) != 0: + val2 = values.pop() + val1 = values.pop() + op = ops.pop() + values.append(applyOp(val1, val2, op)) + ''' Top of 'values' contains result, + return it.''' + + return values[-1] + '''Driver Code''' + +if __name__ == ""__main__"": + print(evaluate(""10 + 2 * 6"")) + print(evaluate(""100 * 2 + 12"")) + print(evaluate(""100 * ( 2 + 12 )"")) + print(evaluate(""100 * ( 2 + 12 ) / 14""))" +MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction),"/*Java Program to compute sum of ranges for different range +queries.*/ + +import java.util.*; +/*Class to represent a query range*/ + +class Query{ + int L; + int R; + Query(int L, int R){ + this.L = L; + this.R = R; + } +} +class GFG +{ +/* Prints sum of all query ranges. m is number of queries + n is the size of the array.*/ + + static void printQuerySums(int a[], int n, ArrayList q, int m) + { +/* One by one compute sum of all queries*/ + + for (int i=0; i q = new ArrayList(); + q.add(new Query(0,4)); + q.add(new Query(1,3)); + q.add(new Query(2,4)); + int m = q.size(); + printQuerySums(a, n, q, m); + } +}"," '''Python program to compute sum of ranges for different range queries.''' + '''Function that accepts array and list of queries and print sum of each query''' + +def printQuerySum(arr,Q): + '''Traverse through each query''' + + for q in Q: + '''Extract left and right indices''' + + L,R = q + + '''Compute sum of current query range''' + s = 0 + for i in range(L,R+1): + s += arr[i] + + '''Print sum of current query range''' + + print(""Sum of"",q,""is"",s) + '''Driver script''' + +arr = [1, 1, 2, 1, 3, 4, 5, 2, 8] +Q = [[0, 4], [1, 3], [2, 4]] +printQuerySum(arr,Q)" +Types of Linked List,"/*Doubly linked list +node*/ + +static class Node +{ + int data; + Node next; + Node prev; +}; + +"," '''structure of Node''' + +class Node: + def __init__(self, data): + self.previous = None + self.data = data + self.next = None +" +Get Level of a node in a Binary Tree,"/*Java program to Get Level of a node in a Binary Tree*/ + +/* A tree node structure */ + +class Node { + int data; + Node left, right; + public Node(int d) + { + data = d; + left = right = null; + } +} +class BinaryTree { + Node root; + /* Helper function for getLevel(). + It returns level of + the data if data is present in tree, + otherwise returns + 0.*/ + + int getLevelUtil(Node node, int data, int level) + { + if (node == null) + return 0; + if (node.data == data) + return level; + int downlevel + = getLevelUtil(node.left, data, level + 1); + if (downlevel != 0) + return downlevel; + downlevel + = getLevelUtil(node.right, data, level + 1); + return downlevel; + } + /* Returns level of given data value */ + + int getLevel(Node node, int data) + { + return getLevelUtil(node, data, 1); + } + /* Driver code */ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + /* Constructing tree given in the above figure */ + + tree.root = new Node(3); + tree.root.left = new Node(2); + tree.root.right = new Node(5); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(4); + for (int x = 1; x <= 5; x++) + { + int level = tree.getLevel(tree.root, x); + if (level != 0) + System.out.println( + ""Level of "" + x + "" is "" + + tree.getLevel(tree.root, x)); + else + System.out.println( + x + "" is not present in tree""); + } + } +}"," '''Python3 program to Get Level of a +node in a Binary Tree +Helper function that allocates a +new node with the given data and +None left and right pairs.''' + +class newNode: + ''' Constructor to create a new node''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Helper function for getLevel(). It +returns level of the data if data is +present in tree, otherwise returns 0''' + +def getLevelUtil(node, data, level): + if (node == None): + return 0 + if (node.data == data): + return level + downlevel = getLevelUtil(node.left, + data, level + 1) + if (downlevel != 0): + return downlevel + downlevel = getLevelUtil(node.right, + data, level + 1) + return downlevel + '''Returns level of given data value''' + +def getLevel(node, data): + return getLevelUtil(node, data, 1) + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us construct the Tree shown + in the above figure''' + + root = newNode(3) + root.left = newNode(2) + root.right = newNode(5) + root.left.left = newNode(1) + root.left.right = newNode(4) + for x in range(1, 6): + level = getLevel(root, x) + if (level): + print(""Level of"", x, + ""is"", getLevel(root, x)) + else: + print(x, ""is not present in tree"")" +Check if all levels of two trees are anagrams or not,"/* Iterative program to check if two trees +are level by level anagram. */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Queue; +public class GFG +{ +/* A Binary Tree Node*/ + + static class Node + { + Node left, right; + int data; + Node(int data){ + this.data = data; + left = null; + right = null; + } + } +/* Returns true if trees with root1 and root2 + are level by level anagram, else returns false.*/ + + static boolean areAnagrams(Node root1, Node root2) + { +/* Base Cases*/ + + if (root1 == null && root2 == null) + return true; + if (root1 == null || root2 == null) + return false; +/* start level order traversal of two trees + using two queues.*/ + + Queue q1 = new LinkedList(); + Queue q2 = new LinkedList(); + q1.add(root1); + q2.add(root2); + while (true) + { +/* n1 (queue size) indicates number of + Nodes at current level in first tree + and n2 indicates number of nodes in + current level of second tree.*/ + + int n1 = q1.size(), n2 = q2.size(); +/* If n1 and n2 are different */ + + if (n1 != n2) + return false; +/* If level order traversal is over */ + + if (n1 == 0) + break; +/* Dequeue all Nodes of current level and + Enqueue all Nodes of next level*/ + + ArrayList curr_level1 = new + ArrayList<>(); + ArrayList curr_level2 = new + ArrayList<>(); + while (n1 > 0) + { + Node node1 = q1.peek(); + q1.remove(); + if (node1.left != null) + q1.add(node1.left); + if (node1.right != null) + q1.add(node1.right); + n1--; + Node node2 = q2.peek(); + q2.remove(); + if (node2.left != null) + q2.add(node2.left); + if (node2.right != null) + q2.add(node2.right); + curr_level1.add(node1.data); + curr_level2.add(node2.data); + } +/* Check if nodes of current levels are + anagrams or not.*/ + + Collections.sort(curr_level1); + Collections.sort(curr_level2); + if (!curr_level1.equals(curr_level2)) + return false; + } + return true; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { +/* Constructing both the trees.*/ + + Node root1 = new Node(1); + root1.left = new Node(3); + root1.right = new Node(2); + root1.right.left = new Node(5); + root1.right.right = new Node(4); + Node root2 = new Node(1); + root2.left = new Node(2); + root2.right = new Node(3); + root2.left.left = new Node(4); + root2.left.right = new Node(5); + System.out.println(areAnagrams(root1, root2)? + ""Yes"" : ""No""); + } +}"," '''Iterative program to check if two +trees are level by level anagram''' + + '''Returns true if trees with root1 +and root2 are level by level +anagram, else returns false. ''' + +def areAnagrams(root1, root2) : + ''' Base Cases ''' + + if (root1 == None and root2 == None) : + return True + if (root1 == None or root2 == None) : + return False + ''' start level order traversal of + two trees using two queues. ''' + + q1 = [] + q2 = [] + q1.append(root1) + q2.append(root2) + while (1) : + ''' n1 (queue size) indicates number + of Nodes at current level in first + tree and n2 indicates number of nodes + in current level of second tree. ''' + + n1 = len(q1) + n2 = len(q2) + ''' If n1 and n2 are different ''' + + if (n1 != n2): + return False + ''' If level order traversal is over ''' + + if (n1 == 0): + break + ''' Dequeue all Nodes of current level + and Enqueue all Nodes of next level''' + + curr_level1 = [] + curr_level2 = [] + while (n1 > 0): + node1 = q1[0] + q1.pop(0) + if (node1.left != None) : + q1.append(node1.left) + if (node1.right != None) : + q1.append(node1.right) + n1 -= 1 + node2 = q2[0] + q2.pop(0) + if (node2.left != None) : + q2.append(node2.left) + if (node2.right != None) : + q2.append(node2.right) + curr_level1.append(node1.data) + curr_level2.append(node2.data) + ''' Check if nodes of current levels + are anagrams or not. ''' + + curr_level1.sort() + curr_level2.sort() + if (curr_level1 != curr_level2) : + return False + return True + '''Utility function to create a +new tree Node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Driver Code ''' + +if __name__ == '__main__': + ''' Constructing both the trees. ''' + + root1 = newNode(1) + root1.left = newNode(3) + root1.right = newNode(2) + root1.right.left = newNode(5) + root1.right.right = newNode(4) + root2 = newNode(1) + root2.left = newNode(2) + root2.right = newNode(3) + root2.left.left = newNode(4) + root2.left.right = newNode(5) + if areAnagrams(root1, root2): + print(""Yes"") + else: + print(""No"")" +Program for Identity Matrix,"/*Java program to check if a given +matrix is identity*/ + +class GFG { + int MAX = 100; + static boolean isIdentity(int mat[][], int N) + { + for (int row = 0; row < N; row++) + { + for (int col = 0; col < N; col++) + { + if (row == col && mat[row][col] != 1) + return false; + else if (row != col && mat[row][col] != 0) + return false; + } + } + return true; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int N = 4; + int mat[][] = {{1, 0, 0, 0}, + {0, 1, 0, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 1}}; + if (isIdentity(mat, N)) + System.out.println(""Yes ""); + else + System.out.println(""No ""); + } +}"," '''Python3 program to check +if a given matrix is identity''' + +MAX = 100; +def isIdentity(mat, N): + for row in range(N): + for col in range(N): + if (row == col and + mat[row][col] != 1): + return False; + elif (row != col and + mat[row][col] != 0): + return False; + return True; + '''Driver Code''' + +N = 4; +mat = [[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1]]; +if (isIdentity(mat, N)): + print(""Yes ""); +else: + print(""No "");" +Sort a Rotated Sorted Array,"/*Java implementation for restoring original +sort in rotated sorted array*/ + +class GFG +{ + +/*Function to restore the Original Sort*/ + +static void restoreSortedArray(int arr[], int n) +{ + for (int i = 0; i < n; i++) + { + if (arr[i] > arr[i + 1]) + { + +/* In reverse(), the first parameter + is iterator to beginning element + and second parameter is iterator + to last element plus one.*/ + + reverse(arr,0,i); + reverse(arr , i + 1, n); + reverse(arr,0, n); + } + } +} + +static void reverse(int[] arr, int i, int j) +{ + int temp; + while(i < j) + { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + i++; + j--; + } +} + +/*Function to print the Array*/ + +static void printArray(int arr[], int size) +{ + for (int i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 3, 4, 5, 1, 2 }; + int n = arr.length; + restoreSortedArray(arr, n - 1); + printArray(arr, n); +} +} + + +"," '''Python3 implementation for restoring original +sort in rotated sorted array''' + + + '''Function to restore the Original Sort''' + +def restoreSortedArray(arr, n): + for i in range(n): + if (arr[i] > arr[i + 1]): + ''' In reverse(), the first parameter + is iterator to beginning element + and second parameter is iterator + to last element plus one.''' + + reverse(arr, 0, i); + reverse(arr, i + 1, n); + reverse(arr, 0, n); + +def reverse(arr, i, j): + while (i < j): + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + i += 1; + j -= 1; + + '''Function to print the Array''' + +def printArray(arr, size): + for i in range(size): + print(arr[i], end=""""); + + '''Driver code''' + +if __name__ == '__main__': + arr = [3, 4, 5, 1, 2]; + n = len(arr); + restoreSortedArray(arr, n - 1); + printArray(arr, n); + + +" +Construct a complete binary tree from given array in level order fashion,"/*Java program to construct binary tree from +given array in level order fashion*/ + +public class Tree { + Node root; +/* Tree Node*/ + + static class Node { + int data; + Node left, right; + Node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } + } +/* Function to insert nodes in level order*/ + + public Node insertLevelOrder(int[] arr, Node root, + int i) + { +/* Base case for recursion*/ + + if (i < arr.length) { + Node temp = new Node(arr[i]); + root = temp; +/* insert left child*/ + + root.left = insertLevelOrder(arr, root.left, + 2 * i + 1); +/* insert right child*/ + + root.right = insertLevelOrder(arr, root.right, + 2 * i + 2); + } + return root; + } +/* Function to print tree nodes in InOrder fashion*/ + + public void inOrder(Node root) + { + if (root != null) { + inOrder(root.left); + System.out.print(root.data + "" ""); + inOrder(root.right); + } + } +/* Driver program to test above function*/ + + public static void main(String args[]) + { + Tree t2 = new Tree(); + int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 }; + t2.root = t2.insertLevelOrder(arr, t2.root, 0); + t2.inOrder(t2.root); + } +}"," '''Python3 program to construct binary +tree from given array in level +order fashion Tree Node ''' + + '''Helper function that allocates a +new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to insert nodes in level order ''' + +def insertLevelOrder(arr, root, i, n): + ''' Base case for recursion ''' + + if i < n: + temp = newNode(arr[i]) + root = temp + ''' insert left child ''' + + root.left = insertLevelOrder(arr, root.left, + 2 * i + 1, n) + ''' insert right child ''' + + root.right = insertLevelOrder(arr, root.right, + 2 * i + 2, n) + return root + '''Function to print tree nodes in +InOrder fashion ''' + +def inOrder(root): + if root != None: + inOrder(root.left) + print(root.data,end="" "") + inOrder(root.right) + '''Driver Code''' + +if __name__ == '__main__': + arr = [1, 2, 3, 4, 5, 6, 6, 6, 6] + n = len(arr) + root = None + root = insertLevelOrder(arr, root, 0, n) + inOrder(root)" +Divide an array into k segments to maximize maximum of segment minimums,"/*Java Program to find maximum +value of maximum of minimums +of k segments.*/ + +import java .io.*; +import java .util.*; + +class GFG +{ + +/* function to calculate + the max of all the + minimum segments*/ + + static int maxOfSegmentMins(int []a, + int n, + int k) + { + +/* if we have to divide + it into 1 segment then + the min will be the answer*/ + + if (k == 1) + { + Arrays.sort(a); + return a[0]; + } + + if (k == 2) + return Math.max(a[0], + a[n - 1]); + +/* If k >= 3, return + maximum of all + elements.*/ + + return a[n - 1]; + } + +/* Driver Code*/ + + static public void main (String[] args) + { + int []a = {-10, -9, -8, + 2, 7, -6, -5}; + int n = a.length; + int k = 2; + + System.out.println( + maxOfSegmentMins(a, n, k)); + } +} + + +"," '''Python3 Program to find maximum value of +maximum of minimums of k segments.''' + + + '''function to calculate the max of all the +minimum segments''' + +def maxOfSegmentMins(a,n,k): + + ''' if we have to divide it into 1 segment + then the min will be the answer''' + + if k ==1: + return min(a) + if k==2: + return max(a[0],a[n-1]) + + ''' If k >= 3, return maximum of all + elements.''' + + return max(a) + + '''Driver code''' + +if __name__=='__main__': + a = [-10, -9, -8, 2, 7, -6, -5] + n = len(a) + k =2 + print(maxOfSegmentMins(a,n,k)) + + +" +Array range queries over range queries,"/*Java program to perform range queries over range +queries.*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Updates a node in Binary Index Tree (BITree) at given index + in BITree. The given value 'val' is added to BITree[i] and + all of its ancestors in tree.*/ + + static void updateBIT(int BITree[], int n, int index, int val) + { +/* index in BITree[] is 1 more than the index in arr[]*/ + + index = index + 1; +/* Traverse all ancestors and add 'val'*/ + + while (index <= n) + { +/* Add 'val' to current node of BI Tree*/ + + BITree[index] = (val + BITree[index]); +/* Update index to that of parent in update View*/ + + index = (index + (index & (-index))); + } + return; + } +/* Constructs and returns a Binary Indexed Tree for given + array of size n.*/ + + static int[] constructBITree(int n) + { +/* Create and initialize BITree[] as 0*/ + + int[] BITree = new int[n + 1]; + for (int i = 1; i <= n; i++) + BITree[i] = 0; + return BITree; + } +/* Returns sum of arr[0..index]. This function assumes + that the array is preprocessed and partial sums of + array elements are stored in BITree[]*/ + + static int getSum(int BITree[], int index) + { + int sum = 0; +/* index in BITree[] is 1 more than the index in arr[]*/ + + index = index + 1; +/* Traverse ancestors of BITree[index]*/ + + while (index > 0) + { +/* Add element of BITree to sum*/ + + sum = (sum + BITree[index]); +/* Move index to parent node in getSum View*/ + + index -= index & (-index); + } + return sum; + } +/* Function to update the BITree*/ + + static void update(int BITree[], int l, int r, int n, int val) + { + updateBIT(BITree, n, l, val); + updateBIT(BITree, n, r + 1, -val); + return; + } +/* Driver code*/ + + public static void main (String[] args) + { + int n = 5, m = 5; + int temp[] = { 1, 1, 2, 1, 4, 5, 2, 1, 2, + 2, 1, 3, 2, 3, 4 }; + int[][] q = new int[6][3]; + int j = 0; + for (int i = 1; i <= m; i++) { + q[i][0] = temp[j++]; + q[i][1] = temp[j++]; + q[i][2] = temp[j++]; + } +/* BITree for query of type 2*/ + + int[] BITree = constructBITree(m); +/* BITree for query of type 1*/ + + int[] BITree2 = constructBITree(n); +/* Input the queries in a 2D matrix*/ +Scanner sc=new Scanner(System.in); + for (int i = 1; i <= m; i++) + { + q[i][0]=sc.nextInt(); + q[i][1]=sc.nextInt(); + q[i][2]=sc.nextInt(); + } + /* If query is of type 2 then function call + to update with BITree*/ + + for (int i = m; i >= 1; i--) + if (q[i][0] == 2) + update(BITree, q[i][1] - 1, q[i][2] - 1, m, 1); + for (int i = m; i >= 1; i--) { + if (q[i][0] == 2) { + int val = getSum(BITree, i - 1); + update(BITree, q[i][1] - 1, q[i][2] - 1, m, val); + } + } +/* If query is of type 1 then function call + to update with BITree2*/ + + for (int i = m; i >= 1; i--) { + if (q[i][0] == 1) { + int val = getSum(BITree, i - 1); + update(BITree2, q[i][1] - 1, q[i][2] - 1, + n, (val + 1)); + } + } + for (int i = 1; i <= n; i++) + System.out.print(getSum(BITree2, i - 1)+"" ""); + } +}", +Remove all nodes which don't lie in any path with sum>= k,"/*Java program to implement +the above approach*/ + +import java.util.*; +class GFG +{ +/*A utility function to get +maximum of two integers */ + +static int max(int l, int r) +{ + return (l > r ? l : r); +} +/*A Binary Tree Node */ + +static class Node +{ + int data; + Node left, right; +}; +static class INT +{ + int v; +INT(int a) +{ + v = a; +} +} +/*A utility function to create +a new Binary Tree node with +given data */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return node; +} +/*print the tree in LVR +(Inorder traversal) way. */ + +static void print(Node root) +{ + if (root != null) + { + print(root.left); + System.out.print(root.data + "" ""); + print(root.right); + } +} +/*Main function which +truncates the binary tree. */ + +static Node pruneUtil(Node root, int k, + INT sum) +{ +/* Base Case */ + + if (root == null) return null; +/* Initialize left and right + sums as sum from root to + this node (including this node) */ + + INT lsum = new INT(sum.v + (root.data)); + INT rsum = new INT(lsum.v); +/* Recursively prune left + and right subtrees */ + + root.left = pruneUtil(root.left, k, lsum); + root.right = pruneUtil(root.right, k, rsum); +/* Get the maximum of + left and right sums */ + + sum.v = max(lsum.v, rsum.v); +/* If maximum is smaller + than k, then this node + must be deleted */ + + if (sum.v < k) + { + root = null; + } + return root; +} +/*A wrapper over pruneUtil() */ + +static Node prune(Node root, int k) +{ + INT sum = new INT(0); + return pruneUtil(root, k, sum); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int k = 45; + 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.left.left.left = newNode(8); + root.left.left.right = newNode(9); + root.left.right.left = newNode(12); + root.right.right.left = newNode(10); + root.right.right.left.right = newNode(11); + root.left.left.right.left = newNode(13); + root.left.left.right.right = newNode(14); + root.left.left.right.right.left = newNode(15); + System.out.println(""Tree before truncation\n""); + print(root); +/*k is 45 */ + +root = prune(root, k); + System.out.println(""\n\nTree after truncation\n""); + print(root); +} +}"," '''A class to create a new Binary Tree +node with given data ''' + + '''A utility function to create a new Binary Tree node with given data''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''print the tree in LVR (Inorder traversal) way. ''' + +def Print(root): + if (root != None): + Print(root.left) + print(root.data, end = "" "") + Print(root.right) + '''Main function which truncates +the binary tree. ''' + +def pruneUtil(root, k, Sum): + ''' Base Case ''' + + if (root == None): + return None + ''' Initialize left and right Sums as + Sum from root to this node + (including this node) ''' + + lSum = [Sum[0] + (root.data)] + rSum = [lSum[0]] + ''' Recursively prune left and right + subtrees ''' + + root.left = pruneUtil(root.left, k, lSum) + root.right = pruneUtil(root.right, k, rSum) + ''' Get the maximum of left and right Sums ''' + + Sum[0] = max(lSum[0], rSum[0]) + ''' If maximum is smaller than k, + then this node must be deleted ''' + + if (Sum[0] < k[0]): + root = None + return root + '''A wrapper over pruneUtil() ''' + +def prune(root, k): + Sum = [0] + return pruneUtil(root, k, Sum) + '''Driver Code''' + +if __name__ == '__main__': + k = [45] + 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.left.left.left = newNode(8) + root.left.left.right = newNode(9) + root.left.right.left = newNode(12) + root.right.right.left = newNode(10) + root.right.right.left.right = newNode(11) + root.left.left.right.left = newNode(13) + root.left.left.right.right = newNode(14) + root.left.left.right.right.left = newNode(15) + print(""Tree before truncation"") + Print(root) + print() + '''k is 45 ''' + + root = prune(root, k) + print(""Tree after truncation"") + Print(root)" +Check whether a given point lies inside a triangle or not,"/*JAVA Code for Check whether a given point +lies inside a triangle or not*/ + +import java.util.*; +class GFG { + /* A utility function to calculate area of triangle + formed by (x1, y1) (x2, y2) and (x3, y3) */ + + static double area(int x1, int y1, int x2, int y2, + int x3, int y3) + { + return Math.abs((x1*(y2-y3) + x2*(y3-y1)+ + x3*(y1-y2))/2.0); + } + /* A function to check whether point P(x, y) lies + inside the triangle formed by A(x1, y1), + B(x2, y2) and C(x3, y3) */ + + static boolean isInside(int x1, int y1, int x2, + int y2, int x3, int y3, int x, int y) + { + /* Calculate area of triangle ABC */ + + double A = area (x1, y1, x2, y2, x3, y3); + /* Calculate area of triangle PBC */ + + double A1 = area (x, y, x2, y2, x3, y3); + /* Calculate area of triangle PAC */ + + double A2 = area (x1, y1, x, y, x3, y3); + /* Calculate area of triangle PAB */ + + double A3 = area (x1, y1, x2, y2, x, y); + /* Check if sum of A1, A2 and A3 is same as A */ + + return (A == A1 + A2 + A3); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + /* Let us check whether the point P(10, 15) + lies inside the triangle formed by + A(0, 0), B(20, 0) and C(10, 30) */ + + if (isInside(0, 0, 20, 0, 10, 30, 10, 15)) + System.out.println(""Inside""); + else + System.out.println(""Not Inside""); + } +}"," '''A utility function to calculate area +of triangle formed by (x1, y1), +(x2, y2) and (x3, y3)''' + +def area(x1, y1, x2, y2, x3, y3): + return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + + x3 * (y1 - y2)) / 2.0) + '''A function to check whether point P(x, y) +lies inside the triangle formed by +A(x1, y1), B(x2, y2) and C(x3, y3)''' + +def isInside(x1, y1, x2, y2, x3, y3, x, y): + ''' Calculate area of triangle ABC''' + + A = area (x1, y1, x2, y2, x3, y3) + ''' Calculate area of triangle PBC''' + + A1 = area (x, y, x2, y2, x3, y3) + ''' Calculate area of triangle PAC''' + + A2 = area (x1, y1, x, y, x3, y3) + ''' Calculate area of triangle PAB''' + + A3 = area (x1, y1, x2, y2, x, y) + ''' Check if sum of A1, A2 and A3 + is same as A''' + + if(A == A1 + A2 + A3): + return True + else: + return False + '''Driver program to test above function''' + '''Let us check whether the point P(10, 15) +lies inside the triangle formed by +A(0, 0), B(20, 0) and C(10, 30)''' + +if (isInside(0, 0, 20, 0, 10, 30, 10, 15)): + print('Inside') +else: + print('Not Inside')" +Sorting a Queue without extra space,"/*Java program to implement sorting a +queue data structure*/ + +import java.util.LinkedList; +import java.util.Queue; +class GFG +{ +/* Queue elements after sortIndex are + already sorted. This function returns + index of minimum element from front to + sortIndex*/ + + public static int minIndex(Queue list, + int sortIndex) + { + int min_index = -1; + int min_value = Integer.MAX_VALUE; + int s = list.size(); + for (int i = 0; i < s; i++) + { + int current = list.peek(); +/* This is dequeue() in Java STL*/ + + list.poll(); +/* we add the condition i <= sortIndex + because we don't want to traverse + on the sorted part of the queue, + which is the right part.*/ + + if (current <= min_value && i <= sortIndex) + { + min_index = i; + min_value = current; + } +/*This is enqueue() in C++ STL*/ + + list.add(current); + } + return min_index; +} +/* Moves given minimum element + to rear of queue*/ + + public static void insertMinToRear(Queue list, + int min_index) + { + int min_value = 0; + int s = list.size(); + for (int i = 0; i < s; i++) + { + int current = list.peek(); + list.poll(); + if (i != min_index) + list.add(current); + else + min_value = current; + } + list.add(min_value); + } + +/* SortQueue Function*/ + + public static void sortQueue(Queue list) + { + for(int i = 1; i <= list.size(); i++) + { + int min_index = minIndex(list,list.size() - i); + insertMinToRear(list, min_index); + } + }/* Driver function*/ + + public static void main (String[] args) + { + Queue list = new LinkedList(); + list.add(30); + list.add(11); + list.add(15); + list.add(4); +/* Sort Queue*/ + + sortQueue(list); +/* print sorted Queue*/ + + while(list.isEmpty()== false) + { + System.out.print(list.peek() + "" ""); + list.poll(); + } + } +}"," '''Python3 program to implement sorting a +queue data structure ''' + +from queue import Queue + '''Queue elements after sortedIndex are +already sorted. This function returns +index of minimum element from front to +sortedIndex ''' + +def minIndex(q, sortedIndex): + min_index = -1 + min_val = 999999999999 + n = q.qsize() + for i in range(n): + curr = q.queue[0] + '''This is dequeue() in C++ STL ''' + + q.get() + ''' we add the condition i <= sortedIndex + because we don't want to traverse + on the sorted part of the queue, + which is the right part. ''' + + if (curr <= min_val and i <= sortedIndex): + min_index = i + min_val = curr + '''This is enqueue() in C++ STL''' + + q.put(curr) + return min_index '''Moves given minimum element to +rear of queue ''' + +def insertMinToRear(q, min_index): + min_val = None + n = q.qsize() + for i in range(n): + curr = q.queue[0] + q.get() + if (i != min_index): + q.put(curr) + else: + min_val = curr + q.put(min_val) + ''' SortQueue Function''' + +def sortQueue(q): + for i in range(1, q.qsize() + 1): + min_index = minIndex(q, q.qsize() - i) + insertMinToRear(q, min_index) + '''Driver code ''' + +if __name__ == '__main__': + q = Queue() + q.put(30) + q.put(11) + q.put(15) + q.put(4) + ''' Sort queue ''' + + sortQueue(q) + ''' Prsorted queue ''' + + while (q.empty() == False): + print(q.queue[0], end = "" "") + q.get()" +Check for Majority Element in a sorted array,"/* Program to check for majority element in a sorted array */ + +import java.io.*; +class Majority { + static boolean isMajority(int arr[], int n, int x) + { + int i, last_index = 0; + /* get last index according to n (even or odd) */ + + last_index = (n%2==0)? n/2: n/2+1; + /* search for first occurrence of x in arr[]*/ + + for (i = 0; i < last_index; i++) + { + /* check if x is present and is present more + than n/2 times */ + + if (arr[i] == x && arr[i+n/2] == x) + return true; + } + return false; + } + /* Driver function to check for above functions*/ + + public static void main (String[] args) { + int arr[] = {1, 2, 3, 4, 4, 4, 4}; + int n = arr.length; + int x = 4; + if (isMajority(arr, n, x)==true) + System.out.println(x+"" appears more than ""+ + n/2+"" times in arr[]""); + else + System.out.println(x+"" does not appear more than ""+ + n/2+"" times in arr[]""); + } +}"," '''Python3 Program to check for majority element in a sorted array''' + +def isMajority(arr, n, x): + ''' get last index according to n (even or odd) */''' + + last_index = (n//2 + 1) if n % 2 == 0 else (n//2) + ''' search for first occurrence of x in arr[]*/''' + + for i in range(last_index): + ''' check if x is present and is present more than n / 2 times */''' + + if arr[i] == x and arr[i + n//2] == x: + return 1 + '''Driver program to check above function */''' + +arr = [1, 2, 3, 4, 4, 4, 4] +n = len(arr) +x = 4 +if (isMajority(arr, n, x)): + print (""% d appears more than % d times in arr[]"" + %(x, n//2)) +else: + print (""% d does not appear more than % d times in arr[]"" + %(x, n//2))" +Find height of a special binary tree whose leaf nodes are connected,"/*Java implementation to calculate height of a special tree +whose leaf nodes forms a circular doubly linked list*/ + +import java.io.*; +import java.util.*; +/*User defined node class*/ + +class Node { + int data; + Node left, right; +/* Constructor to create a new tree node*/ + + Node(int key) + { + data = key; + left = right = null; + } +} +class GFG { +/* function to check if given node is a leaf node or + node*/ + + static boolean isLeaf(Node node) + { +/* If given node's left's right is pointing to given + node and its right's left is pointing to the node + itself then it's a leaf*/ + + return (node.left != null && node.left.right == node + && node.right != null + && node.right.left == node); + } + /* Compute the height of a tree -- the number of + Nodes along the longest path from the root node + down to the farthest leaf node.*/ + + static int maxDepth(Node node) + { +/* if node is NULL, return 0*/ + + if (node == null) + return 0; +/* if node is a leaf node, return 1*/ + + if (isLeaf(node)) + return 1; +/* compute the depth of each subtree and take + maximum*/ + + return 1 + + Math.max(maxDepth(node.left), + maxDepth(node.right)); + } +/* Driver code*/ + + public static void main(String args[]) + { + 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.left.left.left = new Node(6); +/* Given tree contains 3 leaf nodes*/ + + Node L1 = root.left.left.left; + Node L2 = root.left.right; + Node L3 = root.right; +/* create circular doubly linked list out of + leaf nodes of the tree + set next pointer of linked list*/ + + L1.right = L2; + L2.right = L3; + L3.right = L1; +/* set prev pointer of linked list*/ + + L3.left = L2; + L2.left = L1; + L1.left = L3; +/* calculate height of the tree*/ + + System.out.println(""Height of tree is "" + + maxDepth(root)); + } +} +"," ''' program to Delete a Tree ''' + + '''Helper function that allocates a new +node with the given data and None +left and right poers.''' + +class newNode: + ''' Construct to create a new node''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''function to check if given node is a leaf node or node''' + +def isLeaf(node): + ''' If given node's left's right is pointing to given node + and its right's left is pointing to the node itself + then it's a leaf''' + + return node.left and node.left.right == node and \ + node.right and node.right.left == node + ''' Compute the height of a tree -- the number of +Nodes along the longest path from the root node +down to the farthest leaf node.''' + +def maxDepth(node): + ''' if node is None, return 0''' + + if (node == None): + return 0 + ''' if node is a leaf node, return 1''' + + if (isLeaf(node)): + return 1 + ''' compute the depth of each subtree and take maximum''' + + return 1 + max(maxDepth(node.left), maxDepth(node.right)) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.left.left.left = newNode(6) + ''' Given tree contains 3 leaf nodes''' + + L1 = root.left.left.left + L2 = root.left.right + L3 = root.right + ''' create circular doubly linked list out of + leaf nodes of the tree + set next pointer of linked list''' + + L1.right = L2 + L2.right = L3 + L3.right = L1 + ''' set prev pointer of linked list''' + + L3.left = L2 + L2.left = L1 + L1.left = L3 + ''' calculate height of the tree''' + + print(""Height of tree is "", maxDepth(root))" +Longest Increasing Subsequence | DP-3,"/* A Naive Java Program for LIS Implementation */ + +class LIS { +/*stores the LIS*/ + +static int max_ref; + /* To make use of recursive calls, this function must + return two things: 1) Length of LIS ending with element + arr[n-1]. We use max_ending_here for this purpose 2) + Overall maximum as the LIS may end with an element + before arr[n-1] max_ref is used this purpose. + The value of LIS of full array of size n is stored in + *max_ref which is our final result */ + + static int _lis(int arr[], int n) + { +/* base case*/ + + if (n == 1) + return 1; +/* 'max_ending_here' is length of LIS ending with + arr[n-1]*/ + + int res, max_ending_here = 1; + /* Recursively get all LIS ending with arr[0], + arr[1] ... arr[n-2]. If arr[i-1] is smaller + than arr[n-1], and max ending with arr[n-1] needs + to be updated, then update it */ + + for (int i = 1; i < n; i++) { + res = _lis(arr, i); + if (arr[i - 1] < arr[n - 1] + && res + 1 > max_ending_here) + max_ending_here = res + 1; + } +/* Compare max_ending_here with the overall max. And + update the overall max if needed*/ + + if (max_ref < max_ending_here) + max_ref = max_ending_here; +/* Return length of LIS ending with arr[n-1]*/ + + return max_ending_here; + } +/* The wrapper function for _lis()*/ + + static int lis(int arr[], int n) + { +/* The max variable holds the result*/ + + max_ref = 1; +/* The function _lis() stores its result in max*/ + + _lis(arr, n); +/* returns max*/ + + return max_ref; + } +/* driver program to test above functions*/ + + public static void main(String args[]) + { + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; + int n = arr.length; + System.out.println(""Length of lis is "" + lis(arr, n) + + ""\n""); + } +}"," '''A naive Python implementation of LIS problem''' + + '''global variable to store the maximum''' + +global maximum ''' To make use of recursive calls, this function must return + two things: + 1) Length of LIS ending with element arr[n-1]. We use + max_ending_here for this purpose + 2) Overall maximum as the LIS may end with an element + before arr[n-1] max_ref is used this purpose. + The value of LIS of full array of size n is stored in + *max_ref which is our final result ''' +def _lis(arr, n): + global maximum + ''' Base Case''' + + if n == 1: + return 1 + ''' maxEndingHere is the length of LIS ending with arr[n-1]''' + + maxEndingHere = 1 + '''Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] + IF arr[n-1] is maller than arr[n-1], and max ending with + arr[n-1] needs to be updated, then update it''' + + for i in xrange(1, n): + res = _lis(arr, i) + if arr[i-1] < arr[n-1] and res+1 > maxEndingHere: + maxEndingHere = res + 1 + ''' Compare maxEndingHere with overall maximum. And + update the overall maximum if needed''' + + maximum = max(maximum, maxEndingHere) + '''Return length of LIS ending with arr[n-1]''' + return maxEndingHere + ''' The wrapper function for _lis()''' +def lis(arr): + global maximum + n = len(arr) + ''' maximum variable holds the result''' + + maximum = 1 + ''' The function _lis() stores its result in maximum''' + + _lis(arr, n) + + '''returns max''' + + return maximum '''Driver program to test the above function''' + +arr = [10, 22, 9, 33, 21, 50, 41, 60] +n = len(arr) +print ""Length of lis is "", lis(arr)" +Prufer Code to Tree Creation,"/*Java program to construct tree from given Prufer Code*/ + +class GFG { +/* Prints edges of tree represented by give Prufer code*/ + + static void printTreeEdges(int prufer[], int m) + { + int vertices = m + 2; + int vertex_set[] = new int[vertices]; +/* Initialize the array of vertices*/ + + for (int i = 0; i < vertices; i++) + vertex_set[i] = 0; +/* Number of occurrences of vertex in code*/ + + for (int i = 0; i < vertices - 2; i++) + vertex_set[prufer[i] - 1] += 1; + System.out.print(""\nThe edge set E(G) is :\n""); +/* Find the smallest label not present in + prufer[].*/ + + int j = 0; + for (int i = 0; i < vertices - 2; i++) { + for (j = 0; j < vertices; j++) { +/* If j+1 is not present in prufer set*/ + + if (vertex_set[j] == 0) { +/* Remove from Prufer set and print + pair.*/ + + vertex_set[j] = -1; + System.out.print(""("" + (j + 1) + "", "" + + prufer[i] + "") ""); + vertex_set[prufer[i] - 1]--; + break; + } + } + } + j = 0; +/* For the last element*/ + + for (int i = 0; i < vertices; i++) { + if (vertex_set[i] == 0 && j == 0) { + System.out.print(""("" + (i + 1) + "", ""); + j++; + } + else if (vertex_set[i] == 0 && j == 1) + System.out.print((i + 1) + "")\n""); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int prufer[] = { 4, 1, 3, 4 }; + int n = prufer.length; + printTreeEdges(prufer, n); + } +}"," '''Python3 program to construct +tree from given Prufer Code ''' + + '''Prints edges of tree represented +by give Prufer code ''' + +def printTreeEdges(prufer, m): + vertices = m + 2 ''' Initialize the array of vertices ''' + + vertex_set = [0] * vertices + ''' Number of occurrences of vertex in code ''' + + for i in range(vertices - 2): + vertex_set[prufer[i] - 1] += 1 + print(""The edge set E(G) is :"") + ''' Find the smallest label not present in + prufer. ''' + + j = 0 + for i in range(vertices - 2): + for j in range(vertices): + ''' If j+1 is not present in prufer set ''' + + if (vertex_set[j] == 0): + ''' Remove from Prufer set and print + pair. ''' + + vertex_set[j] = -1 + print(""("" , (j + 1),"", "",prufer[i],"") "",sep = """",end = """") + vertex_set[prufer[i] - 1] -= 1 + break + j = 0 + ''' For the last element ''' + + for i in range(vertices): + if (vertex_set[i] == 0 and j == 0): + print(""("", (i + 1),"", "", sep="""", end="""") + j += 1 + elif (vertex_set[i] == 0 and j == 1): + print((i + 1),"")"") + '''Driver code ''' + +prufer = [4, 1, 3, 4] +n = len(prufer) +printTreeEdges(prufer, n)" +Distinct adjacent elements in an array,"/*Java program to check if we can make +neighbors distinct.*/ + +import java.io.*; +import java.util.HashMap; +import java.util.Map; +class GFG { + +static void distinctAdjacentElement(int a[], int n) +{ +/*map used to count the frequency +of each element occurring in the +array*/ + +HashMap m = new HashMap(); + +/*In this loop we count the frequency +of element through map m .*/ + +for (int i = 0; i < n; ++i){ + +if(m.containsKey(a[i])){ +int x = m.get(a[i]) + 1; +m.put(a[i],x); +} +else{ +m.put(a[i],1); +} + +} +/*mx store the frequency of element which +occurs most in array .*/ + +int mx = 0; + +/*In this loop we calculate the maximum +frequency and store it in variable mx.*/ + +for (int i = 0; i < n; ++i) +if (mx < m.get(a[i])) +mx = m.get(a[i]); + +/*By swapping we can adjust array only +when the frequency of the element +which occurs most is less than or +equal to (n + 1)/2 .*/ + +if (mx > (n + 1) / 2) +System.out.println(""NO""); +else +System.out.println(""YES""); +} + +/*Driver program to test the above function*/ + +public static void main (String[] args) { +int a[] = { 7, 7, 7, 7 }; +int n = 4; +distinctAdjacentElement(a, n); +} +} + +"," '''Python program to check if we can make +neighbors distinct.''' + +def distantAdjacentElement(a, n): + + ''' dict used to count the frequency + of each element occurring in the + array''' + + m = dict() + + ''' In this loop we count the frequency + of element through map m''' + + for i in range(n): + if a[i] in m: + m[a[i]] += 1 + else: + m[a[i]] = 1 + + ''' mx store the frequency of element which + occurs most in array .''' + + mx = 0 + + ''' In this loop we calculate the maximum + frequency and store it in variable mx.''' + + for i in range(n): + if mx < m[a[i]]: + mx = m[a[i]] + + ''' By swapping we can adjust array only + when the frequency of the element + which occurs most is less than or + equal to (n + 1)/2 .''' + + if mx > (n+1) // 2: + print(""NO"") + else: + print(""YES"") + + + '''Driver Code''' + +if __name__ == ""__main__"": + a = [7, 7, 7, 7] + n = len(a) + distantAdjacentElement(a, n) + + +" +Number of subarrays having sum exactly equal to k,"/*Java program to find number of subarrays +with sum exactly equal to k.*/ + +import java.util.HashMap; +import java.util.Map; +public class GfG { +/* Function to find number of subarrays + with sum exactly equal to k.*/ + + static int findSubarraySum(int arr[], int n, int sum) + { +/* HashMap to store number of subarrays + starting from index zero having + particular value of sum.*/ + + HashMap prevSum = new HashMap<>(); + int res = 0; +/* Sum of elements so far.*/ + + int currsum = 0; + for (int i = 0; i < n; i++) { +/* Add current element to sum so far.*/ + + currsum += arr[i]; +/* If currsum is equal to desired sum, + then a new subarray is found. So + increase count of subarrays.*/ + + if (currsum == sum) + res++; +/* currsum exceeds given sum by currsum + - sum. Find number of subarrays having + this sum and exclude those subarrays + from currsum by increasing count by + same amount.*/ + + if (prevSum.containsKey(currsum - sum)) + res += prevSum.get(currsum - sum); +/* Add currsum value to count of + different values of sum.*/ + + Integer count = prevSum.get(currsum); + if (count == null) + prevSum.put(currsum, 1); + else + prevSum.put(currsum, count + 1); + } + return res; + } + /* Driver Code*/ + +public static void main(String[] args) + { + int arr[] = { 10, 2, -2, -20, 10 }; + int sum = -10; + int n = arr.length; + System.out.println(findSubarraySum(arr, n, sum)); + } +}"," '''Python3 program to find the number of +subarrays with sum exactly equal to k.''' + +from collections import defaultdict + '''Function to find number of subarrays +with sum exactly equal to k.''' + +def findSubarraySum(arr, n, Sum): + ''' Dictionary to store number of subarrays + starting from index zero having + particular value of sum.''' + + prevSum = defaultdict(lambda : 0) + res = 0 + ''' Sum of elements so far.''' + + currsum = 0 + for i in range(0, n): + ''' Add current element to sum so far.''' + + currsum += arr[i] + ''' If currsum is equal to desired sum, + then a new subarray is found. So + increase count of subarrays.''' + + if currsum == Sum: + res += 1 + ''' currsum exceeds given sum by currsum - sum. + Find number of subarrays having + this sum and exclude those subarrays + from currsum by increasing count by + same amount.''' + + if (currsum - Sum) in prevSum: + res += prevSum[currsum - Sum] + ''' Add currsum value to count of + different values of sum.''' + + prevSum[currsum] += 1 + return res + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [10, 2, -2, -20, 10] + Sum = -10 + n = len(arr) + print(findSubarraySum(arr, n, Sum))" +Largest subarray with equal number of 0s and 1s,"class LargestSubArray { +/* This function Prints the starting and ending + indexes of the largest subarray with equal + number of 0s and 1s. Also returns the size + of such subarray.*/ + + int findSubArray(int arr[], int n) + { + int sum = 0; + int maxsize = -1, startindex = 0; + int endindex = 0; +/* Pick a starting point as i*/ + + for (int i = 0; i < n - 1; i++) { + sum = (arr[i] == 0) ? -1 : 1; +/* Consider all subarrays starting from i*/ + + for (int j = i + 1; j < n; j++) { + if (arr[j] == 0) + sum += -1; + else + sum += 1; +/* If this is a 0 sum subarray, then + compare it with maximum size subarray + calculated so far*/ + + if (sum == 0 && maxsize < j - i + 1) { + maxsize = j - i + 1; + startindex = i; + } + } + } + endindex = startindex + maxsize - 1; + if (maxsize == -1) + System.out.println(""No such subarray""); + else + System.out.println(startindex + "" to "" + endindex); + return maxsize; + } + /* Driver program to test the above functions */ + + public static void main(String[] args) + { + LargestSubArray sub; + sub = new LargestSubArray(); + int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; + int size = arr.length; + sub.findSubArray(arr, size); + } +}"," '''A simple program to find the largest subarray +with equal number of 0s and 1s + ''' '''This function Prints the starting and ending +indexes of the largest subarray with equal +number of 0s and 1s. Also returns the size +of such subarray.''' + +def findSubArray(arr, n): + sum = 0 + maxsize = -1 + ''' Pick a starting point as i''' + + for i in range(0, n-1): + sum = -1 if(arr[i] == 0) else 1 + ''' Consider all subarrays starting from i''' + + for j in range(i + 1, n): + sum = sum + (-1) if (arr[j] == 0) else sum + 1 + ''' If this is a 0 sum subarray, then + compare it with maximum size subarray + calculated so far''' + + if (sum == 0 and maxsize < j-i + 1): + maxsize = j - i + 1 + startindex = i + if (maxsize == -1): + print(""No such subarray""); + else: + print(startindex, ""to"", startindex + maxsize-1); + return maxsize + '''Driver program to test above functions''' + +arr = [1, 0, 0, 1, 0, 1, 1] +size = len(arr) +findSubArray(arr, size)" +Activity Selection Problem | Greedy Algo-1,," ''' Python program for activity selection problem + when input activities may not be sorted.''' + + ''' Returns count of the maximum set of activities that + can + be done by a single person, one at a time.''' + +def MaxActivities(arr, n): + + ''' Sort jobs according to finish time''' + selected = [] + Activity.sort(key = lambda x : x[1]) + ''' The first activity always gets selected''' + + i = 0 + selected.append(arr[i]) + + ''' Consider rest of the activities''' + + for j in range(1, n): '''If this activity has start time greater than or + equal to the finish time of previously selected + activity, then select it''' + + if arr[j][0] >= arr[i][1]: + selected.append(arr[j]) + i = j + return selected + '''Driver code''' + +Activity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]] +n = len(Activity) +selected = MaxActivities(Activity, n) +print(""Following activities are selected :"") +print(selected)" +Longest Palindromic Subsequence | DP-12,"/*Java program of above approach*/ + +class GFG { +/* A utility function to get max of two integers*/ + + static int max(int x, int y) { + return (x > y) ? x : y; + } +/* Returns the length of the longest palindromic subsequence in seq*/ + + static int lps(char seq[], int i, int j) { +/* Base Case 1: If there is only 1 character*/ + + if (i == j) { + return 1; + } +/* Base Case 2: If there are only 2 characters and both are same*/ + + if (seq[i] == seq[j] && i + 1 == j) { + return 2; + } +/* If the first and last characters match*/ + + if (seq[i] == seq[j]) { + return lps(seq, i + 1, j - 1) + 2; + } +/* If the first and last characters do not match*/ + + return max(lps(seq, i, j - 1), lps(seq, i + 1, j)); + } + /* Driver program to test above function */ + + public static void main(String[] args) { + String seq = ""GEEKSFORGEEKS""; + int n = seq.length(); + System.out.printf(""The length of the LPS is %d"", lps(seq.toCharArray(), 0, n - 1)); + } +}"," '''Python 3 program of above approach''' + '''A utility function to get max +of two integers''' + +def max(x, y): + if(x > y): + return x + return y + '''Returns the length of the longest +palindromic subsequence in seq''' + +def lps(seq, i, j): + ''' Base Case 1: If there is + only 1 character''' + + if (i == j): + return 1 + ''' Base Case 2: If there are only 2 + characters and both are same''' + + if (seq[i] == seq[j] and i + 1 == j): + return 2 + ''' If the first and last characters match''' + + if (seq[i] == seq[j]): + return lps(seq, i + 1, j - 1) + 2 + ''' If the first and last characters + do not match''' + + return max(lps(seq, i, j - 1), + lps(seq, i + 1, j)) + '''Driver Code''' + +if __name__ == '__main__': + seq = ""GEEKSFORGEEKS"" + n = len(seq) + print(""The length of the LPS is"", + lps(seq, 0, n - 1))" +Longest subarray not having more than K distinct elements,"/*Java program to find longest subarray with +k or less distinct elements.*/ + +import java.util.*; +class GFG +{ +/*function to print the longest sub-array*/ + +static void longest(int a[], int n, int k) +{ + int[] freq = new int[7]; + int start = 0, end = 0, now = 0, l = 0; + for (int i = 0; i < n; i++) + { +/* mark the element visited*/ + + freq[a[i]]++; +/* if its visited first time, then increase + the counter of distinct elements by 1*/ + + if (freq[a[i]] == 1) + now++; +/* When the counter of distinct elements + increases from k, then reduce it to k*/ + + while (now > k) + { +/* from the left, reduce the number of + time of visit*/ + + freq[a[l]]--; +/* if the reduced visited time element + is not present in further segment + then decrease the count of distinct + elements*/ + + if (freq[a[l]] == 0) + now--; +/* increase the subsegment mark*/ + + l++; + } +/* check length of longest sub-segment + when greater then previous best + then change it*/ + + if (i - l + 1 >= end - start + 1) + { + end = i; + start = l; + } + } +/* print the longest sub-segment*/ + + for (int i = start; i <= end; i++) + System.out.print(a[i]+"" ""); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int a[] = { 6, 5, 1, 2, 3, 2, 1, 4, 5 }; + int n = a.length; + int k = 3; + longest(a, n, k); +} +}"," '''Python 3 program to find longest +subarray with k or less distinct elements. + ''' '''function to print the longest sub-array''' + +import collections +def longest(a, n, k): + freq = collections.defaultdict(int) + start = 0 + end = 0 + now = 0 + l = 0 + for i in range(n): + ''' mark the element visited''' + + freq[a[i]] += 1 + ''' if its visited first time, then increase + the counter of distinct elements by 1''' + + if (freq[a[i]] == 1): + now += 1 + ''' When the counter of distinct elements + increases from k, then reduce it to k''' + + while (now > k) : + ''' from the left, reduce the number + of time of visit''' + + freq[a[l]] -= 1 + ''' if the reduced visited time element + is not present in further segment + then decrease the count of distinct + elements''' + + if (freq[a[l]] == 0): + now -= 1 + ''' increase the subsegment mark''' + + l += 1 + ''' check length of longest sub-segment + when greater then previous best + then change it''' + + if (i - l + 1 >= end - start + 1): + end = i + start = l + ''' print the longest sub-segment''' + + for i in range(start, end + 1): + print(a[i], end = "" "") + '''Driver Code''' + +if __name__ == ""__main__"": + a = [ 6, 5, 1, 2, 3, + 2, 1, 4, 5 ] + n = len(a) + k = 3 + longest(a, n, k)" +Pairs such that one is a power multiple of other,"/*Java program to find pairs count*/ + +import java.io.*; +import java .util.*; + +class GFG { + +/* function to count the required pairs*/ + + static int countPairs(int A[], int n, int k) + { + int ans = 0; + +/* sort the given array*/ + + Arrays.sort(A); + +/* for each A[i] traverse rest array*/ + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) + { + +/* count Aj such that Ai*k^x = Aj*/ + + int x = 0; + +/* increase x till Ai * k^x <= largest element*/ + + while ((A[i] * Math.pow(k, x)) <= A[j]) + { + if ((A[i] * Math.pow(k, x)) == A[j]) + { + ans++; + break; + } + x++; + } + } + } + return ans; + } + +/* Driver program*/ + + public static void main (String[] args) + { + int A[] = {3, 8, 9, 12, 18, 4, 24, 2, 6}; + int n = A.length; + int k = 3; + System.out.println (countPairs(A, n, k)); + + } +} + + +"," '''Program to find pairs count''' + +import math + + '''function to count the required pairs''' + +def countPairs(A, n, k): + ans = 0 + + ''' sort the given array''' + + A.sort() + + ''' for each A[i] traverse rest array''' + + for i in range(0,n): + + for j in range(i + 1, n): + + ''' count Aj such that Ai*k^x = Aj''' + + x = 0 + + ''' increase x till Ai * k^x <= largest element''' + + while ((A[i] * math.pow(k, x)) <= A[j]) : + if ((A[i] * math.pow(k, x)) == A[j]) : + ans+=1 + break + x+=1 + return ans + + + '''driver program''' + +A = [3, 8, 9, 12, 18, 4, 24, 2, 6] +n = len(A) +k = 3 + +print(countPairs(A, n, k)) + + +" +Flatten a multi-level linked list | Set 2 (Depth wise),"Node flattenList2(Node head) +{ + Node headcop = head; + Stack save = new Stack<>(); + save.push(head); + Node prev = null; + + while (!save.isEmpty()) { + Node temp = save.peek(); + save.pop(); + + if (temp.next) + save.push(temp.next); + if (temp.down) + save.push(temp.down); + + if (prev != null) + prev.next = temp; + + prev = temp; + } + return headcop; +} + + +","def flattenList2(head): + + headcop = head + save = [] + save.append(head) + prev = None + + while (len(save) != 0): + temp = save[-1] + save.pop() + + if (temp.next): + save.append(temp.next) + if (temp.down): + save.append(temp.down) + + if (prev != None): + prev.next = temp + + prev = temp + + return headcop + + +" +Online algorithm for checking palindrome in a stream,"/*Java program for online algorithm for +palindrome checking*/ + +public class GFG +{ +/* d is the number of characters in + input alphabet*/ + + static final int d = 256; + +/* q is a prime number used for + evaluating Rabin Karp's Rolling hash*/ + + static final int q = 103; + + static void checkPalindromes(String str) + { +/* Length of input string*/ + + int N = str.length(); + +/* A single character is always a palindrome*/ + + System.out.println(str.charAt(0)+"" Yes""); + +/* Return if string has only one character*/ + + if (N == 1) return; + +/* Initialize first half reverse and second + half for as firstr and second characters*/ + + int firstr = str.charAt(0) % q; + int second = str.charAt(1) % q; + + int h = 1, i, j; + +/* Now check for palindromes from second + character onward*/ + + for (i = 1; i < N; i++) + { +/* If the hash values of 'firstr' and + 'second' match, then only check + individual characters*/ + + if (firstr == second) + { + /* Check if str[0..i] is palindrome + using simple character by character + match */ + + for (j = 0; j < i/2; j++) + { + if (str.charAt(j) != str.charAt(i + - j)) + break; + } + System.out.println((j == i/2) ? + str.charAt(i) + "" Yes"": str.charAt(i)+ + "" No""); + } + else System.out.println(str.charAt(i)+ "" No""); + +/* Calculate hash values for next iteration. + Don't calculate hash for next characters + if this is the last character of string*/ + + if (i != N - 1) + { +/* If i is even (next i is odd) */ + + if (i % 2 == 0) + { +/* Add next character after first + half at beginning of 'firstr'*/ + + h = (h * d) % q; + firstr = (firstr + h *str.charAt(i / + 2)) % q; + +/* Add next character after second + half at the end of second half.*/ + + second = (second * d + str.charAt(i + + 1)) % q; + } + else + { +/* If next i is odd (next i is even) + then we need not to change firstr, + we need to remove first character + of second and append a character + to it.*/ + + second = (d * (second + q - str.charAt( + (i + 1) / 2) * h) % q + + str.charAt(i + 1)) % q; + } + } + } + } + + /* Driver program to test above function */ + + public static void main(String args[]) + { + String txt = ""aabaacaabaa""; + checkPalindromes(txt); + } +} + +"," '''Python program Online algorithm for checking palindrome +in a stream''' + + + '''d is the number of characters in input alphabet''' + +d = 256 + + '''q is a prime number used for evaluating Rabin Karp's +Rolling hash''' + +q = 103 + +def checkPalindromes(string): + + ''' Length of input string''' + + N = len(string) + + ''' A single character is always a palindrome''' + + print string[0] + "" Yes"" + + ''' Return if string has only one character''' + + if N == 1: + return + + ''' Initialize first half reverse and second half for + as firstr and second characters''' + + firstr = ord(string[0]) % q + second = ord(string[1]) % q + + h = 1 + i = 0 + j = 0 + + ''' Now check for palindromes from second character + onward''' + + for i in xrange(1,N): + + ''' If the hash values of 'firstr' and 'second' + match, then only check individual characters''' + + if firstr == second: + + ''' Check if str[0..i] is palindrome using + simple character by character match''' + + for j in xrange(0,i/2): + if string[j] != string[i-j]: + break + j += 1 + if j == i/2: + print string[i] + "" Yes"" + else: + print string[i] + "" No"" + else: + print string[i] + "" No"" + + ''' Calculate hash values for next iteration. + Don't calculate hash for next characters if + this is the last character of string''' + + if i != N-1: + + ''' If i is even (next i is odd)''' + + if i % 2 == 0: + + ''' Add next character after first half at + beginning of 'firstr''' + ''' + h = (h*d) % q + firstr = (firstr + h*ord(string[i/2]))%q + + ''' Add next character after second half at + the end of second half.''' + + second = (second*d + ord(string[i+1]))%q + else: + ''' If next i is odd (next i is even) then we + need not to change firstr, we need to remove + first character of second and append a + character to it.''' + + second = (d*(second + q - ord(string[(i+1)/2])*h)%q + + ord(string[i+1]))%q + + '''Driver program''' + +txt = ""aabaacaabaa"" +checkPalindromes(txt) + +" +Rearrange an array in maximum minimum form | Set 2 (O(1) extra space),"/*Java program to rearrange an +array in minimum maximum form*/ + +public class Main { +/* Prints max at first position, min at second + position second max at third position, second + min at fourth position and so on.*/ + + public static void rearrange(int arr[], int n) + { +/* initialize index of first minimum and first + maximum element*/ + + int max_idx = n - 1, min_idx = 0; +/* store maximum element of array*/ + + int max_elem = arr[n - 1] + 1; +/* traverse array elements*/ + + for (int i = 0; i < n; i++) { +/* at even index : we have to put + maximum element*/ + + if (i % 2 == 0) { + arr[i] += (arr[max_idx] % max_elem) * max_elem; + max_idx--; + } +/* at odd index : we have to put minimum element*/ + + else { + arr[i] += (arr[min_idx] % max_elem) * max_elem; + min_idx++; + } + } +/* array elements back to it's original form*/ + + for (int i = 0; i < n; i++) + arr[i] = arr[i] / max_elem; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + int n = arr.length; + System.out.println(""Original Array""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + rearrange(arr, n); + System.out.print(""\nModified Array\n""); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +}"," '''Python3 program to rearrange an +array in minimum maximum form + ''' '''Prints max at first position, min at second position +second max at third position, second min at fourth +position and so on.''' + +def rearrange(arr, n): + ''' Initialize index of first minimum + and first maximum element''' + + max_idx = n - 1 + min_idx = 0 + ''' Store maximum element of array''' + + max_elem = arr[n-1] + 1 + ''' Traverse array elements''' + + for i in range(0, n) : + ''' At even index : we have to put maximum element''' + + if i % 2 == 0 : + arr[i] += (arr[max_idx] % max_elem ) * max_elem + max_idx -= 1 + ''' At odd index : we have to put minimum element''' + + else : + arr[i] += (arr[min_idx] % max_elem ) * max_elem + min_idx += 1 + ''' array elements back to it's original form''' + + for i in range(0, n) : + arr[i] = arr[i] / max_elem + '''Driver Code''' + +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +n = len(arr) +print (""Original Array"") +for i in range(0, n): + print (arr[i], end = "" "") +rearrange(arr, n) +print (""\nModified Array"") +for i in range(0, n): + print (int(arr[i]), end = "" "")" +Count minimum steps to get the given desired array,"/* Java program to count minimum number of operations + to get the given arr array */ + +class Test +{ + static int arr[] = new int[]{16, 16, 16} ; +/* Returns count of minimum operations to convert a + zero array to arr array with increment and + doubling operations. + This function computes count by doing reverse + steps, i.e., convert arr to zero array.*/ + + static int countMinOperations(int n) + { +/* Initialize result (Count of minimum moves)*/ + + int result = 0; +/* Keep looping while all elements of arr + don't become 0.*/ + + while (true) + { +/* To store count of zeroes in current + arr array*/ + + int zero_count = 0; +/*To find first odd element*/ + +int i; + for (i=0; i 0): + break; + ''' If 0, then increment + zero_count''' + + elif (target[i] == 0): + zero_count += 1; + i += 1; + ''' All numbers are 0''' + + if (zero_count == n): + return result; + ''' All numbers are even''' + + if (i == n): + ''' Divide the whole array by 2 + and increment result''' + + for j in range(n): + target[j] = target[j] // 2; + result += 1; + ''' Make all odd numbers even by + subtracting one and increment result.''' + + for j in range(i, n): + if (target[j] & 1): + target[j] -= 1; + result += 1; + '''Driver Code''' + +arr = [16, 16, 16]; +n = len(arr); +print(""Minimum number of steps required to"", + ""\nget the given target array is"", + countMinOperations(arr, n));" +Search in a row wise and column wise sorted matrix,"/*Java program to search an element in row-wise +and column-wise sorted matrix*/ + +class GFG { + +/* Searches the element x in mat[][]. If the +element is found, then prints its position +and returns true, otherwise prints ""not found"" +and returns false */ + + static int search(int[][] mat, int n, int x) + { + if (n == 0) + return -1;/* traverse through the matrix*/ + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) +/* if the element is found*/ + + if (mat[i][j] == x) { + System.out.print(""Element found at ("" + + i + "", "" + j + + "")\n""); + return 1; + } + } + System.out.print("" Element not found""); + return 0; + } +/*Driver code*/ + + public static void main(String[] args) + { + int mat[][] = { { 10, 20, 30, 40 }, + { 15, 25, 35, 45 }, + { 27, 29, 37, 48 }, + { 32, 33, 39, 50 } }; + search(mat, 4, 29); + } +}"," '''Python program to search an element in row-wise +and column-wise sorted matrix''' + '''Searches the element x in mat[][]. If the +element is found, then prints its position +and returns true, otherwise prints ""not found"" +and returns false''' + +def search(mat, n, x): + if(n == 0): + return -1 + ''' Traverse through the matrix ''' + + for i in range(n): + for j in range(n): + ''' If the element is found''' + + if(mat[i][j] == x): + print(""Element found at ("", i, "","", j, "")"") + return 1 + print("" Element not found"") + return 0 + '''Driver code''' + +mat = [[10, 20, 30, 40], [15, 25, 35, 45],[27, 29, 37, 48],[32, 33, 39, 50]] +search(mat, 4, 29)" +Merge Two Binary Trees by doing Node Sum (Recursive and Iterative),"/*Java program to Merge Two Binary Trees*/ + +import java.util.*; +class GFG{ +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; +/*Structure to store node pair onto stack*/ + +static class snode +{ + Node l, r; +}; +/* Helper function that allocates a new node with the +given data and null left and right pointers. */ + +static Node newNode(int data) +{ + Node new_node = new Node(); + new_node.data = data; + new_node.left = new_node.right = null; + return new_node; +} +/* Given a binary tree, print its nodes in inorder*/ + +static void inorder(Node node) +{ + if (node == null) + return; + /* first recur on left child */ + + inorder(node.left); + /* then print the data of node */ + + System.out.printf(""%d "", node.data); + /* now recur on right child */ + + inorder(node.right); +} +/* Function to merge given two binary trees*/ + +static Node MergeTrees(Node t1, Node t2) +{ + if ( t1 == null) + return t2; + if ( t2 == null) + return t1; + Stack s = new Stack<>(); + snode temp = new snode(); + temp.l = t1; + temp.r = t2; + s.add(temp); + snode n; + while (! s.isEmpty()) + { + n = s.peek(); + s.pop(); + if (n.l == null|| n.r == null) + continue; + n.l.data += n.r.data; + if (n.l.left == null) + n.l.left = n.r.left; + else + { + snode t = new snode(); + t.l = n.l.left; + t.r = n.r.left; + s.add(t); + } + if (n.l.right == null) + n.l.right = n.r.right; + else + { + snode t = new snode(); + t.l = n.l.right; + t.r = n.r.right; + s.add(t); + } + } + return t1; +} +/*Driver code*/ + +public static void main(String[] args) +{ + /* Let us conthe first Binary Tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 + */ + + Node root1 = newNode(1); + root1.left = newNode(2); + root1.right = newNode(3); + root1.left.left = newNode(4); + root1.left.right = newNode(5); + root1.right.right = newNode(6); + /* Let us conthe second Binary Tree + 4 + / \ + 1 7 + / / \ + 3 2 6 */ + + Node root2 = newNode(4); + root2.left = newNode(1); + root2.right = newNode(7); + root2.left.left = newNode(3); + root2.right.left = newNode(2); + root2.right.right = newNode(6); + Node root3 = MergeTrees(root1, root2); + System.out.printf(""The Merged Binary Tree is:\n""); + inorder(root3); +} +}"," '''Python3 program to Merge Two Binary Trees''' + + ''' A binary tree node has data, pointer to left child +and a pointer to right child ''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Structure to store node pair onto stack''' + +class snode: + def __init__(self, l, r): + self.l = l + self.r = r + ''' Helper function that allocates a new node with the +given data and None left and right pointers. ''' + +def newNode(data): + new_node = Node(data) + return new_node + ''' Given a binary tree, print its nodes in inorder''' + +def inorder(node): + if (not node): + return; + ''' first recur on left child ''' + + inorder(node.left); + ''' then print the data of node ''' + + print(node.data, end=' '); + ''' now recur on right child ''' + + inorder(node.right); + ''' Function to merge given two binary trees''' + +def MergeTrees(t1, t2): + if (not t1): + return t2; + if (not t2): + return t1; + s = [] + temp = snode(t1, t2) + s.append(temp); + n = None + while (len(s) != 0): + n = s[-1] + s.pop(); + if (n.l == None or n.r == None): + continue; + n.l.data += n.r.data; + if (n.l.left == None): + n.l.left = n.r.left; + else: + t=snode(n.l.left, n.r.left) + s.append(t); + if (n.l.right == None): + n.l.right = n.r.right; + else: + t=snode(n.l.right, n.r.right) + s.append(t); + return t1; + '''Driver code''' + +if __name__=='__main__': + ''' Let us construct the first Binary Tree + 1 + / \ + 2 3 + / \ \ + 4 5 6 + ''' + + root1 = newNode(1); + root1.left = newNode(2); + root1.right = newNode(3); + root1.left.left = newNode(4); + root1.left.right = newNode(5); + root1.right.right = newNode(6); + ''' Let us construct the second Binary Tree + 4 + / \ + 1 7 + / / \ + 3 2 6 ''' + + root2 = newNode(4); + root2.left = newNode(1); + root2.right = newNode(7); + root2.left.left = newNode(3); + root2.right.left = newNode(2); + root2.right.right = newNode(6); + root3 = MergeTrees(root1, root2); + print(""The Merged Binary Tree is:""); + inorder(root3);" +Linked List | Set 2 (Inserting a node),"/* This function is in LinkedList class. +Inserts a new node after the given prev_node. This method is +defined inside LinkedList class shown above */ + +public void insertAfter(Node prev_node, int new_data) +{ + /* 1. Check if the given Node is null */ + + if (prev_node == null) + { + System.out.println(""The given previous node cannot be null""); + return; + } + + /* 2. Allocate the Node & + 3. Put in the data*/ + + Node new_node = new Node(new_data); + + /* 4. Make next of new Node as next of prev_node */ + + new_node.next = prev_node.next; + + /* 5. make next of prev_node as new_node */ + + prev_node.next = new_node; +} +"," '''This function is in LinkedList class. +Inserts a new node after the given prev_node. This method is +defined inside LinkedList class shown above */''' + +def insertAfter(self, prev_node, new_data): + + ''' 1. check if the given prev_node exists''' + + if prev_node is None: + print ""The given previous node must inLinkedList."" + return + + ''' 2. Create new node & + 3. Put in the data''' + + new_node = Node(new_data) + + ''' 4. Make next of new Node as next of prev_node''' + + new_node.next = prev_node.next + + ''' 5. make next of prev_node as new_node''' + + prev_node.next = new_node +" +Check whether all the rotations of a given number is greater than or equal to the given number or not,"/*Java implementation of the approach*/ + +class GFG +{ + + static void CheckKCycles(int n, String s) + { + boolean ff = true; + int x = 0; + for (int i = 1; i < n; i++) + { + +/* Splitting the number at index i + and adding to the front*/ + + x = (s.substring(i) + s.substring(0, i)).length(); + +/* Checking if the value is greater than + or equal to the given value*/ + + if (x >= s.length()) + { + continue; + } + ff = false; + break; + } + if (ff) + { + System.out.println(""Yes""); + } + else + { + System.out.println(""No""); + } + + } + +/* Driver code*/ + + public static void main(String[] args) + { + int n = 3; + String s = ""123""; + CheckKCycles(n, s); + } +} + + +"," '''Python3 implementation of the approach''' + +def CheckKCycles(n, s): + ff = True + for i in range(1, n): + + ''' Splitting the number at index i + and adding to the front''' + + x = int(s[i:] + s[0:i]) + + ''' Checking if the value is greater than + or equal to the given value''' + + if (x >= int(s)): + continue + ff = False + break + if (ff): + print(""Yes"") + else: + print(""No"") + + '''Driver code''' + + +n = 3 +s = ""123"" +CheckKCycles(n, s)" +Reverse a number using stack,"/*Java program to reverse the number +using a stack*/ + +import java.util.Stack; +public class GFG +{ +/* Stack to maintain order of digits*/ + + static Stack st= new Stack<>(); +/* Function to push digits into stack*/ + + static void push_digits(int number) + { + while(number != 0) + { + st.push(number % 10); + number = number / 10; + } + } +/* Function to reverse the number*/ + + static int reverse_number(int number) + { +/* Function call to push number's + digits to stack*/ + + push_digits(number); + int reverse = 0; + int i = 1; +/* Popping the digits and forming + the reversed number*/ + + while (!st.isEmpty()) + { + reverse = reverse + (st.peek() * i); + st.pop(); + i = i * 10; + } +/* Return the reversed number formed*/ + + return reverse; + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int number = 39997; +/* Function call to reverse number*/ + + System.out.println(reverse_number(number)); + } +}"," '''Python3 program to reverse the +number using a stack''' ''' +Stack to maintain order of digits''' + +st = []; + '''Function to push digits into stack''' + +def push_digits(number): + while (number != 0): + st.append(number % 10); + number = int(number / 10); + '''Function to reverse the number''' + +def reverse_number(number): + ''' Function call to push number's + digits to stack''' + + push_digits(number); + reverse = 0; + i = 1; + ''' Popping the digits and forming + the reversed number''' + + while (len(st) > 0): + reverse = reverse + (st[len(st) - 1] * i); + st.pop(); + i = i * 10; + ''' Return the reversed number formed''' + + return reverse; + '''Driver Code''' + +number = 39997; + '''Function call to reverse number''' + +print(reverse_number(number));" +Rotate the sub-list of a linked list from position M to N to the right by K places,"/*Java implementation of the above approach*/ + +import java.util.*; + +class Solution +{ + + +/*Definition of node of linkedlist*/ + +static class ListNode { + int data; + ListNode next; +} + +/*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.*/ + +static void rotateSubList(ListNode A, int m, int n, int k) +{ + int size = n - m + 1; + +/* If k is greater than size of sublist then + we will take its modulo with size of sublist*/ + + if (k > size) { + k = k % size; + } + +/* If k is zero or k is equal to size or k is + a multiple of size of sublist then list + remains intact*/ + + if (k == 0 || k == size) { + ListNode head = A; + while (head != null) { + System.out.print( head.data); + head = head.next; + } + return; + } + +/*m-th node*/ + +ListNode link = null; + if (m == 1) { + link = A; + } + +/* This loop will traverse all node till + end node of sublist. +Current traversed node*/ + +ListNode c = A; +/*Count of traversed nodes*/ + +int count = 0; + ListNode end = null; +/*Previous of m-th node*/ + +ListNode pre = null; + while (c != null) { + count++; + +/* We will save (m-1)th node and later + make it point to (n-k+1)th node*/ + + if (count == m - 1) { + pre = c; + link = c.next; + } + if (count == n - k) { + if (m == 1) { + end = c; + A = c.next; + } + else { + end = c; + +/* That is how we bring (n-k+1)th + node to front of sublist.*/ + + pre.next = c.next; + } + } + +/* This keeps rest part of list intact.*/ + + if (count == n) { + ListNode d = c.next; + c.next = link; + end.next = d; + ListNode head = A; + while (head != null) { + System.out.print( head.data+"" ""); + head = head.next; + } + return; + } + c = c.next; + } +} + +/*Function for creating and linking new nodes*/ + +static ListNode push( ListNode head, int val) +{ + ListNode new_node = new ListNode(); + new_node.data = val; + new_node.next = (head); + (head) = new_node; + return head; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + ListNode head = null; + head =push(head, 70); + head =push(head, 60); + head =push(head, 50); + head =push(head, 40); + head =push(head, 30); + head =push(head, 20); + head =push(head, 10); + ListNode tmp = head; + System.out.print(""Given List: ""); + while (tmp != null) { + System.out.print( tmp.data + "" ""); + tmp = tmp.next; + } + System.out.println(); + + int m = 3, n = 6, k = 2; + System.out.print( ""After rotation of sublist: ""); + rotateSubList(head, m, n, k); + +} +} + + +"," '''Python3 implementation of the above approach''' + +import math + + '''Definition of node of linkedlist''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''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.''' + +def rotateSubList(A, m, n, k): + size = n - m + 1 + + ''' If k is greater than size of sublist then + we will take its modulo with size of sublist''' + + if (k > size): + k = k % size + + ''' If k is zero or k is equal to size or k is + a multiple of size of sublist then list + remains intact''' + + if (k == 0 or k == size): + head = A + while (head != None): + print(head.data) + head = head.next + + return + + '''m-th node''' + + link = None + if (m == 1) : + link = A + + + ''' This loop will traverse all node till + end node of sublist. +Current traversed node''' + + c = A + + '''Count of traversed nodes''' + + count = 0 + end = None + + '''Previous of m-th node''' + + pre = None + while (c != None) : + count = count + 1 + + ''' We will save (m-1)th node and later + make it point to (n-k+1)th node''' + + if (count == m - 1) : + pre = c + link = c.next + + if (count == n - k) : + if (m == 1) : + end = c + A = c.next + + else : + end = c + + ''' That is how we bring (n-k+1)th + node to front of sublist.''' + + pre.next = c.next + + ''' This keeps rest part of list intact.''' + + if (count == n) : + d = c.next + c.next = link + end.next = d + head = A + while (head != None) : + print(head.data, end = "" "") + head = head.next + + return + + c = c.next + + '''Function for creating and linking new nodes''' + +def push(head, val): + new_node = Node(val) + new_node.data = val + new_node.next = head + head = new_node + return head + + '''Driver code''' + +if __name__=='__main__': + head = None + head = push(head, 70) + head = push(head, 60) + head = push(head, 50) + head = push(head, 40) + head = push(head, 30) + head = push(head, 20) + head = push(head, 10) + tmp = head + print(""Given List: "", end = """") + while (tmp != None) : + print(tmp.data, end = "" "") + tmp = tmp.next + + print() + + m = 3 + n = 6 + k = 2 + print(""After rotation of sublist: "", end = """") + rotateSubList(head, m, n, k) + + +" +Find whether a given number is a power of 4 or not,"/*Java code to check if given +number is power of 4 or not*/ + +class GFG { +/* Function to check if + x is power of 4*/ + + static int isPowerOfFour(int n) + { + if(n == 0) + return 0; + while(n != 1) + { + if(n % 4 != 0) + return 0; + n = n / 4; + } + return 1; + } +/* Driver program*/ + + public static void main(String[] args) + { + int test_no = 64; + if(isPowerOfFour(test_no) == 1) + System.out.println(test_no + + "" is a power of 4""); + else + System.out.println(test_no + + ""is not a power of 4""); + } +}"," '''Python3 program to check if given +number is power of 4 or not + ''' '''Function to check if x is power of 4''' + +def isPowerOfFour(n): + if (n == 0): + return False + while (n != 1): + if (n % 4 != 0): + return False + n = n // 4 + return True + '''Driver code''' + +test_no = 64 +if(isPowerOfFour(64)): + print(test_no, 'is a power of 4') +else: + print(test_no, 'is not a power of 4')" +Non-overlapping sum of two sets,"/*Java program to find Non-overlapping sum */ + +import java.io.*; +import java.util.*; +class GFG +{ +/* function for calculating + Non-overlapping sum of two array */ + + static int findSum(int[] A, int[] B, int n) + { +/* Insert elements of both arrays*/ + + HashMap hash = new HashMap<>(); + for (int i = 0; i < n; i++) + { + if (hash.containsKey(A[i])) + hash.put(A[i], 1 + hash.get(A[i])); + else + hash.put(A[i], 1); + if (hash.containsKey(B[i])) + hash.put(B[i], 1 + hash.get(B[i])); + else + hash.put(B[i], 1); + } +/* calculate non-overlapped sum */ + + int sum = 0; + for (Map.Entry entry : hash.entrySet()) + { + if (Integer.parseInt((entry.getValue()).toString()) == 1) + sum += Integer.parseInt((entry.getKey()).toString()); + } + return sum; + } +/* Driver code*/ + + public static void main(String args[]) + { + int[] A = { 5, 4, 9, 2, 3 }; + int[] B = { 2, 8, 7, 6, 3 }; +/* size of array */ + + int n = A.length; +/* function call */ + + System.out.println(findSum(A, B, n)); + } +}"," '''Python3 program to find Non-overlapping sum ''' + +from collections import defaultdict + '''Function for calculating +Non-overlapping sum of two array ''' + +def findSum(A, B, n): + ''' Insert elements of both arrays ''' + + Hash = defaultdict(lambda:0) + for i in range(0, n): + Hash[A[i]] += 1 + Hash[B[i]] += 1 + ''' calculate non-overlapped sum ''' + + Sum = 0 + for x in Hash: + if Hash[x] == 1: + Sum += x + return Sum + '''Driver code ''' + +if __name__ == ""__main__"": + A = [5, 4, 9, 2, 3] + B = [2, 8, 7, 6, 3] + ''' size of array ''' + + n = len(A) + ''' Function call ''' + + print(findSum(A, B, n))" +"Sum of f(a[i], a[j]) over all pairs in an array of n integers","/*Java program to calculate +the sum of f(a[i], aj])*/ + +import java.util.*; +public class GfG { +/* Function to calculate the sum*/ + + public static int sum(int a[], int n) + { +/* Map to keep a count of occurrences*/ + + Map cnt = new HashMap(); +/* Traverse in the list from start to end + number of times a[i] can be in a pair and + to get the difference we subtract pre_sum*/ + + int ans = 0, pre_sum = 0; + for (int i = 0; i < n; i++) { + ans += (i * a[i]) - pre_sum; + pre_sum += a[i]; +/* If the (a[i]-1) is present then subtract + that value as f(a[i], a[i]-1) = 0*/ + + if (cnt.containsKey(a[i] - 1)) + ans -= cnt.get(a[i] - 1); +/* If the (a[i]+1) is present then + add that value as f(a[i], a[i]-1)=0 + here we add as a[i]-(a[i]-1)<0 which would + have been added as negative sum, so we add + to remove this pair from the sum value*/ + + if (cnt.containsKey(a[i] + 1)) + ans += cnt.get(a[i] + 1); +/* keeping a counter for every element*/ + + if(cnt.containsKey(a[i])) { + cnt.put(a[i], cnt.get(a[i]) + 1); + } + else { + cnt.put(a[i], 1); + } + } + return ans; + } +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 1, 2, 3, 1, 3 }; + int n = a.length; + System.out.println(sum(a, n)); + } +}"," '''Python3 program to calculate the +sum of f(a[i], aj]) + ''' '''Function to calculate the sum''' + +def sum(a, n): + ''' map to keep a count of occurrences''' + + cnt = dict() + ''' Traverse in the list from start to end + number of times a[i] can be in a pair and + to get the difference we subtract pre_sum.''' + + ans = 0 + pre_sum = 0 + for i in range(n): + ans += (i * a[i]) - pre_sum + pre_sum += a[i] + ''' if the (a[i]-1) is present then + subtract that value as f(a[i], a[i]-1)=0''' + + if (a[i] - 1) in cnt: + ans -= cnt[a[i] - 1] + ''' if the (a[i]+1) is present then add that + value as f(a[i], a[i]-1)=0 here we add + as a[i]-(a[i]-1)<0 which would have been + added as negative sum, so we add to remove + this pair from the sum value''' + + if (a[i] + 1) in cnt: + ans += cnt[a[i] + 1] + ''' keeping a counter for every element''' + + if a[i] not in cnt: + cnt[a[i]] = 0 + cnt[a[i]] += 1 + return ans + '''Driver Code''' + +if __name__ == '__main__': + a = [1, 2, 3, 1, 3] + n = len(a) + print(sum(a, n))" +Move all negative numbers to beginning and positive to end with constant extra space,"/*Java program to put all negative +numbers before positive numbers*/ + +import java.io.*; +class GFG { + static void rearrange(int arr[], int n) + { + int j = 0, temp; + for (int i = 0; i < n; i++) { + if (arr[i] < 0) { + if (i != j) { + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + j++; + } + } + } +/* A utility function to print an array*/ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 }; + int n = arr.length; + rearrange(arr, n); + printArray(arr, n); + } +}"," '''A Python 3 program to put +all negative numbers before +positive numbers''' + +def rearrange(arr, n ) : + j = 0 + for i in range(0, n) : + if (arr[i] < 0) : + temp = arr[i] + arr[i] = arr[j] + arr[j]= temp + j = j + 1 ''' print an array''' + + print(arr) + '''Driver code''' + +arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9] +n = len(arr) +rearrange(arr, n)" +Count number of ways to reach a given score in a game,"/*Java program to count number of +possible ways to a given score +can be reached in a game where +a move can earn 3 or 5 or 10*/ + +import java.util.Arrays; +class GFG +{ +/* Returns number of ways to reach score n*/ + + static int count(int n) + { +/* table[i] will store count of solutions for + value i.*/ + + int table[] = new int[n + 1], i; +/* Initialize all table values as 0*/ + + Arrays.fill(table, 0); +/* Base case (If given value is 0)*/ + + table[0] = 1; +/* One by one consider given 3 + moves and update the table[] + values after the index greater + than or equal to the value of + the picked move*/ + + for (i = 3; i <= n; i++) + table[i] += table[i - 3]; + for (i = 5; i <= n; i++) + table[i] += table[i - 5]; + for (i = 10; i <= n; i++) + table[i] += table[i - 10]; + return table[n]; + } +/* Driver code*/ + + public static void main (String[] args) + { + int n = 20; + System.out.println(""Count for ""+n+"" is ""+count(n)); + n = 13; + System.out.println(""Count for ""+n+"" is ""+count(n)); + } +}"," '''Python program to count number of possible ways to a given +score can be reached in a game where a move can earn 3 or +5 or 10.''' + '''Returns number of ways to reach score n.''' + +def count(n): + ''' table[i] will store count of solutions for value i. + Initialize all table values as 0.''' + + table = [0 for i in range(n+1)] + ''' Base case (If given value is 0)''' + + table[0] = 1 + ''' One by one consider given 3 moves and update the + table[] values after the index greater than or equal + to the value of the picked move.''' + + for i in range(3, n+1): + table[i] += table[i-3] + for i in range(5, n+1): + table[i] += table[i-5] + for i in range(10, n+1): + table[i] += table[i-10] + return table[n] + '''Driver Program''' + +n = 20 +print('Count for', n, 'is', count(n)) +n = 13 +print('Count for', n, 'is', count(n))" +Find the Number Occurring Odd Number of Times,"/*Java program to find the element occurring odd +number of times*/ + +import java.io.*; +import java.util.HashMap; +class OddOccurrence +{ +/* function to find the element occurring odd + number of times*/ + + static int getOddOccurrence(int arr[], int n) + { + HashMap hmap = new HashMap<>(); +/* Putting all elements into the HashMap*/ + + for(int i = 0; i < n; i++) + { + if(hmap.containsKey(arr[i])) + { + int val = hmap.get(arr[i]); +/* If array element is already present then + increase the count of that element.*/ + + hmap.put(arr[i], val + 1); + } + else +/* if array element is not present then put + element into the HashMap and initialize + the count to one.*/ + + hmap.put(arr[i], 1); + } +/* Checking for odd occurrence of each element present + in the HashMap*/ + + for(Integer a:hmap.keySet()) + { + if(hmap.get(a) % 2 != 0) + return a; + } + return -1; + } +/* driver code */ + + public static void main(String[] args) + { + int arr[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2}; + int n = arr.length; + System.out.println(getOddOccurrence(arr, n)); + } +}"," '''Python3 program to find the element +occurring odd number of times + ''' '''function to find the element +occurring odd number of times''' + +def getOddOccurrence(arr,size): + Hash=dict() ''' Putting all elements into the HashMap''' + + for i in range(size): + Hash[arr[i]]=Hash.get(arr[i],0) + 1; + ''' Iterate through HashMap to check an element + occurring odd number of times and return it''' + + for i in Hash: + if(Hash[i]% 2 != 0): + return i + return -1 + '''Driver code''' + +arr=[2, 3, 5, 4, 5, 2, 4,3, 5, 2, 4, 4, 2] +n = len(arr) +print(getOddOccurrence(arr, n))" +Count set bits in an integer,"/*Java program to Count set +bits in an integer*/ + +import java.io.*; +class countSetBits { + /* Function to get no of set + bits in binary representation + of positive integer n */ + + static int countSetBits(int n) + { + int count = 0; + while (n > 0) { + count += n & 1; + n >>= 1; + } + return count; + } +/* driver program*/ + + public static void main(String args[]) + { + int i = 9; + System.out.println(countSetBits(i)); + } +}"," '''Python3 program to Count set +bits in an integer + ''' '''Function to get no of set bits in binary +representation of positive integer n */''' + +def countSetBits(n): + count = 0 + while (n): + count += n & 1 + n >>= 1 + return count + '''Program to test function countSetBits */''' + +i = 9 +print(countSetBits(i))" +Find the Missing Number,"/*Java program to find +the missing Number*/ + +class GFG{ + +/*getMissingNo function for +finding missing number*/ + +static int getMissingNo(int a[], int n) +{ + int n_elements_sum = n * (n + 1) / 2; + int sum = 0; + + for(int i = 0; i < n - 1; i++) + sum += a[i]; + + return n_elements_sum - sum; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int a[] = { 1, 2, 4, 5, 6 }; + int n = a.length + 1; + int miss = getMissingNo(a, n); + + System.out.print(miss); +} +} + + +"," '''Python3 program to find +the missing Number''' + + + + '''getMissingNo takes list as argument''' + +def getMissingNo(a, n): + n_elements_sum=n*(n+1)//2 + return n_elements_sum-sum(a) '''Driver program to test above function''' + +if __name__=='__main__': + + a = [1, 2, 4, 5, 6] + n = len(a)+1 + miss = getMissingNo(a, n) + print(miss) +" +Sum of nodes at maximum depth of a Binary Tree,"/*Java code for sum of nodes +at maximum depth*/ + +import java.util.*; + +/* Constructor*/ +class Node { + int data; + Node left, right; + public Node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } +} +class GfG { +/* function to find the sum of nodes at + maximum depth arguments are node and + max, where max is to match the depth + of node at every call to node, if + max will be equal to 1, means + we are at deepest node.*/ + + public static int sumMaxLevelRec(Node node, + int max) + { +/* base case*/ + + if (node == null) + return 0; +/* max == 1 to track the node + at deepest level*/ + + if (max == 1) + return node.data; +/* recursive call to left and right nodes*/ + + return sumMaxLevelRec(node.left, max - 1) + + sumMaxLevelRec(node.right, max - 1); + } + +/* maxDepth function to find the + max depth of the tree*/ + + public static int maxDepth(Node node) + { +/* base case*/ + + if (node == null) + return 0; +/* either leftDepth of rightDepth is + greater add 1 to include height + of node at which call is*/ + + return 1 + Math.max(maxDepth(node.left), + maxDepth(node.right)); + } +/* call to function to calculate + max depth*/ + public static int sumMaxLevel(Node root) { + int MaxDepth = maxDepth(root); + return sumMaxLevelRec(root, MaxDepth); + } +/* Driver code*/ + + public static void main(String[] args) + { + /* 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 */ + +/* Constructing tree*/ + + 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); +/* call to calculate required sum*/ + + System.out.println(sumMaxLevel(root)); + } +}"," '''Python3 code for sum of nodes at maximum depth''' + + + ''' Constructor''' +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to find the sum of nodes at maximum depth +arguments are node and max, where Max is to match +the depth of node at every call to node, if Max +will be equal to 1, means we are at deepest node.''' + +def sumMaxLevelRec(node, Max): + ''' base case''' + + if node == None: + return 0 + ''' Max == 1 to track the node at deepest level''' + + if Max == 1: + return node.data + ''' recursive call to left and right nodes''' + + return (sumMaxLevelRec(node.left, Max - 1) + + sumMaxLevelRec(node.right, Max - 1)) + + '''maxDepth function to find +the max depth of the tree''' + +def maxDepth(node): + ''' base case''' + + if node == None: + return 0 + ''' Either leftDepth of rightDepth is + greater add 1 to include height + of node at which call is''' + + return 1 + max(maxDepth(node.left), + maxDepth(node.right)) + ''' call to function to calculate max depth''' +def sumMaxLevel(root): + MaxDepth = maxDepth(root) + return sumMaxLevelRec(root, MaxDepth) + '''Driver code''' + +if __name__ == ""__main__"": + ''' Constructing tree''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + ''' call to calculate required sum''' + + print(sumMaxLevel(root))" +Count number of occurrences (or frequency) in a sorted array,"/*Java program to count +occurrences of an element*/ + +class GFG +{ + +/* A recursive binary search + function. It returns location + of x in given array arr[l..r] + is present, otherwise -1*/ + + static int binarySearch(int arr[], int l, + int r, int x) + { + if (r < l) + return -1; + + int mid = l + (r - l) / 2; + +/* If the element is present + at the middle itself*/ + + if (arr[mid] == x) + return mid; + +/* If element is smaller than + mid, then it can only be + present in left subarray*/ + + if (arr[mid] > x) + return binarySearch(arr, l, + mid - 1, x); + +/* Else the element can + only be present in + right subarray*/ + + return binarySearch(arr, mid + 1, r, x); + } + +/* Returns number of times x + occurs in arr[0..n-1]*/ + + static int countOccurrences(int arr[], + int n, int x) + { + int ind = binarySearch(arr, 0, + n - 1, x); + +/* If element is not present*/ + + if (ind == -1) + return 0; + +/* Count elements on left side.*/ + + int count = 1; + int left = ind - 1; + while (left >= 0 && + arr[left] == x) + { + count++; + left--; + } + +/* Count elements + on right side.*/ + + int right = ind + 1; + while (right < n && + arr[right] == x) + { + count++; + right++; + } + + return count; + } + + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {1, 2, 2, 2, 2, + 3, 4, 7, 8, 8}; + int n = arr.length; + int x = 2; + System.out.print(countOccurrences(arr, n, x)); + } +} + + +"," '''Python 3 program to count +occurrences of an element''' + + + '''A recursive binary search +function. It returns location +of x in given array arr[l..r] +is present, otherwise -1''' + +def binarySearch(arr, l, r, x): + if (r < l): + return -1 + + mid = int( l + (r - l) / 2) + + ''' If the element is present + at the middle itself''' + + if arr[mid] == x: + return mid + + ''' If element is smaller than + mid, then it can only be + present in left subarray''' + + if arr[mid] > x: + return binarySearch(arr, l, + mid - 1, x) + + ''' Else the element + can only be present + in right subarray''' + + return binarySearch(arr, mid + 1, + r, x) + + '''Returns number of times +x occurs in arr[0..n-1]''' + +def countOccurrences(arr, n, x): + ind = binarySearch(arr, 0, n - 1, x) + + ''' If element is not present''' + + if ind == -1: + return 0 + + ''' Count elements + on left side.''' + + count = 1 + left = ind - 1 + while (left >= 0 and + arr[left] == x): + count += 1 + left -= 1 + + ''' Count elements on + right side.''' + + right = ind + 1; + while (right < n and + arr[right] == x): + count += 1 + right += 1 + + return count + + '''Driver code''' + +arr = [ 1, 2, 2, 2, 2, + 3, 4, 7, 8, 8 ] +n = len(arr) +x = 2 +print(countOccurrences(arr, n, x)) + + +" +Search an element in an unsorted array using minimum number of comparisons,"/*Java implementation to search an element in +the unsorted array using minimum number of +comparisons*/ + +import java.io.*; + +class GFG { + +/* Function to search an element in + minimum number of comparisons*/ + + static String search(int arr[], int n, int x) + { +/* 1st comparison*/ + + if (arr[n - 1] == x) + return ""Found""; + + int backup = arr[n - 1]; + arr[n - 1] = x; + +/* no termination condition and thus + no comparison*/ + + for (int i = 0;; i++) { +/* this would be executed at-most n times + and therefore at-most n comparisons*/ + + if (arr[i] == x) { +/* replace arr[n-1] with its actual element + as in original 'arr[]'*/ + + arr[n - 1] = backup; + +/* if 'x' is found before the '(n-1)th' + index, then it is present in the array + final comparison*/ + + if (i < n - 1) + return ""Found""; + +/* else not present in the array*/ + + return ""Not Found""; + } + } + } + +/* driver program*/ + + public static void main(String[] args) + { + int arr[] = { 4, 6, 1, 5, 8 }; + int n = arr.length; + int x = 1; + System.out.println(search(arr, n, x)); + } +} + +"," '''Python3 implementation to search an +element in the unsorted array using +minimum number of comparisons''' + + + '''function to search an element in +minimum number of comparisons''' + +def search(arr, n, x): + + ''' 1st comparison''' + + if (arr[n-1] == x) : + return ""Found"" + + backup = arr[n-1] + arr[n-1] = x + + ''' no termination condition and + thus no comparison''' + + i = 0 + while(i < n) : + + ''' this would be executed at-most n times + and therefore at-most n comparisons''' + + if (arr[i] == x) : + + ''' replace arr[n-1] with its actual + element as in original 'arr[]''' + ''' + arr[n-1] = backup + + ''' if 'x' is found before the '(n-1)th' + index, then it is present in the + array final comparison''' + + if (i < n-1): + return ""Found"" + + ''' else not present in the array''' + + return ""Not Found"" + i = i + 1 + + '''Driver Code''' + +arr = [4, 6, 1, 5, 8] +n = len(arr) +x = 1 +print (search(arr, n, x)) + + +" +Add two numbers without using arithmetic operators,"static int Add(int x, int y) +{ + if (y == 0) + return x; + else + return Add(x ^ y, (x & y) << 1); +}","def Add(x, y): + if (y == 0): + return x + else: + return Add( x ^ y, (x & y) << 1)" +Count Non-Leaf nodes in a Binary Tree,"/*Java program to count total number of +non-leaf nodes in a binary tree */ + +class GfG { +/* A binary tree node has data, pointer to +left child and a pointer to right child */ + +static class Node { + int data; + Node left; + Node right; +} +/* Helper function that allocates a new node with the +given data and NULL left and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/* Computes the number of non-leaf nodes in a tree. */ + +static int countNonleaf(Node root) +{ +/* Base cases. */ + + if (root == null || (root.left == null && + root.right == null)) + return 0; +/* If root is Not NULL and its one of its + child is also not NULL */ + + return 1 + countNonleaf(root.left) + + countNonleaf(root.right); +} +/* Driver program to test size function*/ + +public static void main(String[] args) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + System.out.println(countNonleaf(root)); +} +}"," '''Python3 program to count total number +of non-leaf nodes in a binary tree''' + + '''class that allocates a new node with the +given data and None left and right pointers. ''' + +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None '''Computes the number of non-leaf +nodes in a tree. ''' + +def countNonleaf(root): + ''' Base cases. ''' + + if (root == None or (root.left == None and + root.right == None)): + return 0 + ''' If root is Not None and its one of + its child is also not None ''' + + return (1 + countNonleaf(root.left) + + countNonleaf(root.right)) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + print(countNonleaf(root))" +Pascal's Triangle,"/*Java program for Pascal's Triangle +A O(n^2) time and O(1) extra +space method for Pascal's Triangle*/ + +import java.io.*; +class GFG { +public static void printPascal(int n) +{ + for(int line = 1; line <= n; line++) + {/*used to represent C(line, i)*/ + +int C=1; + for(int i = 1; i <= line; i++) + { +/* The first value in a line is always 1*/ + + System.out.print(C+"" ""); + C = C * (line - i) / i; + } + System.out.println(); + } +} +/*Driver code*/ + +public static void main (String[] args) { + int n = 5; + printPascal(n); +} +}"," '''Python3 program for Pascal's Triangle +A O(n^2) time and O(1) extra +space method for Pascal's Triangle +Pascal function''' + +def printPascal(n): + for line in range(1, n + 1): + '''used to represent C(line, i)''' + + C = 1; + for i in range(1, line + 1): + ''' The first value in a + line is always 1''' + + print(C, end = "" ""); + C = int(C * (line - i) / i); + print(""""); + '''Driver code''' + +n = 5; +printPascal(n);" +Print Ancestors of a given node in Binary Tree,"/*Java program to print ancestors of given node*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right, nextRight; + Node(int item) + { + data = item; + left = right = nextRight = null; + } +} +class BinaryTree +{ + Node root; + /* If target is present in tree, then prints the ancestors + and returns true, otherwise returns false. */ + + boolean printAncestors(Node node, int target) + { + /* base cases */ + + if (node == null) + return false; + if (node.data == target) + return true; + /* If target is present in either left or right subtree + of this node, then print this node */ + + if (printAncestors(node.left, target) + || printAncestors(node.right, target)) + { + System.out.print(node.data + "" ""); + return true; + } + /* Else return false */ + + return false; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* Construct the following binary tree + 1 + / \ + 2 3 + / \ + 4 5 + / + 7 + */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.left.left.left = new Node(7); + tree.printAncestors(tree.root, 7); + } +}"," '''Python program to print ancestors of given node in +binary tree''' + + '''A Binary Tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''If target is present in tree, then prints the ancestors +and returns true, otherwise returns false''' + +def printAncestors(root, target): + ''' Base case''' + + if root == None: + return False + if root.data == target: + return True + ''' If target is present in either left or right subtree + of this node, then print this node''' + + if (printAncestors(root.left, target) or + printAncestors(root.right, target)): + print root.data, + return True + ''' Else return False ''' + + return False + '''Driver program to test above function''' + + ''' Construct the following binary tree + 1 + / \ + 2 3 + / \ + 4 5 + / + 7 + ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.left.left.left = Node(7) +printAncestors(root, 7)" +Check if each internal node of a BST has exactly one child,"/*Check if each internal node of BST has only one child*/ + +class BinaryTree { + boolean hasOnlyOneChild(int pre[], int size) { +/* Initialize min and max using last two elements*/ + + int min, max; + if (pre[size - 1] > pre[size - 2]) { + max = pre[size - 1]; + min = pre[size - 2]; + } else { + max = pre[size - 2]; + min = pre[size - 1]; + } +/* Every element must be either smaller than min or + greater than max*/ + + for (int i = size - 3; i >= 0; i--) { + if (pre[i] < min) { + min = pre[i]; + } else if (pre[i] > max) { + max = pre[i]; + } else { + return false; + } + } + return true; + } +/*Driver program to test above function*/ + + public static void main(String[] args) { + BinaryTree tree = new BinaryTree(); + int pre[] = new int[]{8, 3, 5, 7, 6}; + int size = pre.length; + if (tree.hasOnlyOneChild(pre, size) == true) { + System.out.println(""Yes""); + } else { + System.out.println(""No""); + } + } +}"," '''Check if each internal +node of BST has only one child +approach 2''' + +def hasOnlyOneChild(pre,size): + ''' Initialize min and max + using last two elements''' + + min=0; max=0 + if pre[size-1] > pre[size-2] : + max = pre[size-1] + min = pre[size-2] + else : + max = pre[size-2] + min = pre[size-1] + ''' Every element must be + either smaller than min or + greater than max''' + + for i in range(size-3, 0, -1): + if pre[i] < min: + min = pre[i] + elif pre[i] > max: + max = pre[i] + else: + return False + return True + '''Driver program to +test above function''' + +if __name__ == ""__main__"": + pre = [8, 3, 5, 7, 6] + size = len(pre) + if (hasOnlyOneChild(pre, size)): + print(""Yes"") + else: + print(""No"")" +Find the Number Occurring Odd Number of Times,"/*Java program to find the element occurring +odd number of times*/ + +class OddOccurrence { +/* function to find the element occurring odd + number of times*/ + + static int getOddOccurrence(int arr[], int arr_size) + { + int i; + for (i = 0; i < arr_size; i++) { + int count = 0; + for (int j = 0; j < arr_size; j++) { + if (arr[i] == arr[j]) + count++; + } + if (count % 2 != 0) + return arr[i]; + } + return -1; + } +/* driver code*/ + + public static void main(String[] args) + { + int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; + int n = arr.length; +/* Function calling*/ + + System.out.println(getOddOccurrence(arr, n)); + } +}"," '''Python program to find the element occurring +odd number of times''' + '''function to find the element occurring odd +number of times''' + +def getOddOccurrence(arr, arr_size): + for i in range(0,arr_size): + count = 0 + for j in range(0, arr_size): + if arr[i] == arr[j]: + count+=1 + if (count % 2 != 0): + return arr[i] + return -1 + '''driver code''' + +arr = [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 ] +n = len(arr) + ''' Function calling''' + +print(getOddOccurrence(arr, n))" +Move all zeroes to end of array | Set-2 (Using single traversal),"/*Java implementation to move +all zeroes at the end of array*/ + +import java.io.*; +class GFG { +/*function to move all zeroes at +the end of array*/ + +static void moveZerosToEnd(int arr[], int n) { +/* Count of non-zero elements*/ + + int count = 0; + int temp; +/* Traverse the array. If arr[i] is + non-zero, then swap the element at + index 'count' with the element at + index 'i'*/ + + for (int i = 0; i < n; i++) { + if ((arr[i] != 0)) { + temp = arr[count]; + arr[count] = arr[i]; + arr[i] = temp; + count = count + 1; + } + } +} +/*function to print the array elements*/ + +static void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); +} +/*Driver program to test above*/ + +public static void main(String args[]) { + int arr[] = {0, 1, 9, 8, 4, 0, 0, 2, + 7, 0, 6, 0, 9}; + int n = arr.length; + System.out.print(""Original array: ""); + printArray(arr, n); + moveZerosToEnd(arr, n); + System.out.print(""\nModified array: ""); + printArray(arr, n); +} +}"," '''Python implementation to move all zeroes at +the end of array + ''' '''function to move all zeroes at +the end of array''' + +def moveZerosToEnd (arr, n): + ''' Count of non-zero elements''' + + count = 0; + ''' Traverse the array. If arr[i] is non-zero, then + swap the element at index 'count' with the + element at index 'i''' + ''' + for i in range(0, n): + if (arr[i] != 0): + arr[count], arr[i] = arr[i], arr[count] + count+=1 + '''function to print the array elements''' + +def printArray(arr, n): + for i in range(0, n): + print(arr[i],end="" "") + '''Driver program to test above''' + +arr = [ 0, 1, 9, 8, 4, 0, 0, 2, + 7, 0, 6, 0, 9 ] +n = len(arr) +print(""Original array:"", end="" "") +printArray(arr, n) +moveZerosToEnd(arr, n) +print(""\nModified array: "", end="" "") +printArray(arr, n)" +Smallest subarray with k distinct numbers,"/*Java program to find minimum +range that contains exactly +k distinct numbers.*/ + +import java.util.*; +class GFG +{ +/*Prints the minimum range +that contains exactly k +distinct numbers.*/ + +static void minRange(int arr[], + int n, int k) +{ + int l = 0, r = n; +/* Consider every element + as starting point.*/ + + for (int i = 0; i < n; i++) + { +/* Find the smallest window + starting with arr[i] and + containing exactly k + distinct elements.*/ + + Set s = new HashSet(); + int j; + for (j = i; j < n; j++) + { + s.add(arr[j]); + if (s.size() == k) + { + if ((j - i) < (r - l)) + { + r = j; + l = i; + } + break; + } + } +/* There are less than k + distinct elements now, + so no need to continue.*/ + + if (j == n) + break; + } +/* If there was no window + with k distinct elements + (k is greater than total + distinct elements)*/ + + if (l == 0 && r == n) + System.out.println(""Invalid k""); + else + System.out.println(l + "" "" + r); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = { 1, 2, 3, 4, 5 }; + int n = arr.length; + int k = 3; + minRange(arr, n, k); +} +}"," '''Python 3 program to find minimum range +that contains exactly k distinct numbers. + ''' '''Prints the minimum range that contains +exactly k distinct numbers.''' + +def minRange(arr, n, k): + l = 0 + r = n + ''' Consider every element as + starting point.''' + + for i in range(n): + ''' Find the smallest window starting + with arr[i] and containing exactly + k distinct elements.''' + + s = [] + for j in range(i, n) : + s.append(arr[j]) + if (len(s) == k): + if ((j - i) < (r - l)) : + r = j + l = i + break + ''' There are less than k distinct + elements now, so no need to continue.''' + + if (j == n): + break + ''' If there was no window with k distinct + elements (k is greater than total + distinct elements)''' + + if (l == 0 and r == n): + print(""Invalid k"") + else: + print(l, r) + '''Driver code''' + +if __name__ == ""__main__"": + arr = [ 1, 2, 3, 4, 5 ] + n = len(arr) + k = 3 + minRange(arr, n, k)" +Rearrange positive and negative numbers with constant extra space,"/*Java program to Rearrange positive +and negative numbers in a array*/ + +import java.io.*; +class GFG { +/* A utility function to print + an array of size n*/ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Function to Rearrange positive and negative + numbers in a array*/ + + static void RearrangePosNeg(int arr[], int n) + { + int key, j; + for (int i = 1; i < n; i++) { + key = arr[i]; +/* if current element is positive + do nothing*/ + + if (key > 0) + continue; + /* if current element is negative, + shift positive elements of arr[0..i-1], + to one position to their right */ + + j = i - 1; + while (j >= 0 && arr[j] > 0) { + arr[j + 1] = arr[j]; + j = j - 1; + } +/* Put negative element at its right position*/ + + arr[j + 1] = key; + } + } +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; + int n = arr.length; + RearrangePosNeg(arr, n); + printArray(arr, n); + } +}"," '''Python 3 program to Rearrange positive +and negative numbers in a array''' '''A utility function to print +an array of size n''' + +def printArray(arr, n): + for i in range(n): + print(arr[i], end = "" "") + print() + '''Function to Rearrange positive +and negative numbers in a array''' + +def RearrangePosNeg(arr, n): + for i in range(1, n): + key = arr[i] + ''' if current element is positive + do nothing''' + + if (key > 0): + continue + ''' if current element is negative, + shift positive elements of arr[0..i-1], + to one position to their right ''' + + j = i - 1 + while (j >= 0 and arr[j] > 0): + arr[j + 1] = arr[j] + j = j - 1 + ''' Put negative element at its + right position''' + + arr[j + 1] = key + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ -12, 11, -13, -5, + 6, -7, 5, -3, -6 ] + n = len(arr) + RearrangePosNeg(arr, n) + printArray(arr, n)" +Remove brackets from an algebraic string containing + and,"/*Java program to simplify algebraic string*/ + +import java.util.*; +class GfG { +/*Function to simplify the string */ + +static String simplify(String str) +{ + int len = str.length(); +/* resultant string of max length equal + to length of input string */ + + char res[] = new char[len]; + int index = 0, i = 0; +/* create empty stack */ + + Stack s = new Stack (); + s.push(0); + while (i < len) { + if (str.charAt(i) == '+') { +/* If top is 1, flip the operator */ + + if (s.peek() == 1) + res[index++] = '-'; +/* If top is 0, append the same operator */ + + if (s.peek() == 0) + res[index++] = '+'; + } else if (str.charAt(i) == '-') { + if (s.peek() == 1) + res[index++] = '+'; + else if (s.peek() == 0) + res[index++] = '-'; + } else if (str.charAt(i) == '(' && i > 0) { + if (str.charAt(i - 1) == '-') { +/* x is opposite to the top of stack */ + + int x = (s.peek() == 1) ? 0 : 1; + s.push(x); + } +/* push value equal to top of the stack */ + + else if (str.charAt(i - 1) == '+') + s.push(s.peek()); + } +/* If closing parentheses pop the stack once */ + + else if (str.charAt(i) == ')') + s.pop(); +/* copy the character to the result */ + + else + res[index++] = str.charAt(i); + i++; + } + return new String(res); +} +/*Driver program */ + +public static void main(String[] args) +{ + String s1 = ""a-(b+c)""; + String s2 = ""a-(b-c-(d+e))-f""; + System.out.println(simplify(s1)); + System.out.println(simplify(s2)); +} +}"," '''Python3 program to simplify algebraic String + ''' '''Function to simplify the String ''' + +def simplify(Str): + Len = len(Str) + ''' resultant String of max Length + equal to Length of input String ''' + + res = [None] * Len + index = 0 + i = 0 + ''' create empty stack ''' + + s = [] + s.append(0) + while (i < Len): + if (Str[i] == '+'): + ''' If top is 1, flip the operator ''' + + if (s[-1] == 1): + res[index] = '-' + index += 1 + ''' If top is 0, append the + same operator ''' + + if (s[-1] == 0): + res[index] = '+' + index += 1 + elif (Str[i] == '-'): + if (s[-1] == 1): + res[index] = '+' + index += 1 + elif (s[-1] == 0): + res[index] = '-' + index += 1 + elif (Str[i] == '(' and i > 0): + if (Str[i - 1] == '-'): + ''' x is opposite to the top of stack ''' + + x = 0 if (s[-1] == 1) else 1 + s.append(x) + ''' append value equal to top of the stack ''' + + elif (Str[i - 1] == '+'): + s.append(s[-1]) + ''' If closing parentheses pop + the stack once ''' + + elif (Str[i] == ')'): + s.pop() + ''' copy the character to the result ''' + + else: + res[index] = Str[i] + index += 1 + i += 1 + return res + '''Driver Code''' + +if __name__ == '__main__': + s1 = ""a-(b+c)"" + s2 = ""a-(b-c-(d+e))-f"" + r1 = simplify(s1) + for i in r1: + if i != None: + print(i, end = "" "") + else: + break + print() + r2 = simplify(s2) + for i in r2: + if i != None: + print(i, end = "" "") + else: + break" +Median of two sorted arrays of same size,"/*A Simple Merge based O(n) solution +to find median of two sorted arrays*/ + +class Main +{ +/* function to calculate median*/ + + static int getMedian(int ar1[], int ar2[], int n) + { + int i = 0; + int j = 0; + int count; + int m1 = -1, m2 = -1; + /* Since there are 2n elements, median will + be average of elements at index n-1 and + n in the array obtained after merging ar1 + and ar2 */ + + for (count = 0; count <= n; count++) + { + /* Below is to handle case where all + elements of ar1[] are smaller than + smallest(or first) element of ar2[] */ + + if (i == n) + { + m1 = m2; + m2 = ar2[0]; + break; + } + /* Below is to handle case where all + elements of ar2[] are smaller than + smallest(or first) element of ar1[] */ + + else if (j == n) + { + m1 = m2; + m2 = ar1[0]; + break; + } + /* equals sign because if two + arrays have some common elements */ + + if (ar1[i] <= ar2[j]) + { + /* Store the prev median */ + + m1 = m2; + m2 = ar1[i]; + i++; + } + else + { + /* Store the prev median */ + + m1 = m2; + m2 = ar2[j]; + j++; + } + } + return (m1 + m2)/2; + } + /* Driver program to test above function */ + + public static void main (String[] args) + { + int ar1[] = {1, 12, 15, 26, 38}; + int ar2[] = {2, 13, 17, 30, 45}; + int n1 = ar1.length; + int n2 = ar2.length; + if (n1 == n2) + System.out.println(""Median is "" + + getMedian(ar1, ar2, n1)); + else + System.out.println(""arrays are of unequal size""); + } +}"," '''A Simple Merge based O(n) Python 3 solution +to find median of two sorted lists''' + '''This function returns median of ar1[] and ar2[]. +Assumptions in this function: +Both ar1[] and ar2[] are sorted arrays +Both have n elements''' + +def getMedian( ar1, ar2 , n): + i = 0 + j = 0 + m1 = -1 + m2 = -1 + ''' Since there are 2n elements, median + will be average of elements at index + n-1 and n in the array obtained after + merging ar1 and ar2''' + + count = 0 + while count < n + 1: + count += 1 + ''' Below is to handle case where all + elements of ar1[] are smaller than + smallest(or first) element of ar2[]''' + + if i == n: + m1 = m2 + m2 = ar2[0] + break + ''' Below is to handle case where all + elements of ar2[] are smaller than + smallest(or first) element of ar1[]''' + + elif j == n: + m1 = m2 + m2 = ar1[0] + break + ''' equals sign because if two + arrays have some common elements''' + + if ar1[i] <= ar2[j]: + '''Store the prev median''' + + m1 = m2 + m2 = ar1[i] + i += 1 + else: + '''Store the prev median''' + + m1 = m2 + m2 = ar2[j] + j += 1 + return (m1 + m2)/2 + '''Driver code to test above function''' + +ar1 = [1, 12, 15, 26, 38] +ar2 = [2, 13, 17, 30, 45] +n1 = len(ar1) +n2 = len(ar2) +if n1 == n2: + print(""Median is "", getMedian(ar1, ar2, n1)) +else: + print(""Doesn't work for arrays of unequal size"")" +Count of only repeated element in a sorted array of consecutive elements,"/*Java program to find the only repeated element +and number of times it appears*/ + + +import java.awt.Point; +import java.util.Arrays; +import java.util.Vector; + +class Test +{ +/* Assumptions : vector a is sorted, max-difference + of two adjacent elements is 1*/ + + static Point sequence(Vector a) + { + if (a.size() == 0) + return new Point(0, 0); + + int s = 0; + int e = a.size() - 1; + while (s < e) + { + int m = (s + e) / 2; + +/* if a[m] = m + a[0], there is no + repeating character in [s..m]*/ + + if (a.get(m) >= m + a.get(0)) + s = m + 1; + +/* if a[m] < m + a[0], there is a + repeating character in [s..m]*/ + + else + e = m; + } + return new Point(a.get(s), a.size() - (a.get(a.size() - 1) - a.get(0))); + } + +/* Driver method*/ + + public static void main(String args[]) + { + Integer array[] = new Integer[]{1, 2, 3, 4, 4, 4, 5, 6}; + Point p = sequence(new Vector<>(Arrays.asList(array))); + System.out.println(""Repeated element is "" + p.x + + "", it appears "" + p.y + "" times""); + } +} +"," '''Python3 program to find the +only repeated element and +number of times it appears''' + + + '''Assumptions : vector a is sorted, +max-difference of two adjacent +elements is 1''' + +def sequence(a): + if (len(a) == 0): + return [0, 0] + + s = 0 + e = len(a) - 1 + while (s < e): + m = (s + e) // 2 + + ''' if a[m] = m + a[0], there is no + repeating character in [s..m]''' + + if (a[m] >= m + a[0]): + s = m + 1 + + ''' if a[m] < m + a[0], there is a + repeating character in [s..m]''' + + else: + e = m + return [a[s], len(a) - ( + a[len(a) - 1] - a[0])] + + '''Driver code''' + +p = sequence([1, 2, 3, 4, 4, 4, 5, 6]) +print(""Repeated element is"", p[0], + "", it appears"", p[1], ""times"") + + +" +Sort a Rotated Sorted Array,"/*Java implementation for restoring original +sort in rotated sorted array using binary search*/ + +import java.util.*; + +class GFG +{ + +/* Function to find start index of array*/ + + static int findStartIndexOfArray(int arr[], + int low, int high) + { + if (low > high) + { + return -1; + } + + if (low == high) + { + return low; + } + + int mid = low + (high - low) / 2; + if (arr[mid] > arr[mid + 1]) + { + return mid + 1; + } + + if (arr[mid - 1] > arr[mid]) + { + return mid; + } + + if (arr[low] > arr[mid]) + { + return findStartIndexOfArray(arr, low, mid - 1); + } + else + { + return findStartIndexOfArray(arr, mid + 1, high); + } + } + +/* Function to restore the Original Sort*/ + + static void restoreSortedArray(int arr[], int n) + { +/* array is already sorted*/ + + if (arr[0] < arr[n - 1]) + { + return; + } + + int start = findStartIndexOfArray(arr, 0, n - 1); + +/* In reverse(), the first parameter + is iterator to beginning element + and second parameter is iterator + to last element plus one.*/ + + Arrays.sort(arr, 0, start); + Arrays.sort(arr, start, n); + Arrays.sort(arr); + + } + +/* Function to print the Array*/ + + static void printArray(int arr[], int size) + { + for (int i = 0; i < size; i++) + { + System.out.print(arr[i] + "" ""); + } + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {1, 2, 3, 4, 5}; + int n = arr.length; + restoreSortedArray(arr, n); + printArray(arr, n); + } +} + + +"," '''Python3 implementation for restoring original +sort in rotated sorted array using binary search''' + + + '''Function to find start index of array''' + +def findStartIndexOfArray(arr, low, high): + if (low > high): + return -1; + + if (low == high): + return low; + + mid = low + (high - low) / 2; + if (arr[mid] > arr[mid + 1]): + return mid + 1; + + if (arr[mid - 1] > arr[mid]): + return mid; + + if (arr[low] > arr[mid]): + return findStartIndexOfArray(arr, low, mid - 1); + else: + return findStartIndexOfArray(arr, mid + 1, high); + + '''Function to restore the Original Sort''' + +def restoreSortedArray(arr, n): + + ''' array is already sorted''' + + if (arr[0] < arr[n - 1]): + return; + + start = findStartIndexOfArray(arr, 0, n - 1); + + ''' In reverse(), the first parameter + is iterator to beginning element + and second parameter is iterator + to last element plus one.''' + + reverse(arr, 0, start); + reverse(arr, start, n); + reverse(arr); + + '''Function to print the Array''' + +def printArray(arr, size): + for i in range(size): + print(arr[i], end=""""); + +def reverse(arr, i, j): + while (i < j): + temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + i += 1; + j -= 1; + + '''Driver code''' + +if __name__ == '__main__': + arr = [ 1, 2, 3, 4, 5 ]; + n = len(arr); + restoreSortedArray(arr, n); + printArray(arr, n); + + +" +Find the sum of last n nodes of the given Linked List,"/*Java implementation to find the sum of last +'n' nodes of the Linked List*/ + +import java.util.*; + +class GFG +{ + +/* A Linked list node */ + +static class Node +{ + int data; + Node next; +}; +static Node head; + +/*function to insert a node at the +beginning of the linked list*/ + +static void push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list to the new node */ + + new_node.next = head_ref; + + /* move the head to point to the new node */ + + head_ref = new_node; + head=head_ref; +} + +static void reverseList(Node head_ref) +{ + 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; + head = head_ref; +} + +/*utility function to find the sum of last 'n' nodes*/ + +static int sumOfLastN_NodesUtil(int n) +{ +/* if n == 0*/ + + if (n <= 0) + return 0; + +/* reverse the linked list*/ + + reverseList(head); + + int sum = 0; + Node current = head; + +/* traverse the 1st 'n' nodes of the reversed + linked list and add them*/ + + while (current != null && n-- >0) + { + +/* accumulate node's data to 'sum'*/ + + sum += current.data; + +/* move to next node*/ + + current = current.next; + } + +/* reverse back the linked list*/ + + reverseList(head); + +/* required sum*/ + + return sum; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* create linked list 10.6.8.4.12*/ + + push(head, 12); + push(head, 4); + push(head, 8); + push(head, 6); + push(head, 10); + + int n = 2; + System.out.println(""Sum of last "" + n + "" nodes = "" + + sumOfLastN_NodesUtil(n)); +} +} + + +"," '''Python implementation to find the sum of last + '''n' Nodes of the Linked List''' + + '''A Linked list Node''' + +class Node: + + def __init__(self, x): + self.data = x + self.next = None + +head = None + + '''Function to insert a Node at the +beginning of the linked list''' + +def push(head_ref, new_data): + + ''' Allocate Node''' + + new_Node = Node(new_data) + + ''' Put in the data''' + + new_Node.data = new_data + + ''' Link the old list to the new Node''' + + new_Node.next = head_ref + + ''' Move the head to poto the new Node''' + + head_ref = new_Node + head = head_ref + return head + +def reverseList(): + global head; + current, prev, next = None, None, None; + current = head; + prev = None; + + while (current != None): + next = current.next; + current.next = prev; + prev = current; + current = next; + + head = prev; + + '''utility function to find the sum of last 'n' Nodes''' + +def sumOfLastN_NodesUtil(n): + + ''' if n == 0''' + + if (n <= 0): + return 0; + + ''' reverse the linked list''' + + reverseList(); + + sum = 0; + current = head; + + ''' traverse the 1st 'n' Nodes of the reversed + linked list and add them''' + + while (current != None and n > 0): + + ''' accumulate Node's data to 'sum''' + ''' + sum += current.data; + + ''' move to next Node''' + + current = current.next; + n -= 1; + + ''' reverse back the linked list''' + + reverseList(); + + ''' required sum''' + + return sum; + + '''Driver code''' + +if __name__ == '__main__': + ''' create linked list 10.6.8.4.12''' + + head = push(head, 12) + head = push(head, 4) + head = push(head, 8) + head = push(head, 6) + head = push(head, 10) + + n = 2; + print(""Sum of last "" , n , "" Nodes = "" , sumOfLastN_NodesUtil(n)); + + +" +Program to check if a matrix is symmetric,"/*Efficient Java code for check a matrix is +symmetric or no*/ + +import java.io.*; +class GFG { +static int MAX = 100; +/*Returns true if mat[N][N] +is symmetric, else false*/ + + static boolean isSymmetric(int mat[][], int N) +{ + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + if (mat[i][j] != mat[j][i]) + return false; + return true; +} +/*Driver code*/ + + public static void main (String[] args) + { + int mat[][] = { { 1, 3, 5 }, + { 3, 2, 4 }, + { 5, 4, 1 } }; + if (isSymmetric(mat, 3)) + System.out.println( ""Yes""); + else + System.out.println(""NO""); + } +}"," '''Efficient Python code for check a matrix is +symmetric or not. + ''' '''Returns true if mat[N][N] is symmetric, else false''' + +def isSymmetric(mat, N): + for i in range(N): + for j in range(N): + if (mat[i][j] != mat[j][i]): + return False + return True + '''Driver code''' + +mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ] +if (isSymmetric(mat, 3)): + print ""Yes"" +else: + print ""No""" +Program to find transpose of a matrix,"/*Java Program to find +transpose of a matrix*/ + +class GFG +{ + static final int M = 3; + static final int N = 4; +/* This function stores transpose + of A[][] in B[][]*/ + + static void transpose(int A[][], int B[][]) + { + int i, j; + for (i = 0; i < N; i++) + for (j = 0; j < M; j++) + B[i][j] = A[j][i]; + } +/* Driver code*/ + + public static void main (String[] args) + { + int A[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}}; + int B[][] = new int[N][M], i, j; + transpose(A, B); + System.out.print(""Result matrix is \n""); + for (i = 0; i < N; i++) + { + for (j = 0; j < M; j++) + System.out.print(B[i][j] + "" ""); + System.out.print(""\n""); + } + } +}"," '''Python3 Program to find +transpose of a matrix''' + +M = 3 +N = 4 + '''This function stores +transpose of A[][] in B[][]''' + +def transpose(A, B): + for i in range(N): + for j in range(M): + B[i][j] = A[j][i] + '''driver code''' + +A = [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3]] +B = [[0 for x in range(M)] for y in range(N)] +transpose(A, B) +print(""Result matrix is"") +for i in range(N): + for j in range(M): + print(B[i][j], "" "", end='') + print() '''To store result''' + +" +Minimum move to end operations to make all strings equal,"/*Java program to make all +strings same using move +to end operations.*/ + +import java.util.*; +class GFG +{ + +/*Returns minimum number of +moves to end operations +to make all strings same.*/ + +static int minimunMoves(String arr[], int n) +{ + int ans = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) + { + int curr_count = 0; + +/* Consider s[i] as target + string and count rotations + required to make all other + strings same as str[i].*/ + + String tmp = """"; + for (int j = 0; j < n; j++) + { + tmp = arr[j] + arr[j]; + +/* find function returns the + index where we found arr[i] + which is actually count of + move-to-front operations.*/ + + int index = tmp.indexOf(arr[i]); + +/* If any two strings are not + rotations of each other, + we can't make them same.*/ + + if (index == arr[i].length()) + return -1; + + curr_count += index; + } + + ans = Math.min(curr_count, ans); + } + + return ans; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + String arr[] = {""xzzwo"", ""zwoxz"", + ""zzwox"", ""xzzwo""}; + int n = arr.length; + System.out.println(minimunMoves(arr, n)); +} +} + + +"," '''Python 3 program to make all strings +same using move to end operations.''' + +import sys + + '''Returns minimum number of moves to end +operations to make all strings same.''' + +def minimunMoves(arr, n): + + ans = sys.maxsize + for i in range(n): + + curr_count = 0 + + ''' Consider s[i] as target string and + count rotations required to make + all other strings same as str[i].''' + + for j in range(n): + + tmp = arr[j] + arr[j] + + ''' find function returns the index where + we found arr[i] which is actually + count of move-to-front operations.''' + + index = tmp.find(arr[i]) + + ''' If any two strings are not rotations of + each other, we can't make them same.''' + + if (index == len(arr[i])): + return -1 + + curr_count += index + + ans = min(curr_count, ans) + + return ans + + '''Driver Code''' + +if __name__ == ""__main__"": + + arr = [""xzzwo"", ""zwoxz"", ""zzwox"", ""xzzwo""] + n = len(arr) + print( minimunMoves(arr, n)) + + +" +Check sum of Covered and Uncovered nodes of Binary Tree,"/*Java program to find sum of covered and uncovered nodes +of a binary tree */ + +/* A binary tree node has key, pointer to left child and + a pointer to right child */ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Utility function to calculate sum of all node of tree */ + + int sum(Node t) + { + if (t == null) + return 0; + return t.key + sum(t.left) + sum(t.right); + } + /* Recursive function to calculate sum of left boundary + elements */ + + int uncoveredSumLeft(Node t) + { + /* If left node, then just return its key value */ + + if (t.left == null && t.right == null) + return t.key; + /* If left is available then go left otherwise go right */ + + if (t.left != null) + return t.key + uncoveredSumLeft(t.left); + else + return t.key + uncoveredSumLeft(t.right); + } + /* Recursive function to calculate sum of right boundary + elements */ + + int uncoveredSumRight(Node t) + { + /* If left node, then just return its key value */ + + if (t.left == null && t.right == null) + return t.key; + /* If right is available then go right otherwise go left */ + + if (t.right != null) + return t.key + uncoveredSumRight(t.right); + else + return t.key + uncoveredSumRight(t.left); + } +/* Returns sum of uncovered elements*/ + + int uncoverSum(Node t) + { + /* Initializing with 0 in case we don't have + left or right boundary */ + + int lb = 0, rb = 0; + if (t.left != null) + lb = uncoveredSumLeft(t.left); + if (t.right != null) + rb = uncoveredSumRight(t.right); + /* returning sum of root node, left boundary + and right boundary*/ + + return t.key + lb + rb; + } +/* Returns true if sum of covered and uncovered elements + is same.*/ + + boolean isSumSame(Node root) + { +/* Sum of uncovered elements*/ + + int sumUC = uncoverSum(root); +/* Sum of all elements*/ + + int sumT = sum(root); +/* Check if sum of covered and uncovered is same*/ + + return (sumUC == (sumT - sumUC)); + } + /* Helper function to print inorder traversal of + binary tree */ + + void inorder(Node root) + { + if (root != null) + { + inorder(root.left); + System.out.print(root.key + "" ""); + inorder(root.right); + } + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); +/* Making above given diagram's binary tree*/ + + tree.root = new Node(8); + tree.root.left = new Node(3); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(6); + tree.root.left.right.left = new Node(4); + tree.root.left.right.right = new Node(7); + tree.root.right = new Node(10); + tree.root.right.right = new Node(14); + tree.root.right.right.left = new Node(13); + if (tree.isSumSame(tree.root)) + System.out.println(""Sum of covered and uncovered is same""); + else + System.out.println(""Sum of covered and uncovered is not same""); + } +}"," '''Python3 program to find sum of Covered and +Uncovered node of binary tree ''' + '''To create a newNode of tree and return pointer ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + '''Utility function to calculate sum +of all node of tree ''' + +def Sum(t): + if (t == None): + return 0 + return t.key + Sum(t.left) + Sum(t.right) + '''Recursive function to calculate sum +of left boundary elements ''' + +def uncoveredSumLeft(t): + ''' If leaf node, then just return + its key value ''' + + if (t.left == None and t.right == None): + return t.key + ''' If left is available then go + left otherwise go right ''' + + if (t.left != None): + return t.key + uncoveredSumLeft(t.left) + else: + return t.key + uncoveredSumLeft(t.right) + '''Recursive function to calculate sum of +right boundary elements ''' + +def uncoveredSumRight(t): + ''' If leaf node, then just return + its key value ''' + + if (t.left == None and t.right == None): + return t.key + ''' If right is available then go right + otherwise go left ''' + + if (t.right != None): + return t.key + uncoveredSumRight(t.right) + else: + return t.key + uncoveredSumRight(t.left) + '''Returns sum of uncovered elements ''' + +def uncoverSum(t): + ''' Initializing with 0 in case we + don't have left or right boundary ''' + + lb = 0 + rb = 0 + if (t.left != None): + lb = uncoveredSumLeft(t.left) + if (t.right != None): + rb = uncoveredSumRight(t.right) + ''' returning sum of root node, + left boundary and right boundary''' + + return t.key + lb + rb + '''Returns true if sum of covered and +uncovered elements is same. ''' + +def isSumSame(root): + ''' Sum of uncovered elements ''' + + sumUC = uncoverSum(root) + ''' Sum of all elements ''' + + sumT = Sum(root) + ''' Check if sum of covered and + uncovered is same''' + + return (sumUC == (sumT - sumUC)) + '''Helper function to prinorder +traversal of binary tree ''' + +def inorder(root): + if (root): + inorder(root.left) + print(root.key, end = "" "") + inorder(root.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' Making above given diagram's + binary tree ''' + + root = newNode(8) + root.left = newNode(3) + root.left.left = newNode(1) + root.left.right = newNode(6) + root.left.right.left = newNode(4) + root.left.right.right = newNode(7) + root.right = newNode(10) + root.right.right = newNode(14) + root.right.right.left = newNode(13) + if (isSumSame(root)): + print(""Sum of covered and uncovered is same"") + else: + print(""Sum of covered and uncovered is not same"")" +Binary Search,"/*Java implementation of recursive Binary Search*/ + +class BinarySearch { +/* Returns index of x if it is present in arr[l.. + r], else return -1*/ + + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) { + int mid = l + (r - l) / 2; +/* If the element is present at the + middle itself*/ + + if (arr[mid] == x) + return mid; +/* If element is smaller than mid, then + it can only be present in left subarray*/ + + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); +/* Else the element can only be present + in right subarray*/ + + return binarySearch(arr, mid + 1, r, x); + } +/* We reach here when element is not present + in array*/ + + return -1; + } +/* Driver method to test above*/ + + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, 0, n - 1, x); + if (result == -1) + System.out.println(""Element not present""); + else + System.out.println(""Element found at index "" + result); + } +}"," '''Python3 Program for recursive binary search.''' + '''Returns index of x in arr if present, else -1''' + +def binarySearch (arr, l, r, x): + if r >= l: + mid = l + (r - l) // 2 ''' If element is present at the middle itself''' + + if arr[mid] == x: + return mid + ''' If element is smaller than mid, then it + can only be present in left subarray''' + + elif arr[mid] > x: + return binarySearch(arr, l, mid-1, x) + ''' Else the element can only be present + in right subarray''' + + else: + return binarySearch(arr, mid + 1, r, x) + else: + ''' Element is not present in the array''' + + return -1 + '''Driver Code''' + +arr = [ 2, 3, 4, 10, 40 ] +x = 10 +result = binarySearch(arr, 0, len(arr)-1, x) +if result != -1: + print (""Element is present at index % d"" % result) +else: + print (""Element is not present in array"") +" +Naive algorithm for Pattern Searching,"/*Java program for Naive Pattern Searching*/ + +public class NaiveSearch { + public static void search(String txt, String pat) + { + int M = pat.length(); + int N = txt.length(); + /* A loop to slide pat one by one */ + + for (int i = 0; i <= N - M; i++) { + int j; + /* For current index i, check for pattern + match */ + + for (j = 0; j < M; j++) + if (txt.charAt(i + j) != pat.charAt(j)) + break; +/*if pat[0...M-1] = txt[i, i+1, ...i+M-1]*/ + +if (j == M) + System.out.println(""Pattern found at index "" + i); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + String txt = ""AABAACAADAABAAABAA""; + String pat = ""AABA""; + search(txt, pat); + } +}"," '''Python3 program for Naive Pattern +Searching algorithm''' + +def search(pat, txt): + M = len(pat) + N = len(txt) + ''' A loop to slide pat[] one by one */''' + + for i in range(N - M + 1): + j = 0 + ''' For current index i, check + for pattern match */''' + + while(j < M): + if (txt[i + j] != pat[j]): + break + j += 1 + + '''if pat[0...M-1] = txt[i, i+1, ...i+M-1]''' + + if (j == M): + print(""Pattern found at index "", i) '''Driver Code''' + +if __name__ == '__main__': + txt = ""AABAACAADAABAAABAA"" + pat = ""AABA"" + search(pat, txt)" +Smallest Difference Triplet from Three arrays,"/*Java implementation of smallest difference +triplet*/ + +import java.util.Arrays; +class GFG { +/* function to find maximum number*/ + + static int maximum(int a, int b, int c) + { + return Math.max(Math.max(a, b), c); + } +/* function to find minimum number*/ + + static int minimum(int a, int b, int c) + { + return Math.min(Math.min(a, b), c); + } +/* Finds and prints the smallest Difference + Triplet*/ + + static void smallestDifferenceTriplet(int arr1[], + int arr2[], int arr3[], int n) + { +/* sorting all the three arrays*/ + + Arrays.sort(arr1); + Arrays.sort(arr2); + Arrays.sort(arr3); +/* To store resultant three numbers*/ + + int res_min=0, res_max=0, res_mid=0; +/* pointers to arr1, arr2, arr3 + respectively*/ + + int i = 0, j = 0, k = 0; +/* Loop until one array reaches to its end + Find the smallest difference.*/ + + int diff = 2147483647; + while (i < n && j < n && k < n) + { + int sum = arr1[i] + arr2[j] + arr3[k]; +/* maximum number*/ + + int max = maximum(arr1[i], arr2[j], arr3[k]); +/* Find minimum and increment its index.*/ + + int min = minimum(arr1[i], arr2[j], arr3[k]); + if (min == arr1[i]) + i++; + else if (min == arr2[j]) + j++; + else + k++; +/* comparing new difference with the + previous one and updating accordingly*/ + + if (diff > (max - min)) + { + diff = max - min; + res_max = max; + res_mid = sum - (max + min); + res_min = min; + } + } +/* Print result*/ + + System.out.print(res_max + "", "" + res_mid + + "", "" + res_min); + } +/* driver code*/ + + public static void main (String[] args) + { + int arr1[] = {5, 2, 8}; + int arr2[] = {10, 7, 12}; + int arr3[] = {9, 14, 6}; + int n = arr1.length; + smallestDifferenceTriplet(arr1, arr2, arr3, n); + } +}"," '''Python3 implementation of smallest +difference triplet''' + '''Function to find maximum number''' + +def maximum(a, b, c): + return max(max(a, b), c) + '''Function to find minimum number''' + +def minimum(a, b, c): + return min(min(a, b), c) + '''Finds and prints the smallest +Difference Triplet''' + +def smallestDifferenceTriplet(arr1, arr2, arr3, n): + ''' sorting all the three arrays''' + + arr1.sort() + arr2.sort() + arr3.sort() + ''' To store resultant three numbers''' + + res_min = 0; res_max = 0; res_mid = 0 + ''' pointers to arr1, arr2, + arr3 respectively''' + + i = 0; j = 0; k = 0 + ''' Loop until one array reaches to its end + Find the smallest difference.''' + + diff = 2147483647 + while (i < n and j < n and k < n): + sum = arr1[i] + arr2[j] + arr3[k] + ''' maximum number''' + + max = maximum(arr1[i], arr2[j], arr3[k]) + ''' Find minimum and increment its index.''' + + min = minimum(arr1[i], arr2[j], arr3[k]) + if (min == arr1[i]): + i += 1 + elif (min == arr2[j]): + j += 1 + else: + k += 1 + ''' Comparing new difference with the + previous one and updating accordingly''' + + if (diff > (max - min)): + diff = max - min + res_max = max + res_mid = sum - (max + min) + res_min = min + ''' Print result''' + + print(res_max, "","", res_mid, "","", res_min) + '''Driver code''' + +arr1 = [5, 2, 8] +arr2 = [10, 7, 12] +arr3 = [9, 14, 6] +n = len(arr1) +smallestDifferenceTriplet(arr1, arr2, arr3, n)" +Mobile Numeric Keypad Problem,"/*A Space Optimized Java program to +count number of possible numbers +of given length*/ + +class GFG +{ +/*Return count of all possible numbers of +length n in a given numeric keyboard*/ + +static int getCount(char keypad[][], int n) +{ + if(keypad == null || n <= 0) + return 0; + if(n == 1) + return 10; +/* odd[i], even[i] arrays represent count of + numbers starting with digit i for any length j*/ + + int []odd = new int[10]; + int []even = new int[10]; + int i = 0, j = 0, useOdd = 0, totalCount = 0; + for (i = 0; i <= 9; i++) +/*for j = 1*/ + +odd[i] = 1; +/* Bottom Up calculation from j = 2 to n*/ + + for (j = 2; j <= n; j++) + { + useOdd = 1 - useOdd; +/* Here we are explicitly writing lines + for each number 0 to 9. But it can always be + written as DFS on 4X3 grid using row, + column array valid moves*/ + + if(useOdd == 1) + { + even[0] = odd[0] + odd[8]; + even[1] = odd[1] + odd[2] + odd[4]; + even[2] = odd[2] + odd[1] + + odd[3] + odd[5]; + even[3] = odd[3] + odd[2] + odd[6]; + even[4] = odd[4] + odd[1] + + odd[5] + odd[7]; + even[5] = odd[5] + odd[2] + odd[4] + + odd[8] + odd[6]; + even[6] = odd[6] + odd[3] + + odd[5] + odd[9]; + even[7] = odd[7] + odd[4] + odd[8]; + even[8] = odd[8] + odd[0] + odd[5] + + odd[7] + odd[9]; + even[9] = odd[9] + odd[6] + odd[8]; + } + else + { + odd[0] = even[0] + even[8]; + odd[1] = even[1] + even[2] + even[4]; + odd[2] = even[2] + even[1] + + even[3] + even[5]; + odd[3] = even[3] + even[2] + even[6]; + odd[4] = even[4] + even[1] + + even[5] + even[7]; + odd[5] = even[5] + even[2] + even[4] + + even[8] + even[6]; + odd[6] = even[6] + even[3] + + even[5] + even[9]; + odd[7] = even[7] + even[4] + even[8]; + odd[8] = even[8] + even[0] + even[5] + + even[7] + even[9]; + odd[9] = even[9] + even[6] + even[8]; + } + } +/* Get count of all possible numbers of + length ""n"" starting with digit 0, 1, 2, ..., 9*/ + + totalCount = 0; + if(useOdd == 1) + { + for (i = 0; i <= 9; i++) + totalCount += even[i]; + } + else + { + for (i = 0; i <= 9; i++) + totalCount += odd[i]; + } + return totalCount; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + char keypad[][] = {{'1','2','3'}, + {'4','5','6'}, + {'7','8','9'}, + {'*','0','#'}}; + System.out.printf(""Count for numbers of length %d: %d\n"", 1, + getCount(keypad, 1)); + System.out.printf(""Count for numbers of length %d: %d\n"", 2, + getCount(keypad, 2)); + System.out.printf(""Count for numbers of length %d: %d\n"", 3, + getCount(keypad, 3)); + System.out.printf(""Count for numbers of length %d: %d\n"", 4, + getCount(keypad, 4)); + System.out.printf(""Count for numbers of length %d: %d\n"", 5, + getCount(keypad, 5)); +} +}"," '''A Space Optimized Python program to count +number of possible numbers +of given length''' + + '''Return count of all possible numbers +of length n +in a given numeric keyboard''' + +def getCount(keypad, n): + if(not keypad or n <= 0): + return 0 + if(n == 1): + return 10 ''' odd[i], even[i] arrays represent + count of numbers starting + with digit i for any length j''' + + odd = [0]*10 + even = [0]*10 + i = 0 + j = 0 + useOdd = 0 + totalCount = 0 + for i in range(10): + '''for j = 1''' + + odd[i] = 1 + '''Bottom Up calculation from j = 2 to n''' + + for j in range(2,n+1): + useOdd = 1 - useOdd + ''' Here we are explicitly writing lines for each number 0 + to 9. But it can always be written as DFS on 4X3 grid + using row, column array valid moves''' + + if(useOdd == 1): + even[0] = odd[0] + odd[8] + even[1] = odd[1] + odd[2] + odd[4] + even[2] = odd[2] + odd[1] + odd[3] + odd[5] + even[3] = odd[3] + odd[2] + odd[6] + even[4] = odd[4] + odd[1] + odd[5] + odd[7] + even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6] + even[6] = odd[6] + odd[3] + odd[5] + odd[9] + even[7] = odd[7] + odd[4] + odd[8] + even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9] + even[9] = odd[9] + odd[6] + odd[8] + else: + odd[0] = even[0] + even[8] + odd[1] = even[1] + even[2] + even[4] + odd[2] = even[2] + even[1] + even[3] + even[5] + odd[3] = even[3] + even[2] + even[6] + odd[4] = even[4] + even[1] + even[5] + even[7] + odd[5] = even[5] + even[2] + even[4] + even[8] + even[6] + odd[6] = even[6] + even[3] + even[5] + even[9] + odd[7] = even[7] + even[4] + even[8] + odd[8] = even[8] + even[0] + even[5] + even[7] + even[9] + odd[9] = even[9] + even[6] + even[8] + ''' Get count of all possible numbers of length ""n"" starting + with digit 0, 1, 2, ..., 9''' + + totalCount = 0 + if(useOdd == 1): + for i in range(10): + totalCount += even[i] + else: + for i in range(10): + totalCount += odd[i] + return totalCount + '''Driver program to test above function''' + +if __name__ == ""__main__"": + keypad = [['1','2','3'], + ['4','5','6'], + ['7','8','9'], + ['*','0','#']] + print(""Count for numbers of length "",1,"": "", getCount(keypad, 1)) + print(""Count for numbers of length "",2,"": "", getCount(keypad, 2)) + print(""Count for numbers of length "",3,"": "", getCount(keypad, 3)) + print(""Count for numbers of length "",4,"": "", getCount(keypad, 4)) + print(""Count for numbers of length "",5,"": "", getCount(keypad, 5)) +" +Maximum difference between groups of size two,"/*Java program to find minimum difference +between groups of highest and lowest +sums.*/ + +import java.util.Arrays; +import java.io.*; + +class GFG { +static int CalculateMax(int arr[], int n) +{ +/* Sorting the whole array.*/ + + Arrays.sort(arr); + + int min_sum = arr[0] + arr[1]; + int max_sum = arr[n-1] + arr[n-2]; + + return (Math.abs(max_sum - min_sum)); +} + +/*Driver code*/ + + + public static void main (String[] args) { + + int arr[] = { 6, 7, 1, 11 }; + int n = arr.length; + System.out.println (CalculateMax(arr, n)); + } +} +"," '''Python 3 program to find minimum difference +between groups of highest and lowest''' + +def CalculateMax(arr, n): + + ''' Sorting the whole array.''' + + arr.sort() + min_sum = arr[0] + arr[1] + max_sum = arr[n - 1] + arr[n - 2] + return abs(max_sum - min_sum) + + '''Driver code''' + +arr = [6, 7, 1, 11] +n = len(arr) +print(CalculateMax(arr, n)) + + +" +Sum of all elements between k1'th and k2'th smallest elements,"/*Java program to find sum of all element +between to K1'th and k2'th smallest +elements in array*/ + +import java.util.Arrays; +class GFG { +/* Returns sum between two kth smallest + element of array*/ + + static int sumBetweenTwoKth(int arr[], + int k1, int k2) + { +/* Sort the given array*/ + + Arrays.sort(arr); +/* Below code is equivalent to*/ + + int result = 0; + for (int i = k1; i < k2 - 1; i++) + result += arr[i]; + return result; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 20, 8, 22, 4, 12, 10, 14 }; + int k1 = 3, k2 = 6; + int n = arr.length; + System.out.print(sumBetweenTwoKth(arr, + k1, k2)); + } +}"," '''Python program to find sum of +all element between to K1'th and +k2'th smallest elements in array''' + + '''Returns sum between two kth +smallest element of array''' + +def sumBetweenTwoKth(arr, n, k1, k2): ''' Sort the given array''' + + arr.sort() + + ''' Below code is equivalent to''' + + result = 0 + for i in range(k1, k2-1): + result += arr[i] + return result '''Driver code''' + +arr = [ 20, 8, 22, 4, 12, 10, 14 ] +k1 = 3; k2 = 6 +n = len(arr) +print(sumBetweenTwoKth(arr, n, k1, k2))" +Jump Search,"/*Java program to implement Jump Search.*/ + +public class JumpSearch +{ + public static int jumpSearch(int[] arr, int x) + { + int n = arr.length; +/* Finding block size to be jumped*/ + + int step = (int)Math.floor(Math.sqrt(n)); +/* Finding the block where element is + present (if it is present)*/ + + int prev = 0; + while (arr[Math.min(step, n)-1] < x) + { + prev = step; + step += (int)Math.floor(Math.sqrt(n)); + if (prev >= n) + return -1; + } +/* Doing a linear search for x in block + beginning with prev.*/ + + while (arr[prev] < x) + { + prev++; +/* If we reached next block or end of + array, element is not present.*/ + + if (prev == Math.min(step, n)) + return -1; + } +/* If element is found*/ + + if (arr[prev] == x) + return prev; + return -1; + } +/* Driver program to test function*/ + + public static void main(String [ ] args) + { + int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610}; + int x = 55; +/* Find the index of 'x' using Jump Search*/ + + int index = jumpSearch(arr, x); +/* Print the index where 'x' is located*/ + + System.out.println(""\nNumber "" + x + + "" is at index "" + index); + } +}"," '''Python3 code to implement Jump Search''' + +import math +def jumpSearch( arr , x , n ): + ''' Finding block size to be jumped''' + + step = math.sqrt(n) + ''' Finding the block where element is + present (if it is present)''' + + prev = 0 + while arr[int(min(step, n)-1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + ''' Doing a linear search for x in + block beginning with prev.''' + + while arr[int(prev)] < x: + prev += 1 + ''' If we reached next block or end + of array, element is not present.''' + + if prev == min(step, n): + return -1 + ''' If element is found''' + + if arr[int(prev)] == x: + return prev + return -1 + '''Driver code to test function''' + +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 ] +x = 55 +n = len(arr) + '''Find the index of 'x' using Jump Search''' + +index = jumpSearch(arr, x, n) + '''Print the index where 'x' is located''' + +print(""Number"" , x, ""is at index"" ,""%.0f""%index)" +Mth element after K Right Rotations of an Array,"/*Java program to implement +the above approach*/ + +class GFG{ + +/*Function to return Mth element of +array after k right rotations*/ + +static int getFirstElement(int a[], int N, + int K, int M) +{ +/* The array comes to original state + after N rotations*/ + + K %= N; + int index; + +/* If K is greater or equal to M*/ + + if (K >= M) + +/* Mth element after k right + rotations is (N-K)+(M-1) th + element of the array*/ + + index = (N - K) + (M - 1); + +/* Otherwise*/ + + else + +/* (M - K - 1) th element + of the array*/ + + index = (M - K - 1); + + int result = a[index]; + +/* Return the result*/ + + return result; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = { 1, 2, 3, 4, 5 }; + + int N = 5; + + int K = 3, M = 2; + + System.out.println(getFirstElement(a, N, K, M)); +} +} + + +"," '''Python3 program to implement +the above approach''' + + + '''Function to return Mth element of +array after k right rotations''' + +def getFirstElement(a, N, K, M): + + ''' The array comes to original state + after N rotations''' + + K %= N + + ''' If K is greater or equal to M''' + + if (K >= M): + + ''' Mth element after k right + rotations is (N-K)+(M-1) th + element of the array''' + + index = (N - K) + (M - 1) + + ''' Otherwise''' + + else: + + ''' (M - K - 1) th element + of the array''' + + index = (M - K - 1) + + result = a[index] + + ''' Return the result''' + + return result + + '''Driver Code''' + +if __name__ == ""__main__"": + + a = [ 1, 2, 3, 4, 5 ] + N = len(a) + + K , M = 3, 2 + + print( getFirstElement(a, N, K, M)) + + +" +Minimize the number of weakly connected nodes,," '''Python3 code to minimize the number +of weakly connected nodes''' '''Set of nodes which are traversed +in each launch of the DFS''' + +node = set() +Graph = [[] for i in range(10001)] + '''Function traversing the graph using DFS +approach and updating the set of nodes''' + +def dfs(visit, src): + visit[src] = True + node.add(src) + llen = len(Graph[src]) + for i in range(llen): + if (not visit[Graph[src][i]]): + dfs(visit, Graph[src][i]) + '''Building a undirected graph''' + +def buildGraph(x, y, llen): + for i in range(llen): + p = x[i] + q = y[i] + Graph[p].append(q) + Graph[q].append(p) + '''Computes the minimum number of disconnected +components when a bi-directed graph is +converted to a undirected graph''' + +def compute(n): + ''' Declaring and initializing + a visited array''' + + visit = [False for i in range(n + 5)] + number_of_nodes = 0 + ''' We check if each node is + visited once or not''' + + for i in range(n): + ''' We only launch DFS from a + node iff it is unvisited.''' + + if (not visit[i]): + ''' Clearing the set of nodes + on every relaunch of DFS''' + + node.clear() + ''' Relaunching DFS from an + unvisited node.''' + + dfs(visit, i) + ''' Iterating over the node set to count the + number of nodes visited after making the + graph directed and storing it in the + variable count. If count / 2 == number + of nodes - 1, then increment count by 1.''' + + count = 0 + for it in node: + count += len(Graph[(it)]) + count //= 2 + if (count == len(node) - 1): + number_of_nodes += 1 + return number_of_nodes + '''Driver code''' + +if __name__=='__main__': + n = 6 + m = 4 + x = [ 1, 1, 4, 4, 0, 0, 0, 0, 0 ] + y = [ 2, 3, 5, 6, 0, 0, 0, 0, 0 ] + '''For given x and y above, graph is as below : + 1-----2 4------5 + | | + | | + | | + 3 6 + Note : This code will work for + connected graph also as : + 1-----2 + | | \ + | | \ + | | \ + 3-----4----5 + ''' ''' Building graph in the form of a adjacency list''' + + buildGraph(x, y, n) + print(str(compute(n)) + + "" weakly connected nodes"")" +Subarray/Substring vs Subsequence and Programs to Generate them,"/*Java program toto generate all possible subarrays/subArrays + Complexity- O(n^3) */ +*/ +class Test +{ + static int arr[] = new int[]{1, 2, 3, 4}; +/* Prints all subarrays in arr[0..n-1]*/ + + static void subArray( int n) + { +/* Pick starting point*/ + + for (int i=0; i = 1) + { + x = x ^ m; + m <<= 1; + } +/* flip the rightmost 0 bit*/ + + x = x ^ m; + return x; + } + /* Driver program to test above functions*/ + + public static void main(String[] args) + { + System.out.println(addOne(13)); + } +}"," '''Python3 code to add 1 +one to a given number''' + +def addOne(x) : + m = 1; + ''' Flip all the set bits + until we find a 0''' + + while(x & m): + x = x ^ m + m <<= 1 + ''' flip the rightmost + 0 bit''' + + x = x ^ m + return x + '''Driver program''' + +n = 13 +print addOne(n)" +Median of two sorted arrays of same size,"import java.io.*; +import java.util.*; +class GFG +{ + /* This function returns + median of ar1[] and ar2[]. + Assumptions in this function: + Both ar1[] and ar2[] + are sorted arrays + Both have n elements */ + + public static int getMedian(int ar1[], + int ar2[], int n) + { + int j = 0; + int i = n - 1; + while (ar1[i] > ar2[j] && j < n && i > -1) + { + int temp = ar1[i]; + ar1[i] = ar2[j]; + ar2[j] = temp; + i--; j++; + } + Arrays.sort(ar1); + Arrays.sort(ar2); + return (ar1[n - 1] + ar2[0]) / 2; + } +/* Driver code*/ + + public static void main (String[] args) + { + int ar1[] = { 1, 12, 15, 26, 38 }; + int ar2[] = { 2, 13, 17, 30, 45 }; + int n1 = 5; + int n2 = 5; + if (n1 == n2) + System.out.println(""Median is ""+ getMedian(ar1, ar2, n1)); + else + System.out.println(""Doesn't work for arrays of unequal size""); + } +}"," '''Python program for above approach +function to return median of the arrays +both are sorted & of same size''' + + + ''' while loop to swap all smaller numbers to arr1''' + +def getMedian(ar1, ar2, n): + i, j = n - 1, 0 + while(ar1[i] > ar2[j] and i > -1 and j < n): + ar1[i], ar2[j] = ar2[j], ar1[i] + i -= 1 + j += 1 + ar1.sort() + ar2.sort() + return (ar1[-1] + ar2[0]) >> 1 + '''Driver program''' + +if __name__ == '__main__': + ar1 = [1, 12, 15, 26, 38] + ar2 = [2, 13, 17, 30, 45] + n1, n2 = len(ar1), len(ar2) + if(n1 == n2): + print('Median is', getMedian(ar1, ar2, n1)) + else: + print(""Doesn't work for arrays of unequal size"")" +Convert a given Binary tree to a tree that holds Logical AND property,"/*Java code to convert a given binary tree +to a tree that holds logical AND property. */ + +class GfG { +/*Structure of binary tree */ + +static class Node +{ + int data; + Node left; + Node right; +} +/*function to create a new node */ + +static Node newNode(int key) +{ + Node node = new Node(); + node.data= key; + node.left = null; + node.right = null; + return node; +} +/*Convert the given tree to a tree where +each node is logical AND of its children +The main idea is to do Postorder traversal */ + +static void convertTree(Node root) +{ + if (root == null) + return; + /* first recur on left child */ + + convertTree(root.left); + /* then recur on right child */ + + convertTree(root.right); + if (root.left != null && root.right != null) + root.data = (root.left.data) & (root.right.data); +} +static void printInorder(Node root) +{ + if (root == null) + return; + /* first recur on left child */ + + printInorder(root.left); + /* then print the data of node */ + + System.out.print(root.data + "" ""); + /* now recur on right child */ + + printInorder(root.right); +} +/*main function */ + +public static void main(String[] args) +{ + /* Create following Binary Tree + 1 + / \ + 1 0 + / \ / \ + 0 1 1 1 + */ + + Node root=newNode(0); + root.left=newNode(1); + root.right=newNode(0); + root.left.left=newNode(0); + root.left.right=newNode(1); + root.right.left=newNode(1); + root.right.right=newNode(1); + System.out.print(""Inorder traversal before conversion ""); + printInorder(root); + convertTree(root); + System.out.println(); + System.out.print(""Inorder traversal after conversion ""); + printInorder(root); +}}"," '''Program to convert an aribitary binary tree +to a tree that holds children sum property +Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newNode: + ''' Construct to create a new node ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Convert the given tree to a tree where +each node is logical AND of its children +The main idea is to do Postorder traversal ''' + +def convertTree(root) : + if (root == None) : + return + ''' first recur on left child ''' + + convertTree(root.left) + ''' then recur on right child ''' + + convertTree(root.right) + if (root.left != None and root.right != None): + root.data = ((root.left.data) & + (root.right.data)) +def printInorder(root) : + if (root == None) : + return + ''' first recur on left child ''' + + printInorder(root.left) + ''' then print the data of node ''' + + print( root.data, end = "" "") + ''' now recur on right child ''' + + printInorder(root.right) + '''Driver Code ''' + +if __name__ == '__main__': + ''' Create following Binary Tree + 1 + / \ + 1 0 + / \ / \ + 0 1 1 1 + ''' + + root = newNode(0) + root.left = newNode(1) + root.right = newNode(0) + root.left.left = newNode(0) + root.left.right = newNode(1) + root.right.left = newNode(1) + root.right.right = newNode(1) + print(""Inorder traversal before conversion"", + end = "" "") + printInorder(root) + convertTree(root) + print(""\nInorder traversal after conversion "", + end = "" "") + printInorder(root)" +How to swap two numbers without using a temporary variable?,"/*Java code to swap using XOR*/ + +import java.io.*; +public class GFG { + public static void main(String a[]) + { + int x = 10; + int y = 5; +/* Code to swap 'x' (1010) and 'y' (0101) +x now becomes 15 (1111)*/ + +x = x ^ y; +/*y becomes 10 (1010)*/ + +y = x ^ y; +/*x becomes 5 (0101)*/ + +x = x ^ y; + System.out.println(""After swap: x = "" + + x + "", y = "" + y); + } +}"," '''Python3 code to swap using XOR''' + +x = 10 +y = 5 + '''Code to swap 'x' and 'y' +x now becomes 15 (1111)''' + +x = x ^ y; + '''y becomes 10 (1010)''' + +y = x ^ y; + '''x becomes 5 (0101)''' + +x = x ^ y; +print (""After Swapping: x = "", x, "" y ="", y)" +Check for Majority Element in a sorted array,"import java.util.*; +class GFG{ +static boolean isMajorityElement(int arr[], int n, + int key) +{ + if (arr[n / 2] == key) + return true; + else + return false; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 2, 3, 3, 3, 3, 10 }; + int n = arr.length; + int x = 3; + if (isMajorityElement(arr, n, x)) + System.out.printf(""%d appears more than %d "" + + ""times in arr[]"", x, n / 2); + else + System.out.printf(""%d does not appear more "" + + ""than %d times in "" + ""arr[]"", + x, n / 2); +} +}","def isMajorityElement(arr, + n, key): + if (arr[n // 2] == key): + return True + return False + '''Driver code''' + +if __name__ == ""__main__"": + arr = [1, 2, 3, 3, + 3, 3, 10] + n = len(arr) + x = 3 + if (isMajorityElement(arr, n, x)): + print(x, "" appears more than "", + n // 2 , "" times in arr[]"") + else: + print(x, "" does not appear more than"", + n // 2, "" times in arr[]"")" +Minimum swaps to make two arrays identical,"/*Java program to make an array same to another +using minimum number of swap*/ + +import java.io.*; +import java.util.*; + +/*Function returns the minimum number of swaps +required to sort the array +This method is taken from below post +www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/ +https:*/ + +class GFG +{ + + static int minSwapsToSort(int arr[], int n) + { + +/* Create an array of pairs where first + element is array element and second element + is position of first element */ + + ArrayList> arrPos = new ArrayList>(); + for (int i = 0; i < n; i++) + { + arrPos.add(new ArrayList(Arrays.asList(arr[i],i))); + } + +/* Sort the array by array element values to + get right position of every element as second + element of pair.*/ + + Collections.sort(arrPos, new Comparator>() { + @Override + public int compare(ArrayList o1, ArrayList o2) { + return o1.get(0).compareTo(o2.get(0)); + } + }); + +/* To keep track of visited elements. Initialize + all elements as not visited or false.*/ + + boolean[] vis = new boolean[n]; + +/* Initialize result*/ + + int ans = 0; + +/* Traverse array elements*/ + + for (int i = 0; i < n; i++) + { + +/* already swapped and corrected or + already present at correct pos*/ + + if (vis[i] || arrPos.get(i).get(1) == i) + continue; + +/* find out the number of node in + this cycle and add in ans*/ + + int cycle_size = 0; + int j = i; + while (!vis[j]) + { + vis[j] = true; + +/* move to next node*/ + + j = arrPos.get(j).get(1); + cycle_size++; + } + +/* Update answer by adding current cycle.*/ + + ans += (cycle_size - 1); + } + +/* Return result*/ + + return ans; + } + +/* method returns minimum number of swap to make + array B same as array A*/ + + static int minSwapToMakeArraySame(int a[], int b[], int n) + { + +/* map to store position of elements in array B + we basically store element to index mapping.*/ + + Map mp + = new HashMap(); + + for (int i = 0; i < n; i++) + { + mp.put(b[i], i); + } + +/* now we're storing position of array A elements + in array B.*/ + + for (int i = 0; i < n; i++) + b[i] = mp.get(a[i]); + + /* returing minimum swap for sorting in modified + array B as final answer*/ + + return minSwapsToSort(b, n); + } + +/* Driver code*/ + + public static void main (String[] args) + { + int a[] = {3, 6, 4, 8}; + int b[] = {4, 6, 8, 3}; + int n = a.length; + + System.out.println( minSwapToMakeArraySame(a, b, n)); + } +} + + +"," '''Python3 program to make +an array same to another +using minimum number of swap''' + + + '''Function returns the minimum +number of swaps required to +sort the array +This method is taken from below post +https: // www.geeksforgeeks.org/ +minimum-number-swaps-required-sort-array/''' + +def minSwapsToSort(arr, n): + + ''' Create an array of pairs + where first element is + array element and second + element is position of + first element''' + + arrPos = [[0 for x in range(2)] + for y in range(n)] + + for i in range(n): + arrPos[i][0] = arr[i] + arrPos[i][1] = i + + ''' Sort the array by array + element values to get right + position of every element + as second element of pair.''' + + arrPos.sort() + + ''' To keep track of visited + elements. Initialize all + elements as not visited + or false.''' + + vis = [False] * (n) + + ''' Initialize result''' + + ans = 0 + + ''' Traverse array elements''' + + for i in range(n): + + ''' Already swapped and corrected or + already present at correct pos''' + + if (vis[i] or arrPos[i][1] == i): + continue + + ''' Find out the number of node in + this cycle and add in ans''' + + cycle_size = 0 + j = i + + while (not vis[j]): + vis[j] = 1 + + ''' Move to next node''' + + j = arrPos[j][1] + cycle_size+= 1 + + ''' Update answer by + adding current cycle.''' + + ans += (cycle_size - 1) + + ''' Return result''' + + return ans + + '''Method returns minimum +number of swap to mak +array B same as array A''' + +def minSwapToMakeArraySame(a, b, n): + + ''' map to store position + of elements in array B + we basically store + element to index mapping.''' + + mp = {} + for i in range(n): + mp[b[i]] = i + + ''' now we're storing position + of array A elements + in array B.''' + + for i in range(n): + b[i] = mp[a[i]] + + ''' Returing minimum swap + for sorting in modified + array B as final answer''' + + return minSwapsToSort(b, n) + + '''Driver code''' + +if __name__ == ""__main__"": + + a = [3, 6, 4, 8] + b = [4, 6, 8, 3] + n = len(a) + print(minSwapToMakeArraySame(a, b, n)) + + +" +Find if an expression has duplicate parenthesis or not,"/*Java program to find duplicate parenthesis in a +balanced expression */ +import java.util.Stack; +public class GFG {/*Function to find duplicate parenthesis in a +balanced expression */ + + static boolean findDuplicateparenthesis(String s) { +/* create a stack of characters */ + + Stack Stack = new Stack<>(); +/* Iterate through the given expression */ + + char[] str = s.toCharArray(); + for (char ch : str) { +/* if current character is close parenthesis ')' */ + + if (ch == ')') { +/* pop character from the stack */ + + char top = Stack.peek(); + Stack.pop(); +/* stores the number of characters between a + closing and opening parenthesis + if this count is less than or equal to 1 + then the brackets are redundant else not */ + + int elementsInside = 0; + while (top != '(') { + elementsInside++; + top = Stack.peek(); + Stack.pop(); + } + if (elementsInside < 1) { + return true; + } +} /*push open parenthesis '(', operators and operands to stack */ + + else { + Stack.push(ch); + } + } + + +/* No duplicates found */ + + return false; + } +/*Driver code */ + +public static void main(String[] args) { +/* input balanced expression */ + + String str = ""(((a+(b))+(c+d)))""; + if (findDuplicateparenthesis(str)) { + System.out.println(""Duplicate Found ""); + } else { + System.out.println(""No Duplicates Found ""); + } + } +}"," '''Python3 program to find duplicate +parenthesis in a balanced expression ''' + + '''Function to find duplicate parenthesis +in a balanced expression ''' + +def findDuplicateparenthesis(string): ''' create a stack of characters ''' + + Stack = [] + ''' Iterate through the given expression ''' + + for ch in string: + ''' if current character is + close parenthesis ')' ''' + + if ch == ')': + ''' pop character from the stack ''' + + top = Stack.pop() + ''' stores the number of characters between + a closing and opening parenthesis + if this count is less than or equal to 1 + then the brackets are redundant else not ''' + + elementsInside = 0 + while top != '(': + elementsInside += 1 + top = Stack.pop() + if elementsInside < 1: + return True + ''' push open parenthesis '(', operators + and operands to stack ''' + + else: + Stack.append(ch) + ''' No duplicates found ''' + + return False + '''Driver Code''' + +if __name__ == ""__main__"": + ''' input balanced expression ''' + + string = ""(((a+(b))+(c+d)))"" + if findDuplicateparenthesis(string) == True: + print(""Duplicate Found"") + else: + print(""No Duplicates Found"")" +Palindrome Partitioning | DP-17,," '''Using memoizatoin to solve the partition problem. +Function to check if input string is pallindrome or not''' + +def ispallindrome(input, start, end): + ''' Using two pointer technique to check pallindrome''' + + while (start < end): + if (input[start] != input[end]): + return False; + start += 1 + end -= 1 + return True; + '''Function to find keys for the Hashmap''' + +def convert(a, b): + return str(a) + str(b); + '''Returns the minimum number of cuts needed to partition a string +such that every part is a palindrome''' + +def minpalparti_memo(input, i, j, memo): + if (i > j): + return 0; + ''' Key for the Input String''' + + ij = convert(i, j); + ''' If the no of partitions for string ""ij"" is already calculated + then return the calculated value using the Hashmap''' + + if (ij in memo): + return memo[ij]; + ''' Every String of length 1 is a pallindrome''' + + if (i == j): + memo[ij] = 0; + return 0; + if (ispallindrome(input, i, j)): + memo[ij] = 0; + return 0; + minimum = 1000000000 + ''' Make a cut at every possible location starting from i to j''' + + for k in range(i, j): + left_min = 1000000000 + right_min = 1000000000 + left = convert(i, k); + right = convert(k + 1, j); + ''' If left cut is found already''' + + if (left in memo): + left_min = memo[left]; + ''' If right cut is found already''' + + if (right in memo): + right_min = memo[right]; + ''' Recursively calculating for left and right strings''' + + if (left_min == 1000000000): + left_min = minpalparti_memo(input, i, k, memo); + if (right_min == 1000000000): + right_min = minpalparti_memo(input, k + 1, j, memo); + ''' Taking minimum of all k possible cuts''' + + minimum = min(minimum, left_min + 1 + right_min); + memo[ij] = minimum; + ''' Return the min cut value for complete string.''' + + return memo[ij]; + ''' Driver code''' + +if __name__=='__main__': + input = ""ababbbabbababa""; + memo = dict() + print(minpalparti_memo(input, 0, len(input) - 1, memo))" +Sum of leaf nodes at minimum level,"/*Java implementation to find the sum of +leaf nodes at minimum level*/ + +import java.util.*; +class GFG +{ +/*structure of a node of binary tree*/ + +static class Node +{ + int data; + Node left, right; +}; +/*function to get a new node*/ + +static Node getNode(int data) +{ +/* allocate space*/ + + Node newNode = new Node(); +/* put in the data*/ + + newNode.data = data; + newNode.left = newNode.right = null; + return newNode; +} +/*function to find the sum of +leaf nodes at minimum level*/ + +static int sumOfLeafNodesAtMinLevel(Node root) +{ +/* if tree is empty*/ + + if (root == null) + return 0; +/* if there is only one node*/ + + if (root.left == null && + root.right == null) + return root.data; +/* queue used for level order traversal*/ + + Queue q = new LinkedList<>(); + int sum = 0; + boolean f = false; +/* push root node in the queue 'q'*/ + + q.add(root); + while (f == false) + { +/* count number of nodes in the + current level*/ + + int nc = q.size(); +/* traverse the current level nodes*/ + + while (nc-- >0) + { +/* get front element from 'q'*/ + + Node top = q.peek(); + q.remove(); +/* if it is a leaf node*/ + + if (top.left == null && + top.right == null) + { +/* accumulate data to 'sum'*/ + + sum += top.data; +/* set flag 'f' to 1, to signify + minimum level for leaf nodes + has been encountered*/ + + f = true; + } + else + { +/* if top's left and right child + exists, then push them to 'q'*/ + + if (top.left != null) + q.add(top.left); + if (top.right != null) + q.add(top.right); + } + } + } +/* required sum*/ + + return sum; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* binary tree creation*/ + + Node root = getNode(1); + root.left = getNode(2); + root.right = getNode(3); + root.left.left = getNode(4); + root.left.right = getNode(5); + root.right.left = getNode(6); + root.right.right = getNode(7); + root.left.right.left = getNode(8); + root.right.left.right = getNode(9); + System.out.println(""Sum = "" + + sumOfLeafNodesAtMinLevel(root)); + } +}"," '''Python3 implementation to find the sum +of leaf node at minimum level''' + +from collections import deque + '''Structure of a node in binary tree''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''function to find the sum of leaf nodes +at minimum level''' + +def sumOfLeafNodesAtLeafLevel(root): + ''' if tree is empty''' + + if not root: + return 0 + ''' if there is only root node''' + + if not root.left and not root.right: + return root.data + ''' Queue used for level order traversal''' + + Queue = deque() + sum = f = 0 + ''' push rioot node in the queue''' + + Queue.append(root) + while not f: + ''' count no. of nodes present at current level''' + + nc = len(Queue) + ''' traverse current level nodes''' + + while nc: + + ''' get front element from 'q' ''' + + top = Queue.popleft() ''' if node is leaf node''' + + if not top.left and not top.right: + + ''' accumulate data to 'sum' ''' + + sum += top.data ''' set flag = 1 to signify that + we have encountered the minimum level''' + + f = 1 + else: + ''' if top's left or right child exist + push them to Queue''' + + if top.left: + Queue.append(top.left) + if top.right: + Queue.append(top.right) + nc -= 1 + ''' return the sum''' + + return sum + '''Driver code''' + +if __name__ == ""__main__"": + ''' binary tree creation''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.left.right.left = Node(8) + root.right.left.right = Node(9) + print(""Sum = "", sumOfLeafNodesAtLeafLevel(root))" +Level of Each node in a Tree from source node (using BFS),"/*Java Program to determine level of each node +and print level */ + +import java.util.*; +class GFG +{ +/*function to determine level of each node starting +from x using BFS */ + +static void printLevels(Vector> graph, int V, int x) +{ +/* array to store level of each node */ + + int level[] = new int[V]; + boolean marked[] = new boolean[V]; +/* create a queue */ + + Queue que = new LinkedList(); +/* enqueue element x */ + + que.add(x); +/* initialize level of source node to 0 */ + + level[x] = 0; +/* marked it as visited */ + + marked[x] = true; +/* do until queue is empty */ + + while (que.size() > 0) + { +/* get the first element of queue */ + + x = que.peek(); +/* dequeue element */ + + que.remove(); +/* traverse neighbors of node x */ + + for (int i = 0; i < graph.get(x).size(); i++) + { +/* b is neighbor of node x */ + + int b = graph.get(x).get(i); +/* if b is not marked already */ + + if (!marked[b]) + { +/* enqueue b in queue */ + + que.add(b); +/* level of b is level of x + 1 */ + + level[b] = level[x] + 1; +/* mark b */ + + marked[b] = true; + } + } + } +/* display all nodes and their levels */ + + System.out.println( ""Nodes"" + + "" "" + + ""Level""); + for (int i = 0; i < V; i++) + System.out.println("" "" + i +"" --> "" + level[i] ); +} +/*Driver Code */ + +public static void main(String args[]) +{ +/* adjacency graph for tree */ + + int V = 8; + Vector> graph=new Vector>(); + for(int i = 0; i < V + 1; i++) + graph.add(new Vector()); + graph.get(0).add(1); + graph.get(0).add(2); + graph.get(1).add(3); + graph.get(1).add(4); + graph.get(1).add(5); + graph.get(2).add(5); + graph.get(2).add(6); + graph.get(6).add(7); +/* call levels function with source as 0 */ + + printLevels(graph, V, 0); +} +}"," '''Python3 Program to determine level +of each node and print level ''' + +import queue + '''function to determine level of +each node starting from x using BFS ''' + +def printLevels(graph, V, x): + ''' array to store level of each node ''' + + level = [None] * V + marked = [False] * V + ''' create a queue ''' + + que = queue.Queue() + ''' enqueue element x ''' + + que.put(x) + ''' initialize level of source + node to 0 ''' + + level[x] = 0 + ''' marked it as visited ''' + + marked[x] = True + ''' do until queue is empty ''' + + while (not que.empty()): + ''' get the first element of queue ''' + + x = que.get() + ''' traverse neighbors of node x''' + + for i in range(len(graph[x])): + ''' b is neighbor of node x ''' + + b = graph[x][i] + ''' if b is not marked already ''' + + if (not marked[b]): + ''' enqueue b in queue ''' + + que.put(b) + ''' level of b is level of x + 1 ''' + + level[b] = level[x] + 1 + ''' mark b ''' + + marked[b] = True + ''' display all nodes and their levels ''' + + print(""Nodes"", "" "", ""Level"") + for i in range(V): + print("" "",i, "" --> "", level[i]) + '''Driver Code ''' + +if __name__ == '__main__': + ''' adjacency graph for tree ''' + + V = 8 + graph = [[] for i in range(V)] + graph[0].append(1) + graph[0].append(2) + graph[1].append(3) + graph[1].append(4) + graph[1].append(5) + graph[2].append(5) + graph[2].append(6) + graph[6].append(7) + ''' call levels function with source as 0 ''' + + printLevels(graph, V, 0)" +Pairs with Difference less than K,"/*java code to find count of Pairs with +difference less than K.*/ + +import java.io.*; + +class GFG { + + +/* Function to count pairs*/ + + static int countPairs(int a[], int n, int k) + { + int res = 0; + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + if (Math.abs(a[j] - a[i]) < k) + res++; + + return res; + }/* Driver code*/ + + public static void main (String[] args) + { + int a[] = {1, 10, 4, 2}; + int k = 3; + int n = a.length; + System.out.println(countPairs(a, n, k)); + + } +} + + +"," '''Python3 code to find count of Pairs +with difference less than K.''' + + + + ''' Function to count pairs''' + + +def countPairs(a, n, k): + res = 0 + for i in range(n): + for j in range(i + 1, n): + if (abs(a[j] - a[i]) < k): + res += 1 + + return res '''Driver code''' + +a = [1, 10, 4, 2] +k = 3 +n = len(a) +print(countPairs(a, n, k), end = """") + + +" +Length of longest strict bitonic subsequence,"/*Java implementation to find length of longest +strict bitonic subsequence*/ + +import java.util.*; +class GfG +{ +/*function to find length of longest +strict bitonic subsequence*/ + +static int longLenStrictBitonicSub(int arr[], int n) +{ +/* hash table to map the array element with the + length of the longest subsequence of which + it is a part of and is the last/first element of + that subsequence*/ + + HashMap inc = new HashMap (); + HashMap dcr = new HashMap (); +/* arrays to store the length of increasing and + decreasing subsequences which end at them + or start from them*/ + + int len_inc[] = new int[n]; + int len_dcr[] = new int[n]; +/* to store the length of longest strict + bitonic subsequence*/ + + int longLen = 0; +/* traverse the array elements + from left to right*/ + + for (int i = 0; i < n; i++) + { +/* initialize current length + for element arr[i] as 0*/ + + int len = 0; +/* if 'arr[i]-1' is in 'inc'*/ + + if (inc.containsKey(arr[i] - 1)) + len = inc.get(arr[i] - 1); +/* update arr[i] subsequence length in 'inc' + and in len_inc[]*/ + + len_inc[i] = len + 1; + inc.put(arr[i], len_inc[i]); + } +/* traverse the array elements + from right to left*/ + + for (int i = n - 1; i >= 0; i--) + { +/* initialize current length + for element arr[i] as 0*/ + + int len = 0; +/* if 'arr[i]-1' is in 'dcr'*/ + + if (dcr.containsKey(arr[i] - 1)) + len = dcr.get(arr[i] - 1); +/* update arr[i] subsequence length in 'dcr' + and in len_dcr[]*/ + + len_dcr[i] = len + 1; + dcr.put(arr[i], len_dcr[i]); + } +/* calculating the length of all the strict + bitonic subsequence*/ + + for (int i = 0; i < n; i++) + if (longLen < (len_inc[i] + len_dcr[i] - 1)) + longLen = len_inc[i] + len_dcr[i] - 1; +/* required longest length strict + bitonic subsequence*/ + + return longLen; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {1, 5, 2, 3, 4, 5, 3, 2}; + int n = arr.length; + System.out.println(""Longest length strict "" + + ""bitonic subsequence = "" + + longLenStrictBitonicSub(arr, n)); +} +}"," '''Python3 implementation to find length of +longest strict bitonic subsequence + ''' '''function to find length of longest +strict bitonic subsequence''' + +def longLenStrictBitonicSub(arr, n): + ''' hash table to map the array element + with the length of the longest subsequence + of which it is a part of and is the + last/first element of that subsequence''' + + inc, dcr = dict(), dict() + ''' arrays to store the length of increasing + and decreasing subsequences which end at + them or start from them''' + + len_inc, len_dcr = [0] * n, [0] * n + ''' to store the length of longest strict + bitonic subsequence''' + + longLen = 0 + ''' traverse the array elements + from left to right''' + + for i in range(n): + ''' initialize current length + for element arr[i] as 0''' + + len = 0 + ''' if 'arr[i]-1' is in 'inc''' + ''' + if inc.get(arr[i] - 1) in inc.values(): + len = inc.get(arr[i] - 1) + ''' update arr[i] subsequence length in 'inc' + and in len_inc[]''' + + inc[arr[i]] = len_inc[i] = len + 1 + ''' traverse the array elements + from right to left''' + + for i in range(n - 1, -1, -1): + ''' initialize current length + for element arr[i] as 0''' + + len = 0 + ''' if 'arr[i]-1' is in 'dcr''' + ''' + if dcr.get(arr[i] - 1) in dcr.values(): + len = dcr.get(arr[i] - 1) + ''' update arr[i] subsequence length + in 'dcr' and in len_dcr[]''' + + dcr[arr[i]] = len_dcr[i] = len + 1 + ''' calculating the length of + all the strict bitonic subsequence''' + + for i in range(n): + if longLen < (len_inc[i] + len_dcr[i] - 1): + longLen = len_inc[i] + len_dcr[i] - 1 + ''' required longest length strict + bitonic subsequence''' + + return longLen + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 5, 2, 3, 4, 5, 3, 2] + n = len(arr) + print(""Longest length strict bitonic subsequence ="", + longLenStrictBitonicSub(arr, n))" +Iteratively Reverse a linked list using only 2 pointers (An Interesting Method),"/*Java program to reverse a linked +list using two pointers.*/ + +import java.util.*; + +class Main{ + +/*Link list node*/ + +static class Node +{ + int data; + Node next; +}; + +static Node head_ref = null; + +/*Function to reverse the linked +list using 2 pointers*/ + +static void reverse() +{ + Node prev = null; + Node current = head_ref; + +/* At last prev points to new head*/ + + while (current != null) + { + +/* This expression evaluates from left to right + current.next = prev, changes the link fron + next to prev node + prev = current, moves prev to current node for + next reversal of node + This example of list will clear it more 1.2.3.4 + initially prev = 1, current = 2 + Final expression will be current = 1^2^3^2^1, + as we know that bitwise XOR of two same + numbers will always be 0 i.e; 1^1 = 2^2 = 0 + After the evaluation of expression current = 3 that + means it has been moved by one node from its + previous position*/ + + Node next = current.next; + current.next = prev; + prev = current; + current = next; + } + head_ref = prev; +} + +/*Function to push a node*/ + +static void push(int new_data) +{ + +/* Allocate node*/ + + Node new_node = new Node(); + +/* Put in the data */ + + new_node.data = new_data; + +/* Link the old list off the new node*/ + + new_node.next = (head_ref); + +/* Move the head to point to the new node*/ + + (head_ref) = new_node; +} + +/*Function to print linked list*/ + +static void printList() +{ + Node temp = head_ref; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } +} + +/*Driver code*/ + +public static void main(String []args) +{ + push(20); + push(4); + push(15); + push(85); + + System.out.print(""Given linked list\n""); + printList(); + reverse(); + System.out.print(""\nReversed Linked list \n""); + printList(); +} +} + + +", +Perfect Binary Tree Specific Level Order Traversal,"/*Java program for special level order traversal*/ + +import java.util.LinkedList; +import java.util.Queue; +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} + + /* Given a perfect binary tree, print its nodes in specific + level order */ +class BinaryTree +{ + Node root; + void printSpecificLevelOrder(Node node) + { + if (node == null) + return; +/* Let us print root and next level first*/ + + System.out.print(node.data); +/* Since it is perfect Binary Tree, right is not checked*/ + + if (node.left != null) + System.out.print("" "" + node.left.data + "" "" + node.right.data); +/* Do anything more if there are nodes at next level in + given perfect Binary Tree*/ + + if (node.left.left == null) + return; +/* Create a queue and enqueue left and right children of root*/ + + Queue q = new LinkedList(); + q.add(node.left); + q.add(node.right); +/* We process two nodes at a time, so we need two variables + to store two front items of queue*/ + + Node first = null, second = null; +/* traversal loop*/ + + while (!q.isEmpty()) + { +/* Pop two items from queue*/ + + first = q.peek(); + q.remove(); + second = q.peek(); + q.remove(); +/* Print children of first and second in reverse order*/ + + System.out.print("" "" + first.left.data + "" "" +second.right.data); + System.out.print("" "" + first.right.data + "" "" +second.left.data); +/* If first and second have grandchildren, enqueue them + in reverse order*/ + + if (first.left.left != null) + { + q.add(first.left); + q.add(second.right); + q.add(first.right); + q.add(second.left); + } + } + } +/* Driver program to test for above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.left.left = new Node(8); + tree.root.left.left.right = new Node(9); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(11); + tree.root.right.left.left = new Node(12); + tree.root.right.left.right = new Node(13); + tree.root.right.right.left = new Node(14); + tree.root.right.right.right = new Node(15); + tree.root.left.left.left.left = new Node(16); + tree.root.left.left.left.right = new Node(17); + tree.root.left.left.right.left = new Node(18); + tree.root.left.left.right.right = new Node(19); + tree.root.left.right.left.left = new Node(20); + tree.root.left.right.left.right = new Node(21); + tree.root.left.right.right.left = new Node(22); + tree.root.left.right.right.right = new Node(23); + tree.root.right.left.left.left = new Node(24); + tree.root.right.left.left.right = new Node(25); + tree.root.right.left.right.left = new Node(26); + tree.root.right.left.right.right = new Node(27); + tree.root.right.right.left.left = new Node(28); + tree.root.right.right.left.right = new Node(29); + tree.root.right.right.right.left = new Node(30); + tree.root.right.right.right.right = new Node(31); + System.out.println(""Specific Level Order traversal of binary"" + +""tree is ""); + tree.printSpecificLevelOrder(tree.root); + } +}"," '''Python program for special order traversal ''' + + '''A binary tree ndoe ''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Given a perfect binary tree print its node in +specific order''' + +def printSpecificLevelOrder(root): + if root is None: + return + ''' Let us print root and next level first''' + + print root.data, + ''' Since it is perfect Binary tree, + one of the node is needed to be checked''' + + if root.left is not None : + print root.left.data, + print root.right.data, + ''' Do anythong more if there are nodes at next level + in given perfect Binary Tree''' + + if root.left.left is None: + return + ''' Create a queue and enqueue left and right + children of root''' + + q = [] + q.append(root.left) + q.append(root.right) + ''' We process two nodes at a time, so we need + two variables to stroe two front items of queue''' + + first = None + second = None + ''' Traversal loop ''' + + while(len(q) > 0): + ''' Pop two items from queue''' + + first = q.pop(0) + second = q.pop(0) + ''' Print children of first and second in reverse order''' + + print first.left.data, + print second.right.data, + print first.right.data, + print second.left.data, + ''' If first and second have grandchildren, + enqueue them in reverse order''' + + if first.left.left is not None: + q.append(first.left) + q.append(second.right) + q.append(first.right) + q.append(second.left) + '''Driver program to test above function +Perfect Binary Tree of Height 4''' + +root = Node(1) +root.left= Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) +root.left.left.left = Node(8) +root.left.left.right = Node(9) +root.left.right.left = Node(10) +root.left.right.right = Node(11) +root.right.left.left = Node(12) +root.right.left.right = Node(13) +root.right.right.left = Node(14) +root.right.right.right = Node(15) +root.left.left.left.left = Node(16) +root.left.left.left.right = Node(17) +root.left.left.right.left = Node(18) +root.left.left.right.right = Node(19) +root.left.right.left.left = Node(20) +root.left.right.left.right = Node(21) +root.left.right.right.left = Node(22) +root.left.right.right.right = Node(23) +root.right.left.left.left = Node(24) +root.right.left.left.right = Node(25) +root.right.left.right.left = Node(26) +root.right.left.right.right = Node(27) +root.right.right.left.left = Node(28) +root.right.right.left.right = Node(29) +root.right.right.right.left = Node(30) +root.right.right.right.right = Node(31) +print ""Specific Level Order traversal of binary tree is"" +printSpecificLevelOrder(root);" +Program to Interchange Diagonals of Matrix,"/*Java program to interchange +the diagonals of matrix*/ + +import java.io.*; +class GFG +{ + public static int N = 3; +/* Function to interchange diagonals*/ + + static void interchangeDiagonals(int array[][]) + { +/* swap elements of diagonal*/ + + for (int i = 0; i < N; ++i) + if (i != N / 2) + { + int temp = array[i][i]; + array[i][i] = array[i][N - i - 1]; + array[i][N - i - 1] = temp; + } + for (int i = 0; i < N; ++i) + { + for (int j = 0; j < N; ++j) + System.out.print(array[i][j]+"" ""); + System.out.println(); + } + } +/* Driver Code*/ + + public static void main (String[] args) + { + int array[][] = { {4, 5, 6}, + {1, 2, 3}, + {7, 8, 9} + }; + interchangeDiagonals(array); + } +}"," '''Python program to interchange +the diagonals of matrix''' + +N = 3; + '''Function to interchange diagonals''' + +def interchangeDiagonals(array): + ''' swap elements of diagonal''' + + for i in range(N): + if (i != N / 2): + temp = array[i][i]; + array[i][i] = array[i][N - i - 1]; + array[i][N - i - 1] = temp; + for i in range(N): + for j in range(N): + print(array[i][j], end = "" ""); + print(); + '''Driver Code''' + +if __name__ == '__main__': + array = [ 4, 5, 6 ],[ 1, 2, 3 ],[ 7, 8, 9 ]; + interchangeDiagonals(array);" +Longest Palindromic Substring | Set 1,"/*Java Solution*/ + +public class LongestPalinSubstring { +/* A utility function to print + a substring str[low..high]*/ + + static void printSubStr( + String str, int low, int high) + { + System.out.println( + str.substring( + low, high + 1)); + } +/* This function prints the longest + palindrome substring of str[]. + It also returns the length of the + longest palindrome*/ + + static int longestPalSubstr(String str) + { +/* get length of input string*/ + + int n = str.length(); +/* table[i][j] will be false if + substring str[i..j] is not palindrome. + Else table[i][j] will be true*/ + + boolean table[][] = new boolean[n][n]; +/* All substrings of length 1 are palindromes*/ + + int maxLength = 1; + for (int i = 0; i < n; ++i) + table[i][i] = true; +/* check for sub-string of length 2.*/ + + int start = 0; + for (int i = 0; i < n - 1; ++i) { + if (str.charAt(i) == str.charAt(i + 1)) { + table[i][i + 1] = true; + start = i; + maxLength = 2; + } + } +/* Check for lengths greater than 2. + k is length of substring*/ + + for (int k = 3; k <= n; ++k) { +/* Fix the starting index*/ + + for (int i = 0; i < n - k + 1; ++i) { +/* Get the ending index of substring from + starting index i and length k*/ + + int j = i + k - 1; +/* checking for sub-string from ith index to + jth index iff str.charAt(i+1) to + str.charAt(j-1) is a palindrome*/ + + if (table[i + 1][j - 1] + && str.charAt(i) == str.charAt(j)) { + table[i][j] = true; + if (k > maxLength) { + start = i; + maxLength = k; + } + } + } + } + System.out.print(""Longest palindrome substring is; ""); + printSubStr(str, start, + start + maxLength - 1); +/* return length of LPS*/ + + return maxLength; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + String str = ""forgeeksskeegfor""; + System.out.println(""Length is: "" + longestPalSubstr(str)); + } +}"," '''Python program''' + +import sys + '''A utility function to print a +substring str[low..high]''' + +def printSubStr(st, low, high) : + sys.stdout.write(st[low : high + 1]) + sys.stdout.flush() + return '' + '''This function prints the longest palindrome +substring of st[]. It also returns the length +of the longest palindrome''' + +def longestPalSubstr(st) : + '''get length of input string''' + + n = len(st) + ''' table[i][j] will be false if substring + str[i..j] is not palindrome. Else + table[i][j] will be true''' + + table = [[0 for x in range(n)] for y + in range(n)] + ''' All substrings of length 1 are + palindromes''' + + maxLength = 1 + i = 0 + while (i < n) : + table[i][i] = True + i = i + 1 + ''' check for sub-string of length 2.''' + + start = 0 + i = 0 + while i < n - 1 : + if (st[i] == st[i + 1]) : + table[i][i + 1] = True + start = i + maxLength = 2 + i = i + 1 + ''' Check for lengths greater than 2. + k is length of substring''' + + k = 3 + while k <= n : + ''' Fix the starting index''' + + i = 0 + while i < (n - k + 1) : + ''' Get the ending index of + substring from starting + index i and length k''' + + j = i + k - 1 + ''' checking for sub-string from + ith index to jth index iff + st[i + 1] to st[(j-1)] is a + palindrome''' + + if (table[i + 1][j - 1] and + st[i] == st[j]) : + table[i][j] = True + if (k > maxLength) : + start = i + maxLength = k + i = i + 1 + k = k + 1 + print ""Longest palindrome substring is: "", printSubStr(st, start, + start + maxLength - 1) + '''return length of LPS''' + + return maxLength + '''Driver program to test above functions''' + +st = ""forgeeksskeegfor"" +l = longestPalSubstr(st) +print ""Length is:"", l" +"Given an array arr[], find the maximum j","/*Java implementation of +the hashmap approach*/ + +import java.io.*; +import java.util.*; + +class GFG{ + +/*Function to find maximum +index difference*/ + +static int maxIndexDiff(ArrayList arr, int n) +{ + +/* Initilaise unordered_map*/ + + Map> hashmap = new HashMap>(); + +/* Iterate from 0 to n - 1*/ + + for(int i = 0; i < n; i++) + { + if(hashmap.containsKey(arr.get(i))) + { + hashmap.get(arr.get(i)).add(i); + } + else + { + hashmap.put(arr.get(i), new ArrayList()); + hashmap.get(arr.get(i)).add(i); + } + } + +/* Sort arr*/ + + Collections.sort(arr); + int maxDiff = Integer.MIN_VALUE; + int temp = n; + +/* Iterate from 0 to n - 1*/ + + for(int i = 0; i < n; i++) + { + if (temp > hashmap.get(arr.get(i)).get(0)) + { + temp = hashmap.get(arr.get(i)).get(0); + } + maxDiff = Math.max(maxDiff, + hashmap.get(arr.get(i)).get( + hashmap.get(arr.get(i)).size() - 1) - temp); + } + return maxDiff; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int n = 9; + ArrayList arr = new ArrayList( + Arrays.asList(34, 8, 10, 3, 2, 80, 30, 33, 1)); + +/* Function Call*/ + + int ans = maxIndexDiff(arr, n); + + System.out.println(""The maxIndexDiff is : "" + ans); +} +} + + +", +Construct a Binary Tree from Postorder and Inorder,"/*Java program to construct a tree using inorder +and postorder traversals*/ + +/* A binary tree node has data, pointer to left + child and a pointer to right child */ + +class Node { + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree { + /* Recursive function to construct binary of size n + from Inorder traversal in[] and Postrder traversal + post[]. Initial values of inStrt and inEnd should + be 0 and n -1. The function doesn't do any error + checking for cases where inorder and postorder + do not form a tree */ + + Node buildUtil(int in[], int post[], int inStrt, + int inEnd, int postStrt, int postEnd) + { +/* Base case*/ + + if (inStrt > inEnd) + return null; + /* Pick current node from Postrder traversal using + postIndex and decrement postIndex */ + + Node node = new Node(post[postEnd]); + /* If this node has no children then return */ + + if (inStrt == inEnd) + return node; + + /* Else find the index of this node in Inorder + traversal */ + + int iIndex = search(in, inStrt, inEnd, node.data);/* Using index in Inorder traversal, construct left + and right subtress */ + + node.left = buildUtil( + in, post, inStrt, iIndex - 1, postStrt, + postStrt - inStrt + iIndex - 1); + node.right = buildUtil(in, post, iIndex + 1, inEnd, + postEnd - inEnd + iIndex, + postEnd - 1); + return node; + } + /* Function to find index of value in arr[start...end] + The function assumes that value is postsent in in[] + */ + + int search(int arr[], int strt, int end, int value) + { + int i; + for (i = strt; i <= end; i++) { + if (arr[i] == value) + break; + } + return i; + } + /* This funtcion is here just to test */ + + void preOrder(Node node) + { + if (node == null) + return; + System.out.print(node.data + "" ""); + preOrder(node.left); + preOrder(node.right); + } +/* Driver Code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + int in[] = new int[] { 4, 8, 2, 5, 1, 6, 3, 7 }; + int post[] = new int[] { 8, 4, 5, 2, 6, 7, 3, 1 }; + int n = in.length; + Node root + = tree.buildUtil(in, post, 0, n - 1, 0, n - 1); + System.out.println( + ""Preorder of the constructed tree : ""); + tree.preOrder(root); + } +}"," '''Python3 program to construct tree using +inorder and postorder traversals''' + + '''Recursive function to construct binary +of size n from Inorder traversal in[] +and Postorder traversal post[]. Initial +values of inStrt and inEnd should be +0 and n -1. The function doesn't do any +error checking for cases where inorder +and postorder do not form a tree''' + +def buildUtil(In, post, inStrt, inEnd, pIndex): + ''' Base case''' + + if (inStrt > inEnd): + return None + ''' Pick current node from Postorder traversal + using postIndex and decrement postIndex''' + + node = newNode(post[pIndex[0]]) + pIndex[0] -= 1 + ''' If this node has no children + then return''' + + if (inStrt == inEnd): + return node + ''' Else find the index of this node + in Inorder traversal''' + + iIndex = search(In, inStrt, inEnd, node.data) + ''' Using index in Inorder traversal, + construct left and right subtress''' + + node.right = buildUtil(In, post, iIndex + 1, + inEnd, pIndex) + node.left = buildUtil(In, post, inStrt, + iIndex - 1, pIndex) + return node + '''This function mainly initializes index +of root and calls buildUtil()''' + +def buildTree(In, post, n): + pIndex = [n - 1] + return buildUtil(In, post, 0, n - 1, pIndex) + '''Function to find index of value in +arr[start...end]. The function assumes +that value is postsent in in[]''' + +def search(arr, strt, end, value): + i = 0 + for i in range(strt, end + 1): + if (arr[i] == value): + break + return i + '''Helper function that allocates +a new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''This funtcion is here just to test''' + +def preOrder(node): + if node == None: + return + print(node.data,end="" "") + preOrder(node.left) + preOrder(node.right) + '''Driver code''' + +if __name__ == '__main__': + In = [4, 8, 2, 5, 1, 6, 3, 7] + post = [8, 4, 5, 2, 6, 7, 3, 1] + n = len(In) + root = buildTree(In, post, n) + print(""Preorder of the constructed tree :"") + preOrder(root)" +Maximizing Unique Pairs from two arrays,"/*Java program for Maximizing Unique Pairs +from two arrays*/ + +import java.util.*; + +class GFG +{ + +/*Returns count of maximum pairs that caan +be formed from a[] and b[] under given +constraints.*/ + +static int findMaxPairs(int a[], int b[], + int n, int k) +{ +/*Sorting the first array.*/ + +Arrays.sort(a); +/*Sorting the second array.*/ + +Arrays.sort(b); + + int result = 0; + for (int i = 0, j = 0; i < n && j < n;) + { + if (Math.abs(a[i] - b[j]) <= k) + { + result++; + +/* Increasing array pointer of + both the first and the second array.*/ + + i++; + j++; + } + +/* Increasing array pointer + of the second array.*/ + + else if(a[i] > b[j]) + j++; + +/* Increasing array pointer + of the first array.*/ + + else + i++; + } + return result; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + int a[] = {10, 15, 20}; + int b[] = {17, 12, 24}; + int n = a.length; + int k = 3; + System.out.println(findMaxPairs(a, b, n, k)); +} +} + + +"," '''Python3 program for +Maximizing Unique Pairs +from two arrays''' + + + '''Returns count of maximum pairs that caan +be formed from a[] and b[] under given +constraints.''' + +def findMaxPairs(a,b,n,k): + + ''' Sorting the first array.''' + + a.sort() + + ''' Sorting the second array.''' + + b.sort() + + result =0 + j=0 + for i in range(n): + if jb[j]: + j+=1 + return result + + '''Driver code''' + +if __name__=='__main__': + a = [10,15,20] + b = [17,12,24] + n = len(a) + k =3 + print(findMaxPairs(a,b,n,k)) + + +" +Two Pointers Technique,"/*Naive solution to find if there is a +pair in A[0..N-1] with given sum.*/ + +import java.io.*; +class GFG { + + private static int isPairSum(int A[], int N, int X) + { + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { +/* as equal i and j means same element*/ + + if (i == j) + continue; +/* pair exists*/ + + if (A[i] + A[j] == X) + return true; +/* as the array is sorted*/ + + if (A[i] + A[j] > X) + break; + } + } +/* No pair found with given sum.*/ + + return 0; + } +}/*Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 3, 5, 9, 2, 8, 10, 11 }; + int val = 17; +/* Function call*/ + + System.out.println(isPairSum(arr, arr.length, val)); + }"," '''Naive solution to find if there is a +pair in A[0..N-1] with given sum.''' + +def isPairSum(A, N, X): + for i in range(N): + for j in range(N): + ''' as equal i and j means same element''' + + if(i == j): + continue + ''' pair exists''' + + if (A[i] + A[j] == X): + return True + ''' as the array is sorted''' + + if (A[i] + A[j] > X): + break + ''' No pair found with given sum''' + + return 0 + '''Driver code''' + +arr = [3, 5, 9, 2, 8, 10, 11] +val = 17 + ''' Function call''' + +print(isPairSum(arr, len(arr), val))" +A Boolean Matrix Question,"class GFG +{ + public static void modifyMatrix(int mat[][]){ +/* variables to check if there are any 1 + in first row and column*/ + + boolean row_flag = false; + boolean col_flag = false; +/* updating the first row and col if 1 + is encountered*/ + + for (int i = 0; i < mat.length; i++ ){ + for (int j = 0; j < mat[0].length; j++){ + if (i == 0 && mat[i][j] == 1) + row_flag = true; + if (j == 0 && mat[i][j] == 1) + col_flag = true; + if (mat[i][j] == 1){ + mat[0][j] = 1; + mat[i][0] = 1; + } + } + } +/* Modify the input matrix mat[] using the + first row and first column of Matrix mat*/ + + for (int i = 1; i < mat.length; i ++){ + for (int j = 1; j < mat[0].length; j ++){ + if (mat[0][j] == 1 || mat[i][0] == 1){ + mat[i][j] = 1; + } + } + } +/* modify first row if there was any 1*/ + + if (row_flag == true){ + for (int i = 0; i < mat[0].length; i++){ + mat[0][i] = 1; + } + } +/* modify first col if there was any 1*/ + + if (col_flag == true){ + for (int i = 0; i < mat.length; i ++){ + mat[i][0] = 1; + } + } + } + /* A utility function to print a 2D matrix */ + + public static void printMatrix(int mat[][]){ + for (int i = 0; i < mat.length; i ++){ + for (int j = 0; j < mat[0].length; j ++){ + System.out.print( mat[i][j] ); + } + System.out.println(""""); + } + } +/* Driver function to test the above function*/ + + public static void main(String args[] ){ + int mat[][] = {{1, 0, 0, 1}, + {0, 0, 1, 0}, + {0, 0, 0, 0}}; + System.out.println(""Input Matrix :""); + printMatrix(mat); + modifyMatrix(mat); + System.out.println(""Matrix After Modification :""); + printMatrix(mat); + } +}"," '''Python3 Code For A Boolean Matrix Question''' + +def modifyMatrix(mat) : + ''' variables to check if there are any 1 + in first row and column''' + + row_flag = False + col_flag = False + ''' updating the first row and col + if 1 is encountered''' + + for i in range(0, len(mat)) : + for j in range(0, len(mat)) : + if (i == 0 and mat[i][j] == 1) : + row_flag = True + if (j == 0 and mat[i][j] == 1) : + col_flag = True + if (mat[i][j] == 1) : + mat[0][j] = 1 + mat[i][0] = 1 + ''' Modify the input matrix mat[] using the + first row and first column of Matrix mat''' + + for i in range(1, len(mat)) : + for j in range(1, len(mat) + 1) : + if (mat[0][j] == 1 or mat[i][0] == 1) : + mat[i][j] = 1 + ''' modify first row if there was any 1''' + + if (row_flag == True) : + for i in range(0, len(mat)) : + mat[0][i] = 1 + ''' modify first col if there was any 1''' + + if (col_flag == True) : + for i in range(0, len(mat)) : + mat[i][0] = 1 + '''A utility function to print a 2D matrix''' + +def printMatrix(mat) : + for i in range(0, len(mat)) : + for j in range(0, len(mat) + 1) : + print( mat[i][j], end = """" ) + print() + '''Driver Code''' + +mat = [ [1, 0, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0] ] +print(""Input Matrix :"") +printMatrix(mat) +modifyMatrix(mat) +print(""Matrix After Modification :"") +printMatrix(mat)" +Find minimum number of coins that make a given value,"/*A Dynamic Programming based Java +program to find minimum of coins +to make a given change V*/ + +import java.io.*; +class GFG +{ +/* m is size of coins array + (number of different coins)*/ + + static int minCoins(int coins[], int m, int V) + { +/* table[i] will be storing + the minimum number of coins + required for i value. So + table[V] will have result*/ + + int table[] = new int[V + 1]; +/* Base case (If given value V is 0)*/ + + table[0] = 0; +/* Initialize all table values as Infinite*/ + + for (int i = 1; i <= V; i++) + table[i] = Integer.MAX_VALUE; +/* Compute minimum coins required for all + values from 1 to V*/ + + for (int i = 1; i <= V; i++) + { +/* Go through all coins smaller than i*/ + + for (int j = 0; j < m; j++) + if (coins[j] <= i) + { + int sub_res = table[i - coins[j]]; + if (sub_res != Integer.MAX_VALUE + && sub_res + 1 < table[i]) + table[i] = sub_res + 1; + } + } + if(table[V]==Integer.MAX_VALUE) + return -1; + return table[V]; + } +/* Driver program*/ + + public static void main (String[] args) + { + int coins[] = {9, 6, 5, 1}; + int m = coins.length; + int V = 11; + System.out.println ( ""Minimum coins required is "" + + minCoins(coins, m, V)); + } +}"," '''A Dynamic Programming based Python3 program to +find minimum of coins to make a given change V''' + +import sys + '''m is size of coins array (number of +different coins)''' + +def minCoins(coins, m, V): + ''' table[i] will be storing the minimum + number of coins required for i value. + So table[V] will have result''' + + table = [0 for i in range(V + 1)] + ''' Base case (If given value V is 0)''' + + table[0] = 0 + ''' Initialize all table values as Infinite''' + + for i in range(1, V + 1): + table[i] = sys.maxsize + ''' Compute minimum coins required + for all values from 1 to V''' + + for i in range(1, V + 1): + ''' Go through all coins smaller than i''' + + for j in range(m): + if (coins[j] <= i): + sub_res = table[i - coins[j]] + if (sub_res != sys.maxsize and + sub_res + 1 < table[i]): + table[i] = sub_res + 1 + if table[V] == sys.maxsize: + return -1 + return table[V] + '''Driver Code''' + +if __name__ == ""__main__"": + coins = [9, 6, 5, 1] + m = len(coins) + V = 11 + print(""Minimum coins required is "", + minCoins(coins, m, V))" +Sum of nodes at maximum depth of a Binary Tree,"/*Java code to find the sum of the nodes +which are present at the maximum depth.*/ + +class GFG +{ +static int sum = 0, max_level = Integer.MIN_VALUE; +static class Node +{ + int d; + Node l; + Node r; +}; +/*Function to return a new node*/ + +static Node createNode(int d) +{ + Node node; + node = new Node(); + node.d = d; + node.l = null; + node.r = null; + return node; +} +/*Function to find the sum of the node +which are present at the maximum depth. +While traversing the nodes compare the level +of the node with max_level +(Maximum level till the current node). +If the current level exceeds the maximum level, +update the max_level as current level. +If the max level and current level are same, +add the root data to current sum.*/ + +static void sumOfNodesAtMaxDepth(Node ro,int level) +{ + if(ro == null) + return; + if(level > max_level) + { + sum = ro . d; + max_level = level; + } + else if(level == max_level) + { + sum = sum + ro . d; + } + sumOfNodesAtMaxDepth(ro . l, level + 1); + sumOfNodesAtMaxDepth(ro . r, level + 1); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root; + root = createNode(1); + root.l = createNode(2); + root.r = createNode(3); + root.l.l = createNode(4); + root.l.r = createNode(5); + root.r.l = createNode(6); + root.r.r = createNode(7); + sumOfNodesAtMaxDepth(root, 0); + System.out.println(sum); +} +}"," '''Python3 code to find the sum of the nodes +which are present at the maximum depth.''' + +sum = [0] +max_level = [-(2**32)] + '''Binary tree node''' + +class createNode: + def __init__(self, data): + self.d = data + self.l = None + self.r = None + '''Function to find the sum of the node +which are present at the maximum depth. +While traversing the nodes compare the level +of the node with max_level +(Maximum level till the current node). +If the current level exceeds the maximum level, +update the max_level as current level. +If the max level and current level are same, +add the root data to current sum.''' + +def sumOfNodesAtMaxDepth(ro, level): + if(ro == None): + return + if(level > max_level[0]): + sum[0] = ro . d + max_level[0] = level + elif(level == max_level[0]): + sum[0] = sum[0] + ro . d + sumOfNodesAtMaxDepth(ro . l, level + 1) + sumOfNodesAtMaxDepth(ro . r, level + 1) + '''Driver Code''' + +root = createNode(1) +root.l = createNode(2) +root.r = createNode(3) +root.l.l = createNode(4) +root.l.r = createNode(5) +root.r.l = createNode(6) +root.r.r = createNode(7) +sumOfNodesAtMaxDepth(root, 0) +print(sum[0])" +Sink Odd nodes in Binary Tree,," '''Python3 program to sink odd nodes +to the bottom of binary tree +A binary tree node ''' + '''Helper function to allocates a new node ''' + +class newnode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Helper function to check +if node is leaf node ''' + +def isLeaf(root): + return (root.left == None and + root.right == None) + '''A recursive method to sink a tree with odd root +This method assumes that the subtrees are +already sinked. This method is similar to +Heapify of Heap-Sort ''' + +def sink(root): + ''' If None or is a leaf, do nothing ''' + + if (root == None or isLeaf(root)): + return + ''' if left subtree exists and + left child is even ''' + + if (root.left and not(root.left.data & 1)): + ''' swap root's data with left child + and fix left subtree ''' + + root.data, \ + root.left.data = root.left.data, \ + root.data + sink(root.left) + ''' if right subtree exists and + right child is even ''' + + elif(root.right and not(root.right.data & 1)): + ''' swap root's data with right child + and fix right subtree ''' + + root.data, \ + root.right.data = root.right.data, \ + root.data + sink(root.right) + '''Function to sink all odd nodes to +the bottom of binary tree. It does +a postorder traversal and calls sink() +if any odd node is found ''' + +def sinkOddNodes(root): + ''' If None or is a leaf, do nothing ''' + + if (root == None or isLeaf(root)): + return + ''' Process left and right subtrees + before this node ''' + + sinkOddNodes(root.left) + sinkOddNodes(root.right) + ''' If root is odd, sink it ''' + + if (root.data & 1): + sink(root) + '''Helper function to do Level Order Traversal +of Binary Tree level by level. This function +is used here only for showing modified tree. ''' + +def printLevelOrder(root): + q = [] + q.append(root) + ''' Do Level order traversal ''' + + while (len(q)): + nodeCount = len(q) + ''' Print one level at a time ''' + + while (nodeCount): + node = q[0] + print(node.data, end = "" "") + q.pop(0) + if (node.left != None): + q.append(node.left) + if (node.right != None): + q.append(node.right) + nodeCount -= 1 + ''' Line separator for levels ''' + + print() + '''Driver Code ''' + + ''' Constructed binary tree is + 1 + / \ + 5 8 + / \ / \ + 2 4 9 10 ''' + +root = newnode(1) +root.left = newnode(5) +root.right = newnode(8) +root.left.left = newnode(2) +root.left.right = newnode(4) +root.right.left = newnode(9) +root.right.right = newnode(10) +sinkOddNodes(root) +print(""Level order traversal of modified tree"") +printLevelOrder(root)" +Convert a given Binary Tree to Circular Doubly Linked List | Set 2,"/*Java program for conversion +of Binary Tree to CDLL*/ + +import java.util.*; +class GFG +{ + +/*A binary tree node has data, +and left and right pointers*/ + +static class Node +{ + int data; + Node left; + Node right; + + Node(int x) + { + data = x; + left = right = null; + } +}; + +/*Function to perform In-Order traversal of the +tree and store the nodes in a vector*/ + +static void inorder(Node root, Vector v) +{ + if (root == null) + return; + + /* first recur on left child */ + + inorder(root.left, v); + + /* append the data of node in vector */ + + v.add(root.data); + + /* now recur on right child */ + + inorder(root.right, v); +} + +/*Function to convert Binary Tree to Circular +Doubly Linked list using the vector which stores +In-Order traversal of the Binary Tree*/ + +static Node bTreeToCList(Node root) +{ +/* Base cases*/ + + if (root == null) + return null; + +/* Vector to be used for storing the nodes + of tree in In-order form*/ + + Vector v = new Vector<>(); + +/* Calling the In-Order traversal function*/ + + inorder(root, v); + +/* Create the head of the linked list pointing + to the root of the tree*/ + + Node head_ref = new Node(v.get(0)); + +/* Create a current pointer to be used in traversal*/ + + Node curr = head_ref; + +/* Traversing the nodes of the tree starting + from the second elements*/ + + for (int i = 1; i < v.size(); i++) + { + +/* Create a temporary pointer + pointing to current*/ + + Node temp = curr; + +/* Current's right points to the current + node in traversal*/ + + curr.right = new Node(v.get(i)); + +/* Current points to its right*/ + + curr = curr.right; + +/* Current's left points to temp*/ + + curr.left = temp; + } + +/* Current's right points to head of the list*/ + + curr.right = head_ref; + +/* Head's left points to current*/ + + head_ref.left = curr; + +/* Return head of the list*/ + + return head_ref; +} + +/*Display Circular Link List*/ + +static void displayCList(Node head) +{ + System.out.println(""Circular Doubly Linked List is :""); + + Node itr = head; + do + { + System.out.print(itr.data + "" ""); + itr = itr.right; + } while (head != itr); + + System.out.println(); +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root = new Node(10); + root.left = new Node(12); + root.right = new Node(15); + root.left.left = new Node(25); + root.left.right = new Node(30); + root.right.left = new Node(36); + + Node head = bTreeToCList(root); + displayCList(head); +} +} + + +"," '''Python program for conversion +of Binary Tree to CDLL''' + + + '''A binary tree node has data, +and left and right pointers''' + +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None + +v = [] + + '''Function to perform In-Order traversal of the +tree and store the nodes in a vector''' + +def inorder(root): + global v + + if (root == None): + return + + ''' first recur on left child''' + + inorder(root.left) + + ''' append the data of node in vector''' + + v.append(root.data) + + ''' now recur on right child''' + + inorder(root.right) + + '''Function to convert Binary Tree to Circular +Doubly Linked list using the vector which stores +In-Order traversal of the Binary Tree''' + +def bTreeToCList(root): + + global v + + ''' Base cases''' + + if (root == None): + return None + + ''' Vector to be used for storing the nodes + of tree in In-order form''' + + v = [] + + ''' Calling the In-Order traversal function''' + + inorder(root) + + ''' Create the head of the linked list pointing + to the root of the tree''' + + head_ref = Node(v[0]) + + ''' Create a current pointer to be used in traversal''' + + curr = head_ref + + i = 1 + + ''' Traversing the nodes of the tree starting + from the second elements''' + + while ( i < len(v)) : + + + ''' Create a temporary pointer + pointing to current''' + + temp = curr + + ''' Current's right points to the current + node in traversal''' + + curr.right = Node(v[i]) + + ''' Current points to its right''' + + curr = curr.right + + ''' Current's left points to temp''' + + curr.left = temp + i = i + 1 + + ''' Current's right points to head of the list''' + + curr.right = head_ref + + ''' Head's left points to current''' + + head_ref.left = curr + + ''' Return head of the list''' + + return head_ref + + '''Display Circular Link List''' + +def displayCList(head): + + print(""Circular Doubly Linked List is :"", end = """") + + itr = head + while(True): + print(itr.data, end = "" "") + itr = itr.right + if(head == itr): + break + + print() + + '''Driver Code''' + +root = Node(10) +root.left = Node(12) +root.right = Node(15) +root.left.left = Node(25) +root.left.right = Node(30) +root.right.left = Node(36) + +head = bTreeToCList(root) +displayCList(head) + + +" +Find maximum average subarray of k length,"/*Java program to find maximum average +subarray of given length.*/ + +import java .io.*; +class GFG { +/* Returns beginning index + of maximum average + subarray of length 'k'*/ + + static int findMaxAverage(int []arr, + int n, int k) + { +/* Check if 'k' is valid*/ + + if (k > n) + return -1; +/* Create and fill array + to store cumulative + sum. csum[i] stores + sum of arr[0] to arr[i]*/ + + int []csum = new int[n]; + csum[0] = arr[0]; + for (int i = 1; i < n; i++) + csum[i] = csum[i - 1] + arr[i]; +/* Initialize max_sm as + sum of first subarray*/ + + int max_sum = csum[k - 1], + max_end = k - 1; +/* Find sum of other + subarrays and update + max_sum if required.*/ + + for (int i = k; i < n; i++) + { + int curr_sum = csum[i] - + csum[i - k]; + if (curr_sum > max_sum) + { + max_sum = curr_sum; + max_end = i; + } + } +/* Return starting index*/ + + return max_end - k + 1; + } +/* Driver Code*/ + + static public void main (String[] args) + { + int []arr = {1, 12, -5, -6, 50, 3}; + int k = 4; + int n = arr.length; + System.out.println(""The maximum "" + + ""average subarray of length "" + + k + "" begins at index "" + + findMaxAverage(arr, n, k)); + } +}"," '''Python program to find maximum average subarray +of given length.''' + + '''Returns beginning index of maximum average +subarray of length k''' +def findMaxAverage(arr, n, k): ''' Check if 'k' is valid''' + + if k > n: + return -1 + ''' Create and fill array to store cumulative + sum. csum[i] stores sum of arr[0] to arr[i]''' + + csum = [0]*n + csum[0] = arr[0] + for i in range(1, n): + csum[i] = csum[i-1] + arr[i]; + ''' Initialize max_sm as sum of first subarray''' + + max_sum = csum[k-1] + max_end = k-1 + ''' Find sum of other subarrays and update + max_sum if required.''' + + for i in range(k, n): + curr_sum = csum[i] - csum[i-k] + if curr_sum > max_sum: + max_sum = curr_sum + max_end = i + ''' Return starting index''' + + return max_end - k + 1 + '''Driver program''' + +arr = [1, 12, -5, -6, 50, 3] +k = 4 +n = len(arr) +print(""The maximum average subarray of length"",k, +""begins at index"",findMaxAverage(arr, n, k))" +Maximum Consecutive Increasing Path Length in Binary Tree,"/*Java Program to find Maximum Consecutive +Path Length in a Binary Tree */ + +import java.util.*; +class GfG { +/*To represent a node of a Binary Tree */ + +static class Node +{ + Node left, right; + int val; +} +/*Create a new Node and return its address */ + +static Node newNode(int val) +{ + Node temp = new Node(); + temp.val = val; + temp.left = null; + temp.right = null; + return temp; +} +/*Returns the maximum consecutive Path Length */ + +static int maxPathLenUtil(Node root, int prev_val, int prev_len) +{ + if (root == null) + return prev_len; +/* Get the value of Current Node + The value of the current node will be + prev Node for its left and right children */ + + int cur_val = root.val; +/* If current node has to be a part of the + consecutive path then it should be 1 greater + than the value of the previous node */ + + if (cur_val == prev_val+1) + { +/* a) Find the length of the Left Path + b) Find the length of the Right Path + Return the maximum of Left path and Right path */ + + return Math.max(maxPathLenUtil(root.left, cur_val, prev_len+1), + maxPathLenUtil(root.right, cur_val, prev_len+1)); + } +/* Find length of the maximum path under subtree rooted with this + node (The path may or may not include this node) */ + + int newPathLen = Math.max(maxPathLenUtil(root.left, cur_val, 1), + maxPathLenUtil(root.right, cur_val, 1)); +/* Take the maximum previous path and path under subtree rooted + with this node. */ + + return Math.max(prev_len, newPathLen); +} +/*A wrapper over maxPathLenUtil(). */ + +static int maxConsecutivePathLength(Node root) +{ +/* Return 0 if root is NULL */ + + if (root == null) + return 0; +/* Else compute Maximum Consecutive Increasing Path + Length using maxPathLenUtil. */ + + return maxPathLenUtil(root, root.val-1, 0); +} +/*Driver program to test above function */ + +public static void main(String[] args) +{ + Node root = newNode(10); + root.left = newNode(11); + root.right = newNode(9); + root.left.left = newNode(13); + root.left.right = newNode(12); + root.right.left = newNode(13); + root.right.right = newNode(8); + System.out.println(""Maximum Consecutive Increasing Path Length is ""+maxConsecutivePathLength(root)); +} +}"," '''Python program to find Maximum consecutive +path length in binary tree''' + + '''A binary tree node''' + +class Node: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + '''Returns the maximum consecutive path length''' + +def maxPathLenUtil(root, prev_val, prev_len): + if root is None: + return prev_len + ''' Get the vlue of current node + The value of the current node will be + prev node for its left and right children''' + + curr_val = root.val + ''' If current node has to be a part of the + consecutive path then it should be 1 greater + thn the value of the previous node''' + + if curr_val == prev_val +1 : + ''' a) Find the length of the left path + b) Find the length of the right path + Return the maximum of left path and right path''' + + return max(maxPathLenUtil(root.left, curr_val, prev_len+1), + maxPathLenUtil(root.right, curr_val, prev_len+1)) + ''' Find the length of the maximum path under subtree + rooted with this node''' + + newPathLen = max(maxPathLenUtil(root.left, curr_val, 1), + maxPathLenUtil(root.right, curr_val, 1)) + ''' Take the maximum previous path and path under subtree + rooted with this node''' + + return max(prev_len , newPathLen) + '''A Wrapper over maxPathLenUtil()''' + +def maxConsecutivePathLength(root): + ''' Return 0 if root is None''' + + if root is None: + return 0 + ''' Else compute maximum consecutive increasing path + length using maxPathLenUtil''' + + return maxPathLenUtil(root, root.val -1 , 0) + '''Driver program to test above function''' + +root = Node(10) +root.left = Node(11) +root.right = Node(9) +root.left.left = Node(13) +root.left.right = Node(12) +root.right.left = Node(13) +root.right.right = Node(8) +print ""Maximum Consecutive Increasing Path Length is"", +print maxConsecutivePathLength(root)" +Print n x n spiral matrix using O(1) extra space,"/*Java program to print a n x n spiral matrix +in clockwise direction using O(1) space*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Prints spiral matrix of size n x n + containing numbers from 1 to n x n*/ + + static void printSpiral(int n) + { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { +/* x stores the layer in which (i, j)th + element lies*/ + + int x; +/* Finds minimum of four inputs*/ + + x = Math.min(Math.min(i, j), + Math.min(n - 1 - i, n - 1 - j)); +/* For upper right half*/ + + if (i <= j) + System.out.print((n - 2 * x) * (n - 2 * x) - + (i - x) - (j - x) + ""\t""); +/* for lower left half*/ + + else + System.out.print((n - 2 * x - 2) * (n - 2 * x - 2) + + (i - x) + (j - x) + ""\t""); + } + System.out.println(); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 5; +/* print a n x n spiral matrix in O(1) space*/ + + printSpiral(n); + } +}"," '''Python3 program to print a n x n spiral matrix +in clockwise direction using O(1) space''' + + '''Prints spiral matrix of size n x n +containing numbers from 1 to n x n''' + +def printSpiral(n) : + for i in range(0, n) : + for j in range(0, n) : ''' Finds minimum of four inputs''' + + x = min(min(i, j), min(n - 1 - i, n - 1 - j)) + ''' For upper right half''' + + if (i <= j) : + print((n - 2 * x) * (n - 2 * x) - + (i - x)- (j - x), end = ""\t"") + ''' For lower left half''' + + else : + print(((n - 2 * x - 2) * + (n - 2 * x - 2) + + (i - x) + (j - x)), end = ""\t"") + print() + '''Driver code''' + +n = 5 + '''print a n x n spiral matrix +in O(1) space''' + +printSpiral(n)" +Positive elements at even and negative at odd positions (Relative order not maintained),"/*Java program to rearrange positive +and negative numbers*/ + +import java.io.*; +class GFG { +static void rearrange(int a[], int size) +{ + int positive = 0, negative = 1, temp; + while (true) { + /* Move forward the positive pointer till + negative number number not encountered */ + + while (positive < size && a[positive] >= 0) + positive += 2; + /* Move forward the negative pointer till + positive number number not encountered */ + + while (negative < size && a[negative] <= 0) + negative += 2; +/* Swap array elements to fix their position.*/ + + if (positive < size && negative < size) { + temp = a[positive]; + a[positive] = a[negative]; + a[negative] = temp; + } + /* Break from the while loop when any index + exceeds the size of the array */ + + else + break; + } +} +/*Driver code*/ + +public static void main(String args[]) { + int arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}; + int n = arr.length; + rearrange(arr, n); + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); +} +}"," '''Python 3 program to rearrange +positive and negative numbers''' + +def rearrange(a, size) : + positive = 0 + negative = 1 + while (True) : + ''' Move forward the positive + pointer till negative number + number not encountered''' + + while (positive < size and a[positive] >= 0) : + positive = positive + 2 + ''' Move forward the negative + pointer till positive number + number not encountered''' + + while (negative < size and a[negative] <= 0) : + negative = negative + 2 + ''' Swap array elements to fix + their position.''' + + if (positive < size and negative < size) : + temp = a[positive] + a[positive] = a[negative] + a[negative] = temp + ''' Break from the while loop when + any index exceeds the size of + the array''' + + else : + break + '''Driver code''' + +arr =[ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ] +n = len(arr) +rearrange(arr, n) +for i in range(0, n) : + print(arr[i], end = "" "")" +Turn off the rightmost set bit,"/*Java program to unset the +rightmost set bit of an integer.*/ + +class GFG { + /* unsets the rightmost set bit + of n and returns the result */ + + static int fun(int n) + { + return n & (n - 1); + } +/* Driver code*/ + + public static void main(String arg[]) + { + int n = 7; + System.out.print(""The number after unsetting "" + + ""the rightmost set bit "" + fun(n)); + } +}"," '''unsets the rightmost set bit +of n and returns the result''' + +def fun(n): + return n & (n-1) + '''Driver code''' + +n = 7 +print(""The number after unsetting the rightmost set bit"", fun(n))" +Merge two sorted arrays with O(1) extra space,"/*Java program for the above approach*/ + +import java.util.Arrays; +import java.util.Collections; +class GFG { + +/* Function to merge two arrays*/ + + static void merge(int m, int n) + { + int i = 0, j = 0, k = n - 1; + +/* Untill i less than equal to k + or j is less tha m*/ + + while (i <= k and j < m) { + if (arr1[i] < arr2[j]) + i++; + else { + int temp = arr2[j]; + arr2[j] = arr1[k]; + arr1[k] = temp; + j++; + k--; + } + } +/* Sort first array*/ + + Arrays.sort(arr1); +/* Sort second array*/ + + Arrays.sort(arr2); + }/*Driver Code*/ + + public static void main(String[] args) + { + int arr1[] = new int[] { 1, 5, 9, 10, 15, 20 }; + int arr2[] = new int[] { 2, 3, 8, 13 }; + merge(arr1.length, arr2.length); + System.out.print(""After Merging \nFirst Array: ""); + System.out.println(Arrays.toString(arr1)); + System.out.print(""Second Array: ""); + System.out.println(Arrays.toString(arr2)); + } +}", +FIFO (First-In-First-Out) approach in Programming,"/*Java program to demonstrate +working of FIFO +using Queue interface in Java*/ + +import java.util.LinkedList; +import java.util.Queue; +public class QueueExample { + +/*Driver code*/ + + public static void main(String[] args) + { + Queue q = new LinkedList<>();/* Adds elements {0, 1, 2, 3, 4} to queue*/ + + for (int i = 0; i < 5; i++) + q.add(i); +/* Display contents of the queue.*/ + + System.out.println(""Elements of queue-"" + q); +/* To remove the head of queue. + In this the oldest element '0' will be removed*/ + + int removedele = q.remove(); + System.out.println(""removed element-"" + removedele); + System.out.println(q); +/* To view the head of queue*/ + + int head = q.peek(); + System.out.println(""head of queue-"" + head); +/* Rest all methods of collection interface, + Like size and contains can be used with this + implementation.*/ + + int size = q.size(); + System.out.println(""Size of queue-"" + size); + } +}", +Find the maximum element in an array which is first increasing and then decreasing,"/*java program to find maximum +element*/ + + +class Main +{ +/* function to find the + maximum element*/ + + static int findMaximum(int arr[], int low, int high) + { + int max = arr[low]; + int i; + for (i = low; i <= high; i++) + { + if (arr[i] > max) + max = arr[i]; + } + return max; + } + +/* main function*/ + + public static void main (String[] args) + { + int arr[] = {1, 30, 40, 50, 60, 70, 23, 20}; + int n = arr.length; + System.out.println(""The maximum element is ""+ + findMaximum(arr, 0, n-1)); + } +} +"," '''Python3 program to find +maximum element''' + + +def findMaximum(arr, low, high): + max = arr[low] + i = low + for i in range(high+1): + if arr[i] > max: + max = arr[i] + return max + + '''Driver program to check above functions */''' + +arr = [1, 30, 40, 50, 60, 70, 23, 20] +n = len(arr) +print (""The maximum element is %d""% + findMaximum(arr, 0, n-1)) + + +" +Coin Change | DP-7,"/*Dynamic Programming Java implementation +of Coin Change problem*/ + +public static int count( int S[], int m, int n ) +{ +/* table[i] will be storing the number of solutions for + value i. We need n+1 rows as the table is constructed + in bottom up manner using the base case (n = 0)*/ + + int table[]=new int[n+1]; +/* Base case (If given value is 0)*/ + + table[0] = 1; +/* Pick all coins one by one and update the table[] values + after the index greater than or equal to the value of the + picked coin*/ + + for(int i=0; i max) + { + max = arr[i]; + result = i; + } + } + + /* Return index of the maximum element*/ + + return result; + } + + /*Driver function to check for above function*/ + + public static void main (String[] args) + { + + int arr[] = {2, 3, 3, 5, 3, 4, 1, 7}; + int n = arr.length; + int k=8; + System.out.println(""Maximum repeating element is: "" + + maxRepeating(arr,n,k)); + } +} + +"," '''Python program to find the maximum repeating number''' + + + '''Returns maximum repeating element in arr[0..n-1]. +The array elements are in range from 0 to k-1''' + +def maxRepeating(arr, n, k): + + ''' Iterate though input array, for every element + arr[i], increment arr[arr[i]%k] by k''' + + for i in range(0, n): + arr[arr[i]%k] += k + + ''' Find index of the maximum repeating element''' + + max = arr[0] + result = 0 + for i in range(1, n): + + if arr[i] > max: + max = arr[i] + result = i + + ''' Return index of the maximum element''' + + return result + + + '''Driver program to test above function''' + +arr = [2, 3, 3, 5, 3, 4, 1, 7] +n = len(arr) +k = 8 +print(""The maximum repeating number is"",maxRepeating(arr, n, k)) + + +" +Print all possible rotations of a given Array,"/*Java program to print +all possible rotations +of the given array*/ + +class GFG{ + +/*Global declaration of array*/ + +static int arr[] = new int[10000]; + +/*Function to reverse array +between indices s and e*/ + +public static void reverse(int arr[], + int s, int e) +{ + while(s < e) + { + int tem = arr[s]; + arr[s] = arr[e]; + arr[e] = tem; + s = s + 1; + e = e - 1; + } +} + +/*Function to generate all +possible rotations of array*/ + +public static void fun(int arr[], int k) +{ + int n = 4 - 1; + int v = n - k; + + if (v >= 0) + { + reverse(arr, 0, v); + reverse(arr, v + 1, n); + reverse(arr, 0, n); + } +} + +/*Driver code*/ + +public static void main(String args[]) +{ + arr[0] = 1; + arr[1] = 2; + arr[2] = 3; + arr[3] = 4; + + for(int i = 0; i < 4; i++) + { + fun(arr, i); + + System.out.print(""[""); + for(int j = 0; j < 4; j++) + { + System.out.print(arr[j] + "", ""); + } + System.out.print(""]""); + } +} +} + + +"," '''Python program to print +all possible rotations +of the given array''' + + + '''Function to reverse array +between indices s and e''' + +def reverse(arr, s, e): + while s < e: + tem = arr[s] + arr[s] = arr[e] + arr[e] = tem + s = s + 1 + e = e - 1 + '''Function to generate all +possible rotations of array''' + +def fun(arr, k): + n = len(arr)-1 + v = n - k + if v>= 0: + reverse(arr, 0, v) + reverse(arr, v + 1, n) + reverse(arr, 0, n) + return arr + '''Driver Code''' + +arr = [1, 2, 3, 4] +for i in range(0, len(arr)): + count = 0 + p = fun(arr, i) + print(p, end ="" "") +" +Last seen array element (last appearance is earliest),"/*Java program to find last seen element in +an array.*/ + +import java.util.*; +class GFG +{ +/*Returns last seen element in arr[]*/ + +static int lastSeenElement(int a[], int n) +{ +/* Store last occurrence index of + every element*/ + + HashMap hash = new HashMap(); + for (int i = 0; i < n; i++) + { + hash.put(a[i], i); + } +/* Find an element in hash with minimum + index value*/ + + int res_ind = Integer.MAX_VALUE, res = 0; + for (Map.Entry x : hash.entrySet()) + { + if (x.getValue() < res_ind) + { + res_ind = x.getValue(); + res = x.getKey(); + } + } + return res; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = { 2, 1, 2, 2, 4, 1 }; + int n = a.length; + System.out.println(lastSeenElement(a, n)); +} +}"," '''Python3 program to find last seen +element in an array.''' + +import sys; + '''Returns last seen element in arr[]''' + +def lastSeenElement(a, n): + ''' Store last occurrence index of + every element''' + + hash = {} + for i in range(n): + hash[a[i]] = i + ''' Find an element in hash with minimum + index value''' + + res_ind = sys.maxsize + res = 0 + for x, y in hash.items(): + if y < res_ind: + res_ind = y + res = x + return res + '''Driver code ''' + +if __name__==""__main__"": + a = [ 2, 1, 2, 2, 4, 1 ] + n = len(a) + print(lastSeenElement(a,n))" +Check if a linked list is Circular Linked List,"/*Java program to check if +linked list is circular*/ + +import java.util.*; +class GFG +{ +/* Link list Node */ + +static class Node +{ + int data; + Node next; +} +/*This function returns true if given linked +list is circular, else false. */ + +static boolean isCircular( Node head) +{ +/* An empty linked list is circular*/ + + if (head == null) + return true; +/* Next of head*/ + + Node node = head.next; +/* This loop would stop in both cases (1) If + Circular (2) Not circular*/ + + while (node != null && node != head) + node = node.next; +/* If loop stopped because of circular + condition*/ + + return (node == head); +} +/*Utility function to create a new node.*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.next = null; + return temp; +} +/* Driver code*/ + +public static void main(String args[]) +{ + /* Start with the empty list */ + + Node head = newNode(1); + head.next = newNode(2); + head.next.next = newNode(3); + head.next.next.next = newNode(4); + System.out.print(isCircular(head)? ""Yes\n"" : + ""No\n"" ); +/* Making linked list circular*/ + + head.next.next.next.next = head; + System.out.print(isCircular(head)? ""Yes\n"" : + ""No\n"" ); +} +}", +Maximum value possible by rotating digits of a given number,"/*Java program for the above approach*/ + +import java.util.*; +class GFG +{ + +/*Function to find the maximum value +possible by rotations of digits of N*/ + +static void findLargestRotation(int num) +{ + +/* Store the required result*/ + + int ans = num; + +/* Store the number of digits*/ + + int len = (int)Math.floor(((int)Math.log10(num)) + 1); + int x = (int)Math.pow(10, len - 1); + +/* Iterate over the range[1, len-1]*/ + + for (int i = 1; i < len; i++) { + +/* Store the unit's digit*/ + + int lastDigit = num % 10; + +/* Store the remaining number*/ + + num = num / 10; + +/* Find the next rotation*/ + + num += (lastDigit * x); + +/* If the current rotation is + greater than the overall + answer, then update answer*/ + + if (num > ans) { + ans = num; + } + } + +/* Print the result*/ + + System.out.print(ans); +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int N = 657; + findLargestRotation(N); +} +} + + +"," '''Python program for the above approach''' + + + '''Function to find the maximum value +possible by rotations of digits of N''' + +def findLargestRotation(num): + + ''' Store the required result''' + + ans = num + + ''' Store the number of digits''' + + length = len(str(num)) + x = 10**(length - 1) + + ''' Iterate over the range[1, len-1]''' + + for i in range(1, length): + + ''' Store the unit's digit''' + + lastDigit = num % 10 + + ''' Store the remaining number''' + + num = num // 10 + + ''' Find the next rotation''' + + num += (lastDigit * x) + + ''' If the current rotation is + greater than the overall + answer, then update answer''' + + if (num > ans): + ans = num + + ''' Print the result''' + + print(ans) + + '''Driver Code''' + +N = 657 +findLargestRotation(N) + + +" +Next Greater Element,"/*Simple Java program to print next +greater elements in a given array*/ + +class Main +{ + /* prints element and NGE pair for + all elements of arr[] of size n */ + + static void printNGE(int arr[], int n) + { + int next, i, j; + for (i=0; i sq) + { + selected_block = i; + break; + } + } +/* after finding block with size > sq + method of hashing is used to find + the element repeating in this block */ + + HashMap m = new HashMap<>(); + for (int i = 0; i <= n; i++) + { +/* checks if the element belongs to the + selected_block */ + + if ( ((selected_block * sq) < arr[i]) && + (arr[i] <= ((selected_block + 1) * sq))) + { + m.put(arr[i], 1); +/* repeating element found*/ + + if (m.get(arr[i]) == 1) + return arr[i]; + } + } +/* return -1 if no repeating element exists */ + + return -1; +} +/*Driver code*/ + +public static void main(String args[]) +{ +/* read only array, not to be modified */ + + int[] arr = { 1, 1, 2, 3, 5, 4 }; +/* array of size 6(n + 1) having + elements between 1 and 5 */ + + int n = 5; + System.out.println(""One of the numbers repeated in the array is: "" + + findRepeatingNumber(arr, n)); +} +}"," '''Python 3program to find one of the repeating +elements in a read only array''' + +from math import sqrt + '''Function to find one of the repeating +elements''' + +def findRepeatingNumber(arr, n): + ''' Size of blocks except the + last block is sq''' + + sq = sqrt(n) + ''' Number of blocks to incorporate 1 to + n values blocks are numbered from 0 + to range-1 (both included)''' + + range__= int((n / sq) + 1) + ''' Count array maintains the count for + all blocks''' + + count = [0 for i in range(range__)] + ''' Traversing the read only array and + updating count''' + + for i in range(0, n + 1, 1): + ''' arr[i] belongs to block number + (arr[i]-1)/sq i is considered + to start from 0''' + + count[int((arr[i] - 1) / sq)] += 1 + ''' The selected_block is set to last + block by default. Rest of the blocks + are checked''' + + selected_block = range__ - 1 + for i in range(0, range__ - 1, 1): + if (count[i] > sq): + selected_block = i + break + ''' after finding block with size > sq + method of hashing is used to find + the element repeating in this block''' + + m = {i:0 for i in range(n)} + for i in range(0, n + 1, 1): + ''' checks if the element belongs + to the selected_block''' + + if (((selected_block * sq) < arr[i]) and + (arr[i] <= ((selected_block + 1) * sq))): + m[arr[i]] += 1 + ''' repeating element found''' + + if (m[arr[i]] > 1): + return arr[i] + ''' return -1 if no repeating element exists''' + + return -1 + '''Driver Code''' + +if __name__ == '__main__': + ''' read only array, not to be modified''' + + arr = [1, 1, 2, 3, 5, 4] + ''' array of size 6(n + 1) having + elements between 1 and 5''' + + n = 5 + print(""One of the numbers repeated in the array is:"", + findRepeatingNumber(arr, n))" +Count total set bits in all numbers from 1 to n,"/*Java A O(Logn) complexity program to count +set bits in all numbers from 1 to n*/ + +import java.io.*; +class GFG +{ +/* Returns position of leftmost set bit. +The rightmost position is considered +as 0 */ + +static int getLeftmostBit(int n) +{ + int m = 0; + while (n > 1) + { + n = n >> 1; + m++; + } + return m; +} +/* Given the position of previous leftmost +set bit in n (or an upper bound on +leftmost position) returns the new +position of leftmost set bit in n */ + +static int getNextLeftmostBit(int n, int m) +{ + int temp = 1 << m; + while (n < temp) + { + temp = temp >> 1; + m--; + } + return m; +} +/*The main recursive function used by countSetBits() +Returns count of set bits present in +all numbers from 1 to n*/ + +static int countSetBits(int n) +{ +/* Get the position of leftmost set + bit in n. This will be used as an + upper bound for next set bit function*/ + + int m = getLeftmostBit(n); +/* Use the position*/ + + return countSetBits(n, m); +} +static int countSetBits( int n, int m) +{ +/* Base Case: if n is 0, then set bit + count is 0*/ + + if (n == 0) + return 0; + /* get position of next leftmost set bit */ + + m = getNextLeftmostBit(n, m); +/* If n is of the form 2^x-1, i.e., if n + is like 1, 3, 7, 15, 31, .. etc, + then we are done. + Since positions are considered starting + from 0, 1 is added to m*/ + + if (n == ((int)1 << (m + 1)) - 1) + return (int)(m + 1) * (1 << m); +/* update n for next recursive call*/ + + n = n - (1 << m); + return (n + 1) + countSetBits(n) + m * (1 << (m - 1)); +} +/*Driver code*/ + +public static void main (String[] args) +{ + int n = 17; + System.out.println (""Total set bit count is "" + countSetBits(n)); +} +}"," '''A O(Logn) complexity program to count +set bits in all numbers from 1 to n''' + + ''' +/* Returns position of leftmost set bit. +The rightmost position is considered +as 0 */ + ''' + +def getLeftmostBit(n): + m = 0 + while (n > 1) : + n = n >> 1 + m += 1 + return m + ''' +/* Given the position of previous leftmost +set bit in n (or an upper bound on +leftmost position) returns the new +position of leftmost set bit in n */ + ''' + +def getNextLeftmostBit(n, m) : + temp = 1 << m + while (n < temp) : + temp = temp >> 1 + m -= 1 + return m + '''The main recursive function used by countSetBits() +def _countSetBits(n, m) +Returns count of set bits present in +all numbers from 1 to n''' + +def countSetBits(n) : + ''' Get the position of leftmost set + bit in n. This will be used as an + upper bound for next set bit function''' + + m = getLeftmostBit(n) + ''' Use the position''' + + return _countSetBits(n, m) +def _countSetBits(n, m) : + ''' Base Case: if n is 0, then set bit + count is 0''' + + if (n == 0) : + return 0 + ''' /* get position of next leftmost set bit */''' + + m = getNextLeftmostBit(n, m) + ''' If n is of the form 2^x-1, i.e., if n + is like 1, 3, 7, 15, 31, .. etc, + then we are done. + Since positions are considered starting + from 0, 1 is added to m''' + + if (n == (1 << (m + 1)) - 1) : + return ((m + 1) * (1 << m)) + ''' update n for next recursive call''' + + n = n - (1 << m) + return (n + 1) + countSetBits(n) + m * (1 << (m - 1)) + '''Driver code''' + +n = 17 +print(""Total set bit count is"", countSetBits(n))" +Binomial Coefficient | DP-9,"import java.util.*; +class GFG { +/* pow(base,exp,mod) is used to find + (base^exp)%mod fast -> O(log(exp))*/ + + static long pow(long b, long exp, long mod) + { + long ret = 1; + while (exp > 0) { + if ((exp & 1) > 0) + ret = (ret * b) % mod; + b = (b * b) % mod; + exp >>= 1; + } + return ret; + } + +/*base case*/ + static int nCr(int n, int r) + { +if (r > n) + return 0; +/* C(n,r) = C(n,n-r) Complexity for + this code is lesser for lower n-r*/ + + if (n - r > r) + r = n - r; +/* list to smallest prime factor + of each number from 1 to n*/ + + int[] SPF = new int[n + 1]; +/* set smallest prime factor of each + number as itself*/ + + for (int i = 1; i <= n; i++) + SPF[i] = i; +/* set smallest prime factor of all + even numbers as 2*/ + + for (int i = 4; i <= n; i += 2) + SPF[i] = 2; + for (int i = 3; i * i < n + 1; i += 2) + { +/* Check if i is prime*/ + + if (SPF[i] == i) + { +/* All multiples of i are + composite (and divisible by + i) so add i to their prime + factorization getpow(j,i) + times*/ + + for (int j = i * i; j < n + 1; j += i) + if (SPF[j] == j) { + SPF[j] = i; + } + } + } +/* Hash Map to store power of + each prime in C(n,r)*/ + + Map prime_pow + = new HashMap<>(); +/* For numerator count frequency of each prime factor*/ + + for (int i = r + 1; i < n + 1; i++) + { + int t = i; +/* Recursive division to find + prime factorization of i*/ + + while (t > 1) + { + prime_pow.put(SPF[t], + prime_pow.getOrDefault(SPF[t], 0) + 1); + t /= SPF[t]; + } + } +/* For denominator subtract the power of + each prime factor*/ + + for (int i = 1; i < n - r + 1; i++) + { + int t = i; +/* Recursive division to find + prime factorization of i*/ + + while (t > 1) + { + prime_pow.put(SPF[t], + prime_pow.get(SPF[t]) - 1); + t /= SPF[t]; + } + } +/* long because mod is large and a%mod + * b%mod can overflow int*/ + + long ans = 1, mod = 1000000007; +/* use (a*b)%mod = (a%mod * b%mod)%mod*/ + + for (int i : prime_pow.keySet()) +/* pow(base,exp,mod) is used to + find (base^exp)%mod fast*/ + + ans = (ans * pow(i, prime_pow.get(i), mod)) + % mod; + return (int)ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + int n = 5, r = 2; + System.out.print(""Value of C("" + n + "", "" + r + + "") is "" + nCr(n, r) + ""\n""); + } +}"," '''Python code for the above approach''' + +import math +class GFG: + + ''' Base case''' + def nCr(self, n, r): + if r > n: + return 0 + ''' C(n,r) = C(n,n-r) Complexity for this + code is lesser for lower n-r''' + + if n - r > r: + r = n - r + ''' set smallest prime factor of each + number as itself''' + + SPF = [i for i in range(n+1)] + + ''' set smallest prime factor of + all even numbers as 2''' + for i in range(4, n+1, 2): + SPF[i] = 2 + for i in range(3, n+1, 2): + if i*i > n: + break + ''' Check if i is prime''' + + if SPF[i] == i: + ''' All multiples of i are composite + (and divisible by i) so add i to + their prime factorization getpow(j,i) times''' + + for j in range(i*i, n+1, i): + if SPF[j] == j: + SPF[j] = i ''' dictionary to store power of each prime in C(n,r)''' + + prime_pow = {} + ''' For numerator count frequency + of each prime factor''' + + for i in range(r+1, n+1): + t = i + ''' Recursive division to + find prime factorization of i''' + + while t > 1: + if not SPF[t] in prime_pow: + prime_pow[SPF[t]] = 1 + else: + prime_pow[SPF[t]] += 1 + t //= SPF[t] + ''' For denominator subtract the + power of each prime factor''' + + for i in range(1, n-r+1): + t = i + ''' Recursive division to + find prime factorization of i''' + + while t > 1: + prime_pow[SPF[t]] -= 1 + t //= SPF[t] + + ans = 1 + mod = 10**9 + 7 ''' Use (a*b)%mod = (a%mod * b%mod)%mod''' + + for i in prime_pow: + ''' pow(base,exp,mod) is used to + find (base^exp)%mod fast''' + + ans = (ans*pow(i, prime_pow[i], mod)) % mod + return ans + '''Driver code''' + +n = 5 +k = 2 +ob = GFG() +print(""Value of C("" + str(n) + + "", "" + str(k) + "") is"", + ob.nCr(n, k))" +Return maximum occurring character in an input string,"/*Java program to output the maximum occurring character +in a string*/ + +public class GFG +{ + static final int ASCII_SIZE = 256; + static char getMaxOccuringChar(String str) + { +/* Create array to keep the count of individual + characters and initialize the array as 0*/ + + int count[] = new int[ASCII_SIZE]; +/* Construct character count array from the input + string.*/ + + int len = str.length(); + for (int i=0; i q = new LinkedList<>(); + q.add(s); + visited[s] = true; + parent[s] = -1; +/* Standard BFS Loop*/ + + while (!q.isEmpty()) + { + int u = q.peek(); + q.remove(); + for (int v = 0; v < V; v++) + { + if (visited[v] == false && + rGraph[u][v] > 0) + { + q.add(v); + parent[v] = u; + visited[v] = true; + } + } + } +/* If we reached sink in BFS + starting from source, then + return true, else false*/ + + return (visited[t] == true); +} +/*Returns tne maximum number of edge-disjoint +paths from s to t. This function is copy of +goo.gl/wtQ4Ks +forFulkerson() discussed at http:*/ + +static int findDisjointPaths(int graph[][], int s, int t) +{ + int u, v; +/* Create a residual graph and fill the + residual graph with given capacities + in the original graph as residual capacities + in residual graph + Residual graph where rGraph[i][j] indicates + residual capacity of edge from i to j (if there + is an edge. If rGraph[i][j] is 0, then there is not)*/ + + int [][]rGraph = new int[V][V]; + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; +/* This array is filled by BFS and to store path*/ + + int []parent = new int[V]; +/*There is no flow initially*/ + +int max_flow = 0; +/* Augment the flow while there is path + from source to sink*/ + + while (bfs(rGraph, s, t, parent)) + { +/* Find minimum residual capacity of the edges + along the path filled by BFS. Or we can say + find the maximum flow through the path found.*/ + + int path_flow = Integer.MAX_VALUE; + for (v = t; v != s; v = parent[v]) + { + u = parent[v]; + path_flow = Math.min(path_flow, rGraph[u][v]); + } +/* update residual capacities of the edges and + reverse edges along the path*/ + + for (v = t; v != s; v = parent[v]) + { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } +/* Add path flow to overall flow*/ + + max_flow += path_flow; + } +/* Return the overall flow (max_flow is equal to + maximum number of edge-disjoint paths)*/ + + return max_flow; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Let us create a graph shown in the above example*/ + + int graph[][] = {{0, 1, 1, 1, 0, 0, 0, 0}, + {0, 0, 1, 0, 0, 0, 0, 0}, + {0, 0, 0, 1, 0, 0, 1, 0}, + {0, 0, 0, 0, 0, 0, 1, 0}, + {0, 0, 1, 0, 0, 0, 0, 1}, + {0, 1, 0, 0, 0, 0, 0, 1}, + {0, 0, 0, 0, 0, 1, 0, 1}, + {0, 0, 0, 0, 0, 0, 0, 0}}; + int s = 0; + int t = 7; + System.out.println(""There can be maximum "" + + findDisjointPaths(graph, s, t) + + "" edge-disjoint paths from "" + + s + "" to ""+ t); +} +}", +Ugly Numbers,"/*Java program to find nth ugly number*/ + +class GFG { + /*This function divides a by greatest + divisible power of b*/ + + static int maxDivide(int a, int b) + { + while (a % b == 0) + a = a / b; + return a; + } + /* Function to check if a number + is ugly or not */ + + static int isUgly(int no) + { + no = maxDivide(no, 2); + no = maxDivide(no, 3); + no = maxDivide(no, 5); + return (no == 1) ? 1 : 0; + } + /* Function to get the nth ugly + number*/ + + static int getNthUglyNo(int n) + { + int i = 1; +/* ugly number count*/ + + int count = 1; +/* check for all integers + until count becomes n*/ + + while (n > count) { + i++; + if (isUgly(i) == 1) + count++; + } + return i; + } + /* Driver Code*/ + + public static void main(String args[]) + { + int no = getNthUglyNo(150); + System.out.println(""150th ugly "" + + ""no. is "" + no); + } +}"," '''Python3 code to find nth ugly number''' + + '''This function divides a by greatest +divisible power of b''' + +def maxDivide(a, b): + while a % b == 0: + a = a / b + return a '''Function to check if a number +is ugly or not''' + +def isUgly(no): + no = maxDivide(no, 2) + no = maxDivide(no, 3) + no = maxDivide(no, 5) + return 1 if no == 1 else 0 + '''Function to get the nth ugly number''' + +def getNthUglyNo(n): + i = 1 + ''' ugly number count''' + + count = 1 + ''' Check for all integers untill + ugly count becomes n''' + + while n > count: + i += 1 + if isUgly(i): + count += 1 + return i + '''Driver code''' + +no = getNthUglyNo(150) +print(""150th ugly no. is "", no)" +Pair with given sum and maximum shortest distance from end,"/*Java code to find maximum shortest distance +from endpoints*/ + +import java.util.*; +class GFG +{ +static void makePermutation(int []a, int n) +{ +/* Store counts of all elements.*/ + + HashMap count = new HashMap(); + for (int i = 0; i < n; i++) + { + if(count.containsKey(a[i])) + { + count.put(a[i], count.get(a[i]) + 1); + } + else + { + count.put(a[i], 1); + } + } +} +/*function to find maximum shortest distance*/ + +static int find_maximum(int a[], int n, int k) +{ +/* stores the shortest distance of every + element in original array.*/ + + HashMap b = new HashMap(); + for (int i = 0; i < n; i++) + { + int x = a[i]; +/* shortest distance from ends*/ + + int d = Math.min(1 + i, n - i); + if (!b.containsKey(x)) + b.put(x, d); + else + { + /* if duplicates are found, b[x] + is replaced with minimum of the + previous and current position's + shortest distance*/ + + b. put(x, Math.min(d, b.get(x))); + } + } + int ans = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) + { + int x = a[i]; +/* similar elements ignore them + cause we need distinct elements*/ + + if (x != k - x && b.containsKey(k - x)) + ans = Math.min(Math.max(b.get(x), + b.get(k - x)), ans); + } + return ans; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = { 3, 5, 8, 6, 7 }; + int K = 11; + int n = a.length; + System.out.println(find_maximum(a, n, K)); +} +}"," '''Python3 code to find maximum shortest +distance from endpoints''' + + '''function to find maximum shortest distance''' + +def find_maximum(a, n, k): ''' stores the shortest distance of every + element in original array.''' + + b = dict() + for i in range(n): + x = a[i] + ''' shortest distance from ends''' + + d = min(1 + i, n - i) + if x not in b.keys(): + b[x] = d + else: + ''' if duplicates are found, b[x] + is replaced with minimum of the + previous and current position's + shortest distance*/''' + + b[x] = min(d, b[x]) + ans = 10**9 + for i in range(n): + x = a[i] + ''' similar elements ignore them + cause we need distinct elements''' + + if (x != (k - x) and (k - x) in b.keys()): + ans = min(max(b[x], b[k - x]), ans) + return ans + '''Driver code''' + +a = [3, 5, 8, 6, 7] +K = 11 +n = len(a) +print(find_maximum(a, n, K))" +Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree,"/*Java implementation of the approach*/ + +import java.util.*; + +class GFG +{ + +/*Structure of binary tree*/ + +static class Node +{ + Node left; + Node right; + int data; +}; + +/*Function to create a new node*/ + +static Node newNode(int key) +{ + Node node = new Node(); + node.left = node.right = null; + node.data = key; + return node; +} + +static Vector path; + +/*Function to store the path from root node +to given node of the tree in path vector and +then returns true if the path exists +otherwise false*/ + +static boolean FindPath(Node root, int key) +{ + if (root == null) + return false; + + path.add(root.data); + + if (root.data == key) + return true; + + if (FindPath(root.left, key) + || FindPath(root.right, key)) + return true; + + path.remove(path.size()-1); + return false; +} + +/*Function to print the minimum and the maximum +value present in the path connecting the +given two nodes of the given binary tree*/ + +static int minMaxNodeInPath(Node root, int a, int b) +{ + +/* To store the path from the root node to a*/ + + path = new Vector (); + boolean flag = true; + +/* To store the path from the root node to b*/ + + Vector Path2 = new Vector(), + Path1 = new Vector(); + +/* To store the minimum and the maximum value + in the path from LCA to a*/ + + int min1 = Integer.MAX_VALUE; + int max1 = Integer.MIN_VALUE; + +/* To store the minimum and the maximum value + in the path from LCA to b*/ + + int min2 = Integer.MAX_VALUE; + int max2 = Integer.MIN_VALUE; + + int i = 0; + int j = 0; + + flag = FindPath(root, a); + Path1 = path; + + path = new Vector(); + + flag&= FindPath(root, b); + Path2 = path; + +/* If both a and b are present in the tree*/ + + if ( flag) + { + +/* Compare the paths to get the first different value*/ + + for (i = 0; i < Path1.size() && i < Path2.size(); i++) + if (Path1.get(i) != Path2.get(i)) + break; + + i--; + j = i; + +/* Find minimum and maximum value + in the path from LCA to a*/ + + for (; i < Path1.size(); i++) + { + if (min1 > Path1.get(i)) + min1 = Path1.get(i); + if (max1 < Path1.get(i)) + max1 = Path1.get(i); + } + +/* Find minimum and maximum value + in the path from LCA to b*/ + + for (; j < Path2.size(); j++) + { + if (min2 > Path2.get(j)) + min2 = Path2.get(j); + if (max2 < Path2.get(j)) + max2 = Path2.get(j); + } + +/* Minimum of min values in first + path and second path*/ + + System.out.println( ""Min = "" + Math.min(min1, min2) ); + +/* Maximum of max values in first + path and second path*/ + + System.out.println( ""Max = "" + Math.max(max1, max2)); + } + +/* If no path exists*/ + + else + System.out.println(""Min = -1\nMax = -1""); + return 0; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + Node root = newNode(20); + root.left = newNode(8); + root.right = newNode(22); + root.left.left = newNode(5); + root.left.right = newNode(3); + root.right.left = newNode(4); + root.right.right = newNode(25); + root.left.right.left = newNode(10); + root.left.right.right = newNode(14); + + int a = 5; + int b = 14; + + minMaxNodeInPath(root, a, b); +} +} + + +"," '''Python3 implementation of the approach''' + + +class Node: + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + + '''Function to store the path from root +node to given node of the tree in +path vector and then returns true if +the path exists otherwise false''' + +def FindPath(root, path, key): + + if root == None: + return False + + path.append(root.data) + + if root.data == key: + return True + + if (FindPath(root.left, path, key) or + FindPath(root.right, path, key)): + return True + + path.pop() + return False + + '''Function to print the minimum and the +maximum value present in the path +connecting the given two nodes of the +given binary tree''' + +def minMaxNodeInPath(root, a, b): + + ''' To store the path from the + root node to a''' + + Path1 = [] + + ''' To store the path from the + root node to b''' + + Path2 = [] + + ''' To store the minimum and the maximum + value in the path from LCA to a''' + + min1, max1 = float('inf'), float('-inf') + + ''' To store the minimum and the maximum + value in the path from LCA to b''' + + min2, max2 = float('inf'), float('-inf') + + i, j = 0, 0 + + ''' If both a and b are present in the tree''' + + if (FindPath(root, Path1, a) and + FindPath(root, Path2, b)): + + ''' Compare the paths to get the + first different value''' + + while i < len(Path1) and i < len(Path2): + if Path1[i] != Path2[i]: + break + i += 1 + + i -= 1 + j = i + + ''' Find minimum and maximum value + in the path from LCA to a''' + + while i < len(Path1): + if min1 > Path1[i]: + min1 = Path1[i] + if max1 < Path1[i]: + max1 = Path1[i] + i += 1 + + ''' Find minimum and maximum value + in the path from LCA to b''' + + while j < len(Path2): + if min2 > Path2[j]: + min2 = Path2[j] + if max2 < Path2[j]: + max2 = Path2[j] + j += 1 + + ''' Minimum of min values in first + path and second path''' + + print(""Min ="", min(min1, min2)) + + ''' Maximum of max values in first + path and second path''' + + print(""Max ="", max(max1, max2)) + + ''' If no path exists''' + + else: + print(""Min = -1\nMax = -1"") + + '''Driver Code''' + +if __name__ == ""__main__"": + + root = Node(20) + root.left = Node(8) + root.right = Node(22) + root.left.left = Node(5) + root.left.right = Node(3) + root.right.left = Node(4) + root.right.right = Node(25) + root.left.right.left = Node(10) + root.left.right.right = Node(14) + + a, b = 5, 14 + + minMaxNodeInPath(root, a, b) + + +" +Print matrix in diagonal pattern,"/*Java program to print matrix in diagonal order*/ + +class GFG { + static final int MAX = 100; + static void printMatrixDiagonal(int mat[][], int n) + { +/* Initialize indexes of element to be printed next*/ + + int i = 0, j = 0; +/* Direction is initially from down to up*/ + + boolean isUp = true; +/* Traverse the matrix till all elements get traversed*/ + + for (int k = 0; k < n * n;) { +/* If isUp = true then traverse from downward + to upward*/ + + if (isUp) { + for (; i >= 0 && j < n; j++, i--) { + System.out.print(mat[i][j] + "" ""); + k++; + } +/* Set i and j according to direction*/ + + if (i < 0 && j <= n - 1) + i = 0; + if (j == n) { + i = i + 2; + j--; + } + } +/* If isUp = 0 then traverse up to down*/ + + else { + for (; j >= 0 && i < n; i++, j--) { + System.out.print(mat[i][j] + "" ""); + k++; + } +/* Set i and j according to direction*/ + + if (j < 0 && i <= n - 1) + j = 0; + if (i == n) { + j = j + 2; + i--; + } + } +/* Revert the isUp to change the direction*/ + + isUp = !isUp; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + int mat[][] = { { 1, 2, 3 }, + { 4, 5, 6 }, + { 7, 8, 9 } }; + int n = 3; + printMatrixDiagonal(mat, n); + } +}"," '''Python 3 program to print matrix in diagonal order''' + +MAX = 100 +def printMatrixDiagonal(mat, n): + ''' Initialize indexes of element to be printed next''' + + i = 0 + j = 0 + k = 0 + ''' Direction is initially from down to up''' + + isUp = True + ''' Traverse the matrix till all elements get traversed''' + + while k= 0 and j= 0 and i s = new Stack<>(); +/* Arrays to store previous and next smaller*/ + + int left[] = new int[n+1]; + int right[] = new int[n+1]; +/* Initialize elements of left[] and right[]*/ + + for (int i=0; i= arr[i]) + s.pop(); + if (!s.empty()) + left[i] = s.peek(); + s.push(i); + } +/* Empty the stack as stack is +going to be used for right[]*/ + + while (!s.empty()) + s.pop(); +/* Fill elements of right[] using same logic*/ + + for (int i = n-1 ; i>=0 ; i-- ) + { + while (!s.empty() && arr[s.peek()] >= arr[i]) + s.pop(); + if(!s.empty()) + right[i] = s.peek(); + s.push(i); + } +/* Create and initialize answer array*/ + + int ans[] = new int[n+1]; + for (int i=0; i<=n; i++) + ans[i] = 0; +/* Fill answer array by comparing minimums of all + lengths computed using left[] and right[]*/ + + for (int i=0; i=1; i--) + ans[i] = Math.max(ans[i], ans[i+1]); +/* Print the result*/ + + for (int i=1; i<=n; i++) + System.out.print(ans[i] + "" ""); + } +/* Driver method*/ + + public static void main(String[] args) + { + printMaxOfMin(arr.length); + } +}"," '''An efficient Python3 program to find +maximum of all minimums of windows of +different sizes''' + +def printMaxOfMin(arr, n): + '''Used to find previous and next smaller''' + + s = [] + ''' Arrays to store previous and next + smaller.''' + + + ''' Initialize elements of + left[] and right[]''' + + left = [-1] * (n + 1) + right = [n] * (n + 1) ''' Fill elements of left[] using logic discussed on +www.geeksforgeeks.org/next-greater-element +https:''' + + for i in range(n): + while (len(s) != 0 and + arr[s[-1]] >= arr[i]): + s.pop() + if (len(s) != 0): + left[i] = s[-1] + s.append(i) + ''' Empty the stack as stack is going + to be used for right[]''' + + while (len(s) != 0): + s.pop() + ''' Fill elements of right[] using same logic''' + + for i in range(n - 1, -1, -1): + while (len(s) != 0 and arr[s[-1]] >= arr[i]): + s.pop() + if(len(s) != 0): + right[i] = s[-1] + s.append(i) + ''' Create and initialize answer array''' + + ans = [0] * (n + 1) + for i in range(n + 1): + ans[i] = 0 + ''' Fill answer array by comparing minimums + of all. Lengths computed using left[] + and right[]''' + + for i in range(n): + ''' Length of the interval''' + + Len = right[i] - left[i] - 1 + ''' arr[i] is a possible answer for this + Length 'Len' interval, check if arr[i] + is more than max for 'Len''' + ''' + ans[Len] = max(ans[Len], arr[i]) + ''' Some entries in ans[] may not be filled + yet. Fill them by taking values from + right side of ans[]''' + + for i in range(n - 1, 0, -1): + ans[i] = max(ans[i], ans[i + 1]) + ''' Print the result''' + + for i in range(1, n + 1): + print(ans[i], end = "" "") + '''Driver Code''' + +if __name__ == '__main__': + arr = [10, 20, 30, 50, 10, 70, 30] + n = len(arr) + printMaxOfMin(arr, n)" +Sliding Window Maximum (Maximum of all subarrays of size k),"/*Java Program to find the maximum for +each and every contiguous subarray of size k.*/ + +import java.util.Deque; +import java.util.LinkedList; +public class SlidingWindow +{ +/* A Dequeue (Double ended queue) + based method for printing + maximum element of + all subarrays of size k*/ + + static void printMax(int arr[], int n, int k) + { +/* Create a Double Ended Queue, Qi + that will store indexes of array elements + The queue will store indexes of + useful elements in every window and it will + maintain decreasing order of values + from front to rear in Qi, i.e., + arr[Qi.front[]] to arr[Qi.rear()] + are sorted in decreasing order*/ + + Deque Qi = new LinkedList(); + /* Process first k (or first window) + elements of array */ + + int i; + for (i = 0; i < k; ++i) + { +/* For every element, the previous + smaller elements are useless so + remove them from Qi*/ + + while (!Qi.isEmpty() && arr[i] >= + arr[Qi.peekLast()]) +/* Remove from rear*/ + + Qi.removeLast(); +/* Add new element at rear of queue*/ + + Qi.addLast(i); + } +/* Process rest of the elements, + i.e., from arr[k] to arr[n-1]*/ + + for (; i < n; ++i) + { +/* The element at the front of the + queue is the largest element of + previous window, so print it*/ + + System.out.print(arr[Qi.peek()] + "" ""); +/* Remove the elements which + are out of this window*/ + + while ((!Qi.isEmpty()) && Qi.peek() <= + i - k) + +/* Remove from front of queue*/ + + Qi.removeFirst();/* Remove all elements smaller + than the currently + being added element (remove + useless elements)*/ + + while ((!Qi.isEmpty()) && arr[i] >= + arr[Qi.peekLast()]) + Qi.removeLast(); +/* Add current element at the rear of Qi*/ + + Qi.addLast(i); + } +/* Print the maximum element of last window*/ + + System.out.print(arr[Qi.peek()]); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; + int k = 3; + printMax(arr, arr.length, k); + } +}"," '''Python program to find the maximum for +each and every contiguous subarray of +size k''' + +from collections import deque '''A Deque (Double ended queue) based +method for printing maximum element +of all subarrays of size k''' + +def printMax(arr, n, k): + ''' Create a Double Ended Queue, Qi that + will store indexes of array elements. + The queue will store indexes of useful + elements in every window and it will + maintain decreasing order of values from + front to rear in Qi, i.e., arr[Qi.front[]] + to arr[Qi.rear()] are sorted in decreasing + order''' + + Qi = deque() + ''' Process first k (or first window) + elements of array''' + + for i in range(k): + ''' For every element, the previous + smaller elements are useless + so remove them from Qi''' + + while Qi and arr[i] >= arr[Qi[-1]] : + + '''Remove from rear''' + + Qi.pop() ''' Add new element at rear of queue''' + + Qi.append(i); + ''' Process rest of the elements, i.e. + from arr[k] to arr[n-1]''' + + for i in range(k, n): + ''' The element at the front of the + queue is the largest element of + previous window, so print it''' + + print(str(arr[Qi[0]]) + "" "", end = """") + ''' Remove the elements which are + out of this window''' + + while Qi and Qi[0] <= i-k: + ''' remove from front of deque''' + + Qi.popleft() + ''' Remove all elements smaller than + the currently being added element + (Remove useless elements)''' + + while Qi and arr[i] >= arr[Qi[-1]] : + Qi.pop() + ''' Add current element at the rear of Qi''' + + Qi.append(i) + ''' Print the maximum element of last window''' + + print(str(arr[Qi[0]])) + '''Driver code''' + +if __name__==""__main__"": + arr = [12, 1, 78, 90, 57, 89, 56] + k = 3 + printMax(arr, len(arr), k)" +Move all zeroes to end of array,"/* Java program to push zeroes to back of array */ + +import java.io.*; +class PushZero +{ +/* Function which pushes all zeros to end of an array.*/ + + static void pushZerosToEnd(int arr[], int n) + { +/*Count of non-zero elements*/ + +int count = 0; +/* Traverse the array. If element encountered is + non-zero, then replace the element at index 'count' + with this element*/ + + for (int i = 0; i < n; i++) + if (arr[i] != 0) +/*here count is*/ + +arr[count++] = arr[i]; +/* incremented + Now all non-zero elements have been shifted to + front and 'count' is set as index of first 0. + Make all elements 0 from count to end.*/ + + while (count < n) + arr[count++] = 0; + } + /*Driver function to check for above functions*/ + + public static void main (String[] args) + { + int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; + int n = arr.length; + pushZerosToEnd(arr, n); + System.out.println(""Array after pushing zeros to the back: ""); + for (int i=0; i s = new HashSet<>(); + for (int i = 0; i < m; i++) + s.add(b[i]); +/* Print all elements of first array + that are not present in hash table*/ + + for (int i = 0; i < n; i++) + if (!s.contains(a[i])) + System.out.print(a[i] + "" ""); + } +/* Driver code*/ + + public static void main(String []args){ + int a[] = { 1, 2, 6, 3, 4, 5 }; + int b[] = { 2, 4, 3, 1, 0 }; + int n = a.length; + int m = b.length; + findMissing(a, b, n, m); + } +}"," '''Python3 efficient program to find elements +which are not present in second array''' + + '''Function for finding elements which +are there in a[] but not in b[].''' + +def findMissing(a, b, n, m): ''' Store all elements of second + array in a hash table''' + + s = dict() + for i in range(m): + s[b[i]] = 1 + ''' Print all elements of first array + that are not present in hash table''' + + for i in range(n): + if a[i] not in s.keys(): + print(a[i], end = "" "") + '''Driver code''' + +a = [ 1, 2, 6, 3, 4, 5 ] +b = [ 2, 4, 3, 1, 0 ] +n = len(a) +m = len(b) +findMissing(a, b, n, m)" +The Stock Span Problem,"/*Java program for a linear time +solution for stock span problem +without using stack*/ + +class GFG { +/* An efficient method to calculate + stock span values implementing the + same idea without using stack*/ + + static void calculateSpan(int A[], + int n, int ans[]) + { +/* Span value of first element is always 1*/ + + ans[0] = 1; +/* Calculate span values for rest of the elements*/ + + for (int i = 1; i < n; i++) { + int counter = 1; + while ((i - counter) >= 0 && A[i] >= A[i - counter]) { + counter += ans[i - counter]; + } + ans[i] = counter; + } + } +/* A utility function to print elements of array*/ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int price[] = { 10, 4, 5, 90, 120, 80 }; + int n = price.length; + int S[] = new int[n]; +/* Fill the span values in array S[]*/ + + calculateSpan(price, n, S); +/* print the calculated span values*/ + + printArray(S, n); + } +}"," '''Python3 program for a linear time +solution for stock span problem +without using stack + ''' '''An efficient method to calculate +stock span values implementing +the same idea without using stack''' + +def calculateSpan(A, n, ans): + ''' Span value of first element + is always 1''' + + ans[0] = 1 + ''' Calculate span values for rest + of the elements''' + + for i in range(1, n): + counter = 1 + while ((i - counter) >= 0 and + A[i] >= A[i - counter]): + counter += ans[i - counter] + ans[i] = counter + '''A utility function to print elements +of array''' + +def printArray(arr, n): + for i in range(n): + print(arr[i], end = ' ') + print() + '''Driver code''' + +price = [ 10, 4, 5, 90, 120, 80 ] +n = len(price) +S = [0] * (n) + '''Fill the span values in array S[]''' + +calculateSpan(price, n, S) + '''Print the calculated span values''' + +printArray(S, n)" +Move weighting scale alternate under given constraints,"/*Java program to print weights for alternating +the weighting scale*/ + +class GFG +{ +/* DFS method to traverse among + states of weighting scales*/ + + static boolean dfs(int residue, int curStep, + int[] wt, int[] arr, + int N, int steps) + { +/* If we reach to more than required steps, + return true*/ + + if (curStep >= steps) + return true; +/* Try all possible weights and + choose one which returns 1 afterwards*/ + + for (int i = 0; i < N; i++) + { + /* + * Try this weight only if it is + * greater than current residue + * and not same as previous chosen weight + */ + + if (curStep - 1 < 0 || + (arr[i] > residue && + arr[i] != wt[curStep - 1])) + { +/* assign this weight to array and + recur for next state*/ + + wt[curStep] = arr[i]; + if (dfs(arr[i] - residue, curStep + 1, + wt, arr, N, steps)) + return true; + } + } +/* if any weight is not possible, + return false*/ + + return false; + } +/* method prints weights for alternating scale + and if not possible prints 'not possible'*/ + + static void printWeightOnScale(int[] arr, + int N, int steps) + { + int[] wt = new int[steps]; +/* call dfs with current residue as 0 + and current steps as 0*/ + + if (dfs(0, 0, wt, arr, N, steps)) + { + for (int i = 0; i < steps; i++) + System.out.print(wt[i] + "" ""); + System.out.println(); + } + else + System.out.println(""Not Possible""); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 2, 3, 5, 6 }; + int N = arr.length; + int steps = 10; + printWeightOnScale(arr, N, steps); + } +}"," '''Python3 program to print weights for +alternating the weighting scale ''' + + '''DFS method to traverse among states +of weighting scales ''' + +def dfs(residue, curStep, wt, arr, N, steps): ''' If we reach to more than required + steps, return true ''' + + if (curStep >= steps): + return True + ''' Try all possible weights and choose + one which returns 1 afterwards''' + + for i in range(N): + ''' Try this weight only if it is greater + than current residueand not same as + previous chosen weight ''' + + if (arr[i] > residue and + arr[i] != wt[curStep - 1]): + ''' assign this weight to array and + recur for next state ''' + + wt[curStep] = arr[i] + if (dfs(arr[i] - residue, curStep + 1, + wt, arr, N, steps)): + return True + ''' if any weight is not possible, + return false ''' + + return False + '''method prints weights for alternating scale +and if not possible prints 'not possible' ''' + +def printWeightsOnScale(arr, N, steps): + wt = [0] * (steps) + ''' call dfs with current residue as 0 + and current steps as 0 ''' + + if (dfs(0, 0, wt, arr, N, steps)): + for i in range(steps): + print(wt[i], end = "" "") + else: + print(""Not possible"") + '''Driver Code''' + +if __name__ == '__main__': + arr = [2, 3, 5, 6] + N = len(arr) + steps = 10 + printWeightsOnScale(arr, N, steps)" +Construct an array from its pair-sum array,"import java.io.*; +class PairSum { +/* Fills element in arr[] from its pair sum array pair[]. + n is size of arr[]*/ + + static void constructArr(int arr[], int pair[], int n) + { + arr[0] = (pair[0]+pair[1]-pair[n-1]) / 2; + for (int i=1; i[] tree = new Vector[MAX_SIZE]; + +/* Function that returns true if a palindromic + string can be formed using the given characters*/ + + static boolean canFormPalindrome(int[] charArray) { + +/* Count odd occurring characters*/ + + int oddCount = 0; + for (int i = 0; i < MAX_CHAR; i++) { + if (charArray[i] % 2 == 1) + oddCount++; + } +/* Return false if odd count is more than 1,*/ + + if (oddCount >= 2) + return false; + else + return true; + } + +/* Find to find the Lowest Common + Ancestor in the tree*/ + + static int LCA(int currentNode, int x, int y) { + +/* Base case*/ + + if (currentNode == x) + return x; + +/* Base case*/ + + if (currentNode == y) + return y; + int xLca, yLca; + +/* Initially value -1 denotes that + we need to find the ancestor*/ + + xLca = yLca = -1; + +/* -1 denotes that we need to find the lca + for x and y, values other than x and y + will be the LCA of x and y*/ + + int gotLca = -1; + +/* Iterating in the child + substree of the currentNode*/ + + for (int l = 0; l < tree[currentNode].size(); l++) { + +/* Next node that will be checked*/ + + int nextNode = tree[currentNode].elementAt(l); + +/* Look for the next child subtree*/ + + int out_ = LCA(nextNode, x, y); + + if (out_ == x) + xLca = out_; + if (out_ == y) + yLca = out_; + +/* Both the nodes exist in the different + subtrees, in this case parent node + will be the lca*/ + + if (xLca != -1 && yLca != -1) + return currentNode; + +/* Handle the cases where LCA is already + calculated or both x and y are present + in the same subtree*/ + + if (out_ != -1) + gotLca = out_; + } + return gotLca; + } + +/* Function to calculate the character count for + each path from node i to 1 (root node)*/ + + static void buildTree(int i) { + for (int l = 0; l < tree[i].size(); l++) { + + int nextNode = tree[i].elementAt(l); + for (int j = 0; j < MAX_CHAR; j++) { + +/* Updating the character count + for each node*/ + + nodeCharactersCount[nextNode][j] += nodeCharactersCount[i][j]; + } + +/* Look for the child subtree*/ + + buildTree(nextNode); + } + } + +/* Function that returns true if a palindromic path + is possible between the nodes x and y*/ + + static boolean canFormPalindromicPath(int x, int y) { + + int lcaNode; + +/* If both x and y are same then + lca will be the node itself*/ + + if (x == y) + lcaNode = x; + +/* Find the lca of x and y*/ + + else + lcaNode = LCA(1, x, y); + + int[] charactersCountFromXtoY = new int[MAX_CHAR]; + Arrays.fill(charactersCountFromXtoY, 0); + +/* Calculating the character count + for path node x to y*/ + + for (int i = 0; i < MAX_CHAR; i++) { + charactersCountFromXtoY[i] = nodeCharactersCount[x][i] + + nodeCharactersCount[y][i] + - 2 * nodeCharactersCount[lcaNode][i]; + } + +/* Checking if we can form the palindrome + string with the all character count*/ + + if (canFormPalindrome(charactersCountFromXtoY)) + return true; + return false; + } + +/* Function to update character count at node v*/ + + static void updateNodeCharactersCount(String str, int v) { + +/* Updating the character count at node v*/ + + for (int i = 0; i < str.length(); i++) + nodeCharactersCount[v][str.charAt(i) - 'a']++; + } + +/* Function to perform the queries*/ + + static void performQueries(int[][] queries, int q) { + int i = 0; + while (i < q) { + + int x = queries[i][0]; + int y = queries[i][1]; + +/* If path can be a palindrome*/ + + if (canFormPalindromicPath(x, y)) + System.out.println(""Yes""); + else + System.out.println(""No""); + i++; + } + } + +/* Driver Code*/ + + public static void main(String[] args) { + +/* Fill the complete array with 0*/ + + for (int i = 0; i < MAX_SIZE; i++) { + for (int j = 0; j < MAX_CHAR; j++) { + nodeCharactersCount[i][j] = 0; + } + } + for (int i = 0; i < MAX_SIZE; i++) { + tree[i] = new Vector<>(); + } + +/* Edge between 1 and 2 labelled ""bbc""*/ + + tree[1].add(2); + updateNodeCharactersCount(""bbc"", 2); + +/* Edge between 1 and 3 labelled ""ac""*/ + + tree[1].add(3); + updateNodeCharactersCount(""ac"", 3); + +/* Update the character count + from root to the ith node*/ + + buildTree(1); + + int[][] queries = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 3, 3 } }; + int q = queries.length; + +/* Perform the queries*/ + + performQueries(queries, q); + } +} + + +", +Longest Palindromic Substring | Set 1,"/*A Java solution for longest palindrome*/ + +import java.util.*; +class GFG{ +/*Function to print a subString str[low..high]*/ + +static void printSubStr(String str, int low, int high) +{ + for (int i = low; i <= high; ++i) + System.out.print(str.charAt(i)); +} +/*This function prints the +longest palindrome subString +It also returns the length +of the longest palindrome*/ + +static int longestPalSubstr(String str) +{ +/* get length of input String*/ + + int n = str.length(); +/* All subStrings of length 1 + are palindromes*/ + + int maxLength = 1, start = 0; +/* Nested loop to mark start and end index*/ + + for (int i = 0; i < str.length(); i++) { + for (int j = i; j < str.length(); j++) { + int flag = 1; +/* Check palindrome*/ + + for (int k = 0; k < (j - i + 1) / 2; k++) + if (str.charAt(i + k) != str.charAt(j - k)) + flag = 0; +/* Palindrome*/ + + if (flag!=0 && (j - i + 1) > maxLength) { + start = i; + maxLength = j - i + 1; + } + } + } + System.out.print(""Longest palindrome subString is: ""); + printSubStr(str, start, start + maxLength - 1); +/* return length of LPS*/ + + return maxLength; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + String str = ""forgeeksskeegfor""; + System.out.print(""\nLength is: "" + + longestPalSubstr(str)); +} +}"," '''A Python3 solution for longest palindrome + ''' '''Function to pra subString str[low..high]''' + +def printSubStr(str, low, high): + for i in range(low, high + 1): + print(str[i], end = """") + '''This function prints the +longest palindrome subString +It also returns the length +of the longest palindrome''' + +def longestPalSubstr(str): + ''' Get length of input String''' + + n = len(str) + ''' All subStrings of length 1 + are palindromes''' + + maxLength = 1 + start = 0 + ''' Nested loop to mark start + and end index''' + + for i in range(n): + for j in range(i, n): + flag = 1 + ''' Check palindrome''' + + for k in range(0, ((j - i) // 2) + 1): + if (str[i + k] != str[j - k]): + flag = 0 + ''' Palindrome''' + + if (flag != 0 and (j - i + 1) > maxLength): + start = i + maxLength = j - i + 1 + print(""Longest palindrome subString is: "", end = """") + printSubStr(str, start, start + maxLength - 1) + ''' Return length of LPS''' + + return maxLength + '''Driver Code''' + +if __name__ == '__main__': + str = ""forgeeksskeegfor"" + print(""\nLength is: "", longestPalSubstr(str))" +Check if a string can be obtained by rotating another string d places,," '''Python3 implementation of the approach''' + + + '''Function to reverse an array from left +index to right index (both inclusive)''' + +def ReverseArray(arr, left, right) : + + while (left < right) : + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left += 1; + right -= 1; + + '''Function that returns true if str1 can be +made equal to str2 by rotating either +d places to the left or to the right''' + +def RotateAndCheck(str1, str2, d) : + + if (len(str1) != len(str2)) : + return False; + + ''' Left Rotation string will contain + the string rotated Anti-Clockwise + Right Rotation string will contain + the string rotated Clockwise''' + + left_rot_str1 = []; right_rot_str1 = []; + left_flag = True; right_flag = True; + str1_size = len(str1); + + ''' Copying the str1 string to left rotation string + and right rotation string''' + + for i in range(str1_size) : + left_rot_str1.append(str1[i]); + right_rot_str1.append(str1[i]); + + ''' Rotating the string d positions to the left''' + + ReverseArray(left_rot_str1, 0, d - 1); + ReverseArray(left_rot_str1, d, str1_size - 1); + ReverseArray(left_rot_str1, 0, str1_size - 1); + + ''' Rotating the string d positions to the right''' + + 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); + + ''' Compairing the rotated strings''' + + for i in range(str1_size) : + + ''' If cannot be made equal with left rotation''' + + if (left_rot_str1[i] != str2[i]) : + left_flag = False; + + ''' If cannot be made equal with right rotation''' + + if (right_rot_str1[i] != str2[i]) : + right_flag = False; + + ''' If both or any one of the rotations + of str1 were equal to str2''' + + if (left_flag or right_flag) : + return True; + return False; + + '''Driver code''' + +if __name__ == ""__main__"" : + + str1 = list(""abcdefg""); + str2 = list(""cdefgab""); + + ''' d is the rotating factor''' + + d = 2; + + ''' In case length of str1 < d''' + + d = d % len(str1); + + if (RotateAndCheck(str1, str2, d)) : + print(""Yes""); + else : + print(""No""); + + +" +Bottom View of a Binary Tree,"/*Java Program to print Bottom View of Binary Tree*/ + +import java.util.*; +import java.util.Map.Entry; +/*Tree node class*/ + +class Node +{ +/*data of the node*/ + +int data; +/*horizontal distance of the node*/ + +int hd; +/*left and right references*/ + +Node left, right; +/* Constructor of tree node*/ + + public Node(int key) + { + data = key; + hd = Integer.MAX_VALUE; + left = right = null; + } +} +/*Tree class*/ + +class Tree +{ +/*root node of tree*/ + +Node root; +/* Default constructor*/ + + public Tree() {} +/* Parameterized tree constructor*/ + + public Tree(Node node) + { + root = node; + } +/* Method that prints the bottom view.*/ + + public void bottomView() + { + if (root == null) + return; +/* Initialize a variable 'hd' with 0 for the root element.*/ + + int hd = 0; +/* TreeMap which stores key value pair sorted on key value*/ + + Map map = new TreeMap<>(); +/* Queue to store tree nodes in level order traversal*/ + + Queue queue = new LinkedList(); +/* Assign initialized horizontal distance value to root + node and add it to the queue.*/ + + root.hd = hd; +/*In STL, push() is used enqueue an item*/ + + queue.add(root);/* Loop until the queue is empty (standard level order loop)*/ + + while (!queue.isEmpty()) + { + Node temp = queue.remove(); +/* Extract the horizontal distance value from the + dequeued tree node.*/ + + hd = temp.hd; +/* Put the dequeued tree node to TreeMap having key + as horizontal distance. Every time we find a node + having same horizontal distance we need to replace + the data in the map.*/ + + map.put(hd, temp.data); +/* If the dequeued node has a left child add it to the + queue with a horizontal distance hd-1.*/ + + if (temp.left != null) + { + temp.left.hd = hd-1; + queue.add(temp.left); + } +/* If the dequeued node has a right child add it to the + queue with a horizontal distance hd+1.*/ + + if (temp.right != null) + { + temp.right.hd = hd+1; + queue.add(temp.right); + } + } +/* Extract the entries of map into a set to traverse + an iterator over that.*/ + + Set> set = map.entrySet(); +/* Make an iterator*/ + + Iterator> iterator = set.iterator(); +/* Traverse the map elements using the iterator.*/ + + while (iterator.hasNext()) + { + Map.Entry me = iterator.next(); + System.out.print(me.getValue()+"" ""); + } + } +} +/*Main driver class*/ + +public class BottomView +{ + public static void main(String[] args) + { + Node root = new Node(20); + root.left = new Node(8); + root.right = new Node(22); + root.left.left = new Node(5); + root.left.right = new Node(3); + root.right.left = new Node(4); + root.right.right = new Node(25); + root.left.right.left = new Node(10); + root.left.right.right = new Node(14); + Tree tree = new Tree(root); + System.out.println(""Bottom view of the given binary tree:""); + tree.bottomView(); + } +}"," '''Python3 program to print Bottom +View of Binary Tree''' + + '''Tree node class''' + +class Node: + ''' Constructor of tree node''' + + def __init__(self, key): + self.data = key + self.hd = 1000000 + self.left = None + self.right = None '''Method that prints the bottom view.''' + +def bottomView(root): + if (root == None): + return + ''' Initialize a variable 'hd' with 0 + for the root element.''' + + hd = 0 + ''' TreeMap which stores key value pair + sorted on key value''' + + m = dict() + ''' Queue to store tree nodes in level + order traversal''' + + q = [] + ''' Assign initialized horizontal distance + value to root node and add it to the queue.''' + + root.hd = hd + ''' In STL, append() is used enqueue an item''' + + q.append(root) + ''' Loop until the queue is empty (standard + level order loop)''' + + while (len(q) != 0): + temp = q[0] + ''' In STL, pop() is used dequeue an item''' + + q.pop(0) + ''' Extract the horizontal distance value + from the dequeued tree node.''' + + hd = temp.hd + ''' Put the dequeued tree node to TreeMap + having key as horizontal distance. Every + time we find a node having same horizontal + distance we need to replace the data in + the map.''' + + m[hd] = temp.data + ''' If the dequeued node has a left child, add + it to the queue with a horizontal distance hd-1.''' + + if (temp.left != None): + temp.left.hd = hd - 1 + q.append(temp.left) + ''' If the dequeued node has a right child, add + it to the queue with a horizontal distance + hd+1.''' + + if (temp.right != None): + temp.right.hd = hd + 1 + q.append(temp.right) + ''' Traverse the map elements using the iterator.''' + + for i in sorted(m.keys()): + print(m[i], end = ' ') + '''Driver Code''' + +if __name__=='__main__': + root = Node(20) + root.left = Node(8) + root.right = Node(22) + root.left.left = Node(5) + root.left.right = Node(3) + root.right.left = Node(4) + root.right.right = Node(25) + root.left.right.left = Node(10) + root.left.right.right = Node(14) + print(""Bottom view of the given binary tree :"") + bottomView(root)" +Maximum size rectangle binary sub-matrix with all 1s,"/*Java program to find largest rectangle with all 1s +in a binary matrix*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Finds the maximum area under the histogram + represented by histogram. See below article for*/ + + static int maxHist(int R, int C, int row[]) + { +/* Create an empty stack. The stack holds indexes of + hist[] array/ The bars stored in stack are always + in increasing order of their heights.*/ + + Stack result = new Stack(); +/*Top of stack*/ + +int top_val; +/*Initialize max area in current*/ + +int max_area = 0; +/* row (or histogram) +Initialize area with current top*/ + +int area = 0; +/* Run through all bars of given histogram (or row)*/ + + int i = 0; + while (i < C) { +/* If this bar is higher than the bar on top + stack, push it to stack*/ + + if (result.empty() + || row[result.peek()] <= row[i]) + result.push(i++); + else { +/* If this bar is lower than top of stack, + then calculate area of rectangle with + stack top as the smallest (or minimum + height) bar. 'i' is 'right index' for the + top and element before top in stack is + 'left index'*/ + + top_val = row[result.peek()]; + result.pop(); + area = top_val * i; + if (!result.empty()) + area + = top_val * (i - result.peek() - 1); + max_area = Math.max(area, max_area); + } + } +/* Now pop the remaining bars from stack and + calculate area with every popped bar as the + smallest bar*/ + + while (!result.empty()) { + top_val = row[result.peek()]; + result.pop(); + area = top_val * i; + if (!result.empty()) + area = top_val * (i - result.peek() - 1); + max_area = Math.max(area, max_area); + } + return max_area; + } +/* Returns area of the largest rectangle with all 1s in + A[][]*/ + + static int maxRectangle(int R, int C, int A[][]) + { +/* Calculate area for first row and initialize it as + result*/ + + int result = maxHist(R, C, A[0]); +/* iterate over row to find maximum rectangular area + considering each row as histogram*/ + + for (int i = 1; i < R; i++) { + for (int j = 0; j < C; j++) +/* if A[i][j] is 1 then add A[i -1][j]*/ + + if (A[i][j] == 1) + A[i][j] += A[i - 1][j]; +/* Update result if area with current row (as + last row of rectangle) is more*/ + + result = Math.max(result, maxHist(R, C, A[i])); + } + return result; + } +/* Driver code*/ + + public static void main(String[] args) + { + int R = 4; + int C = 4; + int A[][] = { + { 0, 1, 1, 0 }, + { 1, 1, 1, 1 }, + { 1, 1, 1, 1 }, + { 1, 1, 0, 0 }, + }; + System.out.print(""Area of maximum rectangle is "" + + maxRectangle(R, C, A)); + } +} +"," '''Python3 program to find largest rectangle +with all 1s in a binary matrix''' + + '''Finds the maximum area under the +histogram represented +by histogram. See below article for details.''' + +class Solution(): + def maxHist(self, row): ''' Create an empty stack. The stack holds + indexes of hist array / The bars stored + in stack are always in increasing order + of their heights.''' + + result = [] + ''' Top of stack''' + + top_val = 0 + ''' Initialize max area in current''' + + max_area = 0 + ''' row (or histogram) +Initialize area with current top''' + + area = 0 + ''' Run through all bars of given + histogram (or row)''' + + i = 0 + while (i < len(row)): + ''' If this bar is higher than the + bar on top stack, push it to stack''' + + if (len(result) == 0) or (row[result[-1]] <= row[i]): + result.append(i) + i += 1 + else: + ''' If this bar is lower than top of stack, + then calculate area of rectangle with + stack top as the smallest (or minimum + height) bar. 'i' is 'right index' for + the top and element before top in stack + is 'left index''' + ''' + top_val = row[result.pop()] + area = top_val * i + if (len(result)): + area = top_val * (i - result[-1] - 1) + max_area = max(area, max_area) + ''' Now pop the remaining bars from stack + and calculate area with every popped + bar as the smallest bar''' + + while (len(result)): + top_val = row[result.pop()] + area = top_val * i + if (len(result)): + area = top_val * (i - result[-1] - 1) + max_area = max(area, max_area) + return max_area + ''' Returns area of the largest rectangle + with all 1s in A''' + + def maxRectangle(self, A): + ''' Calculate area for first row and + initialize it as result''' + + result = self.maxHist(A[0]) + ''' iterate over row to find maximum rectangular + area considering each row as histogram''' + + for i in range(1, len(A)): + for j in range(len(A[i])): + ''' if A[i][j] is 1 then add A[i -1][j]''' + + if (A[i][j]): + A[i][j] += A[i - 1][j] + ''' Update result if area with current + row (as last row) of rectangle) is more''' + + result = max(result, self.maxHist(A[i])) + return result + '''Driver Code''' + +if __name__ == '__main__': + A = [[0, 1, 1, 0], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 0, 0]] + ans = Solution() + print(""Area of maximum rectangle is"", + ans.maxRectangle(A))" +Sum of all the numbers that are formed from root to leaf paths,"/*Java program to find sum of all numbers that are formed from root +to leaf paths +A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* Returns sum of all root to leaf paths. The first parameter is + root of current subtree, the second parameter is value of the + number formed by nodes from root to this node*/ + + int treePathsSumUtil(Node node, int val) + { +/* Base case*/ + + if (node == null) + return 0; +/* Update val*/ + + val = (val * 10 + node.data); +/* if current node is leaf, return the current value of val*/ + + if (node.left == null && node.right == null) + return val; +/* recur sum of values for left and right subtree*/ + + return treePathsSumUtil(node.left, val) + + treePathsSumUtil(node.right, val); + } +/* A wrapper function over treePathsSumUtil()*/ + + int treePathsSum(Node node) + { +/* Pass the initial value as 0 as there is nothing above root*/ + + return treePathsSumUtil(node, 0); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(6); + tree.root.left = new Node(3); + tree.root.right = new Node(5); + tree.root.right.right = new Node(4); + tree.root.left.left = new Node(2); + tree.root.left.right = new Node(5); + tree.root.left.right.right = new Node(4); + tree.root.left.right.left = new Node(7); + System.out.print(""Sum of all paths is "" + + tree.treePathsSum(tree.root)); + } +}"," '''Python program to find sum of all paths from root to leaves +A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Returs sums of all root to leaf paths. The first parameter is root +of current subtree, the second paramete""r is value of the number +formed by nodes from root to this node''' + +def treePathsSumUtil(root, val): + ''' Base Case''' + + if root is None: + return 0 + ''' Update val''' + + val = (val*10 + root.data) + ''' If current node is leaf, return the current value of val''' + + if root.left is None and root.right is None: + return val + ''' Recur sum of values for left and right subtree''' + + return (treePathsSumUtil(root.left, val) + + treePathsSumUtil(root.right, val)) + '''A wrapper function over treePathSumUtil()''' + +def treePathsSum(root): + ''' Pass the initial value as 0 as ther is nothing above root''' + + return treePathsSumUtil(root, 0) + '''Driver function to test above function''' + +root = Node(6) +root.left = Node(3) +root.right = Node(5) +root.left.left = Node(2) +root.left.right = Node(5) +root.right.right = Node(4) +root.left.right.left = Node(7) +root.left.right.right = Node(4) +print ""Sum of all paths is"", treePathsSum(root)" +Insertion in a sorted circular linked list when a random pointer is given,"/*Java implementation of the approach*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class GFG +{ + +/*Node structure*/ + +static class Node +{ + Node next; + int data; +}; + +/*Function to create a node*/ + +static Node create() +{ + Node new_node = new Node(); + new_node.next = null; + + return new_node; +} + +/*Function to find and return the head*/ + +static Node find_head(Node random) +{ +/* If the list is empty*/ + + if (random == null) + return null; + + Node head, var = random; + +/* Finding the last node of the linked list + the last node must have the highest value + if no such element is present then all the nodes + of the linked list must be same*/ + + while (!(var.data > var.next.data || + var.next == random)) + { + var = var.next; + } + +/* Return the head*/ + + return var.next; +} + +/*Function to insert a new_node in the list +in sorted fashion. Note that this function +expects a pointer to head node as this can +modify the head of the input linked list*/ + +static Node sortedInsert(Node head_ref, + Node new_node) +{ + Node current = head_ref; + +/* If the list is empty*/ + + if (current == null) + { + new_node.next = new_node; + head_ref = new_node; + } + +/* If the node to be inserted is the smallest + then it has to be the new head*/ + + else if (current.data >= new_node.data) + { + +/* Find the last node of the list as it + will be pointing to the head*/ + + while (current.next != head_ref) + current = current.next; + current.next = new_node; + new_node.next = head_ref; + head_ref = new_node; + } + + else + { +/* Locate the node before the point of insertion*/ + + while (current.next != head_ref && + current.next.data < new_node.data) + { + current = current.next; + } + new_node.next = current.next; + current.next = new_node; + } + +/* Return the new head*/ + + return head_ref; +} + +/*Function to print the nodes of the linked list*/ + +static void printList(Node start) +{ + Node temp; + + if (start != null) + { + temp = start; + do + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } while (temp != start); + } +} + +/*Driver code*/ + +public static void main(String args[]) +{ + + int arr[] = { 12, 56, 2, 11, 1, 90 }; + int list_size, i; + +/* Start with an empty linked list*/ + + Node start = null; + Node temp; + +/* Create linked list from the given array*/ + + for (i = 0; i < 6; i++) + { + +/* Move to a random node if it exists*/ + + if (start != null) + for (int j = 0; + j < (Math.random() * 10); j++) + start = start.next; + + temp = create(); + temp.data = arr[i]; + start = sortedInsert(find_head(start), temp); + } + +/* Print the contents of the created list*/ + + printList(find_head(start)); +} +} + + +"," '''Python3 implementation of the approach''' + +from random import randint + + '''Node structure''' + +class Node: + + def __init__(self): + + self.next = None + self.data = 0 + + '''Function to create a node''' + +def create(): + + new_node = Node() + new_node.next = None + return new_node + + '''Function to find and return the head''' + +def find_head(random): + + ''' If the list is empty''' + + if (random == None): + return None + + head = None + var = random + + ''' Finding the last node of the linked list + the last node must have the highest value + if no such element is present then all + the nodes of the linked list must be same''' + + while (not(var.data > var.next.data or + var.next == random)): + var = var.next + + ''' Return the head''' + + return var.next + + '''Function to insert a new_node in the list in +sorted fashion. Note that this function expects +a pointer to head node as this can modify the +head of the input linked list''' + +def sortedInsert(head_ref, new_node): + + current = head_ref + + ''' If the list is empty''' + + if (current == None): + new_node.next = new_node + head_ref = new_node + + ''' If the node to be inserted is the smallest + then it has to be the new head''' + + elif (current.data >= new_node.data): + + ''' Find the last node of the list as it + will be pointing to the head''' + + while (current.next != head_ref): + current = current.next + + current.next = new_node + new_node.next = head_ref + head_ref = new_node + + else: + + ''' Locate the node before the point of insertion''' + + while (current.next != head_ref and + current.next.data < new_node.data): + current = current.next + + new_node.next = current.next + current.next = new_node + + ''' Return the new head''' + + return head_ref + + '''Function to print the nodes of the linked list''' + +def printList(start): + + temp = 0 + + if (start != None): + temp = start + + while True: + print(temp.data, end = ' ') + temp = temp.next + + if (temp == start): + break + + '''Driver code''' + +if __name__=='__main__': + + arr = [ 12, 56, 2, 11, 1, 90 ] + + ''' Start with an empty linked list''' + + start = None; + temp = 0 + + ''' Create linked list from the given array''' + + for i in range(6): + + ''' Move to a random node if it exists''' + + if (start != None): + for j in range(randint(0, 10)): + start = start.next + + temp = create() + temp.data = arr[i] + start = sortedInsert(find_head(start), temp) + + ''' Print the contents of the created list''' + + printList(find_head(start)) + + +" +Print all root to leaf paths with there relative positions,"/*Java program to print all root to leaf +paths with there relative position*/ + +import java.util.ArrayList; +class Graph{ +static final int MAX_PATH_SIZE = 1000; +/*tree structure*/ + +static class Node +{ + char data; + Node left, right; +}; +/*Function create new node*/ + +static Node newNode(char data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Store path information*/ + +static class PATH +{ + int Hd; + char key; + public PATH(int Hd, char key) + { + this.Hd = Hd; + this.key = key; + } + public PATH() + {} +}; +/*Prints given root to leaf path with underscores*/ + +static void printPath(ArrayList path, int size) +{ +/* Find the minimum horizontal distance value + in current root to leaf path*/ + + int minimum_Hd = Integer.MAX_VALUE; + PATH p; +/* Find minimum horizontal distance*/ + + for(int it = 0; it < size; it++) + { + p = path.get(it); + minimum_Hd = Math.min(minimum_Hd, p.Hd); + } +/* Print the root to leaf path with ""_"" + that indicate the related position*/ + + for(int it = 0; it < size; it++) + { +/* Current tree node*/ + + p = path.get(it); + int noOfUnderScores = Math.abs( + p.Hd - minimum_Hd); +/* Print underscore*/ + + for(int i = 0; i < noOfUnderScores; i++) + System.out.print(""_""); +/* Print current key*/ + + System.out.println(p.key); + } + System.out.println(""==============================""); +} +/*A utility function print all path from root to leaf +working of this function is similar to function of +""Print_vertical_order"" : Print paths of binary tree +in vertical order +www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/ +https:*/ + +static void printAllPathsUtil(Node root, + ArrayList AllPath, + int HD, int order) +{ +/* Base case*/ + + if (root == null) + return; +/* Leaf node*/ + + if (root.left == null && root.right == null) + { +/* Add leaf node and then print path*/ + + AllPath.set(order, new PATH(HD, root.data)); + printPath(AllPath, order + 1); + return; + }/* Store current path information*/ + + AllPath.set(order, new PATH(HD, root.data)); +/*Call left sub_tree*/ + + printAllPathsUtil(root.left, AllPath, + HD - 1, order + 1); +/* Call left sub_tree*/ + + printAllPathsUtil(root.right, AllPath, + HD + 1, order + 1); +} +static void printAllPaths(Node root) +{ +/* Base case*/ + + if (root == null) + return; + ArrayList Allpaths = new ArrayList<>(); + for(int i = 0; i < MAX_PATH_SIZE; i++) + { + Allpaths.add(new PATH()); + } + printAllPathsUtil(root, Allpaths, 0, 0); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newNode('A'); + root.left = newNode('B'); + root.right = newNode('C'); + root.left.left = newNode('D'); + root.left.right = newNode('E'); + root.right.left = newNode('F'); + root.right.right = newNode('G'); + printAllPaths(root); +} +}"," '''Python3 program to print the longest +leaf to leaf path''' + + +MAX_PATH_SIZE = 1000 + '''Tree node structure used in the program''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + '''Prints given root to leafAllpaths +with underscores''' + +def printPath(size): + + ''' Find the minimum horizontal distance + value in current root to leafAllpaths''' + + minimum_Hd = 10**19 + p = [] + global Allpaths ''' Find minimum horizontal distance''' + + for it in range(size): + p = Allpaths[it] + minimum_Hd = min(minimum_Hd, p[0]) + ''' Print the root to leafAllpaths with ""_"" + that indicate the related position''' + + for it in range(size): + ''' Current tree node''' + + p = Allpaths[it] + noOfUnderScores = abs(p[0] - minimum_Hd) + ''' Print underscore''' + + for i in range(noOfUnderScores): + print(end = ""_ "") + ''' Print current key''' + + print(p[1]) + print(""=============================="") + '''A utility function prall path from root to leaf +working of this function is similar to function of +""Print_vertical_order"" : Prpaths of binary tree +in vertical order +https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/''' + +def printAllPathsUtil(root, HD, order): + ''' Base case''' + + global Allpaths + if (root == None): + return + ''' Leaf node''' + + if (root.left == None and root.right == None): + ''' Add leaf node and then prpath''' + + Allpaths[order] = [HD, root.data] + printPath(order + 1) + return + ''' Store current path information''' + + Allpaths[order] = [HD, root.data] + ''' Call left sub_tree''' + + printAllPathsUtil(root.left, HD - 1, order + 1) + ''' Call left sub_tree''' + + printAllPathsUtil(root.right, HD + 1, order + 1) +def printAllPaths(root): + global Allpaths + ''' Base case''' + + if (root == None): + return + printAllPathsUtil(root, 0, 0) + '''Driver code''' + +if __name__ == '__main__': + Allpaths = [ [0, 0] for i in range(MAX_PATH_SIZE)] + root = Node('A') + root.left = Node('B') + root.right = Node('C') + root.left.left = Node('D') + root.left.right = Node('E') + root.right.left = Node('F') + root.right.right = Node('G') + printAllPaths(root)" +Construct a Binary Tree from Postorder and Inorder,"/*Java program for above approach*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Node class*/ + + static class Node { + int data; + Node left, right; +/* Constructor*/ + + Node(int x) + { + data = x; + left = right = null; + } + } +/* Tree building function*/ + + static Node buildTree(int in[], int post[], int n) + { +/* Create Stack of type Node**/ + + Stack st = new Stack<>(); +/* Create HashSet of type Node**/ + + HashSet s = new HashSet<>(); +/* Initialise postIndex with n - 1*/ + + int postIndex = n - 1; +/* Initialise root with null*/ + + Node root = null; + for (int p = n - 1, i = n - 1; p >= 0 { +/* Initialise node with NULL*/ + + Node node = null; +/* Run do-while loop*/ + + do { +/* Initialise node with + new Node(post[p]);*/ + + node = new Node(post[p]); +/* Check is root is + equal to NULL*/ + + if (root == null) { + root = node; + } +/* If size of set + is greater than 0*/ + + if (st.size() > 0) { +/* If st.peek() is present in the + set s*/ + + if (s.contains(st.peek())) { + s.remove(st.peek()); + st.peek().left = node; + st.pop(); + } + else { + st.peek().right = node; + } + } + st.push(node); + } while (post[p--] != in[i] && p >= 0); + node = null; +/* If the stack is not empty and + st.top().data is equal to in[i]*/ + + while (st.size() > 0 && i >= 0 + && st.peek().data == in[i]) { + node = st.peek(); +/* Pop elements from stack*/ + + st.pop(); + i--; + } +/* If node not equal to NULL*/ + + if (node != null) { + s.add(node); + st.push(node); + } + } +/* Return root*/ + + return root; + } +/* For print preOrder Traversal*/ + + static void preOrder(Node node) + { + if (node == null) + return; + System.out.printf(""%d "", node.data); + preOrder(node.left); + preOrder(node.right); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; + int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; + int n = in.length; +/* Function Call*/ + + Node root = buildTree(in, post, n); + System.out.print( + ""Preorder of the constructed tree : \n""); +/* Function Call for preOrder*/ + + preOrder(root); + } +}", +Maximum in array which is at-least twice of other elements,"/*Java program for Maximum of the array +which is at least twice of other elements +of the array.*/ + +import java.util.*; +import java.lang.*; + +class GfG { + +/* Function to find the index of Max element + that satisfies the condition*/ + + public static int findIndex(int[] arr) { + +/* Finding index of max of the array*/ + + int maxIndex = 0; + for (int i = 0; i < arr.length; ++i) + if (arr[i] > arr[maxIndex]) + maxIndex = i; + +/* Returns -1 if the max element is not + twice of the i-th element. */ + + for (int i = 0; i < arr.length; ++i) + if (maxIndex != i && arr[maxIndex] < 2 * arr[i]) + return -1; + + return maxIndex; + } + +/* Driver function*/ + + public static void main(String argc[]){ + int[] arr = new int[]{3, 6, 1, 0}; + System.out.println(findIndex(arr)); + } +} +"," '''Python 3 program for Maximum of +the array which is at least twice +of other elements of the array.''' + + + '''Function to find the index of Max +element that satisfies the condition''' + +def findIndex(arr): + + ''' Finding index of max of the array''' + + maxIndex = 0 + for i in range(0,len(arr)): + if (arr[i] > arr[maxIndex]): + maxIndex = i + + ''' Returns -1 if the max element is not + twice of the i-th element. ''' + + for i in range(0,len(arr)): + if (maxIndex != i and + arr[maxIndex] < (2 * arr[i])): + return -1 + + return maxIndex + + + '''Driver code''' + +arr = [3, 6, 1, 0] +print(findIndex(arr)) + + +" +Largest subset of Graph vertices with edges of 2 or more colors,"/*Java program to find size of +subset of graph vertex such that +each vertex has more than 1 color edges */ + +import java.util.*; +class GFG +{ +/* Number of vertices */ + + static int N = 6; +/* function to calculate max subset size */ + + static int subsetGraph(int C[][]) + { +/* set for number of vertices */ + + HashSet vertices = new HashSet<>(); + for (int i = 0; i < N; ++i) + { + vertices.add(i); + } +/* loop for deletion of vertex from set */ + + while (!vertices.isEmpty()) + { +/* if subset has only 1 vertex return 0 */ + + if (vertices.size() == 1) + { + return 1; + } +/* for each vertex iterate and keep removing + a vertix while we find a vertex with all + edges of same color. */ + + boolean someone_removed = false; + for (int x : vertices) + { +/* note down different color values + for each vertex */ + + HashSet values = new HashSet<>(); + for (int y : vertices) + { + if (y != x) + { + values.add(C[x][y]); + } + } +/* if only one color is found + erase that vertex (bad vertex) */ + + if (values.size() == 1) + { + vertices.remove(x); + someone_removed = true; + break; + } + } +/* If no vertex was removed in the + above loop. */ + + if (!someone_removed) + { + break; + } + } + return (vertices.size()); + } +/* Driver code */ + + public static void main(String[] args) + { + int C[][] = {{0, 9, 2, 4, 7, 8}, + {9, 0, 9, 9, 7, 9}, + {2, 9, 0, 3, 7, 6}, + {4, 9, 3, 0, 7, 1}, + {7, 7, 7, 7, 0, 7}, + {8, 9, 6, 1, 7, 0} + }; + System.out.println(subsetGraph(C)); + } +}"," '''Python3 program to find size of subset +of graph vertex such that each vertex +has more than 1 color edges''' + '''Number of vertices ''' + +N = 6 '''function to calculate max subset size ''' + +def subsetGraph(C): + global N + ''' set for number of vertices ''' + + vertices = set() + for i in range(N): + vertices.add(i) + ''' loop for deletion of vertex from set ''' + + while (len(vertices) != 0): + ''' if subset has only 1 vertex return 0 ''' + + if (len(vertices) == 1): + return 1 + ''' for each vertex iterate and keep removing + a vertix while we find a vertex with all + edges of same color. ''' + + someone_removed = False + for x in vertices: + ''' note down different color values + for each vertex ''' + + values = set() + for y in vertices: + if (y != x): + values.add(C[x][y]) + ''' if only one color is found + erase that vertex (bad vertex) ''' + + if (len(values) == 1): + vertices.remove(x) + someone_removed = True + break + ''' If no vertex was removed in the + above loop. ''' + + if (not someone_removed): + break + return len(vertices) + '''Driver Code''' + +C = [[0, 9, 2, 4, 7, 8], + [9, 0, 9, 9, 7, 9], + [2, 9, 0, 3, 7, 6], + [4, 9, 3, 0, 7, 1], + [7, 7, 7, 7, 0, 7], + [8, 9, 6, 1, 7, 0]] +print(subsetGraph(C))" +Doubly Circular Linked List | Set 1 (Introduction and Insertion),"/*Function to insert at the end*/ + +static void insertEnd(int value) +{ +/* If the list is empty, create a single + node circular and doubly list*/ + + if (start == null) + { + Node new_node = new Node(); + new_node.data = value; + new_node.next = new_node.prev = new_node; + start = new_node; + return; + } +/* If list is not empty + Find last node*/ + + Node last = (start).prev; +/* Create Node dynamically*/ + + Node new_node = new Node(); + new_node.data = value; +/* Start is going to be + next of new_node*/ + + new_node.next = start; +/* Make new node previous of start*/ + + (start).prev = new_node; +/* Make last preivous of new node*/ + + new_node.prev = last; +/* Make new node next of old last*/ + + last.next = new_node; +}", +Shortest Common Supersequence,"/*A Naive recursive Java program to find +length of the shortest supersequence*/ + +class GFG { + static int superSeq(String X, String Y, int m, int n) + { + if (m == 0) + return n; + if (n == 0) + return m; + if (X.charAt(m - 1) == Y.charAt(n - 1)) + return 1 + superSeq(X, Y, m - 1, n - 1); + return 1 + + Math.min(superSeq(X, Y, m - 1, n), + superSeq(X, Y, m, n - 1)); + } +/* Driver code*/ + + public static void main(String args[]) + { + String X = ""AGGTAB""; + String Y = ""GXTXAYB""; + System.out.println( + ""Length of the shortest"" + + ""supersequence is: "" + + superSeq(X, Y, X.length(), Y.length())); + } +}"," '''A Naive recursive python program to find +length of the shortest supersequence''' + +def superSeq(X, Y, m, n): + if (not m): + return n + if (not n): + return m + if (X[m - 1] == Y[n - 1]): + return 1 + superSeq(X, Y, m - 1, n - 1) + return 1 + min(superSeq(X, Y, m - 1, n), + superSeq(X, Y, m, n - 1)) + '''Driver Code''' + +X = ""AGGTAB"" +Y = ""GXTXAYB"" +print(""Length of the shortest supersequence is %d"" + % superSeq(X, Y, len(X), len(Y)))" +Vertical width of Binary tree | Set 1,"/*Java program to print vertical width +of a tree*/ + +import java.util.*; +class GFG +{ +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +}; +static int maximum = 0, minimum = 0; +/*get vertical width*/ + +static void lengthUtil(Node root, int curr) +{ + if (root == null) + return; +/* traverse left*/ + + lengthUtil(root.left, curr - 1); +/* if curr is decrease then get + value in minimum*/ + + if (minimum > curr) + minimum = curr; +/* if curr is increase then get + value in maximum*/ + + if (maximum < curr) + maximum = curr; +/* traverse right*/ + + lengthUtil(root.right, curr + 1); +} +static int getLength(Node root) +{ + maximum = 0; minimum = 0; + lengthUtil(root, 0); +/* 1 is added to include root in the width*/ + + return (Math.abs(minimum) + maximum) + 1; +} +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node curr = new Node(); + curr.data = data; + curr.left = curr.right = null; + return curr; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + System.out.println(getLength(root)); +} +}"," '''Python3 program to prvertical width +of a tree ''' + '''class to create a new tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''get vertical width ''' + +def lengthUtil(root, maximum, minimum, curr = 0): + if (root == None): + return + ''' traverse left ''' + + lengthUtil(root.left, maximum, + minimum, curr - 1) + ''' if curr is decrease then get + value in minimum ''' + + if (minimum[0] > curr): + minimum[0] = curr + ''' if curr is increase then get + value in maximum ''' + + if (maximum[0] < curr): + maximum[0] = curr + ''' traverse right ''' + + lengthUtil(root.right, maximum, + minimum, curr + 1) +def getLength(root): + maximum = [0] + minimum = [0] + lengthUtil(root, maximum, minimum, 0) + ''' 1 is added to include root in the width ''' + + return (abs(minimum[0]) + maximum[0]) + 1 + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(7) + root.left = newNode(6) + root.right = newNode(5) + root.left.left = newNode(4) + root.left.right = newNode(3) + root.right.left = newNode(2) + root.right.right = newNode(1) + print(getLength(root))" +Check if a linked list of strings forms a palindrome,"/*Java Program to check if a given linked list of strings +form a palindrome*/ + + +import java.util.Scanner; + +/*Linked List node*/ + +class Node +{ + String data; + Node next; + + Node(String d) + { + data = d; + next = null; + } +} + + +class LinkedList_Palindrome +{ + Node head; + /* A utility function to check if str is palindrome + or not*/ + + boolean isPalidromeUtil(String str) + { + int length = str.length(); + +/* Match characters from beginning and + end.*/ + + for (int i=0; i key) + root.left = insert(root.left, key); + else if (root.data < key) + root.right = insert(root.right, key); +/* return the (unchanged) Node pointer*/ + + return root; + } + static int count = 0; +/* function return sum of all element smaller than + and equal to Kth smallest element*/ + + static int ksmallestElementSumRec(Node root, int k) + { +/* Base cases*/ + + if (root == null) + return 0; + if (count > k) + return 0; +/* Compute sum of elements in left subtree*/ + + int res = ksmallestElementSumRec(root.left, k); + if (count >= k) + return res; +/* Add root's data*/ + + res += root.data; +/* Add current Node*/ + + count++; + if (count >= k) + return res; +/* If count is less than k, return right subtree Nodes*/ + + return res + ksmallestElementSumRec(root.right, k); + } +/* Wrapper over ksmallestElementSumRec()*/ + + static int ksmallestElementSum(Node root, int k) + { + int res = ksmallestElementSumRec(root, k); + return res; + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + /* 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 + */ + + Node root = null; + root = insert(root, 20); + root = insert(root, 8); + root = insert(root, 4); + root = insert(root, 12); + root = insert(root, 10); + root = insert(root, 14); + root = insert(root, 22); + int k = 3; + int count = ksmallestElementSum(root, k); + System.out.println(count); + } +}"," '''Python3 program to find Sum Of All +Elements smaller than or equal to +Kth Smallest Element In BST''' + +INT_MAX = 2147483647 + '''Binary Tree Node''' + + ''' utility that allocates a newNode +with the given key ''' + +class createNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''A utility function to insert a new +Node with given key in BST and also +maintain lcount ,Sum''' + +def insert(root, key) : + ''' If the tree is empty, return a new Node''' + + if (root == None) : + return createNode(key) + ''' Otherwise, recur down the tree''' + + if (root.data > key) : + root.left = insert(root.left, key) + elif (root.data < key): + root.right = insert(root.right, key) + ''' return the (unchanged) Node pointer''' + + return root + '''function return sum of all element smaller +than and equal to Kth smallest element''' + +def ksmallestElementSumRec(root, k, count) : + ''' Base cases''' + + if (root == None) : + return 0 + if (count[0] > k[0]) : + return 0 + ''' Compute sum of elements in left subtree''' + + res = ksmallestElementSumRec(root.left, k, count) + if (count[0] >= k[0]) : + return res + ''' Add root's data''' + + res += root.data + ''' Add current Node''' + + count[0] += 1 + if (count[0] >= k[0]) : + return res + ''' If count is less than k, return + right subtree Nodes''' + + return res + ksmallestElementSumRec(root.right, + k, count) + '''Wrapper over ksmallestElementSumRec()''' + +def ksmallestElementSum(root, k): + count = [0] + return ksmallestElementSumRec(root, k, count) + '''Driver Code''' + +if __name__ == '__main__': + ''' 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 + ''' + + root = None + root = insert(root, 20) + root = insert(root, 8) + root = insert(root, 4) + root = insert(root, 12) + root = insert(root, 10) + root = insert(root, 14) + root = insert(root, 22) + k = [3] + print(ksmallestElementSum(root, k))" +Index Mapping (or Trivial Hashing) with negatives allowed,"/*Java program to implement direct index +mapping with negative values allowed. */ + +class GFG +{ +final static int MAX = 1000; +/*Since array is global, it +is initialized as 0. */ + +static boolean[][] has = new boolean[MAX + 1][2]; +/*searching if X is Present in +the given array or not. */ + +static boolean search(int X) +{ + if (X >= 0) + { + if (has[X][0] == true) + { + return true; + } + else + { + return false; + } + } +/* if X is negative take the + absolute value of X. */ + + X = Math.abs(X); + if (has[X][1] == true) + { + return true; + } + return false; +} +static void insert(int a[], int n) +{ + for (int i = 0; i < n; i++) + { + if (a[i] >= 0) + { + has[a[i]][0] = true; + } + else + { + has[Math.abs(a[i])][1] = true; + } + } +} +/*Driver code */ + +public static void main(String args[]) +{ + int a[] = {-1, 9, -5, -8, -5, -2}; + int n = a.length; + insert(a, n); + int X = -5; + if (search(X) == true) + { + System.out.println(""Present""); + } + else + { + System.out.println(""Not Present""); + } +} +}"," '''Python3 program to implement direct index +mapping with negative values allowed.''' +MAX = 1000 + '''Since array is global, it +is initialized as 0.''' + +has = [[0 for i in range(2)] + for j in range(MAX + 1)] '''Searching if X is Present in the +given array or not.''' + +def search(X): + if X >= 0: + return has[X][0] == 1 ''' if X is negative take the absolute + value of X.''' + + X = abs(X) + return has[X][1] == 1 +def insert(a, n): + for i in range(0, n): + if a[i] >= 0: + has[a[i]][0] = 1 + else: + has[abs(a[i])][1] = 1 + '''Driver code''' + +if __name__ == ""__main__"": + a = [-1, 9, -5, -8, -5, -2] + n = len(a) + + ''' Since array is global, it is + initialized as 0.''' + + + insert(a, n) + X = -5 + if search(X) == True: + print(""Present"") + else: + print(""Not Present"")" +"Search, insert and delete in an unsorted array","/*Java program to implement insert +operation in an unsorted array.*/ + +class Main +{ +/* Function to insert a given key in + the array. This function returns n+1 + if insertion is successful, else n.*/ + + static int insertSorted(int arr[], int n, + int key, + int capacity) + { +/* Cannot insert more elements if n + is already more than or equal to + capcity*/ + + if (n >= capacity) + return n; + arr[n] = key; + return (n + 1); + } +/* Driver Code*/ + + public static void main (String[] args) + { + int[] arr = new int[20]; + arr[0] = 12; + arr[1] = 16; + arr[2] = 20; + arr[3] = 40; + arr[4] = 50; + arr[5] = 70; + int capacity = 20; + int n = 6; + int i, key = 26; + System.out.print(""Before Insertion: ""); + for (i = 0; i < n; i++) + System.out.print(arr[i]+"" ""); +/* Inserting key*/ + + n = insertSorted(arr, n, key, capacity); + System.out.print(""\n After Insertion: ""); + for (i = 0; i < n; i++) + System.out.print(arr[i]+"" ""); + } +}", +Left Leaning Red Black Tree (Insertion),"/*Java program to implement insert operation +in Red Black Tree.*/ + +class node +{ + node left, right; + int data; +/* red ==> true, black ==> false*/ + + boolean color; + node(int data) + { + this.data = data; + left = null; + right = null; +/* New Node which is created is + always red in color.*/ + + color = true; + } +} +public class LLRBTREE { + private static node root = null; +/* utility function to rotate node anticlockwise.*/ + + node rotateLeft(node myNode) + { + System.out.printf(""left rotation!!\n""); + node child = myNode.right; + node childLeft = child.left; + child.left = myNode; + myNode.right = childLeft; + return child; + } +/* utility function to rotate node clockwise.*/ + + node rotateRight(node myNode) + { + System.out.printf(""right rotation\n""); + node child = myNode.left; + node childRight = child.right; + child.right = myNode; + myNode.left = childRight; + return child; + } +/* utility function to check whether + node is red in color or not.*/ + + boolean isRed(node myNode) + { + if (myNode == null) + return false; + return (myNode.color == true); + } +/* utility function to swap color of two + nodes.*/ + + void swapColors(node node1, node node2) + { + boolean temp = node1.color; + node1.color = node2.color; + node2.color = temp; + } +/* insertion into Left Leaning Red Black Tree.*/ + + node insert(node myNode, int data) + { +/* Normal insertion code for any Binary + Search tree. */ + + if (myNode == null) + return new node(data); + if (data < myNode.data) + myNode.left = insert(myNode.left, data); + else if (data > myNode.data) + myNode.right = insert(myNode.right, data); + else + return myNode; +/* case 1. + when right child is Red but left child is + Black or doesn't exist.*/ + + if (isRed(myNode.right) && !isRed(myNode.left)) + { +/* left rotate the node to make it into + valid structure.*/ + + myNode = rotateLeft(myNode); +/* swap the colors as the child node + should always be red*/ + + swapColors(myNode, myNode.left); + } +/* case 2 + when left child as well as left grand child in Red*/ + + if (isRed(myNode.left) && isRed(myNode.left.left)) + { +/* right rotate the current node to make + it into a valid structure.*/ + + myNode = rotateRight(myNode); + swapColors(myNode, myNode.right); + } +/* case 3 + when both left and right child are Red in color.*/ + + if (isRed(myNode.left) && isRed(myNode.right)) + { +/* invert the color of node as well + it's left and right child.*/ + + myNode.color = !myNode.color; +/* change the color to black.*/ + + myNode.left.color = false; + myNode.right.color = false; + } + return myNode; + } +/* Inorder traversal*/ + + void inorder(node node) + { + if (node != null) + { + inorder(node.left); + System.out.print(node.data + "" ""); + inorder(node.right); + } + } + + /*Driver Code*/ + + public static void main(String[] args) {/* LLRB tree made after all insertions are made. + + 1. Nodes which have double INCOMING edge means + that they are RED in color. + 2. Nodes which have single INCOMING edge means + that they are BLACK in color. + + root + | + 40 + // \ + 20 50 + / \ + 10 30 + // + 25 */ + + LLRBTREE node = new LLRBTREE(); + root = node.insert(root, 10);/* to make sure that root remains + black is color*/ + + root.color = false; + root = node.insert(root, 20); + root.color = false; + root = node.insert(root, 30); + root.color = false; + root = node.insert(root, 40); + root.color = false; + root = node.insert(root, 50); + root.color = false; + root = node.insert(root, 25); + root.color = false; +/* display the tree through inorder traversal.*/ + + node.inorder(root); + } +}", +DFS for a n-ary tree (acyclic graph) represented as adjacency list,"/*JAVA Code For DFS for a n-ary tree (acyclic graph) +represented as adjacency list*/ + +import java.util.*; +class GFG { +/* DFS on tree*/ + + public static void dfs(LinkedList list[], + int node, int arrival) + { +/* Printing traversed node*/ + + System.out.println(node); +/* Traversing adjacent edges*/ + + for (int i = 0; i < list[node].size(); i++) { +/* Not traversing the parent node*/ + + if (list[node].get(i) != arrival) + dfs(list, list[node].get(i), node); + } + } + /* Driver program to test above function */ + + public static void main(String[] args) + { +/* Number of nodes*/ + + int nodes = 5; +/* Adjacency list*/ + + LinkedList list[] = new LinkedList[nodes+1]; + for (int i = 0; i < list.length; i ++){ + list[i] = new LinkedList(); + } +/* Designing the tree*/ + + list[1].add(2); + list[2].add(1); + list[1].add(3); + list[3].add(1); + list[2].add(4); + list[4].add(2); + list[3].add(5); + list[5].add(3); +/* Function call*/ + + dfs(list, 1, 0); + } +}"," '''Python3 code to perform DFS of given tree :''' + + '''DFS on tree ''' + +def dfs(List, node, arrival): ''' Printing traversed node ''' + + print(node) + ''' Traversing adjacent edges''' + + for i in range(len(List[node])): + ''' Not traversing the parent node ''' + + if (List[node][i] != arrival): + dfs(List, List[node][i], node) + '''Driver Code''' + +if __name__ == '__main__': + ''' Number of nodes ''' + + nodes = 5 + ''' Adjacency List ''' + + List = [[] for i in range(10000)] + ''' Designing the tree ''' + + List[1].append(2) + List[2].append(1) + List[1].append(3) + List[3].append(1) + List[2].append(4) + List[4].append(2) + List[3].append(5) + List[5].append(3) + ''' Function call ''' + + dfs(List, 1, 0)" +"Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n","/*Java code to Count Distinct +Non-Negative Integer Pairs +(x, y) that Satisfy the +inequality x*x + y*y < n*/ + +import java.io.*; +class GFG +{ +/* This function counts number + of pairs (x, y) that satisfy + the inequality x*x + y*y < n.*/ + + static int countSolutions(int n) + { + int res = 0; + for (int x = 0; x * x < n; x++) + for (int y = 0; x * x + y * y < n; y++) + res++; + return res; + } +/* Driver program*/ + + public static void main(String args[]) + { + System.out.println ( ""Total Number of distinct Non-Negative pairs is "" + +countSolutions(6)); + } +}"," '''Python3 implementation of above approach''' + + '''This function counts number of pairs +(x, y) that satisfy +the inequality x*x + y*y < n.''' + +def countSolutions(n): + res = 0 + x = 0 + while(x * x < n): + y = 0 + while(x * x + y * y < n): + res = res + 1 + y = y + 1 + x = x + 1 + return res '''Driver program to test above function''' + +if __name__=='__main__': + print(""Total Number of distinct Non-Negative pairs is "", + countSolutions(6))" +Print Postorder traversal from given Inorder and Preorder traversals,"/*Java program to print Postorder traversal from +given Inorder and Preorder traversals.*/ + +import java.util.*; +public class PrintPost { + static int preIndex = 0; + void printPost(int[] in, int[] pre, int inStrt, + int inEnd, HashMap hm) + { + if (inStrt > inEnd) + return; +/* Find index of next item in preorder traversal in + inorder.*/ + + int inIndex = hm.get(pre[preIndex++]); +/* traverse left tree*/ + + printPost(in, pre, inStrt, inIndex - 1, hm); +/* traverse right tree*/ + + printPost(in, pre, inIndex + 1, inEnd, hm); +/* print root node at the end of traversal*/ + + System.out.print(in[inIndex] + "" ""); + } + void printPostMain(int[] in, int[] pre) + { + int n = pre.length; + HashMap hm = new HashMap(); + for (int i=0; i inEnd): + return + ''' Find index of next item in preorder traversal in + inorder.''' + + inIndex = hm[pre[preIndex]] + preIndex += 1 + ''' traverse left tree''' + + printPost(inn, pre, inStrt, inIndex - 1) + ''' traverse right tree''' + + printPost(inn, pre, inIndex + 1, inEnd) + ''' prroot node at the end of traversal''' + + print(inn[inIndex], end = "" "") +def printPostMain(inn, pre, n): + for i in range(n): + hm[inn[i]] = i + printPost(inn, pre, 0, n - 1) + '''Driver code''' + +if __name__ == '__main__': + hm = {} + preIndex = 0 + inn = [4, 2, 5, 1, 3, 6] + pre = [1, 2, 4, 5, 3, 6] + n = len(pre) + printPostMain(inn, pre, n)" +Find postorder traversal of BST from preorder traversal,"/* run loop from 1 to length of pre*/ +import java.io.*; +class GFG { + public void getPostOrderBST(int pre[]) + { + int pivotPoint = 0; +/* print from pivot length -1 to zero*/ + + for (int i = 1; i < pre.length; i++) + { + if (pre[0] <= pre[i]) + { + pivotPoint = i; + break; + } + } +/* print from end to pivot length*/ + + for (int i = pivotPoint - 1; i > 0; i--) + { + System.out.print(pre[i] + "" ""); + } +/* Driver Code*/ + + for (int i = pre.length - 1; i >= pivotPoint; i--) + { + System.out.print(pre[i] + "" ""); + } + System.out.print(pre[0]); + } +"," ''' Run loop from 1 to length of pre''' +def getPostOrderBST(pre, N): + pivotPoint = 0 + ''' Prfrom pivot length -1 to zero''' + + for i in range(1, N): + if (pre[0] <= pre[i]): + pivotPoint= i + break + ''' Prfrom end to pivot length''' + + for i in range(pivotPoint - 1, 0, -1): + print(pre[i], end = "" "") + '''Driver Code''' + + for i in range(N - 1, pivotPoint - 1, -1): + print(pre[i], end = "" "") + print(pre[0]) +" +Find the maximum path sum between two leaves of a binary tree,"/*Java program to find maximum path sum between two leaves +of a binary tree*/ + + +/*A binary tree node*/ + +class Node { + int data; + Node left, right; + Node(int item) { + data = item; + left = right = null; + } +}/*An object of Res is passed around so that the +same value can be used by multiple recursive calls.*/ + +class Res { + int val; +} +class BinaryTree { + static Node root; +/* A utility function to find the maximum sum between any + two leaves.This function calculates two values: + 1) Maximum path sum between two leaves which is stored + in res. + 2) The maximum root to leaf path sum which is returned. + If one side of root is empty, then it returns INT_MIN*/ + + int maxPathSumUtil(Node node, Res res) { +/* Base cases*/ + + if (node == null) + return 0; + if (node.left == null && node.right == null) + return node.data; +/* Find maximum sum in left and right subtree. Also + find maximum root to leaf sums in left and right + subtrees and store them in ls and rs*/ + + int ls = maxPathSumUtil(node.left, res); + int rs = maxPathSumUtil(node.right, res); +/* If both left and right children exist*/ + + if (node.left != null && node.right != null) { +/* Update result if needed*/ + + res.val = Math.max(res.val, ls + rs + node.data); +/* Return maxium possible value for root being + on one side*/ + + return Math.max(ls, rs) + node.data; + } +/* If any of the two children is empty, return + root sum for root being on one side*/ + + return (node.left == null) ? rs + node.data + : ls + node.data; + } +/* The main function which returns sum of the maximum + sum path between two leaves. This function mainly + uses maxPathSumUtil()*/ + + int maxPathSum(Node node) + { + Res res = new Res(); + res.val = Integer.MIN_VALUE; + maxPathSumUtil(root, res); + return res.val; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(-15); + tree.root.left = new Node(5); + tree.root.right = new Node(6); + tree.root.left.left = new Node(-8); + tree.root.left.right = new Node(1); + tree.root.left.left.left = new Node(2); + tree.root.left.left.right = new Node(6); + tree.root.right.left = new Node(3); + tree.root.right.right = new Node(9); + tree.root.right.right.right = new Node(0); + tree.root.right.right.right.left = new Node(4); + tree.root.right.right.right.right = new Node(-1); + tree.root.right.right.right.right.left = new Node(10); + System.out.println(""Max pathSum of the given binary tree is "" + + tree.maxPathSum(root)); + } +}"," '''Python program to find maximumpath sum between two leaves +of a binary tree''' + +INT_MIN = -2**32 + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Utility function to find maximum sum between any +two leaves. This function calculates two values: +1) Maximum path sum between two leaves which are stored + in res +2) The maximum root to leaf path sum which is returned +If one side of root is empty, then it returns INT_MIN''' + +def maxPathSumUtil(root, res): + ''' Base Case''' + + if root is None: + return 0 + ''' Find maximumsum in left and righ subtree. Also + find maximum root to leaf sums in left and righ + subtrees ans store them in ls and rs''' + + ls = maxPathSumUtil(root.left, res) + rs = maxPathSumUtil(root.right, res) + ''' If both left and right children exist''' + + if root.left is not None and root.right is not None: + ''' update result if needed''' + + res[0] = max(res[0], ls + rs + root.data) + ''' Return maximum possible value for root being + on one side''' + + return max(ls, rs) + root.data + ''' If any of the two children is empty, return + root sum for root being on one side''' + + if root.left is None: + return rs + root.data + else: + return ls + root.data + '''The main function which returns sum of the maximum +sum path betwee ntwo leaves. THis function mainly +uses maxPathSumUtil()''' + +def maxPathSum(root): + res = [INT_MIN] + maxPathSumUtil(root, res) + return res[0] + '''Driver program to test above function''' + +root = Node(-15) +root.left = Node(5) +root.right = Node(6) +root.left.left = Node(-8) +root.left.right = Node(1) +root.left.left.left = Node(2) +root.left.left.right = Node(6) +root.right.left = Node(3) +root.right.right = Node(9) +root.right.right.right = Node(0) +root.right.right.right.left = Node(4) +root.right.right.right.right = Node(-1) +root.right.right.right.right.left = Node(10) +print ""Max pathSum of the given binary tree is"", maxPathSum(root)" +Minimum adjacent swaps required to Sort Binary array,"/*Java code to find minimum number of +swaps to sort a binary array*/ + +class gfg { +/*Function to find minimum swaps to +sort an array of 0s and 1s.*/ + + + static int findMinSwaps(int arr[], int n) + { +/* Array to store count of zeroes*/ + + int noOfZeroes[] = new int[n]; + int i, count = 0; + +/* Count number of zeroes + on right side of every one.*/ + + noOfZeroes[n - 1] = 1 - arr[n - 1]; + for (i = n - 2; i >= 0; i--) + { + noOfZeroes[i] = noOfZeroes[i + 1]; + if (arr[i] == 0) + noOfZeroes[i]++; + } + +/* Count total number of swaps by adding number + of zeroes on right side of every one.*/ + + for (i = 0; i < n; i++) + { + if (arr[i] == 1) + count += noOfZeroes[i]; + } + return count; + } + +/* Driver Code*/ + + public static void main(String args[]) + { + int ar[] = { 0, 0, 1, 0, 1, 0, 1, 1 }; + System.out.println(findMinSwaps(ar, ar.length)); + } +} + + +"," '''Python3 code to find minimum number of +swaps to sort a binary array''' + + + '''Function to find minimum swaps to +sort an array of 0s and 1s.''' + +def findMinSwaps(arr, n) : + ''' Array to store count of zeroes''' + + noOfZeroes = [0] * n + count = 0 + + ''' Count number of zeroes + on right side of every one.''' + + noOfZeroes[n - 1] = 1 - arr[n - 1] + for i in range(n-2, -1, -1) : + noOfZeroes[i] = noOfZeroes[i + 1] + if (arr[i] == 0) : + noOfZeroes[i] = noOfZeroes[i] + 1 + + ''' Count total number of swaps by adding + number of zeroes on right side of + every one.''' + + for i in range(0, n) : + if (arr[i] == 1) : + count = count + noOfZeroes[i] + + return count + + '''Driver code''' + +arr = [ 0, 0, 1, 0, 1, 0, 1, 1 ] +n = len(arr) +print (findMinSwaps(arr, n)) + + +" +The Celebrity Problem,"/*Java program to find celebrity*/ + +import java.util.*; +class GFG { +/* Max # of persons in the party*/ + + static final int N = 8; +/* Person with 2 is celebrity*/ + + static int MATRIX[][] = { { 0, 0, 1, 0 }, + { 0, 0, 1, 0 }, + { 0, 0, 0, 0 }, + { 0, 0, 1, 0 } }; + static int knows(int a, int b) { return MATRIX[a][b]; } +/* Returns -1 if celebrity + is not present. If present, + returns id (value from 0 to n-1).*/ + + static int findCelebrity(int n) + { +/* the graph needs not be constructed + as the edges can be found by + using knows function + degree array;*/ + + int[] indegree = new int[n]; + int[] outdegree = new int[n]; +/* query for all edges*/ + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + int x = knows(i, j); +/* set the degrees*/ + + outdegree[i] += x; + indegree[j] += x; + } + } +/* find a person with indegree n-1 + and out degree 0*/ + + for (int i = 0; i < n; i++) + if (indegree[i] == n - 1 && outdegree[i] == 0) + return i; + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + int n = 4; + int id = findCelebrity(n); + if (id == -1) + System.out.print(""No celebrity""); + else + System.out.print(""Celebrity ID "" + id); + } +}"," '''Python3 program to find celebrity +of persons in the party''' + + '''Max''' +N = 8 '''Person with 2 is celebrity''' + +MATRIX = [ [ 0, 0, 1, 0 ], + [ 0, 0, 1, 0 ], + [ 0, 0, 0, 0 ], + [ 0, 0, 1, 0 ] ] +def knows(a, b): + return MATRIX[a][b] + ''' Returns -1 if celebrity + is not present. If present, + returns id (value from 0 to n-1)''' + +def findCelebrity(n): ''' The graph needs not be constructed + as the edges can be found by + using knows function + degree array;''' + + indegree = [0 for x in range(n)] + outdegree = [0 for x in range(n)] + ''' Query for all edges''' + + for i in range(n): + for j in range(n): + x = knows(i, j) + ''' Set the degrees''' + + outdegree[i] += x + indegree[j] += x + ''' Find a person with indegree n-1 + and out degree 0''' + + for i in range(n): + if (indegree[i] == n - 1 and + outdegree[i] == 0): + return i + return -1 + '''Driver code ''' + +if __name__ == '__main__': + n = 4 + id_ = findCelebrity(n) + if id_ == -1: + print(""No celebrity"") + else: + print(""Celebrity ID"", id_)" +"Given two unsorted arrays, find all pairs whose sum is x","/*Java program to find all pairs in both arrays +whose sum is equal to given value x*/ + +import java.io.*; +class GFG { +/* Function to print all pairs in both arrays + whose sum is equal to given value x*/ + + static void findPairs(int arr1[], int arr2[], int n, + int m, int x) + { + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (arr1[i] + arr2[j] == x) + System.out.println(arr1[i] + "" "" + + arr2[j]); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr1[] = { 1, 2, 3, 7, 5, 4 }; + int arr2[] = { 0, 7, 4, 3, 2, 1 }; + int x = 8; + findPairs(arr1, arr2, arr1.length, arr2.length, x); + } +}"," '''Python 3 program to find all +pairs in both arrays whose +sum is equal to given value x + ''' '''Function to print all pairs +in both arrays whose sum is +equal to given value x''' + +def findPairs(arr1, arr2, n, m, x): + for i in range(0, n): + for j in range(0, m): + if (arr1[i] + arr2[j] == x): + print(arr1[i], arr2[j]) + '''Driver code''' + +arr1 = [1, 2, 3, 7, 5, 4] +arr2 = [0, 7, 4, 3, 2, 1] +n = len(arr1) +m = len(arr2) +x = 8 +findPairs(arr1, arr2, n, m, x)" +Replace every matrix element with maximum of GCD of row or column,"/*Java program to replace each each element with +maximum of GCD of row or column.*/ + +import java .io.*; +class GFG +{ + static int R = 3; + static int C = 4; +/* returning the greatest common + divisor of two number*/ + + static int gcd(int a, int b) + { + if (b == 0) + return a; + return gcd(b, a%b); + } +/*Finding GCD of each row and column and +replacing with each element with maximum +of GCD of row or column.*/ + +static void replacematrix(int [][]mat, int n, int m) +{ + int []rgcd = new int[R] ; + int []cgcd = new int[C]; +/* Calculating GCD of each row and each column in + O(mn) and store in arrays.*/ + + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + rgcd[i] = gcd(rgcd[i], mat[i][j]); + cgcd[j] = gcd(cgcd[j], mat[i][j]); + } + } +/* Replacing matrix element*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + mat[i][j] = Math.max(rgcd[i], cgcd[j]); +} +/*Driver program*/ + + static public void main (String[] args){ + int [][]m = + { + {1, 2, 3, 3}, + {4, 5, 6, 6}, + {7, 8, 9, 9}, + }; + replacematrix(m, R, C); + for (int i = 0; i < R; i++) + { + for (int j = 0; j < C; j++) + System.out.print(m[i][j] + "" ""); + System.out.println(); + } + } +}"," '''Python3 program to replace each each element +with maximum of GCD of row or column.''' + +R = 3 +C = 4 + '''returning the greatest common +divisor of two number''' + +def gcd(a, b): + if (b == 0): + return a + return gcd(b, a % b) + '''Finding GCD of each row and column +and replacing with each element with +maximum of GCD of row or column.''' + +def replacematrix(mat, n, m): + rgcd = [0] * R + cgcd = [0] * C + ''' Calculating GCD of each row and each + column in O(mn) and store in arrays.''' + + for i in range (n): + for j in range (m): + rgcd[i] = gcd(rgcd[i], mat[i][j]) + cgcd[j] = gcd(cgcd[j], mat[i][j]) + ''' Replacing matrix element''' + + for i in range (n): + for j in range (m): + mat[i][j] = max(rgcd[i], cgcd[j]) + '''Driver Code''' + +if __name__ == ""__main__"": + m = [[1, 2, 3, 3], + [4, 5, 6, 6], + [7, 8, 9, 9]] + replacematrix(m, R, C) + for i in range(R): + for j in range (C): + print ( m[i][j], end = "" "") + print ()" +Write a Program to Find the Maximum Depth or Height of a Tree,"/*Java program to find height of tree*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* Compute the ""maxDepth"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + + int maxDepth(Node node) + { + if (node == null) + return 0; + else + { + /* compute the depth of each subtree */ + + int lDepth = maxDepth(node.left); + int rDepth = maxDepth(node.right); + /* use the larger one */ + + if (lDepth > rDepth) + return (lDepth + 1); + else + return (rDepth + 1); + } + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println(""Height of tree is : "" + + tree.maxDepth(tree.root)); + } +}"," '''Python3 program to find the maximum depth of tree''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Compute the ""maxDepth"" of a tree -- the number of nodes +along the longest path from the root node down to the +farthest leaf node''' + +def maxDepth(node): + if node is None: + return 0 ; + else : + ''' Compute the depth of each subtree''' + + lDepth = maxDepth(node.left) + rDepth = maxDepth(node.right) + ''' Use the larger one''' + + if (lDepth > rDepth): + return lDepth+1 + else: + return rDepth+1 + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +print (""Height of tree is %d"" %(maxDepth(root)))" +Longest Consecutive Subsequence,"/*Java program to find longest +consecutive subsequence*/ + +import java.io.*; +import java.util.*; +class ArrayElements { +/* Returns length of the longest + consecutive subsequence*/ + + static int findLongestConseqSubseq(int arr[], int n) + { + HashSet S = new HashSet(); + int ans = 0; +/* Hash all the array elements*/ + + for (int i = 0; i < n; ++i) + S.add(arr[i]); +/* check each possible sequence from the start + then update optimal length*/ + + for (int i = 0; i < n; ++i) + { +/* if current element is the starting + element of a sequence*/ + + if (!S.contains(arr[i] - 1)) + { +/* Then check for next elements + in the sequence*/ + + int j = arr[i]; + while (S.contains(j)) + j++; +/* update optimal length if this + length is more*/ + + if (ans < j - arr[i]) + ans = j - arr[i]; + } + } + return ans; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; + int n = arr.length; + System.out.println( + ""Length of the Longest consecutive subsequence is "" + + findLongestConseqSubseq(arr, n)); + } +}"," '''Python program to find longest contiguous subsequence''' + +from sets import Set +def findLongestConseqSubseq(arr, n): + s = Set() + ans = 0 + ''' Hash all the array elements''' + + for ele in arr: + s.add(ele) + ''' check each possible sequence from the start + then update optimal length''' + + for i in range(n): + ''' if current element is the starting + element of a sequence''' + + if (arr[i]-1) not in s: + ''' Then check for next elements in the + sequence''' + + j = arr[i] + while(j in s): + j += 1 + ''' update optimal length if this length + is more''' + + ans = max(ans, j-arr[i]) + return ans + '''Driver code''' + +if __name__ == '__main__': + n = 7 + arr = [1, 9, 3, 10, 4, 20, 2] + print ""Length of the Longest contiguous subsequence is "", + print findLongestConseqSubseq(arr, n) +" +Number of loops of size k starting from a specific node,"/*Java Program to find number of +cycles of length k in a graph +with n nodes.*/ + +public class GFG { +/* Return the Number of ways + from a node to make a loop + of size K in undirected + complete connected graph of + N nodes*/ + + static int numOfways(int n, int k) + { + int p = 1; + if (k % 2 != 0) + p = -1; + return (int)(Math.pow(n - 1, k) + + p * (n - 1)) / n; + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 4, k = 2; + System.out.println(numOfways(n, k)); + } +}"," '''python Program to find number of +cycles of length k in a graph +with n nodes.''' + + '''Return the Number of ways from a +node to make a loop of size K in +undirected complete connected +graph of N nodes''' + +def numOfways(n,k): + p = 1 + if (k % 2): + p = -1 + return (pow(n - 1, k) + + p * (n - 1)) / n '''Driver code''' + +n = 4 +k = 2 +print (numOfways(n, k))" +Split the array and add the first part to the end | Set 2,"/*Java program to Split the array and +add the first part to the end*/ + +class Geeks +{ + +/* Function to reverse arr[] from index start to end*/ + +static void rvereseArray(int arr[], int start, int end) +{ + while (start < end) { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } +} + +/*Function to print an array*/ + +static void printArray(int arr[], int size) +{ + for (int i = 0; i < size; i++) + System.out.print(arr[i] +"" ""); +} + +/* Function to left rotate arr[] of size n by k */ + +static 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); +} + +/* Driver program to test above functions */ + +public static void main(String args[]) +{ + int arr[] = { 12, 10, 5, 6, 52, 36 }; + int n = arr.length; + int k = 2; + +/* Function calling*/ + + splitArr(arr, k, n); + printArray(arr, n); + +} + +} + + +"," '''Python3 program to Split the array +and add the first part to the end''' + + + '''Function to reverse arr[] +from index start to end*/''' + +def rvereseArray(arr, start, end): + while start < end : + temp = arr[start] + arr[start] = arr[end] + arr[end] =temp + start += 1 + end -= 1 + + '''Function to print an array''' + +def printArray(arr, n) : + for i in range(n): + print(arr[i], end = "" "") + + + '''Function to left rotate +arr[] of size n by k */''' + +def splitArr(arr, k, n): + rvereseArray(arr, 0, n - 1) + rvereseArray(arr, 0, n - k - 1) + rvereseArray(arr, n - k, n - 1) + + '''Driver Code''' + +arr = [12, 10, 5, 6, 52, 36] +n = len(arr) +k = 2 + + ''' Function calling''' + + +splitArr(arr, k, n) +printArray(arr, n) + " +Kth ancestor of a node in binary tree | Set 2,"/*Java program to calculate Kth ancestor of given node */ + +class Solution +{ +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*temporary node to keep track of Node returned +from previous recursive call during backtrack*/ + +static Node temp = null; +static int k; +/*recursive function to calculate Kth ancestor*/ + +static Node kthAncestorDFS(Node root, int node ) +{ +/* Base case*/ + + if (root == null) + return null; + if (root.data == node|| + (temp = kthAncestorDFS(root.left,node)) != null || + (temp = kthAncestorDFS(root.right,node)) != null) + { + if (k > 0) + k--; + else if (k == 0) + { +/* print the kth ancestor*/ + + System.out.print(""Kth ancestor is: ""+root.data); +/* return null to stop further backtracking*/ + + return null; + } +/* return current node to previous call*/ + + return root; + } + return null; +} +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver code*/ + +public static void main(String args[]) +{ + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + k = 2; + int node = 5;/* print kth ancestor of given node*/ + + Node parent = kthAncestorDFS(root,node); +/* check if parent is not null, it means + there is no Kth ancestor of the node*/ + + if (parent != null) + System.out.println(""-1""); +} +}"," ''' Python3 program to calculate Kth + ancestor of given node ''' + + '''A Binary Tree Node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''recursive function to calculate +Kth ancestor ''' + +def kthAncestorDFS(root, node, k): + ''' Base case ''' + + if (not root): + return None + if (root.data == node or + (kthAncestorDFS(root.left, node, k)) or + (kthAncestorDFS(root.right, node, k))): + if (k[0] > 0): + k[0] -= 1 + elif (k[0] == 0): + ''' print the kth ancestor ''' + + print(""Kth ancestor is:"", root.data) + ''' return None to stop further + backtracking ''' + + return None + ''' return current node to previous call ''' + + return root + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + k = [2] + node = 5 + ''' prkth ancestor of given node ''' + + parent = kthAncestorDFS(root,node,k) + ''' check if parent is not None, it means + there is no Kth ancestor of the node ''' + + if (parent): + print(""-1"")" +Delete consecutive same words in a sequence,"/* Java implementation of above method*/ + +import java.util.Stack; +import java.util.Vector; +class Test +{ +/* Method to find the size of manipulated sequence*/ + + static int removeConsecutiveSame(Vector v) + { + Stack st = new Stack<>(); +/* Start traversing the sequence*/ + + for (int i=0; i v = new Vector<>(); + v.addElement(""ab""); v.addElement(""aa""); + v.addElement(""aa"");v.addElement(""bcd""); + v.addElement(""ab""); + System.out.println(removeConsecutiveSame(v)); + } +}"," '''Python implementation of above method + ''' '''Function to find the size of manipulated sequence ''' + +def removeConsecutiveSame(v): + st = [] + ''' Start traversing the sequence''' + + for i in range(len(v)): + ''' Push the current string if the stack + is empty ''' + + if (len(st) == 0): + st.append(v[i]) + else: + Str = st[-1] + ''' compare the current string with stack top + if equal, pop the top ''' + + if (Str == v[i]): + st.pop() + ''' Otherwise push the current string ''' + + else: + st.append(v[i]) + ''' Return stack size ''' + + return len(st) + '''Driver code ''' + +if __name__ == '__main__': + V = [ ""ab"", ""aa"", ""aa"", ""bcd"", ""ab""] + print(removeConsecutiveSame(V))" +Count subsets having distinct even numbers,"/*Java implementation to count subsets having +even numbers only and all are distinct*/ + +import java.util.*; +class GFG +{ +/*function to count the +required subsets*/ + +static int countSubsets(int arr[], int n) +{ + HashSet us = new HashSet<>(); + int even_count = 0; +/* inserting even numbers in the set 'us' + single copy of each number is retained*/ + + for (int i = 0; i < n; i++) + if (arr[i] % 2 == 0) + us.add(arr[i]); +/* counting distinct even numbers*/ + + even_count=us.size(); +/* total count of required subsets*/ + + return (int) (Math.pow(2, even_count) - 1); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {4, 2, 1, 9, 2, 6, 5, 3}; + int n = arr.length; + System.out.println(""Number of subsets = "" + + countSubsets(arr, n)); +} +}"," '''python implementation to count subsets having +even numbers only and all are distinct + ''' '''function to count the required subsets ''' + +def countSubSets(arr, n): + us = set() + even_count = 0 + ''' inserting even numbers in the set 'us' + single copy of each number is retained ''' + + for i in range(n): + if arr[i] % 2 == 0: + us.add(arr[i]) + ''' counting distinct even numbers ''' + + even_count = len(us) + ''' total count of required subsets ''' + + return pow(2, even_count)- 1 + '''Driver program''' + +arr = [4, 2, 1, 9, 2, 6, 5, 3] +n = len(arr) +print(""Numbers of subset="", countSubSets(arr,n))" +Remove all Fibonacci Nodes from a Circular Singly Linked List,"/*Java program to delete all the +Fibonacci nodes from the +circular singly linked list*/ + +import java.util.*; + +class GFG{ + +/*Structure for a node*/ + +static class Node { + int data; + Node next; +}; + +/*Function to insert a node at the beginning +of a Circular linked list*/ + +static Node push(Node head_ref, int data) +{ +/* Create a new node and make head as next + of it.*/ + + Node ptr1 = new Node(); + Node temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + +/* If linked list is not null then + set the next of last node*/ + + if (head_ref != null) { + +/* Find the node before head + and update next of it.*/ + + while (temp.next != head_ref) + temp = temp.next; + + temp.next = ptr1; + } + else + +/* Point for the first node*/ + + ptr1.next = ptr1; + + head_ref = ptr1; + return head_ref; +} + +/*Delete the node from a Circular Linked list*/ + +static void deleteNode(Node head_ref, Node del) +{ + Node temp = head_ref; + +/* If node to be deleted is head node*/ + + if (head_ref == del) + head_ref = del.next; + +/* Traverse list till not found + delete node*/ + + while (temp.next != del) { + temp = temp.next; + } + +/* Copy the address of the node*/ + + temp.next = del.next; + +/* Finally, free the memory + occupied by del*/ + + del = null; + + return; +} + +/*Function to find the maximum +node of the circular linked list*/ + +static int largestElement(Node head_ref) +{ +/* Pointer for traversing*/ + + Node current; + +/* Initialize head to the current pointer*/ + + current = head_ref; + +/* Initialize min int value to max*/ + + int maxEle = Integer.MIN_VALUE; + +/* While the last node is not reached*/ + + do { + +/* If current node data is + greater for max then replace it*/ + + if (current.data > maxEle) { + maxEle = current.data; + } + + current = current.next; + } while (current != head_ref); + + return maxEle; +} + +/*Function to create hash table to +check Fibonacci numbers*/ + +static void createHash(HashSet hash, + int maxElement) +{ + int prev = 0, curr = 1; + +/* Adding the first two elements + to the hash*/ + + hash.add(prev); + hash.add(curr); + +/* Inserting the Fibonacci numbers + into the hash*/ + + while (curr <= maxElement) { + int temp = curr + prev; + hash.add(temp); + prev = curr; + curr = temp; + } +} + +/*Function to delete all the Fibonacci nodes +from the singly circular linked list*/ + +static void deleteFibonacciNodes(Node head) +{ +/* Find the largest node value + in Circular Linked List*/ + + int maxEle = largestElement(head); + +/* Creating a hash containing + all the Fibonacci numbers + upto the maximum data value + in the circular linked list*/ + + HashSet hash = new HashSet(); + createHash(hash, maxEle); + + Node ptr = head; + + Node next; + +/* Traverse the list till the end*/ + + do { + +/* If the node's data is Fibonacci, + delete node 'ptr'*/ + + if (hash.contains(ptr.data)) + deleteNode(head, ptr); + +/* Point to the next node*/ + + next = ptr.next; + ptr = next; + + } while (ptr != head); +} + +/*Function to print nodes in a +given Circular linked list*/ + +static void printList(Node head) +{ + Node temp = head; + if (head != null) { + do { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } while (temp != head); + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ +/* Initialize lists as empty*/ + + Node head = null; + +/* Created linked list will be + 9.11.34.6.13.20*/ + + head = push(head, 20); + head = push(head, 13); + head = push(head, 6); + head = push(head, 34); + head = push(head, 11); + head = push(head, 9); + + deleteFibonacciNodes(head); + + printList(head); +} +} + + +"," '''Python3 program to delete all the +Fibonacci nodes from the +circular singly linked list''' + + + '''Structure for a node''' + +class Node: + + def __init__(self): + self.data = 0 + self.next = None + + '''Function to add a node at the beginning +of a Circular linked list''' + +def push(head_ref, data): + + ''' Create a new node and make head as next + of it.''' + + ptr1 = Node() + temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + + ''' If linked list is not None then + set the next of last node''' + + if (head_ref != None): + + ''' Find the node before head + and update next of it.''' + + while (temp.next != head_ref): + temp = temp.next; + + temp.next = ptr1; + + else: + + ''' Point for the first node''' + + ptr1.next = ptr1; + + head_ref = ptr1; + + return head_ref + + '''Delete the node from a Circular Linked list''' + +def deleteNode( head_ref, delt): + + temp = head_ref; + + ''' If node to be deleted is head node''' + + if (head_ref == delt): + head_ref = delt.next; + + ''' Traverse list till not found + delete node''' + + while (temp.next != delt): + temp = temp.next; + + ''' Copy the address of the node''' + + temp.next = delt.next; + + ''' Finally, free the memory + occupied by delt''' + + del(delt); + + return; + + '''Function to find the maximum +node of the circular linked list''' + +def largestElement( head_ref): + + ''' Pointer for traversing''' + + current = None + + ''' Initialize head to the current pointer''' + + current = head_ref; + + ''' Initialize min value to max''' + + maxEle = -10000000 + + ''' While the last node is not reached''' + + while(True): + + ''' If current node data is + greater for max then replace it''' + + if (current.data > maxEle): + maxEle = current.data; + + current = current.next; + + if(current == head_ref): + break + + return maxEle; + + '''Function to create hashmap table to +check Fibonacci numbers''' + +def createHash(hashmap, maxElement): + + prev = 0 + curr = 1; + + ''' Adding the first two elements + to the hashmap''' + + hashmap.add(prev); + hashmap.add(curr); + + ''' Inserting the Fibonacci numbers + into the hashmap''' + + while (curr <= maxElement): + temp = curr + prev; + hashmap.add(temp); + prev = curr; + curr = temp; + + '''Function to delete all the Fibonacci nodes +from the singly circular linked list''' + +def deleteFibonacciNodes( head): + + ''' Find the largest node value + in Circular Linked List''' + + maxEle = largestElement(head); + + ''' Creating a hashmap containing + all the Fibonacci numbers + upto the maximum data value + in the circular linked list''' + + hashmap = set() + createHash(hashmap, maxEle); + + ptr = head; + + next = None + + ''' Traverse the list till the end''' + + while(True): + + ''' If the node's data is Fibonacci, + delete node 'ptr''' + ''' + if (ptr.data in hashmap): + deleteNode(head, ptr); + + ''' Point to the next node''' + + next = ptr.next; + ptr = next; + + if(ptr == head): + break + + '''Function to print nodes in a +given Circular linked list''' + +def printList( head): + + temp = head; + if (head != None): + + while(True): + + print(temp.data, end = ' ') + temp = temp.next + + if(temp == head): + break + + '''Driver code''' + +if __name__=='__main__': + + ''' Initialize lists as empty''' + + head = None; + + ''' Created linked list will be + 9.11.34.6.13.20''' + + head = push(head, 20); + head = push(head, 13); + head = push(head, 6); + head = push(head, 34); + head = push(head, 11); + head = push(head, 9); + + deleteFibonacciNodes(head); + + printList(head); + + +" +Find the two repeating elements in a given array,"class RepeatElement +{ +/*Function*/ + + void printRepeating(int arr[], int size) + { + int count[] = new int[size]; + int i; + System.out.println(""Repeated elements are : ""); + for (i = 0; i < size; i++) + { + if (count[arr[i]] == 1) + System.out.print(arr[i] + "" ""); + else + count[arr[i]]++; + } + } +/*Driver code*/ + + public static void main(String[] args) + { + RepeatElement repeat = new RepeatElement(); + int arr[] = {4, 2, 4, 5, 2, 3, 1}; + int arr_size = arr.length; + repeat.printRepeating(arr, arr_size); + } +}"," '''Python3 code for Find the two repeating +elements in a given array''' + + + '''Function''' + +def printRepeating(arr,size) : + count = [0] * size + print("" Repeating elements are "",end = """") + for i in range(0, size) : + if(count[arr[i]] == 1) : + print(arr[i], end = "" "") + else : + count[arr[i]] = count[arr[i]] + 1 '''Driver code''' + +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size)" +Maximum spiral sum in Binary Tree,"/*Java implementation to find maximum spiral sum*/ + +import java.util.ArrayList; +import java.util.Stack; +public class MaxSpiralSum { +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data ; + Node left, right ; + Node(int data) + { + this.data=data; + left=right=null; + } +};/* function to find the maximum sum contiguous subarray. + implements kadane's algorithm */ + + static int maxSum(ArrayList arr) + { +/* to store the maximum value that is ending + up to the current index */ + + int max_ending_here = Integer.MIN_VALUE; +/* to store the maximum value encountered so far */ + + int max_so_far = Integer.MIN_VALUE; +/* traverse the array elements */ + + for (int i = 0; i < arr.size(); i++) + { +/* if max_ending_here < 0, then it could + not possibly contribute to the maximum + sum further */ + + if (max_ending_here < 0) + max_ending_here = arr.get(i); +/* else add the value arr[i] to max_ending_here */ + + else + max_ending_here +=arr.get(i); +/* update max_so_far */ + + max_so_far = Math.max(max_so_far, max_ending_here); + } +/* required maxium sum contiguous subarray value */ + + return max_so_far; + } +/* Function to find maximum spiral sum */ + + public static int maxSpiralSum(Node root) + { +/* if tree is empty */ + + if (root == null) + return 0; +/* Create two stacks to store alternate levels +For levels from right to left */ + +Stack s1=new Stack<>(); +/*For levels from left to right */ + +Stack s2=new Stack<>(); +/* ArrayList to store spiral order traversal + of the binary tree */ + + ArrayList arr=new ArrayList<>(); +/* Push first level to first stack 's1' */ + + s1.push(root); +/* traversing tree in spiral form until + there are elements in any one of the + stacks */ + + while (!s1.isEmpty() || !s2.isEmpty()) + { +/* traverse current level from s1 and + push nodes of next level to s2 */ + + while (!s1.isEmpty()) + { + Node temp = s1.pop(); +/* push temp-data to 'arr' */ + + arr.add(temp.data); +/* Note that right is pushed before left */ + + if (temp.right!=null) + s2.push(temp.right); + if (temp.left!=null) + s2.push(temp.left); + } +/* traverse current level from s2 and + push nodes of next level to s1 */ + + while (!s2.isEmpty()) + { + Node temp = s2.pop(); +/* push temp-data to 'arr' */ + + arr.add(temp.data); +/* Note that left is pushed before right */ + + if (temp.left!=null) + s1.push(temp.left); + if (temp.right!=null) + s1.push(temp.right); + } + } +/* required maximum spiral sum */ + + return maxSum(arr); + } +/*Driver program to test above*/ + + public static void main(String args[]) { + Node root = new Node(-2); + root.left = new Node(-3); + root.right = new Node(4); + root.left.left = new Node(5); + root.left.right = new Node(1); + root.right.left = new Node(-2); + root.right.right = new Node(-1); + root.left.left.left = new Node(-3); + root.right.right.right = new Node(2); + System.out.print(""Maximum Spiral Sum = ""+maxSpiralSum(root)); + } +} +", +Queries for GCD of all numbers of an array except elements in a given range,"/*Java program for queries of GCD excluding +given range of elements.*/ + +import java.util.*; +class GFG { +/*Calculating GCD using euclid algorithm*/ + +static int GCD(int a, int b) +{ + if (b == 0) + return a; + return GCD(b, a % b); +} +/*Filling the prefix and suffix array*/ + +static void FillPrefixSuffix(int prefix[], + int arr[], int suffix[], int n) +{ +/* Filling the prefix array following relation + prefix(i) = GCD(prefix(i-1), arr(i))*/ + + prefix[0] = arr[0]; + for (int i = 1; i < n; i++) + prefix[i] = GCD(prefix[i - 1], arr[i]); +/* Filling the suffix array following the + relation suffix(i) = GCD(suffix(i+1), arr(i))*/ + + suffix[n - 1] = arr[n - 1]; + for (int i = n - 2; i >= 0; i--) + suffix[i] = GCD(suffix[i + 1], arr[i]); +} +/*To calculate gcd of the numbers outside range*/ + +static int GCDoutsideRange(int l, int r, + int prefix[], int suffix[], int n) { +/* If l=0, we need to tell GCD of numbers + from r+1 to n*/ + + if (l == 0) + return suffix[r + 1]; +/* If r=n-1 we need to return the gcd of + numbers from 1 to l*/ + + if (r == n - 1) + return prefix[l - 1]; + return GCD(prefix[l - 1], suffix[r + 1]); +} +/*Driver code*/ + +public static void main(String[] args) { + int arr[] = {2, 6, 9}; + int n = arr.length; + int prefix[] = new int[n]; + int suffix[] = new int[n]; + FillPrefixSuffix(prefix, arr, suffix, n); + int l = 0, r = 0; + System.out.println(GCDoutsideRange + (l, r, prefix, suffix, n)); + l = 1; + r = 1; + System.out.println(GCDoutsideRange + (l, r, prefix, suffix, n)); + l = 1; + r = 2; + System.out.println(GCDoutsideRange + (l, r, prefix, suffix, n)); +} +}"," '''Python program for +queries of GCD excluding +given range of elements.''' + + '''Calculating GCD +using euclid algorithm''' + +def GCD(a,b): + if (b==0): + return a + return GCD (b, a%b) '''Filling the prefix +and suffix array''' + +def FillPrefixSuffix(prefix,arr,suffix,n): + ''' Filling the prefix array + following relation + prefix(i) = GCD(prefix(i-1), arr(i))''' + + prefix[0] = arr[0] + for i in range(1,n): + prefix[i] = GCD (prefix[i-1], arr[i]) + ''' Filling the suffix + array following the + relation suffix(i) = GCD(suffix(i+1), arr(i))''' + + suffix[n-1] = arr[n-1] + for i in range(n-2,-1,-1): + suffix[i] = GCD (suffix[i+1], arr[i]) + '''To calculate gcd of +the numbers outside range''' + +def GCDoutsideRange(l,r,prefix,suffix,n): + ''' If l=0, we need to tell GCD of numbers + from r+1 to n''' + + if (l==0): + return suffix[r+1] + ''' If r=n-1 we need to return the gcd of + numbers from 1 to l''' + + if (r==n-1): + return prefix[l-1] + return GCD(prefix[l-1], suffix[r+1]) + '''Driver code''' + +arr = [2, 6, 9] +n = len(arr) +prefix=[] +suffix=[] +for i in range(n+1): + prefix.append(0) + suffix.append(0) +FillPrefixSuffix(prefix, arr, suffix, n) +l = 0 +r = 0 +print(GCDoutsideRange(l, r, prefix, suffix, n)) +l = 1 +r = 1 +print(GCDoutsideRange(l, r, prefix, suffix, n)) +l = 1 +r = 2 +print(GCDoutsideRange(l, r, prefix, suffix, n))" +Find the largest three distinct elements in an array,"/*Java code to find largest +three elements in an array*/ + +import java.io.*; +import java.util.Arrays; +class GFG { + void find3largest(int[] arr) + { +/*It uses Tuned Quicksort with*/ + +Arrays.sort(arr); +/* avg. case Time complexity = O(nLogn)*/ + + int n = arr.length; + int check = 0, count = 1; + for (int i = 1; i <= n; i++) { + if (count < 4) { + if (check != arr[n - i]) { +/* to handle duplicate values*/ + + System.out.print(arr[n - i] + "" ""); + check = arr[n - i]; + count++; + } + } + else + break; + } + } +/* Driver code*/ + + public static void main(String[] args) + { + GFG obj = new GFG(); + int[] arr = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; + obj.find3largest(arr); + } +} +"," '''Python3 code to find largest +three elements in an array''' + +def find3largest(arr, n): + '''It uses Tuned Quicksort with''' + + arr = sorted(arr) ''' avg. case Time complexity = O(nLogn)''' + + check = 0 + count = 1 + for i in range(1, n + 1): + if(count < 4): + if(check != arr[n - i]): + ''' to handle duplicate values''' + + print(arr[n - i], end = "" "") + check = arr[n - i] + count += 1 + else: + break + '''Driver code''' + +arr = [12, 45, 1, -1, 45, + 54, 23, 5, 0, -10] +n = len(arr) +find3largest(arr, n) +" +HeapSort,"/*Java program for implementation of Heap Sort*/ + +public class HeapSort { + +/* To heapify a subtree rooted with node i which is + an index in arr[]. n is size of heap*/ + + void heapify(int arr[], int n, int i) + { +/*Initialize largest as root*/ + +int largest = i; +/*left = 2*i + 1*/ + +int l = 2 * i + 1; +/*right = 2*i + 2*/ + +int r = 2 * i + 2; +/* If left child is larger than root*/ + + if (l < n && arr[l] > arr[largest]) + largest = l; +/* If right child is larger than largest so far*/ + + if (r < n && arr[r] > arr[largest]) + largest = r; +/* If largest is not root*/ + + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; +/* Recursively heapify the affected sub-tree*/ + + heapify(arr, n, largest); + } + } + /*The main function to sort an array of given size*/ + + public void sort(int arr[]) + { + int n = arr.length;/* Build heap (rearrange array)*/ + + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); +/* One by one extract an element from heap*/ + + for (int i = n - 1; i > 0; i--) { +/* Move current root to end*/ + + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; +/* call max heapify on the reduced heap*/ + + heapify(arr, i, 0); + } + } +/* A utility function to print array of size n */ + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6, 7 }; + int n = arr.length; + HeapSort ob = new HeapSort(); + ob.sort(arr); + System.out.println(""Sorted array is""); + printArray(arr); + } +}"," '''Python program for implementation of heap Sort''' + + '''To heapify subtree rooted at index i. +n is size of heap''' + +def heapify(arr, n, i): '''Initialize largest as root''' + + largest = i + + '''left = 2*i + 1''' + + l = 2 * i + 1 + + '''right = 2*i + 2''' + + r = 2 * i + 2 + ''' See if left child of root exists and is + greater than root''' + + if l < n and arr[largest] < arr[l]: + largest = l + ''' See if right child of root exists and is + greater than root''' + + if r < n and arr[largest] < arr[r]: + largest = r + ''' Change root, if needed''' + + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] ''' Heapify the root.''' + + heapify(arr, n, largest) + '''The main function to sort an array of given size''' + +def heapSort(arr): + n = len(arr) + ''' Build a maxheap.''' + + for i in range(n//2 - 1, -1, -1): + heapify(arr, n, i) + ''' One by one extract elements''' + + for i in range(n-1, 0, -1): + '''swap''' + + arr[i], arr[0] = arr[0], arr[i] + + + '''call max heapify on the reduced heap''' + + heapify(arr, i, 0) '''Driver code''' + +arr = [12, 11, 13, 5, 6, 7] +heapSort(arr) +n = len(arr) +print(""Sorted array is"") +for i in range(n): + print(""%d"" % arr[i])," +Longest path between any pair of vertices,," '''Python3 program to find the longest +cable length between any two cities. ''' + + '''visited[] array to make nodes visited +src is starting node for DFS traversal +prev_len is sum of cable length till +current node max_len is pointer which +stores the maximum length of cable +value after DFS traversal ''' + +def DFS(graph, src, prev_len, + max_len, visited): ''' Mark the src node visited ''' + + visited[src] = 1 + ''' curr_len is for length of cable + from src city to its adjacent city ''' + + curr_len = 0 + ''' Adjacent is pair type which stores + destination city and cable length ''' + + adjacent = None + ''' Traverse all adjacent ''' + + for i in range(len(graph[src])): + ''' Adjacent element ''' + + adjacent = graph[src][i] + ''' If node or city is not visited ''' + + if (not visited[adjacent[0]]): + ''' Total length of cable from + src city to its adjacent ''' + + curr_len = prev_len + adjacent[1] + ''' Call DFS for adjacent city ''' + + DFS(graph, adjacent[0], curr_len, + max_len, visited) + ''' If total cable length till + now greater than previous + length then update it ''' + + if (max_len[0] < curr_len): + max_len[0] = curr_len + ''' make curr_len = 0 for next adjacent ''' + + curr_len = 0 + '''n is number of cities or nodes in +graph cable_lines is total cable_lines +among the cities or edges in graph ''' + +def longestCable(graph, n): + ''' maximum length of cable among + the connected cities ''' + + max_len = [-999999999999] + ''' call DFS for each city to find + maximum length of cable''' + + for i in range(1, n + 1): + ''' initialize visited array with 0 ''' + + visited = [False] * (n + 1) + ''' Call DFS for src vertex i ''' + + DFS(graph, i, 0, max_len, visited) + return max_len[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' n is number of cities ''' + + n = 6 + graph = [[] for i in range(n + 1)] + ''' create undirected graph + first edge ''' + + graph[1].append([2, 3]) + graph[2].append([1, 3]) + ''' second edge ''' + + graph[2].append([3, 4]) + graph[3].append([2, 4]) + ''' third edge ''' + + graph[2].append([6, 2]) + graph[6].append([2, 2]) + ''' fourth edge ''' + + graph[4].append([6, 6]) + graph[6].append([4, 6]) + ''' fifth edge ''' + + graph[5].append([6, 5]) + graph[6].append([5, 5]) + print(""Maximum length of cable ="", + longestCable(graph, n))" +Iterative Quick Sort,"/*Java program for implementation of QuickSort*/ + +import java.util.*; +class QuickSort { + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ + + static int partition(int arr[], int low, int high) + { + int pivot = arr[high]; + + int i = (low - 1); + for (int j = low; j <= high - 1; j++) { + if (arr[j] <= pivot) { + i++; + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return i + 1; + } + /* A[] --> Array to be sorted, + l --> Starting index, + h --> Ending index */ + + static void quickSortIterative(int arr[], int l, int h) + { +/* Create an auxiliary stack*/ + + int[] stack = new int[h - l + 1]; +/* initialize top of stack*/ + + int top = -1; +/* push initial values of l and h to stack*/ + + stack[++top] = l; + stack[++top] = h; +/* Keep popping from stack while is not empty*/ + + while (top >= 0) { +/* Pop h and l*/ + + h = stack[top--]; + l = stack[top--]; +/* Set pivot element at its correct position + in sorted array*/ + + int p = partition(arr, l, h); +/* If there are elements on left side of pivot, + then push left side to stack*/ + + if (p - 1 > l) { + stack[++top] = l; + stack[++top] = p - 1; + } +/* If there are elements on right side of pivot, + then push right side to stack*/ + + if (p + 1 < h) { + stack[++top] = p + 1; + stack[++top] = h; + } + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; + int n = 8; +/* Function calling*/ + + quickSortIterative(arr, 0, n - 1); + for (int i = 0; i < n; i++) { + System.out.print(arr[i] + "" ""); + } + } +}"," '''Python program for implementation of Quicksort ''' + + '''This function is same in both iterative and recursive''' + +def partition(arr, l, h): + i = ( l - 1 ) + x = arr[h] + for j in range(l, h): + if arr[j] <= x: + i = i + 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i + 1], arr[h] = arr[h], arr[i + 1] + return (i + 1) '''Function to do Quick sort +arr[] --> Array to be sorted, +l --> Starting index, +h --> Ending index''' + +def quickSortIterative(arr, l, h): + ''' Create an auxiliary stack''' + + size = h - l + 1 + stack = [0] * (size) + ''' initialize top of stack''' + + top = -1 + ''' push initial values of l and h to stack''' + + top = top + 1 + stack[top] = l + top = top + 1 + stack[top] = h + ''' Keep popping from stack while is not empty''' + + while top >= 0: + ''' Pop h and l''' + + h = stack[top] + top = top - 1 + l = stack[top] + top = top - 1 + ''' Set pivot element at its correct position in + sorted array''' + + p = partition( arr, l, h ) + ''' If there are elements on left side of pivot, + then push left side to stack''' + + if p-1 > l: + top = top + 1 + stack[top] = l + top = top + 1 + stack[top] = p - 1 + ''' If there are elements on right side of pivot, + then push right side to stack''' + + if p + 1 < h: + top = top + 1 + stack[top] = p + 1 + top = top + 1 + stack[top] = h + '''Driver code to test above''' + +arr = [4, 3, 5, 2, 1, 3, 2, 3] +n = len(arr) + ''' Function calling''' + +quickSortIterative(arr, 0, n-1) +print (""Sorted array is:"") +for i in range(n): + print (""% d"" % arr[i])," +Maximum Sum Increasing Subsequence | DP-14,"/* Dynamic Programming Java + implementation of Maximum Sum + Increasing Subsequence (MSIS) + problem */ + +class GFG +{ + /* maxSumIS() returns the + maximum sum of increasing + subsequence in arr[] of size n */ + + static int maxSumIS(int arr[], int n) + { + int i, j, max = 0; + int msis[] = new int[n]; + /* Initialize msis values + for all indexes */ + + for (i = 0; i < n; i++) + msis[i] = arr[i]; + /* Compute maximum sum values + in bottom up manner */ + + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && + msis[i] < msis[j] + arr[i]) + msis[i] = msis[j] + arr[i]; + /* Pick maximum of all + msis values */ + + for (i = 0; i < n; i++) + if (max < msis[i]) + max = msis[i]; + return max; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = new int[]{1, 101, 2, 3, 100, 4, 5}; + int n = arr.length; + System.out.println(""Sum of maximum sum ""+ + ""increasing subsequence is ""+ + maxSumIS(arr, n)); + } +}"," '''Dynamic Programming bsed Python +implementation of Maximum Sum +Increasing Subsequence (MSIS) +problem + ''' '''maxSumIS() returns the maximum +sum of increasing subsequence +in arr[] of size n''' + +def maxSumIS(arr, n): + max = 0 + msis = [0 for x in range(n)] + ''' Initialize msis values + for all indexes''' + + for i in range(n): + msis[i] = arr[i] + ''' Compute maximum sum + values in bottom up manner''' + + for i in range(1, n): + for j in range(i): + if (arr[i] > arr[j] and + msis[i] < msis[j] + arr[i]): + msis[i] = msis[j] + arr[i] + ''' Pick maximum of + all msis values''' + + for i in range(n): + if max < msis[i]: + max = msis[i] + return max + '''Driver Code''' + +arr = [1, 101, 2, 3, 100, 4, 5] +n = len(arr) +print(""Sum of maximum sum increasing "" + + ""subsequence is "" + + str(maxSumIS(arr, n)))" +Program for array rotation,"/*Java program to rotate an array by +d elements*/ + +class RotateArray { + /*Function to left Rotate arr[] of + size n by 1*/ + + void leftRotatebyOne(int arr[], int n) + { + int i, temp; + temp = arr[0]; + for (i = 0; i < n - 1; i++) + arr[i] = arr[i + 1]; + arr[n-1] = temp; + }/*Function to left rotate arr[] of size n by d*/ + + void leftRotate(int arr[], int d, int n) + { + for (int i = 0; i < d; i++) + leftRotatebyOne(arr, n); + } + + /* utility function to print an array */ + + void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + RotateArray rotate = new RotateArray(); + int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; + rotate.leftRotate(arr, 2, 7); + rotate.printArray(arr, 7); + } +}"," '''Python3 program to rotate an array by +d elements''' + '''Function to left Rotate arr[] of size n by 1*/''' + +def leftRotatebyOne(arr, n): + temp = arr[0] + for i in range(n-1): + arr[i] = arr[i + 1] + arr[n-1] = temp + '''Function to left rotate arr[] of size n by d*/''' + +def leftRotate(arr, d, n): + for i in range(d): + leftRotatebyOne(arr, n) + '''utility function to print an array */''' + +def printArray(arr, size): + for i in range(size): + print (""% d""% arr[i], end ="" "") + '''Driver program to test above functions */''' + +arr = [1, 2, 3, 4, 5, 6, 7] +leftRotate(arr, 2, 7) +printArray(arr, 7)" +Check if array elements are consecutive | Added Method 3,"class AreConsecutive +{ + /* The function checks if the array elements are consecutive + If elements are consecutive, then returns true, else returns + false */ + + boolean areConsecutive(int arr[], int n) + { + if (n < 1) + return false; + /* 1) Get the minimum element in array */ + + int min = getMin(arr, n); + /* 2) Get the maximum element in array */ + + int max = getMax(arr, n); + /* 3) max-min+1 is equal to n then only check all elements */ + + if (max - min + 1 == n) + { + int i; + for (i = 0; i < n; i++) + { + int j; + if (arr[i] < 0) + j = -arr[i] - min; + else + j = arr[i] - min; +/* if the value at index j is negative then + there is repitition*/ + + if (arr[j] > 0) + arr[j] = -arr[j]; + else + return false; + } + /* If we do not see a negative value then all elements + are distinct */ + + return true; + } +/*if (max-min+1 != n)*/ + +return false; + } + /* UTILITY FUNCTIONS */ + + int getMin(int arr[], int n) + { + int min = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] < min) + min = arr[i]; + } + return min; + } + int getMax(int arr[], int n) + { + int max = arr[0]; + for (int i = 1; i < n; i++) + { + if (arr[i] > max) + max = arr[i]; + } + return max; + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + AreConsecutive consecutive = new AreConsecutive(); + int arr[] = {5, 4, 2, 3, 1, 6}; + int n = arr.length; + if (consecutive.areConsecutive(arr, n) == true) + System.out.println(""Array elements are consecutive""); + else + System.out.println(""Array elements are not consecutive""); + } +}"," '''''' '''Helper functions to get minimum and +maximum in an array +The function checks if the array +elements are consecutive. If elements +are consecutive, then returns true, +else returns false''' + +def areConsecutive(arr, n): + if ( n < 1 ): + return False + ''' 1) Get the minimum element in array''' + + min = getMin(arr, n) + ''' 2) Get the maximum element in array''' + + max = getMax(arr, n) + ''' 3) max - min + 1 is equal to n + then only check all elements''' + + if (max - min + 1 == n): + for i in range(n): + if (arr[i] < 0): + j = -arr[i] - min + else: + j = arr[i] - min + ''' if the value at index j is negative + then there is repetition''' + + if (arr[j] > 0): + arr[j] = -arr[j] + else: + return False + ''' If we do not see a negative value + then all elements are distinct''' + + return True + '''if (max - min + 1 != n)''' + + return False + '''UTILITY FUNCTIONS''' + +def getMin(arr, n): + min = arr[0] + for i in range(1, n): + if (arr[i] < min): + min = arr[i] + return min +def getMax(arr, n): + max = arr[0] + for i in range(1, n): + if (arr[i] > max): + max = arr[i] + return max + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 4, 5, 3, 2, 6] + n = len(arr) + if(areConsecutive(arr, n) == True): + print("" Array elements are consecutive "") + else: + print("" Array elements are not consecutive "")" +Find the repeating and the missing | Added 3 new methods,"/*Java program to Find the repeating +and missing elements*/ + + +import java.io.*; + +class GFG { + static int x, y; + + /* The output of this function is stored at +*x and *y */ + + + static void getTwoElements(int arr[], int n) + {/* Will hold xor of all elements + and numbers from 1 to n */ + + int xor1; + + /* Will have only single set bit of xor1 */ + + int set_bit_no; + + int i; + x = 0; + y = 0; + + xor1 = arr[0]; + + /* Get the xor of all array elements */ + + for (i = 1; i < n; i++) + xor1 = xor1 ^ arr[i]; + + /* XOR the previous result with numbers from + 1 to n*/ + + for (i = 1; i <= n; i++) + xor1 = xor1 ^ i; + + /* Get the rightmost set bit in set_bit_no */ + + set_bit_no = xor1 & ~(xor1 - 1); + + /* Now divide elements into two sets by comparing + rightmost set bit of xor1 with the bit at the same + position in each element. Also, get XORs of two + sets. The two XORs are the output elements. The + following two for loops serve the purpose */ + + for (i = 0; i < n; i++) { + if ((arr[i] & set_bit_no) != 0) + /* arr[i] belongs to first set */ + + x = x ^ arr[i]; + + else + /* arr[i] belongs to second set*/ + + y = y ^ arr[i]; + } + for (i = 1; i <= n; i++) { + if ((i & set_bit_no) != 0) + /* i belongs to first set */ + + x = x ^ i; + + else + /* i belongs to second set*/ + + y = y ^ i; + } + + /* *x and *y hold the desired output elements */ + + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = { 1, 3, 4, 5, 1, 6, 2 }; + + int n = arr.length; + getTwoElements(arr, n); + System.out.println("" The missing element is "" + + x + ""and the "" + + ""repeating number is "" + + y); + } +} + + +"," '''Python3 program to find the repeating +and missing elements''' + + + '''The output of this function is stored +at x and y''' + +def getTwoElements(arr, n): + + global x, y + x = 0 + y = 0 + + ''' Will hold xor of all elements + and numbers from 1 to n''' + + xor1 = arr[0] + + ''' Get the xor of all array elements''' + + for i in range(1, n): + xor1 = xor1 ^ arr[i] + + ''' XOR the previous result with numbers + from 1 to n''' + + for i in range(1, n + 1): + xor1 = xor1 ^ i + + ''' Will have only single set bit of xor1''' + + set_bit_no = xor1 & ~(xor1 - 1) + + ''' Now divide elements into two + sets by comparing a rightmost set + bit of xor1 with the bit at the same + position in each element. Also, + get XORs of two sets. The two + XORs are the output elements. + The following two for loops + serve the purpose''' + + for i in range(n): + if (arr[i] & set_bit_no) != 0: + + ''' arr[i] belongs to first set''' + + x = x ^ arr[i] + else: + + ''' arr[i] belongs to second set''' + + y = y ^ arr[i] + + for i in range(1, n + 1): + if (i & set_bit_no) != 0: + + ''' i belongs to first set''' + + x = x ^ i + else: + + ''' i belongs to second set''' + + y = y ^ i + + ''' x and y hold the desired + output elements''' + + + '''Driver code''' + +arr = [ 1, 3, 4, 5, 5, 6, 2 ] +n = len(arr) + +getTwoElements(arr, n) + +print(""The missing element is"", x, + ""and the repeating number is"", y) + + +" +Rotate a matrix by 90 degree in clockwise direction without using any extra space,"/*Java implementation of above approach*/ + +import java.io.*; + +class GFG { + static int N = 4; + +/* Function to rotate the matrix 90 degree clockwise*/ + + static void rotate90Clockwise(int arr[][]) + { +/* printing the matrix on the basis of + observations made on indices.*/ + + for (int j = 0; j < N; j++) + { + for (int i = N - 1; i >= 0; i--) + System.out.print(arr[i][j] + "" ""); + System.out.println(); + } + } + + +/*Driver code*/ + + public static void main(String[] args) + { + int arr[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; + rotate90Clockwise(arr); + } +}"," '''Python3 implementation of above approach''' + +N = 4 + + '''Function to rotate the matrix 90 degree clockwise''' + +def rotate90Clockwise(arr) : + global N + + ''' printing the matrix on the basis of + observations made on indices.''' + + for j in range(N) : + for i in range(N - 1, -1, -1) : + print(arr[i][j], end = "" "") + print() + + '''Driver code ''' + +arr = [ [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 9, 10, 11, 12 ], + [ 13, 14, 15, 16 ] ] +rotate90Clockwise(arr); + + +" +A Boolean Matrix Question,"/*Java Code For A Boolean Matrix Question*/ + +class GFG +{ + public static void modifyMatrix(int mat[ ][ ], int R, int C) + { + int row[ ]= new int [R]; + int col[ ]= new int [C]; + int i, j; + /* Initialize all values of row[] as 0 */ + + for (i = 0; i < R; i++) + { + row[i] = 0; + } + /* Initialize all values of col[] as 0 */ + + for (i = 0; i < C; i++) + { + col[i] = 0; + } + /* Store the rows and columns to be marked as + 1 in row[] and col[] arrays respectively */ + + for (i = 0; i < R; i++) + { + for (j = 0; j < C; j++) + { + if (mat[i][j] == 1) + { + row[i] = 1; + col[j] = 1; + } + } + } + /* Modify the input matrix mat[] using the + above constructed row[] and col[] arrays */ + + for (i = 0; i < R; i++) + { + for (j = 0; j < C; j++) + { + if ( row[i] == 1 || col[j] == 1 ) + { + mat[i][j] = 1; + } + } + } + } + /* A utility function to print a 2D matrix */ + + public static void printMatrix(int mat[ ][ ], int R, int C) + { + int i, j; + for (i = 0; i < R; i++) + { + for (j = 0; j < C; j++) + { + System.out.print(mat[i][j]+ "" ""); + } + System.out.println(); + } + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + int mat[ ][ ] = { {1, 0, 0, 1}, + {0, 0, 1, 0}, + {0, 0, 0, 0},}; + System.out.println(""Matrix Intially""); + printMatrix(mat, 3, 4); + modifyMatrix(mat, 3, 4); + System.out.println(""Matrix after modification n""); + printMatrix(mat, 3, 4); + } +}"," '''Python3 Code For A Boolean Matrix Question''' + +R = 3 +C = 4 +def modifyMatrix(mat): + row = [0] * R + col = [0] * C + ''' Initialize all values of row[] as 0''' + + for i in range(0, R): + row[i] = 0 + ''' Initialize all values of col[] as 0''' + + for i in range(0, C) : + col[i] = 0 + ''' Store the rows and columns to be marked + as 1 in row[] and col[] arrays respectively''' + + for i in range(0, R) : + for j in range(0, C) : + if (mat[i][j] == 1) : + row[i] = 1 + col[j] = 1 + ''' Modify the input matrix mat[] using the + above constructed row[] and col[] arrays''' + + for i in range(0, R) : + for j in range(0, C): + if ( row[i] == 1 or col[j] == 1 ) : + mat[i][j] = 1 + '''A utility function to print a 2D matrix''' + +def printMatrix(mat) : + for i in range(0, R): + for j in range(0, C) : + print(mat[i][j], end = "" "") + print() + '''Driver Code''' + +mat = [ [1, 0, 0, 1], + [0, 0, 1, 0], + [0, 0, 0, 0] ] +print(""Input Matrix n"") +printMatrix(mat) +modifyMatrix(mat) +print(""Matrix after modification n"") +printMatrix(mat)" +Types of Linked List,"/*Structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +"," '''structure of Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None +" +Find minimum difference between any two elements,"/*Java program to find minimum difference between +any pair in an unsorted array*/ + +import java.util.Arrays; +class GFG +{ +/* Returns minimum difference between any pair*/ + + static int findMinDiff(int[] arr, int n) + { +/* Sort array in non-decreasing order*/ + + Arrays.sort(arr); +/* Initialize difference as infinite*/ + + int diff = Integer.MAX_VALUE; +/* Find the min diff by comparing adjacent + pairs in sorted array*/ + + for (int i=0; i S=new LinkedList<>(),G=new LinkedList<>(); +/* Process first window of size K*/ + + int i = 0; + for (i = 0; i < k; i++) + { +/* Remove all previous greater elements + that are useless.*/ + + while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) +/*Remove from rear*/ + +S.removeLast(); +/* Remove all previous smaller that are elements + are useless.*/ + + while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) +/*Remove from rear*/ + +G.removeLast(); +/* Add current element at rear of both deque*/ + + G.addLast(i); + S.addLast(i); + } +/* Process rest of the Array elements*/ + + for ( ; i < arr.length; i++ ) + { +/* Element at the front of the deque 'G' & 'S' + is the largest and smallest + element of previous window respectively*/ + + sum += arr[S.peekFirst()] + arr[G.peekFirst()]; +/* Remove all elements which are out of this + window*/ + + while ( !S.isEmpty() && S.peekFirst() <= i - k) + S.removeFirst(); + while ( !G.isEmpty() && G.peekFirst() <= i - k) + G.removeFirst(); +/* remove all previous greater element that are + useless*/ + + while ( !S.isEmpty() && arr[S.peekLast()] >= arr[i]) +/*Remove from rear*/ + +S.removeLast(); +/* remove all previous smaller that are elements + are useless*/ + + while ( !G.isEmpty() && arr[G.peekLast()] <= arr[i]) +/*Remove from rear*/ + +G.removeLast(); +/* Add current element at rear of both deque*/ + + G.addLast(i); + S.addLast(i); + } +/* Sum of minimum and maximum element of last window*/ + + sum += arr[S.peekFirst()] + arr[G.peekFirst()]; + return sum; + } +/*Driver program to test above functions*/ + + public static void main(String args[]) + { + int arr[] = {2, 5, -1, 7, -3, -1, -2} ; + int k = 3; + System.out.println(SumOfKsubArray(arr, k)); + } +}"," '''Python3 program to find Sum of all minimum and maximum +elements Of Sub-array Size k.''' + +from collections import deque + '''Returns Sum of min and max element of all subarrays +of size k''' + +def SumOfKsubArray(arr, n , k): + '''Initialize result''' + + Sum = 0 + ''' The queue will store indexes of useful elements + in every window + In deque 'G' we maintain decreasing order of + values from front to rear + In deque 'S' we maintain increasing order of + values from front to rear''' + + S = deque() + G = deque() + ''' Process first window of size K''' + + for i in range(k): + ''' Remove all previous greater elements + that are useless.''' + + while ( len(S) > 0 and arr[S[-1]] >= arr[i]): + '''Remove from rear''' + + S.pop() + ''' Remove all previous smaller that are elements + are useless.''' + + while ( len(G) > 0 and arr[G[-1]] <= arr[i]): + '''Remove from rear''' + + G.pop() + ''' Add current element at rear of both deque''' + + G.append(i) + S.append(i) + ''' Process rest of the Array elements''' + + for i in range(k, n): + ''' Element at the front of the deque 'G' & 'S' + is the largest and smallest + element of previous window respectively''' + + Sum += arr[S[0]] + arr[G[0]] + ''' Remove all elements which are out of this + window''' + + while ( len(S) > 0 and S[0] <= i - k): + S.popleft() + while ( len(G) > 0 and G[0] <= i - k): + G.popleft() + ''' remove all previous greater element that are + useless''' + + while ( len(S) > 0 and arr[S[-1]] >= arr[i]): + '''Remove from rear''' + + S.pop() + ''' remove all previous smaller that are elements + are useless''' + + while ( len(G) > 0 and arr[G[-1]] <= arr[i]): + '''Remove from rear''' + + G.pop() + ''' Add current element at rear of both deque''' + + G.append(i) + S.append(i) + ''' Sum of minimum and maximum element of last window''' + + Sum += arr[S[0]] + arr[G[0]] + return Sum + '''Driver program to test above functions''' + +arr=[2, 5, -1, 7, -3, -1, -2] +n = len(arr) +k = 3 +print(SumOfKsubArray(arr, n, k))" +Rearrange a given linked list in-place.,"/*Java code to rearrange linked list in place*/ + +class Geeks { + + static class Node { + int data; + Node next; + } + +/* function for rearranging a linked list + with high and low value.*/ + + static Node rearrange(Node head) + { +/*Base case.*/ + +if (head == null) + return null; + +/* two pointer variable.*/ + + Node prev = head, curr = head.next; + + while (curr != null) { +/* swap function for swapping data.*/ + + if (prev.data > curr.data) { + int t = prev.data; + prev.data = curr.data; + curr.data = t; + } + +/* swap function for swapping data.*/ + + if (curr.next != null + && curr.next.data > curr.data) { + int t = curr.next.data; + curr.next.data = curr.data; + curr.data = t; + } + + prev = curr.next; + + if (curr.next == null) + break; + curr = curr.next.next; + } + return head; + } + +/* function to insert a Node in + the linked list at the beginning.*/ + + static Node push(Node head, int k) + { + Node tem = new Node(); + tem.data = k; + tem.next = head; + head = tem; + return head; + } + +/* function to display Node of linked list.*/ + + static void display(Node head) + { + Node curr = head; + while (curr != null) { + System.out.printf(""%d "", curr.data); + curr = curr.next; + } + } + +/* Driver code*/ + + public static void main(String args[]) + { + + Node head = null; + +/* let create a linked list. + 9 . 6 . 8 . 3 . 7*/ + + head = push(head, 7); + head = push(head, 3); + head = push(head, 8); + head = push(head, 6); + head = push(head, 9); + + head = rearrange(head); + + display(head); + } +} + + +"," '''Python3 code to rearrange linked list in place''' + +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + + '''Function for rearranging a linked +list with high and low value''' + + + +def rearrange(head): + + ''' Base case''' + + if (head == None): + return head + + ''' Two pointer variable''' + + prev, curr = head, head.next + + while (curr): + + ''' Swap function for swapping data''' + + if (prev.data > curr.data): + prev.data, curr.data = curr.data, prev.data + + ''' Swap function for swapping data''' + + if (curr.next and curr.next.data > curr.data): + curr.next.data, curr.data = curr.data, curr.next.data + + prev = curr.next + + if (not curr.next): + break + + curr = curr.next.next + + return head + + '''Function to insert a node in the +linked list at the beginning''' + + + +def push(head, k): + + tem = Node(k) + tem.data = k + tem.next = head + head = tem + return head + + '''Function to display node of linked list''' + + + +def display(head): + + curr = head + + while (curr != None): + print(curr.data, end="" "") + curr = curr.next + + + '''Driver code''' + +if __name__ == '__main__': + + head = None + + ''' Let create a linked list + 9 . 6 . 8 . 3 . 7''' + + head = push(head, 7) + head = push(head, 3) + head = push(head, 8) + head = push(head, 6) + head = push(head, 9) + + head = rearrange(head) + + display(head) + + +" +Sum of all the parent nodes having child node x,"/*Java implementation to find +the sum of all the parent +nodes having child node x */ + +class GFG +{ +/*sum*/ + +static int sum = 0; +/*Node of a binary tree */ + +static class Node +{ + int data; + Node left, right; +}; +/*function to get a new node */ + +static Node getNode(int data) +{ +/* allocate memory for the node */ + + Node newNode = new Node(); +/* put in the data */ + + newNode.data = data; + newNode.left = newNode.right = null; + return newNode; +} +/*function to find the sum of all the +parent nodes having child node x */ + +static void sumOfParentOfX(Node root, int x) +{ +/* if root == NULL */ + + if (root == null) + return; +/* if left or right child + of root is 'x', then + add the root's data to 'sum' */ + + if ((root.left != null && root.left.data == x) || + (root.right != null && root.right.data == x)) + sum += root.data; +/* recursively find the required + parent nodes in the left and + right subtree */ + + sumOfParentOfX(root.left, x); + sumOfParentOfX(root.right, x); +} +/*utility function to find the +sum of all the parent nodes +having child node x */ + +static int sumOfParentOfXUtil(Node root, + int x) +{ + sum = 0; + sumOfParentOfX(root, x); +/* required sum of parent nodes */ + + return sum; +} +/*Driver Code*/ + +public static void main(String args[]) +{ +/* binary tree formation + 4 */ + +Node root = getNode(4); +/* / \ */ + +root.left = getNode(2); +/* 2 5 */ + +root.right = getNode(5); +/* / \ / \ */ + +root.left.left = getNode(7); +/*7 2 2 3 */ + +root.left.right = getNode(2); + root.right.left = getNode(2); + root.right.right = getNode(3); + int x = 2; + System.out.println( ""Sum = "" + + sumOfParentOfXUtil(root, x)); +} +}"," '''Python3 implementation to find the Sum of +all the parent nodes having child node x ''' + '''function to get a new node ''' + +class getNode: + def __init__(self, data): + ''' put in the data ''' + + self.data = data + self.left = self.right = None + '''function to find the Sum of all the +parent nodes having child node x ''' + +def SumOfParentOfX(root, Sum, x): + ''' if root == None ''' + + if (not root): + return + ''' if left or right child of root is 'x', + then add the root's data to 'Sum' ''' + + if ((root.left and root.left.data == x) or + (root.right and root.right.data == x)): + Sum[0] += root.data + ''' recursively find the required parent + nodes in the left and right subtree ''' + + SumOfParentOfX(root.left, Sum, x) + SumOfParentOfX(root.right, Sum, x) + '''utility function to find the Sum of all +the parent nodes having child node x ''' + +def SumOfParentOfXUtil(root, x): + Sum = [0] + SumOfParentOfX(root, Sum, x) + ''' required Sum of parent nodes ''' + + return Sum[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree formation + 4 ''' + + root = getNode(4) + ''' / \ ''' + + root.left = getNode(2) + ''' 2 5 ''' + + root.right = getNode(5) + ''' / \ / \ ''' + + root.left.left = getNode(7) + '''7 2 2 3 ''' + + root.left.right = getNode(2) + root.right.left = getNode(2) + root.right.right = getNode(3) + x = 2 + print(""Sum = "", SumOfParentOfXUtil(root, x))" +Print all k-sum paths in a binary tree,"/*Java program to print all paths with sum k. */ + +import java.util.*; +class GFG +{ +/*utility function to print contents of +a vector from index i to it's end */ + +static void printVector( Vector v, int i) +{ + for (int j = i; j < v.size(); j++) + System.out.print( v.get(j) + "" ""); + System.out.println(); +} +/*binary tree node */ + +static class Node +{ + int data; + Node left,right; + Node(int x) + { + data = x; + left = right = null; + } +}; +static Vector path = new Vector(); +/*This function prints all paths that have sum k */ + +static void printKPathUtil(Node root, int k) +{ +/* empty node */ + + if (root == null) + return; +/* add current node to the path */ + + path.add(root.data); +/* check if there's any k sum path + in the left sub-tree. */ + + printKPathUtil(root.left, k); +/* check if there's any k sum path + in the right sub-tree. */ + + printKPathUtil(root.right, k); +/* check if there's any k sum path that + terminates at this node + Traverse the entire path as + there can be negative elements too */ + + int f = 0; + for (int j = path.size() - 1; j >= 0; j--) + { + f += path.get(j); +/* If path sum is k, print the path */ + + if (f == k) + printVector(path, j); + } +/* Remove the current element from the path */ + + path.remove(path.size() - 1); +} +/*A wrapper over printKPathUtil() */ + +static void printKPath(Node root, int k) +{ + path = new Vector(); + printKPathUtil(root, k); +} +/*Driver code */ + +public static void main(String args[]) +{ + Node root = new Node(1); + root.left = new Node(3); + root.left.left = new Node(2); + root.left.right = new Node(1); + root.left.right.left = new Node(1); + root.right = new Node(-1); + root.right.left = new Node(4); + root.right.left.left = new Node(1); + root.right.left.right = new Node(2); + root.right.right = new Node(5); + root.right.right.right = new Node(2); + int k = 5; + printKPath(root, k); +} +}"," '''Python3 program to print all paths +with sum k ''' + + '''utility function to print contents of +a vector from index i to it's end ''' + +def printVector(v, i): + for j in range(i, len(v)): + print(v[j], end = "" "") + print() '''Binary Tree Node ''' + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''This function prints all paths +that have sum k ''' + +def printKPathUtil(root, path, k): + ''' empty node ''' + + if (not root) : + return + ''' add current node to the path ''' + + path.append(root.data) + ''' check if there's any k sum path + in the left sub-tree. ''' + + printKPathUtil(root.left, path, k) + ''' check if there's any k sum path + in the right sub-tree. ''' + + printKPathUtil(root.right, path, k) + ''' check if there's any k sum path that + terminates at this node + Traverse the entire path as + there can be negative elements too ''' + + f = 0 + for j in range(len(path) - 1, -1, -1): + f += path[j] + ''' If path sum is k, print the path ''' + + if (f == k) : + printVector(path, j) + ''' Remove the current element + from the path ''' + + path.pop(-1) + '''A wrapper over printKPathUtil() ''' + +def printKPath(root, k): + path =[] + printKPathUtil(root, path, k) + '''Driver Code ''' + +if __name__ == '__main__': + root = newNode(1) + root.left = newNode(3) + root.left.left = newNode(2) + root.left.right = newNode(1) + root.left.right.left = newNode(1) + root.right = newNode(-1) + root.right.left = newNode(4) + root.right.left.left = newNode(1) + root.right.left.right = newNode(2) + root.right.right = newNode(5) + root.right.right.right = newNode(2) + k = 5 + printKPath(root, k)" +Program for Markov matrix,"/*Java code to check Markov Matrix*/ + +import java.io.*; +public class markov +{ + static boolean checkMarkov(double m[][]) + { +/* outer loop to access rows + and inner to access columns*/ + + for (int i = 0; i < m.length; i++) { +/* Find sum of current row*/ + + double sum = 0; + for (int j = 0; j < m[i].length; j++) + sum = sum + m[i][j]; + if (sum != 1) + return false; + } + return true; + } + +/*Driver Code*/ + + public static void main(String args[]) + {/* Matrix to check*/ + + double m[][] = { { 0, 0, 1 }, + { 0.5, 0, 0.5 }, + { 1, 0, 0 } }; +/* calls the function check()*/ + + if (checkMarkov(m)) + System.out.println("" yes ""); + else + System.out.println("" no ""); + } +}"," '''Python 3 code to check Markov Matrix''' + +def checkMarkov(m) : + ''' Outer loop to access rows + and inner to access columns''' + + for i in range(0, len(m)) : + ''' Find sum of current row''' + + sm = 0 + for j in range(0, len(m[i])) : + sm = sm + m[i][j] + if (sm != 1) : + return False + return True + '''Driver code''' '''Matrix to check''' + +m = [ [ 0, 0, 1 ], + [ 0.5, 0, 0.5 ], + [ 1, 0, 0 ] ] + '''Calls the function check()''' + +if (checkMarkov(m)) : + print("" yes "") +else : + print("" no "")" +Modify given array to a non-decreasing array by rotation,"/*Java program for the above approach*/ + +import java.util.*; + +class GFG{ + +/* Function to check if a + non-decreasing array can be obtained + by rotating the original array*/ + + static void rotateArray(int[] arr, int N) + { +/* Stores copy of original array*/ + + int[] v = arr; + +/* Sort the given vector*/ + + Arrays.sort(v); + +/* Traverse the array*/ + + for (int i = 1; i <= N; ++i) { + +/* Rotate the array by 1*/ + + int x = arr[N - 1]; + i = N - 1; + while(i > 0){ + arr[i] = arr[i - 1]; + arr[0] = x; + i -= 1; + } + +/* If array is sorted*/ + + if (arr == v) { + + System.out.print(""YES""); + return; + } + } + +/* If it is not possible to + sort the array*/ + + System.out.print(""NO""); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + +/* Given array*/ + + int[] arr = { 3, 4, 5, 1, 2 }; + +/* Size of the array*/ + + int N = arr.length; + +/* Function call to check if it is possible + to make array non-decreasing by rotating*/ + + rotateArray(arr, N); + } +} + + +"," '''Python 3 program for the above approach''' + + + + '''Function to check if a +non-decreasing array can be obtained +by rotating the original array''' + +def rotateArray(arr, N): + + ''' Stores copy of original array''' + + v = arr + + ''' Sort the given vector''' + + v.sort(reverse = False) + + ''' Traverse the array''' + + for i in range(1, N + 1, 1): + + ''' Rotate the array by 1''' + + x = arr[N - 1] + i = N - 1 + while(i > 0): + arr[i] = arr[i - 1] + arr[0] = x + i -= 1 + + ''' If array is sorted''' + + if (arr == v): + print(""YES"") + return + + ''' If it is not possible to + sort the array''' + + print(""NO"") + + '''Driver Code''' + +if __name__ == '__main__': + + ''' Given array''' + + arr = [3, 4, 5, 1, 2] + + ''' Size of the array''' + + N = len(arr) + + ''' Function call to check if it is possible + to make array non-decreasing by rotating''' + + rotateArray(arr, N) + + +" +Counting Sort,"/*Java implementation of Counting Sort*/ + +class CountingSort { +/*The main function that sort +the given string arr[] in +alphabetical order*/ + + void sort(char arr[]) + { + int n = arr.length; +/* The output character array that will have sorted arr*/ + + char output[] = new char[n]; +/* Create a count array to store count of inidividul + characters and initialize count array as 0*/ + + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; +/* store count of each character*/ + + for (int i = 0; i < n; ++i) + ++count[arr[i]]; +/* Change count[i] so that count[i] now contains actual + position of this character in output array*/ + + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; +/* Build the output character array + To make it stable we are operating in reverse order.*/ + + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } +/* Copy the output array to arr, so that arr now + contains sorted characters*/ + + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } +/* Driver method*/ + + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' }; + ob.sort(arr); + System.out.print(""Sorted character array is ""); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +}"," '''Python program for counting sort''' + + '''The main function that sort the given string arr[] in +alphabetical order''' + +def countSort(arr): ''' The output character array that will have sorted arr''' + + output = [0 for i in range(len(arr))] + ''' Create a count array to store count of inidividul + characters and initialize count array as 0''' + + count = [0 for i in range(256)] + ''' Store count of each character''' + + for i in arr: + count[ord(i)] += 1 + ''' Change count[i] so that count[i] now contains actual + position of this character in output array''' + + for i in range(256): + count[i] += count[i-1] + ''' Build the output character array''' + + for i in range(len(arr)): + output[count[ord(arr[i])]-1] = arr[i] + count[ord(arr[i])] -= 1 + ''' Copy the output array to arr, so that arr now + contains sorted characters''' + ans = ["""" for _ in arr] + for i in range(len(arr)): + ans[i] = output[i] + return ans + '''Driver program to test above function''' + +arr = ""geeksforgeeks"" +ans = countSort(arr) +print(""Sorted character array is % s"" %("""".join(ans)))" +Inorder Non-threaded Binary Tree Traversal without Recursion or Stack,"/* Java program to print inorder traversal of a Binary Search Tree + without recursion and stack */ + +/*BST node*/ + +class Node +{ + int key; + Node left, right, parent; + public Node(int key) + { + this.key = key; + left = right = parent = null; + } +} +class BinaryTree +{ + Node root; + /* A utility function to insert a new node with + given key in BST */ + + Node insert(Node node, int key) + { + /* If the tree is empty, return a new node */ + + if (node == null) + return new Node(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + { + node.left = insert(node.left, key); + node.left.parent = node; + } + else if (key > node.key) + { + node.right = insert(node.right, key); + node.right.parent = node; + } + /* return the (unchanged) node pointer */ + + return node; + } +/* Function to print inorder traversal using parent + pointer*/ + + void inorder(Node root) + { + boolean leftdone = false; +/* Start traversal from root*/ + + while (root != null) + { +/* If left child is not traversed, find the + leftmost child*/ + + if (!leftdone) + { + while (root.left != null) + { + root = root.left; + } + } +/* Print root's data*/ + + System.out.print(root.key + "" ""); +/* Mark left as done*/ + + leftdone = true; +/* If right child exists*/ + + if (root.right != null) + { + leftdone = false; + root = root.right; + } +/* If right child doesn't exist, move to parent*/ + + else if (root.parent != null) + { +/* If this node is right child of its parent, + visit parent's parent first*/ + + while (root.parent != null + && root == root.parent.right) + root = root.parent; + if (root.parent == null) + break; + root = root.parent; + } + else + break; + } + } +/*Driver Code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = tree.insert(tree.root, 24); + tree.root = tree.insert(tree.root, 27); + tree.root = tree.insert(tree.root, 29); + tree.root = tree.insert(tree.root, 34); + tree.root = tree.insert(tree.root, 14); + tree.root = tree.insert(tree.root, 4); + tree.root = tree.insert(tree.root, 10); + tree.root = tree.insert(tree.root, 22); + tree.root = tree.insert(tree.root, 13); + tree.root = tree.insert(tree.root, 3); + tree.root = tree.insert(tree.root, 2); + tree.root = tree.insert(tree.root, 6); + System.out.println(""Inorder traversal is ""); + tree.inorder(tree.root); + } +}"," '''Python3 program to print inorder traversal of a +Binary Search Tree (BST) without recursion and stack''' + + '''A utility function to create a new BST node''' + +class newNode: + def __init__(self, item): + self.key = item + self.parent = self.left = self.right = None '''A utility function to insert a new +node with given key in BST''' + +def insert(node, key): + ''' If the tree is empty, return a new node''' + + if node == None: + return newNode(key) + ''' Otherwise, recur down the tree''' + + if key < node.key: + node.left = insert(node.left, key) + node.left.parent = node + elif key > node.key: + node.right = insert(node.right, key) + node.right.parent = node + ''' return the (unchanged) node pointer''' + + return node + '''Function to print inorder traversal +using parent pointer''' + +def inorder(root): + leftdone = False + ''' Start traversal from root''' + + while root: + ''' If left child is not traversed, + find the leftmost child''' + + if leftdone == False: + while root.left: + root = root.left + ''' Print root's data''' + + print(root.key, end = "" "") + ''' Mark left as done''' + + leftdone = True + ''' If right child exists''' + + if root.right: + leftdone = False + root = root.right + ''' If right child doesn't exist, move to parent''' + + elif root.parent: + ''' If this node is right child of its + parent, visit parent's parent first''' + + while root.parent and root == root.parent.right: + root = root.parent + if root.parent == None: + break + root = root.parent + else: + break + '''Driver Code''' + +if __name__ == '__main__': + root = None + root = insert(root, 24) + root = insert(root, 27) + root = insert(root, 29) + root = insert(root, 34) + root = insert(root, 14) + root = insert(root, 4) + root = insert(root, 10) + root = insert(root, 22) + root = insert(root, 13) + root = insert(root, 3) + root = insert(root, 2) + root = insert(root, 6) + print(""Inorder traversal is "") + inorder(root)" +Add 1 to a number represented as linked list,"/*Recursive Java program to add 1 to a linked list*/ + +class GfG { + + /* Linked list node */ + + static class Node + { + int data; + Node next; + } + + /* Function to create a new node with given data */ + + static Node newNode(int data) + { + Node new_node = new Node(); + new_node.data = data; + new_node.next = null; + return new_node; + } + +/* Recursively add 1 from end to beginning and returns + carry after all nodes are processed.*/ + + static int addWithCarry(Node head) + { + +/* If linked list is empty, then + return carry*/ + + if (head == null) + return 1; + +/* Add carry returned be next node call*/ + + int res = head.data + addWithCarry(head.next); + +/* Update data and return new carry*/ + + head.data = (res) % 10; + return (res) / 10; + } + +/* This function mainly uses addWithCarry().*/ + + static Node addOne(Node head) + { + +/* Add 1 to linked list from end to beginning*/ + + int carry = addWithCarry(head); + +/* If there is carry after processing all nodes, + then we need to add a new node to linked list*/ + + if (carry > 0) + { + Node newNode = newNode(carry); + newNode.next = head; +/*New node becomes head now*/ + +return newNode; + } + + return head; + } + +/* A utility function to print a linked list*/ + + static void printList(Node node) + { + while (node != null) + { + System.out.print(node.data); + node = node.next; + } + System.out.println(); + } + + /* Driver code */ + + public static void main(String[] args) + { + Node head = newNode(1); + head.next = newNode(9); + head.next.next = newNode(9); + head.next.next.next = newNode(9); + + System.out.print(""List is ""); + printList(head); + + head = addOne(head); + System.out.println(); + System.out.print(""Resultant list is ""); + printList(head); + } +} + + +"," '''Recursive Python program to add 1 to a linked list''' + + + '''Node class''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to create a new node with given data''' + +def newNode(data): + + new_node = Node(0) + new_node.data = data + new_node.next = None + return new_node + + '''Recursively add 1 from end to beginning and returns +carry after all nodes are processed.''' + +def addWithCarry(head): + + ''' If linked list is empty, then + return carry''' + + if (head == None): + return 1 + + ''' Add carry returned be next node call''' + + res = head.data + addWithCarry(head.next) + + ''' Update data and return new carry''' + + head.data = int((res) % 10) + return int((res) / 10) + + '''This function mainly uses addWithCarry().''' + +def addOne(head): + + ''' Add 1 to linked list from end to beginning''' + + carry = addWithCarry(head) + + ''' If there is carry after processing all nodes, + then we need to add a new node to linked list''' + + if (carry != 0): + + newNode = Node(0) + newNode.data = carry + newNode.next = head + '''New node becomes head now''' + + return newNode + return head + + '''A utility function to print a linked list''' + +def printList(node): + + while (node != None): + + print( node.data,end = """") + node = node.next + + print(""\n"") + + '''Driver program to test above function''' + + +head = newNode(1) +head.next = newNode(9) +head.next.next = newNode(9) +head.next.next.next = newNode(9) + +print(""List is "") +printList(head) + +head = addOne(head) + +print(""\nResultant list is "") +printList(head) + + + +" +All unique triplets that sum up to a given value,"/*Java program to find all unique triplets +without using any extra space.*/ + +import java.util.*; +public class Main +{ +/* Function to all find unique triplets + without using extra space*/ + + public static void findTriplets(int a[], int n, int sum) + { + int i; +/* Sort the input array*/ + + Arrays.sort(a); +/* For handling the cases when no such + triplets exits.*/ + + boolean flag = false; +/* Iterate over the array from start to n-2.*/ + + for (i = 0; i < n - 2; i++) + { + if (i == 0 || a[i] > a[i - 1]) + { +/* Index of the first element in + remaining range.*/ + + int start = i + 1; +/* Index of the last element*/ + + int end = n - 1; +/* Setting our new target*/ + + int target = sum - a[i]; + while (start < end) + { +/* Checking if current element + is same as previous*/ + + if (start > i + 1 + && a[start] == a[start - 1]) + { + start++; + continue; + } +/* Checking if current element is + same as previous*/ + + if (end < n - 1 + && a[end] == a[end + 1]) + { + end--; + continue; + } +/* If we found the triplets then print it + and set the flag*/ + + if (target == a[start] + a[end]) + { + System.out.print(""["" + a[i] + + "","" + a[start] + + "","" + a[end] + ""] ""); + flag = true; + start++; + end--; + } +/* If target is greater then + increment the start index*/ + + else if (target > (a[start] + a[end])) + { + start++; + } +/* If target is smaller than + decrement the end index*/ + + else { + end--; + } + } + } + } +/* If no such triplets found*/ + + if (flag == false) { + System.out.print(""No Such Triplets Exist""); + } + } + +/*Driver code*/ + + public static void main(String[] args) { + int a[] = { 12, 3, 6, 1, 6, 9 }; + int n = a.length; + int sum = 24;/* Function call*/ + + findTriplets(a, n, sum); + } +}"," '''Python3 program to find all +unique triplets without using +any extra space.''' + '''Function to all find unique +triplets without using extra +space''' + +def findTriplets(a, n, sum): + ''' Sort the input array''' + + a.sort() + ''' For handling the cases + when no such triplets exits.''' + + flag = False + ''' Iterate over the array from + start to n-2.''' + + for i in range(n - 2): + if (i == 0 or + a[i] > a[i - 1]): + ''' Index of the first + element in remaining + range.''' + + start = i + 1 + ''' Index of the last + element''' + + end = n - 1 + ''' Setting our new target''' + + target = sum - a[i] + while (start < end): + ''' Checking if current element + is same as previous''' + + if (start > i + 1 and + a[start] == a[start - 1]): + start += 1 + continue + ''' Checking if current + element is same as + previous''' + + if (end < n - 1 and + a[end] == a[end + 1]): + end -= 1 + continue + ''' If we found the triplets + then print it and set the + flag''' + + if (target == a[start] + a[end]): + print(""["", a[i], "","", + a[start], "","", + a[end], ""]"", + end = "" "") + flag = True + start += 1 + end -= 1 + ''' If target is greater then + increment the start index''' + + elif (target > + (a[start] + a[end])): + start += 1 + ''' If target is smaller than + decrement the end index''' + + else: + end -= 1 + ''' If no such triplets found''' + + if (flag == False): + print(""No Such Triplets Exist"") + '''Driver code''' + +if __name__ == ""__main__"": + a = [12, 3, 6, 1, 6, 9] + n = len(a) + sum = 24 + ''' Function call''' + + findTriplets(a, n, sum)" +Partition problem | DP-18,"/*A Dynamic Programming based +Java program to partition problem*/ + +import java.io.*; +class GFG{ +/*Returns true if arr[] can be partitioned +in two subsets of equal sum, otherwise false*/ + +public static boolean findPartiion(int arr[], int n) +{ + int sum = 0; + int i, j; +/* Calculate sum of all elements*/ + + for(i = 0; i < n; i++) + sum += arr[i]; + if (sum % 2 != 0) + return false; + boolean[] part = new boolean[sum / 2 + 1]; +/* Initialze the part array + as 0*/ + + for(i = 0; i <= sum / 2; i++) + { + part[i] = false; + } +/* Fill the partition table in + bottom up manner*/ + + for(i = 0; i < n; i++) + { +/* The element to be included + in the sum cannot be + greater than the sum*/ + + for(j = sum / 2; j >= arr[i]; j--) + { +/* Check if sum - arr[i] could be + formed from a subset using elements + before index i*/ + + if (part[j - arr[i]] == true || j == arr[i]) + part[j] = true; + } + } + return part[sum / 2]; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 3, 3, 2, 3, 2 }; + int n = 6; +/* Function call*/ + + if (findPartiion(arr, n) == true) + System.out.println(""Can be divided into two "" + + ""subsets of equal sum""); + else + System.out.println(""Can not be divided into "" + + ""two subsets of equal sum""); +} +}"," '''A Dynamic Programming based +Python3 program to partition problem''' + '''Returns true if arr[] can be partitioned +in two subsets of equal sum, otherwise false''' + +def findPartiion(arr, n) : + Sum = 0 + ''' Calculate sum of all elements''' + + for i in range(n) : + Sum += arr[i] + if (Sum % 2 != 0) : + return 0 + part = [0] * ((Sum // 2) + 1) + ''' Initialze the part array as 0''' + + for i in range((Sum // 2) + 1) : + part[i] = 0 + ''' Fill the partition table in bottom up manner''' + + for i in range(n) : + ''' the element to be included + in the sum cannot be + greater than the sum''' + + for j in range(Sum // 2, arr[i] - 1, -1) : + ''' check if sum - arr[i] + could be formed + from a subset + using elements + before index i''' + + if (part[j - arr[i]] == 1 or j == arr[i]) : + part[j] = 1 + return part[Sum // 2] + '''Drive code ''' + +arr = [ 1, 3, 3, 2, 3, 2 ] +n = len(arr) + '''Function call''' + +if (findPartiion(arr, n) == 1) : + print(""Can be divided into two subsets of equal sum"") +else : + print(""Can not be divided into two subsets of equal sum"")" +Check linked list with a loop is palindrome or not,"/*Java program to check if a linked list +with loop is palindrome or not.*/ + +import java.util.*; + +class GfG +{ + +/* Link list node */ + +static class Node +{ + int data; + Node next; +} + +/* 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 */ + +static Node getLoopstart(Node loop_node, + Node head) +{ + Node ptr1 = loop_node; + Node ptr2 = loop_node; + +/* Count the number of nodes in loop*/ + + int k = 1, i; + while (ptr1.next != ptr2) + { + ptr1 = ptr1.next; + k++; + } + +/* Fix one pointer to head*/ + + ptr1 = head; + +/* And the other pointer to k + nodes after head*/ + + ptr2 = head; + for (i = 0; i < k; i++) + ptr2 = ptr2.next; + + /* Move both pointers at the same pace, + they will meet at loop starting node */ + + while (ptr2 != ptr1) + { + ptr1 = ptr1.next; + ptr2 = ptr2.next; + } + return ptr1; +} + +/* This function detects and find +loop starting node in the list*/ + +static Node detectAndgetLoopstarting(Node head) +{ + Node slow_p = head, fast_p = head,loop_start = null; + +/* Start traversing list and detect loop*/ + + while (slow_p != null && fast_p != null && + fast_p.next != null) + { + slow_p = slow_p.next; + fast_p = fast_p.next.next; + + /* If slow_p and fast_p meet then find + the loop starting node*/ + + if (slow_p == fast_p) + { + loop_start = getLoopstart(slow_p, head); + break; + } + } + +/* Return starting node of loop*/ + + return loop_start; +} + +/*Utility function to check if +a linked list with loop is +palindrome with given starting point.*/ + +static boolean isPalindromeUtil(Node head, + Node loop_start) +{ + Node ptr = head; + Stack s = new Stack (); + +/* Traverse linked list until last node + is equal to loop_start and store the + elements till start in a stack*/ + + 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; + +/* Traverse linked list until last node is + equal to loop_start second time*/ + + while (ptr != loop_start || count != 1) + { +/* Compare data of node with the top of stack + If equal then continue*/ + + if (ptr.data == s.peek()) + s.pop(); + +/* Else return false*/ + + else + return false; + + if (ptr == loop_start) + count = 1; + ptr = ptr.next; + } + +/* Return true if linked list is palindrome*/ + + return true; +} + +/*Function to find if linked list +is palindrome or not*/ + +static boolean isPalindrome(Node head) +{ +/* Find the loop starting node*/ + + Node loop_start = detectAndgetLoopstarting(head); + +/* Check if linked list is palindrome*/ + + return isPalindromeUtil(head, loop_start); +} + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; +} + +/* Driver code*/ + +public static void main(String[] args) +{ + 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); + + /* Create a loop for testing */ + + head.next.next.next.next.next = head.next.next; + + if(isPalindrome(head) == true) + System.out.println(""Palindrome""); + else + System.out.println(""Not Palindrome""); + +} +} + + +"," '''Python3 program to check if a linked list +with loop is palindrome or not.''' + + + '''Node class''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + + '''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''' + +def getLoopstart(loop_node,head): + + ptr1 = loop_node + ptr2 = loop_node + + ''' Count the number of nodes in loop''' + + k = 1 + i = 0 + while (ptr1.next != ptr2): + + ptr1 = ptr1.next + k = k + 1 + + + ''' Fix one pointer to head''' + + ptr1 = head + + ''' And the other pointer to k + nodes after head''' + + ptr2 = head + i = 0 + while ( i < k ) : + ptr2 = ptr2.next + i = i + 1 + + ''' Move both pointers at the same pace, + they will meet at loop starting node */''' + + while (ptr2 != ptr1): + + ptr1 = ptr1.next + ptr2 = ptr2.next + + return ptr1 + + '''This function detects and find +loop starting node in the list''' + +def detectAndgetLoopstarting(head): + + slow_p = head + fast_p = head + loop_start = None + + ''' Start traversing list and detect loop''' + + while (slow_p != None and fast_p != None and + fast_p.next != None) : + + slow_p = slow_p.next + fast_p = fast_p.next.next + + ''' If slow_p and fast_p meet then find + the loop starting node''' + + if (slow_p == fast_p) : + + loop_start = getLoopstart(slow_p, head) + break + + ''' Return starting node of loop''' + + return loop_start + + '''Utility function to check if +a linked list with loop is +palindrome with given starting point.''' + +def isPalindromeUtil(head, loop_start): + + ptr = head + s = [] + + ''' Traverse linked list until last node + is equal to loop_start and store the + elements till start in a stack''' + + count = 0 + while (ptr != loop_start or count != 1): + + s.append(ptr.data) + if (ptr == loop_start) : + count = 1 + ptr = ptr.next + + ptr = head + count = 0 + + ''' Traverse linked list until last node is + equal to loop_start second time''' + + while (ptr != loop_start or count != 1): + + ''' Compare data of node with the top of stack + If equal then continue''' + + if (ptr.data == s[-1]): + s.pop() + + ''' Else return False''' + + else: + return False + + if (ptr == loop_start) : + count = 1 + ptr = ptr.next + + ''' Return True if linked list is palindrome''' + + return True + + '''Function to find if linked list +is palindrome or not''' + +def isPalindrome(head) : + + ''' Find the loop starting node''' + + loop_start = detectAndgetLoopstarting(head) + + ''' Check if linked list is palindrome''' + + return isPalindromeUtil(head, loop_start) + +def newNode(key) : + + temp = Node(0) + temp.data = key + temp.next = None + return temp + + '''Driver code''' + +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) + + '''Create a loop for testing''' + +head.next.next.next.next.next = head.next.next + +if(isPalindrome(head) == True): + print(""Palindrome"") +else: + print(""Not Palindrome"") + + +" +Minimum number of jumps to reach end,"/*Java program to find Minimum +number of jumps to reach end*/ + +class GFG { +/* Returns Minimum number + of jumps to reach end*/ + + static int minJumps(int arr[], + int n) + { +/* jumps[0] will + hold the result*/ + + int[] jumps = new int[n]; + int min; +/* Minimum number of jumps + needed to reach last + element from last elements + itself is always 0*/ + + jumps[n - 1] = 0; +/* Start from the second + element, move from right + to left and construct the + jumps[] array where jumps[i] + represents minimum number of + jumps needed to reach arr[m-1] + from arr[i]*/ + + for (int i = n - 2; i >= 0; i--) { +/* If arr[i] is 0 then arr[n-1] + can't be reached from here*/ + + if (arr[i] == 0) + jumps[i] = Integer.MAX_VALUE; +/* If we can direcly reach to + the end point from here then + jumps[i] is 1*/ + + else if (arr[i] >= n - i - 1) + jumps[i] = 1; +/* Otherwise, to find out + the minimum number of + jumps needed to reach + arr[n-1], check all the + points reachable from + here and jumps[] value + for those points*/ + + else { +/* initialize min value*/ + + min = Integer.MAX_VALUE; +/* following loop checks + with all reachable points + and takes the minimum*/ + + for (int j = i + 1; j < n && j <= arr[i] + i; j++) { + if (min > jumps[j]) + min = jumps[j]; + } +/* Handle overflow*/ + + if (min != Integer.MAX_VALUE) + jumps[i] = min + 1; + else +/*or Integer.MAX_VALUE*/ + +jumps[i] = min; + } + } + return jumps[0]; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 1, 3, 6, 1, 0, 9 }; + int size = arr.length; + System.out.println(""Minimum number of"" + + "" jumps to reach end is "" + minJumps(arr, size)); + } +}"," '''Python3 progrma to find Minimum +number of jumps to reach end''' + + '''Returns Minimum number of +jumps to reach end''' + +def minJumps(arr, n): ''' jumps[0] will hold the result''' + + jumps = [0 for i in range(n)] + ''' Minimum number of jumps needed + to reach last element from + last elements itself is always 0 + jumps[n-1] is also initialized to 0''' + + ''' Start from the second element, + move from right to left and + construct the jumps[] array where + jumps[i] represents minimum number + of jumps needed to reach arr[m-1] + form arr[i]''' + + for i in range(n-2, -1, -1): ''' If arr[i] is 0 then arr[n-1] + can't be reached from here''' + + if (arr[i] == 0): + jumps[i] = float('inf') + ''' If we can directly reach to + the end point from here then + jumps[i] is 1''' + + elif (arr[i] >= n - i - 1): + jumps[i] = 1 + ''' Otherwise, to find out the + minimum number of jumps + needed to reach arr[n-1], + check all the points + reachable from here and + jumps[] value for those points''' + + else: + ''' initialize min value''' + + min = float('inf') + ''' following loop checks with + all reachavle points and + takes the minimum''' + + for j in range(i + 1, n): + if (j <= arr[i] + i): + if (min > jumps[j]): + min = jumps[j] + ''' Handle overflow''' + + if (min != float('inf')): + jumps[i] = min + 1 + else: + ''' or INT_MAX''' + + jumps[i] = min + return jumps[0] + '''Driver program to test above function''' + +arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5] +n = len(arr) +print('Minimum number of jumps to reach', + 'end is', minJumps(arr, n-1))" +Recaman's sequence,"/*Java program to print n-th number +in Recaman's sequence*/ + +import java.util.*; +class GFG +{ +/*Prints first n terms of Recaman sequence*/ + +static void recaman(int n) +{ + if (n <= 0) + return; +/* Print first term and store it in a hash*/ + + System.out.printf(""%d, "", 0); + HashSet s = new HashSet(); + s.add(0); +/* Print remaining terms using + recursive formula.*/ + + int prev = 0; + for (int i = 1; i< n; i++) + { + int curr = prev - i; +/* If arr[i-1] - i is negative or + already exists.*/ + + if (curr < 0 || s.contains(curr)) + curr = prev + i; + s.add(curr); + System.out.printf(""%d, "", curr); + prev = curr; + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 17; + recaman(n); +} +}"," '''Python3 program to print n-th number in +Recaman's sequence + ''' '''Prints first n terms of Recaman sequence''' + +def recaman(n): + if(n <= 0): + return + ''' Print first term and store it in a hash''' + + print(0, "","", end='') + s = set([]) + s.add(0) + ''' Print remaining terms using recursive + formula.''' + + prev = 0 + for i in range(1, n): + curr = prev - i + ''' If arr[i-1] - i is negative or + already exists.''' + + if(curr < 0 or curr in s): + curr = prev + i + s.add(curr) + print(curr, "","", end='') + prev = curr + '''Driver code''' + +if __name__=='__main__': + n = 17 + recaman(n)" +Row-wise common elements in two diagonals of a square matrix,"/*Java program to find common +elements in two diagonals.*/ + +import java.io.*; +class GFG +{ + int MAX = 100; +/* Returns count of row wise same elements + in two diagonals of mat[n][n]*/ + + static int countCommon(int mat[][], int n) + { + int res = 0; + for (int i = 0; i < n; i++) + if (mat[i][i] == mat[i][n - i - 1]) + res++; + return res; + } +/* Driver Code*/ + + public static void main(String args[])throws IOException + { + int mat[][] = {{1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + System.out.println(countCommon(mat, 3)); + } +}"," '''Python3 program to find common +elements in two diagonals.''' + +Max = 100 + '''Returns count of row wise same +elements in two diagonals of +mat[n][n]''' + +def countCommon(mat, n): + res = 0 + for i in range(n): + if mat[i][i] == mat[i][n-i-1] : + res = res + 1 + return res + '''Driver Code''' + +mat = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] +print(countCommon(mat, 3))" +Longest Common Extension / LCE | Set 1 (Introduction and Naive Method),"/*A Java Program to find the length of longest +common extension using Naive Method*/ + +import java.util.*; +class GFG +{ + +/*Structure to represent a query of form (L,R)*/ + +static class Query +{ + int L, R; + Query(int L, int R) + { + this.L = L; + this.R = R; + } +}; + +/*A utility function to find longest common +extension from index - L and index - R*/ + +static int LCE(String str, int n, int L, int R) +{ + int length = 0; + while ( R + length < n && str.charAt(L + length) == str.charAt(R + length)) + length++; + return(length); +} + +/*A function to answer queries of longest +common extension*/ + +static void LCEQueries(String str, int n, Query q[], + int m) +{ + for (int i = 0; i < m; i++) + { + int L = q[i].L; + int R = q[i].R; + System.out.printf(""LCE (%d, %d) = %d\n"", L, R, + LCE(str, n, L, R)); + } + return; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + String str = ""abbababba""; + int n = str.length(); + +/* LCA Queries to answer*/ + + Query q[] = new Query[3]; + q[0] = new Query(1, 2); + q[1] = new Query(1, 6); + q[2] = new Query (0, 5); + int m = q.length; + LCEQueries(str, n, q, m); +} +} + + +", +Sum of middle row and column in Matrix,"/*java program to find sum of +middle row and column in matrix*/ + +import java.io.*; +class GFG { +static int MAX = 100; + static void middlesum(int mat[][], int n) +{ + int row_sum = 0, col_sum = 0; +/* loop for sum of row*/ + + for (int i = 0; i < n; i++) + row_sum += mat[n / 2][i]; + System.out.println ( ""Sum of middle row = "" + + row_sum); +/* loop for sum of column*/ + + for (int i = 0; i < n; i++) + col_sum += mat[i][n / 2]; + System.out.println ( ""Sum of middle column = "" + + col_sum); +} +/*Driver function*/ + + public static void main (String[] args) { + int mat[][] = {{2, 5, 7}, + {3, 7, 2}, + {5, 6, 9}}; + middlesum(mat, 3); + } +}"," '''Python program to find sum of +middle row and column in matrix''' + +def middlesum(mat,n): + row_sum = 0 + col_sum = 0 + ''' loop for sum of row''' + + for i in range(n): + row_sum += mat[n // 2][i] + print(""Sum of middle row = "", + row_sum) + ''' loop for sum of column''' + + for i in range(n): + col_sum += mat[i][n // 2] + print(""Sum of middle column = "", + col_sum) + '''Driver code''' + +mat= [[2, 5, 7], + [3, 7, 2], + [5, 6, 9]] +middlesum(mat, 3)" +Longest Palindromic Subsequence | DP-12,"/*A Dynamic Programming based Java +Program for the Egg Dropping Puzzle*/ + +class LPS +{ +/* A utility function to get max of two integers*/ + + static int max (int x, int y) { return (x > y)? x : y; } +/* Returns the length of the longest + palindromic subsequence in seq*/ + + static int lps(String seq) + { + int n = seq.length(); + int i, j, cl; +/* Create a table to store results of subproblems*/ + + int L[][] = new int[n][n]; +/* Strings of length 1 are palindrome of lentgh 1*/ + + for (i = 0; i < n; i++) + L[i][i] = 1; +/* Build the table. Note that the lower + diagonal values of table are + useless and not filled in the process. + The values are filled in a manner similar + to Matrix Chain Multiplication DP solution (See +www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). +https: + cl is length of substring*/ + + for (cl=2; cl<=n; cl++) + { + for (i=0; i> 4); + } +/* Driver code*/ + + public static void main(String[] args) + { + int num = 31; + System.out.println(countSetBitsRec(num)); + } +}"," '''Python3 program to count set bits by pre-storing +count set bits in nibbles.''' + +num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; + '''Recursively get nibble of a given number +and map them in the array''' + +def countSetBitsRec(num): + nibble = 0; + if(0 == num): + return num_to_bits[0]; + ''' Find last nibble''' + + nibble = num & 0xf; + ''' Use pre-stored values to find count + in last nibble plus recursively add + remaining nibbles.''' + + return num_to_bits[nibble] + countSetBitsRec(num >> 4); + '''Driver code''' + +num = 31; +print(countSetBitsRec(num));" +Program for Method Of False Position,"/*java program for implementation +of Bisection Method for +solving equations*/ + +import java.io.*; +class GFG { + static int MAX_ITER = 1000000; +/* An example function whose + solution is determined using + Bisection Method. The function + is x^3 - x^2 + 2*/ + + static double func(double x) + { + return (x * x * x - x * x + 2); + } +/* Prints root of func(x) + in interval [a, b]*/ + + static void regulaFalsi(double a, double b) + { + if (func(a) * func(b) >= 0) + { + System.out.println(""You have not assumed right a and b""); + } +/* Initialize result*/ + + double c = a; + for (int i = 0; i < MAX_ITER; i++) + { +/* Find the point that touches x axis*/ + + c = (a * func(b) - b * func(a)) + / (func(b) - func(a)); +/* Check if the above found point is root*/ + + if (func(c) == 0) + break; +/* Decide the side to repeat the steps*/ + + else if (func(c) * func(a) < 0) + b = c; + else + a = c; + } + System.out.println(""The value of root is : "" + (int)c); + } +/* Driver program*/ + + public static void main(String[] args) + { +/* Initial values assumed*/ + + double a = -200, b = 300; + regulaFalsi(a, b); + } +}"," '''Python3 implementation of Bisection +Method for solving equations''' + +MAX_ITER = 1000000 + '''An example function whose solution +is determined using Bisection Method. +The function is x^3 - x^2 + 2''' + +def func( x ): + return (x * x * x - x * x + 2) + '''Prints root of func(x) in interval [a, b]''' + +def regulaFalsi( a , b): + if func(a) * func(b) >= 0: + print(""You have not assumed right a and b"") + return -1 + '''Initialize result''' + + c = a + for i in range(MAX_ITER): + ''' Find the point that touches x axis''' + + c = (a * func(b) - b * func(a))/ (func(b) - func(a)) + ''' Check if the above found point is root''' + + if func(c) == 0: + break + ''' Decide the side to repeat the steps''' + + elif func(c) * func(a) < 0: + b = c + else: + a = c + print(""The value of root is : "" , '%.4f' %c) + '''Driver code to test above function''' + '''Initial values assumed''' + +a =-200 +b = 300 +regulaFalsi(a, b)" +Check if a doubly linked list of characters is palindrome or not,"/*Java program to check if doubly +linked list is palindrome or not*/ + +class GFG +{ + +/*Structure of node*/ + +static class Node +{ + char data; + Node next; + Node prev; +}; + +/* 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. */ + +static Node push(Node head_ref, char new_data) +{ + 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; + return head_ref; +} + +/*Function to check if list is palindrome or not*/ + +static boolean isPalindrome(Node left) +{ + if (left == null) + return true; + +/* Find rightmost node*/ + + 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; +} + +/*Driver program*/ + +public static void main(String[] args) +{ + Node head = null; + head = push(head, 'l'); + head = push(head, 'e'); + head = push(head, 'v'); + head = push(head, 'e'); + head = push(head, 'l'); + + if (isPalindrome(head)) + System.out.printf(""It is Palindrome""); + else + System.out.printf(""Not Palindrome""); +} +} + + +"," '''Python3 program to check if doubly +linked list is a palindrome or not''' + + '''Structure of node''' + + +class Node: + + def __init__(self, data, next, prev): + self.data = data + self.next = next + self.prev = prev + + '''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.''' + +def push(head_ref, new_data): + + new_node = Node(new_data, head_ref, None) + + if head_ref != None: + head_ref.prev = new_node + head_ref = new_node + + return head_ref + + '''Function to check if list is palindrome or not''' + +def isPalindrome(left): + + if left == None: + return True + + ''' Find rightmost node''' + + right = left + while right.next != None: + right = right.next + + while left != right: + + if left.data != right.data: + return False + + left = left.next + right = right.prev + + return True + + '''Driver program''' + +if __name__ == ""__main__"": + + head = None + head = push(head, 'l') + head = push(head, 'e') + head = push(head, 'v') + head = push(head, 'e') + head = push(head, 'l') + + if isPalindrome(head): + print(""It is Palindrome"") + else: + print(""Not Palindrome"") + + +" +Shortest distance between two nodes in BST,"/*Java program to find distance between +two nodes in BST*/ + +class GfG { + +static class Node { + Node left, right; + int key; +} + +static Node newNode(int key) +{ + Node ptr = new Node(); + ptr.key = key; + ptr.left = null; + ptr.right = null; + return ptr; +} + +/*Standard BST insert function*/ + +static Node insert(Node root, int key) +{ + if (root == null) + root = newNode(key); + else if (root.key > key) + root.left = insert(root.left, key); + else if (root.key < key) + root.right = insert(root.right, key); + return root; +} + +/*This function returns distance of x from +root. This function assumes that x exists +in BST and BST is not NULL.*/ + +static int distanceFromRoot(Node root, int x) +{ + if (root.key == x) + return 0; + else if (root.key > x) + return 1 + distanceFromRoot(root.left, x); + return 1 + distanceFromRoot(root.right, x); +} + +/*Returns minimum distance beween a and b. +This function assumes that a and b exist +in BST.*/ + +static int distanceBetween2(Node root, int a, int b) +{ + if (root == null) + return 0; + +/* Both keys lie in left*/ + + if (root.key > a && root.key > b) + return distanceBetween2(root.left, a, b); + +/* Both keys lie in right +same path*/ + +if (root.key < a && root.key < b) + return distanceBetween2(root.right, a, b); + +/* Lie in opposite directions (Root is + LCA of two nodes)*/ + + if (root.key >= a && root.key <= b) + return distanceFromRoot(root, a) + distanceFromRoot(root, b); + + return 0; +} + +/*This function make sure that a is smaller +than b before making a call to findDistWrapper()*/ + +static int findDistWrapper(Node root, int a, int b) +{ + int temp = 0; +if (a > b) + { + temp = a; + a = b; + b = temp; + } +return distanceBetween2(root, a, b); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = null; + root = insert(root, 20); + insert(root, 10); + insert(root, 5); + insert(root, 15); + insert(root, 30); + insert(root, 25); + insert(root, 35); + System.out.println(findDistWrapper(root, 5, 35)); +} +} +"," '''Python3 program to find distance between +two nodes in BST''' + +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + + '''Standard BST insert function''' + +def insert(root, key): + if root == None: + root = newNode(key) + elif root.key > key: + root.left = insert(root.left, key) + elif root.key < key: + root.right = insert(root.right, key) + return root + + '''This function returns distance of x from +root. This function assumes that x exists +in BST and BST is not NULL.''' + +def distanceFromRoot(root, x): + if root.key == x: + return 0 + elif root.key > x: + return 1 + distanceFromRoot(root.left, x) + return 1 + distanceFromRoot(root.right, x) + + '''Returns minimum distance beween a and b. +This function assumes that a and b exist +in BST.''' + +def distanceBetween2(root, a, b): + if root == None: + return 0 + + ''' Both keys lie in left''' + + if root.key > a and root.key > b: + return distanceBetween2(root.left, a, b) + + ''' Both keys lie in right +same path''' + + if root.key < a and root.key < b: + return distanceBetween2(root.right, a, b) + + ''' Lie in opposite directions + (Root is LCA of two nodes)''' + + if root.key >= a and root.key <= b: + return (distanceFromRoot(root, a) + + distanceFromRoot(root, b)) + + '''This function make sure that a is smaller +than b before making a call to findDistWrapper()''' + +def findDistWrapper(root, a, b): + if a > b: + a, b = b, a + return distanceBetween2(root, a, b) + + '''Driver code''' + +if __name__ == '__main__': + root = None + root = insert(root, 20) + insert(root, 10) + insert(root, 5) + insert(root, 15) + insert(root, 30) + insert(root, 25) + insert(root, 35) + a, b = 5, 55 + print(findDistWrapper(root, 5, 35)) + + +" +Find the fractional (or n/k,"/*Java program to find fractional node in +a linked list*/ + +public class FractionalNodell +{ + /* Linked list node */ + + static class Node{ + int data; + Node next; +/* Constructor*/ + + Node (int data){ + this.data = data; + } + } + /* Function to find fractional node in the + linked list */ + + static Node fractionalNodes(Node head, int k) + { +/* Corner cases*/ + + if (k <= 0 || head == null) + return null; + Node fractionalNode = null; +/* Traverse the given list*/ + + int i = 0; + for (Node temp = head; temp != null; + temp = temp.next){ +/* For every k nodes, we move + fractionalNode one step ahead.*/ + + if (i % k == 0){ +/* First time we see a multiple of k*/ + + if (fractionalNode == null) + fractionalNode = head; + else + fractionalNode = fractionalNode.next; + } + i++; + } + return fractionalNode; + } +/* A utility function to print a linked list*/ + + static void printList(Node node) + { + while (node != null) + { + System.out.print(node.data+"" ""); + node = node.next; + } + System.out.println(); + } + /* Driver program to test above function */ + + public static void main(String[] args) { + Node head = new Node(1); + head.next = new Node(2); + head.next.next = new Node(3); + head.next.next.next = new Node(4); + head.next.next.next.next = new Node(5); + int k =2; + System.out.print(""List is ""); + printList(head); + Node answer = fractionalNodes(head, k); + System.out.println(""Fractional node is ""+ + answer.data); + } +}"," '''Python3 program to find fractional node +in a linked list''' + +import math + '''Linked list node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + '''Function to create a new node +with given data''' + +def newNode(data): + new_node = Node(data) + new_node.data = data + new_node.next = None + return new_node + '''Function to find fractional node +in the linked list''' + +def fractionalNodes(head, k): + ''' Corner cases''' + + if (k <= 0 or head == None): + return None + fractionalNode = None + ''' Traverse the given list''' + + i = 0 + temp = head + while (temp != None): + ''' For every k nodes, we move + fractionalNode one step ahead. ''' + + if (i % k == 0): + ''' First time we see a multiple of k''' + + if (fractionalNode == None): + fractionalNode = head + else: + fractionalNode = fractionalNode.next + i = i + 1 + temp = temp.next + return fractionalNode + '''A utility function to print a linked list''' + +def prList(node): + while (node != None): + print(node.data, end = ' ') + node = node.next + '''Driver Code''' + +if __name__ == '__main__': + 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) + k = 2 + print(""List is"", end = ' ') + prList(head) + answer = fractionalNodes(head, k) + print(""\nFractional node is"", end = ' ') + print(answer.data)" +Optimal Binary Search Tree | DP-24,"/*A naive recursive implementation of optimal binary +search tree problem*/ + +public class GFG +{ +/* A utility function to get sum of array elements + freq[i] to freq[j]*/ + + static int sum(int freq[], int i, int j) + { + int s = 0; + for (int k = i; k <=j; k++) + s += freq[k]; + return s; + } +/* A recursive function to calculate cost of + optimal binary search tree*/ + + static int optCost(int freq[], int i, int j) + { +/* Base cases +no elements in this subarray*/ + +if (j < i) + return 0; +/*one element in this subarray*/ + +if (j == i) + return freq[i]; +/* Get sum of freq[i], freq[i+1], ... freq[j]*/ + + int fsum = sum(freq, i, j); +/* Initialize minimum value*/ + + int min = Integer.MAX_VALUE; +/* One by one consider all elements as root and + recursively find cost of the BST, compare the + cost with min and update min if needed*/ + + for (int r = i; r <= j; ++r) + { + int cost = optCost(freq, i, r-1) + + optCost(freq, r+1, j); + if (cost < min) + min = cost; + } +/* Return minimum value*/ + + return min + fsum; + } +/* The main function that calculates minimum cost of + a Binary Search Tree. It mainly uses optCost() to + find the optimal cost.*/ + + static int optimalSearchTree(int keys[], int freq[], int n) + { +/* Here array keys[] is assumed to be sorted in + increasing order. If keys[] is not sorted, then + add code to sort keys, and rearrange freq[] + accordingly.*/ + + return optCost(freq, 0, n-1); + } +/* Driver code*/ + + public static void main(String[] args) { + int keys[] = {10, 12, 20}; + int freq[] = {34, 8, 50}; + int n = keys.length; + System.out.println(""Cost of Optimal BST is "" + + optimalSearchTree(keys, freq, n)); + } +}"," '''A naive recursive implementation of +optimal binary search tree problem''' + + '''A utility function to get sum of +array elements freq[i] to freq[j]''' + +def Sum(freq, i, j): + s = 0 + for k in range(i, j + 1): + s += freq[k] + return s + '''A recursive function to calculate +cost of optimal binary search tree''' + +def optCost(freq, i, j): ''' Base cases +no elements in this subarray''' + + if j < i: + return 0 + + '''one element in this subarray''' + + if j == i: + return freq[i] + ''' Get sum of freq[i], freq[i+1], ... freq[j]''' + + fsum = Sum(freq, i, j) + ''' Initialize minimum value''' + + Min = 999999999999 + ''' One by one consider all elements as + root and recursively find cost of + the BST, compare the cost with min + and update min if needed''' + + for r in range(i, j + 1): + cost = (optCost(freq, i, r - 1) + + optCost(freq, r + 1, j)) + if cost < Min: + Min = cost + ''' Return minimum value''' + + return Min + fsum + '''The main function that calculates minimum +cost of a Binary Search Tree. It mainly +uses optCost() to find the optimal cost.''' + +def optimalSearchTree(keys, freq, n): + ''' Here array keys[] is assumed to be + sorted in increasing order. If keys[] + is not sorted, then add code to sort + keys, and rearrange freq[] accordingly.''' + + return optCost(freq, 0, n - 1) + '''Driver Code''' + +if __name__ == '__main__': + keys = [10, 12, 20] + freq = [34, 8, 50] + n = len(keys) + print(""Cost of Optimal BST is"", + optimalSearchTree(keys, freq, n))" +Sorted insert in a doubly linked list with head and tail pointers,"/* Java program to insetail nodes in doubly +linked list such that list remains in +ascending order on printing from left +to right */ + +import java.io.*; +import java.util.*; +/*A linked list node*/ + +class Node +{ + int info; + Node prev, next; +} +class GFG +{ + static Node head, tail; +/* Function to insetail new node*/ + + static void nodeInsetail(int key) + { + Node p = new Node(); + p.info = key; + p.next = null; +/* If first node to be insetailed in doubly + linked list*/ + + if (head == null) + { + head = p; + tail = p; + head.prev = null; + return; + } +/* If node to be insetailed has value less + than first node*/ + + if (p.info < head.info) + { + p.prev = null; + head.prev = p; + p.next = head; + head = p; + return; + } +/* If node to be insetailed has value more + than last node*/ + + if (p.info > tail.info) + { + p.prev = tail; + tail.next = p; + tail = p; + return; + } +/* Find the node before which we need to + insert p.*/ + + Node temp = head.next; + while (temp.info < p.info) + temp = temp.next; +/* Insert new node before temp*/ + + (temp.prev).next = p; + p.prev = temp.prev; + temp.prev = p; + p.next = temp; + } +/* Function to print nodes in from left to right*/ + + static void printList(Node temp) + { + while (temp != null) + { + System.out.print(temp.info + "" ""); + temp = temp.next; + } + } +/* Driver code*/ + + public static void main(String args[]) + { + head = tail = null; + nodeInsetail(30); + nodeInsetail(50); + nodeInsetail(90); + nodeInsetail(10); + nodeInsetail(40); + nodeInsetail(110); + nodeInsetail(60); + nodeInsetail(95); + nodeInsetail(23); + System.out.println(""Doubly linked list on printing from left to right""); + printList(head); + } +}"," '''Python program to insetail nodes in doubly +linked list such that list remains in +ascending order on printing from left +to right''' + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.info = data + self.next = None + self.prev = None +head = None +tail = None '''Function to insetail new node''' + +def nodeInsetail( key) : + global head + global tail + p = Node(0) + p.info = key + p.next = None + ''' If first node to be insetailed in doubly + linked list''' + + if ((head) == None) : + (head) = p + (tail) = p + (head).prev = None + return + ''' If node to be insetailed has value less + than first node''' + + if ((p.info) < ((head).info)) : + p.prev = None + (head).prev = p + p.next = (head) + (head) = p + return + ''' If node to be insetailed has value more + than last node''' + + if ((p.info) > ((tail).info)) : + p.prev = (tail) + (tail).next = p + (tail) = p + return + ''' Find the node before which we need to + insert p.''' + + temp = (head).next + while ((temp.info) < (p.info)) : + temp = temp.next + ''' Insert new node before temp''' + + (temp.prev).next = p + p.prev = temp.prev + temp.prev = p + p.next = temp + '''Function to print nodes in from left to right''' + +def printList(temp) : + while (temp != None) : + print( temp.info, end = "" "") + temp = temp.next + '''Driver program to test above functions''' + +nodeInsetail( 30) +nodeInsetail( 50) +nodeInsetail( 90) +nodeInsetail( 10) +nodeInsetail( 40) +nodeInsetail( 110) +nodeInsetail( 60) +nodeInsetail( 95) +nodeInsetail( 23) +print(""Doubly linked list on printing from left to right\n"" ) +printList(head)" +Check if an array represents Inorder of Binary Search tree or not,"/*Java program to check if a given array is sorted +or not.*/ + +class GFG { +/*Function that returns true if array is Inorder +traversal of any Binary Search Tree or not.*/ + + static boolean isInorder(int[] arr, int n) { +/* Array has one or no element*/ + + if (n == 0 || n == 1) { + return true; + } +/*Unsorted pair found*/ + +for (int i = 1; i < n; i++) + { + if (arr[i - 1] > arr[i]) { + return false; + } + } +/* No unsorted pair found*/ + + return true; + } +/*Drivers code*/ + + public static void main(String[] args) { + int arr[] = {19, 23, 25, 30, 45}; + int n = arr.length; + if (isInorder(arr, n)) { + System.out.println(""Yes""); + } else { + System.out.println(""Non""); + } + } +}"," '''Python 3 program to check if a given array +is sorted or not.''' + + '''Function that returns true if array is Inorder +traversal of any Binary Search Tree or not.''' + +def isInorder(arr, n): ''' Array has one or no element''' + + if (n == 0 or n == 1): + return True + for i in range(1, n, 1): + ''' Unsorted pair found''' + + if (arr[i - 1] > arr[i]): + return False + ''' No unsorted pair found''' + + return True + '''Driver code''' + +if __name__ == '__main__': + arr = [19, 23, 25, 30, 45] + n = len(arr) + if (isInorder(arr, n)): + print(""Yes"") + else: + print(""No"")" +How to check if a given number is Fibonacci number?,"/*Java program to check if x is a perfect square*/ + +class GFG +{ +/* A utility method that returns true if x is perfect square*/ + + static boolean isPerfectSquare(int x) + { + int s = (int) Math.sqrt(x); + return (s*s == x); + } +/* Returns true if n is a Fibonacci Number, else false*/ + + static boolean isFibonacci(int n) + { +/* n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both + is a perfect square*/ + + return isPerfectSquare(5*n*n + 4) || + isPerfectSquare(5*n*n - 4); + } +/* Driver method*/ + + public static void main(String[] args) + { + for (int i = 1; i <= 10; i++) + System.out.println(isFibonacci(i) ? i + "" is a Fibonacci Number"" : + i + "" is a not Fibonacci Number""); + } +}"," '''python program to check if x is a perfect square''' + +import math + '''A utility function that returns true if x is perfect square''' + +def isPerfectSquare(x): + s = int(math.sqrt(x)) + return s*s == x + '''Returns true if n is a Fibinacci Number, else false''' + +def isFibonacci(n): + ''' n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both + is a perferct square''' + + return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4) + '''A utility function to test above functions''' + +for i in range(1,11): + if (isFibonacci(i) == True): + print i,""is a Fibonacci Number"" + else: + print i,""is a not Fibonacci Number """ +Lucky Numbers,"/*Java program to check Lucky Number*/ + +import java.io.*; +class GFG +{ + public static int counter = 2; +/* Returns 1 if n is a lucky no. + ohterwise returns 0*/ + + static boolean isLucky(int n) + { +/* variable next_position is just + for readability of + the program we can remove it + and use n only*/ + + int next_position = n; + if(counter > n) + return true; + if(n%counter == 0) + return false; +/* calculate next position of input no*/ + + next_position -= next_position/counter; + counter++; + return isLucky(next_position); + } +/* driver program*/ + + public static void main (String[] args) + { + int x = 5; + if( isLucky(x) ) + System.out.println(x+"" is a lucky no.""); + else + System.out.println(x+"" is not a lucky no.""); + } +} +/*Contributed by Pramod Kumar*/ +"," '''Python program to check for lucky number''' + + '''Returns 1 if n is a lucky number +otherwise returns 0''' + +def isLucky(n): ''' Function attribute will act + as static variable + just for readability, can be + removed and used n instead''' + + next_position = n + if isLucky.counter > n: + return 1 + if n % isLucky.counter == 0: + return 0 + ''' Calculate next position of input number''' + + next_position = next_position - next_position /isLucky.counter + isLucky.counter = isLucky.counter + 1 + return isLucky(next_position) + '''Driver Code +Acts as static variable''' + +isLucky.counter = 2 +x = 5 +if isLucky(x): + print x,""is a Lucky number"" +else: + print x,""is not a Lucky number"" +" +Modify a matrix by rotating ith row exactly i times in clockwise direction,"/*java program for the above approach*/ + +import java.io.*; +import java.lang.*; +import java.util.*; + +class GFG { + +/* Function to reverse arr[] from start to end*/ + + static void reverse(int arr[], int start, int end) + { + while (start < end) { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + } + +/* Function to rotate every i-th + row of the matrix i times*/ + + static void rotateMatrix(int mat[][]) + { + int i = 0; + +/* Traverse the matrix row-wise*/ + + for (int rows[] : mat) { + +/* Reverse the current row*/ + + reverse(rows, 0, rows.length - 1); + +/* Reverse the first i elements*/ + + reverse(rows, 0, i - 1); + +/* Reverse the last (N - i) elements*/ + + reverse(rows, i, rows.length - 1); + +/* Increment count*/ + + i++; + } + +/* Print final matrix*/ + + for (int rows[] : mat) { + for (int cols : rows) { + System.out.print(cols + "" ""); + } + System.out.println(); + } + } + +/* Driver Code*/ + + public static void main(String[] args) + { + + int mat[][] = { { 1, 2, 3 }, + { 4, 5, 6 }, + { 7, 8, 9 } }; + + rotateMatrix(mat); + } +} + + +"," '''Python3 program for the above approach''' + + + '''Function to rotate every i-th +row of the matrix i times''' + +def rotateMatrix(mat): + + i = 0 + mat1 = [] + + ''' Traverse the matrix row-wise''' + + for it in mat: + + ''' Reverse the current row''' + + it.reverse() + + ''' Reverse the first i elements''' + + it1 = it[:i] + it1.reverse() + + ''' Reverse the last (N - i) elements''' + + it2 = it[i:] + it2.reverse() + + ''' Increment count''' + + i += 1 + mat1.append(it1 + it2) + + ''' Print final matrix''' + + for rows in mat1: + for cols in rows: + print(cols, end = "" "") + + print() + + '''Driver Code''' + +if __name__ == ""__main__"": + + mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] + + rotateMatrix(mat) + + +" +Print all leaf nodes of a Binary Tree from left to right,"/*Java program to print leaf nodes +from left to right*/ + +import java.util.*; + +class GFG{ + +/*A Binary Tree Node*/ + +static class Node +{ + public int data; + public Node left, right; +}; + +/*Function to print leaf +nodes from left to right*/ + +static void printLeafNodes(Node root) +{ + +/* If node is null, return*/ + + if (root == null) + return; + +/* If node is leaf node, print its data */ + + if (root.left == null && + root.right == null) + { + System.out.print(root.data + "" ""); + return; + } + +/* If left child exists, check for leaf + recursively*/ + + if (root.left != null) + printLeafNodes(root.left); + +/* If right child exists, check for leaf + recursively*/ + + if (root.right != null) + printLeafNodes(root.right); +} + +/*Utility function to create a new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; +} + +/*Driver code*/ + +public static void main(String []args) +{ + +/* Let us create binary tree shown in + above diagram*/ + + 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); + +/* Print leaf nodes of the given tree*/ + + printLeafNodes(root); +} +} + + +"," '''Python3 program to print +leaf nodes from left to right''' + + + '''Binary tree node''' + +class Node: + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + '''Function to print leaf +nodes from left to right''' + +def printLeafNodes(root: Node) -> None: + + ''' If node is null, return''' + + if (not root): + return + + ''' If node is leaf node, + print its data''' + + if (not root.left and + not root.right): + print(root.data, + end = "" "") + return + + ''' If left child exists, + check for leaf recursively''' + + if root.left: + printLeafNodes(root.left) + + ''' If right child exists, + check for leaf recursively''' + + if root.right: + printLeafNodes(root.right) + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Let us create binary tree shown in + above diagram''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.right.left = Node(5) + root.right.right = Node(8) + root.right.left.left = Node(6) + root.right.left.right = Node(7) + root.right.right.left = Node(9) + root.right.right.right = Node(10) + + ''' print leaf nodes of the given tree''' + + printLeafNodes(root) + + +" +Program to find Normal and Trace of a matrix,"/*Java program to find trace and normal +of given matrix*/ + +import java.io.*; +class GFG { +/*Size of given matrix*/ + +static int MAX = 100; +/*Returns Normal of a matrix of size n x n*/ + + static int findNormal(int mat[][], int n) +{ + int sum = 0; + for (int i=0; i stack = new Stack<>(); + +/* size of the array*/ + + int n = height.length; + +/* Stores the final result*/ + + int ans = 0; + +/* Loop through the each bar*/ + + for (int i = 0; i < n; i++) { + +/* Remove bars from the stack + until the condition holds*/ + + while ((!stack.isEmpty()) + && (height[stack.peek()] < height[i])) { + +/* store the height of the top + and pop it.*/ + + int pop_height = height[stack.peek()]; + stack.pop(); + +/* If the stack does not have any + bars or the the popped bar + has no left boundary*/ + + if (stack.isEmpty()) + break; + +/* Get the distance between the + left and right boundary of + popped bar*/ + + int distance = i - stack.peek() - 1; + +/* Calculate the min. height*/ + + int min_height + = Math.min(height[stack.peek()], + height[i]) + - pop_height; + + ans += distance * min_height; + } + +/* If the stack is either empty or + height of the current bar is less than + or equal to the top bar of stack*/ + + stack.push(i); + } + + return ans; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + System.out.print(maxWater(arr)); + } +} +"," '''Python implementation of the approach''' + + + '''Function to return the maximum +water that can be stored''' + +def maxWater(height): + + ''' Stores the indices of the bars''' + + stack = [] + + ''' size of the array''' + + n = len(height) + + ''' Stores the final result''' + + ans = 0 + + ''' Loop through the each bar''' + + for i in range(n): + + ''' Remove bars from the stack + until the condition holds''' + + while(len(stack) != 0 and (height[stack[-1]] < height[i]) ): + + ''' store the height of the top + and pop it.''' + + pop_height = height[stack[-1]] + stack.pop() + + ''' If the stack does not have any + bars or the the popped bar + has no left boundary''' + + if(len(stack) == 0): + break + + ''' Get the distance between the + left and right boundary of + popped bar''' + + distance = i - stack[-1] - 1 + + ''' Calculate the min. height''' + + min_height = min(height[stack[-1]],height[i])-pop_height + + ans += distance * min_height + + ''' If the stack is either empty or + height of the current bar is less than + or equal to the top bar of stack''' + + stack.append(i) + + return ans + + '''Driver code''' + +arr=[ 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] +print(maxWater(arr)) + + +" +Rank of an element in a stream,"/*Java program to find rank of an +element in a stream.*/ + +class GfG { +static class Node { + int data; + Node left, right; + int leftSize; +} +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + temp.leftSize = 0; + return temp; +} +/*Inserting a new Node.*/ + +static Node insert(Node root, int data) +{ + if (root == null) + return newNode(data); +/* Updating size of left subtree.*/ + + if (data <= root.data) { + root.left = insert(root.left, data); + root.leftSize++; + } + else + root.right = insert(root.right, data); + return root; +} +/*Function to get Rank of a Node x.*/ + +static int getRank(Node root, int x) +{ +/* Step 1.*/ + + if (root.data == x) + return root.leftSize; +/* Step 2.*/ + + if (x < root.data) { + if (root.left == null) + return -1; + else + return getRank(root.left, x); + } +/* Step 3.*/ + + else { + if (root.right == null) + return -1; + else { + int rightSize = getRank(root.right, x); + if(rightSize == -1) return -1; + return root.leftSize + 1 + rightSize; + } + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; + int n = arr.length; + int x = 4; + Node root = null; + for (int i = 0; i < n; i++) + root = insert(root, arr[i]); + System.out.println(""Rank of "" + x + "" in stream is : ""+getRank(root, x)); + x = 13; + System.out.println(""Rank of "" + x + "" in stream is : ""+getRank(root, x)); +} +}"," '''Python3 program to find rank of an +element in a stream.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + self.leftSize = 0 + '''Inserting a new Node.''' + +def insert(root, data): + if root is None: + return newNode(data) + ''' Updating size of left subtree.''' + + if data <= root.data: + root.left = insert(root.left, data) + root.leftSize += 1 + else: + root.right = insert(root.right, data) + return root + '''Function to get Rank of a Node x.''' + +def getRank(root, x): + ''' Step 1.''' + + if root.data == x: + return root.leftSize + ''' Step 2.''' + + if x < root.data: + if root.left is None: + return -1 + else: + return getRank(root.left, x) + ''' Step 3.''' + + else: + if root.right is None: + return -1 + else: + rightSize = getRank(root.right, x) + if rightSize == -1: + return -1 + else: + return root.leftSize + 1 + rightSize '''Driver code''' + +if __name__ == '__main__': + arr = [5, 1, 4, 4, 5, 9, 7, 13, 3] + n = len(arr) + x = 4 + root = None + for i in range(n): + root = insert(root, arr[i]) + print(""Rank of"", x, ""in stream is:"", + getRank(root, x)) + x = 13 + print(""Rank of"", x, ""in stream is:"", + getRank(root, x)) + x = 8 + print(""Rank of"", x, ""in stream is:"", + getRank(root, x))" +Position of rightmost set bit,"/*Java Code for Position of rightmost set bit*/ + +class GFG { + public static int getFirstSetBitPos(int n) + { + return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; + } +/* Drive code*/ + + public static void main(String[] args) + { + int n = 12; + System.out.println(getFirstSetBitPos(n)); + } +}"," '''Python Code for Position +of rightmost set bit''' + +import math +def getFirstSetBitPos(n): + return math.log2(n&-n)+1 + '''driver code''' + +n = 12 +print(int(getFirstSetBitPos(n)))" +Print Binary Tree in 2-Dimensions,"/*Java Program to print binary tree in 2D*/ + +class GFG +{ + +static final int COUNT = 10; + +/*A binary tree node*/ + +static class Node +{ + int data; + Node left, right; + + /* Constructor that allocates a new node with the + given data and null left and right pointers. */ + + Node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } +}; + +/*Function to print binary tree in 2D +It does reverse inorder traversal*/ + +static void print2DUtil(Node root, int space) +{ +/* Base case*/ + + if (root == null) + return; + +/* Increase distance between levels*/ + + space += COUNT; + +/* Process right child first*/ + + print2DUtil(root.right, space); + +/* Print current node after space + count*/ + + System.out.print(""\n""); + for (int i = COUNT; i < space; i++) + System.out.print("" ""); + System.out.print(root.data + ""\n""); + +/* Process left child*/ + + print2DUtil(root.left, space); +} + +/*Wrapper over print2DUtil()*/ + +static void print2D(Node root) +{ +/* Pass initial space count as 0*/ + + print2DUtil(root, 0); +} + +/*Driver code*/ + +public static void main(String args[]) +{ + 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); +} +} + + +"," '''Python3 Program to print binary tree in 2D''' + +COUNT = [10] + + '''Binary Tree Node''' + +class newNode: + + + + '''Constructor that allocates a new node with the + given data and null left and right pointers. ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Function to print binary tree in 2D +It does reverse inorder traversal''' + +def print2DUtil(root, space) : + + ''' Base case''' + + if (root == None) : + return + + ''' Increase distance between levels''' + + space += COUNT[0] + + ''' Process right child first''' + + print2DUtil(root.right, space) + + ''' Print current node after space + count''' + + print() + for i in range(COUNT[0], space): + print(end = "" "") + print(root.data) + + ''' Process left child''' + + print2DUtil(root.left, space) + + '''Wrapper over print2DUtil()''' + +def print2D(root) : + + ''' space=[0] + Pass initial space count as 0''' + + print2DUtil(root, 0) + + '''Driver Code''' + +if __name__ == '__main__': + + 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.left.left.left = newNode(8) + root.left.left.right = newNode(9) + root.left.right.left = newNode(10) + root.left.right.right = newNode(11) + root.right.left.left = newNode(12) + root.right.left.right = newNode(13) + root.right.right.left = newNode(14) + root.right.right.right = newNode(15) + + print2D(root) + + +" +"Write a program to calculate pow(x,n)","class GFG { + /* Function to calculate x raised to the power y */ + + static int power(int x, int y) + { + if (y == 0) + return 1; + else if (y % 2 == 0) + return power(x, y / 2) * power(x, y / 2); + else + return x * power(x, y / 2) * power(x, y / 2); + } + /* Program to test function power */ + + public static void main(String[] args) + { + int x = 2; + int y = 3; + System.out.printf(""%d"", power(x, y)); + } +}"," '''Python3 program to calculate pow(x,n) + ''' '''Function to calculate x +raised to the power y''' + +def power(x, y): + if (y == 0): return 1 + elif (int(y % 2) == 0): + return (power(x, int(y / 2)) * + power(x, int(y / 2))) + else: + return (x * power(x, int(y / 2)) * + power(x, int(y / 2))) + '''Driver Code''' + +x = 2; y = 3 +print(power(x, y))" +Count rotations required to sort given array in non-increasing order,"/*Java program for the above approach*/ + +import java.util.*; + +class GFG{ + +/*Function to count minimum anti- +clockwise rotations required to +sort the array in non-increasing order*/ + +static void minMovesToSort(int arr[], int N) +{ + +/* Stores count of arr[i + 1] > arr[i]*/ + + int count = 0; + +/* Store last index of arr[i+1] > arr[i]*/ + + int index = 0; + +/* Traverse the given array*/ + + for(int i = 0; i < N - 1; i++) + { + +/* If the adjacent elements are + in increasing order*/ + + if (arr[i] < arr[i + 1]) + { + +/* Increment count*/ + + count++; + +/* Update index*/ + + index = i; + } + } + +/* Print the result according + to the following conditions*/ + + if (count == 0) + { + System.out.print(""0""); + } + else if (count == N - 1) + { + System.out.print(N - 1); + } + else if (count == 1 && + arr[0] <= arr[N - 1]) + { + System.out.print(index + 1); + } + +/* Otherwise, it is not + possible to sort the array*/ + + else + { + System.out.print(""-1""); + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + +/* Given array*/ + + int[] arr = { 2, 1, 5, 4, 2 }; + int N = arr.length; + +/* Function Call*/ + + minMovesToSort(arr, N); +} +} + + +"," '''Python program for the above approach''' + + + '''Function to count minimum anti- +clockwise rotations required to +sort the array in non-increasing order''' + +def minMovesToSort(arr, N) : + + ''' Stores count of arr[i + 1] > arr[i]''' + + count = 0 + + ''' Store last index of arr[i+1] > arr[i]''' + + index = 0 + + ''' Traverse the given array''' + + for i in range(N-1): + + ''' If the adjacent elements are + in increasing order''' + + if (arr[i] < arr[i + 1]) : + + ''' Increment count''' + + count += 1 + + ''' Update index''' + + index = i + + ''' Prthe result according + to the following conditions''' + + if (count == 0) : + print(""0"") + + elif (count == N - 1) : + print( N - 1) + + elif (count == 1 + and arr[0] <= arr[N - 1]) : + print(index + 1) + + ''' Otherwise, it is not + possible to sort the array''' + + else : + print(""-1"") + + '''Driver Code''' + + + '''Given array''' + +arr = [ 2, 1, 5, 4, 2 ] +N = len(arr) + + '''Function Call''' + +minMovesToSort(arr, N) + + +" +Construct BST from its given level order traversal,"/*Java implementation to construct a BST +from its level order traversal*/ + +class GFG +{ +/*node of a BST*/ + +static class Node +{ + int data; + Node left, right; +}; +/*function to get a new node*/ + +static Node getNode(int data) +{ +/* Allocate memory*/ + + Node newNode = new Node(); +/* put in the data */ + + newNode.data = data; + newNode.left = newNode.right = null; + return newNode; +} +/*function to construct a BST from +its level order traversal*/ + +static Node LevelOrder(Node root , int data) +{ + if(root == null) + { + root = getNode(data); + return root; + } + if(data <= root.data) + root.left = LevelOrder(root.left, data); + else + root.right = LevelOrder(root.right, data); + return root; +} +static Node constructBst(int arr[], int n) +{ + if(n == 0)return null; + Node root = null; + for(int i = 0; i < n; i++) + root = LevelOrder(root , arr[i]); + return root; +} +/*function to print the inorder traversal*/ + +static void inorderTraversal(Node root) +{ + if (root == null) + return; + inorderTraversal(root.left); + System.out.print( root.data + "" ""); + inorderTraversal(root.right); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10}; + int n = arr.length; + Node root = constructBst(arr, n); + System.out.print( ""Inorder Traversal: ""); + inorderTraversal(root); +} +}"," '''Python implementation to construct a BST +from its level order traversal''' + +import math + '''node of a BST''' + +class Node: + def __init__(self,data): + self.data = data + self.left = None + self.right = None + '''function to get a new node''' + +def getNode( data): + ''' Allocate memory''' + + newNode = Node(data) + ''' put in the data ''' + + newNode.data = data + newNode.left =None + newNode.right = None + return newNode + '''function to construct a BST from +its level order traversal''' + +def LevelOrder(root , data): + if(root == None): + root = getNode(data) + return root + if(data <= root.data): + root.left = LevelOrder(root.left, data) + else: + root.right = LevelOrder(root.right, data) + return root +def constructBst(arr, n): + if(n == 0): + return None + root = None + for i in range(0, n): + root = LevelOrder(root , arr[i]) + return root + '''function to print the inorder traversal''' + +def inorderTraversal( root): + if (root == None): + return None + inorderTraversal(root.left) + print(root.data,end = "" "") + inorderTraversal(root.right) + '''Driver program''' + +if __name__=='__main__': + arr = [7, 4, 12, 3, 6, 8, 1, 5, 10] + n = len(arr) + root = constructBst(arr, n) + print(""Inorder Traversal: "", end = """") + root = inorderTraversal(root)" +Reverse alternate levels of a perfect binary tree,"/*Java program to reverse alternate +levels of perfect binary tree*/ + +/*A binary tree node*/ + +class Node { + char data; + Node left, right; + Node(char item) { + data = item; + left = right = null; + } +}/*class to access index value by reference*/ + +class Index { + int index; +} +class BinaryTree { + Node root; + Index index_obj = new Index(); +/* function to store alternate levels in a tree*/ + + void storeAlternate(Node node, char arr[], + Index index, int l) + { +/* base case*/ + + if (node == null) { + return; + } +/* store elements of left subtree*/ + + storeAlternate(node.left, arr, index, l + 1); +/* store this node only if level is odd*/ + + if (l % 2 != 0) { + arr[index.index] = node.data; + index.index++; + } + storeAlternate(node.right, arr, index, l + 1); + } +/* Function to modify Binary Tree + (All odd level nodes are + updated by taking elements from + array in inorder fashion)*/ + + void modifyTree(Node node, char arr[], + Index index, int l) + { +/* Base case*/ + + if (node == null) { + return; + } +/* Update nodes in left subtree*/ + + modifyTree(node.left, arr, index, l + 1); +/* Update this node only if + this is an odd level node*/ + + if (l % 2 != 0) { + node.data = arr[index.index]; + (index.index)++; + } +/* Update nodes in right subtree*/ + + modifyTree(node.right, arr, index, l + 1); + } +/* A utility function to reverse an array from index + 0 to n-1*/ + + void reverse(char arr[], int n) { + int l = 0, r = n - 1; + while (l < r) { + char temp = arr[l]; + arr[l] = arr[r]; + arr[r] = temp; + l++; + r--; + } + } + void reverseAlternate() + { + reverseAlternate(root); + } +/* The main function to reverse + alternate nodes of a binary tree*/ + + void reverseAlternate(Node node) + { +/* Create an auxiliary array to store + nodes of alternate levels*/ + + char[] arr = new char[100]; +/* First store nodes of alternate levels*/ + + storeAlternate(node, arr, index_obj, 0); +/* index_obj.index = 0; + Reverse the array*/ + + reverse(arr, index_obj.index); +/* Update tree by taking elements from array*/ + + index_obj.index = 0; + modifyTree(node, arr, index_obj, 0); + } + void printInorder() { + printInorder(root); + } +/* A utility function to print + indorder traversal of a + binary tree*/ + + void printInorder(Node node) { + if (node == null) { + return; + } + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); + } +/* Driver program to test the above functions*/ + + public static void main(String args[]) { + BinaryTree tree = new BinaryTree(); + tree.root = new Node('a'); + tree.root.left = new Node('b'); + tree.root.right = new Node('c'); + tree.root.left.left = new Node('d'); + tree.root.left.right = new Node('e'); + tree.root.right.left = new Node('f'); + tree.root.right.right = new Node('g'); + tree.root.left.left.left = new Node('h'); + tree.root.left.left.right = new Node('i'); + tree.root.left.right.left = new Node('j'); + tree.root.left.right.right = new Node('k'); + tree.root.right.left.left = new Node('l'); + tree.root.right.left.right = new Node('m'); + tree.root.right.right.left = new Node('n'); + tree.root.right.right.right = new Node('o'); + System.out.println(""Inorder Traversal of given tree""); + tree.printInorder(); + tree.reverseAlternate(); + System.out.println(""""); + System.out.println(""""); + System.out.println(""Inorder Traversal of modified tree""); + tree.printInorder(); + } +}"," '''Python3 program to reverse +alternate levels of a binary tree''' + +MAX = 100 + '''A Binary Tree node''' + +class Node: + def __init__(self, data): + self.left = None + self.right = None + self.data = data + '''A utility function to +create a new Binary Tree +Node''' + +def newNode(item): + temp = Node(item) + return temp + '''Function to store nodes of +alternate levels in an array''' + +def storeAlternate(root, arr, + index, l): + ''' Base case''' + + if (root == None): + return index; + ''' Store elements of + left subtree''' + + index = storeAlternate(root.left, + arr, index, + l + 1); + ''' Store this node only if + this is a odd level node''' + + if(l % 2 != 0): + arr[index] = root.data; + index += 1; + index=storeAlternate(root.right, + arr, index, + l + 1); + return index '''Function to modify Binary Tree +(All odd level nodes are +updated by taking elements from +array in inorder fashion)''' + +def modifyTree(root, arr, index, l): + ''' Base case''' + + if (root == None): + return index; + ''' Update nodes in left subtree''' + + index=modifyTree(root.left, + arr, index, + l + 1); + ''' Update this node only + if this is an odd level + node''' + + if (l % 2 != 0): + root.data = arr[index]; + index += 1; + ''' Update nodes in right + subtree''' + + index=modifyTree(root.right, + arr, index, + l + 1); + return index + '''A utility function to +reverse an array from +index 0 to n-1''' + +def reverse(arr, n): + l = 0 + r = n - 1; + while (l < r): + arr[l], arr[r] = (arr[r], + arr[l]); + l += 1 + r -= 1 + '''The main function to reverse +alternate nodes of a binary tree''' + +def reverseAlternate(root): + ''' Create an auxiliary array + to store nodes of alternate + levels''' + + arr = [0 for i in range(MAX)] + index = 0; + ''' First store nodes of + alternate levels''' + + index=storeAlternate(root, arr, + index, 0); + ''' Reverse the array''' + + reverse(arr, index); + ''' Update tree by taking + elements from array''' + + index = 0; + index=modifyTree(root, arr, + index, 0); + '''A utility function to print +indorder traversal of a +binary tree''' + +def printInorder(root): + if(root == None): + return; + printInorder(root.left); + print(root.data, end = ' ') + printInorder(root.right); + '''Driver code''' + +if __name__==""__main__"": + root = newNode('a'); + root.left = newNode('b'); + root.right = newNode('c'); + root.left.left = newNode('d'); + root.left.right = newNode('e'); + root.right.left = newNode('f'); + root.right.right = newNode('g'); + root.left.left.left = newNode('h'); + root.left.left.right = newNode('i'); + root.left.right.left = newNode('j'); + root.left.right.right = newNode('k'); + root.right.left.left = newNode('l'); + root.right.left.right = newNode('m'); + root.right.right.left = newNode('n'); + root.right.right.right = newNode('o'); + print(""Inorder Traversal of given tree"") + printInorder(root); + reverseAlternate(root); + print(""\nInorder Traversal of modified tree"") + printInorder(root);" +Print root to leaf paths without using recursion,"/*Java program to Print root to leaf path WITHOUT +using recursion */ + +import java.util.Stack; +import java.util.HashMap; +public class PrintPath { + /* A binary tree node */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + left=right=null; + this.data=data; + } +};/* Function to print root to leaf path for a leaf + using parent nodes stored in map */ + + public static void printTopToBottomPath(Node curr, HashMap parent) + { + Stack stk=new Stack<>() ; +/* start from leaf node and keep on pushing + nodes into stack till root node is reached */ + + while (curr!=null) + { + stk.push(curr); + curr = parent.get(curr); + } +/* Start popping nodes from stack and print them */ + + while (!stk.isEmpty()) + { + curr = stk.pop(); + System.out.print(curr.data+"" ""); + } + System.out.println(); + } + /* An iterative function to do preorder traversal + of binary tree and print root to leaf path + without using recursion */ + + public static void printRootToLeaf(Node root) + { +/* Corner Case */ + + if (root == null) + return; +/* Create an empty stack and push root to it */ + + Stack nodeStack=new Stack<>(); + nodeStack.push(root); +/* Create a map to store parent pointers of binary + tree nodes */ + + HashMap parent=new HashMap<>(); +/* parent of root is NULL */ + + parent.put(root,null); + /* Pop all items one by one. Do following for + every popped item + a) push its right child and set its parent + pointer + b) push its left child and set its parent + pointer + Note that right child is pushed first so that + left is processed first */ + + while (!nodeStack.isEmpty()) + { +/* Pop the top item from stack */ + + Node current = nodeStack.pop(); +/* If leaf node encountered, print Top To + Bottom path */ + + if (current.left==null && current.right==null) + printTopToBottomPath(current, parent); +/* Push right & left children of the popped node + to stack. Also set their parent pointer in + the map */ + + if (current.right!=null) + { + parent.put(current.right,current); + nodeStack.push(current.right); + } + if (current.left!=null) + { + parent.put(current.left,current); + nodeStack.push(current.left); + } + } + } + +/*Driver program to test above functions*/ + + public static void main(String args[]) {/* Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 */ + + Node root=new Node(10); + root.left = new Node(8); + root.right = new Node(2); + root.left.left = new Node(3); + root.left.right = new Node(5); + root.right.left = new Node(2); + printRootToLeaf(root); + } +}"," '''Python3 program to Print root to +leaf path without using recursion''' + + '''Helper function that allocates a new +node with the given data and None left +and right pointers.''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to print root to leaf path for a +leaf using parent nodes stored in map ''' + +def printTopToBottomPath(curr, parent): + stk = [] + ''' start from leaf node and keep on appending + nodes into stack till root node is reached ''' + + while (curr): + stk.append(curr) + curr = parent[curr] + ''' Start popping nodes from stack + and print them ''' + + while len(stk) != 0: + curr = stk[-1] + stk.pop(-1) + print(curr.data, end = "" "") + print() + '''An iterative function to do preorder +traversal of binary tree and print +root to leaf path without using recursion ''' + +def printRootToLeaf(root): + ''' Corner Case ''' + + if (root == None): + return + ''' Create an empty stack and + append root to it ''' + + nodeStack = [] + nodeStack.append(root) + ''' Create a map to store parent + pointers of binary tree nodes ''' + + parent = {} + ''' parent of root is None ''' + + parent[root] = None + ''' Pop all items one by one. Do following + for every popped item + a) append its right child and set its + parent pointer + b) append its left child and set its + parent pointer + Note that right child is appended first + so that left is processed first ''' + + while len(nodeStack) != 0: + ''' Pop the top item from stack ''' + + current = nodeStack[-1] + nodeStack.pop(-1) + ''' If leaf node encountered, print + Top To Bottom path ''' + + if (not (current.left) and + not (current.right)): + printTopToBottomPath(current, parent) + ''' append right & left children of the + popped node to stack. Also set their + parent pointer in the map ''' + + if (current.right): + parent[current.right] = current + nodeStack.append(current.right) + if (current.left): + parent[current.left] = current + nodeStack.append(current.left) + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ / + 3 5 2 ''' + + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.left = newNode(2) + printRootToLeaf(root)" +Find sum of all left leaves in a given Binary Tree,"/*Java program to find sum of all left leaves*/ + +import java.util.*; +class GFG +{ +/*A binary tree node*/ + +static class Node +{ + int key; + Node left, right; +/* constructor to create a new Node*/ + + Node(int key_) + { + key = key_; + left = null; + right = null; + } +}; +static class pair +{ + Node first; + boolean second; + public pair(Node first, boolean second) + { + this.first = first; + this.second = second; + } +} +/*Return the sum of left leaf nodes*/ + +static int sumOfLeftLeaves(Node root) +{ + if (root == null) + return 0; +/* A queue of pairs to do bfs traversal + and keep track if the node is a left + or right child if boolean value + is true then it is a left child.*/ + + Queue q = new LinkedList<>(); + q.add(new pair( root, false )); + int sum = 0; +/* do bfs traversal*/ + + while (!q.isEmpty()) + { + Node temp = q.peek().first; + boolean is_left_child = + q.peek().second; + q.remove(); +/* if temp is a leaf node and + left child of its parent*/ + + if (is_left_child) + sum = sum + temp.key; + if(temp.left != null && temp.right != null && is_left_child) + sum = sum-temp.key; +/* if it is not leaf then + push its children nodes + into queue*/ + + if (temp.left != null) + { +/* boolean value is true + here because it is left + child of its parent*/ + + q.add(new pair( temp.left, true)); + } + if (temp.right != null) + { +/* boolean value is false + here because it is + right child of its parent*/ + + q.add(new pair( temp.right, false)); + } + } + return sum; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + Node root = new Node(20); + root.left = new Node(9); + root.right = new Node(49); + root.right.left = new Node(23); + root.right.right = new Node(52); + root.right.right.left = new Node(50); + root.left.left = new Node(5); + root.left.right = new Node(12); + root.left.right.right = new Node(12); + System.out.print(""Sum of left leaves is "" + + sumOfLeftLeaves(root) +""\n""); +} +}"," '''Python3 program to find sum of +all left leaves''' + +from collections import deque + '''A binary tree node''' + +class Node: + def __init__(self, x): + self.key = x + self.left = None + self.right = None + '''Return the sum of left leaf nodes''' + +def sumOfLeftLeaves(root): + if (root == None): + return 0 + ''' A queue of pairs to do bfs traversal + and keep track if the node is a left + or right child if boolean value + is true then it is a left child.''' + + q = deque() + q.append([root, 0]) + sum = 0 + ''' Do bfs traversal''' + + while (len(q) > 0): + temp = q[0][0] + is_left_child = q[0][1] + q.popleft() + ''' If temp is a leaf node and + left child of its parent''' + + if (not temp.left and + not temp.right and + is_left_child): + sum = sum + temp.key + ''' If it is not leaf then + push its children nodes + into queue''' + + if (temp.left): + ''' Boolean value is true + here because it is left + child of its parent''' + + q.append([temp.left, 1]) + if (temp.right): + ''' Boolean value is false + here because it is + right child of its parent''' + + q.append([temp.right, 0]) + return sum + '''Driver Code''' + +if __name__ == '__main__': + root = Node(20) + root.left = Node(9) + root.right = Node(49) + root.right.left = Node(23) + root.right.right = Node(52) + root.right.right.left = Node(50) + root.left.left = Node(5) + root.left.right = Node(12) + root.left.right.right = Node(12) + print(""Sum of left leaves is"", + sumOfLeftLeaves(root))" +Leaf nodes from Preorder of a Binary Search Tree,"/*Java program to print leaf node from +preorder of binary search tree.*/ + +import java.util.*; +class GFG +{ +/*Binary Search*/ + +static int binarySearch(int inorder[], int l, + int r, int d) +{ + int mid = (l + r) >> 1; + if (inorder[mid] == d) + return mid; + else if (inorder[mid] > d) + return binarySearch(inorder, l, + mid - 1, d); + else + return binarySearch(inorder, + mid + 1, r, d); +} +/*Point to the index in preorder.*/ + +static int ind; +/*Function to print Leaf Nodes by +doing preorder traversal of tree +using preorder and inorder arrays.*/ + +static void leafNodesRec(int preorder[], + int inorder[], + int l, int r, int n) +{ +/* If l == r, therefore no right or left subtree. + So, it must be leaf Node, print it.*/ + + if(l == r) + { + System.out.printf(""%d "", inorder[l]); + ind = ind + 1; + return; + } +/* If array is out of bound, return.*/ + + if (l < 0 || l > r || r >= n) + return; +/* Finding the index of preorder element + in inorder array using binary search.*/ + + int loc = binarySearch(inorder, l, r, + preorder[ind]); +/* Incrementing the index.*/ + + ind = ind + 1; +/* Finding on the left subtree.*/ + + leafNodesRec(preorder, inorder, + l, loc - 1, n); +/* Finding on the right subtree.*/ + + leafNodesRec(preorder, inorder, + loc + 1, r, n); +} +/*Finds leaf nodes from given preorder traversal.*/ + +static void leafNodes(int preorder[], int n) +{ +/* To store inorder traversal*/ + + int inorder[] = new int[n]; +/* Copy the preorder into another array.*/ + + for (int i = 0; i < n; i++) + inorder[i] = preorder[i]; +/* Finding the inorder by sorting the array.*/ + + Arrays.sort(inorder); +/* Print the Leaf Nodes.*/ + + leafNodesRec(preorder, inorder, 0, n - 1, n); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int preorder[] = { 890, 325, 290, 530, 965 }; + int n = preorder.length; + leafNodes(preorder, n); +} +}"," '''Python3 program to print leaf node from +preorder of binary search tree. + ''' '''Binary Search''' + +def binarySearch(inorder, l, r, d): + mid = (l + r) >> 1 + if (inorder[mid] == d): + return mid + elif (inorder[mid] > d): + return binarySearch(inorder, l, + mid - 1, d) + else: + return binarySearch(inorder, + mid + 1, r, d) + ''' Poto the index in preorder.''' + + ind = [0] + '''Function to prLeaf Nodes by doing +preorder traversal of tree using +preorder and inorder arrays.''' + +def leafNodesRec(preorder, inorder, + l, r, ind, n): + ''' If l == r, therefore no right or left subtree. + So, it must be leaf Node, print it.''' + + if(l == r): + print(inorder[l], end = "" "") + ind[0] = ind[0] + 1 + return + ''' If array is out of bound, return.''' + + if (l < 0 or l > r or r >= n): + return + ''' Finding the index of preorder element + in inorder array using binary search.''' + + loc = binarySearch(inorder, l, r, + preorder[ind[0]]) + ''' Incrementing the index.''' + + ind[0] = ind[0] + 1 + ''' Finding on the left subtree.''' + + leafNodesRec(preorder, inorder, + l, loc - 1, ind, n) + ''' Finding on the right subtree.''' + + leafNodesRec(preorder, inorder, + loc + 1, r, ind, n) + '''Finds leaf nodes from +given preorder traversal.''' + +def leafNodes(preorder, n): + ''' To store inorder traversal''' + + inorder = [0] * n + ''' Copy the preorder into another array.''' + + for i in range(n): + inorder[i] = preorder[i] + ''' Finding the inorder by sorting the array.''' + + inorder.sort() + ind = [0] + ''' Print the Leaf Nodes.''' + + leafNodesRec(preorder, inorder, 0, + n - 1, ind, n) + '''Driver Code''' + +preorder = [890, 325, 290, 530, 965] +n = len(preorder) +leafNodes(preorder, n)" +Union and Intersection of two sorted arrays,"/*Java program to find union of two +sorted arrays (Handling Duplicates)*/ + +class FindUnion { + static void UnionArray(int arr1[], + int arr2[]) + { +/* Taking max element present in either array*/ + + int m = arr1[arr1.length - 1]; + int n = arr2[arr2.length - 1]; + int ans = 0; + if (m > n) { + ans = m; + } + else + ans = n; +/* Finding elements from 1st array + (non duplicates only). Using + another array for storing union + elements of both arrays + Assuming max element present + in array is not more than 10^7*/ + + int newtable[] = new int[ans + 1]; +/* First element is always + present in final answer*/ + + System.out.print(arr1[0] + "" ""); +/* Incrementing the First element's count + in it's corresponding index in newtable*/ + + ++newtable[arr1[0]]; +/* Starting traversing the first + array from 1st index till last*/ + + for (int i = 1; i < arr1.length; i++) { +/* Checking whether current element + is not equal to it's previous element*/ + + if (arr1[i] != arr1[i - 1]) { + System.out.print(arr1[i] + "" ""); + ++newtable[arr1[i]]; + } + } +/* Finding only non common + elements from 2nd array*/ + + for (int j = 0; j < arr2.length; j++) { +/* By checking whether it's already + present in newtable or not*/ + + if (newtable[arr2[j]] == 0) { + System.out.print(arr2[j] + "" ""); + ++newtable[arr2[j]]; + } + } + } +/* Driver Code*/ + + public static void main(String args[]) + { + int arr1[] = { 1, 2, 2, 2, 3 }; + int arr2[] = { 2, 3, 4, 5 }; + UnionArray(arr1, arr2); + } +}"," '''Python3 program to find union of two +sorted arrays (Handling Duplicates)''' + +def UnionArray(arr1, arr2): + ''' Taking max element present in either array''' + + m = arr1[-1] + n = arr2[-1] + ans = 0 + if m > n: + ans = m + else: + ans = n + ''' Finding elements from 1st array + (non duplicates only). Using + another array for storing union + elements of both arrays + Assuming max element present + in array is not more than 10 ^ 7''' + + newtable = [0] * (ans + 1) + ''' First element is always + present in final answer''' + + print(arr1[0], end = "" "") + ''' Incrementing the First element's count + in it's corresponding index in newtable''' + + newtable[arr1[0]] += 1 + ''' Starting traversing the first + array from 1st index till last''' + + for i in range(1, len(arr1)): + ''' Checking whether current element + is not equal to it's previous element''' + + if arr1[i] != arr1[i - 1]: + print(arr1[i], end = "" "") + newtable[arr1[i]] += 1 + ''' Finding only non common + elements from 2nd array ''' + + for j in range(0, len(arr2)): + ''' By checking whether it's already + present in newtable or not''' + + if newtable[arr2[j]] == 0: + print(arr2[j], end = "" "") + newtable[arr2[j]] += 1 + '''Driver Code''' + +if __name__ == ""__main__"": + arr1 = [1, 2, 2, 2, 3] + arr2 = [2, 3, 4, 5] + UnionArray(arr1, arr2)" +Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time),"/*Java program to find LCA using Sqrt decomposition*/ + +import java.util.*; +class GFG +{ +static final int MAXN = 1001; + +/*block size = Math.sqrt(height)*/ + +static int block_sz; +/*stores depth for each node*/ + +static int []depth = new int[MAXN]; +/*stores first parent for each node*/ + +static int []parent = new int[MAXN]; +/*stores first ancestor in previous block*/ + +static int []jump_parent = new int[MAXN]; +static Vector []adj = new Vector[MAXN]; + +static void addEdge(int u,int v) +{ + adj[u].add(v); + adj[v].add(u); +} + +static int LCANaive(int u,int v) +{ + if (u == v) return u; + if (depth[u] > depth[v]) + { + int t = u; + u = v; + v = t; + } + v = parent[v]; + return LCANaive(u, v); +} +/*precalculating the required parameters +associated with every node*/ + +static void dfs(int cur, int prev) +{ + +/* marking depth of cur node*/ + + depth[cur] = depth[prev] + 1; + +/* marking parent of cur node*/ + + parent[cur] = prev; + +/* making jump_parent of cur node*/ + + if (depth[cur] % block_sz == 0) + + /* if it is first node of the block + then its jump_parent is its cur parent */ + + jump_parent[cur] = parent[cur]; + else + + /* if it is not the first node of this block + then its jump_parent is jump_parent of + its parent */ + + jump_parent[cur] = jump_parent[prev]; + +/* propogating the marking down the subtree*/ + + for (int i = 0; i < adj[cur].size(); ++i) + if (adj[cur].get(i) != prev) + dfs(adj[cur].get(i), cur); +} + +/*using sqrt decomposition trick*/ + +static int LCASQRT(int u, int v) +{ + while (jump_parent[u] != jump_parent[v]) + { + if (depth[u] > depth[v]) + { + +/* maintaining depth[v] > depth[u]*/ + + int t = u; + u = v; + v = t; + } + +/* climb to its jump parent*/ + + v = jump_parent[v]; + } + +/* u and v have same jump_parent*/ + + return LCANaive(u, v); +} + +static void preprocess(int height) +{ + block_sz = (int)Math.sqrt(height); + depth[0] = -1; + +/* precalclating 1)depth. 2)parent. 3)jump_parent + for each node*/ + + dfs(1, 0); +} + +/*Driver code*/ + +public static void main(String []args) +{ + for (int i = 0; i < adj.length; i++) + adj[i] = new Vector(); + +/* adding edges to the tree*/ + + addEdge(1, 2); + addEdge(1, 3); + addEdge(1, 4); + addEdge(2, 5); + addEdge(2, 6); + addEdge(3, 7); + addEdge(4, 8); + addEdge(4, 9); + addEdge(9, 10); + addEdge(9, 11); + addEdge(7, 12); + addEdge(7, 13); + +/* here we are directly taking height = 4 + according to the given tree but we can + pre-calculate height = max depth + in one more dfs*/ + + int height = 4; + preprocess(height); + System.out.print(""LCA(11,8) : "" + LCASQRT(11, 8) +""\n""); + System.out.print(""LCA(3,13) : "" + LCASQRT(3, 13) +""\n""); +} +} + + +", +Josephus Circle implementation using STL list,"/*Java Code to find the last man Standing*/ + +public class GFG { +/* Node class to store data*/ + + static class Node + { + public int data ; + public Node next; + public Node( int data ) + { + this.data = data; + } + } + /* Function to find the only person left + after one in every m-th node is killed + in a circle of n nodes */ + + static void getJosephusPosition(int m, int n) + { +/* Create a circular linked list of + size N.*/ + + Node head = new Node(1); + Node prev = head; + for(int i = 2; i <= n; i++) + { + prev.next = new Node(i); + prev = prev.next; + } +/* Connect last node to first*/ + + prev.next = head; + /* while only one node is left in the + linked list*/ + + Node ptr1 = head, ptr2 = head; + while(ptr1.next != ptr1) + { +/* Find m-th node*/ + + int count = 1; + while(count != m) + { + ptr2 = ptr1; + ptr1 = ptr1.next; + count++; + } + /* Remove the m-th node */ + + ptr2.next = ptr1.next; + ptr1 = ptr2.next; + } + System.out.println (""Last person left standing "" + + ""(Josephus Position) is "" + ptr1.data); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + int n = 14, m = 2; + getJosephusPosition(m, n); + } +}"," '''Python3 program to find last man standing''' + '''/* structure for a node in circular + linked list */''' + +class Node: + def __init__(self, x): + self.data = x + self.next = None + '''/* Function to find the only person left + after one in every m-th node is killed + in a circle of n nodes */''' + +def getJosephusPosition(m, n): + ''' Create a circular linked list of + size N.''' + + head = Node(1) + prev = head + for i in range(2, n + 1): + prev.next = Node(i) + prev = prev.next + '''Connect last node to first''' + + prev.next = head + ''' + /* while only one node is left in the + linked list*/''' + + ptr1 = head + ptr2 = head + while (ptr1.next != ptr1): + ''' Find m-th node''' + + count = 1 + while (count != m): + ptr2 = ptr1 + ptr1 = ptr1.next + count += 1 + ''' /* Remove the m-th node */''' + + ptr2.next = ptr1.next + ptr1 = ptr2.next + print(""Last person left standing (Josephus Position) is "", ptr1.data) '''/* Driver program to test above functions */''' + +if __name__ == '__main__': + n = 14 + m = 2 + getJosephusPosition(m, n)" +How to check if two given line segments intersect?,"/*Java program to check if two given line segments intersect*/ + +class GFG +{ +static class Point +{ + int x; + int y; + public Point(int x, int y) + { + this.x = x; + this.y = y; + } +}; +/*Given three colinear points p, q, r, the function checks if +point q lies on line segment 'pr'*/ + +static boolean onSegment(Point p, Point q, Point r) +{ + if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && + q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) + return true; + return false; +} +/*To find orientation of ordered triplet (p, q, r). +The function returns following values +0 --> p, q and r are colinear +1 --> Clockwise +2 --> Counterclockwise*/ + +static int orientation(Point p, Point q, Point r) +{ +/*www.geeksforgeeks.org/orientation-3-ordered-points/ +See https: + for details of below formula.*/ + + int val = (q.y - p.y) * (r.x - q.x) - + (q.x - p.x) * (r.y - q.y); +/*colinear*/ + +if (val == 0) return 0; +/*clock or counterclock wise*/ + +return (val > 0)? 1: 2; +} +/*The main function that returns true if line segment 'p1q1' +and 'p2q2' intersect.*/ + +static boolean doIntersect(Point p1, Point q1, Point p2, Point q2) +{ +/* Find the four orientations needed for general and + special cases*/ + + int o1 = orientation(p1, q1, p2); + int o2 = orientation(p1, q1, q2); + int o3 = orientation(p2, q2, p1); + int o4 = orientation(p2, q2, q1); +/* General case*/ + + if (o1 != o2 && o3 != o4) + return true; +/* Special Cases + p1, q1 and p2 are colinear and p2 lies on segment p1q1*/ + + if (o1 == 0 && onSegment(p1, p2, q1)) return true; +/* p1, q1 and q2 are colinear and q2 lies on segment p1q1*/ + + if (o2 == 0 && onSegment(p1, q2, q1)) return true; +/* p2, q2 and p1 are colinear and p1 lies on segment p2q2*/ + + if (o3 == 0 && onSegment(p2, p1, q2)) return true; +/* p2, q2 and q1 are colinear and q1 lies on segment p2q2*/ + + if (o4 == 0 && onSegment(p2, q1, q2)) return true; +/*Doesn't fall in any of the above cases*/ + +return false; +} +/*Driver code*/ + +public static void main(String[] args) +{ + Point p1 = new Point(1, 1); + Point q1 = new Point(10, 1); + Point p2 = new Point(1, 2); + Point q2 = new Point(10, 2); + if(doIntersect(p1, q1, p2, q2)) + System.out.println(""Yes""); + else + System.out.println(""No""); + p1 = new Point(10, 1); q1 = new Point(0, 10); + p2 = new Point(0, 0); q2 = new Point(10, 10); + if(doIntersect(p1, q1, p2, q2)) + System.out.println(""Yes""); + else + System.out.println(""No""); + p1 = new Point(-5, -5); q1 = new Point(0, 0); + p2 = new Point(1, 1); q2 = new Point(10, 10);; + if(doIntersect(p1, q1, p2, q2)) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''A Python3 program to find if 2 given line segments intersect or not''' + +class Point: + def __init__(self, x, y): + self.x = x + self.y = y + '''Given three colinear points p, q, r, the function checks if +point q lies on line segment 'pr' ''' + +def onSegment(p, q, r): + if ( (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and + (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))): + return True + return False +def orientation(p, q, r): + ''' to find the orientation of an ordered triplet (p,q,r) + function returns the following values: + 0 : Colinear points + 1 : Clockwise points + 2 : Counterclockwise + See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/ + for details of below formula. ''' + + val = (float(q.y - p.y) * (r.x - q.x)) - (float(q.x - p.x) * (r.y - q.y)) + if (val > 0): + ''' Counterclockwise orientation''' + return 1 + elif (val < 0): + return 2 + else: + return 0 '''The main function that returns true if +the line segment 'p1q1' and 'p2q2' intersect.''' + +def doIntersect(p1,q1,p2,q2): + ''' Find the 4 orientations required for + the general and special cases''' + + o1 = orientation(p1, q1, p2) + o2 = orientation(p1, q1, q2) + o3 = orientation(p2, q2, p1) + o4 = orientation(p2, q2, q1) + ''' General case''' + + if ((o1 != o2) and (o3 != o4)): + return True + ''' Special Cases + p1 , q1 and p2 are colinear and p2 lies on segment p1q1''' + + if ((o1 == 0) and onSegment(p1, p2, q1)): + return True + ''' p1 , q1 and q2 are colinear and q2 lies on segment p1q1''' + + if ((o2 == 0) and onSegment(p1, q2, q1)): + return True + ''' p2 , q2 and p1 are colinear and p1 lies on segment p2q2''' + + if ((o3 == 0) and onSegment(p2, p1, q2)): + return True + ''' p2 , q2 and q1 are colinear and q1 lies on segment p2q2''' + + if ((o4 == 0) and onSegment(p2, q1, q2)): + return True + ''' If none of the cases''' + + return False + '''Driver program to test above functions:''' + +p1 = Point(1, 1) +q1 = Point(10, 1) +p2 = Point(1, 2) +q2 = Point(10, 2) +if doIntersect(p1, q1, p2, q2): + print(""Yes"") +else: + print(""No"") +p1 = Point(10, 0) +q1 = Point(0, 10) +p2 = Point(0, 0) +q2 = Point(10,10) +if doIntersect(p1, q1, p2, q2): + print(""Yes"") +else: + print(""No"") +p1 = Point(-5,-5) +q1 = Point(0, 0) +p2 = Point(1, 1) +q2 = Point(10, 10) +if doIntersect(p1, q1, p2, q2): + print(""Yes"") +else: + print(""No"")" +Find lost element from a duplicated array,"/*Java program to find missing element +from same arrays +(except one missing element)*/ + + +import java.io.*; +class MissingNumber { + + /* Function to find missing element based + on binary search approach. arr1[] is of + larger size and N is size of it.arr1[] and + arr2[] are assumed to be in same order. */ + + int findMissingUtil(int arr1[], int arr2[], + int N) + { +/* special case, for only element + which is missing in second array*/ + + if (N == 1) + return arr1[0]; + +/* special case, for first + element missing*/ + + if (arr1[0] != arr2[0]) + return arr1[0]; + +/* Initialize current corner points*/ + + int lo = 0, hi = N - 1; + +/* loop until lo < hi*/ + + while (lo < hi) { + int mid = (lo + hi) / 2; + +/* If element at mid indices are + equal then go to right subarray*/ + + if (arr1[mid] == arr2[mid]) + lo = mid; + else + hi = mid; + +/* if lo, hi becomes + contiguous, break*/ + + if (lo == hi - 1) + break; + } + +/* missing element will be at hi + index of bigger array*/ + + return arr1[hi]; + } + +/* This function mainly does basic error + checking and calls findMissingUtil*/ + + void findMissing(int arr1[], int arr2[], + int M, int N) + { + if (N == M - 1) + System.out.println(""Missing Element is "" + + findMissingUtil(arr1, arr2, M) + ""\n""); + else if (M == N - 1) + System.out.println(""Missing Element is "" + + findMissingUtil(arr2, arr1, N) + ""\n""); + else + System.out.println(""Invalid Input""); + } + +/* Driver Code*/ + + public static void main(String args[]) + { + MissingNumber obj = new MissingNumber(); + int arr1[] = { 1, 4, 5, 7, 9 }; + int arr2[] = { 4, 5, 7, 9 }; + int M = arr1.length; + int N = arr2.length; + obj.findMissing(arr1, arr2, M, N); + } +} + + +"," '''Python3 program to find missing +element from same arrays +(except one missing element)''' + + + '''Function to find missing element based +on binary search approach. arr1[] is +of larger size and N is size of it. +arr1[] and arr2[] are assumed +to be in same order.''' + +def findMissingUtil(arr1, arr2, N): + + ''' special case, for only element + which is missing in second array''' + + if N == 1: + return arr1[0]; + + ''' special case, for first + element missing''' + + if arr1[0] != arr2[0]: + return arr1[0] + + ''' Initialize current corner points''' + + lo = 0 + hi = N - 1 + + ''' loop until lo < hi''' + + while (lo < hi): + + mid = (lo + hi) / 2 + + ''' If element at mid indices + are equal then go to + right subarray''' + + if arr1[mid] == arr2[mid]: + lo = mid + else: + hi = mid + + ''' if lo, hi becomes + contiguous, break''' + + if lo == hi - 1: + break + + ''' missing element will be at + hi index of bigger array''' + + return arr1[hi] + + '''This function mainly does basic +error checking and calls +findMissingUtil''' + +def findMissing(arr1, arr2, M, N): + + if N == M-1: + print(""Missing Element is"", + findMissingUtil(arr1, arr2, M)) + elif M == N-1: + print(""Missing Element is"", + findMissingUtil(arr2, arr1, N)) + else: + print(""Invalid Input"") + + '''Driver Code''' + +arr1 = [1, 4, 5, 7, 9] +arr2 = [4, 5, 7, 9] +M = len(arr1) +N = len(arr2) +findMissing(arr1, arr2, M, N) + + +" +Search in an almost sorted array,"/*Java program to find an element +in an almost sorted array*/ + +class GFG +{ +/* A recursive binary search based function. + It returns index of x in given array + arr[l..r] is present, otherwise -1*/ + + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) + { + int mid = l + (r - l) / 2; +/* If the element is present at + one of the middle 3 positions*/ + + if (arr[mid] == x) + return mid; + if (mid > l && arr[mid - 1] == x) + return (mid - 1); + if (mid < r && arr[mid + 1] == x) + return (mid + 1); +/* If element is smaller than mid, then + it can only be present in left subarray*/ + + if (arr[mid] > x) + return binarySearch(arr, l, mid - 2, x); +/* Else the element can only be present + in right subarray*/ + + return binarySearch(arr, mid + 2, r, x); + } +/* We reach here when element is + not present in array*/ + + return -1; + } +/* Driver code*/ + + public static void main(String args[]) + { + GFG ob = new GFG(); + int arr[] = {3, 2, 10, 4, 40}; + int n = arr.length; + int x = 4; + int result = ob.binarySearch(arr, 0, n - 1, x); + if(result == -1) + System.out.println(""Element is not present in array""); + else + System.out.println(""Element is present at index "" + + result); + } +}"," '''Python 3 program to find an element +in an almost sorted array''' '''A recursive binary search based function. +It returns index of x in given array arr[l..r] +is present, otherwise -1''' + +def binarySearch(arr, l, r, x): + if (r >= l): + mid = int(l + (r - l) / 2) + ''' If the element is present at one + of the middle 3 positions''' + + if (arr[mid] == x): return mid + if (mid > l and arr[mid - 1] == x): + return (mid - 1) + if (mid < r and arr[mid + 1] == x): + return (mid + 1) + ''' If element is smaller than mid, then + it can only be present in left subarray''' + + if (arr[mid] > x): + return binarySearch(arr, l, mid - 2, x) + ''' Else the element can only + be present in right subarray''' + + return binarySearch(arr, mid + 2, r, x) + ''' We reach here when element + is not present in array''' + + return -1 + '''Driver Code''' + +arr = [3, 2, 10, 4, 40] +n = len(arr) +x = 4 +result = binarySearch(arr, 0, n - 1, x) +if (result == -1): + print(""Element is not present in array"") +else: + print(""Element is present at index"", result)" +Construct Tree from given Inorder and Preorder traversals,"/*Java program to construct a tree using inorder and preorder traversal*/ + +import java.util.*; +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } +} +class BinaryTree { + static Set set = new HashSet<>(); + static Stack stack = new Stack<>(); +/* Function to build tree using given traversal*/ + + public TreeNode buildTree(int[] preorder, int[] inorder) + { + TreeNode root = null; + for (int pre = 0, in = 0; pre < preorder.length;) { + TreeNode node = null; + do { + node = new TreeNode(preorder[pre]); + if (root == null) { + root = node; + } + if (!stack.isEmpty()) { + if (set.contains(stack.peek())) { + set.remove(stack.peek()); + stack.pop().right = node; + } + else { + stack.peek().left = node; + } + } + stack.push(node); + } while (preorder[pre++] != inorder[in] && pre < preorder.length); + node = null; + while (!stack.isEmpty() && in < inorder.length && + stack.peek().val == inorder[in]) { + node = stack.pop(); + in++; + } + if (node != null) { + set.add(node); + stack.push(node); + } + } + return root; + } +/* Function to print tree in Inorder*/ + + void printInorder(TreeNode node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.val + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } +/* driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + int in[] = new int[] { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 }; + int pre[] = new int[] { 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 }; + int len = in.length; + TreeNode root = tree.buildTree(pre, in); + tree.printInorder(root); + } +}"," '''Python3 program to construct a tree using +inorder and preorder traversal''' + +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None +s = set() +st = [] + '''Function to build tree using given traversal''' + +def buildTree(preorder, inorder, n): + root = None; + pre = 0 + in_t = 0 + while pre < n: + node = None; + while True: + node = TreeNode(preorder[pre]) + if (root == None): + root = node; + if (len(st) > 0): + if (st[-1] in s): + s.discard(st[-1]); + st[-1].right = node; + st.pop(); + else: + st[-1].left = node; + st.append(node); + if pre>=n or preorder[pre] == inorder[in_t]: + pre += 1 + break + pre += 1 + node = None; + while (len(st) > 0 and in_t < n and st[-1].val == inorder[in_t]): + node = st[-1]; + st.pop(); + in_t += 1 + if (node != None): + s.add(node); + st.append(node); + return root; + '''Function to prtree in_t Inorder''' + +def printInorder( node): + if (node == None): + return; + ''' first recur on left child ''' + + printInorder(node.left); + ''' then prthe data of node ''' + + print(node.val, end="" ""); + ''' now recur on right child ''' + + printInorder(node.right); + '''Driver code''' + +if __name__=='__main__': + in_t = [ 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 ] + pre = [ 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 ] + l = len(in_t) + root = buildTree(pre, in_t, l); + printInorder(root);" +Longest Consecutive Subsequence,"/*Java Program to find longest consecutive +subsequence This Program uses Priority Queue*/ + +import java.io.*; +import java.util.PriorityQueue; +public class Longset_Sub +{ +/* return the length of the longest + subsequence of consecutive integers*/ + + static int findLongestConseqSubseq(int arr[], int N) + { + PriorityQueue pq + = new PriorityQueue(); + for (int i = 0; i < N; i++) + { +/* adding element from + array to PriorityQueue*/ + + pq.add(arr[i]); + } +/* Storing the first element + of the Priority Queue + This first element is also + the smallest element*/ + + int prev = pq.poll(); +/* Taking a counter variable with value 1*/ + + int c = 1; +/* Storing value of max as 1 + as there will always be + one element*/ + + int max = 1; + for (int i = 1; i < N; i++) + { +/* check if current peek + element minus previous + element is greater then + 1 This is done because + if it's greater than 1 + then the sequence + doesn't start or is broken here*/ + + if (pq.peek() - prev > 1) + { +/* Store the value of counter to 1 + As new sequence may begin*/ + + c = 1; +/* Update the previous position with the + current peek And remove it*/ + + prev = pq.poll(); + } +/* Check if the previous + element and peek are same*/ + + else if (pq.peek() - prev == 0) + { +/* Update the previous position with the + current peek And remove it*/ + + prev = pq.poll(); + } +/* if the difference + between previous element and peek is 1*/ + + else + { +/* Update the counter + These are consecutive elements*/ + + c++; +/* Update the previous position + with the current peek And remove it*/ + + prev = pq.poll(); + } +/* Check if current longest + subsequence is the greatest*/ + + if (max < c) + { +/* Store the current subsequence count as + max*/ + + max = c; + } + } + return max; + } +/* Driver Code*/ + + public static void main(String args[]) + throws IOException + { + int arr[] = { 1, 9, 3, 10, 4, 20, 2 }; + int n = arr.length; + System.out.println( + ""Length of the Longest consecutive subsequence is "" + + findLongestConseqSubseq(arr, n)); + } +}", +Find sum of non-repeating (distinct) elements in an array,"/*Java Find the sum of all non- repeated +elements in an array*/ + +import java.util.*; +class GFG +{ +/* Find the sum of all non-repeated elements + in an array*/ + + static int findSum(int arr[], int n) + { + int sum = 0; +/* Hash to store all element of array*/ + + HashSet s = new HashSet(); + for (int i = 0; i < n; i++) + { + if (!s.contains(arr[i])) + { + sum += arr[i]; + s.add(arr[i]); + } + } + return sum; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {1, 2, 3, 1, 1, 4, 5, 6}; + int n = arr.length; + System.out.println(findSum(arr, n)); + } +}"," '''Python3 Find the sum of all +non- repeated elements in an array''' ''' +Find the sum of all non-repeated +elements in an array''' + +def findSum(arr, n): + s = set() + sum = 0 + ''' Hash to store all element + of array''' + + for i in range(n): + if arr[i] not in s: + s.add(arr[i]) + for i in s: + sum = sum + i + return sum + '''Driver code''' + +arr = [1, 2, 3, 1, 1, 4, 5, 6] +n = len(arr) +print(findSum(arr, n))" +Threaded Binary Tree | Insertion,"/*Java program Insertion in Threaded Binary Search Tree.*/ + +import java.util.*; +class solution +{ +static class Node +{ + Node left, right; + int info; +/* True if left pointer points to predecessor + in Inorder Traversal*/ + + boolean lthread; +/* True if right pointer points to successor + in Inorder Traversal*/ + + boolean rthread; +}; +/*Insert a Node in Binary Threaded Tree*/ + +static Node insert( Node root, int ikey) +{ +/* Searching for a Node with given value*/ + + Node ptr = root; +/*Parent of key to be inserted*/ + +Node par = null; + while (ptr != null) + { +/* If key already exists, return*/ + + if (ikey == (ptr.info)) + { + System.out.printf(""Duplicate Key !\n""); + return root; + } +/*Update parent pointer*/ + +par = ptr; +/* Moving on left subtree.*/ + + if (ikey < ptr.info) + { + if (ptr . lthread == false) + ptr = ptr . left; + else + break; + } +/* Moving on right subtree.*/ + + else + { + if (ptr.rthread == false) + ptr = ptr . right; + else + break; + } + } +/* Create a new node*/ + + Node tmp = new Node(); + tmp . info = ikey; + tmp . lthread = true; + tmp . rthread = true; + if (par == null) + { + root = tmp; + tmp . left = null; + tmp . right = null; + } + else if (ikey < (par . info)) + { + tmp . left = par . left; + tmp . right = par; + par . lthread = false; + par . left = tmp; + } + else + { + tmp . left = par; + tmp . right = par . right; + par . rthread = false; + par . right = tmp; + } + return root; +} +/*Returns inorder successor using rthread*/ + +static Node inorderSuccessor( Node ptr) +{ +/* If rthread is set, we can quickly find*/ + + if (ptr . rthread == true) + return ptr.right; +/* Else return leftmost child of right subtree*/ + + ptr = ptr . right; + while (ptr . lthread == false) + ptr = ptr . left; + return ptr; +} +/*Printing the threaded tree*/ + +static void inorder( Node root) +{ + if (root == null) + System.out.printf(""Tree is empty""); +/* Reach leftmost node*/ + + Node ptr = root; + while (ptr . lthread == false) + ptr = ptr . left; +/* One by one print successors*/ + + while (ptr != null) + { + System.out.printf(""%d "",ptr . info); + ptr = inorderSuccessor(ptr); + } +} +/*Driver Program*/ + +public static void main(String[] args) +{ + Node root = null; + root = insert(root, 20); + root = insert(root, 10); + root = insert(root, 30); + root = insert(root, 5); + root = insert(root, 16); + root = insert(root, 14); + root = insert(root, 17); + root = insert(root, 13); + inorder(root); +} +}"," '''Insertion in Threaded Binary Search Tree.''' + +class newNode: + def __init__(self, key): + ''' True if left pointer points to + predecessor in Inorder Traversal''' + + self.info = key + self.left = None + self.right =None + self.lthread = True + ''' True if right pointer points to + successor in Inorder Traversal''' + + self.rthread = True + '''Insert a Node in Binary Threaded Tree''' + +def insert(root, ikey): + ''' Searching for a Node with given value''' + + ptr = root + '''Parent of key to be inserted''' + + par = None + while ptr != None: + ''' If key already exists, return''' + + if ikey == (ptr.info): + print(""Duplicate Key !"") + return root + '''Update parent pointer''' + + par = ptr + ''' Moving on left subtree.''' + + if ikey < ptr.info: + if ptr.lthread == False: + ptr = ptr.left + else: + break + ''' Moving on right subtree.''' + + else: + if ptr.rthread == False: + ptr = ptr.right + else: + break + ''' Create a new node''' + + tmp = newNode(ikey) + if par == None: + root = tmp + tmp.left = None + tmp.right = None + elif ikey < (par.info): + tmp.left = par.left + tmp.right = par + par.lthread = False + par.left = tmp + else: + tmp.left = par + tmp.right = par.right + par.rthread = False + par.right = tmp + return root + '''Returns inorder successor using rthread''' + +def inorderSuccessor(ptr): + ''' If rthread is set, we can quickly find''' + + if ptr.rthread == True: + return ptr.right + ''' Else return leftmost child of + right subtree''' + + ptr = ptr.right + while ptr.lthread == False: + ptr = ptr.left + return ptr + '''Printing the threaded tree''' + +def inorder(root): + if root == None: + print(""Tree is empty"") + ''' Reach leftmost node''' + + ptr = root + while ptr.lthread == False: + ptr = ptr.left + ''' One by one print successors''' + + while ptr != None: + print(ptr.info,end="" "") + ptr = inorderSuccessor(ptr) + '''Driver Code''' + +if __name__ == '__main__': + root = None + root = insert(root, 20) + root = insert(root, 10) + root = insert(root, 30) + root = insert(root, 5) + root = insert(root, 16) + root = insert(root, 14) + root = insert(root, 17) + root = insert(root, 13) + inorder(root)" +GCDs of given index ranges in an array,"/*Java Program to find GCD of a number in a given Range +using segment Trees*/ + +import java.io.*; +public class Main +{ +/*Array to store segment tree*/ + +private static int[] st; + /* A recursive function that constructs Segment + Tree for array[ss..se]. si is index of current + node in segment tree st*/ + + public static int constructST(int[] arr, int ss, + int se, int si) + { + if (ss==se) + { + st[si] = arr[ss]; + return st[si]; + } + int mid = ss+(se-ss)/2; + st[si] = gcd(constructST(arr, ss, mid, si*2+1), + constructST(arr, mid+1, se, si*2+2)); + return st[si]; + } +/* Function to construct segment tree from given array. + This function allocates memory for segment tree and + calls constructSTUtil() to fill the allocated memory */ + + public static int[] constructSegmentTree(int[] arr) + { + int height = (int)Math.ceil(Math.log(arr.length)/Math.log(2)); + int size = 2*(int)Math.pow(2, height)-1; + st = new int[size]; + constructST(arr, 0, arr.length-1, 0); + return st; + } +/* Function to find gcd of 2 numbers.*/ + + private static int gcd(int a, int b) + { + if (a < b) + { +/* If b greater than a swap a and b*/ + + int temp = b; + b = a; + a = temp; + } + if (b==0) + return a; + return gcd(b,a%b); + } +/* A recursive function to get gcd of given + range of array indexes. The following are parameters for + this function. + st --> Pointer to segment tree + si --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment + represented by current node, i.e., st[si] + qs & qe --> Starting and ending indexes of query range */ + + public static int findGcd(int ss, int se, int qs, int qe, int si) + { + if (ss>qe || se < qs) + return 0; + if (qs<=ss && qe>=se) + return st[si]; + int mid = ss+(se-ss)/2; + return gcd(findGcd(ss, mid, qs, qe, si*2+1), + findGcd(mid+1, se, qs, qe, si*2+2)); + } +/* Finding The gcd of given Range*/ + + public static int findRangeGcd(int ss, int se, int[] arr) + { + int n = arr.length; + if (ss<0 || se > n-1 || ss>se) + throw new IllegalArgumentException(""Invalid arguments""); + return findGcd(0, n-1, ss, se, 0); + } + /* Driver Code*/ + + public static void main(String[] args)throws IOException + { + int[] a = {2, 3, 6, 9, 5}; + constructSegmentTree(a); +/*Starting index of range.*/ + +int l = 1; +/*Last index of range.*/ + +int r = 3; + System.out.print(""GCD of the given range is: ""); + System.out.print(findRangeGcd(l, r, a)); + } +}", +Check if leaf traversal of two Binary Trees is same?,"/*Java program to check if two Leaf Traversal of +Two Binary Trees is same or not*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +/*Binary Tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int x) + { + data = x; + left = right = null; + } + +/*checks if a given node is leaf or not.*/ + + public boolean isLeaf() + { + return (left == null && right == null); + } +} +class LeafOrderTraversal +{/* Returns true of leaf traversal of two trees is + same, else false*/ + + public static boolean isSame(Node root1, Node root2) + { +/* Create empty stacks. These stacks are going + to be used for iterative traversals.*/ + + Stack s1 = new Stack(); + Stack s2 = new Stack(); + s1.push(root1); + s2.push(root2); +/* Loop until either of two stacks is not empty*/ + + while (!s1.empty() || !s2.empty()) + { +/* If one of the stacks is empty means other + stack has extra leaves so return false*/ + + if (s1.empty() || s2.empty()) + return false; + Node temp1 = s1.pop(); + while (temp1 != null && !temp1.isLeaf()) + { +/* Push right and left children of temp1. + Note that right child is inserted + before left*/ + + if (temp1.right != null) + s1.push(temp1.right); + if (temp1.left != null) + s1.push(temp1.left); + temp1 = s1.pop(); + } +/* same for tree2*/ + + Node temp2 = s2.pop(); + while (temp2 != null && !temp2.isLeaf()) + { + if (temp2.right != null) + s2.push(temp2.right); + if (temp2.left != null) + s2.push(temp2.left); + temp2 = s2.pop(); + } +/* If one is null and other is not, then + return false*/ + + if (temp1 == null && temp2 != null) + return false; + if (temp1 != null && temp2 == null) + return false; +/* If both are not null and data is not + same return false*/ + + if (temp1 != null && temp2 != null) + { + if (temp1.data != temp2.data) + return false; + } + } +/* If control reaches this point, all leaves + are matched*/ + + return true; + } +/* Driver code*/ + + public static void main(String[] args) + { +/* Let us create trees in above example 1*/ + + Node root1 = new Node(1); + root1.left = new Node(2); + root1.right = new Node(3); + root1.left.left = new Node(4); + root1.right.left = new Node(6); + root1.right.right = new Node(7); + Node root2 = new Node(0); + root2.left = new Node(1); + root2.right = new Node(5); + root2.left.right = new Node(4); + root2.right.left = new Node(6); + root2.right.right = new Node(7); + if (isSame(root1, root2)) + System.out.println(""Same""); + else + System.out.println(""Not Same""); + } +}"," '''Python3 program to check if two Leaf Traversal of Two Binary Trees is same or not''' + + '''Binary Tree node''' + +class Node: + def __init__(self, x): + self.data = x + self.left = self.right = None + '''checks if a given node is leaf or not.''' + + def isLeaf(self): + return (self.left == None and + self.right == None) '''Returns true of leaf traversal of +two trees is same, else false''' + +def isSame(root1, root2): + ''' Create empty stacks. These stacks are going + to be used for iterative traversals.''' + + s1 = [] + s2 = [] + s1.append(root1) + s2.append(root2) + ''' Loop until either of two stacks + is not empty''' + + while (len(s1) != 0 or len(s2) != 0): + ''' If one of the stacks is empty means other + stack has extra leaves so return false''' + + if (len(s1) == 0 or len(s2) == 0): + return False + temp1 = s1.pop(-1) + while (temp1 != None and not temp1.isLeaf()): + ''' append right and left children of temp1. + Note that right child is inserted + before left''' + + if (temp1.right != None): + s1.append(temp1. right) + if (temp1.left != None): + s1.append(temp1.left) + temp1 = s1.pop(-1) + ''' same for tree2''' + + temp2 = s2.pop(-1) + while (temp2 != None and not temp2.isLeaf()): + if (temp2.right != None): + s2.append(temp2.right) + if (temp2.left != None): + s2.append(temp2.left) + temp2 = s2.pop(-1) + ''' If one is None and other is not, + then return false''' + + if (temp1 == None and temp2 != None): + return False + if (temp1 != None and temp2 == None): + return False + ''' If both are not None and data is + not same return false''' + + if (temp1 != None and temp2 != None): + if (temp1.data != temp2.data): + return False + ''' If control reaches this point, + all leaves are matched''' + + return True + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create trees in above example 1''' + + root1 = Node(1) + root1.left = Node(2) + root1.right = Node(3) + root1.left.left = Node(4) + root1.right.left = Node(6) + root1.right.right = Node(7) + root2 = Node(0) + root2.left = Node(1) + root2.right = Node(5) + root2.left.right = Node(4) + root2.right.left = Node(6) + root2.right.right = Node(7) + if (isSame(root1, root2)): + print(""Same"") + else: + print(""Not Same"")" +Count rotations which are divisible by 10,"/*Java implementation to find the +count of rotations which are +divisible by 10*/ + + +class GFG { + +/* Function to return the count + of all rotations which are + divisible by 10.*/ + + static int countRotation(int n) + { + int count = 0; + +/* Loop to iterate through the + number*/ + + do { + int digit = n % 10; + +/* If the last digit is 0, + then increment the count*/ + + if (digit == 0) + count++; + n = n / 10; + } while (n != 0); + + return count; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int n = 10203; + + System.out.println(countRotation(n)); + } +} +"," '''Python3 implementation to find the +count of rotations which are +divisible by 10''' + + + '''Function to return the count of +all rotations which are divisible +by 10.''' + +def countRotation(n): + count = 0; + + ''' Loop to iterate through the + number''' + + while n > 0: + digit = n % 10 + + ''' If the last digit is 0, + then increment the count''' + + if(digit % 2 == 0): + count = count + 1 + n = int(n / 10) + + return count; + + '''Driver code ''' + +if __name__ == ""__main__"" : + + n = 10203; + print(countRotation(n)); +" +Program to find whether a no is power of two,"/*Java Program to find whether a +no is power of two*/ + +class GFG +{ +/* Function to check if x is power of 2*/ + +static boolean isPowerOfTwo(int n) +{ + if(n==0) + return false; +return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == + (int)(Math.floor(((Math.log(n) / Math.log(2))))); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + if(isPowerOfTwo(31)) + System.out.println(""Yes""); + else + System.out.println(""No""); + if(isPowerOfTwo(64)) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Python3 Program to find +whether a no is +power of two''' + +import math + '''Function to check +Log base 2''' + +def Log2(x): + if x == 0: + return false; + return (math.log10(x) / + math.log10(2)); + '''Function to check +if x is power of 2''' + +def isPowerOfTwo(n): + return (math.ceil(Log2(n)) == + math.floor(Log2(n))); + '''Driver Code''' + +if(isPowerOfTwo(31)): + print(""Yes""); +else: + print(""No""); +if(isPowerOfTwo(64)): + print(""Yes""); +else: + print(""No"");" +Find first k natural numbers missing in given array,"/*Java program to find missing k numbers +in an array.*/ + +import java.util.Arrays; + +class GFG { +/* Prints first k natural numbers in + arr[0..n-1]*/ + + static void printKMissing(int[] arr, int n, int k) + { + Arrays.sort(arr); + +/* Find first positive number*/ + + int i = 0; + while (i < n && arr[i] <= 0) + i++; + +/* Now find missing numbers + between array elements*/ + + int count = 0, curr = 1; + while (count < k && i < n) { + if (arr[i] != curr) { + System.out.print(curr + "" ""); + count++; + } + else + i++; + curr++; + } + +/* Find missing numbers after + maximum.*/ + + while (count < k) { + System.out.print(curr + "" ""); + curr++; + count++; + } + } + +/* Driver code*/ + + public static void main(String[] args) + { + int[] arr = { 2, 3, 4 }; + int n = arr.length; + int k = 3; + printKMissing(arr, n, k); + } +} + +"," '''Python3 program to find missing +k numbers in an array.''' + + + '''Prints first k natural numbers +in arr[0..n-1]''' + +def printKMissing(arr, n, k) : + + arr.sort() + + ''' Find first positive number''' + + i = 0 + while (i < n and arr[i] <= 0) : + i = i + 1 + + ''' Now find missing numbers + between array elements''' + + count = 0 + curr = 1 + while (count < k and i < n) : + if (arr[i] != curr) : + print(str(curr) + "" "", end = '') + count = count + 1 + else: + i = i + 1 + + curr = curr + 1 + + ''' Find missing numbers after + maximum.''' + + while (count < k) : + print(str(curr) + "" "", end = '') + curr = curr + 1 + count = count + 1 + + '''Driver code''' + +arr = [ 2, 3, 4 ] +n = len(arr) +k = 3 +printKMissing(arr, n, k); + + +" +Print left rotation of array in O(n) time and O(1) space,"/*Java implementation for print left +rotation of any array K times*/ + +import java.io.*; +import java.util.*; +class GFG{ +/*Function for the k times left rotation*/ + +static void leftRotate(Integer arr[], int k, + int n) +{ +/* In Collection class rotate function + takes two parameters - the name of + array and the position by which it + should be rotated + The below function will be rotating + the array left in linear time + Collections.rotate()rotate the + array from right hence n-k*/ + + Collections.rotate(Arrays.asList(arr), n - k); +/* Print the rotated array from start position*/ + + for(int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Integer arr[] = { 1, 3, 5, 7, 9 }; + int n = arr.length; + int k = 2; +/* Function call*/ + + leftRotate(arr, k, n); +} +}"," '''Python3 implementation to print left +rotation of any array K times''' + +from collections import deque + '''Function For The k Times Left Rotation''' + +def leftRotate(arr, k, n): + ''' The collections module has deque class + which provides the rotate(), which is + inbuilt function to allow rotation''' + + arr = deque(arr) + arr.rotate(-k) + arr = list(arr) ''' Print the rotated array from + start position''' + + for i in range(n): + print(arr[i], end = "" "") + '''Driver Code''' + +if __name__ == '__main__': + arr = [ 1, 3, 5, 7, 9 ] + n = len(arr) + k = 2 + ''' Function Call''' + + leftRotate(arr, k, n)" +Reversal algorithm for right rotation of an array,"/*Java program for right rotation of +an array (Reversal Algorithm)*/ + +import java.io.*; +class GFG +{ +/* Function to reverse arr[] + from index start to end*/ + + static void reverseArray(int arr[], int start, + int end) + { + while (start < end) + { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } + } +/* Function to right rotate + arr[] of size n by d*/ + + static void rightRotate(int arr[], int d, int n) + { + reverseArray(arr, 0, n - 1); + reverseArray(arr, 0, d - 1); + reverseArray(arr, d, n - 1); + } +/* Function to print an array*/ + + static void printArray(int arr[], int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + } +/*driver code*/ + + public static void main (String[] args) + { + int arr[] = {1, 2, 3, 4, 5, + 6, 7, 8, 9, 10}; + int n = arr.length; + int k = 3; + rightRotate(arr, k, n); + printArray(arr, n); + } +}"," '''Python3 program for right rotation of +an array (Reversal Algorithm)''' + + '''Function to reverse arr +from index start to end''' + +def reverseArray( arr, start, end): + while (start < end): + arr[start], arr[end] = arr[end], arr[start] + start = start + 1 + end = end - 1 '''Function to right rotate arr +of size n by d''' + +def rightRotate( arr, d, n): + reverseArray(arr, 0, n - 1); + reverseArray(arr, 0, d - 1); + reverseArray(arr, d, n - 1); + '''function to pr an array''' + +def prArray( arr, size): + for i in range(0, size): + print (arr[i], end = ' ') + '''Driver code''' + +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +n = len(arr) +k = 3 +rightRotate(arr, k, n) +prArray(arr, n)" +Majority Element,"/*Java program to demonstrate insert +operation in binary search tree.*/ + +import java.io.*; +class Node +{ + int key; + int c = 0; + Node left,right; +} +class GFG{ +static int ma = 0; +/*A utility function to create a +new BST node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.key = item; + temp.c = 1; + temp.left = temp.right = null; + return temp; +} +/*A utility function to insert a new node +with given key in BST*/ + +static Node insert(Node node, int key) +{ +/* If the tree is empty, + return a new node*/ + + if (node == null) + { + if (ma == 0) + ma = 1; + return newNode(key); + } +/* Otherwise, recur down the tree*/ + + if (key < node.key) + node.left = insert(node.left, key); + else if (key > node.key) + node.right = insert(node.right, key); + else + node.c++; +/* Find the max count*/ + + ma = Math.max(ma, node.c); +/* Return the (unchanged) node pointer*/ + + return node; +} +/*A utility function to do inorder +traversal of BST*/ + +static void inorder(Node root, int s) +{ + if (root != null) + { + inorder(root.left, s); + if (root.c > (s / 2)) + System.out.println(root.key + ""\n""); + inorder(root.right, s); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = { 1, 3, 3, 3, 2 }; + int size = a.length; + Node root = null; + for(int i = 0; i < size; i++) + { + root = insert(root, a[i]); + } +/* Function call*/ + + if (ma > (size / 2)) + inorder(root, size); + else + System.out.println(""No majority element\n""); +} +}", +Print all possible combinations of r elements in a given array of size n,"/*Java program to print all combination of size r in an array of size n*/ + +import java.io.*; +class Combination { + /* The main function that prints all combinations of size r + in arr[] of size n. This function mainly uses combinationUtil()*/ + + static void printCombination(int arr[], int n, int r) + { +/* A temporary array to store all combination one by one*/ + + int data[]=new int[r]; +/* Print all combination using temprary array 'data[]'*/ + + combinationUtil(arr, data, 0, n-1, 0, r); + } + /* arr[] ---> Input Array + data[] ---> Temporary array to store current combination + start & end ---> Staring and Ending indexes in arr[] + index ---> Current index in data[] + r ---> Size of a combination to be printed */ + + static void combinationUtil(int arr[], int data[], int start, + int end, int index, int r) + { +/* Current combination is ready to be printed, print it*/ + + if (index == r) + { + for (int j=0; j= r-index"" makes sure that including one element + at index will make a combination with remaining elements + at remaining positions*/ + + for (int i=start; i<=end && end-i+1 >= r-index; i++) + { + data[index] = arr[i]; + combinationUtil(arr, data, i+1, end, index+1, r); + } + } +/*Driver function to check for above function*/ + + public static void main (String[] args) { + int arr[] = {1, 2, 3, 4, 5}; + int r = 3; + int n = arr.length; + printCombination(arr, n, r); + } +}"," '''Program to print all combination +of size r in an array of size n + ''' '''The main function that prints +all combinations of size r in +arr[] of size n. This function +mainly uses combinationUtil()''' + +def printCombination(arr, n, r): + ''' A temporary array to + store all combination + one by one''' + + data = [0]*r; + ''' Print all combination + using temprary array 'data[]''' + ''' + combinationUtil(arr, data, 0, + n - 1, 0, r); + '''arr[] ---> Input Array +data[] ---> Temporary array to + store current combination +start & end ---> Staring and Ending + indexes in arr[] +index ---> Current index in data[] +r ---> Size of a combination +to be printed''' + +def combinationUtil(arr, data, start, + end, index, r): + ''' Current combination is ready + to be printed, print it''' + + if (index == r): + for j in range(r): + print(data[j], end = "" ""); + print(); + return; + ''' replace index with all + possible elements. The + condition ""end-i+1 >= + r-index"" makes sure that + including one element at + index will make a combination + with remaining elements at + remaining positions''' + + i = start; + while(i <= end and end - i + 1 >= r - index): + data[index] = arr[i]; + combinationUtil(arr, data, i + 1, + end, index + 1, r); + i += 1; + '''Driver Code''' + +arr = [1, 2, 3, 4, 5]; +r = 3; +n = len(arr); +printCombination(arr, n, r);" +Delete all odd or even positioned nodes from Circular Linked List,"/*Function to delete all even position nodes*/ + +static Node DeleteAllEvenNode( Node head) +{ +/* Take size of list*/ + + int len = Length(head); + + int count = 1; + Node previous = head, next = head; + +/* Check list is empty + if empty simply return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return null; + } + +/* if list have single node + then return*/ + + if (len < 2) + { + return null; + } + +/* make first node is previous*/ + + previous = head; + +/* make second node is current*/ + + next = previous.next; + + while (len > 0) + { + +/* check node number is even + if node is even then + delete that node*/ + + if (count % 2 == 0) + { + previous.next = next.next; + previous = next.next; + next = previous.next; + } + + len--; + count++; + } + return head; +} + + +", +Succinct Encoding of Binary Tree,"/*Java program to demonstrate Succinct +Tree Encoding and decoding*/ + +import java.util.*; +class GFG{ +/*A Binary Tree Node*/ + +static class Node +{ + int key; + Node left, right; +}; +/*Utility function to create new Node*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.key = key; + temp.left = temp.right = null; + return (temp); +} +static Vector struc; +static Vector data; +static Node root; +/*This function fills lists 'struc' and +'data'. 'struc' list stores structure +information. 'data' list stores tree data*/ + +static void EncodeSuccinct(Node root) +{ +/* If root is null, put 0 in + structure array and return*/ + + if (root == null) + { + struc.add(false); + return; + } +/* Else place 1 in structure array, + key in 'data' array and recur + for left and right children*/ + + struc.add(true); + data.add(root.key); + EncodeSuccinct(root.left); + EncodeSuccinct(root.right); +} +/*Constructs tree from 'struc' and 'data'*/ + +static Node DecodeSuccinct() +{ + if (struc.size() <= 0) + return null; +/* Remove one item from structure list*/ + + boolean b = struc.get(0); + struc.remove(0); +/* If removed bit is 1,*/ + + if (b == true) + { +/* Remove an item from data list*/ + + int key = data.get(0); + data.remove(0); +/* Create a tree node with the + removed data*/ + + Node root = newNode(key); +/* And recur to create left and + right subtrees*/ + + root.left = DecodeSuccinct(); + root.right = DecodeSuccinct(); + return root; + } + return null; +} +/*A utility function to print tree*/ + +static void preorder(Node root) +{ + if (root != null) + { + System.out.print(""key: ""+ root.key); + if (root.left != null) + System.out.print("" | left child: "" + + root.left.key); + if (root.right != null) + System.out.print("" | right child: "" + + root.right.key); + System.out.println(); + preorder(root.left); + preorder(root.right); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Let us conthe Tree shown in + the above figure*/ + + Node root = newNode(10); + root.left = newNode(20); + root.right = newNode(30); + root.left.left = newNode(40); + root.left.right = newNode(50); + root.right.right = newNode(70); + System.out.print(""Given Tree\n""); + preorder(root); + struc = new Vector<>(); + data = new Vector<>(); + EncodeSuccinct(root); + System.out.print(""\nEncoded Tree\n""); + System.out.print(""Structure List\n""); +/*Structure iterator*/ + + for(boolean si : struc) + { + if (si == true) + System.out.print(1 + "" ""); + else + System.out.print(0 + "" ""); + } + System.out.print(""\nData List\n""); +/*Data iterator*/ + + for(int di : data) + System.out.print(di + "" ""); + Node newroot = DecodeSuccinct(); + System.out.print(""\n\nPreorder traversal"" + + ""of decoded tree\n""); + preorder(newroot); +} +}"," '''Python program to demonstrate Succinct Tree Encoding and Decoding''' + '''Node structure''' + +class Node: + def __init__(self , key): + self.key = key + self.left = None + self.right = None + + ''' This function fills lists 'struc' and + 'data'. 'struc' list stores structure + information. 'data' list stores tree data''' + +def EncodeSuccint(root , struc , data): ''' If root is None , put 0 in structure array and return''' + + if root is None : + struc.append(0) + return + ''' Else place 1 in structure array, key in 'data' array + and recur for left and right children''' + + struc.append(1) + data.append(root.key) + EncodeSuccint(root.left , struc , data) + EncodeSuccint(root.right , struc ,data) + '''Constructs tree from 'struc' and 'data''' + ''' +def DecodeSuccinct(struc , data): + if(len(struc) <= 0): + return None + ''' Remove one item from structure list''' + + b = struc[0] + struc.pop(0) + ''' If removed bit is 1''' + + if b == 1: + + ''' Remove an item from data list''' + + key = data[0] + data.pop(0) ''' Create a tree node with removed data''' + + root = Node(key) + ''' And recur to create left and right subtrees''' + + root.left = DecodeSuccinct(struc , data); + root.right = DecodeSuccinct(struc , data); + return root + return None + + ''' A utility function to print tree''' + +def preorder(root): + if root is not None: + print ""key: %d"" %(root.key), + if root.left is not None: + print ""| left child: %d"" %(root.left.key), + if root.right is not None: + print ""| right child %d"" %(root.right.key), + print """" + preorder(root.left) + preorder(root.right) '''Driver Program''' ''' Let us conthe Tree shown in + the above figure''' + +root = Node(10) +root.left = Node(20) +root.right = Node(30) +root.left.left = Node(40) +root.left.right = Node(50) +root.right.right = Node(70) +print ""Given Tree"" +preorder(root) +struc = [] +data = [] +EncodeSuccint(root , struc , data) +print ""\nEncoded Tree"" +print ""Structure List"" + '''Structure iterator''' + +for i in struc: + print i , +print ""\nDataList"" + '''Data iterator''' + +for value in data: + print value, +newroot = DecodeSuccinct(struc , data) +print ""\n\nPreorder Traversal of decoded tree"" +preorder(newroot)" +Find the element that appears once in an array where every other element appears twice,"/*Java program to find +element that appears once*/ + +import java.io.*; +import java.util.*; + +class GFG +{ + +/* function which find number*/ + + static int singleNumber(int[] nums, int n) + { + HashMap m = new HashMap<>(); + long sum1 = 0, sum2 = 0; + for (int i = 0; i < n; i++) + { + if (!m.containsKey(nums[i])) + { + sum1 += nums[i]; + m.put(nums[i], 1); + } + sum2 += nums[i]; + } + +/* applying the formula.*/ + + return (int)(2 * (sum1) - sum2); + } + +/* Driver code*/ + + public static void main(String args[]) + { + int[] a = {2, 3, 5, 4, 5, 3, 4}; + int n = 7; + System.out.println(singleNumber(a,n)); + + int[] b = {15, 18, 16, 18, 16, 15, 89}; + System.out.println(singleNumber(b,n)); + } +} + + +"," '''Python3 program to find +element that appears once''' + + + '''function which find number''' + +def singleNumber(nums): + + '''applying the formula.''' + + return 2 * sum(set(nums)) - sum(nums) + + '''driver code''' + +a = [2, 3, 5, 4, 5, 3, 4] +print (int(singleNumber(a))) + +a = [15, 18, 16, 18, 16, 15, 89] +print (int(singleNumber(a))) + + +" +Find k closest elements to a given value,"/*Java program to find k closest elements to a given value*/ + +class KClosest +{ + /* Function to find the cross over point (the point before + which elements are smaller than or equal to x and after + which greater than x)*/ + + int findCrossOver(int arr[], int low, int high, int x) + { +/* Base cases +x is greater than all*/ + +if (arr[high] <= x) + return high; +/*x is smaller than all*/ + +if (arr[low] > x) + return low; +/* Find the middle point*/ + + int mid = (low + high)/2; /* If x is same as middle element, then return mid */ + + if (arr[mid] <= x && arr[mid+1] > x) + return mid; + /* If x is greater than arr[mid], then either arr[mid + 1] + is ceiling of x or ceiling lies in arr[mid+1...high] */ + + if(arr[mid] < x) + return findCrossOver(arr, mid+1, high, x); + return findCrossOver(arr, low, mid - 1, x); + } +/* This function prints k closest elements to x in arr[]. + n is the number of elements in arr[]*/ + + void printKclosest(int arr[], int x, int k, int n) + { +/* Find the crossover point*/ + + int l = findCrossOver(arr, 0, n-1, x); +/*Right index to search*/ + +int r = l+1; +/*To keep track of count of elements already printed*/ + +int count = 0; +/*If x is present in arr[], then reduce left index + Assumption: all elements in arr[] are distinct*/ + + if (arr[l] == x) l--; +/* Compare elements on left and right of crossover + point to find the k closest elements*/ + + while (l >= 0 && r < n && count < k) + { + if (x - arr[l] < arr[r] - x) + System.out.print(arr[l--]+"" ""); + else + System.out.print(arr[r++]+"" ""); + count++; + } +/* If there are no more elements on right side, then + print left elements*/ + + while (count < k && l >= 0) + { + System.out.print(arr[l--]+"" ""); + count++; + } +/* If there are no more elements on left side, then + print right elements*/ + + while (count < k && r < n) + { + System.out.print(arr[r++]+"" ""); + count++; + } + } + /* Driver program to check above functions */ + + public static void main(String args[]) + { + KClosest ob = new KClosest(); + int arr[] = {12, 16, 22, 30, 35, 39, 42, + 45, 48, 50, 53, 55, 56 + }; + int n = arr.length; + int x = 35, k = 4; + ob.printKclosest(arr, x, 4, n); + } +}"," '''Function to find the cross over point +(the point before which elements are +smaller than or equal to x and after +which greater than x)''' + +def findCrossOver(arr, low, high, x) : + ''' Base cases +x is greater than all''' + + if (arr[high] <= x) : + return high + + '''x is smaller than all''' + + if (arr[low] > x) : + return low + + ''' Find the middle point''' + + mid = (low + high) // 2 + ''' If x is same as middle element, + then return mid''' + + if (arr[mid] <= x and arr[mid + 1] > x) : + return mid + ''' If x is greater than arr[mid], then + either arr[mid + 1] is ceiling of x + or ceiling lies in arr[mid+1...high]''' + + if(arr[mid] < x) : + return findCrossOver(arr, mid + 1, high, x) + return findCrossOver(arr, low, mid - 1, x) + '''This function prints k closest elements to x +in arr[]. n is the number of elements in arr[]''' + +def printKclosest(arr, x, k, n) : + ''' Find the crossover point''' + + l = findCrossOver(arr, 0, n - 1, x) + '''Right index to search''' + + r = l + 1 + + '''To keep track of count of elements already printed''' + + count = 0 + '''If x is present in arr[], then reduce + left index. Assumption: all elements + in arr[] are distinct''' + + if (arr[l] == x) : + l -= 1 + ''' Compare elements on left and right of crossover + point to find the k closest elements''' + + while (l >= 0 and r < n and count < k) : + if (x - arr[l] < arr[r] - x) : + print(arr[l], end = "" "") + l -= 1 + else : + print(arr[r], end = "" "") + r += 1 + count += 1 + ''' If there are no more elements on right + side, then print left elements''' + + while (count < k and l >= 0) : + print(arr[l], end = "" "") + l -= 1 + count += 1 + ''' If there are no more elements on left + side, then print right elements''' + + while (count < k and r < n) : + print(arr[r], end = "" "") + r += 1 + count += 1 + '''Driver Code''' + +if __name__ == ""__main__"" : + arr =[12, 16, 22, 30, 35, 39, 42, + 45, 48, 50, 53, 55, 56] + n = len(arr) + x = 35 + k = 4 + printKclosest(arr, x, 4, n)" +Ways of filling matrix such that product of all rows and all columns are equal to unity,"/*Java program to find number of ways to fill +a matrix under given constraints*/ + +import java.io.*; +class Example { + final static long mod = 100000007; + /* Returns a raised power t under modulo mod */ + + static long modPower(long a, long t, long mod) + { + long now = a, ret = 1; +/* Counting number of ways of filling the + matrix*/ + + while (t > 0) { + if (t % 2 == 1) + ret = now * (ret % mod); + now = now * (now % mod); + t >>= 1; + } + return ret; + } +/* Function calculating the answer*/ + + static long countWays(int n, int m, int k) + { +/* if sum of numbers of rows and columns is + odd i.e (n + m) % 2 == 1 and k = -1, + then there are 0 ways of filiing the matrix.*/ + + if (n == 1 || m == 1) + return 1; +/* If there is one row or one column then + there is only one way of filling the matrix*/ + + else if ((n + m) % 2 == 1 && k == -1) + return 0; +/* If the above cases are not followed then we + find ways to fill the n - 1 rows and m - 1 + columns which is 2 ^ ((m-1)*(n-1)).*/ + + return (modPower(modPower((long)2, n - 1, mod), + m - 1, mod) % mod); + } +/* Driver function for the program*/ + + public static void main(String args[]) throws IOException + { + int n = 2, m = 7, k = 1; + System.out.println(countWays(n, m, k)); + } +}"," '''Python program to find number of ways to +fill a matrix under given constraints + ''' '''Returns a raised power t under modulo mod''' + +def modPower(a, t): + now = a; + ret = 1; + mod = 100000007; + ''' Counting number of ways of filling + the matrix''' + + while (t): + if (t & 1): + ret = now * (ret % mod); + now = now * (now % mod); + t >>= 1; + return ret; + '''Function calculating the answer''' + +def countWays(n, m, k): + mod= 100000007; + ''' if sum of numbers of rows and columns + is odd i.e (n + m) % 2 == 1 and k = -1 + then there are 0 ways of filiing the matrix.''' + + if (k == -1 and ((n + m) % 2 == 1)): + return 0; + ''' If there is one row or one column then + there is only one way of filling the matrix''' + + if (n == 1 or m == 1): + return 1; + ''' If the above cases are not followed then we + find ways to fill the n - 1 rows and m - 1 + columns which is 2 ^ ((m-1)*(n-1)).''' + + return (modPower(modPower(2, n - 1), + m - 1) % mod); + '''Driver Code''' + +n = 2; +m = 7; +k = 1; +print(countWays(n, m, k));" +Find a triplet that sum to a given value,"/*Java program to find a triplet using Hashing*/ + +import java.util.*; +class GFG { +/* returns true if there is triplet + with sum equal to 'sum' present + in A[]. Also, prints the triplet*/ + + static boolean find3Numbers(int A[], + int arr_size, int sum) + { +/* Fix the first element as A[i]*/ + + for (int i = 0; i < arr_size - 2; i++) { +/* Find pair in subarray A[i+1..n-1] + with sum equal to sum - A[i]*/ + + HashSet s = new HashSet(); + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.contains(curr_sum - A[j])) + { + System.out.printf(""Triplet is %d, + %d, %d"", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.add(A[j]); + } + } +/* If we reach here, then no triplet was found*/ + + return false; + } + /* Driver code */ + + public static void main(String[] args) + { + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + find3Numbers(A, arr_size, sum); + } +}"," '''Python3 program to find a triplet using Hashing''' + '''returns true if there is triplet with sum equal +to 'sum' present in A[]. Also, prints the triplet''' + +def find3Numbers(A, arr_size, sum): + ''' Fix the first element as A[i]''' + + for i in range(0, arr_size-1): + ''' Find pair in subarray A[i + 1..n-1] + with sum equal to sum - A[i]''' + + s = set() + curr_sum = sum - A[i] + for j in range(i + 1, arr_size): + if (curr_sum - A[j]) in s: + print(""Triplet is"", A[i], + "", "", A[j], "", "", curr_sum-A[j]) + return True + s.add(A[j]) + + ''' If we reach here, then no triplet was found''' + + return False '''Driver program to test above function ''' + +A = [1, 4, 45, 6, 10, 8] +sum = 22 +arr_size = len(A) +find3Numbers(A, arr_size, sum)" +Sum of heights of all individual nodes in a binary tree,"/*Java program to find sum of heights of all +nodes in a binary tree*/ + +class GFG +{ + /* A binary tree Node has data, pointer to + left child and a pointer to right child */ + + static class Node + { + int data; + Node left; + Node right; + }; + static int sum; + /* Helper function that allocates a new Node with the + given data and null left and right pointers. */ + + static Node newNode(int data) + { + Node Node = new Node(); + Node.data = data; + Node.left = null; + Node.right = null; + return (Node); + } + /* Function to sum of heights of individual Nodes + Uses Inorder traversal */ + + static int getTotalHeightUtil(Node root) + { + if (root == null) + { + return 0; + } + int lh = getTotalHeightUtil(root.left); + int rh = getTotalHeightUtil(root.right); + int h = Math.max(lh, rh) + 1; + sum = sum + h; + return h; + } + static int getTotalHeight(Node root) + { + sum = 0; + getTotalHeightUtil(root); + return sum; + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + System.out.printf(""Sum of heights of all Nodes = %d"", + getTotalHeight(root)); + } +}"," '''Python3 program to find sum of heights +of all nodes in a binary tree''' + + '''A binary tree Node has data, pointer to +left child and a pointer to right child''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None +sum = 0 '''Function to sum of heights of individual +Nodes Uses Inorder traversal''' + +def getTotalHeightUtil(root): + global sum + if (root == None): + return 0 + lh = getTotalHeightUtil(root.left) + rh = getTotalHeightUtil(root.right) + h = max(lh, rh) + 1 + sum = sum + h + return h +def getTotalHeight(root): + getTotalHeightUtil(root) + return sum + '''Driver code''' + +if __name__ == '__main__': + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + print(""Sum of heights of all Nodes ="", + getTotalHeight(root))" +Count the number of possible triangles,"/*Java code to count the number of +possible triangles using brute +force approach*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Function to count all possible + triangles with arr[] elements*/ + + static int findNumberOfTriangles(int arr[], int n) + { +/* Count of triangles*/ + + int count = 0; +/* The three loops select three + different values from array*/ + + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { +/* The innermost loop checks for + the triangle property*/ + + for (int k = j + 1; k < n; k++) +/* Sum of two sides is greater + than the third*/ + + if ( + arr[i] + arr[j] > arr[k] + && arr[i] + arr[k] > arr[j] + && arr[k] + arr[j] > arr[i]) + count++; + } + } + return count; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; + int size = arr.length; + System.out.println( ""Total number of triangles possible is ""+ + findNumberOfTriangles(arr, size)); + } +}"," '''Python3 code to count the number of +possible triangles using brute +force approach + ''' '''Function to count all possible +triangles with arr[] elements''' + +def findNumberOfTriangles(arr, n): + ''' Count of triangles''' + + count = 0 + ''' The three loops select three + different values from array''' + + for i in range(n): + for j in range(i + 1, n): + ''' The innermost loop checks for + the triangle property''' + + for k in range(j + 1, n): + ''' Sum of two sides is greater + than the third''' + + if (arr[i] + arr[j] > arr[k] and + arr[i] + arr[k] > arr[j] and + arr[k] + arr[j] > arr[i]): + count += 1 + return count + '''Driver code''' + +arr = [ 10, 21, 22, 100, 101, 200, 300 ] +size = len(arr) +print(""Total number of triangles possible is"", + findNumberOfTriangles(arr, size))" +Write Code to Determine if Two Trees are Identical,"/*Java program to see if two trees are identical*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root1, root2;/* Given two trees, return true if they are + structurally identical */ + + boolean identicalTrees(Node a, Node b) + { + /*1. both empty */ + + if (a == null && b == null) + return true; + /* 2. both non-empty -> compare them */ + + if (a != null && b != null) + return (a.data == b.data + && identicalTrees(a.left, b.left) + && identicalTrees(a.right, b.right)); + /* 3. one empty, one not -> false */ + + return false; + } + /* Driver program to test identicalTrees() function */ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root1 = new Node(1); + tree.root1.left = new Node(2); + tree.root1.right = new Node(3); + tree.root1.left.left = new Node(4); + tree.root1.left.right = new Node(5); + tree.root2 = new Node(1); + tree.root2.left = new Node(2); + tree.root2.right = new Node(3); + tree.root2.left.left = new Node(4); + tree.root2.left.right = new Node(5); + if (tree.identicalTrees(tree.root1, tree.root2)) + System.out.println(""Both trees are identical""); + else + System.out.println(""Trees are not identical""); + } +}"," '''Python program to determine if two trees are identical''' + + '''A binary tree node has data, pointer to left child +and a pointer to right child''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Given two trees, return true if they are structurally +identical''' + +def identicalTrees(a, b): + ''' 1. Both empty''' + + if a is None and b is None: + return True + ''' 2. Both non-empty -> Compare them''' + + if a is not None and b is not None: + return ((a.data == b.data) and + identicalTrees(a.left, b.left)and + identicalTrees(a.right, b.right)) + ''' 3. one empty, one not -- false''' + + return False + '''Driver program to test identicalTress function''' + +root1 = Node(1) +root2 = Node(1) +root1.left = Node(2) +root1.right = Node(3) +root1.left.left = Node(4) +root1.left.right = Node(5) +root2.left = Node(2) +root2.right = Node(3) +root2.left.left = Node(4) +root2.left.right = Node(5) +if identicalTrees(root1, root2): + print ""Both trees are identical"" +else: + print ""Trees are not identical""" +Check if an array is sorted and rotated,"/*Java program to check if an +array is sorted and rotated +clockwise*/ + +import java.io.*; + +class GFG { + +/* Function to check if an array is + sorted and rotated clockwise*/ + + static void checkIfSortRotated(int arr[], int n) + { + int minEle = Integer.MAX_VALUE; + int maxEle = Integer.MIN_VALUE; + + int minIndex = -1; + +/* Find the minimum element + and it's index*/ + + for (int i = 0; i < n; i++) { + if (arr[i] < minEle) { + minEle = arr[i]; + minIndex = i; + } + } + + boolean flag1 = true; + +/* Check if all elements before + minIndex are in increasing order*/ + + for (int i = 1; i < minIndex; i++) { + if (arr[i] < arr[i - 1]) { + flag1 = false; + break; + } + } + + boolean flag2 = true; + +/* Check if all elements after + minIndex are in increasing order*/ + + for (int i = minIndex + 1; i < n; i++) { + if (arr[i] < arr[i - 1]) { + flag2 = false; + break; + } + } + +/* check if the minIndex is 0, i.e the first element + is the smallest , which is the case when array is + sorted but not rotated.*/ + + if (minIndex == 0) { + System.out.print(""NO""); + return; + } +/* Check if last element of the array + is smaller than the element just + before the element at minIndex + starting element of the array + for arrays like [3,4,6,1,2,5] - not sorted + circular array*/ + + if (flag1 && flag2 && (arr[n - 1] < arr[0])) + System.out.println(""YES""); + else + System.out.print(""NO""); + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 3, 4, 5, 1, 2 }; + + int n = arr.length; + +/* Function Call*/ + + checkIfSortRotated(arr, n); + } +} + + +"," '''Python3 program to check if an +array is sorted and rotated clockwise''' + +import sys + + '''Function to check if an array is +sorted and rotated clockwise''' + + + +def checkIfSortRotated(arr, n): + minEle = sys.maxsize + maxEle = -sys.maxsize - 1 + minIndex = -1 + + ''' Find the minimum element + and it's index''' + + for i in range(n): + if arr[i] < minEle: + minEle = arr[i] + minIndex = i + flag1 = 1 + + ''' Check if all elements before + minIndex are in increasing order''' + + for i in range(1, minIndex): + if arr[i] < arr[i - 1]: + flag1 = 0 + break + flag2 = 2 + + ''' Check if all elements after + minIndex are in increasing order''' + + for i in range(minIndex + 1, n): + if arr[i] < arr[i - 1]: + flag2 = 0 + break + + ''' Check if last element of the array + is smaller than the element just + before the element at minIndex + starting element of the array + for arrays like [3,4,6,1,2,5] - not sorted circular array''' + + if (flag1 and flag2 and + arr[n - 1] < arr[0]): + print(""YES"") + else: + print(""NO"") + + + '''Driver code''' + +arr = [3, 4, 5, 1, 2] +n = len(arr) + + '''Function Call''' + +checkIfSortRotated(arr, n) + + +" +Deepest left leaf node in a binary tree | iterative approach,"/*Java program to find deepest left leaf +node of binary tree*/ + +import java.util.*; +class GFG +{ +/*tree node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*returns a new tree Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*return the deepest left leaf node +of binary tree*/ + +static Node getDeepestLeftLeafNode(Node root) +{ + if (root == null) + return null; +/* create a queue for level order traversal*/ + + Queue q = new LinkedList<>(); + q.add(root); + Node result = null; +/* traverse until the queue is empty*/ + + while (!q.isEmpty()) + { + Node temp = q.peek(); + q.remove(); +/* Since we go level by level, the last + stored left leaf node is deepest one,*/ + + if (temp.left != null) + { + q.add(temp.left); + if (temp.left.left == null && + temp.left.right == null) + result = temp.left; + } + if (temp.right != null) + q.add(temp.right); + } + return result; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* construct a tree*/ + + 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(6); + root.right.left.right = newNode(7); + root.right.right.right = newNode(8); + root.right.left.right.left = newNode(9); + root.right.right.right.right = newNode(10); + Node result = getDeepestLeftLeafNode(root); + if (result != null) + System.out.println(""Deepest Left Leaf Node :: "" + + result.data); + else + System.out.println(""No result, "" + + ""left leaf not found""); + } +}"," '''Python3 program to find deepest +left leaf Binary search Tree''' + '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newnode: + ''' Constructor to create a new node ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''utility function to return deepest +left leaf node''' + +def getDeepestLeftLeafNode(root) : + if (not root): + return None + ''' create a queue for level + order traversal ''' + + q = [] + q.append(root) + result = None + ''' traverse until the queue is empty ''' + + while (len(q)): + temp = q[0] + q.pop(0) + if (temp.left): + q.append(temp.left) + if (not temp.left.left and + not temp.left.right): + result = temp.left + ''' Since we go level by level, + the last stored right leaf + node is deepest one ''' + + if (temp.right): + q.append(temp.right) + return result + '''Driver Code ''' + +if __name__ == '__main__': + ''' create a binary tree ''' + + 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(6) + root.right.left.right = newnode(7) + root.right.right.right = newnode(8) + root.right.left.right.left = newnode(9) + root.right.right.right.right = newnode(10) + result = getDeepestLeftLeafNode(root) + if result: + print(""Deepest Left Leaf Node ::"", + result.data) + else: + print(""No result, Left leaf not found"")" +Find maximum (or minimum) in Binary Tree,"/*Returns the min value in a binary tree*/ + +static int findMin(Node node) +{ + if (node == null) + return Integer.MAX_VALUE; + int res = node.data; + int lres = findMin(node.left); + int rres = findMin(node.right); + if (lres < res) + res = lres; + if (rres < res) + res = rres; + return res; +}"," '''Returns the min value in a binary tree''' + +def find_min_in_BT(root): + if root is None: + return float('inf') + res = root.data + lres = find_min_in_BT(root.leftChild) + rres = find_min_in_BT(root.rightChild) + if lres < res: + res = lres + if rres < res: + res = rres + return res" +Count the number of possible triangles,"/*Java implementation of the above approach*/ + +import java.util.*; +class GFG { + +/*CountTriangles function*/ + + static void CountTriangles(int[] A) + { + int n = A.length; + Arrays.sort(A); + int count = 0; + for (int i = n - 1; i >= 1; i--) { + int l = 0, r = i - 1; + while (l < r) { + if (A[l] + A[r] > A[i]) {/* If it is possible with a[l], a[r] + and a[i] then it is also possible + with a[l+1]..a[r-1], a[r] and a[i]*/ + + count += r - l; +/* checking for more possible solutions*/ + + r--; + } +/*if not possible check for higher values of arr[l]*/ + +else + { + l++; + } + } + } + System.out.print(""No of possible solutions: "" + count); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] A = { 4, 3, 5, 7, 6 }; + CountTriangles(A); + } +}"," '''Python implementation of the above approach''' + + + '''CountTriangles function''' + +def CountTriangles( A): + n = len(A); + A.sort(); + count = 0; + for i in range(n - 1, 0, -1): + l = 0; + r = i - 1; + while(l < r): + if(A[l] + A[r] > A[i]): ''' If it is possible with a[l], a[r] + and a[i] then it is also possible + with a[l + 1]..a[r-1], a[r] and a[i]''' + + count += r - l; + ''' checking for more possible solutions''' + + r -= 1; + + ''' if not possible check for + higher values of arr[l]''' + else: + l += 1; + print(""No of possible solutions: "", count); + '''Driver Code''' + +if __name__ == '__main__': + A = [ 4, 3, 5, 7, 6 ]; + CountTriangles(A);" +Find distance from root to given node in a binary tree,"/*Java program to find distance of a given +node from root.*/ + +import java.util.*; +class GfG { +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +} +/*A utility function to create a new Binary +Tree Node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.data = item; + temp.left = null; + temp.right = null; + return temp; +} +/*Returns -1 if x doesn't exist in tree. Else +returns distance of x from root*/ + +static int findDistance(Node root, int x) +{ +/* Base case*/ + + if (root == null) + return -1; +/* Initialize distance*/ + + int dist = -1; +/* Check if x is present at root or in left + subtree or right subtree.*/ + + if ((root.data == x) || + (dist = findDistance(root.left, x)) >= 0 || + (dist = findDistance(root.right, x)) >= 0) + return dist + 1; + return dist; +} +/*Driver Program to test above functions*/ + +public static void main(String[] args) +{ + Node root = newNode(5); + root.left = newNode(10); + root.right = newNode(15); + root.left.left = newNode(20); + root.left.right = newNode(25); + root.left.right.right = newNode(45); + root.right.left = newNode(30); + root.right.right = newNode(35); + System.out.println(findDistance(root, 45)); +} +}"," '''Python3 program to find distance of +a given node from root.''' + + '''A class to create a new Binary +Tree Node''' + +class newNode: + def __init__(self, item): + self.data = item + self.left = self.right = None '''Returns -1 if x doesn't exist in tree. +Else returns distance of x from root''' + +def findDistance(root, x): + ''' Base case''' + + if (root == None): + return -1 + ''' Initialize distance''' + + dist = -1 + ''' Check if x is present at root or + in left subtree or right subtree.''' + + if (root.data == x): + return dist + 1 + else: + dist = findDistance(root.left, x) + if dist >= 0: + return dist + 1 + else: + dist = findDistance(root.right, x) + if dist >= 0: + return dist + 1 + return dist + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(5) + root.left = newNode(10) + root.right = newNode(15) + root.left.left = newNode(20) + root.left.right = newNode(25) + root.left.right.right = newNode(45) + root.right.left = newNode(30) + root.right.right = newNode(35) + print(findDistance(root, 45))" +Maximum area rectangle by picking four sides from array,"/*Java program for finding maximum +area possible of a rectangle*/ + +import java.util.HashSet; +import java.util.Set; +public class GFG +{ +/* function for finding max area*/ + + static int findArea(int arr[], int n) + { + Set s = new HashSet<>();/* traverse through array*/ + + int first = 0, second = 0; + for (int i = 0; i < n; i++) { +/* If this is first occurrence of + arr[i], simply insert and continue*/ + + if (!s.contains(arr[i])) { + s.add(arr[i]); + continue; + } +/* If this is second (or more) + occurrence, update first and + second maximum values.*/ + + if (arr[i] > first) { + second = first; + first = arr[i]; + } else if (arr[i] > second) + second = arr[i]; + } +/* return the product of dimensions*/ + + return (first * second); + } +/* driver function*/ + + public static void main(String args[]) + { + int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; + int n = arr.length; + System.out.println(findArea(arr, n)); + } +}"," '''Python 3 program for finding maximum +area possible of a rectangle''' + '''function for finding max area''' + +def findArea(arr, n): + s = [] + ''' traverse through array''' + + first = 0 + second = 0 + for i in range(n) : + ''' If this is first occurrence of + arr[i], simply insert and continue''' + + if arr[i] not in s: + s.append(arr[i]) + continue + ''' If this is second (or more) occurrence, + update first and second maximum values.''' + + if (arr[i] > first) : + second = first + first = arr[i] + elif (arr[i] > second): + second = arr[i] + ''' return the product of dimensions''' + + return (first * second) + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ] + n = len(arr) + print(findArea(arr, n))" +Count the number of possible triangles,"/*Java program to count number of triangles that can be +formed from given array*/ + +import java.io.*; +import java.util.*; +class CountTriangles { +/* Function to count all possible triangles with arr[] + elements*/ + + static int findNumberOfTriangles(int arr[]) + { + int n = arr.length; +/* Sort the array elements in non-decreasing order*/ + + Arrays.sort(arr); +/* Initialize count of triangles*/ + + int count = 0; +/* Fix the first element. We need to run till n-3 as + the other two elements are selected from arr[i+1...n-1]*/ + + for (int i = 0; i < n - 2; ++i) { +/* Initialize index of the rightmost third element*/ + + int k = i + 2; +/* Fix the second element*/ + + for (int j = i + 1; j < n; ++j) { + /* Find the rightmost element which is smaller + than the sum of two fixed elements + The important thing to note here is, we use + the previous value of k. If value of arr[i] + + arr[j-1] was greater than arr[k], then arr[i] + + arr[j] must be greater than k, because the + array is sorted. */ + + while (k < n && arr[i] + arr[j] > arr[k]) + ++k; + /* Total number of possible triangles that can be + formed with the two fixed elements is k - j - 1. + The two fixed elements are arr[i] and arr[j]. All + elements between arr[j+1] to arr[k-1] can form a + triangle with arr[i] and arr[j]. One is subtracted + from k because k is incremented one extra in above + while loop. k will always be greater than j. If j + becomes equal to k, then above loop will increment + k, because arr[k] + arr[i] is always/ greater than + arr[k] */ + + if (k > j) + count += k - j - 1; + } + } + return count; + } +/*Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; + System.out.println(""Total number of triangles is "" + findNumberOfTriangles(arr)); + } +}"," '''Python function to count all possible triangles with arr[] +elements''' + + ''' Function to count all possible triangles with arr[] + elements''' + +def findnumberofTriangles(arr): + n = len(arr) ''' Sort array and initialize count as 0''' + + + arr.sort() + + ''' Initialize count of triangles''' + + count = 0 ''' Fix the first element. We need to run till n-3 as + the other two elements are selected from arr[i + 1...n-1]''' + + for i in range(0, n-2): + ''' Initialize index of the rightmost third element''' + + k = i + 2 + ''' Fix the second element''' + + for j in range(i + 1, n): + ''' Find the rightmost element which is smaller + than the sum of two fixed elements + The important thing to note here is, we use + the previous value of k. If value of arr[i] + + arr[j-1] was greater than arr[k], then arr[i] + + arr[j] must be greater than k, because the array + is sorted.''' + + while (k < n and arr[i] + arr[j] > arr[k]): + k += 1 + ''' Total number of possible triangles that can be + formed with the two fixed elements is k - j - 1. + The two fixed elements are arr[i] and arr[j]. All + elements between arr[j + 1] to arr[k-1] can form a + triangle with arr[i] and arr[j]. One is subtracted + from k because k is incremented one extra in above + while loop. k will always be greater than j. If j + becomes equal to k, then above loop will increment k, + because arr[k] + arr[i] is always greater than arr[k]''' + + if(k>j): + count += k - j - 1 + return count + '''Driver function to test above function''' + +arr = [10, 21, 22, 100, 101, 200, 300] +print ""Number of Triangles:"", findnumberofTriangles(arr)" +Check whether given degrees of vertices represent a Graph or Tree,"/*Java program to check whether input degree +sequence is graph or tree */ + +class GFG +{ +/* Function returns true for tree + false for graph */ + + static boolean check(int degree[], int n) + { +/* Find sum of all degrees */ + + int deg_sum = 0; + for (int i = 0; i < n; i++) + { + deg_sum += degree[i]; + } +/* Graph is tree if sum is equal to 2(n-1) */ + + return (2 * (n - 1) == deg_sum); + } +/* Driver code */ + + public static void main(String[] args) + { + int n = 5; + int degree[] = {2, 3, 1, 1, 1}; + if (check(degree, n)) + { + System.out.println(""Tree""); + } + else + { + System.out.println(""Graph""); + } + } +}"," '''Python program to check whether input degree +sequence is graph or tree''' + + '''Function returns true for tree + false for graph''' + +def check(degree, n): ''' Find sum of all degrees''' + + deg_sum = sum(degree) + ''' It is tree if sum is equal to 2(n-1)''' + + if (2*(n-1) == deg_sum): + return True + else: + return False + '''main''' + +n = 5 +degree = [2, 3, 1, 1, 1]; +if (check(degree, n)): + print ""Tree"" +else: + print ""Graph""" +Count subarrays with equal number of 1's and 0's,"/*Java implementation to count subarrays with +equal number of 1's and 0's*/ + +import java.util.*; +class GFG +{ +/*function to count subarrays with +equal number of 1's and 0's*/ + +static int countSubarrWithEqualZeroAndOne(int arr[], int n) +{ +/* 'um' implemented as hash table to store + frequency of values obtained through + cumulative sum*/ + + Map um = new HashMap<>(); + int curr_sum = 0; +/* Traverse original array and compute cumulative + sum and increase count by 1 for this sum + in 'um'. Adds '-1' when arr[i] == 0*/ + + for (int i = 0; i < n; i++) { + curr_sum += (arr[i] == 0) ? -1 : arr[i]; + um.put(curr_sum, um.get(curr_sum)==null?1:um.get(curr_sum)+1); + } + int count = 0; +/* traverse the hash table 'um'*/ + + for (Map.Entry itr : um.entrySet()) + { +/* If there are more than one prefix subarrays + with a particular sum*/ + + if (itr.getValue() > 1) + count += ((itr.getValue()* (itr.getValue()- 1)) / 2); + } +/* add the subarrays starting from 1st element and + have equal number of 1's and 0's*/ + + if (um.containsKey(0)) + count += um.get(0); +/* required count of subarrays*/ + + return count; +} +/*Driver program to test above*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; + int n = arr.length; + System.out.println(""Count = "" + + countSubarrWithEqualZeroAndOne(arr, n)); +} +}"," '''Python3 implementation to count +subarrays with equal number +of 1's and 0's + ''' '''function to count subarrays with +equal number of 1's and 0's''' + +def countSubarrWithEqualZeroAndOne (arr, n): + ''' 'um' implemented as hash table + to store frequency of values + obtained through cumulative sum''' + + um = dict() + curr_sum = 0 + ''' Traverse original array and compute + cumulative sum and increase count + by 1 for this sum in 'um'. + Adds '-1' when arr[i] == 0''' + + for i in range(n): + curr_sum += (-1 if (arr[i] == 0) else arr[i]) + if um.get(curr_sum): + um[curr_sum]+=1 + else: + um[curr_sum]=1 + count = 0 + ''' traverse the hash table um''' + for itr in um: + ''' If there are more than one + prefix subarrays with a + particular sum''' + + if um[itr] > 1: + count += ((um[itr] * int(um[itr] - 1)) / 2) + ''' add the subarrays starting from + 1st element and have equal + number of 1's and 0's''' + + if um.get(0): + count += um[0] + ''' required count of subarrays''' + + return int(count) + '''Driver code to test above''' + +arr = [ 1, 0, 0, 1, 0, 1, 1 ] +n = len(arr) +print(""Count ="", + countSubarrWithEqualZeroAndOne(arr, n))" +Range LCM Queries,"/*LCM of given range queries +using Segment Tree*/ + +class GFG +{ + static final int MAX = 1000; +/* allocate space for tree*/ + + static int tree[] = new int[4 * MAX]; +/* declaring the array globally*/ + + static int arr[] = new int[MAX]; +/* Function to return gcd of a and b*/ + + static int gcd(int a, int b) { + if (a == 0) { + return b; + } + return gcd(b % a, a); + } +/* utility function to find lcm*/ + + static int lcm(int a, int b) + { + return a * b / gcd(a, b); + } +/* Function to build the segment tree + Node starts beginning index + of current subtree. start and end + are indexes in arr[] which is global*/ + + static void build(int node, int start, int end) + { +/* If there is only one element + in current subarray*/ + + if (start == end) + { + tree[node] = arr[start]; + return; + } + int mid = (start + end) / 2; +/* build left and right segments*/ + + build(2 * node, start, mid); + build(2 * node + 1, mid + 1, end); +/* build the parent*/ + + int left_lcm = tree[2 * node]; + int right_lcm = tree[2 * node + 1]; + tree[node] = lcm(left_lcm, right_lcm); + } +/* Function to make queries for + array range )l, r). Node is index + of root of current segment in segment + tree (Note that indexes in segment + tree begin with 1 for simplicity). + start and end are indexes of subarray + covered by root of current segment.*/ + + static int query(int node, int start, + int end, int l, int r) + { +/* Completely outside the segment, returning + 1 will not affect the lcm;*/ + + if (end < l || start > r) + { + return 1; + } +/* completely inside the segment*/ + + if (l <= start && r >= end) + { + return tree[node]; + } +/* partially inside*/ + + int mid = (start + end) / 2; + int left_lcm = query(2 * node, start, mid, l, r); + int right_lcm = query(2 * node + 1, mid + 1, end, l, r); + return lcm(left_lcm, right_lcm); + } +/* Driver code*/ + + public static void main(String[] args) + { +/* initialize the array*/ + + arr[0] = 5; + arr[1] = 7; + arr[2] = 5; + arr[3] = 2; + arr[4] = 10; + arr[5] = 12; + arr[6] = 11; + arr[7] = 17; + arr[8] = 14; + arr[9] = 1; + arr[10] = 44; +/* build the segment tree*/ + + build(1, 0, 10); +/* Now we can answer each query efficiently + Print LCM of (2, 5)*/ + + System.out.println(query(1, 0, 10, 2, 5)); +/* Print LCM of (5, 10)*/ + + System.out.println(query(1, 0, 10, 5, 10)); +/* Print LCM of (0, 10)*/ + + System.out.println(query(1, 0, 10, 0, 10)); + } +}"," '''LCM of given range queries using Segment Tree''' + +MAX = 1000 + '''allocate space for tree''' + +tree = [0] * (4 * MAX) + '''declaring the array globally''' + +arr = [0] * MAX + '''Function to return gcd of a and b''' + +def gcd(a: int, b: int): + if a == 0: + return b + return gcd(b % a, a) + '''utility function to find lcm''' + +def lcm(a: int, b: int): + return (a * b) // gcd(a, b) + '''Function to build the segment tree +Node starts beginning index of current subtree. +start and end are indexes in arr[] which is global''' + +def build(node: int, start: int, end: int): + ''' If there is only one element + in current subarray''' + + if start == end: + tree[node] = arr[start] + return + mid = (start + end) // 2 + ''' build left and right segments''' + + build(2 * node, start, mid) + build(2 * node + 1, mid + 1, end) + ''' build the parent''' + + left_lcm = tree[2 * node] + right_lcm = tree[2 * node + 1] + tree[node] = lcm(left_lcm, right_lcm) + '''Function to make queries for array range )l, r). +Node is index of root of current segment in segment +tree (Note that indexes in segment tree begin with 1 +for simplicity). +start and end are indexes of subarray covered by root +of current segment.''' + +def query(node: int, start: int, + end: int, l: int, r: int): + ''' Completely outside the segment, + returning 1 will not affect the lcm;''' + + if end < l or start > r: + return 1 + ''' completely inside the segment''' + + if l <= start and r >= end: + return tree[node] + ''' partially inside''' + + mid = (start + end) // 2 + left_lcm = query(2 * node, start, mid, l, r) + right_lcm = query(2 * node + 1, + mid + 1, end, l, r) + return lcm(left_lcm, right_lcm) + '''Driver Code''' + +if __name__ == ""__main__"": + ''' initialize the array''' + + arr[0] = 5 + arr[1] = 7 + arr[2] = 5 + arr[3] = 2 + arr[4] = 10 + arr[5] = 12 + arr[6] = 11 + arr[7] = 17 + arr[8] = 14 + arr[9] = 1 + arr[10] = 44 + ''' build the segment tree''' + + build(1, 0, 10) + ''' Now we can answer each query efficiently + Print LCM of (2, 5)''' + + print(query(1, 0, 10, 2, 5)) + ''' Print LCM of (5, 10)''' + + print(query(1, 0, 10, 5, 10)) + ''' Print LCM of (0, 10)''' + + print(query(1, 0, 10, 0, 10))" +Count quadruples from four sorted arrays whose sum is equal to a given value x,"/*Java implementation to count quadruples from +four sorted arrays whose sum is equal to a +given value x*/ + +class GFG { +/*count pairs from the two sorted array whose sum +is equal to the given 'value'*/ + +static int countPairs(int arr1[], int arr2[], int n, int value) +{ + int count = 0; + int l = 0, r = n - 1; +/* traverse 'arr1[]' from left to right + traverse 'arr2[]' from right to left*/ + + while (l < n & r >= 0) { + int sum = arr1[l] + arr2[r]; +/* if the 'sum' is equal to 'value', then + increment 'l', decrement 'r' and + increment 'count'*/ + + if (sum == value) { + l++; r--; + count++; + } +/* if the 'sum' is greater than 'value', then + decrement r*/ + + else if (sum > value) + r--; +/* else increment l*/ + + else + l++; + } +/* required count of pairs*/ + + return count; +} +/*function to count all quadruples from four sorted arrays +whose sum is equal to a given value x*/ + +static int countQuadruples(int arr1[], int arr2[], int arr3[], + int arr4[], int n, int x) +{ + int count = 0; +/* generate all pairs from arr1[] and arr2[]*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) { +/* calculate the sum of elements in + the pair so generated*/ + + int p_sum = arr1[i] + arr2[j]; +/* count pairs in the 3rd and 4th array + having value 'x-p_sum' and then + accumulate it to 'count'*/ + + count += countPairs(arr3, arr4, n, x - p_sum); + } +/* required count of quadruples*/ + + return count; +} +/*Driver program to test above*/ + + static public void main(String[] args) { +/* four sorted arrays each of size 'n'*/ + + int arr1[] = {1, 4, 5, 6}; + int arr2[] = {2, 3, 7, 8}; + int arr3[] = {1, 4, 6, 10}; + int arr4[] = {2, 4, 7, 8}; + int n = arr1.length; + int x = 30; + System.out.println(""Count = "" + + countQuadruples(arr1, arr2, arr3, arr4, n, x)); + } +}"," '''Python3 implementation to +count quadruples from four +sorted arrays whose sum is +equal to a given value x''' + + '''count pairs from the two +sorted array whose sum +is equal to the given 'value' ''' +def countPairs(arr1, arr2, + n, value): + count = 0 + l = 0 + r = n - 1 ''' traverse 'arr1[]' from + left to right + traverse 'arr2[]' from + right to left''' + + while (l < n and r >= 0): + sum = arr1[l] + arr2[r] + ''' if the 'sum' is equal + to 'value', then + increment 'l', decrement + 'r' and increment 'count' ''' + if (sum == value): + l += 1 + r -= 1 + count += 1 + ''' if the 'sum' is greater + than 'value', then decrement r''' + + elif (sum > value): + r -= 1 + ''' else increment l''' + + else: + l += 1 + ''' required count of pairs + print(count)''' + + return count + '''function to count all quadruples +from four sorted arrays whose sum +is equal to a given value x''' + +def countQuadruples(arr1, arr2, + arr3, arr4, + n, x): + count = 0 + ''' generate all pairs from + arr1[] and arr2[]''' + + for i in range(0, n): + for j in range(0, n): + ''' calculate the sum of + elements in the pair + so generated''' + + p_sum = arr1[i] + arr2[j] + ''' count pairs in the 3rd + and 4th array having + value 'x-p_sum' and then + accumulate it to 'count' ''' + count += int(countPairs(arr3, arr4, + n, x - p_sum)) + ''' required count of quadruples''' + + return count + '''Driver code''' + + ''' four sorted arrays each of size 'n' ''' + +arr1 = [1, 4, 5, 6] +arr2 = [2, 3, 7, 8] +arr3 = [1, 4, 6, 10] +arr4 = [2, 4, 7, 8] +n = len(arr1) +x = 30 +print(""Count = "", countQuadruples(arr1, arr2, + arr3, arr4, + n, x))" +Identical Linked Lists,"/*A recursive Java method to check if two linked +lists are identical or not*/ + +boolean areIdenticalRecur(Node a, Node b) +{ +/* If both lists are empty*/ + + if (a == null && b == null) + return true; + +/* If both lists are not empty, then data of + current nodes must match, and same should + be recursively true for rest of the nodes.*/ + + if (a != null && b != null) + return (a.data == b.data) && + areIdenticalRecur(a.next, b.next); + +/* If we reach here, then one of the lists + is empty and other is not*/ + + return false; +} + +/* Returns true if linked lists a and b are identical, + otherwise false */ + +boolean areIdentical(LinkedList listb) +{ + return areIdenticalRecur(this.head, listb.head); +} +"," '''A recursive Python3 function to check +if two linked lists are identical or not''' + +def areIdentical(a, b): + + ''' If both lists are empty''' + + if (a == None and b == None): + return True + + ''' If both lists are not empty, + then data of current nodes must match, + and same should be recursively true + for rest of the nodes.''' + + if (a != None and b != None): + return ((a.data == b.data) and + areIdentical(a.next, b.next)) + + ''' If we reach here, then one of the lists + is empty and other is not''' + + return False + + +" +Find Minimum Depth of a Binary Tree,"/* Java implementation to find minimum depth +of a given Binary tree */ + +/* Class containing left and right child of current +Node and key value*/ + +class Node { + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +public class MinimumTreeHeight { +/* Root of the Binary Tree*/ + + Node root; + int minimumDepth() { return minimumDepth(root, 0); } + /* Function to calculate the minimum depth of the tree + */ + + int minimumDepth(Node root, int level) + { + if (root == null) + return level; + level++; + return Math.min(minimumDepth(root.left, level), + minimumDepth(root.right, level)); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + MinimumTreeHeight tree = new MinimumTreeHeight(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println(""The minimum depth of "" + + ""binary tree is : "" + + tree.minimumDepth()); + } +}", +Count distinct elements in every window of size k,"/*Simple Java program to count distinct elements in every +window of size k*/ + +import java.util.Arrays; +class Test { +/* Counts distinct elements in window of size k*/ + + static int countWindowDistinct(int win[], int k) + { + int dist_count = 0; +/* Traverse the window*/ + + for (int i = 0; i < k; i++) { +/* Check if element arr[i] exists in arr[0..i-1]*/ + + int j; + for (j = 0; j < i; j++) + if (win[i] == win[j]) + break; + if (j == i) + dist_count++; + } + return dist_count; + } +/* Counts distinct elements in all windows of size k*/ + + static void countDistinct(int arr[], int n, int k) + { +/* Traverse through every window*/ + + for (int i = 0; i <= n - k; i++) + System.out.println(countWindowDistinct(Arrays.copyOfRange(arr, i, arr.length), k)); + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = { 1, 2, 1, 3, 4, 2, 3 }, k = 4; + countDistinct(arr, arr.length, k); + } +}"," '''Simple Python3 program to count distinct +elements in every window of size k''' + +import math as mt + '''Counts distinct elements in window +of size k''' + +def countWindowDistinct(win, k): + dist_count = 0 + ''' Traverse the window''' + + for i in range(k): + ''' Check if element arr[i] exists + in arr[0..i-1]''' + + j = 0 + while j < i: + if (win[i] == win[j]): + break + else: + j += 1 + if (j == i): + dist_count += 1 + return dist_count + '''Counts distinct elements in all +windows of size k''' + +def countDistinct(arr, n, k): + ''' Traverse through every window''' + + for i in range(n - k + 1): + print(countWindowDistinct(arr[i:k + i], k)) + '''Driver Code''' + +arr = [1, 2, 1, 3, 4, 2, 3] +k = 4 +n = len(arr) +countDistinct(arr, n, k)" +Smallest Derangement of Sequence,"/*Efficient Java program to find +smallest derangement.*/ + +class GFG +{ +static void generate_derangement(int N) +{ +/* Generate Sequence S*/ + + int S[] = new int[N + 1]; + for (int i = 1; i <= N; i++) + S[i] = i; +/* Generate Derangement*/ + + int D[] = new int[N + 1]; + for (int i = 1; i <= N; i += 2) + { + if (i == N) + { +/* Only if i is odd + Swap S[N-1] and S[N]*/ + + D[N] = S[N - 1]; + D[N - 1] = S[N]; + } + else + { + D[i] = i + 1; + D[i + 1] = i; + } + } +/* Print Derangement*/ + + for (int i = 1; i <= N; i++) + System.out.print(D[i] + "" ""); + System.out.println(); +} +/*Driver Program*/ + +public static void main(String[] args) +{ + generate_derangement(10); +} +}"," '''Efficient Python3 program to find +smallest derangement.''' + +def generate_derangement(N): + ''' Generate Sequence S''' + + S = [0] * (N + 1) + for i in range(1, N + 1): + S[i] = i + ''' Generate Derangement''' + + D = [0] * (N + 1) + for i in range(1, N + 1, 2): + if i == N: + ''' Only if i is odd + Swap S[N-1] and S[N]''' + + D[N] = S[N - 1] + D[N - 1] = S[N] + else: + D[i] = i + 1 + D[i + 1] = i + ''' Print Derangement''' + + for i in range(1, N + 1): + print(D[i], end = "" "") + print() + '''Driver Code''' + +if __name__ == '__main__': + generate_derangement(10)" +Segregate even and odd numbers | Set 3,"/*Java Implementation of the above approach*/ + +import java.io.*; +class GFG +{ +public static void arrayEvenAndOdd(int arr[], int n) +{ + int[] a; + a = new int[n]; + int ind = 0; + for (int i = 0; i < n; i++) + { + if (arr[i] % 2 == 0) + { + a[ind] = arr[i]; + ind++; + } + } + for (int i = 0; i < n; i++) + { + if (arr[i] % 2 != 0) + { + a[ind] = arr[i]; + ind++; + } + } + for (int i = 0; i < n; i++) + { + System.out.print(a[i] + "" ""); + } + System.out.println(""""); +} +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; + int n = arr.length; +/* Function call*/ + + arrayEvenAndOdd(arr, n); + } +}"," '''Python3 implementation of the above approach''' + +def arrayEvenAndOdd(arr, n): + ind = 0; + a = [0 for i in range(n)] + for i in range(n): + if (arr[i] % 2 == 0): + a[ind] = arr[i] + ind += 1 + for i in range(n): + if (arr[i] % 2 != 0): + a[ind] = arr[i] + ind += 1 + for i in range(n): + print(a[i], end = "" "") + print() + '''Driver code''' + +arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ] +n = len(arr) + '''Function call''' + +arrayEvenAndOdd(arr, n)" +Queries on XOR of greatest odd divisor of the range,"/*Java code Queries on XOR of +greatest odd divisor of the range*/ + +import java.io.*; + +class GFG +{ +/* Precompute the prefix XOR of greatest + odd divisor*/ + + static void prefixXOR(int arr[], int preXOR[], int n) + { +/* Finding the Greatest Odd divisor*/ + + for (int i = 0; i < n; i++) + { + while (arr[i] % 2 != 1) + arr[i] /= 2; + + preXOR[i] = arr[i]; + } + +/* Finding prefix XOR*/ + + for (int i = 1; i < n; i++) + preXOR[i] = preXOR[i - 1] ^ preXOR[i]; + } + +/* Return XOR of the range*/ + + static int query(int preXOR[], int l, int r) + { + if (l == 0) + return preXOR[r]; + else + return preXOR[r] ^ preXOR[l - 1]; + } + +/* Driven Program*/ + + public static void main (String[] args) + { + int arr[] = { 3, 4, 5 }; + int n = arr.length; + + int preXOR[] = new int[n]; + prefixXOR(arr, preXOR, n); + + System.out.println(query(preXOR, 0, 2)) ; + System.out.println (query(preXOR, 1, 2)); + + + } +} + + +"," '''Precompute the prefix XOR of greatest +odd divisor''' + +def prefixXOR(arr, preXOR, n): + + ''' Finding the Greatest Odd divisor''' + + for i in range(0, n, 1): + while (arr[i] % 2 != 1): + arr[i] = int(arr[i] / 2) + + preXOR[i] = arr[i] + + ''' Finding prefix XOR''' + + for i in range(1, n, 1): + preXOR[i] = preXOR[i - 1] ^ preXOR[i] + + '''Return XOR of the range''' + +def query(preXOR, l, r): + if (l == 0): + return preXOR[r] + else: + return preXOR[r] ^ preXOR[l - 1] + + '''Driver Code''' + +if __name__ == '__main__': + arr = [3, 4, 5] + n = len(arr) + + preXOR = [0 for i in range(n)] + prefixXOR(arr, preXOR, n) + + print(query(preXOR, 0, 2)) + print(query(preXOR, 1, 2)) + + +" +Convert an array to reduced form | Set 1 (Simple and Hashing),"/*Java Program to convert an Array +to reduced form*/ + +import java.util.*; +class GFG +{ + public static void convert(int arr[], int n) + { +/* Create a temp array and copy contents + of arr[] to temp*/ + + int temp[] = arr.clone(); +/* Sort temp array*/ + + Arrays.sort(temp); +/* Create a hash table.*/ + + HashMap umap = new HashMap<>(); +/* One by one insert elements of sorted + temp[] and assign them values from 0 + to n-1*/ + + int val = 0; + for (int i = 0; i < n; i++) + umap.put(temp[i], val++); +/* Convert array by taking positions from + umap*/ + + for (int i = 0; i < n; i++) + arr[i] = umap.get(arr[i]); + } + public static void printArr(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {10, 20, 15, 12, 11, 50}; + int n = arr.length; + System.out.println(""Given Array is ""); + printArr(arr, n); + convert(arr , n); + System.out.println(""\n\nConverted Array is ""); + printArr(arr, n); + } +}"," '''Python3 program to convert an array +in reduced form''' + +def convert(arr, n): + ''' Create a temp array and copy contents + of arr[] to temp''' + + temp = [arr[i] for i in range (n) ] + ''' Sort temp array''' + + temp.sort() + ''' create a map''' + + umap = {} + ''' One by one insert elements of sorted + temp[] and assign them values from 0 + to n-1''' + + val = 0 + for i in range (n): + umap[temp[i]] = val + val += 1 + ''' Convert array by taking positions from umap''' + + for i in range (n): + arr[i] = umap[arr[i]] +def printArr(arr, n): + for i in range(n): + print(arr[i], end = "" "") + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [10, 20, 15, 12, 11, 50] + n = len(arr) + print(""Given Array is "") + printArr(arr, n) + convert(arr , n) + print(""\n\nConverted Array is "") + printArr(arr, n)" +Count full nodes in a Binary tree (Iterative and Recursive),"/*Java program to count full nodes in a Binary Tree */ + +import java.util.*; +class GfG { +/*A binary tree Node has data, pointer to left +child and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +} +/*Function to get the count of full Nodes in +a binary tree */ + +static int getfullCount(Node root) +{ + if (root == null) + return 0; + int res = 0; + if (root.left != null && root.right != null) + res++; + res += (getfullCount(root.left) + getfullCount(root.right)); + return res; +} +/* Helper function that allocates a new +Node with the given data and NULL left +and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Driver program */ + +public static void main(String[] args) +{ + /* 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree as shown + */ + + Node root = newNode(2); + root.left = newNode(7); + root.right = newNode(5); + root.left.right = newNode(6); + root.left.right.left = newNode(1); + root.left.right.right = newNode(11); + root.right.right = newNode(9); + root.right.right.left = newNode(4); + System.out.println(getfullCount(root)); +} +}"," '''Python program to count full +nodes in a Binary Tree''' + + + '''A binary tree Node has data, pointer to left +child and a pointer to right child''' + +class newNode(): + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to get the count of +full Nodes in a binary tree ''' + +def getfullCount(root): + if (root == None): + return 0 + res = 0 + if (root.left and root.right): + res += 1 + res += (getfullCount(root.left) + + getfullCount(root.right)) + return res + '''Driver code ''' + +if __name__ == '__main__': + ''' 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree as shown + ''' + + root = newNode(2) + root.left = newNode(7) + root.right = newNode(5) + root.left.right = newNode(6) + root.left.right.left = newNode(1) + root.left.right.right = newNode(11) + root.right.right = newNode(9) + root.right.right.left = newNode(4) + print(getfullCount(root))" +Total number of non-decreasing numbers with n digits,"/*java program to count non-decreasing +numner with n digits*/ + +public class GFG { + static long countNonDecreasing(int n) + { + int N = 10; +/* Compute value of N * (N+1)/2 * + (N+2)/3 * ....* (N+n-1)/n*/ + + long count = 1; + for (int i = 1; i <= n; i++) + { + count *= (N + i - 1); + count /= i; + } + return count; + } +/* Driver code*/ + + public static void main(String args[]) { + int n = 3; + System.out.print(countNonDecreasing(n)); + } +}"," '''python program to count non-decreasing +numner with n digits''' + +def countNonDecreasing(n): + N = 10 + ''' Compute value of N*(N+1)/2*(N+2)/3 + * ....*(N+n-1)/n''' + + count = 1 + for i in range(1, n+1): + count = int(count * (N+i-1)) + count = int(count / i ) + return count + '''Driver program''' + +n = 3; +print(countNonDecreasing(n))" +Find zeroes to be flipped so that number of consecutive 1's is maximized,"/*Java to find positions of zeroes flipping which +produces maximum number of consecutive 1's*/ + +class Test +{ + static int arr[] = new int[]{1, 0, 0, 1, 1, 0, 1, 0, 1, 1}; + +/* m is maximum of number zeroes allowed to flip*/ + + static void findZeroes(int m) + { +/* Left and right indexes of current window*/ + + int wL = 0, wR = 0; + +/* Left index and size of the widest window*/ + + int bestL = 0, bestWindow = 0; + +/* Count of zeroes in current window*/ + + int zeroCount = 0; + +/* While right boundary of current window doesn't cross + right end*/ + + while (wR < arr.length) + { +/* If zero count of current window is less than m, + widen the window toward right*/ + + if (zeroCount <= m) + { + if (arr[wR] == 0) + zeroCount++; + wR++; + } + +/* If zero count of current window is more than m, + reduce the window from left*/ + + if (zeroCount > m) + { + if (arr[wL] == 0) + zeroCount--; + wL++; + } + +/* Update widest window if this window size is more*/ + + if ((wR-wL > bestWindow) && (zeroCount<=m)) + { + bestWindow = wR-wL; + bestL = wL; + } + } + +/* Print positions of zeroes in the widest window*/ + + for (int i=0; i m : + if arr[wL] == 0 : + zeroCount -= 1 + wL += 1 + + ''' Updqate widest window if + this window size is more''' + + if (wR-wL > bestWindow) and (zeroCount<=m) : + bestWindow = wR - wL + bestL = wL + + ''' Print positions of zeroes + in the widest window''' + + for i in range(0, bestWindow): + if arr[bestL + i] == 0: + print (bestL + i, end = "" "") + + '''Driver program''' + +arr = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1] +m = 2 +n = len(arr) +print (""Indexes of zeroes to be flipped are"", end = "" "") +findZeroes(arr, n, m) + + +" +Find number of pairs in an array such that their XOR is 0,"/*Java program to find number of pairs +in an array such that their XOR is 0*/ + +import java.util.*; +class GFG +{ +/* Function to calculate the answer*/ + + static int calculate(int a[], int n) + { +/* Finding the maximum of the array*/ + + int maximum = Arrays.stream(a).max().getAsInt(); +/* Creating frequency array + With initial value 0*/ + + int frequency[] = new int[maximum + 1]; +/* Traversing through the array*/ + + for (int i = 0; i < n; i++) + { +/* Counting frequency*/ + + frequency[a[i]] += 1; + } + int answer = 0; +/* Traversing through the frequency array*/ + + for (int i = 0; i < (maximum) + 1; i++) + { +/* Calculating answer*/ + + answer = answer + frequency[i] * (frequency[i] - 1); + } + return answer / 2; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = {1, 2, 1, 2, 4}; + int n = a.length; +/* Function calling*/ + + System.out.println(calculate(a, n)); + } +}"," '''Python3 program to find number of pairs +in an array such that their XOR is 0''' + + '''Function to calculate the answer''' + +def calculate(a) : ''' Finding the maximum of the array''' + + maximum = max(a) + ''' Creating frequency array + With initial value 0''' + + frequency = [0 for x in range(maximum + 1)] + ''' Traversing through the array''' + + for i in a : + ''' Counting frequency''' + + frequency[i] += 1 + answer = 0 + ''' Traversing through the frequency array''' + + for i in frequency : + ''' Calculating answer''' + + answer = answer + i * (i - 1) // 2 + return answer + '''Driver Code''' + +a = [1, 2, 1, 2, 4] + ''' Function calling''' + +print(calculate(a))" +Multistage Graph (Shortest Path),"/*Java program to find shortest distance +in a multistage graph.*/ + +class GFG +{ + static int N = 8; + static int INF = Integer.MAX_VALUE; +/* Returns shortest distance from 0 to + N-1.*/ + + public static int shortestDist(int[][] graph) + { +/* dist[i] is going to store shortest + distance from node i to node N-1.*/ + + int[] dist = new int[N]; + dist[N - 1] = 0; +/* Calculating shortest path for + rest of the nodes*/ + + for (int i = N - 2; i >= 0; i--) + { +/* Initialize distance from i to + destination (N-1)*/ + + dist[i] = INF; +/* Check all nodes of next stages + to find shortest distance from + i to N-1.*/ + + for (int j = i; j < N; j++) + { +/* Reject if no edge exists*/ + + if (graph[i][j] == INF) + { + continue; + } +/* We apply recursive equation to + distance to target through j. + and compare with minimum distance + so far.*/ + + dist[i] = Math.min(dist[i], graph[i][j] + + dist[j]); + } + } + return dist[0]; + } +/* Driver code*/ + + public static void main(String[] args) + { +/* Graph stored in the form of an + adjacency Matrix*/ + + int[][] graph = new int[][]{{INF, 1, 2, 5, INF, INF, INF, INF}, + {INF, INF, INF, INF, 4, 11, INF, INF}, + {INF, INF, INF, INF, 9, 5, 16, INF}, + {INF, INF, INF, INF, INF, INF, 2, INF}, + {INF, INF, INF, INF, INF, INF, INF, 18}, + {INF, INF, INF, INF, INF, INF, INF, 13}, + {INF, INF, INF, INF, INF, INF, INF, 2}}; + System.out.println(shortestDist(graph)); + } +}"," '''Python3 program to find shortest +distance in a multistage graph. + ''' '''Returns shortest distance from +0 to N-1.''' + +def shortestDist(graph): + global INF + ''' dist[i] is going to store shortest + distance from node i to node N-1.''' + + dist = [0] * N + dist[N - 1] = 0 + ''' Calculating shortest path + for rest of the nodes''' + + for i in range(N - 2, -1, -1): + ''' Initialize distance from + i to destination (N-1)''' + + dist[i] = INF + ''' Check all nodes of next stages + to find shortest distance from + i to N-1.''' + + for j in range(N): + ''' Reject if no edge exists''' + + if graph[i][j] == INF: + continue + ''' We apply recursive equation to + distance to target through j. + and compare with minimum + distance so far.''' + + dist[i] = min(dist[i], + graph[i][j] + dist[j]) + return dist[0] + '''Driver code''' + +N = 8 +INF = 999999999999 + '''Graph stored in the form of an +adjacency Matrix''' + +graph = [[INF, 1, 2, 5, INF, INF, INF, INF], + [INF, INF, INF, INF, 4, 11, INF, INF], + [INF, INF, INF, INF, 9, 5, 16, INF], + [INF, INF, INF, INF, INF, INF, 2, INF], + [INF, INF, INF, INF, INF, INF, INF, 18], + [INF, INF, INF, INF, INF, INF, INF, 13], + [INF, INF, INF, INF, INF, INF, INF, 2]] +print(shortestDist(graph))" +Find the repeating and the missing | Added 3 new methods,"/*Java program to Find the repeating +and missing elements*/ + + +import java.io.*; + +class GFG { + + static void printTwoElements(int arr[], int size) + { + int i; + System.out.print(""The repeating element is ""); + + for (i = 0; i < size; i++) { + int abs_val = Math.abs(arr[i]); + if (arr[abs_val - 1] > 0) + arr[abs_val - 1] = -arr[abs_val - 1]; + else + System.out.println(abs_val); + } + + System.out.print(""And the missing element is ""); + for (i = 0; i < size; i++) { + if (arr[i] > 0) + System.out.println(i + 1); + } + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 7, 3, 4, 5, 5, 6, 2 }; + int n = arr.length; + printTwoElements(arr, n); + } +} + + +"," '''Python3 code to Find the repeating +and the missing elements''' + + +def printTwoElements( arr, size): + for i in range(size): + if arr[abs(arr[i])-1] > 0: + arr[abs(arr[i])-1] = -arr[abs(arr[i])-1] + else: + print(""The repeating element is"", abs(arr[i])) + + for i in range(size): + if arr[i]>0: + print(""and the missing element is"", i + 1) + + '''Driver program to test above function */''' + +arr = [7, 3, 4, 5, 5, 6, 2] +n = len(arr) +printTwoElements(arr, n) + + +" +Unique cells in a binary matrix,"/*Efficient Java program to count unique +cells in a binary matrix*/ + +class GFG +{ +static int MAX = 100; +static int countUnique(int mat[][], int n, int m) +{ + int []rowsum = new int[n]; + int []colsum = new int[m]; +/* Count number of 1s in each row + and in each column*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (mat[i][j] != 0) + { + rowsum[i]++; + colsum[j]++; + } +/* Using above count arrays, find + cells*/ + + int uniquecount = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (mat[i][j] != 0 && + rowsum[i] == 1 && + colsum[j] == 1) + uniquecount++; + return uniquecount; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int mat[][] = {{0, 1, 0, 0}, + {0, 0, 1, 0}, + {1, 0, 0, 1}}; + System.out.print(countUnique(mat, 3, 4)); +} +}"," '''Efficient Python3 program to count unique +cells in a binary matrix''' + +MAX = 100; +def countUnique(mat, n, m): + rowsum = [0] * n; + colsum = [0] * m; + ''' Count number of 1s in each row + and in each column''' + + for i in range(n): + for j in range(m): + if (mat[i][j] != 0): + rowsum[i] += 1; + colsum[j] += 1; + ''' Using above count arrays, + find cells''' + + uniquecount = 0; + for i in range(n): + for j in range(m): + if (mat[i][j] != 0 and + rowsum[i] == 1 and + colsum[j] == 1): + uniquecount += 1; + return uniquecount; + '''Driver code''' + +if __name__ == '__main__': + mat = [[ 0, 1, 0, 0 ], + [ 0, 0, 1, 0 ], + [ 1, 0, 0, 1 ]]; + print(countUnique(mat, 3, 4));" +Magic Square | Even Order,"/*Java program to print Magic square +of Doubly even order*/ + +import java.io.*; +class GFG +{ +/* Function for calculating Magic square*/ + + static void doublyEven(int n) + { + int[][] arr = new int[n][n]; + int i, j; +/* filling matrix with its count value + starting from 1;*/ + + for ( i = 0; i < n; i++) + for ( j = 0; j < n; j++) + arr[i][j] = (n*i) + j + 1; +/* change value of Array elements + at fix location as per rule + (n*n+1)-arr[i][j] + Top Left corner of Matrix + (order (n/4)*(n/4))*/ + + for ( i = 0; i < n/4; i++) + for ( j = 0; j < n/4; j++) + arr[i][j] = (n*n + 1) - arr[i][j]; +/* Top Right corner of Matrix + (order (n/4)*(n/4))*/ + + for ( i = 0; i < n/4; i++) + for ( j = 3 * (n/4); j < n; j++) + arr[i][j] = (n*n + 1) - arr[i][j]; +/* Bottom Left corner of Matrix + (order (n/4)*(n/4))*/ + + for ( i = 3 * n/4; i < n; i++) + for ( j = 0; j < n/4; j++) + arr[i][j] = (n*n+1) - arr[i][j]; +/* Bottom Right corner of Matrix + (order (n/4)*(n/4))*/ + + for ( i = 3 * n/4; i < n; i++) + for ( j = 3 * n/4; j < n; j++) + arr[i][j] = (n*n + 1) - arr[i][j]; +/* Centre of Matrix (order (n/2)*(n/2))*/ + + for ( i = n/4; i < 3 * n/4; i++) + for ( j = n/4; j < 3 * n/4; j++) + arr[i][j] = (n*n + 1) - arr[i][j]; +/* Printing the magic-square*/ + + for (i = 0; i < n; i++) + { + for ( j = 0; j < n; j++) + System.out.print(arr[i][j]+"" ""); + System.out.println(); + } + } +/* driver program*/ + + public static void main (String[] args) + { + int n = 8; +/* Function call*/ + + doublyEven(n); + } +} +"," '''Python program to print magic square of double order''' + + '''Function for calculating Magic square''' + +def DoublyEven(n): ''' 2-D matrix with all entries as 0''' + + arr = [[(n*y)+x+1 for x in range(n)]for y in range(n)] + ''' Change value of array elements at fix location + as per the rule (n*n+1)-arr[i][[j] + Corners of order (n/4)*(n/4) + Top left corner''' + + for i in range(0,n/4): + for j in range(0,n/4): + arr[i][j] = (n*n + 1) - arr[i][j]; + ''' Top right corner''' + + for i in range(0,n/4): + for j in range(3 * (n/4),n): + arr[i][j] = (n*n + 1) - arr[i][j]; + ''' Bottom Left corner''' + + for i in range(3 * (n/4),n): + for j in range(0,n/4): + arr[i][j] = (n*n + 1) - arr[i][j]; + ''' Bottom Right corner''' + + for i in range(3 * (n/4),n): + for j in range(3 * (n/4),n): + arr[i][j] = (n*n + 1) - arr[i][j]; + ''' Centre of matrix,order (n/2)*(n/2)''' + + for i in range(n/4,3 * (n/4)): + for j in range(n/4,3 * (n/4)): + arr[i][j] = (n*n + 1) - arr[i][j]; + ''' Printing the square''' + + for i in range(n): + for j in range(n): + print '%2d ' %(arr[i][j]), + print + '''Driver Program''' + +n = 8 + + '''Function call''' + +DoublyEven(n)" +Print unique rows in a given boolean matrix,"/*Java code to print unique row in a +given binary matrix*/ + +import java.util.HashSet; +public class GFG { + public static void printArray(int arr[][], + int row,int col) + { + HashSet set = new HashSet(); + for(int i = 0; i < row; i++) + { + String s = """"; + for(int j = 0; j < col; j++) + s += String.valueOf(arr[i][j]); + if(!set.contains(s)) { + set.add(s); + System.out.println(s); + } + } + } +/* Driver code*/ + + public static void main(String[] args) { + int arr[][] = { {0, 1, 0, 0, 1}, + {1, 0, 1, 1, 0}, + {0, 1, 0, 0, 1}, + {1, 1, 1, 0, 0} }; + printArray(arr, 4, 5); + } +}"," '''Python3 code to print unique row in a +given binary matrix''' + +def printArray(matrix): + rowCount = len(matrix) + if rowCount == 0: + return + columnCount = len(matrix[0]) + if columnCount == 0: + return + row_output_format = "" "".join([""%s""] * columnCount) + printed = {} + for row in matrix: + routput = row_output_format % tuple(row) + if routput not in printed: + printed[routput] = True + print(routput) + '''Driver Code''' + +mat = [[0, 1, 0, 0, 1], + [1, 0, 1, 1, 0], + [0, 1, 0, 0, 1], + [1, 1, 1, 0, 0]] +printArray(mat)" +Lowest Common Ancestor for a Set of Nodes in a Rooted Tree,"/*Java Program to find the LCA +in a rooted tree for a given +set of nodes*/ + +import java.util.*; +class GFG +{ + +/*Set time 1 initially*/ + +static int T = 1; +static void dfs(int node, int parent, + Vector g[], + int level[], int t_in[], + int t_out[]) +{ + +/* Case for root node*/ + + if (parent == -1) + { + level[node] = 1; + } + else + { + level[node] = level[parent] + 1; + } + +/* In-time for node*/ + + t_in[node] = T; + for (int i : g[node]) + { + if (i != parent) + { + T++; + dfs(i, node, g, + level, t_in, t_out); + } + } + T++; + +/* Out-time for the node*/ + + t_out[node] = T; +} + +static int findLCA(int n, Vector g[], + Vector v) +{ + +/* level[i]-. Level of node i*/ + + int []level = new int[n + 1]; + +/* t_in[i]-. In-time of node i*/ + + int []t_in = new int[n + 1]; + +/* t_out[i]-. Out-time of node i*/ + + int []t_out = new int[n + 1]; + +/* Fill the level, in-time + and out-time of all nodes*/ + + dfs(1, -1, g, + level, t_in, t_out); + + int mint = Integer.MAX_VALUE, maxt = Integer.MIN_VALUE; + int minv = -1, maxv = -1; + for (int i =0; i maxt) + { + maxt = t_out[v.get(i)]; + maxv = v.get(i); + } + } + +/* Node with same minimum + and maximum out time + is LCA for the set*/ + + if (minv == maxv) + { + return minv; + } + +/* Take the minimum level as level of LCA*/ + + int lev = Math.min(level[minv], level[maxv]); + int node = 0, l = Integer.MIN_VALUE; + for (int i = 1; i <= n; i++) + { + +/* If i-th node is at a higher level + than that of the minimum among + the nodes of the given set*/ + + if (level[i] > lev) + continue; + +/* Compare in-time, out-time + and level of i-th node + to the respective extremes + among all nodes of the given set*/ + + if (t_in[i] <= mint + && t_out[i] >= maxt + && level[i] > l) + { + node = i; + l = level[i]; + } + } + + return node; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 10; + Vector []g = new Vector[n + 1]; + for (int i = 0; i < g.length; i++) + g[i] = new Vector(); + g[1].add(2); + g[2].add(1); + g[1].add(3); + g[3].add(1); + g[1].add(4); + g[4].add(1); + g[2].add(5); + g[5].add(2); + g[2].add(6); + g[6].add(2); + g[3].add(7); + g[7].add(3); + g[4].add(10); + g[10].add(4); + g[8].add(7); + g[7].add(8); + g[9].add(7); + g[7].add(9); + Vector v = new Vector<>(); + v.add(7); + v.add(3); + v.add(8); + System.out.print(findLCA(n, g, v) +""\n""); +} +} + + +"," '''Python Program to find the LCA +in a rooted tree for a given +set of nodes''' + +from typing import List +from sys import maxsize +INT_MAX = maxsize +INT_MIN = -maxsize + + '''Set time 1 initially''' + +T = 1 + +def dfs(node: int, parent: int, g: List[List[int]], level: List[int], + t_in: List[int], t_out: List[int]) -> None: + global T + + ''' Case for root node''' + + if (parent == -1): + level[node] = 1 + else: + level[node] = level[parent] + 1 + + ''' In-time for node''' + + t_in[node] = T + for i in g[node]: + if (i != parent): + T += 1 + dfs(i, node, g, level, t_in, t_out) + T += 1 + + ''' Out-time for the node''' + + t_out[node] = T + +def findLCA(n: int, g: List[List[int]], v: List[int]) -> int: + + ''' level[i]--> Level of node i''' + + level = [0 for _ in range(n + 1)] + + ''' t_in[i]--> In-time of node i''' + + t_in = [0 for _ in range(n + 1)] + + ''' t_out[i]--> Out-time of node i''' + + t_out = [0 for _ in range(n + 1)] + + ''' Fill the level, in-time + and out-time of all nodes''' + + dfs(1, -1, g, level, t_in, t_out) + mint = INT_MAX + maxt = INT_MIN + minv = -1 + maxv = -1 + for i in v: + + ''' To find minimum in-time among + all nodes in LCA set''' + + if (t_in[i] < mint): + mint = t_in[i] + minv = i + + ''' To find maximum in-time among + all nodes in LCA set''' + + if (t_out[i] > maxt): + maxt = t_out[i] + maxv = i + + ''' Node with same minimum + and maximum out time + is LCA for the set''' + + if (minv == maxv): + return minv + + ''' Take the minimum level as level of LCA''' + + lev = min(level[minv], level[maxv]) + node = 0 + l = INT_MIN + for i in range(n): + + ''' If i-th node is at a higher level + than that of the minimum among + the nodes of the given set''' + + if (level[i] > lev): + continue + + ''' Compare in-time, out-time + and level of i-th node + to the respective extremes + among all nodes of the given set''' + + if (t_in[i] <= mint and t_out[i] >= maxt and level[i] > l): + node = i + l = level[i] + return node + + '''Driver code''' + +if __name__ == ""__main__"": + n = 10 + g = [[] for _ in range(n + 1)] + g[1].append(2) + g[2].append(1) + g[1].append(3) + g[3].append(1) + g[1].append(4) + g[4].append(1) + g[2].append(5) + g[5].append(2) + g[2].append(6) + g[6].append(2) + g[3].append(7) + g[7].append(3) + g[4].append(10) + g[10].append(4) + g[8].append(7) + g[7].append(8) + g[9].append(7) + g[7].append(9) + + v = [7, 3, 8] + print(findLCA(n, g, v)) + + +" +Count total set bits in all numbers from 1 to n,"static int getSetBitsFromOneToN(int N){ + int two = 2,ans = 0; + int n = N; + while(n != 0) + { + ans += (N / two)*(two >> 1); + if((N&(two - 1)) > (two >> 1) - 1) + ans += (N&(two - 1)) - (two >> 1) + 1; + two <<= 1; + n >>= 1; + } + return ans; +}","def getSetBitsFromOneToN(N): + two = 2 + ans = 0 + n = N + while(n != 0): + ans += int(N / two) * (two >> 1) + if((N & (two - 1)) > (two >> 1) - 1): + ans += (N&(two - 1)) - (two >> 1) + 1 + two <<= 1; + n >>= 1; + return ans" +Maximum and minimum of an array using minimum number of comparisons,"/*Java program of above implementation*/ + +public class GFG { +/* Class Pair is used to return two values from getMinMax() */ + + static class Pair { + int min; + int max; + } + static Pair getMinMax(int arr[], int n) { + Pair minmax = new Pair(); + int i; + /*If there is only one element then return it as min and max both*/ + + if (n == 1) { + minmax.max = arr[0]; + minmax.min = arr[0]; + return minmax; + } + /* If there are more than one elements, then initialize min + and max*/ + + if (arr[0] > arr[1]) { + minmax.max = arr[0]; + minmax.min = arr[1]; + } else { + minmax.max = arr[1]; + minmax.min = arr[0]; + } + for (i = 2; i < n; i++) { + if (arr[i] > minmax.max) { + minmax.max = arr[i]; + } else if (arr[i] < minmax.min) { + minmax.min = arr[i]; + } + } + return minmax; + } + /* Driver program to test above function */ + + public static void main(String args[]) { + int arr[] = {1000, 11, 445, 1, 330, 3000}; + int arr_size = 6; + Pair minmax = getMinMax(arr, arr_size); + System.out.printf(""\nMinimum element is %d"", minmax.min); + System.out.printf(""\nMaximum element is %d"", minmax.max); + } +}"," '''Python program of above implementation''' + '''structure is used to return two values from minMax()''' + +class pair: + def __init__(self): + self.min = 0 + self.max = 0 +def getMinMax(arr: list, n: int) -> pair: + minmax = pair() + ''' If there is only one element then return it as min and max both''' + + if n == 1: + minmax.max = arr[0] + minmax.min = arr[0] + return minmax + ''' If there are more than one elements, then initialize min + and max''' + + if arr[0] > arr[1]: + minmax.max = arr[0] + minmax.min = arr[1] + else: + minmax.max = arr[1] + minmax.min = arr[0] + for i in range(2, n): + if arr[i] > minmax.max: + minmax.max = arr[i] + elif arr[i] < minmax.min: + minmax.min = arr[i] + return minmax + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1000, 11, 445, 1, 330, 3000] + arr_size = 6 + minmax = getMinMax(arr, arr_size) + print(""Minimum element is"", minmax.min) + print(""Maximum element is"", minmax.max)" +Connect n ropes with minimum cost,"/*Java program to connect n +ropes with minimum cost*/ + +/*A class for Min Heap*/ + +class MinHeap { +/*Array of elements in heap*/ + +int[] harr; +/*Current number of elements in min heap*/ + +int heap_size; +/*maximum possible size of min heap*/ + +int capacity; +/* Constructor: Builds a heap from + a given array a[] of given size*/ + + public MinHeap(int a[], int size) + { + heap_size = size; + capacity = size; + harr = a; + int i = (heap_size - 1) / 2; + while (i >= 0) { + MinHeapify(i); + i--; + } + } +/* A recursive method to heapify a subtree + with the root at given index + This method assumes that the subtrees + are already heapified*/ + + void MinHeapify(int i) + { + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) { + swap(i, smallest); + MinHeapify(smallest); + } + } + int parent(int i) { return (i - 1) / 2; } +/* to get index of left child of node at index i*/ + + int left(int i) { return (2 * i + 1); } +/* to get index of right child of node at index i*/ + + int right(int i) { return (2 * i + 2); } +/* Method to remove minimum element (or root) from min heap*/ + + int extractMin() + { + if (heap_size <= 0) + return Integer.MAX_VALUE; + if (heap_size == 1) { + heap_size--; + return harr[0]; + } +/* Store the minimum value, and remove it from heap*/ + + int root = harr[0]; + harr[0] = harr[heap_size - 1]; + heap_size--; + MinHeapify(0); + return root; + } +/* Inserts a new key 'k'*/ + + void insertKey(int k) + { + if (heap_size == capacity) { + System.out.println(""Overflow: Could not insertKey""); + return; + } +/* First insert the new key at the end*/ + + heap_size++; + int i = heap_size - 1; + harr[i] = k; +/* Fix the min heap property if it is violated*/ + + while (i != 0 && harr[parent(i)] > harr[i]) { + swap(i, parent(i)); + i = parent(i); + } + } +/* A utility function to check + if size of heap is 1 or not*/ + + boolean isSizeOne() + { + return (heap_size == 1); + } +/* A utility function to swap two elements*/ + + void swap(int x, int y) + { + int temp = harr[x]; + harr[x] = harr[y]; + harr[y] = temp; + } +/* The main function that returns the + minimum cost to connect n ropes of + lengths stored in len[0..n-1]*/ + + static int minCost(int len[], int n) + { +/*Initialize result*/ + +int cost = 0; +/* Create a min heap of capacity equal + to n and put all ropes in it*/ + + MinHeap minHeap = new MinHeap(len, n); +/* Iterate while size of heap doesn't become 1*/ + + while (!minHeap.isSizeOne()) { +/* Extract two minimum length ropes from min heap*/ + + int min = minHeap.extractMin(); + int sec_min = minHeap.extractMin(); +/*Update total cost*/ + +cost += (min + sec_min); +/* Insert a new rope in min heap with length equal to sum + of two extracted minimum lengths*/ + + minHeap.insertKey(min + sec_min); + } +/* Finally return total minimum + cost for connecting all ropes*/ + + return cost; + } +/* Driver code*/ + + public static void main(String args[]) + { + int len[] = { 4, 3, 2, 6 }; + int size = len.length; + System.out.println(""Total cost for connecting ropes is "" + minCost(len, size)); + } +};", +Min Cost Path | DP-6,"/*Java program for the +above approach*/ + +import java.util.*; +class GFG{ +static int row = 3; +static int col = 3; +static int minCost(int cost[][]) +{ +/* for 1st column*/ + + for (int i = 1; i < row; i++) + { + cost[i][0] += cost[i - 1][0]; + } +/* for 1st row*/ + + for (int j = 1; j < col; j++) + { + cost[0][j] += cost[0][j - 1]; + } +/* for rest of the 2d matrix*/ + + for (int i = 1; i < row; i++) + { + for (int j = 1; j < col; j++) + { + cost[i][j] += Math.min(cost[i - 1][j - 1], + Math.min(cost[i - 1][j], + cost[i][j - 1])); + } + } +/* Returning the value in + last cell*/ + + return cost[row - 1][col - 1]; +} +/*Driver code */ + +public static void main(String[] args) +{ + int cost[][] = {{1, 2, 3}, + {4, 8, 2}, + {1, 5, 3} }; + System.out.print(minCost(cost) + ""\n""); +} +}"," '''Python3 program for the +above approach''' + +def minCost(cost, row, col): ''' For 1st column''' + + for i in range(1, row): + cost[i][0] += cost[i - 1][0] + ''' For 1st row''' + + for j in range(1, col): + cost[0][j] += cost[0][j - 1] + ''' For rest of the 2d matrix''' + + for i in range(1, row): + for j in range(1, col): + cost[i][j] += (min(cost[i - 1][j - 1], + min(cost[i - 1][j], + cost[i][j - 1]))) + ''' Returning the value in + last cell''' + + return cost[row - 1][col - 1] + '''Driver code''' + +if __name__ == '__main__': + row = 3 + col = 3 + cost = [ [ 1, 2, 3 ], + [ 4, 8, 2 ], + [ 1, 5, 3 ] ] + print(minCost(cost, row, col));" +"Given 1's, 2's, 3's ......k's print them in zig zag way.","/*Java program to print given +number of 1's, 2's, 3's ....k's +in zig-zag way.*/ + +import java.util.*; +import java.lang.*; +public class GfG{ +/* function that prints given number of 1's, + 2's, 3's ....k's in zig-zag way.*/ + + public static void ZigZag(int rows, + int columns, + int numbers[]) + { + int k = 0; +/* two-dimensional array to store numbers.*/ + + int[][] arr = new int[rows][columns]; + for (int i=0; i0; j++) + { +/* storing element.*/ + + arr[i][j] = k+1; +/* decrement element at + kth index.*/ + + numbers[k]--; +/* if array contains zero + then increment index to + make this next index*/ + + if (numbers[k] == 0) + k++; + } + } +/* for odd row.*/ + + else + { +/* for each column.*/ + + for (int j=columns-1; j>=0 && + numbers[k]>0; j--) + { +/* storing element.*/ + + arr[i][j] = k+1; +/* decrement element + at kth index.*/ + + numbers[k]--; +/* if array contains zero then + increment index to make this + next index.*/ + + if (numbers[k]==0) + k++; + } + } + } +/* printing the stored elements.*/ + + for (int i=0;i 0: + ''' storing element.''' + + arr[i][j] = k + 1 + ''' decrement element at + kth index.''' + + numbers[k] -= 1 + ''' if array contains zero + then increment index to + make this next index''' + + if numbers[k] == 0: + k += 1 + j += 1 + ''' for odd row.''' + + else: + ''' for each column.''' + + j = columns-1 + while j>=0 and numbers[k]>0: + ''' storing element.''' + + arr[i][j] = k+1 + ''' decrement element + at kth index.''' + + numbers[k] -= 1 + ''' if array contains zero then + increment index to make this + next index.''' + + if numbers[k] == 0: + k += 1 + j -= 1 + ''' printing the stored elements.''' + + for i in arr: + for j in i: + print(j, end ="" "") + print() + '''Driver code''' + +rows = 4; +columns = 5; +Numbers = [3, 4, 2, 2, 3, 1, 5] +ZigZag(rows, columns, Numbers)" +Check if array contains contiguous integers with duplicates allowed,"/*Sorting based Java implementation +to check whether the array +contains a set of contiguous +integers*/ + +import java.util.*; +class GFG { +/* function to check whether + the array contains a set + of contiguous integers*/ + + static boolean areElementsContiguous(int arr[], + int n) + { +/* Sort the array*/ + + Arrays.sort(arr); +/* After sorting, check if + current element is either + same as previous or is + one more.*/ + + for (int i = 1; i < n; i++) + if (arr[i] - arr[i-1] > 1) + return false; + return true; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = { 5, 2, 3, 6, + 4, 4, 6, 6 }; + int n = arr.length; + if (areElementsContiguous(arr, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Sorting based Python implementation +to check whether the array +contains a set of contiguous integers''' + + + ''' function to check whether + the array contains a set + of contiguous integers''' + +def areElementsContiguous(arr, n): ''' Sort the array''' + + arr.sort() + ''' After sorting, check if + current element is either + same as previous or is + one more.''' + + for i in range(1,n): + if (arr[i] - arr[i-1] > 1) : + return 0 + return 1 + '''Driver code''' + +arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ] +n = len(arr) +if areElementsContiguous(arr, n): print(""Yes"") +else: print(""No"")" +Modify a binary tree to get preorder traversal using right pointers only,"/*Java code to modify binary tree for +traversal using only right pointer */ + +class GFG +{ +/*A binary tree node has data, +left child and right child */ + +static class Node +{ + int data; + Node left; + Node right; +}; +/*function that allocates a new node +with the given data and null left +and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Function to modify tree */ + +static Node modifytree( Node root) +{ + Node right = root.right; + Node rightMost = root; +/* if the left tree exists */ + + if (root.left != null) + { +/* get the right-most of the + original left subtree */ + + rightMost = modifytree(root.left); +/* set root right to left subtree */ + + root.right = root.left; + root.left = null; + } +/* if the right subtree does + not exists we are done! */ + + if (right == null) + return rightMost; +/* set right pointer of right-most + of the original left subtree */ + + rightMost.right = right; +/* modify the rightsubtree */ + + rightMost = modifytree(right); + return rightMost; +} +/*printing using right pointer only */ + +static void printpre( Node root) +{ + while (root != null) + { + System.out.print( root.data + "" ""); + root = root.right; + } +} +/*Driver cde */ + +public static void main(String args[]) +{ + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 5 */ + + Node root = newNode(10); + root.left = newNode(8); + root.right = newNode(2); + root.left.left = newNode(3); + root.left.right = newNode(5); + modifytree(root); + printpre(root); +} +}"," '''Python code to modify binary tree for +traversal using only right pointer ''' + + + '''A binary tree node has data, +left child and right child''' + +class newNode(): + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Function to modify tree ''' + +def modifytree(root): + right = root.right + rightMost = root + ''' if the left tree exists ''' + + if (root.left): + ''' get the right-most of the + original left subtree ''' + + rightMost = modifytree(root.left) + ''' set root right to left subtree ''' + + root.right = root.left + root.left = None + ''' if the right subtree does + not exists we are done! ''' + + if (not right): + return rightMost + ''' set right pointer of right-most + of the original left subtree ''' + + rightMost.right = right + ''' modify the rightsubtree ''' + + rightMost = modifytree(right) + return rightMost + '''printing using right pointer only ''' + +def printpre(root): + while (root != None): + print(root.data,end="" "") + root = root.right + '''Driver code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 5 ''' + + root = newNode(10) + root.left = newNode(8) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + modifytree(root) + printpre(root)" +Rotate matrix by 45 degrees,"/*Java program for +the above approach*/ + +import java.util.*; +class GFG{ + +/*Function to rotate +matrix by 45 degree*/ + +static void matrix(int n, int m, + int [][]li) +{ +/* Counter Variable*/ + + int ctr = 0; + + while (ctr < 2 * n - 1) + { + for(int i = 0; i < Math.abs(n - ctr - 1); + i++) + { + System.out.print("" ""); + } + + Vector lst = new Vector(); + +/* Iterate [0, m]*/ + + for(int i = 0; i < m; i++) + { +/* Iterate [0, n]*/ + + for(int j = 0; j < n; j++) + { +/* Diagonal Elements + Condition*/ + + if (i + j == ctr) + { +/* Appending the + Diagonal Elements*/ + + lst.add(li[i][j]); + } + } + } + +/* Printing reversed Diagonal + Elements*/ + + for(int i = lst.size() - 1; i >= 0; i--) + { + System.out.print(lst.get(i) + "" ""); + } + + System.out.println(); + ctr += 1; + } +} + +/*Driver code */ + +public static void main(String[] args) +{ +/* Dimensions of Matrix*/ + + int n = 8; + int m = n; + +/* Given matrix*/ + + 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}}; + +/* Function call*/ + + matrix(n, m, li); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Function to rotate matrix by 45 degree''' + + + +def matrix(n, m, li): + + ''' Counter Variable''' + + ctr = 0 + while(ctr < 2 * n-1): + print("" ""*abs(n-ctr-1), end ="""") + lst = [] + + ''' Iterate [0, m]''' + + for i in range(m): + + ''' Iterate [0, n]''' + + for j in range(n): + + ''' Diagonal Elements + Condition''' + + if i + j == ctr: + + ''' Appending the + Diagonal Elements''' + + lst.append(li[i][j]) + + ''' Printing reversed Diagonal + Elements''' + + lst.reverse() + print(*lst) + ctr += 1 + + + '''Driver Code''' + + + '''Dimensions of Matrix''' + +n = 8 +m = n + + '''Given matrix''' + +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]] + + '''Function Call''' + +matrix(n, m, li) +" +Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String,"/*Java program for the above approach*/ + +import java.util.*; + +class GFG{ + +/*Function to find the maximum sum of +consecutive 0s present at the start +and end of a string present in any +of the rotations of the given string*/ + +static void findMaximumZeros(String str, int n) +{ + +/* Check if all the characters + in the string are 0*/ + + int c0 = 0; + +/* Iterate over characters + of the string*/ + + for(int i = 0; i < n; ++i) + { + if (str.charAt(i) == '0') + c0++; + } + +/* If the frequency of '1' is 0*/ + + if (c0 == n) + { + +/* Print n as the result*/ + + System.out.print(n); + return; + } + +/* Concatenate the string + with itself*/ + + String s = str + str; + +/* Stores the required result*/ + + int mx = 0; + +/* Generate all rotations of the string*/ + + for(int i = 0; i < n; ++i) + { + +/* Store the number of consecutive 0s + at the start and end of the string*/ + + int cs = 0; + int ce = 0; + +/* Count 0s present at the start*/ + + for(int j = i; j < i + n; ++j) + { + if (s.charAt(j) == '0') + cs++; + else + break; + } + +/* Count 0s present at the end*/ + + for(int j = i + n - 1; j >= i; --j) + { + if (s.charAt(j) == '0') + ce++; + else + break; + } + +/* Calculate the sum*/ + + int val = cs + ce; + +/* Update the overall + maximum sum*/ + + mx = Math.max(val, mx); + } + +/* Print the result*/ + + System.out.print(mx); +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + +/* Given string*/ + + String s = ""1001""; + +/* Store the size of the string*/ + + int n = s.length(); + + findMaximumZeros(s, n); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Function to find the maximum sum of +consecutive 0s present at the start +and end of a string present in any +of the rotations of the given string''' + +def findMaximumZeros(st, n): + + ''' Check if all the characters + in the string are 0''' + + c0 = 0 + + ''' Iterate over characters + of the string''' + + for i in range(n): + if (st[i] == '0'): + c0 += 1 + + ''' If the frequency of '1' is 0''' + + if (c0 == n): + + ''' Print n as the result''' + + print(n) + return + + ''' Concatenate the string + with itself''' + + s = st + st + + ''' Stores the required result''' + + mx = 0 + + ''' Generate all rotations of the string''' + + for i in range(n): + + ''' Store the number of consecutive 0s + at the start and end of the string''' + + cs = 0 + ce = 0 + + ''' Count 0s present at the start''' + + for j in range(i, i + n): + if (s[j] == '0'): + cs += 1 + else: + break + + ''' Count 0s present at the end''' + + for j in range(i + n - 1, i - 1, -1): + if (s[j] == '0'): + ce += 1 + else: + break + + ''' Calculate the sum''' + + val = cs + ce + + ''' Update the overall + maximum sum''' + + mx = max(val, mx) + + ''' Print the result''' + + print(mx) + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Given string''' + + s = ""1001"" + + ''' Store the size of the string''' + + n = len(s) + + findMaximumZeros(s, n) + + +" +Find a common element in all rows of a given row-wise sorted matrix,"/*Java implementation of the approach*/ + +import java.util.*; +class GFG +{ +/*Specify number of rows and columns*/ + +static int M = 4; +static int N = 5; +/*Returns common element in all rows of mat[M][N]. +If there is no common element, then -1 is returned*/ + +static int findCommon(int mat[][]) +{ +/* A hash map to store count of elements*/ + + HashMap cnt = new HashMap(); + int i, j; + for (i = 0; i < M; i++) + { +/* Increment the count of first + element of the row*/ + + if(cnt.containsKey(mat[i][0])) + { + cnt.put(mat[i][0], + cnt.get(mat[i][0]) + 1); + } + else + { + cnt.put(mat[i][0], 1); + } +/* Starting from the second element + of the current row*/ + + for (j = 1; j < N; j++) + { +/* If current element is different from + the previous element i.e. it is appearing + for the first time in the current row*/ + + if (mat[i][j] != mat[i][j - 1]) + if(cnt.containsKey(mat[i][j])) + { + cnt.put(mat[i][j], + cnt.get(mat[i][j]) + 1); + } + else + { + cnt.put(mat[i][j], 1); + } + } + } +/* Find element having count + equal to number of rows*/ + + for (Map.Entry ele : cnt.entrySet()) + { + if (ele.getValue() == M) + return ele.getKey(); + } +/* No such element found*/ + + return -1; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int mat[][] = {{ 1, 2, 3, 4, 5 }, + { 2, 4, 5, 8, 10 }, + { 3, 5, 7, 9, 11 }, + { 1, 3, 5, 7, 9 }}; + int result = findCommon(mat); + if (result == -1) + System.out.println(""No common element""); + else + System.out.println(""Common element is "" + result); + } +}"," '''Python3 implementation of the approach''' + +from collections import defaultdict + '''Specify number of rows and columns''' + +M = 4 +N = 5 + '''Returns common element in all rows of +mat[M][N]. If there is no +common element, then -1 is returned''' + +def findCommon(mat): + global M + global N + ''' A hash map to store count of elements''' + + cnt = dict() + cnt = defaultdict(lambda: 0, cnt) + i = 0 + j = 0 + while (i < M ): + ''' Increment the count of first + element of the row''' + + cnt[mat[i][0]] = cnt[mat[i][0]] + 1 + j = 1 + ''' Starting from the second element + of the current row''' + + while (j < N ) : + ''' If current element is different from + the previous element i.e. it is appearing + for the first time in the current row''' + + if (mat[i][j] != mat[i][j - 1]): + cnt[mat[i][j]] = cnt[mat[i][j]] + 1 + j = j + 1 + i = i + 1 + ''' Find element having count equal to number of rows''' + + for ele in cnt: + if (cnt[ele] == M): + return ele + ''' No such element found''' + + return -1 + '''Driver Code''' + +mat = [[1, 2, 3, 4, 5 ], + [2, 4, 5, 8, 10], + [3, 5, 7, 9, 11], + [1, 3, 5, 7, 9 ],] +result = findCommon(mat) +if (result == -1): + print(""No common element"") +else: + print(""Common element is "", result)" +Convert Ternary Expression to a Binary Tree,"/*Java program to convert a ternary +expreesion to a tree.*/ + +import java.util.Queue; +import java.util.LinkedList; +/*Class to represent Tree node */ + +class Node +{ + char data; + Node left, right; + public Node(char item) + { + data = item; + left = null; + right = null; + } +} +/*Class to convert a ternary expression to a Tree */ + +class BinaryTree +{ +/* Function to convert Ternary Expression to a Binary + Tree. It return the root of tree*/ + + Node convertExpression(char[] expression, int i) + { +/* Base case*/ + + if (i >= expression.length) + return null; +/* store current character of expression_string + [ 'a' to 'z']*/ + + Node root = new Node(expression[i]); +/* Move ahead in str*/ + + ++i; +/* if current character of ternary expression is '?' + then we add next character as a left child of + current node*/ + + if (i < expression.length && expression[i]=='?') + root.left = convertExpression(expression, i+1); +/* else we have to add it as a right child of + current node expression.at(0) == ':'*/ + + else if (i < expression.length) + root.right = convertExpression(expression, i+1); + return root; + } +/* function print tree*/ + + public void printTree( Node root) + { + if (root == null) + return; + System.out.print(root.data +"" ""); + printTree(root.left); + printTree(root.right); + } +/*Driver program to test above function*/ + + public static void main(String args[]) + { + String exp = ""a?b?c:d:e""; + BinaryTree tree = new BinaryTree(); + char[] expression=exp.toCharArray(); + Node root = tree.convertExpression(expression, 0); + tree.printTree(root) ; + } +}"," '''Class to define a node +structure of the tree''' + +class Node: + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''Function to convert ternary +expression to a Binary tree +It returns the root node +of the tree''' + +def convert_expression(expression, i): + + ''' Base case ''' + + if i >= len(expression): + return None ''' Create a new node object + for the expression at + ith index''' + + root = Node(expression[i]) + + ''' Move ahead in str''' + + i += 1 ''' if current character of + ternary expression is '?' + then we add next character + as a left child of + current node''' + + if (i < len(expression) and expression[i]==""?""): + root.left = convert_expression(expression, i + 1) + ''' else we have to add it + as a right child of + current node expression[0] == ':''' + ''' + elif i < len(expression): + root.right = convert_expression(expression, i + 1) + return root + '''Function to print the tree +in a pre-order traversal pattern''' + +def print_tree(root): + if not root: + return + print(root.data, end=' ') + print_tree(root.left) + print_tree(root.right) + '''Driver Code''' + +if __name__ == ""__main__"": + string_expression = ""a?b?c:d:e"" + root_node = convert_expression(string_expression, 0) + print_tree(root_node)" +"Sort an array of 0s, 1s and 2s","/*Java implementation of the approach*/ + +import java.io.*; +class GFG { +/* Utility function to print the contents of an array*/ + + static void printArr(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Function to sort the array of 0s, 1s and 2s*/ + + static void sortArr(int arr[], int n) + { + int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; +/* Count the number of 0s, 1s and 2s in the array*/ + + for (i = 0; i < n; i++) { + switch (arr[i]) { + case 0: + cnt0++; + break; + case 1: + cnt1++; + break; + case 2: + cnt2++; + break; + } + } +/* Update the array*/ + + i = 0; +/* Store all the 0s in the beginning*/ + + while (cnt0 > 0) { + arr[i++] = 0; + cnt0--; + } +/* Then all the 1s*/ + + while (cnt1 > 0) { + arr[i++] = 1; + cnt1--; + } +/* Finally all the 2s*/ + + while (cnt2 > 0) { + arr[i++] = 2; + cnt2--; + } +/* Print the sorted array*/ + + printArr(arr, n); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; + int n = arr.length; + sortArr(arr, n); + } +}"," '''Python implementation of the approach + ''' '''Utility function to print contents of an array''' + +def printArr(arr, n): + for i in range(n): + print(arr[i],end="" "") + '''Function to sort the array of 0s, 1s and 2s''' + +def sortArr(arr, n): + cnt0 = 0 + cnt1 = 0 + cnt2 = 0 + ''' Count the number of 0s, 1s and 2s in the array''' + + for i in range(n): + if arr[i] == 0: + cnt0+=1 + elif arr[i] == 1: + cnt1+=1 + elif arr[i] == 2: + cnt2+=1 + ''' Update the array''' + + i = 0 + ''' Store all the 0s in the beginning''' + + while (cnt0 > 0): + arr[i] = 0 + i+=1 + cnt0-=1 + ''' Then all the 1s''' + + while (cnt1 > 0): + arr[i] = 1 + i+=1 + cnt1-=1 + ''' Finally all the 2s''' + + while (cnt2 > 0): + arr[i] = 2 + i+=1 + cnt2-=1 + ''' Prthe sorted array''' + + printArr(arr, n) + '''Driver code''' + +arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] +n = len(arr) +sortArr(arr, n)" +Find number of transformation to make two Matrix Equal,"/*Java program to find number of +countOpsation to make two matrix +equals*/ + +import java.io.*; +class GFG +{ + static int countOps(int A[][], int B[][], + int m, int n) + { +/* Update matrix A[][] so that only + A[][] has to be countOpsed*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + A[i][j] -= B[i][j]; +/* Check necessary condition for + condition for existence of full + countOpsation*/ + + for (int i = 1; i < n; i++) + for (int j = 1; j < m; j++) + if (A[i][j] - A[i][0] - + A[0][j] + A[0][0] != 0) + return -1; +/* If countOpsation is possible + calculate total countOpsation*/ + + int result = 0; + for (int i = 0; i < n; i++) + result += Math.abs(A[i][0]); + for (int j = 0; j < m; j++) + result += Math.abs(A[0][j] - A[0][0]); + return (result); + } +/* Driver code*/ + + public static void main (String[] args) + { + int A[][] = { {1, 1, 1}, + {1, 1, 1}, + {1, 1, 1} }; + int B[][] = { {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} }; + System.out.println(countOps(A, B, 3, 3)) ; + } +}"," '''Python3 program to find number of +countOpsation to make two matrix +equals''' + +def countOps(A, B, m, n): + ''' Update matrix A[][] so that only + A[][] has to be countOpsed''' + + for i in range(n): + for j in range(m): + A[i][j] -= B[i][j]; + ''' Check necessary condition for + condition for existence of full + countOpsation''' + + for i in range(1, n): + for j in range(1, n): + if (A[i][j] - A[i][0] - + A[0][j] + A[0][0] != 0): + return -1; + ''' If countOpsation is possible + calculate total countOpsation''' + + result = 0; + for i in range(n): + result += abs(A[i][0]); + for j in range(m): + result += abs(A[0][j] - A[0][0]); + return (result); + '''Driver code''' + +if __name__ == '__main__': + A = [[1, 1, 1], + [1, 1, 1], + [1, 1, 1]]; + B = [[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]; + print(countOps(A, B, 3, 3));" +Binary Indexed Tree : Range Updates and Point Queries,"/*Java program to demonstrate Range Update +and Point Queries Without using BIT */ + +class GfG { +/*Updates such that getElement() gets an increased +value when queried from l to r. */ + +static void update(int arr[], int l, int r, int val) +{ + arr[l] += val; + if(r + 1 < arr.length) + arr[r+1] -= val; +} +/*Get the element indexed at i */ + +static int getElement(int arr[], int i) +{ +/* To get ith element sum of all the elements + from 0 to i need to be computed */ + + int res = 0; + for (int j = 0 ; j <= i; j++) + res += arr[j]; + return res; +} +/*Driver program to test above function */ + +public static void main(String[] args) +{ + int arr[] = {0, 0, 0, 0, 0}; + int n = arr.length; + int l = 2, r = 4, val = 2; + update(arr, l, r, val); +/* Find the element at Index 4 */ + + int index = 4; + System.out.println(""Element at index "" + index + "" is "" +getElement(arr, index)); + l = 0; + r = 3; + val = 4; + update(arr,l,r,val); +/* Find the element at Index 3 */ + + index = 3; + System.out.println(""Element at index "" + index + "" is "" +getElement(arr, index)); +} +}"," '''Python3 program to demonstrate Range +Update and PoQueries Without using BIT ''' + + '''Updates such that getElement() gets an +increased value when queried from l to r. ''' + +def update(arr, l, r, val): + arr[l] += val + if r + 1 < len(arr): + arr[r + 1] -= val '''Get the element indexed at i ''' + +def getElement(arr, i): + ''' To get ith element sum of all the elements + from 0 to i need to be computed ''' + + res = 0 + for j in range(i + 1): + res += arr[j] + return res + '''Driver Code''' + +if __name__ == '__main__': + arr = [0, 0, 0, 0, 0] + n = len(arr) + l = 2 + r = 4 + val = 2 + update(arr, l, r, val) + ''' Find the element at Index 4 ''' + + index = 4 + print(""Element at index"", index, + ""is"", getElement(arr, index)) + l = 0 + r = 3 + val = 4 + update(arr, l, r, val) + ''' Find the element at Index 3 ''' + + index = 3 + print(""Element at index"", index, + ""is"", getElement(arr, index))" +Matrix Chain Multiplication | DP-8,"/*Dynamic Programming Java implementation of Matrix +Chain Multiplication. +See the Cormen book for details of the following +algorithm*/ + +class MatrixChainMultiplication +{ +/* Matrix Ai has dimension p[i-1] x p[i] for i = 1..n*/ + + static int MatrixChainOrder(int p[], int n) + { + /* For simplicity of the + program, one extra row and + one extra column are allocated in m[][]. 0th row + and 0th column of m[][] are not used */ + + int m[][] = new int[n][n]; + int i, j, k, L, q; + /* m[i, j] = Minimum number of scalar + multiplications needed to compute the matrix + A[i]A[i+1]...A[j] = A[i..j] where + dimension of A[i] is p[i-1] x p[i] */ + +/* cost is zero when multiplying one matrix.*/ + + for (i = 1; i < n; i++) + m[i][i] = 0; +/* L is chain length.*/ + + for (L = 2; L < n; L++) + { + for (i = 1; i < n - L + 1; i++) + { + j = i + L - 1; + if (j == n) + continue; + m[i][j] = Integer.MAX_VALUE; + for (k = i; k <= j - 1; k++) + { +/* q = cost/scalar multiplications*/ + + q = m[i][k] + m[k + 1][j] + + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) + m[i][j] = q; + } + } + } + return m[1][n - 1]; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = new int[] { 1, 2, 3, 4 }; + int size = arr.length; + System.out.println( + ""Minimum number of multiplications is "" + + MatrixChainOrder(arr, size)); + } +}"," '''Dynamic Programming Python implementation of Matrix +Chain Multiplication. See the Cormen book for details +of the following algorithm''' + +import sys '''Matrix Ai has dimension p[i-1] x p[i] for i = 1..n''' + +def MatrixChainOrder(p, n): + ''' For simplicity of the program, + one extra row and one + extra column are allocated in m[][]. + 0th row and 0th + column of m[][] are not used''' + + m = [[0 for x in range(n)] for x in range(n)] + ''' m[i, j] = Minimum number of scalar + multiplications needed + to compute the matrix A[i]A[i + 1]...A[j] = + A[i..j] where + dimension of A[i] is p[i-1] x p[i]''' + + '''cost is zero when multiplying one matrix.''' + + for i in range(1, n): + m[i][i] = 0 ''' L is chain length.''' + + for L in range(2, n): + for i in range(1, n-L + 1): + j = i + L-1 + m[i][j] = sys.maxint + for k in range(i, j): + ''' q = cost / scalar multiplications''' + + q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j] + if q < m[i][j]: + m[i][j] = q + return m[1][n-1] + '''Driver code''' + +arr = [1, 2, 3, 4] +size = len(arr) +print(""Minimum number of multiplications is "" + + str(MatrixChainOrder(arr, size)))" +Count quadruples from four sorted arrays whose sum is equal to a given value x,"/*Java implementation to count quadruples from +four sorted arrays whose sum is equal to a +given value x*/ + +class GFG +{ +/* find the 'value' in the given array 'arr[]' + binary search technique is applied*/ + + static boolean isPresent(int[] arr, int low, + int high, int value) + { + while (low <= high) + { + int mid = (low + high) / 2; +/* 'value' found*/ + + if (arr[mid] == value) + return true; + else if (arr[mid] > value) + high = mid - 1; + else + low = mid + 1; + } +/* 'value' not found*/ + + return false; + } +/* function to count all quadruples from four + sorted arrays whose sum is equal to a given value x*/ + + static int countQuadruples(int[] arr1, int[] arr2, + int[] arr3, int[] arr4, + int n, int x) + { + int count = 0; +/* generate all triplets from the 1st three arrays*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + for (int k = 0; k < n; k++) + { +/* calculate the sum of elements in + the triplet so generated*/ + + int T = arr1[i] + arr2[j] + arr3[k]; +/* check if 'x-T' is present in 4th + array or not*/ + + if (isPresent(arr4, 0, n-1, x - T)) +/* increment count*/ + + count++; + } +/* required count of quadruples*/ + + return count; + } +/* Driver code*/ + + public static void main(String[] args) + { +/* four sorted arrays each of size 'n'*/ + + int[] arr1 = { 1, 4, 5, 6 }; + int[] arr2 = { 2, 3, 7, 8 }; + int[] arr3 = { 1, 4, 6, 10 }; + int[] arr4 = { 2, 4, 7, 8 }; + int n = 4; + int x = 30; + System.out.println( ""Count = "" + + countQuadruples(arr1, arr2, arr3, arr4, n, x)); + } +}", +Sort an array in wave form,"/*Java implementation of naive method for sorting +an array in wave form.*/ + +import java.util.*; +class SortWave +{ +/* A utility method to swap two numbers.*/ + + void swap(int arr[], int a, int b) + { + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + } +/* This function sorts arr[0..n-1] in wave form, i.e., + arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]..*/ + + void sortInWave(int arr[], int n) + { +/* Sort the input array*/ + + Arrays.sort(arr); +/* Swap adjacent elements*/ + + for (int i=0; i= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]''' + +def sortInWave(arr, n): + ''' sort the array''' + + arr.sort() + ''' Swap adjacent elements''' + + for i in range(0,n-1,2): + arr[i], arr[i+1] = arr[i+1], arr[i] + '''Driver program''' + +arr = [10, 90, 49, 2, 1, 5, 23] +sortInWave(arr, len(arr)) +for i in range(0,len(arr)): + print arr[i]," +Queue using Stacks,"/*Java program to implement Queue using +two stacks with costly enQueue() */ + +import java.util.*; +class GFG +{ +static class Queue +{ + static Stack s1 = new Stack(); + static Stack s2 = new Stack(); + static void enQueue(int x) + { +/* Move all elements from s1 to s2 */ + + while (!s1.isEmpty()) + { + s2.push(s1.pop()); + s1.pop(); + } /* Push item into s1 */ + + s1.push(x); +/* Push everything back to s1 */ + + while (!s2.isEmpty()) + { + s1.push(s2.pop()); + s2.pop(); + + } + } /* Dequeue an item from the queue */ + + static int deQueue() + { +/* if first stack is empty */ + + if (s1.isEmpty()) + { + System.out.println(""Q is Empty""); + System.exit(0); + } +/* Return top of s1 */ + + int x = s1.peek(); + s1.pop(); + return x; + } +}; +/*Driver code */ + +public static void main(String[] args) +{ + Queue q = new Queue(); + q.enQueue(1); + q.enQueue(2); + q.enQueue(3); + System.out.println(q.deQueue()); + System.out.println(q.deQueue()); + System.out.println(q.deQueue()); +} +}"," '''Python3 program to implement Queue using +two stacks with costly enQueue() ''' + +class Queue: + def __init__(self): + self.s1 = [] + self.s2 = [] + def enQueue(self, x): + ''' Move all elements from s1 to s2 ''' + + while len(self.s1) != 0: + self.s2.append(self.s1[-1]) + self.s1.pop() + ''' Push item into self.s1 ''' + + self.s1.append(x) + ''' Push everything back to s1 ''' + + while len(self.s2) != 0: + self.s1.append(self.s2[-1]) + self.s2.pop() + ''' Dequeue an item from the queue ''' + + def deQueue(self): + ''' if first stack is empty ''' + + if len(self.s1) == 0: + print(""Q is Empty"") + ''' Return top of self.s1 ''' + + x = self.s1[-1] + self.s1.pop() + return x + '''Driver code ''' + +if __name__ == '__main__': + q = Queue() + q.enQueue(1) + q.enQueue(2) + q.enQueue(3) + print(q.deQueue()) + print(q.deQueue()) + print(q.deQueue())" +Find position of the only set bit,"/*Java program to find position of only +set bit in a given number*/ + +class GFG { +/* A utility function to check whether + n is power of 2 or not*/ + + static boolean isPowerOfTwo(int n) + { + return n > 0 && ((n & (n - 1)) == 0); + } +/* Returns position of the only set bit in 'n'*/ + + static int findPosition(int n) + { + if (!isPowerOfTwo(n)) + return -1; + int count = 0; +/* One by one move the only set bit + to right till it reaches end*/ + + while (n > 0) { + n = n >> 1; +/* increment count of shifts*/ + + ++count; + } + return count; + } +/* Driver code*/ + + public static void main(String[] args) + { + int n = 0; + int pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + n = 12; + pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + n = 128; + pos = findPosition(n); + if (pos == -1) + System.out.println(""n = "" + n + "", Invalid number""); + else + System.out.println(""n = "" + n + "", Position "" + pos); + } +}"," '''Python 3 program to find position +of only set bit in a given number''' ''' +A utility function to check whether +n is power of 2 or not''' + +def isPowerOfTwo(n) : + return (n and ( not (n & (n-1)))) + '''Returns position of the only set bit in 'n''' + ''' +def findPosition(n) : + if not isPowerOfTwo(n) : + return -1 + count = 0 + ''' One by one move the only set bit to + right till it reaches end''' + + while (n) : + n = n >> 1 + ''' increment count of shifts''' + + count += 1 + return count + '''Driver program to test above function''' + +if __name__ == ""__main__"" : + n = 0 + pos = findPosition(n) + if pos == -1 : + print(""n ="", n, ""Invalid number"") + else : + print(""n ="", n, ""Position"", pos) + n = 12 + pos = findPosition(n) + if pos == -1 : + print(""n ="", n, ""Invalid number"") + else : + print(""n ="", n, ""Position"", pos) + n = 128 + pos = findPosition(n) + if pos == -1 : + print(""n ="", n, ""Invalid number"") + else : + print(""n ="", n, ""Position"", pos)" +Sorting rows of matrix in ascending order followed by columns in descending order,"/*Java implementation to sort the rows +of matrix in ascending order followed by +sorting the columns in descending order*/ + +import java.util.Arrays; +import java.util.Collections; +class GFG +{ + static int MAX_SIZE=10; +/* function to sort each row of the matrix + according to the order specified by + ascending.*/ + + static void sortByRow(Integer mat[][], int n, + boolean ascending) + { + for (int i = 0; i < n; i++) + { + if (ascending) + Arrays.sort(mat[i]); + else + Arrays.sort(mat[i],Collections.reverseOrder()); + } + } +/* function to find transpose of the matrix*/ + + static void transpose(Integer mat[][], int n) + { + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + { +/* swapping element at index (i, j) + by element at index (j, i)*/ + + int temp = mat[i][j]; + mat[i][j] = mat[j][i]; + mat[j][i] = temp; + } + } +/* function to sort the matrix row-wise + and column-wise*/ + + static void sortMatRowAndColWise(Integer mat[][], + int n) + { +/* sort rows of mat[][]*/ + + sortByRow(mat, n, true); +/* get transpose of mat[][]*/ + + transpose(mat, n); +/* again sort rows of mat[][] in descending + order.*/ + + sortByRow(mat, n, false); +/* again get transpose of mat[][]*/ + + transpose(mat, n); + } +/* function to print the matrix*/ + + static void printMat(Integer mat[][], int n) + { + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + System.out.print(mat[i][j] + "" ""); + System.out.println(); + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int n = 3; + Integer mat[][] = {{3, 2, 1}, + {9, 8, 7}, + {6, 5, 4}}; + System.out.print(""Original Matrix:\n""); + printMat(mat, n); + sortMatRowAndColWise(mat, n); + System.out.print(""\nMatrix After Sorting:\n""); + printMat(mat, n); + } +}"," '''Python implementation to sort the rows +of matrix in ascending order followed by +sorting the columns in descending order''' + +MAX_SIZE=10 + '''function to sort each row of the matrix +according to the order specified by +ascending.''' + +def sortByRow(mat, n, ascending): + for i in range(n): + if (ascending): + mat[i].sort() + else: + mat[i].sort(reverse=True) + '''function to find +transpose of the matrix''' + +def transpose(mat, n): + for i in range(n): + for j in range(i + 1, n): + ''' swapping element at index (i, j) + by element at index (j, i)''' + + temp = mat[i][j] + mat[i][j] = mat[j][i] + mat[j][i] = temp + '''function to sort +the matrix row-wise +and column-wise''' + +def sortMatRowAndColWise(mat, n): + ''' sort rows of mat[][]''' + + sortByRow(mat, n, True) + ''' get transpose of mat[][]''' + + transpose(mat, n) + ''' again sort rows of + mat[][] in descending + order.''' + + sortByRow(mat, n, False) + ''' again get transpose of mat[][]''' + + transpose(mat, n) + '''function to print the matrix''' + +def printMat(mat, n): + for i in range(n): + for j in range(n): + print(mat[i][j] , "" "", end="""") + print() + '''Driver code''' + +n = 3 +mat = [[3, 2, 1], + [9, 8, 7], + [6, 5, 4]] +print(""Original Matrix:"") +printMat(mat, n) +sortMatRowAndColWise(mat, n) +print(""Matrix After Sorting:"") +printMat(mat, n)" +Rearrange positive and negative numbers using inbuilt sort function,"/*Java program to implement the +above approach*/ + +import java.io.*; +class GFG{ +static void printArray(int[] array, int length) +{ + System.out.print(""[""); + for (int i = 0; i < length; i++) + { + System.out.print(array[i]); + if (i < (length - 1)) + System.out.print("",""); + else + System.out.print(""]\n""); + } +} +static void reverse(int[] array, + int start, + int end) +{ + while (start < end) + { + int temp = array[start]; + array[start] = array[end]; + array[end] = temp; + start++; + end--; + } +} +/*Rearrange the array with +all negative integers on left +and positive integers on right +use recursion to split the +array with first element +as one half and the rest +array as another and then +merge it with head of +the array in each step*/ + +static void rearrange(int[] array, + int start, + int end) +{ +/* exit condition*/ + + if (start == end) + return; +/* rearrange the array + except the first element + in each recursive call*/ + + rearrange(array, + (start + 1), end); +/* If the first element of + the array is positive, + then right-rotate the + array by one place first + and then reverse the merged array.*/ + + if (array[start] >= 0) + { + reverse(array, + (start + 1), end); + reverse(array, + start, end); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int[] array = {-12, -11, -13, + -5, -6, 7, 5, 3, 6}; + int length = array.length; + int countNegative = 0; + for (int i = 0; i < length; i++) + { + if (array[i] < 0) + countNegative++; + } + System.out.print(""array: ""); + printArray(array, length); + rearrange(array, 0, + (length - 1)); + reverse(array, countNegative, + (length - 1)); + System.out.print(""rearranged array: ""); + printArray(array, length); +} +}"," '''Python3 implementation of the above approach''' + +def printArray(array, length): + print(""["", end = """") + for i in range(length): + print(array[i], end = """") + if(i < (length - 1)): + print("","", end = "" "") + else: + print(""]"") +def reverse(array, start, end): + while(start < end): + temp = array[start] + array[start] = array[end] + array[end] = temp + start += 1 + end -= 1 + '''Rearrange the array with all negative integers +on left and positive integers on right +use recursion to split the array with first element +as one half and the rest array as another and then +merge it with head of the array in each step''' + +def rearrange(array, start, end): + ''' exit condition''' + + if(start == end): + return + ''' rearrange the array except the first + element in each recursive call''' + + rearrange(array, (start + 1), end) + ''' If the first element of the array is positive, + then right-rotate the array by one place first + and then reverse the merged array.''' + + if(array[start] >= 0): + reverse(array, (start + 1), end) + reverse(array, start, end) + '''Driver code''' + +if __name__ == '__main__': + array = [-12, -11, -13, -5, -6, 7, 5, 3, 6] + length = len(array) + countNegative = 0 + for i in range(length): + if(array[i] < 0): + countNegative += 1 + print(""array: "", end = """") + printArray(array, length) + rearrange(array, 0, (length - 1)) + reverse(array, countNegative, (length - 1)) + print(""rearranged array: "", end = """") + printArray(array, length)" +Three way partitioning of an array around a given range,"/*Java program to implement three way partitioning +around a given range.*/ + +import java.io.*; + +class GFG +{ + +/* Partitions arr[0..n-1] around [lowVal..highVal]*/ + + public static void threeWayPartition(int[] arr, int lowVal, int highVal) + { + + int n = arr.length; + +/* Initialize ext available positions for + smaller (than range) and greater lements*/ + + int start = 0, end = n-1; + +/* Traverse elements from left*/ + + for(int i = 0; i <= end;) + { + +/* If current element is smaller than + range, put it on next available smaller + position.*/ + + + if(arr[i] < lowVal) + { + + int temp = arr[start]; + arr[start] = arr[i]; + arr[i] = temp; + start++; + i++; + + } + +/* If current element is greater than + range, put it on next available greater + position.*/ + + else if(arr[i] > highVal) + { + + int temp = arr[end]; + arr[end] = arr[i]; + arr[i] = temp; + end--; + + } + + else + i++; + } + + } + + + + /*Driver code*/ + + + public static void main (String[] args) + { + + + int arr[] = {1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32}; + + threeWayPartition(arr, 10, 20); + + System.out.println(""Modified array ""); + for (int i=0; i < arr.length; i++) + { + System.out.print(arr[i] + "" ""); + + } + } +}"," '''Python3 program to implement three way +partitioning around a given range.''' + + + '''Partitions arr[0..n-1] around [lowVal..highVal]''' + +def threeWayPartition(arr, n, lowVal, highVal): + + ''' Initialize ext available positions for + smaller (than range) and greater lements''' + + start = 0 + end = n - 1 + i = 0 + + ''' Traverse elements from left''' + + while i <= end: + + ''' If current element is smaller than + range, put it on next available smaller + position.''' + + if arr[i] < lowVal: + temp = arr[i] + arr[i] = arr[start] + arr[start] = temp + i += 1 + start += 1 + + ''' If current element is greater than + range, put it on next available greater + position.''' + + elif arr[i] > highVal: + temp = arr[i] + arr[i] = arr[end] + arr[end] = temp + end -= 1 + + else: + i += 1 + + '''Driver code''' + +if __name__ == ""__main__"": + arr = [1, 14, 5, 20, 4, 2, 54, + 20, 87, 98, 3, 1, 32] + n = len(arr) + + threeWayPartition(arr, n, 10, 20) + + print(""Modified array"") + for i in range(n): + print(arr[i], end = "" "") + + +" +Print BST keys in given Range | O(1) Space,"/*Java code to print BST keys in given Range in +constant space using Morris traversal.*/ + +class GfG { +static class node { + int data; + node left, right; +} +/*Function to print the keys in range*/ + +static void RangeTraversal(node root, int n1, int n2) +{ + if (root == null) + return; + node curr = root; + while (curr != null) { + if (curr.left == null) + { +/* check if current node + lies between n1 and n2*/ + + if (curr.data <= n2 && curr.data >= n1) + { + System.out.print(curr.data + "" ""); + } + curr = curr.right; + } + else { + node pre = curr.left; +/* finding the inorder predecessor- + inorder predecessor is the right + most in left subtree or the left + child, i.e in BST it is the + maximum(right most) in left subtree.*/ + + while (pre.right != null && pre.right != curr) + pre = pre.right; + if (pre.right == null) + { + pre.right = curr; + curr = curr.left; + } + else { + pre.right = null; +/* check if current node lies + between n1 and n2*/ + + if (curr.data <= n2 && curr.data >= n1) + { + System.out.print(curr.data + "" ""); + } + curr = curr.right; + } + } + } +} +/*Helper function to create a new node*/ + +static node newNode(int data) +{ + node temp = new node(); + temp.data = data; + temp.right = null; + temp.left = null; + return temp; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + /* Constructed binary tree is + 4 + / \ + 2 7 + / \ / \ + 1 3 6 10 +*/ + + node root = newNode(4); + root.left = newNode(2); + root.right = newNode(7); + root.left.left = newNode(1); + root.left.right = newNode(3); + root.right.left = newNode(6); + root.right.right = newNode(10); + RangeTraversal(root, 4, 12); +} +}"," '''Python3 code to print BST keys in given Range +in constant space using Morris traversal. +Helper function to create a new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to print the keys in range''' + +def RangeTraversal(root, n1, n2): + if root == None: + return + curr = root + while curr: + if curr.left == None: + ''' check if current node lies + between n1 and n2''' + + if curr.data <= n2 and curr.data >= n1: + print(curr.data, end = "" "") + curr = curr.right + else: + pre = curr.left + ''' finding the inorder predecessor- + inorder predecessor is the right + most in left subtree or the left + child, i.e in BST it is the + maximum(right most) in left subtree.''' + + while (pre.right != None and + pre.right != curr): + pre = pre.right + if pre.right == None: + pre.right = curr; + curr = curr.left + else: + pre.right = None + ''' check if current node lies + between n1 and n2''' + + if curr.data <= n2 and curr.data >= n1: + print(curr.data, end = "" "") + curr = curr.right + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 4 + / \ + 2 7 + / \ / \ + 1 3 6 10''' + + root = newNode(4) + root.left = newNode(2) + root.right = newNode(7) + root.left.left = newNode(1) + root.left.right = newNode(3) + root.right.left = newNode(6) + root.right.right = newNode(10) + RangeTraversal(root, 4, 12)" +Check if there is a root to leaf path with given sequence,"/*Java program to see if there is a root to leaf path +with given sequence.*/ + +import java.io.*; +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +class Node +{ + int data; + Node left; + Node right; + Node(int data) + { + this.data = data; + this.left = null; + this.right = null; + } +} +class GFG { +/* Util function*/ + + static boolean existPathUtil(Node root, int arr[], + int n, int index) + { +/* If root is NULL or + reached end of the array*/ + + if(root == null || index==n) + return false; +/* If current node is leaf*/ + + if (root.left == null && + root.right == null) + { + if((root.data == arr[index]) && + (index == n-1)) + return true; + return false; + } +/* If current node is equal to arr[index] this means + that till this level path has been matched and + remaining path can be either in left subtree or + right subtree.*/ + + return ((index < n) && (root.data == arr[index]) + && (existPathUtil(root.left, arr, n, index+1) + || existPathUtil(root.right, arr, n, index+1) )); + } +/* Function to check given sequence of root + to leaf path exist in tree or not. + index : current element in sequence of root to + leaf path*/ + + static boolean existPath(Node root, int arr[], + int n, int index) + { + if(root == null) + return (n==0); + return existPathUtil(root, arr, n, 0); + } + +/* Driver code*/ + + public static void main (String[] args) {/* arr[] : sequence of root to leaf path*/ + + int arr[] = {5, 8, 6, 7}; + int n = arr.length; + Node root = new Node(5); + root.left = new Node(3); + root.right = new Node(8); + root.left.left = new Node(2); + root.left.right = new Node(4); + root.left.left.left = new Node(1); + root.right.left = new Node(6); + root.right.left.right = new Node(7); + if(existPath(root, arr, n, 0)) + System.out.println(""Path Exists""); + else + System.out.println(""Path does not Exist""); + } +}"," '''Python program to see if +there is a root to leaf path +with given sequence''' + + '''Class of Node''' + +class Node: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + '''Util function ''' + +def existPathUtil(root, arr, n, index): + ''' If root is NULL or reached + end of the array''' + + if not root or index == n: + return False + ''' If current node is leaf''' + + if not root.left and not root.right: + if root.val == arr[index] and index == n-1: + return True + return False + ''' If current node is equal to arr[index] this means + that till this level path has been matched and + remaining path can be either in left subtree or + right subtree.''' + + return ((index < n) and (root.val == arr[index]) and \ + (existPathUtil(root.left, arr, n, index+1) or \ + existPathUtil(root.right, arr, n, index+1))) + '''Function to check given sequence of root to leaf path exist +in tree or not. +index represents current element in sequence of rooth to +leaf path ''' + +def existPath(root, arr, n, index): + if not root: + return (n == 0) + return existPathUtil(root, arr, n, 0) + '''Driver Code''' + +if __name__ == ""__main__"": + ''' arr[] : sequence of root to leaf path''' + + arr = [5, 8, 6, 7] + n = len(arr) + root = Node(5) + root.left = Node(3) + root.right = Node(8) + root.left.left = Node(2) + root.left.right = Node(4) + root.left.left.left = Node(1) + root.right.left = Node(6) + root.right.left.right = Node(7) + if existPath(root, arr, n, 0): + print(""Path Exists"") + else: + print(""Path does not Exist"")" +Find the minimum element in a sorted and rotated array,"/*Java program to find minimum element +in a sorted and rotated array contating +duplicate elements.*/ + +import java.util.*; +import java.lang.*; +class GFG{ +/*Function to find minimum element*/ + +public static int findMin(int arr[], + int low, int high) +{ + while(low < high) + { + int mid = low + (high - low) / 2; + if (arr[mid] == arr[high]) + high--; + else if(arr[mid] > arr[high]) + low = mid + 1; + else + high = mid; + } + return arr[high]; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr1[] = { 5, 6, 1, 2, 3, 4 }; + int n1 = arr1.length; + System.out.println(""The minimum element is "" + + findMin(arr1, 0, n1 - 1)); + int arr2[] = { 1, 2, 3, 4 }; + int n2 = arr2.length; + System.out.println(""The minimum element is "" + + findMin(arr2, 0, n2 - 1)); + int arr3[] = {1}; + int n3 = arr3.length; + System.out.println(""The minimum element is "" + + findMin(arr3, 0, n3 - 1)); + int arr4[] = { 1, 2 }; + int n4 = arr4.length; + System.out.println(""The minimum element is "" + + findMin(arr4, 0, n4 - 1)); + int arr5[] = { 2, 1 }; + int n5 = arr5.length; + System.out.println(""The minimum element is "" + + findMin(arr5, 0, n5 - 1)); + int arr6[] = { 5, 6, 7, 1, 2, 3, 4 }; + int n6 = arr6.length; + System.out.println(""The minimum element is "" + + findMin(arr6, 0, n6 - 1)); + int arr7[] = { 1, 2, 3, 4, 5, 6, 7 }; + int n7 = arr7.length; + System.out.println(""The minimum element is "" + + findMin(arr7, 0, n7 - 1)); + int arr8[] = { 2, 3, 4, 5, 6, 7, 8, 1 }; + int n8 = arr8.length; + System.out.println(""The minimum element is "" + + findMin(arr8, 0, n8 - 1)); + int arr9[] = { 3, 4, 5, 1, 2 }; + int n9 = arr9.length; + System.out.println(""The minimum element is "" + + findMin(arr9, 0, n9 - 1)); +} +}"," '''Python3 program to find +minimum element in a sorted +and rotated array contating +duplicate elements.''' + + '''Function to find minimum element''' + +def findMin(arr, low, high): + while (low < high): + mid = low + (high - low) // 2; + if (arr[mid] == arr[high]): + high -= 1; + elif (arr[mid] > arr[high]): + low = mid + 1; + else: + high = mid; + return arr[high]; '''Driver code''' + +if __name__ == '__main__': + arr1 = [5, 6, 1, 2, 3, 4]; + n1 = len(arr1); + print(""The minimum element is "", + findMin(arr1, 0, n1 - 1)); + arr2 = [1, 2, 3, 4]; + n2 = len(arr2); + print(""The minimum element is "", + findMin(arr2, 0, n2 - 1)); + arr3 = [1]; + n3 = len(arr3); + print(""The minimum element is "", + findMin(arr3, 0, n3 - 1)); + arr4 = [1, 2]; + n4 = len(arr4); + print(""The minimum element is "", + findMin(arr4, 0, n4 - 1)); + arr5 = [2, 1]; + n5 = len(arr5); + print(""The minimum element is "", + findMin(arr5, 0, n5 - 1)); + arr6 = [5, 6, 7, 1, 2, 3, 4]; + n6 = len(arr6); + print(""The minimum element is "", + findMin(arr6, 0, n6 - 1)); + arr7 = [1, 2, 3, 4, 5, 6, 7]; + n7 = len(arr7); + print(""The minimum element is "", + findMin(arr7, 0, n7 - 1)); + arr8 = [2, 3, 4, 5, 6, 7, 8, 1]; + n8 = len(arr8); + print(""The minimum element is "", + findMin(arr8, 0, n8 - 1)); + arr9 = [3, 4, 5, 1, 2]; + n9 = len(arr9); + print(""The minimum element is "", + findMin(arr9, 0, n9 - 1));" +"Search, insert and delete in an unsorted array","/*Java program to implement delete +operation in an unsorted array*/ + +class Main +{ +/* function to search a key to + be deleted*/ + + static int findElement(int arr[], int n, int key) + { + int i; + for (i = 0; i < n; i++) + if (arr[i] == key) + return i; + return -1; + } +/* Function to delete an element*/ + + static int deleteElement(int arr[], int n, int key) + { +/* Find position of element to be + deleted*/ + + int pos = findElement(arr, n, key); + if (pos == -1) + { + System.out.println(""Element not found""); + return n; + } +/* Deleting element*/ + + int i; + for (i = pos; i< n - 1; i++) + arr[i] = arr[i + 1]; + return n - 1; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int i; + int arr[] = {10, 50, 30, 40, 20}; + int n = arr.length; + int key = 30; + System.out.println(""Array before deletion""); + for (i=0; i freq = new HashMap<>(); + for(int i = 0; i < n; i++) + freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1); +/* Find maximum frequency among all frequencies.*/ + + int max_freq = Integer.MIN_VALUE; + for(Map.Entry entry : freq.entrySet()) + max_freq = Math.max(max_freq, + entry.getValue()); +/* To minimize delete operations, + we remove all elements but the + most frequent element.*/ + + return n - max_freq ; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 4, 3, 4, 4, 2, 4 }; + int n = arr.length; + System.out.print(minDelete(arr, n)); +} +}"," '''Python3 program to find minimum +number of deletes required to +make all elements same. + ''' '''Function to get minimum number +of elements to be deleted from +array to make array elements equal''' + +def minDelete(arr, n): + ''' Create an dictionary and store + frequencies of all array + elements in it using + element as key and + frequency as value''' + + freq = {} + for i in range(n): + if arr[i] in freq: + freq[arr[i]] += 1 + else: + freq[arr[i]] = 1; + ''' Find maximum frequency + among all frequencies.''' + + max_freq = 0; + for i, j in freq.items(): + max_freq = max(max_freq, j); + ''' To minimize delete operations, + we remove all elements but the + most frequent element.''' + + return n - max_freq; + '''Driver code''' + +arr = [ 4, 3, 4, 4, 2, 4 ]; +n = len(arr) +print(minDelete(arr, n));" +Arrange consonants and vowels nodes in a linked list,"/* Java program to arrange consonants and +vowels nodes in a linked list */ + +class GfG +{ +/* A linked list node */ + +static class Node +{ + char data; + Node next; +} +/* Function to add new node to the List */ + +static Node newNode(char key) +{ + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; +} +/*utility function to print linked list*/ + +static void printlist(Node head) +{ + if (head == null) + { + System.out.println(""Empty List""); + return; + } + while (head != null) + { + System.out.print(head.data +"" ""); + if (head.next != null) + System.out.print(""-> ""); + head = head.next; + } + System.out.println(); +} +/*utility function for checking vowel*/ + +static boolean isVowel(char x) +{ + return (x == 'a' || x == 'e' || x == 'i' || + x == 'o' || x == 'u'); +} +/* function to arrange consonants and +vowels nodes */ + +static Node arrange(Node head) +{ + Node newHead = head; +/* for keep track of vowel*/ + + Node latestVowel; + Node curr = head; +/* list is empty*/ + + if (head == null) + return null; +/* We need to discover the first vowel + in the list. It is going to be the + returned head, and also the initial + latestVowel.*/ + + if (isVowel(head.data) == true) +/* first element is a vowel. It will + also be the new head and the initial + latestVowel;*/ + + latestVowel = head; + else + { +/* First element is not a vowel. Iterate + through the list until we find a vowel. + Note that curr points to the element + *before* the element with the vowel.*/ + + while (curr.next != null && + !isVowel(curr.next.data)) + curr = curr.next; +/* This is an edge case where there are + only consonants in the list.*/ + + if (curr.next == null) + return head; +/* Set the initial latestVowel and the + new head to the vowel item that we found. + Relink the chain of consonants after + that vowel item: + old_head_consonant->consonant1->consonant2-> + vowel->rest_of_list becomes + vowel->old_head_consonant->consonant1-> + consonant2->rest_of_list*/ + + latestVowel = newHead = curr.next; + curr.next = curr.next.next; + latestVowel.next = head; + } +/* Now traverse the list. Curr is always the item + *before* the one we are checking, so that we + can use it to re-link.*/ + + while (curr != null && curr.next != null) + { + if (isVowel(curr.next.data) == true) + { +/* The next discovered item is a vowel*/ + + if (curr == latestVowel) + { +/* If it comes directly after the + previous vowel, we don't need to + move items around, just mark the + new latestVowel and advance curr.*/ + + latestVowel = curr = curr.next; + } + else + { +/* But if it comes after an intervening + chain of consonants, we need to chain + the newly discovered vowel right after + the old vowel. Curr is not changed as + after the re-linking it will have a + new next, that has not been checked yet, + and we always keep curr at one before + the next to check.*/ + + Node temp = latestVowel.next; +/* Chain in new vowel*/ + + latestVowel.next = curr.next; +/* Advance latestVowel*/ + + latestVowel = latestVowel.next; +/* Remove found vowel from previous place*/ + + curr.next = curr.next.next; +/* Re-link chain of consonants after latestVowel*/ + + latestVowel.next = temp; + } + } + else + { +/* No vowel in the next element, advance curr.*/ + + curr = curr.next; + } + } + return newHead; +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node head = newNode('a'); + head.next = newNode('b'); + head.next.next = newNode('c'); + head.next.next.next = newNode('e'); + head.next.next.next.next = newNode('d'); + head.next.next.next.next.next = newNode('o'); + head.next.next.next.next.next.next = newNode('x'); + head.next.next.next.next.next.next.next = newNode('i'); + System.out.println(""Linked list before : ""); + printlist(head); + head = arrange(head); + System.out.println(""Linked list after :""); + printlist(head); +} +}"," '''Python3 program to remove vowels +Nodes in a linked list + ''' '''A linked list node''' + +class Node: + def __init__(self, x): + self.data = x + self.next = None + '''Utility function to print the +linked list''' + +def printlist(head): + if (not head): + print(""Empty List"") + return + while (head != None): + print(head.data, end = "" "") + if (head.next): + print(end = ""-> "") + head = head.next + print() + '''Utility function for checking vowel''' + +def isVowel(x): + return (x == 'a' or x == 'e' or x == 'i' + or x == 'o' or x == 'u' or x == 'A' + or x == 'E' or x == 'I' or x == 'O' + or x == 'U') + '''/* function to arrange consonants and + vowels nodes */''' + +def arrange(head): + newHead = head + ''' for keep track of vowel''' + + latestVowel = None + curr = head + ''' list is empty''' + + if (head == None): + return None + ''' We need to discover the first vowel + in the list. It is going to be the + returned head, and also the initial + latestVowel.''' + + if (isVowel(head.data)): + ''' first element is a vowel. It will + also be the new head and the initial + latestVowel''' + + latestVowel = head + else: + ''' First element is not a vowel. Iterate + through the list until we find a vowel. + Note that curr points to the element + *before* the element with the vowel.''' + + while (curr.next != None and + not isVowel(curr.next.data)): + curr = curr.next + ''' This is an edge case where there are + only consonants in the list.''' + + if (curr.next == None): + return head + ''' Set the initial latestVowel and the + new head to the vowel item that we found. + Relink the chain of consonants after + that vowel item: + old_head_consonant.consonant1.consonant2. + vowel.rest_of_list becomes + vowel.old_head_consonant.consonant1. + consonant2.rest_of_list''' + + latestVowel = newHead = curr.next + curr.next = curr.next.next + latestVowel.next = head + ''' Now traverse the list. Curr is always the item + *before* the one we are checking, so that we + can use it to re-link.''' + + while (curr != None and curr.next != None): + if (isVowel(curr.next.data)): + ''' The next discovered item is a vowel''' + + if (curr == latestVowel): + ''' If it comes directly after the + previous vowel, we don't need to + move items around, just mark the + new latestVowel and advance curr.''' + + latestVowel = curr = curr.next + else: + ''' But if it comes after an intervening + chain of consonants, we need to chain + the newly discovered vowel right after + the old vowel. Curr is not changed as + after the re-linking it will have a + new next, that has not been checked yet, + and we always keep curr at one before + the next to check.''' + + temp = latestVowel.next + ''' Chain in new vowel''' + + latestVowel.next = curr.next + ''' Advance latestVowel''' + + latestVowel = latestVowel.next + ''' Remove found vowel from previous place''' + + curr.next = curr.next.next + ''' Re-link chain of consonants after latestVowel''' + + latestVowel.next = temp + else: + ''' No vowel in the next element, advance curr.''' + + curr = curr.next + return newHead + '''Driver code''' + +if __name__ == '__main__': + head = Node('a') + head.next = Node('b') + head.next.next = Node('c') + head.next.next.next = Node('e') + head.next.next.next.next = Node('d') + head.next.next.next.next.next = Node('o') + head.next.next.next.next.next.next = Node('x') + head.next.next.next.next.next.next.next = Node('i') + print(""Linked list before :"") + printlist(head) + head = arrange(head) + print(""Linked list after :"") + printlist(head)" +Minimum Possible value of |ai + aj,"/*Java program to find number of pairs +and minimal possible value*/ + +import java.util.*; +class GFG { +/* function for finding pairs and min value*/ + + static void pairs(int arr[], int n, int k) + { +/* initialize smallest and count*/ + + int smallest = Integer.MAX_VALUE; + int count=0; +/* iterate over all pairs*/ + + for (int i=0; i n) + return 0; + +/* If current pair is valid so + DO NOT DISTURB this pair + and move ahead.*/ + + if (pairs[arr[i]] == arr[i + 1]) + return minSwapsUtil(arr, pairs, index, i + 2, n); + +/* If we reach here, then arr[i] and + arr[i+1] don't form a pair*/ + + +/* Swap pair of arr[i] with arr[i+1] + and recursively compute minimum swap + required if this move is made.*/ + + int one = arr[i + 1]; + int indextwo = i + 1; + int indexone = index[pairs[arr[i]]]; + int two = arr[index[pairs[arr[i]]]]; + arr[i + 1] = arr[i + 1] ^ arr[indexone] ^ + (arr[indexone] = arr[i + 1]); + updateindex(index, one, indexone, two, indextwo); + int a = minSwapsUtil(arr, pairs, index, i + 2, n); + +/* Backtrack to previous configuration. + Also restore the previous + indices, of one and two*/ + + arr[i + 1] = arr[i + 1] ^ arr[indexone] ^ + (arr[indexone] = arr[i + 1]); + updateindex(index, one, indextwo, two, indexone); + one = arr[i]; + indexone = index[pairs[arr[i + 1]]]; + +/* Now swap arr[i] with pair of arr[i+1] + and recursively compute minimum swaps + required for the subproblem + after this move*/ + + two = arr[index[pairs[arr[i + 1]]]]; + indextwo = i; + arr[i] = arr[i] ^ arr[indexone] ^ (arr[indexone] = arr[i]); + updateindex(index, one, indexone, two, indextwo); + int b = minSwapsUtil(arr, pairs, index, i + 2, n); + +/* Backtrack to previous configuration. Also restore + the previous indices, of one and two*/ + + arr[i] = arr[i] ^ arr[indexone] ^ (arr[indexone] = arr[i]); + updateindex(index, one, indextwo, two, indexone); + +/* Return minimum of two cases*/ + + return 1 + Math.min(a, b); +} + +/*Returns minimum swaps required*/ + +static int minSwaps(int n, int pairs[], int arr[]) +{ +/* To store indices of array elements*/ + + int index[] = new int[2 * n + 1]; + +/* Store index of each element in array index*/ + + for (int i = 1; i <= 2 * n; i++) + index[arr[i]] = i; + +/* Call the recursive function*/ + + return minSwapsUtil(arr, pairs, index, 1, 2 * n); +} + +/*Driver code*/ + +public static void main(String[] args) { + +/* For simplicity, it is assumed that arr[0] is + not used. The elements from index 1 to n are + only valid elements*/ + + int arr[] = {0, 3, 5, 6, 4, 1, 2}; + +/* if (a, b) is pair than we have assigned elements + in array such that pairs[a] = b and pairs[b] = a*/ + + int pairs[] = {0, 3, 6, 1, 5, 4, 2}; + int m = pairs.length; + +/* Number of pairs n is half of total elements*/ + + int n = m / 2; + +/* If there are n elements in array, then + there are n pairs*/ + + System.out.print(""Min swaps required is "" + + minSwaps(n, pairs, arr)); +} +} + + +"," '''Python program to find +minimum number of swaps +required so that +all pairs become adjacent.''' + + + '''This function updates +indexes of elements 'a' and 'b''' + ''' +def updateindex(index,a,ai,b,bi): + + index[a] = ai + index[b] = bi + + + '''This function returns minimum +number of swaps required to arrange +all elements of arr[i..n] +become arranged''' + +def minSwapsUtil(arr,pairs,index,i,n): + + ''' If all pairs procesed so + no swapping needed return 0''' + + if (i > n): + return 0 + + ''' If current pair is valid so + DO NOT DISTURB this pair + and move ahead.''' + + if (pairs[arr[i]] == arr[i+1]): + return minSwapsUtil(arr, pairs, index, i+2, n) + + ''' If we reach here, then arr[i] + and arr[i+1] don't form a pair''' + + + ''' Swap pair of arr[i] with + arr[i+1] and recursively compute + minimum swap required + if this move is made.''' + + one = arr[i+1] + indextwo = i+1 + indexone = index[pairs[arr[i]]] + two = arr[index[pairs[arr[i]]]] + arr[i+1],arr[indexone]=arr[indexone],arr[i+1] + + updateindex(index, one, indexone, two, indextwo) + + a = minSwapsUtil(arr, pairs, index, i+2, n) + + ''' Backtrack to previous configuration. + Also restore the + previous indices, + of one and two''' + + arr[i+1],arr[indexone]=arr[indexone],arr[i+1] + updateindex(index, one, indextwo, two, indexone) + one = arr[i] + indexone = index[pairs[arr[i+1]]] + + ''' Now swap arr[i] with pair + of arr[i+1] and recursively + compute minimum swaps + required for the subproblem + after this move''' + + two = arr[index[pairs[arr[i+1]]]] + indextwo = i + arr[i],arr[indexone]=arr[indexone],arr[i] + updateindex(index, one, indexone, two, indextwo) + b = minSwapsUtil(arr, pairs, index, i+2, n) + + ''' Backtrack to previous + configuration. Also restore + 3 the previous indices, + of one and two''' + + arr[i],arr[indexone]=arr[indexone],arr[i] + updateindex(index, one, indextwo, two, indexone) + + ''' Return minimum of two cases''' + + return 1 + min(a, b) + + '''Returns minimum swaps required''' + +def minSwaps(n,pairs,arr): + + '''To store indices of array elements''' + + index=[] + for i in range(2*n+1+1): + index.append(0) + + ''' Store index of each + element in array index''' + + for i in range(1,2*n+1): + index[arr[i]] = i + + ''' Call the recursive function''' + + return minSwapsUtil(arr, pairs, index, 1, 2*n) + + '''Driver code''' + + + '''For simplicity, it is +assumed that arr[0] is +not used. The elements +from index 1 to n are +only valid elements''' + +arr = [0, 3, 5, 6, 4, 1, 2] + + '''if (a, b) is pair than +we have assigned elements +in array such that +pairs[a] = b and pairs[b] = a''' + +pairs= [0, 3, 6, 1, 5, 4, 2] +m = len(pairs) + + '''Number of pairs n is half of total elements''' + +n = m//2 + '''If there are n +elements in array, then +there are n pairs''' + +print(""Min swaps required is "",minSwaps(n, pairs, arr)) + + +" +Find if there is a pair in root to a leaf path with sum equals to root's data,"/*Java program to find if there is a pair in any root +to leaf path with sum equals to root's key.*/ + +import java.util.*; +class GFG +{ +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +}; +/* utility that allocates a new node with the +given data and null left and right pointers. */ + +static Node newnode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); +} +/*Function to print root to leaf path which satisfies the condition*/ + +static boolean printPathUtil(Node node, HashSet s, int root_data) +{ +/* Base condition*/ + + if (node == null) + return false; +/* Check if current node makes a pair with any of the + existing elements in set.*/ + + int rem = root_data - node.data; + if (s.contains(rem)) + return true; +/* Insert current node in set*/ + + s.add(node.data); +/* If result returned by either left or right child is + true, return true.*/ + + boolean res = printPathUtil(node.left, s, root_data) || + printPathUtil(node.right, s, root_data); +/* Remove current node from hash table*/ + + s.remove(node.data); + return res; +} +/*A wrapper over printPathUtil()*/ + +static boolean isPathSum(Node root) +{ +/*create an empty hash table*/ + +HashSet s = new HashSet(); +/*Recursively check in left and right subtrees.*/ + +return printPathUtil(root.left, s, root.data) || + printPathUtil(root.right, s, root.data); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = newnode(8); + root.left = newnode(5); + root.right = newnode(4); + root.left.left = newnode(9); + root.left.right = newnode(7); + root.left.right.left = newnode(1); + root.left.right.right = newnode(12); + root.left.right.right.right = newnode(2); + root.right.right = newnode(11); + root.right.right.left = newnode(3); + System.out.print(isPathSum(root)==true ?""Yes"" : ""No""); +} +}"," '''Python3 program to find if there is a +pair in any root to leaf path with sum +equals to root's key''' + + + '''A binary tree node has data, pointer to +left child and a pointer to right child''' ''' utility that allocates a new node with the +given data and None left and right pointers. ''' + +class newnode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''Function to prroot to leaf path which +satisfies the condition''' + +def printPathUtil(node, s, root_data) : + ''' Base condition''' + + if (node == None) : + return False + ''' Check if current node makes a pair + with any of the existing elements in set.''' + + rem = root_data - node.data + if rem in s: + return True + ''' Insert current node in set''' + + s.add(node.data) + ''' If result returned by either left or + right child is True, return True.''' + + res = printPathUtil(node.left, s, root_data) or \ + printPathUtil(node.right, s, root_data) + ''' Remove current node from hash table''' + + s.remove(node.data) + return res + '''A wrapper over printPathUtil()''' + +def isPathSum(root) : + ''' create an empty hash table''' + + s = set() + ''' Recursively check in left and right subtrees.''' + + return printPathUtil(root.left, s, root.data) or \ + printPathUtil(root.right, s, root.data) + '''Driver Code''' + +if __name__ == '__main__': + root = newnode(8) + root.left = newnode(5) + root.right = newnode(4) + root.left.left = newnode(9) + root.left.right = newnode(7) + root.left.right.left = newnode(1) + root.left.right.right = newnode(12) + root.left.right.right.right = newnode(2) + root.right.right = newnode(11) + root.right.right.left = newnode(3) + print(""Yes"") if (isPathSum(root)) else print(""No"")" +Minimum insertions to form a palindrome with permutations allowed,"/*Java program to find minimum number +of insertions to make a string +palindrome*/ + +public class Palindrome { +/* Function will return number of + characters to be added*/ + + static int minInsertion(String str) + { +/* To store string length*/ + + int n = str.length(); +/* To store number of characters + occurring odd number of times*/ + + int res = 0; +/* To store count of each + character*/ + + int[] count = new int[26]; +/* To store occurrence of each + character*/ + + for (int i = 0; i < n; i++) + count[str.charAt(i) - 'a']++; +/* To count characters with odd + occurrence*/ + + for (int i = 0; i < 26; i++) { + if (count[i] % 2 == 1) + res++; + } +/* As one character can be odd return + res - 1 but if string is already + palindrome return 0*/ + + return (res == 0) ? 0 : res - 1; + } +/* Driver program*/ + + public static void main(String[] args) + { + String str = ""geeksforgeeks""; + System.out.println(minInsertion(str)); + } +}"," '''Python3 program to find minimum number +of insertions to make a string +palindrome''' + +import math as mt + '''Function will return number of +characters to be added''' + +def minInsertion(tr1): + ''' To store str1ing length''' + + n = len(str1) + ''' To store number of characters + occurring odd number of times''' + + res = 0 + ''' To store count of each + character''' + + count = [0 for i in range(26)] + ''' To store occurrence of each + character''' + + for i in range(n): + count[ord(str1[i]) - ord('a')] += 1 + ''' To count characters with odd + occurrence''' + + for i in range(26): + if (count[i] % 2 == 1): + res += 1 + ''' As one character can be odd return + res - 1 but if str1ing is already + palindrome return 0''' + + if (res == 0): + return 0 + else: + return res - 1 + '''Driver Code''' + +str1 = ""geeksforgeeks"" +print(minInsertion(str1))" +"Given two unsorted arrays, find all pairs whose sum is x","/*JAVA Code for Given two unsorted arrays, +find all pairs whose sum is x*/ + +import java.util.*; +class GFG { +/* Function to find all pairs in both arrays + whose sum is equal to given value x*/ + + public static void findPairs(int arr1[], int arr2[], + int n, int m, int x) + { +/* Insert all elements of first array in a hash*/ + + HashMap s = new HashMap(); + for (int i = 0; i < n; i++) + s.put(arr1[i], 0); +/* Subtract sum from second array elements one + by one and check it's present in array first + or not*/ + + for (int j = 0; j < m; j++) + if (s.containsKey(x - arr2[j])) + System.out.println(x - arr2[j] + "" "" + arr2[j]); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr1[] = { 1, 0, -4, 7, 6, 4 }; + int arr2[] = { 0, 2, 4, -3, 2, 1 }; + int x = 8; + findPairs(arr1, arr2, arr1.length, arr2.length, x); + } +}"," '''Python3 program to find all +pair in both arrays whose +sum is equal to given value x + ''' '''Function to find all pairs +in both arrays whose sum is +equal to given value x''' + +def findPairs(arr1, arr2, n, m, x): + ''' Insert all elements of + first array in a hash''' + + s = set() + for i in range (0, n): + s.add(arr1[i]) + ''' Subtract sum from second + array elements one by one + and check it's present in + array first or not''' + + for j in range(0, m): + if ((x - arr2[j]) in s): + print((x - arr2[j]), '', arr2[j]) + '''Driver code''' + +arr1 = [1, 0, -4, 7, 6, 4] +arr2 = [0, 2, 4, -3, 2, 1] +x = 8 +n = len(arr1) +m = len(arr2) +findPairs(arr1, arr2, n, m, x)" +Count natural numbers whose all permutation are greater than that number,"/*Java program to count the number less than N, +whose all permutation is greater +than or equal to the number.*/ + +import java.util.Stack; +class GFG +{ +/* Return the count of the number having all + permutation greater than or equal to the number.*/ + + static int countNumber(int n) + { + int result = 0; +/* Pushing 1 to 9 because all number from 1 + to 9 have this property.*/ + + Stack s = new Stack<>(); + for (int i = 1; i <= 9; i++) + { + if (i <= n) + { + s.push(i); + result++; + } +/* take a number from stack and add + a digit smaller than last digit + of it.*/ + + while (!s.empty()) + { + int tp = s.peek(); + s.pop(); + for (int j = tp % 10; j <= 9; j++) + { + int x = tp * 10 + j; + if (x <= n) { + s.push(x); + result++; + } + } + } + } + return result; + } +/* Driven Code*/ + + public static void main(String[] args) + { + int n = 15; + System.out.println(countNumber(n)); + } +}"," '''Python3 program to count the number less +than N, whose all permutation is greater +than or equal to the number. + ''' '''Return the count of the number having +all permutation greater than or equal +to the number.''' + +def countNumber(n): + result = 0 + ''' Pushing 1 to 9 because all number + from 1 to 9 have this property.''' + + s = [] + for i in range(1, 10): + if (i <= n): + s.append(i) + result += 1 + ''' take a number from stack and add + a digit smaller than last digit + of it.''' + + while len(s) != 0: + tp = s[-1] + s.pop() + for j in range(tp % 10, 10): + x = tp * 10 + j + if (x <= n): + s.append(x) + result += 1 + return result + '''Driver Code''' + +if __name__ == '__main__': + n = 15 + print(countNumber(n))" +"Reduce the given Array of [1, N] by rotating left or right based on given conditions","/*Java program for the above approach*/ + +import java.io.*; + +class GFG +{ + +/* Function to find the last element +left after performing N - 1 queries +of type X*/ + +static int rotate(int arr[], int N, int X) +{ + +/* Stores the next power of 2*/ + + long nextPower = 1; + +/* Iterate until nextPower is at most N*/ + + while (nextPower <= N) + nextPower *= 2; + +/* If X is equal to 1*/ + + if (X == 1) + return (int) nextPower - N; + +/* Stores the power of 2 less than or + equal to N*/ + + long prevPower = nextPower / 2; + +/* Return the final value*/ + + return 2 * (N - (int)prevPower) + 1; +} + +/*Driver Code*/ + + public static void main (String[] args) { + int arr[] = { 1, 2, 3, 4, 5 }; + int X = 1; + int N =arr.length; + + System.out.println(rotate(arr, N, X)); + + } +} + + +"," '''Python3 program for the above approach''' + + + '''Function to find the last element +left after performing N - 1 queries +of type X''' + +def rotate(arr, N, X): + ''' Stores the next power of 2''' + + nextPower = 1 + + ''' Iterate until nextPower is at most N''' + + while (nextPower <= N): + nextPower *= 2 + + ''' If X is equal to 1''' + + if (X == 1): + ans = nextPower - N + return ans + + ''' Stores the power of 2 less than or + equal to N''' + + prevPower = nextPower // 2 + + ''' Return the final value''' + + return 2 * (N - prevPower) + 1 + + + '''Driver Code''' + +arr = [1, 2, 3, 4, 5] +X = 1 +N = len(arr) +print(rotate(arr, N, X)) + + +" +Generating numbers that are divisor of their right-rotations,"/*Java program to Generating numbers that +are divisor of their right-rotations*/ + +import java.util.*; +import java.io.*; + +class GFG +{ + +/* Function to generate m-digit + numbers which are divisor of + their right-rotation*/ + + static void generateNumbers(int m) + { + ArrayList numbers = new ArrayList<>(); + int k_max, x; + + for (int y = 0; y < 10; y++) + { + + k_max = (int)(Math.pow(10,m-2) * (10 * y + 1)) / + (int)(Math.pow(10, m-1) + y); + + for (int k = 1; k <= k_max; k++) + { + x = (int)(y*(Math.pow(10,m-1)-k)) / (10 * k -1); + + if ((int)(y*(Math.pow(10,m-1)-k)) % (10 * k -1) == 0) + numbers.add(10 * x + y); + } + + } + + Collections.sort(numbers); + for (int i = 0; i < numbers.size(); i++) + System.out.println(numbers.get(i)); + } + +/* Driver code*/ + + public static void main(String args[]) + { + int m = 3; + generateNumbers(m); + } +} + + +"," '''Python program to Generating numbers that +are divisor of their right-rotations''' + +from math import log10 + + '''Function to generate m-digit +numbers which are divisor of +their right-rotation''' + +def generateNumbers(m): + numbers = [] + + for y in range(1, 10): + k_max = ((10 ** (m - 2) * + (10 * y + 1)) // + (10 ** (m - 1) + y)) + + for k in range(1, k_max + 1): + x = ((y * (10 ** (m - 1) - k)) + // (10 * k - 1)) + + if ((y * (10 ** (m - 1) - k)) + % (10 * k - 1) == 0): + numbers.append(10 * x + y) + + for n in sorted(numbers): + print(n) + + '''Driver code''' + +m = 3 +generateNumbers(m) +" +Minimum number of bracket reversals needed to make an expression balanced,"/*Java Code to count minimum reversal for +making an expression balanced.*/ + +import java.util.Stack; +public class GFG +{ +/* Method count minimum reversal for + making an expression balanced. + Returns -1 if expression cannot be balanced*/ + + static int countMinReversals(String expr) + { + int len = expr.length(); +/* length of expression must be even to make + it balanced by using reversals.*/ + + if (len%2 != 0) + return -1; +/* After this loop, stack contains unbalanced + part of expression, i.e., expression of the + form ""}}..}{{..{""*/ + + Stack s=new Stack<>(); + for (int i=0; i y) ? x : y; } + +/* This function returns the sum of elements on maximum + path from beginning to end*/ + + int maxPathSum(int ar1[], int ar2[], int m, int n) + { +/* initialize indexes for ar1[] and ar2[]*/ + + int i = 0, j = 0; + +/* Initialize result and current sum through ar1[] + and ar2[].*/ + + int result = 0, sum1 = 0, sum2 = 0; + +/* Below 3 loops are similar to merge in merge sort*/ + + while (i < m && j < n) + { +/* Add elements of ar1[] to sum1*/ + + if (ar1[i] < ar2[j]) + sum1 += ar1[i++]; + +/* Add elements of ar2[] to sum2*/ + + else if (ar1[i] > ar2[j]) + sum2 += ar2[j++]; + +/* we reached a common point*/ + + else + { +/* Take the maximum of two sums and add to + result + Also add the common element of array, once*/ + + result += max(sum1, sum2) + ar1[i]; + +/* Update sum1 and sum2 for elements after this + intersection point*/ + + sum1 = 0; + sum2 = 0; + +/* update i and j to move to next element of each array*/ + + i++; + j++; + } + } + +/* Add remaining elements of ar1[]*/ + + while (i < m) + sum1 += ar1[i++]; + +/* Add remaining elements of ar2[]*/ + + while (j < n) + sum2 += ar2[j++]; + +/* Add maximum of two sums of remaining elements*/ + + result += max(sum1, sum2); + + return result; + } + +/* Driver code*/ + + public static void main(String[] args) + { + MaximumSumPath sumpath = new MaximumSumPath(); + int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 }; + int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 }; + int m = ar1.length; + int n = ar2.length; + +/* Function call*/ + + System.out.println( + ""Maximum sum path is :"" + + sumpath.maxPathSum(ar1, ar2, m, n)); + } +} + + +"," '''Python program to find maximum sum path''' + + + '''This function returns the sum of elements on maximum path from +beginning to end''' + + + +def maxPathSum(ar1, ar2, m, n): + + ''' initialize indexes for ar1[] and ar2[]''' + + i, j = 0, 0 + + ''' Initialize result and current sum through ar1[] and ar2[]''' + + result, sum1, sum2 = 0, 0, 0 + + ''' Below 3 loops are similar to merge in merge sort''' + + while (i < m and j < n): + + ''' Add elements of ar1[] to sum1''' + + if ar1[i] < ar2[j]: + sum1 += ar1[i] + i += 1 + + ''' Add elements of ar2[] to sum2''' + + elif ar1[i] > ar2[j]: + sum2 += ar2[j] + j += 1 + + '''we reached a common point''' + + else: + + ''' Take the maximum of two sums and add to result''' + + result += max(sum1, sum2) +ar1[i] + ''' update sum1 and sum2 to be considered fresh for next elements''' + + sum1 = 0 + sum2 = 0 + ''' update i and j to move to next element in each array''' + + i +=1 + j +=1 + + + + ''' Add remaining elements of ar1[]''' + + while i < m: + sum1 += ar1[i] + i += 1 + ''' Add remaining elements of b[]''' + + while j < n: + sum2 += ar2[j] + j += 1 + + ''' Add maximum of two sums of remaining elements''' + + result += max(sum1, sum2) + + return result + + + '''Driver code''' + +ar1 = [2, 3, 7, 10, 12, 15, 30, 34] +ar2 = [1, 5, 7, 8, 10, 15, 16, 19] +m = len(ar1) +n = len(ar2) + + '''Function call''' + +print ""Maximum sum path is"", maxPathSum(ar1, ar2, m, n) + + +" +Convert a tree to forest of even nodes,"/*Java program to find maximum number to be removed +to convert a tree into forest containing trees of +even number of nodes*/ + +import java.util.*; +class GFG +{ + static int N = 12,ans; + static Vector> tree=new Vector>(); +/* Return the number of nodes of subtree having + node as a root.*/ + + static int dfs( int visit[], int node) + { + int num = 0, temp = 0; +/* Mark node as visited.*/ + + visit[node] = 1; +/* Traverse the adjacency list to find non- + visited node.*/ + + for (int i = 0; i < tree.get(node).size(); i++) + { + if (visit[tree.get(node).get(i)] == 0) + { +/* Finding number of nodes of the subtree + of a subtree.*/ + + temp = dfs( visit, tree.get(node).get(i)); +/* If nodes are even, increment number of + edges to removed. + Else leave the node as child of subtree.*/ + + if(temp%2!=0) + num += temp; + else + ans++; + } + } + return num+1; + } +/* Return the maximum number of edge to remove + to make forest.*/ + + static int minEdge( int n) + { + int visit[] = new int[n+2]; + ans = 0; + dfs( visit, 1); + return ans; + } +/* Driven Program*/ + + public static void main(String args[]) + { + int n = 10; + for(int i = 0; i < n + 2;i++) + tree.add(new Vector()); + tree.get(1).add(3); + tree.get(3).add(1); + tree.get(1).add(6); + tree.get(6).add(1); + tree.get(1).add(2); + tree.get(2).add(1); + tree.get(3).add(4); + tree.get(4).add(3); + tree.get(6).add(8); + tree.get(8).add(6); + tree.get(2).add(7); + tree.get(7).add(2); + tree.get(2).add(5); + tree.get(5).add(2); + tree.get(4).add(9); + tree.get(9).add(4); + tree.get(4).add(10); + tree.get(10).add(4); + System.out.println( minEdge( n)); + } +}"," '''Python3 program to find maximum +number to be removed to convert +a tree into forest containing trees +of even number of nodes''' + + '''Return the number of nodes of +subtree having node as a root.''' + +def dfs(tree, visit, ans, node): + num = 0 + temp = 0 ''' Mark node as visited.''' + + visit[node] = 1 + ''' Traverse the adjacency list + to find non-visited node.''' + + for i in range(len(tree[node])): + if (visit[tree[node][i]] == 0): + ''' Finding number of nodes of + the subtree of a subtree.''' + + temp = dfs(tree, visit, ans, + tree[node][i]) + ''' If nodes are even, increment + number of edges to removed. + Else leave the node as child + of subtree.''' + + if(temp % 2): + num += temp + else: + ans[0] += 1 + return num + 1 + '''Return the maximum number of +edge to remove to make forest.''' + +def minEdge(tree, n): + visit = [0] * (n + 2) + ans = [0] + dfs(tree, visit, ans, 1) + return ans[0] + '''Driver Code''' + +N = 12 +n = 10 +tree = [[] for i in range(n + 2)] +tree[1].append(3) +tree[3].append(1) +tree[1].append(6) +tree[6].append(1) +tree[1].append(2) +tree[2].append(1) +tree[3].append(4) +tree[4].append(3) +tree[6].append(8) +tree[8].append(6) +tree[2].append(7) +tree[7].append(2) +tree[2].append(5) +tree[5].append(2) +tree[4].append(9) +tree[9].append(4) +tree[4].append(10) +tree[10].append(4) +print(minEdge(tree, n))" +Find a Fixed Point (Value equal to index) in a given array,"/*Java program to check fixed point +in an array using binary search*/ + +class Main +{ + static int binarySearch(int arr[], int low, int high) + { + if(high >= low) + { + /* low + (high - low)/2; */ + + int mid = (low + high)/2; + if(mid == arr[mid]) + return mid; + if(mid > arr[mid]) + return binarySearch(arr, (mid + 1), high); + else + return binarySearch(arr, low, (mid -1)); + } + /* Return -1 if there is + no Fixed Point */ + + return -1; + } +/* main function*/ + + public static void main(String args[]) + { + int arr[] = {-10, -1, 0, 3 , 10, 11, 30, 50, 100}; + int n = arr.length; + System.out.println(""Fixed Point is "" + + binarySearch(arr,0, n-1)); + } +}"," '''Python program to check fixed point +in an array using binary search''' + +def binarySearch(arr,low, high): + if high >= low: + mid = (low + high)//2 + if mid is arr[mid]: + return mid + if mid > arr[mid]: + return binarySearch(arr, (mid + 1), high) + else: + return binarySearch(arr, low, (mid -1)) + ''' Return -1 if there is no Fixed Point''' + + return -1 + '''Driver program to check above functions */''' + +arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100] +n = len(arr) +print(""Fixed Point is "" + str(binarySearch(arr, 0, n-1)))" +Find three element from different three arrays such that a + b + c = sum,"/*Java program to find three element +from different three arrays such +that a + b + c is equal to +given sum*/ + +class GFG +{ +/* Function to check if there is + an element from each array such + that sum of the three elements + is equal to given sum.*/ + + static boolean findTriplet(int a1[], int a2[], + int a3[], int n1, + int n2, int n3, int sum) + { + for (int i = 0; i < n1; i++) + for (int j = 0; j < n2; j++) + for (int k = 0; k < n3; k++) + if (a1[i] + a2[j] + a3[k] == sum) + return true; + return false; + } +/* Driver code*/ + + public static void main (String[] args) + { + int a1[] = { 1 , 2 , 3 , 4 , 5 }; + int a2[] = { 2 , 3 , 6 , 1 , 2 }; + int a3[] = { 3 , 2 , 4 , 5 , 6 }; + int sum = 9; + int n1 = a1.length; + int n2 = a2.length; + int n3 = a3.length; + if(findTriplet(a1, a2, a3, n1, n2, n3, sum)) + System.out.print(""Yes""); + else + System.out.print(""No""); + } +}"," '''Python3 program to find +three element from different +three arrays such that +a + b + c is equal to +given sum + ''' '''Function to check if there +is an element from each +array such that sum of the +three elements is equal to +given sum.''' + +def findTriplet(a1, a2, a3, + n1, n2, n3, sum): + for i in range(0 , n1): + for j in range(0 , n2): + for k in range(0 , n3): + if (a1[i] + a2[j] + + a3[k] == sum): + return True + return False + '''Driver Code''' + +a1 = [ 1 , 2 , 3 , 4 , 5 ] +a2 = [ 2 , 3 , 6 , 1 , 2 ] +a3 = [ 3 , 2 , 4 , 5 , 6 ] +sum = 9 +n1 = len(a1) +n2 = len(a2) +n3 = len(a3) +print(""Yes"") if findTriplet(a1, a2, a3, + n1, n2, n3, + sum) else print(""No"")" +Print leftmost and rightmost nodes of a Binary Tree,"/*Java program to print corner node at each level in a binary tree*/ + + +import java.util.*; + +/* A binary tree node has key, pointer to left + child and a pointer to right child */ + +class Node +{ + int key; + Node left, right; + + public Node(int key) + { + this.key = key; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + + /* Function to print corner node at each level */ + + void printCorner(Node root) + { +/* star node is for keeping track of levels*/ + + Queue q = new LinkedList(); + +/* pushing root node and star node*/ + + q.add(root); +/* Do level order traversal of Binary Tree*/ + + while (!q.isEmpty()) + { +/* n is the no of nodes in current Level*/ + + int n = q.size(); + for(int i = 0 ; i < n ; i++){ + Node temp = q.peek(); + q.poll(); +/* If it is leftmost corner value or rightmost corner value then print it*/ + + if(i==0 || i==n-1) + System.out.print(temp.key + "" ""); +/* push the left and right children of the temp node*/ + + if (temp.left != null) + q.add(temp.left); + if (temp.right != null) + q.add(temp.right); + } + } + + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(15); + tree.root.left = new Node(10); + tree.root.right = new Node(20); + tree.root.left.left = new Node(8); + tree.root.left.right = new Node(12); + tree.root.right.left = new Node(16); + tree.root.right.right = new Node(25); + + tree.printCorner(tree.root); + } +} + + +"," '''Python3 program to print corner +node at each level of binary tree''' + +from collections import deque + + '''A binary tree node has key, pointer to left +child and a pointer to right child''' + +class Node: + def __init__(self, key): + + self.key = key + self.left = None + self.right = None + + '''Function to print corner node at each level''' + +def printCorner(root: Node): + + ''' If the root is null then simply return''' + + if root == None: + return + + ''' star node is for keeping track of levels''' + + + q = deque() ''' pushing root node and star node''' + + q.append(root) + + ''' Do level order traversal + using a single queue''' + + + while q: + ''' n denotes the size of the current + level in the queue''' + + n = len(q) + for i in range(n): + temp = q[0] + q.popleft() + + ''' If it is leftmost corner value or + rightmost corner value then print it''' + + if i == 0 or i == n - 1: + print(temp.key, end = "" "") + + ''' push the left and right children + of the temp node''' + + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + + '''Driver Code''' + +if __name__ == ""__main__"": + + root = Node(15) + root.left = Node(10) + root.right = Node(20) + root.left.left = Node(8) + root.left.right = Node(12) + root.right.left = Node(16) + root.right.right = Node(25) + + printCorner(root) + + +" +Ways to color a skewed tree such that parent and child have different colors,"/*Java program to count number of ways to color +a N node skewed tree with k colors such that +parent and children have different colors.*/ + +import java.io.*; +class GFG { +/* fast_way is recursive + method to calculate power*/ + + static int fastPow(int N, int K) + { + if (K == 0) + return 1; + int temp = fastPow(N, K / 2); + if (K % 2 == 0) + return temp * temp; + else + return N * temp * temp; + } + static int countWays(int N, int K) + { + return K * fastPow(K - 1, N - 1); + } +/* Driver program*/ + + public static void main(String[] args) + { + int N = 3, K = 3; + System.out.println(countWays(N, K)); + } +}"," '''Python3 program to count +number of ways to color +a N node skewed tree with +k colors such that parent +and children have different +colors.''' + + '''fast_way is recursive +method to calculate power''' + +def fastPow(N, K): + if (K == 0): + return 1; + temp = fastPow(N, int(K / 2)); + if (K % 2 == 0): + return temp * temp; + else: + return N * temp * temp; +def countWays(N, K): + return K * fastPow(K - 1, N - 1); '''Driver Code''' + +N = 3; +K = 3; +print(countWays(N, K));" +Count of index pairs with equal elements in an array,"/*Java program to count of pairs with equal +elements in an array.*/ + +class GFG { +/* Return the number of pairs with equal + values.*/ + + static int countPairs(int arr[], int n) + { + int ans = 0; +/* for each index i and j*/ + + for (int i = 0; i < n; i++) + for (int j = i+1; j < n; j++) +/* finding the index with same + value but different index.*/ + + if (arr[i] == arr[j]) + ans++; + return ans; + } +/* driver code*/ + + public static void main (String[] args) + { + int arr[] = { 1, 1, 2 }; + int n = arr.length; + System.out.println(countPairs(arr, n)); + } +}"," '''Python3 program to +count of pairs with equal +elements in an array. + ''' '''Return the number of +pairs with equal values.''' + +def countPairs(arr, n): + ans = 0 + ''' for each index i and j''' + + for i in range(0 , n): + for j in range(i + 1, n): + ''' finding the index + with same value but + different index.''' + + if (arr[i] == arr[j]): + ans += 1 + return ans + '''Driven Code''' + +arr = [1, 1, 2 ] +n = len(arr) +print(countPairs(arr, n))" +Number of indexes with equal elements in given range,"/*Java program to count the number of +indexes in range L R such that +Ai = Ai+1*/ + +class GFG { +/* function that answers every query + in O(r-l)*/ + + static int answer_query(int a[], int n, + int l, int r) + { +/* traverse from l to r and count + the required indexes*/ + + int count = 0; + for (int i = l; i < r; i++) + if (a[i] == a[i + 1]) + count += 1; + return count; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = {1, 2, 2, 2, 3, 3, 4, 4, 4}; + int n = a.length; +/* 1-st query*/ + + int L, R; + L = 1; + R = 8; + System.out.println( + answer_query(a, n, L, R)); +/* 2nd query*/ + + L = 0; + R = 4; + System.out.println( + answer_query(a, n, L, R)); + } +} +"," '''Python 3 program to count the +number of indexes in range L R +such that Ai = Ai + 1''' + + '''function that answers every +query in O(r-l)''' + +def answer_query(a, n, l, r): ''' traverse from l to r and + count the required indexes''' + + count = 0 + for i in range(l, r): + if (a[i] == a[i + 1]): + count += 1 + return count + '''Driver Code''' + +a = [1, 2, 2, 2, 3, 3, 4, 4, 4] +n = len(a) + '''1-st query''' + +L = 1 +R = 8 +print(answer_query(a, n, L, R)) + '''2nd query''' + +L = 0 +R = 4 +print(answer_query(a, n, L, R))" +Connect nodes at same level using constant extra space,"/*Iterative Java program to connect nodes at same level +using constant extra space*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right, nextRight; + Node(int item) + { + data = item; + left = right = nextRight = null; + } +} +class BinaryTree +{ + Node root;/* This function returns the leftmost child of nodes at the same level + as p. This function is used to getNExt right of p's right child + If right child of is NULL then this can also be used for the + left child */ + + Node getNextRight(Node p) + { + Node temp = p.nextRight; + /* Traverse nodes at p's level and find and return + the first node's first child */ + + while (temp != null) + { + if (temp.left != null) + return temp.left; + if (temp.right != null) + return temp.right; + temp = temp.nextRight; + } +/* If all the nodes at p's level are leaf nodes then return NULL*/ + + return null; + } + /* Sets nextRight of all nodes of a tree with root as p */ + + void connect(Node p) { + Node temp = null; + if (p == null) + return; +/* Set nextRight for root*/ + + p.nextRight = null; +/* set nextRight of all levels one by one*/ + + while (p != null) + { + Node q = p; + /* Connect all childrem nodes of p and children nodes of all other + nodes at same level as p */ + + while (q != null) + { +/* Set the nextRight pointer for p's left child*/ + + if (q.left != null) + { +/* If q has right child, then right child is nextRight of + p and we also need to set nextRight of right child*/ + + if (q.right != null) + q.left.nextRight = q.right; + else + q.left.nextRight = getNextRight(q); + } + if (q.right != null) + q.right.nextRight = getNextRight(q); +/* Set nextRight for other nodes in pre order fashion*/ + + q = q.nextRight; + } +/* start from the first node of next level*/ + + if (p.left != null) + p = p.left; + else if (p.right != null) + p = p.right; + else + p = getNextRight(p); + } + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + /* Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 90 + */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.right.right = new Node(90); +/* Populates nextRight pointer in all nodes*/ + + tree.connect(tree.root); +/* Let us check the values of nextRight pointers*/ + + int a = tree.root.nextRight != null ? + tree.root.nextRight.data : -1; + int b = tree.root.left.nextRight != null ? + tree.root.left.nextRight.data : -1; + int c = tree.root.right.nextRight != null ? + tree.root.right.nextRight.data : -1; + int d = tree.root.left.left.nextRight != null ? + tree.root.left.left.nextRight.data : -1; + int e = tree.root.right.right.nextRight != null ? + tree.root.right.right.nextRight.data : -1; + System.out.println(""Following are populated nextRight pointers in "" + + "" the tree(-1 is printed if there is no nextRight)""); + System.out.println(""nextRight of "" + tree.root.data + "" is "" + a); + System.out.println(""nextRight of "" + tree.root.left.data + + "" is "" + b); + System.out.println(""nextRight of "" + tree.root.right.data + + "" is "" + c); + System.out.println(""nextRight of "" + tree.root.left.left.data + + "" is "" + d); + System.out.println(""nextRight of "" + tree.root.right.right.data + + "" is "" + e); + } +}"," '''Iterative Python program to connect nodes +at same level using constant extra space ''' + '''Helper class that allocates a new node +with the given data and None left and +right pointers. ''' + +class newnode: + def __init__(self,data): + self.data = data + self.left = None + self.right = None + self.nextRight = None + '''This function returns the leftmost child of +nodes at the same level as p. This function +is used to getNExt right of p's right child +If right child of is None then this can also +be used for the left child ''' + +def getNextRight(p): + temp = p.nextRight + ''' Traverse nodes at p's level and find + and return the first node's first child ''' + + while (temp != None): + if (temp.left != None): + return temp.left + if (temp.right != None): + return temp.right + temp = temp.nextRight + ''' If all the nodes at p's level are + leaf nodes then return None ''' + + return None + '''Sets nextRight of all nodes of a tree +with root as p ''' + +def connect(p): + temp = None + if (not p): + return + ''' Set nextRight for root ''' + + p.nextRight = None + ''' set nextRight of all levels one by one ''' + + while (p != None): + q = p + ''' Connect all childrem nodes of p and + children nodes of all other nodes + at same level as p ''' + + while (q != None): + ''' Set the nextRight pointer for + p's left child ''' + + if (q.left): + ''' If q has right child, then right + child is nextRight of p and we + also need to set nextRight of + right child ''' + + if (q.right): + q.left.nextRight = q.right + else: + q.left.nextRight = getNextRight(q) + if (q.right): + q.right.nextRight = getNextRight(q) + ''' Set nextRight for other nodes in + pre order fashion ''' + + q = q.nextRight + ''' start from the first node + of next level ''' + + if (p.left): + p = p.left + elif (p.right): + p = p.right + else: + p = getNextRight(p) + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 10 + / \ + 8 2 + / \ + 3 90 ''' + + root = newnode(10) + root.left = newnode(8) + root.right = newnode(2) + root.left.left = newnode(3) + root.right.right = newnode(90) + ''' Populates nextRight pointer in all nodes ''' + + connect(root) + ''' Let us check the values of nextRight pointers ''' + + print(""Following are populated nextRight "" + ""pointers in the tree (-1 is printed "" + ""if there is no nextRight) \n"") + print(""nextRight of"", root.data, + ""is"", end = "" "") + if root.nextRight: + print(root.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.data, + ""is"", end = "" "") + if root.left.nextRight: + print(root.left.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.right.data, + ""is"", end = "" "") + if root.right.nextRight: + print(root.right.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.left.data, + ""is"", end = "" "") + if root.left.left.nextRight: + print(root.left.left.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.right.right.data, + ""is"", end = "" "") + if root.right.right.nextRight: + print(root.right.right.nextRight.data) + else: + print(-1)" +Find the subarray with least average,"/*A Simple Java program to find +minimum average subarray*/ + +class Test { + static int arr[] = new int[] { 3, 7, 90, 20, 10, 50, 40 }; +/* Prints beginning and ending indexes of subarray + of size k with minimum average*/ + + static void findMinAvgSubarray(int n, int k) + { +/* k must be smaller than or equal to n*/ + + if (n < k) + return; +/* Initialize beginning index of result*/ + + int res_index = 0; +/* Compute sum of first subarray of size k*/ + + int curr_sum = 0; + for (int i = 0; i < k; i++) + curr_sum += arr[i]; +/* Initialize minimum sum as current sum*/ + + int min_sum = curr_sum; +/* Traverse from (k+1)'th element to n'th element*/ + + for (int i = k; i < n; i++) + { +/* Add current item and remove first + item of previous subarray*/ + + curr_sum += arr[i] - arr[i - k]; +/* Update result if needed*/ + + if (curr_sum < min_sum) { + min_sum = curr_sum; + res_index = (i - k + 1); + } + } + System.out.println(""Subarray between ["" + + res_index + "", "" + (res_index + k - 1) + + ""] has minimum average""); + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { +/*Subarray size*/ + +int k = 3; + findMinAvgSubarray(arr.length, k); + } +}"," '''Python3 program to find +minimum average subarray + ''' '''Prints beginning and ending +indexes of subarray of size k +with minimum average''' + +def findMinAvgSubarray(arr, n, k): + ''' k must be smaller than or equal to n''' + + if (n < k): return 0 + ''' Initialize beginning index of result''' + + res_index = 0 + ''' Compute sum of first subarray of size k''' + + curr_sum = 0 + for i in range(k): + curr_sum += arr[i] + ''' Initialize minimum sum as current sum''' + + min_sum = curr_sum + ''' Traverse from (k + 1)'th + element to n'th element''' + + for i in range(k, n): + ''' Add current item and remove first + item of previous subarray''' + + curr_sum += arr[i] - arr[i-k] + ''' Update result if needed''' + + if (curr_sum < min_sum): + min_sum = curr_sum + res_index = (i - k + 1) + print(""Subarray between ["", res_index, + "", "", (res_index + k - 1), + ""] has minimum average"") + '''Driver Code''' + +arr = [3, 7, 90, 20, 10, 50, 40] + '''Subarray size''' + +k = 3 +n = len(arr) +findMinAvgSubarray(arr, n, k)" +Sum of matrix in which each element is absolute difference of its row and column numbers,"/*Java program to find sum of matrix +in which each element is absolute +difference of its corresponding +row and column number row.*/ + +import java.io.*; +public class GFG { +/*Retuen the sum of matrix in which +each element is absolute difference +of its corresponding row and column +number row*/ + +static int findSum(int n) +{ +/* Generate matrix*/ + + int [][]arr = new int[n][n]; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + arr[i][j] = Math.abs(i - j); +/* Compute sum*/ + + int sum = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + sum += arr[i][j]; + return sum; +} +/* Driver Code*/ + + static public void main (String[] args) + { + int n = 3; + System.out.println(findSum(n)); + } +}"," '''Python3 program to find sum of matrix +in which each element is absolute +difference of its corresponding +row and column number row.''' + + '''Return the sum of matrix in which each +element is absolute difference of its +corresponding row and column number row''' + +def findSum(n): ''' Generate matrix''' + + arr = [[0 for x in range(n)] + for y in range (n)] + for i in range (n): + for j in range (n): + arr[i][j] = abs(i - j) + ''' Compute sum''' + + sum = 0 + for i in range (n): + for j in range(n): + sum += arr[i][j] + return sum + '''Driver Code''' + +if __name__ == ""__main__"": + n = 3 + print (findSum(n))" +Sum of nodes on the longest path from root to leaf node,"/*Java implementation to find the sum of nodes +on the longest path from root to leaf node*/ + +public class GFG +{ +/* Node of a binary tree*/ + + static class Node { + int data; + Node left, right; + Node(int data){ + this.data = data; + left = null; + right = null; + } + } + static int maxLen; + static int maxSum; +/* function to find the sum of nodes on the + longest path from root to leaf node*/ + + static void sumOfLongRootToLeafPath(Node root, int sum, + int len) + { +/* if true, then we have traversed a + root to leaf path*/ + + if (root == null) { +/* update maximum length and maximum sum + according to the given conditions*/ + + if (maxLen < len) { + maxLen = len; + maxSum = sum; + } else if (maxLen == len && maxSum < sum) + maxSum = sum; + return; + } +/* recur for left subtree*/ + + sumOfLongRootToLeafPath(root.left, sum + root.data, + len + 1); + +/* recur for right subtree*/ + + sumOfLongRootToLeafPath(root.right, sum + root.data, + len + 1); + }/* utility function to find the sum of nodes on + the longest path from root to leaf node*/ + + static int sumOfLongRootToLeafPathUtil(Node root) + { +/* if tree is NULL, then sum is 0*/ + + if (root == null) + return 0; + maxSum = Integer.MIN_VALUE; + maxLen = 0; +/* finding the maximum sum 'maxSum' for the + maximum length root to leaf path*/ + + sumOfLongRootToLeafPath(root, 0, 0); +/* required maximum sum*/ + + return maxSum; + } +/* Driver program to test above*/ + + public static void main(String args[]) + { +/* binary tree formation*/ + + Node root = new Node(4); /* 4 */ + + root.left = new Node(2); /* / \ */ + + root.right = new Node(5); /* 2 5 */ + + root.left.left = new Node(7); /* / \ / \ */ + + root.left.right = new Node(1); /* 7 1 2 3 */ + + root.right.left = new Node(2); /* 6 */ + root.right.right = new Node(3); + root.left.right.left = new Node(6); + System.out.println( ""Sum = "" + + sumOfLongRootToLeafPathUtil(root)); + } +}"," '''Python3 implementation to find the +Sum of nodes on the longest path +from root to leaf nodes''' + + '''function to get a new node ''' + +class getNode: + def __init__(self, data): ''' put in the data ''' + + self.data = data + self.left = self.right = None + '''function to find the Sum of nodes on the +longest path from root to leaf node ''' + +def SumOfLongRootToLeafPath(root, Sum, Len, + maxLen, maxSum): + ''' if true, then we have traversed a + root to leaf path ''' + + if (not root): + ''' update maximum Length and maximum Sum + according to the given conditions ''' + + if (maxLen[0] < Len): + maxLen[0] = Len + maxSum[0] = Sum + elif (maxLen[0]== Len and + maxSum[0] < Sum): + maxSum[0] = Sum + return + ''' recur for left subtree ''' + + SumOfLongRootToLeafPath(root.left, Sum + root.data, + Len + 1, maxLen, maxSum) + ''' recur for right subtree ''' + + SumOfLongRootToLeafPath(root.right, Sum + root.data, + Len + 1, maxLen, maxSum) + '''utility function to find the Sum of nodes on +the longest path from root to leaf node ''' + +def SumOfLongRootToLeafPathUtil(root): + ''' if tree is NULL, then Sum is 0 ''' + + if (not root): + return 0 + maxSum = [-999999999999] + maxLen = [0] + ''' finding the maximum Sum 'maxSum' for + the maximum Length root to leaf path ''' + + SumOfLongRootToLeafPath(root, 0, 0, + maxLen, maxSum) + ''' required maximum Sum ''' + + return maxSum[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' binary tree formation + 4 ''' + + root = getNode(4) + ''' / \ ''' + + root.left = getNode(2) + ''' 2 5 ''' + + root.right = getNode(5) + ''' / \ / \ ''' + + root.left.left = getNode(7) + '''7 1 2 3 ''' + + root.left.right = getNode(1) + ''' / ''' + + root.right.left = getNode(2) + ''' 6 ''' + + root.right.right = getNode(3) + root.left.right.left = getNode(6) + print(""Sum = "", SumOfLongRootToLeafPathUtil(root))" +Search an Element in Doubly Circular Linked List,"/*Java program to illustrate inserting +a Node in a Cicular Doubly Linked list +in begging, end and middle*/ + +class GFG +{ + +/*Structure of a Node*/ + +static class Node +{ + int data; + Node next; + Node prev; +}; + +/*Function to insert a node at the end*/ + +static Node insertNode(Node start, int value) +{ +/* If the list is empty, create a single node + circular and doubly list*/ + + if (start == null) + { + Node new_node = new Node(); + new_node.data = value; + new_node.next = new_node.prev = new_node; + start = new_node; + return new_node; + } + +/* If list is not empty*/ + + +/* Find last node /*/ + + Node last = (start).prev; + +/* Create Node dynamically*/ + + Node new_node = new Node(); + new_node.data = value; + +/* Start is going to be next of new_node*/ + + new_node.next = start; + +/* Make new node previous of start*/ + + (start).prev = new_node; + +/* Make last preivous of new node*/ + + new_node.prev = last; + +/* Make new node next of old last*/ + + last.next = new_node; + + return start; +} + +/*Function to display the +circular doubly linked list*/ + +static void displayList(Node start) +{ + Node temp = start; + + while (temp.next != start) + { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } + System.out.printf(""%d "", temp.data); +} + +/*Function to search the particular element +from the list*/ + +static int searchList(Node start, int search) +{ +/* Declare the temp variable*/ + + Node temp = start; + +/* Declare other control + variable for the searching*/ + + int count = 0, flag = 0, value; + +/* If start is null return -1*/ + + if(temp == null) + return -1; + else + { +/* Move the temp pointer until, + temp.next doesn't move + start address (Circular Fashion)*/ + + while(temp.next != start) + { +/* Increment count for location*/ + + count++; + +/* If it is found raise the + flag and break the loop*/ + + if(temp.data == search) + { + flag = 1; + count--; + break; + } + +/* Increment temp pointer*/ + + temp = temp.next; + } + +/* Check whether last element in the + list content the value if contain, + raise a flag and increment count*/ + + if(temp.data == search) + { + count++; + flag = 1; + } + +/* If flag is true, then element + found, else not*/ + + if(flag == 1) + System.out.println(""\n""+search +"" found at location ""+ + count); + else + System.out.println(""\n""+search +"" not found""); + } + return -1; +} + +/*Driver code*/ + +public static void main(String args[]) +{ +/* Start with the empty list /*/ + + Node start = null; + +/* Insert 4. So linked list becomes 4.null*/ + + start= insertNode(start, 4); + +/* Insert 5. So linked list becomes 4.5*/ + + start= insertNode(start, 5); + +/* Insert 7. So linked list + becomes 4.5.7*/ + + start= insertNode(start, 7); + +/* Insert 8. So linked list + becomes 4.5.7.8*/ + + start= insertNode(start, 8); + +/* Insert 6. So linked list + becomes 4.5.7.8.6*/ + + start= insertNode(start, 6); + + System.out.printf(""Created circular doubly linked list is: ""); + displayList(start); + + searchList(start, 5); +} +} + + +"," '''Python3 program to illustrate inserting a Node in +a Cicular Doubly Linked list in begging, end +and middle''' + +import math + + '''Structure of a Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to insert a node at the end''' + +def insertNode(start, value): + + ''' If the list is empty, create a single node + circular and doubly list''' + + if (start == None) : + new_node = Node(value) + new_node.data = value + new_node.next = new_node + new_node.prev = new_node + start = new_node + return new_node + + ''' If list is not empty''' + + + ''' Find last node */''' + + last = start.prev + + ''' Create Node dynamically''' + + new_node = Node(value) + new_node.data = value + + ''' Start is going to be next of new_node''' + + new_node.next = start + + ''' Make new node previous of start''' + + (start).prev = new_node + + ''' Make last preivous of new node''' + + new_node.prev = last + + ''' Make new node next of old last''' + + last.next = new_node + return start + + '''Function to display the +circular doubly linked list''' + +def displayList(start): + temp = start + + while (temp.next != start): + print(temp.data, end = "" "") + temp = temp.next + + print(temp.data) + + '''Function to search the particular element +from the list''' + +def searchList(start, search): + + ''' Declare the temp variable''' + + temp = start + + ''' Declare other control + variable for the searching''' + + count = 0 + flag = 0 + value = 0 + + ''' If start is None return -1''' + + if(temp == None): + return -1 + else: + + ''' Move the temp pointer until, + temp.next doesn't move + start address (Circular Fashion)''' + + while(temp.next != start): + + ''' Increment count for location''' + + count = count + 1 + + ''' If it is found raise the + flag and break the loop''' + + if(temp.data == search): + flag = 1 + count = count - 1 + break + + ''' Increment temp pointer''' + + temp = temp.next + + ''' Check whether last element in the + list content the value if contain, + raise a flag and increment count''' + + if(temp.data == search): + count = count + 1 + flag = 1 + + ''' If flag is true, then element + found, else not''' + + if(flag == 1): + print(search,""found at location "", count) + else: + print(search, "" not found"") + + return -1 + + '''Driver code''' + +if __name__=='__main__': + + ''' Start with the empty list */''' + + start = None + + ''' Insert 4. So linked list becomes 4.None''' + + start = insertNode(start, 4) + + ''' Insert 5. So linked list becomes 4.5''' + + start = insertNode(start, 5) + + ''' Insert 7. So linked list + becomes 4.5.7''' + + start = insertNode(start, 7) + + ''' Insert 8. So linked list + becomes 4.5.7.8''' + + start = insertNode(start, 8) + + ''' Insert 6. So linked list + becomes 4.5.7.8.6''' + + start = insertNode(start, 6) + + print(""Created circular doubly linked list is: "", + end = """") + displayList(start) + + searchList(start, 5) + + +" +Print K'th element in spiral form of matrix,"/*Java program for Kth element in spiral +form of matrix*/ + +class GFG { + static int MAX = 100; + /* function for Kth element */ + + static int findK(int A[][], int i, int j, + int n, int m, int k) + { + if (n < 1 || m < 1) + return -1; + /*.....If element is in outermost ring ....*/ + + /* Element is in first row */ + + if (k <= m) + return A[i + 0][j + k - 1]; + /* Element is in last column */ + + if (k <= (m + n - 1)) + return A[i + (k - m)][j + m - 1]; + /* Element is in last row */ + + if (k <= (m + n - 1 + m - 1)) + return A[i + n - 1][j + m - 1 - (k - (m + n - 1))]; + /* Element is in first column */ + + if (k <= (m + n - 1 + m - 1 + n - 2)) + return A[i + n - 1 - (k - (m + n - 1 + m - 1))][j + 0]; + /*.....If element is NOT in outermost ring ....*/ + + /* Recursion for sub-matrix. &A[1][1] is + address to next inside sub matrix.*/ + + return findK(A, i + 1, j + 1, n - 2, + m - 2, k - (2 * n + 2 * m - 4)); + } + /* Driver code */ + + public static void main(String args[]) + { + int a[][] = { { 1, 2, 3, 4, 5, 6 }, + { 7, 8, 9, 10, 11, 12 }, + { 13, 14, 15, 16, 17, 18 } }; + int k = 17; + System.out.println(findK(a, 0, 0, 3, 6, k)); + } +}"," '''Python3 program for Kth element in spiral +form of matrix''' + +MAX = 100 + ''' function for Kth element ''' + +def findK(A, n, m, k): + if (n < 1 or m < 1): + return -1 + '''....If element is in outermost ring ....''' + + ''' Element is in first row ''' + + if (k <= m): + return A[0][k - 1] + ''' Element is in last column ''' + + if (k <= (m + n - 1)): + return A[(k - m)][m - 1] + ''' Element is in last row ''' + + if (k <= (m + n - 1 + m - 1)): + return A[n - 1][m - 1 - (k - (m + n - 1))] + ''' Element is in first column ''' + + if (k <= (m + n - 1 + m - 1 + n - 2)): + return A[n - 1 - (k - (m + n - 1 + m - 1))][0] + '''....If element is NOT in outermost ring ....''' + + ''' Recursion for sub-matrix. &A[1][1] is + address to next inside sub matrix.''' + + A.pop(0) + [j.pop(0) for j in A] + return findK(A, n - 2, m - 2, k - (2 * n + 2 * m - 4)) + ''' Driver code ''' + +a = [[1, 2, 3, 4, 5, 6],[7, 8, 9, 10, 11, 12 ], + [ 13, 14, 15, 16, 17, 18 ]] +k = 17 +print(findK(a, 3, 6, k))" +Find the Deepest Node in a Binary Tree," +/*A Java program to find value of the +deepest node in a given binary tree*/ + +import java.util.*; +/*A tree node with constructor*/ + +public class Node +{ + int data; + Node left, right; +/* constructor*/ + + Node(int key) + { + data = key; + left = null; + right = null; + } +}; +class Gfg +{ +/* Funtion to return the deepest node*/ + + public static Node deepestNode(Node root) + { + Node tmp = null; + if (root == null) + return null; +/* Creating a Queue*/ + + Queue q = new LinkedList(); + q.offer(root); +/* Iterates untill queue become empty*/ + + while (!q.isEmpty()) + { + tmp = q.poll(); + if (tmp.left != null) + q.offer(tmp.left); + if (tmp.right != null) + q.offer(tmp.right); + } + return tmp; + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.left.left = new Node(4); + root.right.left = new Node(5); + root.right.right = new Node(6); + root.right.left.right = new Node(7); + root.right.right.right = new Node(8); + root.right.left.right.left = new Node(9); + Node deepNode = deepestNode(root); + System.out.println(deepNode.data); + } +}"," '''A Python3 program to find value of the +deepest node in a given binary tree by method 3''' + +from collections import deque + + '''A tree node with constructor''' + +class new_Node: + ''' constructor''' + + def __init__(self, key): + self.data = key + self.left = self.right = None ''' Funtion to return the deepest node''' +def deepestNode(root): + node = None + if root == None: + return 0 + + ''' Creating a Queue''' + + q = deque() + q.append(root) + ''' Iterates untill queue become empty''' + + while len(q) != 0: + node = q.popleft() + if node.left is not None: + q.append(node.left) + if node.right is not None: + q.append(node.right) + return node.data '''Driver Code''' + +if __name__ == '__main__': + root = new_Node(1) + root.left = new_Node(2) + root.right = new_Node(3) + root.left.left = new_Node(4) + root.right.left = new_Node(5) + root.right.right = new_Node(6) + root.right.left.right = new_Node(7) + root.right.right.right = new_Node(8) + root.right.left.right.left = new_Node(9) + levels = deepestNode(root) + print(levels) +" +N Queen Problem using Branch And Bound,"/*Java program to solve N Queen Problem +using Branch and Bound*/ + +import java.io.*; +import java.util.Arrays; +class GFG{ +static int N = 8; +/*A utility function to print solution*/ + +static void printSolution(int board[][]) +{ + int N = board.length; + for(int i = 0; i < N; i++) + { + for(int j = 0; j < N; j++) + System.out.printf(""%2d "", board[i][j]); + System.out.printf(""\n""); + } +} +/*A Optimized function to check if a queen +can be placed on board[row][col]*/ + +static boolean isSafe(int row, int col, + int slashCode[][], + int backslashCode[][], + boolean rowLookup[], + boolean slashCodeLookup[], + boolean backslashCodeLookup[]) +{ + if (slashCodeLookup[slashCode[row][col]] || + backslashCodeLookup[backslashCode[row][col]] || + rowLookup[row]) + return false; + return true; +} +/*A recursive utility function to +solve N Queen problem*/ + +static boolean solveNQueensUtil( + int board[][], int col, int slashCode[][], + int backslashCode[][], boolean rowLookup[], + boolean slashCodeLookup[], + boolean backslashCodeLookup[]) +{ +/* Base case: If all queens are placed + then return true*/ + + int N = board.length; + if (col >= N) + return true; +/* Consider this column and try placing + this queen in all rows one by one*/ + + for(int i = 0; i < N; i++) + { +/* Check if queen can be placed on board[i][col]*/ + + if (isSafe(i, col, slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup)) + { +/* Place this queen in board[i][col]*/ + + board[i][col] = 1; + rowLookup[i] = true; + slashCodeLookup[slashCode[i][col]] = true; + backslashCodeLookup[backslashCode[i][col]] = true; +/* recur to place rest of the queens*/ + + if (solveNQueensUtil( + board, col + 1, slashCode, + backslashCode, rowLookup, + slashCodeLookup, + backslashCodeLookup)) + return true; +/* Remove queen from board[i][col]*/ + + board[i][col] = 0; + rowLookup[i] = false; + slashCodeLookup[slashCode[i][col]] = false; + backslashCodeLookup[backslashCode[i][col]] = false; + } + } +/* If queen can not be place in any row + in this colum col then return false*/ + + return false; +} +/* + * This function solves the N Queen problem using Branch + * and Bound. It mainly uses solveNQueensUtil() to solve + * the problem. It returns false if queens cannot be + * placed, otherwise return true and prints placement of + * queens in the form of 1s. Please note that there may + * be more than one solutions, this function prints one + * of the feasible solutions. + */ + +static boolean solveNQueens() +{ + int board[][] = new int[N][N]; +/* Helper matrices*/ + + int slashCode[][] = new int[N][N]; + int backslashCode[][] = new int[N][N]; +/* Arrays to tell us which rows are occupied*/ + + boolean[] rowLookup = new boolean[N]; +/* Keep two arrays to tell us + which diagonals are occupied*/ + + boolean slashCodeLookup[] = new boolean[2 * N - 1]; + boolean backslashCodeLookup[] = new boolean[2 * N - 1]; +/* Initialize helper matrices*/ + + for(int r = 0; r < N; r++) + for(int c = 0; c < N; c++) + { + slashCode[r] = r + c; + backslashCode[r] = r - c + 7; + } + if (solveNQueensUtil(board, 0, slashCode, + backslashCode, rowLookup, + slashCodeLookup, + backslashCodeLookup) == false) + { + System.out.printf(""Solution does not exist""); + return false; + } +/* Solution found*/ + + printSolution(board); + return true; +} +/*Driver code*/ + +public static void main(String[] args) +{ + solveNQueens(); +} +}"," ''' Python3 program to solve N Queen Problem +using Branch or Bound ''' + +N = 8 + ''' A utility function to pri nt solution ''' + +def printSolution(board): + for i in range(N): + for j in range(N): + print(board[i][j], end = "" "") + print() + ''' A Optimized function to check if +a queen can be placed on board[row][col] ''' + +def isSafe(row, col, slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup): + if (slashCodeLookup[slashCode[row][col]] or + backslashCodeLookup[backslashCode[row][col]] or + rowLookup[row]): + return False + return True + ''' A recursive utility function + to solve N Queen problem ''' + +def solveNQueensUtil(board, col, slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup): + ''' base case: If all queens are + placed then return True ''' + + if(col >= N): + return True + + ''' Consider this column and try placing + this queen in all rows one by one''' + + for i in range(N): + ''' Check if queen can be placed on board[i][col]''' + + if(isSafe(i, col, slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup)): ''' Place this queen in board[i][col] ''' + + board[i][col] = 1 + rowLookup[i] = True + slashCodeLookup[slashCode[i][col]] = True + backslashCodeLookup[backslashCode[i][col]] = True + ''' recur to place rest of the queens ''' + + if(solveNQueensUtil(board, col + 1, + slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup)): + return True + ''' Remove queen from board[i][col] ''' + + board[i][col] = 0 + rowLookup[i] = False + slashCodeLookup[slashCode[i][col]] = False + backslashCodeLookup[backslashCode[i][col]] = False + ''' If queen can not be place in any row in + this colum col then return False ''' + + return False + ''' This function solves the N Queen problem using +Branch or Bound. It mainly uses solveNQueensUtil()to +solve the problem. It returns False if queens +cannot be placed,otherwise return True or +prints placement of queens in the form of 1s. +Please note that there may be more than one +solutions,this function prints one of the +feasible solutions.''' + +def solveNQueens(): + board = [[0 for i in range(N)] + for j in range(N)] + ''' helper matrices''' + + slashCode = [[0 for i in range(N)] + for j in range(N)] + backslashCode = [[0 for i in range(N)] + for j in range(N)] + ''' arrays to tell us which rows are occupied''' + + rowLookup = [False] * N + ''' keep two arrays to tell us + which diagonals are occupied''' + + x = 2 * N - 1 + slashCodeLookup = [False] * x + backslashCodeLookup = [False] * x + ''' initialize helper matrices''' + + for rr in range(N): + for cc in range(N): + slashCode[rr][cc] = rr + cc + backslashCode[rr][cc] = rr - cc + 7 + if(solveNQueensUtil(board, 0, slashCode, backslashCode, + rowLookup, slashCodeLookup, + backslashCodeLookup) == False): + print(""Solution does not exist"") + return False + ''' solution found''' + + printSolution(board) + return True + '''Driver Cde''' + +solveNQueens()" +Find n-th node of inorder traversal,"/*Java program for nth nodes of inorder traversals */ + +import java.util. *; +class Solution +{ +static int count =0; +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +static class Node { + int data; + Node left; + Node right; +} +/* Helper function that allocates a new node with the +given data and null left and right pointers. */ + + static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/* Given a binary tree, print its nth nodes of inorder*/ + +static void NthInorder( Node node, int n) +{ + if (node == null) + return; + if (count <= n) { + /* first recur on left child */ + + NthInorder(node.left, n); + count++; +/* when count = n then print element */ + + if (count == n) + System.out.printf(""%d "", node.data); + /* now recur on right child */ + + NthInorder(node.right, n); + } +} +/* Driver program to test above functions*/ + +public static void main(String args[]) +{ + Node root = newNode(10); + root.left = newNode(20); + root.right = newNode(30); + root.left.left = newNode(40); + root.left.right = newNode(50); + int n = 4; + NthInorder(root, n); +} +}"," '''Python3 program for nth node of + inorder traversal''' + +count = [0] '''A Binary Tree Node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.visited = False ''' Given a binary tree, print the nth + node of inorder traversal''' + +def NthInorder(node, n): + if (node == None): + return + if (count[0] <= n): + ''' first recur on left child ''' + + NthInorder(node.left, n) + count[0] += 1 + ''' when count = n then prelement ''' + + if (count[0] == n): + print(node.data, end = "" "") + ''' now recur on right child ''' + + NthInorder(node.right, n) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(10) + root.left = newNode(20) + root.right = newNode(30) + root.left.left = newNode(40) + root.left.right = newNode(50) + n = 4 + NthInorder(root, n)" +Non-Repeating Element,"/*Efficient Java program to print all non- +repeating elements.*/ + +import java.util.*; +class GFG { + static void firstNonRepeating(int arr[], int n) + { +/* Insert all array elements in hash + table*/ + + Map m = new HashMap<>(); + for (int i = 0; i < n; i++) { + if (m.containsKey(arr[i])) { + m.put(arr[i], m.get(arr[i]) + 1); + } + else { + m.put(arr[i], 1); + } + } +/* Traverse through map only and + using for-each loop for iteration over Map.entrySet()*/ + + for (Map.Entry x : m.entrySet()) + if (x.getValue() == 1) + System.out.print(x.getKey() + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 9, 4, 9, 6, 7, 4 }; + int n = arr.length; + firstNonRepeating(arr, n); + } +}"," '''Efficient Python program to print all non- +repeating elements.''' + +def firstNonRepeating(arr, n): + ''' Insert all array elements in hash + table''' + + mp={} + for i in range(n): + if arr[i] not in mp: + mp[arr[i]]=0 + mp[arr[i]]+=1 + ''' Traverse through map only and''' + + for x in mp: + if (mp[x]== 1): + print(x,end="" "") + '''Driver code''' + +arr = [ 9, 4, 9, 6, 7, 4 ] +n = len(arr) +firstNonRepeating(arr, n)" +Find whether a subarray is in form of a mountain or not,"/*Java program to check whether a subarray is in +mountain form or not*/ + +class SubArray +{ +/* Utility method to construct left and right array*/ + + static void preprocess(int arr[], int N, int left[], int right[]) + { +/* initialize first left index as that index only*/ + + left[0] = 0; + int lastIncr = 0; + + for (int i = 1; i < N; i++) + { +/* if current value is greater than previous, + update last increasing*/ + + if (arr[i] > arr[i - 1]) + lastIncr = i; + left[i] = lastIncr; + } + +/* initialize last right index as that index only*/ + + right[N - 1] = N - 1; + int firstDecr = N - 1; + + for (int i = N - 2; i >= 0; i--) + { +/* if current value is greater than next, + update first decreasing*/ + + if (arr[i] > arr[i + 1]) + firstDecr = i; + right[i] = firstDecr; + } + } + +/* method returns true if arr[L..R] is in mountain form*/ + + static boolean isSubarrayMountainForm(int arr[], int left[], + int right[], int L, int R) + { +/* return true only if right at starting range is + greater than left at ending range*/ + + return (right[L] >= left[R]); + } + +/* Driver Code*/ + + + public static void main(String[] args) + { + int arr[] = {2, 3, 2, 4, 4, 6, 3, 2}; + int N = arr.length; + int left[] = new int[N]; + int right[] = new int[N]; + preprocess(arr, N, left, right); + int L = 0; + int R = 2; + + if (isSubarrayMountainForm(arr, left, right, L, R)) + System.out.println(""Subarray is in mountain form""); + else + System.out.println(""Subarray is not in mountain form""); + + L = 1; + R = 3; + + if (isSubarrayMountainForm(arr, left, right, L, R)) + System.out.println(""Subarray is in mountain form""); + else + System.out.println(""Subarray is not in mountain form""); + } +} + +"," '''Python 3 program to check whether a subarray is in +mountain form or not''' + + + '''Utility method to construct left and right array''' + +def preprocess(arr, N, left, right): + ''' initialize first left index as that index only''' + + left[0] = 0 + lastIncr = 0 + + for i in range(1,N): + ''' if current value is greater than previous, + update last increasing''' + + if (arr[i] > arr[i - 1]): + lastIncr = i + left[i] = lastIncr + + ''' initialize last right index as that index only''' + + right[N - 1] = N - 1 + firstDecr = N - 1 + + i = N - 2 + while(i >= 0): + ''' if current value is greater than next, + update first decreasing''' + + if (arr[i] > arr[i + 1]): + firstDecr = i + right[i] = firstDecr + i -= 1 + + '''method returns true if arr[L..R] is in mountain form''' + +def isSubarrayMountainForm(arr, left, right, L, R): + + ''' return true only if right at starting range is + greater than left at ending range''' + + return (right[L] >= left[R]) + + '''Driver code''' + +if __name__ == '__main__': + arr = [2, 3, 2, 4, 4, 6, 3, 2] + N = len(arr) + + left = [0 for i in range(N)] + right = [0 for i in range(N)] + preprocess(arr, N, left, right) + + L = 0 + R = 2 + if (isSubarrayMountainForm(arr, left, right, L, R)): + print(""Subarray is in mountain form"") + else: + print(""Subarray is not in mountain form"") + + L = 1 + R = 3 + if (isSubarrayMountainForm(arr, left, right, L, R)): + print(""Subarray is in mountain form"") + else: + print(""Subarray is not in mountain form"") + + +" +Count number of rotated strings which have more number of vowels in the first half than second half,"/*Java implementation of the approach*/ + +class GFG +{ + +/*Function to return the count of rotated +Strings which have more number of vowels in +the first half than the second half*/ + +static int cntRotations(String s, int n) +{ +/* Create a new String*/ + + String str = s + s; + +/* Pre array to store count of all vowels*/ + + int pre[]=new int[2 * n] ; + +/* Compute the prefix array*/ + + for (int i = 0; i < 2 * n; i++) + { + if (i != 0) + pre[i] += pre[i - 1]; + + if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || + str.charAt(i) == 'i' || str.charAt(i) == 'o' || + str.charAt(i) == 'u') + { + pre[i]++; + } + } + +/* To store the required answer*/ + + int ans = 0; + +/* Find all rotated Strings*/ + + for (int i = n - 1; i < 2 * n - 1; i++) + { + +/* Right and left index of the String*/ + + int r = i, l = i - n; + +/* x1 stores the number of vowels + in the rotated String*/ + + int x1 = pre[r]; + if (l >= 0) + x1 -= pre[l]; + r = i - n / 2; + +/* Left stores the number of vowels + in the first half of rotated String*/ + + int left = pre[r]; + if (l >= 0) + left -= pre[l]; + +/* Right stores the number of vowels + in the second half of rotated String*/ + + int right = x1 - left; + +/* If the count of vowels in the first half + is greater than the count in the second half*/ + + if (left > right) + { + ans++; + } + } + +/* Return the required answer*/ + + return ans; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + String s = ""abecidft""; + int n = s.length(); + + System.out.println( cntRotations(s, n)); +} +} + + +"," '''Python3 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''' + +def cntRotations(s, n): + + ''' Create a new string''' + + str = s + s; + + ''' Pre array to store count of all vowels''' + + pre = [0] * (2 * n); + + ''' Compute the prefix array''' + + for i in range(2 * n): + if (i != 0): + pre[i] += pre[i - 1]; + + if (str[i] == 'a' or str[i] == 'e' or + str[i] == 'i' or str[i] == 'o' or + str[i] == 'u'): + pre[i] += 1; + + ''' To store the required answer''' + + ans = 0; + + ''' Find all rotated strings''' + + for i in range(n - 1, 2 * n - 1, 1): + + ''' Right and left index of the string''' + + r = i; l = i - n; + + ''' x1 stores the number of vowels + in the rotated string''' + + x1 = pre[r]; + if (l >= 0): + x1 -= pre[l]; + r = (int)(i - n / 2); + + ''' Left stores the number of vowels + in the first half of rotated string''' + + left = pre[r]; + if (l >= 0): + left -= pre[l]; + + ''' Right stores the number of vowels + in the second half of rotated string''' + + right = x1 - left; + + ''' If the count of vowels in the first half + is greater than the count in the second half''' + + if (left > right): + ans += 1; + + ''' Return the required answer''' + + return ans; + + '''Driver code''' + +s = ""abecidft""; +n = len(s); + +print(cntRotations(s, n)); + + +" +Possible moves of knight,"/*Java program to find number of possible moves of knight*/ + +public class Main { +public static final int n = 4; +public static final int m = 4; +/* To calculate possible moves*/ + + static int findPossibleMoves(int mat[][], int p, int q) + { +/* All possible moves of a knight*/ + + int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; + int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; + int count = 0; +/* Check if each possible move is valid or not*/ + + for (int i = 0; i < 8; i++) { +/* Position of knight after move*/ + + int x = p + X[i]; + int y = q + Y[i]; +/* count valid moves*/ + + if (x >= 0 && y >= 0 && x < n && y < m + && mat[x][y] == 0) + count++; + } +/* Return number of possible moves*/ + + return count; + } +/* Driver program to check findPossibleMoves()*/ + + public static void main(String[] args) + { + int mat[][] = { { 1, 0, 1, 0 }, + { 0, 1, 1, 1 }, + { 1, 1, 0, 1 }, + { 0, 1, 1, 1 } }; + int p = 2, q = 2; + System.out.println(findPossibleMoves(mat, p, q)); + } +}"," '''Python3 program to find number +of possible moves of knight''' + +n = 4; +m = 4; + '''To calculate possible moves''' + +def findPossibleMoves(mat, p, q): + global n, m; + ''' All possible moves of a knight''' + + X = [2, 1, -1, -2, -2, -1, 1, 2]; + Y = [1, 2, 2, 1, -1, -2, -2, -1]; + count = 0; + ''' Check if each possible move + is valid or not''' + + for i in range(8): + ''' Position of knight after move''' + + x = p + X[i]; + y = q + Y[i]; + ''' count valid moves''' + + if(x >= 0 and y >= 0 and x < n and + y < m and mat[x][y] == 0): + count += 1; + ''' Return number of possible moves''' + + return count; + '''Driver code''' + +if __name__ == '__main__': + mat = [[1, 0, 1, 0], [0, 1, 1, 1], + [1, 1, 0, 1], [0, 1, 1, 1]]; + p, q = 2, 2; + print(findPossibleMoves(mat, p, q));" +Count Inversions in an array | Set 1 (Using Merge Sort),"/*Java program to count +inversions in an array*/ + +class Test { + static int arr[] = new int[] { 1, 20, 6, 4, 5 }; + static int getInvCount(int n) + { + int inv_count = 0; + for (int i = 0; i < n - 1; i++) + for (int j = i + 1; j < n; j++) + if (arr[i] > arr[j]) + inv_count++; + return inv_count; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.println(""Number of inversions are "" + + getInvCount(arr.length)); + } +}"," '''Python3 program to count +inversions in an array''' + +def getInvCount(arr, n): + inv_count = 0 + for i in range(n): + for j in range(i + 1, n): + if (arr[i] > arr[j]): + inv_count += 1 + return inv_count + '''Driver Code''' + +arr = [1, 20, 6, 4, 5] +n = len(arr) +print(""Number of inversions are"", + getInvCount(arr, n))" +Maximum number of partitions that can be sorted individually to make sorted,"/*java program to find Maximum number of partitions +such that we can get a sorted array*/ + + +import java.io.*; + +class GFG +{ +/* Function to find maximum partitions.*/ + + static int maxPartitions(int arr[], int n) + { + int ans = 0, max_so_far = 0; + for (int i = 0; i < n; ++i) { + +/* Find maximum in prefix arr[0..i]*/ + + max_so_far = Math.max(max_so_far, arr[i]); + +/* If maximum so far is equal to index, + we can make a new partition ending at + index i.*/ + + if (max_so_far == i) + ans++; + } + return ans; + } + +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = { 1, 0, 2, 3, 4 }; + int n = arr.length; + System.out.println (maxPartitions(arr, n)); + + } +} + + +"," '''Python3 program to find Maximum +number of partitions such that +we can get a sorted array.''' + + + '''Function to find maximum partitions.''' + +def maxPartitions(arr, n): + + ans = 0; max_so_far = 0 + for i in range(0, n): + + ''' Find maximum in prefix arr[0..i]''' + + max_so_far = max(max_so_far, arr[i]) + + ''' If maximum so far is equal to + index, we can make a new partition + ending at index i.''' + + if (max_so_far == i): + ans += 1 + + return ans + + '''Driver code''' + +arr = [1, 0, 2, 3, 4] +n = len(arr) +print(maxPartitions(arr, n)) + + +" +Number of unique triplets whose XOR is zero,"/*Java program to count +the number of unique +triplets whose XOR is 0*/ + +import java.io.*; +import java.util.*; + +class GFG +{ +/* function to count the + number of unique triplets + whose xor is 0*/ + + static int countTriplets(int []a, + int n) + { +/* To store values + that are present*/ + + ArrayList s = + new ArrayList(); + for (int i = 0; i < n; i++) + s.add(a[i]); + +/* stores the count + of unique triplets*/ + + int count = 0; + +/* traverse for all i, + j pairs such that j>i*/ + + for (int i = 0; i < n; i++) + { + for (int j = i + 1; + j < n; j++) + { + +/* xor of a[i] and a[j]*/ + + int xr = a[i] ^ a[j]; + +/* if xr of two numbers + is present, then + increase the count*/ + + if (s.contains(xr) && + xr != a[i] && xr != a[j]) + count++; + } + } + +/* returns answer*/ + + return count / 3; + } + +/* Driver code*/ + + public static void main(String srgs[]) + { + int []a = {1, 3, 5, + 10, 14, 15}; + int n = a.length; + System.out.print(countTriplets(a, n)); + } +} + + +"," '''Python 3 program to count the number of +unique triplets whose XOR is 0''' + + + '''function to count the number of +unique triplets whose xor is 0''' + +def countTriplets(a, n): + + ''' To store values that are present''' + + s = set() + for i in range(n): + s.add(a[i]) + + ''' stores the count of unique triplets''' + + count = 0 + + ''' traverse for all i, j pairs such that j>i''' + + for i in range(n): + for j in range(i + 1, n, 1): + + ''' xor of a[i] and a[j]''' + + xr = a[i] ^ a[j] + + ''' if xr of two numbers is present, + then increase the count''' + + if (xr in s and xr != a[i] and + xr != a[j]): + count += 1; + + ''' returns answer''' + + return int(count / 3) + + '''Driver code''' + +if __name__ == '__main__': + a = [1, 3, 5, 10, 14, 15] + n = len(a) + print(countTriplets(a, n)) + + +" +Find a number in minimum steps,"/*Java program to find a number in minimum steps*/ + +import java.util.*; +class GFG +{ + static final int InF = 99999; +/* To represent data of a node in tree*/ + + static class number + { + int no; + int level; + number() {} + number(int n, int l) + { + this.no = n; + this.level = l; + } + }; +/* Prints level of node n*/ + + static void findnthnumber(int n) + { +/* Create a queue and insert root*/ + + Queue q = new LinkedList<>(); + number r = new number(0, 1); + q.add(r); +/* Do level order traversal*/ + + while (!q.isEmpty()) + { +/* Remove a node from queue*/ + + number temp = q.peek(); + q.remove(); +/* To astatic void infinite loop*/ + + if (temp.no >= InF || temp.no <= -InF) + break; +/* Check if dequeued number is same as n*/ + + if (temp.no == n) + { + System.out.print(""Found number n at level "" + + (temp.level - 1)); + break; + } +/* Insert children of dequeued node to queue*/ + + q.add(new number(temp.no + temp.level, temp.level + 1)); + q.add(new number(temp.no - temp.level, temp.level + 1)); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + findnthnumber(13); + } +}"," '''Python program to find a number in minimum steps''' +from collections import deque +InF = 99999 + + '''To represent data of a node in tree''' + +class number: + def __init__(self,n,l): + self.no = n + self.level = l + '''Prints level of node n''' + +def findnthnumber(n): + ''' Create a queue and insert root''' + + q = deque() + r = number(0, 1) + q.append(r) + ''' Do level order traversal''' + + while (len(q) > 0): + ''' Remove a node from queue''' + + temp = q.popleft() + ''' q.pop() + To avoid infinite loop''' + + if (temp.no >= InF or temp.no <= -InF): + break + ''' Check if dequeued number is same as n''' + + if (temp.no == n): + print(""Found number n at level"", temp.level - 1) + break + ''' Insert children of dequeued node to queue''' + + q.append(number(temp.no + temp.level, temp.level + 1)) + q.append(number(temp.no - temp.level, temp.level + 1)) + '''Driver code''' + +if __name__ == '__main__': + findnthnumber(13)" +Find an array element such that all elements are divisible by it,"/*Java program to find an array element +that divides all numbers in the array +using naive approach*/ + +import java.io.*; + +class GFG { + +/* function to find smallest num*/ + + static int findSmallest(int a[], int n) + { +/* traverse for all elements*/ + + for (int i = 0; i < n; i++) + { + + int j; + for (j = 0; j < n; j++) + if (a[j] % a[i]>=1) + break; + +/* stores the minimum if + it divides all*/ + + if (j == n) + return a[i]; + } + + return -1; + } + +/* driver code*/ + + public static void main(String args[]) + { + int a[] = { 25, 20, 5, 10, 100 }; + int n = a.length; + System.out.println(findSmallest(a, n)); + } +} + + + +"," '''Python 3 program to find an array +element that divides all numbers +in the array using naive approach''' + + + '''Function to find smallest num''' + +def findSmallest(a, n) : + + ''' Traverse for all elements''' + + for i in range(0, n ) : + + for j in range(0, n) : + + if ((a[j] % a[i]) >= 1) : + break + + ''' Stores the minimum + if it divides all''' + + if (j == n - 1) : + return a[i] + + return -1 + + + '''Driver code''' + +a = [ 25, 20, 5, 10, 100 ] +n = len(a) +print(findSmallest(a, n)) + + + +" +Program for Rank of Matrix,"/*Java program to find rank of a matrix*/ + +class GFG { + static final int R = 3; + static final int C = 3; +/* function for exchanging two rows + of a matrix*/ + + static void swap(int mat[][], + int row1, int row2, int col) + { + for (int i = 0; i < col; i++) + { + int temp = mat[row1][i]; + mat[row1][i] = mat[row2][i]; + mat[row2][i] = temp; + } + } +/* function for finding rank of matrix*/ + + static int rankOfMatrix(int mat[][]) + { + int rank = C; + for (int row = 0; row < rank; row++) + { +/* Before we visit current row + 'row', we make sure that + mat[row][0],....mat[row][row-1] + are 0. + Diagonal element is not zero*/ + + if (mat[row][row] != 0) + { + for (int col = 0; col < R; col++) + { + if (col != row) + { +/* This makes all entries + of current column + as 0 except entry + 'mat[row][row]'*/ + + double mult = + (double)mat[col][row] / + mat[row][row]; + for (int i = 0; i < rank; i++) + mat[col][i] -= mult + * mat[row][i]; + } + } + } +/* Diagonal element is already zero. + Two cases arise: + 1) If there is a row below it + with non-zero entry, then swap + this row with that row and process + that row + 2) If all elements in current + column below mat[r][row] are 0, + then remvoe this column by + swapping it with last column and + reducing number of columns by 1.*/ + + else + { + boolean reduce = true; +/* Find the non-zero element + in current column*/ + + for (int i = row + 1; i < R; i++) + { +/* Swap the row with non-zero + element with this row.*/ + + if (mat[i][row] != 0) + { + swap(mat, row, i, rank); + reduce = false; + break ; + } + } +/* If we did not find any row with + non-zero element in current + columnm, then all values in + this column are 0.*/ + + if (reduce) + { +/* Reduce number of columns*/ + + rank--; +/* Copy the last column here*/ + + for (int i = 0; i < R; i ++) + mat[i][row] = mat[i][rank]; + } +/* Process this row again*/ + + row--; + } +/* Uncomment these lines to see + intermediate results display(mat, R, C); + printf(""\n"");*/ + + } + return rank; + } +/* Function to display a matrix*/ + + static void display(int mat[][], + int row, int col) + { + for (int i = 0; i < row; i++) + { + for (int j = 0; j < col; j++) + System.out.print("" "" + + mat[i][j]); + System.out.print(""\n""); + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int mat[][] = {{10, 20, 10}, + {-20, -30, 10}, + {30, 50, 0}}; + System.out.print(""Rank of the matrix is : "" + + rankOfMatrix(mat)); + } +}"," '''Python 3 program to find rank of a matrix''' + +class rankMatrix(object): + def __init__(self, Matrix): + self.R = len(Matrix) + self.C = len(Matrix[0]) + ''' Function for exchanging two rows of a matrix''' + + def swap(self, Matrix, row1, row2, col): + for i in range(col): + temp = Matrix[row1][i] + Matrix[row1][i] = Matrix[row2][i] + Matrix[row2][i] = temp + ''' Find rank of a matrix''' + + def rankOfMatrix(self, Matrix): + rank = self.C + for row in range(0, rank, 1): + ''' Before we visit current row + 'row', we make sure that + mat[row][0],....mat[row][row-1] + are 0. + Diagonal element is not zero''' + + if Matrix[row][row] != 0: + for col in range(0, self.R, 1): + if col != row: + ''' This makes all entries of current + column as 0 except entry 'mat[row][row]''' + ''' + multiplier = (Matrix[col][row] / + Matrix[row][row]) + for i in range(rank): + Matrix[col][i] -= (multiplier * + Matrix[row][i]) + ''' Diagonal element is already zero. + Two cases arise: + 1) If there is a row below it + with non-zero entry, then swap + this row with that row and process + that row + 2) If all elements in current + column below mat[r][row] are 0, + then remvoe this column by + swapping it with last column and + reducing number of columns by 1.''' + + else: + reduce = True + ''' Find the non-zero element + in current column''' + + for i in range(row + 1, self.R, 1): + ''' Swap the row with non-zero + element with this row.''' + + if Matrix[i][row] != 0: + self.swap(Matrix, row, i, rank) + reduce = False + break + ''' If we did not find any row with + non-zero element in current + columnm, then all values in + this column are 0.''' + + if reduce: + ''' Reduce number of columns''' + + rank -= 1 + ''' copy the last column here''' + + for i in range(0, self.R, 1): + Matrix[i][row] = Matrix[i][rank] + ''' process this row again''' + + row -= 1 + ''' self.Display(Matrix, self.R,self.C)''' + + return (rank) + ''' Function to Display a matrix''' + + def Display(self, Matrix, row, col): + for i in range(row): + for j in range(col): + print ("" "" + str(Matrix[i][j])) + print ('\n') + '''Driver Code''' + +if __name__ == '__main__': + Matrix = [[10, 20, 10], + [-20, -30, 10], + [30, 50, 0]] + RankMatrix = rankMatrix(Matrix) + print (""Rank of the Matrix is:"", + (RankMatrix.rankOfMatrix(Matrix)))" +Find depth of the deepest odd level leaf node,"/*Java program to find depth of deepest odd level node*/ + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root;/* A recursive function to find depth of the deepest odd level leaf*/ + + int depthOfOddLeafUtil(Node node, int level) + { +/* Base Case*/ + + if (node == null) + return 0; +/* If this node is a leaf and its level is odd, return its level*/ + + if (node.left == null && node.right == null && (level & 1) != 0) + return level; +/* If not leaf, return the maximum value from left and right subtrees*/ + + return Math.max(depthOfOddLeafUtil(node.left, level + 1), + depthOfOddLeafUtil(node.right, level + 1)); + } + /* Main function which calculates the depth of deepest odd level leaf. + This function mainly uses depthOfOddLeafUtil() */ + + int depthOfOddLeaf(Node node) + { + int level = 1, depth = 0; + return depthOfOddLeafUtil(node, level); + } +/*Driver Code*/ + + public static void main(String args[]) + { + int k = 45; + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.right.left = new Node(5); + tree.root.right.right = new Node(6); + tree.root.right.left.right = new Node(7); + tree.root.right.right.right = new Node(8); + tree.root.right.left.right.left = new Node(9); + tree.root.right.right.right.right = new Node(10); + tree.root.right.right.right.right.left = new Node(11); + System.out.println(tree.depthOfOddLeaf(tree.root) + + "" is the required depth""); + } +}"," '''Python program to find depth of the deepest odd level +leaf node''' + + '''A Binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''A recursive function to find depth of the deepest +odd level leaf node''' + +def depthOfOddLeafUtil(root, level): + ''' Base Case''' + + if root is None: + return 0 + ''' If this node is leaf and its level is odd, return + its level''' + + if root.left is None and root.right is None and level&1: + return level + ''' If not leaf, return the maximum value from left + and right subtrees''' + + return (max(depthOfOddLeafUtil(root.left, level+1), + depthOfOddLeafUtil(root.right, level+1))) + '''Main function which calculates the depth of deepest odd +level leaf . +This function mainly uses depthOfOddLeafUtil()''' + +def depthOfOddLeaf(root): + level = 1 + depth = 0 + return depthOfOddLeafUtil(root, level) + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.right.left = Node(5) +root.right.right = Node(6) +root.right.left.right = Node(7) +root.right.right.right = Node(8) +root.right.left.right.left = Node(9) +root.right.right.right.right = Node(10) +root.right.right.right.right.left= Node(11) +print ""%d is the required depth"" %(depthOfOddLeaf(root))" +Find position of an element in a sorted array of infinite numbers,"/*Java program to demonstrate working of +an algorithm that finds an element in an +array of infinite size*/ + +class Test +{ +/* Simple binary search algorithm*/ + + static int binarySearch(int arr[], int l, int r, int x) + { + if (r>=l) + { + int mid = l + (r - l)/2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid-1, x); + return binarySearch(arr, mid+1, r, x); + } + return -1; + } +/* Method takes an infinite size array and a key to be + searched and returns its position if found else -1. + We don't know size of arr[] and we can assume size to be + infinite in this function. + NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE + THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING*/ + + static int findPos(int arr[],int key) + { + int l = 0, h = 1; + int val = arr[0]; +/* Find h to do binary search*/ + + while (val < key) + { +/*store previous high*/ + +l = h; +/* check that 2*h doesn't exceeds array + length to prevent ArrayOutOfBoundException*/ + + if(2*h < arr.length-1) + h = 2*h; + else + h = arr.length-1; +/*update new val*/ + +val = arr[h]; + } +/* at this point we have updated low + and high indices, thus use binary + search between them*/ + + return binarySearch(arr, l, h, key); + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + int arr[] = new int[]{3, 5, 7, 9, 10, 90, + 100, 130, 140, 160, 170}; + int ans = findPos(arr,10); + if (ans==-1) + System.out.println(""Element not found""); + else + System.out.println(""Element found at index "" + ans); + } +}"," '''Python Program to demonstrate working of an algorithm that finds +an element in an array of infinite size''' + + '''Binary search algorithm implementation''' + +def binary_search(arr,l,r,x): + if r >= l: + mid = l+(r-l)/2 + if arr[mid] == x: + return mid + if arr[mid] > x: + return binary_search(arr,l,mid-1,x) + return binary_search(arr,mid+1,r,x) + return -1 '''function takes an infinite size array and a key to be +searched and returns its position if found else -1. +We don't know size of a[] and we can assume size to be +infinite in this function. +NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE +THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING''' + +def findPos(a, key): + l, h, val = 0, 1, arr[0] + ''' Find h to do binary search''' + + while val < key: + '''store previous high''' + + l = h + + '''double high index''' + + h = 2*h + + '''update new val''' + + val = arr[h] + ''' at this point we have updated low and high indices, + thus use binary search between them''' + + return binary_search(a, l, h, key) + '''Driver function''' + +arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170] +ans = findPos(arr,10) +if ans == -1: + print ""Element not found"" +else: + print""Element found at index"",ans" +Third largest element in an array of distinct elements,"/*Java program to find third +Largest element in an array +of distinct elements*/ + + +class GFG +{ +static void thirdLargest(int arr[], + int arr_size) +{ + /* There should be + atleast three elements */ + + if (arr_size < 3) + { + System.out.printf("" Invalid Input ""); + return; + } + +/* Find first + largest element*/ + + int first = arr[0]; + for (int i = 1; + i < arr_size ; i++) + if (arr[i] > first) + first = arr[i]; + +/* Find second + largest element*/ + + int second = Integer.MIN_VALUE; + for (int i = 0; + i < arr_size ; i++) + if (arr[i] > second && + arr[i] < first) + second = arr[i]; + +/* Find third + largest element*/ + + int third = Integer.MIN_VALUE; + for (int i = 0; + i < arr_size ; i++) + if (arr[i] > third && + arr[i] < second) + third = arr[i]; + + System.out.printf(""The third Largest "" + + ""element is %d\n"", third); +} + +/*Driver code*/ + +public static void main(String []args) +{ + int arr[] = {12, 13, 1, + 10, 34, 16}; + int n = arr.length; + thirdLargest(arr, n); +} +} + + +"," '''Python 3 program to find +third Largest element in +an array of distinct elements''' + +import sys +def thirdLargest(arr, arr_size): + + ''' There should be + atleast three elements''' + + if (arr_size < 3): + + print("" Invalid Input "") + return + + + ''' Find first + largest element''' + + first = arr[0] + for i in range(1, arr_size): + if (arr[i] > first): + first = arr[i] + + ''' Find second + largest element''' + + second = -sys.maxsize + for i in range(0, arr_size): + if (arr[i] > second and + arr[i] < first): + second = arr[i] + + ''' Find third + largest element''' + + third = -sys.maxsize + for i in range(0, arr_size): + if (arr[i] > third and + arr[i] < second): + third = arr[i] + + print(""The Third Largest"", + ""element is"", third) + + '''Driver Code''' + +arr = [12, 13, 1, + 10, 34, 16] +n = len(arr) +thirdLargest(arr, n) + + +" +Program to check diagonal matrix and scalar matrix,"/*Program to check matrix +is scalar matrix or not.*/ + +import java.io.*; +class GFG { + static int N = 4; +/* Function to check matrix + is scalar matrix or not.*/ + + static boolean isScalarMatrix(int mat[][]) + { +/* Check all elements + except main diagonal are + zero or not.*/ + + for (int i = 0; i < N; i++) + for (int j = 0; j < N; j++) + if ((i != j) + && (mat[i][j] != 0)) + return false; +/* Check all diagonal elements + are same or not.*/ + + for (int i = 0; i < N - 1; i++) + if (mat[i][i] != mat[i + 1][i + 1]) + return false; + return true; + } +/* Driver function*/ + + public static void main(String args[]) + { + int mat[ ][ ] = { { 2, 0, 0, 0 }, + { 0, 2, 0, 0 }, + { 0, 0, 2, 0 }, + { 0, 0, 0, 2 } }; +/* Function call*/ + + if (isScalarMatrix(mat)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Program to check matrix +is scalar matrix or not.''' + +N = 4 + '''Function to check matrix is +scalar matrix or not.''' + +def isScalarMatrix(mat) : + ''' Check all elements + except main diagonal are + zero or not.''' + + for i in range(0,N) : + for j in range(0,N) : + if ((i != j) + and (mat[i][j] != 0)) : + return False + ''' Check all diagonal + elements are same or not.''' + + for i in range(0,N-1) : + if (mat[i][i] != + mat[i + 1][i + 1]) : + return False + return True + '''Driver function''' + +mat = [[ 2, 0, 0, 0 ], + [ 0, 2, 0, 0 ], + [ 0, 0, 2, 0 ], + [ 0, 0, 0, 2 ]] + '''Function call''' + +if (isScalarMatrix(mat)): + print(""Yes"") +else : + print(""No"")" +Union and Intersection of two sorted arrays,"/*Java program to find intersection of +two sorted arrays*/ + +class FindIntersection { + /* Function prints Intersection of arr1[] and arr2[] + m is the number of elements in arr1[] + n is the number of elements in arr2[] */ + + static void printIntersection(int arr1[], int arr2[], int m, int n) + { + int i = 0, j = 0; + while (i < m && j < n) { + if (arr1[i] < arr2[j]) + i++; + else if (arr2[j] < arr1[i]) + j++; + else { + System.out.print(arr2[j++] + "" ""); + i++; + } + } + } +/* Driver program to test above function */ + + public static void main(String args[]) + { + int arr1[] = { 1, 2, 4, 5, 6 }; + int arr2[] = { 2, 3, 5, 7 }; + int m = arr1.length; + int n = arr2.length; +/* Function calling*/ + + printIntersection(arr1, arr2, m, n); + } +}"," '''Python program to find intersection of +two sorted arrays''' + + '''Function prints Intersection of arr1[] and arr2[] +m is the number of elements in arr1[] +n is the number of elements in arr2[]''' + +def printIntersection(arr1, arr2, m, n): + i, j = 0, 0 + while i < m and j < n: + if arr1[i] < arr2[j]: + i += 1 + elif arr2[j] < arr1[i]: + j+= 1 + else: + print(arr2[j]) + j += 1 + i += 1 '''Driver program to test above function''' + +arr1 = [1, 2, 4, 5, 6] +arr2 = [2, 3, 5, 7] +m = len(arr1) +n = len(arr2) + ''' Function calling''' + +printIntersection(arr1, arr2, m, n)" +Shortest path to reach one prime to other by changing single digit at a time,," '''Python3 program to reach a prime number +from another by changing single digits +and using only prime numbers.''' + +import queue +class Graph: + def __init__(self, V): + self.V = V; + self.l = [[] for i in range(V)] + def addedge(self, V1, V2): + self.l[V1].append(V2); + self.l[V2].append(V1); + ''' Finding all 4 digit prime numbers ''' + +def SieveOfEratosthenes(v): + ''' Create a boolean array ""prime[0..n]"" and + initialize all entries it as true. A value + in prime[i] will finally be false if i is + Not a prime, else true. ''' + + n = 9999 + prime = [True] * (n + 1) + p = 2 + while p * p <= n: + ''' If prime[p] is not changed, + then it is a prime ''' + + if (prime[p] == True): + ''' Update all multiples of p''' + + for i in range(p * p, n + 1, p): + prime[i] = False + p += 1 + ''' Forming a vector of prime numbers''' + + for p in range(1000, n + 1): + if (prime[p]): + v.append(p) + + ''' in1 and in2 are two vertices of graph + which are actually indexes in pset[] ''' + + def bfs(self, in1, in2): + visited = [0] * self.V + que = queue.Queue() + visited[in1] = 1 + que.put(in1) + while (not que.empty()): + p = que.queue[0] + que.get() + i = 0 + while i < len(self.l[p]): + if (not visited[self.l[p][i]]): + visited[self.l[p][i]] = visited[p] + 1 + que.put(self.l[p][i]) + if (self.l[p][i] == in2): + return visited[self.l[p][i]] - 1 + i += 1 + '''Returns true if num1 and num2 differ +by single digit.''' +def compare(num1, num2): ''' To compare the digits ''' + + s1 = str(num1) + s2 = str(num2) + c = 0 + if (s1[0] != s2[0]): + c += 1 + if (s1[1] != s2[1]): + c += 1 + if (s1[2] != s2[2]): + c += 1 + if (s1[3] != s2[3]): + c += 1 + ''' If the numbers differ only by a single + digit return true else false ''' + + return (c == 1) +def shortestPath(num1, num2): + ''' Generate all 4 digit ''' + + pset = [] + SieveOfEratosthenes(pset) + ''' Create a graph where node numbers + are indexes in pset[] and there is + an edge between two nodes only if + they differ by single digit. ''' + + g = Graph(len(pset)) + for i in range(len(pset)): + for j in range(i + 1, len(pset)): + if (compare(pset[i], pset[j])): + g.addedge(i, j) + ''' Since graph nodes represent indexes + of numbers in pset[], we find indexes + of num1 and num2. ''' + + in1, in2 = None, None + for j in range(len(pset)): + if (pset[j] == num1): + in1 = j + for j in range(len(pset)): + if (pset[j] == num2): + in2 = j + return g.bfs(in1, in2) + '''Driver code ''' + +if __name__ == '__main__': + num1 = 1033 + num2 = 8179 + print(shortestPath(num1, num2))" +Merging two unsorted arrays in sorted order,"/*JAVA Code for Merging two unsorted +arrays in sorted order*/ + +import java.util.*; + +class GFG { + +/* Function to merge array in sorted order*/ + + public static void sortedMerge(int a[], int b[], + int res[], int n, + int m) + { +/* Sorting a[] and b[]*/ + + Arrays.sort(a); + Arrays.sort(b); + +/* Merge two sorted arrays into res[]*/ + + int i = 0, j = 0, k = 0; + while (i < n && j < m) { + if (a[i] <= b[j]) { + res[k] = a[i]; + i += 1; + k += 1; + } else { + res[k] = b[j]; + j += 1; + k += 1; + } + } + +/*Merging remaining elements of a[] (if any)*/ + +while (i < n) { + res[k] = a[i]; + i += 1; + k += 1; + } + +/*Merging remaining elements of b[] (if any)*/ + +while (j < m) { + res[k] = b[j]; + j += 1; + k += 1; + } + } + +/* Driver program to test above function */ + + public static void main(String[] args) + { + int a[] = { 10, 5, 15 }; + int b[] = { 20, 3, 2, 12 }; + int n = a.length; + int m = b.length; + +/* Final merge list*/ + + int res[] = new int[n + m]; + sortedMerge(a, b, res, n, m); + + System.out.print( ""Sorted merged list :""); + for (int i = 0; i < n + m; i++) + System.out.print("" "" + res[i]); + } +} + +"," '''Python program to merge two unsorted lists +in sorted order''' + + + '''Function to merge array in sorted order''' + +def sortedMerge(a, b, res, n, m): + ''' Sorting a[] and b[]''' + + a.sort() + b.sort() + + ''' Merge two sorted arrays into res[]''' + + i, j, k = 0, 0, 0 + while (i < n and j < m): + if (a[i] <= b[j]): + res[k] = a[i] + i += 1 + k += 1 + else: + res[k] = b[j] + j += 1 + k += 1 + + '''Merging remaining elements of a[] (if any)''' + + while (i < n): + res[k] = a[i] + i += 1 + k += 1 + '''Merging remaining elements of b[] (if any)''' + while (j < m): + res[k] = b[j] + j += 1 + k += 1 + '''Driver code''' + +a = [ 10, 5, 15 ] +b = [ 20, 3, 2, 12 ] +n = len(a) +m = len(b) + + '''Final merge list''' + +res = [0 for i in range(n + m)] +sortedMerge(a, b, res, n, m) +print ""Sorted merged list :"" +for i in range(n + m): + print res[i], + + +" +Range Minimum Query (Square Root Decomposition and Sparse Table),"/*Java program to do range minimum query +in O(1) time with O(n Log n) extra space +and O(n Log n) preprocessing time*/ + +import java.util.*; +class GFG { + static int MAX = 500; +/* lookup[i][j] is going to store index + of minimum value in arr[i..j]. + Ideally lookup table size should not be fixed + and should be determined using n Log n. + It is kept constant to keep code simple.*/ + + static int[][] lookup = new int[MAX][MAX]; +/* Structure to represent a query range*/ + + static class Query { + int L, R; + public Query(int L, int R) + { + this.L = L; + this.R = R; + } + }; +/* Fills lookup array lookup[][] + in bottom up manner.*/ + + static void preprocess(int arr[], int n) + { +/* Initialize M for the intervals + with length 1*/ + + for (int i = 0; i < n; i++) + lookup[i][0] = i; +/* Compute values from smaller + to bigger intervals*/ + + for (int j = 1; (1 << j) <= n; j++) + { +/* Compute minimum value for + all intervals with size 2^j*/ + + for (int i = 0; + (i + (1 << j) - 1) < n; + i++) + { +/* For arr[2][10], we compare + arr[lookup[0][3]] + and arr[lookup[3][3]]*/ + + if (arr[lookup[i][j - 1]] + < arr[lookup[i + (1 << (j - 1))] + [j - 1]]) + lookup[i][j] = lookup[i][j - 1]; + else + lookup[i][j] + = lookup[i + (1 << (j - 1))][j - 1]; + } + } + } +/* Returns minimum of arr[L..R]*/ + + static int query(int arr[], int L, int R) + { +/* For [2,10], j = 3*/ + + int j = (int)Math.log(R - L + 1); +/* For [2,10], we compare + arr[lookup[0][3]] + and arr[lookup[3][3]],*/ + + if (arr[lookup[L][j]] + <= arr[lookup[R - (1 << j) + 1][j]]) + return arr[lookup[L][j]]; + else + return arr[lookup[R - (1 << j) + 1][j]]; + } +/* Prints minimum of given m + query ranges in arr[0..n-1]*/ + + static void RMQ(int arr[], int n, + Query q[], int m) + { +/* Fills table lookup[n][Log n]*/ + + preprocess(arr, n); +/* One by one compute sum of all queries*/ + + for (int i = 0; i < m; i++) + { +/* Left and right boundaries + of current range*/ + + int L = q[i].L, R = q[i].R; +/* Print sum of current query range*/ + + System.out.println(""Minimum of ["" + + L + "", "" + R + + ""] is "" + + query(arr, L, R)); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; + int n = a.length; + Query q[] = { new Query(0, 4), new Query(4, 7), + new Query(7, 8) }; + int m = q.length; + RMQ(a, n, q, m); + } +}"," '''Python3 program to do range minimum query +in O(1) time with O(n Log n) extra space +and O(n Log n) preprocessing time''' + +from math import log2 +MAX = 500 + '''lookup[i][j] is going to store index of +minimum value in arr[i..j]. +Ideally lookup table size should +not be fixed and should be determined +using n Log n. It is kept constant +to keep code simple.''' + +lookup = [[0 for i in range(500)] + for j in range(500)] + '''Structure to represent a query range''' + +class Query: + def __init__(self, l, r): + self.L = l + self.R = r + '''Fills lookup array lookup[][] +in bottom up manner.''' + +def preprocess(arr: list, n: int): + global lookup + ''' Initialize M for the + intervals with length 1''' + + for i in range(n): + lookup[i][0] = i + ''' Compute values from + smaller to bigger intervals''' + + j = 1 + while (1 << j) <= n: + ''' Compute minimum value for + all intervals with size 2^j''' + + i = 0 + while i + (1 << j) - 1 < n: + ''' For arr[2][10], we compare + arr[lookup[0][3]] and + arr[lookup[3][3]]''' + + if (arr[lookup[i][j - 1]] < + arr[lookup[i + (1 << (j - 1))][j - 1]]): + lookup[i][j] = lookup[i][j - 1] + else: + lookup[i][j] = lookup[i + + (1 << (j - 1))][j - 1] + i += 1 + j += 1 + '''Returns minimum of arr[L..R]''' + +def query(arr: list, L: int, R: int) -> int: + global lookup + ''' For [2,10], j = 3''' + + j = int(log2(R - L + 1)) + ''' For [2,10], we compare + arr[lookup[0][3]] and + arr[lookup[3][3]],''' + + if (arr[lookup[L][j]] <= + arr[lookup[R - (1 << j) + 1][j]]): + return arr[lookup[L][j]] + else: + return arr[lookup[R - (1 << j) + 1][j]] + '''Prints minimum of given +m query ranges in arr[0..n-1]''' + +def RMQ(arr: list, n: int, q: list, m: int): + ''' Fills table lookup[n][Log n]''' + + preprocess(arr, n) + ''' One by one compute sum of all queries''' + + for i in range(m): + ''' Left and right boundaries + of current range''' + + L = q[i].L + R = q[i].R + ''' Print sum of current query range''' + + print(""Minimum of [%d, %d] is %d"" % + (L, R, query(arr, L, R))) + '''Driver Code''' + +if __name__ == ""__main__"": + a = [7, 2, 3, 0, 5, 10, 3, 12, 18] + n = len(a) + q = [Query(0, 4), Query(4, 7), + Query(7, 8)] + m = len(q) + RMQ(a, n, q, m)" +Partitioning a linked list around a given value and keeping the original order,"/*Java program to partition a +linked list around a given value.*/ + +class GfG +{ + +/* Link list Node */ + +static class Node +{ + int data; + Node next; +} + +/*A utility function to create a new node*/ + +static Node newNode(int data) +{ + Node new_node = new Node(); + new_node.data = data; + new_node.next = null; + return new_node; +} + +/*Function to make two separate lists and return +head after concatenating*/ + +static Node partition(Node head, int x) +{ + + /* Let us initialize first and last nodes of + three linked lists + 1) Linked list of values smaller than x. + 2) Linked list of values equal to x. + 3) Linked list of values greater than x.*/ + + Node smallerHead = null, smallerLast = null; + Node greaterLast = null, greaterHead = null; + Node equalHead = null, equalLast =null; + +/* Now iterate original list and connect nodes + of appropriate linked lists.*/ + + while (head != null) + { +/* If current node is equal to x, append it + to the list of x values*/ + + if (head.data == x) + { + if (equalHead == null) + equalHead = equalLast = head; + else + { + equalLast.next = head; + equalLast = equalLast.next; + } + } + +/* If current node is less than X, append + it to the list of smaller values*/ + + else if (head.data < x) + { + if (smallerHead == null) + smallerLast = smallerHead = head; + else + { + smallerLast.next = head; + smallerLast = head; + } + } +/*Append to the list of greater values*/ + +else + { + if (greaterHead == null) + greaterLast = greaterHead = head; + else + { + greaterLast.next = head; + greaterLast = head; + } + } + head = head.next; + } + +/* Fix end of greater linked list to NULL if this + list has some nodes*/ + + if (greaterLast != null) + greaterLast.next = null; + +/* Connect three lists*/ + + +/* If smaller list is empty*/ + + if (smallerHead == null) + { + if (equalHead == null) + return greaterHead; + equalLast.next = greaterHead; + return equalHead; + } + +/* If smaller list is not empty + and equal list is empty*/ + + if (equalHead == null) + { + smallerLast.next = greaterHead; + return smallerHead; + } + +/* If both smaller and equal list + are non-empty*/ + + smallerLast.next = equalHead; + equalLast.next = greaterHead; + return smallerHead; +} + +/* Function to print linked list */ + +static void printList(Node head) +{ + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + /* Start with the empty list */ + + Node head = newNode(10); + head.next = newNode(4); + head.next.next = newNode(5); + head.next.next.next = newNode(30); + head.next.next.next.next = newNode(2); + head.next.next.next.next.next = newNode(50); + + int x = 3; + head = partition(head, x); + printList(head); +} +} + + +"," '''Python3 program to partition a +linked list around a given value.''' + + + '''Link list Node''' + +class Node: + def __init__(self): + self.data = 0 + self.next = None + + '''A utility function to create a new node''' + +def newNode( data): + + new_node = Node() + new_node.data = data + new_node.next = None + return new_node + + '''Function to make two separate lists and return +head after concatenating''' + +def partition( head, x) : + + ''' Let us initialize first and last nodes of + three linked lists + 1) Linked list of values smaller than x. + 2) Linked list of values equal to x. + 3) Linked list of values greater than x.''' + + smallerHead = None + smallerLast = None + greaterLast = None + greaterHead = None + equalHead = None + equalLast = None + + ''' Now iterate original list and connect nodes + of appropriate linked lists.''' + + while (head != None) : + + ''' If current node is equal to x, append it + to the list of x values''' + + if (head.data == x): + + if (equalHead == None): + equalHead = equalLast = head + else: + + equalLast.next = head + equalLast = equalLast.next + + ''' If current node is less than X, append + it to the list of smaller values''' + + elif (head.data < x): + + if (smallerHead == None): + smallerLast = smallerHead = head + else: + + smallerLast.next = head + smallerLast = head + + else : + ''' Append to the list of greater values''' + + + if (greaterHead == None) : + greaterLast = greaterHead = head + else: + + greaterLast.next = head + greaterLast = head + + head = head.next + + ''' Fix end of greater linked list to None if this + list has some nodes''' + + if (greaterLast != None) : + greaterLast.next = None + + ''' Connect three lists''' + + + ''' If smaller list is empty''' + + if (smallerHead == None) : + + if (equalHead == None) : + return greaterHead + equalLast.next = greaterHead + return equalHead + + ''' If smaller list is not empty + and equal list is empty''' + + if (equalHead == None) : + + smallerLast.next = greaterHead + return smallerHead + + ''' If both smaller and equal list + are non-empty''' + + smallerLast.next = equalHead + equalLast.next = greaterHead + return smallerHead + + '''Function to print linked list''' + +def printList(head) : + + temp = head + while (temp != None): + + print(temp.data ,end= "" "") + temp = temp.next + + '''Driver code''' + + + '''Start with the empty list''' + +head = newNode(10) +head.next = newNode(4) +head.next.next = newNode(5) +head.next.next.next = newNode(30) +head.next.next.next.next = newNode(2) +head.next.next.next.next.next = newNode(50) + +x = 3 +head = partition(head, x) +printList(head) + + +" +Print all full nodes in a Binary Tree,"/*Java program to find the all full nodes in +a given binary tree */ + +/* A binary tree node */ + +class Node +{ + int data; + Node left, right; + Node(int data) + { + left=right=null; + this.data=data; + } +};/* Traverses given tree in Inorder fashion and + prints all nodes that have both children as + non-empty. */ + +public class FullNodes { + public static void findFullNode(Node root) + { + if (root != null) + { + findFullNode(root.left); + if (root.left != null && root.right != null) + System.out.print(root.data+"" ""); + findFullNode(root.right); + } + } + +/*Driver program to test above function*/ + + public static void main(String args[]) { + Node root = new Node(1); + root.left = new Node(2); + root.right = new Node(3); + root.left.left = new Node(4); + root.right.left = new Node(5); + root.right.right = new Node(6); + root.right.left.right = new Node(7); + root.right.right.right = new Node(8); + root.right.left.right.left = new Node(9); + findFullNode(root); + } +}"," '''Python3 program to find the all +full nodes in a given binary tree +Binary Tree Node ''' + + ''' utility that allocates a newNode +with the given key ''' + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Traverses given tree in Inorder +fashion and prints all nodes that +have both children as non-empty. ''' + +def findFullNode(root) : + if (root != None) : + findFullNode(root.left) + if (root.left != None and + root.right != None) : + print(root.data, end = "" "") + findFullNode(root.right) + '''Driver Code ''' + +if __name__ == '__main__': + 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(6) + root.right.left.right = newNode(7) + root.right.right.right = newNode(8) + root.right.left.right.left = newNode(9) + findFullNode(root)" +Count possible ways to construct buildings,"class Building +{ +/* Returns count of possible ways for N sections*/ + + static int countWays(int N) + { +/* Base case*/ + + if (N == 1) +/*2 for one side and 4 for two sides*/ + +return 4; +/* countB is count of ways with a building at the end + countS is count of ways with a space at the end + prev_countB and prev_countS are previous values of + countB and countS respectively. + Initialize countB and countS for one side*/ + + int countB=1, countS=1, prev_countB, prev_countS; +/* Use the above recursive formula for calculating + countB and countS using previous values*/ + + for (int i=2; i<=N; i++) + { + prev_countB = countB; + prev_countS = countS; + countS = prev_countB + prev_countS; + countB = prev_countS; + } +/* Result for one side is sum of ways ending with building + and ending with space*/ + + int result = countS + countB; +/* Result for 2 sides is square of result for one side*/ + + return (result*result); + } + public static void main(String args[]) + { + int N = 3; + System.out.println(""Count of ways for ""+ N+"" sections is "" + +countWays(N)); + } +}"," '''Python 3 program to count all possible +way to construct buildings''' + '''Returns count of possible ways +for N sections''' + +def countWays(N) : + ''' Base case''' + + if (N == 1) : + ''' 2 for one side and 4 + for two sides''' + + return 4 + ''' countB is count of ways with a + building at the end + countS is count of ways with a + space at the end + prev_countB and prev_countS are + previous values of + countB and countS respectively. + Initialize countB and countS + for one side''' + + countB=1 + countS=1 + ''' Use the above recursive formula + for calculating + countB and countS using previous values''' + + for i in range(2,N+1) : + prev_countB = countB + prev_countS = countS + countS = prev_countB + prev_countS + countB = prev_countS + ''' Result for one side is sum of ways + ending with building + and ending with space''' + + result = countS + countB + ''' Result for 2 sides is square of + result for one side''' + + return (result*result) + '''Driver program''' + +if __name__ == ""__main__"": + N = 3 + print (""Count of ways for "", N + ,"" sections is "" ,countWays(N))" +"Find all pairs (a, b) in an array such that a % b = k","/*Java implementation to find such pairs*/ + +class Test { +/* method to find pair such that (a % b = k)*/ + + static boolean printPairs(int arr[], int n, int k) + { + boolean isPairFound = true; +/* Consider each and every pair*/ + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { +/* Print if their modulo equals to k*/ + + if (i != j && arr[i] % arr[j] == k) { + System.out.print(""("" + arr[i] + "", "" + arr[j] + "")"" + + "" ""); + isPairFound = true; + } + } + } + return isPairFound; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = { 2, 3, 5, 4, 7 }; + int k = 3; + if (printPairs(arr, arr.length, k) == false) + System.out.println(""No such pair exists""); + } +}"," '''Python3 implementation to find such pairs''' + + '''Function to find pair such that (a % b = k)''' + +def printPairs(arr, n, k): + isPairFound = True ''' Consider each and every pair''' + + for i in range(0, n): + for j in range(0, n): + ''' Print if their modulo equals to k''' + + if (i != j and arr[i] % arr[j] == k): + print(""("", arr[i], "", "", arr[j], "")"", + sep = """", end = "" "") + isPairFound = True + return isPairFound + '''Driver Code''' + +arr = [2, 3, 5, 4, 7] +n = len(arr) +k = 3 +if (printPairs(arr, n, k) == False): + print(""No such pair exists"")" +Number whose sum of XOR with given array range is maximum,"/*Java program to find smallest integer X +such that sum of its XOR with range is +maximum.*/ + +import java.lang.Math; +class GFG { + private static final int MAX = 2147483647; + static int[][] one = new int[100001][32]; +/* Function to make prefix array which counts + 1's of each bit up to that number*/ + + static void make_prefix(int A[], int n) + { + for (int j = 0; j < 32; j++) + one[0][j] = 0; +/* Making a prefix array which sums + number of 1's up to that position*/ + + for (int i = 1; i <= n; i++) + { + int a = A[i - 1]; + for (int j = 0; j < 32; j++) + { + int x = (int)Math.pow(2, j); +/* If j-th bit of a number is set then + add one to previously counted 1's*/ + + if ((a & x) != 0) + one[i][j] = 1 + one[i - 1][j]; + else + one[i][j] = one[i - 1][j]; + } + } + } +/* Function to find X*/ + + static int Solve(int L, int R) + { + int l = L, r = R; + int tot_bits = r - l + 1; +/* Initially taking maximum + value all bits 1*/ + + int X = MAX; +/* Iterating over each bit*/ + + for (int i = 0; i < 31; i++) + { +/* get 1's at ith bit between the range + L-R by subtracting 1's till + Rth number - 1's till L-1th number*/ + + int x = one[r][i] - one[l - 1][i]; +/* If 1's are more than or equal to 0's + then unset the ith bit from answer*/ + + if (x >= tot_bits - x) + { + int ith_bit = (int)Math.pow(2, i); +/* Set ith bit to 0 by + doing Xor with 1*/ + + X = X ^ ith_bit; + } + } + return X; + } +/* Driver program*/ + + public static void main(String[] args) + { + int n = 5, q = 3; + int A[] = { 210, 11, 48, 22, 133 }; + int L[] = { 1, 4, 2 }, R[] = { 3, 14, 4 }; + make_prefix(A, n); + for (int j = 0; j < q; j++) + System.out.println(Solve(L[j], R[j])); + } +}"," '''Python3 program to find smallest integer X +such that sum of its XOR with range is +maximum.''' + +import math +one = [[0 for x in range(32)] + for y in range(100001)] +MAX = 2147483647 + '''Function to make prefix array +which counts 1's of each bit +up to that number''' + +def make_prefix(A, n) : + global one, MAX + for j in range(0 , 32) : + one[0][j] = 0 + ''' Making a prefix array which + sums number of 1's up to + that position''' + + for i in range(1, n+1) : + a = A[i - 1] + for j in range(0 , 32) : + x = int(math.pow(2, j)) + ''' If j-th bit of a number + is set then add one to + previously counted 1's''' + + if (a & x) : + one[i][j] = 1 + one[i - 1][j] + else : + one[i][j] = one[i - 1][j] + '''Function to find X''' + +def Solve(L, R) : + global one, MAX + l = L + r = R + tot_bits = r - l + 1 + ''' Initially taking maximum + value all bits 1''' + + X = MAX + ''' Iterating over each bit''' + + for i in range(0, 31) : + ''' get 1's at ith bit between the + range L-R by subtracting 1's till + Rth number - 1's till L-1th number''' + + x = one[r][i] - one[l - 1][i] + ''' If 1's are more than or equal + to 0's then unset the ith bit + from answer''' + + if (x >= (tot_bits - x)) : + ith_bit = pow(2, i) + ''' Set ith bit to 0 by + doing Xor with 1''' + + X = X ^ ith_bit + return X + '''Driver Code''' + +n = 5 +q = 3 +A = [ 210, 11, 48, 22, 133 ] +L = [ 1, 4, 2 ] +R = [ 3, 14, 4 ] +make_prefix(A, n) +for j in range(0, q) : + print (Solve(L[j], R[j]),end=""\n"")" +The Stock Span Problem,"/*Java implementation for brute force method to calculate stock span values*/ + +import java.util.Arrays; +class GFG { +/* method to calculate stock span values*/ + + static void calculateSpan(int price[], int n, int S[]) + { +/* Span value of first day is always 1*/ + + S[0] = 1; +/* Calculate span value of remaining days by linearly checking + previous days*/ + + for (int i = 1; i < n; i++) { +/*Initialize span value*/ + +S[i] = 1; +/* Traverse left while the next element on left is smaller + than price[i]*/ + + for (int j = i - 1; (j >= 0) && (price[i] >= price[j]); j--) + S[i]++; + } + } +/* A utility function to print elements of array*/ + + static void printArray(int arr[]) + { + System.out.print(Arrays.toString(arr)); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int price[] = { 10, 4, 5, 90, 120, 80 }; + int n = price.length; + int S[] = new int[n]; +/* Fill the span values in array S[]*/ + + calculateSpan(price, n, S); +/* print the calculated span values*/ + + printArray(S); + } +}"," '''Python program for brute force method to calculate stock span values''' + + '''Fills list S[] with span values''' + +def calculateSpan(price, n, S): ''' Span value of first day is always 1''' + + S[0] = 1 + ''' Calculate span value of remaining days by linearly + checking previous days''' + + for i in range(1, n, 1): + '''Initialize span value''' + + S[i] = 1 + ''' Traverse left while the next element on left is + smaller than price[i]''' + + j = i - 1 + while (j>= 0) and (price[i] >= price[j]) : + S[i] += 1 + j -= 1 + '''A utility function to print elements of array''' + +def printArray(arr, n): + for i in range(n): + print(arr[i], end = "" "") + '''Driver program to test above function ''' + +price = [10, 4, 5, 90, 120, 80] +n = len(price) +S = [None] * n + '''Fill the span values in list S[]''' + +calculateSpan(price, n, S) + '''print the calculated span values''' + +printArray(S, n)" +Doubly Circular Linked List | Set 1 (Introduction and Insertion),"/*Java program to illustrate inserting a Node in +a Cicular Doubly Linked list in begging, end +and middle*/ + +import java.util.*; +class GFG +{ +static Node start; +/*Structure of a Node*/ + +static class Node +{ + int data; + Node next; + Node prev; +}; +/*Function to insert at the end*/ + +static void insertEnd(int value) +{ +/* If the list is empty, create a single node + circular and doubly list*/ + + if (start == null) + { + Node new_node = new Node(); + new_node.data = value; + new_node.next = new_node.prev = new_node; + start = new_node; + return; + } +/* If list is not empty*/ + + /* Find last node */ + + Node last = (start).prev; +/* Create Node dynamically*/ + + Node new_node = new Node(); + new_node.data = value; +/* Start is going to be next of new_node*/ + + new_node.next = start; +/* Make new node previous of start*/ + + (start).prev = new_node; +/* Make last preivous of new node*/ + + new_node.prev = last; +/* Make new node next of old last*/ + + last.next = new_node; +} +/*Function to insert Node at the beginning +of the List,*/ + +static void insertBegin(int value) +{ +/* Pointer points to last Node*/ + + Node last = (start).prev; + Node new_node = new Node(); +/*Inserting the data*/ + +new_node.data = value; +/* setting up previous and next of new node*/ + + new_node.next = start; + new_node.prev = last; +/* Update next and previous pointers of start + and last.*/ + + last.next = (start).prev = new_node; +/* Update start pointer*/ + + start = new_node; +} +/*Function to insert node with value as value1. +The new node is inserted after the node with +with value2*/ + +static void insertAfter(int value1, + int value2) +{ + Node new_node = new Node(); +/*Inserting the data*/ + +new_node.data = value1; +/* Find node having value2 and next node of it*/ + + Node temp = start; + while (temp.data != value2) + temp = temp.next; + Node next = temp.next; +/* insert new_node between temp and next.*/ + + temp.next = new_node; + new_node.prev = temp; + new_node.next = next; + next.prev = new_node; +} +static void display() +{ + Node temp = start; + System.out.printf(""\nTraversal in forward direction \n""); + while (temp.next != start) + { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } + System.out.printf(""%d "", temp.data); + System.out.printf(""\nTraversal in reverse direction \n""); + Node last = start.prev; + temp = last; + while (temp.prev != last) + { + System.out.printf(""%d "", temp.data); + temp = temp.prev; + } + System.out.printf(""%d "", temp.data); +} +/* Driver code*/ + +public static void main(String[] args) +{ + /* Start with the empty list */ + + Node start = null; +/* Insert 5. So linked list becomes 5.null*/ + + insertEnd(5); +/* Insert 4 at the beginning. So linked + list becomes 4.5*/ + + insertBegin(4); +/* Insert 7 at the end. So linked list + becomes 4.5.7*/ + + insertEnd(7); +/* Insert 8 at the end. So linked list + becomes 4.5.7.8*/ + + insertEnd(8); +/* Insert 6, after 5. So linked list + becomes 4.5.6.7.8*/ + + insertAfter(6, 5); + System.out.printf(""Created circular doubly linked list is: ""); + display(); +} +}"," '''Python3 program to illustrate inserting +a Node in a Cicular Doubly Linked list +in begging, end and middle''' + '''Structure of a Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + '''Function to insert at the end''' + +def insertEnd(value) : + global start + ''' If the list is empty, create a + single node circular and doubly list''' + + if (start == None) : + new_node = Node(0) + new_node.data = value + new_node.next = new_node.prev = new_node + start = new_node + return + ''' If list is not empty''' + + '''Find last node ''' + + last = (start).prev ''' Create Node dynamically''' + + new_node = Node(0) + new_node.data = value + ''' Start is going to be next of new_node''' + + new_node.next = start + ''' Make new node previous of start''' + + (start).prev = new_node + ''' Make last preivous of new node''' + + new_node.prev = last + ''' Make new node next of old last''' + + last.next = new_node + '''Function to insert Node at the beginning +of the List,''' + +def insertBegin( value) : + global start + ''' Pointer points to last Node''' + + last = (start).prev + new_node = Node(0) + '''Inserting the data''' + + new_node.data = value + ''' setting up previous and + next of new node''' + + new_node.next = start + new_node.prev = last + ''' Update next and previous pointers + of start and last.''' + + last.next = (start).prev = new_node + ''' Update start pointer''' + + start = new_node + '''Function to insert node with value as value1. +The new node is inserted after the node with +with value2''' + +def insertAfter(value1, value2) : + global start + new_node = Node(0) + '''Inserting the data''' + + new_node.data = value1 + ''' Find node having value2 and + next node of it''' + + temp = start + while (temp.data != value2) : + temp = temp.next + next = temp.next + ''' insert new_node between temp and next.''' + + temp.next = new_node + new_node.prev = temp + new_node.next = next + next.prev = new_node +def display() : + global start + temp = start + print (""Traversal in forward direction:"") + while (temp.next != start) : + print (temp.data, end = "" "") + temp = temp.next + print (temp.data) + print (""Traversal in reverse direction:"") + last = start.prev + temp = last + while (temp.prev != last) : + print (temp.data, end = "" "") + temp = temp.prev + print (temp.data) + '''Driver Code''' + +if __name__ == '__main__': + global start + ''' Start with the empty list''' + + start = None + ''' Insert 5. So linked list becomes 5.None''' + + insertEnd(5) + ''' Insert 4 at the beginning. So linked + list becomes 4.5''' + + insertBegin(4) + ''' Insert 7 at the end. So linked list + becomes 4.5.7''' + + insertEnd(7) + ''' Insert 8 at the end. So linked list + becomes 4.5.7.8''' + + insertEnd(8) + ''' Insert 6, after 5. So linked list + becomes 4.5.6.7.8''' + + insertAfter(6, 5) + print (""Created circular doubly linked list is: "") + display()" +Print all nodes that don't have sibling,"/*Java program to print all nodes +that don't have sibling*/ + + +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + + Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + Node root; + +/* Function to print all non-root nodes + that don't have a sibling*/ + + void printSingles(Node node) + { +/* Base case*/ + + if (node == null) + return; + +/* If this is an internal node, recur for left + and right subtrees*/ + + if (node.left != null && node.right != null) + { + printSingles(node.left); + printSingles(node.right); + } + +/* If left child is NULL and right + is not, print right child + and recur for right child*/ + + else if (node.right != null) + { + System.out.print(node.right.data + "" ""); + printSingles(node.right); + } + +/* If right child is NULL and left + is not, print left child + and recur for left child*/ + + else if (node.left != null) + { + System.out.print( node.left.data + "" ""); + printSingles(node.left); + } +} +/* Driver program to test the above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + + /* Let us construct the tree + shown in above diagram */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.right = new Node(4); + tree.root.right.left = new Node(5); + tree.root.right.left.right = new Node(6); + tree.printSingles(tree.root); + } +} + + +"," '''Python3 program to find singles in a given binary tree''' + + + '''A Binary Tree Node''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + + '''Function to print all non-root nodes that don't have +a sibling''' + +def printSingles(root): + + ''' Base Case''' + + if root is None: + return + + ''' If this is an internal node , recur for left + and right subtrees''' + + if root.left is not None and root.right is not None: + printSingles(root.left) + printSingles(root.right) + + ''' If left child is NULL, and right is not, print + right child and recur for right child''' + + elif root.right is not None: + print root.right.key, + printSingles(root.right) + + ''' If right child is NULL and left is not, print + left child and recur for left child''' + + elif root.left is not None: + print root.left.key, + printSingles(root.left) + + '''Driver program to test above function''' + + + ''' Let us create binary tree + given in the above example''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.right = Node(4) +root.right.left = Node(5) +root.right.left.left = Node(6) +printSingles(root) + " +Least frequent element in an array,"/*Java program to find the least frequent element +in an array*/ + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +class GFG { + + static int leastFrequent(int arr[],int n) + { + +/* Insert all elements in hash.*/ + + Map count = + new HashMap(); + + for(int i = 0; i < n; i++) + { + int key = arr[i]; + if(count.containsKey(key)) + { + int freq = count.get(key); + freq++; + count.put(key,freq); + } + else + count.put(key,1); + } + +/* find min frequency.*/ + + int min_count = n+1, res = -1; + for(Entry val : count.entrySet()) + { + if (min_count >= val.getValue()) + { + res = val.getKey(); + min_count = val.getValue(); + } + } + + return res; + } + +/* driver program*/ + + public static void main (String[] args) { + + int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; + int n = arr.length; + + System.out.println(leastFrequent(arr,n)); + } +} + + +"," '''Python3 program to find the most +frequent element in an array.''' + +import math as mt + +def leastFrequent(arr, n): + + ''' Insert all elements in Hash.''' + + Hash = dict() + for i in range(n): + if arr[i] in Hash.keys(): + Hash[arr[i]] += 1 + else: + Hash[arr[i]] = 1 + + ''' find the max frequency''' + + min_count = n + 1 + res = -1 + for i in Hash: + if (min_count >= Hash[i]): + res = i + min_count = Hash[i] + + return res + + '''Driver Code''' + +arr = [1, 3, 2, 1, 2, 2, 3, 1] +n = len(arr) +print(leastFrequent(arr, n)) + + +" +Print array after it is right rotated K times,"/*Java Implementation of Right Rotation +of an Array K number of times*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class Array_Rotation +{ + +/*Function to rightRotate array*/ + +static void RightRotate(int a[], + int n, int k) +{ + +/* If rotation is greater + than size of array*/ + + k=k%n; + + for(int i = 0; i < n; i++) + { + if(i= l; --i) { + count++; + if (count == c) + System.out.println(a[m - 1][i]+"" ""); + } + m--; + } + /* check the first column from + the remaining columns */ + + if (l < n) { + for (i = m - 1; i >= k; --i) { + count++; + if (count == c) + System.out.println(a[i][l]+"" ""); + } + l++; + } + } + } + /* Driver program to test above functions */ + + public static void main (String[] args) + { + int a[][] = { { 1, 2, 3, 4, 5, 6 }, + { 7, 8, 9, 10, 11, 12 }, + { 13, 14, 15, 16, 17, 18 } }; + int k = 17; + spiralPrint(R, C, a, k); + } +}","R = 3 +C = 6 +def spiralPrint(m, n, a, c): + k = 0 + l = 0 + count = 0 + ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index + i - iterator + ''' + + while (k < m and l < n): + + '''check the first row from + the remaining rows ''' + + for i in range(l,n): + count+=1 + if (count == c): + print(a[k][i] , end="" "") + k+=1 ''' check the last column + from the remaining columns ''' + + for i in range(k,m): + count+=1 + if (count == c): + print(a[i][n - 1],end="" "") + n-=1 + ''' check the last row from + the remaining rows ''' + + if (k < m): + for i in range(n - 1,l-1,-1): + count+=1 + if (count == c): + print(a[m - 1][i],end="" "") + m-=1 + ''' check the first column from + the remaining columns ''' + + if (l < n): + for i in range(m - 1,k-1,-1): + count+=1 + if (count == c): + print(a[i][l],end="" "") + l+=1 + ''' Driver program to test above functions ''' + +a = [[1, 2, 3, 4, 5, 6 ],[ 7, 8, 9, 10, 11, 12 ],[ 13, 14, 15, 16, 17, 18]] +k = 17 +spiralPrint(R, C, a, k)" +Matrix Chain Multiplication | DP-8,"/*Java program using memoization*/ + +import java.io.*; +import java.util.*; +class GFG +{ + static int[][] dp = new int[100][100]; +/* Function for matrix chain multiplication*/ + + static int matrixChainMemoised(int[] p, int i, int j) + { + if (i == j) + { + return 0; + } + if (dp[i][j] != -1) + { + return dp[i][j]; + } + dp[i][j] = Integer.MAX_VALUE; + for (int k = i; k < j; k++) + { + dp[i][j] = Math.min( + dp[i][j], matrixChainMemoised(p, i, k) + + matrixChainMemoised(p, k + 1, j) + + p[i - 1] * p[k] * p[j]); + } + return dp[i][j]; + } + static int MatrixChainOrder(int[] p, int n) + { + int i = 1, j = n - 1; + return matrixChainMemoised(p, i, j); + } +/* Driver Code*/ + + public static void main (String[] args) + { + int arr[] = { 1, 2, 3, 4 }; + int n= arr.length; + for (int[] row : dp) + Arrays.fill(row, -1); + System.out.println(""Minimum number of multiplications is "" + MatrixChainOrder(arr, n)); + } +}"," '''Python program using memoization''' + +import sys +dp = [[-1 for i in range(100)] for j in range(100)] + '''Function for matrix chain multiplication''' + +def matrixChainMemoised(p, i, j): + if(i == j): + return 0 + if(dp[i][j] != -1): + return dp[i][j] + dp[i][j] = sys.maxsize + for k in range(i,j): + dp[i][j] = min(dp[i][j], matrixChainMemoised(p, i, k) + matrixChainMemoised(p, k + 1, j)+ p[i - 1] * p[k] * p[j]) + return dp[i][j] +def MatrixChainOrder(p,n): + i = 1 + j = n - 1 + return matrixChainMemoised(p, i, j) + '''Driver Code''' + +arr = [1, 2, 3, 4] +n = len(arr) +print(""Minimum number of multiplications is"",MatrixChainOrder(arr, n))" +Insert node into the middle of the linked list,"/*Java implementation to insert node +at the middle of the linked list*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class LinkedList +{ +/*head of list*/ + +static Node head; + + /* Node Class */ + + static class Node { + int data; + Node next; + +/* Constructor to create a new node*/ + + Node(int d) { + data = d; + next = null; + } + } + +/* function to insert node at the + middle of the linked list*/ + + static void insertAtMid(int x) + { +/* if list is empty*/ + + if (head == null) + head = new Node(x); + else { +/* get a new node*/ + + Node newNode = new Node(x); + + Node ptr = head; + int len = 0; + +/* calculate length of the linked list + , i.e, the number of nodes*/ + + while (ptr != null) { + len++; + ptr = ptr.next; + } + +/* 'count' the number of nodes after which + the new node is to be inserted*/ + + int count = ((len % 2) == 0) ? (len / 2) : + (len + 1) / 2; + ptr = head; + +/* 'ptr' points to the node after which + the new node is to be inserted*/ + + while (count-- > 1) + ptr = ptr.next; + +/* insert the 'newNode' and adjust + the required links*/ + + newNode.next = ptr.next; + ptr.next = newNode; + } + } + +/* function to display the linked list*/ + + static void display() + { + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + } + } + +/* Driver program to test above*/ + + public static void main (String[] args) + { +/* Creating the list 1.2.4.5*/ + + head = null; + head = new Node(1); + head.next = new Node(2); + head.next.next = new Node(4); + head.next.next.next = new Node(5); + + System.out.println(""Linked list before ""+ + ""insertion: ""); + display(); + + int x = 3; + insertAtMid(x); + + System.out.println(""\nLinked list after""+ + "" insertion: ""); + display(); + } +} + + +"," '''Python3 implementation to insert node +at the middle of a linked list''' + + + '''Node class''' + +class Node: + + ''' constructor to create a new node''' + + def __init__(self, data): + self.data = data + self.next = None + + '''function to insert node at the +middle of linked list given the head''' + +def insertAtMid(head, x): + + '''if the list is empty''' + + if(head == None): + head = Node(x) + else: + + ''' create a new node for the value + to be inserted''' + + newNode = Node(x) + + ptr = head + length = 0 + + ''' calcualte the length of the linked + list''' + + while(ptr != None): + ptr = ptr.next + length += 1 + + ''' 'count' the number of node after which + the new node has to be inserted''' + + if(length % 2 == 0): + count = length / 2 + else: + (length + 1) / 2 + + ptr = head + + ''' move ptr to the node after which + the new node has to inserted''' + + while(count > 1): + count -= 1 + ptr = ptr.next + + ''' insert the 'newNode' and adjust + links accordingly''' + + newNode.next = ptr.next + ptr.next = newNode + + '''function to displat the linked list''' + +def display(head): + temp = head + while(temp != None): + print(str(temp.data), end = "" "") + temp = temp.next + + '''Driver Code''' + + + '''Creating the linked list 1.2.4.5''' + +head = Node(1) +head.next = Node(2) +head.next.next = Node(4) +head.next.next.next = Node(5) + +print(""Linked list before insertion: "", end = """") +display(head) + + '''inserting 3 in the middle of the linked list.''' + +x = 3 +insertAtMid(head, x) + +print(""\nLinked list after insertion: "" , end = """") +display(head) + + +" +Delete Edge to minimize subtree sum difference,"/*Java program to minimize subtree sum +difference by one edge deletion*/ + +import java.util.ArrayList; +class Graph{ +static int res; +/*DFS method to traverse through edges, +calculating subtree sum at each node +and updating the difference between subtrees*/ + +static void dfs(int u, int parent, int totalSum, + ArrayList[] edge, int subtree[]) +{ + int sum = subtree[u]; +/* Loop for all neighbors except parent + and aggregate sum over all subtrees*/ + + for(int i = 0; i < edge[u].size(); i++) + { + int v = edge[u].get(i); + if (v != parent) + { + dfs(v, u, totalSum, edge, subtree); + sum += subtree[v]; + } + } +/* Store sum in current node's subtree index*/ + + subtree[u] = sum; +/* At one side subtree sum is 'sum' and other + side subtree sum is 'totalSum - sum' so + their difference will be totalSum - 2*sum, + by which we'll update res*/ + + if (u != 0 && Math.abs(totalSum - 2 * sum) < res) + res = Math.abs(totalSum - 2 * sum); +} +/*Method returns minimum subtree sum difference*/ + +static int getMinSubtreeSumDifference(int vertex[], + int[][] edges, + int N) +{ + int totalSum = 0; + int[] subtree = new int[N]; +/* Calculating total sum of tree and + initializing subtree sum's by + vertex values*/ + + for(int i = 0; i < N; i++) + { + subtree[i] = vertex[i]; + totalSum += vertex[i]; + } +/* Filling edge data structure*/ + + @SuppressWarnings(""unchecked"") + ArrayList[] edge = new ArrayList[N]; + for(int i = 0; i < N; i++) + { + edge[i] = new ArrayList<>(); + } + for(int i = 0; i < N - 1; i++) + { + edge[edges[i][0]].add(edges[i][1]); + edge[edges[i][1]].add(edges[i][0]); + } +/* Calling DFS method at node 0, with + parent as -1*/ + + dfs(0, -1, totalSum, edge, subtree); + return res; +} +/*Driver code*/ + +public static void main(String[] args) +{ + res = Integer.MAX_VALUE; + int[] vertex = { 4, 2, 1, 6, 3, 5, 2 }; + int[][] edges = { { 0, 1 }, { 0, 2 }, + { 0, 3 }, { 2, 4 }, + { 2, 5 }, { 3, 6 } }; + int N = vertex.length; + System.out.println(getMinSubtreeSumDifference( + vertex, edges, N)); +} +}"," '''Python3 program to minimize subtree +Sum difference by one edge deletion''' + '''DFS method to traverse through edges, +calculating subtree Sum at each node and +updating the difference between subtrees''' + +def dfs(u, parent, totalSum, edge, + subtree, res): + Sum = subtree[u] + ''' loop for all neighbors except parent + and aggregate Sum over all subtrees''' + + for i in range(len(edge[u])): + v = edge[u][i] + if (v != parent): + dfs(v, u, totalSum, edge, + subtree, res) + Sum += subtree[v] + ''' store Sum in current node's + subtree index''' + + subtree[u] = Sum + ''' at one side subtree Sum is 'Sum' and + other side subtree Sum is 'totalSum - Sum' + so their difference will be totalSum - 2*Sum, + by which we'll update res''' + + if (u != 0 and abs(totalSum - 2 * Sum) < res[0]): + res[0] = abs(totalSum - 2 * Sum) + '''Method returns minimum subtree +Sum difference''' + +def getMinSubtreeSumDifference(vertex, edges, N): + totalSum = 0 + subtree = [None] * N + ''' Calculating total Sum of tree + and initializing subtree Sum's + by vertex values''' + + for i in range(N): + subtree[i] = vertex[i] + totalSum += vertex[i] + ''' filling edge data structure''' + + edge = [[] for i in range(N)] + for i in range(N - 1): + edge[edges[i][0]].append(edges[i][1]) + edge[edges[i][1]].append(edges[i][0]) + res = [999999999999] + ''' calling DFS method at node 0, + with parent as -1''' + + dfs(0, -1, totalSum, edge, subtree, res) + return res[0] + '''Driver Code''' + +if __name__ == '__main__': + vertex = [4, 2, 1, 6, 3, 5, 2] + edges = [[0, 1], [0, 2], [0, 3], + [2, 4], [2, 5], [3, 6]] + N = len(vertex) + print(getMinSubtreeSumDifference(vertex, + edges, N))" +Find minimum and maximum elements in singly Circular Linked List,"/*Java program to find minimum and maximum +value from singly circular linked list*/ + +class GFG +{ + +/*structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to print minimum and maximum +nodes of the circular linked list*/ + +static void printMinMax(Node head) +{ +/* check list is empty*/ + + if (head == null) + { + return; + } + +/* pointer for traversing*/ + + Node current; + +/* initialize head to current pointer*/ + + current = head; + +/* initialize max int value to min + initialize min int value to max*/ + + int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; + +/* While last node is not reached*/ + + while (current.next != head) + { + +/* If current node data is lesser for min + then replace it*/ + + if (current.data < min) + { + min = current.data; + } + +/* If current node data is greater for max + then replace it*/ + + if (current.data > max) + { + max = current.data; + } + + current = current.next; + } + + System.out.println( ""\nMinimum = "" + min + "", Maximum = "" + max); +} + +/*Function to insert a node at the end of +a Circular linked list*/ + +static Node insertNode(Node head, int data) +{ + Node current = head; + +/* Create a new node*/ + + Node newNode = new Node(); + +/* check node is created or not*/ + + if (newNode == null) + { + System.out.printf(""\nMemory Error\n""); + return null; + } + +/* insert data into newly created node*/ + + newNode.data = data; + +/* check list is empty + if not have any node then + make first node it*/ + + if (head == null) + { + newNode.next = newNode; + head = newNode; + return head; + } + +/* if list have already some node*/ + + else + { + +/* move firt node to last node*/ + + while (current.next != head) + { + current = current.next; + } + +/* put first or head node address + in new node link*/ + + newNode.next = head; + +/* put new node address into + last node link(next)*/ + + current.next = newNode; + } + return head; +} + +/*Function to print the Circular linked list*/ + +static void displayList(Node head) +{ + + Node current = head; + +/* if list is empty simply show message*/ + + if (head == null) + { + System.out.printf(""\nDisplay List is empty\n""); + return; + } + +/* traverse first to last node*/ + + else + { + do + { + System.out.printf(""%d "", current.data); + current = current.next; + } while (current != head); + } +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + Node Head = null; + + Head=insertNode(Head, 99); + Head=insertNode(Head, 11); + Head=insertNode(Head, 22); + Head=insertNode(Head, 33); + Head=insertNode(Head, 44); + Head=insertNode(Head, 55); + Head=insertNode(Head, 66); + + System.out.println(""Initial List: ""); + + displayList(Head); + + printMinMax(Head); +} +} + + +"," '''Python3 program to find minimum and maximum +value from singly circular linked list''' + + + '''structure for a node''' + +class Node: + + def __init__(self): + + self.data = 0 + self.next = None + + '''Function to print minimum and maximum +nodes of the circular linked list''' + +def printMinMax(head): + + ''' check list is empty''' + + if (head == None): + return; + + ''' initialize head to current pointer''' + + current = head; + + ''' initialize max int value to min + initialize min int value to max''' + + min = 1000000000 + max = -1000000000; + + ''' While last node is not reached''' + + while True: + + ''' If current node data is lesser for min + then replace it''' + + if (current.data < min): + min = current.data; + + ''' If current node data is greater for max + then replace it''' + + if (current.data > max): + max = current.data; + + current = current.next; + if(current == head): + break + print('Minimum = {}, Maximum = {}'.format(min, max)) + + '''Function to insert a node at the end of +a Circular linked list''' + +def insertNode(head, data): + current = head; + + ''' Create a new node''' + + newNode = Node() + + ''' check node is created or not''' + + if not newNode: + print(""\nMemory Error""); + return head + + ''' insert data into newly created node''' + + newNode.data = data; + + ''' check list is empty + if not have any node then + make first node it''' + + if (head == None): + newNode.next = newNode; + head = newNode; + return head + + ''' if list have already some node''' + + else: + + ''' move firt node to last node''' + + while (current.next != head): + current = current.next; + + ''' put first or head node address + in new node link''' + + newNode.next = head; + + ''' put new node address into + last node link(next)''' + + current.next = newNode; + return head + + '''Function to print the Circular linked list''' + +def displayList(head): + current = head; + + ''' if list is empty simply show message''' + + if (head == None): + print(""\nDisplay List is empty""); + return; + + ''' traverse first to last node''' + + else: + + while True: + print(current.data, end=' '); + current = current.next; + if(current==head): + break + print() + + '''Driver Code''' + +if __name__=='__main__': + + Head = None; + + Head = insertNode(Head, 99); + Head = insertNode(Head, 11); + Head = insertNode(Head, 22); + Head = insertNode(Head, 33); + Head = insertNode(Head, 44); + Head = insertNode(Head, 55); + Head = insertNode(Head, 66); + + print(""Initial List: "", end = '') + + displayList(Head); + + printMinMax(Head); + + +" +Search an element in a Linked List (Iterative and Recursive),"/*Recursive Java program to search an element +in linked list*/ + + + +/*Node class*/ + +class Node +{ + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } +} + +/*Linked list class*/ + +class LinkedList +{ +/*Head of list*/ + +Node head; + +/* Inserts a new node at the front of the list*/ + + public void push(int new_data) + { +/* Allocate new node and putting data*/ + + Node new_node = new Node(new_data); + +/* Make next of new node as head*/ + + new_node.next = head; + +/* Move the head to point to new Node*/ + + head = new_node; + } + +/* Checks whether the value x is present + in linked list*/ + + public boolean search(Node head, int x) + { +/* Base case*/ + + if (head == null) + return false; + +/* If key is present in current node, + return true*/ + + if (head.data == x) + return true; + +/* Recur for remaining list*/ + + return search(head.next, x); + } + +/* Driver function to test the above functions*/ + + public static void main(String args[]) + { +/* Start with the empty list*/ + + LinkedList llist = new LinkedList(); + + /* Use push() to construct below list + 14->21->11->30->10 */ + + llist.push(10); + llist.push(30); + llist.push(11); + llist.push(21); + llist.push(14); + + if (llist.search(llist.head, 21)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +} + +", +How to swap two numbers without using a temporary variable?,"/*Java program to implement +the above approach*/ + +class GFG { +/*Swap function*/ + + static void swap(int[] xp, int[] yp) + { + xp[0] = xp[0] ^ yp[0]; + yp[0] = xp[0] ^ yp[0]; + xp[0] = xp[0] ^ yp[0]; + } +/* Driver code*/ + + public static void main(String[] args) + { + int[] x = { 10 }; + swap(x, x); + System.out.println(""After swap(&x, &x): x = "" + + x[0]); + } +}"," '''Python program to implement +the above approach''' + + '''Swap function''' + +def swap(xp, yp): + xp[0] = xp[0] ^ yp[0] + yp[0] = xp[0] ^ yp[0] + xp[0] = xp[0] ^ yp[0] + '''Driver code''' + +x = [10] +swap(x, x) +print(""After swap(&x, &x): x = "", x[0])" +Find whether a given number is a power of 4 or not,"/*Java program to check +if given number is +power of 4 or not*/ + +import java.io.*; +class GFG { + static boolean isPowerOfFour(int n) { + return n != 0 && ((n&(n-1)) == 0) && (n & 0xAAAAAAAA) == 0; + } +/* Driver Code*/ + + public static void main(String[] args) { + int test_no = 64; + if(isPowerOfFour(test_no)) + System.out.println(test_no + + "" is a power of 4""); + else + System.out.println(test_no + + "" is not a power of 4""); + } +}"," '''Python3 program to check +if given number is +power of 4 or not''' + +def isPowerOfFour(n): + return (n != 0 and + ((n & (n - 1)) == 0) and + not(n & 0xAAAAAAAA)); + '''Driver code''' + +test_no = 64; +if(isPowerOfFour(test_no)): + print(test_no ,""is a power of 4""); +else: + print(test_no , ""is not a power of 4"");" +Maximize sum of consecutive differences in a circular array,"/*Java program to maximize the sum of difference +between consecutive elements in circular array*/ + +import java.io.*; +import java.util.Arrays; + +class MaxSum +{ +/* Return the maximum Sum of difference between + consecutive elements.*/ + + static int maxSum(int arr[], int n) + { + int sum = 0; + +/* Sorting the array.*/ + + Arrays.sort(arr); + +/* Subtracting a1, a2, a3,....., a(n/2)-1, + an/2 twice and adding a(n/2)+1, a(n/2)+2, + a(n/2)+3,....., an - 1, an twice.*/ + + for (int i = 0; i < n/2; i++) + { + sum -= (2 * arr[i]); + sum += (2 * arr[n - i - 1]); + } + + return sum; + } + +/* Driver Program*/ + + public static void main (String[] args) + { + int arr[] = { 4, 2, 1, 8 }; + int n = arr.length; + System.out.println(maxSum(arr, n)); + } +} + +"," '''Python3 program to maximize the sum of difference +between consecutive elements in circular array''' + + + '''Return the maximum Sum of difference +between consecutive elements''' + +def maxSum(arr, n): + sum = 0 + + ''' Sorting the array''' + + arr.sort() + + ''' Subtracting a1, a2, a3,....., a(n/2)-1, an/2 + twice and adding a(n/2)+1, a(n/2)+2, a(n/2)+3,. + ...., an - 1, an twice.''' + + for i in range(0, int(n / 2)) : + sum -= (2 * arr[i]) + sum += (2 * arr[n - i - 1]) + + return sum + + + '''Driver Program''' + +arr = [4, 2, 1, 8] +n = len(arr) +print (maxSum(arr, n)) + + +" +Populate Inorder Successor for all nodes,"/*Java program to populate inorder traversal of all nodes*/ + +class Node +{ + int data; + Node left, right, next; + + Node(int item) + { + data = item; + left = right = next = null; + } +}/*A wrapper over populateNextRecur*/ + + void populateNext(Node node) { +/* The first visited node will be the rightmost node + next of the rightmost node will be NULL*/ + + populateNextRecur(node, next); + } + /* Set next of all descendants of p by traversing them in reverse Inorder */ + + void populateNextRecur(Node p, Node next_ref) { + if (p != null) { +/* First set the next pointer in right subtree*/ + + populateNextRecur(p.right, next_ref); +/* Set the next as previously visited node in reverse Inorder*/ + + p.next = next_ref; +/* Change the prev for subsequent node*/ + + next_ref = p; +/* Finally, set the next pointer in right subtree*/ + + populateNextRecur(p.left, next_ref); + } + }"," '''Python3 program to populate inorder traversal of all nodes''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.next = None +next = None '''A wrapper over populateNextRecur''' + +def populateNext(node): + ''' The first visited node will be the rightmost node + next of the rightmost node will be NULL''' + + populateNextRecur(node, next) + '''/* Set next of all descendants of p by +traversing them in reverse Inorder */''' + +def populateNextRecur(p, next_ref): + if (p != None): + ''' First set the next pointer in right subtree''' + + populateNextRecur(p.right, next_ref) + ''' Set the next as previously visited node in reverse Inorder''' + + p.next = next_ref + ''' Change the prev for subsequent node''' + + next_ref = p + ''' Finally, set the next pointer in right subtree''' + + populateNextRecur(p.left, next_ref)" +Minimum number of swaps required to sort an array,"/*Java program to find +minimum number of swaps +required to sort an array*/ + +import javafx.util.Pair; +import java.util.ArrayList; +import java.util.*; +class GfG +{ +/* Function returns the + minimum number of swaps + required to sort the array*/ + + public static int minSwaps(int[] arr) + { + int n = arr.length; +/* Create two arrays and + use as pairs where first + array is element and second array + is position of first element*/ + + ArrayList > arrpos = + new ArrayList > (); + for (int i = 0; i < n; i++) + arrpos.add(new Pair (arr[i], i)); +/* Sort the array by array element values to + get right position of every element as the + elements of second array.*/ + + arrpos.sort(new Comparator>() + { + @Override + public int compare(Pair o1, + Pair o2) + { + if (o1.getKey() > o2.getKey()) + return -1; + else if (o1.getKey().equals(o2.getKey())) + return 0; + else + return 1; + } + });/* To keep track of visited elements. Initialize + all elements as not visited or false.*/ + + Boolean[] vis = new Boolean[n]; + Arrays.fill(vis, false); +/* Initialize result*/ + + int ans = 0; +/* Traverse array elements*/ + + for (int i = 0; i < n; i++) + { +/* already swapped and corrected or + already present at correct pos*/ + + if (vis[i] || arrpos.get(i).getValue() == i) + continue; +/* find out the number of node in + this cycle and add in ans*/ + + int cycle_size = 0; + int j = i; + while (!vis[j]) + { + vis[j] = true; +/* move to next node*/ + + j = arrpos.get(j).getValue(); + cycle_size++; + } +/* Update answer by adding current cycle.*/ + + if(cycle_size > 0) + { + ans += (cycle_size - 1); + } + } +/* Return result*/ + + return ans; + } +} +/*Driver class*/ + +class MinSwaps +{ +/* Driver program to test the above function*/ + + public static void main(String[] args) + { + int []a = {1, 5, 4, 3, 2}; + GfG g = new GfG(); + System.out.println(g.minSwaps(a)); + } +}"," '''Python3 program to find +minimum number of swaps +required to sort an array''' + '''Function returns the minimum +number of swaps required to +sort the array''' + +def minSwaps(arr): + n = len(arr) + ''' Create two arrays and use + as pairs where first array + is element and second array + is position of first element''' + + arrpos = [*enumerate(arr)] + ''' Sort the array by array element + values to get right position of + every element as the elements + of second array.''' + + arrpos.sort(key = lambda it : it[1]) + ''' To keep track of visited elements. + Initialize all elements as not + visited or false.''' + + vis = {k : False for k in range(n)} + ''' Initialize result''' + + ans = 0 + + ''' Traverse array elements''' + + for i in range(n): ''' alreadt swapped or + alreadt present at + correct position''' + + if vis[i] or arrpos[i][0] == i: + continue + ''' find number of nodes + in this cycle and + add it to ans''' + + cycle_size = 0 + j = i + while not vis[j]: + vis[j] = True ''' move to next node''' + + j = arrpos[j][0] + cycle_size += 1 + ''' update answer by adding + current cycle''' + + if cycle_size > 0: + ans += (cycle_size - 1) + ''' return answer''' + + return ans + '''Driver Code ''' + +arr = [1, 5, 4, 3, 2] +print(minSwaps(arr))" +Largest Sum Contiguous Subarray,"/*Java program to print largest +contiguous array sum*/ + +class GFG { + static void maxSubArraySum(int a[], int size) + { + int max_so_far = Integer.MIN_VALUE, + max_ending_here = 0,start = 0, + end = 0, s = 0; + for (int i = 0; i < size; i++) + { + max_ending_here += a[i]; + if (max_so_far < max_ending_here) + { + max_so_far = max_ending_here; + start = s; + end = i; + } + if (max_ending_here < 0) + { + max_ending_here = 0; + s = i + 1; + } + } + System.out.println(""Maximum contiguous sum is "" + + max_so_far); + System.out.println(""Starting index "" + start); + System.out.println(""Ending index "" + end); + } +/* Driver code*/ + + public static void main(String[] args) + { + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = a.length; + maxSubArraySum(a, n); + } +}"," '''Function to find the maximum contiguous subarray +and print its starting and end index''' + +from sys import maxsize +def maxSubArraySum(a,size): + max_so_far = -maxsize - 1 + max_ending_here = 0 + start = 0 + end = 0 + s = 0 + for i in range(0,size): + max_ending_here += a[i] + if max_so_far < max_ending_here: + max_so_far = max_ending_here + start = s + end = i + if max_ending_here < 0: + max_ending_here = 0 + s = i+1 + print (""Maximum contiguous sum is %d""%(max_so_far)) + print (""Starting Index %d""%(start)) + print (""Ending Index %d""%(end)) + '''Driver program to test maxSubArraySum''' + +a = [-2, -3, 4, -1, -2, 1, 5, -3] +maxSubArraySum(a,len(a))" +Program for nth Catalan Number,"/*Java program for nth Catalan Number*/ + +class GFG { +/* Returns value of Binomial Coefficient C(n, k)*/ + + static long binomialCoeff(int n, int k) + { + long res = 1; +/* Since C(n, k) = C(n, n-k)*/ + + if (k > n - k) { + k = n - k; + } +/* Calculate value of [n*(n-1)*---*(n-k+1)] / + [k*(k-1)*---*1]*/ + + for (int i = 0; i < k; ++i) { + res *= (n - i); + res /= (i + 1); + } + return res; + } +/* A Binomial coefficient based function + to find nth catalan number in O(n) time*/ + + static long catalan(int n) + { +/* Calculate value of 2nCn*/ + + long c = binomialCoeff(2 * n, n); +/* return 2nCn/(n+1)*/ + + return c / (n + 1); + } +/* Driver code*/ + + public static void main(String[] args) + { + for (int i = 0; i < 10; i++) { + System.out.print(catalan(i) + "" ""); + } + } +}"," '''Python program for nth Catalan Number''' + '''Returns value of Binomial Coefficient C(n, k)''' + +def binomialCoefficient(n, k): + res = 1 + ''' since C(n, k) = C(n, n - k)''' + + if (k > n - k): + k = n - k + ''' Calculate value of [n * (n-1) *---* (n-k + 1)] + / [k * (k-1) *----* 1]''' + + for i in range(k): + res = res * (n - i) + res = res / (i + 1) + return res + '''A Binomial coefficient based function to +find nth catalan number in O(n) time''' + +def catalan(n): + + + ''' Calculate value of 2nCn''' + + c = binomialCoefficient(2*n, n) ''' return 2nCn/(n+1)''' + + return c/(n + 1) '''Driver Code''' + +for i in range(10): + print(catalan(i), end="" "")" +Minimum number of squares whose sum equals to given number n,"/*A dynamic programming based +JAVA program to find minimum +number of squares whose sum +is equal to a given number*/ + +class squares +{ +/* Returns count of minimum + squares that sum to n*/ + + static int getMinSquares(int n) + { +/* We need to add a check + here for n. If user enters + 0 or 1 or 2 + the below array creation + will go OutOfBounds.*/ + + if (n <= 3) + return n; +/* Create a dynamic programming + table + to store sq*/ + + int dp[] = new int[n + 1]; +/* getMinSquares table for + base case entries*/ + + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + dp[3] = 3; +/* getMinSquares rest of the + table using recursive + formula*/ + + for (int i = 4; i <= n; i++) + { +/* max value is i as i can + always be represented + as 1*1 + 1*1 + ...*/ + + dp[i] = i; +/* Go through all smaller numbers to + to recursively find minimum*/ + + for (int x = 1; x <= Math.ceil( + Math.sqrt(i)); x++) + { + int temp = x * x; + if (temp > i) + break; + else + dp[i] = Math.min(dp[i], 1 + + dp[i - temp]); + } + } +/* Store result and free dp[]*/ + + int res = dp[n]; + return res; + } +/* Driver Code*/ + + public static void main(String args[]) + { + System.out.println(getMinSquares(6)); + } +}"," '''A dynamic programming based Python +program to find minimum number of +squares whose sum is equal to a +given number''' + +from math import ceil, sqrt + '''Returns count of minimum squares +that sum to n''' + +def getMinSquares(n): + ''' getMinSquares table + for base case entries''' + + dp = [0, 1, 2, 3] + ''' getMinSquares rest of the table + using recursive formula''' + + for i in range(4, n + 1): + ''' max value is i as i can always + be represented as 1 * 1 + 1 * 1 + ...''' + + dp.append(i) + ''' Go through all smaller numbers + to recursively find minimum''' + + for x in range(1, int(ceil(sqrt(i))) + 1): + temp = x * x; + if temp > i: + break + else: + dp[i] = min(dp[i], 1 + dp[i-temp]) + ''' Store result''' + + return dp[n] + '''Driver code''' + +print(getMinSquares(6))" +Find Minimum Depth of a Binary Tree,"/* Java implementation to find minimum depth + of a given Binary tree */ + +/* Class containing left and right child of current +node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +public class BinaryTree +{ +/* Root of the Binary Tree*/ + + Node root; + int minimumDepth() + { + return minimumDepth(root); + } + /* Function to calculate the minimum depth of the tree */ + + int minimumDepth(Node root) + { +/* Corner case. Should never be hit unless the code is + called on root = NULL*/ + + if (root == null) + return 0; +/* Base case : Leaf Node. This accounts for height = 1.*/ + + if (root.left == null && root.right == null) + return 1; +/* If left subtree is NULL, recur for right subtree*/ + + if (root.left == null) + return minimumDepth(root.right) + 1; +/* If right subtree is NULL, recur for left subtree*/ + + if (root.right == null) + return minimumDepth(root.left) + 1; + return Math.min(minimumDepth(root.left), + minimumDepth(root.right)) + 1; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { +/* Let us construct the Tree shown in the above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println(""The minimum depth of ""+ + ""binary tree is : "" + tree.minimumDepth()); + } +}"," '''Python program to find minimum depth of a given Binary Tree''' + + '''Tree node''' + +class Node: + def __init__(self , key): + self.data = key + self.left = None + self.right = None + ''' Function to calculate the minimum depth of the tree ''' + +def minDepth(root): ''' Corner Case.Should never be hit unless the code is + called on root = NULL''' + + if root is None: + return 0 + ''' Base Case : Leaf node.This acoounts for height = 1''' + + if root.left is None and root.right is None: + return 1 + ''' If left subtree is Null, recur for right subtree''' + + if root.left is None: + return minDepth(root.right)+1 + ''' If right subtree is Null , recur for left subtree''' + + if root.right is None: + return minDepth(root.left) +1 + return min(minDepth(root.left), minDepth(root.right))+1 + '''Driver Program''' + + ''' Let us construct the Tree shown in the above figure''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +print minDepth(root)" +Shortest Un-ordered Subarray,"/*JAVA program to find shortest subarray which is +unsorted.*/ + +import java.util.*; +import java.io.*; +class GFG { +/* boolean function to check array elements + are in increasing order or not*/ + + public static boolean increasing(int a[],int n) + { + for (int i = 0; i < n - 1; i++) + if (a[i] >= a[i + 1]) + return false; + return true; + } +/* boolean function to check array elements + are in decreasing order or not*/ + + public static boolean decreasing(int arr[],int n) + { + for (int i = 0; i < n - 1; i++) + if (arr[i] < arr[i + 1]) + return false; + return true; + } + public static int shortestUnsorted(int a[],int n) + { +/* increasing and decreasing are two functions. + if function return true value then print + 0 otherwise 3.*/ + + if (increasing(a, n) == true || + decreasing(a, n) == true) + return 0; + else + return 3; + } +/* driver program*/ + + public static void main (String[] args) { + int ar[] = new int[]{7, 9, 10, 8, 11}; + int n = ar.length; + System.out.println(shortestUnsorted(ar,n)); + } +}"," '''Python3 program to find shortest +subarray which is unsorted + ''' '''Bool function for checking an array +elements are in increasing''' + +def increasing(a, n): + for i in range(0, n - 1): + if (a[i] >= a[i + 1]): + return False + return True + '''Bool function for checking an array +elements are in decreasing''' + +def decreasing(a, n): + for i in range(0, n - 1): + if (a[i] < a[i + 1]): + return False + return True +def shortestUnsorted(a, n): + ''' increasing and decreasing are two functions. + if function return True value then print + 0 otherwise 3.''' + + if (increasing(a, n) == True or + decreasing(a, n) == True): + return 0 + else: + return 3 + '''Driver code''' + +ar = [7, 9, 10, 8, 11] +n = len(ar) +print(shortestUnsorted(ar, n))" +Convert a given Binary Tree to Doubly Linked List | Set 1,"/*Java program to convert binary tree to double linked list*/ + +/* A binary tree node has data, and left and right pointers */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* This is the core function to convert Tree to list. This function + follows steps 1 and 2 of the above algorithm */ + + Node bintree2listUtil(Node node) + { +/* Base case*/ + + if (node == null) + return node; +/* Convert the left subtree and link to root*/ + + if (node.left != null) + { +/* Convert the left subtree*/ + + Node left = bintree2listUtil(node.left); +/* Find inorder predecessor. After this loop, left + will point to the inorder predecessor*/ + + for (; left.right != null; left = left.right); +/* Make root as next of the predecessor*/ + + left.right = node; +/* Make predecssor as previous of root*/ + + node.left = left; + } +/* Convert the right subtree and link to root*/ + + if (node.right != null) + { +/* Convert the right subtree*/ + + Node right = bintree2listUtil(node.right); +/* Find inorder successor. After this loop, right + will point to the inorder successor*/ + + for (; right.left != null; right = right.left); +/* Make root as previous of successor*/ + + right.left = node; +/* Make successor as next of root*/ + + node.right = right; + } + return node; + } +/* The main function that first calls bintree2listUtil(), then follows + step 3 of the above algorithm*/ + + Node bintree2list(Node node) + { +/* Base case*/ + + if (node == null) + return node; +/* Convert to DLL using bintree2listUtil()*/ + + node = bintree2listUtil(node); +/* bintree2listUtil() returns root node of the converted + DLL. We need pointer to the leftmost node which is + head of the constructed DLL, so move to the leftmost node*/ + + while (node.left != null) + node = node.left; + return node; + } + /* Function to print nodes in a given doubly linked list */ + + void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.right; + } + } + /* Driver program to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); +/* Let us create the tree shown in above diagram*/ + + tree.root = new Node(10); + tree.root.left = new Node(12); + tree.root.right = new Node(15); + tree.root.left.left = new Node(25); + tree.root.left.right = new Node(30); + tree.root.right.left = new Node(36); +/* Convert to DLL*/ + + Node head = tree.bintree2list(tree.root); +/* Print the converted list*/ + + tree.printList(head); + } +}"," '''Python program to convert +binary tree to doubly linked list''' + + + '''Binary tree Node class has + data, left and right child''' +class Node(object): + def __init__(self, item): + self.data = item + self.left = None + self.right = None + + '''This is a utility function to + convert the binary tree to doubly + linked list. Most of the core task + is done by this function.''' +def BTToDLLUtil(root): + + ''' Base case''' + + if root is None: + return root ''' Convert left subtree + and link to root''' + + if root.left: + ''' Convert the left subtree''' + + left = BTToDLLUtil(root.left) + ''' Find inorder predecessor, After + this loop, left will point to the + inorder predecessor of root''' + + while left.right: + left = left.right + ''' Make root as next of predecessor''' + + left.right = root + ''' Make predecessor as + previous of root''' + + root.left = left + ''' Convert the right subtree + and link to root''' + + if root.right: + ''' Convert the right subtree''' + + right = BTToDLLUtil(root.right) + ''' Find inorder successor, After + this loop, right will point to + the inorder successor of root''' + + while right.left: + right = right.left + ''' Make root as previous + of successor''' + + right.left = root + ''' Make successor as + next of root''' + + root.right = right + return root + ''' The main function that first calls bintree2listUtil(), then follows + step 3 of the above algorithm''' + +def BTToDLL(root): + + ''' Base case''' + + if root is None: + return root ''' Convert to doubly linked + list using BLLToDLLUtil''' + + root = BTToDLLUtil(root) + ''' We need pointer to left most + node which is head of the + constructed Doubly Linked list''' + + while root.left: + root = root.left + return root + + '''Function to print the given + doubly linked list''' +def print_list(head): + if head is None: + return + while head: + print(head.data, end = "" "") + head = head.right + '''Driver Code''' +if __name__ == '__main__': + + ''' Let us create the tree shown in above diagram''' + root = Node(10) + root.left = Node(12) + root.right = Node(15) + root.left.left = Node(25) + root.left.right = Node(30) + root.right.left = Node(36) + ''' Convert to DLL''' + + head = BTToDLL(root) + ''' Print the converted list''' + + print_list(head)" +Delete consecutive same words in a sequence,"/*Java program to remove consecutive same words*/ + +import java.util.Vector; +class Test +{ +/* Method to find the size of manipulated sequence*/ + + static int removeConsecutiveSame(Vector v) + { + int n = v.size(); +/* Start traversing the sequence*/ + + for (int i=0; i 0) + i--; +/* Reduce sequence size*/ + + n = n-2; + } +/* Increment i, if not equal*/ + + else + i++; + } +/* Return modified size*/ + + return v.size(); + } +/* Driver method*/ + + public static void main(String[] args) + { + Vector v = new Vector<>(); + v.addElement(""tom""); v.addElement(""jerry""); + v.addElement(""jerry"");v.addElement(""tom""); + System.out.println(removeConsecutiveSame(v)); + } +}"," '''Python3 program to remove consecutive +same words + ''' '''Function to find the size of +manipulated sequence ''' + +def removeConsecutiveSame(v): + n = len(v) + ''' Start traversing the sequence''' + + i = 0 + while(i < n - 1): + ''' Compare the current string with + next one Erase both if equal ''' + + if ((i + 1) < len(v)) and (v[i] == v[i + 1]): + ''' Erase function delete the element and + also shifts other element that's why + i is not updated ''' + + v = v[:i] + v = v[:i] + ''' Update i, as to check from previous + element again ''' + + if (i > 0): + i -= 1 + ''' Reduce sequence size ''' + + n = n - 2 + ''' Increment i, if not equal ''' + + else: + i += 1 + ''' Return modified size ''' + + return len(v[:i - 1]) + '''Driver Code''' + +if __name__ == '__main__': + v = [""tom"", ""jerry"", ""jerry"", ""tom""] + print(removeConsecutiveSame(v))" +Selection Sort,"/*Java program for implementation of Selection Sort*/ + +class SelectionSort +{ + +/*sort function*/ + + void sort(int arr[]) + { + int n = arr.length;/* One by one move boundary of unsorted subarray*/ + + for (int i = 0; i < n-1; i++) + { +/* Find the minimum element in unsorted array*/ + + int min_idx = i; + for (int j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; +/* Swap the found minimum element with the first + element*/ + + int temp = arr[min_idx]; + arr[min_idx] = arr[i]; + arr[i] = temp; + } + } +/* Prints the array*/ + + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i 0) + node.data = node.data + diff; + /* THIS IS TRICKY --> If node's data is greater than children + sum, then increment subtree by diff */ + + if (diff < 0) +/* -diff is used to make diff positive*/ + + increment(node, -diff); + } + } + /* This function is used to increment subtree by diff */ + + void increment(Node node, int diff) + { + /* IF left child is not NULL then increment it */ + + if (node.left != null) + { + node.left.data = node.left.data + diff; +/* Recursively call to fix the descendants of node->left*/ + + increment(node.left, diff); + } +/*Else increment right child*/ + +else if (node.right != null) + { + node.right.data = node.right.data + diff; +/* Recursively call to fix the descendants of node->right*/ + + increment(node.right, diff); + } + } + /* Given a binary tree, printInorder() prints out its + inorder traversal*/ + + void printInorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.data + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(50); + tree.root.left = new Node(7); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(1); + tree.root.right.right = new Node(30); + System.out.println(""Inorder traversal before conversion is :""); + tree.printInorder(tree.root); + tree.convertTree(tree.root); + System.out.println(""""); + System.out.println(""Inorder traversal after conversion is :""); + tree.printInorder(tree.root); + } +}"," '''Program to convert an aribitary binary tree +to a tree that holds children sum property ''' + + '''This function changes a tree to +hold children sum property ''' + +def convertTree(node): + left_data = 0 + right_data = 0 + diff=0 + ''' If tree is empty or it's a + leaf node then return true ''' + + if (node == None or (node.left == None and + node.right == None)): + return + else: + ''' convert left and right subtrees ''' + + convertTree(node.left) + convertTree(node.right) + ''' If left child is not present then 0 + is used as data of left child ''' + + if (node.left != None): + left_data = node.left.data + ''' If right child is not present then 0 + is used as data of right child ''' + + if (node.right != None): + right_data = node.right.data + ''' get the diff of node's data + and children sum ''' + + diff = left_data + right_data - node.data + ''' If node's children sum is greater + than the node's data ''' + + if (diff > 0): + node.data = node.data + diff + ''' THIS IS TRICKY -. If node's data is + greater than children sum, then increment + subtree by diff ''' + + if (diff < 0): + '''-diff is used to''' + + increment(node, -diff) ''' This function is used to increment + subtree by diff ''' + +def increment(node, diff): + ''' IF left child is not None + then increment it ''' + + if(node.left != None): + node.left.data = node.left.data + diff + ''' Recursively call to fix the + descendants of node.left''' + + increment(node.left, diff) + '''Else increment right child''' + + elif(node.right != None): + node.right.data = node.right.data + diff + increment(node.right, diff) + ''' Recursively call to fix the + descendants of node.right''' + + increment(node.right, diff) + ''' Given a binary tree, printInorder() +prints out its inorder traversal''' + +def printInorder(node): + if (node == None): + return + ''' first recur on left child ''' + + printInorder(node.left) + ''' then print the data of node ''' + + print(node.data,end="" "") + ''' now recur on right child ''' + + printInorder(node.right) + '''Helper function that allocates a new +node with the given data and None +left and right poers.''' + +class newNode: + def __init__(self, key): + self.data = key + self.left = None + self.right = None '''Driver Code ''' + +if __name__ == '__main__': + root = newNode(50) + root.left = newNode(7) + root.right = newNode(2) + root.left.left = newNode(3) + root.left.right = newNode(5) + root.right.left = newNode(1) + root.right.right = newNode(30) + print(""Inorder traversal before conversion"") + printInorder(root) + convertTree(root) + print(""\nInorder traversal after conversion "") + printInorder(root)" +Expression contains redundant bracket or not,"/* Java Program to check whether valid +expression is redundant or not*/ + +import java.util.Stack; +public class GFG { +/*Function to check redundant brackets in a +balanced expression*/ + + static boolean checkRedundancy(String s) { +/* create a stack of characters*/ + + Stack st = new Stack<>(); + char[] str = s.toCharArray(); +/* Iterate through the given expression*/ + + for (char ch : str) { +/* if current character is close parenthesis ')'*/ + + if (ch == ')') { + char top = st.peek(); + st.pop(); +/* If immediate pop have open parenthesis '(' + duplicate brackets found*/ + + boolean flag = true; + while (top != '(') { +/* Check for operators in expression*/ + + if (top == '+' || top == '-' + || top == '*' || top == '/') { + flag = false; + } +/* Fetch top element of stack*/ + + top = st.peek(); + st.pop(); + } +/* If operators not found*/ + + if (flag == true) { + return true; + } + } else { +/*push open parenthesis '(',*/ + +st.push(ch); +/*operators and operands to stack*/ + +} + } + return false; + } +/*Function to check redundant brackets*/ + + static void findRedundant(String str) { + boolean ans = checkRedundancy(str); + if (ans == true) { + System.out.println(""Yes""); + } else { + System.out.println(""No""); + } + } +/*Driver code*/ + + public static void main(String[] args) { + String str = ""((a+b))""; + findRedundant(str); + str = ""(a+(b)/c)""; + findRedundant(str); + str = ""(a+b*(c-d))""; + findRedundant(str); + } +}"," '''Python3 Program to check whether valid +expression is redundant or not + ''' '''Function to check redundant brackets +in a balanced expression''' + +def checkRedundancy(Str): + ''' create a stack of characters''' + + st = [] + ''' Iterate through the given expression''' + + for ch in Str: + ''' if current character is close + parenthesis ')''' + ''' + if (ch == ')'): + top = st[-1] + st.pop() + ''' If immediate pop have open parenthesis + '(' duplicate brackets found''' + + flag = True + while (top != '('): + ''' Check for operators in expression''' + + if (top == '+' or top == '-' or + top == '*' or top == '/'): + flag = False + ''' Fetch top element of stack''' + + top = st[-1] + st.pop() + ''' If operators not found''' + + if (flag == True): + return True + else: + '''append open parenthesis '(',''' + + st.append(ch) + ''' operators and operands to stack''' + + return False + '''Function to check redundant brackets''' + +def findRedundant(Str): + ans = checkRedundancy(Str) + if (ans == True): + print(""Yes"") + else: + print(""No"") + '''Driver code''' + +if __name__ == '__main__': + Str = ""((a+b))"" + findRedundant(Str) + Str = ""(a+(b)/c)"" + findRedundant(Str) + Str = ""(a+b*(c-d))"" + findRedundant(Str)" +"Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap","/*Java program to check if a given tree is +Binary Heap or not*/ + +import java.io.*; +import java.util.*; +public class detheap +{ +/* Returns true if given level order traversal + is Min Heap.*/ + + static boolean isMinHeap(int []level) + { + int n = level.length - 1; +/* First non leaf node is at index (n/2-1). + Check whether each parent is greater than child*/ + + for (int i=(n/2-1) ; i>=0 ; i--) + { +/* Left child will be at index 2*i+1 + Right child will be at index 2*i+2*/ + + if (level[i] > level[2 * i + 1]) + return false; + if (2*i + 2 < n) + { +/* If parent is greater than right child*/ + + if (level[i] > level[2 * i + 2]) + return false; + } + } + return true; + } +/* Driver code*/ + + public static void main(String[] args) + throws IOException + { + int[] level = new int[]{10, 15, 14, 25, 30}; + if (isMinHeap(level)) + System.out.println(""True""); + else + System.out.println(""False""); + } +}"," '''Python3 program to check if a given +tree is Binary Heap or not ''' + + '''Returns true if given level order +traversal is Min Heap. ''' + +def isMinHeap(level, n): ''' First non leaf node is at index + (n/2-1). Check whether each parent + is greater than child ''' + + for i in range(int(n / 2) - 1, -1, -1): + ''' Left child will be at index 2*i+1 + Right child will be at index 2*i+2 ''' + + if level[i] > level[2 * i + 1]: + return False + if 2 * i + 2 < n: + ''' If parent is greater than right child ''' + + if level[i] > level[2 * i + 2]: + return False + return True + '''Driver code ''' + +if __name__ == '__main__': + level = [10, 15, 14, 25, 30] + n = len(level) + if isMinHeap(level, n): + print(""True"") + else: + print(""False"")" +Maximum possible difference of two subsets of an array,"/*java find maximum difference of +subset sum*/ + +import java. io.*; +import java .util.*; +public class GFG { +/* function for maximum subset diff*/ + + static int maxDiff(int []arr, int n) + { + int result = 0; +/* sort the array*/ + + Arrays.sort(arr); +/* calculate the result*/ + + for (int i = 0; i < n - 1; i++) + { + if (arr[i] != arr[i + 1]) + result += Math.abs(arr[i]); + else + i++; + } +/* check for last element*/ + + if (arr[n - 2] != arr[n - 1]) + result += Math.abs(arr[n - 1]); +/* return result*/ + + return result; + } +/* driver program*/ + + static public void main (String[] args) + { + int[] arr = { 4, 2, -3, 3, -2, -2, 8 }; + int n = arr.length; + System.out.println(""Maximum Difference = "" + + maxDiff(arr, n)); + } +}"," '''Python 3 find maximum difference +of subset sum + ''' '''function for maximum subset diff''' + +def maxDiff(arr, n): + result = 0 + ''' sort the array''' + + arr.sort() + ''' calculate the result''' + + for i in range(n - 1): + if (abs(arr[i]) != abs(arr[i + 1])): + result += abs(arr[i]) + else: + pass + ''' check for last element''' + + if (arr[n - 2] != arr[n - 1]): + result += abs(arr[n - 1]) + ''' return result''' + + return result + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ 4, 2, -3, 3, -2, -2, 8 ] + n = len(arr) + print(""Maximum Difference = "" , + maxDiff(arr, n))" +Queries for number of distinct elements in a subarray,"/*Java code to find number of distinct numbers +in a subarray */ + +import java.io.*; +import java.util.*; + +class GFG +{ + static int MAX = 1000001; + +/* structure to store queries*/ + + static class Query + { + int l, r, idx; + } + +/* updating the bit array*/ + + static void update(int idx, int val, + int bit[], int n) + { + for (; idx <= n; idx += idx & -idx) + bit[idx] += val; + } + +/* querying the bit array*/ + + static int query(int idx, int bit[], int n) + { + int sum = 0; + for (; idx > 0; idx -= idx & -idx) + sum += bit[idx]; + return sum; + } + + static void answeringQueries(int[] arr, int n, + Query[] queries, int q) + { + +/* initialising bit array*/ + + int[] bit = new int[n + 1]; + Arrays.fill(bit, 0); + +/* holds the rightmost index of any number + as numbers of a[i] are less than or equal to 10^6*/ + + int[] last_visit = new int[MAX]; + Arrays.fill(last_visit, -1); + +/* answer for each query*/ + + int[] ans = new int[q]; + int query_counter = 0; + for (int i = 0; i < n; i++) + { + +/* If last visit is not -1 update -1 at the + idx equal to last_visit[arr[i]]*/ + + if (last_visit[arr[i]] != -1) + update(last_visit[arr[i]] + 1, -1, bit, n); + +/* Setting last_visit[arr[i]] as i and updating + the bit array accordingly*/ + + last_visit[arr[i]] = i; + update(i + 1, 1, bit, n); + +/* If i is equal to r of any query store answer + for that query in ans[]*/ + + while (query_counter < q && queries[query_counter].r == i) + { + ans[queries[query_counter].idx] = + query(queries[query_counter].r + 1, bit, n) + - query(queries[query_counter].l, bit, n); + query_counter++; + } + } + +/* print answer for each query*/ + + for (int i = 0; i < q; i++) + System.out.println(ans[i]); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int a[] = { 1, 1, 2, 1, 3 }; + int n = a.length; + Query[] queries = new Query[3]; + for (int i = 0; i < 3; i++) + queries[i] = new Query(); + queries[0].l = 0; + queries[0].r = 4; + queries[0].idx = 0; + queries[1].l = 1; + queries[1].r = 3; + queries[1].idx = 1; + queries[2].l = 2; + queries[2].r = 4; + queries[2].idx = 2; + int q = queries.length; + Arrays.sort(queries, new Comparator() + { + public int compare(Query x, Query y) + { + if (x.r < y.r) + return -1; + else if (x.r == y.r) + return 0; + else + return 1; + } + }); + answeringQueries(a, n, queries, q); + } +} + + +"," '''Python3 code to find number of +distinct numbers in a subarray''' + +MAX = 1000001 + + '''structure to store queries''' + +class Query: + def __init__(self, l, r, idx): + self.l = l + self.r = r + self.idx = idx + + '''updating the bit array''' + +def update(idx, val, bit, n): + while idx <= n: + bit[idx] += val + idx += idx & -idx + + '''querying the bit array''' + +def query(idx, bit, n): + summ = 0 + while idx: + summ += bit[idx] + idx -= idx & -idx + return summ + +def answeringQueries(arr, n, queries, q): + + ''' initialising bit array''' + + bit = [0] * (n + 1) + + ''' holds the rightmost index of + any number as numbers of a[i] + are less than or equal to 10^6''' + + last_visit = [-1] * MAX + + ''' answer for each query''' + + ans = [0] * q + + query_counter = 0 + for i in range(n): + + ''' If last visit is not -1 update -1 at the + idx equal to last_visit[arr[i]]''' + + if last_visit[arr[i]] != -1: + update(last_visit[arr[i]] + 1, -1, bit, n) + + ''' Setting last_visit[arr[i]] as i and + updating the bit array accordingly''' + + last_visit[arr[i]] = i + update(i + 1, 1, bit, n) + + ''' If i is equal to r of any query store answer + for that query in ans[]''' + + while query_counter < q and queries[query_counter].r == i: + ans[queries[query_counter].idx] = \ + query(queries[query_counter].r + 1, bit, n) - \ + query(queries[query_counter].l, bit, n) + query_counter += 1 + + ''' print answer for each query''' + + for i in range(q): + print(ans[i]) + + '''Driver Code''' + +if __name__ == ""__main__"": + a = [1, 1, 2, 1, 3] + n = len(a) + queries = [Query(0, 4, 0), + Query(1, 3, 1), + Query(2, 4, 2)] + q = len(queries) + + queries.sort(key = lambda x: x.r) + answeringQueries(a, n, queries, q) + + +" +Find k-th smallest element in BST (Order Statistics in BST),"/*A simple inorder traversal based Java program +to find k-th smallest element in a BST.*/ + +import java.io.*; +import java.util.*; +/*A BST node*/ + +class Node { + int data; + Node left, right; + int lCount; + Node(int x) + { + data = x; + left = right = null; + lCount = 0; + } +} +class Gfg +{ +/* Recursive function to insert an key into BST*/ + + public static Node insert(Node root, int x) + { + if (root == null) + return new Node(x); +/* If a node is inserted in left subtree, then + lCount of this node is increased. For simplicity, + we are assuming that all keys (tried to be + inserted) are distinct.*/ + + if (x < root.data) { + root.left = insert(root.left, x); + root.lCount++; + } + else if (x > root.data) + root.right = insert(root.right, x); + return root; + } +/* Function to find k'th largest element in BST + Here count denotes the number of + nodes processed so far*/ + + public static Node kthSmallest(Node root, int k) + { +/* base case*/ + + if (root == null) + return null; + int count = root.lCount + 1; + if (count == k) + return root; + if (count > k) + return kthSmallest(root.left, k); +/* else search in right subtree*/ + + return kthSmallest(root.right, k - count); + } +/* main function*/ + + public static void main(String args[]) + { + Node root = null; + int keys[] = { 20, 8, 22, 4, 12, 10, 14 }; + for (int x : keys) + root = insert(root, x); + int k = 4; + Node res = kthSmallest(root, k); + if (res == null) + System.out.println(""There are less "" + + ""than k nodes in the BST""); + else + System.out.println(""K-th Smallest"" + + "" Element is "" + res.data); + } +}"," '''A simple inorder traversal based Python3 +program to find k-th smallest element in a BST.''' '''A BST node''' + +class newNode: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + self.lCount = 0 + '''Recursive function to insert +an key into BST''' + +def insert(root, x): + if (root == None): + return newNode(x) + ''' If a node is inserted in left subtree, + then lCount of this node is increased. + For simplicity, we are assuming that + all keys (tried to be inserted) are + distinct.''' + + if (x < root.data): + root.left = insert(root.left, x) + root.lCount += 1 + elif (x > root.data): + root.right = insert(root.right, x); + return root + '''Function to find k'th largest element +in BST. Here count denotes the number +of nodes processed so far''' + +def kthSmallest(root, k): + ''' Base case''' + + if (root == None): + return None + count = root.lCount + 1 + if (count == k): + return root + if (count > k): + return kthSmallest(root.left, k) + ''' Else search in right subtree''' + + return kthSmallest(root.right, k - count) + '''Driver code''' + +if __name__ == '__main__': + root = None + keys = [ 20, 8, 22, 4, 12, 10, 14 ] + for x in keys: + root = insert(root, x) + k = 4 + res = kthSmallest(root, k) + if (res == None): + print(""There are less than k nodes in the BST"") + else: + print(""K-th Smallest Element is"", res.data)" +2-Satisfiability (2-SAT) Problem,"/*Java implementation to find if the given +expression is satisfiable using the +Kosaraju's Algorithm*/ + +import java.io.*; +import java.util.*; +class GFG{ +static final int MAX = 100000; +/*Data structures used to implement Kosaraju's +Algorithm. Please refer +http:www.geeksforgeeks.org/strongly-connected-components/*/ + +@SuppressWarnings(""unchecked"") +static List > adj = new ArrayList(); +@SuppressWarnings(""unchecked"") +static List > adjInv = new ArrayList(); +static boolean[] visited = new boolean[MAX]; +static boolean[] visitedInv = new boolean[MAX]; +static Stack s = new Stack(); +/*This array will store the SCC that the +particular node belongs to*/ + +static int[] scc = new int[MAX]; +/*counter maintains the number of the SCC*/ + +static int counter = 1; +/*Adds edges to form the original graph void*/ + +static void addEdges(int a, int b) +{ + adj.get(a).add(b); +} +/*Add edges to form the inverse graph*/ + +static void addEdgesInverse(int a, int b) +{ + adjInv.get(b).add(a); +} +/*For STEP 1 of Kosaraju's Algorithm*/ + +static void dfsFirst(int u) +{ + if (visited[u]) + return; + visited[u] = true; + for(int i = 0; i < adj.get(u).size(); i++) + dfsFirst(adj.get(u).get(i)); + s.push(u); +} +/*For STEP 2 of Kosaraju's Algorithm*/ + +static void dfsSecond(int u) +{ + if (visitedInv[u]) + return; + visitedInv[u] = true; + for(int i = 0; i < adjInv.get(u).size(); i++) + dfsSecond(adjInv.get(u).get(i)); + scc[u] = counter; +} +/*Function to check 2-Satisfiability*/ + +static void is2Satisfiable(int n, int m, + int a[], int b[]) +{ +/* Adding edges to the graph*/ + + for(int i = 0; i < m; i++) + { +/* variable x is mapped to x + variable -x is mapped to n+x = n-(-x) + for a[i] or b[i], addEdges -a[i] -> b[i] + AND -b[i] -> a[i]*/ + + if (a[i] > 0 && b[i] > 0) + { + addEdges(a[i] + n, b[i]); + addEdgesInverse(a[i] + n, b[i]); + addEdges(b[i] + n, a[i]); + addEdgesInverse(b[i] + n, a[i]); + } + else if (a[i] > 0 && b[i] < 0) + { + addEdges(a[i] + n, n - b[i]); + addEdgesInverse(a[i] + n, n - b[i]); + addEdges(-b[i], a[i]); + addEdgesInverse(-b[i], a[i]); + } + else if (a[i] < 0 && b[i] > 0) + { + addEdges(-a[i], b[i]); + addEdgesInverse(-a[i], b[i]); + addEdges(b[i] + n, n - a[i]); + addEdgesInverse(b[i] + n, n - a[i]); + } + else + { + addEdges(-a[i], n - b[i]); + addEdgesInverse(-a[i], n - b[i]); + addEdges(-b[i], n - a[i]); + addEdgesInverse(-b[i], n - a[i]); + } + } +/* STEP 1 of Kosaraju's Algorithm which + traverses the original graph*/ + + for(int i = 1; i <= 2 * n; i++) + if (!visited[i]) + dfsFirst(i); +/* STEP 2 pf Kosaraju's Algorithm which + traverses the inverse graph. After this, + array scc[] stores the corresponding value*/ + + while (!s.isEmpty()) + { + int top = s.peek(); + s.pop(); + if (!visitedInv[top]) + { + dfsSecond(top); + counter++; + } + } + for(int i = 1; i <= n; i++) + { +/* For any 2 vairable x and -x lie in + same SCC*/ + + if (scc[i] == scc[i + n]) + { + System.out.println(""The given expression"" + + ""is unsatisfiable.""); + return; + } + } +/* No such variables x and -x exist which lie + in same SCC*/ + + System.out.println(""The given expression "" + + ""is satisfiable.""); +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* n is the number of variables + 2n is the total number of nodes + m is the number of clauses*/ + + int n = 5, m = 7; + for(int i = 0; i < MAX; i++) + { + adj.add(new ArrayList()); + adjInv.add(new ArrayList()); + } +/* Each clause is of the form a or b + for m clauses, we have a[m], b[m] + representing a[i] or b[i] + Note: + 1 <= x <= N for an uncomplemented variable x + -N <= x <= -1 for a complemented variable x + -x is the complement of a variable x + The CNF being handled is: + '+' implies 'OR' and '*' implies 'AND' + (x1+x2)*(x2â??+x3)*(x1â??+x2â??)*(x3+x4)*(x3â??+x5)* + (x4â??+x5â??)*(x3â??+x4)*/ + + int a[] = { 1, -2, -1, 3, -3, -4, -3 }; + int b[] = { 2, 3, -2, 4, 5, -5, 4 }; +/* We have considered the same example + for which Implication Graph was made*/ + + is2Satisfiable(n, m, a, b); +} +}", +Activity Selection Problem | Greedy Algo-1,"/*java program for the above approach*/ + +import java.io.*; +import java.lang.*; +import java.util.*; +class GFG { +/* Pair class*/ + + static class Pair { + int first; + int second; + Pair(int first, int second) + { + this.first = first; + this.second = second; + } + } + +/* Vector to store results.*/ + static void SelectActivities(int s[], int f[]) + { + ArrayList ans = new ArrayList<>(); +/* Minimum Priority Queue to sort activities in + ascending order of finishing time (f[i]).*/ + + PriorityQueue p = new PriorityQueue<>( + (p1, p2) -> p1.first - p2.first); + for (int i = 0; i < s.length; i++) { +/* Pushing elements in priority queue where the + key is f[i]*/ + + p.add(new Pair(f[i], s[i])); + } + Pair it = p.poll(); + int start = it.second; + int end = it.first; + ans.add(new Pair(start, end)); + while (!p.isEmpty()) { + Pair itr = p.poll(); + if (itr.second >= end) { + start = itr.second; + end = itr.first; + ans.add(new Pair(start, end)); + } + } + System.out.println( + ""Following Activities should be selected. \n""); + for (Pair itr : ans) { + System.out.println( + ""Activity started at: "" + itr.first + + "" and ends at "" + itr.second); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int s[] = { 1, 3, 0, 5, 8, 5 }; + int f[] = { 2, 4, 6, 7, 9, 9 }; +/* Function call*/ + + SelectActivities(s, f); + } +}", +Row wise sorting in 2D array,"/*Java code to sort 2D matrix row-wise*/ + +import java.io.*; +import java.util.Arrays; +public class Sort2DMatrix { + static int sortRowWise(int m[][]) + { +/* One by one sort individual rows.*/ + + for (int i = 0; i < m.length; i++) + Arrays.sort(m[i]); +/* printing the sorted matrix*/ + + for (int i = 0; i < m.length; i++) { + for (int j = 0; j < m[i].length; j++) + System.out.print(m[i][j] + "" ""); + System.out.println(); + } + return 0; + } +/* driver code*/ + + public static void main(String args[]) + { + int m[][] = { { 9, 8, 7, 1 }, + { 7, 3, 0, 2 }, + { 9, 5, 3, 2 }, + { 6, 3, 1, 2 } }; + sortRowWise(m); + } +}"," '''Python3 code to sort 2D matrix row-wise''' + +def sortRowWise(m): + ''' One by one sort individual rows.''' + + for i in range(len(m)): + m[i].sort() + ''' printing the sorted matrix''' + + for i in range(len(m)): + for j in range(len(m[i])): + print(m[i][j], end="" "") + print() + return 0 + '''Driver code''' + +m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2 ],[ 6, 3, 1, 2]] +sortRowWise(m)" +Find perimeter of shapes formed with 1s in binary matrix,"/*Java program to find perimeter of area +coverede by 1 in 2D matrix consisits +of 0's and 1's*/ + +class GFG { + static final int R = 3; + static final int C = 5; +/* Find the number of covered side + for mat[i][j].*/ + + static int numofneighbour(int mat[][], + int i, int j) + { + int count = 0; +/* UP*/ + + if (i > 0 && mat[i - 1][j] == 1) + count++; +/* LEFT*/ + + if (j > 0 && mat[i][j - 1] == 1) + count++; +/* DOWN*/ + + if (i < R - 1 && mat[i + 1][j] == 1) + count++; +/* RIGHT*/ + + if (j < C - 1 && mat[i][j + 1] == 1) + count++; + return count; + } +/* Returns sum of perimeter of shapes + formed with 1s*/ + + static int findperimeter(int mat[][]) + { + int perimeter = 0; +/* Traversing the matrix and + finding ones to calculate + their contribution.*/ + + for (int i = 0; i < R; i++) + for (int j = 0; j < C; j++) + if (mat[i][j] == 1) + perimeter += (4 - + numofneighbour(mat, i, j)); + return perimeter; + } +/* Driver code*/ + + public static void main(String[] args) + { + int mat[][] = {{0, 1, 0, 0, 0}, + {1, 1, 1, 0, 0}, + {1, 0, 0, 0, 0}}; + System.out.println(findperimeter(mat)); + } +}"," '''Python3 program to find perimeter of area +covered by 1 in 2D matrix consisits of 0's and 1's.''' + +R = 3 +C = 5 + '''Find the number of covered side for mat[i][j].''' + +def numofneighbour(mat, i, j): + count = 0; + ''' UP''' + + if (i > 0 and mat[i - 1][j]): + count+= 1; + ''' LEFT''' + + if (j > 0 and mat[i][j - 1]): + count+= 1; + ''' DOWN''' + + if (i < R-1 and mat[i + 1][j]): + count+= 1 + ''' RIGHT''' + + if (j < C-1 and mat[i][j + 1]): + count+= 1; + return count; + '''Returns sum of perimeter of shapes formed with 1s''' + +def findperimeter(mat): + perimeter = 0; + ''' Traversing the matrix and finding ones to + calculate their contribution.''' + + for i in range(0, R): + for j in range(0, C): + if (mat[i][j]): + perimeter += (4 - numofneighbour(mat, i, j)); + return perimeter; + '''Driver Code''' + +mat = [ [0, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [1, 0, 0, 0, 0] ] +print(findperimeter(mat), end=""\n"");" +Find Length of a Linked List (Iterative and Recursive),"/*Recursive Java program to count number of nodes in +a linked list*/ + +/* Linked list Node*/ + +class Node +{ + int data; + Node next; + Node(int d) { data = d; next = null; } +} +/*Linked List class*/ + +class LinkedList +{ +/*head of list*/ + +Node head; + /* Inserts a new Node at front of the list. */ + + public void push(int new_data) + { + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + /* 3. Make next of new Node as head */ + + new_node.next = head; + /* 4. Move the head to point to new Node */ + + head = new_node; + } + /* Returns count of nodes in linked list */ + + public int getCountRec(Node node) + { +/* Base case*/ + + if (node == null) + return 0; +/* Count is this node plus rest of the list*/ + + return 1 + getCountRec(node.next); + } + /* Wrapper over getCountRec() */ + + public int getCount() + { + return getCountRec(head); + } + /* Driver program to test above functions. Ideally + this function should be in a separate user class. + It is kept here to keep code compact */ + + public static void main(String[] args) + { + /* Start with the empty list */ + + LinkedList llist = new LinkedList(); + llist.push(1); + llist.push(3); + llist.push(1); + llist.push(2); + llist.push(1); + System.out.println(""Count of nodes is "" + + llist.getCount()); + } +}"," '''A complete working Python program to find length of a +Linked List recursively''' + + '''Node class''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None '''Linked List class contains a Node object''' + +class LinkedList: + ''' Function to initialize head''' + + def __init__(self): + self.head = None + ''' This function is in LinkedList class. It inserts + a new node at the beginning of Linked List.''' + + def push(self, new_data): + ''' 1 & 2: Allocate the Node & + Put in the data''' + + new_node = Node(new_data) + ''' 3. Make next of new Node as head''' + + new_node.next = self.head + ''' 4. Move the head to point to new Node''' + + self.head = new_node + ''' This function counts number of nodes in Linked List + recursively, given 'node' as starting node.''' + + def getCountRec(self, node): + '''Base case''' + + if (not node): + return 0 + + '''Count is this node plus rest of the list''' + + else: + return 1 + self.getCountRec(node.next) ''' A wrapper over getCountRec()''' + + def getCount(self): + return self.getCountRec(self.head) + '''Code execution starts here''' + +if __name__=='__main__': + '''Start with the empty list ''' + + llist = LinkedList() + llist.push(1) + llist.push(3) + llist.push(1) + llist.push(2) + llist.push(1) + print 'Count of nodes is :',llist.getCount()" +Maximum element between two nodes of BST,"/*Java program to find maximum element in the path +between two Nodes of Binary Search Tree.*/ + +class Solution +{ +static class Node +{ + Node left, right; + int data; +} +/*Create and return a pointer of new Node.*/ + +static Node createNode(int x) +{ + Node p = new Node(); + p . data = x; + p . left = p . right = null; + return p; +} +/*Insert a new Node in Binary Search Tree.*/ + +static void insertNode( Node root, int x) +{ + Node p = root, q = null; + while (p != null) + { + q = p; + if (p . data < x) + p = p . right; + else + p = p . left; + } + if (q == null) + p = createNode(x); + else + { + if (q . data < x) + q . right = createNode(x); + else + q . left = createNode(x); + } +} +/*Return the maximum element between a Node +and its given ancestor.*/ + +static int maxelpath(Node q, int x) +{ + Node p = q; + int mx = -1; +/* Traversing the path between ansector and + Node and finding maximum element.*/ + + while (p . data != x) + { + if (p . data > x) + { + mx = Math.max(mx, p . data); + p = p . left; + } + else + { + mx = Math.max(mx, p . data); + p = p . right; + } + } + return Math.max(mx, x); +} +/*Return maximum element in the path between +two given Node of BST.*/ + +static int maximumElement( Node root, int x, int y) +{ + Node p = root; +/* Finding the LCA of Node x and Node y*/ + + while ((x < p . data && y < p . data) || + (x > p . data && y > p . data)) + { +/* Checking if both the Node lie on the + left side of the parent p.*/ + + if (x < p . data && y < p . data) + p = p . left; +/* Checking if both the Node lie on the + right side of the parent p.*/ + + else if (x > p . data && y > p . data) + p = p . right; + } +/* Return the maximum of maximum elements occur + in path from ancestor to both Node.*/ + + return Math.max(maxelpath(p, x), maxelpath(p, y)); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + int arr[] = { 18, 36, 9, 6, 12, 10, 1, 8 }; + int a = 1, b = 10; + int n =arr.length; +/* Creating the root of Binary Search Tree*/ + + Node root = createNode(arr[0]); +/* Inserting Nodes in Binary Search Tree*/ + + for (int i = 1; i < n; i++) + insertNode(root, arr[i]); + System.out.println( maximumElement(root, a, b) ); +} +}"," '''Python 3 program to find maximum element +in the path between two Nodes of Binary +Search Tree. +Create and return a pointer of new Node.''' + +class createNode: + ''' Constructor to create a new node''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Insert a new Node in Binary Search Tree.''' + +def insertNode(root, x): + p, q = root, None + while p != None: + q = p + if p.data < x: + p = p.right + else: + p = p.left + if q == None: + p = createNode(x) + else: + if q.data < x: + q.right = createNode(x) + else: + q.left = createNode(x) + '''Return the maximum element between a +Node and its given ancestor.''' + +def maxelpath(q, x): + p = q + mx = -999999999999 + ''' Traversing the path between ansector + and Node and finding maximum element.''' + + while p.data != x: + if p.data > x: + mx = max(mx, p.data) + p = p.left + else: + mx = max(mx, p.data) + p = p.right + return max(mx, x) + '''Return maximum element in the path +between two given Node of BST.''' + +def maximumElement(root, x, y): + p = root + ''' Finding the LCA of Node x and Node y''' + + while ((x < p.data and y < p.data) or + (x > p.data and y > p.data)): + ''' Checking if both the Node lie on + the left side of the parent p.''' + + if x < p.data and y < p.data: + p = p.left + ''' Checking if both the Node lie on + the right side of the parent p.''' + + elif x > p.data and y > p.data: + p = p.right + ''' Return the maximum of maximum elements + occur in path from ancestor to both Node.''' + + return max(maxelpath(p, x), maxelpath(p, y)) + '''Driver Code''' + +if __name__ == '__main__': + arr = [ 18, 36, 9, 6, 12, 10, 1, 8] + a, b = 1, 10 + n = len(arr) + ''' Creating the root of Binary Search Tree''' + + root = createNode(arr[0]) + ''' Inserting Nodes in Binary Search Tree''' + + for i in range(1,n): + insertNode(root, arr[i]) + print(maximumElement(root, a, b))" +Move all occurrences of an element to end in a linked list,"/*Java program to move all occurrences of a +given key to end.*/ + +class GFG { + +/* A Linked list Node*/ + + static class Node { + int data; + Node next; + } + +/* A urility function to create a new node.*/ + + static Node newNode(int x) + { + Node temp = new Node(); + temp.data = x; + temp.next = null; + return temp; + } + +/* Utility function to print the elements + in Linked list*/ + + static void printList(Node head) + { + Node temp = head; + while (temp != null) { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } + System.out.printf(""\n""); + } + +/* Moves all occurrences of given key to + end of linked list.*/ + + static void moveToEnd(Node head, int key) + { +/* Keeps track of locations where key + is present.*/ + + Node pKey = head; + +/* Traverse list*/ + + Node pCrawl = head; + while (pCrawl != null) { +/* 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.*/ + + if (pCrawl != pKey && pCrawl.data != key) { + pKey.data = pCrawl.data; + pCrawl.data = key; + pKey = pKey.next; + } + +/* Find next position where key is present*/ + + if (pKey.data != key) + pKey = pKey.next; + +/* Moving to next Node*/ + + pCrawl = pCrawl.next; + } + } + +/* Driver code*/ + + public static void main(String args[]) + { + 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); + + System.out.printf(""Before moveToEnd(), the Linked list is\n""); + printList(head); + + int key = 10; + moveToEnd(head, key); + + System.out.printf(""\nAfter moveToEnd(), the Linked list is\n""); + printList(head); + } +} + + +"," '''Python3 program to move all occurrences of a +given key to end.''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''A urility function to create a new node.''' + +def newNode(x): + + temp = Node(0) + temp.data = x + temp.next = None + return temp + + '''Utility function to print the elements +in Linked list''' + +def printList( head): + + temp = head + while (temp != None) : + print( temp.data,end = "" "") + temp = temp.next + + print() + + '''Moves all occurrences of given key to +end of linked list.''' + +def moveToEnd(head, key): + + ''' Keeps track of locations where key + is present.''' + + pKey = head + + ''' Traverse list''' + + pCrawl = head + while (pCrawl != None) : + + ''' 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.''' + + if (pCrawl != pKey and pCrawl.data != key) : + pKey.data = pCrawl.data + pCrawl.data = key + pKey = pKey.next + + ''' Find next position where key is present''' + + if (pKey.data != key): + pKey = pKey.next + + ''' Moving to next Node''' + + pCrawl = pCrawl.next + + return head + + '''Driver code''' + +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) + +print(""Before moveToEnd(), the Linked list is\n"") +printList(head) + +key = 10 +head = moveToEnd(head, key) + +print(""\nAfter moveToEnd(), the Linked list is\n"") +printList(head) + + +" +Diameter of a Binary Tree,"/*Recursive optimized Java program to find the diameter of +a Binary Tree*/ +/*Class containing left and right child of current +node and key value*/ + +class Node { + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +/*Class to print the Diameter*/ + +class BinaryTree { + Node root; +/* The function Compute the ""height"" of a tree. Height + is the number of nodes along the longest path from the + root node down to the farthest leaf node.*/ + + static int height(Node node) + { +/* base case tree is empty*/ + + if (node == null) + return 0; +/* If tree is not empty then height = 1 + max of + left height and right heights*/ + + return (1 + + Math.max(height(node.left), + height(node.right))); + } +/* Method to calculate the diameter and return it to + main*/ + + int diameter(Node root) + { +/* base case if tree is empty*/ + + if (root == null) + return 0; +/* get the height of left and right sub-trees*/ + + int lheight = height(root.left); + int rheight = height(root.right); +/* get the diameter of left and right sub-trees*/ + + int ldiameter = diameter(root.left); + int rdiameter = diameter(root.right); + /* Return max of following three + 1) Diameter of left subtree + 2) Diameter of right subtree + 3) Height of left subtree + height of right subtree + 1 + */ + + return Math.max(lheight + rheight + 1, + Math.max(ldiameter, rdiameter)); + } +/* A wrapper over diameter(Node root)*/ + + int diameter() { return diameter(root); } +/* Driver Code*/ + + public static void main(String args[]) + { +/* creating a binary tree and entering the nodes*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); +/* Function Call*/ + + System.out.println( + ""The diameter of given binary tree is : "" + + tree.diameter()); + } +}"," '''Python3 program to find the diameter of binary tree''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''The function Compute the ""height"" of a tree. Height is the +number of nodes along the longest path from the root node +down to the farthest leaf node.''' + +def height(node): + ''' Base Case : Tree is empty''' + + if node is None: + return 0 + ''' If tree is not empty then height = 1 + max of left + height and right heights''' + + return 1 + max(height(node.left), height(node.right)) + '''Function to get the diameter of a binary tree''' + +def diameter(root): + ''' Base Case when tree is empty''' + + if root is None: + return 0 + ''' Get the height of left and right sub-trees''' + + lheight = height(root.left) + rheight = height(root.right) + ''' Get the diameter of left and right sub-trees''' + + ldiameter = diameter(root.left) + rdiameter = diameter(root.right) + ''' Return max of the following tree: + 1) Diameter of left subtree + 2) Diameter of right subtree + 3) Height of left subtree + height of right subtree +1''' + + return max(lheight + rheight + 1, max(ldiameter, rdiameter)) + '''Driver Code''' + + ''' +Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + '''Function Call''' + +print(diameter(root))" +Find subarray with given sum | Set 1 (Nonnegative Numbers),"class SubarraySum { + /* Returns true if the there is a +subarray of arr[] with a sum equal to + 'sum' otherwise returns false. +Also, prints the result */ + + int subArraySum(int arr[], int n, int sum) + { + int curr_sum, i, j; +/* Pick a starting point*/ + + for (i = 0; i < n; i++) { + curr_sum = arr[i]; +/* try all subarrays starting with 'i'*/ + + for (j = i + 1; j <= n; j++) { + if (curr_sum == sum) { + int p = j - 1; + System.out.println( + ""Sum found between indexes "" + i + + "" and "" + p); + return 1; + } + if (curr_sum > sum || j == n) + break; + curr_sum = curr_sum + arr[j]; + } + } + System.out.println(""No subarray found""); + return 0; + } +/*Driver Code*/ + + public static void main(String[] args) + { + SubarraySum arraysum = new SubarraySum(); + int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; + int n = arr.length; + int sum = 23; + arraysum.subArraySum(arr, n, sum); + } +}"," '''Returns true if the +there is a subarray +of arr[] with sum +equal to 'sum' +otherwise returns +false. Also, prints +the result''' + +def subArraySum(arr, n, sum_): + ''' Pick a starting + point''' + + for i in range(n): + curr_sum = arr[i] + ''' try all subarrays + starting with 'i''' + ''' + j = i + 1 + while j <= n: + if curr_sum == sum_: + print (""Sum found between"") + print(""indexes % d and % d""%( i, j-1)) + return 1 + if curr_sum > sum_ or j == n: + break + curr_sum = curr_sum + arr[j] + j += 1 + print (""No subarray found"") + return 0 + '''Driver program''' + +arr = [15, 2, 4, 8, 9, 5, 10, 23] +n = len(arr) +sum_ = 23 +subArraySum(arr, n, sum_) +" +Print all permutations in sorted (lexicographic) order,, +k smallest elements in same order using O(1) extra space,"/*Java for printing smallest k numbers in order*/ + +import java.util.*; +import java.lang.*; +public class GfG { +/* Function to print smallest k numbers + in arr[0..n-1]*/ + + public static void printSmall(int arr[], int n, int k) + { +/* For each arr[i] find whether + it is a part of n-smallest + with insertion sort concept*/ + + for (int i = k; i < n; ++i) { +/* Find largest from top n-element*/ + + int max_var = arr[k - 1]; + int pos = k - 1; + for (int j = k - 2; j >= 0; j--) { + if (arr[j] > max_var) { + max_var = arr[j]; + pos = j; + } + } +/* If largest is greater than arr[i] + shift all element one place left*/ + + if (max_var > arr[i]) { + int j = pos; + while (j < k - 1) { + arr[j] = arr[j + 1]; + j++; + } +/* make arr[k-1] = arr[i]*/ + + arr[k - 1] = arr[i]; + } + } +/* print result*/ + + for (int i = 0; i < k; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver function*/ + + public static void main(String argc[]) + { + int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; + int n = 10; + int k = 5; + printSmall(arr, n, k); + } +}"," '''Python 3 for printing smallest +k numbers in order + ''' '''Function to print smallest k +numbers in arr[0..n-1]''' + +def printSmall(arr, n, k): + ''' For each arr[i] find whether + it is a part of n-smallest + with insertion sort concept''' + + for i in range(k, n): + ''' find largest from first k-elements''' + + max_var = arr[k - 1] + pos = k - 1 + for j in range(k - 2, -1, -1): + if (arr[j] > max_var): + max_var = arr[j] + pos = j + ''' if largest is greater than arr[i] + shift all element one place left''' + + if (max_var > arr[i]): + j = pos + while (j < k - 1): + arr[j] = arr[j + 1] + j += 1 + ''' make arr[k-1] = arr[i]''' + + arr[k - 1] = arr[i] + ''' print result''' + + for i in range(0, k): + print(arr[i], end = "" "") + '''Driver program''' + +arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0] +n = len(arr) +k = 5 +printSmall(arr, n, k)" +Sort an array containing two types of elements,"/*Java program to sort an array with two types +of values in one traversal*/ + +class segregation {/* Method for segregation 0 and 1 + given input array */ + + + static void segregate0and1(int arr[], int n) + { + int type0 = 0; + int type1 = n - 1; + while (type0 < type1) { + if (arr[type0] == 1) { + + arr[type0] = arr[type0] + arr[type1]; + arr[type1] = arr[type0] - arr[type1]; + arr[type0] = arr[type0] - arr[type1]; + type1--; + } + else { + type0++; + } + } + }/* Driver program*/ + + public static void main(String[] args) + { + int arr[] + = { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0 }; + segregate0and1(arr, arr.length); + for (int a : arr) + System.out.print(a + "" ""); + } +}"," '''Python3 program to sort an array with +two types of values in one traversal.''' + + '''Method for segregation 0 and +1 given input array''' + +def segregate0and1(arr, n): + type0 = 0; type1 = n - 1 + while (type0 < type1): + if (arr[type0] == 1): + arr[type0], arr[type1] = arr[type1], arr[type0] + type1 -= 1 + else: + type0 += 1 '''Driver Code''' + +arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1] +n = len(arr) +segregate0and1(arr, n) +for i in range(0, n): + print(arr[i], end = "" "")" +"Minimize (max(A[i], B[j], C[k])","/*Java code for above approach*/ + +import java.util.*; +class GFG +{ + static int solve(int[] A, int[] B, int[] C) + { + int i, j, k; +/* assigning the length -1 value + to each of three variables*/ + + i = A.length - 1; + j = B.length - 1; + k = C.length - 1; + int min_diff, current_diff, max_term; +/* calculating min difference + from last index of lists*/ + + min_diff = Math.abs(Math.max(A[i], Math.max(B[j], C[k])) + - Math.min(A[i], Math.min(B[j], C[k]))); + while (i != -1 && j != -1 && k != -1) + { + current_diff = Math.abs(Math.max(A[i], Math.max(B[j], C[k])) + - Math.min(A[i], Math.min(B[j], C[k]))); +/* checking condition*/ + + if (current_diff < min_diff) + min_diff = current_diff; +/* calculating max term from list*/ + + max_term = Math.max(A[i], Math.max(B[j], C[k])); +/* Moving to smaller value in the + array with maximum out of three.*/ + + if (A[i] == max_term) + i -= 1; + else if (B[j] == max_term) + j -= 1; + else + k -= 1; + } + return min_diff; + } +/* Driver code*/ + + public static void main(String []args) + { + int[] D = { 5, 8, 10, 15 }; + int[] E = { 6, 9, 15, 78, 89 }; + int[] F = { 2, 3, 6, 6, 8, 8, 10 }; + System.out.println(solve(D, E, F)); + } +}"," '''python code for above approach.''' + +def solve(A, B, C): + ''' assigning the length -1 value + to each of three variables''' + + i = len(A) - 1 + j = len(B) - 1 + k = len(C) - 1 + ''' calculating min difference + from last index of lists''' + + min_diff = abs(max(A[i], B[j], C[k]) - + min(A[i], B[j], C[k])) + while i != -1 and j != -1 and k != -1: + current_diff = abs(max(A[i], B[j], + C[k]) - min(A[i], B[j], C[k])) + ''' checking condition''' + + if current_diff < min_diff: + min_diff = current_diff + ''' calculating max term from list''' + + max_term = max(A[i], B[j], C[k]) + ''' Moving to smaller value in the + array with maximum out of three.''' + + if A[i] == max_term: + i -= 1 + elif B[j] == max_term: + j -= 1 + else: + k -= 1 + return min_diff + '''driver code''' + +A = [ 5, 8, 10, 15 ] +B = [ 6, 9, 15, 78, 89 ] +C = [ 2, 3, 6, 6, 8, 8, 10 ] +print(solve(A, B, C))" +Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ),"/*JAVA code to find LCA of given +two nodes in a tree*/ + +import java.util.*; +public class GFG +{ + static int maxn = 100005; + static int left(int i) + { + return (2 * i + 1); + } + static int right(int i) { return 2 * i + 2;} +/* the graph*/ + + static Vector []g = new Vector[maxn]; +/* level of each node*/ + + static int []level = new int[maxn]; + static Vector e = new Vector<>(); + static Vector l= new Vector<>(); + static int []h = new int[maxn]; +/* the segment tree*/ + + static int []st = new int[5 * maxn]; +/* adding edges to the graph(tree)*/ + + static void add_edge(int u, int v) + { + g[u].add(v); + g[v].add(u); + } +/* assigning level to nodes*/ + + static void levelling(int src) + { + for (int i = 0; i < (g[src].size()); i++) + { + int des = g[src].get(i); + if (level[des] != 0) + { + level[des] = level[src] + 1; + leveling(des); + } + } + } + static boolean []visited = new boolean[maxn]; +/* storing the dfs traversal + in the array e*/ + + static void dfs(int src) + { + e.add(src); + visited[src] = true; + for (int i = 0; i < (g[src]).size(); i++) + { + int des = g[src].get(i); + if (!visited[des]) + { + dfs(des); + e.add(src); + } + } + } +/* making the array l*/ + + static void setting_l(int n) + { + for (int i = 0; i < e.size(); i++) + l.add(level[e.get(i)]); + } +/* making the array h*/ + + static void setting_h(int n) + { + for (int i = 0; i <= n; i++) + h[i] = -1; + for (int i = 0; i < e.size(); i++) + { +/* if is already stored*/ + + if (h[e.get(i)] == -1) + h[e.get(i)] = i; + } + } +/* Range minimum query to return the index + of minimum in the subarray L[qs:qe]*/ + + static int RMQ(int ss, int se, int qs, int qe, int i) + { + if (ss > se) + return -1; +/* out of range*/ + + if (se < qs || qe < ss) + return -1; +/* in the range*/ + + if (qs <= ss && se <= qe) + return st[i]; + int mid = (ss + se)/2 ; + int st = RMQ(ss, mid, qs, qe, left(i)); + int en = RMQ(mid + 1, se, qs, qe, right(i)); + if (st != -1 && en != -1) + { + if (l.get(st) < l.get(en)) + return st; + return en; + } else if (st != -1) + return st-2; + else if (en != -1) + return en-1; + return 0; + } +/* constructs the segment tree*/ + + static void SegmentTreeConstruction(int ss, + int se, int i) + { + if (ss > se) + return; +/*leaf*/ + +if (ss == se) + { + st[i] = ss; + return; + } + int mid = (ss + se) /2; + SegmentTreeConstruction(ss, mid, left(i)); + SegmentTreeConstruction(mid + 1, se, right(i)); + if (l.get(st[left(i)]) < l.get(st[right(i)])) + st[i] = st[left(i)]; + else + st[i] = st[right(i)]; + } +/* Function to get LCA*/ + + static int LCA(int x, int y) + { + if (h[x] > h[y]) + { + int t = x; + x = y; + y = t; + } + return e.get(RMQ(0, l.size() - 1, h[x], h[y], 0)); + } +/* Driver code*/ + + public static void main(String[] args) + { +/* n=number of nodes in the tree + q=number of queries to answer*/ + + int n = 15, q = 5; + for (int i = 0; i < g.length; i++) + g[i] = new Vector(); +/* making the tree*/ + + /* + 1 + / | \ + 2 3 4 + | \ + 5 6 + / | \ + 8 7 9 (right of 5) + / | \ | \ + 10 11 12 13 14 + | + 15 + */ + + add_edge(1, 2); + add_edge(1, 3); + add_edge(1, 4); + add_edge(3, 5); + add_edge(4, 6); + add_edge(5, 7); + add_edge(5, 8); + add_edge(5, 9); + add_edge(7, 10); + add_edge(7, 11); + add_edge(7, 12); + add_edge(9, 13); + add_edge(9, 14); + add_edge(12, 15); + level[1] = 1; + leveling(1); + dfs(1); + setting_l(n); + setting_h(n); + SegmentTreeConstruction(0, l.size() - 1, 0); + System.out.print(LCA(10, 15) +""\n""); + System.out.print(LCA(11, 14) +""\n""); + } +}"," '''Python code to find LCA of given +two nodes in a tree''' + +maxn = 100005 + '''the graph''' + +g = [[] for i in range(maxn)] + '''level of each node''' + +level = [0] * maxn +e = [] +l = [] +h = [0] * maxn + '''the segment tree''' + +st = [0] * (5 * maxn) + '''adding edges to the graph(tree)''' + +def add_edge(u: int, v: int): + g[u].append(v) + g[v].append(u) + '''assigning level to nodes''' + +def leveling(src: int): + for i in range(len(g[src])): + des = g[src][i] + if not level[des]: + level[des] = level[src] + 1 + leveling(des) +visited = [False] * maxn + '''storing the dfs traversal +in the array e''' + +def dfs(src: int): + e.append(src) + visited[src] = True + for i in range(len(g[src])): + des = g[src][i] + if not visited[des]: + dfs(des) + e.append(src) + '''making the array l''' + +def setting_l(n: int): + for i in range(len(e)): + l.append(level[e[i]]) + '''making the array h''' + +def setting_h(n: int): + for i in range(n + 1): + h[i] = -1 + for i in range(len(e)): + ''' if is already stored''' + + if h[e[i]] == -1: + h[e[i]] = i + '''Range minimum query to return the index +of minimum in the subarray L[qs:qe]''' + +def RMQ(ss: int, se: int, qs: int, qe: int, i: int) -> int: + global st + if ss > se: + return -1 + ''' out of range''' + + if se < qs or qe < ss: + return -1 + ''' in the range''' + + if qs <= ss and se <= qe: + return st[i] + mid = (se + ss) >> 1 + stt = RMQ(ss, mid, qs, qe, 2 * i + 1) + en = RMQ(mid + 1, se, qs, qe, 2 * i + 2) + if stt != -1 and en != -1: + if l[stt] < l[en]: + return stt + return en + elif stt != -1: + return stt + elif en != -1: + return en + '''constructs the segment tree''' + +def segmentTreeConstruction(ss: int, se: int, i: int): + if ss > se: + return + '''leaf''' + + if ss == se: + st[i] = ss + return + mid = (ss + se) >> 1 + segmentTreeConstruction(ss, mid, 2 * i + 1) + segmentTreeConstruction(mid + 1, se, 2 * i + 2) + if l[st[2 * i + 1]] < l[st[2 * i + 2]]: + st[i] = st[2 * i + 1] + else: + st[i] = st[2 * i + 2] + '''Function to get LCA''' + +def LCA(x: int, y: int) -> int: + if h[x] > h[y]: + x, y = y, x + return e[RMQ(0, len(l) - 1, h[x], h[y], 0)] + '''Driver Code''' + +if __name__ == ""__main__"": + ''' n=number of nodes in the tree + q=number of queries to answer''' + + n = 15 + q = 5 + ''' making the tree''' + ''' + 1 + / | \ + 2 3 4 + | \ + 5 6 + / | \ + 8 7 9 (right of 5) + / | \ | \ + 10 11 12 13 14 + | + 15 + ''' + + add_edge(1, 2) + add_edge(1, 3) + add_edge(1, 4) + add_edge(3, 5) + add_edge(4, 6) + add_edge(5, 7) + add_edge(5, 8) + add_edge(5, 9) + add_edge(7, 10) + add_edge(7, 11) + add_edge(7, 12) + add_edge(9, 13) + add_edge(9, 14) + add_edge(12, 15) + level[1] = 1 + leveling(1) + dfs(1) + setting_l(n) + setting_h(n) + segmentTreeConstruction(0, len(l) - 1, 0) + print(LCA(10, 15)) + print(LCA(11, 14))" +Find the element that appears once in an array where every other element appears twice,"/*Java program to find +element that appears once*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* function which find number*/ + + static int singleNumber(int[] nums, int n) + { + HashMap m = new HashMap<>(); + long sum1 = 0, sum2 = 0; + for (int i = 0; i < n; i++) + { + if (!m.containsKey(nums[i])) + { + sum1 += nums[i]; + m.put(nums[i], 1); + } + sum2 += nums[i]; + } +/* applying the formula.*/ + + return (int)(2 * (sum1) - sum2); + } +/* Driver code*/ + + public static void main(String args[]) + { + int[] a = {2, 3, 5, 4, 5, 3, 4}; + int n = 7; + System.out.println(singleNumber(a,n)); + int[] b = {15, 18, 16, 18, 16, 15, 89}; + System.out.println(singleNumber(b,n)); + } +}"," '''Python3 program to find +element that appears once + ''' '''function which find number''' + +def singleNumber(nums): + '''applying the formula.''' + + return 2 * sum(set(nums)) - sum(nums) + '''driver code''' + +a = [2, 3, 5, 4, 5, 3, 4] +print (int(singleNumber(a))) +a = [15, 18, 16, 18, 16, 15, 89] +print (int(singleNumber(a)))" +Mirror of matrix across diagonal,"/*Simple Java program to find mirror of +matrix across diagonal.*/ + +import java.util.*; +class GFG +{ + static int MAX = 100; + static void imageSwap(int mat[][], int n) + { +/* for diagonal which start from at + first row of matrix*/ + + int row = 0; +/* traverse all top right diagonal*/ + + for (int j = 0; j < n; j++) + { +/* here we use stack for reversing + the element of diagonal*/ + + Stack s = new Stack<>(); + int i = row, k = j; + while (i < n && k >= 0) + { + s.push(mat[i++][k--]); + } +/* push all element back to matrix + in reverse order*/ + + i = row; + k = j; + while (i < n && k >= 0) + { + mat[i++][k--] = s.peek(); + s.pop(); + } + } +/* do the same process for all the + diagonal which start from last + column*/ + + int column = n - 1; + for (int j = 1; j < n; j++) + { +/* here we use stack for reversing + the elements of diagonal*/ + + Stack s = new Stack<>(); + int i = j, k = column; + while (i < n && k >= 0) + { + s.push(mat[i++][k--]); + } +/* push all element back to matrix + in reverse order*/ + + i = j; + k = column; + while (i < n && k >= 0) + { + mat[i++][k--] = s.peek(); + s.pop(); + } + } + } +/* Utility function to print a matrix*/ + + static void printMatrix(int mat[][], int n) + { + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + System.out.print(mat[i][j] + "" ""); + } + System.out.println(""""); + } + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { + int mat[][] = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16}}; + int n = 4; + imageSwap(mat, n); + printMatrix(mat, n); + } +}"," '''Simple Python3 program to find mirror of +matrix across diagonal.''' + +MAX = 100 +def imageSwap(mat, n): + ''' for diagonal which start from at + first row of matrix''' + + row = 0 + ''' traverse all top right diagonal''' + + for j in range(n): + ''' here we use stack for reversing + the element of diagonal''' + + s = [] + i = row + k = j + while (i < n and k >= 0): + s.append(mat[i][k]) + i += 1 + k -= 1 + ''' push all element back to matrix + in reverse order''' + + i = row + k = j + while (i < n and k >= 0): + mat[i][k] = s[-1] + k -= 1 + i += 1 + s.pop() + ''' do the same process for all the + diagonal which start from last + column''' + + column = n - 1 + for j in range(1, n): + ''' here we use stack for reversing + the elements of diagonal''' + + s = [] + i = j + k = column + while (i < n and k >= 0): + s.append(mat[i][k]) + i += 1 + k -= 1 + ''' push all element back to matrix + in reverse order''' + + i = j + k = column + while (i < n and k >= 0): + mat[i][k] = s[-1] + i += 1 + k -= 1 + s.pop() + '''Utility function to pra matrix''' + +def printMatrix(mat, n): + for i in range(n): + for j in range(n): + print(mat[i][j], end="" "") + print() + '''Driver code''' + +mat = [[1, 2, 3, 4],[5, 6, 7, 8], + [9, 10, 11, 12],[13, 14, 15, 16]] +n = 4 +imageSwap(mat, n) +printMatrix(mat, n)" +Graph and its representations,"/*Java code to demonstrate Graph representation +using ArrayList in Java*/ + +import java.util.*; +class Graph { +/* A utility function to add an edge in an + undirected graph*/ + + static void addEdge(ArrayList > adj, + int u, int v) + { + adj.get(u).add(v); + adj.get(v).add(u); + } +/* A utility function to print the adjacency list + representation of graph*/ + + static void printGraph(ArrayList > adj) + { + for (int i = 0; i < adj.size(); i++) { + System.out.println(""\nAdjacency list of vertex"" + i); + System.out.print(""head""); + for (int j = 0; j < adj.get(i).size(); j++) { + System.out.print("" -> ""+adj.get(i).get(j)); + } + System.out.println(); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Creating a graph with 5 vertices*/ + + int V = 5; + ArrayList > adj + = new ArrayList >(V); + for (int i = 0; i < V; i++) + adj.add(new ArrayList()); +/* Adding edges one by one*/ + + addEdge(adj, 0, 1); + addEdge(adj, 0, 4); + addEdge(adj, 1, 2); + addEdge(adj, 1, 3); + addEdge(adj, 1, 4); + addEdge(adj, 2, 3); + addEdge(adj, 3, 4); + printGraph(adj); + } +}", +Double the first element and move zero to end,"class GFG { +/* Function For Swaping Two Element Of An Array*/ + + public static void swap(int[] A, int i, int j) + { + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +/* shift all zero to left side of an array*/ + + static void shiftAllZeroToLeft(int array[], int n) + { +/* Maintain last index with positive value*/ + + int lastSeenNonZero = 0; + for (int index = 0; index < n; index++) { +/* If Element is non-zero*/ + + if (array[index] != 0) { +/* swap current index, with lastSeen + non-zero*/ + + swap(array, array[index], + array[lastSeenNonZero]); +/* next element will be last seen non-zero*/ + + lastSeenNonZero++; + } + } + } +} +"," '''shift all zero to left side of an array''' + +def shiftAllZeroToLeft(arr, n): + '''Maintain last index with positive value''' + + lastSeenNonZero = 0 + for index in range(0, n): ''' If Element is non-zero''' + + if (array[index] != 0): + ''' swap current index, with lastSeen + non-zero''' + + array[index], array[lastSeenNonZero] = array[lastSeenNonZero], array[index] + ''' next element will be last seen non-zero''' + + lastSeenNonZero+=1 +" +Largest subset whose all elements are Fibonacci numbers,"/*Java program to find +largest Fibonacci subset*/ + +import java.util.*; +class GFG +{ +/* Prints largest subset of an array whose + all elements are fibonacci numbers*/ + + public static void findFibSubset(Integer[] x) + { + + List fib = new ArrayList(); + List result = new ArrayList(); +/* Find maximum element in arr[]*/ + + Integer max = Collections.max(Arrays.asList(x));/* Generate all Fibonacci numbers + till max and store them*/ + + Integer a = 0; + Integer b = 1; + while (b < max){ + Integer c = a + b; + a=b; + b=c; + fib.add(c); + } +/* Now iterate through all numbers and + quickly check for Fibonacci*/ + + for (Integer i = 0; i < x.length; i++){ + if(fib.contains(x[i])){ + result.add(x[i]); + } + } + System.out.println(result); + } +/* Driver code*/ + + public static void main(String args[]) + { + Integer[] a = {4, 2, 8, 5, 20, 1, 40, 13, 23}; + findFibSubset(a); + } +}"," '''python3 program to find largest Fibonacci subset + ''' '''Prints largest subset of an array whose +all elements are fibonacci numbers''' + +def findFibSubset(arr, n): + ''' Find maximum element in arr[]''' + + m= max(arr) + ''' Generate all Fibonacci numbers till + max and store them in hash.''' + + a = 0 + b = 1 + hash = [] + hash.append(a) + hash.append(b) + while (b < m): + c = a + b + a = b + b = c + hash.append(b) + ''' Npw iterate through all numbers and + quickly check for Fibonacci using + hash.''' + + for i in range (n): + if arr[i] in hash : + print( arr[i],end="" "") + '''Driver code''' + +if __name__ == ""__main__"": + arr = [4, 2, 8, 5, 20, 1, 40, 13, 23] + n = len(arr) + findFibSubset(arr, n)" +K'th smallest element in BST using O(1) Extra Space,"/*Java program to find k'th largest element in BST*/ + +import java.util.*; +class GfG { +/*A BST node*/ + +static class Node +{ + int key; + Node left, right; +} +/*A function to find*/ + +static int KSmallestUsingMorris(Node root, int k) +{ +/* Count to iterate over elements till we + get the kth smallest number*/ + + int count = 0; +/*store the Kth smallest*/ + +int ksmall = Integer.MIN_VALUE; +/*to store the current node*/ + +Node curr = root; + while (curr != null) + { +/* Like Morris traversal if current does + not have left child rather than printing + as we did in inorder, we will just + increment the count as the number will + be in an increasing order*/ + + if (curr.left == null) + { + count++; +/* if count is equal to K then we found the + kth smallest, so store it in ksmall*/ + + if (count==k) + ksmall = curr.key; +/* go to current's right child*/ + + curr = curr.right; + } + else + { +/* we create links to Inorder Successor and + count using these links*/ + + Node pre = curr.left; + while (pre.right != null && pre.right != curr) + pre = pre.right; +/* building links*/ + + if (pre.right== null) + { +/* link made to Inorder Successor*/ + + pre.right = curr; + curr = curr.left; + } +/* While breaking the links in so made temporary + threaded tree we will check for the K smallest + condition*/ + + else + { +/* Revert the changes made in if part (break link + from the Inorder Successor)*/ + + pre.right = null; + count++; +/* If count is equal to K then we found + the kth smallest and so store it in ksmall*/ + + if (count==k) + ksmall = curr.key; + curr = curr.right; + } + } + } +/*return the found value*/ + +return ksmall; +} +/*A utility function to create a new BST node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.key = item; + temp.left = null; + temp.right = null; + return temp; +} +/* A utility function to insert a new node with given key in BST */ + +static Node insert(Node node, int key) +{ + /* If the tree is empty, return a new node */ + + if (node == null) return newNode(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + node.left = insert(node.left, key); + else if (key > node.key) + node.right = insert(node.right, key); + /* return the (unchanged) node pointer */ + + return node; +} +/*Driver Program to test above functions*/ + +public static void main(String[] args) +{ + /* Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80 */ + + Node root = null; + root = insert(root, 50); + insert(root, 30); + insert(root, 20); + insert(root, 40); + insert(root, 70); + insert(root, 60); + insert(root, 80); + for (int k=1; k<=7; k++) + System.out.print(KSmallestUsingMorris(root, k) + "" ""); +} +}"," '''Python 3 program to find k'th +largest element in BST''' + '''A BST node''' + +class Node: + def __init__(self, data): + self.key = data + self.left = None + self.right = None '''A function to find''' + +def KSmallestUsingMorris(root, k): + ''' Count to iterate over elements + till we get the kth smallest number''' + + count = 0 + '''store the Kth smallest''' + + ksmall = -9999999999 + '''to store the current node''' + + curr = root + while curr != None: + ''' Like Morris traversal if current does + not have left child rather than + printing as we did in inorder, we + will just increment the count as the + number will be in an increasing order''' + + if curr.left == None: + count += 1 + ''' if count is equal to K then we + found the kth smallest, so store + it in ksmall''' + + if count == k: + ksmall = curr.key + ''' go to current's right child''' + + curr = curr.right + else: + ''' we create links to Inorder Successor + and count using these links''' + + pre = curr.left + while (pre.right != None and + pre.right != curr): + pre = pre.right + ''' building links''' + + if pre.right == None: + ''' link made to Inorder Successor''' + + pre.right = curr + curr = curr.left + ''' While breaking the links in so made + temporary threaded tree we will check + for the K smallest condition''' + + else: + ''' Revert the changes made in if part + (break link from the Inorder Successor)''' + + pre.right = None + count += 1 + ''' If count is equal to K then we + found the kth smallest and so + store it in ksmall''' + + if count == k: + ksmall = curr.key + curr = curr.right + '''return the found value''' + + return ksmall + '''A utility function to insert a new +node with given key in BST''' + +def insert(node, key): + ''' If the tree is empty, + return a new node''' + + if node == None: + return Node(key) + ''' Otherwise, recur down the tree''' + + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + ''' return the (unchanged) node pointer''' + + return node + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80''' + + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + for k in range(1,8): + print(KSmallestUsingMorris(root, k), + end = "" "")" +Write you own Power without using multiplication(*) and division(/) operators,"import java.io.*; +class GFG { + /* Works only if a >= 0 and b >= 0 */ + + static int pow(int a, int b) + { + if (b == 0) + return 1; + int answer = a; + int increment = a; + int i, j; + for (i = 1; i < b; i++) { + for (j = 1; j < a; j++) { + answer += increment; + } + increment = answer; + } + return answer; + } +/* driver program to test above function*/ + + public static void main(String[] args) + { + System.out.println(pow(5, 3)); + } +}"," '''Python 3 code for power +function + ''' '''Works only if a >= 0 and b >= 0''' + +def pow(a,b): + if(b==0): + return 1 + answer=a + increment=a + for i in range(1,b): + for j in range (1,a): + answer+=increment + increment=answer + return answer + '''driver code''' + +print(pow(5,3))" +Find the closest element in Binary Search Tree,"/*Recursive Java program to find key closest to k +in given Binary Search Tree.*/ + + class solution + { + static int min_diff, min_diff_key; +/* A binary tree node has key, pointer to left child +and a pointer to right child */ + +static class Node +{ + int key; + Node left, right; +}; +/* Utility that allocates a new node with the + given key and null left and right pointers. */ + + static Node newnode(int key) +{ + Node node = new Node(); + node.key = key; + node.left = node.right = null; + return (node); +} +/*Function to find node with minimum absolute +difference with given K +min_diff -. minimum difference till now +min_diff_key -. node having minimum absolute + difference with K*/ + +static void maxDiffUtil(Node ptr, int k) +{ + if (ptr == null) + return ; +/* If k itself is present*/ + + if (ptr.key == k) + { + min_diff_key = k; + return; + } +/* update min_diff and min_diff_key by checking + current node value*/ + + if (min_diff > Math.abs(ptr.key - k)) + { + min_diff = Math.abs(ptr.key - k); + min_diff_key = ptr.key; + } +/* if k is less than ptr.key then move in + left subtree else in right subtree*/ + + if (k < ptr.key) + maxDiffUtil(ptr.left, k); + else + maxDiffUtil(ptr.right, k); +} +/*Wrapper over maxDiffUtil()*/ + +static int maxDiff(Node root, int k) +{ +/* Initialize minimum difference*/ + + min_diff = 999999999; min_diff_key = -1; +/* Find value of min_diff_key (Closest key + in tree with k)*/ + + maxDiffUtil(root, k); + return min_diff_key; +} +/*Driver program to run the case*/ + +public static void main(String args[]) +{ + Node root = newnode(9); + root.left = newnode(4); + root.right = newnode(17); + root.left.left = newnode(3); + root.left.right = newnode(6); + root.left.right.left = newnode(5); + root.left.right.right = newnode(7); + root.right.right = newnode(22); + root.right.right.left = newnode(20); + int k = 18; + System.out.println( maxDiff(root, k)); +} +}"," '''Recursive Python program to find key +closest to k in given Binary Search Tree. ''' + '''Utility that allocates a new node with the +given key and NULL left and right pointers. ''' + +class newnode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None '''Function to find node with minimum +absolute difference with given K +min_diff --> minimum difference till now +min_diff_key --> node having minimum absolute + difference with K ''' + +def maxDiffUtil(ptr, k, min_diff, min_diff_key): + if ptr == None: + return + ''' If k itself is present ''' + + if ptr.key == k: + min_diff_key[0] = k + return + ''' update min_diff and min_diff_key by + checking current node value ''' + + if min_diff > abs(ptr.key - k): + min_diff = abs(ptr.key - k) + min_diff_key[0] = ptr.key + ''' if k is less than ptr->key then move + in left subtree else in right subtree ''' + + if k < ptr.key: + maxDiffUtil(ptr.left, k, min_diff, + min_diff_key) + else: + maxDiffUtil(ptr.right, k, min_diff, + min_diff_key) + '''Wrapper over maxDiffUtil() ''' + +def maxDiff(root, k): + ''' Initialize minimum difference ''' + + min_diff, min_diff_key = 999999999999, [-1] + ''' Find value of min_diff_key (Closest + key in tree with k) ''' + + maxDiffUtil(root, k, min_diff, min_diff_key) + return min_diff_key[0] + '''Driver Code''' + +if __name__ == '__main__': + root = newnode(9) + root.left = newnode(4) + root.right = newnode(17) + root.left.left = newnode(3) + root.left.right = newnode(6) + root.left.right.left = newnode(5) + root.left.right.right = newnode(7) + root.right.right = newnode(22) + root.right.right.left = newnode(20) + k = 18 + print(maxDiff(root, k))" +Binary Search,"/*Java implementation of iterative Binary Search*/ + +class BinarySearch { +/* Returns index of x if it is present in arr[], + else return -1*/ + + int binarySearch(int arr[], int x) + { + int l = 0, r = arr.length - 1; + while (l <= r) { + int m = l + (r - l) / 2; +/* Check if x is present at mid*/ + + if (arr[m] == x) + return m; +/* If x greater, ignore left half*/ + + if (arr[m] < x) + l = m + 1; +/* If x is smaller, ignore right half*/ + + else + r = m - 1; + } +/* if we reach here, then element was + not present*/ + + return -1; + } +/* Driver method to test above*/ + + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, x); + if (result == -1) + System.out.println(""Element not present""); + else + System.out.println(""Element found at "" + + ""index "" + result); + } +}"," '''Python3 code to implement iterative Binary +Search.''' + + '''It returns location of x in given array arr +if present, else returns -1''' + +def binarySearch(arr, l, r, x): + while l <= r: + mid = l + (r - l) // 2; ''' Check if x is present at mid''' + + if arr[mid] == x: + return mid + ''' If x is greater, ignore left half''' + + elif arr[mid] < x: + l = mid + 1 + ''' If x is smaller, ignore right half''' + + else: + r = mid - 1 + ''' If we reach here, then the element + was not present''' + + return -1 + '''Driver Code''' + +arr = [ 2, 3, 4, 10, 40 ] +x = 10 +result = binarySearch(arr, 0, len(arr)-1, x) +if result != -1: + print (""Element is present at index % d"" % result) +else: + print (""Element is not present in array"") +" +Cumulative frequency of count of each element in an unsorted array,"/*Java program to print the cumulative frequency +according to the order given*/ + +class GFG +{ +/*Function to print the cumulative frequency +according to the order given*/ + +static void countFreq(int a[], int n) +{ +/* Insert elements and their + frequencies in hash map.*/ + + int hm[] = new int[n]; + for (int i = 0; i < n; i++) + hm[a[i]]++; + int cumul = 0; +/*traverse in the array*/ + +for(int i = 0; i < n; i++) +{ +/* add the frequencies*/ + + cumul += hm[a[i]]; +/* if the element has not been + visited previously*/ + + if(hm[a[i]] != 0) + { + System.out.println(a[i] + ""->"" + cumul); + } +/* mark the hash 0 + as the element's cumulative frequency + has been printed*/ + + hm[a[i]] = 0; +} +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = {1, 3, 2, 4, 2, 1}; + int n = a.length; + countFreq(a, n); +} +}"," '''Python3 program to print the cumulative +frequency according to the order given + ''' '''Function to print the cumulative frequency +according to the order given''' + +def countFreq(a, n): + ''' Insert elements and their + frequencies in hash map.''' + + hm = dict() + for i in range(n): + hm[a[i]] = hm.get(a[i], 0) + 1 + cumul = 0 + ''' traverse in the array''' + + for i in range(n): + ''' add the frequencies''' + + cumul += hm[a[i]] + ''' if the element has not been + visited previously''' + + if(hm[a[i]] > 0): + print(a[i], ""->"", cumul) + ''' mark the hash 0 + as the element's cumulative + frequency has been printed''' + + hm[a[i]] = 0 + '''Driver Code''' + +a = [1, 3, 2, 4, 2, 1] +n = len(a) +countFreq(a, n)" +Find Count of Single Valued Subtrees,"/*Java program to find count of single valued subtrees*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +class Count +{ + int count = 0; +} +class BinaryTree +{ + Node root; + Count ct = new Count(); +/* This function increments count by number of single + valued subtrees under root. It returns true if subtree + under root is Singly, else false.*/ + + boolean countSingleRec(Node node, Count c) + { +/* Return false to indicate NULL*/ + + if (node == null) + return true; +/* Recursively count in left and right subtrees also*/ + + boolean left = countSingleRec(node.left, c); + boolean right = countSingleRec(node.right, c); +/* If any of the subtrees is not singly, then this + cannot be singly.*/ + + if (left == false || right == false) + return false; +/* If left subtree is singly and non-empty, but data + doesn't match*/ + + if (node.left != null && node.data != node.left.data) + return false; +/* Same for right subtree*/ + + if (node.right != null && node.data != node.right.data) + return false; +/* If none of the above conditions is true, then + tree rooted under root is single valued, increment + count and return true.*/ + + c.count++; + return true; + } +/* This function mainly calls countSingleRec() + after initializing count as 0*/ + + int countSingle() + { + return countSingle(root); + } + int countSingle(Node node) + { +/* Recursive function to count*/ + + countSingleRec(node, ct); + return ct.count; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + /* Let us construct the below tree + 5 + / \ + 4 5 + / \ \ + 4 4 5 */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(5); + tree.root.left = new Node(4); + tree.root.right = new Node(5); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(4); + tree.root.right.right = new Node(5); + System.out.println(""The count of single valued sub trees is : "" + + tree.countSingle()); + } +}"," '''Python program to find the count of single valued subtrees''' + + + ''' Utility function to create a new node''' +class Node: + def __init__(self ,data): + self.data = data + self.left = None + self.right = None + '''This function increments count by number of single +valued subtrees under root. It returns true if subtree +under root is Singly, else false.''' + +def countSingleRec(root , count): + ''' Return False to indicate None''' + + if root is None : + return True + ''' Recursively count in left and right subtress also''' + + left = countSingleRec(root.left , count) + right = countSingleRec(root.right , count) + ''' If any of the subtress is not singly, then this + cannot be singly''' + + if left == False or right == False : + return False + ''' If left subtree is singly and non-empty , but data + doesn't match''' + + if root.left and root.data != root.left.data: + return False + ''' same for right subtree''' + + if root.right and root.data != root.right.data: + return False + ''' If none of the above conditions is True, then + tree rooted under root is single valued,increment + count and return true''' + + count[0] += 1 + return True + '''This function mainly calss countSingleRec() +after initializing count as 0''' + +def countSingle(root): + ''' initialize result''' + + count = [0] + ''' Recursive function to count''' + + countSingleRec(root , count) + return count[0] + '''Driver program to test''' + + '''Let us construct the below tree + 5 + / \ + 4 5 + / \ \ + 4 4 5 + ''' + +root = Node(5) +root.left = Node(4) +root.right = Node(5) +root.left.left = Node(4) +root.left.right = Node(4) +root.right.right = Node(5) +countSingle(root) +print ""Count of Single Valued Subtress is"" , countSingle(root)" +Deletion in a Binary Tree,"/*Java program to delete element +in binary tree*/ + +import java.util.LinkedList; +import java.util.Queue; +class GFG{ +/*A binary tree node has key, pointer to +left child and a pointer to right child*/ + +static class Node +{ + int key; + Node left, right; +/* Constructor*/ + + Node(int key) + { + this.key = key; + left = null; + right = null; + } +} +static Node root; +static Node temp = root; +/*Inorder traversal of a binary tree*/ + +static void inorder(Node temp) +{ + if (temp == null) + return; + inorder(temp.left); + System.out.print(temp.key + "" ""); + inorder(temp.right); +} +/*Function to delete deepest +element in binary tree*/ + +static void deleteDeepest(Node root, + Node delNode) +{ + Queue q = new LinkedList(); + q.add(root); + Node temp = null; +/* Do level order traversal until last node*/ + + while (!q.isEmpty()) + { + temp = q.peek(); + q.remove(); + if (temp == delNode) + { + temp = null; + return; + } + if (temp.right!=null) + { + if (temp.right == delNode) + { + temp.right = null; + return; + } + else + q.add(temp.right); + } + if (temp.left != null) + { + if (temp.left == delNode) + { + temp.left = null; + return; + } + else + q.add(temp.left); + } +} +} +/*Function to delete given element +in binary tree*/ + +static void delete(Node root, int key) +{ + if (root == null) + return; + if (root.left == null && + root.right == null) + { + if (root.key == key) + { + root=null; + return; + } + else + return; + } + Queue q = new LinkedList(); + q.add(root); + Node temp = null, keyNode = null; +/* Do level order traversal until + we find key and last node.*/ + + while (!q.isEmpty()) + { + temp = q.peek(); + q.remove(); + if (temp.key == key) + keyNode = temp; + if (temp.left != null) + q.add(temp.left); + if (temp.right != null) + q.add(temp.right); + } + if (keyNode != null) + { + int x = temp.key; + deleteDeepest(root, temp); + keyNode.key = x; + } +} +/*Driver code*/ + +public static void main(String args[]) +{ + root = new Node(10); + root.left = new Node(11); + root.left.left = new Node(7); + root.left.right = new Node(12); + root.right = new Node(9); + root.right.left = new Node(15); + root.right.right = new Node(8); + System.out.print(""Inorder traversal "" + + ""before deletion:""); + inorder(root); + int key = 11; + delete(root, key); + System.out.print(""\nInorder traversal "" + + ""after deletion:""); + inorder(root); +} +}"," '''Python3 program to illustrate deletion in a Binary Tree''' + '''class to create a node with data, left child and right child.''' + +class Node: + def __init__(self,data): + self.data = data + self.left = None + self.right = None + '''Inorder traversal of a binary tree''' + +def inorder(temp): + if(not temp): + return + inorder(temp.left) + print(temp.data, end = "" "") + inorder(temp.right) + '''function to delete the given deepest node (d_node) in binary tree''' + +def deleteDeepest(root,d_node): + q = [] + q.append(root) + + ''' Do level order traversal until last node''' + + while(len(q)): + temp = q.pop(0) + if temp is d_node: + temp = None + return + if temp.right: + if temp.right is d_node: + temp.right = None + return + else: + q.append(temp.right) + if temp.left: + if temp.left is d_node: + temp.left = None + return + else: + q.append(temp.left) '''function to delete element in binary tree''' + +def deletion(root, key): + if root == None : + return None + if root.left == None and root.right == None: + if root.key == key : + return None + else : + return root + key_node = None + q = [] + q.append(root) ''' Do level order traversal to find deepest + node(temp) and node to be deleted (key_node)''' + + + while(len(q)): + temp = q.pop(0) + if temp.data == key: + key_node = temp + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + if key_node : + x = temp.data + deleteDeepest(root,temp) + key_node.data = x + return root + '''Driver code''' + +if __name__=='__main__': + root = Node(10) + root.left = Node(11) + root.left.left = Node(7) + root.left.right = Node(12) + root.right = Node(9) + root.right.left = Node(15) + root.right.right = Node(8) + print(""The tree before the deletion:"") + inorder(root) + key = 11 + root = deletion(root, key) + print() + print(""The tree after the deletion;"") + inorder(root)" +"Search, insert and delete in a sorted array","/*Java program to delete an +element from a sorted array*/ + +class Main { +/* binary search*/ + + static int binarySearch(int arr[], int low, int high, int key) + { + if (high < low) + return -1; + int mid = (low + high) / 2; + if (key == arr[mid]) + return mid; + if (key > arr[mid]) + return binarySearch(arr, (mid + 1), high, key); + return binarySearch(arr, low, (mid - 1), key); + } + /* Function to delete an element */ + + static int deleteElement(int arr[], int n, int key) + { +/* Find position of element to be deleted*/ + + int pos = binarySearch(arr, 0, n - 1, key); + if (pos == -1) { + System.out.println(""Element not found""); + return n; + } +/* Deleting element*/ + + int i; + for (i = pos; i < n - 1; i++) + arr[i] = arr[i + 1]; + return n - 1; + } + /* Driver Code */ + + public static void main(String[] args) + { + int i; + int arr[] = { 10, 20, 30, 40, 50 }; + int n = arr.length; + int key = 30; + System.out.print(""Array before deletion:\n""); + for (i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + n = deleteElement(arr, n, key); + System.out.print(""\n\nArray after deletion:\n""); + for (i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +}"," '''Python program to implement delete operation in a +sorted array''' '''To search a ley to be deleted''' + +def binarySearch(arr, low, high, key): + if (high < low): + return -1 + mid = (low + high) // 2 + if (key == arr[mid]): + return mid + if (key > arr[mid]): + return binarySearch(arr, (mid + 1), high, key) + return binarySearch(arr, low, (mid - 1), key) + ''' Function to delete an element ''' + +def deleteElement(arr, n, key): + ''' Find position of element to be deleted''' + + pos = binarySearch(arr, 0, n - 1, key) + if (pos == -1): + print(""Element not found"") + return n + ''' Deleting element''' + + for i in range(pos,n - 1): + arr[i] = arr[i + 1] + return n - 1 + '''Driver code''' + +arr = [10, 20, 30, 40, 50 ] +n = len(arr) +key = 30 +print(""Array before deletion"") +for i in range(n): + print(arr[i],end="" "") +n = deleteElement(arr, n, key) +print(""\n\nArray after deletion"") +for i in range(n): + print(arr[i],end="" "")" +Types of Linked List,," '''structure of Node''' + +class Node: + def __init__(self, data): + self.previous = None + self.data = data + self.next = None +" +Sieve of Eratosthenes,"/*Java program to print all +primes smaller than or equal to +n using Sieve of Eratosthenes*/ + +class SieveOfEratosthenes { + void sieveOfEratosthenes(int n) + { +/* Create a boolean array + ""prime[0..n]"" and + initialize all entries + it as true. A value in + prime[i] will finally be + false if i is Not a + prime, else true.*/ + + boolean prime[] = new boolean[n + 1]; + for (int i = 0; i <= n; i++) + prime[i] = true; + for (int p = 2; p * p <= n; p++) + { +/* If prime[p] is not changed, then it is a + prime*/ + + if (prime[p] == true) + { +/* Update all multiples of p*/ + + for (int i = p * p; i <= n; i += p) + prime[i] = false; + } + } +/* Print all prime numbers*/ + + for (int i = 2; i <= n; i++) + { + if (prime[i] == true) + System.out.print(i + "" ""); + } + } +/* Driver Code*/ + + public static void main(String args[]) + { + int n = 30; + System.out.print( + ""Following are the prime numbers ""); + System.out.println(""smaller than or equal to "" + n); + SieveOfEratosthenes g = new SieveOfEratosthenes(); + g.sieveOfEratosthenes(n); + } +}"," '''Python program to print all +primes smaller than or equal to +n using Sieve of Eratosthenes''' + +def SieveOfEratosthenes(n): + ''' Create a boolean array + ""prime[0..n]"" and initialize + all entries it as true. + A value in prime[i] will + finally be false if i is + Not a prime, else true.''' + + prime = [True for i in range(n+1)] + p = 2 + while (p * p <= n): + ''' If prime[p] is not + changed, then it is a prime''' + + if (prime[p] == True): + ''' Update all multiples of p''' + + for i in range(p * p, n+1, p): + prime[i] = False + p += 1 + ''' Print all prime numbers''' + + for p in range(2, n+1): + if prime[p]: + print p, + '''Driver code''' + +if __name__ == '__main__': + n = 30 + print ""Following are the prime numbers smaller"", + print ""than or equal to"", n + SieveOfEratosthenes(n)" +Smallest value in each level of Binary Tree,"/*JAVA program to print minimum element +in each level of binary tree.*/ + +import java.util.*; +class GFG +{ +/*A Binary Tree Node*/ + +static class Node +{ + int data; + Node left, right; +}; +/*return height of tree*/ + +static int heightoftree(Node root) +{ + if (root == null) + return 0; + int left = heightoftree(root.left); + int right = heightoftree(root.right); + return ((left > right ? left : right) + 1); +} +/*Iterative method to find every level +minimum element of Binary Tree*/ + +static void printPerLevelMinimum(Node root) +{ +/* Base Case*/ + + if (root == null) + return ; +/* Create an empty queue for + level order traversal*/ + + Queue q = new LinkedList(); +/* push the root for Change the level*/ + + q.add(root); +/* for go level by level*/ + + q.add(null); + int min = Integer.MAX_VALUE; +/* for check the level*/ + + int level = 0; + while (q.isEmpty() == false) + { +/* Get top of queue*/ + + Node node = q.peek(); + q.remove(); +/* if node == null (Means this is + boundary between two levels)*/ + + if (node == null) + { + System.out.print(""level "" + level + + "" min is = "" + min+ ""\n""); +/* here queue is empty represent + no element in the actual + queue*/ + + if (q.isEmpty()) + break; + q.add(null); +/* increment level*/ + + level++; +/* Reset min for next level + minimum value*/ + + min = Integer.MAX_VALUE; + continue; + } +/* get Minimum in every level*/ + + if (min > node.data) + min = node.data; + /* Enqueue left child */ + + if (node.left != null) + { + q.add(node.left); + } + /*Enqueue right child */ + + if (node.right != null) + { + q.add(node.right); + } + } +} +/*Utility function to create a +new tree node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree shown + in above diagram*/ + + Node root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + /* 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 */ + + System.out.print(""Every Level minimum is"" + + ""\n""); + printPerLevelMinimum(root); +} +}"," '''Python3 program to prminimum element +in each level of binary tree. +Importing Queue''' + +from queue import Queue + '''Utility class to create a +new tree node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None + '''return height of tree p''' + +def heightoftree(root): + if (root == None): + return 0 + left = heightoftree(root.left) + right = heightoftree(root.right) + if left > right: + return left + 1 + else: + return right + 1 + '''Iterative method to find every level +minimum element of Binary Tree''' + +def printPerLevelMinimum(root): + ''' Base Case''' + + if (root == None): + return + ''' Create an empty queue for + level order traversal''' + + q = Queue() + ''' put the root for Change the level''' + + q.put(root) + ''' for go level by level''' + + q.put(None) + Min = 9999999999999 + ''' for check the level''' + + level = 0 + while (q.empty() == False): + ''' Get get of queue''' + + node = q.queue[0] + q.get() + ''' if node == None (Means this is + boundary between two levels)''' + + if (node == None): + print(""level"", level, ""min is ="", Min) + ''' here queue is empty represent + no element in the actual + queue''' + + if (q.empty()): + break + q.put(None) + ''' increment level''' + + level += 1 + ''' Reset min for next level + minimum value''' + + Min = 999999999999 + continue + ''' get Minimum in every level''' + + if (Min > node.data): + Min = node.data + ''' Enqueue left child''' + + if (node.left != None): + q.put(node.left) + ''' Enqueue right child''' + + if (node.right != None): + q.put(node.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create binary tree shown + in above diagram''' + + root = newNode(7) + root.left = newNode(6) + root.right = newNode(5) + root.left.left = newNode(4) + root.left.right = newNode(3) + root.right.left = newNode(2) + root.right.right = newNode(1) + ''' 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 ''' + + print(""Every Level minimum is"") + printPerLevelMinimum(root)" +Dynamic Connectivity | Set 1 (Incremental),"/*Java implementation of +incremental connectivity*/ + +import java.util.*; +class GFG +{ +/*Finding the root of node i*/ + +static int root(int arr[], int i) +{ + while (arr[i] != i) + { + arr[i] = arr[arr[i]]; + i = arr[i]; + } + return i; +} +/*union of two nodes a and b*/ + +static void weighted_union(int arr[], int rank[], + int a, int b) +{ + int root_a = root (arr, a); + int root_b = root (arr, b); +/* union based on rank*/ + + if (rank[root_a] < rank[root_b]) + { + arr[root_a] = arr[root_b]; + rank[root_b] += rank[root_a]; + } + else + { + arr[root_b] = arr[root_a]; + rank[root_a] += rank[root_b]; + } +} +/*Returns true if two nodes have same root*/ + +static boolean areSame(int arr[], + int a, int b) +{ + return (root(arr, a) == root(arr, b)); +} +/*Performing an operation +according to query type*/ + +static void query(int type, int x, int y, + int arr[], int rank[]) +{ +/* type 1 query means checking if + node x and y are connected or not*/ + + if (type == 1) + { +/* If roots of x and y is same then yes + is the answer*/ + + if (areSame(arr, x, y) == true) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +/* type 2 query refers union of x and y*/ + + else if (type == 2) + { +/* If x and y have different roots then + union them*/ + + if (areSame(arr, x, y) == false) + weighted_union(arr, rank, x, y); + } +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* No.of nodes*/ + + int n = 7; +/* The following two arrays are used to + implement disjoint set data structure. + arr[] holds the parent nodes while rank + array holds the rank of subset*/ + + int []arr = new int[n]; + int []rank = new int[n]; +/* initializing both array and rank*/ + + for (int i = 0; i < n; i++) + { + arr[i] = i; + rank[i] = 1; + } +/* number of queries*/ + + int q = 11; + query(1, 0, 1, arr, rank); + query(2, 0, 1, arr, rank); + query(2, 1, 2, arr, rank); + query(1, 0, 2, arr, rank); + query(2, 0, 2, arr, rank); + query(2, 2, 3, arr, rank); + query(2, 3, 4, arr, rank); + query(1, 0, 5, arr, rank); + query(2, 4, 5, arr, rank); + query(2, 5, 6, arr, rank); + query(1, 2, 6, arr, rank); +} +}"," '''Python3 implementation of +incremental connectivity + ''' '''Finding the root of node i ''' + +def root(arr, i): + while (arr[i] != i): + arr[i] = arr[arr[i]] + i = arr[i] + return i + '''union of two nodes a and b ''' + +def weighted_union(arr, rank, a, b): + root_a = root (arr, a) + root_b = root (arr, b) + ''' union based on rank ''' + + if (rank[root_a] < rank[root_b]): + arr[root_a] = arr[root_b] + rank[root_b] += rank[root_a] + else: + arr[root_b] = arr[root_a] + rank[root_a] += rank[root_b] + '''Returns true if two nodes have +same root ''' + +def areSame(arr, a, b): + return (root(arr, a) == root(arr, b)) + '''Performing an operation according +to query type ''' + +def query(type, x, y, arr, rank): + ''' type 1 query means checking if + node x and y are connected or not ''' + + if (type == 1): + ''' If roots of x and y is same + then yes is the answer ''' + + if (areSame(arr, x, y) == True): + print(""Yes"") + else: + print(""No"") + ''' type 2 query refers union of + x and y ''' + + elif (type == 2): + ''' If x and y have different + roots then union them ''' + + if (areSame(arr, x, y) == False): + weighted_union(arr, rank, x, y) + '''Driver Code''' + +if __name__ == '__main__': + ''' No.of nodes ''' + + n = 7 + ''' The following two arrays are used to + implement disjoset data structure. + arr[] holds the parent nodes while rank + array holds the rank of subset ''' + + arr = [None] * n + rank = [None] * n + ''' initializing both array + and rank''' + + for i in range(n): + arr[i] = i + rank[i] = 1 + ''' number of queries ''' + + q = 11 + query(1, 0, 1, arr, rank) + query(2, 0, 1, arr, rank) + query(2, 1, 2, arr, rank) + query(1, 0, 2, arr, rank) + query(2, 0, 2, arr, rank) + query(2, 2, 3, arr, rank) + query(2, 3, 4, arr, rank) + query(1, 0, 5, arr, rank) + query(2, 4, 5, arr, rank) + query(2, 5, 6, arr, rank) + query(1, 2, 6, arr, rank)" +Longest Common Subsequence | DP-4,"/* Dynamic Programming Java implementation of LCS problem */ + +public class LongestCommonSubsequence +{ + /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ + + int lcs( char[] X, char[] Y, int m, int n ) + { + int L[][] = new int[m+1][n+1]; + /* Following steps build L[m+1][n+1] in bottom up fashion. Note + that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ + + for (int i=0; i<=m; i++) + { + for (int j=0; j<=n; j++) + { + if (i == 0 || j == 0) + L[i][j] = 0; + else if (X[i-1] == Y[j-1]) + L[i][j] = L[i-1][j-1] + 1; + else + L[i][j] = max(L[i-1][j], L[i][j-1]); + } + } + + /* L[m][n] contains length of LCS + for X[0..n-1] and Y[0..m-1] */ + + return L[m][n]; + }/* Utility function to get max of 2 integers */ + + int max(int a, int b) + { + return (a > b)? a : b; + } +/*Driver Code*/ + + public static void main(String[] args) + { + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + String s1 = ""AGGTAB""; + String s2 = ""GXTXAYB""; + char[] X=s1.toCharArray(); + char[] Y=s2.toCharArray(); + int m = X.length; + int n = Y.length; + System.out.println(""Length of LCS is"" + "" "" + + lcs.lcs( X, Y, m, n ) ); + } +}"," '''Dynamic Programming implementation of LCS problem''' + +def lcs(X , Y): + ''' Returns length of LCS for X[0..m-1], Y[0..n-1]''' + + m = len(X) + n = len(Y) + L = [[None]*(n+1) for i in xrange(m+1)] '''Following steps build L[m+1][n+1] in bottom up fashion + Note: L[i][j] contains length of LCS of X[0..i-1] + and Y[0..j-1]''' + + for i in range(m+1): + for j in range(n+1): + if i == 0 or j == 0 : + L[i][j] = 0 + elif X[i-1] == Y[j-1]: + L[i][j] = L[i-1][j-1]+1 + else: + L[i][j] = max(L[i-1][j] , L[i][j-1]) + ''' L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]''' + + return L[m][n] + '''end of function lcs +Driver program to test the above function''' + +X = ""AGGTAB"" +Y = ""GXTXAYB"" +print ""Length of LCS is "", lcs(X, Y)" +Number of elements less than or equal to a given number in a given subarray | Set 2 (Including Updates),"/*Number of elements less than or equal to a given +number in a given subarray and allowing update +operations.*/ + +class Test +{ + static final int MAX = 10001; +/* updating the bit array of a valid block*/ + + static void update(int idx, int blk, int val, int bit[][]) + { + for (; idx 0 ; idx -= idx&-idx) + sum += bit[l/blk_sz][idx]; + l += blk_sz; + } +/* Traversing the last block*/ + + while (l <= r) + { + if (arr[l] <= k) + sum++; + l++; + } + return sum; + } +/* Preprocessing the array*/ + + static void preprocess(int arr[], int blk_sz, int n, int bit[][]) + { + for (int i=0; i 0: + summ += bit[l // blk_sz][idx] + idx -= (idx & -idx) + l += blk_sz + ''' Traversing the last block''' + + while l <= r: + if arr[l] <= k: + summ += 1 + l += 1 + return summ + '''Preprocessing the array''' + +def preprocess(arr, blk_sz, n, bit): + for i in range(n): + update(arr[i], i // blk_sz, 1, bit) +def preprocessUpdate(i, v, blk_sz, arr, bit): + ''' updating the bit array at the original + and new value of array''' + + update(arr[i], i // blk_sz, -1, bit) + update(v, i // blk_sz, 1, bit) + arr[i] = v + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [5, 1, 2, 3, 4] + n = len(arr) + ''' size of block size will be equal + to square root of n''' + + from math import sqrt + blk_sz = int(sqrt(n)) + ''' initialising bit array of each block + as elements of array cannot exceed 10^4 + so size of bit array is accordingly''' + + bit = [[0 for i in range(MAX)] + for j in range(blk_sz + 1)] + preprocess(arr, blk_sz, n, bit) + print(query(1, 3, 1, arr, blk_sz, bit)) + preprocessUpdate(3, 10, blk_sz, arr, bit) + print(query(3, 3, 4, arr, blk_sz, bit)) + preprocessUpdate(2, 1, blk_sz, arr, bit) + preprocessUpdate(0, 2, blk_sz, arr, bit) + print(query(0, 4, 5, arr, blk_sz, bit))" +Convert a normal BST to Balanced BST,"/*Java program to convert a left unbalanced BST to a balanced BST*/ + +import java.util.*; +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* This function traverse the skewed binary tree and + stores its nodes pointers in vector nodes[] */ + + void storeBSTNodes(Node root, Vector nodes) + { +/* Base case*/ + + if (root == null) + return; +/* Store nodes in Inorder (which is sorted + order for BST)*/ + + storeBSTNodes(root.left, nodes); + nodes.add(root); + storeBSTNodes(root.right, nodes); + } + /* Recursive function to construct binary tree */ + + Node buildTreeUtil(Vector nodes, int start, + int end) + { +/* base case*/ + + if (start > end) + return null; + /* Get the middle element and make it root */ + + int mid = (start + end) / 2; + Node node = nodes.get(mid); + /* Using index in Inorder traversal, construct + left and right subtress */ + + node.left = buildTreeUtil(nodes, start, mid - 1); + node.right = buildTreeUtil(nodes, mid + 1, end); + return node; + } +/* This functions converts an unbalanced BST to + a balanced BST*/ + + Node buildTree(Node root) + { +/* Store nodes of given BST in sorted order*/ + + Vector nodes = new Vector(); + storeBSTNodes(root, nodes); +/* Constucts BST from nodes[]*/ + + int n = nodes.size(); + return buildTreeUtil(nodes, 0, n - 1); + } + /* Function to do preorder traversal of tree */ + + void preOrder(Node node) + { + if (node == null) + return; + System.out.print(node.data + "" ""); + preOrder(node.left); + preOrder(node.right); + } +/* Driver program to test the above functions*/ + + public static void main(String[] args) + { + /* Constructed skewed binary tree is + 10 + / + 8 + / + 7 + / + 6 + / + 5 */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.left.left = new Node(7); + tree.root.left.left.left = new Node(6); + tree.root.left.left.left.left = new Node(5); + tree.root = tree.buildTree(tree.root); + System.out.println(""Preorder traversal of balanced BST is :""); + tree.preOrder(tree.root); + } +}"," '''Python3 program to convert a left +unbalanced BST to a balanced BST ''' + +import sys +import math + '''A binary tree node has data, pointer to left child +and a pointer to right child ''' + +class Node: + def __init__(self,data): + self.data=data + self.left=None + self.right=None + '''This function traverse the skewed binary tree and +stores its nodes pointers in vector nodes[]''' + +def storeBSTNodes(root,nodes): + ''' Base case''' + + if not root: + return + ''' Store nodes in Inorder (which is sorted + order for BST) ''' + + storeBSTNodes(root.left,nodes) + nodes.append(root) + storeBSTNodes(root.right,nodes) + '''Recursive function to construct binary tree ''' + +def buildTreeUtil(nodes,start,end): + ''' base case ''' + + if start>end: + return None + ''' Get the middle element and make it root ''' + + mid=(start+end)//2 + node=nodes[mid] + ''' Using index in Inorder traversal, construct + left and right subtress''' + + node.left=buildTreeUtil(nodes,start,mid-1) + node.right=buildTreeUtil(nodes,mid+1,end) + return node + '''This functions converts an unbalanced BST to +a balanced BST''' + +def buildTree(root): + ''' Store nodes of given BST in sorted order ''' + + nodes=[] + storeBSTNodes(root,nodes) + ''' Constucts BST from nodes[] ''' + + n=len(nodes) + return buildTreeUtil(nodes,0,n-1) + '''Function to do preorder traversal of tree''' + +def preOrder(root): + if not root: + return + print(""{} "".format(root.data),end="""") + preOrder(root.left) + preOrder(root.right) + '''Driver code''' + +if __name__=='__main__': + ''' Constructed skewed binary tree is + 10 + / + 8 + / + 7 + / + 6 + / + 5 ''' + + root = Node(10) + root.left = Node(8) + root.left.left = Node(7) + root.left.left.left = Node(6) + root.left.left.left.left = Node(5) + root = buildTree(root) + print(""Preorder traversal of balanced BST is :"") + preOrder(root)" +Compute sum of digits in all numbers from 1 to n,"/*JAVA program to compute sum of digits +in numbers from 1 to n*/ + +import java.io.*; +import java.math.*; +class GFG{ +/* Function to computer sum of digits in + numbers from 1 to n. Comments use + example of 328 to explain the code*/ + + static int sumOfDigitsFrom1ToN(int n) + { +/* base case: if n<10 return sum of + first n natural numbers*/ + + if (n < 10) + return (n * (n + 1) / 2); +/* d = number of digits minus one in + n. For 328, d is 2*/ + + int d = (int)(Math.log10(n)); +/* computing sum of digits from 1 to 10^d-1, + d=1 a[0]=0; + d=2 a[1]=sum of digit from 1 to 9 = 45 + d=3 a[2]=sum of digit from 1 to 99 = + a[1]*10 + 45*10^1 = 900 + d=4 a[3]=sum of digit from 1 to 999 = + a[2]*10 + 45*10^2 = 13500*/ + + int a[] = new int[d+1]; + a[0] = 0; a[1] = 45; + for (int i = 2; i <= d; i++) + a[i] = a[i-1] * 10 + 45 * + (int)(Math.ceil(Math.pow(10, i-1))); +/* computing 10^d*/ + + int p = (int)(Math.ceil(Math.pow(10, d))); +/* Most significant digit (msd) of n, + For 328, msd is 3 which can be obtained + using 328/100*/ + + int msd = n / p; +/* EXPLANATION FOR FIRST and SECOND TERMS IN + BELOW LINE OF CODE + First two terms compute sum of digits from + 1 to 299 + (sum of digits in range 1-99 stored in a[d]) + + (sum of digits in range 100-199, can be + calculated as 1*100 + a[d] + (sum of digits in range 200-299, can be + calculated as 2*100 + a[d] + The above sum can be written as 3*a[d] + + (1+2)*100 + EXPLANATION FOR THIRD AND FOURTH TERMS IN + BELOW LINE OF CODE + The last two terms compute sum of digits in + number from 300 to 328. The third term adds + 3*29 to sum as digit 3 occurs in all numbers + from 300 to 328. The fourth term recursively + calls for 28*/ + + return (msd * a[d] + (msd * (msd - 1) / 2) * p + + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); + } +/* Driver Program*/ + + public static void main(String args[]) + { + int n = 328; + System.out.println(""Sum of digits in numbers "" + + ""from 1 to "" +n + "" is "" + + sumOfDigitsFrom1ToN(n)); + } +}"," '''PYTHON 3 program to compute sum of digits +in numbers from 1 to n''' + +import math + '''Function to computer sum of digits in +numbers from 1 to n. Comments use example +of 328 to explain the code''' + +def sumOfDigitsFrom1ToN( n) : + ''' base case: if n<10 return sum of + first n natural numbers''' + + if (n<10) : + return (n*(n+1)/2) + ''' d = number of digits minus one in n. + For 328, d is 2''' + + d = (int)(math.log10(n)) + '''computing sum of digits from 1 to 10^d-1, + d=1 a[0]=0; + d=2 a[1]=sum of digit from 1 to 9 = 45 + d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + + 45*10^1 = 900 + d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + + 45*10^2 = 13500''' + + a = [0] * (d + 1) + a[0] = 0 + a[1] = 45 + for i in range(2, d+1) : + a[i] = a[i-1] * 10 + 45 * (int)(math.ceil(math.pow(10,i-1))) + ''' computing 10^d''' + + p = (int)(math.ceil(math.pow(10, d))) + ''' Most significant digit (msd) of n, + For 328, msd is 3 which can be obtained + using 328/100''' + + msd = n//p + '''EXPLANATION FOR FIRST and SECOND TERMS IN + BELOW LINE OF CODE + First two terms compute sum of digits from 1 to 299 + (sum of digits in range 1-99 stored in a[d]) + + (sum of digits in range 100-199, can be calculated + as 1*100 + a[d]. (sum of digits in range 200-299, + can be calculated as 2*100 + a[d] + The above sum can be written as 3*a[d] + (1+2)*100 + EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW + LINE OF CODE + The last two terms compute sum of digits in number + from 300 to 328. The third term adds 3*29 to sum + as digit 3 occurs in all numbers from 300 to 328. + The fourth term recursively calls for 28''' + + return (int)(msd * a[d] + (msd*(msd-1) // 2) * p + + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)) + '''Driver Program''' + +n = 328 +print(""Sum of digits in numbers from 1 to"", + n ,""is"",sumOfDigitsFrom1ToN(n))" +Sum of matrix element where each elements is integer division of row and column,"/*java program to find sum of matrix element +where each element is integer division of +row and column.*/ + +import java.io.*; +class GFG { +/* Return sum of matrix element where each + element is division of its corresponding + row and column.*/ + + static int findSum(int n) + { + int ans = 0, temp = 0, num; +/* For each column.*/ + + for (int i = 1; i <= n && temp < n; i++) + { +/* count the number of elements of + each column. Initialize to i -1 + because number of zeroes are i - 1.*/ + + temp = i - 1; +/* For multiply*/ + + num = 1; + while (temp < n) + { + if (temp + i <= n) + ans += (i * num); + else + ans += ((n - temp) * num); + temp += i; + num ++; + } + } + return ans; + } +/* Driven Program*/ + + public static void main (String[] args) + { + int N = 2; + System.out.println(findSum(N)); + } +}"," '''Program to find sum of matrix element +where each element is integer division +of row and column.''' + + '''Return sum of matrix element where each +element is division of its corresponding +row and column.''' + +def findSum(n): + ans = 0; temp = 0; + ''' For each column.''' + + for i in range(1, n + 1): + if temp < n: ''' count the number of elements of + each column. Initialize to i -1 + because number of zeroes are i - 1.''' + + + temp = i - 1 + ''' For multiply''' + + num = 1 + while temp < n: + if temp + i <= n: + ans += i * num + else: + ans += (n - temp) * num + temp += i + num += 1 + return ans + '''Driver Code''' + +N = 2 +print(findSum(N))" +Types of Linked List,"/*Java program to illustrate +creation and traversal of +Singly Linked List*/ + +class GFG{ + +/*Structure of Node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to print the content of +linked list starting from the +given node*/ + +static void printList(Node n) +{ +/* Iterate till n reaches null*/ + + while (n != null) + { +/* Print the data*/ + + System.out.print(n.data + "" ""); + n = n.next; + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + Node head = null; + Node second = null; + Node third = null; + +/* Allocate 3 nodes in + the heap*/ + + head = new Node(); + second = new Node(); + third = new Node(); + +/* Assign data in first + node*/ + + head.data = 1; + +/* Link first node with + second*/ + + head.next = second; + +/* Assign data to second + node*/ + + second.data = 2; + second.next = third; + +/* Assign data to third + node*/ + + third.data = 3; + third.next = null; + + printList(head); +} +} + + +", +Detect loop in a linked list,"/*Java program to detect loop in a linked list*/ + +import java.util.*; +class GFG{ +/*Link list node*/ + +static class Node +{ + int data; + Node next; + int flag; +}; +static Node push(Node head_ref, int new_data) +{ +/* Allocate node*/ + + Node new_node = new Node(); +/* Put in the data*/ + + new_node.data = new_data; + new_node.flag = 0; +/* Link the old list off the new node*/ + + new_node.next = head_ref; +/* Move the head to point to the new node*/ + + head_ref = new_node; + return head_ref; +} +/*Returns true if there is a loop in linked +list else returns false.*/ + +static boolean detectLoop(Node h) +{ + while (h != null) + { +/* If this node is already traverse + it means there is a cycle + (Because you we encountering the + node for the second time).*/ + + if (h.flag == 1) + return true; +/* If we are seeing the node for + the first time, mark its flag as 1*/ + + h.flag = 1; + h = h.next; + } + return false; +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* Start with the empty list*/ + + Node head = null; + head = push(head, 20); + head = push(head, 4); + head = push(head, 15); + head = push(head, 10); +/* Create a loop for testing*/ + + head.next.next.next.next = head; + if (detectLoop(head)) + System.out.print(""Loop found""); + else + System.out.print(""No Loop""); +} +}"," '''Python3 program to detect loop in a linked list''' + + ''' Link list node ''' + +class Node: + def __init__(self): + self.data = 0 + self.next = None + self.flag = 0 +def push(head_ref, new_data): + ''' allocate node ''' + + new_node = Node(); + ''' put in the data ''' + + new_node.data = new_data; + new_node.flag = 0; + ''' link the old list off the new node ''' + + new_node.next = (head_ref); + ''' move the head to point to the new node ''' + + (head_ref) = new_node; + return head_ref + '''Returns true if there is a loop in linked list +else returns false.''' + +def detectLoop(h): + while (h != None): + ''' If this node is already traverse + it means there is a cycle + (Because you we encountering the + node for the second time).''' + + if (h.flag == 1): + return True; + ''' If we are seeing the node for + the first time, mark its flag as 1''' + + h.flag = 1; + h = h.next; + return False; + ''' Driver program to test above function''' + +if __name__=='__main__': + ''' Start with the empty list ''' + + head = None; + head = push(head, 20); + head = push(head, 4); + head = push(head, 15); + head = push( head, 10) + ''' Create a loop for testing ''' + + head.next.next.next.next = head; + if (detectLoop(head)): + print(""Loop found"") + else: + print(""No Loop"")" +Print all elements in sorted order from row and column wise sorted matrix,"/*A Java program to Print all elements +in sorted order from row and +column wise sorted matrix*/ + +class GFG +{ + static final int INF = Integer.MAX_VALUE; + static final int N = 4; +/* A utility function to youngify a Young Tableau. + This is different from standard youngify. + It assumes that the value at mat[0][0] is infinite.*/ + + static void youngify(int mat[][], int i, int j) + { +/* Find the values at down and right sides of mat[i][j]*/ + + int downVal = (i + 1 < N) ? + mat[i + 1][j] : INF; + int rightVal = (j + 1 < N) ? + mat[i][j + 1] : INF; +/* If mat[i][j] is the down right corner element, + return*/ + + if (downVal == INF && rightVal == INF) + { + return; + } +/* Move the smaller of two values + (downVal and rightVal) to mat[i][j] + and recur for smaller value*/ + + if (downVal < rightVal) + { + mat[i][j] = downVal; + mat[i + 1][j] = INF; + youngify(mat, i + 1, j); + } + else + { + mat[i][j] = rightVal; + mat[i][j + 1] = INF; + youngify(mat, i, j + 1); + } + } +/* A utility function to extract + minimum element from Young tableau*/ + + static int extractMin(int mat[][]) + { + int ret = mat[0][0]; + mat[0][0] = INF; + youngify(mat, 0, 0); + return ret; + } +/* This function uses extractMin() + to print elements in sorted order*/ + + static void printSorted(int mat[][]) + { + System.out.println(""Elements of matrix in sorted order n""); + for (int i = 0; i < N * N; i++) + { + System.out.print(extractMin(mat) + "" ""); + } + } +/* Driver Code*/ + + public static void main(String args[]) + { + int mat[][] = {{10, 20, 30, 40}, + {15, 25, 35, 45}, + {27, 29, 37, 48}, + {32, 33, 39, 50}}; + printSorted(mat); + } +}"," '''Python 3 program to Print all elements +in sorted order from row and column +wise sorted matrix''' + +import sys +INF = sys.maxsize +N = 4 + '''A utility function to youngify a Young +Tableau. This is different from standard +youngify. It assumes that the value at +mat[0][0] is infinite.''' + +def youngify(mat, i, j): + ''' Find the values at down and + right sides of mat[i][j]''' + + downVal = mat[i + 1][j] if (i + 1 < N) else INF + rightVal = mat[i][j + 1] if (j + 1 < N) else INF + ''' If mat[i][j] is the down right + corner element, return''' + + if (downVal == INF and rightVal == INF): + return + ''' Move the smaller of two values + (downVal and rightVal) to mat[i][j] + and recur for smaller value''' + + if (downVal < rightVal): + mat[i][j] = downVal + mat[i + 1][j] = INF + youngify(mat, i + 1, j) + else: + mat[i][j] = rightVal + mat[i][j + 1] = INF + youngify(mat, i, j + 1) + '''A utility function to extract minimum +element from Young tableau''' + +def extractMin(mat): + ret = mat[0][0] + mat[0][0] = INF + youngify(mat, 0, 0) + return ret + '''This function uses extractMin() to +print elements in sorted order''' + +def printSorted(mat): + print(""Elements of matrix in sorted order n"") + i = 0 + while i < N * N: + print(extractMin(mat), end = "" "") + i += 1 + '''Driver Code''' + +if __name__ == ""__main__"": + mat = [[10, 20, 30, 40], + [15, 25, 35, 45], + [27, 29, 37, 48], + [32, 33, 39, 50]] + printSorted(mat)" +Minimum flip required to make Binary Matrix symmetric,"/*Java Program to find minimum flip +required to make Binary Matrix +symmetric along main diagonal*/ + +import java.util.*; +class GFG { +/* Return the minimum flip required + to make Binary Matrix symmetric + along main diagonal.*/ + + static int minimumflip(int mat[][], int n) + { +/* Comparing elements across diagonal*/ + + int flip = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < i; j++) + if (mat[i][j] != mat[j][i]) + flip++; + return flip; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int n = 3; + int mat[][] = {{ 0, 0, 1 }, + { 1, 1, 1 }, + { 1, 0, 0 }}; + System.out.println(minimumflip(mat, n)); + } +}"," '''Python3 code to find minimum flip +required to make Binary Matrix +symmetric along main diagonal''' + +N = 3 + '''Return the minimum flip required +to make Binary Matrix symmetric +along main diagonal.''' + +def minimumflip( mat , n ): + ''' Comparing elements across diagonal''' + + flip = 0 + for i in range(n): + for j in range(i): + if mat[i][j] != mat[j][i] : + flip += 1 + return flip + '''Driver Program''' + +n = 3 +mat =[[ 0, 0, 1], + [ 1, 1, 1], + [ 1, 0, 0]] +print( minimumflip(mat, n))" +Reorder an array according to given indexes,"/*Java code to reorder an array +according to given indices*/ + +class GFG{ +static int heapSize; +public static void heapify(int arr[], + int index[], int i) +{ + int largest = i; +/* left child in 0 based indexing*/ + + int left = 2 * i + 1; +/* right child in 1 based indexing*/ + + int right = 2 * i + 2; +/* Find largest index from root, + left and right child*/ + + if (left < heapSize && + index[left] > index[largest] ) + { + largest = left; + } + if (right < heapSize && + index[right] > index[largest] ) + { + largest = right; + } + if (largest != i) + { +/* swap arr whenever index is swapped*/ + + int temp = arr[largest]; + arr[largest] = arr[i]; + arr[i] = temp; + temp = index[largest]; + index[largest] = index[i]; + index[i] = temp; + heapify(arr, index, largest); + } +} +public static void heapSort(int arr[], + int index[], int n) +{ +/* Build heap*/ + + for(int i = (n - 1) / 2 ; i >= 0 ; i--) + { + heapify(arr, index, i); + } +/* Swap the largest element of + index(first element) + with the last element*/ + + for(int i = n - 1 ; i > 0 ; i--) + { + int temp = index[0]; + index[0] = index[i]; + index[i] = temp; +/* swap arr whenever index is swapped*/ + + temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + heapSize--; + heapify(arr, index, 0); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 50, 40, 70, 60, 90 }; + int index[] = { 3, 0, 4, 1, 2 }; + int n = arr.length; + heapSize = n; + heapSort(arr, index, n); + System.out.println(""Reordered array is: ""); + for(int i = 0 ; i < n ; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + System.out.println(""Modified Index array is: ""); + for(int i = 0; i < n; i++) + System.out.print(index[i] + "" ""); +} +}"," '''Python3 code to reorder an array +according to given indices''' + +def heapify(arr, index, i): + largest = i + ''' left child in 0 based indexing''' + + left = 2 * i + 1 + ''' right child in 1 based indexing''' + + right = 2 * i + 2 + global heapSize + ''' Find largest index from root, + left and right child''' + + if (left < heapSize and + index[left] > index[largest]): + largest = left + if (right < heapSize and + index[right] > index[largest]): + largest = right + if (largest != i): + ''' Swap arr whenever index is swapped''' + + arr[largest], arr[i] = arr[i], arr[largest] + index[largest], index[i] = index[i], index[largest] + heapify(arr, index, largest) +def heapSort(arr, index, n): + ''' Build heap''' + + global heapSize + for i in range(int((n - 1) / 2), -1, -1): + heapify(arr, index, i) + ''' Swap the largest element of + index(first element) with + the last element''' + + for i in range(n - 1, 0, -1): + index[0], index[i] = index[i], index[0] + ''' Swap arr whenever index is swapped''' + + arr[0], arr[i] = arr[i], arr[0] + heapSize -= 1 + heapify(arr, index, 0) + '''Driver Code''' + +arr = [ 50, 40, 70, 60, 90 ] +index = [ 3, 0, 4, 1, 2 ] +n = len(arr) +global heapSize +heapSize = n +heapSort(arr, index, n) +print(""Reordered array is: "") +print(*arr, sep = ' ') +print(""Modified Index array is: "") +print(*index, sep = ' ')" +Kronecker Product of two matrices,"/*Java code to find the Kronecker Product of +two matrices and stores it as matrix C*/ + +import java.io.*; +import java.util.*; +class GFG { +/* rowa and cola are no of rows and columns + of matrix A + rowb and colb are no of rows and columns + of matrix B*/ + + static int cola = 2, rowa = 3, colb = 3, rowb = 2; +/* Function to computes the Kronecker Product + of two matrices*/ + + static void Kroneckerproduct(int A[][], int B[][]) + { + int[][] C= new int[rowa * rowb][cola * colb]; +/* i loops till rowa*/ + + for (int i = 0; i < rowa; i++) + { +/* k loops till rowb*/ + + for (int k = 0; k < rowb; k++) + { +/* j loops till cola*/ + + for (int j = 0; j < cola; j++) + { +/* l loops till colb*/ + + for (int l = 0; l < colb; l++) + { +/* Each element of matrix A is + multiplied by whole Matrix B + resp and stored as Matrix C*/ + + C[i + l + 1][j + k + 1] = A[i][j] * B[k][l]; + System.out.print( C[i + l + 1][j + k + 1]+"" ""); + } + } + System.out.println(); + } + } + } +/* Driver program*/ + + public static void main (String[] args) + { + int A[][] = { { 1, 2 }, + { 3, 4 }, + { 1, 0 } }; + int B[][] = { { 0, 5, 2 }, + { 6, 7, 3 } }; + Kroneckerproduct(A, B); + } +}"," '''Python3 code to find the Kronecker Product of two +matrices and stores it as matrix C''' + '''rowa and cola are no of rows and columns +of matrix A +rowb and colb are no of rows and columns +of matrix B''' + +cola = 2 +rowa = 3 +colb = 3 +rowb = 2 + '''Function to computes the Kronecker Product +of two matrices''' + +def Kroneckerproduct( A , B ): + C = [[0 for j in range(cola * colb)] for i in range(rowa * rowb)] + ''' i loops till rowa''' + + for i in range(0, rowa): + ''' k loops till rowb''' + + for k in range(0, rowb): + ''' j loops till cola''' + + for j in range(0, cola): + ''' l loops till colb''' + + for l in range(0, colb): + ''' Each element of matrix A is + multiplied by whole Matrix B + resp and stored as Matrix C''' + + C[i + l + 1][j + k + 1] = A[i][j] * B[k][l] + print (C[i + l + 1][j + k + 1],end=' ') + print (""\n"") + '''Driver code.''' + +A = [[0 for j in range(2)] for i in range(3)] +B = [[0 for j in range(3)] for i in range(2)] +A[0][0] = 1 +A[0][1] = 2 +A[1][0] = 3 +A[1][1] = 4 +A[2][0] = 1 +A[2][1] = 0 +B[0][0] = 0 +B[0][1] = 5 +B[0][2] = 2 +B[1][0] = 6 +B[1][1] = 7 +B[1][2] = 3 +Kroneckerproduct( A , B )" +Maximum width of a binary tree,"/*Java program to calculate width of binary tree*/ + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; + /* Function to get the maximum width of a binary tree*/ + + int getMaxWidth(Node node) + { + int width; + int h = height(node); +/* Create an array that will store count of nodes at + each level*/ + + int count[] = new int[10]; + int level = 0; +/* Fill the count array using preorder traversal*/ + + getMaxWidthRecur(node, count, level); +/* Return the maximum value from count array*/ + + return getMax(count, h); + } +/* A function that fills count array with count of nodes + at every level of given binary tree*/ + + void getMaxWidthRecur(Node node, int count[], int level) + { + if (node != null) { + count[level]++; + getMaxWidthRecur(node.left, count, level + 1); + getMaxWidthRecur(node.right, count, level + 1); + } + } + /* Compute the ""height"" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + + int height(Node node) + { + if (node == null) + return 0; + else { + /* compute the height of each subtree */ + + int lHeight = height(node.left); + int rHeight = height(node.right); + /* use the larger one */ + + return (lHeight > rHeight) ? (lHeight + 1) + : (rHeight + 1); + } + } +/* Return the maximum value from count array*/ + + int getMax(int arr[], int n) + { + int max = arr[0]; + int i; + for (i = 0; i < n; i++) { + if (arr[i] > max) + max = arr[i]; + } + return max; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* + Constructed bunary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(8); + tree.root.right.right.left = new Node(6); + tree.root.right.right.right = new Node(7); + System.out.println(""Maximum width is "" + + tree.getMaxWidth(tree.root)); + } +}"," '''Python program to find the maximum width of +binary tree using Preorder Traversal.''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Function to get the maximum width of a binary tree''' + +def getMaxWidth(root): + h = height(root) + ''' Create an array that will store count of nodes at each level''' + + count = [0] * h + level = 0 + ''' Fill the count array using preorder traversal''' + + getMaxWidthRecur(root, count, level) + ''' Return the maximum value from count array''' + + return getMax(count, h) + '''A function that fills count array with count of nodes at every +level of given binary tree''' + +def getMaxWidthRecur(root, count, level): + if root is not None: + count[level] += 1 + getMaxWidthRecur(root.left, count, level+1) + getMaxWidthRecur(root.right, count, level+1) + '''Compute the ""height"" of a tree -- the number of +nodes along the longest path from the root node +down to the farthest leaf node.''' + +def height(node): + if node is None: + return 0 + else: + ''' compute the height of each subtree''' + + lHeight = height(node.left) + rHeight = height(node.right) + ''' use the larger one''' + + return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) + '''Return the maximum value from count array''' + +def getMax(count, n): + max = count[0] + for i in range(1, n): + if (count[i] > max): + max = count[i] + return max + '''Driver program to test above function''' + + + ''' +Constructed bunary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 + ''' +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(8) +root.right.right.left = Node(6) +root.right.right.right = Node(7) +print ""Maximum width is %d"" % (getMaxWidth(root))" +Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way),"/*Java program to fill a matrix with values from +1 to n*n in spiral fashion.*/ + +class GFG { + static int MAX = 100; +/*Fills a[m][n] with values from 1 to m*n in +spiral fashion.*/ + + static void spiralFill(int m, int n, int a[][]) { +/* Initialize value to be filled in matrix*/ + + int val = 1; + /* k - starting row index + m - ending row index + l - starting column index + n - ending column index */ + + int k = 0, l = 0; + while (k < m && l < n) { + /* Print the first row from the remaining + rows */ + + for (int i = l; i < n; ++i) { + a[k][i] = val++; + } + k++; + /* Print the last column from the remaining + columns */ + + for (int i = k; i < m; ++i) { + a[i][n - 1] = val++; + } + n--; + /* Print the last row from the remaining + rows */ + + if (k < m) { + for (int i = n - 1; i >= l; --i) { + a[m - 1][i] = val++; + } + m--; + } + /* Print the first column from the remaining + columns */ + + if (l < n) { + for (int i = m - 1; i >= k; --i) { + a[i][l] = val++; + } + l++; + } + } + } + /* Driver program to test above functions */ + + public static void main(String[] args) { + int m = 4, n = 4; + int a[][] = new int[MAX][MAX]; + spiralFill(m, n, a); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + System.out.print(a[i][j] + "" ""); + } + System.out.println(""""); + } + } +}"," '''Python program to fill a matrix with +values from 1 to n*n in spiral fashion. + ''' '''Fills a[m][n] with values +from 1 to m*n in spiral fashion.''' + +def spiralFill(m, n, a): + ''' Initialize value to be filled in matrix.''' + + val = 1 + ''' k - starting row index + m - ending row index + l - starting column index + n - ending column index''' + + k, l = 0, 0 + while (k < m and l < n): + ''' Print the first row from the remaining rows.''' + + for i in range(l, n): + a[k][i] = val + val += 1 + k += 1 + ''' Print the last column from the remaining columns.''' + + for i in range(k, m): + a[i][n - 1] = val + val += 1 + n -= 1 + ''' Print the last row from the remaining rows.''' + + if (k < m): + for i in range(n - 1, l - 1, -1): + a[m - 1][i] = val + val += 1 + m -= 1 + ''' Print the first column from the remaining columns.''' + + if (l < n): + for i in range(m - 1, k - 1, -1): + a[i][l] = val + val += 1 + l += 1 + '''Driver program''' + +if __name__ == '__main__': + m, n = 4, 4 + a = [[0 for j in range(m)] for i in range(n)] + spiralFill(m, n, a) + for i in range(m): + for j in range(n): + print(a[i][j], end=' ') + print('')" +k-th smallest absolute difference of two elements in an array,"/*Java program to find k-th absolute difference +between two elements*/ + +import java.util.Scanner; +import java.util.Arrays; +class GFG +{ +/* returns number of pairs with absolute + difference less than or equal to mid */ + + static int countPairs(int[] a, int n, int mid) + { + int res = 0, value; + for(int i = 0; i < n; i++) + { +/* Upper bound returns pointer to position + of next higher number than a[i]+mid in + a[i..n-1]. We subtract (ub + i + 1) from + this position to count */ + + int ub = upperbound(a, n, a[i]+mid); + res += (ub- (i-1)); + } + return res; + } +/* returns the upper bound*/ + + static int upperbound(int a[], int n, int value) + { + int low = 0; + int high = n; + while(low < high) + { + final int mid = (low + high)/2; + if(value >= a[mid]) + low = mid + 1; + else + high = mid; + } + return low; + } +/* Returns k-th absolute difference*/ + + static int kthDiff(int a[], int n, int k) + { +/* Sort array*/ + + Arrays.sort(a); +/* Minimum absolute difference*/ + + int low = a[1] - a[0]; + for (int i = 1; i <= n-2; ++i) + low = Math.min(low, a[i+1] - a[i]); +/* Maximum absolute difference*/ + + int high = a[n-1] - a[0]; +/* Do binary search for k-th absolute difference*/ + + while (low < high) + { + int mid = (low + high) >> 1; + if (countPairs(a, n, mid) < k) + low = mid + 1; + else + high = mid; + } + return low; + } +/* Driver function to check the above functions*/ + + public static void main(String args[]) + { + Scanner s = new Scanner(System.in); + int k = 3; + int a[] = {1,2,3,4}; + int n = a.length; + System.out.println(kthDiff(a, n, k)); + } +}"," '''Python3 program to find +k-th absolute difference +between two elements ''' + +from bisect import bisect as upper_bound + '''returns number of pairs with +absolute difference less than +or equal to mid. ''' + +def countPairs(a, n, mid): + res = 0 + for i in range(n): + ''' Upper bound returns pointer to position + of next higher number than a[i]+mid in + a[i..n-1]. We subtract (a + i + 1) from + this position to count ''' + + res += upper_bound(a, a[i] + mid) + return res + '''Returns k-th absolute difference ''' + +def kthDiff(a, n, k): + ''' Sort array ''' + + a = sorted(a) + ''' Minimum absolute difference ''' + + low = a[1] - a[0] + for i in range(1, n - 1): + low = min(low, a[i + 1] - a[i]) + ''' Maximum absolute difference ''' + + high = a[n - 1] - a[0] + ''' Do binary search for k-th absolute difference ''' + + while (low < high): + mid = (low + high) >> 1 + if (countPairs(a, n, mid) < k): + low = mid + 1 + else: + high = mid + return low + '''Driver code ''' + +k = 3 +a = [1, 2, 3, 4] +n = len(a) +print(kthDiff(a, n, k))" +Find element in a sorted array whose frequency is greater than or equal to n/2.,"/*Java code to find majority element in a +sorted array*/ + +public class Test { + + public static int findMajority(int arr[], int n) + { + return arr[n / 2]; + } + +/* Driver Code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 2, 2, 3 }; + int n = arr.length; + System.out.println(findMajority(arr, n)); + } +}"," '''Python 3 code to find +majority element in a +sorted array''' + + +def findMajority(arr, n): + + return arr[int(n / 2)] + + '''Driver Code''' + +arr = [1, 2, 2, 3] +n = len(arr) +print(findMajority(arr, n)) + + +" +Smallest subarray with k distinct numbers,"/*Java program to find minimum range that +contains exactly k distinct numbers.*/ + +import java.util.*; +class GFG{ +/*Prints the minimum range that contains exactly +k distinct numbers.*/ + +static void minRange(int arr[], int n, int k) +{ +/* Initially left and right side is -1 and -1, + number of distinct elements are zero and + range is n.*/ + + int l = 0, r = n; +/* Initialize right side*/ + + int j = -1; + HashMap hm = new HashMap<>(); + for(int i = 0; i < n; i++) + { + while (j < n) + { +/* Increment right side.*/ + + j++; +/* If number of distinct elements less + than k.*/ + + if (j < n && hm.size() < k) + hm.put(arr[j], + hm.getOrDefault(arr[j], 0) + 1); +/* If distinct elements are equal to k + and length is less than previous length.*/ + + if (hm.size() == k && + ((r - l) >= (j - i))) + { + l = i; + r = j; + break; + } + } +/* If number of distinct elements less + than k, then break.*/ + + if (hm.size() < k) + break; +/* If distinct elements equals to k then + try to increment left side.*/ + + while (hm.size() == k) + { + if (hm.getOrDefault(arr[i], 0) == 1) + hm.remove(arr[i]); + else + hm.put(arr[i], + hm.getOrDefault(arr[i], 0) - 1); +/* Increment left side.*/ + + i++; +/* It is same as explained in above loop.*/ + + if (hm.size() == k && + (r - l) >= (j - i)) + { + l = i; + r = j; + } + } + if (hm.getOrDefault(arr[i], 0) == 1) + hm.remove(arr[i]); + else + hm.put(arr[i], + hm.getOrDefault(arr[i], 0) - 1); + } + if (l == 0 && r == n) + System.out.println(""Invalid k""); + else + System.out.println(l + "" "" + r); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; + int n = arr.length; + int k = 3; + minRange(arr, n, k); +} +}"," '''Python3 program to find the minimum range +that contains exactly k distinct numbers.''' + +from collections import defaultdict + '''Prints the minimum range that contains +exactly k distinct numbers.''' + +def minRange(arr, n, k): + ''' Initially left and right side is -1 + and -1, number of distinct elements + are zero and range is n.''' + + l, r = 0, n + i = 0 + '''Initialize right side''' + + j = -1 + hm = defaultdict(lambda:0) + while i < n: + while j < n: + ''' increment right side.''' + + j += 1 + ''' if number of distinct elements less than k.''' + + if len(hm) < k and j < n: + hm[arr[j]] += 1 + ''' if distinct elements are equal to k + and length is less than previous length.''' + + if len(hm) == k and ((r - l) >= (j - i)): + l, r = i, j + break + ''' if number of distinct elements less + than k, then break.''' + + if len(hm) < k: + break + ''' if distinct elements equals to k then + try to increment left side.''' + + while len(hm) == k: + if hm[arr[i]] == 1: + del(hm[arr[i]]) + else: + hm[arr[i]] -= 1 + ''' increment left side.''' + + i += 1 + ''' it is same as explained in above loop.''' + + if len(hm) == k and (r - l) >= (j - i): + l, r = i, j + if hm[arr[i]] == 1: + del(hm[arr[i]]) + else: + hm[arr[i]] -= 1 + i += 1 + if l == 0 and r == n: + print(""Invalid k"") + else: + print(l, r) + '''Driver code for above function.''' + +if __name__ == ""__main__"": + arr = [1, 1, 2, 2, 3, 3, 4, 5] + n = len(arr) + k = 3 + minRange(arr, n, k)" +Expression Tree,"/*Java program to construct an expression tree*/ + +import java.util.Stack; +/*Java program for expression tree*/ + +class Node { + char value; + Node left, right; + Node(char item) { + value = item; + left = right = null; + } +} +class ExpressionTree { +/* A utility function to check if 'c' + is an operator*/ + + boolean isOperator(char c) { + if (c == '+' || c == '-' + || c == '*' || c == '/' + || c == '^') { + return true; + } + return false; + } +/* Utility function to do inorder traversal*/ + + void inorder(Node t) { + if (t != null) { + inorder(t.left); + System.out.print(t.value + "" ""); + inorder(t.right); + } + } +/* Returns root of constructed tree for given + postfix expression*/ + + Node constructTree(char postfix[]) { + Stack st = new Stack(); + Node t, t1, t2; +/* Traverse through every character of + input expression*/ + + for (int i = 0; i < postfix.length; i++) { +/* If operand, simply push into stack*/ + + if (!isOperator(postfix[i])) { + t = new Node(postfix[i]); + st.push(t); +/*operator*/ + +} else + { + t = new Node(postfix[i]); +/* Pop two top nodes + Store top +Remove top*/ + +t1 = st.pop(); + t2 = st.pop(); +/* make them children*/ + + t.right = t1; + t.left = t2; +/* System.out.println(t1 + """" + t2); + Add this subexpression to stack*/ + + st.push(t); + } + } +/* only element will be root of expression + tree*/ + + t = st.peek(); + st.pop(); + return t; + } +/*Driver program to test above*/ + + public static void main(String args[]) { + ExpressionTree et = new ExpressionTree(); + String postfix = ""ab+ef*g*-""; + char[] charArray = postfix.toCharArray(); + Node root = et.constructTree(charArray); + System.out.println(""infix expression is""); + et.inorder(root); + } +}"," '''Python program for expression tree''' + + '''An expression tree node''' + +class Et: + def __init__(self , value): + self.value = value + self.left = None + self.right = None + '''A utility function to check if 'c' +is an operator''' + +def isOperator(c): + if (c == '+' or c == '-' or c == '*' + or c == '/' or c == '^'): + return True + else: + return False + '''A utility function to do inorder traversal''' + +def inorder(t): + if t is not None: + inorder(t.left) + print t.value, + inorder(t.right) + '''Returns root of constructed tree for +given postfix expression''' + +def constructTree(postfix): + stack = [] + ''' Traverse through every character of input expression''' + + for char in postfix : + ''' if operand, simply push into stack''' + + if not isOperator(char): + t = Et(char) + stack.append(t) + ''' Operator''' + + else: + t = Et(char) ''' Pop two top nodes''' + + + t1 = stack.pop() + t2 = stack.pop() + ''' make them children''' + + t.right = t1 + t.left = t2 + ''' Add this subexpression to stack''' + + stack.append(t) + ''' Only element will be the root of expression tree''' + + t = stack.pop() + return t + '''Driver program to test above''' + +postfix = ""ab+ef*g*-"" +r = constructTree(postfix) +print ""Infix expression is"" +inorder(r)" +0-1 Knapsack Problem | DP-10,"/* A Naive recursive implementation +of 0-1 Knapsack problem */ + +class Knapsack { +/* A utility function that returns + maximum of two integers*/ + + static int max(int a, int b) + { + return (a > b) ? a : b; + } +/* Returns the maximum value that + can be put in a knapsack of + capacity W*/ + + static int knapSack(int W, int wt[], int val[], int n) + { +/* Base Case*/ + + if (n == 0 || W == 0) + return 0; +/* If weight of the nth item is + more than Knapsack capacity W, + then this item cannot be included + in the optimal solution*/ + + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); +/* Return the maximum of two cases: + (1) nth item included + (2) not included*/ + + else + return max(val[n - 1] + + knapSack(W - wt[n - 1], wt, + val, n - 1), + knapSack(W, wt, val, n - 1)); + } +/* Driver code*/ + + public static void main(String args[]) + { + int val[] = new int[] { 60, 100, 120 }; + int wt[] = new int[] { 10, 20, 30 }; + int W = 50; + int n = val.length; + System.out.println(knapSack(W, wt, val, n)); + } +}"," '''A naive recursive implementation +of 0-1 Knapsack Problem''' + '''Returns the maximum value that +can be put in a knapsack of +capacity W''' + +def knapSack(W, wt, val, n): + ''' Base Case''' + + if n == 0 or W == 0: + return 0 + ''' If weight of the nth item is + more than Knapsack of capacity W, + then this item cannot be included + in the optimal solution''' + + if (wt[n-1] > W): + return knapSack(W, wt, val, n-1) + ''' return the maximum of two cases: + (1) nth item included + (2) not included''' + + else: + return max( + val[n-1] + knapSack( + W-wt[n-1], wt, val, n-1), + knapSack(W, wt, val, n-1)) + '''Driver Code''' + +val = [60, 100, 120] +wt = [10, 20, 30] +W = 50 +n = len(val) +print knapSack(W, wt, val, n)" +Delete all the even nodes of a Circular Linked List,"/*Java program to delete all prime +node from a Circular singly linked list*/ + +class GFG +{ + +/*Structure for a node*/ + +static class Node +{ + int data; + Node next; +}; + +/*Function to insert a node at the beginning +of a Circular linked list*/ + +static Node push(Node head_ref, int data) +{ + Node ptr1 = new Node(); + Node temp = head_ref; + ptr1.data = data; + ptr1.next = head_ref; + +/* If linked list is not null then + set the next of last node*/ + + if (head_ref != null) + { + while (temp.next != head_ref) + temp = temp.next; + temp.next = ptr1; + return head_ref; + } + else +/*For the first node*/ + +ptr1.next = ptr1; + + head_ref = ptr1; +return head_ref; +} + +/*Delete the node if it is even*/ + +static Node deleteNode(Node head_ref, Node del) +{ + Node temp = head_ref; +/* If node to be deleted is head node*/ + + + if (head_ref == del) + head_ref = del.next; + +/* traverse list till not found + delete node*/ + + while (temp.next != del) + { + temp = temp.next; + } + +/* copy address of node*/ + + temp.next = del.next; + + return head_ref; +} + +/*Function to delete all even nodes +from the singly circular linked list*/ + +static Node deleteEvenNodes(Node head) +{ + Node ptr = head; + + Node next; + +/* traverse list till the end + if the node is even then delete it*/ + + do + { +/* if node is even*/ + + if (ptr.data % 2 == 0) + deleteNode(head, ptr); + +/* point to next node*/ + + next = ptr.next; + ptr = next; + } + while (ptr != head); + return head; +} + +/*Function to print nodes*/ + +static void printList(Node head) +{ + Node temp = head; + if (head != null) + { + do + { + System.out.printf(""%d "", temp.data); + temp = temp.next; + } + while (temp != head); + } +} + +/*Driver code*/ + +public static void main(String args[]) +{ +/* Initialize lists as empty*/ + + Node head = null; + +/* Created linked list will be 57.11.2.56.12.61*/ + + head=push(head, 61); + head=push(head, 12); + head=push(head, 56); + head=push(head, 2); + head=push(head, 11); + head=push(head, 57); + + System.out.println( ""\nList after deletion : ""); + head=deleteEvenNodes(head); + printList(head); +} +} + + +"," '''Python3 program to delete all even +node from a Circular singly linked list''' + +import math + + '''Structure for a node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to insert a node at the beginning +of a Circular linked list''' + +def push(head_ref, data): + ptr1 = Node(data) + temp = head_ref + ptr1.data = data + ptr1.next = head_ref + + ''' If linked list is not None then + set the next of last node''' + + if (head_ref != None): + while (temp.next != head_ref): + temp = temp.next + temp.next = ptr1 + + else: + '''For the first node''' + + ptr1.next = ptr1 + + head_ref = ptr1 + return head_ref + + '''Delete the node if it is even''' + +def deleteNode(head_ref, delete): + temp = head_ref + + ''' If node to be deleted is head node''' + + if (head_ref == delete): + head_ref = delete.next + + ''' traverse list till not found + delete node''' + + while (temp.next != delete): + temp = temp.next + + ''' copy address of node''' + + temp.next = delete.next + + ''' Finally, free the memory occupied by delete''' + + + '''Function to delete all even nodes +from the singly circular linked list''' + +def deleteEvenNodes(head): + ptr = head + next = None + + ''' if node is even''' + + next = ptr.next + ptr = next + while (ptr != head): + if (ptr.data % 2 == 0): + deleteNode(head, ptr) + + ''' po to next node''' + + next = ptr.next + ptr = next + return head + + '''Function to pr nodes''' + +def prList(head): + temp = head + if (head != None): + print(temp.data, end = "" "") + temp = temp.next + while (temp != head): + print(temp.data, end = "" "") + temp = temp.next + + '''Driver code''' + +if __name__=='__main__': + + ''' Initialize lists as empty''' + + head = None + + ''' Created linked list will be 57.11.2.56.12.61''' + + head = push(head, 61) + head = push(head, 12) + head = push(head, 56) + head = push(head, 2) + head = push(head, 11) + head = push(head, 57) + + print(""List after deletion : "", end = """") + head = deleteEvenNodes(head) + prList(head) + + +" +Find length of the longest consecutive path from a given starting character,"/*Java program to find the longest consecutive path*/ + +class path +{ +/* tool matrices to recur for adjacent cells.*/ + + static int x[] = {0, 1, 1, -1, 1, 0, -1, -1}; + static int y[] = {1, 0, 1, 1, -1, -1, 0, -1}; + static int R = 3; + static int C = 3; +/* dp[i][j] Stores length of longest consecutive path + starting at arr[i][j].*/ + + static int dp[][] = new int[R][C]; +/* check whether mat[i][j] is a valid cell or not.*/ + + static boolean isvalid(int i, int j) + { + if (i < 0 || j < 0 || i >= R || j >= C) + return false; + return true; + } +/* Check whether current character is adjacent to previous + character (character processed in parent call) or not.*/ + + static boolean isadjacent(char prev, char curr) + { + return ((curr - prev) == 1); + } +/* i, j are the indices of the current cell and prev is the + character processed in the parent call.. also mat[i][j] + is our current character.*/ + + static int getLenUtil(char mat[][], int i, int j, char prev) + { +/* If this cell is not valid or current character is not + adjacent to previous one (e.g. d is not adjacent to b ) + or if this cell is already included in the path than return 0.*/ + + if (!isvalid(i, j) || !isadjacent(prev, mat[i][j])) + return 0; +/* If this subproblem is already solved , return the answer*/ + + if (dp[i][j] != -1) + return dp[i][j]; +/*Initialize answer*/ + +int ans = 0; +/* recur for paths with different adjacent cells and store + the length of longest path.*/ + + for (int k=0; k<8; k++) + ans = Math.max(ans, 1 + getLenUtil(mat, i + x[k], + j + y[k], mat[i][j])); +/* save the answer and return*/ + + return dp[i][j] = ans; + } +/* Returns length of the longest path with all characters consecutive + to each other. This function first initializes dp array that + is used to store results of subproblems, then it calls + recursive DFS based function getLenUtil() to find max length path*/ + + static int getLen(char mat[][], char s) + { + for(int i = 0;i= R or j >= C): + return False + return True + '''Check whether current character is adjacent to previous +character (character processed in parent call) or not.''' + +def isadjacent( prev, curr): + if (ord(curr) -ord(prev)) == 1: + return True + return False + '''i, j are the indices of the current cell and prev is the +character processed in the parent call.. also mat[i][j] +is our current character.''' + +def getLenUtil(mat,i,j, prev): + ''' If this cell is not valid or current character is not + adjacent to previous one (e.g. d is not adjacent to b ) + or if this cell is already included in the path than return 0.''' + + if (isvalid(i, j)==False or isadjacent(prev, mat[i][j])==False): + return 0 + ''' If this subproblem is already solved , return the answer''' + + if (dp[i][j] != -1): + return dp[i][j] + '''Initialize answer''' + + ans = 0 + ''' recur for paths with different adjacent cells and store + the length of longest path.''' + + for k in range(8): + ans = max(ans, 1 + getLenUtil(mat, i + x[k],j + y[k], mat[i][j])) + ''' save the answer and return''' + + dp[i][j] = ans + return dp[i][j] + '''Returns length of the longest path with all characters consecutive +to each other. This function first initializes dp array that +is used to store results of subproblems, then it calls +recursive DFS based function getLenUtil() to find max length path''' + +def getLen(mat, s): + for i in range(R): + for j in range(C): + dp[i][j]=-1 + ans = 0 + for i in range(R): + for j in range(C): + ''' check for each possible starting point''' + + if (mat[i][j] == s): + ''' recur for all eight adjacent cells''' + + for k in range(8): + ans = max(ans, 1 + getLenUtil(mat,i + x[k], j + y[k], s)); + return ans + '''Driver program''' + +mat = [['a','c','d'], + [ 'h','b','a'], + [ 'i','g','f']] +print (getLen(mat, 'a')) +print (getLen(mat, 'e')) +print (getLen(mat, 'b')) +print (getLen(mat, 'f'))" +Swap bits in a given number,"/*Java Program to swap bits +in a given number*/ + +class GFG { + static int swapBits(int x, int p1, int p2, int n) + { +/* Move all bits of first set + to rightmost side*/ + + int set1 = (x >> p1) & ((1 << n) - 1); +/* Move all bits of second set + to rightmost side*/ + + int set2 = (x >> p2) & ((1 << n) - 1); +/* XOR the two sets*/ + + int xor = (set1 ^ set2); +/* Put the xor bits back to + their original positions*/ + + xor = (xor << p1) | (xor << p2); +/* XOR the 'xor' with the original number + so that the two sets are swapped*/ + + int result = x ^ xor; + return result; + } +/* Driver program*/ + + public static void main(String[] args) + { + int res = swapBits(28, 0, 3, 2); + System.out.println(""Result = "" + res); + } +}"," '''Python program to +swap bits in a given number''' + +def swapBits(x, p1, p2, n): + ''' Move all bits of first + set to rightmost side''' + + set1 = (x >> p1) & ((1<< n) - 1) + ''' Moce all bits of second + set to rightmost side''' + + set2 = (x >> p2) & ((1 << n) - 1) + ''' XOR the two sets''' + + xor = (set1 ^ set2) + ''' Put the xor bits back + to their original positions''' + + xor = (xor << p1) | (xor << p2) + ''' XOR the 'xor' with the + original number so that the + two sets are swapped''' + + result = x ^ xor + return result + '''Driver code''' + +res = swapBits(28, 0, 3, 2) +print(""Result ="", res)" +Binary Tree | Set 1 (Introduction),"/*Class containing left and right child of current + node and key value*/ + +class Node +{ + int key; + Node left, right; + public Node(int item) + { + key = item; + left = right = null; + } +}"," '''A Python class that represents an individual node +in a Binary Tree''' + +class Node: + def __init__(self,key): + self.left = None + self.right = None + self.val = key" +How to determine if a binary tree is height-balanced?,"/* Java program to determine if binary tree is + height balanced or not */ + +/* A binary tree node has data, pointer to left child, + and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int d) + { + data = d; + left = right = null; + } +} +class BinaryTree { + Node root; + /* Returns true if binary tree with root as root is height-balanced */ + + boolean isBalanced(Node node) + {/* for height of left subtree */ + + int lh; /* for height of right subtree */ + + int rh; /* If tree is empty then return true */ + + if (node == null) + return true; + /* Get the height of left and right sub trees */ + + lh = height(node.left); + rh = height(node.right); + if (Math.abs(lh - rh) <= 1 + && isBalanced(node.left) + && isBalanced(node.right)) + return true; + /* If we reach here then tree is not height-balanced */ + + return false; + } + /* The function Compute the ""height"" of a tree. Height is the + number of nodes along the longest path from the root node + down to the farthest leaf node.*/ + + int height(Node node) + { + /* base case tree is empty */ + + if (node == null) + return 0; + /* If tree is not empty then height = 1 + max of left + height and right heights */ + + return 1 + Math.max(height(node.left), height(node.right)); + } +/*Driver code*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.left.left.left = new Node(8); + if (tree.isBalanced(tree.root)) + System.out.println(""Tree is balanced""); + else + System.out.println(""Tree is not balanced""); + } +}"," ''' +Python3 program to check if a tree is height-balanced + ''' + + '''A binary tree Node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''function to check if tree is height-balanced or not''' + +def isBalanced(root): + ''' Base condition''' + + if root is None: + return True + ''' for left and right subtree height allowed values for (lh - rh) are 1, -1, 0''' + + lh = height(root.left) + rh = height(root.right) + if (abs(lh - rh) <= 1) and isBalanced( + root.left) is True and isBalanced( root.right) is True: + return True ''' if we reach here means tree is not + height-balanced tree''' + + return False + '''function to find height of binary tree''' + +def height(root): + ''' base condition when binary tree is empty''' + + if root is None: + return 0 + ''' If tree is not empty then height = 1 + max of left + height and right heights ''' + + return max(height(root.left), height(root.right)) + 1 '''Driver function to test the above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.left.left.left = Node(8) +if isBalanced(root): + print(""Tree is balanced"") +else: + print(""Tree is not balanced"")" +Calculate the angle between hour hand and minute hand,"/*Java program to find angle between hour and minute hands*/ + +import java.io.*; +class GFG +{ +/* Function to calculate the angle*/ + + static int calcAngle(double h, double m) + { +/* validate the input*/ + + if (h <0 || m < 0 || h >12 || m > 60) + System.out.println(""Wrong input""); + if (h == 12) + h = 0; + if (m == 60) + { + m = 0; + h += 1; + if(h>12) + h = h-12; + } +/* Calculate the angles moved by hour and minute hands + with reference to 12:00*/ + + int hour_angle = (int)(0.5 * (h*60 + m)); + int minute_angle = (int)(6*m); +/* Find the difference between two angles*/ + + int angle = Math.abs(hour_angle - minute_angle); +/* smaller angle of two possible angles*/ + + angle = Math.min(360-angle, angle); + return angle; + } +/* Driver Code*/ + + public static void main (String[] args) + { + System.out.println(calcAngle(9, 60)+"" degree""); + System.out.println(calcAngle(3, 30)+"" degree""); + } +} +"," '''Python program to find angle +between hour and minute hands''' + '''Function to Calculate angle b/w +hour hand and minute hand''' + +def calcAngle(h,m): + ''' validate the input''' + + if (h < 0 or m < 0 or h > 12 or m > 60): + print('Wrong input') + if (h == 12): + h = 0 + if (m == 60): + m = 0 + h += 1; + if(h>12): + h = h-12; + ''' Calculate the angles moved by + hour and minute hands with + reference to 12:00''' + + hour_angle = 0.5 * (h * 60 + m) + minute_angle = 6 * m + ''' Find the difference between two angles''' + + angle = abs(hour_angle - minute_angle) + ''' Return the smaller angle of two + possible angles''' + + angle = min(360 - angle, angle) + return angle + '''Driver Code''' + +h = 9 +m = 60 +print('Angle ', calcAngle(h,m))" +Longest Bitonic Subsequence | DP-15,"/* Dynamic Programming implementation in Java for longest bitonic + subsequence problem */ + +import java.util.*; +import java.lang.*; +import java.io.*; +class LBS +{ + /* lbs() returns the length of the Longest Bitonic Subsequence in + arr[] of size n. The function mainly creates two temporary arrays + lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1. + lis[i] ==> Longest Increasing subsequence ending with arr[i] + lds[i] ==> Longest decreasing subsequence starting with arr[i] + */ + + static int lbs( int arr[], int n ) + { + int i, j; + /* Allocate memory for LIS[] and initialize LIS values as 1 for + all indexes */ + + int[] lis = new int[n]; + for (i = 0; i < n; i++) + lis[i] = 1; + /* Compute LIS values from left to right */ + + for (i = 1; i < n; i++) + for (j = 0; j < i; j++) + if (arr[i] > arr[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + /* Allocate memory for lds and initialize LDS values for + all indexes */ + + int[] lds = new int [n]; + for (i = 0; i < n; i++) + lds[i] = 1; + /* Compute LDS values from right to left */ + + for (i = n-2; i >= 0; i--) + for (j = n-1; j > i; j--) + if (arr[i] > arr[j] && lds[i] < lds[j] + 1) + lds[i] = lds[j] + 1; + /* Return the maximum value of lis[i] + lds[i] - 1*/ + + int max = lis[0] + lds[0] - 1; + for (i = 1; i < n; i++) + if (lis[i] + lds[i] - 1 > max) + max = lis[i] + lds[i] - 1; + return max; + } +/* Driver code*/ + + public static void main (String[] args) + { + int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, + 13, 3, 11, 7, 15}; + int n = arr.length; + System.out.println(""Length of LBS is ""+ lbs( arr, n )); + } +}"," '''Dynamic Programming implementation of longest bitonic subsequence problem''' + + ''' +lbs() returns the length of the Longest Bitonic Subsequence in +arr[] of size n. The function mainly creates two temporary arrays +lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1. +lis[i] ==> Longest Increasing subsequence ending with arr[i] +lds[i] ==> Longest decreasing subsequence starting with arr[i] + ''' + +def lbs(arr): + n = len(arr) + ''' allocate memory for LIS[] and initialize LIS values as 1 + for all indexes''' + + lis = [1 for i in range(n+1)] + ''' Compute LIS values from left to right''' + + for i in range(1 , n): + for j in range(0 , i): + if ((arr[i] > arr[j]) and (lis[i] < lis[j] +1)): + lis[i] = lis[j] + 1 + ''' allocate memory for LDS and initialize LDS values for + all indexes''' + + lds = [1 for i in range(n+1)] + ''' Compute LDS values from right to left''' + + for i in reversed(range(n-1)): + for j in reversed(range(i-1 ,n)): + if(arr[i] > arr[j] and lds[i] < lds[j] + 1): + lds[i] = lds[j] + 1 ''' Return the maximum value of (lis[i] + lds[i] - 1)''' + + maximum = lis[0] + lds[0] - 1 + for i in range(1 , n): + maximum = max((lis[i] + lds[i]-1), maximum) + return maximum + '''Driver program to test the above function''' + +arr = [0 , 8 , 4, 12, 2, 10 , 6 , 14 , 1 , 9 , 5 , 13, + 3, 11 , 7 , 15] +print ""Length of LBS is"",lbs(arr)" +Maximum Subarray Sum Excluding Certain Elements,"/*Java Program implementation of the +above idea*/ + +import java.util.*; +class GFG +{ +/* Function to calculate the max sum of contigous + subarray of B whose elements are not present in A*/ + + static int findMaxSubarraySum(int A[], int B[]) + { + HashMap m = new HashMap<>(); +/* mark all the elements present in B*/ + + for(int i = 0; i < B.length; i++) + { + m.put(B[i], 1); + } +/* initialize max_so_far with INT_MIN*/ + + int max_so_far = Integer.MIN_VALUE; + int currmax = 0; +/* traverse the array A*/ + + for(int i = 0; i < A.length; i++) + { + if(currmax < 0 || (m.containsKey(A[i]) && m.get(A[i]) == 1)) + { + currmax = 0; + continue; + } + currmax = Math.max(A[i], A[i] + currmax); +/* if current max is greater than + max so far then update max so far*/ + + if(max_so_far < currmax) + { + max_so_far = currmax; + } + } + return max_so_far; + } +/* Driver code*/ + + public static void main(String[] args) + { + int a[] = { 3, 4, 5, -4, 6 }; + int b[] = { 1, 8, 5 }; +/* Function call*/ + + System.out.println(findMaxSubarraySum(a, b)); + } +}"," '''Python3 program implementation of the +above idea''' + +import sys + '''Function to calculate the max sum of +contigous subarray of B whose elements +are not present in A''' + +def findMaxSubarraySum(A, B): + m = dict() + ''' Mark all the elements present in B''' + + for i in range(len(B)): + if B[i] not in m: + m[B[i]] = 0 + m[B[i]] = 1 + ''' Initialize max_so_far with INT_MIN''' + + max_so_far = -sys.maxsize - 1 + currmax = 0 + ''' Traverse the array A''' + + for i in range(len(A)): + if (currmax < 0 or (A[i] in m and m[A[i]] == 1)): + currmax = 0 + continue + currmax = max(A[i], A[i] + currmax) + ''' If current max is greater than + max so far then update max so far''' + + if (max_so_far map = new HashMap<>(); +/* put first element as ""key"" and its length as ""value""*/ + + map.put(arr[0], 1); +/* iterate for all element*/ + + for (int i = 1; i < n; i++) { +/* check if last consequent of arr[i] exist or not*/ + + if (map.containsKey(arr[i] - 1)) { +/* put the updated consequent number + and increment its value(length)*/ + + map.put(arr[i], map.get(arr[i] - 1) + 1); + map.remove(arr[i] - 1); + } + else { + map.put(arr[i], 1); + } + } + return Collections.max(map.values()); + } +/* driver code*/ + + public static void main(String args[]) + { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int arr[] = new int[n]; + for (int i = 0; i < n; i++) + arr[i] = sc.nextInt(); + System.out.println(LongIncrConseqSubseq(arr, n)); + } +}"," '''python program to find length of the +longest increasing subsequence +whose adjacent element differ by 1''' + +from collections import defaultdict +import sys + '''function that returns the length of the +longest increasing subsequence +whose adjacent element differ by 1''' + +def longestSubsequence(a, n): + '''create hashmap to save latest consequent + number as ""key"" and its length as ""value"" ''' + + mp = defaultdict(lambda:0) + ''' stores the length of the longest + subsequence that ends with a[i]''' + + dp = [0 for i in range(n)] + maximum = -sys.maxsize + ''' iterate for all element''' + + for i in range(n): + ''' if a[i]-1 is present before i-th index''' + + if a[i] - 1 in mp: + ''' last index of a[i]-1''' + + lastIndex = mp[a[i] - 1] - 1 + dp[i] = 1 + dp[lastIndex] + else: + dp[i] = 1 + mp[a[i]] = i + 1 + maximum = max(maximum, dp[i]) + return maximum + '''Driver Code''' + +a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12] +n = len(a) +print(longestSubsequence(a, n))" +Print all palindromic paths from top left to bottom right in a matrix,"/*Java program to print all palindromic paths +from top left to bottom right in a grid.*/ + +public class PalinPath { + public static boolean isPalin(String str) + { + int len = str.length() / 2; + for (int i = 0; i < len; i++) { + if (str.charAt(i) != str.charAt(str.length() - i - 1)) + return false; + } + return true; + } +/* i and j are row and column indexes of current cell + (initially these are 0 and 0).*/ + + public static void palindromicPath(String str, char a[][], + int i, int j, int m, int n) + { +/* If we have not reached bottom right corner, keep + exlporing*/ + + if (j < m - 1 || i < n - 1) { + if (i < n - 1) + palindromicPath(str + a[i][j], a, i + 1, j, m, n); + if (j < m - 1) + palindromicPath(str + a[i][j], a, i, j + 1, m, n); + } +/* If we reach bottom right corner, we check if + if the path used is palindrome or not.*/ + + else { + str = str + a[n - 1][m - 1]; + if (isPalin(str)) + System.out.println(str); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + char arr[][] = { { 'a', 'a', 'a', 'b' }, + { 'b', 'a', 'a', 'a' }, + { 'a', 'b', 'b', 'a' } }; + String str = """"; + palindromicPath(str, arr, 0, 0, 4, 3); + } +}"," '''Python 3 program to print all +palindromic paths from top left +to bottom right in a grid.''' + +def isPalin(str): + l = len(str) // 2 + for i in range( l) : + if (str[i] != str[len(str) - i - 1]): + return False + return True + '''i and j are row and column +indexes of current cell +(initially these are 0 and 0).''' + +def palindromicPath(str, a, i, j, m, n): + ''' If we have not reached bottom + right corner, keep exlporing''' + + if (j < m - 1 or i < n - 1) : + if (i < n - 1): + palindromicPath(str + a[i][j], a, + i + 1, j, m, n) + if (j < m - 1): + palindromicPath(str + a[i][j], a, + i, j + 1, m, n) + ''' If we reach bottom right corner, + we check if the path used is + palindrome or not.''' + + else : + str = str + a[n - 1][m - 1] + if isPalin(str): + print(str) + '''Driver code''' + +if __name__ == ""__main__"": + arr = [[ 'a', 'a', 'a', 'b' ], + ['b', 'a', 'a', 'a' ], + [ 'a', 'b', 'b', 'a' ]] + str = """" + palindromicPath(str, arr, 0, 0, 4, 3)" +Stepping Numbers,"/*A Java program to find all the Stepping Number in [n, m]*/ + +class Main +{ +/* This Method checks if an integer n + is a Stepping Number*/ + + public static boolean isStepNum(int n) + { +/* Initalize prevDigit with -1*/ + + int prevDigit = -1; +/* Iterate through all digits of n and compare + difference between value of previous and + current digits*/ + + while (n > 0) + { +/* Get Current digit*/ + + int curDigit = n % 10; +/* Single digit is consider as a + Stepping Number*/ + + if (prevDigit != -1) + { +/* Check if absolute difference between + prev digit and current digit is 1*/ + + if (Math.abs(curDigit-prevDigit) != 1) + return false; + } + n /= 10; + prevDigit = curDigit; + } + return true; + } +/* A brute force approach based function to find all + stepping numbers.*/ + + public static void displaySteppingNumbers(int n,int m) + { +/* Iterate through all the numbers from [N,M] + and check if it is a stepping number.*/ + + for (int i = n; i <= m; i++) + if (isStepNum(i)) + System.out.print(i+ "" ""); + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 0, m = 21; +/* Display Stepping Numbers in the range [n,m]*/ + + displaySteppingNumbers(n,m); + } +}"," '''A Python3 program to find all the Stepping Number in [n, m]''' + + '''This function checks if an integer n is a Stepping Number''' + +def isStepNum(n): ''' Initalize prevDigit with -1''' + + prevDigit = -1 + ''' Iterate through all digits of n and compare difference + between value of previous and current digits''' + + while (n): + ''' Get Current digit''' + + curDigit = n % 10 + ''' Single digit is consider as a + Stepping Number''' + + if (prevDigit == -1): + prevDigit = curDigit + else: + ''' Check if absolute difference between + prev digit and current digit is 1''' + + if (abs(prevDigit - curDigit) != 1): + return False + prevDigit = curDigit + n //= 10 + return True + '''A brute force approach based function to find all +stepping numbers.''' + +def displaySteppingNumbers(n, m): + ''' Iterate through all the numbers from [N,M] + and check if it’s a stepping number.''' + + for i in range(n, m + 1): + if (isStepNum(i)): + print(i, end = "" "") + '''Driver code''' + +if __name__ == '__main__': + n, m = 0, 21 + ''' Display Stepping Numbers in + the range [n, m]''' + + displaySteppingNumbers(n, m)" +Find three element from different three arrays such that a + b + c = sum,"/*Java program to find three element +from different three arrays such +that a + b + c is equal to +given sum*/ + +import java.util.*; +class GFG +{ +/* Function to check if there is + an element from each array such + that sum of the three elements is + equal to given sum.*/ + + static boolean findTriplet(int a1[], int a2[], int a3[], + int n1, int n2, int n3, + int sum) + { +/* Store elements of + first array in hash*/ + + HashSet s = new HashSet(); + for (int i = 0; i < n1; i++) + { + s.add(a1[i]); + } +/* sum last two arrays + element one by one*/ + + ArrayList al = new ArrayList<>(s); + for (int i = 0; i < n2; i++) + { + for (int j = 0; j < n3; j++) + { +/* Consider current pair and + find if there is an element + in a1[] such that these three + form a required triplet*/ + + if (al.contains(sum - a2[i] - a3[j]) & + al.indexOf(sum - a2[i] - a3[j]) + != al.get(al.size() - 1)) + { + return true; + } + } + } + return false; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int a1[] = {1, 2, 3, 4, 5}; + int a2[] = {2, 3, 6, 1, 2}; + int a3[] = {3, 2, 4, 5, 6}; + int sum = 9; + int n1 = a1.length; + int n2 = a2.length; + int n3 = a3.length; + if (findTriplet(a1, a2, a3, n1, n2, n3, sum)) + { + System.out.println(""Yes""); + } + else + { + System.out.println(""No""); + } + } +}"," '''Python3 program to find three element +from different three arrays such +that a + b + c is equal to +given sum + ''' '''Function to check if there is +an element from each array such +that sum of the three elements is +equal to given sum.''' + +def findTriplet(a1, a2, a3, + n1, n2, n3, sum): + ''' Store elements of first + array in hash''' + + s = set() + ''' sum last two arrays element + one by one''' + + for i in range(n1): + s.add(a1[i]) + for i in range(n2): + for j in range(n3): + ''' Consider current pair and + find if there is an element + in a1[] such that these three + form a required triplet''' + + if sum - a2[i] - a3[j] in s: + return True + return False + '''Driver code''' + +a1 = [1, 2, 3, 4, 5] +a2 = [2, 3, 6, 1, 2] +a3 = [3, 24, 5, 6] +n1 = len(a1) +n2 = len(a2) +n3 = len(a3) +sum = 9 +if findTriplet(a1, a2, a3, + n1, n2, n3, sum) == True: + print(""Yes"") +else: + print(""No"")" +Symmetric Tree (Mirror Image of itself),"/*Java program to check is +binary tree is symmetric or not*/ + + +/*A Binary Tree Node*/ + +class Node { + int key; + Node left, right; + Node(int item) + { + key = item; + left = right = null; + } +} +class BinaryTree { + Node root;/* returns true if trees + with roots as root1 and root2are mirror*/ + + boolean isMirror(Node node1, Node node2) + { +/* if both trees are empty, + then they are mirror image*/ + + if (node1 == null && node2 == null) + return true; +/* For two trees to be mirror images, the following + three conditions must be true 1 - Their root + node's key must be same 2 - left subtree of left + tree and right subtree + of right tree have to be mirror images + 3 - right subtree of left tree and left subtree + of right tree have to be mirror images*/ + + if (node1 != null && node2 != null + && node1.key == node2.key) + return (isMirror(node1.left, node2.right) + && isMirror(node1.right, node2.left)); +/* if none of the above conditions is true then + root1 and root2 are not mirror images*/ + + return false; + } +/* returns true if the tree is symmetric i.e + mirror image of itself*/ + + boolean isSymmetric() + { +/* check if tree is mirror of itself*/ + + return isMirror(root, root); + } +/* Driver code*/ + + public static void main(String args[]) + { +/* Let us construct the Tree shown in the above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); + tree.root.left.right = new Node(4); + tree.root.right.left = new Node(4); + tree.root.right.right = new Node(3); + boolean output = tree.isSymmetric(); + if (output == true) + System.out.println(""Symmetric""); + else + System.out.println(""Not symmetric""); + } +}"," '''Python program to check if a +given Binary Tree is symmetric or not''' + + '''Node structure''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Returns True if trees +with roots as root1 and root 2 are mirror''' + +def isMirror(root1, root2): + ''' If both trees are empty, then they are mirror images''' + + if root1 is None and root2 is None: + return True + ''' For two trees to be mirror images, + the following three conditions must be true + 1 - Their root node's key must be same + 2 - left subtree of left tree and right subtree + of the right tree have to be mirror images + 3 - right subtree of left tree and left subtree + of right tree have to be mirror images + ''' + + if (root1 is not None and root2 is not None): + if root1.key == root2.key: + return (isMirror(root1.left, root2.right)and + isMirror(root1.right, root2.left)) + ''' If none of the above conditions is true then root1 + and root2 are not mirror images''' + + return False + + ''' returns true if the tree is symmetric i.e + mirror image of itself''' + +def isSymmetric(root): ''' Check if tree is mirror of itself''' + + return isMirror(root, root) + '''Driver Code''' + '''Let's construct the tree show in the above figure''' + +root = Node(1) +root.left = Node(2) +root.right = Node(2) +root.left.left = Node(3) +root.left.right = Node(4) +root.right.left = Node(4) +root.right.right = Node(3) +print ""Symmetric"" if isSymmetric(root) == True else ""Not symmetric""" +Reverse alternate levels of a perfect binary tree,"/*Java program to reverse +alternate levels of a tree*/ + +class Sol +{ + static class Node + { + char key; + Node left, right; + }; + static void preorder(Node root1, + Node root2, int lvl) + { +/* Base cases*/ + + if (root1 == null || root2 == null) + return; +/* Swap subtrees if level is even*/ + + if (lvl % 2 == 0) { + char t = root1.key; + root1.key = root2.key; + root2.key = t; + } +/* Recur for left and right subtrees + (Note : left of root1 + is passed and right of root2 in first + call and opposite + in second call.*/ + + preorder(root1.left, root2.right, + lvl + 1); + preorder(root1.right, root2.left, + lvl + 1); + } +/* This function calls preorder() + for left and right + children of root*/ + + static void reverseAlternate(Node root) + { + preorder(root.left, root.right, 0); + } +/* Inorder traversal (used to + print initial and + modified trees)*/ + + static void printInorder(Node root) + { + if (root == null) + return; + printInorder(root.left); + System.out.print(root.key + "" ""); + printInorder(root.right); + } +/* A utility function to create a new node*/ + + static Node newNode(int key) + { + Node temp = new Node(); + temp.left = temp.right = null; + temp.key = (char)key; + return temp; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + Node root = newNode('a'); + root.left = newNode('b'); + root.right = newNode('c'); + root.left.left = newNode('d'); + root.left.right = newNode('e'); + root.right.left = newNode('f'); + root.right.right = newNode('g'); + root.left.left.left = newNode('h'); + root.left.left.right = newNode('i'); + root.left.right.left = newNode('j'); + root.left.right.right = newNode('k'); + root.right.left.left = newNode('l'); + root.right.left.right = newNode('m'); + root.right.right.left = newNode('n'); + root.right.right.right = newNode('o'); + System.out.print( + ""Inorder Traversal of given tree\n""); + printInorder(root); + reverseAlternate(root); + System.out.print( + ""\n\nInorder Traversal of modified tree\n""); + printInorder(root); + } +}"," '''Python3 program to reverse +alternate levels of a tree +A Binary Tree Node +Utility function to create +a new tree node ''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None +def preorder(root1, root2, lvl): ''' Base cases''' + + if (root1 == None or root2 == None): + return + ''' Swap subtrees if level is even''' + + if (lvl % 2 == 0): + t = root1.key + root1.key = root2.key + root2.key = t + ''' Recur for left and right subtrees + (Note : left of root1 is passed and + right of root2 in first call and + opposite in second call.''' + + preorder(root1.left, root2.right, lvl + 1) + preorder(root1.right, root2.left, lvl + 1) + '''This function calls preorder() +for left and right children of root''' + +def reverseAlternate(root): + preorder(root.left, root.right, 0) + '''Inorder traversal (used to print +initial and modified trees)''' + +def printInorder(root): + if (root == None): + return + printInorder(root.left) + print( root.key, end = "" "") + printInorder(root.right) + '''A utility function to create a new node''' + +def newNode(key): + temp = Node(' ') + temp.left = temp.right = None + temp.key = key + return temp + '''Driver Code''' + +if __name__ == '__main__': + root = newNode('a') + root.left = newNode('b') + root.right = newNode('c') + root.left.left = newNode('d') + root.left.right = newNode('e') + root.right.left = newNode('f') + root.right.right = newNode('g') + root.left.left.left = newNode('h') + root.left.left.right = newNode('i') + root.left.right.left = newNode('j') + root.left.right.right = newNode('k') + root.right.left.left = newNode('l') + root.right.left.right = newNode('m') + root.right.right.left = newNode('n') + root.right.right.right = newNode('o') + print( ""Inorder Traversal of given tree"") + printInorder(root) + reverseAlternate(root) + print(""\nInorder Traversal of modified tree"") + printInorder(root)" +Rearrange an array such that 'arr[j]' becomes 'i' if 'arr[i]' is 'j' | Set 1,"/*A simple Java program to rearrange contents of arr[] +such that arr[j] becomes j if arr[i] is j*/ + +class RearrangeArray { +/* A simple method to rearrange 'arr[0..n-1]' so that 'arr[j]' + becomes 'i' if 'arr[i]' is 'j'*/ + + void rearrangeNaive(int arr[], int n) + { +/* Create an auxiliary array of same size*/ + + int temp[] = new int[n]; + int i; +/* Store result in temp[]*/ + + for (i = 0; i < n; i++) + temp[arr[i]] = i; +/* Copy temp back to arr[]*/ + + for (i = 0; i < n; i++) + arr[i] = temp[i]; + } +/* A utility function to print contents of arr[0..n-1]*/ + + void printArray(int arr[], int n) + { + int i; + for (i = 0; i < n; i++) { + System.out.print(arr[i] + "" ""); + } + System.out.println(""""); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + RearrangeArray arrange = new RearrangeArray(); + int arr[] = { 1, 3, 0, 2 }; + int n = arr.length; + System.out.println(""Given array is ""); + arrange.printArray(arr, n); + arrange.rearrangeNaive(arr, n); + System.out.println(""Modified array is ""); + arrange.printArray(arr, n); + } +}"," '''A simple Python3 program to rearrange +contents of arr[] such that arr[j] +becomes j if arr[i] is j''' '''A simple method to rearrange + '''arr[0..n-1]' so that 'arr[j]' +becomes 'i' if 'arr[i]' is 'j''' + ''' +def rearrangeNaive(arr, n): + ''' Create an auxiliary array + of same size''' + + temp = [0] * n + ''' Store result in temp[]''' + + for i in range(0, n): + temp[arr[i]] = i + ''' Copy temp back to arr[]''' + + for i in range(0, n): + arr[i] = temp[i] + ''' A utility function to print + contents of arr[0..n-1]''' + +def printArray(arr, n): + for i in range(0, n): + print(arr[i], end = "" "") + '''Driver program''' + +arr = [1, 3, 0, 2] +n = len(arr) +print(""Given array is"", end = "" "") +printArray(arr, n) +rearrangeNaive(arr, n) +print(""\nModified array is"", end = "" "") +printArray(arr, n)" +Maximum area rectangle by picking four sides from array,"/*Java program for finding maximum area +possible of a rectangle*/ + +import java.util.Arrays; +import java.util.Collections; +public class GFG +{ +/* function for finding max area*/ + + static int findArea(Integer arr[], int n) + { +/* sort array in non-increasing order*/ + + Arrays.sort(arr, Collections.reverseOrder()); +/* Initialize two sides of rectangle*/ + + int[] dimension = { 0, 0 }; +/* traverse through array*/ + + for (int i = 0, j = 0; i < n - 1 && j < 2; + i++) +/* if any element occurs twice + store that as dimension*/ + + if (arr[i] == arr[i + 1]) + dimension[j++] = arr[i++]; +/* return the product of dimensions*/ + + return (dimension[0] * dimension[1]); + } +/* driver function*/ + + public static void main(String args[]) + { + Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; + int n = arr.length; + System.out.println(findArea(arr, n)); + } +}"," '''Python3 program for finding +maximum area possible of +a rectangle + ''' '''function for finding +max area''' + +def findArea(arr, n): + ''' sort array in + non-increasing order''' + + arr.sort(reverse = True) + ''' Initialize two + sides of rectangle''' + + dimension = [0, 0] + ''' traverse through array''' + + i = 0 + j = 0 + while(i < n - 1 and j < 2): + ''' if any element occurs twice + store that as dimension''' + + if (arr[i] == arr[i + 1]): + dimension[j] = arr[i] + j += 1 + i += 1 + i += 1 + ''' return the product + of dimensions''' + + return (dimension[0] * + dimension[1]) + '''Driver code''' + +arr = [4, 2, 1, 4, 6, 6, 2, 5] +n = len(arr) +print(findArea(arr, n))" +Form minimum number from given sequence,"/*Java program to print minimum number that can be formed +from a given sequence of Is and Ds*/ +import java.util.Stack; +class GFG { +/*Function to decode the given sequence to construct +minimum number without repeated digits*/ + + static void PrintMinNumberForPattern(String seq) { +/* result store output string*/ + + String result = """"; +/* create an empty stack of integers*/ + + Stack stk = new Stack(); +/* run n+1 times where n is length of input sequence*/ + + for (int i = 0; i <= seq.length(); i++) { +/* push number i+1 into the stack*/ + + stk.push(i + 1); +/* if all characters of the input sequence are + processed or current character is 'I' + (increasing)*/ + + if (i == seq.length() || seq.charAt(i) == 'I') { +/* run till stack is empty*/ + + while (!stk.empty()) { +/* remove top element from the stack and + add it to solution*/ + + result += String.valueOf(stk.peek()); + result += "" ""; + stk.pop(); + } + } + } + System.out.println(result); + } +/*main function*/ + + public static void main(String[] args) { + PrintMinNumberForPattern(""IDID""); + PrintMinNumberForPattern(""I""); + PrintMinNumberForPattern(""DD""); + PrintMinNumberForPattern(""II""); + PrintMinNumberForPattern(""DIDI""); + PrintMinNumberForPattern(""IIDDD""); + PrintMinNumberForPattern(""DDIDDIID""); + } +}"," '''Python3 program to print minimum +number that can be formed from a +given sequence of Is and Ds''' + + + '''Function to decode the given sequence to construct +minimum number without repeated digits''' + +def PrintMinNumberForPattern(Strr): ''' String for storing result''' + + res = '' + ''' Take a List to work as Stack''' + + stack = [] + ''' run n+1 times where n is length + of input sequence, As length of + result string is always 1 greater''' + + for i in range(len(Strr) + 1): + ''' Push number i+1 into the stack''' + + stack.append(i + 1) + ''' If all characters of the input + sequence are processed or current + character is 'I''' + + if (i == len(Strr) or Strr[i] == 'I'): + ''' Run While Loop Untill stack is empty''' + + while len(stack) > 0: + ''' pop the element on top of stack + And store it in result String''' + + res += str(stack.pop()) + res += ' ' + print(res) '''Driver Code''' + +PrintMinNumberForPattern(""IDID"") +PrintMinNumberForPattern(""I"") +PrintMinNumberForPattern(""DD"") +PrintMinNumberForPattern(""II"") +PrintMinNumberForPattern(""DIDI"") +PrintMinNumberForPattern(""IIDDD"") +PrintMinNumberForPattern(""DDIDDIID"")" +Practice questions for Linked List and Recursion,"static void fun1(Node head) +{ + if (head == null) + { + return; + } + fun1(head.next); + System.out.print(head.data + "" ""); +}","def fun1(head): + if(head == None): + return + fun1(head.next) + print(head.data, end = "" "")" +Threaded Binary Search Tree | Deletion,"/*Here 'par' is pointer to parent Node and 'ptr' is +pointer to current Node.*/ + +Node caseA(Node root, Node par, + Node ptr) +{ +/* If Node to be deleted is root*/ + + if (par == null) + root = null; +/* If Node to be deleted is left + of its parent*/ + + else if (ptr == par.left) { + par.lthread = true; + par.left = ptr.left; + } + else { + par.rthread = true; + par.right = ptr.right; + } + return root; +}", +Form coils in a matrix,"/*Java program to print 2 coils +of a 4n x 4n matrix.*/ + +class GFG { +/* Print coils in a matrix of size 4n x 4n*/ + + static void printCoils(int n) + { +/* Number of elements in each coil*/ + + int m = 8 * n * n; +/* Let us fill elements in coil 1.*/ + + int coil1[] = new int[m]; +/* First element of coil1 + 4*n*2*n + 2*n;*/ + + coil1[0] = 8 * n * n + 2 * n; + int curr = coil1[0]; + int nflg = 1, step = 2; +/* Fill remaining m-1 elements in coil1[]*/ + + int index = 1; + while (index < m) + { +/* Fill elements of current step from + down to up*/ + + for (int i = 0; i < step; i++) + { +/* Next element from current element*/ + + curr = coil1[index++] = (curr - 4 * n * nflg); + if (index >= m) + break; + } + if (index >= m) + break; +/* Fill elements of current step from + up to down.*/ + + for (int i = 0; i < step; i++) + { + curr = coil1[index++] = curr + nflg; + if (index >= m) + break; + } + nflg = nflg * (-1); + step += 2; + } + /* get coil2 from coil1 */ + + int coil2[] = new int[m]; + for (int i = 0; i < 8 * n * n; i++) + coil2[i] = 16 * n * n + 1 - coil1[i]; +/* Print both coils*/ + + System.out.print(""Coil 1 : ""); + for (int i = 0; i < 8 * n * n; i++) + System.out.print(coil1[i] + "" ""); + System.out.print(""\nCoil 2 : ""); + for (int i = 0; i < 8 * n * n; i++) + System.out.print(coil2[i] + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int n = 1; + printCoils(n); + } +}"," '''Python3 program to pr2 coils of a +4n x 4n matrix.''' + '''Prcoils in a matrix of size 4n x 4n''' + +def printCoils(n): + ''' Number of elements in each coil''' + + m = 8*n*n + ''' Let us fill elements in coil 1.''' + + coil1 = [0]*m + ''' First element of coil1 + 4*n*2*n + 2*n''' + + coil1[0] = 8*n*n + 2*n + curr = coil1[0] + nflg = 1 + step = 2 + ''' Fill remaining m-1 elements in coil1[]''' + + index = 1 + while (index < m): + ''' Fill elements of current step from + down to up''' + + for i in range(step): + ''' Next element from current element''' + + curr = coil1[index] = (curr - 4*n*nflg) + index += 1 + if (index >= m): + break + if (index >= m): + break + ''' Fill elements of current step from + up to down.''' + + for i in range(step): + curr = coil1[index] = curr + nflg + index += 1 + if (index >= m): + break + nflg = nflg*(-1) + step += 2 + ''' get coil2 from coil1 */''' + + coil2 = [0]*m + i = 0 + while(i < 8*n*n): + coil2[i] = 16*n*n + 1 -coil1[i] + i += 1 + ''' Prboth coils''' + + print(""Coil 1 :"", end = "" "") + i = 0 + while(i < 8*n*n): + print(coil1[i], end = "" "") + i += 1 + print(""\nCoil 2 :"", end = "" "") + i = 0 + while(i < 8*n*n): + print(coil2[i], end = "" "") + i += 1 + '''Driver code''' + +n = 1 +printCoils(n)" +Find maximum average subarray of k length,"/*Java program to find maximum average subarray +of given length.*/ + +import java.io.*; +class GFG { +/* Returns beginning index of maximum average + subarray of length 'k'*/ + + static int findMaxAverage(int arr[], int n, int k) + { +/* Check if 'k' is valid*/ + + if (k > n) + return -1; +/* Compute sum of first 'k' elements*/ + + int sum = arr[0]; + for (int i = 1; i < k; i++) + sum += arr[i]; + int max_sum = sum, max_end = k-1; +/* Compute sum of remaining subarrays*/ + + for (int i = k; i < n; i++) + { + sum = sum + arr[i] - arr[i-k]; + if (sum > max_sum) + { + max_sum = sum; + max_end = i; + } + } +/* Return starting index*/ + + return max_end - k + 1; + } +/* Driver program*/ + + public static void main (String[] args) + { + int arr[] = {1, 12, -5, -6, 50, 3}; + int k = 4; + int n = arr.length; + System.out.println( ""The maximum average"" + + "" subarray of length "" + k + + "" begins at index "" + + findMaxAverage(arr, n, k)); + } +}"," '''Python 3 program to find maximum +average subarray of given length.''' + '''Returns beginning index of maximum +average subarray of length k''' +def findMaxAverage(arr, n, k): + ''' Check if 'k' is valid''' + + if (k > n): + return -1 + ''' Compute sum of first 'k' elements''' + + sum = arr[0] + for i in range(1, k): + sum += arr[i] + max_sum = sum + max_end = k - 1 + ''' Compute sum of remaining subarrays''' + + for i in range(k, n): + sum = sum + arr[i] - arr[i - k] + if (sum > max_sum): + max_sum = sum + max_end = i + ''' Return starting index''' + + return max_end - k + 1 + '''Driver program''' + +arr = [1, 12, -5, -6, 50, 3] +k = 4 +n = len(arr) +print(""The maximum average subarray of length"", k, + ""begins at index"", + findMaxAverage(arr, n, k))" +Binomial Coefficient | DP-9,"/*JAVA Code for Dynamic Programming | +Set 9 (Binomial Coefficient)*/ + +import java.util.*; +class GFG { + static int binomialCoeff(int n, int k) + { + int C[] = new int[k + 1]; +/* nC0 is 1*/ + + C[0] = 1; + for (int i = 1; i <= n; i++) { +/* Compute next row of pascal + triangle using the previous row*/ + + for (int j = Math.min(i, k); j > 0; j--) + C[j] = C[j] + C[j - 1]; + } + return C[k]; + } + /* Driver code */ + + public static void main(String[] args) + { + int n = 5, k = 2; + System.out.printf(""Value of C(%d, %d) is %d "", n, k, + binomialCoeff(n, k)); + } +}"," '''Python program for Optimized +Dynamic Programming solution to +Binomail Coefficient. This one +uses the concept of pascal +Triangle and less memory''' + +def binomialCoeff(n, k): + C = [0 for i in xrange(k+1)] + '''since nC0 is 1''' + + C[0] = 1 + for i in range(1, n+1): + ''' Compute next row of pascal triangle using + the previous row''' + + j = min(i, k) + while (j > 0): + C[j] = C[j] + C[j-1] + j -= 1 + return C[k] + '''Driver Code''' + +n = 5 +k = 2 +print ""Value of C(%d,%d) is %d"" % (n, k, binomialCoeff(n, k)) +" +Find closest number in array,"/*Java program to find element closet to given target.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; + +class FindClosestNumber { + +/* Returns element closest to target in arr[]*/ + + public static int findClosest(int arr[], int target) + { + int n = arr.length; + +/* Corner cases*/ + + if (target <= arr[0]) + return arr[0]; + if (target >= arr[n - 1]) + return arr[n - 1]; + +/* Doing binary search*/ + + int i = 0, j = n, mid = 0; + while (i < j) { + mid = (i + j) / 2; + + if (arr[mid] == target) + return arr[mid]; + + /* If target is less than array element, + then search in left */ + + if (target < arr[mid]) { + +/* If target is greater than previous + to mid, return closest of two*/ + + if (mid > 0 && target > arr[mid - 1]) + return getClosest(arr[mid - 1], + arr[mid], target); + + /* Repeat for left half */ + + j = mid; + } + +/* If target is greater than mid*/ + + else { + if (mid < n-1 && target < arr[mid + 1]) + return getClosest(arr[mid], + arr[mid + 1], target); +/*update i*/ + +i = mid + 1; + } + } + +/* Only single element left after search*/ + + return arr[mid]; + } + +/* Method to compare which one is the more close + We find the closest by taking the difference + between the target and both values. It assumes + that val2 is greater than val1 and target lies + between these two.*/ + + public static int getClosest(int val1, int val2, + int target) + { + if (target - val1 >= val2 - target) + return val2; + else + return val1; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 }; + int target = 11; + System.out.println(findClosest(arr, target)); + } +} +"," '''Python3 program to find element +closet to given target.''' + + + '''Returns element closest to target in arr[]''' + +def findClosest(arr, n, target): + + ''' Corner cases''' + + if (target <= arr[0]): + return arr[0] + if (target >= arr[n - 1]): + return arr[n - 1] + + ''' Doing binary search''' + + i = 0; j = n; mid = 0 + while (i < j): + mid = (i + j) // 2 + + if (arr[mid] == target): + return arr[mid] + + ''' If target is less than array + element, then search in left''' + + if (target < arr[mid]) : + + ''' If target is greater than previous + to mid, return closest of two''' + + if (mid > 0 and target > arr[mid - 1]): + return getClosest(arr[mid - 1], arr[mid], target) + + ''' Repeat for left half''' + + j = mid + + ''' If target is greater than mid''' + + else : + if (mid < n - 1 and target < arr[mid + 1]): + return getClosest(arr[mid], arr[mid + 1], target) + + ''' update i''' + + i = mid + 1 + + ''' Only single element left after search''' + + return arr[mid] + + + '''Method to compare which one is the more close. +We find the closest by taking the difference +between the target and both values. It assumes +that val2 is greater than val1 and target lies +between these two.''' + +def getClosest(val1, val2, target): + + if (target - val1 >= val2 - target): + return val2 + else: + return val1 + + '''Driver code''' + +arr = [1, 2, 4, 5, 6, 6, 8, 9] +n = len(arr) +target = 11 +print(findClosest(arr, n, target)) + + +" +Deletion at different positions in a Circular Linked List,"/*Function to delete First node of +Circular Linked List*/ + +static void DeleteFirst(Node head) +{ + Node previous = head, firstNode = head; + +/* Check if list doesn't have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return; + } + +/* Check if list have single node + if yes then delete it and return*/ + + if (previous.next == previous) + { + head = null; + return; + } + +/* Traverse second node to first*/ + + while (previous.next != head) + { + previous = previous.next; + } + +/* Now previous is last node and + first node(firstNode) link address + put in last node(previous) link*/ + + previous.next = firstNode.next; + +/* Make second node as head node*/ + + head = previous.next; + System.gc(); + return; +} + + +", +Leaf nodes from Preorder of a Binary Search Tree,"/*Stack based Java program to print leaf nodes +from preorder traversal.*/ + +import java.util.*; +class GfG { +/*Print the leaf node from the given preorder of BST. */ + +static void leafNode(int preorder[], int n) +{ + Stack s = new Stack (); + for (int i = 0, j = 1; j < n; i++, j++) + { + boolean found = false; + if (preorder[i] > preorder[j]) + s.push(preorder[i]); + else + { + while (!s.isEmpty()) + { + if (preorder[j] > s.peek()) + { + s.pop(); + found = true; + } + else + break; + } + } + if (found) + System.out.print(preorder[i] + "" ""); + } +/* Since rightmost element is always leaf node. */ + + System.out.println(preorder[n - 1]); +} +/*Driver code */ + +public static void main(String[] args) +{ + int preorder[] = { 890, 325, 290, 530, 965 }; + int n = preorder.length; + leafNode(preorder, n); +} +}"," '''Stack based Python program to print +leaf nodes from preorder traversal. + ''' '''Print the leaf node from the given +preorder of BST. ''' + +def leafNode(preorder, n): + s = [] + i = 0 + for j in range(1, n): + found = False + if preorder[i] > preorder[j]: + s.append(preorder[i]) + else: + while len(s) != 0: + if preorder[j] > s[-1]: + s.pop(-1) + found = True + else: + break + if found: + print(preorder[i], end = "" "") + i += 1 + ''' Since rightmost element is + always leaf node. ''' + + print(preorder[n - 1]) + '''Driver code ''' + +if __name__ == '__main__': + preorder = [890, 325, 290, 530, 965] + n = len(preorder) + leafNode(preorder, n)" +Trapping Rain Water,"/*Java implementation of the approach*/ + +class GFG { + +/* Function to return the maximum + water that can be stored*/ + + public static int maxWater(int arr[], int n) + { + int size = n - 1; + +/* Let the first element be stored as + previous, we shall loop from index 1*/ + + int prev = arr[0]; + +/* To store previous wall's index*/ + + int prev_index = 0; + int water = 0; + +/* To store the water until a larger wall + is found, if there are no larger walls + then delete temp value from water*/ + + int temp = 0; + for (int i = 1; i <= size; i++) { + +/* If the current wall is taller than + the previous wall then make current + wall as the previous wall and its + index as previous wall's index + for the subsequent loops*/ + + if (arr[i] >= prev) { + prev = arr[i]; + prev_index = i; + +/* Because larger or same height wall is found*/ + + temp = 0; + } + else { + +/* Since current wall is shorter than + the previous, we subtract previous + wall's height from the current wall's + height and add it to the water*/ + + water += prev - arr[i]; + +/* Store the same value in temp as well + If we dont find any larger wall then + we will subtract temp from water*/ + + temp += prev - arr[i]; + } + } + +/* If the last wall was larger than or equal + to the previous wall then prev_index would + be equal to size of the array (last element) + If we didn't find a wall greater than or equal + to the previous wall from the left then + prev_index must be less than the index + of the last element*/ + + if (prev_index < size) { + +/* Temp would've stored the water collected + from previous largest wall till the end + of array if no larger wall was found then + it has excess water and remove that + from 'water' var*/ + + water -= temp; + +/* We start from the end of the array, so previous + should be assigned to the last element*/ + + prev = arr[size]; + +/* Loop from the end of array up to the 'previous index' + which would contain the ""largest wall from the left""*/ + + for (int i = size; i >= prev_index; i--) { + +/* Right end wall will be definitely smaller + than the 'previous index' wall*/ + + if (arr[i] >= prev) { + prev = arr[i]; + } + else { + water += prev - arr[i]; + } + } + } + +/* Return the maximum water*/ + + return water; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + int n = arr.length; + System.out.print(maxWater(arr, n)); + } +} +"," '''Pythpn3 implementation of the approach''' + + + '''Function to return the maximum +water that can be stored''' + +def maxWater(arr, n): + size = n - 1 + + ''' Let the first element be stored as + previous, we shall loop from index 1''' + + prev = arr[0] + + ''' To store previous wall's index''' + + prev_index = 0 + water = 0 + + ''' To store the water until a larger wall + is found, if there are no larger walls + then delete temp value from water''' + + temp = 0 + for i in range(1, size + 1): + + ''' If the current wall is taller than + the previous wall then make current + wall as the previous wall and its + index as previous wall's index + for the subsequent loops''' + + if (arr[i] >= prev): + prev = arr[i] + prev_index = i + + ''' Because larger or same height wall is found''' + + temp = 0 + else: + + ''' Since current wall is shorter than + the previous, we subtract previous + wall's height from the current wall's + height and add it to the water''' + + water += prev - arr[i] + + ''' Store the same value in temp as well + If we dont find any larger wall then + we will subtract temp from water''' + + temp += prev - arr[i] + + ''' If the last wall was larger than or equal + to the previous wall then prev_index would + be equal to size of the array (last element) + If we didn't find a wall greater than or equal + to the previous wall from the left then + prev_index must be less than the index + of the last element''' + + if (prev_index < size): + + ''' Temp would've stored the water collected + from previous largest wall till the end + of array if no larger wall was found then + it has excess water and remove that + from 'water' var''' + + water -= temp + + ''' We start from the end of the array, so previous + should be assigned to the last element''' + + prev = arr[size] + + ''' Loop from the end of array up to the 'previous index' + which would contain the ""largest wall from the left""''' + + for i in range(size, prev_index - 1, -1): + + ''' Right end wall will be definitely smaller + than the 'previous index' wall''' + + if (arr[i] >= prev): + prev = arr[i] + else: + water += prev - arr[i] + + ''' Return the maximum water''' + + return water + + '''Driver code''' + +arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] +n = len(arr) +print(maxWater(arr, n)) + + +" +Pascal's Triangle,"/*java program for Pascal's Triangle*/ + +import java.io.*; +class GFG { +/*A O(n^2) time and O(n^2) extra +space method for Pascal's Triangle*/ + +public static void printPascal(int n) +{/*An auxiliary array to store generated pascal triangle values*/ + +int[][] arr = new int[n][n]; +/*Iterate through every line and print integer(s) in it*/ + +for (int line = 0; line < n; line++) +{ +/* Every line has number of integers equal to line number*/ + + for (int i = 0; i <= line; i++) + { +/* First and last values in every row are 1*/ + + if (line == i || i == 0) + arr[line][i] = 1; +/*Other values are sum of values just above and left of above*/ + +else + arr[line][i] = arr[line-1][i-1] + arr[line-1][i]; + System.out.print(arr[line][i]); + } + System.out.println(""""); +} +} +}/*Driver code*/ + + public static void main (String[] args) { + int n = 5; + printPascal(n); + }"," '''Python3 program for Pascal's Triangle''' + + '''A O(n^2) time and O(n^2) extra +space method for Pascal's Triangle''' + +def printPascal(n:int): ''' An auxiliary array to store + generated pascal triangle values''' + + arr = [[0 for x in range(n)] + for y in range(n)] + ''' Iterate through every line + and print integer(s) in it''' + + for line in range (0, n): + ''' Every line has number of + integers equal to line number''' + + for i in range (0, line + 1): + ''' First and last values + in every row are 1''' + + if(i==0 or i==line): + arr[line][i] = 1 + print(arr[line][i], end = "" "") + ''' Other values are sum of values + just above and left of above''' + + else: + arr[line][i] = (arr[line - 1][i - 1] + + arr[line - 1][i]) + print(arr[line][i], end = "" "") + print(""\n"", end = """") + '''Driver Code''' + +n = 5 +printPascal(n)" +Find Union and Intersection of two unsorted arrays,"/*Java program to find union and intersection +using Hashing*/ + +import java.util.HashSet; +class Test { +/* Prints union of arr1[0..m-1] and arr2[0..n-1]*/ + + static void printUnion(int arr1[], int arr2[]) + { + HashSet hs = new HashSet<>(); + for (int i = 0; i < arr1.length; i++) + hs.add(arr1[i]); + for (int i = 0; i < arr2.length; i++) + hs.add(arr2[i]); + System.out.println(hs); + } +/* Prints intersection of arr1[0..m-1] and arr2[0..n-1]*/ + + static void printIntersection(int arr1[], int arr2[]) + { + HashSet hs = new HashSet<>(); + HashSet hs1 = new HashSet<>(); + for (int i = 0; i < arr1.length; i++) + hs.add(arr1[i]); + for (int i = 0; i < arr2.length; i++) + if (hs.contains(arr2[i])) + System.out.print(arr2[i] + "" ""); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr1[] = { 7, 1, 5, 2, 3, 6 }; + int arr2[] = { 3, 8, 6, 20, 7 }; +/* Function call*/ + + System.out.println(""Union of two arrays is : ""); + printUnion(arr1, arr2); + System.out.println( + ""Intersection of two arrays is : ""); + printIntersection(arr1, arr2); + } +}"," '''Python program to find union and intersection +using sets''' + + + '''Prints union of arr1[0..n1-1] and arr2[0..n2-1]''' + +def printUnion(arr1, arr2, n1, n2): + hs = set() + for i in range(0, n1): + hs.add(arr1[i]) + for i in range(0, n2): + hs.add(arr2[i]) + print(""Union:"") + for i in hs: + print(i, end="" "") + print(""\n"") ''' Prints intersection of arr1[0..n1-1] and + arr2[0..n2-1]''' + +def printIntersection(arr1, arr2, n1, n2): + hs = set() + for i in range(0, n1): + hs.add(arr1[i]) + print(""Intersection:"") + for i in range(0, n2): + if arr2[i] in hs: + print(arr2[i], end="" "") + + '''Driver Program''' + +arr1 = [7, 1, 5, 2, 3, 6] +arr2 = [3, 8, 6, 20, 7] +n1 = len(arr1) +n2 = len(arr2) + '''Function call''' + +printUnion(arr1, arr2, n1, n2) +printIntersection(arr1, arr2, n1, n2)" +Count 1's in a sorted binary array,"/*Java program to count 1's in a sorted array*/ + +class CountOnes +{ + /* Returns counts of 1's in arr[low..high]. The + array is assumed to be sorted in non-increasing + order */ + + int countOnes(int arr[], int low, int high) + { + if (high >= low) + { +/* get the middle index*/ + + int mid = low + (high - low) / 2; +/* check if the element at middle index is last + 1*/ + + if ((mid == high || arr[mid + 1] == 0) + && (arr[mid] == 1)) + return mid + 1; +/* If element is not last 1, recur for right + side*/ + + if (arr[mid] == 1) + return countOnes(arr, (mid + 1), high); +/* else recur for left side*/ + + return countOnes(arr, low, (mid - 1)); + } + return 0; + } + /* Driver code */ + + public static void main(String args[]) + { + CountOnes ob = new CountOnes(); + int arr[] = { 1, 1, 1, 1, 0, 0, 0 }; + int n = arr.length; + System.out.println(""Count of 1's in given array is "" + + ob.countOnes(arr, 0, n - 1)); + } +}"," '''Python program to count one's in a boolean array + ''' '''Returns counts of 1's in arr[low..high]. The array is +assumed to be sorted in non-increasing order''' + +def countOnes(arr,low,high): + if high>=low: + ''' get the middle index''' + + mid = low + (high-low)//2 + ''' check if the element at middle index is last 1''' + + if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)): + return mid+1 + ''' If element is not last 1, recur for right side''' + + if arr[mid]==1: + return countOnes(arr, (mid+1), high) + ''' else recur for left side''' + + return countOnes(arr, low, mid-1) + return 0 + '''Driver Code''' + +arr=[1, 1, 1, 1, 0, 0, 0] +print (""Count of 1's in given array is"",countOnes(arr, 0 , len(arr)-1))" +Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix,"/*Java implementation of Efficient +method to count of negative numbers +in M[n][m]*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG { +/* Function to count + negative number*/ + + static int countNegative(int M[][], int n, + int m) + { +/* initialize result*/ + + int count = 0; +/* Start with top right corner*/ + + int i = 0; + int j = m - 1; +/* Follow the path shown using + arrows above*/ + + while (j >= 0 && i < n) { + if (M[i][j] < 0) { +/* j is the index of the + last negative number + in this row. So there + must be ( j+1 )*/ + + count += j + 1; +/* negative numbers in + this row.*/ + + i += 1; + } +/* move to the left and see + if we can find a negative + number there*/ + + else + j -= 1; + } + return count; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int M[][] = { { -3, -2, -1, 1 }, + { -2, 2, 3, 4 }, + { 4, 5, 7, 8 } }; + System.out.println(countNegative(M, 3, 4)); + } +}"," '''Python implementation of Efficient method to count of +negative numbers in M[n][m]''' + + '''Function to count + negative number''' + +def countNegative(M, n, m): '''initialize result''' + + count = 0 + ''' Start with top right corner''' + + i = 0 + j = m - 1 + ''' Follow the path shown using arrows above''' + + while j >= 0 and i < n: + if M[i][j] < 0: + ''' j is the index of the last negative number + in this row. So there must be ( j + 1 )''' + + count += (j + 1) + ''' negative numbers in this row.''' + + i += 1 + else: + ''' move to the left and see if we can + find a negative number there''' + + j -= 1 + return count + '''Driver code''' + +M = [ + [-3, -2, -1, 1], + [-2, 2, 3, 4], + [4, 5, 7, 8] + ] +print(countNegative(M, 3, 4))" +Merge two sorted lists (in-place),"/*Java program to merge two sorted +linked lists in-place.*/ + +class GfG { + + + +/*Linked List node*/ + + static class Node { + int data; + Node next; + }/* Function to create newNode in a linkedlist*/ + + static Node newNode(int key) + { + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; + } + +/* A utility function to print linked list*/ + + static void printList(Node node) + { + while (node != null) { + System.out.print(node.data + "" ""); + node = node.next; + } + } + +/* Merges two lists with headers as h1 and h2. + It assumes that h1's data is smaller than + or equal to h2's data.*/ + + static Node mergeUtil(Node h1, Node h2) + { +/* if only one node in first list + simply point its head to second list*/ + + if (h1.next == null) { + h1.next = h2; + return h1; + } + +/* Initialize current and next pointers of + both lists*/ + + Node curr1 = h1, next1 = h1.next; + Node curr2 = h2, next2 = h2.next; + + while (next1 != null && curr2 != null) { +/* if curr2 lies in between curr1 and next1 + then do curr1->curr2->next1*/ + + if ((curr2.data) >= (curr1.data) && (curr2.data) <= (next1.data)) { + next2 = curr2.next; + curr1.next = curr2; + curr2.next = next1; + +/* now let curr1 and curr2 to point + to their immediate next pointers*/ + + curr1 = curr2; + curr2 = next2; + } + else { +/* if more nodes in first list*/ + + if (next1.next != null) { + next1 = next1.next; + curr1 = curr1.next; + } + +/* else point the last node of first list + to the remaining nodes of second list*/ + + else { + next1.next = curr2; + return h1; + } + } + } + return h1; + } + +/* Merges two given lists in-place. This function + mainly compares head nodes and calls mergeUtil()*/ + + static Node merge(Node h1, Node h2) + { + if (h1 == null) + return h2; + if (h2 == null) + return h1; + +/* start with the linked list + whose head data is the least*/ + + if (h1.data < h2.data) + return mergeUtil(h1, h2); + else + return mergeUtil(h2, h1); + } + +/* Driver code*/ + + public static void main(String[] args) + { + Node head1 = newNode(1); + head1.next = newNode(3); + head1.next.next = newNode(5); + +/* 1->3->5 LinkedList created*/ + + + Node head2 = newNode(0); + head2.next = newNode(2); + head2.next.next = newNode(4); + +/* 0->2->4 LinkedList created*/ + + + Node mergedhead = merge(head1, head2); + + printList(mergedhead); + } +} + + +"," '''Python program to merge two sorted linked lists +in-place.''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Function to create newNode in a linkedlist''' + +def newNode(key): + + temp = Node(0) + temp.data = key + temp.next = None + return temp + + '''A utility function to print linked list''' + +def printList(node): + + while (node != None) : + print( node.data, end ="" "") + node = node.next + + '''Merges two lists with headers as h1 and h2. +It assumes that h1's data is smaller than +or equal to h2's data.''' + +def mergeUtil(h1, h2): + + ''' if only one node in first list + simply point its head to second list''' + + if (h1.next == None) : + h1.next = h2 + return h1 + + ''' Initialize current and next pointers of + both lists''' + + curr1 = h1 + next1 = h1.next + curr2 = h2 + next2 = h2.next + + while (next1 != None and curr2 != None): + + ''' if curr2 lies in between curr1 and next1 + then do curr1.curr2.next1''' + + if ((curr2.data) >= (curr1.data) and + (curr2.data) <= (next1.data)) : + next2 = curr2.next + curr1.next = curr2 + curr2.next = next1 + + ''' now let curr1 and curr2 to point + to their immediate next pointers''' + + curr1 = curr2 + curr2 = next2 + + else : + ''' if more nodes in first list''' + + if (next1.next) : + next1 = next1.next + curr1 = curr1.next + + ''' else point the last node of first list + to the remaining nodes of second list''' + + else : + next1.next = curr2 + return h1 + + return h1 + + '''Merges two given lists in-place. This function +mainly compares head nodes and calls mergeUtil()''' + +def merge( h1, h2): + + if (h1 == None): + return h2 + if (h2 == None): + return h1 + + ''' start with the linked list + whose head data is the least''' + + if (h1.data < h2.data): + return mergeUtil(h1, h2) + else: + return mergeUtil(h2, h1) + + '''Driver program''' + + +head1 = newNode(1) +head1.next = newNode(3) +head1.next.next = newNode(5) + + '''1.3.5 LinkedList created''' + + +head2 = newNode(0) +head2.next = newNode(2) +head2.next.next = newNode(4) + + '''0.2.4 LinkedList created''' + + +mergedhead = merge(head1, head2) + +printList(mergedhead) + + +" +Length of longest palindrome list in a linked list using O(1) extra space,"/*Java program to find longest palindrome +sublist in a list in O(1) time.*/ + +class GfG +{ + +/*structure of the linked list*/ + +static class Node +{ + int data; + Node next; +} + +/*function for counting the common elements*/ + +static int countCommon(Node a, Node b) +{ + int count = 0; + +/* loop to count coomon in the list starting + from node a and b*/ + + for (; a != null && b != null; + a = a.next, b = b.next) + +/* increment the count for same values*/ + + if (a.data == b.data) + ++count; + else + break; + + return count; +} + +/*Returns length of the longest palindrome +sublist in given list*/ + +static int maxPalindrome(Node head) +{ + int result = 0; + Node prev = null, curr = head; + +/* loop till the end of the linked list*/ + + while (curr != null) + { +/* The sublist from head to current + reversed.*/ + + Node next = curr.next; + curr.next = prev; + +/* check for odd length + palindrome by finding + longest common list elements + beginning from prev and + from next (We exclude curr)*/ + + result = Math.max(result, + 2 * countCommon(prev, next)+1); + +/* check for even length palindrome + by finding longest common list elements + beginning from curr and from next*/ + + result = Math.max(result, + 2*countCommon(curr, next)); + +/* update prev and curr for next iteration*/ + + prev = curr; + curr = next; + } + return result; +} + +/*Utility function to create a new list node*/ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.data = key; + temp.next = null; + return temp; +} + +/* Driver code*/ + +public static void main(String[] args) +{ + /* Let us create a linked lists to test + the functions + Created list is a: 2->4->3->4->2->15 */ + + 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); + + System.out.println(maxPalindrome(head)); +} +} + + +"," '''Python program to find longest palindrome +sublist in a list in O(1) time.''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''function for counting the common elements''' + +def countCommon(a, b) : + + count = 0 + + ''' loop to count coomon in the list starting + from node a and b''' + + while ( a != None and b != None ) : + + ''' increment the count for same values''' + + if (a.data == b.data) : + count = count + 1 + else: + break + + a = a.next + b = b.next + + return count + + '''Returns length of the longest palindrome +sublist in given list''' + +def maxPalindrome(head) : + + result = 0 + prev = None + curr = head + + ''' loop till the end of the linked list''' + + while (curr != None) : + + ''' The sublist from head to current + reversed.''' + + next = curr.next + curr.next = prev + + ''' check for odd length + palindrome by finding + longest common list elements + beginning from prev and + from next (We exclude curr)''' + + result = max(result, + 2 * countCommon(prev, next) + 1) + + ''' check for even length palindrome + by finding longest common list elements + beginning from curr and from next''' + + result = max(result, + 2 * countCommon(curr, next)) + + ''' update prev and curr for next iteration''' + + prev = curr + curr = next + + return result + + '''Utility function to create a new list node''' + +def newNode(key) : + + temp = Node(0) + temp.data = key + temp.next = None + return temp + + '''Driver code''' + + + '''Let us create a linked lists to test +the functions +Created list is a: 2->4->3->4->2->15''' + +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) + +print(maxPalindrome(head)) + + +" +Convert a Binary Tree into Doubly Linked List in spiral fashion,"/* Java program to convert Binary Tree into Doubly Linked List + where the nodes are represented spirally */ + +import java.util.*; +/*A binary tree node*/ + +class Node +{ + int data; + Node left, right; + public Node(int data) + { + this.data = data; + left = right = null; + } +} +class BinaryTree +{ + Node root; + Node head; + /* Given a reference to a node, + inserts the node on the front of the list. */ + + void push(Node node) + { +/* Make right of given node as head and left as + NULL*/ + + node.right = head; + node.left = null; +/* change left of head node to given node*/ + + if (head != null) + head.left = node; +/* move the head to point to the given node*/ + + head = node; + } +/* Function to prints contents of DLL*/ + + void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + "" ""); + node = node.right; + } + } + /* Function to print corner node at each level */ + + void spiralLevelOrder(Node root) + { +/* Base Case*/ + + if (root == null) + return; +/* Create an empty deque for doing spiral + level order traversal and enqueue root*/ + + Deque q = new LinkedList(); + q.addFirst(root); +/* create a stack to store Binary Tree nodes + to insert into DLL later*/ + + Stack stk = new Stack(); + int level = 0; + while (!q.isEmpty()) + { +/* nodeCount indicates number of Nodes + at current level.*/ + + int nodeCount = q.size(); +/* Dequeue all Nodes of current level and + Enqueue all Nodes of next level +odd level*/ + +if ((level & 1) %2 != 0) + { + while (nodeCount > 0) + { +/* dequeue node from front & push it to + stack*/ + + Node node = q.peekFirst(); + q.pollFirst(); + stk.push(node); +/* insert its left and right children + in the back of the deque*/ + + if (node.left != null) + q.addLast(node.left); + if (node.right != null) + q.addLast(node.right); + nodeCount--; + } + } +/*even level*/ + +else + { + while (nodeCount > 0) + { +/* dequeue node from the back & push it + to stack*/ + + Node node = q.peekLast(); + q.pollLast(); + stk.push(node); +/* inserts its right and left children + in the front of the deque*/ + + if (node.right != null) + q.addFirst(node.right); + if (node.left != null) + q.addFirst(node.left); + nodeCount--; + } + } + level++; + } +/* pop all nodes from stack and + push them in the beginning of the list*/ + + while (!stk.empty()) + { + push(stk.peek()); + stk.pop(); + } + System.out.println(""Created DLL is : ""); + printList(head); + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { +/* Let us create binary tree as shown in above diagram*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.left.left = new Node(8); + tree.root.left.left.right = new Node(9); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(11); +/* tree.root.right.left.left = new Node(12);*/ + + tree.root.right.left.right = new Node(13); + tree.root.right.right.left = new Node(14); +/* tree.root.right.right.right = new Node(15);*/ + + tree.spiralLevelOrder(tree.root); + } +}"," '''Python3 program to convert Binary Tree +into Doubly Linked List where the nodes +are represented spirally.''' + + '''Binary tree node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None ''' Given a reference to the head of a list + and a node, inserts the node on the front + of the list. ''' + +def push(head_ref, node): + ''' Make right of given node as + head and left as None''' + + node.right = (head_ref) + node.left = None + ''' change left of head node to + given node''' + + if ((head_ref) != None): + (head_ref).left = node + ''' move the head to point to + the given node''' + + (head_ref) = node + '''Function to prints contents of DLL''' + +def printList(node): + i = 0 + while (i < len(node)): + print(node[i].data, end = "" "") + i += 1 + ''' Function to prcorner node at each level ''' + +def spiralLevelOrder(root): + ''' Base Case''' + + if (root == None): + return + ''' Create an empty deque for doing spiral + level order traversal and enqueue root''' + + q = [] + q.append(root) + ''' create a stack to store Binary + Tree nodes to insert into DLL later''' + + stk = [] + level = 0 + while (len(q)): + ''' nodeCount indicates number of + Nodes at current level.''' + + nodeCount = len(q) + ''' Dequeue all Nodes of current level + and Enqueue all Nodes of next level +odd level''' + + if (level&1): + while (nodeCount > 0): + ''' dequeue node from front & + push it to stack''' + + node = q[0] + q.pop(0) + stk.append(node) + ''' insert its left and right children + in the back of the deque''' + + if (node.left != None): + q.append(node.left) + if (node.right != None): + q.append(node.right) + nodeCount -= 1 + '''even level''' + + else: + while (nodeCount > 0): + ''' dequeue node from the back & + push it to stack''' + + node = q[-1] + q.pop(-1) + stk.append(node) + ''' inserts its right and left + children in the front of + the deque''' + + if (node.right != None): + q.insert(0, node.right) + if (node.left != None): + q.insert(0, node.left) + nodeCount -= 1 + level += 1 + ''' head pointer for DLL''' + + head = [] + ''' pop all nodes from stack and push + them in the beginning of the list''' + + while (len(stk)): + head.append(stk[0]) + stk.pop(0) + print(""Created DLL is:"") + printList(head) + '''Driver Code''' + +if __name__ == '__main__': + '''Let us create Binary Tree as + shown in above example ''' + + 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.left.left.left = newNode(8) + root.left.left.right = newNode(9) + root.left.right.left = newNode(10) + root.left.right.right = newNode(11) + ''' root.right.left.left = newNode(12)''' + + root.right.left.right = newNode(13) + root.right.right.left = newNode(14) + ''' root.right.right.right = newNode(15)''' + + spiralLevelOrder(root)" +Count number of islands where every island is row-wise and column-wise separated,"/*A Java program to count the number of rectangular +islands where every island is separated by a line*/ + +import java.io.*; +class islands +{ +/* This function takes a matrix of 'X' and 'O' + and returns the number of rectangular islands + of 'X' where no two islands are row-wise or + column-wise adjacent, the islands may be diagonaly + adjacent*/ + + static int countIslands(int mat[][], int m, int n) + { +/* Initialize result*/ + + int count = 0; +/* Traverse the input matrix*/ + + for (int i=0; i q=new LinkedList<>(); +/* Enqueue Root and initialize height*/ + + q.add(root); + while(true) + { +/* nodeCount (queue size) indicates number + of nodes at current lelvel.*/ + + int nodeCount = q.size(); + if (nodeCount == 0) + break; +/* Dequeue all nodes of current level and + Enqueue all nodes of next level*/ + + while (nodeCount > 0) + { + Node node = q.remove(); + System.out.print(node.data+"" ""); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + nodeCount--; + } + System.out.println(); + } + } + +/* Driver code*/ + + public static void main(String args[]) { + Node root=new Node(1); + root.left=new Node(2); + root.right=new Node(1); + root.right.left = new Node(4); + root.right.right = new Node(5); + System.out.println(""Level order traversal of given tree""); + printLevelOrder(root); + root = flipBinaryTree(root); + System.out.println(""Level order traversal of flipped tree""); + printLevelOrder(root); + } +}"," '''Python3 program to flip +a binary tree''' + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.right = None + self.left = None + + ''' method to flip the binary tree''' + + +def flipBinaryTree(root): + if root is None: + return root + if (root.left is None and + root.right is None): + return root ''' Recursively call the + same method''' + + flippedRoot = flipBinaryTree(root.left) + ''' Rearranging main root Node + after returning from + recursive call''' + + root.left.left = root.right + root.left.right = root + root.left = root.right = None + return flippedRoot + '''Iterative method to do the level +order traversal line by line''' + +def printLevelOrder(root): + ''' Base Case''' + + if root is None: + return + ''' Create an empty queue for + level order traversal''' + + from Queue import Queue + q = Queue() + ''' Enqueue root and initialize + height''' + + q.put(root) + while(True): + ''' nodeCount (queue size) indicates + number of nodes at current level''' + + nodeCount = q.qsize() + if nodeCount == 0: + break + ''' Dequeue all nodes of current + level and Enqueue all nodes + of next level ''' + + while nodeCount > 0: + node = q.get() + print node.data, + if node.left is not None: + q.put(node.left) + if node.right is not None: + q.put(node.right) + nodeCount -= 1 + print + '''Driver code''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.right.left = Node(4) +root.right.right = Node(5) +print ""Level order traversal of given tree"" +printLevelOrder(root) +root = flipBinaryTree(root) +print ""\nLevel order traversal of the flipped tree"" +printLevelOrder(root)" +Construct binary palindrome by repeated appending and trimming,"/*JAVA code to form binary palindrome*/ + +import java.util.*; +class GFG +{ +/*function to apply DFS*/ + +static void dfs(int parent, int ans[], + Vector connectchars[]) +{ +/* set the parent marked*/ + + ans[parent] = 1; +/* if the node has not been visited set it and + its children marked*/ + + for (int i = 0; i < connectchars[parent].size(); i++) + { + if (ans[connectchars[parent].get(i)] != 1) + dfs(connectchars[parent].get(i), ans, connectchars); + } +} +static void printBinaryPalindrome(int n, int k) +{ + int []arr = new int[n]; + int []ans = new int[n]; +/* link which digits must be equal*/ + + Vector []connectchars = new Vector[k]; + for (int i = 0; i < k; i++) + connectchars[i] = new Vector(); + for (int i = 0; i < n; i++) + arr[i] = i % k; +/* connect the two indices*/ + + for (int i = 0; i < n / 2; i++) + { + connectchars[arr[i]].add(arr[n - i - 1]); + connectchars[arr[n - i - 1]].add(arr[i]); + } +/* set everything connected to + first character as 1*/ + + dfs(0, ans, connectchars); + for (int i = 0; i < n; i++) + System.out.print(ans[arr[i]]); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 10, k = 4; + printBinaryPalindrome(n, k); +} +}"," '''Python3 code to form binary palindrome''' + + '''function to apply DFS ''' + +def dfs(parent, ans, connectchars): ''' set the parent marked ''' + + ans[parent] = 1 + ''' if the node has not been visited + set it and its children marked''' + + for i in range(len(connectchars[parent])): + if (not ans[connectchars[parent][i]]): + dfs(connectchars[parent][i], ans, + connectchars) +def printBinaryPalindrome(n, k): + arr = [0] * n + ans = [0] * n + ''' link which digits must be equal ''' + + connectchars = [[] for i in range(k)] + for i in range(n): + arr[i] = i % k + ''' connect the two indices''' + + for i in range(int(n / 2)): + connectchars[arr[i]].append(arr[n - i - 1]) + connectchars[arr[n - i - 1]].append(arr[i]) + ''' set everything connected to + first character as 1 ''' + + dfs(0, ans, connectchars) + for i in range(n): + print(ans[arr[i]], end = """") + '''Driver Code ''' + +if __name__ == '__main__': + n = 10 + k = 4 + printBinaryPalindrome(n, k)" +Check if two BSTs contain same set of elements,"/*Java program to check if two BSTs +contain same set of elements*/ + +import java.util.*; +class GFG +{ +/*BST Node*/ + +static class Node +{ + int data; + Node left; + Node right; +}; +/*Utility function to create new Node*/ + +static Node newNode(int val) +{ + Node temp = new Node(); + temp.data = val; + temp.left = temp.right = null; + return temp; +} +/*function to insert elements +of the tree to map m*/ + +static void storeInorder(Node root, + Vector v) +{ + if (root == null) + return; + storeInorder(root.left, v); + v.add(root.data); + storeInorder(root.right, v); +} +/*function to check if the two BSTs +contain same set of elements*/ + +static boolean checkBSTs(Node root1, Node root2) +{ +/* Base cases*/ + + if (root1 != null && root2 != null) + return true; + if ((root1 == null && root2 != null) || + (root1 != null && root2 == null)) + return false; +/* Create two vectors and store + inorder traversals of both BSTs + in them.*/ + + Vector v1 = new Vector(); + Vector v2 = new Vector(); + storeInorder(root1, v1); + storeInorder(root2, v2); +/* Return true if both vectors are + identical*/ + + return (v1 == v2); +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* First BST*/ + + Node root1 = newNode(15); + root1.left = newNode(10); + root1.right = newNode(20); + root1.left.left = newNode(5); + root1.left.right = newNode(12); + root1.right.right = newNode(25); +/* Second BST*/ + + Node root2 = newNode(15); + root2.left = newNode(12); + root2.right = newNode(20); + root2.left.left = newNode(5); + root2.left.left.right = newNode(10); + root2.right.right = newNode(25); +/* check if two BSTs have same set of elements*/ + + if (checkBSTs(root1, root2)) + System.out.print(""YES""); + else + System.out.print(""NO""); +} +}"," '''Python3 program to check if two BSTs contains +same set of elements''' + + '''BST Node''' + +class Node: + def __init__(self): + self.val = 0 + self.left = None + self.right = None '''Utility function to create Node''' + +def Node_(val1): + temp = Node() + temp.val = val1 + temp.left = temp.right = None + return temp +v = [] + '''function to insert elements of the +tree to map m''' + +def storeInorder(root): + if (root == None): + return + storeInorder(root.left) + v.append(root.data) + storeInorder(root.right) + '''function to check if the two BSTs contain +same set of elements''' + +def checkBSTs(root1, root2): + ''' Base cases''' + + if (root1 != None and root2 != None) : + return True + if ((root1 == None and root2 != None) or \ + (root1 != None and root2 == None)): + return False + ''' Create two hash sets and store + elements both BSTs in them.''' + + v1 = [] + v2 = [] + v = v1 + storeInorder(root1) + v1 = v + v = v2 + storeInorder(root2) + v2 = v + ''' Return True if both hash sets + contain same elements.''' + + return (v1 == v2) + '''Driver code''' + + '''First BST''' + +root1 = Node_(15) +root1.left = Node_(10) +root1.right = Node_(20) +root1.left.left = Node_(5) +root1.left.right = Node_(12) +root1.right.right = Node_(25) '''Second BST''' + +root2 = Node_(15) +root2.left = Node_(12) +root2.right = Node_(20) +root2.left.left = Node_(5) +root2.left.left.right = Node_(10) +root2.right.right = Node_(25) + '''check if two BSTs have same set of elements''' + +if (checkBSTs(root1, root2)): + print(""YES"") +else: + print(""NO"")" +Count all distinct pairs with difference equal to k,"/*A sorting based Java program to +count pairs with difference k*/ + +import java.util.*; +class GFG { +/* Returns count of pairs with +difference k in arr[] of size n. */ + +static int countPairsWithDiffK(int arr[], int n, + int k) +{ + int count = 0; +/*Sort array elements*/ + +Arrays.sort(arr); + int l = 0; + int r = 0; + while(r < n) + { + if(arr[r] - arr[l] == k) + { + count++; + l++; + r++; + } + else if(arr[r] - arr[l] > k) + l++; +/*arr[r] - arr[l] < sum*/ + +else + r++; + } + return count; +} +/*Driver program to test above function*/ + +public static void main(String[] args) +{ + int arr[] = {1, 5, 3, 4, 2}; + int n = arr.length; + int k = 3; + System.out.println(""Count of pairs with given diff is "" + + countPairsWithDiffK(arr, n, k)); +} +}"," '''A sorting based program to +count pairs with difference k''' + + + '''Returns count of pairs with difference k in arr[] of size n. ''' +def countPairsWithDiffK(arr,n,k): + count =0 + ''' Sort array elements''' + + arr.sort() + l =0 + r=0 + while rk: + l+=1 + else: + r+=1 + return count + '''Driver code''' + +if __name__=='__main__': + arr = [1, 5, 3, 4, 2] + n = len(arr) + k = 3 + print(""Count of pairs with given diff is "", + countPairsWithDiffK(arr, n, k))" +Find LCA in Binary Tree using RMQ,"/*Java program to find LCA of u and v by reducing problem to RMQ*/ + +import java.util.*; +/*A binary tree node*/ + +class Node +{ + Node left, right; + int data; + Node(int item) + { + data = item; + left = right = null; + } +} +class St_class +{ + int st; + int stt[] = new int[10000]; +} +class BinaryTree +{ + Node root; +/*v is the highest value of node in our tree*/ + +int v = 9; +/*for euler tour sequence*/ + +int euler[] = new int[2 * v - 1]; +/*level of nodes in tour sequence*/ + +int level[] = new int[2 * v - 1]; +/*to store 1st occurrence of nodes*/ + +int f_occur[] = new int[2 * v - 1]; +/*variable to fill euler and level arrays*/ + +int fill; + St_class sc = new St_class(); +/* log base 2 of x*/ + + int Log2(int x) + { + int ans = 0; + int y = x >>= 1; + while (y-- != 0) + ans++; + return ans; + } + int swap(int a, int b) + { + return a; + } + /* A recursive function to get the minimum value in a given range + of array indexes. The following are parameters for this function. + st --> Pointer to segment tree + index --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment represented + by current node, i.e., st[index] + qs & qe --> Starting and ending indexes of query range */ + + int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) + { +/* If segment of this node is a part of given range, then return + the min of the segment*/ + + if (qs <= ss && qe >= se) + return st.stt[index]; +/* If segment of this node is outside the given range*/ + + else if (se < qs || ss > qe) + return -1; +/* If a part of this segment overlaps with the given range*/ + + int mid = (ss + se) / 2; + int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); + int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); + if (q1 == -1) + return q2; + else if (q2 == -1) + return q1; + return (level[q1] < level[q2]) ? q1 : q2; + } +/* Return minimum of elements in range from index qs (query start) to + qe (query end). It mainly uses RMQUtil()*/ + + int RMQ(St_class st, int n, int qs, int qe) + { +/* Check for erroneous input values*/ + + if (qs < 0 || qe > n - 1 || qs > qe) + { + System.out.println(""Invalid input""); + return -1; + } + return RMQUtil(0, 0, n - 1, qs, qe, st); + } +/* A recursive function that constructs Segment Tree for array[ss..se]. + si is index of current node in segment tree st*/ + + void constructSTUtil(int si, int ss, int se, int arr[], St_class st) + { +/* If there is one element in array, store it in current node of + segment tree and return*/ + + if (ss == se) + st.stt[si] = ss; + else + { +/* If there are more than one elements, then recur for left and + right subtrees and store the minimum of two values in this node*/ + + int mid = (ss + se) / 2; + constructSTUtil(si * 2 + 1, ss, mid, arr, st); + constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); + if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) + st.stt[si] = st.stt[2 * si + 1]; + else + st.stt[si] = st.stt[2 * si + 2]; + } + } + /* Function to construct segment tree from given array. This function + allocates memory for segment tree and calls constructSTUtil() to + fill the allocated memory */ + + int constructST(int arr[], int n) + { +/* Allocate memory for segment tree + Height of segment tree*/ + + int x = Log2(n) + 1; +/* Maximum size of segment tree + 2*pow(2,x) -1*/ + +int max_size = 2 * (1 << x) - 1; + sc.stt = new int[max_size]; +/* Fill the allocated memory st*/ + + constructSTUtil(0, 0, n - 1, arr, sc); +/* Return the constructed segment tree*/ + + return sc.st; + } +/* Recursive version of the Euler tour of T*/ + + void eulerTour(Node node, int l) + { + /* if the passed node exists */ + + if (node != null) + { +/*insert in euler array*/ + +euler[fill] = node.data; +/*insert l in level array*/ + +level[fill] = l; +/*increment index*/ + +fill++; + /* if unvisited, mark first occurrence */ + + if (f_occur[node.data] == -1) + f_occur[node.data] = fill - 1; + /* tour left subtree if exists, and remark euler + and level arrays for parent on return */ + + if (node.left != null) + { + eulerTour(node.left, l + 1); + euler[fill] = node.data; + level[fill] = l; + fill++; + } + /* tour right subtree if exists, and remark euler + and level arrays for parent on return */ + + if (node.right != null) + { + eulerTour(node.right, l + 1); + euler[fill] = node.data; + level[fill] = l; + fill++; + } + } + } +/* returns LCA of node n1 and n2 assuming they are present in tree*/ + + int findLCA(Node node, int u, int v) + { + /* Mark all nodes unvisited. Note that the size of + firstOccurrence is 1 as node values which vary from + 1 to 9 are used as indexes */ + + Arrays.fill(f_occur, -1); + /* To start filling euler and level arrays from index 0 */ + + fill = 0; + /* Start Euler tour with root node on level 0 */ + + eulerTour(root, 0); + /* construct segment tree on level array */ + + sc.st = constructST(level, 2 * v - 1); + /* If v before u in Euler tour. For RMQ to work, first + parameter 'u' must be smaller than second 'v' */ + + if (f_occur[u] > f_occur[v]) + u = swap(u, u = v); +/* Starting and ending indexes of query range*/ + + int qs = f_occur[u]; + int qe = f_occur[v]; +/* query for index of LCA in tour*/ + + int index = RMQ(sc, 2 * v - 1, qs, qe); + /* return LCA node */ + + return euler[index]; + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); +/* Let us create the Binary Tree as shown in the diagram.*/ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.right.left = new Node(8); + tree.root.left.right.right = new Node(9); + int u = 4, v = 9; + System.out.println(""The LCA of node "" + u + "" and "" + v + "" is "" + + tree.findLCA(tree.root, u, v)); + } +}", +Smallest Difference pair of values between two unsorted Arrays,"/*Java Code to find Smallest +Difference between two Arrays*/ + +import java.util.*; + +class GFG +{ + +/* function to calculate Small + result between two arrays*/ + + static int findSmallestDifference(int A[], int B[], + int m, int n) + { +/* Sort both arrays + using sort function*/ + + Arrays.sort(A); + Arrays.sort(B); + + int a = 0, b = 0; + +/* Initialize result as max value*/ + + int result = Integer.MAX_VALUE; + +/* Scan Both Arrays upto + sizeof of the Arrays*/ + + while (a < m && b < n) + { + if (Math.abs(A[a] - B[b]) < result) + result = Math.abs(A[a] - B[b]); + +/* Move Smaller Value*/ + + if (A[a] < B[b]) + a++; + + else + b++; + } + +/* return final sma result*/ + + return result; + } + +/* Driver Code*/ + + public static void main(String[] args) + { +/* Input given array A*/ + + int A[] = {1, 2, 11, 5}; + +/* Input given array B*/ + + int B[] = {4, 12, 19, 23, 127, 235}; + + +/* Calculate size of Both arrays*/ + + int m = A.length; + int n = B.length; + +/* Call function to + print smallest result*/ + + System.out.println(findSmallestDifference + (A, B, m, n)); + + } +} + +"," '''Python 3 Code to find +Smallest Difference between +two Arrays''' + +import sys + + '''function to calculate +Small result between +two arrays''' + +def findSmallestDifference(A, B, m, n): + + ''' Sort both arrays + using sort function''' + + A.sort() + B.sort() + + a = 0 + b = 0 + + ''' Initialize result as max value''' + + result = sys.maxsize + + ''' Scan Both Arrays upto + sizeof of the Arrays''' + + while (a < m and b < n): + + if (abs(A[a] - B[b]) < result): + result = abs(A[a] - B[b]) + + ''' Move Smaller Value''' + + if (A[a] < B[b]): + a += 1 + + else: + b += 1 + ''' return final sma result''' + + return result + + '''Driver Code''' + + + '''Input given array A''' + +A = [1, 2, 11, 5] + + '''Input given array B''' + +B = [4, 12, 19, 23, 127, 235] + + '''Calculate size of Both arrays''' + +m = len(A) +n = len(B) + + '''Call function to +print smallest result''' + +print(findSmallestDifference(A, B, m, n)) + + +" +m Coloring Problem | Backtracking-5,"public class GFG +{ +/* Number of vertices in the graph*/ + + static int V = 4; + /* A utility function to print solution */ + + static void printSolution(int[] color) + { + System.out.println(""Solution Exists:"" + + "" Following are the assigned colors ""); + for (int i = 0; i < V; i++) + System.out.print("" "" + color[i]); + System.out.println(); + } +/* check if the colored + graph is safe or not*/ + + static boolean isSafe(boolean[][] graph, int[] color) + { +/* check for every edge*/ + + for (int i = 0; i < V; i++) + for (int j = i + 1; j < V; j++) + if (graph[i][j] && color[j] == color[i]) + return false; + return true; + } + /* This function solves the m Coloring + problem using recursion. It returns + false if the m colours cannot be assigned, + otherwise, return true and prints + assignments of colours to all vertices. + Please note that there may be more than + one solutions, this function prints one + of the feasible solutions.*/ + + static boolean graphColoring(boolean[][] graph, int m, + int i, int[] color) + { +/* if current index reached end*/ + + if (i == V) { +/* if coloring is safe*/ + + if (isSafe(graph, color)) + { +/* Print the solution*/ + + printSolution(color); + return true; + } + return false; + } +/* Assign each color from 1 to m*/ + + for (int j = 1; j <= m; j++) + { + color[i] = j; +/* Recur of the rest vertices*/ + + if (graphColoring(graph, m, i + 1, color)) + return true; + color[i] = 0; + } + return false; + } +/* Driver code*/ + + public static void main(String[] args) + { + /* Create following graph and + test whether it is 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */ + + boolean[][] graph = { + { false, true, true, true }, + { true, false, true, false }, + { true, true, false, true }, + { true, false, true, false }, + }; +/*Number of colors*/ + +int m = 3; +/* Initialize all color values as 0. + This initialization is needed + correct functioning of isSafe()*/ + + int[] color = new int[V]; + for (int i = 0; i < V; i++) + color[i] = 0; + if (!graphColoring(graph, m, 0, color)) + System.out.println(""Solution does not exist""); + } +}"," '''/* A utility function to prsolution */''' + +def printSolution(color): + print(""Solution Exists:"" "" Following are the assigned colors "") + for i in range(4): + print(color[i],end="" "") + '''check if the colored +graph is safe or not''' + +def isSafe(graph, color): + ''' check for every edge''' + + for i in range(4): + for j in range(i + 1, 4): + if (graph[i][j] and color[j] == color[i]): + return False + return True + '''/* This function solves the m Coloring +problem using recursion. It returns +false if the m colours cannot be assigned, +otherwise, return true and prints +assignments of colours to all vertices. +Please note that there may be more than +one solutions, this function prints one +of the feasible solutions.*/''' + +def graphColoring(graph, m, i, color): + ''' if current index reached end''' + + if (i == 4): + ''' if coloring is safe''' + + if (isSafe(graph, color)): + ''' Prthe solution''' + + printSolution(color) + return True + return False + ''' Assign each color from 1 to m''' + + for j in range(1, m + 1): + color[i] = j + ''' Recur of the rest vertices''' + + if (graphColoring(graph, m, i + 1, color)): + return True + color[i] = 0 + return False + '''Driver code''' + +if __name__ == '__main__': + ''' /* Create following graph and + test whether it is 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */''' + + graph = [ + [ 0, 1, 1, 1 ], + [ 1, 0, 1, 0 ], + [ 1, 1, 0, 1 ], + [ 1, 0, 1, 0 ], + ] + '''Number of colors''' + + m = 3 + ''' Initialize all color values as 0. + This initialization is needed + correct functioning of isSafe()''' + + color = [0 for i in range(4)] + if (not graphColoring(graph, m, 0, color)): + print (""Solution does not exist"")" +Find lost element from a duplicated array,"/*Java program to find missing element +from one array such that it has all +elements of other array except one. +Elements in two arrays can be in any order.*/ + + +import java.io.*; +class Missing { + +/* This function mainly does XOR of + all elements of arr1[] and arr2[]*/ + + void findMissing(int arr1[], int arr2[], + int M, int N) + { + if (M != N - 1 && N != M - 1) { + System.out.println(""Invalid Input""); + return; + } + +/* Do XOR of all element*/ + + int res = 0; + for (int i = 0; i < M; i++) + res = res ^ arr1[i]; + for (int i = 0; i < N; i++) + res = res ^ arr2[i]; + + System.out.println(""Missing element is "" + + res); + } + +/* Driver Code*/ + + public static void main(String args[]) + { + Missing obj = new Missing(); + int arr1[] = { 4, 1, 5, 9, 7 }; + int arr2[] = { 7, 5, 9, 4 }; + int M = arr1.length; + int N = arr2.length; + obj.findMissing(arr1, arr2, M, N); + } +} + + +"," '''Python 3 program to find +missing element from one array +such that it has all elements +of other array except +one. Elements in two arrays +can be in any order.''' + + + '''This function mainly does XOR of all elements +of arr1[] and arr2[]''' + +def findMissing(arr1,arr2, M, N): + if (M != N-1 and N != M-1): + + print(""Invalid Input"") + return + + + ''' Do XOR of all element''' + + res = 0 + for i in range(0,M): + res = res^arr1[i]; + for i in range(0,N): + res = res^arr2[i] + + print(""Missing element is"",res) + + '''Driver Code''' + +arr1 = [4, 1, 5, 9, 7] +arr2 = [7, 5, 9, 4] +M = len(arr1) +N = len(arr2) +findMissing(arr1, arr2, M, N) + + +" +Sum of all leaf nodes of binary tree,"/*Java program to find sum of +all leaf nodes of binary tree*/ + +public class GFG { +/* user define class node*/ + + static class Node{ + int data; + Node left, right; +/* constructor*/ + + Node(int data){ + this.data = data; + left = null; + right = null; + } + } + static int sum; +/* utility function which calculates + sum of all leaf nodes*/ + + static void leafSum(Node root){ + if (root == null) + return; +/* add root data to sum if + root is a leaf node*/ + + if (root.left == null && root.right == null) + sum += root.data; +/* propagate recursively in left + and right subtree*/ + + leafSum(root.left); + leafSum(root.right); + } +/* driver program*/ + + public static void main(String args[]) + { +/* construct binary tree*/ + + Node root = new Node(1); + root.left = new Node(2); + root.left.left = new Node(4); + root.left.right = new Node(5); + root.right = new Node(3); + root.right.right = new Node(7); + root.right.left = new Node(6); + root.right.left.right = new Node(8); +/* variable to store sum of leaf nodes*/ + + sum = 0; + leafSum(root); + System.out.println(sum); + } +}"," '''Python3 Program to find the +sum of leaf nodes of a binary tree''' + + '''Class for node creation''' + +class Node: + + ''' constructor ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Utility function to calculate +the sum of all leaf nodes''' + +def leafSum(root): + global total + if root is None: + return + + ''' add root data to sum if + root is a leaf node ''' + + if (root.left is None and root.right is None): + total += root.data + ''' propagate recursively in left + and right subtree ''' + + leafSum(root.left) + leafSum(root.right) '''Driver Code''' '''Binary tree Fromation''' + +if __name__=='__main__': + root = Node(1) + root.left = Node(2) + root.left.left = Node(4) + root.left.right = Node(5) + root.right = Node(3) + root.right.right = Node(7) + root.right.left = Node(6) + root.right.left.right = Node(8) + '''Variable to store the sum of leaf nodes''' + + total = 0 + leafSum(root) + print(total) +" +Find a rotation with maximum hamming distance,"/*Java program to Find another array +such that the hamming distance +from the original array is maximum*/ + +class GFG +{ +/*Return the maximum hamming +distance of a rotation*/ + +static int maxHamming(int arr[], int n) +{ +/* arr[] to brr[] two times so that + we can traverse through all rotations.*/ + + int brr[]=new int[2 *n + 1]; + for (int i = 0; i < n; i++) + brr[i] = arr[i]; + for (int i = 0; i < n; i++) + brr[n+i] = arr[i]; +/* We know hamming distance with + 0 rotation would be 0.*/ + + int maxHam = 0; +/* We try other rotations one by one + and compute Hamming distance + of every rotation*/ + + for (int i = 1; i < n; i++) + { + int currHam = 0; + for (int j = i, k=0; j < (i + n); j++, + k++) + if (brr[j] != arr[k]) + currHam++; +/* We can never get more than n.*/ + + if (currHam == n) + return n; + maxHam = Math.max(maxHam, currHam); + } + return maxHam; +} +/*driver code*/ + +public static void main (String[] args) +{ + int arr[] = {2, 4, 6, 8}; + int n = arr.length; + System.out.print(maxHamming(arr, n)); +} +}"," '''Python3 code to Find another array +such that the hamming distance +from the original array is maximum + ''' '''Return the maximum hamming +distance of a rotation''' + +def maxHamming( arr , n ): + ''' arr[] to brr[] two times so + that we can traverse through + all rotations.''' + + brr = [0] * (2 * n + 1) + for i in range(n): + brr[i] = arr[i] + for i in range(n): + brr[n+i] = arr[i] + ''' We know hamming distance + with 0 rotation would be 0.''' + + maxHam = 0 + ''' We try other rotations one by + one and compute Hamming + distance of every rotation''' + + for i in range(1, n): + currHam = 0 + k = 0 + for j in range(i, i + n): + if brr[j] != arr[k]: + currHam += 1 + k = k + 1 + ''' We can never get more than n.''' + + if currHam == n: + return n + maxHam = max(maxHam, currHam) + return maxHam + '''driver program''' + +arr = [2, 4, 6, 8] +n = len(arr) +print(maxHamming(arr, n))" +Equilibrium index of an array,"/*Java program to find equilibrium +index of an array*/ + +class EquilibriumIndex { + /* function to find the equilibrium index*/ + + int equilibrium(int arr[], int n) + { +/*initialize sum of whole array*/ + +int sum = 0; +/*initialize leftsum*/ + +int leftsum = 0; + /* Find sum of the whole array */ + + for (int i = 0; i < n; ++i) + sum += arr[i]; + for (int i = 0; i < n; ++i) { +/*sum is now right sum for index i*/ + +sum -= arr[i]; + if (leftsum == sum) + return i; + leftsum += arr[i]; + } + /* If no equilibrium index found, then return 0 */ + + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + EquilibriumIndex equi = new EquilibriumIndex(); + int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; + int arr_size = arr.length; + System.out.println(""First equilibrium index is "" + + equi.equilibrium(arr, arr_size)); + } +}"," '''Python program to find the equilibrium +index of an array''' + + '''function to find the equilibrium index''' + +def equilibrium(arr): ''' finding the sum of whole array''' + + total_sum = sum(arr) + leftsum = 0 + for i, num in enumerate(arr): + ''' total_sum is now right sum + for index i''' + + total_sum -= num + if leftsum == total_sum: + return i + leftsum += num + ''' If no equilibrium index found, + then return -1''' + + return -1 + '''Driver code''' + +arr = [-7, 1, 5, 2, -4, 3, 0] +print ('First equilibrium index is ', + equilibrium(arr))" +Minimum edge reversals to make a root,"/*Java program to find min edge reversal to +make every node reachable from root*/ + +import java.util.*; +class GFG +{ +/* pair class*/ + + static class pair + { + int first,second; + pair(int a ,int b) + { + first = a; + second = b; + } + } +/*method to dfs in tree and populates disRev values*/ + +static int dfs(Vector> g, + pair disRev[], boolean visit[], int u) +{ +/* visit current node*/ + + visit[u] = true; + int totalRev = 0; +/* looping over all neighbors*/ + + for (int i = 0; i < g.get(u).size(); i++) + { + int v = g.get(u).get(i).first; + if (!visit[v]) + { +/* distance of v will be one more than distance of u*/ + + disRev[v].first = disRev[u].first + 1; +/* initialize back edge count same as + parent node's count*/ + + disRev[v].second = disRev[u].second; +/* if there is a reverse edge from u to i, + then only update*/ + + if (g.get(u).get(i).second!=0) + { + disRev[v].second = disRev[u].second + 1; + totalRev++; + } + totalRev += dfs(g, disRev, visit, v); + } + } +/* return total reversal in subtree rooted at u*/ + + return totalRev; +} +/*method prints root and minimum number of edge reversal*/ + +static void printMinEdgeReverseForRootNode(int edges[][], int e) +{ +/* number of nodes are one more than number of edges*/ + + int V = e + 1; +/* data structure to store directed tree*/ + + Vector> g=new Vector>(); + for(int i = 0; i < V + 1; i++) + g.add(new Vector()); +/* disRev stores two values - distance and back + edge count from root node*/ + + pair disRev[] = new pair[V]; + for(int i = 0; i < V; i++) + disRev[i] = new pair(0, 0); + boolean visit[] = new boolean[V]; + int u, v; + for (int i = 0; i < e; i++) + { + u = edges[i][0]; + v = edges[i][1]; +/* add 0 weight in direction of u to v*/ + + g.get(u).add(new pair(v, 0)); +/* add 1 weight in reverse direction*/ + + g.get(v).add(new pair(u, 1)); + } +/* initialize all variables*/ + + for (int i = 0; i < V; i++) + { + visit[i] = false; + disRev[i].first = disRev[i].second = 0; + } + int root = 0; +/* dfs populates disRev data structure and + store total reverse edge counts*/ + + int totalRev = dfs(g, disRev, visit, root); +/* UnComment below lines to print each node's + distance and edge reversal count from root node*/ + + /* + for (int i = 0; i < V; i++) + { + cout << i << "" : "" << disRev[i].first + << "" "" << disRev[i].second << endl; + } + */ + + int res = Integer.MAX_VALUE; +/* loop over all nodes to choose minimum edge reversal*/ + + for (int i = 0; i < V; i++) + { +/* (reversal in path to i) + (reversal + in all other tree parts)*/ + + int edgesToRev = (totalRev - disRev[i].second) + + (disRev[i].first - disRev[i].second); +/* choose minimum among all values*/ + + if (edgesToRev < res) + { + res = edgesToRev; + root = i; + } + } +/* print the designated root and total + edge reversal made*/ + + System.out.println(root + "" "" + res ); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int edges[][] = + { + {0, 1}, + {2, 1}, + {3, 2}, + {3, 4}, + {5, 4}, + {5, 6}, + {7, 6} + }; + int e = edges.length; + printMinEdgeReverseForRootNode(edges, e); +} +}"," '''Python3 program to find min edge reversal +to make every node reachable from root''' + +import sys + '''Method to dfs in tree and populates +disRev values''' + +def dfs(g, disRev, visit, u): + ''' Visit current node''' + + visit[u] = True + totalRev = 0 + ''' Looping over all neighbors''' + + for i in range(len(g[u])): + v = g[u][i][0] + if (not visit[v]): + ''' Distance of v will be one more + than distance of u''' + + disRev[v][0] = disRev[u][0] + 1 + ''' Initialize back edge count same as + parent node's count''' + + disRev[v][1] = disRev[u][1] + ''' If there is a reverse edge from u to i, + then only update''' + + if (g[u][i][1]): + disRev[v][1] = disRev[u][1] + 1 + totalRev += 1 + totalRev += dfs(g, disRev, visit, v) + ''' Return total reversal in subtree rooted at u''' + + return totalRev + '''Method prints root and minimum number of +edge reversal''' + +def printMinEdgeReverseForRootNode(edges, e): + ''' Number of nodes are one more than + number of edges''' + + V = e + 1 + ''' Data structure to store directed tree''' + + g = [[] for i in range(V)] + ''' disRev stores two values - distance + and back edge count from root node''' + + disRev = [[0, 0] for i in range(V)] + visit = [False for i in range(V)] + for i in range(e): + u = edges[i][0] + v = edges[i][1] ''' Add 0 weight in direction of u to v''' + + g[u].append([v, 0]) + ''' Add 1 weight in reverse direction''' + + g[v].append([u, 1]) + ''' Initialize all variables''' + + for i in range(V): + visit[i] = False + disRev[i][0] = disRev[i][1] = 0 + root = 0 + ''' dfs populates disRev data structure and + store total reverse edge counts''' + + totalRev = dfs(g, disRev, visit, root) + ''' UnComment below lines to preach node's + distance and edge reversal count from root node''' '''for (i = 0 i < V i++) + { + cout << i << "" : "" << disRev[i][0] + << "" "" << disRev[i][1] << endl + }''' + + res = sys.maxsize + ''' Loop over all nodes to choose + minimum edge reversal''' + + for i in range(V): + ''' (reversal in path to i) + (reversal + in all other tree parts)''' + + edgesToRev = ((totalRev - disRev[i][1]) + + (disRev[i][0] - disRev[i][1])) + ''' Choose minimum among all values''' + + if (edgesToRev < res): + res = edgesToRev + root = i + ''' Print the designated root and total + edge reversal made''' + + print(root, res) + '''Driver code''' + +if __name__ == '__main__': + edges = [ [ 0, 1 ], [ 2, 1 ], + [ 3, 2 ], [ 3, 4 ], + [ 5, 4 ], [ 5, 6 ], + [ 7, 6 ] ] + e = len(edges) + printMinEdgeReverseForRootNode(edges, e)" +Number of pairs with maximum sum,"/*Java program to count pairs +with maximum sum.*/ + +class GFG { + +/*function to find the number of +maximum pair sums*/ + +static int sum(int a[], int n) +{ +/* traverse through all the pairs*/ + + int maxSum = Integer.MIN_VALUE; + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + maxSum = Math.max(maxSum, a[i] + + a[j]); + +/* traverse through all pairs and + keep a count of the number of + maximum pairs*/ + + int c = 0; + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + if (a[i] + a[j] == maxSum) + c++; + return c; +} + +/*driver program to test the above function*/ + +public static void main(String[] args) +{ + int array[] = { 1, 1, 1, 2, 2, 2 }; + int n = array.length; + System.out.println(sum(array, n)); +} +} + + +"," '''Python program to count pairs with +maximum sum''' + + +def _sum( a, n): + + ''' traverse through all the pairs''' + + maxSum = -9999999 + for i in range(n): + for j in range(n): + maxSum = max(maxSum, a[i] + a[j]) + + ''' traverse through all pairs and + keep a count of the number + of maximum pairs''' + + c = 0 + for i in range(n): + for j in range(i+1, n): + if a[i] + a[j] == maxSum: + c+=1 + return c + + '''driver code''' + +array = [ 1, 1, 1, 2, 2, 2 ] +n = len(array) +print(_sum(array, n)) + + +" +Inorder Tree Traversal without recursion and without stack!,"/*Java program to print inorder +traversal without recursion +and stack*/ + +/* A binary tree tNode has data, + a pointer to left child + and a pointer to right child */ + +class tNode { + int data; + tNode left, right; + tNode(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + tNode root; + /* Function to traverse a + binary tree without recursion + and without stack */ + + void MorrisTraversal(tNode root) + { + tNode current, pre; + if (root == null) + return; + current = root; + while (current != null) + { + if (current.left == null) + { + System.out.print(current.data + "" ""); + current = current.right; + } + else { + /* Find the inorder + predecessor of current + */ + + pre = current.left; + while (pre.right != null + && pre.right != current) + pre = pre.right; + /* Make current as right + child of its + * inorder predecessor */ + + if (pre.right == null) { + pre.right = current; + current = current.left; + } + /* Revert the changes made + in the 'if' part + to restore the original + tree i.e., fix + the right child of predecessor*/ + + else + { + pre.right = null; + System.out.print(current.data + "" ""); + current = current.right; + } + } + } + }/* Driver Code*/ + + public static void main(String args[]) + { + /* Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + */ + + BinaryTree tree = new BinaryTree(); + tree.root = new tNode(1); + tree.root.left = new tNode(2); + tree.root.right = new tNode(3); + tree.root.left.left = new tNode(4); + tree.root.left.right = new tNode(5); + tree.MorrisTraversal(tree.root); + } +}"," '''Python program to do Morris inOrder Traversal: +inorder traversal without recursion and without stack''' + + + '''A binary tree node''' +class Node: + def __init__(self, data, left=None, right=None): + self.data = data + self.left = left + self.right = right + + '''Generator function for + iterative inorder tree traversal''' +def morris_traversal(root): + current = root + while current is not None: + if current.left is None: + yield current.data + current = current.right + else: + ''' Find the inorder + predecessor of current''' + + pre = current.left + while pre.right is not None and pre.right is not current: + pre = pre.right + + ''' Make current as right + child of its inorder predecessor''' + if pre.right is None: + pre.right = current + current = current.left + ''' Revert the changes made + in the 'if' part to restore the + original tree. i.e., fix + the right child of predecessor''' + + else: + pre.right = None + yield current.data + current = current.right + '''Driver code''' + + ''' +Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + ''' + +root = Node(1, + right=Node(3), + left=Node(2, + left=Node(4), + right=Node(5) + ) + ) +for v in morris_traversal(root): + print(v, end=' ')" +Find maximum of minimum for every window size in a given array,"/*A naive method to find maximum of +minimum of all windows of different sizes*/ + +class Test { + static int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; + static void printMaxOfMin(int n) + { +/* Consider all windows of different + sizes starting from size 1*/ + + for (int k = 1; k <= n; k++) { +/* Initialize max of min for current + window size k*/ + + int maxOfMin = Integer.MIN_VALUE; +/* Traverse through all windows of + current size k*/ + + for (int i = 0; i <= n - k; i++) { +/* Find minimum of current window*/ + + int min = arr[i]; + for (int j = 1; j < k; j++) { + if (arr[i + j] < min) + min = arr[i + j]; + } +/* Update maxOfMin if required*/ + + if (min > maxOfMin) + maxOfMin = min; + } +/* Print max of min for current + window size*/ + + System.out.print(maxOfMin + "" ""); + } + } +/* Driver method*/ + + public static void main(String[] args) + { + printMaxOfMin(arr.length); + } +}"," '''A naive method to find maximum of +minimum of all windows of different sizes''' + +INT_MIN = -1000000 +def printMaxOfMin(arr, n): + ''' Consider all windows of different + sizes starting from size 1''' + + for k in range(1, n + 1): + ''' Initialize max of min for + current window size k''' + + maxOfMin = INT_MIN; + ''' Traverse through all windows + of current size k''' + + for i in range(n - k + 1): + ''' Find minimum of current window''' + + min = arr[i] + for j in range(k): + if (arr[i + j] < min): + min = arr[i + j] + ''' Update maxOfMin if required''' + + if (min > maxOfMin): + maxOfMin = min + ''' Print max of min for current window size''' + + print(maxOfMin, end = "" "") + '''Driver Code''' + +arr = [10, 20, 30, 50, 10, 70, 30] +n = len(arr) +printMaxOfMin(arr, n)" +Remove all leaf nodes from the binary search tree,"/*Java program to delete leaf Node from +binary search tree.*/ + +class GfG { + static class Node { + int data; + Node left; + Node right; + } +/* Create a newNode in binary search tree.*/ + + static Node newNode(int data) + { + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; + } +/* Insert a Node in binary search tree.*/ + + static Node insert(Node root, int data) + { + if (root == null) + return newNode(data); + if (data < root.data) + root.left = insert(root.left, data); + else if (data > root.data) + root.right = insert(root.right, data); + return root; + } +/* Function for inorder traversal in a BST.*/ + + static void inorder(Node root) + { + if (root != null) { + inorder(root.left); + System.out.print(root.data + "" ""); + inorder(root.right); + } + } +/* Delete leaf nodes from binary search tree.*/ + + static Node leafDelete(Node root) + { + if (root == null) { + return null; + } + if (root.left == null && root.right == null) { + return null; + } +/* Else recursively delete in left and right + subtrees.*/ + + root.left = leafDelete(root.left); + root.right = leafDelete(root.right); + return root; + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = null; + root = insert(root, 20); + insert(root, 10); + insert(root, 5); + insert(root, 15); + insert(root, 30); + insert(root, 25); + insert(root, 35); + System.out.println(""Inorder before Deleting the leaf Node. ""); + inorder(root); + System.out.println(); + leafDelete(root); + System.out.println(""INorder after Deleting the leaf Node. ""); + inorder(root); + } +}"," '''Python 3 program to delete leaf +Node from binary search tree. +Create a newNode in binary search tree.''' + +class newNode: + ''' Constructor to create a new node''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Insert a Node in binary search tree.''' + +def insert(root, data): + if root == None: + return newNode(data) + if data < root.data: + root.left = insert(root.left, data) + elif data > root.data: + root.right = insert(root.right, data) + return root + '''Function for inorder traversal in a BST.''' + +def inorder(root): + if root != None: + inorder(root.left) + print(root.data, end = "" "") + inorder(root.right) + '''Delete leaf nodes from binary search tree.''' + +def leafDelete(root): + if root == None: + return None + if root.left == None and root.right == None: + return None + ''' Else recursively delete in left + and right subtrees.''' + + root.left = leafDelete(root.left) + root.right = leafDelete(root.right) + return root + '''Driver code''' + +if __name__ == '__main__': + root = None + root = insert(root, 20) + insert(root, 10) + insert(root, 5) + insert(root, 15) + insert(root, 30) + insert(root, 25) + insert(root, 35) + print(""Inorder before Deleting the leaf Node."") + inorder(root) + leafDelete(root) + print() + print(""INorder after Deleting the leaf Node."") + inorder(root)" +Minimum number of subsets with distinct elements,"/*A hashing based solution to find the +minimum number of subsets of a set +such that every subset contains distinct +elements.*/ + +import java.util.HashMap; +import java.util.Map; +class GFG +{ +/*Function to count subsets such that all +subsets have distinct elements.*/ + +static int subset(int arr[], int n) +{ +/* Traverse the input array and + store frequencies of elements*/ + + HashMap mp = new HashMap<>(); + for (int i = 0; i < n; i++) + mp.put(arr[i],mp.get(arr[i]) == null?1:mp.get(arr[i])+1); +/* Find the maximum value in map.*/ + + int res = 0; + for (Map.Entry entry : mp.entrySet()) + res = Math.max(res, entry.getValue()); + return res; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; + int n = arr.length; + System.out.println( subset(arr, n)); +} +}"," '''A hashing based solution to find the +minimum number of subsets of a set such +that every subset contains distinct +elements. + ''' '''Function to count subsets such that +all subsets have distinct elements.''' + +def subset(arr, n): + ''' Traverse the input array and + store frequencies of elements''' + + mp = {i:0 for i in range(10)} + for i in range(n): + mp[arr[i]] += 1 + ''' Find the maximum value in map.''' + + res = 0 + for key, value in mp.items(): + res = max(res, value) + return res + '''Driver code''' + +if __name__ == '__main__': + arr = [5, 6, 9, 3, 4, 3, 4] + n = len(arr) + print(subset(arr, n))" +Optimized Naive Algorithm for Pattern Searching,"/* Java program for A modified Naive Pattern Searching +algorithm that is optimized for the cases when all +characters of pattern are different */ + +class GFG +{ +/* A modified Naive Pettern Searching +algorithn that is optimized for the +cases when all characters of pattern are different */ + +static void search(String pat, String txt) +{ + int M = pat.length(); + int N = txt.length(); + int i = 0; + while (i <= N - M) + { + int j; + /* For current index i, check for pattern match */ + + for (j = 0; j < M; j++) + if (txt.charAt(i + j) != pat.charAt(j)) + break; +/*if pat[0...M-1] = txt[i, i+1, ...i+M-1]*/ + +if (j == M) + { + System.out.println(""Pattern found at index ""+i); + i = i + M; + } + else if (j == 0) + i = i + 1; + else +/*slide the pattern by j*/ + +i = i + j; + } +} +/* Driver code*/ + +public static void main (String[] args) +{ + String txt = ""ABCEABCDABCEABCD""; + String pat = ""ABCD""; + search(pat, txt); +} +}"," '''Python program for A modified Naive Pattern Searching +algorithm that is optimized for the cases when all +characters of pattern are different''' + +def search(pat, txt): + M = len(pat) + N = len(txt) + i = 0 + while i <= N-M: + ''' For current index i, check for pattern match''' + + for j in xrange(M): + if txt[i+j] != pat[j]: + break + j += 1 + '''if pat[0...M-1] = txt[i,i+1,...i+M-1]''' + + if j==M: + print ""Pattern found at index "" + str(i) + i = i + M + elif j==0: + i = i + 1 + else: + '''slide the pattern by j''' + + i = i+ j + '''Driver program to test the above function''' + +txt = ""ABCEABCDABCEABCD"" +pat = ""ABCD"" +search(pat, txt)" +QuickSort,"/*Java implementation of QuickSort*/ + +import java.io.*; +class GFG{ +/*A utility function to swap two elements*/ + +static void swap(int[] arr, int i, int j) +{ + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} +/* This function takes last element as pivot, places + the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) + to left of pivot and all greater elements to right + of pivot */ + +static int partition(int[] arr, int low, int high) +{ +/* pivot*/ + + int pivot = arr[high]; +/* Index of smaller element and + indicates the right position + of pivot found so far*/ + + int i = (low - 1); + for(int j = low; j <= high - 1; j++) + { +/* If current element is smaller + than the pivot*/ + + if (arr[j] < pivot) + { +/* Increment index of + smaller element*/ + + i++; + swap(arr, i, j); + } + } + swap(arr, i + 1, high); + return (i + 1); +} +/* The main function that implements QuickSort + arr[] --> Array to be sorted, + low --> Starting index, + high --> Ending index + */ + +static void quickSort(int[] arr, int low, int high) +{ + if (low < high) + { +/* pi is partitioning index, arr[p] + is now at right place*/ + + int pi = partition(arr, low, high); +/* Separately sort elements before + partition and after partition*/ + + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} +/*Function to print an array*/ + +static void printArray(int[] arr, int size) +{ + for(int i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int[] arr = { 10, 7, 8, 9, 1, 5 }; + int n = arr.length; + quickSort(arr, 0, n - 1); + System.out.println(""Sorted array: ""); + printArray(arr, n); +} +}", +Number of cells a queen can move with obstacles on the chessborad,"/*Java program to find number of cells a +queen can move with obstacles on the +chessborad*/ + +import java.io.*; +class GFG { +/* Return the number of position a Queen + can move.*/ + + static int numberofPosition(int n, int k, int x, + int y, int obstPosx[], int obstPosy[]) + { +/* d11, d12, d21, d22 are for diagnoal distances. + r1, r2 are for vertical distance. + c1, c2 are for horizontal distance.*/ + + int d11, d12, d21, d22, r1, r2, c1, c2; +/* Initialise the distance to end of the board.*/ + + d11 = Math.min( x-1, y-1 ); + d12 = Math.min( n-x, n-y ); + d21 = Math.min( n-x, y-1 ); + d22 = Math.min( x-1, n-y ); + r1 = y-1; + r2 = n-y; + c1 = x-1; + c2 = n-x; +/* For each obstacle find the minimum distance. + If obstacle is present in any direction, + distance will be updated.*/ + + for (int i = 0; i < k; i++) + { + if ( x > obstPosx[i] && y > obstPosy[i] && + x-obstPosx[i] == y-obstPosy[i] ) + d11 = Math.min(d11, x-obstPosx[i]-1); + if ( obstPosx[i] > x && obstPosy[i] > y && + obstPosx[i]-x == obstPosy[i]-y ) + d12 = Math.min( d12, obstPosx[i]-x-1); + if ( obstPosx[i] > x && y > obstPosy[i] && + obstPosx[i]-x == y-obstPosy[i] ) + d21 = Math.min(d21, obstPosx[i]-x-1); + if ( x > obstPosx[i] && obstPosy[i] > y && + x-obstPosx[i] == obstPosy[i]-y ) + d22 = Math.min(d22, x-obstPosx[i]-1); + if ( x == obstPosx[i] && obstPosy[i] < y ) + r1 = Math.min(r1, y-obstPosy[i]-1); + if ( x == obstPosx[i] && obstPosy[i] > y ) + r2 = Math.min(r2, obstPosy[i]-y-1); + if ( y == obstPosy[i] && obstPosx[i] < x ) + c1 = Math.min(c1, x-obstPosx[i]-1); + if ( y == obstPosy[i] && obstPosx[i] > x ) + c2 = Math.min(c2, obstPosx[i]-x-1); + } + return d11 + d12 + d21 + d22 + r1 + r2 + c1 + c2; + } +/* Driver code*/ + + public static void main (String[] args) { +/*Chessboard size*/ + +int n = 8; +/*number of obstacles*/ + +int k = 1; +/*Queen x position*/ + +int Qposx = 4; +/*Queen y position*/ + +int Qposy = 4; +/*x position of obstacles*/ + +int obstPosx[] = { 3 }; +/*y position of obstacles*/ + +int obstPosy[] = { 5 }; + System.out.println(numberofPosition(n, k, Qposx, + Qposy, obstPosx, obstPosy)); + } +}", +Lowest Common Ancestor in a Binary Tree | Set 1,"/*Java implementation to find lowest common ancestor of +n1 and n2 using one traversal of binary tree +It also handles cases even when n1 and n2 are not there in Tree*/ + +/* Class containing left and right child of current node and key */ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +public class BinaryTree +{ +/* Root of the Binary Tree*/ + + Node root; + static boolean v1 = false, v2 = false; +/* This function returns pointer to LCA of two given + values n1 and n2. + v1 is set as true by this function if n1 is found + v2 is set as true by this function if n2 is found*/ + + Node findLCAUtil(Node node, int n1, int n2) + { +/* Base case*/ + + if (node == null) + return null; +/* Store result in temp, in case of key match so that we can search for other key also.*/ + + Node temp=null; +/* If either n1 or n2 matches with root's key, report the presence + by setting v1 or v2 as true and return root (Note that if a key + is ancestor of other, then the ancestor key becomes LCA)*/ + + if (node.data == n1) + { + v1 = true; + temp = node; + } + if (node.data == n2) + { + v2 = true; + temp = node; + } +/* Look for keys in left and right subtrees*/ + + Node left_lca = findLCAUtil(node.left, n1, n2); + Node right_lca = findLCAUtil(node.right, n1, n2); + if (temp != null) + return temp; +/* If both of the above calls return Non-NULL, then one key + is present in once subtree and other is present in other, + So this node is the LCA*/ + + if (left_lca != null && right_lca != null) + return node; +/* Otherwise check if left subtree or right subtree is LCA*/ + + return (left_lca != null) ? left_lca : right_lca; + } +/* Finds lca of n1 and n2 under the subtree rooted with 'node'*/ + + Node findLCA(int n1, int n2) + { +/* Initialize n1 and n2 as not visited*/ + + v1 = false; + v2 = false; +/* Find lca of n1 and n2 using the technique discussed above*/ + + Node lca = findLCAUtil(root, n1, n2); +/* Return LCA only if both n1 and n2 are present in tree*/ + + if (v1 && v2) + return lca; +/* Else return NULL*/ + + return null; + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + Node lca = tree.findLCA(4, 5); + if (lca != null) + System.out.println(""LCA(4, 5) = "" + lca.data); + else + System.out.println(""Keys are not present""); + lca = tree.findLCA(4, 10); + if (lca != null) + System.out.println(""LCA(4, 10) = "" + lca.data); + else + System.out.println(""Keys are not present""); + } +}"," ''' Program to find LCA of n1 and n2 using one traversal of + Binary tree +It handles all cases even when n1 or n2 is not there in tree + ''' + + '''A binary tree node''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''This function retturn pointer to LCA of two given values +n1 and n2 +v1 is set as true by this function if n1 is found +v2 is set as true by this function if n2 is found''' + +def findLCAUtil(root, n1, n2, v): + ''' Base Case''' + + if root is None: + return None + ''' IF either n1 or n2 matches ith root's key, report + the presence by setting v1 or v2 as true and return + root (Note that if a key is ancestor of other, then + the ancestor key becomes LCA)''' + + if root.key == n1 : + v[0] = True + return root + if root.key == n2: + v[1] = True + return root + ''' Look for keys in left and right subtree''' + + left_lca = findLCAUtil(root.left, n1, n2, v) + right_lca = findLCAUtil(root.right, n1, n2, v) + ''' If both of the above calls return Non-NULL, then one key + is present in once subtree and other is present in other, + So this node is the LCA''' + + if left_lca and right_lca: + return root + ''' Otherwise check if left subtree or right subtree is LCA''' + + return left_lca if left_lca is not None else right_lca + '''Returns true if key k is present in tree rooted with root''' + +def find(root, k): + if root is None: + return False + if (root.key == k or find(root.left, k) or + find(root.right, k)): + return True + return False + + '''This function returns LCA of n1 and n2 onlue if both +n1 and n2 are present in tree, otherwise returns None''' + +def findLCA(root, n1, n2): + ''' Initialize n1 and n2 as not visited''' + + v = [False, False] + ''' Find lac of n1 and n2 using the technique discussed above''' + + lca = findLCAUtil(root, n1, n2, v) + ''' Returns LCA only if both n1 and n2 are present in tree''' + + if (v[0] and v[1] or v[0] and find(lca, n2) or v[1] and + find(lca, n1)): + return lca + ''' Else return None''' + + return None + '''Driver program to test above function''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) +lca = findLCA(root, 4, 5) +if lca is not None: + print ""LCA(4, 5) = "", lca.key +else : + print ""Keys are not present"" +lca = findLCA(root, 4, 10) +if lca is not None: + print ""LCA(4,10) = "", lca.key +else: + print ""Keys are not present""" +Noble integers in an array (count of greater elements is equal to value),, +How to implement decrease key or change key in Binary Search Tree?,"/*Java program to demonstrate decrease +key operation on binary search tree*/ + +class GfG +{ +static class node +{ + int key; + node left, right; +} +static node root = null; +/*A utility function to +create a new BST node*/ + +static node newNode(int item) +{ + node temp = new node(); + temp.key = item; + temp.left = null; + temp.right = null; + return temp; +} +/*A utility function to +do inorder traversal of BST*/ + +static void inorder(node root) +{ + if (root != null) + { + inorder(root.left); + System.out.print(root.key + "" ""); + inorder(root.right); + } +} +/* A utility function to insert +a new node with given key in BST */ + +static node insert(node node, int key) +{ + /* If the tree is empty, return a new node */ + + if (node == null) return newNode(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + node.left = insert(node.left, key); + else + node.right = insert(node.right, key); + /* return the (unchanged) node pointer */ + + return node; +} +/* Given a non-empty binary search tree, +return the node with minimum key value +found in that tree. Note that the entire +tree does not need to be searched. */ + +static node minValueNode(node Node) +{ + node current = Node; + /* loop down to find the leftmost leaf */ + + while (current.left != null) + current = current.left; + return current; +} +/* Given a binary search tree and +a key, this function deletes the key +and returns the new root */ + +static node deleteNode(node root, int key) +{ +/* base case*/ + + if (root == null) return root; +/* If the key to be deleted is + smaller than the root's key, + then it lies in left subtree*/ + + if (key < root.key) + root.left = deleteNode(root.left, key); +/* If the key to be deleted is + greater than the root's key, + then it lies in right subtree*/ + + else if (key > root.key) + root.right = deleteNode(root.right, key); +/* if key is same as root's + key, then This is the node + to be deleted*/ + + else + { +/* node with only one child or no child*/ + + if (root.left == null) + { + node temp = root.right; + return temp; + } + else if (root.right == null) + { + node temp = root.left; + return temp; + } +/* node with two children: Get + the inorder successor (smallest + in the right subtree)*/ + + node temp = minValueNode(root.right); +/* Copy the inorder successor's + content to this node*/ + + root.key = temp.key; +/* Delete the inorder successor*/ + + root.right = deleteNode(root.right, temp.key); + } + return root; +} +/*Function to decrease a key +value in Binary Search Tree*/ + +static node changeKey(node root, int oldVal, int newVal) +{ +/* First delete old key value*/ + + root = deleteNode(root, oldVal); +/* Then insert new key value*/ + + root = insert(root, newVal); +/* Return new root*/ + + return root; +} +/*Driver code*/ + +public static void main(String[] args) +{ + /* Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80 */ + + root = insert(root, 50); + root = insert(root, 30); + root = insert(root, 20); + root = insert(root, 40); + root = insert(root, 70); + root = insert(root, 60); + root = insert(root, 80); + System.out.println(""Inorder traversal of the given tree""); + inorder(root); + root = changeKey(root, 40, 10); + /* BST is modified to + 50 + / \ + 30 70 + / / \ + 20 60 80 + / + 10 */ + + System.out.println(""\nInorder traversal of the modified tree ""); + inorder(root); +} +}"," '''Python3 program to demonstrate decrease key +operation on binary search tree + ''' '''A utility function to create a new BST node''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + '''A utility function to do inorder +traversal of BST''' + +def inorder(root): + if root != None: + inorder(root.left) + print(root.key,end="" "") + inorder(root.right) + '''A utility function to insert a new +node with given key in BST''' + +def insert(node, key): + ''' If the tree is empty, return a new node''' + + if node == None: + return newNode(key) + ''' Otherwise, recur down the tree''' + + if key < node.key: + node.left = insert(node.left, key) + else: + node.right = insert(node.right, key) + ''' return the (unchanged) node pointer''' + + return node + '''Given a non-empty binary search tree, return +the node with minimum key value found in that +tree. Note that the entire tree does not +need to be searched.''' + +def minValueNode(node): + current = node + ''' loop down to find the leftmost leaf''' + + while current.left != None: + current = current.left + return current + '''Given a binary search tree and a key, this +function deletes the key and returns the new root''' + +def deleteNode(root, key): + ''' base case''' + + if root == None: + return root + ''' If the key to be deleted is smaller than + the root's key, then it lies in left subtree''' + + if key < root.key: + root.left = deleteNode(root.left, key) + ''' If the key to be deleted is greater than + the root's key, then it lies in right subtree''' + + elif key > root.key: + root.right = deleteNode(root.right, key) + ''' if key is same as root's key, then + this is the node to be deleted''' + + else: + ''' node with only one child or no child''' + + if root.left == None: + temp = root.right + return temp + elif root.right == None: + temp = root.left + return temp + ''' node with two children: Get the inorder + successor (smallest in the right subtree)''' + + temp = minValueNode(root.right) + ''' Copy the inorder successor's content + to this node''' + + root.key = temp.key + ''' Delete the inorder successor''' + + root.right = deleteNode(root.right, temp.key) + return root + '''Function to decrease a key value in +Binary Search Tree''' + +def changeKey(root, oldVal, newVal): + ''' First delete old key value''' + + root = deleteNode(root, oldVal) + ''' Then insert new key value''' + + root = insert(root, newVal) + ''' Return new root''' + + return root + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create following BST + 50 + / \ + 30 70 + / \ / \ + 20 40 60 80''' + + root = None + root = insert(root, 50) + root = insert(root, 30) + root = insert(root, 20) + root = insert(root, 40) + root = insert(root, 70) + root = insert(root, 60) + root = insert(root, 80) + print(""Inorder traversal of the given tree"") + inorder(root) + root = changeKey(root, 40, 10) + print() + ''' BST is modified to + 50 + / \ + 30 70 + / / \ + 20 60 80 + / + 10 ''' + + print(""Inorder traversal of the modified tree"") + inorder(root)" +Print modified array after multiple array range increment operations,"/*Java implementation to increment values in the +given range by a value d for multiple queries*/ + +class GFG +{ + +/* structure to store the (start, end) + index pair for each query*/ + + static class query + { + int start, end; + + query(int start, int end) + { + this.start = start; + this.end = end; + } + } + +/* function to increment values in the given range + by a value d for multiple queries*/ + + public static void incrementByD(int[] arr, query[] q_arr, + int n, int m, int d) + { + int[] sum = new int[n]; + +/* for each (start, end) index pair, perform + the following operations on 'sum[]'*/ + + for (int i = 0; i < m; i++) + { + +/* increment the value at index 'start' + by the given value 'd' in 'sum[]'*/ + + sum[q_arr[i].start] += d; + +/* if the index '(end+1)' exists then + decrement the value at index '(end+1)' + by the given value 'd' in 'sum[]'*/ + + if ((q_arr[i].end + 1) < n) + sum[q_arr[i].end + 1] -= d; + } + +/* Now, perform the following operations: + accumulate values in the 'sum[]' array and + then add them to the corresponding indexes + in 'arr[]'*/ + + arr[0] += sum[0]; + for (int i = 1; i < n; i++) + { + sum[i] += sum[i - 1]; + arr[i] += sum[i]; + } + } + +/* function to print the elements of the given array*/ + + public static void printArray(int[] arr, int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } + +/* Driver code*/ + + public static void main(String[] args) + { + int[] arr = { 3, 5, 4, 8, 6, 1 }; + query[] q_arr = new query[5]; + q_arr[0] = new query(0, 3); + q_arr[1] = new query(4, 5); + q_arr[2] = new query(1, 4); + q_arr[3] = new query(0, 1); + q_arr[4] = new query(2, 5); + int n = arr.length; + int m = q_arr.length; + int d = 2; + System.out.println(""Original Array:""); + printArray(arr, n); + +/* modifying the array for multiple queries*/ + + incrementByD(arr, q_arr, n, m, d); + System.out.println(""\nModified Array:""); + printArray(arr, n); + } +} + + +"," '''Python3 implementation to increment +values in the given range by a value d +for multiple queries''' + + + '''structure to store the (start, end) +index pair for each query''' + + + '''function to increment values in the given range +by a value d for multiple queries''' + +def incrementByD(arr, q_arr, n, m, d): + + sum = [0 for i in range(n)] + + ''' for each (start, end) index pair perform + the following operations on 'sum[]''' + ''' + for i in range(m): + + ''' increment the value at index 'start' + by the given value 'd' in 'sum[]''' + ''' + sum[q_arr[i][0]] += d + + ''' if the index '(end+1)' exists then decrement + the value at index '(end+1)' by the given + value 'd' in 'sum[]''' + ''' + if ((q_arr[i][1] + 1) < n): + sum[q_arr[i][1] + 1] -= d + + ''' Now, perform the following operations: + accumulate values in the 'sum[]' array and + then add them to the corresponding indexes + in 'arr[]''' + ''' + arr[0] += sum[0] + for i in range(1, n): + sum[i] += sum[i - 1] + arr[i] += sum[i] + + '''function to print the elements +of the given array''' + +def printArray(arr, n): + + for i in arr: + print(i, end = "" "") + + '''Driver Code''' + +arr = [ 3, 5, 4, 8, 6, 1] + +q_arr = [[0, 3], [4, 5], [1, 4], + [0, 1], [2, 5]] + +n = len(arr) +m = len(q_arr) + +d = 2 + +print(""Original Array:"") +printArray(arr, n) + + '''modifying the array for multiple queries''' + +incrementByD(arr, q_arr, n, m, d) + +print(""\nModified Array:"") +printArray(arr, n) + + +" +Print a matrix in a spiral form starting from a point,"/*Java program to print a +matrix in spiral form*/ + +import java.io.*; +class GFG { +static void printSpiral(int [][]mat, int r, int c) +{ + int i, a = 0, b = 2; + int low_row = (0 > a) ? 0 : a; + int low_column = (0 > b) ? 0 : b - 1; + int high_row = ((a + 1) >= r) ? r - 1 : a + 1; + int high_column = ((b + 1) >= c) ? c - 1 : b + 1; + while ((low_row > 0 - r && low_column > 0 - c)) + { + for (i = low_column + 1; i <= high_column && + i < c && low_row >= 0; ++i) + System.out.print (mat[low_row][i] + "" ""); + low_row -= 1; + for (i = low_row + 2; i <= high_row && i < r && + high_column < c; ++i) + System.out.print(mat[i][high_column] + "" ""); + high_column += 1; + for (i = high_column - 2; i >= low_column && + i >= 0 && high_row < r; --i) + System.out.print(mat[high_row][i] + "" ""); + high_row += 1; + for (i = high_row - 2; i > low_row && i >= 0 + && low_column >= 0; --i) + System.out.print(mat[i][low_column] +"" ""); + low_column -= 1; + } + System.out.println(); +} +/*Driver code*/ + + static public void main (String[] args) + { + int [][]mat = {{1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}}; + int r = 3, c = 3; +/* Function calling*/ + + printSpiral(mat, r, c); + } +}"," '''Python3 program to print a matrix +in spiral form.''' + +MAX = 100 +def printSpiral(mat, r, c): + a = 0 + b = 2 + low_row = 0 if (0 > a) else a + low_column = 0 if (0 > b) else b - 1 + high_row = r-1 if ((a + 1) >= r) else a + 1 + high_column = c-1 if ((b + 1) >= c) else b + 1 + while ((low_row > 0 - r and low_column > 0 - c)): + i = low_column + 1 + while (i <= high_column and + i < c and low_row >= 0): + print( mat[low_row][i], end = "" "") + i += 1 + low_row -= 1 + i = low_row + 2 + while (i <= high_row and + i < r and high_column < c): + print(mat[i][high_column], end = "" "") + i += 1 + high_column += 1 + i = high_column - 2 + while (i >= low_column and + i >= 0 and high_row < r): + print(mat[high_row][i], end = "" "") + i -= 1 + high_row += 1 + i = high_row - 2 + while (i > low_row and + i >= 0 and low_column >= 0): + print(mat[i][low_column], end = "" "") + i -= 1 + low_column -= 1 + print() + '''Driver code''' + +if __name__ == ""__main__"": + mat = [[ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ]] + r = 3 + c = 3 + '''Function calling''' + + printSpiral(mat, r, c)" +Count triplets in a sorted doubly linked list whose sum is equal to a given value x,"/*Java implementation to count triplets in a sorted doubly linked list +whose sum is equal to a given value 'x'*/ + +import java.util.*; +class GFG{ +/*structure of node of doubly linked list*/ + +static class Node { + int data; + Node next, prev; +}; +/*function to count pairs whose sum equal to given 'value'*/ + +static int countPairs(Node first, Node second, int value) +{ + int count = 0; +/* The loop terminates when either of two pointers + become null, or they cross each other (second.next + == first), or they become same (first == second)*/ + + while (first != null && second != null && + first != second && second.next != first) { +/* pair found*/ + + if ((first.data + second.data) == value) { +/* increment count*/ + + count++; +/* move first in forward direction*/ + + first = first.next; +/* move second in backward direction*/ + + second = second.prev; + } +/* if sum is greater than 'value' + move second in backward direction*/ + + else if ((first.data + second.data) > value) + second = second.prev; +/* else move first in forward direction*/ + + else + first = first.next; + } +/* required count of pairs*/ + + return count; +} +/*function to count triplets in a sorted doubly linked list +whose sum is equal to a given value 'x'*/ + +static int countTriplets(Node head, int x) +{ +/* if list is empty*/ + + if (head == null) + return 0; + Node current, first, last; + int count = 0; +/* get pointer to the last node of + the doubly linked list*/ + + last = head; + while (last.next != null) + last = last.next; +/* traversing the doubly linked list*/ + + for (current = head; current != null; current = current.next) { +/* for each current node*/ + + first = current.next; +/* count pairs with sum(x - current.data) in the range + first to last and add it to the 'count' of triplets*/ + + count += countPairs(first, last, x - current.data); + } +/* required count of triplets*/ + + return count; +} +/*A utility function to insert a new node at the +beginning of doubly linked list*/ + +static Node insert(Node head, int data) +{ +/* allocate node*/ + + Node temp = new Node(); +/* put in the data*/ + + temp.data = data; + temp.next = temp.prev = null; + if ((head) == null) + (head) = temp; + else { + temp.next = head; + (head).prev = temp; + (head) = temp; + } + return head; +} +/*Driver program to test above*/ + +public static void main(String[] args) +{ +/* start with an empty doubly linked list*/ + + Node head = null; +/* insert values in sorted order*/ + + head = insert(head, 9); + head = insert(head, 8); + head = insert(head, 6); + head = insert(head, 5); + head = insert(head, 4); + head = insert(head, 2); + head = insert(head, 1); + int x = 17; + System.out.print(""Count = "" + + countTriplets(head, x)); +} +}"," '''Python3 implementation to count triplets +in a sorted doubly linked list whose sum +is equal to a given value x''' + '''Structure of node of doubly linked list''' + +class Node: + def __init__(self, x): + self.data = x + self.next = None + self.prev = None + '''Function to count pairs whose sum +equal to given 'value''' + ''' +def countPairs(first, second, value): + count = 0 + ''' The loop terminates when either of two pointers + become None, or they cross each other (second.next + == first), or they become same (first == second)''' + + while (first != None and second != None and + first != second and second.next != first): + ''' Pair found''' + + if ((first.data + second.data) == value): + ''' Increment count''' + + count += 1 + ''' Move first in forward direction''' + + first = first.next + ''' Move second in backward direction''' + + second = second.prev + ''' If sum is greater than 'value' + move second in backward direction''' + + elif ((first.data + second.data) > value): + second = second.prev + ''' Else move first in forward direction''' + + else: + first = first.next + ''' Required count of pairs''' + + return count + '''Function to count triplets in a sorted +doubly linked list whose sum is equal +to a given value 'x''' + ''' +def countTriplets(head, x): + ''' If list is empty''' + + if (head == None): + return 0 + current, first, last = head, None, None + count = 0 + ''' Get pointer to the last node of + the doubly linked list''' + + last = head + while (last.next != None): + last = last.next + ''' Traversing the doubly linked list''' + + while current != None: + ''' For each current node''' + + first = current.next + ''' count pairs with sum(x - current.data) in + the range first to last and add it to the + 'count' of triplets''' + + count, current = count + countPairs( + first, last, x - current.data), current.next + ''' Required count of triplets''' + + return count + '''A utility function to insert a new node +at the beginning of doubly linked list''' + +def insert(head, data): + ''' Allocate node''' + + temp = Node(data) + ''' Put in the data + temp.next = temp.prev = None''' + + if (head == None): + head = temp + else: + temp.next = head + head.prev = temp + head = temp + return head + '''Driver code''' + +if __name__ == '__main__': + ''' Start with an empty doubly linked list''' + + head = None + ''' Insert values in sorted order''' + + head = insert(head, 9) + head = insert(head, 8) + head = insert(head, 6) + head = insert(head, 5) + head = insert(head, 4) + head = insert(head, 2) + head = insert(head, 1) + x = 17 + print(""Count = "", countTriplets(head, x))" +Sort 1 to N by swapping adjacent elements,"/*Java program to test whether an array +can be sorted by swapping adjacent +elements using boolean array*/ + +class GFG +{ +/* Return true if array can be + sorted otherwise false*/ + + static int sortedAfterSwap(int[] A, + int[] B, int n) + { + int t = 0; + for (int i = 0; i < n - 1; i++) + { + if (B[i] != 0) + { + if (A[i] != i + 1) + t = A[i]; + A[i] = A[i + 1]; + A[i + 1] = t; + } + } +/* Check if array is sorted or not*/ + + for (int i = 0; i < n; i++) + { + if (A[i] != i + 1) + return 0; + } + return 1; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] A = { 1, 2, 5, 3, 4, 6 }; + int[] B = { 0, 1, 1, 1, 0 }; + int n = A.length; + if (sortedAfterSwap(A, B, n) == 0) + System.out.println(""A can be sorted""); + else + System.out.println(""A can not be sorted""); + } +}"," '''Python3 program to test whether array +can be sorted by swapping adjacent +elements using boolean array + ''' '''Return true if array can be +sorted otherwise false''' + +def sortedAfterSwap(A,B,n): + for i in range(0,n-1): + if B[i]: + if A[i]!=i+1: + A[i], A[i+1] = A[i+1], A[i] + ''' Check if array is sorted or not''' + + for i in range(n): + if A[i]!=i+1: + return False + return True + '''Driver program''' + +if __name__=='__main__': + A = [1, 2, 5, 3, 4, 6] + B = [0, 1, 1, 1, 0] + n =len(A) + if (sortedAfterSwap(A, B, n)) : + print(""A can be sorted"") + else : + print(""A can not be sorted"")" +Find Minimum Depth of a Binary Tree,"/*Java program to find minimum depth +of a given Binary Tree*/ + +import java.util.*; +class GFG +{ +/*A binary Tree node*/ + +static class Node +{ + int data; + Node left, right; +} +/*A queue item (Stores pointer to +node and an integer)*/ + +static class qItem +{ + Node node; + int depth; + public qItem(Node node, int depth) + { + this.node = node; + this.depth = depth; + } +} +/*Iterative method to find +minimum depth of Binary Tree*/ + +static int minDepth(Node root) +{ +/* Corner Case*/ + + if (root == null) + return 0; +/* Create an empty queue for level order traversal*/ + + Queue q = new LinkedList<>(); +/* Enqueue Root and initialize depth as 1*/ + + qItem qi = new qItem(root, 1); + q.add(qi); +/* Do level order traversal*/ + + while (q.isEmpty() == false) + { +/* Remove the front queue item*/ + + qi = q.peek(); + q.remove(); +/* Get details of the remove item*/ + + Node node = qi.node; + int depth = qi.depth; +/* If this is the first leaf node seen so far + Then return its depth as answer*/ + + if (node.left == null && node.right == null) + return depth; +/* If left subtree is not null, + add it to queue*/ + + if (node.left != null) + { + qi.node = node.left; + qi.depth = depth + 1; + q.add(qi); + } +/* If right subtree is not null, + add it to queue*/ + + if (node.right != null) + { + qi.node = node.right; + qi.depth = depth + 1; + q.add(qi); + } + } + return 0; +} +/*Utility function to create a new tree Node*/ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* Let us create binary tree shown in above diagram*/ + + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + System.out.println(minDepth(root)); +} +}"," '''Python program to find minimum depth of a given Binary Tree''' + + '''A Binary Tree node''' + +class Node: + def __init__(self , data): + self.data = data + self.left = None + self.right = None + + '''Iterative method to find +minimum depth of Binary Tree''' + +def minDepth(root): ''' Corner Case''' + + if root is None: + return 0 + ''' Create an empty queue for level order traversal''' + + q = [] + ''' Enqueue root and initialize depth as 1''' + + q.append({'node': root , 'depth' : 1}) + ''' Do level order traversal''' + + while(len(q)>0): + ''' Remove the front queue item''' + + queueItem = q.pop(0) + ''' Get details of the removed item''' + + node = queueItem['node'] + depth = queueItem['depth'] + ''' If this is the first leaf node seen so far + then return its depth as answer''' + + if node.left is None and node.right is None: + return depth + ''' If left subtree is not None, add it to queue''' + + if node.left is not None: + q.append({'node' : node.left , 'depth' : depth+1}) + ''' if right subtree is not None, add it to queue''' + + if node.right is not None: + q.append({'node': node.right , 'depth' : depth+1}) + '''Driver program to test above function''' + '''Lets construct a binary tree shown in above diagram''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +print minDepth(root)" +Flatten a multilevel linked list,"static class List +{ + public int data; + public List next; + public List child; +}; + + +"," '''A linked list node has data, +next pointer and child pointer''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.child = None + + +" +Iterative program to count leaf nodes in a Binary Tree,"/*Java Program for above approach*/ + +import java.util.LinkedList; +import java.util.Queue; +import java.io.*; +import java.util.*; +class GfG +{ +/* Node class*/ + + static class Node + { + int data; + Node left, right; + } +/* Program to count leaves*/ + + static int countLeaves(Node node) + { +/* If the node itself is ""null"" + return 0, as there + are no leaves*/ + + if (node == null) + return 0; +/* It the node is a leaf then + both right and left + children will be ""null""*/ + + if (node.left == null && + node.right == null) + return 1; +/* Now we count the leaves in + the left and right + subtrees and return the sum*/ + + return countLeaves(node.left) + + countLeaves(node.right); + } +/* Class newNode of Node type*/ + + static Node newNode(int data) + { + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); + } +/* Driver Code*/ + + public static void main(String[] args) + { + Node root = newNode(1); + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + /* get leaf count of the above + created tree */ + + System.out.println(countLeaves(root)); + } +} +"," '''Python3 Program for above approach''' + + '''Node class''' + +class Node: + def __init__(self,x): + self.data = x + self.left = None + self.right = None '''Program to count leaves''' + +def countLeaves(node): + ''' If the node itself is ""None"" + return 0, as there + are no leaves''' + + if (node == None): + return 0 + ''' It the node is a leaf then + both right and left + children will be ""None""''' + + if (node.left == None and node.right == None): + return 1 + ''' Now we count the leaves in + the left and right + subtrees and return the sum''' + + return countLeaves(node.left) + countLeaves(node.right) + '''Driver Code''' + +if __name__ == '__main__': + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + ''' /* get leaf count of the above + created tree */''' + + print(countLeaves(root))" +Largest increasing subsequence of consecutive integers,"/*Java implementation of longest continuous increasing +subsequence*/ + +import java.util.*; +class GFG +{ +/*Function for LIS*/ + +static void findLIS(int A[], int n) +{ + Map hash = new HashMap(); +/* Initialize result*/ + + int LIS_size = 1; + int LIS_index = 0; + hash.put(A[0], 1); +/* iterate through array and find + end index of LIS and its Size*/ + + for (int i = 1; i < n; i++) + { + hash.put(A[i], hash.get(A[i] - 1)==null? 1:hash.get(A[i] - 1)+1); + if (LIS_size < hash.get(A[i])) + { + LIS_size = hash.get(A[i]); + LIS_index = A[i]; + } + } +/* print LIS size*/ + + System.out.println(""LIS_size = "" + LIS_size); +/* print LIS after setting start element*/ + + System.out.print(""LIS : ""); + int start = LIS_index - LIS_size + 1; + while (start <= LIS_index) + { + System.out.print(start + "" ""); + start++; + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; + int n = A.length; + findLIS(A, n); +} +}"," '''Python3 implementation of longest +continuous increasing subsequence +Function for LIS''' + +def findLIS(A, n): + hash = dict() + ''' Initialize result''' + + LIS_size, LIS_index = 1, 0 + hash[A[0]] = 1 + ''' iterate through array and find + end index of LIS and its Size''' + + for i in range(1, n): + if A[i] - 1 not in hash: + hash[A[i] - 1] = 0 + hash[A[i]] = hash[A[i] - 1] + 1 + if LIS_size < hash[A[i]]: + LIS_size = hash[A[i]] + LIS_index = A[i] ''' print LIS size''' + + print(""LIS_size ="", LIS_size) + ''' print LIS after setting start element''' + + print(""LIS : "", end = """") + start = LIS_index - LIS_size + 1 + while start <= LIS_index: + print(start, end = "" "") + start += 1 + '''Driver Code''' + +if __name__ == ""__main__"": + A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ] + n = len(A) + findLIS(A, n)" +Find the smallest positive number missing from an unsorted array | Set 1,"/*Java program for the above approach*/ + +import java.util.Arrays; + +class GFG{ + +/*Function for finding the first +missing positive number*/ + +static int firstMissingPositive(int arr[], int n) +{ + +/* Check if 1 is present in array or not*/ + + for(int i = 0; i < n; i++) + { + +/* Loop to check boundary + condition and for swapping*/ + + while (arr[i] >= 1 && arr[i] <= n + && arr[i] != arr[arr[i] - 1]) { + + int temp=arr[arr[i]-1]; + arr[arr[i]-1]=arr[i]; + arr[i]=temp; + } + } + +/* Finding which index has value less than n*/ + + for(int i = 0; i < n; i++) + if (arr[i] != i + 1) + return (i + 1); + +/* If array has values from 1 to n*/ + + return (n + 1); +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = {2, 3, -7, 6, 8, 1, -10, 15 }; + int n = arr.length; + int ans = firstMissingPositive(arr, n); + + System.out.println(ans); +} +} + + +", +Smallest power of 2 greater than or equal to n,"/*Java program to find +smallest power of 2 +greater than or equal to n*/ + +import java.io.*; +class GFG +{ + static int nextPowerOf2(int n) + { + int count = 0; +/* First n in the below + condition is for the + case where n is 0*/ + + if (n > 0 && (n & (n - 1)) == 0) + return n; + while(n != 0) + { + n >>= 1; + count += 1; + } + return 1 << count; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int n = 0; + System.out.println(nextPowerOf2(n)); + } +}","def nextPowerOf2(n): + count = 0; + ''' First n in the below + condition is for the + case where n is 0''' + + if (n and not(n & (n - 1))): + return n + while( n != 0): + n >>= 1 + count += 1 + return 1 << count; + '''Driver Code''' + +n = 0 +print(nextPowerOf2(n))" +Smallest subarray with sum greater than a given value,"class SmallestSubArraySum +{ +/* Returns length of smallest subarray with sum greater than x. + If there is no subarray with given sum, then returns n+1*/ + + static int smallestSubWithSum(int arr[], int n, int x) + { +/* Initialize length of smallest subarray as n+1*/ + + int min_len = n + 1; +/* Pick every element as starting point*/ + + for (int start = 0; start < n; start++) + { +/* Initialize sum starting with current start*/ + + int curr_sum = arr[start]; +/* If first element itself is greater*/ + + if (curr_sum > x) + return 1; +/* Try different ending points for curremt start*/ + + for (int end = start + 1; end < n; end++) + { +/* add last element to current sum*/ + + curr_sum += arr[end]; +/* If sum becomes more than x and length of + this subarray is smaller than current smallest + length, update the smallest length (or result)*/ + + if (curr_sum > x && (end - start + 1) < min_len) + min_len = (end - start + 1); + } + } + return min_len; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int arr1[] = {1, 4, 45, 6, 10, 19}; + int x = 51; + int n1 = arr1.length; + int res1 = smallestSubWithSum(arr1, n1, x); + if (res1 == n1+1) + System.out.println(""Not Possible""); + else + System.out.println(res1); + int arr2[] = {1, 10, 5, 2, 7}; + int n2 = arr2.length; + x = 9; + int res2 = smallestSubWithSum(arr2, n2, x); + if (res2 == n2+1) + System.out.println(""Not Possible""); + else + System.out.println(res2); + int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; + int n3 = arr3.length; + x = 280; + int res3 = smallestSubWithSum(arr3, n3, x); + if (res3 == n3+1) + System.out.println(""Not Possible""); + else + System.out.println(res3); + } +}"," '''Python3 program to find Smallest +subarray with sum greater +than a given value''' + + '''Returns length of smallest subarray +with sum greater than x. If there +is no subarray with given sum, +then returns n+1''' + +def smallestSubWithSum(arr, n, x): ''' Initialize length of smallest + subarray as n+1''' + + min_len = n + 1 + ''' Pick every element as starting point''' + + for start in range(0,n): + ''' Initialize sum starting + with current start''' + + curr_sum = arr[start] + ''' If first element itself is greater''' + + if (curr_sum > x): + return 1 + ''' Try different ending points + for curremt start''' + + for end in range(start+1,n): + ''' add last element to current sum''' + + curr_sum += arr[end] + ''' If sum becomes more than x + and length of this subarray + is smaller than current smallest + length, update the smallest + length (or result)''' + + if curr_sum > x and (end - start + 1) < min_len: + min_len = (end - start + 1) + return min_len; + '''Driver program to test above function */''' + +arr1 = [1, 4, 45, 6, 10, 19] +x = 51 +n1 = len(arr1) +res1 = smallestSubWithSum(arr1, n1, x); +if res1 == n1+1: + print(""Not possible"") +else: + print(res1) +arr2 = [1, 10, 5, 2, 7] +n2 = len(arr2) +x = 9 +res2 = smallestSubWithSum(arr2, n2, x); +if res2 == n2+1: + print(""Not possible"") +else: + print(res2) +arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250] +n3 = len(arr3) +x = 280 +res3 = smallestSubWithSum(arr3, n3, x) +if res3 == n3+1: + print(""Not possible"") +else: + print(res3)" +Channel Assignment Problem,"import java.util.*; +class GFG +{ +static int M = 3; +static int N = 3; +/*A Depth First Search based recursive function +that returns true if a matching for vertex u is possible*/ + +static boolean bpm(int table[][], int u, + boolean seen[], int matchR[]) +{ +/* Try every receiver one by one*/ + + for (int v = 0; v < N; v++) + { +/* If sender u has packets to send + to receiver v and receiver v is not + already mapped to any other sender + just check if the number of packets is + greater than '0' because only one packet + can be sent in a time frame anyways*/ + + if (table[u][v] > 0 && !seen[v]) + { +/*Mark v as visited*/ + +seen[v] = true; +/* If receiver 'v' is not assigned to + any sender OR previously assigned sender + for receiver v (which is matchR[v]) has an + alternate receiver available. Since v is + marked as visited in the above line, + matchR[v] in the following recursive call + will not get receiver 'v' again*/ + + if (matchR[v] < 0 || bpm(table, matchR[v], + seen, matchR)) + { + matchR[v] = u; + return true; + } + } + } + return false; +} +/*Returns maximum number of packets +that can be sent parallely in +1 time slot from sender to receiver*/ + +static int maxBPM(int table[][]) +{ +/* An array to keep track of the receivers + assigned to the senders. The value of matchR[i] + is the sender ID assigned to receiver i. + The value -1 indicates nobody is assigned.*/ + + int []matchR = new int[N]; +/* Initially all receivers are + not mapped to any senders*/ + + Arrays.fill(matchR, -1); +/*Count of receivers assigned to senders*/ + +int result = 0; + for (int u = 0; u < M; u++) + { +/* Mark all receivers as not seen for next sender*/ + + boolean []seen = new boolean[N]; + Arrays.fill(seen, false); +/* Find if the sender 'u' can be + assigned to the receiver*/ + + if (bpm(table, u, seen, matchR)) + result++; + } + System.out.println(""The number of maximum packets"" + + "" sent in the time slot is "" + result); + for (int x = 0; x < N; x++) + if (matchR[x] + 1 != 0) + System.out.println(""T"" + (matchR[x] + 1) + + ""-> R"" + (x + 1)); + return result; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int table[][] = {{0, 2, 0}, + {3, 0, 1}, + {2, 4, 0}}; + maxBPM(table); +} +}"," '''A Depth First Search based recursive +function that returns true if a matching +for vertex u is possible ''' + +def bpm(table, u, seen, matchR): + global M, N + ''' Try every receiver one by one ''' + + for v in range(N): + ''' If sender u has packets to send to + receiver v and receiver v is not + already mapped to any other sender + just check if the number of packets + is greater than '0' because only one + packet can be sent in a time frame anyways ''' + + if (table[u][v] > 0 and not seen[v]): + '''Mark v as visited ''' + + seen[v] = True + ''' If receiver 'v' is not assigned to any + sender OR previously assigned sender + for receiver v (which is matchR[v]) has + an alternate receiver available. Since + v is marked as visited in the above line, + matchR[v] in the following recursive call + will not get receiver 'v' again ''' + + if (matchR[v] < 0 or bpm(table, matchR[v], + seen, matchR)): + matchR[v] = u + return True + return False + '''Returns maximum number of packets +that can be sent parallely in 1 +time slot from sender to receiver ''' + +def maxBPM(table): + global M, N + ''' An array to keep track of the receivers + assigned to the senders. The value of + matchR[i] is the sender ID assigned to + receiver i. The value -1 indicates nobody + is assigned.''' + + ''' Initially all receivers are not mapped + to any senders ''' + + matchR = [-1] * N '''Count of receivers assigned to senders''' + + result = 0 + for u in range(M): + ''' Mark all receivers as not seen + for next sender ''' + + seen = [0] * N + ''' Find if the sender 'u' can be assigned + to the receiver ''' + + if (bpm(table, u, seen, matchR)): + result += 1 + print(""The number of maximum packets sent"", + ""in the time slot is"", result) + for x in range(N): + if (matchR[x] + 1 != 0): + print(""T"", matchR[x] + 1, ""-> R"", x + 1) + return result + '''Driver Code''' + +M = 3 +N = 4 +table = [[0, 2, 0], [3, 0, 1], [2, 4, 0]] +max_flow = maxBPM(table)" +Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i,"/*Java program to rearrange the array +as per the given condition*/ + +import java.util.*; +import java.lang.*; +public class GfG{ +/* function to rearrange the array*/ + + public static void rearrangeArr(int arr[], + int n) + { +/* total even positions*/ + + int evenPos = n / 2; +/* total odd positions*/ + + int oddPos = n - evenPos; + int[] tempArr = new int [n]; +/* copy original array in an + auxiliary array*/ + + for (int i = 0; i < n; i++) + tempArr[i] = arr[i]; +/* sort the auxiliary array*/ + + Arrays.sort(tempArr); + int j = oddPos - 1; +/* fill up odd position in + original array*/ + + for (int i = 0; i < n; i += 2) { + arr[i] = tempArr[j]; + j--; + } + j = oddPos; +/* fill up even positions in + original array*/ + + for (int i = 1; i < n; i += 2) { + arr[i] = tempArr[j]; + j++; + } +/* display array*/ + + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver function*/ + + public static void main(String argc[]){ + int[] arr = new int []{ 1, 2, 3, 4, 5, + 6, 7 }; + int size = 7; + rearrangeArr(arr, size); + } +}"," '''Python3 code to rearrange the array +as per the given condition''' + +import array as a +import numpy as np + '''function to rearrange the array''' + +def rearrangeArr(arr, n): + ''' total even positions''' + + evenPos = int(n / 2) + ''' total odd positions''' + + oddPos = n - evenPos + tempArr = np.empty(n, dtype = object) ''' copy original array in an + auxiliary array''' + + for i in range(0, n): + tempArr[i] = arr[i] + ''' sort the auxiliary array''' + + tempArr.sort() + j = oddPos - 1 + ''' fill up odd position in original + array''' + + for i in range(0, n, 2): + arr[i] = tempArr[j] + j = j - 1 + j = oddPos + ''' fill up even positions in original + array''' + + for i in range(1, n, 2): + arr[i] = tempArr[j] + j = j + 1 + ''' display array''' + + for i in range(0, n): + print (arr[i], end = ' ') + '''Driver code''' + +arr = a.array('i', [ 1, 2, 3, 4, 5, 6, 7 ]) +rearrangeArr(arr, 7)" +Binary array after M range toggle operations,"/*Java program to find modified array +after m range toggle operations.*/ + +class GFG +{ + +/*function for toggle*/ + +static void command(boolean arr[], + int a, int b) +{ + arr[a] ^= true; + arr[b + 1] ^= true; +} + +/*function for final processing of array*/ + +static void process(boolean arr[], int n) +{ + for (int k = 1; k <= n; k++) + { + arr[k] ^= arr[k - 1]; + } +} + +/*function for printing result*/ + +static void result(boolean arr[], int n) +{ + for (int k = 1; k <= n; k++) + { + if(arr[k] == true) + System.out.print(""1"" + "" ""); + else + System.out.print(""0"" + "" ""); + } +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + int n = 5, m = 3; + boolean arr[] = new boolean[n + 2]; + +/* function call for toggle*/ + + command(arr, 1, 5); + command(arr, 2, 5); + command(arr, 3, 5); + +/* process array*/ + + process(arr, n); + +/* print result*/ + + result(arr, n); +} +} + + +"," '''Python 3 program to find modified array after +m range toggle operations.''' + + + '''function for toggle''' + +def command(brr, a, b): + arr[a] ^= 1 + arr[b+1] ^= 1 + + '''function for final processing of array''' + +def process(arr, n): + for k in range(1, n + 1, 1): + arr[k] ^= arr[k - 1] + + '''function for printing result''' + +def result(arr, n): + for k in range(1, n + 1, 1): + print(arr[k], end = "" "") + + '''Driver Code''' + +if __name__ == '__main__': + n = 5 + m = 3 + arr = [0 for i in range(n+2)] + + ''' function call for toggle''' + + command(arr, 1, 5) + command(arr, 2, 5) + command(arr, 3, 5) + + ''' process array''' + + process(arr, n) + + ''' print result''' + + result(arr, n) + + +" +Find the Rotation Count in Rotated Sorted array,"/*Java program to find number of +rotations in a sorted and rotated +array.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class LinearSearch +{ +/* Returns count of rotations for an + array which is first sorted in + ascending order, then rotated*/ + + static int countRotations(int arr[], int n) + { +/* We basically find index of minimum + element*/ + + int min = arr[0], min_index = -1; + for (int i = 0; i < n; i++) + { + if (min > arr[i]) + { + min = arr[i]; + min_index = i; + } + } + return min_index; + } +/* Driver program to test above functions*/ + + public static void main (String[] args) + { + int arr[] = {15, 18, 2, 3, 6, 12}; + int n = arr.length; + System.out.println(countRotations(arr, n)); + } +}"," '''Python3 program to find number +of rotations in a sorted and +rotated array. + ''' '''Returns count of rotations for +an array which is first sorted +in ascending order, then rotated''' + +def countRotations(arr, n): + ''' We basically find index + of minimum element''' + + min = arr[0] + for i in range(0, n): + if (min > arr[i]): + min = arr[i] + min_index = i + return min_index; + '''Driver code''' + +arr = [15, 18, 2, 3, 6, 12] +n = len(arr) +print(countRotations(arr, n))" +Maximum difference between two elements such that larger element appears after the smaller number,"/*Java program to find Maximum +difference between two elements +such that larger element appears +after the smaller number*/ + +class GFG +{ + +/* The function assumes that there +are at least two elements in array. +The function returns a negative +value if the array is sorted in +decreasing order and returns 0 if +elements are equal */ + +static int maxDiff (int arr[], int n) +{ +/* Initialize diff, current + sum and max sum*/ + + int diff = arr[1] - arr[0]; + int curr_sum = diff; + int max_sum = curr_sum; + + for(int i = 1; i < n - 1; i++) + { +/* Calculate current diff*/ + + diff = arr[i + 1] - arr[i]; + +/* Calculate current sum*/ + + if (curr_sum > 0) + curr_sum += diff; + else + curr_sum = diff; + +/* Update max sum, if needed*/ + + if (curr_sum > max_sum) + max_sum = curr_sum; + } + + return max_sum; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ +int arr[] = {80, 2, 6, 3, 100}; +int n = arr.length; + +/*Function calling*/ + +System.out.print(""Maximum difference is "" + + maxDiff(arr, n)); +} +} + + +"," '''Python3 program to find Maximum difference +between two elements such that larger +element appears after the smaller number''' + + + '''The function assumes that there are +at least two elements in array. The +function returns a negative value if +the array is sorted in decreasing +order and returns 0 if elements are equal''' + +def maxDiff (arr, n): + + ''' Initialize diff, current + sum and max sum''' + + diff = arr[1] - arr[0] + curr_sum = diff + max_sum = curr_sum + + for i in range(1, n - 1): + + ''' Calculate current diff''' + + diff = arr[i + 1] - arr[i] + + ''' Calculate current sum''' + + if (curr_sum > 0): + curr_sum += diff + else: + curr_sum = diff + + ''' Update max sum, if needed''' + + if (curr_sum > max_sum): + max_sum = curr_sum + return max_sum + + '''Driver Code''' + +if __name__ == '__main__': + arr = [80, 2, 6, 3, 100] + n = len(arr) + + ''' Function calling''' + + print(""Maximum difference is"", + maxDiff(arr, n)) + + +" +Next higher number with same number of set bits,"/*Java Implementation on above approach*/ + +class GFG +{ +/*this function returns next higher +number with same number of set bits as x.*/ + +static int snoob(int x) +{ +int rightOne, nextHigherOneBit, rightOnesPattern, next = 0; +if(x > 0) +{ +/* right most set bit*/ + + rightOne = x & -x; +/* reset the pattern and set next higher bit + left part of x will be here*/ + + nextHigherOneBit = x + rightOne; +/* nextHigherOneBit is now part [D] of the above explanation. + isolate the pattern*/ + + rightOnesPattern = x ^ nextHigherOneBit; +/* right adjust pattern*/ + + rightOnesPattern = (rightOnesPattern)/rightOne; +/* correction factor*/ + + rightOnesPattern >>= 2; +/* rightOnesPattern is now part [A] of the above explanation. + integrate new pattern (Add [D] and [A])*/ + + next = nextHigherOneBit | rightOnesPattern; +} +return next; +} +/*Driver code*/ + +public static void main (String[] args) +{ + int x = 156; + System.out.println(""Next higher number with same"" + + ""number of set bits is ""+snoob(x)); +} +}"," '''This function returns next +higher number with same +number of set bits as x.''' + +def snoob(x): + next = 0 + if(x): + ''' right most set bit''' + + rightOne = x & -(x) + ''' reset the pattern and + set next higher bit + left part of x will + be here''' + + nextHigherOneBit = x + int(rightOne) + ''' nextHigherOneBit is + now part [D] of the + above explanation. + isolate the pattern''' + + rightOnesPattern = x ^ int(nextHigherOneBit) + ''' right adjust pattern''' + + rightOnesPattern = (int(rightOnesPattern) / + int(rightOne)) + ''' correction factor''' + + rightOnesPattern = int(rightOnesPattern) >> 2 + ''' rightOnesPattern is now part + [A] of the above explanation. + integrate new pattern + (Add [D] and [A])''' + + next = nextHigherOneBit | rightOnesPattern + return next + '''Driver Code''' + +x = 156 +print(""Next higher number with "" + + ""same number of set bits is"", + snoob(x))" +Maximize the sum of arr[i]*i,"/*Java program to find the +maximum value of i*arr[i]*/ + +import java.util.*; + +class GFG { + + static int maxSum(int arr[], int n) + { +/* Sort the array*/ + + Arrays.sort(arr); + +/* Finding the sum of arr[i]*i*/ + + int sum = 0; + for (int i = 0; i < n; i++) + sum += (arr[i] * i); + + return sum; + } + +/* Driven Program*/ + + public static void main(String[] args) + { + int arr[] = { 3, 5, 6, 1 }; + int n = arr.length; + + System.out.println(maxSum(arr, n)); + + } +} + +"," '''Python program to find the +maximum value of i*arr[i]''' + +def maxSum(arr,n): + + ''' Sort the array''' + + arr.sort() + + ''' Finding the sum of + arr[i]*i''' + + sum = 0 + for i in range(n): + sum += arr[i] * i + + return sum + + '''Driver Program''' + +arr = [3,5,6,1] +n = len(arr) +print(maxSum(arr,n)) + + +" +Maximum difference of sum of elements in two rows in a matrix,"/*Java program to find maximum difference +of sum of elements of two rows*/ + +class GFG { +static final int MAX = 100; +/*Function to find maximum difference of sum +of elements of two rows such that second +row appears before first row.*/ + +static int maxRowDiff(int mat[][], int m, int n) { +/* auxiliary array to store sum + of all elements of each row*/ + + int rowSum[] = new int[m]; +/* calculate sum of each row and + store it in rowSum array*/ + + for (int i = 0; i < m; i++) { + int sum = 0; + for (int j = 0; j < n; j++) + sum += mat[i][j]; + rowSum[i] = sum; + } +/* calculating maximum difference of two elements + such that rowSum[i] max_diff) + max_diff = rowSum[i] - min_element; +/* if new element is less than previous + minimum element then update it so that + we may get maximum difference in remaining array*/ + + if (rowSum[i] < min_element) + min_element = rowSum[i]; + } + return max_diff; +} +/*Driver code*/ + +public static void main(String[] args) { + int m = 5, n = 4; + int mat[][] = {{-1, 2, 3, 4 }, + {5, 3, -2, 1 }, + {6, 7, 2, -3}, + {2, 9, 1, 4 }, + {2, 1, -2, 0}}; + System.out.print(maxRowDiff(mat, m, n)); +} +}"," '''Python3 program to find maximum difference +of sum of elements of two rows + ''' '''Function to find maximum difference of +sum of elements of two rows such that +second row appears before first row.''' + +def maxRowDiff(mat, m, n): + ''' auxiliary array to store sum of + all elements of each row''' + + rowSum = [0] * m + ''' calculate sum of each row and + store it in rowSum array''' + + for i in range(0, m): + sum = 0 + for j in range(0, n): + sum += mat[i][j] + rowSum[i] = sum + ''' calculating maximum difference of + two elements such that + rowSum[i] max_diff): + max_diff = rowSum[i] - min_element + ''' if new element is less than previous + minimum element then update it so + that we may get maximum difference + in remaining array''' + + if (rowSum[i] < min_element): + min_element = rowSum[i] + return max_diff + '''Driver program to run the case''' + +m = 5 +n = 4 +mat = [[-1, 2, 3, 4], + [5, 3, -2, 1], + [6, 7, 2, -3], + [2, 9, 1, 4], + [2, 1, -2, 0]] +print( maxRowDiff(mat, m, n))" +Total numbers with no repeated digits in a range,"/*Java implementation of brute +force solution. */ + +import java.util.LinkedHashSet; +class GFG +{ +/*Function to check if the given +number has repeated digit or not */ + +static int repeated_digit(int n) +{ + LinkedHashSet s = new LinkedHashSet<>(); +/* Traversing through each digit */ + + while (n != 0) + { + int d = n % 10; +/* if the digit is present + more than once in the + number */ + + if (s.contains(d)) + { +/* return 0 if the number + has repeated digit */ + + return 0; + } + s.add(d); + n = n / 10; + } +/* return 1 if the number has + no repeated digit */ + + return 1; +} +/*Function to find total number +in the given range which has +no repeated digit */ + +static int calculate(int L, int R) +{ + int answer = 0; +/* Traversing through the range */ + + for (int i = L; i < R + 1; ++i) + { +/* Add 1 to the answer if i has + no repeated digit else 0 */ + + answer = answer + repeated_digit(i); + } + return answer; +} +/*Driver Code */ + +public static void main(String[] args) +{ + int L = 1, R = 100; +/* Calling the calculate */ + + System.out.println(calculate(L, R)); +} +}"," '''Python implementation of brute +force solution.''' + + '''Function to check if the given +number has repeated digit or not ''' + +def repeated_digit(n): + a = [] ''' Traversing through each digit''' + + while n != 0: + d = n%10 + ''' if the digit is present + more than once in the + number''' + + if d in a: + ''' return 0 if the number + has repeated digit''' + + return 0 + a.append(d) + n = n//10 + ''' return 1 if the number has no + repeated digit''' + + return 1 + '''Function to find total number +in the given range which has +no repeated digit''' + +def calculate(L,R): + answer = 0 + ''' Traversing through the range''' + + for i in range(L,R+1): + ''' Add 1 to the answer if i has + no repeated digit else 0''' + + answer = answer + repeated_digit(i) + return answer '''Driver's Code ''' + +L=1 +R=100 + '''Calling the calculate''' + +print(calculate(L, R))" +Find a pair with the given difference,"/*Java program to find a pair with the given difference*/ + +import java.io.*; + +class PairDifference +{ +/* The function assumes that the array is sorted*/ + + static boolean findPair(int arr[],int n) + { + int size = arr.length; + +/* Initialize positions of two elements*/ + + int i = 0, j = 1; + +/* Search for a pair*/ + + while (i < size && j < size) + { + if (i != j && arr[j]-arr[i] == n) + { + System.out.print(""Pair Found: ""+ + ""( ""+arr[i]+"", ""+ arr[j]+"" )""); + return true; + } + else if (arr[j] - arr[i] < n) + j++; + else + i++; + } + + System.out.print(""No such pair""); + return false; + } + +/* Driver program to test above function*/ + + public static void main (String[] args) + { + int arr[] = {1, 8, 30, 40, 100}; + int n = 60; + findPair(arr,n); + } +} + +"," '''Python program to find a pair with the given difference''' + + + '''The function assumes that the array is sorted''' + +def findPair(arr,n): + + size = len(arr) + + ''' Initialize positions of two elements''' + + i,j = 0,1 + + ''' Search for a pair''' + + while i < size and j < size: + + if i != j and arr[j]-arr[i] == n: + print ""Pair found ("",arr[i],"","",arr[j],"")"" + return True + + elif arr[j] - arr[i] < n: + j+=1 + else: + i+=1 + print ""No pair found"" + return False + + '''Driver function to test above function''' + +arr = [1, 8, 30, 40, 100] +n = 60 +findPair(arr, n) + + +" +Maximum triplet sum in array,"/*Java code to find maximum triplet sum*/ + +import java.io.*; +import java.util.*; +class GFG { +/* This function assumes that there are + at least three elements in arr[].*/ + + static int maxTripletSum(int arr[], int n) + { +/* sort the given array*/ + + Arrays.sort(arr); +/* After sorting the array. + Add last three element + of the given array*/ + + return arr[n - 1] + arr[n - 2] + arr[n - 3]; + } +/* Driven code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 0, 8, 6, 4, 2 }; + int n = arr.length; + System.out.println(maxTripletSum(arr, n)); + } +}"," '''Python 3 code to find +maximum triplet sum + ''' '''This function assumes +that there are at least +three elements in arr[].''' + +def maxTripletSum(arr, n) : + ''' sort the given array''' + + arr.sort() + ''' After sorting the array. + Add last three element + of the given array''' + + return (arr[n - 1] + arr[n - 2] + arr[n - 3]) + '''Driven code''' + +arr = [ 1, 0, 8, 6, 4, 2 ] +n = len(arr) +print(maxTripletSum(arr, n))" +Minimum difference between groups of size two,"/*Java program to find minimum +difference between groups of +highest and lowest sums.*/ + +import java.util.Arrays; +import java.util.Collections; +import java.util.Vector; + + +class GFG { + +static long calculate(long a[], int n) +{ +/* Sorting the whole array.*/ + + Arrays.sort(a); + int i,j; + +/* Generating sum groups.*/ + + Vector s = new Vector<>(); + for (i = 0, j = n - 1; i < j; i++, j--) + s.add((a[i] + a[j])); + + long mini = Collections.min(s); + long maxi = Collections.max(s); + return Math.abs(maxi - mini); +} + +/*Driver code*/ + +public static void main(String[] args) +{ + long a[] = { 2, 6, 4, 3 }; + int n = a.length; + System.out.println(calculate(a, n)); + } +} + +"," '''Python3 program to find minimum +difference between groups of +highest and lowest sums.''' + +def calculate(a, n): + + ''' Sorting the whole array.''' + + a.sort(); + + ''' Generating sum groups.''' + + s = []; + i = 0; + j = n - 1; + while(i < j): + s.append((a[i] + a[j])); + i += 1; + j -= 1; + + mini = min(s); + maxi = max(s); + + return abs(maxi - mini); + + '''Driver Code''' + +a = [ 2, 6, 4, 3 ]; +n = len(a); +print(calculate(a, n)); + + +" +Find largest d in array such that a + b + c = d,"/*Java Program to find the largest +such that d = a + b + c*/ + +import java.io.*; +import java.util.Arrays; +class GFG +{ +/*function to find largest d*/ + +static int findLargestd(int []S, int n) +{ + boolean found = false; +/* sort the array in + ascending order*/ + + Arrays.sort(S); +/* iterating from backwards to + find the required largest d*/ + + for (int i = n - 1; i >= 0; i--) + { + for (int j = 0; j < n; j++) + { +/* since all four a, b, c, + d should be distinct*/ + + if (i == j) + continue; + for (int k = j + 1; k < n; k++) + { + if (i == k) + continue; + for (int l = k + 1; l < n; l++) + { + if (i == l) + continue; +/* if the current combination + of j, k, l in the set is + equal to S[i] return this + value as this would be the + largest d since we are + iterating in descending order*/ + + if (S[i] == S[j] + S[k] + S[l]) + { + found = true; + return S[i]; + } + } + } + } + } + if (found == false) + return Integer.MAX_VALUE; + return -1; +} +/*Driver Code*/ + +public static void main(String []args) +{ + int []S = new int[]{ 2, 3, 5, 7, 12 }; + int n = S.length; + int ans = findLargestd(S, n); + if (ans == Integer.MAX_VALUE) + System.out.println(""No Solution""); + else + System.out.println(""Largest d such that "" + + ""a + "" + ""b + c = d is "" + + ans ); +} +} +"," '''Python Program to find the largest +d such that d = a + b + c''' + '''function to find largest d''' + +def findLargestd(S, n) : + found = False + ''' sort the array in ascending order''' + + S.sort() + ''' iterating from backwards to + find the required largest d''' + + for i in range(n-1, -1, -1) : + for j in range(0, n) : + ''' since all four a, b, c, + d should be distinct''' + + if (i == j) : + continue + for k in range(j + 1, n) : + if (i == k) : + continue + for l in range(k+1, n) : + if (i == l) : + continue + ''' if the current combination + of j, k, l in the set is + equal to S[i] return this + value as this would be the + largest d since we are + iterating in descending order''' + + if (S[i] == S[j] + S[k] + S[l]) : + found = True + return S[i] + if (found == False) : + return -1 + '''Driver Code''' + +S = [ 2, 3, 5, 7, 12 ] +n = len(S) +ans = findLargestd(S, n) +if (ans == -1) : + print (""No Solution"") +else : + print (""Largest d such that a + b +"" , + ""c = d is"" ,ans)" +Shortest Common Supersequence,"/*A dynamic programming based Java program to +find length of the shortest supersequence*/ + +class GFG { +/* Returns length of the shortest + supersequence of X and Y*/ + + static int superSeq(String X, String Y, int m, int n) + { + int[][] dp = new int[m + 1][n + 1]; +/* Fill table in bottom up manner*/ + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { +/* Below steps follow above recurrence*/ + + if (i == 0) + dp[i][j] = j; + else if (j == 0) + dp[i][j] = i; + else if (X.charAt(i - 1) == Y.charAt(j - 1)) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = 1 + + Math.min(dp[i - 1][j], + dp[i][j - 1]); + } + } + return dp[m][n]; + } +/* Driver Code*/ + + public static void main(String args[]) + { + String X = ""AGGTAB""; + String Y = ""GXTXAYB""; + System.out.println( + ""Length of the shortest supersequence is "" + + superSeq(X, Y, X.length(), Y.length())); + } +}"," '''A dynamic programming based python program +to find length of the shortest supersequence + ''' '''Returns length of the shortest supersequence of X and Y''' + +def superSeq(X, Y, m, n): + dp = [[0] * (n + 2) for i in range(m + 2)] + ''' Fill table in bottom up manner''' + + for i in range(m + 1): + for j in range(n + 1): + ''' Below steps follow above recurrence''' + + if (not i): + dp[i][j] = j + elif (not j): + dp[i][j] = i + elif (X[i - 1] == Y[j - 1]): + dp[i][j] = 1 + dp[i - 1][j - 1] + else: + dp[i][j] = 1 + min(dp[i - 1][j], + dp[i][j - 1]) + return dp[m][n] + '''Driver Code''' + +X = ""AGGTAB"" +Y = ""GXTXAYB"" +print(""Length of the shortest supersequence is %d"" + % superSeq(X, Y, len(X), len(Y)))" +Floor and Ceil from a BST,"/*Java program to find floor and ceil +of a given key in BST*/ + +import java.io.*; +/*A binary tree node has key, +left child and right child*/ + +class Node +{ + int data; + Node left, right; + Node(int d) + { + data = d; + left = right = null; + } +} +class BinaryTree{ +Node root; +int floor; +int ceil; +/*Helper function to find floor and +ceil of a given key in BST*/ + +public void floorCeilBSTHelper(Node root, + int key) +{ + while (root != null) + { + if (root.data == key) + { + ceil = root.data; + floor = root.data; + return; + } + if (key > root.data) + { + floor = root.data; + root = root.right; + } + else + { + ceil = root.data; + root = root.left; + } + } + return; +} +/*Display the floor and ceil of a +given key in BST. If key is less +than the min key in BST, floor +will be -1; If key is more than +the max key in BST, ceil will be -1;*/ + +public void floorCeilBST(Node root, int key) +{ +/* Variables 'floor' and 'ceil' + are passed by reference*/ + + floor = -1; + ceil = -1; + floorCeilBSTHelper(root, key); + System.out.println(key + "" "" + + floor + "" "" + ceil); +} +/*Driver code*/ + +public static void main(String[] args) +{ + BinaryTree tree = new BinaryTree(); + tree.root = new Node(8); + tree.root.left = new Node(4); + tree.root.right = new Node(12); + tree.root.left.left = new Node(2); + tree.root.left.right = new Node(6); + tree.root.right.left = new Node(10); + tree.root.right.right = new Node(14); + for(int i = 0; i < 16; i++) + { + tree.floorCeilBST(tree.root, i); + } +} +}"," '''Python3 program to find floor and +ceil of a given key in BST + ''' '''A binary tree node has key, +. left child and right child''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None + '''Helper function to find floor and +ceil of a given key in BST''' + +def floorCeilBSTHelper(root, key): + global floor, ceil + while (root): + if (root.data == key): + ceil = root.data + floor = root.data + return + if (key > root.data): + floor = root.data + root = root.right + else: + ceil = root.data + root = root.left + '''Display the floor and ceil of a given +key in BST. If key is less than the min +key in BST, floor will be -1; If key is +more than the max key in BST, ceil will be -1;''' + +def floorCeilBST(root, key): + global floor, ceil + ''' Variables 'floor' and 'ceil' + are passed by reference''' + + floor = -1 + ceil = -1 + floorCeilBSTHelper(root, key) + print(key, floor, ceil) + '''Driver code''' + +if __name__ == '__main__': + floor, ceil = -1, -1 + root = Node(8) + root.left = Node(4) + root.right = Node(12) + root.left.left = Node(2) + root.left.right = Node(6) + root.right.left = Node(10) + root.right.right = Node(14) + for i in range(16): + floorCeilBST(root, i)" +Print Postorder traversal from given Inorder and Preorder traversals,"/*Java program to print postorder +traversal from preorder and +inorder traversals*/ + +import java.util.Arrays; +class GFG +{ +/*A utility function to search x in arr[] of size n*/ + +static int search(int arr[], int x, int n) +{ + for (int i = 0; i < n; i++) + if (arr[i] == x) + return i; + return -1; +} +/*Prints postorder traversal from +given inorder and preorder traversals*/ + +static void printPostOrder(int in1[], + int pre[], int n) +{ +/* The first element in pre[] is + always root, search it in in[] + to find left and right subtrees*/ + + int root = search(in1, pre[0], n); +/* If left subtree is not empty, + print left subtree*/ + + if (root != 0) + printPostOrder(in1, Arrays.copyOfRange(pre, 1, n), root); +/* If right subtree is not empty, + print right subtree*/ + + if (root != n - 1) + printPostOrder(Arrays.copyOfRange(in1, root+1, n), + Arrays.copyOfRange(pre, 1+root, n), n - root - 1); +/* Print root*/ + + System.out.print( pre[0] + "" ""); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int in1[] = { 4, 2, 5, 1, 3, 6 }; + int pre[] = { 1, 2, 4, 5, 3, 6 }; + int n = in1.length; + System.out.println(""Postorder traversal "" ); + printPostOrder(in1, pre, n); +} +}"," '''Python3 program to print postorder +traversal from preorder and inorder +traversals''' + + '''A utility function to search x in +arr[] of size n''' + +def search(arr, x, n): + for i in range(n): + if (arr[i] == x): + return i + return -1 '''Prints postorder traversal from +given inorder and preorder traversals''' + +def printPostOrder(In, pre, n): + ''' The first element in pre[] is always + root, search it in in[] to find left + and right subtrees''' + + root = search(In, pre[0], n) + ''' If left subtree is not empty, + print left subtree''' + + if (root != 0): + printPostOrder(In, pre[1:n], root) + ''' If right subtree is not empty, + print right subtree''' + + if (root != n - 1): + printPostOrder(In[root + 1 : n], + pre[root + 1 : n], + n - root - 1) + ''' Print root''' + + print(pre[0], end = "" "") + '''Driver code''' + +In = [ 4, 2, 5, 1, 3, 6 ] +pre = [ 1, 2, 4, 5, 3, 6 ] +n = len(In) +print(""Postorder traversal "") +printPostOrder(In, pre, n)" +Find the sum of last n nodes of the given Linked List,"/*Java implementation to find the sum of last +'n' nodes of the Linked List*/ + +import java.util.*; + +class GFG +{ + +/* A Linked list node */ + +static class Node +{ + int data; + Node next; +}; + +/*function to insert a node at the +beginning of the linked list*/ + +static Node push(Node head_ref, int new_data) +{ + /* allocate node */ + + Node new_node = new Node(); + + /* put in the data */ + + new_node.data = new_data; + + /* link the old list to the new node */ + + new_node.next = head_ref; + + /* move the head to point to the new node */ + + head_ref = new_node; + return head_ref; +} + +/*utility function to find the sum of last 'n' nodes*/ + +static int sumOfLastN_NodesUtil(Node head, int n) +{ +/* if n == 0*/ + + if (n <= 0) + return 0; + + Stack st = new Stack(); + int sum = 0; + +/* traverses the list from left to right*/ + + while (head != null) + { + +/* push the node's data onto the stack 'st'*/ + + st.push(head.data); + +/* move to next node*/ + + head = head.next; + } + +/* pop 'n' nodes from 'st' and + add them*/ + + while (n-- >0) + { + sum += st.peek(); + st.pop(); + } + +/* required sum*/ + + return sum; +} + +/*Driver program to test above*/ + +public static void main(String[] args) +{ + Node head = null; + +/* create linked list 10.6.8.4.12*/ + + head = push(head, 12); + head = push(head, 4); + head = push(head, 8); + head = push(head, 6); + head = push(head, 10); + + int n = 2; + System.out.print(""Sum of last "" + n+ "" nodes = "" + + sumOfLastN_NodesUtil(head, n)); +} +} + + +"," '''Python3 implementation to find the sum of +last 'n' nodes of the Linked List''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + +head = None +n = 0 +sum = 0 + + '''function to insert a node at the +beginning of the linked list''' + +def push(head_ref, new_data): + global head + + ''' allocate node''' + + new_node = Node(0) + + ''' put in the data''' + + new_node.data = new_data + + ''' link the old list to the new node''' + + new_node.next = head_ref + + ''' move the head to point to the new node''' + + head_ref = new_node + head = head_ref + + '''utility function to find the sum of last 'n' nodes''' + +def sumOfLastN_NodesUtil(head, n): + + global sum + + ''' if n == 0''' + + if (n <= 0): + return 0 + + st = [] + sum = 0 + + ''' traverses the list from left to right''' + + while (head != None): + + ''' push the node's data onto the stack 'st''' + ''' + st.append(head.data) + + ''' move to next node''' + + head = head.next + + ''' pop 'n' nodes from 'st' and + add them''' + + while (n): + n -= 1 + sum += st[0] + st.pop(0) + + ''' required sum''' + + return sum + + '''Driver Code''' + +head = None + + '''create linked list 10.6.8.4.12''' + +push(head, 12) +push(head, 4) +push(head, 8) +push(head, 6) +push(head, 10) + +n = 2 +print(""Sum of last"" , n , + ""nodes ="", sumOfLastN_NodesUtil(head, n)) + + +" +Find Sum of all unique sub-array sum for a given array.,"/*Java for finding sum of all +unique subarray sum*/ + +import java.util.*; +class GFG +{ +/*function for finding grandSum*/ + +static int findSubarraySum(int []arr, int n) +{ + int res = 0; +/* Go through all subarrays, compute sums + and count occurrences of sums.*/ + + HashMap m = new HashMap(); + for (int i = 0; i < n; i++) + { + int sum = 0; + for (int j = i; j < n; j++) + { + sum += arr[j]; + if (m.containsKey(sum)) + { + m.put(sum, m.get(sum) + 1); + } + else + { + m.put(sum, 1); + } + } + } +/* Print all those sums that appear + once.*/ + + for (Map.Entry x : m.entrySet()) + if (x.getValue() == 1) + res += x.getKey(); + return res; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 3, 2, 3, 1, 4 }; + int n = arr.length; + System.out.println(findSubarraySum(arr, n)); +} +}"," '''Python3 for finding sum of all +unique subarray sum + ''' '''function for finding grandSum''' + +def findSubarraySum(arr, n): + res = 0 + ''' Go through all subarrays, compute sums + and count occurrences of sums.''' + + m = dict() + for i in range(n): + Sum = 0 + for j in range(i, n): + Sum += arr[j] + m[Sum] = m.get(Sum, 0) + 1 + ''' Print all those Sums that appear + once.''' + + for x in m: + if m[x] == 1: + res += x + return res + '''Driver code''' + +arr = [3, 2, 3, 1, 4] +n = len(arr) +print(findSubarraySum(arr, n))" +Detecting negative cycle using Floyd Warshall,"/*Java Program to check if there is a negative weight +cycle using Floyd Warshall Algorithm*/ + +class GFG +{ +/* Number of vertices in the graph*/ + + static final int V = 4; + /* Define Infinite as a large enough value. This + value will be used for vertices not connected + to each other */ + + static final int INF = 99999; +/* Returns true if graph has negative weight cycle + else false.*/ + + static boolean negCyclefloydWarshall(int graph[][]) + { + /* dist[][] will be the output matrix that will + finally have the shortest + distances between every pair of vertices */ + + int dist[][] = new int[V][V], i, j, k; + /* Initialize the solution matrix same as input + graph matrix. Or we can say the initial values + of shortest distances are based on shortest + paths considering no intermediate vertex. */ + + for (i = 0; i < V; i++) + for (j = 0; j < V; j++) + dist[i][j] = graph[i][j]; + /* Add all vertices one by one to the set of + intermediate vertices. + ---> Before start of a iteration, we have shortest + distances between all pairs of vertices such + that the shortest distances consider only the + vertices in set {0, 1, 2, .. k-1} as intermediate + vertices. + ----> After the end of a iteration, vertex no. k is + added to the set of intermediate vertices and + the set becomes {0, 1, 2, .. k} */ + + for (k = 0; k < V; k++) + { +/* Pick all vertices as source one by one*/ + + for (i = 0; i < V; i++) + { +/* Pick all vertices as destination for the + above picked source*/ + + for (j = 0; j < V; j++) + { +/* If vertex k is on the shortest path from + i to j, then update the value of dist[i][j]*/ + + if (dist[i][k] + dist[k][j] < dist[i][j]) + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } +/* If distance of any verex from itself + becomes negative, then there is a negative + weight cycle.*/ + + for (i = 0; i < V; i++) + if (dist[i][i] < 0) + return true; + return false; + } +/* Driver code*/ + + public static void main (String[] args) + { + /* Let us create the following weighted graph + 1 + (0)----------->(1) + /|\ | + | | + -1 | | -1 + | \|/ + (3)<-----------(2) + -1 */ + + int graph[][] = { {0, 1, INF, INF}, + {INF, 0, -1, INF}, + {INF, INF, 0, -1}, + {-1, INF, INF, 0}}; + if (negCyclefloydWarshall(graph)) + System.out.print(""Yes""); + else + System.out.print(""No""); + } +}"," '''Python Program to check +if there is a +negative weight +cycle using Floyd +Warshall Algorithm''' + + '''Number of vertices +in the graph''' + +V = 4 '''Define Infinite as a +large enough value. This +value will be used +for vertices not connected +to each other ''' + +INF = 99999 + '''Returns true if graph has +negative weight cycle +else false.''' + +def negCyclefloydWarshall(graph): + ''' dist[][] will be the + output matrix that will + finally have the shortest + distances between every + pair of vertices ''' + + dist=[[0 for i in range(V+1)]for j in range(V+1)] + ''' Initialize the solution + matrix same as input + graph matrix. Or we can + say the initial values + of shortest distances + are based on shortest + paths considering no + intermediate vertex. ''' + + for i in range(V): + for j in range(V): + dist[i][j] = graph[i][j] + ''' Add all vertices one + by one to the set of + intermediate vertices. + ---> Before start of a iteration, + we have shortest + distances between all pairs + of vertices such + that the shortest distances + consider only the + vertices in set {0, 1, 2, .. k-1} + as intermediate vertices. + ----> After the end of a iteration, + vertex no. k is + added to the set of + intermediate vertices and + the set becomes {0, 1, 2, .. k} ''' + + for k in range(V): + ''' Pick all vertices + as source one by one''' + + for i in range(V): + ''' Pick all vertices as + destination for the + above picked source''' + + for j in range(V): + ''' If vertex k is on + the shortest path from + i to j, then update + the value of dist[i][j]''' + + if (dist[i][k] + dist[k][j] < dist[i][j]): + dist[i][j] = dist[i][k] + dist[k][j] + ''' If distance of any + vertex from itself + becomes negative, then + there is a negative + weight cycle.''' + + for i in range(V): + if (dist[i][i] < 0): + return True + return False + '''Driver code''' + + ''' Let us create the + following weighted graph + 1 + (0)----------->(1) + /|\ | + | | + -1 | | -1 + | \|/ + (3)<-----------(2) + -1 ''' + +graph = [ [0, 1, INF, INF], + [INF, 0, -1, INF], + [INF, INF, 0, -1], + [-1, INF, INF, 0]] +if (negCyclefloydWarshall(graph)): + print(""Yes"") +else: + print(""No"")" +Print n smallest elements from given array in their original order,"/*Java for printing smallest n number in order*/ + +import java.util.*; + +class GFG +{ + + +/*Function to print smallest n numbers*/ + +static void printSmall(int arr[], int asize, int n) +{ +/* Make copy of array*/ + + int []copy_arr = Arrays.copyOf(arr,asize); + +/* Sort copy array*/ + + Arrays.sort(copy_arr); + +/* For each arr[i] find whether + it is a part of n-smallest + with binary search*/ + + for (int i = 0; i < asize; ++i) + { + if (Arrays.binarySearch(copy_arr,0,n, arr[i])>-1) + System.out.print(arr[i] + "" ""); + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; + int asize = arr.length; + int n = 5; + printSmall(arr, asize, n); +} +} + + +"," '''Python3 for printing smallest n number in order''' + + + '''Function for binary_search''' + +def binary_search(arr, low, high, ele): + while low < high: + mid = (low + high) // 2 + if arr[mid] == ele: + return mid + elif arr[mid] > ele: + high = mid + else: + low = mid + 1 + return -1 + + '''Function to print smallest n numbers''' + +def printSmall(arr, asize, n): + + ''' Make copy of array''' + + copy_arr = arr.copy() + + ''' Sort copy array''' + + copy_arr.sort() + + ''' For each arr[i] find whether + it is a part of n-smallest + with binary search''' + + for i in range(asize): + if binary_search(copy_arr, low = 0, + high = n, ele = arr[i]) > -1: + print(arr[i], end = "" "") + + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0] + asize = len(arr) + n = 5 + printSmall(arr, asize, n) + +" +Find Sum of all unique sub-array sum for a given array.,"/*Java for finding sum of all unique +subarray sum*/ + +import java.util.*; +class GFG{ +/*Function for finding grandSum*/ + +static int findSubarraySum(int arr[], int n) +{ + int i, j; +/* Calculate cumulative sum of array + cArray[0] will store sum of zero elements*/ + + int cArray[] = new int[n + 1]; + for(i = 0; i < n; i++) + cArray[i + 1] = cArray[i] + arr[i]; + Vector subArrSum = new Vector(); +/* Store all subarray sum in vector*/ + + for(i = 1; i <= n; i++) + for(j = i; j <= n; j++) + subArrSum.add(cArray[j] - + cArray[i - 1]); +/* Sort the vector*/ + + Collections.sort(subArrSum); +/* Mark all duplicate sub-array + sum to zero*/ + + int totalSum = 0; + for(i = 0; i < subArrSum.size() - 1; i++) + { + if (subArrSum.get(i) == + subArrSum.get(i + 1)) + { + j = i + 1; + while (subArrSum.get(j) == + subArrSum.get(i) && + j < subArrSum.size()) + { + subArrSum.set(j, 0); + j++; + } + subArrSum.set(i, 0); + } + } +/* Calculate total sum*/ + + for(i = 0; i < subArrSum.size(); i++) + totalSum += subArrSum.get(i); +/* Return totalSum*/ + + return totalSum; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = { 3, 2, 3, 1, 4 }; + int n = arr.length; + System.out.print(findSubarraySum(arr, n)); +} +}"," '''Python3 for finding sum of all +unique subarray sum + ''' '''function for finding grandSum''' + +def findSubarraySum(arr, n): + ''' calculate cumulative sum of array + cArray[0] will store sum of zero elements''' + + cArray = [0 for i in range(n + 1)] + for i in range(0, n, 1): + cArray[i + 1] = cArray[i] + arr[i] + subArrSum = [] + ''' store all subarray sum in vector''' + + for i in range(1, n + 1, 1): + for j in range(i, n + 1, 1): + subArrSum.append(cArray[j] - + cArray[i - 1]) + ''' sort the vector''' + + subArrSum.sort(reverse = False) + ''' mark all duplicate sub-array + sum to zero''' + + totalSum = 0 + for i in range(0, len(subArrSum) - 1, 1): + if (subArrSum[i] == subArrSum[i + 1]): + j = i + 1 + while (subArrSum[j] == subArrSum[i] and + j < len(subArrSum)): + subArrSum[j] = 0 + j += 1 + subArrSum[i] = 0 + ''' calculate total sum''' + + for i in range(0, len(subArrSum), 1): + totalSum += subArrSum[i] + ''' return totalSum''' + + return totalSum + '''Drivers code''' + +if __name__ == '__main__': + arr = [3, 2, 3, 1, 4] + n = len(arr) + print(findSubarraySum(arr, n))" +Postorder traversal of Binary Tree without recursion and without stack,"/*JAVA program or postorder traversal*/ + +import java.util.*; +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + + class Node + { + int data; + Node left, right; + Node(int data) + { + this.data = data; + this.left = this.right = null; + } +}; +class GFG +{ +Node root; +/* Helper function that allocates a new node with the +given data and null left and right pointers. */ + + void postorder(Node head) +{ + Node temp = root; + HashSet visited = new HashSet<>(); + while ((temp != null && !visited.contains(temp))) + { +/* Visited left subtree*/ + + if (temp.left != null && + !visited.contains(temp.left)) + temp = temp.left; +/* Visited right subtree*/ + + else if (temp.right != null && + !visited.contains(temp.right)) + temp = temp.right; +/* Print node*/ + + else + { + System.out.printf(""%d "", temp.data); + visited.add(temp); + temp = head; + } + } +} +/* Driver program to test above functions*/ + +public static void main(String[] args) +{ + GFG gfg = new GFG(); + gfg.root = new Node(8); + gfg.root.left = new Node(3); + gfg.root.right = new Node(10); + gfg.root.left.left = new Node(1); + gfg.root.left.right = new Node(6); + gfg.root.left.right.left = new Node(4); + gfg.root.left.right.right = new Node(7); + gfg.root.right.right = new Node(14); + gfg.root.right.right.left = new Node(13); + gfg.postorder(gfg.root); +} +}"," '''Python program or postorder traversal''' + + ''' A binary tree node has data, pointer to left child +and a pointer to right child ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None ''' Helper function that allocates a new node with the +given data and NULL left and right pointers. ''' + +def postorder(head): + temp = head + visited = set() + while (temp and temp not in visited): + ''' Visited left subtree''' + + if (temp.left and temp.left not in visited): + temp = temp.left + ''' Visited right subtree''' + + elif (temp.right and temp.right not in visited): + temp = temp.right + ''' Print node''' + + else: + print(temp.data, end = "" "") + visited.add(temp) + temp = head + ''' Driver program to test above functions''' + +if __name__ == '__main__': + root = newNode(8) + root.left = newNode(3) + root.right = newNode(10) + root.left.left = newNode(1) + root.left.right = newNode(6) + root.left.right.left = newNode(4) + root.left.right.right = newNode(7) + root.right.right = newNode(14) + root.right.right.left = newNode(13) + postorder(root)" +Number which has the maximum number of distinct prime factors in the range M to N,"/*Java program to print the +Number which has the maximum +number of distinct prime +factors of numbers in range +m to n*/ + +import java.io.*; +class GFG +{ +/*Function to return +the maximum number*/ + +static int maximumNumberDistinctPrimeRange(int m, + int n) +{ +/* array to store the + number of distinct primes*/ + + long factorCount[] = new long[n + 1]; +/* true if index 'i' + is a prime*/ + + boolean prime[] = new boolean[n + 1]; +/* initializing the number + of factors to 0 and*/ + + for (int i = 0; i <= n; i++) + { + factorCount[i] = 0; +/*Used in Sieve*/ + +prime[i] = true; + } + for (int i = 2; i <= n; i++) + { +/* condition works only when + 'i' is prime, hence for + factors of all prime number, + the prime status is changed to false*/ + + if (prime[i] == true) + { +/* Number is prime*/ + + factorCount[i] = 1; +/* number of factor of + a prime number is 1*/ + + for (int j = i * 2; j <= n; j += i) + { +/* incrementing factorCount + all the factors of i*/ + + factorCount[j]++; +/* and changing prime + status to false*/ + + prime[j] = false; + } + } + } +/* Initialize the max and num*/ + + int max = (int)factorCount[m]; + int num = m; +/* Gets the maximum number*/ + + for (int i = m; i <= n; i++) + { +/* Gets the maximum number*/ + + if (factorCount[i] > max) + { + max = (int)factorCount[i]; + num = i; + } + } + return num; +} +/*Driver code*/ + +public static void main (String[] args) +{ +int m = 4, n = 6; +/*Calling function*/ + +System.out.println(maximumNumberDistinctPrimeRange(m, n)); +} +}"," '''Python 3 program to print the +Number which has the maximum number +of distinct prime factors of +numbers in range m to n + ''' '''Function to return the maximum number''' + +def maximumNumberDistinctPrimeRange(m, n): + ''' array to store the number + of distinct primes''' + + factorCount = [0] * (n + 1) + ''' true if index 'i' is a prime''' + + prime = [False] * (n + 1) + ''' initializing the number of + factors to 0 and''' + + for i in range(n + 1) : + factorCount[i] = 0 + '''Used in Sieve''' + + prime[i] = True + for i in range(2, n + 1) : + ''' condition works only when 'i' + is prime, hence for factors of + all prime number, the prime + status is changed to false''' + + if (prime[i] == True) : + ''' Number is prime''' + + factorCount[i] = 1 + ''' number of factor of a + prime number is 1''' + + for j in range(i * 2, n + 1, i) : + ''' incrementing factorCount all + the factors of i''' + + factorCount[j] += 1 + ''' and changing prime status + to false''' + + prime[j] = False + ''' Initialize the max and num''' + + max = factorCount[m] + num = m + ''' Gets the maximum number''' + + for i in range(m, n + 1) : + ''' Gets the maximum number''' + + if (factorCount[i] > max) : + max = factorCount[i] + num = i + return num + '''Driver code''' + +if __name__ == ""__main__"": + m = 4 + n = 6 + ''' Calling function''' + + print(maximumNumberDistinctPrimeRange(m, n))" +Count triplets with sum smaller than a given value,"/*A Simple Java program to count triplets with sum smaller +than a given value*/ + + +import java.util.Arrays; + +class Test +{ + static int arr[] = new int[]{5, 1, 3, 4, 7}; + + static int countTriplets(int n, int sum) + { +/* Sort input array*/ + + Arrays.sort(arr); + +/* Initialize result*/ + + int ans = 0; + +/* Every iteration of loop counts triplet with + first element as arr[i].*/ + + for (int i = 0; i < n - 2; i++) + { +/* Initialize other two elements as corner elements + of subarray arr[j+1..k]*/ + + int j = i + 1, k = n - 1; + +/* Use Meet in the Middle concept*/ + + while (j < k) + { +/* If sum of current triplet is more or equal, + move right corner to look for smaller values*/ + + if (arr[i] + arr[j] + arr[k] >= sum) + k--; + +/* Else move left corner*/ + + else + { +/* This is important. For current i and j, there + can be total k-j third elements.*/ + + ans += (k - j); + j++; + } + } + } + return ans; + } + +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + int sum = 12; + System.out.println(countTriplets(arr.length, sum)); + } +} +"," '''Python3 program to count triplets with +sum smaller than a given value''' + + +def countTriplets(arr,n,sum): + + ''' Sort input array''' + + arr.sort() + + ''' Initialize result''' + + ans = 0 + + ''' Every iteration of loop counts triplet with + first element as arr[i].''' + + for i in range(0,n-2): + + ''' Initialize other two elements as corner elements + of subarray arr[j+1..k]''' + + j = i + 1 + k = n-1 + + ''' Use Meet in the Middle concept''' + + while(j < k): + + ''' If sum of current triplet is more or equal, + move right corner to look for smaller values''' + + if (arr[i]+arr[j]+arr[k] >=sum): + k = k-1 + + ''' Else move left corner''' + + else: + + ''' This is important. For current i and j, there + can be total k-j third elements.''' + + ans += (k - j) + j = j+1 + + return ans + + '''Driver program''' + +if __name__=='__main__': + arr = [5, 1, 3, 4, 7] + n = len(arr) + sum = 12 + print(countTriplets(arr, n, sum)) + + +" +Check if it is possible to make array increasing or decreasing by rotating the array,"/*Java implementation of the approach*/ + +class GFG +{ + +/*Function that returns true if the array +can be made increasing or decreasing +after rotating it in any direction*/ + +static boolean isPossible(int a[], int n) +{ +/* If size of the array is less than 3*/ + + if (n <= 2) + return true; + + int flag = 0; + +/* Check if the array is already decreasing*/ + + for (int i = 0; i < n - 2; i++) + { + if (!(a[i] > a[i + 1] && + a[i + 1] > a[i + 2])) + { + flag = 1; + break; + } + } + +/* If the array is already decreasing*/ + + if (flag == 0) + return true; + + flag = 0; + +/* Check if the array is already increasing*/ + + for (int i = 0; i < n - 2; i++) + { + if (!(a[i] < a[i + 1] && + a[i + 1] < a[i + 2])) + { + flag = 1; + break; + } + } + +/* If the array is already increasing*/ + + if (flag == 0) + return true; + +/* Find the indices of the minimum + && the maximum value*/ + + int val1 = Integer.MAX_VALUE, mini = -1, + val2 = Integer.MIN_VALUE, maxi = 0; + 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; + +/* Check if we can make array increasing*/ + + for (int i = 0; i < maxi; i++) + { + if (a[i] > a[i + 1]) + { + flag = 0; + break; + } + } + +/* If the array is increasing upto max index + && minimum element is right to maximum*/ + + if (flag == 1 && maxi + 1 == mini) + { + flag = 1; + +/* Check if array increasing again or not*/ + + for (int i = mini; i < n - 1; i++) + { + if (a[i] > a[i + 1]) + { + flag = 0; + break; + } + } + if (flag == 1) + return true; + } + + flag = 1; + +/* Check if we can make array decreasing*/ + + for (int i = 0; i < mini; i++) + { + if (a[i] < a[i + 1]) + { + flag = 0; + break; + } + } + +/* If the array is decreasing upto min index + && minimum element is left to maximum*/ + + if (flag == 1 && maxi - 1 == mini) + { + flag = 1; + +/* Check if array decreasing again or not*/ + + for (int i = maxi; i < n - 1; i++) + { + if (a[i] < a[i + 1]) + { + flag = 0; + break; + } + } + if (flag == 1) + return true; + } + +/* If it is not possible to make the + array increasing or decreasing*/ + + return false; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + int a[] = { 4, 5, 6, 2, 3 }; + int n = a.length; + + if (isPossible(a, n)) + System.out.println( ""Yes""); + else + System.out.println( ""No""); +} +} + + +"," '''Python3 implementation of the approach''' + +import sys + + '''Function that returns True if the array +can be made increasing or decreasing +after rotating it in any direction''' + +def isPossible(a, n): + + ''' If size of the array is less than 3''' + + if (n <= 2): + return True; + + flag = 0; + + ''' Check if the array is already decreasing''' + + for i in range(n - 2): + if (not(a[i] > a[i + 1] and + a[i + 1] > a[i + 2])): + flag = 1; + break; + + ''' If the array is already decreasing''' + + if (flag == 0): + return True; + + flag = 0; + + ''' Check if the array is already increasing''' + + for i in range(n - 2): + if (not(a[i] < a[i + 1] and + a[i + 1] < a[i + 2])): + flag = 1; + break; + + ''' If the array is already increasing''' + + if (flag == 0): + return True; + + ''' Find the indices of the minimum + and the maximum value''' + + val1 = sys.maxsize; mini = -1; + val2 = -sys.maxsize; maxi = -1; + for i in range(n): + if (a[i] < val1): + mini = i; + val1 = a[i]; + + if (a[i] > val2): + maxi = i; + val2 = a[i]; + + flag = 1; + + ''' Check if we can make array increasing''' + + for i in range(maxi): + if (a[i] > a[i + 1]): + flag = 0; + break; + + ''' If the array is increasing upto max index + and minimum element is right to maximum''' + + if (flag == 1 and maxi + 1 == mini): + flag = 1; + + ''' Check if array increasing again or not''' + + for i in range(mini, n - 1): + if (a[i] > a[i + 1]): + flag = 0; + break; + + if (flag == 1): + return True; + + flag = 1; + + ''' Check if we can make array decreasing''' + + for i in range(mini): + if (a[i] < a[i + 1]): + flag = 0; + break; + + ''' If the array is decreasing upto min index + and minimum element is left to maximum''' + + if (flag == 1 and maxi - 1 == mini): + flag = 1; + + ''' Check if array decreasing again or not''' + + for i in range(maxi, n - 1): + if (a[i] < a[i + 1]): + flag = 0; + break; + + if (flag == 1): + return True; + + ''' If it is not possible to make the + array increasing or decreasing''' + + return False; + + '''Driver code''' + +a = [ 4, 5, 6, 2, 3 ]; +n = len(a); + +if (isPossible(a, n)): + print(""Yes""); +else: + print(""No""); + + +" +Minimum Initial Points to Reach Destination,"class min_steps +{ + static int minInitialPoints(int points[][],int R,int C) + { +/* dp[i][j] represents the minimum initial points player + should have so that when starts with cell(i, j) successfully + reaches the destination cell(m-1, n-1)*/ + + int dp[][] = new int[R][C]; + int m = R, n = C; +/* Base case*/ + + dp[m-1][n-1] = points[m-1][n-1] > 0? 1: + Math.abs(points[m-1][n-1]) + 1; +/* Fill last row and last column as base to fill + entire table*/ + + for (int i = m-2; i >= 0; i--) + dp[i][n-1] = Math.max(dp[i+1][n-1] - points[i][n-1], 1); + for (int j = n-2; j >= 0; j--) + dp[m-1][j] = Math.max(dp[m-1][j+1] - points[m-1][j], 1); +/* fill the table in bottom-up fashion*/ + + for (int i=m-2; i>=0; i--) + { + for (int j=n-2; j>=0; j--) + { + int min_points_on_exit = Math.min(dp[i+1][j], dp[i][j+1]); + dp[i][j] = Math.max(min_points_on_exit - points[i][j], 1); + } + } + return dp[0][0]; + } + /* Driver program to test above function */ + + public static void main (String args[]) + { + int points[][] = { {-2,-3,3}, + {-5,-10,1}, + {10,30,-5} + }; + int R = 3,C = 3; + System.out.println(""Minimum Initial Points Required: ""+ + minInitialPoints(points,R,C) ); + } +}"," '''Python3 program to find minimum initial +points to reach destination''' + +import math as mt +R = 3 +C = 3 +def minInitialPoints(points): + ''' + dp[i][j] represents the minimum initial + points player should have so that when + starts with cell(i, j) successfully + reaches the destination cell(m-1, n-1) + ''' + + dp = [[0 for x in range(C + 1)] + for y in range(R + 1)] + m, n = R, C + + '''Base case''' + + if points[m - 1][n - 1] > 0: + dp[m - 1][n - 1] = 1 + else: + dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1 ''' + Fill last row and last column as base + to fill entire table + ''' + + for i in range (m - 2, -1, -1): + dp[i][n - 1] = max(dp[i + 1][n - 1] - + points[i][n - 1], 1) + for i in range (2, -1, -1): + dp[m - 1][i] = max(dp[m - 1][i + 1] - + points[m - 1][i], 1) + ''' + fill the table in bottom-up fashion + ''' + + for i in range(m - 2, -1, -1): + for j in range(n - 2, -1, -1): + min_points_on_exit = min(dp[i + 1][j], + dp[i][j + 1]) + dp[i][j] = max(min_points_on_exit - + points[i][j], 1) + return dp[0][0] + '''Driver code''' + +points = [[-2, -3, 3], + [-5, -10, 1], + [10, 30, -5]] +print(""Minimum Initial Points Required:"", + minInitialPoints(points))" +Check if removing an edge can divide a Binary Tree in two halves,"/*Java program to check if there exist an edge whose +removal creates two trees of same size*/ + +class Node +{ + int key; + Node left, right; + public Node(int key) + { + this.key = key; + left = right = null; + } +} +class Res +{ + boolean res = false; +} +class BinaryTree +{ + Node root; +/* To calculate size of tree with given root*/ + + int count(Node node) + { + if (node == null) + return 0; + return count(node.left) + count(node.right) + 1; + } +/* This function returns size of tree rooted with given + root. It also set ""res"" as true if there is an edge + whose removal divides tree in two halves. + n is size of tree*/ + + int checkRec(Node root, int n, Res res) + { +/* Base case*/ + + if (root == null) + return 0; +/* Compute sizes of left and right children*/ + + int c = checkRec(root.left, n, res) + 1 + + checkRec(root.right, n, res); +/* If required property is true for current node + set ""res"" as true*/ + + if (c == n - c) + res.res = true; +/* Return size*/ + + return c; + } +/* This function mainly uses checkRec()*/ + + boolean check(Node root) + { +/* Count total nodes in given tree*/ + + int n = count(root); +/* Initialize result and recursively check all nodes*/ + + Res res = new Res(); + checkRec(root, n, res); + return res.res; + } +/* Driver code*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(5); + tree.root.left = new Node(1); + tree.root.right = new Node(6); + tree.root.left.left = new Node(3); + tree.root.right.left = new Node(7); + tree.root.right.right = new Node(4); + if (tree.check(tree.root) == true) + System.out.println(""YES""); + else + System.out.println(""NO""); + } +}"," '''Python3 program to check if there exist +an edge whose removal creates two trees +of same size''' + +class Node: + def __init__(self, x): + self.key = x + self.left = None + self.right = None + '''To calculate size of tree with +given root''' + +def count(node): + if (node == None): + return 0 + return (count(node.left) + + count(node.right) + 1) + '''This function returns size of tree rooted +with given root. It also set ""res"" as true +if there is an edge whose removal divides +tree in two halves.n is size of tree''' + +def checkRec(root, n): + global res + ''' Base case''' + + if (root == None): + return 0 + ''' Compute sizes of left and right children''' + + c = (checkRec(root.left, n) + 1 + + checkRec(root.right, n)) + ''' If required property is true for + current node set ""res"" as true''' + + if (c == n - c): + res = True + ''' Return size''' + + return c + '''This function mainly uses checkRec()''' + +def check(root): + ''' Count total nodes in given tree''' + + n = count(root) + ''' Initialize result and recursively + check all nodes + bool res = false;''' + + checkRec(root, n) + '''Driver code''' + +if __name__ == '__main__': + res = False + root = Node(5) + root.left = Node(1) + root.right = Node(6) + root.left.left = Node(3) + root.right.left = Node(7) + root.right.right = Node(4) + check(root) + if res: + print(""YES"") + else: + print(""NO"")" +Find the Missing Number,"/*Java program to find missing Number*/ + +import java.util.*; +import java.util.Arrays; +class GFG { + public static List + +/* Function to get the missing number*/ + + findDisappearedNumbers(int[] nums) + { + for (int i = 0; i < nums.length; i++) { + int index = Math.abs(nums[i]); + if (nums[index - 1] > 0) { + nums[index - 1] *= -1; + } + } + List res = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + res.add(i + 1); + } + } + return res; + } +/*Driver Code*/ + + public static void main(String[] args) + { + int[] a = { 1, 2, 4, 5, 6 }; + System.out.println(findDisappearedNumbers(a)); + } +}"," '''getMissingNo takes list as argument''' + +def getMissingNo(A): + n = len(A) + total = (n + 1)*(n + 2)/2 + sum_of_A = sum(A) + return total - sum_of_A + + + '''Driver program to test the above function''' + +A = [1, 2, 4, 5, 6] +miss = getMissingNo(A) +print(miss) + +" +Find a pair with given sum in BST,"/*JAVA program to find a pair with +given sum using hashing*/ + +import java.util.*; +class GFG { + static class Node { + int data; + Node left, right; + }; + static Node NewNode(int data) + { + Node temp = new Node(); + temp.data = data; + temp.left = null; + temp.right = null; + return temp; + } + static Node insert(Node root, int key) + { + if (root == null) + return NewNode(key); + if (key < root.data) + root.left = insert(root.left, key); + else + root.right = insert(root.right, key); + return root; + } + static boolean findpairUtil(Node root, int sum, + HashSet set) + { + if (root == null) + return false; + if (findpairUtil(root.left, sum, set)) + return true; + if (set.contains(sum - root.data)) { + System.out.println(""Pair is found ("" + + (sum - root.data) + "", "" + + root.data + "")""); + return true; + } + else + set.add(root.data); + return findpairUtil(root.right, sum, set); + } + static void findPair(Node root, int sum) + { + HashSet set = new HashSet(); + if (!findpairUtil(root, sum, set)) + System.out.print(""Pairs do not exit"" + + ""\n""); + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = null; + root = insert(root, 15); + root = insert(root, 10); + root = insert(root, 20); + root = insert(root, 8); + root = insert(root, 12); + root = insert(root, 16); + root = insert(root, 25); + root = insert(root, 10); + int sum = 33; + findPair(root, sum); + } +}"," '''Python3 program to find a pair with +given sum using hashing''' + +import sys +import math +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None +def insert(root, data): + if root is None: + return Node(data) + if(data < root.data): + root.left = insert(root.left, data) + if(data > root.data): + root.right = insert(root.right, data) + return root +def findPairUtil(root, summ, unsorted_set): + if root is None: + return False + if findPairUtil(root.left, summ, unsorted_set): + return True + if unsorted_set and (summ-root.data) in unsorted_set: + print(""Pair is Found ({},{})"".format(summ-root.data, root.data)) + return True + else: + unsorted_set.add(root.data) + return findPairUtil(root.right, summ, unsorted_set) +def findPair(root, summ): + unsorted_set = set() + if(not findPairUtil(root, summ, unsorted_set)): + print(""Pair do not exist!"") + '''Driver code''' + +if __name__ == '__main__': + root = None + root = insert(root, 15) + root = insert(root, 10) + root = insert(root, 20) + root = insert(root, 8) + root = insert(root, 12) + root = insert(root, 16) + root = insert(root, 25) + root = insert(root, 10) + summ = 33 + findPair(root, summ)" +"Tree Traversals (Inorder, Preorder and Postorder)","/*Java program for different tree traversals*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node { + int key; + Node left, right; + public Node(int item) + { + key = item; + left = right = null; + } +} +class BinaryTree { +/* Root of Binary Tree*/ + + Node root; + BinaryTree() { root = null; } + /* Given a binary tree, print its nodes according to the + ""bottom-up"" postorder traversal. */ + + void printPostorder(Node node) + { + if (node == null) + return; +/* first recur on left subtree*/ + + printPostorder(node.left); +/* then recur on right subtree*/ + + printPostorder(node.right); +/* now deal with the node*/ + + System.out.print(node.key + "" ""); + } + /* Given a binary tree, print its nodes in inorder*/ + + void printInorder(Node node) + { + if (node == null) + return; + /* first recur on left child */ + + printInorder(node.left); + /* then print the data of node */ + + System.out.print(node.key + "" ""); + /* now recur on right child */ + + printInorder(node.right); + } + /* Given a binary tree, print its nodes in preorder*/ + + void printPreorder(Node node) + { + if (node == null) + return; + /* first print data of node */ + + System.out.print(node.key + "" ""); + /* then recur on left sutree */ + + printPreorder(node.left); + /* now recur on right subtree */ + + printPreorder(node.right); + } +/* Wrappers over above recursive functions*/ + + void printPostorder() { printPostorder(root); } + void printInorder() { printInorder(root); } + void printPreorder() { printPreorder(root); } +/* Driver method*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + System.out.println( + ""Preorder traversal of binary tree is ""); + tree.printPreorder(); + System.out.println( + ""\nInorder traversal of binary tree is ""); + tree.printInorder(); + System.out.println( + ""\nPostorder traversal of binary tree is ""); + tree.printPostorder(); + } +}"," '''Python program to for tree traversals''' + '''A class that represents an individual node in a +Binary Tree''' + +class Node: + def __init__(self, key): + self.left = None + self.right = None + self.val = key + '''A function to do postorder tree traversal''' + +def printPostorder(root): + if root: + ''' First recur on left child''' + + printPostorder(root.left) + ''' the recur on right child''' + + printPostorder(root.right) + ''' now print the data of node''' + + print(root.val), + '''A function to do inorder tree traversal''' + +def printInorder(root): + if root: + ''' First recur on left child''' + + printInorder(root.left) + ''' then print the data of node''' + + print(root.val), + ''' now recur on right child''' + + printInorder(root.right) + '''A function to do preorder tree traversal''' + +def printPreorder(root): + if root: + ''' First print the data of node''' + + print(root.val), + ''' Then recur on left child''' + + printPreorder(root.left) + ''' Finally recur on right child''' + + printPreorder(root.right) + '''Driver code''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +print ""Preorder traversal of binary tree is"" +printPreorder(root) +print ""\nInorder traversal of binary tree is"" +printInorder(root) +print ""\nPostorder traversal of binary tree is"" +printPostorder(root)" +Difference Array | Range update query in O(1),"/*Java code to demonstrate Difference Array*/ + +class GFG { +/* Creates a diff array D[] for A[] and returns + it after filling initial values.*/ + + static void initializeDiffArray(int A[], int D[]) + { + int n = A.length; + +/* We use one extra space because + update(l, r, x) updates D[r+1]*/ + + D[0] = A[0]; + D[n] = 0; + for (int i = 1; i < n; i++) + D[i] = A[i] - A[i - 1]; + }/* Does range update*/ + + static void update(int D[], int l, int r, int x) + { + D[l] += x; + D[r + 1] -= x; + } +/* Prints updated Array*/ + + static int printArray(int A[], int D[]) + { + for (int i = 0; i < A.length; i++) { + if (i == 0) + A[i] = D[i]; +/* Note that A[0] or D[0] decides + values of rest of the elements.*/ + + else + A[i] = D[i] + A[i - 1]; + System.out.print(A[i] + "" ""); + } + System.out.println(); + return 0; + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Array to be updated*/ + + int A[] = { 10, 5, 20, 40 }; + int n = A.length; +/* Create and fill difference Array + We use one extra space because + update(l, r, x) updates D[r+1]*/ + + int D[] = new int[n + 1]; + initializeDiffArray(A, D); +/* After below update(l, r, x), the + elements should become 20, 15, 20, 40*/ + + update(D, 0, 1, 10); + printArray(A, D); +/* After below updates, the + array should become 30, 35, 70, 60*/ + + update(D, 1, 3, 20); + update(D, 2, 2, 30); + printArray(A, D); + } +}"," '''Python3 code to demonstrate Difference Array''' + '''Creates a diff array D[] for A[] and returns +it after filling initial values.''' + +def initializeDiffArray( A): + n = len(A) + ''' We use one extra space because + update(l, r, x) updates D[r+1]''' + + D = [0 for i in range(0 , n + 1)] + D[0] = A[0]; D[n] = 0 + for i in range(1, n ): + D[i] = A[i] - A[i - 1] + return D + '''Does range update''' + +def update(D, l, r, x): + D[l] += x + D[r + 1] -= x + '''Prints updated Array''' + +def printArray(A, D): + for i in range(0 , len(A)): + if (i == 0): + A[i] = D[i] + ''' Note that A[0] or D[0] decides + values of rest of the elements.''' + + else: + A[i] = D[i] + A[i - 1] + print(A[i], end = "" "") + print ("""") + '''Driver Code''' + + + ''' Array to be updated''' + +A = [ 10, 5, 20, 40 ] '''Create and fill difference Array''' + +D = initializeDiffArray(A) + '''After below update(l, r, x), the +elements should become 20, 15, 20, 40''' + +update(D, 0, 1, 10) +printArray(A, D) + '''After below updates, the +array should become 30, 35, 70, 60''' + +update(D, 1, 3, 20) +update(D, 2, 2, 30) +printArray(A, D)" +Minimum adjacent swaps required to Sort Binary array,"import java.io.*; + +class GFG { + public static int minswaps(int arr[], int n) + { + int count = 0; + int num_unplaced_zeros = 0; + + for (int index = n - 1; index >= 0; index--) + { + if (arr[index] == 0) + num_unplaced_zeros += 1; + else + count += num_unplaced_zeros; + } + return count; + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 0, 0, 1, 0, 1, 0, 1, 1 }; + System.out.println(minswaps(arr, 9)); + } +} + + +","def minswaps(arr): + count = 0 + num_unplaced_zeros = 0 + + for index in range(len(arr)-1, -1, -1): + if arr[index] == 0: + num_unplaced_zeros += 1 + else: + count += num_unplaced_zeros + return count + + + '''Driver Code''' + + +arr = [0, 0, 1, 0, 1, 0, 1, 1] +print(minswaps(arr))" +Find right sibling of a binary tree with parent pointers,"/*Java program to print right sibling of a node*/ + +public class Right_Sibling { +/* A Binary Tree Node*/ + + static class Node { + int data; + Node left, right, parent; +/* Constructor*/ + + public Node(int data, Node parent) + { + this.data = data; + left = null; + right = null; + this.parent = parent; + } + }; +/* Method to find right sibling*/ + + static Node findRightSibling(Node node, int level) + { + if (node == null || node.parent == null) + return null; +/* GET Parent pointer whose right child is not + a parent or itself of this node. There might + be case when parent has no right child, but, + current node is left child of the parent + (second condition is for that).*/ + + while (node.parent.right == node + || (node.parent.right == null + && node.parent.left == node)) { + if (node.parent == null) + return null; + node = node.parent; + level--; + } +/* Move to the required child, where right sibling + can be present*/ + + node = node.parent.right; +/* find right sibling in the given subtree(from current + node), when level will be 0*/ + + while (level < 0) { +/* Iterate through subtree*/ + + if (node.left != null) + node = node.left; + else if (node.right != null) + node = node.right; + else +/* if no child are there, we cannot have right + sibling in this path*/ + + break; + level++; + } + if (level == 0) + return node; +/* This is the case when we reach 9 node in the tree, + where we need to again recursively find the right + sibling*/ + + return findRightSibling(node, level); + } +/* Driver Program to test above functions*/ + + public static void main(String args[]) + { + Node root = new Node(1, null); + root.left = new Node(2, root); + root.right = new Node(3, root); + root.left.left = new Node(4, root.left); + root.left.right = new Node(6, root.left); + root.left.left.left = new Node(7, root.left.left); + root.left.left.left.left = new Node(10, root.left.left.left); + root.left.right.right = new Node(9, root.left.right); + root.right.right = new Node(5, root.right); + root.right.right.right = new Node(8, root.right.right); + root.right.right.right.right = new Node(12, root.right.right.right); +/* passing 10*/ + + System.out.println(findRightSibling(root.left.left.left.left, 0).data); + } +}"," '''Python3 program to print right sibling +of a node''' + + '''A class to create a new Binary +Tree Node''' + +class newNode: + def __init__(self, item, parent): + self.data = item + self.left = self.right = None + self.parent = parent '''Method to find right sibling''' + +def findRightSibling(node, level): + if (node == None or node.parent == None): + return None + ''' GET Parent pointer whose right child is not + a parent or itself of this node. There might + be case when parent has no right child, but, + current node is left child of the parent + (second condition is for that).''' + + while (node.parent.right == node or + (node.parent.right == None and + node.parent.left == node)): + if (node.parent == None): + return None + node = node.parent + level -= 1 + ''' Move to the required child, where + right sibling can be present''' + + node = node.parent.right + ''' find right sibling in the given subtree + (from current node), when level will be 0''' + + while (level < 0): + ''' Iterate through subtree''' + + if (node.left != None): + node = node.left + elif (node.right != None): + node = node.right + else: + ''' if no child are there, we cannot + have right sibling in this path''' + + break + level += 1 + if (level == 0): + return node + ''' This is the case when we reach 9 node + in the tree, where we need to again + recursively find the right sibling''' + + return findRightSibling(node, level) + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(1, None) + root.left = newNode(2, root) + root.right = newNode(3, root) + root.left.left = newNode(4, root.left) + root.left.right = newNode(6, root.left) + root.left.left.left = newNode(7, root.left.left) + root.left.left.left.left = newNode(10, root.left.left.left) + root.left.right.right = newNode(9, root.left.right) + root.right.right = newNode(5, root.right) + root.right.right.right = newNode(8, root.right.right) + root.right.right.right.right = newNode(12, root.right.right.right) + ''' passing 10''' + + res = findRightSibling(root.left.left.left.left, 0) + if (res == None): + print(""No right sibling"") + else: + print(res.data)" +Maximum sum of i*arr[i] among all rotations of a given array,"/*An efficient Java program to compute +maximum sum of i*arr[i]*/ + +import java.io.*; +class GFG { + static int maxSum(int arr[], int n) + { +/* Compute sum of all array elements*/ + + int cum_sum = 0; + for (int i = 0; i < n; i++) + cum_sum += arr[i]; +/* Compute sum of i*arr[i] for + initial configuration.*/ + + int curr_val = 0; + for (int i = 0; i < n; i++) + curr_val += i * arr[i]; +/* Initialize result*/ + + int res = curr_val; +/* Compute values for other iterations*/ + + for (int i = 1; i < n; i++) + { +/* Compute next value using previous + value in O(1) time*/ + + int next_val = curr_val - (cum_sum - + arr[i-1]) + arr[i-1] * + (n-1); +/* Update current value*/ + + curr_val = next_val; +/* Update result if required*/ + + res = Math.max(res, next_val); + } + return res; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {8, 3, 1, 2}; + int n = arr.length; + System.out.println(maxSum(arr, n)); + } +}"," '''An efficient Python3 program to +compute maximum sum of i * arr[i]''' + +def maxSum(arr, n): + ''' Compute sum of all array elements''' + + cum_sum = 0 + for i in range(0, n): + cum_sum += arr[i] + ''' Compute sum of i * arr[i] for + initial configuration.''' + + curr_val = 0 + for i in range(0, n): + curr_val += i * arr[i] + ''' Initialize result''' + + res = curr_val + ''' Compute values for other iterations''' + + for i in range(1, n): + ''' Compute next value using previous + value in O(1) time''' + + next_val = (curr_val - (cum_sum - arr[i-1]) + + arr[i-1] * (n-1)) + ''' Update current value''' + + curr_val = next_val + ''' Update result if required''' + + res = max(res, next_val) + return res + '''Driver code''' + +arr = [8, 3, 1, 2] +n = len(arr) +print(maxSum(arr, n))" +k-th missing element in sorted array,"/*Java program to check for +even or odd*/ + +import java.io.*; +import java.util.*; + +public class GFG { + +/* Function to find k-th + missing element*/ + + static int missingK(int []a, int k, + int n) + { + int difference = 0, + ans = 0, count = k; + boolean flag = false; + +/* interating over the array*/ + + for(int i = 0 ; i < n - 1; i++) + { + difference = 0; + +/* check if i-th and + (i + 1)-th element + are not consecutive*/ + + if ((a[i] + 1) != a[i + 1]) + { + +/* save their difference*/ + + difference += + (a[i + 1] - a[i]) - 1; + +/* check for difference + and given k*/ + + if (difference >= count) + { + ans = a[i] + count; + flag = true; + break; + } + else + count -= difference; + } + } + +/* if found*/ + + if(flag) + return ans; + else + return -1; + } + +/* Driver code*/ + + public static void main(String args[]) + { + +/* Input array*/ + + int []a = {1, 5, 11, 19}; + +/* k-th missing element + to be found in the array*/ + + int k = 11; + int n = a.length; + +/* calling function to + find missing element*/ + + int missing = missingK(a, k, n); + + System.out.print(missing); + } + +} + + +"," '''Function to find k-th +missing element''' + +def missingK(a, k, n) : + + difference = 0 + ans = 0 + count = k + flag = 0 + + ''' interating over the array''' + + for i in range (0, n-1) : + difference = 0 + + ''' check if i-th and + (i + 1)-th element + are not consecutive''' + + if ((a[i] + 1) != a[i + 1]) : + + + ''' save their difference''' + + difference += (a[i + 1] - a[i]) - 1 + + ''' check for difference + and given k''' + + if (difference >= count) : + ans = a[i] + count + flag = 1 + break + else : + count -= difference + + ''' if found''' + + if(flag) : + return ans + else : + return -1 + + '''Driver code''' + + + '''Input array''' + +a = [1, 5, 11, 19] '''k-th missing element +to be found in the array''' + +k = 11 +n = len(a) + + '''calling function to +find missing element''' + +missing = missingK(a, k, n) + +print(missing) + + +" +Find a sorted subsequence of size 3 in linear time,"/*Java Program for above approach*/ + +class Main +{ +/* Function to find the triplet*/ + + public static void find3Numbers(int[] nums) + { + +/* If number of elements < 3 + then no triplets are possible*/ + + if (nums.length < 3){ + System.out.print(""No such triplet found""); + return; + } + +/* track best sequence length + (not current sequence length)*/ + + int seq = 1; + +/* min number in array*/ + + int min_num = nums[0]; + +/* least max number in best sequence + i.e. track arr[j] (e.g. in + array {1, 5, 3} our best sequence + would be {1, 3} with arr[j] = 3)*/ + + int max_seq = Integer.MIN_VALUE; + +/* save arr[i]*/ + + int store_min = min_num; + +/* Iterate from 1 to nums.size()*/ + + for (int i = 1; i < nums.length; i++) + { + if (nums[i] == min_num) + continue; + + else if (nums[i] < min_num) + { + min_num = nums[i]; + continue; + } + +/* this condition is only hit + when current sequence size is 2*/ + + else if (nums[i] < max_seq) { + +/* update best sequence max number + to a smaller value + (i.e. we've found a + smaller value for arr[j])*/ + + max_seq = nums[i]; + +/* store best sequence start value + i.e. arr[i]*/ + + store_min = min_num; + } + +/* Increase best sequence length & + save next number in our triplet*/ + + else if (nums[i] > max_seq) + { + seq++; + +/* We've found our arr[k]! + Print the output*/ + + if (seq == 3) + { + System.out.println(""Triplet: "" + store_min + + "", "" + max_seq + "", "" + nums[i]); + return; + } + max_seq = nums[i]; + } + } + +/* No triplet found*/ + + System.out.print(""No such triplet found""); + } + +/* Driver program*/ + + public static void main(String[] args) + { + int[] nums = {1,2,-1,7,5}; + +/* Function Call*/ + + find3Numbers(nums); + } +} + + +"," '''Python3 Program for above approach''' + +import sys + + '''Function to find the triplet''' + +def find3Numbers(nums): + + ''' If number of elements < 3 + then no triplets are possible''' + + if (len(nums) < 3): + print(""No such triplet found"", end = '') + return + + ''' Track best sequence length + (not current sequence length)''' + + seq = 1 + + ''' min number in array''' + + min_num = nums[0] + + ''' Least max number in best sequence + i.e. track arr[j] (e.g. in + array {1, 5, 3} our best sequence + would be {1, 3} with arr[j] = 3)''' + + max_seq = -sys.maxsize - 1 + + ''' Save arr[i]''' + + store_min = min_num + + ''' Iterate from 1 to nums.size()''' + + for i in range(1, len(nums)): + if (nums[i] == min_num): + continue + elif (nums[i] < min_num): + min_num = nums[i] + continue + + ''' This condition is only hit + when current sequence size is 2''' + + elif (nums[i] < max_seq): + + ''' Update best sequence max number + to a smaller value + (i.e. we've found a + smaller value for arr[j])''' + + max_seq = nums[i] + + ''' Store best sequence start value + i.e. arr[i]''' + + store_min = min_num + + ''' Increase best sequence length & + save next number in our triplet''' + + elif (nums[i] > max_seq): + if seq == 1: + store_min = min_num + seq += 1 + + ''' We've found our arr[k]! + Print the output''' + + if (seq == 3): + print(""Triplet: "" + str(store_min) + + "", "" + str(max_seq) + "", "" + + str(nums[i])) + + return + + max_seq = nums[i] + + ''' No triplet found''' + + print(""No such triplet found"", end = '') + + '''Driver Code''' + +if __name__=='__main__': + + nums = [ 1, 2, -1, 7, 5 ] + + ''' Function Call''' + + find3Numbers(nums) + + +" +Linked List | Set 2 (Inserting a node),"/* This function is in LinkedList class. Inserts a + new Node at front of the list. This method is + defined inside LinkedList class shown above */ + +public void push(int new_data) +{ + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + + /* 3. Make next of new Node as head */ + + new_node.next = head; + + /* 4. Move the head to point to new Node */ + + head = new_node; +} +"," '''This function is in LinkedList class +Function to insert a new node at the beginning''' + +def push(self, new_data): + + ''' 1 & 2: Allocate the Node & + Put in the data''' + + new_node = Node(new_data) + + ''' 3. Make next of new Node as head''' + + new_node.next = self.head + + ''' 4. Move the head to point to new Node''' + + self.head = new_node +" +Delete all odd or even positioned nodes from Circular Linked List,"/*Function to delete that all +node whose index position is odd*/ + +static void DeleteAllOddNode(Node head) +{ + int len = Length(head); + int count = 0; + Node previous = head, next = head; + +/* Check list have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nDelete Last List is empty\n""); + return; + } + +/* If list have single node means + odd position then delete it*/ + + if (len == 1) + { + DeleteFirst(head); + return; + } + +/* Traverse first to last if + list have more than one node*/ + + while (len > 0) + { + +/* Delete first position node + which is odd position*/ + + if (count == 0) + { + +/* Function to delete first node*/ + + DeleteFirst(head); + } + +/* Check position is odd or not + if yes then delete node*/ + + if (count % 2 == 0 && count != 0) + { + deleteNode(head, previous); + } + + previous = previous.next; + next = previous.next; + + len--; + count++; + } + return; +} + + +", +Hypercube Graph,"/*Java program to find vertices in +a hypercube graph of order n*/ + +class GfG +{ +/* Function to find power of 2*/ + + static int power(int n) + { + if (n == 1) + return 2; + return 2 * power(n - 1); + } +/* Driver program*/ + + public static void main(String []args) + { + int n = 4; + System.out.println(power(n)); + } +}"," '''Python3 program to find vertices in a hypercube + graph of order n''' + + '''function to find power of 2''' + +def power(n): + if n==1: + return 2 + return 2*power(n-1) '''Dricer code''' + +n =4 +print(power(n))" +Count pairs from two sorted arrays whose sum is equal to a given value x,"/*Java implementation to count pairs from +both sorted arrays whose sum is equal +to a given value*/ + +import java.io.*; +class GFG { +/* function to count all pairs + from both the sorted arrays + whose sum is equal to a given + value*/ + + static int countPairs(int []arr1, + int []arr2, int m, int n, int x) + { + int count = 0; +/* generating pairs from + both the arrays*/ + + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) +/* if sum of pair is equal + to 'x' increment count*/ + + if ((arr1[i] + arr2[j]) == x) + count++; +/* required count of pairs*/ + + return count; + } +/* Driver Code*/ + + public static void main (String[] args) + { + int arr1[] = {1, 3, 5, 7}; + int arr2[] = {2, 3, 5, 8}; + int m = arr1.length; + int n = arr2.length; + int x = 10; + System.out.println( ""Count = "" + + countPairs(arr1, arr2, m, n, x)); + } +}"," '''python implementation to count +pairs from both sorted arrays +whose sum is equal to a given +value + ''' '''function to count all pairs from +both the sorted arrays whose sum +is equal to a given value''' + +def countPairs(arr1, arr2, m, n, x): + count = 0 + ''' generating pairs from both + the arrays''' + + for i in range(m): + for j in range(n): + ''' if sum of pair is equal + to 'x' increment count''' + + if arr1[i] + arr2[j] == x: + count = count + 1 + ''' required count of pairs''' + + return count + '''Driver Program''' + +arr1 = [1, 3, 5, 7] +arr2 = [2, 3, 5, 8] +m = len(arr1) +n = len(arr2) +x = 10 +print(""Count = "", + countPairs(arr1, arr2, m, n, x))" +Count set bits in an integer,"/*Java implementation of the approach*/ + +class GFG { +/* Lookup table*/ + + static int[] BitsSetTable256 = new int[256]; +/* Function to initialise the lookup table*/ + + public static void initialize() + { +/* To initially generate the + table algorithmically*/ + + BitsSetTable256[0] = 0; + for (int i = 0; i < 256; i++) { + BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2]; + } + } +/* Function to return the count + of set bits in n*/ + + public static int countSetBits(int n) + { + return (BitsSetTable256[n & 0xff] + + BitsSetTable256[(n >> 8) & 0xff] + + BitsSetTable256[(n >> 16) & 0xff] + + BitsSetTable256[n >> 24]); + } +/* Driver code*/ + + public static void main(String[] args) + { +/* Initialise the lookup table*/ + + initialize(); + int n = 9; + System.out.print(countSetBits(n)); + } +}"," '''Python implementation of the approach''' + ''' Lookup table''' + +BitsSetTable256 = [0] * 256 + '''Function to initialise the lookup table''' + +def initialize(): + ''' To initially generate the + table algorithmically''' + + BitsSetTable256[0] = 0 + for i in range(256): + BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2] + '''Function to return the count +of set bits in n''' + +def countSetBits(n): + return (BitsSetTable256[n & 0xff] + + BitsSetTable256[(n >> 8) & 0xff] + + BitsSetTable256[(n >> 16) & 0xff] + + BitsSetTable256[n >> 24]) + '''Driver code''' + '''Initialise the lookup table''' + +initialize() +n = 9 +print(countSetBits(n))" +Maximum difference between frequency of two elements such that element having greater frequency is also greater,"/*Java program to find maximum difference +between frequency of any two element +such that element with greater frequency +is also greater in value.*/ + +import java.util.*; +class GFG +{ +/*Return the maximum difference between +frequencies of any two elements such that +element with greater frequency is also +greater in value.*/ + +static int maxdiff(int arr[], int n) +{ + Map freq = new HashMap<>(); +/* Finding the frequency of each element.*/ + + for (int i = 0; i < n; i++) + freq.put(arr[i], + freq.get(arr[i]) == null ? 1 : + freq.get(arr[i]) + 1); + int ans = 0; + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { +/* finding difference such that element + having greater frequency is also + greater in value.*/ + + if (freq.get(arr[i]) > freq.get(arr[j]) && + arr[i] > arr[j]) + ans = Math.max(ans, freq.get(arr[i]) - + freq.get(arr[j])); + else if (freq.get(arr[i]) < freq.get(arr[j]) && + arr[i] < arr[j] ) + ans = Math.max(ans, freq.get(arr[j]) - + freq.get(arr[i])); + } + } + return ans; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int arr[] = { 3, 1, 3, 2, 3, 2 }; + int n = arr.length; + System.out.println(maxdiff(arr, n)); +} +}"," '''Python program to find maximum difference +between frequency of any two element +such that element with greater frequency +is also greater in value.''' + +from collections import defaultdict + '''Return the maximum difference between +frequencies of any two elements such that +element with greater frequency is also +greater in value.''' + +def maxdiff(arr, n): + freq = defaultdict(lambda: 0) + ''' Finding the frequency of each element.''' + + for i in range(n): + freq[arr[i]] += 1 + ans = 0 + for i in range(n): + for j in range(n): + ''' finding difference such that element + having greater frequency is also + greater in value.''' + + if freq[arr[i]] > freq[arr[j]] and arr[i] > arr[j]: + ans = max(ans, freq[arr[i]] - freq[arr[j]]) + elif freq[arr[i]] < freq[arr[j]] and arr[i] < arr[j]: + ans = max(ans, freq[arr[j]] - freq[arr[i]]) + return ans + '''Driver Code''' + +arr = [3,1,3,2,3,2] +n = len(arr) +print(maxdiff(arr,n))" +Position of rightmost set bit,"/*Java implementation of above approach*/ + +public class GFG { + static int INT_SIZE = 32; + static int Right_most_setbit(int num) + { + int pos = 1; +/* counting the position of first set bit*/ + + for (int i = 0; i < INT_SIZE; i++) { + if ((num & (1 << i))== 0) + pos++; + else + break; + } + return pos; + } +/* Driver code*/ + + public static void main(String[] args) { + int num = 18; + int pos = Right_most_setbit(num); + System.out.println(pos); + } +}"," '''Python 3 implementation of above approach''' + +INT_SIZE = 32 +def Right_most_setbit(num) : + pos = 1 + ''' counting the position of first set bit''' + + for i in range(INT_SIZE) : + if not(num & (1 << i)) : + pos += 1 + else : + break + return pos + '''Driver code''' + +if __name__ == ""__main__"" : + num = 18 + pos = Right_most_setbit(num) + print(pos)" +Find final value if we double after every successful search in array,"/*Java program to find value +if we double the value after +every successful search*/ + + +class GFG { +/* Function to Find the value of k*/ + + static int findValue(int arr[], int n, int k) + { + +/* Search for k. After every successful + search, double k.*/ + + for (int i = 0; i < n; i++) + if (arr[i] == k) + k *= 2; + + return k; + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { 2, 3, 4, 10, 8, 1 }, k = 2; + int n = arr.length; + System.out.print(findValue(arr, n, k)); + } +} +"," '''Python program to find +value if we double +the value after every +successful search''' + + + '''Function to Find the value of k''' + + + +def findValue(arr, n, k): + + ''' Search for k. + After every successful + search, double k.''' + + for i in range(n): + if (arr[i] == k): + k = k * 2 + + return k + + '''Driver's Code''' + + + +arr = [2, 3, 4, 10, 8, 1] +k = 2 +n = len(arr) + +print(findValue(arr, n, k)) + + +" +Largest Derangement of a Sequence,"/*Java program to find the largest derangement*/ + +import java.io.*; +import java.util.Collections; +import java.util.PriorityQueue; +class GFG{ +public static void printLargest(int a[],int n) +{ + PriorityQueue pq = new PriorityQueue<>( + Collections.reverseOrder()); +/* Stores result*/ + + int res[] = new int[n]; +/* Insert all elements into a priority queue*/ + + for(int i = 0; i < n; i++) + { + pq.add(a[i]); + } +/* Fill Up res[] from left to right*/ + + for(int i = 0; i < n; i++) + { + int p = pq.peek(); + pq.remove(); + if (p != a[i] || i == n - 1) + { + res[i] = p; + } + else + { +/* New Element poped equals the element + in original sequence. Get the next + largest element*/ + + res[i] = pq.peek(); + pq.remove(); + pq.add(p); + } + } +/* If given sequence is in descending + order then we need to swap last two + elements again*/ + + if (res[n - 1] == a[n - 1]) + { + res[n - 1] = res[n - 2]; + res[n - 2] = a[n - 1]; + } + System.out.println(""Largest Derangement""); + for(int i = 0; i < n; i++) + { + System.out.print(res[i] + "" ""); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + int n = 7; + int seq[] = { 92, 3, 52, 13, 2, 31, 1 }; + printLargest(seq, n); +} +}"," '''Python3 program to find the largest derangement''' + +def printLargest(seq, N) : + '''Stores result''' + + res = [0]*N + ''' Insert all elements into a priority queue''' + + pq = [] + for i in range(N) : + pq.append(seq[i]) + ''' Fill Up res[] from left to right''' + + for i in range(N) : + pq.sort() + pq.reverse() + d = pq[0] + del pq[0] + if (d != seq[i] or i == N - 1) : + res[i] = d + else : + ''' New Element poped equals the element + in original sequence. Get the next + largest element''' + + res[i] = pq[0] + del pq[0] + pq.append(d) + ''' If given sequence is in descending order then + we need to swap last two elements again''' + + if (res[N - 1] == seq[N - 1]) : + res[N - 1] = res[N - 2] + res[N - 2] = seq[N - 1] + print(""Largest Derangement"") + for i in range(N) : + print(res[i], end = "" "") + '''Driver code''' + +seq = [ 92, 3, 52, 13, 2, 31, 1 ] +n = len(seq) +printLargest(seq, n)" +Check if strings are rotations of each other or not | Set 2,"/*Java program to check if two strings are rotations +of each other.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class stringMatching { + public static boolean isRotation(String a, String b) + { + int n = a.length(); + int m = b.length(); + if (n != m) + return false; + +/* create lps[] that will hold the longest + prefix suffix values for pattern*/ + + int lps[] = new int[n]; + +/* length of the previous longest prefix suffix*/ + + int len = 0; + int i = 1; +/*lps[0] is always 0*/ + +lps[0] = 0; + +/* the loop calculates lps[i] for i = 1 to n-1*/ + + while (i < n) { + if (a.charAt(i) == b.charAt(len)) { + lps[i] = ++len; + ++i; + } + else { + if (len == 0) { + lps[i] = 0; + ++i; + } + else { + len = lps[len - 1]; + } + } + } + + i = 0; + +/* match from that rotating point*/ + + for (int k = lps[n - 1]; k < m; ++k) { + if (b.charAt(k) != a.charAt(i++)) + return false; + } + return true; + } + +/* Driver code*/ + + public static void main(String[] args) + { + String s1 = ""ABACD""; + String s2 = ""CDABA""; + + System.out.println(isRotation(s1, s2) ? ""1"" : ""0""); + } +} +"," '''Python program to check if +two strings are rotations +of each other''' + +def isRotation(a: str, b: str) -> bool: + n = len(a) + m = len(b) + if (n != m): + return False + + ''' create lps[] that + will hold the longest + prefix suffix values + for pattern''' + + lps = [0 for _ in range(n)] + + ''' length of the previous + longest prefix suffix''' + + length = 0 + i = 1 + + ''' lps[0] is always 0''' + + lps[0] = 0 + + ''' the loop calculates + lps[i] for i = 1 to n-1''' + + while (i < n): + if (a[i] == b[length]): + length += 1 + lps[i] = length + i += 1 + else: + if (length == 0): + lps[i] = 0 + i += 1 + else: + length = lps[length - 1] + i = 0 + + ''' Match from that rotating + point''' + + for k in range(lps[n - 1], m): + if (b[k] != a[i]): + return False + i += 1 + return True + + '''Driver code''' + +if __name__ == ""__main__"": + + s1 = ""ABACD"" + s2 = ""CDABA"" + print(""1"" if isRotation(s1, s2) else ""0"") + + +" +Calculate depth of a full Binary tree from Preorder,"/*Java program to find height +of full binary tree using +preorder*/ + +import java .io.*; +class GFG +{ +/* function to return max + of left subtree height + or right subtree height*/ + + static int findDepthRec(String tree, + int n, int index) + { + if (index >= n || + tree.charAt(index) == 'l') + return 0; +/* calc height of left subtree + (In preorder left subtree + is processed before right)*/ + + index++; + int left = findDepthRec(tree, + n, index); +/* calc height of + right subtree*/ + + index++; + int right = findDepthRec(tree, n, index); + return Math.max(left, right) + 1; + } +/* Wrapper over findDepthRec()*/ + + static int findDepth(String tree, + int n) + { + int index = 0; + return (findDepthRec(tree, + n, index)); + } +/* Driver Code*/ + + static public void main(String[] args) + { + String tree = ""nlnnlll""; + int n = tree.length(); + System.out.println(findDepth(tree, n)); + } +}"," '''Python program to find height of full binary tree +using preorder''' + '''function to return max of left subtree height +or right subtree height''' + +def findDepthRec(tree, n, index) : + if (index[0] >= n or tree[index[0]] == 'l'): + return 0 + ''' calc height of left subtree (In preorder + left subtree is processed before right)''' + + index[0] += 1 + left = findDepthRec(tree, n, index) + ''' calc height of right subtree''' + + index[0] += 1 + right = findDepthRec(tree, n, index) + return (max(left, right) + 1) + '''Wrapper over findDepthRec()''' + +def findDepth(tree, n) : + index = [0] + return findDepthRec(tree, n, index) + '''Driver program to test above functions''' + +if __name__ == '__main__': + tree= ""nlnnlll"" + n = len(tree) + print(findDepth(tree, n))" +Deletion at different positions in a Circular Linked List,"/*Function to delete last node of +Circular Linked List*/ + +static Node DeleteLast(Node head) +{ + Node current = head, temp = head, previous = null; + +/* Check if list doesn't have any node + if not then return*/ + + if (head == null) + { + System.out.printf(""\nList is empty\n""); + return null; + } + +/* Check if list have single node + if yes then delete it and return*/ + + if (current.next == current) + { + head = null; + return null; + } + +/* Move first node to last + previous*/ + + while (current.next != head) + { + previous = current; + current = current.next; + } + + previous.next = current.next; + head = previous.next; + + return head; +} + + +"," '''Function to delete last node of +Circular Linked List''' + +def DeleteLast(head): + current = head + temp = head + previous = None + + ''' check if list doesn't have any node + if not then return''' + + if (head == None): + print(""\nList is empty"") + return None + + ''' check if list have single node + if yes then delete it and return''' + + if (current.next == current): + head = None + return None + + ''' move first node to last + previous''' + + while (current.next != head): + previous = current + current = current.next + + previous.next = current.next + head = previous.next + + return head + + +" +Count Strictly Increasing Subarrays,"/*Java program to count number of strictly +increasing subarrays*/ + + + +class Test +{ + static int arr[] = new int[]{1, 2, 2, 4}; + + static int countIncreasing(int n) + { +/* Initialize count of subarrays as 0*/ + + int cnt = 0; + +/* Pick starting point*/ + + for (int i=0; i arr[j-1]) + cnt++; + +/* If subarray arr[i..j] is not strictly + increasing, then subarrays after it , i.e., + arr[i..j+1], arr[i..j+2], .... cannot + be strictly increasing*/ + + else + break; + } + } + return cnt; + } +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + System.out.println(""Count of strictly increasing subarrays is "" + + countIncreasing(arr.length)); + } +} +"," '''Python3 program to count number +of strictly increasing subarrays''' + + +def countIncreasing(arr, n): + + ''' Initialize count of subarrays as 0''' + + cnt = 0 + + ''' Pick starting point''' + + for i in range(0, n) : + + ''' Pick ending point''' + + for j in range(i + 1, n) : + if arr[j] > arr[j - 1] : + cnt += 1 + + ''' If subarray arr[i..j] is not strictly + increasing, then subarrays after it , i.e., + arr[i..j+1], arr[i..j+2], .... cannot + be strictly increasing''' + + else: + break + return cnt + + + '''Driver code''' + +arr = [1, 2, 2, 4] +n = len(arr) +print (""Count of strictly increasing subarrays is"", + countIncreasing(arr, n)) + + +" +Get level of a node in binary tree | iterative approach,"/*Java program to print level of given node +in binary tree iterative approach */ + +import java.io.*; +import java.util.*; +class GFG +{ + +/* node of binary tree*/ + + static class node + { + int data; + node left, right; + node(int data) + { + this.data = data; + this.left = this.right = null; + } + } +/* utility function to return level of given node*/ + + static int getLevel(node root, int data) + { + Queue q = new LinkedList<>(); + int level = 1; + q.add(root); +/* extra NULL is pushed to keep track + of all the nodes to be pushed before + level is incremented by 1*/ + + q.add(null); + while (!q.isEmpty()) + { + node temp = q.poll(); + if (temp == null) + { + if (q.peek() != null) + { + q.add(null); + } + level += 1; + } + else + { + if (temp.data == data) + { + return level; + } + if (temp.left != null) + { + q.add(temp.left); + } + if (temp.right != null) + { + q.add(temp.right); + } + } + } + return 0; + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* create a binary tree*/ + + node root = new node(20); + root.left = new node(10); + root.right = new node(30); + root.left.left = new node(5); + root.left.right = new node(15); + root.left.right.left = new node(12); + root.right.left = new node(25); + root.right.right = new node(40); +/* return level of node*/ + + int level = getLevel(root, 30); + if (level != 0) + System.out.println(""level of node 30 is "" + level); + else + System.out.println(""node 30 not found""); + level = getLevel(root, 12); + if (level != 0) + System.out.println(""level of node 12 is "" + level); + else + System.out.println(""node 12 not found""); + level = getLevel(root, 25); + if (level != 0) + System.out.println(""level of node 25 is "" + level); + else + System.out.println(""node 25 not found""); + level = getLevel(root, 27); + if (level != 0) + System.out.println(""level of node 27 is "" + level); + else + System.out.println(""node 27 not found""); + } +}"," '''Python3 program to find closest +value in Binary search Tree''' + +_MIN = -2147483648 +_MAX = 2147483648 + '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class getnode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''utility function to return level +of given node''' + +def getlevel(root, data): + q = [] + level = 1 + q.append(root) + ''' extra None is appended to keep track + of all the nodes to be appended + before level is incremented by 1 ''' + + q.append(None) + while (len(q)): + temp = q[0] + q.pop(0) + if (temp == None) : + if len(q) == 0: + return 0 + if (q[0] != None): + q.append(None) + level += 1 + else : + if (temp.data == data) : + return level + if (temp.left): + q.append(temp.left) + if (temp.right) : + q.append(temp.right) + return 0 + '''Driver Code ''' + +if __name__ == '__main__': + ''' create a binary tree ''' + + root = getnode(20) + root.left = getnode(10) + root.right = getnode(30) + root.left.left = getnode(5) + root.left.right = getnode(15) + root.left.right.left = getnode(12) + root.right.left = getnode(25) + root.right.right = getnode(40) + ''' return level of node ''' + + level = getlevel(root, 30) + if level != 0: + print(""level of node 30 is"", level) + else: + print(""node 30 not found"") + level = getlevel(root, 12) + if level != 0: + print(""level of node 12 is"", level) + else: + print(""node 12 not found"") + level = getlevel(root, 25) + if level != 0: + print(""level of node 25 is"", level) + else: + print(""node 25 not found"") + level = getlevel(root, 27) + if level != 0: + print(""level of node 27 is"", level) + else: + print(""node 27 not found"")" +Check if each internal node of a BST has exactly one child,"/*Check if each internal node of BST has only one child*/ + +class BinaryTree { + boolean hasOnlyOneChild(int pre[], int size) { + int nextDiff, lastDiff; + for (int i = 0; i < size - 1; i++) { + nextDiff = pre[i] - pre[i + 1]; + lastDiff = pre[i] - pre[size - 1]; + if (nextDiff * lastDiff < 0) { + return false; + }; + } + return true; + } +/* Driver code*/ + + public static void main(String[] args) { + BinaryTree tree = new BinaryTree(); + int pre[] = new int[]{8, 3, 5, 7, 6}; + int size = pre.length; + if (tree.hasOnlyOneChild(pre, size) == true) { + System.out.println(""Yes""); + } else { + System.out.println(""No""); + } + } +}"," '''Check if each internal +node of BST has only one child''' + +def hasOnlyOneChild (pre, size): + nextDiff=0; lastDiff=0 + for i in range(size-1): + nextDiff = pre[i] - pre[i+1] + lastDiff = pre[i] - pre[size-1] + if nextDiff*lastDiff < 0: + return False + return True + '''driver program to +test above function''' + +if __name__ == ""__main__"": + pre = [8, 3, 5, 7, 6] + size= len(pre) + if (hasOnlyOneChild(pre,size) == True): + print(""Yes"") + else: + print(""No"")" +Finite Automata algorithm for Pattern Searching,"/*Java program for Finite Automata Pattern +searching Algorithm*/ + +class GFG { + static int NO_OF_CHARS = 256; + static int getNextState(char[] pat, int M, + int state, int x) + { +/* If the character c is same as next + character in pattern,then simply + increment state*/ + + if(state < M && x == pat[state]) + return state + 1; +/* ns stores the result which is next state*/ + + int ns, i; +/* ns finally contains the longest prefix + which is also suffix in ""pat[0..state-1]c"" + Start from the largest possible value + and stop when you find a prefix which + is also suffix*/ + + for (ns = state; ns > 0; ns--) + { + if (pat[ns-1] == x) + { + for (i = 0; i < ns-1; i++) + if (pat[i] != pat[state-ns+1+i]) + break; + if (i == ns-1) + return ns; + } + } + return 0; + } + /* This function builds the TF table which + represents Finite Automata for a given pattern */ + + static void computeTF(char[] pat, int M, int TF[][]) + { + int state, x; + for (state = 0; state <= M; ++state) + for (x = 0; x < NO_OF_CHARS; ++x) + TF[state][x] = getNextState(pat, M, state, x); + } + /* Prints all occurrences of pat in txt */ + + static void search(char[] pat, char[] txt) + { + int M = pat.length; + int N = txt.length; + int[][] TF = new int[M+1][NO_OF_CHARS]; + computeTF(pat, M, TF); +/* Process txt over FA.*/ + + int i, state = 0; + for (i = 0; i < N; i++) + { + state = TF[state][txt[i]]; + if (state == M) + System.out.println(""Pattern found "" + + ""at index "" + (i-M+1)); + } + } +/* Driver code*/ + + public static void main(String[] args) + { + char[] pat = ""AABAACAADAABAAABAA"".toCharArray(); + char[] txt = ""AABA"".toCharArray(); + search(txt,pat); + } +}"," '''Python program for Finite Automata +Pattern searching Algorithm''' + +NO_OF_CHARS = 256 +def getNextState(pat, M, state, x): + ''' If the character c is same as next character + in pattern, then simply increment state''' + + if state < M and x == ord(pat[state]): + return state+1 + i=0 + ''' ns stores the result which is next state + ns finally contains the longest prefix + which is also suffix in ""pat[0..state-1]c"" + Start from the largest possible value and + stop when you find a prefix which is also suffix''' + + for ns in range(state,0,-1): + if ord(pat[ns-1]) == x: + while(i2->56->12''' + + head = push(head, 12) + head = push(head, 56) + head = push(head, 2) + head = push(head, 11) + print(""Sum of circular list is = {}"" . + format(sumOfList(head))) + + +" +Linked List | Set 2 (Inserting a node),"/* This function is in LinkedList class. Inserts a + new Node at front of the list. This method is + defined inside LinkedList class shown above */ + +public void push(int new_data) +{ + /* 1 & 2: Allocate the Node & + Put in the data*/ + + Node new_node = new Node(new_data); + /* 3. Make next of new Node as head */ + + new_node.next = head; + /* 4. Move the head to point to new Node */ + + head = new_node; +}"," '''This function is in LinkedList class +Function to insert a new node at the beginning''' + +def push(self, new_data): + ''' 1 & 2: Allocate the Node & + Put in the data''' + + new_node = Node(new_data) + ''' 3. Make next of new Node as head''' + + new_node.next = self.head + ''' 4. Move the head to point to new Node''' + + self.head = new_node" +Maximum sum of increasing order elements from n arrays,"/*Java program to find +maximum sum by selecting +a element from n arrays*/ + +import java.util.*; +class GFG{ + +static int M = 4; + +/*To calculate maximum sum +by selecting element from +each array*/ + +static int maximumSum(int a[][], + int n) +{ +/* Store maximum element + of last array*/ + + int prev = Math.max(a[n - 1][0], + a[n - 1][M - 1] + 1); + +/* Selecting maximum element from + previoulsy selected element*/ + + int sum = prev; + for (int i = n - 2; i >= 0; i--) + { + int max_smaller = Integer.MIN_VALUE; + for (int j = M - 1; j >= 0; j--) + { + if (a[i][j] < prev && + a[i][j] > max_smaller) + max_smaller = a[i][j]; + } + +/* max_smaller equals to + INT_MIN means no element + is found in a[i] so return 0*/ + + if (max_smaller == Integer.MIN_VALUE) + return 0; + + prev = max_smaller; + sum += max_smaller; + } + + return sum; +} + +/*Driver code*/ + +public static void main(String []args) +{ + int arr[][] = {{1, 7, 3, 4}, + {4, 2, 5, 1}, + {9, 5, 1, 8}}; + int n = arr.length; + System.out.print(maximumSum(arr, n)); +} +} + + +"," '''Python3 program to find maximum sum +by selecting a element from n arrays''' + +M = 4 + + '''To calculate maximum sum by +selecting element from each array''' + +def maximumSum(a, n): + + ''' Store maximum element of last array''' + + prev = max(max(a)) + + ''' Selecting maximum element from + previoulsy selected element''' + + Sum = prev + for i in range(n - 2, -1, -1): + + max_smaller = -10**9 + for j in range(M - 1, -1, -1): + if (a[i][j] < prev and + a[i][j] > max_smaller): + max_smaller = a[i][j] + + ''' max_smaller equals to INT_MIN means + no element is found in a[i] so + return 0''' + + if (max_smaller == -10**9): + return 0 + + prev = max_smaller + Sum += max_smaller + + return Sum + + '''Driver Code''' + +arr = [[1, 7, 3, 4], + [4, 2, 5, 1], + [9, 5, 1, 8]] +n = len(arr) +print(maximumSum(arr, n)) + + +" +Lowest Common Ancestor in Parent Array Representation,"/*Java program to find LCA in a tree represented +as parent array.*/ + +import java.util.*; + +class GFG +{ + +/*Maximum value in a node*/ + +static int MAX = 1000; + +/*Function to find the Lowest common ancestor*/ + +static int findLCA(int n1, int n2, int parent[]) +{ +/* Create a visited vector and mark + all nodes as not visited.*/ + + boolean []visited = new boolean[MAX]; + + visited[n1] = true; + +/* Moving from n1 node till root and + mark every accessed node as visited*/ + + while (parent[n1] != -1) + { + visited[n1] = true; + +/* Move to the parent of node n1*/ + + n1 = parent[n1]; + } + + visited[n1] = true; + +/* For second node finding the first + node common*/ + + while (!visited[n2]) + n2 = parent[n2]; + + return n2; +} + +/*Insert function for Binary tree*/ + +static void insertAdj(int parent[], int i, int j) +{ + parent[i] = j; +} + +/*Driver Function*/ + +public static void main(String[] args) +{ +/* Maximum capacity of binary tree*/ + + int []parent = new int[MAX]; + +/* Root marked*/ + + parent[20] = -1; + insertAdj(parent, 8, 20); + insertAdj(parent, 22, 20); + insertAdj(parent, 4, 8); + insertAdj(parent, 12, 8); + insertAdj(parent, 10, 12); + insertAdj(parent, 14, 12); + + System.out.println(findLCA(10, 14, parent)); +} +} + + +"," '''Python 3 program to find LCA in a +tree represented as parent array.''' + + + '''Maximum value in a node''' + +MAX = 1000 + + '''Function to find the Lowest +common ancestor''' + +def findLCA(n1, n2, parent): + + ''' Create a visited vector and mark + all nodes as not visited.''' + + visited = [False for i in range(MAX)] + + visited[n1] = True + + ''' Moving from n1 node till root and + mark every accessed node as visited''' + + while (parent[n1] != -1): + visited[n1] = True + + ''' Move to the parent of node n1''' + + n1 = parent[n1] + + visited[n1] = True + + ''' For second node finding the + first node common''' + + while (visited[n2] == False): + n2 = parent[n2] + + return n2 + + '''Insert function for Binary tree''' + +def insertAdj(parent, i, j): + parent[i] = j + + '''Driver Code''' + +if __name__ =='__main__': + + ''' Maximum capacity of binary tree''' + + parent = [0 for i in range(MAX)] + + ''' Root marked''' + + parent[20] = -1 + insertAdj(parent, 8, 20) + insertAdj(parent, 22, 20) + insertAdj(parent, 4, 8) + insertAdj(parent, 12, 8) + insertAdj(parent, 10, 12) + insertAdj(parent, 14, 12) + + print(findLCA(10, 14, parent)) + + +" +Point arbit pointer to greatest value right side node in a linked list,"/*Java program to point arbit pointers to highest +value on its right*/ + +class GfG +{ + + /* Link list node */ + + static class Node + { + int data; + Node next, arbit; + } + + static Node maxNode; + +/* This function populates arbit pointer in every + node to the greatest value to its right.*/ + + static void populateArbit(Node head) + { + +/* if head is null simply return the list*/ + + if (head == null) + return; + + /* if head->next is null it means we reached at + the last node just update the max and maxNode */ + + if (head.next == null) + { + maxNode = head; + return; + } + + /* Calling the populateArbit to the next node */ + + populateArbit(head.next); + + /* updating the arbit node of the current + node with the maximum value on the right side */ + + head.arbit = maxNode; + + /* if current Node value id greater then + the previous right node then update it */ + + if (head.data > maxNode.data) + maxNode = head; + + return; + } + +/* Utility function to print result linked list*/ + + static void printNextArbitPointers(Node node) + { + System.out.println(""Node\tNext Pointer\tArbit Pointer""); + while (node != null) + { + System.out.print(node.data + ""\t\t\t""); + + if (node.next != null) + System.out.print(node.next.data + ""\t\t\t\t""); + else + System.out.print(""NULL"" +""\t\t\t""); + + if (node.arbit != null) + System.out.print(node.arbit.data); + else + System.out.print(""NULL""); + + System.out.println(); + node = node.next; + } + } + + /* Function to create a new node with given data */ + + static Node newNode(int data) + { + Node new_node = new Node(); + new_node.data = data; + new_node.next = null; + return new_node; + } + + /* Driver code*/ + + public static void main(String[] args) + { + Node head = newNode(5); + head.next = newNode(10); + head.next.next = newNode(2); + head.next.next.next = newNode(3); + + populateArbit(head); + + System.out.println(""Resultant Linked List is: ""); + printNextArbitPointers(head); + + } +} + + +"," '''Python3 program to poarbit pointers to highest +value on its right''' + + + '''Node class''' + +class newNode: + def __init__(self, data): + self.data = data + self.next = None + self.arbit = None + + '''This function populates arbit pointer in every +node to the greatest value to its right.''' + +maxNode = newNode(None) +def populateArbit(head): + + ''' using static maxNode to keep track of maximum + orbit node address on right side''' + + global maxNode + + ''' if head is null simply return the list''' + + if (head == None): + return + + ''' if head.next is null it means we reached at + the last node just update the max and maxNode ''' + + if (head.next == None): + maxNode = head + return + + ''' Calling the populateArbit to the next node ''' + + populateArbit(head.next) + + ''' updating the arbit node of the current + node with the maximum value on the right side ''' + + head.arbit = maxNode + + ''' if current Node value id greater then + the previous right node then update it ''' + + if (head.data > maxNode.data and maxNode.data != None ): + maxNode = head + return + + '''Utility function to prresult linked list''' + +def printNextArbitPointers(node): + print(""Node\tNext Pointer\tArbit Pointer"") + while (node != None): + print(node.data,""\t\t"", end = """") + if(node.next): + print(node.next.data,""\t\t"", end = """") + else: + print(""NULL"",""\t\t"", end = """") + if(node.arbit): + print(node.arbit.data, end = """") + else: + print(""NULL"", end = """") + print() + node = node.next + + ''' Driver code''' + +head = newNode(5) +head.next = newNode(10) +head.next.next = newNode(2) +head.next.next.next = newNode(3) + +populateArbit(head) + +print(""Resultant Linked List is:"") +printNextArbitPointers(head) + + +" +Size of The Subarray With Maximum Sum,"/*Java program to print length of the largest +contiguous array sum*/ + +class GFG { +/* Function to find maximum subarray sum*/ + + static int maxSubArraySum(int a[], int size) + { + int max_so_far = Integer.MIN_VALUE, + max_ending_here = 0,start = 0, + end = 0, s = 0; + for (int i = 0; i < size; i++) + { + max_ending_here += a[i]; + if (max_so_far < max_ending_here) + { + max_so_far = max_ending_here; + start = s; + end = i; + } + if (max_ending_here < 0) + { + max_ending_here = 0; + s = i + 1; + } + } + return (end - start + 1); + } +/* Driver code*/ + + public static void main(String[] args) + { + int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; + int n = a.length; + System.out.println(maxSubArraySum(a, n)); + } +}"," '''Python3 program to print largest contiguous array sum''' + +from sys import maxsize + '''Function to find the maximum contiguous subarray +and print its starting and end index''' + +def maxSubArraySum(a,size): + max_so_far = -maxsize - 1 + max_ending_here = 0 + start = 0 + end = 0 + s = 0 + for i in range(0,size): + max_ending_here += a[i] + if max_so_far < max_ending_here: + max_so_far = max_ending_here + start = s + end = i + if max_ending_here < 0: + max_ending_here = 0 + s = i+1 + return (end - start + 1) + '''Driver program to test maxSubArraySum''' + +a = [-2, -3, 4, -1, -2, 1, 5, -3] +print(maxSubArraySum(a,len(a)))" +Print common nodes on path from root (or common ancestors),"/*Java Program to find common nodes for given two nodes*/ + +import java.util.LinkedList; +/*Class to represent Tree node */ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = null; + right = null; + } +} +/*Class to count full nodes of Tree */ + +class BinaryTree +{ + static Node root; +/*Utility function to find the LCA of two given values +n1 and n2.*/ + +static Node findLCA(Node root, int n1, int n2) +{ +/* Base case*/ + + if (root == null) + return null; +/* If either n1 or n2 matches with root's key, + report the presence by returning root (Note + that if a key is ancestor of other, then the + ancestor key becomes LCA*/ + + if (root.data == n1 || root.data == n2) + return root; +/* Look for keys in left and right subtrees*/ + + Node left_lca = findLCA(root.left, n1, n2); + Node right_lca = findLCA(root.right, n1, n2); +/* If both of the above calls return Non-NULL, then + one key is present in once subtree and other is + present in other, So this node is the LCA*/ + + if (left_lca!=null && right_lca!=null) + return root; +/* Otherwise check if left subtree or right + subtree is LCA*/ + + return (left_lca != null) ? left_lca : right_lca; +} +/*Utility Function to print all ancestors of LCA*/ + +static boolean printAncestors(Node root, int target) +{ + /* base cases */ + + if (root == null) + return false; + if (root.data == target) { + System.out.print(root.data+ "" ""); + return true; + } + /* If target is present in either left or right + subtree of this node, then print this node */ + + if (printAncestors(root.left, target) || + printAncestors(root.right, target)) { + System.out.print(root.data+ "" ""); + return true; + } + /* Else return false */ + + return false; +} +/*Function to find nodes common to given two nodes*/ + +static boolean findCommonNodes(Node root, int first, + int second) +{ + Node LCA = findLCA(root, first, second); + if (LCA == null) + return false; + printAncestors(root, LCA.data); + return true; +} +/*Driver program to test above functions*/ + + public static void main(String args[]) + { + /*Let us create Binary Tree shown in + above example */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + tree.root.left.left.left = new Node(8); + tree.root.right.left.left = new Node(9); + tree.root.right.left.right = new Node(10); + if (findCommonNodes(root, 9, 7) == false) + System.out.println(""No Common nodes""); + } +}"," '''Python3 Program to find common +nodes for given two nodes ''' + + '''Utility class to create a new tree Node ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None '''Utility function to find the LCA of +two given values n1 and n2. ''' + +def findLCA(root, n1, n2): + ''' Base case ''' + + if (root == None): + return None + ''' If either n1 or n2 matches with root's key, + report the presence by returning root (Note + that if a key is ancestor of other, then the + ancestor key becomes LCA ''' + + if (root.key == n1 or root.key == n2): + return root + ''' Look for keys in left and right subtrees ''' + + left_lca = findLCA(root.left, n1, n2) + right_lca = findLCA(root.right, n1, n2) + ''' If both of the above calls return Non-None, + then one key is present in once subtree and + other is present in other, So this node is the LCA ''' + + if (left_lca and right_lca): + return root + ''' Otherwise check if left subtree or + right subtree is LCA''' + + if (left_lca != None): + return left_lca + else: + return right_lca + '''Utility Function to print all ancestors of LCA ''' + +def printAncestors(root, target): + ''' base cases ''' + + if (root == None): + return False + if (root.key == target): + print(root.key, end = "" "") + return True + ''' If target is present in either left or right + subtree of this node, then prthis node ''' + + if (printAncestors(root.left, target) or + printAncestors(root.right, target)): + print(root.key, end = "" "") + return True + ''' Else return False ''' + + return False + '''Function to find nodes common to given two nodes ''' + +def findCommonNodes(root, first, second): + LCA = findLCA(root, first, second) + if (LCA == None): + return False + printAncestors(root, LCA.key) + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us create binary tree given + in the above example ''' + + 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.left.left.left = newNode(8) + root.right.left.left = newNode(9) + root.right.left.right = newNode(10) + if (findCommonNodes(root, 9, 7) == False): + print(""No Common nodes"")" +Maximum possible sum of a window in an array such that elements of same window in other array are unique,"/*Java program to find the maximum +possible sum of a window in one +array such that elements in same +window of other array are unique.*/ + +import java.util.HashSet; +import java.util.Set; +public class MaxPossibleSuminWindow +{ +/* Function to return maximum sum of window + in A[] according to given constraints.*/ + + static int returnMaxSum(int A[], int B[], int n) + { +/* Map is used to store elements + and their counts.*/ + + Set mp = new HashSet(); +/*Initialize result*/ + +int result = 0; +/* calculating the maximum possible + sum for each subarray containing + unique elements.*/ + + int curr_sum = 0, curr_begin = 0; + for (int i = 0; i < n; ++i) + { +/* Remove all duplicate + instances of A[i] in + current window.*/ + + while (mp.contains(A[i])) + { + mp.remove(A[curr_begin]); + curr_sum -= B[curr_begin]; + curr_begin++; + } +/* Add current instance of A[i] + to map and to current sum.*/ + + mp.add(A[i]); + curr_sum += B[i]; +/* Update result if current + sum is more.*/ + + result = Integer.max(result, curr_sum); + } + return result; + } +/* Driver Code to test above method*/ + + public static void main(String[] args) + { + int A[] = { 0, 1, 2, 3, 0, 1, 4 }; + int B[] = { 9, 8, 1, 2, 3, 4, 5 }; + int n = A.length; + System.out.println(returnMaxSum(A, B, n)); + } +}"," '''Python3 program to find the maximum +possible sum of a window in one +array such that elements in same +window of other array are unique. + ''' '''Function to return maximum sum of window +in B[] according to given constraints. ''' + +def returnMaxSum(A, B, n): + ''' Map is used to store elements + and their counts. ''' + + mp = set() + '''Initialize result ''' + + result = 0 + ''' calculating the maximum possible + sum for each subarray containing + unique elements. ''' + + curr_sum = curr_begin = 0 + for i in range(0, n): + ''' Remove all duplicate instances + of A[i] in current window. ''' + + while A[i] in mp: + mp.remove(A[curr_begin]) + curr_sum -= B[curr_begin] + curr_begin += 1 + ''' Add current instance of A[i] + to map and to current sum. ''' + + mp.add(A[i]) + curr_sum += B[i] + ''' Update result if current + sum is more. ''' + + result = max(result, curr_sum) + return result + '''Driver code ''' + +if __name__ == ""__main__"": + A = [0, 1, 2, 3, 0, 1, 4] + B = [9, 8, 1, 2, 3, 4, 5] + n = len(A) + print(returnMaxSum(A, B, n))" +Longest Path with Same Values in a Binary Tree,"/*Java program to find the length of longest +path with same values in a binary tree.*/ + +class GFG +{ +static int ans; +/* A binary tree node has data, pointer to +left child and a pointer to right child */ + +static class Node +{ + int val; + Node left, right; +}; +/* Function to print the longest path +of same values */ + +static int length(Node node) +{ + if (node == null) + return 0; +/* Recursive calls to check for subtrees*/ + + int left = length(node.left); + int right = length(node.right); +/* Variables to store maximum lengths + in two directions*/ + + int Leftmax = 0, Rightmax = 0; +/* If curr node and it's left child + has same value*/ + + if (node.left != null && + node.left.val == node.val) + Leftmax += left + 1; +/* If curr node and it's right child + has same value*/ + + if (node.right != null && + node.right.val == node.val) + Rightmax += right + 1; + ans = Math.max(ans, Leftmax + Rightmax); + return Math.max(Leftmax, Rightmax); +} +/*Function to find length of +longest same value path*/ + +static int longestSameValuePath(Node root) +{ + ans = 0; + length(root); + return ans; +} +/* Helper function that allocates a +new node with the given data and +null left and right pointers. */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.val = data; + temp.left = temp.right = null; + return temp; +} +/*Driver code*/ + +public static void main(String[] args) +{ + /* Let us cona Binary Tree + 4 + / \ + 4 4 + / \ \ + 4 9 5 */ + + Node root = null; + root = newNode(4); + root.left = newNode(4); + root.right = newNode(4); + root.left.left = newNode(4); + root.left.right = newNode(9); + root.right.right = newNode(5); + System.out.print(longestSameValuePath(root)); +} +}"," '''Python3 program to find the length of longest +path with same values in a binary tree. ''' + + '''Function to print the longest path +of same values ''' + +def length(node, ans): + if (not node): + return 0 + ''' Recursive calls to check for subtrees ''' + + left = length(node.left, ans) + right = length(node.right, ans) + ''' Variables to store maximum lengths + in two directions ''' + + Leftmax = 0 + Rightmax = 0 + ''' If curr node and it's left child has same value ''' + + if (node.left and node.left.val == node.val): + Leftmax += left + 1 + ''' If curr node and it's right child has same value ''' + + if (node.right and node.right.val == node.val): + Rightmax += right + 1 + ans[0] = max(ans[0], Leftmax + Rightmax) + return max(Leftmax, Rightmax) + '''Driver function to find length of +longest same value path''' + +def longestSameValuePath(root): + ans = [0] + length(root, ans) + return ans[0] + '''Helper function that allocates a +new node with the given data and +None left and right pointers. ''' + +class newNode: + def __init__(self, data): + self.val = data + self.left = self.right = None '''Driver code ''' + +if __name__ == '__main__': + ''' Let us construct a Binary Tree + 4 + / \ + 4 4 + / \ \ + 4 9 5 ''' + + root = None + root = newNode(4) + root.left = newNode(4) + root.right = newNode(4) + root.left.left = newNode(4) + root.left.right = newNode(9) + root.right.right = newNode(5) + print(longestSameValuePath(root))" +Merge K sorted linked lists | Set 1,"/*Java program to merge k sorted +arrays of size n each*/ + +import java.io.*; + +/*A Linked List node*/ + +class Node +{ + int data; + Node next; + +/* Utility function to create a new node.*/ + + Node(int key) + { + data = key; + next = null; + } +} +class GFG { + + static Node head; + static Node temp; + + /* Function to print nodes in + a given linked list */ + + static void printList(Node node) + { + while(node != null) + { + System.out.print(node.data + "" ""); + + node = node.next; + } + System.out.println(); + } + +/* The main function that + takes an array of lists + arr[0..last] and generates + the sorted output*/ + + static Node mergeKLists(Node arr[], int last) + { + +/* Traverse form second list to last*/ + + for (int i = 1; i <= last; i++) + { + while(true) + { + +/* head of both the lists, + 0 and ith list. */ + + Node head_0 = arr[0]; + Node head_i = arr[i]; + +/* Break if list ended*/ + + if (head_i == null) + break; + +/* Smaller than first element*/ + + if(head_0.data >= head_i.data) + { + arr[i] = head_i.next; + head_i.next = head_0; + arr[0] = head_i; + } + else + { + +/* Traverse the first list*/ + + while (head_0.next != null) + { + +/* Smaller than next element*/ + + 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; + } + +/* go to next node*/ + + head_0 = head_0.next; + +/* if last node*/ + + 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]; + } + +/* Driver program to test + above functions */ + + public static void main (String[] args) + { + +/* Number of linked lists*/ + + int k = 3; + +/* Number of elements in each list*/ + + int n = 4; + +/* an array of pointers storing the + head nodes of the linked lists*/ + + + Node[] arr = new Node[k]; + + arr[0] = new Node(1); + arr[0].next = new Node(3); + arr[0].next.next = new Node(5); + arr[0].next.next.next = new Node(7); + + arr[1] = new Node(2); + arr[1].next = new Node(4); + arr[1].next.next = new Node(6); + arr[1].next.next.next = new Node(8); + + arr[2] = new Node(0); + arr[2].next = new Node(9); + arr[2].next.next = new Node(10); + arr[2].next.next.next = new Node(11); + +/* Merge all lists*/ + + head = mergeKLists(arr, k - 1); + printList(head); + + } +} + + +"," '''Python3 program to merge k +sorted arrays of size n each''' + + + '''A Linked List node''' + +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + + '''Function to prnodes in +a given linked list''' + +def printList(node): + + while (node != None): + print(node.data, + end = "" "") + node = node.next + + '''The main function that +takes an array of lists +arr[0..last] and generates +the sorted output''' + +def mergeKLists(arr, last): + + ''' Traverse form second + list to last''' + + for i in range(1, last + 1): + while (True): + ''' head of both the lists, + 0 and ith list.''' + + head_0 = arr[0] + head_i = arr[i] + + ''' Break if list ended''' + + if (head_i == None): + break + + ''' Smaller than first + element''' + + if (head_0.data >= + head_i.data): + arr[i] = head_i.next + head_i.next = head_0 + arr[0] = head_i + else: + ''' Traverse the first list''' + + while (head_0.next != None): + ''' Smaller than next + element''' + + 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 + ''' go to next node''' + + head_0 = head_0.next + ''' if last node''' + + if (head_0.next == None): + arr[i] = head_i.next + head_i.next = None + head_0.next = head_i + head_0.next.next = None + break + return arr[0] + + '''Driver code''' + +if __name__ == '__main__': + + ''' Number of linked + lists''' + + k = 3 + + ''' Number of elements + in each list''' + + n = 4 + + ''' an array of pointers + storing the head nodes + of the linked lists''' + + arr = [None for i in range(k)] + + arr[0] = Node(1) + arr[0].next = Node(3) + arr[0].next.next = Node(5) + arr[0].next.next.next = Node(7) + + arr[1] = Node(2) + arr[1].next = Node(4) + arr[1].next.next = Node(6) + arr[1].next.next.next = Node(8) + + arr[2] = Node(0) + arr[2].next = Node(9) + arr[2].next.next = Node(10) + arr[2].next.next.next = Node(11) + + ''' Merge all lists''' + + head = mergeKLists(arr, k - 1) + + printList(head) + + +" +Left Rotation and Right Rotation of a String,"/*Java program for Left Rotation and Right +Rotation of a String*/ + +import java.util.*; +import java.io.*; + +class GFG +{ + +/* function that rotates s towards left by d*/ + + static String leftrotate(String str, int d) + { + String ans = str.substring(d) + str.substring(0, d); + return ans; + } + +/* function that rotates s towards right by d*/ + + static String rightrotate(String str, int d) + { + return leftrotate(str, str.length() - d); + } + +/* Driver code*/ + + public static void main(String args[]) + { + String str1 = ""GeeksforGeeks""; + System.out.println(leftrotate(str1, 2)); + + String str2 = ""GeeksforGeeks""; + System.out.println(rightrotate(str2, 2)); + } +} + + +"," '''Python3 program for Left +Rotation and Right +Rotation of a String''' + + + '''In-place rotates s towards left by d''' + +def leftrotate(s, d): + tmp = s[d : ] + s[0 : d] + return tmp + + '''In-place rotates s +towards right by d''' + +def rightrotate(s, d): + + return leftrotate(s, len(s) - d) + + '''Driver code''' + +if __name__==""__main__"": + + str1 = ""GeeksforGeeks"" + print(leftrotate(str1, 2)) + + str2 = ""GeeksforGeeks"" + print(rightrotate(str2, 2)) + + +" +Maximum triplet sum in array,"/*Java code to find maximum triplet sum*/ + +import java.io.*; +import java.util.*; +class GFG { +/* This function assumes that there + are at least three elements in arr[].*/ + + static int maxTripletSum(int arr[], int n) + { +/* Initialize Maximum, second maximum and third + maximum element*/ + + int maxA = -100000000, maxB = -100000000; + int maxC = -100000000; + for (int i = 0; i < n; i++) { +/* Update Maximum, second maximum + and third maximum element*/ + + if (arr[i] > maxA) + { + maxC = maxB; + maxB = maxA; + maxA = arr[i]; + } +/* Update second maximum and third maximum + element*/ + + else if (arr[i] > maxB) + { + maxC = maxB; + maxB = arr[i]; + } +/* Update third maximum element*/ + + else if (arr[i] > maxC) + maxC = arr[i]; + } + return (maxA + maxB + maxC); + } +/* Driven code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 0, 8, 6, 4, 2 }; + int n = arr.length; + System.out.println(maxTripletSum(arr, n)); + } +}"," '''Python 3 code to find +maximum triplet sum + ''' '''This function assumes +that there are at least +three elements in arr[].''' + +def maxTripletSum(arr, n) : + ''' Initialize Maximum, second + maximum and third maximum + element''' + + maxA = -100000000 + maxB = -100000000 + maxC = -100000000 + for i in range(0, n) : + ''' Update Maximum, second maximum + and third maximum element''' + + if (arr[i] > maxA) : + maxC = maxB + maxB = maxA + maxA = arr[i] + ''' Update second maximum and + third maximum element''' + + elif (arr[i] > maxB) : + maxC = maxB + maxB = arr[i] + ''' Update third maximum element''' + + elif (arr[i] > maxC) : + maxC = arr[i] + return (maxA + maxB + maxC) + '''Driven code''' + +arr = [ 1, 0, 8, 6, 4, 2 ] +n = len(arr) +print(maxTripletSum(arr, n))" +Largest Sum Contiguous Subarray,"/*Java program to print largest contiguous array sum*/ + +import java.io.*; +import java.util.*; +class Kadane +{ + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + }/*Driver program to test maxSubArraySum*/ + + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println(""Maximum contiguous sum is "" + + maxSubArraySum(a)); + } +}"," '''Python program to find maximum contiguous subarray +Function to find the maximum contiguous subarray''' + +from sys import maxint +def maxSubArraySum(a,size): + max_so_far = -maxint - 1 + max_ending_here = 0 + for i in range(0, size): + max_ending_here = max_ending_here + a[i] + if (max_so_far < max_ending_here): + max_so_far = max_ending_here + if max_ending_here < 0: + max_ending_here = 0 + return max_so_far + '''Driver function to check the above function''' + +a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] +print ""Maximum contiguous sum is"", maxSubArraySum(a,len(a))" +Check if an array can be divided into pairs whose sum is divisible by k,"/*JAVA program to check if arr[0..n-1] can be divided +in pairs such that every pair is divisible by k.*/ + +import java.util.HashMap; +public class Divisiblepair { +/* Returns true if arr[0..n-1] can be divided into pairs + with sum divisible by k.*/ + + static boolean canPairs(int ar[], int k) + { +/* An odd length array cannot be divided into pairs*/ + + if (ar.length % 2 == 1) + return false; +/* Create a frequency array to count occurrences + of all remainders when divided by k.*/ + + HashMap hm = new HashMap<>(); +/* Count occurrences of all remainders*/ + + for (int i = 0; i < ar.length; i++) { + int rem = ((ar[i] % k) + k) % k; + if (!hm.containsKey(rem)) { + hm.put(rem, 0); + } + hm.put(rem, hm.get(rem) + 1); + } +/* Traverse input array and use freq[] to decide + if given array can be divided in pairs*/ + + for (int i = 0; i < ar.length; i++) { +/* Remainder of current element*/ + + int rem = ((ar[i] % k) + k) % k; +/* If remainder with current element divides + k into two halves.*/ + + if (2 * rem == k) { +/* Then there must be even occurrences of + such remainder*/ + + if (hm.get(rem) % 2 == 1) + return false; + } +/* If remainder is 0, then there must be two + elements with 0 remainder*/ + + else if (rem == 0) { +/* Then there must be even occurrences of + such remainder*/ + + if (hm.get(rem) % 2 == 1) + return false; + } +/* Else number of occurrences of remainder + must be equal to number of occurrences of + k - remainder*/ + + else { + if (hm.get(k - rem) != hm.get(rem)) + return false; + } + } + return true; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 92, 75, 65, 48, 45, 35 }; + int k = 10; +/* Function call*/ + + boolean ans = canPairs(arr, k); + if (ans) + System.out.println(""True""); + else + System.out.println(""False""); + } +}"," '''Python3 program to check if +arr[0..n-1] can be divided +in pairs such that every +pair is divisible by k.''' + +from collections import defaultdict + '''Returns true if arr[0..n-1] can be +divided into pairs with sum +divisible by k.''' + +def canPairs(arr, n, k): + ''' An odd length array cannot + be divided into pairs''' + + if (n & 1): + return 0 + ''' Create a frequency array to + count occurrences of all + remainders when divided by k.''' + + freq = defaultdict(lambda: 0) + ''' Count occurrences of all remainders''' + + for i in range(0, n): + freq[((arr[i] % k) + k) % k] += 1 + ''' Traverse input array and use + freq[] to decide if given array + can be divided in pairs''' + + for i in range(0, n): + ''' Remainder of current element''' + + rem = ((arr[i] % k) + k) % k + ''' If remainder with current element + divides k into two halves.''' + + if (2 * rem == k): + ''' Then there must be even occurrences + of such remainder''' + + if (freq[rem] % 2 != 0): + return 0 + ''' If remainder is 0, then there + must be two elements with 0 remainde''' + + elif (rem == 0): + '''Then there must be even occurrences of + such remainder''' + + if (freq[rem] & 1): + return 0 ''' Else number of occurrences of + remainder must be equal to + number of occurrences of + k - remainder''' + + elif (freq[rem] != freq[k - rem]): + return 0 + return 1 + '''Driver code''' + +arr = [92, 75, 65, 48, 45, 35] +k = 10 +n = len(arr) + '''Function call''' + +if (canPairs(arr, n, k)): + print(""True"") +else: + print(""False"")" +Rat in a Maze | Backtracking-2,"/* Java program to solve Rat in + a Maze problem using backtracking */ + +public class RatMaze { +/* Size of the maze*/ + + static int N; + /* A utility function to print + solution matrix sol[N][N] */ + + void printSolution(int sol[][]) + { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) + System.out.print( + "" "" + sol[i][j] + "" ""); + System.out.println(); + } + } + /* A utility function to check + if x, y is valid index for N*N maze */ + + boolean isSafe( + int maze[][], int x, int y) + { +/* if (x, y outside maze) return false*/ + + return (x >= 0 && x < N && y >= 0 + && y < N && maze[x][y] == 1); + } + /* This function solves the Maze problem using + Backtracking. It mainly uses solveMazeUtil() + to solve the problem. It returns false if no + path is possible, otherwise return true and + prints the path in the form of 1s. Please note + that there may be more than one solutions, this + function prints one of the feasible solutions.*/ + + boolean solveMaze(int maze[][]) + { + int sol[][] = new int[N][N]; + if (solveMazeUtil(maze, 0, 0, sol) == false) { + System.out.print(""Solution doesn't exist""); + return false; + } + printSolution(sol); + return true; + } + /* A recursive utility function to solve Maze + problem */ + + boolean solveMazeUtil(int maze[][], int x, int y, + int sol[][]) + { +/* if (x, y is goal) return true*/ + + if (x == N - 1 && y == N - 1 + && maze[x][y] == 1) { + sol[x][y] = 1; + return true; + } +/* Check if maze[x][y] is valid*/ + + if (isSafe(maze, x, y) == true) { +/* Check if the current block is already part of solution path. */ + + if (sol[x][y] == 1) + return false; +/* mark x, y as part of solution path*/ + + sol[x][y] = 1; + /* Move forward in x direction */ + + if (solveMazeUtil(maze, x + 1, y, sol)) + return true; + /* If moving in x direction doesn't give + solution then Move down in y direction */ + + if (solveMazeUtil(maze, x, y + 1, sol)) + return true; + /* If moving in y direction doesn't give + solution then Move backwards in x direction */ + + if (solveMazeUtil(maze, x - 1, y, sol)) + return true; + /* If moving backwards in x direction doesn't give + solution then Move upwards in y direction */ + + if (solveMazeUtil(maze, x, y - 1, sol)) + return true; + /* If none of the above movements works then + BACKTRACK: unmark x, y as part of solution + path */ + + sol[x][y] = 0; + return false; + } + return false; + } +/*driver program to test above function*/ + + public static void main(String args[]) + { + RatMaze rat = new RatMaze(); + int maze[][] = { { 1, 0, 0, 0 }, + { 1, 1, 0, 1 }, + { 0, 1, 0, 0 }, + { 1, 1, 1, 1 } }; + N = maze.length; + rat.solveMaze(maze); + } +}"," '''Python3 program to solve Rat in a Maze +problem using backracking''' + + '''Maze size''' + +N = 4 '''A utility function to print solution matrix sol''' + +def printSolution( sol ): + for i in sol: + for j in i: + print(str(j) + "" "", end ="""") + print("""") + '''A utility function to check if x, y is valid +index for N * N Maze''' + +def isSafe( maze, x, y ): + if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: + return True + + '''if (x, y outside maze) return false''' + + return False ''' This function solves the Maze problem using Backtracking. + It mainly uses solveMazeUtil() to solve the problem. It + returns false if no path is possible, otherwise return + true and prints the path in the form of 1s. Please note + that there may be more than one solutions, this function + prints one of the feasable solutions. ''' + +def solveMaze( maze ): + sol = [ [ 0 for j in range(4) ] for i in range(4) ] + if solveMazeUtil(maze, 0, 0, sol) == False: + print(""Solution doesn't exist""); + return False + printSolution(sol) + return True '''A recursive utility function to solve Maze problem''' + +def solveMazeUtil(maze, x, y, sol): + ''' if (x, y is goal) return True''' + + if x == N - 1 and y == N - 1 and maze[x][y]== 1: + sol[x][y] = 1 + return True + ''' Check if maze[x][y] is valid''' + + if isSafe(maze, x, y) == True: + ''' Check if the current block is already part of solution path. ''' + + if sol[x][y] == 1: + return False + ''' mark x, y as part of solution path''' + + sol[x][y] = 1 + ''' Move forward in x direction''' + + if solveMazeUtil(maze, x + 1, y, sol) == True: + return True + ''' If moving in x direction doesn't give solution + then Move down in y direction''' + + if solveMazeUtil(maze, x, y + 1, sol) == True: + return True + ''' If moving in y direction doesn't give solution then + Move back in x direction''' + + if solveMazeUtil(maze, x - 1, y, sol) == True: + return True + ''' If moving in backwards in x direction doesn't give solution + then Move upwards in y direction''' + + if solveMazeUtil(maze, x, y - 1, sol) == True: + return True + ''' If none of the above movements work then + BACKTRACK: unmark x, y as part of solution path''' + + sol[x][y] = 0 + return False + '''Driver program to test above function''' + +if __name__ == ""__main__"": + maze = [ [1, 0, 0, 0], + [1, 1, 0, 1], + [0, 1, 0, 0], + [1, 1, 1, 1] ] + solveMaze(maze)" +Find relative complement of two sorted arrays,"/*Java program to find all those +elements of arr1[] that are not +present in arr2[]*/ + +class GFG +{ + static void relativeComplement(int arr1[], int arr2[], + int n, int m) + { + int i = 0, j = 0; + while (i < n && j < m) + { +/* If current element in arr2[] is + greater, then arr1[i] can't be + present in arr2[j..m-1]*/ + + if (arr1[i] < arr2[j]) + { + System.out.print(arr1[i] + "" ""); + i++; +/* Skipping smaller elements of + arr2[]*/ + + } else if (arr1[i] > arr2[j]) + { + j++; +/* Equal elements found (skipping + in both arrays)*/ + + } + else if (arr1[i] == arr2[j]) + { + i++; + j++; + } + } +/* Printing remaining elements of + arr1[]*/ + + while (i < n) + System.out.print(arr1[i] + "" ""); + } +/* Driver code*/ + + public static void main (String[] args) + { + int arr1[] = {3, 6, 10, 12, 15}; + int arr2[] = {1, 3, 5, 10, 16}; + int n = arr1.length; + int m = arr2.length; + relativeComplement(arr1, arr2, n, m); + } +}"," '''Python program to find all those +elements of arr1[] that are not +present in arr2[]''' + +def relativeComplement(arr1, arr2, n, m): + i = 0 + j = 0 + while (i < n and j < m): + ''' If current element in arr2[] is + greater, then arr1[i] can't be + present in arr2[j..m-1]''' + + if (arr1[i] < arr2[j]): + print(arr1[i] , "" "", end="""") + i += 1 + ''' Skipping smaller elements of + arr2[]''' + + elif (arr1[i] > arr2[j]): + j += 1 + ''' Equal elements found (skipping + in both arrays)''' + + elif (arr1[i] == arr2[j]): + i += 1 + j += 1 + ''' Printing remaining elements of + arr1[]''' + + while (i < n): + print(arr1[i] , "" "", end="""") + '''Driver code''' + +arr1= [3, 6, 10, 12, 15] +arr2 = [1, 3, 5, 10, 16] +n = len(arr1) +m = len(arr2) +relativeComplement(arr1, arr2, n, m)" +Minimum number of elements to add to make median equals x,"/*Java program to find minimum number +of elements needs to add to the +array so that its median equals x.*/ + +import java.util.Arrays; + +class GFG +{ + +/*Returns count of elements to be +added to make median x. This function +assumes that a[] has enough extra space.*/ + +static int minNumber(int a[], int n, int x) +{ +/* to sort the array in increasing order.*/ + + Arrays.sort(a); + + int k; + for (k = 0; a[(n) / 2] != x; k++) + { + a[n++] = x; + Arrays.sort(a); + } + return k; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int x = 10; + int a[] = { 10, 20, 30 }; + int n = 3; + System.out.println(minNumber(a, n-1, x)); +} +} + + +"," '''Python3 program to find minimum number +of elements needs to add to the +array so that its median equals x.''' + + + '''Returns count of elements to be added +to make median x. This function +assumes that a[] has enough extra space.''' + +def minNumber(a, n, x): + + ''' to sort the array in increasing order.''' + + a.sort(reverse = False) + k = 0 + while(a[int((n - 1) / 2)] != x): + a[n - 1] = x + n += 1 + a.sort(reverse = False) + k += 1 + + return k + + '''Driver code''' + +if __name__ == '__main__': + x = 10 + a = [10, 20, 30] + n = 3 + print(minNumber(a, n, x)) + + +" +Program to find transpose of a matrix,"/*Java Program to find +transpose of a matrix*/ + +class GFG +{ + static final int N = 4; +/* Finds transpose of A[][] in-place*/ + + static void transpose(int A[][]) + { + for (int i = 0; i < N; i++) + for (int j = i+1; j < N; j++) + { + int temp = A[i][j]; + A[i][j] = A[j][i]; + A[j][i] = temp; + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int A[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {4, 4, 4, 4}}; + transpose(A); + System.out.print(""Modified matrix is \n""); + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + System.out.print(A[i][j] + "" ""); + System.out.print(""\n""); + } + } +}"," '''Python3 Program to find +transpose of a matrix''' + +N = 4 + '''Finds transpose of A[][] in-place''' + +def transpose(A): + for i in range(N): + for j in range(i+1, N): + A[i][j], A[j][i] = A[j][i], A[i][j] + '''driver code''' + +A = [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] +transpose(A) +print(""Modified matrix is"") +for i in range(N): + for j in range(N): + print(A[i][j], "" "", end='') + print()" +Sum of all odd nodes in the path connecting two given nodes,"/*Java program to find sum of all odd nodes +in the path connecting two given nodes*/ + + +import java.util.*; +class solution +{ + +/*Binary Tree node*/ + +static class Node +{ + int data; + Node left; + Node right; +} + +/*Utitlity function to create a +new Binary Tree node*/ + + static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + + return node; +} + +/*Function to check if there is a path from root +to the given node. It also populates +'arr' with the given path*/ + +static boolean getPath(Node root, Vector arr, int x) +{ +/* if root is null + there is no path*/ + + if (root==null) + return false; + +/* push the node's value in 'arr'*/ + + arr.add(root.data); + +/* if it is the required node + return true*/ + + if (root.data == x) + return true; + +/* else check whether the required node lies + in the left subtree or right subtree of + the current node*/ + + if (getPath(root.left, arr, x) || getPath(root.right, arr, x)) + return true; + +/* required node does not lie either in the + left or right subtree of the current node + Thus, remove current node's value from + 'arr'and then return false*/ + + arr.remove(arr.size()-1); + return false; +} + +/*Function to get the sum of odd nodes in the +path between any two nodes in a binary tree*/ + +static int sumOddNodes(Node root, int n1, int n2) +{ +/* vector to store the path of + first node n1 from root*/ + + Vector path1= new Vector(); + +/* vector to store the path of + second node n2 from root*/ + + Vector path2= new Vector(); + + getPath(root, path1, n1); + getPath(root, path2, n2); + + int intersection = -1; + +/* Get intersection point*/ + + int i = 0, j = 0; + while (i != path1.size() || j != path2.size()) { + +/* Keep moving forward until no intersection + is found*/ + + if (i == j && path1.get(i) == path2.get(j)) { + i++; + j++; + } + else { + intersection = j - 1; + break; + } + } + + int sum = 0; + +/* calculate sum of ODD nodes from the path*/ + + for (i = path1.size() - 1; i > intersection; i--) + if(path1.get(i)%2!=0) + sum += path1.get(i); + + for (i = intersection; i < path2.size(); i++) + if(path2.get(i)%2!=0) + sum += path2.get(i); + + return sum; +} + +/*Driver Code*/ + +public static void main(String args[]) +{ + Node root = newNode(1); + + root.left = newNode(2); + root.right = newNode(3); + root.left.left = newNode(4); + root.left.right = newNode(5); + root.right.right = newNode(6); + + int node1 = 5; + int node2 = 6; + + System.out.print(sumOddNodes(root, node1, node2)); + +} +} +"," '''Python3 program to find sum of all odd nodes +in the path connecting two given nodes''' + + + '''Binary Tree node''' + +class Node: + def __init__(self): + self.data = 0 + self.left = None + self.right = None + + '''Utitlity function to create a +Binary Tree node''' + +def newNode( data): + + node = Node() + node.data = data + node.left = None + node.right = None + + return node + + '''Function to check if there is a path from root +to the given node. It also populates + '''arr' with the given path''' + +def getPath(root, arr, x): + + ''' if root is None + there is no path''' + + if (root == None) : + return False + + ''' push the node's value in 'arr''' + ''' + arr.append(root.data) + + ''' if it is the required node + return True''' + + if (root.data == x) : + return True + + ''' else check whether the required node lies + in the left subtree or right subtree of + the current node''' + + if (getPath(root.left, arr, x) or getPath(root.right, arr, x)) : + return True + + ''' required node does not lie either in the + left or right subtree of the current node + Thus, remove current node's value from + 'arr'and then return False''' + + arr.pop() + return False + + '''Function to get the sum of odd nodes in the +path between any two nodes in a binary tree''' + +def sumOddNodes(root, n1, n2) : + + ''' vector to store the path of + first node n1 from root''' + + path1 = [] + + ''' vector to store the path of + second node n2 from root''' + + path2 = [] + + getPath(root, path1, n1) + getPath(root, path2, n2) + + intersection = -1 + + ''' Get intersection point''' + + i = 0 + j = 0 + while (i != len(path1) or j != len(path2)): + + ''' Keep moving forward until no intersection + is found''' + + if (i == j and path1[i] == path2[j]): + i = i + 1 + j = j + 1 + + else : + intersection = j - 1 + break + + sum = 0 + + i = len(path1) - 1 + + ''' calculate sum of ODD nodes from the path''' + + while ( i > intersection ): + if(path1[i] % 2 != 0): + sum += path1[i] + i = i - 1 + + i = intersection + while ( i < len(path2) ): + if(path2[i] % 2 != 0) : + sum += path2[i] + i = i + 1 + + return sum + + '''Driver Code''' + + +root = newNode(1) + +root.left = newNode(2) +root.right = newNode(3) +root.left.left = newNode(4) +root.left.right = newNode(5) +root.right.right = newNode(6) + +node1 = 5 +node2 = 6 + +print(sumOddNodes(root, node1, node2)) + + +" +Anagram Substring Search (Or Search for all permutations),"/*Java program to search all anagrams +of a pattern in a text*/ + +public class GFG +{ + static final int MAX = 256; +/* This function returns true if contents + of arr1[] and arr2[] are same, otherwise + false.*/ + + static boolean compare(char arr1[], char arr2[]) + { + for (int i = 0; i < MAX; i++) + if (arr1[i] != arr2[i]) + return false; + return true; + } +/* This function search for all permutations + of pat[] in txt[]*/ + + static void search(String pat, String txt) + { + int M = pat.length(); + int N = txt.length(); +/* countP[]: Store count of all + characters of pattern + countTW[]: Store count of current + window of text*/ + + char[] countP = new char[MAX]; + char[] countTW = new char[MAX]; + for (int i = 0; i < M; i++) + { + (countP[pat.charAt(i)])++; + (countTW[txt.charAt(i)])++; + } +/* Traverse through remaining characters + of pattern*/ + + for (int i = M; i < N; i++) + { +/* Compare counts of current window + of text with counts of pattern[]*/ + + if (compare(countP, countTW)) + System.out.println(""Found at Index "" + + (i - M)); +/* Add current character to current + window*/ + + (countTW[txt.charAt(i)])++; +/* Remove the first character of previous + window*/ + + countTW[txt.charAt(i-M)]--; + } +/* Check for the last window in text*/ + + if (compare(countP, countTW)) + System.out.println(""Found at Index "" + + (N - M)); + } + /* Driver program to test above function */ + + public static void main(String args[]) + { + String txt = ""BACDGABCDA""; + String pat = ""ABCD""; + search(pat, txt); + } +}"," '''Python program to search all +anagrams of a pattern in a text''' + +MAX=256 + '''This function returns true +if contents of arr1[] and arr2[] +are same, otherwise false.''' + +def compare(arr1, arr2): + for i in range(MAX): + if arr1[i] != arr2[i]: + return False + return True + '''This function search for all +permutations of pat[] in txt[] ''' + +def search(pat, txt): + M = len(pat) + N = len(txt) + ''' countP[]: Store count of + all characters of pattern + countTW[]: Store count of + current window of text''' + + countP = [0]*MAX + countTW = [0]*MAX + for i in range(M): + (countP[ord(pat[i]) ]) += 1 + (countTW[ord(txt[i]) ]) += 1 + ''' Traverse through remaining + characters of pattern''' + + for i in range(M,N): + ''' Compare counts of current + window of text with + counts of pattern[]''' + + if compare(countP, countTW): + print(""Found at Index"", (i-M)) + ''' Add current character to current window''' + + (countTW[ ord(txt[i]) ]) += 1 + ''' Remove the first character of previous window''' + + (countTW[ ord(txt[i-M]) ]) -= 1 + ''' Check for the last window in text ''' + + if compare(countP, countTW): + print(""Found at Index"", N-M) + '''Driver program to test above function ''' + +txt = ""BACDGABCDA"" +pat = ""ABCD"" +search(pat, txt)" +Add two numbers without using arithmetic operators,"/*Java Program to add two numbers +without using arithmetic operator*/ + +import java.io.*; +class GFG +{ + static int Add(int x, int y) + { +/* Iterate till there is no carry*/ + + while (y != 0) + { +/* carry now contains common + set bits of x and y*/ + + int carry = x & y; +/* Sum of bits of x and + y where at least one + of the bits is not set*/ + + x = x ^ y; +/* Carry is shifted by + one so that adding it + to x gives the required sum*/ + + y = carry << 1; + } + return x; + } +/* Driver code*/ + + public static void main(String arg[]) + { + System.out.println(Add(15, 32)); + } +}"," '''Python3 Program to add two numbers +without using arithmetic operator''' + +def Add(x, y): + ''' Iterate till there is no carry''' + + while (y != 0): + ''' carry now contains common + set bits of x and y''' + + carry = x & y + ''' Sum of bits of x and y where at + least one of the bits is not set''' + + x = x ^ y + ''' Carry is shifted by one so that + adding it to x gives the required sum''' + + y = carry << 1 + return x + '''Driver Code''' + +print(Add(15, 32))" +Find k pairs with smallest sums in two arrays,"/*Java code to print first k pairs with least +sum from two arrays.*/ + +import java.io.*; +class KSmallestPair +{ +/* Function to find k pairs with least sum such + that one elemennt of a pair is from arr1[] and + other element is from arr2[]*/ + + static void kSmallestPair(int arr1[], int n1, int arr2[], + int n2, int k) + { + if (k > n1*n2) + { + System.out.print(""k pairs don't exist""); + return ; + } +/* Stores current index in arr2[] for + every element of arr1[]. Initially + all values are considered 0. + Here current index is the index before + which all elements are considered as + part of output.*/ + + int index2[] = new int[n1]; + while (k > 0) + { +/* Initialize current pair sum as infinite*/ + + int min_sum = Integer.MAX_VALUE; + int min_index = 0; +/* To pick next pair, traverse for all + elements of arr1[], for every element, find + corresponding current element in arr2[] and + pick minimum of all formed pairs.*/ + + for (int i1 = 0; i1 < n1; i1++) + { +/* Check if current element of arr1[] plus + element of array2 to be used gives + minimum sum*/ + + if (index2[i1] < n2 && + arr1[i1] + arr2[index2[i1]] < min_sum) + { +/* Update index that gives minimum*/ + + min_index = i1; +/* update minimum sum*/ + + min_sum = arr1[i1] + arr2[index2[i1]]; + } + } + System.out.print(""("" + arr1[min_index] + "", "" + + arr2[index2[min_index]]+ "") ""); + index2[min_index]++; + k--; + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int arr1[] = {1, 3, 11}; + int n1 = arr1.length; + int arr2[] = {2, 4, 8}; + int n2 = arr2.length; + int k = 4; + kSmallestPair( arr1, n1, arr2, n2, k); + } +}"," '''Python3 program to prints first k pairs with least sum from two +arrays.''' + +import sys + '''Function to find k pairs with least sum such +that one elemennt of a pair is from arr1[] and +other element is from arr2[]''' + +def kSmallestPair(arr1, n1, arr2, n2, k): + if (k > n1*n2): + print(""k pairs don't exist"") + return + ''' Stores current index in arr2[] for + every element of arr1[]. Initially + all values are considered 0. + Here current index is the index before + which all elements are considered as + part of output.''' + + index2 = [0 for i in range(n1)] + while (k > 0): + ''' Initialize current pair sum as infinite''' + + min_sum = sys.maxsize + min_index = 0 + ''' To pick next pair, traverse for all elements + of arr1[], for every element, find corresponding + current element in arr2[] and pick minimum of + all formed pairs.''' + + for i1 in range(0,n1,1): + ''' Check if current element of arr1[] plus + element of array2 to be used gives minimum + sum''' + + if (index2[i1] < n2 and arr1[i1] + arr2[index2[i1]] < min_sum): + ''' Update index that gives minimum''' + + min_index = i1 + ''' update minimum sum''' + + min_sum = arr1[i1] + arr2[index2[i1]] + print(""("",arr1[min_index],"","",arr2[index2[min_index]],"")"",end = "" "") + index2[min_index] += 1 + k -= 1 + '''Driver code''' + +if __name__ == '__main__': + arr1 = [1, 3, 11] + n1 = len(arr1) + arr2 = [2, 4, 8] + n2 = len(arr2) + k = 4 + kSmallestPair( arr1, n1, arr2, n2, k)" +Pairs with Difference less than K,"/*Java code to find count of Pairs with +difference less than K.*/ + +import java.io.*; +import java.util.Arrays; + +class GFG +{ + static int countPairs(int a[], int n, int k) + { +/* to sort the array.*/ + + Arrays.sort(a); + + int res = 0; + for (int i = 0; i < n; i++) + { + +/* Keep incrementing result while + subsequent elements are within + limits.*/ + + int j = i + 1; + while (j < n && a[j] - a[i] < k) + { + res++; + j++; + } + } + return res; + } + +/* Driver code*/ + + public static void main (String[] args) + { + int a[] = {1, 10, 4, 2}; + int k = 3; + int n = a.length; + System.out.println(countPairs(a, n, k)); + } +} + + +"," '''Python code to find count of Pairs +with difference less than K.''' + + +def countPairs(a, n, k): + + ''' to sort the array''' + + a.sort() + res = 0 + for i in range(n): + + ''' Keep incrementing result while + subsequent elements are within limits.''' + + j = i+1 + while (j < n and a[j] - a[i] < k): + res += 1 + j += 1 + return res + + '''Driver code''' + +a = [1, 10, 4, 2] +k = 3 +n = len(a) +print(countPairs(a, n, k), end = """") + + +" +Min Cost Path | DP-6,"/* A Naive recursive implementation of +MCP(Minimum Cost Path) problem */ + +public class GFG { + /* A utility function that returns + minimum of 3 integers */ + + static int min(int x, int y, int z) + { + if (x < y) + return (x < z) ? x : z; + else + return (y < z) ? y : z; + } + /* Returns cost of minimum cost path + from (0,0) to (m, n) in mat[R][C]*/ + + static int minCost(int cost[][], int m, + int n) + { + if (n < 0 || m < 0) + return Integer.MAX_VALUE; + else if (m == 0 && n == 0) + return cost[m][n]; + else + return cost[m][n] + + min( minCost(cost, m-1, n-1), + minCost(cost, m-1, n), + minCost(cost, m, n-1) ); + } +/* Driver code*/ + + public static void main(String args[]) + { + int cost[][] = { {1, 2, 3}, + {4, 8, 2}, + {1, 5, 3} }; + System.out.print(minCost(cost, 2, 2)); + } +}"," '''A Naive recursive implementation of MCP(Minimum Cost Path) problem''' + +R = 3 +C = 3 +import sys + '''A utility function that returns minimum of 3 integers */''' + +def min(x, y, z): + if (x < y): + return x if (x < z) else z + else: + return y if (y < z) else z + '''Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]''' + +def minCost(cost, m, n): + if (n < 0 or m < 0): + return sys.maxsize + elif (m == 0 and n == 0): + return cost[m][n] + else: + return cost[m][n] + min( minCost(cost, m-1, n-1), + minCost(cost, m-1, n), + minCost(cost, m, n-1) ) + '''Driver program to test above functions''' + +cost= [ [1, 2, 3], + [4, 8, 2], + [1, 5, 3] ] +print(minCost(cost, 2, 2))" +How to check if two given sets are disjoint?,"/* Java program to check if two sets are distinct or not */ + +import java.util.*; +class Main +{ +/* This function prints all distinct elements*/ + + static boolean areDisjoint(int set1[], int set2[]) + { +/* Creates an empty hashset*/ + + HashSet set = new HashSet<>(); +/* Traverse the first set and store its elements in hash*/ + + for (int i=0; i { + return i1.start - i2.start; + }); + +/* In the sorted array, if start time of an interval + is less than end of previous interval, then there + is an overlap*/ + + for(int i = 1; i < n; i++) + if (arr[i - 1].end > arr[i].start) + return true; + +/* If we reach here, then no overlap*/ + + return false; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + Interval arr1[] = { new Interval(1, 3), + new Interval(7, 9), + new Interval(4, 6), + new Interval(10, 13) }; + int n1 = arr1.length; + + if (isIntersect(arr1, n1)) + System.out.print(""Yes\n""); + else + System.out.print(""No\n""); + + Interval arr2[] = { new Interval(6, 8), + new Interval(1, 3), + new Interval(2, 4), + new Interval(4, 7) }; + int n2 = arr2.length; + + if (isIntersect(arr2, n2)) + System.out.print(""Yes\n""); + else + System.out.print(""No\n""); +} +} + + +", +Sorting array except elements in a subarray,"/*Java program to sort all elements except +given subarray.*/ + +import java.util.Arrays; +import java.io.*; + +public class GFG { + +/* Sort whole array a[] except elements in + range a[l..r]*/ + + public static void sortExceptUandL(int a[], + int l, int u, int n) + { + +/* Copy all those element that need + to be sorted to an auxiliary + array b[]*/ + + int b[] = new int[n - (u - l + 1)]; + + for (int i = 0; i < l; i++) + b[i] = a[i]; + for (int i = u+1; i < n; i++) + b[l + (i - (u+1))] = a[i]; + +/* sort the array b*/ + + Arrays.sort(b); + +/* Copy sorted elements back to a[]*/ + + for (int i = 0; i < l; i++) + a[i] = b[i]; + for (int i = u+1; i < n; i++) + a[i] = b[l + (i - (u+1))]; + } +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 5, 4, 3, 12, 14, 9 }; + int n = a.length; + int l = 2, u = 4; + + sortExceptUandL(a, l, u, n); + + for (int i = 0; i < n; i++) + System.out.print(a[i] + "" ""); + } +} + + +"," '''Python3 program to sort all elements +except given subarray.''' + + + '''Sort whole array a[] except elements in +range a[l..r]''' + +def sortExceptUandL(a, l, u, n) : + + ''' Copy all those element that need + to be sorted to an auxiliary + array b[]''' + + b = [0] * (n - (u - l + 1)) + + for i in range(0, l) : + b[i] = a[i] + + for i in range(u+1, n) : + b[l + (i - (u+1))] = a[i] + + ''' sort the array b''' + + b.sort() + + ''' Copy sorted elements back to a[]''' + + for i in range(0, l) : + a[i] = b[i] + + for i in range(u+1, n) : + a[i] = b[l + (i - (u+1))] + + '''Driver code''' + +a = [ 5, 4, 3, 12, 14, 9 ] +n = len(a) +l = 2 +u = 4 +sortExceptUandL(a, l, u, n) + +for i in range(0, n) : + print (""{} "".format(a[i]), end="""") + + +" +Smallest of three integers without comparison operators,"/*Java program of above approach*/ + +class GfG { +/* Using division operator to + find minimum of three numbers*/ + + static int smallest(int x, int y, int z) + { +/*Same as ""if (y < x)""*/ + +if ((y / x) != 1) + return ((y / z) != 1) ? y : z; + return ((x / z) != 1) ? x : z; + } +/* Driver code*/ + + public static void main(String[] args) + { + int x = 78, y = 88, z = 68; + System.out.printf(""Minimum of 3 numbers"" + + "" is %d"", + smallest(x, y, z)); + } +}"," '''Using division operator to find +minimum of three numbers''' + +def smallest(x, y, z): + '''Same as ""if (y < x)"" ''' + + if (not (y / x)): + return y if (not (y / z)) else z + return x if (not (x / z)) else z + '''Driver Code''' + +if __name__== ""__main__"": + x = 78 + y = 88 + z = 68 + print(""Minimum of 3 numbers is"", + smallest(x, y, z))" +Check if sums of i-th row and i-th column are same in matrix,"/*Java program to check if there are two +adjacent set bits.*/ + +public class GFG { +/* Function to check the if sum of a row + is same as corresponding column*/ + + static boolean areSumSame(int a[][], + int n, int m) + { + int sum1 = 0, sum2 = 0; + for (int i = 0; i < n; i++) + { + sum1 = 0; + sum2 = 0; + for (int j = 0; j < m; j++) + { + sum1 += a[i][j]; + sum2 += a[j][i]; + } + if (sum1 == sum2) + return true; + } + return false; + } +/* Driver code*/ + + public static void main(String args[]) + { +/*number of rows*/ + +int n = 4; +/*number of columns*/ + +int m = 4; + int M[][] = { { 1, 2, 3, 4 }, + { 9, 5, 3, 1 }, + { 0, 3, 5, 6 }, + { 0, 4, 5, 6 } }; + if(areSumSame(M, n, m) == true) + System.out.print(""1\n""); + else + System.out.print(""0\n""); + } +}"," '''Python3 program to check the if +sum of a row is same as +corresponding column''' + +MAX = 100; + '''Function to check the if sum +of a row is same as +corresponding column''' + +def areSumSame(a, n, m): + sum1 = 0 + sum2 = 0 + for i in range(0, n): + sum1 = 0 + sum2 = 0 + for j in range(0, m): + sum1 += a[i][j] + sum2 += a[j][i] + if (sum1 == sum2): + return 1 + return 0 + '''Driver Code''' + + '''number of rows''' + +n = 4; '''number of columns''' + +m = 4; +M = [ [ 1, 2, 3, 4 ], + [ 9, 5, 3, 1 ], + [ 0, 3, 5, 6 ], + [ 0, 4, 5, 6 ] ] +print(areSumSame(M, n, m))" +Merge Sort,"/* Java program for Merge Sort */ + +class MergeSort +{ +/* Merges two subarrays of arr[]. + First subarray is arr[l..m] + Second subarray is arr[m+1..r]*/ + + void merge(int arr[], int l, int m, int r) + { +/* Find sizes of two subarrays to be merged*/ + + int n1 = m - l + 1; + int n2 = r - m; + /* Create temp arrays */ + + int L[] = new int[n1]; + int R[] = new int[n2]; + /*Copy data to temp arrays*/ + + for (int i = 0; i < n1; ++i) + L[i] = arr[l + i]; + for (int j = 0; j < n2; ++j) + R[j] = arr[m + 1 + j]; + /* Merge the temp arrays + Initial indexes of first + and second subarrays*/ + + int i = 0, j = 0; +/* Initial index of merged subarry array*/ + + int k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } + else { + arr[k] = R[j]; + j++; + } + k++; + } + /* Copy remaining elements of L[] if any */ + + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + /* Copy remaining elements of R[] if any */ + + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } + } +/* Main function that sorts arr[l..r] using + merge()*/ + + void sort(int arr[], int l, int r) + { + if (l < r) { +/* Find the middle point*/ + + int m =l+ (r-l)/2; +/* Sort first and second halves*/ + + sort(arr, l, m); + sort(arr, m + 1, r); +/* Merge the sorted halves*/ + + merge(arr, l, m, r); + } + }/* A utility function to print array of size n */ + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6, 7 }; + System.out.println(""Given Array""); + printArray(arr); + MergeSort ob = new MergeSort(); + ob.sort(arr, 0, arr.length - 1); + System.out.println(""\nSorted array""); + printArray(arr); + } +}", +Generate all rotations of a number,"/*Java implementation of the approach*/ + +class GFG +{ + +/*Function to return the count of digits of n*/ + +static int numberOfDigits(int n) +{ + int cnt = 0; + while (n > 0) + { + cnt++; + n /= 10; + } + return cnt; +} + +/*Function to print the left shift numbers*/ + +static void cal(int num) +{ + int digits = numberOfDigits(num); + int powTen = (int) Math.pow(10, digits - 1); + + for (int i = 0; i < digits - 1; i++) + { + int firstDigit = num / powTen; + +/* Formula to calculate left shift + from previous number*/ + + int left = ((num * 10) + firstDigit) - + (firstDigit * powTen * 10); + + System.out.print(left + "" ""); + +/* Update the original number*/ + + num = left; + } +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int num = 1445; + cal(num); +} +} + + +"," '''Python3 implementation of the approach''' + + + '''function to return the count of digit of n''' + +def numberofDigits(n): + cnt = 0 + while n > 0: + cnt += 1 + n //= 10 + return cnt + + '''function to print the left shift numbers''' + +def cal(num): + digit = numberofDigits(num) + powTen = pow(10, digit - 1) + + for i in range(digit - 1): + + firstDigit = num // powTen + + ''' formula to calculate left shift + from previous number''' + + left = (num * 10 + firstDigit - + (firstDigit * powTen * 10)) + print(left, end = "" "") + + ''' Update the original number''' + + num = left + + '''Driver code''' + +num = 1445 +cal(num) + + +" +Array range queries over range queries,"/*Java program to perform range queries +over range queries.*/ + +import java.util.Arrays; +class GFG +{ +/* Function to create the record array*/ + + static void record_sum(int record[], int l, + int r, int n, int adder) + { + for (int i = l; i <= r; i++) + { + record[i] += adder; + } + } +/* Driver Code*/ + + public static void main(String[] args) + { + int n = 5, m = 5; + int arr[] = new int[n]; +/* Build query matrix*/ + + Arrays.fill(arr, 0); + int query[][] = {{1, 1, 2}, {1, 4, 5}, + {2, 1, 2}, {2, 1, 3}, + {2, 3, 4}}; + int record[] = new int[m]; + Arrays.fill(record, 0); + for (int i = m - 1; i >= 0; i--) + { +/* If query is of type 2 then function + call to record_sum*/ + + if (query[i][0] == 2) + { + record_sum(record, query[i][1] - 1, + query[i][2] - 1, m, + record[i] + 1); + } +/* If query is of type 1 then + simply add 1 to the record array*/ + + else + { + record_sum(record, i, i, m, 1); + } + } +/* for type 1 queries adding the contains of + record array to the main array record array*/ + + for (int i = 0; i < m; i++) + { + if (query[i][0] == 1) + { + record_sum(arr, query[i][1] - 1, + query[i][2] - 1, + n, record[i]); + } + } +/* printing the array*/ + + for (int i = 0; i < n; i++) + { + System.out.print(arr[i] + "" ""); + } + } +}"," '''Python3 program to perform range queries over range +queries. + ''' '''Function to create the record array''' + +def record_sum(record, l, r, n, adder): + for i in range(l, r + 1): + record[i] += adder + '''Driver Code''' + +n = 5 +m = 5 +arr = [0]*n + '''Build query matrix''' + +query = [[1, 1, 2 ],[ 1, 4, 5 ],[2, 1, 2 ], + [ 2, 1, 3 ],[ 2, 3, 4]] +record = [0]*m +for i in range(m - 1, -1, -1): + ''' If query is of type 2 then function + call to record_sum''' + + if (query[i][0] == 2): + record_sum(record, query[i][1] - 1, + query[i][2] - 1, m, record[i] + 1) + ''' If query is of type 1 then simply add + 1 to the record array''' + + else: + record_sum(record, i, i, m, 1) + '''for type 1 queries adding the contains of +record array to the main array record array''' + +for i in range(m): + if (query[i][0] == 1): + record_sum(arr, query[i][1] - 1, + query[i][2] - 1, n, record[i]) + '''printing the array''' + +for i in range(n): + print(arr[i], end=' ')" +"Given a sorted and rotated array, find if there is a pair with a given sum","/*Java program to find a pair with a given +sum in a sorted and rotated array*/ + +class PairInSortedRotated +{ +/* This function returns true if arr[0..n-1] + has a pair with sum equals to x.*/ + + static boolean pairInSortedRotated(int arr[], + int n, int x) + { +/* Find the pivot element*/ + + int i; + for (i = 0; i < n - 1; i++) + if (arr[i] > arr[i+1]) + break; +/*l is now index of */ + +int l = (i + 1) % n; +/* smallest element +r is now index of largest*/ + +int r = i; +/* element + Keep moving either l or r till they meet*/ + + while (l != r) + { +/* If we find a pair with sum x, we + return true*/ + + if (arr[l] + arr[r] == x) + return true; +/* If current pair sum is less, move + to the higher sum*/ + + if (arr[l] + arr[r] < x) + l = (l + 1) % n; +/*Move to the lower sum side*/ + +else + r = (n + r - 1) % n; + } + return false; + } + /* Driver program to test above function */ + + public static void main (String[] args) + { + int arr[] = {11, 15, 6, 8, 9, 10}; + int sum = 16; + int n = arr.length; + if (pairInSortedRotated(arr, n, sum)) + System.out.print(""Array has two elements"" + + "" with sum 16""); + else + System.out.print(""Array doesn't have two"" + + "" elements with sum 16 ""); + } +}"," '''Python3 program to find a +pair with a given sum in +a sorted and rotated array + ''' '''This function returns True +if arr[0..n-1] has a pair +with sum equals to x.''' + +def pairInSortedRotated( arr, n, x ): + ''' Find the pivot element''' + + for i in range(0, n - 1): + if (arr[i] > arr[i + 1]): + break; + ''' l is now index of smallest element ''' + + l = (i + 1) % n + ''' r is now index of largest element''' + + r = i + ''' Keep moving either l + or r till they meet''' + + while (l != r): + ''' If we find a pair with + sum x, we return True''' + + if (arr[l] + arr[r] == x): + return True; + ''' If current pair sum is less, + move to the higher sum''' + + if (arr[l] + arr[r] < x): + l = (l + 1) % n; + else: + ''' Move to the lower sum side''' + + r = (n + r - 1) % n; + return False; + '''Driver program to test above function''' + +arr = [11, 15, 6, 8, 9, 10] +sum = 16 +n = len(arr) +if (pairInSortedRotated(arr, n, sum)): + print (""Array has two elements with sum 16"") +else: + print (""Array doesn't have two elements with sum 16 "")" +Minimum operation to make all elements equal in array,"/*JAVA Code For Minimum operation to make +all elements equal in array*/ + +import java.util.*; +class GFG { +/* function for min operation */ + + public static int minOperation (int arr[], int n) + { +/* Insert all elements in hash. */ + + HashMap hash = new HashMap(); + for (int i=0; i s = hash.keySet(); + for (int i : s) + if (max_count < hash.get(i)) + max_count = hash.get(i); +/* return result*/ + + return (n - max_count); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = {1, 5, 2, 1, 3, 2, 1}; + int n = arr.length; + System.out.print(minOperation(arr, n)); + } +}"," '''Python3 program to find the minimum +number of operations required to +make all elements of array equal ''' + +from collections import defaultdict + '''Function for min operation ''' + +def minOperation(arr, n): + ''' Insert all elements in hash. ''' + + Hash = defaultdict(lambda:0) + for i in range(0, n): + Hash[arr[i]] += 1 + ''' find the max frequency ''' + + max_count = 0 + for i in Hash: + if max_count < Hash[i]: + max_count = Hash[i] + ''' return result ''' + + return n - max_count + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [1, 5, 2, 1, 3, 2, 1] + n = len(arr) + print(minOperation(arr, n))" +Efficiently compute sums of diagonals of a matrix,"/*An efficient java program to find +sum of diagonals*/ + +import java.io.*; +public class GFG { + static void printDiagonalSums(int [][]mat, + int n) + { + int principal = 0, secondary = 0; + for (int i = 0; i < n; i++) { + principal += mat[i][i]; + secondary += mat[i][n - i - 1]; + } + System.out.println(""Principal Diagonal:"" + + principal); + System.out.println(""Secondary Diagonal:"" + + secondary); + } +/* Driver code*/ + + static public void main (String[] args) + { + int [][]a = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 1, 2, 3, 4 }, + { 5, 6, 7, 8 } }; + printDiagonalSums(a, 4); + } +}"," '''A simple Python3 program to find +sum of diagonals''' + +MAX = 100 +def printDiagonalSums(mat, n): + principal = 0 + secondary = 0 + for i in range(0, n): + principal += mat[i][i] + secondary += mat[i][n - i - 1] + print(""Principal Diagonal:"", principal) + print(""Secondary Diagonal:"", secondary) + '''Driver code''' + +a = [[ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ], + [ 1, 2, 3, 4 ], + [ 5, 6, 7, 8 ]] +printDiagonalSums(a, 4)" +Longest Common Subsequence | DP-4,"/* A Naive recursive implementation of LCS problem in java*/ + +public class LongestCommonSubsequence +{ + /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ + + int lcs( char[] X, char[] Y, int m, int n ) + { + if (m == 0 || n == 0) + return 0; + if (X[m-1] == Y[n-1]) + return 1 + lcs(X, Y, m-1, n-1); + else + return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); + } + /* Utility function to get max of 2 integers */ + + int max(int a, int b) + { + return (a > b)? a : b; + } + +/* Driver code */ + + public static void main(String[] args) + { + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + String s1 = ""AGGTAB""; + String s2 = ""GXTXAYB""; + char[] X=s1.toCharArray(); + char[] Y=s2.toCharArray(); + int m = X.length; + int n = Y.length; + System.out.println(""Length of LCS is"" + "" "" + + lcs.lcs( X, Y, m, n ) ); + } +} +"," '''A Naive recursive Python implementation of LCS problem''' + + + ''' Returns length of LCS for X[0..m-1], Y[0..n-1] ''' + +def lcs(X, Y, m, n): + if m == 0 or n == 0: + return 0; + elif X[m-1] == Y[n-1]: + return 1 + lcs(X, Y, m-1, n-1); + else: + return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); '''Driver program to test the above function''' + +X = ""AGGTAB"" +Y = ""GXTXAYB"" +print ""Length of LCS is "", lcs(X , Y, len(X), len(Y))" +Collect maximum coins before hitting a dead end,," '''A Naive Recursive Python 3 program to +find maximum number of coins that can be collected before hitting a dead end ''' + +R= 5 +C= 5 + '''to check whether current cell is out of the grid or not ''' + +def isValid( i, j): + return (i >=0 and i < R and j >=0 and j < C) + '''dir = 0 for left, dir = 1 for facing right. +This function returns +number of maximum coins that can be collected +starting from (i, j). ''' + +def maxCoinsRec(arr, i, j, dir): + ''' If this is a invalid cell or if cell is a blocking cell ''' + + if (isValid(i,j) == False or arr[i][j] == '#'): + return 0 + ''' Check if this cell contains the coin 'C' or if its empty 'E'. ''' + + if (arr[i][j] == 'C'): + result=1 + else: + result=0 + ''' Get the maximum of two cases when you are facing right in this cell ''' + + if (dir == 1): + ''' Direction is right ''' + + return (result + max(maxCoinsRec(arr, i+1, j, 0), + maxCoinsRec(arr, i, j+1, 1))) + ''' Direction is left + Get the maximum of two cases when you are facing left in this cell ''' + + return (result + max(maxCoinsRec(arr, i+1, j, 1), + maxCoinsRec(arr, i, j-1, 0))) + '''Driver program to test above function ''' + +if __name__=='__main__': + arr = [ ['E', 'C', 'C', 'C', 'C'], + ['C', '#', 'C', '#', 'E'], + ['#', 'C', 'C', '#', 'C'], + ['C', 'E', 'E', 'C', 'E'], + ['C', 'E', '#', 'C', 'E'] ] + ''' As per the question initial cell is (0, 0) and direction is + right ''' + + print(""Maximum number of collected coins is "", maxCoinsRec(arr, 0, 0, 1))" +An interesting method to print reverse of a linked list,"/*Java program to print reverse of list*/ + +import java.io.*; +import java.util.*; +/*Represents node of a linkedlist*/ + +class Node { + int data; + Node next; + Node(int val) + { + data = val; + next = null; + } +} +public class GFG +{ + /* Function to reverse the linked list */ + + static void printReverse(Node head, int n) + { + int j = 0; + Node current = head; + while (current != null) { +/* For each node, print proper number + of spaces before printing it */ + + for (int i = 0; i < 2 * (n - j); i++) + System.out.print("" ""); +/* use of carriage return to move back + and print.*/ + + System.out.print(""\r"" + current.data); + current = current.next; + j++; + } + } + /* Function to push a node */ + + static Node push(Node head, int data) + { + Node new_node = new Node(data); + new_node.next = head; + head = new_node; + return head; + } + /* Function to print linked list and find its + length */ + + static int printList(Node head) + { +/* i for finding length of list */ + + int i = 0; + Node temp = head; + while (temp != null) + { + System.out.print(temp.data + "" ""); + temp = temp.next; + i++; + } + return i; + } +/* Driver code*/ + + public static void main(String args[]) + { + /* Start with the empty list */ + + Node head = null; +/* list nodes are as 6 5 4 3 2 1*/ + + head = push(head, 1); + head = push(head, 2); + head = push(head, 3); + head = push(head, 4); + head = push(head, 5); + head = push(head, 6); + System.out.println(""Given linked list: ""); +/* printlist print the list and + return the size of list */ + + int n = printList(head); +/* print reverse list with help + of carriage return function*/ + + System.out.println(""Reversed Linked list: ""); + printReverse(head, n); + System.out.println(); + } +}"," '''Python3 program to print reverse of list''' + + '''Link list node ''' + +class Node: + def __init__(self): + self.data= 0 + self.next=None '''Function to reverse the linked list ''' + +def printReverse( head_ref, n): + j = 0 + current = head_ref + while (current != None): + i = 0 + ''' For each node, print proper number + of spaces before printing it''' + + while ( i < 2 * (n - j) ): + print(end="" "") + i = i + 1 + ''' use of carriage return to move back + and print.''' + + print( current.data, end = ""\r"") + current = current.next + j = j + 1 + ''' Function to push a node ''' + +def push( head_ref, new_data): + new_node = Node() + new_node.data = new_data + new_node.next = (head_ref) + (head_ref) = new_node + return head_ref; + '''Function to print linked list and find its + length ''' + +def printList( head): + ''' i for finding length of list''' + + i = 0 + temp = head + while (temp != None): + print( temp.data,end = "" "") + temp = temp.next + i = i + 1 + return i + '''Driver program to test above function''' + + '''Start with the empty list ''' + +head = None '''list nodes are as 6 5 4 3 2 1''' + +head = push(head, 1) +head = push(head, 2) +head = push(head, 3) +head = push(head, 4) +head = push(head, 5) +head = push(head, 6) +print(""Given linked list:"") + '''printlist print the list and +return the size of list''' + +n = printList(head) + '''print reverse list with help +of carriage return function''' + +print(""\nReversed Linked list:"") +printReverse(head, n) +print()" +Minimum flip required to make Binary Matrix symmetric,"/*Java Program to find minimum flip +required to make Binary Matrix +symmetric along main diagonal*/ + +import java.util.*; +class GFG { +/* Return the minimum flip required + to make Binary Matrix symmetric + along main diagonal.*/ + + static int minimumflip(int mat[][], int n) + { + int transpose[][] = new int[n][n]; +/* finding the transpose of the matrix*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + transpose[i][j] = mat[j][i]; +/* Finding the number of position + where element are not same.*/ + + int flip = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (transpose[i][j] != mat[i][j]) + flip++; + return flip / 2; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int n = 3; + int mat[][] = {{ 0, 0, 1 }, + { 1, 1, 1 }, + { 1, 0, 0 }}; + System.out.println(minimumflip(mat, n)); + } +}"," '''Python3 code to find minimum flip +required to make Binary Matrix +symmetric along main diagonal''' + +N = 3 + '''Return the minimum flip required +to make Binary Matrix symmetric +along main diagonal.''' + +def minimumflip(mat, n): + transpose =[[0] * n] * n + ''' finding the transpose of the matrix''' + + for i in range(n): + for j in range(n): + transpose[i][j] = mat[j][i] + ''' Finding the number of position + where element are not same.''' + + flip = 0 + for i in range(n): + for j in range(n): + if transpose[i][j] != mat[i][j]: + flip += 1 + return int(flip / 2) + '''Driver Program''' + +n = 3 +mat =[[ 0, 0, 1], + [ 1, 1, 1], + [ 1, 0, 0]] +print( minimumflip(mat, n))" +Positive elements at even and negative at odd positions (Relative order not maintained),"/*Java program to rearrange positive +and negative numbers*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Swap function*/ + + static void swap(int[] a, int i, int j) + { + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } +/* Print array function*/ + + static void printArray(int[] a, int n) + { + for (int i = 0; i < n; i++) + System.out.print(a[i] + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String args[]) + { + int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; + int n = arr.length; +/* before modification*/ + + printArray(arr, n); + for (int i = 0; i < n; i++) + { + if (arr[i] >= 0 && i % 2 == 1) + { +/* out of order positive element*/ + + for (int j = i + 1; j < n; j++) + { + if (arr[j] < 0 && j % 2 == 0) + { +/* find out of order negative + element in remaining array*/ + + swap(arr, i, j); + break ; + } + } + } + else if (arr[i] < 0 && i % 2 == 0) + { +/* out of order negative element*/ + + for (int j = i + 1; j < n; j++) + { + if (arr[j] >= 0 && j % 2 == 1) + { +/* find out of order positive + element in remaining array*/ + + swap(arr, i, j); + break; + } + } + } + } +/* after modification*/ + + printArray(arr, n); + } +}"," '''Python3 program to rearrange positive +and negative numbers''' + + '''Print array function''' + +def printArray(a, n): + for i in a: + print(i, end = "" "") + print() '''Driver code''' + +arr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10] +n = len(arr) + '''before modification''' + +printArray(arr, n) +for i in range(n): + if(arr[i] >= 0 and i % 2 == 1): + ''' out of order positive element''' + + for j in range(i + 1, n): + if(arr[j] < 0 and j % 2 == 0): + ''' find out of order negative + element in remaining array''' + + arr[i], arr[j] = arr[j], arr[i] + break + elif (arr[i] < 0 and i % 2 == 0): + ''' out of order negative element''' + + for j in range(i + 1, n): + if(arr[j] >= 0 and j % 2 == 1): + ''' find out of order positive + element in remaining array''' + + arr[i], arr[j] = arr[j], arr[i] + break + '''after modification''' + +printArray(arr, n);" +Construct Binary Tree from String with bracket representation,"/* Java program to cona binary tree from + the given String */ + +import java.util.*; +class GFG +{ + /* A binary tree node has data, pointer to left + child and a pointer to right child */ + + static class Node + { + int data; + Node left, right; + }; + /* Helper function that allocates a new node */ + + static Node newNode(int data) + { + Node node = new Node(); + node.data = data; + node.left = node.right = null; + return (node); + } + /* This funtcion is here just to test */ + + static void preOrder(Node node) + { + if (node == null) + return; + System.out.printf(""%d "", node.data); + preOrder(node.left); + preOrder(node.right); + } +/* function to return the index of close parenthesis*/ + + static int findIndex(String str, int si, int ei) + { + if (si > ei) + return -1; +/* Inbuilt stack*/ + + Stack s = new Stack<>(); + for (int i = si; i <= ei; i++) + { +/* if open parenthesis, push it*/ + + if (str.charAt(i) == '(') + s.add(str.charAt(i)); +/* if close parenthesis*/ + + else if (str.charAt(i) == ')') + { + if (s.peek() == '(') + { + s.pop(); +/* if stack is empty, this is + the required index*/ + + if (s.isEmpty()) + return i; + } + } + } +/* if not found return -1*/ + + return -1; + } +/* function to contree from String*/ + + static Node treeFromString(String str, int si, int ei) + { +/* Base case*/ + + if (si > ei) + return null; +/* new root*/ + + Node root = newNode(str.charAt(si) - '0'); + int index = -1; +/* if next char is '(' find the index of + its complement ')'*/ + + if (si + 1 <= ei && str.charAt(si+1) == '(') + index = findIndex(str, si + 1, ei); +/* if index found*/ + + if (index != -1) + { +/* call for left subtree*/ + + root.left = treeFromString(str, si + 2, index - 1); +/* call for right subtree*/ + + root.right + = treeFromString(str, index + 2, ei - 1); + } + return root; + } +/* Driver Code*/ + + public static void main(String[] args) + { + String str = ""4(2(3)(1))(6(5))""; + Node root = treeFromString(str, 0, str.length() - 1); + preOrder(root); + } +}"," '''Python3 program to conStruct a +binary tree from the given String''' + + '''Helper class that allocates a new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''This funtcion is here just to test''' + +def preOrder(node): + if (node == None): + return + print(node.data, end="" "") + preOrder(node.left) + preOrder(node.right) + '''function to return the index of +close parenthesis''' + +def findIndex(Str, si, ei): + if (si > ei): + return -1 + ''' Inbuilt stack''' + + s = [] + for i in range(si, ei + 1): + ''' if open parenthesis, push it''' + + if (Str[i] == '('): + s.append(Str[i]) + ''' if close parenthesis''' + + elif (Str[i] == ')'): + if (s[-1] == '('): + s.pop(-1) + ''' if stack is empty, this is + the required index''' + + if len(s) == 0: + return i + ''' if not found return -1''' + + return -1 + '''function to conStruct tree from String''' + +def treeFromString(Str, si, ei): + ''' Base case''' + + if (si > ei): + return None + ''' new root''' + + root = newNode(ord(Str[si]) - ord('0')) + index = -1 + ''' if next char is '(' find the + index of its complement ')''' + ''' + if (si + 1 <= ei and Str[si + 1] == '('): + index = findIndex(Str, si + 1, ei) + ''' if index found''' + + if (index != -1): + ''' call for left subtree''' + + root.left = treeFromString(Str, si + 2, + index - 1) + ''' call for right subtree''' + + root.right = treeFromString(Str, index + 2, + ei - 1) + return root + '''Driver Code''' + +if __name__ == '__main__': + Str = ""4(2(3)(1))(6(5))"" + root = treeFromString(Str, 0, len(Str) - 1) + preOrder(root)" +"Find all pairs (a, b) in an array such that a % b = k","/*Java program to find all pairs such that +a % b = k.*/ + +import java.util.HashMap; +import java.util.Vector; +class Test { +/* Utility method to find the divisors of + n and store in vector v[]*/ + + static Vector findDivisors(int n) + { + Vector v = new Vector<>(); +/* Vector is used to store the divisors*/ + + for (int i = 1; i <= Math.sqrt(n); i++) { + if (n % i == 0) { +/* If n is a square number, push + only one occurrence*/ + + if (n / i == i) + v.add(i); + else { + v.add(i); + v.add(n / i); + } + } + } + return v; + } +/* method to find pairs such that (a%b = k)*/ + + static boolean printPairs(int arr[], int n, int k) + { +/* Store all the elements in the map + to use map as hash for finding elements + in O(1) time.*/ + + HashMap occ = new HashMap<>(); + for (int i = 0; i < n; i++) + occ.put(arr[i], true); + boolean isPairFound = false; + for (int i = 0; i < n; i++) { +/* Print all the pairs with (a, b) as + (k, numbers greater than k) as + k % (num (> k)) = k i.e. 2%4 = 2*/ + + if (occ.get(k) && k < arr[i]) { + System.out.print(""("" + k + "", "" + arr[i] + "") ""); + isPairFound = true; + } +/* Now check for the current element as 'a' + how many b exists such that a%b = k*/ + + if (arr[i] >= k) { +/* find all the divisors of (arr[i]-k)*/ + + Vector v = findDivisors(arr[i] - k); +/* Check for each divisor i.e. arr[i] % b = k + or not, if yes then print that pair.*/ + + for (int j = 0; j < v.size(); j++) { + if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) { + System.out.print(""("" + arr[i] + "", "" + + v.get(j) + "") ""); + isPairFound = true; + } + } +/* Clear vector*/ + + v.clear(); + } + } + return isPairFound; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = { 3, 1, 2, 5, 4 }; + int k = 2; + if (printPairs(arr, arr.length, k) == false) + System.out.println(""No such pair exists""); + } +}"," '''Python3 program to find all pairs +such that a % b = k.''' + '''Utiltity function to find the divisors +of n and store in vector v[]''' + +import math as mt +def findDivisors(n): + v = [] + ''' Vector is used to store the divisors''' + + for i in range(1, mt.floor(n**(.5)) + 1): + if (n % i == 0): + ''' If n is a square number, push + only one occurrence''' + + if (n / i == i): + v.append(i) + else: + v.append(i) + v.append(n // i) + return v + '''Function to find pairs such that (a%b = k)''' + +def printPairs(arr, n, k): + ''' Store all the elements in the map + to use map as hash for finding elements + in O(1) time.''' + + occ = dict() + for i in range(n): + occ[arr[i]] = True + isPairFound = False + for i in range(n): + ''' Print all the pairs with (a, b) as + (k, numbers greater than k) as + k % (num (> k)) = k i.e. 2%4 = 2''' + + if (occ[k] and k < arr[i]): + print(""("", k, "","", arr[i], "")"", end = "" "") + isPairFound = True + ''' Now check for the current element as 'a' + how many b exists such that a%b = k''' + + if (arr[i] >= k): + ''' find all the divisors of (arr[i]-k)''' + + v = findDivisors(arr[i] - k) + ''' Check for each divisor i.e. arr[i] % b = k + or not, if yes then prthat pair.''' + + for j in range(len(v)): + if (arr[i] % v[j] == k and + arr[i] != v[j] and + occ[v[j]]): + print(""("", arr[i], "","", v[j], + "")"", end = "" "") + isPairFound = True + + ''' Clear vector''' + + return isPairFound '''Driver Code''' + +arr = [3, 1, 2, 5, 4] +n = len(arr) +k = 2 +if (printPairs(arr, n, k) == False): + print(""No such pair exists"")" +Most frequent element in an array,"/*Java program to find the most frequent element +in an array*/ + +import java.util.*; +class GFG { + static int mostFrequent(int arr[], int n) + { +/* Sort the array*/ + + Arrays.sort(arr); +/* find the max frequency using linear + traversal*/ + + int max_count = 1, res = arr[0]; + int curr_count = 1; + for (int i = 1; i < n; i++) + { + if (arr[i] == arr[i - 1]) + curr_count++; + else + { + if (curr_count > max_count) + { + max_count = curr_count; + res = arr[i - 1]; + } + curr_count = 1; + } + } +/* If last element is most frequent*/ + + if (curr_count > max_count) + { + max_count = curr_count; + res = arr[n - 1]; + } + return res; + } +/* Driver program*/ + + public static void main (String[] args) { + int arr[] = {1, 5, 2, 1, 3, 2, 1}; + int n = arr.length; + System.out.println(mostFrequent(arr,n)); + } +}"," '''Python3 program to find the most +frequent element in an array.''' + +def mostFrequent(arr, n): + ''' Sort the array''' + + arr.sort() + ''' find the max frequency using + linear traversal''' + + max_count = 1; res = arr[0]; curr_count = 1 + for i in range(1, n): + if (arr[i] == arr[i - 1]): + curr_count += 1 + else : + if (curr_count > max_count): + max_count = curr_count + res = arr[i - 1] + curr_count = 1 + ''' If last element is most frequent''' + + if (curr_count > max_count): + max_count = curr_count + res = arr[n - 1] + return res + '''Driver Code''' + +arr = [1, 5, 2, 1, 3, 2, 1] +n = len(arr) +print(mostFrequent(arr, n))" +Sorted merge of two sorted doubly circular linked lists,"/*Java implementation for Sorted merge of two +sorted doubly circular linked list*/ + +class GFG +{ + +static class Node +{ + int data; + Node next, prev; +}; + +/*A utility function to insert a new node at the +beginning of doubly circular linked list*/ + +static Node insert(Node head_ref, int data) +{ +/* allocate space*/ + + Node new_node = new Node(); + +/* put in the data*/ + + new_node.data = data; + +/* if list is empty*/ + + if (head_ref == null) + { + new_node.next = new_node; + new_node.prev = new_node; + } + + else + { + +/* pointer points to last Node*/ + + Node last = (head_ref).prev; + +/* setting up previous and next of new node*/ + + new_node.next = head_ref; + new_node.prev = last; + +/* update next and previous pointers of head_ref + and last.*/ + + last.next = (head_ref).prev = new_node; + } + +/* update head_ref pointer*/ + + head_ref = new_node; + return head_ref; +} + +/*function for Sorted merge of two +sorted doubly linked list*/ + +static Node merge(Node first, Node second) +{ +/* If first list is empty*/ + + if (first == null) + return second; + +/* If second list is empty*/ + + if (second == null) + return first; + +/* Pick the smaller value and adjust + the links*/ + + 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; + } +} + +/*function for Sorted merge of two sorted +doubly circular linked list*/ + +static Node mergeUtil(Node head1, Node head2) +{ +/* if 1st list is empty*/ + + if (head1 == null) + return head2; + +/* if 2nd list is empty*/ + + if (head2 == null) + return head1; + +/* get pointer to the node which will be the + last node of the final list*/ + + Node last_node; + if (head1.prev.data < head2.prev.data) + last_node = head2.prev; + else + last_node = head1.prev; + +/* store null to the 'next' link of the last nodes + of the two lists*/ + + head1.prev.next = head2.prev.next = null; + +/* sorted merge of head1 and head2*/ + + Node finalHead = merge(head1, head2); + +/* 'prev' of 1st node pointing the last node + 'next' of last node pointing to 1st node*/ + + finalHead.prev = last_node; + last_node.next = finalHead; + + return finalHead; +} + +/*function to print the list*/ + +static void printList(Node head) +{ + Node temp = head; + + while (temp.next != head) + { + System.out.print ( temp.data+ "" ""); + temp = temp.next; + } + System.out.print ( temp.data + "" ""); +} + +/*Driver code*/ + +public static void main(String args[]) +{ + Node head1 = null, head2 = null; + +/* list 1:*/ + + head1 = insert(head1, 8); + head1 = insert(head1, 5); + head1 = insert(head1, 3); + head1 = insert(head1, 1); + +/* list 2:*/ + + head2 = insert(head2, 11); + head2 = insert(head2, 9); + head2 = insert(head2, 7); + head2 = insert(head2, 2); + + Node newHead = mergeUtil(head1, head2); + + System.out.print( ""Final Sorted List: ""); + printList(newHead); +} +} + + +"," ''' Python3 implementation for Sorted merge +of two sorted doubly circular linked list''' + +import math + +class Node: + def __init__(self, data): + self.data = data + self.next = None + self.prev = None + + '''A utility function to insert +a new node at the beginning +of doubly circular linked list''' + +def insert(head_ref, data): + + ''' allocate space''' + + new_node = Node(data) + + ''' put in the data''' + + new_node.data = data + + ''' if list is empty''' + + if (head_ref == None): + new_node.next = new_node + new_node.prev = new_node + + else : + + ''' pointer points to last Node''' + + last = head_ref.prev + + ''' setting up previous and + next of new node''' + + new_node.next = head_ref + new_node.prev = last + + ''' update next and previous pointers + of head_ref and last.''' + + last.next = new_node + head_ref.prev = new_node + + ''' update head_ref pointer''' + + head_ref = new_node + return head_ref + + '''function for Sorted merge of two +sorted doubly linked list''' + +def merge(first, second): + + ''' If first list is empty''' + + if (first == None): + return second + + ''' If second list is empty''' + + if (second == None): + return first + + ''' Pick the smaller value and + adjust the links''' + + if (first.data < second.data) : + first.next = merge(first.next, + second) + first.next.prev = first + first.prev = None + return first + + else : + second.next = merge(first, + second.next) + second.next.prev = second + second.prev = None + return second + + '''function for Sorted merge of two sorted +doubly circular linked list''' + +def mergeUtil(head1, head2): + + ''' if 1st list is empty''' + + if (head1 == None): + return head2 + + ''' if 2nd list is empty''' + + if (head2 == None): + return head1 + + ''' get pointer to the node + which will be the last node + of the final list last_node''' + + if (head1.prev.data < head2.prev.data): + last_node = head2.prev + else: + last_node = head1.prev + + ''' store None to the 'next' link of + the last nodes of the two lists''' + + head1.prev.next = None + head2.prev.next = None + + ''' sorted merge of head1 and head2''' + + finalHead = merge(head1, head2) + + ''' 'prev' of 1st node pointing the last node + 'next' of last node pointing to 1st node''' + + finalHead.prev = last_node + last_node.next = finalHead + + return finalHead + + '''function to print the list''' + +def printList(head): + temp = head + + while (temp.next != head): + print(temp.data, end = "" "") + temp = temp.next + + print(temp.data, end = "" "") + + '''Driver Code''' + +if __name__=='__main__': + head1 = None + head2 = None + + ''' list 1:''' + + head1 = insert(head1, 8) + head1 = insert(head1, 5) + head1 = insert(head1, 3) + head1 = insert(head1, 1) + + ''' list 2:''' + + head2 = insert(head2, 11) + head2 = insert(head2, 9) + head2 = insert(head2, 7) + head2 = insert(head2, 2) + + newHead = mergeUtil(head1, head2) + + print(""Final Sorted List: "", end = """") + printList(newHead) + + +" +Frequencies of even and odd numbers in a matrix,"/*Java Program to Find the frequency +of even and odd numbers in a matrix*/ + +class GFG { +static final int MAX = 100; +/*function for calculating frequency*/ + +static void freq(int ar[][], int m, int n) { + int even = 0, odd = 0; + for (int i = 0; i < m; ++i) + { + for (int j = 0; j < n; ++j) + { +/* modulo by 2 to check + even and odd*/ + + if ((ar[i][j] % 2) == 0) + ++even; + else + ++odd; + } + } +/* print Frequency of numbers*/ + + System.out.print("" Frequency of odd number ="" + + odd + "" \n""); + System.out.print("" Frequency of even number = "" + + even + "" \n""); +} +/*Driver code*/ + +public static void main(String[] args) { + int m = 3, n = 3; + int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + freq(array, m, n); +} +}"," '''Python Program to Find the frequency +of even and odd numbers in a matrix''' + +MAX=100 + '''Function for calculating frequency''' + +def freq(ar, m, n): + even = 0 + odd = 0 + for i in range(m): + for j in range(n): + ''' modulo by 2 to check + even and odd''' + + if ((ar[i][j] % 2) == 0): + even += 1 + else: + odd += 1 + ''' print Frequency of numbers''' + + print("" Frequency of odd number ="", odd) + print("" Frequency of even number ="", even) + '''Driver code''' + +m = 3 +n = 3 +array = [ [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] ] +freq(array, m, n)" +Partition problem | DP-18,"/*A recursive Java solution for partition problem*/ + +import java.io.*; +class Partition { +/* A utility function that returns true if there is a + subset of arr[] with sun equal to given sum*/ + + static boolean isSubsetSum(int arr[], int n, int sum) + { +/* Base Cases*/ + + if (sum == 0) + return true; + if (n == 0 && sum != 0) + return false; +/* If last element is greater than sum, then ignore + it*/ + + if (arr[n - 1] > sum) + return isSubsetSum(arr, n - 1, sum); + /* else, check if sum can be obtained by any of + the following + (a) including the last element + (b) excluding the last element + */ + + return isSubsetSum(arr, n - 1, sum) + || isSubsetSum(arr, n - 1, sum - arr[n - 1]); + } +/* Returns true if arr[] can be partitioned in two + subsets of equal sum, otherwise false*/ + + static boolean findPartition(int arr[], int n) + { +/* Calculate sum of the elements in array*/ + + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; +/* If sum is odd, there cannot be two subsets + with equal sum*/ + + if (sum % 2 != 0) + return false; +/* Find if there is subset with sum equal to half + of total sum*/ + + return isSubsetSum(arr, n, sum / 2); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 3, 1, 5, 9, 12 }; + int n = arr.length; +/* Function call*/ + + if (findPartition(arr, n) == true) + System.out.println(""Can be divided into two "" + + ""subsets of equal sum""); + else + System.out.println( + ""Can not be divided into "" + + ""two subsets of equal sum""); + } +}"," '''A recursive Python3 program for +partition problem''' '''A utility function that returns +true if there is a subset of +arr[] with sun equal to given sum''' + +def isSubsetSum(arr, n, sum): + ''' Base Cases''' + + if sum == 0: + return True + if n == 0 and sum != 0: + return False + ''' If last element is greater than sum, then + ignore it''' + + if arr[n-1] > sum: + return isSubsetSum(arr, n-1, sum) + ''' else, check if sum can be obtained by any of + the following + (a) including the last element + (b) excluding the last element''' + + return isSubsetSum(arr, n-1, sum) or isSubsetSum(arr, n-1, sum-arr[n-1]) + '''Returns true if arr[] can be partitioned in two +subsets of equal sum, otherwise false''' + +def findPartion(arr, n): + ''' Calculate sum of the elements in array''' + + sum = 0 + for i in range(0, n): + sum += arr[i] + ''' If sum is odd, there cannot be two subsets + with equal sum''' + + if sum % 2 != 0: + return false + ''' Find if there is subset with sum equal to + half of total sum''' + + return isSubsetSum(arr, n, sum // 2) + '''Driver code''' + +arr = [3, 1, 5, 9, 12] +n = len(arr) + '''Function call''' + +if findPartion(arr, n) == True: + print(""Can be divided into two subsets of equal sum"") +else: + print(""Can not be divided into two subsets of equal sum"")" +Binary Tree (Array implementation),"/*JAVA implementation of tree using array +numbering starting from 0 to n-1.*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class Array_imp { + static int root = 0; + static String[] str = new String[10]; + +/*create root*/ + + public void Root(String key) + { + str[0] = key; + } + /*create left son of root*/ + + public void set_Left(String key, int root) + { + int t = (root * 2) + 1; + if (str[root] == null) { + System.out.printf(""Can't set child at %d, no parent found\n"", t); + } + else { + str[t] = key; + } + } + /*create right son of root*/ + + public void set_Right(String key, int root) + { + int t = (root * 2) + 2; + if (str[root] == null) { + System.out.printf(""Can't set child at %d, no parent found\n"", t); + } + else { + str[t] = key; + } + } +/*Print tree*/ + + public void print_Tree() + { + for (int i = 0; i < 10; i++) { + if (str[i] != null) + System.out.print(str[i]); + else + System.out.print(""-""); + } + } +}/*Driver Code*/ + +class Tree { + public static void main(String[] args) + { + Array_imp obj = new Array_imp(); + obj.Root(""A""); + obj.set_Right(""C"", 0); + obj.set_Left(""D"", 1); + obj.set_Right(""E"", 1); + obj.set_Left(""F"", 2); + obj.print_Tree(); + } +}"," '''Python3 implementation of tree using array +numbering starting from 0 to n-1.''' + +tree = [None] * 10 + '''create root''' + +def root(key): + if tree[0] != None: + print(""Tree already had root"") + else: + tree[0] = key '''create left son of root''' + +def set_left(key, parent): + if tree[parent] == None: + print(""Can't set child at"", (parent * 2) + 1, "", no parent found"") + else: + tree[(parent * 2) + 1] = key '''create right son of root''' + +def set_right(key, parent): + if tree[parent] == None: + print(""Can't set child at"", (parent * 2) + 2, "", no parent found"") + else: + tree[(parent * 2) + 2] = key '''Print tree''' + +def print_tree(): + for i in range(10): + if tree[i] != None: + print(tree[i], end="""") + else: + print(""-"", end="""") + print() + '''Driver Code''' + +root('A') +set_right('C', 0) +set_left('D', 1) +set_right('E', 1) +set_right('F', 2) +print_tree()" +Special two digit numbers in a Binary Search Tree,"/*Java program to count number of nodes in +BST containing two digit special number*/ + +/*A binary tree node*/ + +class Node +{ + int info; + Node left, right; + Node(int d) + { + info = d; + left = right = null; + } +} +class BinaryTree{ +static Node head; +static int count;/*Function to create a new node*/ + +Node insert(Node node, int info) +{ +/* If the tree is empty, return a new, + single node*/ + + if (node == null) + { + return (new Node(info)); + } + else + { +/* Otherwise, recur down the tree*/ + + if (info <= node.info) + { + node.left = insert(node.left, info); + } + else + { + node.right = insert(node.right, info); + } +/* return the (unchanged) node pointer*/ + + return node; + } +} +/*Function to find if number +is special or not*/ + +static int check(int num) +{ + int sum = 0, i = num, + sum_of_digits, + prod_of_digits; +/* Check if number is two digit or not*/ + + if (num < 10 || num > 99) + return 0; + else + { + sum_of_digits = (i % 10) + (i / 10); + prod_of_digits = (i % 10) * (i / 10); + sum = sum_of_digits + prod_of_digits; + } + if (sum == num) + return 1; + else + return 0; +} +/*Function to count number of special +two digit number*/ + +static void countSpecialDigit(Node rt) +{ + int x; + if (rt == null) + return; + else + { + x = check(rt.info); + if (x == 1) + count = count + 1; + countSpecialDigit(rt.left); + countSpecialDigit(rt.right); + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + BinaryTree tree = new BinaryTree(); + Node root = null; + root = tree.insert(root, 50); + tree.insert(root, 29); + tree.insert(root, 59); + tree.insert(root, 19); + tree.insert(root, 53); + tree.insert(root, 556); + tree.insert(root, 56); + tree.insert(root, 94); + tree.insert(root, 13); +/* Function call*/ + + countSpecialDigit(root); + System.out.println(count); +} +}"," '''Python3 program to count number of nodes in +BST containing two digit special number''' + + '''A Tree node''' + +class Node: + def __init__(self, x): + self.data = x + self.left = None + self.right = None '''Function to create a new node''' + +def insert(node, data): + global succ + ''' If the tree is empty, return + a new node''' + + root = node + if (node == None): + return Node(data) + ''' If key is smaller than root's key, + go to left subtree and set successor + as current node''' + + if (data < node.data): + root.left = insert(node.left, data) + elif (data > node.data): + root.right = insert(node.right, data) ''' return the (unchanged) node pointer''' + + return root + '''Function to find if number +is special or not''' + +def check(num): + sum = 0 + i = num + ''' sum_of_digits, prod_of_digits + Check if number is two digit or not''' + + if (num < 10 or num > 99): + return 0 + else: + sum_of_digits = (i % 10) + (i // 10) + prod_of_digits = (i % 10) * (i // 10) + sum = sum_of_digits + prod_of_digits + if (sum == num): + return 1 + else: + return 0 + '''Function to count number of special +two digit number''' + +def countSpecialDigit(rt): + global c + if (rt == None): + return + else: + x = check(rt.data) + if (x == 1): + c += 1 + countSpecialDigit(rt.left) + countSpecialDigit(rt.right) + '''Driver code''' + +if __name__ == '__main__': + root = None + c = 0 + root = insert(root, 50) + root = insert(root, 29) + root = insert(root, 59) + root = insert(root, 19) + root = insert(root, 53) + root = insert(root, 556) + root = insert(root, 56) + root = insert(root, 94) + root = insert(root, 13) ''' Function call, to check each node + for special two digit number''' + + countSpecialDigit(root) + print(c)" +Rotate the matrix right by K times,"/*Java program to rotate a matrix +right by k times*/ + +class GFG +{ +/* size of matrix*/ + + static final int M=3; + static final int N=3; +/* function to rotate matrix by k times*/ + + static void rotateMatrix(int matrix[][], int k) + { +/* temporary array of size M*/ + + int temp[]=new int[M]; +/* within the size of matrix*/ + + k = k % M; + for (int i = 0; i < N; i++) + { +/* copy first M-k elements + to temporary array*/ + + for (int t = 0; t < M - k; t++) + temp[t] = matrix[i][t]; +/* copy the elements from k + to end to starting*/ + + for (int j = M - k; j < M; j++) + matrix[i][j - M + k] = matrix[i][j]; +/* copy elements from + temporary array to end*/ + + for (int j = k; j < M; j++) + matrix[i][j] = temp[j - k]; + } + } +/* function to display the matrix*/ + + static void displayMatrix(int matrix[][]) + { + for (int i = 0; i < N; i++) + { + for (int j = 0; j < M; j++) + System.out.print(matrix[i][j] + "" ""); + System.out.println(); + } + } +/* Driver code*/ + + public static void main (String[] args) + { + int matrix[][] = {{12, 23, 34}, + {45, 56, 67}, + {78, 89, 91}}; + int k = 2; +/* rotate matrix by k*/ + + rotateMatrix(matrix, k); +/* display rotated matrix*/ + + displayMatrix(matrix); + } +}"," '''Python program to rotate +a matrix right by k times + ''' '''size of matrix''' + +M = 3 +N = 3 +matrix = [[12, 23, 34], + [45, 56, 67], + [78, 89, 91]] + '''function to rotate +matrix by k times''' + +def rotateMatrix(k) : + global M, N, matrix + ''' temporary array + of size M''' + + temp = [0] * M + ''' within the size + of matrix''' + + k = k % M + for i in range(0, N) : + ''' copy first M-k elements + to temporary array''' + + for t in range(0, M - k) : + temp[t] = matrix[i][t] + ''' copy the elements from + k to end to starting''' + + for j in range(M - k, M) : + matrix[i][j - M + k] = matrix[i][j] + ''' copy elements from + temporary array to end''' + + for j in range(k, M) : + matrix[i][j] = temp[j - k] + '''function to display +the matrix''' + +def displayMatrix() : + global M, N, matrix + for i in range(0, N) : + for j in range(0, M) : + print (""{} "" . + format(matrix[i][j]), end = """") + print () + '''Driver code''' + +k = 2 + '''rotate matrix by k''' + +rotateMatrix(k) + '''display rotated matrix''' + +displayMatrix()" +Find sum of all left leaves in a given Binary Tree,"/*Java program to find sum of all left leaves*/ + + +/* A binary tree Node has key, pointer to left and right + children */ + +class Node +{ + int data; + Node left, right; + Node(int item) { + data = item; + left = right = null; + } +}/*Passing sum as accumulator and implementing pass by reference +of sum variable*/ + +class Sum +{ + int sum = 0; +} +class BinaryTree +{/* Pass in a sum variable as an accumulator */ + + Node root; + void leftLeavesSumRec(Node node, boolean isleft, Sum summ) + { + if (node == null) + return;/* Check whether this node is a leaf node and is left.*/ + + if (node.left == null && node.right == null && isleft) + summ.sum = summ.sum + node.data; +/* Pass true for left and false for right*/ + + leftLeavesSumRec(node.left, true, summ); + leftLeavesSumRec(node.right, false, summ); + } +/* A wrapper over above recursive function*/ + + int leftLeavesSum(Node node) + { + Sum suum = new Sum(); +/* use the above recursive function to evaluate sum*/ + + leftLeavesSumRec(node, false, suum); + return suum.sum; + } +/* Driver program*/ + + public static void main(String args[]) + { +/* Let us construct the Binary Tree shown in the + above figure*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(9); + tree.root.right = new Node(49); + tree.root.left.right = new Node(12); + tree.root.left.left = new Node(5); + tree.root.right.left = new Node(23); + tree.root.right.right = new Node(52); + tree.root.left.right.right = new Node(12); + tree.root.right.right.left = new Node(50); + System.out.println(""The sum of leaves is "" + + tree.leftLeavesSum(tree.root)); + } +}"," '''Python program to find sum of all left leaves''' + + '''A binary tree node''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + ''' Pass in a sum variable as an accumulator ''' + +def leftLeavesSumRec(root, isLeft, summ): + if root is None: + return + ''' Check whether this node is a leaf node and is left''' + + if root.left is None and root.right is None and isLeft == True: + summ[0] += root.key + ''' Pass 1 for left and 0 for right''' + + leftLeavesSumRec(root.left, 1, summ) + leftLeavesSumRec(root.right, 0, summ) + '''A wrapper over above recursive function''' + +def leftLeavesSum(root): + summ = [0] ''' Use the above recursive function to evaluate sum''' + + leftLeavesSumRec(root, 0, summ) + return summ[0] + '''Driver program to test above function''' + '''Let us construct the Binary Tree shown in the +above figure''' + +root = Node(20); +root.left= Node(9); +root.right = Node(49); +root.right.left = Node(23); +root.right.right= Node(52); +root.right.right.left = Node(50); +root.left.left = Node(5); +root.left.right = Node(12); +root.left.right.right = Node(12); +print ""Sum of left leaves is"", leftLeavesSum(root)" +Queries for rotation and Kth character of the given string in constant time,"/*Java implementation of the above approach*/ + +import java.util.*; +class GFG +{ +static int size = 2; + +/*Function to perform the required +queries on the given string*/ + +static void performQueries(String str, int n, + int queries[][], int q) +{ + +/* Pointer pointing to the current + starting character of the string*/ + + int ptr = 0; + +/* For every query*/ + + for (int i = 0; i < q; i++) + { + +/* If the query is to rotate the string*/ + + if (queries[i][0] == 1) + { + +/* Update the pointer pointing to the + starting character of the string*/ + + ptr = (ptr + queries[i][1]) % n; + } + else + { + int k = queries[i][1]; + +/* Index of the kth character in the + current rotation of the string*/ + + int index = (ptr + k - 1) % n; + +/* Print the kth character*/ + + System.out.println(str.charAt(index)); + } + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + String str = ""abcdefgh""; + int n = str.length(); + + int queries[][] = { { 1, 2 }, { 2, 2 }, + { 1, 4 }, { 2, 7 } }; + int q = queries.length; + + performQueries(str, n, queries, q); +} +} + + +"," '''Python3 implementation of the approach''' + +size = 2 + + '''Function to perform the required +queries on the given string''' + +def performQueries(string, n, queries, q) : + + ''' Pointer pointing to the current starting + character of the string''' + + ptr = 0; + + ''' For every query''' + + for i in range(q) : + + ''' If the query is to rotate the string''' + + if (queries[i][0] == 1) : + + ''' Update the pointer pointing to the + starting character of the string''' + + ptr = (ptr + queries[i][1]) % n; + + else : + + k = queries[i][1]; + + ''' Index of the kth character in the + current rotation of the string''' + + index = (ptr + k - 1) % n; + + ''' Print the kth character''' + + print(string[index]); + + '''Driver code''' + +if __name__ == ""__main__"" : + + string = ""abcdefgh""; + n = len(string); + + queries = [[ 1, 2 ], [ 2, 2 ], + [ 1, 4 ], [ 2, 7 ]]; + q = len(queries); + + performQueries(string, n, queries, q); + + +" +Count of rotations required to generate a sorted array,"/*Java Program to find the +count of rotations*/ + +public class GFG { + +/* Function to return the count of + rotations*/ + + public static int countRotation(int[] arr, + int n) + { + for (int i = 1; i < n; i++) { +/* Find the smallest element*/ + + if (arr[i] < arr[i - 1]) { +/* Return its index*/ + + return i; + } + } +/* If array is not + rotated at all*/ + + return 0; + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr1 = { 4, 5, 1, 2, 3 }; + + System.out.println( + countRotation( + arr1, + arr1.length)); + } +} +"," '''Python3 program to find the +count of rotations''' + + + '''Function to return the count +of rotations''' + +def countRotation(arr, n): + + for i in range (1, n): + + ''' Find the smallest element''' + + if (arr[i] < arr[i - 1]): + + ''' Return its index''' + + return i + + ''' If array is not + rotated at all''' + + return 0 + + '''Driver Code''' + +if __name__ == ""__main__"": + + arr1 = [ 4, 5, 1, 2, 3 ] + n = len(arr1) + + print(countRotation(arr1, n)) + + +" +Delete alternate nodes of a Linked List,"/* deletes alternate nodes of a list +starting with head */ + +static Node deleteAlt(Node head) +{ + if (head == null) + return; + + Node node = head.next; + + if (node == null) + return; + + /* Change the next link of head */ + + head.next = node.next; + + + /* Recursively call for the new next of head */ + + head.next = deleteAlt(head.next); +} + + +"," '''deletes alternate nodes of a list starting with head''' + +def deleteAlt(head): + if (head == None): + return + + node = head.next + + if (node == None): + return + + ''' Change the next link of head''' + + head.next = node.next + + ''' free memory allocated for node + free(node)''' + + + ''' Recursively call for the new next of head''' + + deleteAlt(head.next) + + +" +Leaders in an array,"class LeadersInArray +{ + /* Java Function to print leaders in an array */ + + void printLeaders(int arr[], int size) + { + int max_from_right = arr[size-1]; + /* Rightmost element is always leader */ + + System.out.print(max_from_right + "" ""); + for (int i = size-2; i >= 0; i--) + { + if (max_from_right < arr[i]) + { + max_from_right = arr[i]; + System.out.print(max_from_right + "" ""); + } + } + } + /* Driver program to test above functions */ + + public static void main(String[] args) + { + LeadersInArray lead = new LeadersInArray(); + int arr[] = new int[]{16, 17, 4, 3, 5, 2}; + int n = arr.length; + lead.printLeaders(arr, n); + } +}"," '''Python function to print leaders in array''' + +def printLeaders(arr, size): + max_from_right = arr[size-1] + + ''' Rightmost element is always leader''' + + print max_from_right, + for i in range( size-2, -1, -1): + if max_from_right < arr[i]: + print arr[i], + max_from_right = arr[i] '''Driver function''' + +arr = [16, 17, 4, 3, 5, 2] +printLeaders(arr, len(arr))" +Count set bits in an integer,"public class GFG +{ +/* Check each bit in a number is set or not + and return the total count of the set bits.*/ + + static int countSetBits(int N) + { + int count = 0; +/* (1 << i) = pow(2, i)*/ + + for (int i = 0; i < 4 * 8; i++) + { + if ((N & (1 << i)) != 0) + count++; + } + return count; + } +/* Driver code*/ + + public static void main(String[] args) + { + int N = 15; + System.out.println(countSetBits(N)); + } +}"," '''Check each bit in a number is set or not +and return the total count of the set bits''' + +def countSetBits(N): + count = 0 + ''' (1 << i) = pow(2, i)''' + + for i in range(4*8): + if(N & (1 << i)): + count += 1 + return count + ''' Driver code''' + + N = 15 + print(countSetBits(N))" +Maximum triplet sum in array,"/*Java code to find maximum triplet sum*/ + +import java.io.*; +class GFG { + static int maxTripletSum(int arr[], int n) + { +/* Initialize sum with INT_MIN*/ + + int sum = -1000000; + for (int i = 0; i < n; i++) + for (int j = i + 1; j < n; j++) + for (int k = j + 1; k < n; k++) + if (sum < arr[i] + arr[j] + arr[k]) + sum = arr[i] + arr[j] + arr[k]; + return sum; + } +/* Driven code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 0, 8, 6, 4, 2 }; + int n = arr.length; + System.out.println(maxTripletSum(arr, n)); + } +}"," '''Python 3 code to find +maximum triplet sum''' + +def maxTripletSum(arr, n) : + ''' Initialize sum with + INT_MIN''' + + sm = -1000000 + for i in range(0, n) : + for j in range(i + 1, n) : + for k in range(j + 1, n) : + if (sm < (arr[i] + arr[j] + arr[k])) : + sm = arr[i] + arr[j] + arr[k] + return sm + '''Driven code''' + +arr = [ 1, 0, 8, 6, 4, 2 ] +n = len(arr) +print(maxTripletSum(arr, n))" +Most frequent element in an array,"/*Java program to find the most frequent element +in an array*/ + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +class GFG { + static int mostFrequent(int arr[], int n) + { +/* Insert all elements in hash*/ + + Map hp = + new HashMap(); + for(int i = 0; i < n; i++) + { + int key = arr[i]; + if(hp.containsKey(key)) + { + int freq = hp.get(key); + freq++; + hp.put(key, freq); + } + else + { + hp.put(key, 1); + } + } +/* find max frequency.*/ + + int max_count = 0, res = -1; + for(Entry val : hp.entrySet()) + { + if (max_count < val.getValue()) + { + res = val.getKey(); + max_count = val.getValue(); + } + } + return res; + } +/* Driver code*/ + + public static void main (String[] args) { + int arr[] = {1, 5, 2, 1, 3, 2, 1}; + int n = arr.length; + System.out.println(mostFrequent(arr, n)); + } +}"," '''Python3 program to find the most +frequent element in an array.''' + +import math as mt +def mostFrequent(arr, n): + ''' Insert all elements in Hash.''' + + Hash = dict() + for i in range(n): + if arr[i] in Hash.keys(): + Hash[arr[i]] += 1 + else: + Hash[arr[i]] = 1 + ''' find the max frequency''' + + max_count = 0 + res = -1 + for i in Hash: + if (max_count < Hash[i]): + res = i + max_count = Hash[i] + return res + '''Driver Code''' + +arr = [ 1, 5, 2, 1, 3, 2, 1] +n = len(arr) +print(mostFrequent(arr, n))" +Check whether the length of given linked list is Even or Odd," + + +/*Java program to check length +of a given linklist*/ + +import java.io.*; +class GfG +{ + +/*Defining structure*/ + +static class Node +{ + int data; + Node next; +} + +/*Function to check the length of linklist*/ + +static int LinkedListLength(Node head) +{ + while (head != null && head.next != null) + { + head = head.next.next; + } + if (head == null) + return 0; + return 1; +} + +/*Push function*/ + +static void push(Node head, int info) +{ +/* Allocating node*/ + + Node node = new Node(); + +/* Info into node*/ + + node.data = info; + +/* Next of new node to head*/ + + node.next = (head); + +/* head points to new node*/ + + (head) = node; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + Node head = null; + +/* Adding elements to Linked List*/ + + 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); + +/* Checking for length of + linklist*/ + + if(check == 0) + { + System.out.println(""Odd""); + } + else + { + System.out.println(""Even""); + } +} +} + + +"," '''Python program to check length +of a given linklist''' + + + '''Defining structure''' + +class Node: + def __init__(self, d): + self.data = d + self.next = None + self.head = None + + ''' Function to check the length of linklist''' + + def LinkedListLength(self): + while (self.head != None and self.head.next != None): + self.head = self.head.next.next + + if(self.head == None): + return 0 + return 1 + + ''' Push function''' + + def push(self, info): + + ''' Allocating node''' + + node = Node(info) + + ''' Next of new node to head''' + + node.next = (self.head) + + ''' head points to new node''' + + (self.head) = node + + '''Driver code''' + + +head = Node(0) + + '''Adding elements to Linked List''' + +head.push( 4) +head.push( 5) +head.push( 7) +head.push( 2) +head.push( 9) +head.push( 6) +head.push( 1) +head.push( 2) +head.push( 0) +head.push( 5) +head.push( 5) +check = head.LinkedListLength() + + '''Checking for length of +linklist''' + +if(check == 0) : + print(""Even"") +else: + print(""Odd"") + + +" +Delete every Kth node from circular linked list,"/*Java program to delete every kth Node from +circular linked list.*/ + +class GFG +{ + +/* structure for a Node */ + +static class Node +{ + int data; + Node next; + Node(int x) + { + data = x; + next = null; + } +}; + +/*Utility function to print +the circular linked list*/ + +static void printList(Node head) +{ + if (head == null) + return; + Node temp = head; + do + { + System.out.print( temp.data + ""->""); + temp = temp.next; + } + while (temp != head); + System.out.println(head.data ); +} + +/*Function to delete every kth Node*/ + +static Node deleteK(Node head_ref, int k) +{ + Node head = head_ref; + +/* If list is empty, simply return.*/ + + if (head == null) + return null; + +/* take two pointers - current and previous*/ + + Node curr = head, prev=null; + while (true) + { + +/* Check if Node is the only Node\ + If yes, we reached the goal, therefore + return.*/ + + if (curr.next == head && curr == head) + break; + +/* Print intermediate list.*/ + + printList(head); + +/* If more than one Node present in the list, + Make previous pointer point to current + Iterate current pointer k times, + i.e. current Node is to be deleted.*/ + + for (int i = 0; i < k; i++) + { + prev = curr; + curr = curr.next; + } + +/* If Node to be deleted is head*/ + + if (curr == head) + { + prev = head; + while (prev.next != head) + prev = prev.next; + head = curr.next; + prev.next = head; + head_ref = head; + } + +/* If Node to be deleted is last Node.*/ + + else if (curr.next == head) + { + prev.next = head; + } + else + { + prev.next = curr.next; + } + } + return head; +} + +/* Function to insert a Node at the end of +a Circular linked list */ + +static Node insertNode(Node head_ref, int x) +{ +/* Create a new Node*/ + + Node head = head_ref; + Node temp = new Node(x); + +/* if the list is empty, make the new Node head + Also, it will point to itself.*/ + + if (head == null) + { + temp.next = temp; + head_ref = temp; + return head_ref; + } + +/* traverse the list to reach the last Node + and insert the Node*/ + + else + { + Node temp1 = head; + while (temp1.next != head) + temp1 = temp1.next; + temp1.next = temp; + temp.next = head; + } + return head; +} + +/* Driver code */ + +public static void main(String args[]) +{ +/* insert Nodes in the circular linked list*/ + + Node head = null; + head = insertNode(head, 1); + head = insertNode(head, 2); + head = insertNode(head, 3); + head = insertNode(head, 4); + head = insertNode(head, 5); + head = insertNode(head, 6); + head = insertNode(head, 7); + head = insertNode(head, 8); + head = insertNode(head, 9); + + int k = 4; + +/* Delete every kth Node from the + circular linked list.*/ + + head = deleteK(head, k); +} +} + + +"," '''Python3 program to delete every kth Node from +circular linked list.''' + +import math + + '''structure for a Node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''Utility function to print the circular linked list''' + +def prList(head): + if (head == None): + return + temp = head + + print(temp.data, end = ""->"") + temp = temp.next + while (temp != head): + print(temp.data, end = ""->"") + temp = temp.next + print(head.data) + + '''Function to delete every kth Node''' + +def deleteK(head_ref, k): + head = head_ref + + ''' If list is empty, simply return.''' + + if (head == None): + return + + ''' take two poers - current and previous''' + + curr = head + prev = None + while True: + + ''' Check if Node is the only Node\ + If yes, we reached the goal, therefore + return.''' + + if (curr.next == head and curr == head): + break + + ''' Pr intermediate list.''' + + prList(head) + + ''' If more than one Node present in the list, + Make previous pointer po to current + Iterate current pointer k times, + i.e. current Node is to be deleted.''' + + for i in range(k): + prev = curr + curr = curr.next + + ''' If Node to be deleted is head''' + + if (curr == head): + prev = head + while (prev.next != head): + prev = prev.next + head = curr.next + prev.next = head + head_ref = head + + ''' If Node to be deleted is last Node.''' + + elif (curr.next == head) : + prev.next = head + + else : + prev.next = curr.next + + '''Function to insert a Node at the end of +a Circular linked list''' + +def insertNode(head_ref, x): + + ''' Create a new Node''' + + head = head_ref + temp = Node(x) + + ''' if the list is empty, make the new Node head + Also, it will po to itself.''' + + if (head == None): + temp.next = temp + head_ref = temp + return head_ref + + ''' traverse the list to reach the last Node + and insert the Node''' + + else : + temp1 = head + while (temp1.next != head): + temp1 = temp1.next + temp1.next = temp + temp.next = head + return head + + '''Driver Code''' + +if __name__=='__main__': + + ''' insert Nodes in the circular linked list''' + + head = None + head = insertNode(head, 1) + head = insertNode(head, 2) + head = insertNode(head, 3) + head = insertNode(head, 4) + head = insertNode(head, 5) + head = insertNode(head, 6) + head = insertNode(head, 7) + head = insertNode(head, 8) + head = insertNode(head, 9) + + k = 4 + + ''' Delete every kth Node from the + circular linked list.''' + + deleteK(head, k) + + +" +Longest subsequence of a number having same left and right rotation,"/*Java Program to implement +the above approach*/ + +import java.util.*; +class GFG{ + +/*Function to find the longest subsequence +having equal left and right rotation*/ + +static int findAltSubSeq(String s) +{ +/* Length of the String*/ + + int n = s.length(), ans = Integer.MIN_VALUE; + +/* Iterate for all possible combinations + of a two-digit numbers*/ + + for (int i = 0; i < 10; i++) + { + for (int j = 0; j < 10; j++) + { + int cur = 0, f = 0; + +/* Check for alternate occurrence + of current combination*/ + + for (int k = 0; k < n; k++) + { + if (f == 0 && s.charAt(k) - '0' == i) + { + f = 1; + +/* Increment the current value*/ + + cur++; + } + else if (f == 1 && + s.charAt(k) - '0' == j) + { + f = 0; + +/* Increment the current value*/ + + cur++; + } + } + +/* If alternating sequence is + obtained of odd length*/ + + if (i != j && cur % 2 == 1) + +/* Reduce to even length*/ + + cur--; + +/* Update answer to store + the maximum*/ + + ans = Math.max(cur, ans); + } + } + +/* Return the answer*/ + + return ans; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + String s = ""100210601""; + System.out.print(findAltSubSeq(s)); +} +} + + +"," '''Python3 program to implement +the above approach''' + +import sys + + '''Function to find the longest subsequence +having equal left and right rotation''' + +def findAltSubSeq(s): + + ''' Length of the string''' + + n = len(s) + ans = -sys.maxsize - 1 + + ''' Iterate for all possible combinations + of a two-digit numbers''' + + for i in range(10): + for j in range(10): + cur, f = 0, 0 + + ''' Check for alternate occurrence + of current combination''' + + for k in range(n): + if (f == 0 and ord(s[k]) - + ord('0') == i): + f = 1 + + ''' Increment the current value''' + + cur += 1 + + elif (f == 1 and ord(s[k]) - + ord('0') == j): + f = 0 + + ''' Increment the current value''' + + cur += 1 + + ''' If alternating sequence is + obtained of odd length''' + + if i != j and cur % 2 == 1: + + ''' Reduce to even length''' + + cur -= 1 + + ''' Update answer to store + the maximum''' + + ans = max(cur, ans) + + ''' Return the answer''' + + return ans + + '''Driver code''' + +s = ""100210601"" + +print(findAltSubSeq(s)) + + +" +Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix,"/*Java implementation of More efficient +method to count number of negative numbers +in row-column sorted matrix M[n][m]*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG { +/* Recursive binary search to get last negative + value in a row between a start and an end*/ + + static int getLastNegativeIndex(int array[], int start, int end) + { +/* Base case*/ + + if (start == end) { + return start; + } +/* Get the mid for binary search*/ + + int mid = start + (end - start) / 2; +/* If current element is negative*/ + + if (array[mid] < 0) { +/* If it is the rightmost negative + element in the current row*/ + + if (mid + 1 < array.length && array[mid + 1] >= 0) { + return mid; + } +/* Check in the right half of the array*/ + + return getLastNegativeIndex(array, mid + 1, end); + } + else { +/* Check in the left half of the array*/ + + return getLastNegativeIndex(array, start, mid - 1); + } + } +/* Function to return the count of + negative numbers in the given matrix*/ + + static int countNegative(int M[][], int n, int m) + { +/* Initialize result*/ + + int count = 0; +/* To store the index of the rightmost negative + element in the row under consideration*/ + + int nextEnd = m - 1; +/* Iterate over all rows of the matrix*/ + + for (int i = 0; i < n; i++) { +/* If the first element of the current row + is positive then there will be no negatives + in the matrix below or after it*/ + + if (M[i][0] >= 0) { + break; + } +/* Run binary search only until the index of last + negative Integer in the above row*/ + + nextEnd = getLastNegativeIndex(M[i], 0, nextEnd); + count += nextEnd + 1; + } + return count; + } +/* Driver code*/ + + public static void main(String[] args) + { + int M[][] = { { -3, -2, -1, 1 }, + { -2, 2, 3, 4 }, + { 4, 5, 7, 8 } }; + int r = M.length; + int c = M[0].length; + System.out.println(countNegative(M, r, c)); + } +}"," '''Python3 implementation of More efficient +method to count number of negative numbers +in row-column sorted matrix M[n][m] + ''' '''Recursive binary search to get last negative +value in a row between a start and an end''' + +def getLastNegativeIndex(array, start, end, n): + ''' Base case''' + + if (start == end): + return start + ''' Get the mid for binary search''' + + mid = start + (end - start) // 2 + ''' If current element is negative''' + + if (array[mid] < 0): + ''' If it is the rightmost negative + element in the current row''' + + if (mid + 1 < n and array[mid + 1] >= 0): + return mid + ''' Check in the right half of the array''' + + return getLastNegativeIndex(array, mid + 1, end, n) + else: + ''' Check in the left half of the array''' + + return getLastNegativeIndex(array, start, mid - 1, n) + '''Function to return the count of +negative numbers in the given matrix''' + +def countNegative(M, n, m): + ''' Initialize result''' + + count = 0 + ''' To store the index of the rightmost negative + element in the row under consideration''' + + nextEnd = m - 1 + ''' Iterate over all rows of the matrix''' + + for i in range(n): + ''' If the first element of the current row + is positive then there will be no negatives + in the matrix below or after it''' + + if (M[i][0] >= 0): + break + ''' Run binary search only until the index of last + negative Integer in the above row''' + + nextEnd = getLastNegativeIndex(M[i], 0, nextEnd, 4) + count += nextEnd + 1 + return count + '''Driver code''' + +M = [[-3, -2, -1, 1],[-2, 2, 3, 4],[ 4, 5, 7, 8]] +r = 3 +c = 4 +print(countNegative(M, r, c))" +Cutting a Rod | DP-13,"/*A Naive recursive solution for Rod cutting problem +*/ + +class RodCutting +{ + /* Returns the best obtainable price for a rod of length + n and price[] as prices of different pieces */ + + static int cutRod(int price[], int n) + { + if (n <= 0) + return 0; + int max_val = Integer.MIN_VALUE; +/* Recursively cut the rod in different pieces and + compare different configurations*/ + + for (int i = 0; i b) else b + '''Returns the best obtainable price for a rod of length n +and price[] as prices of different pieces''' + +def cutRod(price, n): + if(n <= 0): + return 0 + max_val = -sys.maxsize-1 + ''' Recursively cut the rod in different pieces + and compare different configurations''' + + for i in range(0, n): + max_val = max(max_val, price[i] + + cutRod(price, n - i - 1)) + return max_val + '''Driver code''' + +arr = [1, 5, 8, 9, 10, 17, 17, 20] +size = len(arr) +print(""Maximum Obtainable Value is"", cutRod(arr, size))" +Count pairs whose products exist in array,"/*A hashing based Java program to count pairs whose product +exists in arr[]*/ + +import java.util.*; +class GFG +{ +/* Returns count of pairs whose product exists in arr[]*/ + + static int countPairs(int arr[], int n) { + int result = 0; +/* Create an empty hash-set that store all array element*/ + + HashSet< Integer> Hash = new HashSet<>(); +/* Insert all array element into set*/ + + for (int i = 0; i < n; i++) + { + Hash.add(arr[i]); + } +/* Generate all pairs and check is exist in 'Hash' or not*/ + + for (int i = 0; i < n; i++) + { + for (int j = i + 1; j < n; j++) + { + int product = arr[i] * arr[j]; +/* if product exists in set then we increment + count by 1*/ + + if (Hash.contains(product)) + { + result++; + } + } + } +/* return count of pairs whose product exist in array*/ + + return result; + } +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = {6, 2, 4, 12, 5, 3}; + int n = arr.length; + System.out.println(countPairs(arr, n)); + } +}"," '''A hashing based C++ program to count +pairs whose product exists in arr[] + ''' '''Returns count of pairs whose product +exists in arr[]''' + +def countPairs(arr, n): + result = 0 + ''' Create an empty hash-set that + store all array element''' + + Hash = set() + ''' Insert all array element into set''' + + for i in range(n): + Hash.add(arr[i]) + ''' Generate all pairs and check is + exist in 'Hash' or not''' + + for i in range(n): + for j in range(i + 1, n): + product = arr[i] * arr[j] + ''' if product exists in set then + we increment count by 1''' + + if product in(Hash): + result += 1 + ''' return count of pairs whose + product exist in array''' + + return result + '''Driver Code''' + +if __name__ == '__main__': + arr = [6, 2, 4, 12, 5, 3] + n = len(arr) + print(countPairs(arr, n))" +Find the longest path in a matrix with given constraints,," '''Python3 program to find the longest path in a matrix +with given constraints''' + +n = 3 + '''Returns length of the longest path beginning with mat[i][j]. +This function mainly uses lookup table dp[n][n]''' + +def findLongestFromACell(i, j, mat, dp): + ''' Base case''' + + if (i<0 or i>= n or j<0 or j>= n): + return 0 + ''' If this subproblem is already solved''' + + if (dp[i][j] != -1): + return dp[i][j] + ''' To store the path lengths in all the four directions''' + + x, y, z, w = -1, -1, -1, -1 + ''' Since all numbers are unique and in range from 1 to n * n, + there is atmost one possible direction from any cell''' + + if (j0 and (mat[i][j] +1 == mat[i][j-1])): + y = 1 + findLongestFromACell(i, j-1, mat, dp) + if (i>0 and (mat[i][j] +1 == mat[i-1][j])): + z = 1 + findLongestFromACell(i-1, j, mat, dp) + if (i 0; i--) + { + if (i <= n - 2) + { + back[i] = back[i + 1] + a[i]; + } + else + { + back[i] = a[i]; + } + } +/* Checking for equilibrium index by + compairing front and back sums*/ + + for(int i = 0; i < n; i++) + { + if (front[i] == back[i]) + { + return i; + } + } +/* If no equilibrium index found,then return -1*/ + + return -1; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; + int arr_size = arr.length; + System.out.println(""First Point of equilibrium "" + + ""is at index "" + + equilibrium(arr, arr_size)); +} +}"," '''Python program to find the equilibrium +index of an array +Function to find the equilibrium index''' + +def equilibrium(arr): + left_sum = [] + right_sum = [] + ''' Iterate from 0 to len(arr)''' + + for i in range(len(arr)): + ''' If i is not 0''' + + if(i): + left_sum.append(left_sum[i-1]+arr[i]) + right_sum.append(right_sum[i-1]+arr[len(arr)-1-i]) + else: + left_sum.append(arr[i]) + right_sum.append(arr[len(arr)-1]) + ''' Iterate from 0 to len(arr) ''' + + for i in range(len(arr)): + if(left_sum[i] == right_sum[len(arr) - 1 - i ]): + return(i) + ''' If no equilibrium index found,then return -1''' + + return -1 + '''Driver code''' + +arr = [-7, 1, 5, 2, -4, 3, 0] +print('First equilibrium index is ', + equilibrium(arr))" +Check if a given Binary Tree is Heap,"/*Java program to checks if a +binary tree is max heap or not*/ + +import java.util.*; +class GFG +{ +/* Tree node structure*/ + + static class Node + { + int data; + Node left; + Node right; + }; +/* To add a new node*/ + + static Node newNode(int k) + { + Node node = new Node(); + node.data = k; + node.right = node.left = null; + return node; + } + static boolean isHeap(Node root) + { + Queue q = new LinkedList<>(); + q.add(root); + boolean nullish = false; + while (!q.isEmpty()) + { + Node temp = q.peek(); + q.remove(); + if (temp.left != null) + { + if (nullish + || temp.left.data + >= temp.data) + { + return false; + } + q.add(temp.left); + } + else { + nullish = true; + } + if (temp.right != null) + { + if (nullish + || temp.right.data + >= temp.data) + { + return false; + } + q.add(temp.right); + } + else + { + nullish = true; + } + } + return true; + } +/* Driver code*/ + + public static void main(String[] args) + { + Node root = null; + root = newNode(10); + root.left = newNode(9); + root.right = newNode(8); + root.left.left = newNode(7); + root.left.right = newNode(6); + root.right.left = newNode(5); + root.right.right = newNode(4); + root.left.left.left = newNode(3); + root.left.left.right = newNode(2); + root.left.right.left = newNode(1); +/* Function call*/ + + if (isHeap(root)) + System.out.print(""Given binary tree is a Heap\n""); + else + System.out.print(""Given binary tree is not a Heap\n""); + } +}", +Queries for decimal values of subarrays of a binary array,"/*Java implementation of finding number +represented by binary subarray*/ + +import java.util.Arrays; +class GFG { +/* Fills pre[]*/ + + static void precompute(int arr[], int n, int pre[]) + { + Arrays.fill(pre, 0); + pre[n - 1] = arr[n - 1] * (int)(Math.pow(2, 0)); + for (int i = n - 2; i >= 0; i--) + pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); + } +/* returns the number represented by a binary + subarray l to r*/ + + static int decimalOfSubarr(int arr[], int l, int r, + int n, int pre[]) + { +/* if r is equal to n-1 r+1 does not exist*/ + + if (r != n - 1) + return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); + return pre[l] / (1 << (n - 1 - r)); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 1, 0, 1, 0, 1, 1 }; + int n = arr.length; + int pre[] = new int[n]; + precompute(arr, n, pre); + System.out.println(decimalOfSubarr(arr, + 2, 4, n, pre)); + System.out.println(decimalOfSubarr(arr, + 4, 5, n, pre)); + } +}"," '''implementation of finding number +represented by binary subarray''' + +from math import pow + '''Fills pre[]''' + +def precompute(arr, n, pre): + pre[n - 1] = arr[n - 1] * pow(2, 0) + i = n - 2 + while(i >= 0): + pre[i] = (pre[i + 1] + arr[i] * + (1 << (n - 1 - i))) + i -= 1 + '''returns the number represented by +a binary subarray l to r''' + +def decimalOfSubarr(arr, l, r, n, pre): + ''' if r is equal to n-1 r+1 does not exist''' + + if (r != n - 1): + return ((pre[l] - pre[r + 1]) / + (1 << (n - 1 - r))) + return pre[l] / (1 << (n - 1 - r)) + '''Driver Code''' + +if __name__ == '__main__': + arr = [1, 0, 1, 0, 1, 1] + n = len(arr) + pre = [0 for i in range(n)] + precompute(arr, n, pre) + print(int(decimalOfSubarr(arr, 2, 4, n, pre))) + print(int(decimalOfSubarr(arr, 4, 5, n, pre)))" +Reverse a Doubly Linked List | Set 4 (Swapping Data),"/*Java Program to Reverse a List using Data Swapping*/ + +class GFG +{ +static class Node +{ + int data; + Node prev, next; +}; + +static Node newNode(int val) +{ + Node temp = new Node(); + temp.data = val; + temp.prev = temp.next = null; + return temp; +} + +static void printList(Node head) +{ + while (head.next != null) + { + System.out.print(head.data+ "" <-> ""); + head = head.next; + } + System.out.println( head.data ); +} + +/*Insert a new node at the head of the list*/ + +static Node insert(Node head, int val) +{ + Node temp = newNode(val); + temp.next = head; + (head).prev = temp; + (head) = temp; + return head; +} + +/*Function to reverse the list*/ + +static Node reverseList(Node head) +{ + Node left = head, right = head; + +/* Traverse the list and set right pointer to + end of list*/ + + while (right.next != null) + right = right.next; + +/* Swap data of left and right pointer and move + them towards each other until they meet or + cross each other*/ + + while (left != right && left.prev != right) + { + +/* Swap data of left and right pointer*/ + + int t = left.data; + left.data = right.data; + right.data = t; + +/* Advance left pointer*/ + + left = left.next; + +/* Advance right pointer*/ + + right = right.prev; + } + return head; +} + +/*Driver code*/ + +public static void main(String args[]) +{ + Node head = newNode(5); + head = insert(head, 4); + head = insert(head, 3); + head = insert(head, 2); + head = insert(head, 1); + + printList(head); + System.out.println(""List After Reversing""); + head=reverseList(head); + printList(head); + +} +} + + +"," '''Python3 Program to Reverse a List +using Data Swapping''' + +import math + +class Node: + def __init__(self, data): + self.data = data + self.next = None + +def newNode(val): + temp = Node(val) + temp.data = val + temp.prev =None + temp.next = None + return temp + +def printList( head): + while (head.next != None): + print(head.data, end = ""<-->"") + head = head.next + + print(head.data) + + '''Insert a new node at the head of the list''' + +def insert(head, val): + temp = newNode(val) + temp.next = head + (head).prev = temp + (head) = temp + return head + + '''Function to reverse the list''' + +def reverseList( head): + left = head + right = head + + ''' Traverse the list and set right + pointer to end of list''' + + while (right.next != None): + right = right.next + + ''' Swap data of left and right pointer + and move them towards each other + until they meet or cross each other''' + + while (left != right and left.prev != right): + + ''' Swap data of left and right pointer''' + + t = left.data + left.data = right.data + right.data = t + + ''' Advance left pointer''' + + left = left.next + + ''' Advance right pointer''' + + right = right.prev + + return head + + '''Driver code''' + +if __name__=='__main__': + + head = newNode(5) + head = insert(head, 4) + head = insert(head, 3) + head = insert(head, 2) + head = insert(head, 1) + + printList(head) + print(""List After Reversing"") + head = reverseList(head) + printList(head) + + +" +Find an array element such that all elements are divisible by it,"/*Java Program to find the +smallest number that divides +all numbers in an array*/ + +import java.io.*; + +class GFG { + +/* function to find the smallest element*/ + + static int min_element(int a[]) + { + int min = Integer.MAX_VALUE, i; + for (i = 0; i < a.length; i++) + { + if (a[i] < min) + min = a[i]; + } + + return min; + } + +/* function to find smallest num*/ + + static int findSmallest(int a[], int n) + { +/* Find the smallest element*/ + + int smallest = min_element(a); + +/* Check if all array elements + are divisible by smallest.*/ + + for (int i = 1; i < n; i++) + if (a[i] % smallest >= 1) + return -1; + + return smallest; + } + +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = {25, 20, 5, 10, 100}; + int n = a.length; + System.out.println(findSmallest(a, n)); + } +} + + +"," '''Python3 Program to find the +smallest number that divides +all numbers in an array''' + + + '''Function to find the smallest element''' + +def min_element(a) : + + m = 10000000 + + for i in range(0, len(a)) : + + if (a[i] < m) : + m = a[i] + + return m + + '''Function to find smallest num''' + +def findSmallest(a, n) : + + ''' Find the smallest element''' + + smallest = min_element(a) + + ''' Check if all array elements + are divisible by smallest.''' + + for i in range(1, n) : + + if (a[i] % smallest >= 1) : + return -1 + + return smallest + + + '''Driver code''' + + +a = [ 25, 20, 5, 10, 100 ] +n = len(a) +print(findSmallest(a, n)) + + + +" +Check if there is a cycle with odd weight sum in an undirected graph,"/*Java program to check if there is +a cycle of total odd weight*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/*This function returns true if the current subpart +of the forest is two colorable, else false.*/ + +static boolean twoColorUtil(Vector[] G, + int src, int N, + int[] colorArr) +{ +/* Assign first color to source*/ + + colorArr[src] = 1; +/* Create a queue (FIFO) of vertex numbers and + enqueue source vertex for BFS traversal*/ + + Queue q = new LinkedList<>(); + q.add(src); +/* Run while there are vertices in queue + (Similar to BFS)*/ + + while (!q.isEmpty()) + { + int u = q.peek(); + q.poll(); +/* Find all non-colored adjacent vertices*/ + + for (int v = 0; v < G[u].size(); ++v) + { +/* An edge from u to v exists and + destination v is not colored*/ + + if (colorArr[G[u].elementAt(v)] == -1) + { +/* Assign alternate color to this + adjacent v of u*/ + + colorArr[G[u].elementAt(v)] = 1 - colorArr[u]; + q.add(G[u].elementAt(v)); + } +/* An edge from u to v exists and destination + v is colored with same color as u*/ + + else if (colorArr[G[u].elementAt(v)] == colorArr[u]) + return false; + } + } + return true; +} +/*This function returns true if +graph G[V][V] is two colorable, else false*/ + +static boolean twoColor(Vector[] G, int N) +{ +/* Create a color array to store colors assigned + to all veritces. Vertex number is used as index + in this array. The value '-1' of colorArr[i] + is used to indicate that no color is assigned + to vertex 'i'. The value 1 is used to indicate + first color is assigned and value 0 indicates + second color is assigned.*/ + + int[] colorArr = new int[N + 1]; + for (int i = 1; i <= N; ++i) + colorArr[i] = -1; +/* As we are dealing with graph, the input might + come as a forest, thus start coloring from a + node and if true is returned we'll know that + we successfully colored the subpart of our + forest and we start coloring again from a new + uncolored node. This way we cover the entire forest.*/ + + for (int i = 1; i <= N; i++) + if (colorArr[i] == -1) + if (twoColorUtil(G, i, N, colorArr) == false) + return false; + return true; +} +/*Returns false if an odd cycle is present else true +int info[][] is the information about our graph +int n is the number of nodes +int m is the number of informations given to us*/ + +static boolean isOddSum(int[][] info, int n, int m) +{ +/* Declaring adjacency list of a graph + Here at max, we can encounter all the edges with + even weight thus there will be 1 pseudo node + for each edge + @SuppressWarnings(""unchecked"")*/ + + Vector[] G = new Vector[2 * n]; + for (int i = 0; i < 2 * n; i++) + G[i] = new Vector<>(); + int pseudo = n + 1; + int pseudo_count = 0; + for (int i = 0; i < m; i++) + { +/* For odd weight edges, we directly add it + in our graph*/ + + if (info[i][2] % 2 == 1) + { + int u = info[i][0]; + int v = info[i][1]; + G[u].add(v); + G[v].add(u); + } +/* For even weight edges, we break it*/ + + else + { + int u = info[i][0]; + int v = info[i][1]; +/* Entering a pseudo node between u---v*/ + + G[u].add(pseudo); + G[pseudo].add(u); + G[v].add(pseudo); + G[pseudo].add(v); +/* Keeping a record of number of + pseudo nodes inserted*/ + + pseudo_count++; +/* Making a new pseudo node for next time*/ + + pseudo++; + } + } +/* We pass number graph G[][] and total number + of node = actual number of nodes + number of + pseudo nodes added.*/ + + return twoColor(G, n + pseudo_count); +} +/*Driver Code*/ + +public static void main(String[] args) +{ +/* 'n' correspond to number of nodes in our + graph while 'm' correspond to the number + of information about this graph.*/ + + int n = 4, m = 3; + int[][] info = { { 1, 2, 12 }, { 2, 3, 1 }, + { 4, 3, 1 }, { 4, 1, 20 } }; +/* This function break the even weighted edges in + two parts. Makes the adjacency representation + of the graph and sends it for two coloring.*/ + + if (isOddSum(info, n, m) == true) + System.out.println(""No""); + else + System.out.println(""Yes""); +} +}"," '''Python3 program to check if there +is a cycle of total odd weight ''' + + '''This function returns true if the current subpart +of the forest is two colorable, else false. ''' + +def twoColorUtil(G, src, N, colorArr): ''' Assign first color to source ''' + + colorArr[src] = 1 + ''' Create a queue (FIFO) of vertex numbers and + enqueue source vertex for BFS traversal ''' + + q = [src] + ''' Run while there are vertices in queue + (Similar to BFS) ''' + + while len(q) > 0: + u = q.pop(0) + ''' Find all non-colored adjacent vertices ''' + + for v in range(0, len(G[u])): + ''' An edge from u to v exists and + destination v is not colored ''' + + if colorArr[G[u][v]] == -1: + ''' Assign alternate color to this + adjacent v of u ''' + + colorArr[G[u][v]] = 1 - colorArr[u] + q.append(G[u][v]) + ''' An edge from u to v exists and destination + v is colored with same color as u ''' + + elif colorArr[G[u][v]] == colorArr[u]: + return False + return True + '''This function returns true if graph +G[V][V] is two colorable, else false ''' + +def twoColor(G, N): + ''' Create a color array to store colors assigned + to all veritces. Vertex number is used as index + in this array. The value '-1' of colorArr[i] + is used to indicate that no color is assigned + to vertex 'i'. The value 1 is used to indicate + first color is assigned and value 0 indicates + second color is assigned. ''' + + colorArr = [-1] * N + ''' As we are dealing with graph, the input might + come as a forest, thus start coloring from a + node and if true is returned we'll know that + we successfully colored the subpart of our + forest and we start coloring again from a new + uncolored node. This way we cover the entire forest. ''' + + for i in range(N): + if colorArr[i] == -1: + if twoColorUtil(G, i, N, colorArr) == False: + return False + return True + '''Returns false if an odd cycle is present else true +int info[][] is the information about our graph +int n is the number of nodes +int m is the number of informations given to us ''' + +def isOddSum(info, n, m): + ''' Declaring adjacency list of a graph + Here at max, we can encounter all the + edges with even weight thus there will + be 1 pseudo node for each edge ''' + + G = [[] for i in range(2*n)] + pseudo, pseudo_count = n+1, 0 + for i in range(0, m): + ''' For odd weight edges, we + directly add it in our graph ''' + + if info[i][2] % 2 == 1: + u, v = info[i][0], info[i][1] + G[u].append(v) + G[v].append(u) + ''' For even weight edges, we break it ''' + + else: + u, v = info[i][0], info[i][1] + ''' Entering a pseudo node between u---v ''' + + G[u].append(pseudo) + G[pseudo].append(u) + G[v].append(pseudo) + G[pseudo].append(v) + ''' Keeping a record of number + of pseudo nodes inserted ''' + + pseudo_count += 1 + ''' Making a new pseudo node for next time ''' + + pseudo += 1 + ''' We pass number graph G[][] and total number + of node = actual number of nodes + number of + pseudo nodes added. ''' + + return twoColor(G, n+pseudo_count) + '''Driver function ''' + +if __name__ == ""__main__"": + ''' 'n' correspond to number of nodes in our + graph while 'm' correspond to the number + of information about this graph. ''' + + n, m = 4, 3 + info = [[1, 2, 12], + [2, 3, 1], + [4, 3, 1], + [4, 1, 20]] + ''' This function break the even weighted edges in + two parts. Makes the adjacency representation + of the graph and sends it for two coloring. ''' + + if isOddSum(info, n, m) == True: + print(""No"") + else: + print(""Yes"")" +Double the first element and move zero to end,"/*Java implementation to rearrange the +array elements after modification*/ + +class GFG { +/* function which pushes all + zeros to end of an array.*/ + + static void pushZerosToEnd(int arr[], int n) + { +/* Count of non-zero elements*/ + + int count = 0; +/* Traverse the array. If element + encountered is non-zero, then + replace the element at index + 'count' with this element*/ + + for (int i = 0; i < n; i++) + if (arr[i] != 0) +/* here count is incremented*/ + + arr[count++] = arr[i]; +/* Now all non-zero elements + have been shifted to front and + 'count' is set as index of first 0. + Make all elements 0 from count to end.*/ + + while (count < n) + arr[count++] = 0; + } +/* function to rearrange the array + elements after modification*/ + + static void modifyAndRearrangeArr(int arr[], int n) + { +/* if 'arr[]' contains a single element + only*/ + + if (n == 1) + return; +/* traverse the array*/ + + for (int i = 0; i < n - 1; i++) { +/* if true, perform the required modification*/ + + if ((arr[i] != 0) && (arr[i] == arr[i + 1])) + { +/* double current index value*/ + + arr[i] = 2 * arr[i]; +/* put 0 in the next index*/ + + arr[i + 1] = 0; +/* increment by 1 so as to move two + indexes ahead during loop iteration*/ + + i++; + } + } +/* push all the zeros at + the end of 'arr[]'*/ + + pushZerosToEnd(arr, n); + } +/* function to print the array elements*/ + + static void printArray(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver program to test above*/ + + public static void main(String[] args) + { + int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; + int n = arr.length; + System.out.print(""Original array: ""); + printArray(arr, n); + modifyAndRearrangeArr(arr, n); + System.out.print(""Modified array: ""); + printArray(arr, n); + } +}"," '''Python3 implementation to rearrange +the array elements after modification + ''' '''function which pushes all zeros +to end of an array.''' + +def pushZerosToEnd(arr, n): + ''' Count of non-zero elements''' + + count = 0 + ''' Traverse the array. If element + encountered is non-zero, then + replace the element at index + 'count' with this element''' + + for i in range(0, n): + if arr[i] != 0: + ''' here count is incremented''' + + arr[count] = arr[i] + count+=1 + ''' Now all non-zero elements have been + shifted to front and 'count' is set + as index of first 0. Make all + elements 0 from count to end.''' + + while (count < n): + arr[count] = 0 + count+=1 + '''function to rearrange the array +elements after modification''' + +def modifyAndRearrangeArr(ar, n): + ''' if 'arr[]' contains a single + element only''' + + if n == 1: + return + ''' traverse the array''' + + for i in range(0, n - 1): + ''' if true, perform the required modification''' + + if (arr[i] != 0) and (arr[i] == arr[i + 1]): + ''' double current index value''' + + arr[i] = 2 * arr[i] + ''' put 0 in the next index''' + + arr[i + 1] = 0 + ''' increment by 1 so as to move two + indexes ahead during loop iteration''' + + i+=1 + ''' push all the zeros at the end of 'arr[]''' + ''' + pushZerosToEnd(arr, n) + '''function to print the array elements''' + +def printArray(arr, n): + for i in range(0, n): + print(arr[i],end="" "") + '''Driver program to test above''' + +arr = [ 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 ] +n = len(arr) +print(""Original array:"",end="" "") +printArray(arr, n) +modifyAndRearrangeArr(arr, n) +print(""\nModified array:"",end="" "") +printArray(arr, n)" +Segregate 0s and 1s in an array,"class Segregate +{ + /*Function to put all 0s on left and all 1s on right*/ + + void segregate0and1(int arr[], int size) + { + /* Initialize left and right indexes */ + + int left = 0, right = size - 1; + + while (left < right) + { + /* Increment left index while we see 0 at left */ + + while (arr[left] == 0 && left < right) + left++; + + /* Decrement right index while we see 1 at right */ + + while (arr[right] == 1 && left < right) + right--; + + /* If left is smaller than right then there is a 1 at left + and a 0 at right. Exchange arr[left] and arr[right]*/ + + if (left < right) + { + arr[left] = 0; + arr[right] = 1; + left++; + right--; + } + } + } + + /* Driver Program to test above functions */ + + public static void main(String[] args) + { + Segregate seg = new Segregate(); + int arr[] = new int[]{0, 1, 0, 1, 1, 1}; + int i, arr_size = arr.length; + + seg.segregate0and1(arr, arr_size); + + System.out.print(""Array after segregation is ""); + for (i = 0; i < 6; i++) + System.out.print(arr[i] + "" ""); + } +} +"," '''Python program to sort a binary array in one pass''' + + + '''Function to put all 0s on left and all 1s on right''' + +def segregate0and1(arr, size): + ''' Initialize left and right indexes''' + + left, right = 0, size-1 + + while left < right: + ''' Increment left index while we see 0 at left''' + + while arr[left] == 0 and left < right: + left += 1 + + ''' Decrement right index while we see 1 at right''' + + while arr[right] == 1 and left < right: + right -= 1 + + ''' If left is smaller than right then there is a 1 at left + and a 0 at right. Exchange arr[left] and arr[right]''' + + if left < right: + arr[left] = 0 + arr[right] = 1 + left += 1 + right -= 1 + + return arr + + '''driver program to test''' + +arr = [0, 1, 0, 1, 1, 1] +arr_size = len(arr) +print(""Array after segregation"") +print(segregate0and1(arr, arr_size)) + + +" +Space optimization using bit manipulations,"/*Java program to mark numbers as +multiple of 2 or 5*/ + +import java.lang.*; +class GFG { +/* Driver code*/ + + public static void main(String[] args) + { + int a = 2, b = 10; + int size = Math.abs(b - a) + 1; + int array[] = new int[size]; +/* Iterate through a to b, If + it is a multiple of 2 or 5 + Mark index in array as 1*/ + + for (int i = a; i <= b; i++) + if (i % 2 == 0 || i % 5 == 0) + array[i - a] = 1; + System.out.println(""MULTIPLES of 2"" + + "" and 5:""); + for (int i = a; i <= b; i++) + if (array[i - a] == 1) + System.out.printf(i + "" ""); + } +}"," '''Python3 program to mark numbers +as multiple of 2 or 5''' + +import math + '''Driver code''' + +a = 2 +b = 10 +size = abs(b - a) + 1 +array = [0] * size + '''Iterate through a to b, +If it is a multiple of 2 +or 5 Mark index in array as 1''' + +for i in range(a, b + 1): + if (i % 2 == 0 or i % 5 == 0): + array[i - a] = 1 +print(""MULTIPLES of 2 and 5:"") +for i in range(a, b + 1): + if (array[i - a] == 1): + print(i, end="" "")" +Find the minimum cost to reach destination using a train,"/*A Dynamic Programming based solution to find min cost +to reach station N-1 from station 0.*/ + +class shortest_path +{ + static int INF = Integer.MAX_VALUE,N = 4; +/* A recursive function to find the shortest path from + source 's' to destination 'd'. + This function returns the smallest possible cost to + reach station N-1 from station 0.*/ + + static int minCost(int cost[][]) + { +/* dist[i] stores minimum cost to reach station i + from station 0.*/ + + int dist[] = new int[N]; + for (int i=0; i dist[i] + cost[i][j]) + dist[j] = dist[i] + cost[i][j]; + return dist[N-1]; + } +/*Driver program to test above function*/ + + public static void main(String args[]) + { + int cost[][] = { {0, 15, 80, 90}, + {INF, 0, 40, 50}, + {INF, INF, 0, 70}, + {INF, INF, INF, 0} + }; + System.out.println(""The Minimum cost to reach station ""+ N+ + "" is ""+minCost(cost)); + } +}"," '''A Dynamic Programming based +solution to find min cost +to reach station N-1 +from station 0.''' + +INF = 2147483647 +N = 4 + '''This function returns the +smallest possible cost to +reach station N-1 from station 0.''' + +def minCost(cost): + ''' dist[i] stores minimum + cost to reach station i + from station 0.''' + + dist=[0 for i in range(N)] + for i in range(N): + dist[i] = INF + dist[0] = 0 + ''' Go through every station + and check if using it + as an intermediate station + gives better path''' + + for i in range(N): + for j in range(i+1,N): + if (dist[j] > dist[i] + cost[i][j]): + dist[j] = dist[i] + cost[i][j] + return dist[N-1] + '''Driver program to +test above function''' + +cost= [ [0, 15, 80, 90], + [INF, 0, 40, 50], + [INF, INF, 0, 70], + [INF, INF, INF, 0]] +print(""The Minimum cost to reach station "", + N,"" is "",minCost(cost))" +Noble integers in an array (count of greater elements is equal to value),"/*Java program to find Noble elements +in an array.*/ + +import java.util.Arrays; + +public class Main +{ +/* Returns a Noble integer if present, + else returns -1.*/ + + public static int nobleInteger(int arr[]) + { + Arrays.sort(arr); + +/* Return a Noble element if present + before last.*/ + + int n = arr.length; + for (int i=0; i= 0 + && s.charAt(i - longest[i - 1] - 1) == '(') + { + longest[i] + = longest[i - 1] + 2 + + ((i - longest[i - 1] - 2 >= 0) + ? longest[i - longest[i - 1] - 2] + : 0); + curMax = Math.max(longest[i], curMax); + } + } + return curMax; + } +/* Driver code*/ + + public static void main(String[] args) + { + String str = ""((()()""; +/* Function call*/ + + System.out.print(findMaxLen(str) +""\n""); + str = ""()(()))))""; +/* Function call*/ + + System.out.print(findMaxLen(str) +""\n""); + } +}"," '''Python3 program to find length of +the longest valid substring''' + +def findMaxLen(s): + if (len(s) <= 1): + return 0 + ''' Initialize curMax to zero''' + + curMax = 0 + longest = [0] * (len(s)) + ''' Iterate over the string starting + from second index''' + + for i in range(1, len(s)): + if ((s[i] == ')' + and i - longest[i - 1] - 1 >= 0 + and s[i - longest[i - 1] - 1] == '(')): + longest[i] = longest[i - 1] + 2 + if (i - longest[i - 1] - 2 >= 0): + longest[i] += (longest[i - + longest[i - 1] - 2]) + else: + longest[i] += 0 + curMax = max(longest[i], curMax) + return curMax + '''Driver Code''' + +if __name__ == '__main__': + Str = ""((()()"" + ''' Function call''' + + print(findMaxLen(Str)) + Str = ""()(()))))"" + ''' Function call''' + + print(findMaxLen(Str))" +Insert a node after the n-th node from the end,"/*Java implementation to insert a node after +the n-th node from the end*/ + +class GfG +{ + +/*structure of a node*/ + +static class Node +{ + int data; + Node next; +} + +/*function to get a new node*/ + +static Node getNode(int data) +{ +/* allocate memory for the node*/ + + Node newNode = new Node(); + +/* put in the data*/ + + newNode.data = data; + newNode.next = null; + return newNode; +} + +/*function to insert a node after the +nth node from the end*/ + +static void insertAfterNthNode(Node head, int n, int x) +{ +/* if list is empty*/ + + if (head == null) + return; + +/* get a new node for the value 'x'*/ + + Node newNode = getNode(x); + Node ptr = head; + int len = 0, i; + +/* find length of the list, i.e, the + number of nodes in the list*/ + + while (ptr != null) + { + len++; + ptr = ptr.next; + } + +/* traverse up to the nth node from the end*/ + + ptr = head; + for (i = 1; i <= (len - n); i++) + ptr = ptr.next; + +/* insert the 'newNode' by making the + necessary adjustment in the links*/ + + newNode.next = ptr.next; + ptr.next = newNode; +} + +/*function to print the list*/ + +static void printList(Node head) +{ + while (head != null) + { + System.out.print(head.data + "" ""); + head = head.next; + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ +/* Creating list 1->3->4->5*/ + + Node head = getNode(1); + head.next = getNode(3); + head.next.next = getNode(4); + head.next.next.next = getNode(5); + + int n = 4, x = 2; + + System.out.print(""Original Linked List: ""); + printList(head); + + insertAfterNthNode(head, n, x); + System.out.println(); + System.out.print(""Linked List After Insertion: ""); + printList(head); +} +} + + +"," '''Python implementation to insert a node after +the n-th node from the end''' + + + '''Linked List node''' + +class Node: + def __init__(self, data): + self.data = data + self.next = None + + '''function to get a new node''' + +def getNode(data) : + + ''' allocate memory for the node''' + + newNode = Node(0) + + ''' put in the data''' + + newNode.data = data + newNode.next = None + return newNode + + '''function to insert a node after the +nth node from the end''' + +def insertAfterNthNode(head, n, x) : + + ''' if list is empty''' + + if (head == None) : + return + + ''' get a new node for the value 'x''' + ''' + newNode = getNode(x) + ptr = head + len = 0 + i = 0 + + ''' find length of the list, i.e, the + number of nodes in the list''' + + while (ptr != None) : + + len = len + 1 + ptr = ptr.next + + ''' traverse up to the nth node from the end''' + + ptr = head + i = 1 + while ( i <= (len - n) ) : + ptr = ptr.next + i = i + 1 + + ''' insert the 'newNode' by making the + necessary adjustment in the links''' + + newNode.next = ptr.next + ptr.next = newNode + + '''function to print the list''' + +def printList( head) : + + while (head != None): + + print(head.data ,end = "" "") + head = head.next + + '''Driver code''' + + + '''Creating list 1->3->4->5''' + +head = getNode(1) +head.next = getNode(3) +head.next.next = getNode(4) +head.next.next.next = getNode(5) + +n = 4 +x = 2 + +print(""Original Linked List: "") +printList(head) + +insertAfterNthNode(head, n, x) +print() +print(""Linked List After Insertion: "") +printList(head) + + +" +Print all paths from a given source to a destination using BFS,"/*Java program to print all paths of source to +destination in given graph*/ + +import java.io.*; +import java.util.*; +class Graph{ +/*utility function for printing +the found path in graph*/ + +private static void printPath(List path) +{ + int size = path.size(); + for(Integer v : path) + { + System.out.print(v + "" ""); + } + System.out.println(); +} +/*Utility function to check if current +vertex is already present in path*/ + +private static boolean isNotVisited(int x, + List path) +{ + int size = path.size(); + for(int i = 0; i < size; i++) + if (path.get(i) == x) + return false; + return true; +} +/*Utility function for finding paths in graph +from source to destination*/ + +private static void findpaths(List > g, + int src, int dst, int v) +{ +/* Create a queue which stores + the paths*/ + + Queue > queue = new LinkedList<>(); +/* Path vector to store the current path*/ + + List path = new ArrayList<>(); + path.add(src); + queue.offer(path); + while (!queue.isEmpty()) + { + path = queue.poll(); + int last = path.get(path.size() - 1); +/* If last vertex is the desired destination + then print the path*/ + + if (last == dst) + { + printPath(path); + } +/* Traverse to all the nodes connected to + current vertex and push new path to queue*/ + + List lastNode = g.get(last); + for(int i = 0; i < lastNode.size(); i++) + { + if (isNotVisited(lastNode.get(i), path)) + { + List newpath = new ArrayList<>(path); + newpath.add(lastNode.get(i)); + queue.offer(newpath); + } + } + } +} +/*Driver code*/ + +public static void main(String[] args) +{ + List > g = new ArrayList<>(); + +/* number of vertices*/ + + int v = 4; + for(int i = 0; i < 4; i++) + { + g.add(new ArrayList<>()); + }/* Construct a graph*/ + + g.get(0).add(3); + g.get(0).add(1); + g.get(0).add(2); + g.get(1).add(3); + g.get(2).add(0); + g.get(2).add(1); + int src = 2, dst = 3; + System.out.println(""path from src "" + src + + "" to dst "" + dst + "" are ""); +/* Function for finding the paths */ + + findpaths(g, src, dst, v); +} +}"," '''Python3 program to print all paths of +source to destination in given graph''' + +from typing import List +from collections import deque + '''Utility function for printing +the found path in graph''' + +def printpath(path: List[int]) -> None: + size = len(path) + for i in range(size): + print(path[i], end = "" "") + print() + '''Utility function to check if current +vertex is already present in path''' + +def isNotVisited(x: int, path: List[int]) -> int: + size = len(path) + for i in range(size): + if (path[i] == x): + return 0 + return 1 + '''Utility function for finding paths in graph +from source to destination''' + +def findpaths(g: List[List[int]], src: int, + dst: int, v: int) -> None: + ''' Create a queue which stores + the paths''' + + q = deque() + ''' Path vector to store the current path''' + + path = [] + path.append(src) + q.append(path.copy()) + while q: + path = q.popleft() + last = path[len(path) - 1] + ''' If last vertex is the desired destination + then print the path''' + + if (last == dst): + printpath(path) + ''' Traverse to all the nodes connected to + current vertex and push new path to queue''' + + for i in range(len(g[last])): + if (isNotVisited(g[last][i], path)): + newpath = path.copy() + newpath.append(g[last][i]) + q.append(newpath) + '''Driver code''' + +if __name__ == ""__main__"": + ''' Number of vertices''' + + v = 4 + g = [[] for _ in range(4)] + ''' Construct a graph''' + + g[0].append(3) + g[0].append(1) + g[0].append(2) + g[1].append(3) + g[2].append(0) + g[2].append(1) + src = 2 + dst = 3 + print(""path from src {} to dst {} are"".format( + src, dst)) + ''' Function for finding the paths''' + + findpaths(g, src, dst, v)" +Find the smallest missing number,"class SmallestMissing +{ + +/*function that returns +smallest elements missing +in a sorted array.*/ + + int findFirstMissing(int array[], int start, int end) + { + if (start > end) + return end + 1; + if (start != array[start]) + return start; + int mid = (start + end) / 2;/* Left half has all elements from 0 to mid*/ + + if (array[mid] == mid) + return findFirstMissing(array, mid+1, end); + return findFirstMissing(array, start, mid); + } +/* Driver program to test the above function*/ + + public static void main(String[] args) + { + SmallestMissing small = new SmallestMissing(); + int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; + int n = arr.length; + System.out.println(""First Missing element is : "" + + small.findFirstMissing(arr, 0, n - 1)); + } +}"," '''Python3 program to find the smallest +elements missing in a sorted array.''' + + + '''function that returns +smallest elements missing +in a sorted array.''' + +def findFirstMissing(array, start, end): + if (start > end): + return end + 1 + if (start != array[start]): + return start; + mid = int((start + end) / 2) ''' Left half has all elements + from 0 to mid''' + + if (array[mid] == mid): + return findFirstMissing(array, + mid+1, end) + return findFirstMissing(array, + start, mid) + '''driver program to test above function''' + +arr = [0, 1, 2, 3, 4, 5, 6, 7, 10] +n = len(arr) +print(""Smallest missing element is"", + findFirstMissing(arr, 0, n-1))" +Largest number in BST which is less than or equal to N,"/*Java code to find the largest value smaller +than or equal to N*/ + +class GfG { + +/*Node structure*/ + +static class Node { + int key; + Node left, right; +}/*To create new BST Node*/ + +static Node newNode(int item) +{ + Node temp = new Node(); + temp.key = item; + temp.left = null; + temp.right = null; + return temp; +} +/*To insert a new node in BST*/ + +static Node insert(Node node, int key) +{ +/* if tree is empty return new node*/ + + if (node == null) + return newNode(key); +/* if key is less then or greater then + node value then recur down the tree*/ + + if (key < node.key) + node.left = insert(node.left, key); + else if (key > node.key) + node.right = insert(node.right, key); +/* return the (unchanged) node pointer*/ + + return node; +} +/*function to find max value less then N*/ + +static int findMaxforN(Node root, int N) +{ +/* Base cases*/ + + if (root == null) + return -1; + if (root.key == N) + return N; +/* If root's value is smaller, try in right + subtree*/ + + else if (root.key < N) { + int k = findMaxforN(root.right, N); + if (k == -1) + return root.key; + else + return k; + } +/* If root's key is greater, return value + from left subtree.*/ + + else if (root.key > N) + return findMaxforN(root.left, N); + return -1; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int N = 4; +/*creating following BST + 5 + / \ + 2 12 + / \ / \ + 1 3 9 21 + / \ + 19 25 */ + + Node root = null; + root = insert(root, 25); + insert(root, 2); + insert(root, 1); + insert(root, 3); + insert(root, 12); + insert(root, 9); + insert(root, 21); + insert(root, 19); + insert(root, 25); + System.out.println(findMaxforN(root, N)); +} +}"," '''Python3 code to find the largest +value smaller than or equal to N''' + + + ''' Constructor to create a new node''' +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None + '''To insert a new node in BST''' + +def insert(node, key): + ''' if tree is empty return new node''' + + if node == None: + return newNode(key) + ''' if key is less then or greater then + node value then recur down the tree''' + + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + ''' return the (unchanged) node pointer''' + + return node + '''function to find max value less then N''' + +def findMaxforN(root, N): + ''' Base cases''' + + if root == None: + return -1 + if root.key == N: + return N + ''' If root's value is smaller, try in + right subtree''' + + elif root.key < N: + k = findMaxforN(root.right, N) + if k == -1: + return root.key + else: + return k + ''' If root's key is greater, return + value from left subtree.''' + + elif root.key > N: + return findMaxforN(root.left, N) + '''Driver code''' + +if __name__ == '__main__': + N = 4 + ''' creating following BST + + 5 + / \ + 2 12 + / \ / \ + 1 3 9 21 + / \ + 19 25''' + + root = None + root = insert(root, 25) + insert(root, 2) + insert(root, 1) + insert(root, 3) + insert(root, 12) + insert(root, 9) + insert(root, 21) + insert(root, 19) + insert(root, 25) + print(findMaxforN(root, N))" +Trapping Rain Water,"/*Java program to find maximum amount of water that can +be trapped within given set of bars.*/ + + +class Test { + static int arr[] = new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + +/* Method for maximum amount of water*/ + + static int findWater(int n) + { +/* left[i] contains height of tallest bar to the + left of i'th bar including itself*/ + + int left[] = new int[n]; + +/* Right [i] contains height of tallest bar to + the right of ith bar including itself*/ + + int right[] = new int[n]; + +/* Initialize result*/ + + int water = 0; + +/* Fill left array*/ + + left[0] = arr[0]; + for (int i = 1; i < n; i++) + left[i] = Math.max(left[i - 1], arr[i]); + +/* Fill right array*/ + + right[n - 1] = arr[n - 1]; + for (int i = n - 2; i >= 0; i--) + right[i] = Math.max(right[i + 1], arr[i]); + +/* Calculate the accumulated water element by element + consider the amount of water on i'th bar, the + amount of water accumulated on this particular + bar will be equal to min(left[i], right[i]) - arr[i] .*/ + + for (int i = 0; i < n; i++) + water += Math.min(left[i], right[i]) - arr[i]; + + return water; + } + +/* Driver method to test the above function*/ + + public static void main(String[] args) + { + + System.out.println(""Maximum water that can be accumulated is "" + findWater(arr.length)); + } +} +"," '''Python program to find maximum amount of water that can +be trapped within given set of bars.''' + + +def findWater(arr, n): + + ''' left[i] contains height of tallest bar to the + left of i'th bar including itself''' + + left = [0]*n + + ''' Right [i] contains height of tallest bar to + the right of ith bar including itself''' + + right = [0]*n + + ''' Initialize result''' + + water = 0 + + ''' Fill left array''' + + left[0] = arr[0] + for i in range( 1, n): + left[i] = max(left[i-1], arr[i]) + + ''' Fill right array''' + + right[n-1] = arr[n-1] + for i in range(n-2, -1, -1): + right[i] = max(right[i + 1], arr[i]); + + ''' Calculate the accumulated water element by element + consider the amount of water on i'th bar, the + amount of water accumulated on this particular + bar will be equal to min(left[i], right[i]) - arr[i] .''' + + for i in range(0, n): + water += min(left[i], right[i]) - arr[i] + + return water + + + '''Driver program''' + + +arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] +n = len(arr) +print(""Maximum water that can be accumulated is"", findWater(arr, n)) + + +" +Implementation of Deque using doubly linked list,"/*Java implementation of Deque using +doubly linked list*/ + +import java.util.*; +class GFG +{ +/* Node of a doubly linked list*/ + + static class Node + { + int data; + Node prev, next; +/* Function to get a new node*/ + + static Node getnode(int data) + { + Node newNode = new Node(); + newNode.data = data; + newNode.prev = newNode.next = null; + return newNode; + } + }; +/* A structure to represent a deque*/ + + static class Deque { + Node front; + Node rear; + int Size; + Deque() + { + front = rear = null; + Size = 0; + } +/* Function to check whether deque + is empty or not*/ + + boolean isEmpty() { return (front == null); } +/* Function to return the number of + elements in the deque*/ + + int size() { return Size; } +/* Function to insert an element + at the front end*/ + + void insertFront(int data) + { + Node newNode = Node.getnode(data); +/* If true then new element cannot be added + and it is an 'Overflow' condition*/ + + if (newNode == null) + System.out.print(""OverFlow\n""); + else { +/* If deque is empty*/ + + if (front == null) + rear = front = newNode; +/* Inserts node at the front end*/ + + else { + newNode.next = front; + front.prev = newNode; + front = newNode; + } +/* Increments count of elements by 1*/ + + Size++; + } + } +/* Function to insert an element + at the rear end*/ + + void insertRear(int data) + { + Node newNode = Node.getnode(data); +/* If true then new element cannot be added + and it is an 'Overflow' condition*/ + + if (newNode == null) + System.out.print(""OverFlow\n""); + else { +/* If deque is empty*/ + + if (rear == null) + front = rear = newNode; +/* Inserts node at the rear end*/ + + else { + newNode.prev = rear; + rear.next = newNode; + rear = newNode; + } + Size++; + } + } +/* Function to delete the element + from the front end*/ + + void deleteFront() + { +/* If deque is empty then + 'Underflow' condition*/ + + if (isEmpty()) + System.out.print(""UnderFlow\n""); +/* Deletes the node from the front end and makes + the adjustment in the links*/ + + else { + Node temp = front; + front = front.next; +/* If only one element was present*/ + + if (front == null) + rear = null; + else + front.prev = null; +/* Decrements count of elements by 1*/ + + Size--; + } + } +/* Function to delete the element + from the rear end*/ + + void deleteRear() + { +/* If deque is empty then + 'Underflow' condition*/ + + if (isEmpty()) + System.out.print(""UnderFlow\n""); +/* Deletes the node from the rear end and makes + the adjustment in the links*/ + + else { + Node temp = rear; + rear = rear.prev; +/* If only one element was present*/ + + if (rear == null) + front = null; + else + rear.next = null; +/* Decrements count of elements by 1*/ + + Size--; + } + } +/* Function to return the element + at the front end*/ + + int getFront() + { +/* If deque is empty, then returns + garbage value*/ + + if (isEmpty()) + return -1; + return front.data; + } +/* Function to return the element + at the rear end*/ + + int getRear() + { +/* If deque is empty, then returns + garbage value*/ + + if (isEmpty()) + return -1; + return rear.data; + } +/* Function to delete all the elements + from Deque*/ + + void erase() + { + rear = null; + while (front != null) { + Node temp = front; + front = front.next; + } + Size = 0; + } + } +/* Driver program to test above*/ + + public static void main(String[] args) + { + Deque dq = new Deque(); + System.out.print( + ""Insert element '5' at rear end\n""); + dq.insertRear(5); + System.out.print( + ""Insert element '10' at rear end\n""); + dq.insertRear(10); + System.out.print(""Rear end element: "" + dq.getRear() + + ""\n""); + dq.deleteRear(); + System.out.print( + ""After deleting rear element new rear"" + + "" is: "" + dq.getRear() + ""\n""); + System.out.print( + ""Inserting element '15' at front end \n""); + dq.insertFront(15); + System.out.print( + ""Front end element: "" + dq.getFront() + ""\n""); + System.out.print(""Number of elements in Deque: "" + + dq.size() + ""\n""); + dq.deleteFront(); + System.out.print(""After deleting front element new "" + + ""front is: "" + dq.getFront() + + ""\n""); + } +}", +Add 1 to a given number,"/*Java code to Add 1 to a given number*/ + +class GFG +{ + static int addOne(int x) + { + return (-(~x)); + } +/* Driver program*/ + + public static void main(String[] args) + { + System.out.printf(""%d"", addOne(13)); + } +}"," '''Python3 code to add 1 to a given number''' + +def addOne(x): + return (-(~x)); + '''Driver program''' + +print(addOne(13))" +Fibonacci Cube Graph,"/*java code to find vertices in a fibonacci +cube graph of order n*/ + +public class GFG { +/* function to find fibonacci number*/ + + static int fib(int n) + { + if (n <= 1) + return n; + return fib(n - 1) + fib(n - 2); + } +/* function for finding number of vertices + in fibonacci cube graph*/ + + static int findVertices (int n) + { +/* return fibonacci number for f(n + 2)*/ + + return fib(n + 2); + } + public static void main(String args[]) { +/*Driver code*/ + + int n = 3; + System.out.println(findVertices(n)); + } +}"," '''Python3 code to find vertices in +a fibonacci cube graph of order n''' + + '''Function to find fibonacci number''' + +def fib(n): + if n <= 1: + return n + return fib(n - 1) + fib(n - 2) '''Function for finding number of +vertices in fibonacci cube graph''' + +def findVertices(n): + ''' return fibonacci number + for f(n + 2)''' + + return fib(n + 2) + '''Driver Code''' + +if __name__ == ""__main__"": + n = 3 + print(findVertices(n))" +Write a function that counts the number of times a given int occurs in a Linked List,"/*method can be used to avoid +Global variable 'frequency'*/ + +/* Counts the no. of occurrences of a node +(search_for) in a linked list (head)*/ + +int count(Node head, int key) +{ + if (head == null) + return 0; + if (head.data == key) + return 1 + count(head.next, key); + return count(head.next, key); +}"," '''method can be used to avoid +Global variable frequency''' + ''' Counts the no. of occurrences of a node +(search_for) in a linked list (head)''' +def count(self, temp, key): + if temp is None: + return 0 + if temp.data == key: + return 1 + count(temp.next, key) + return count(temp.next, key) +" +Check if a string can be formed from another string by at most X circular clockwise shifts,"/*Java implementation to check +that a given string can be +converted to another string +by circular clockwise shift +of each character by atmost +X times*/ + +import java.io.*; +import java.util.*; + +class GFG{ + +/*Function to check that all +characters of s1 can be +converted to s2 by circular +clockwise shift atmost X times*/ + +static void isConversionPossible(String s1, + String s2, + int x) +{ + int diff = 0, n; + n = s1.length(); + +/* Check for all characters of + the strings whether the + difference between their + ascii values is less than + X or not*/ + + for(int i = 0; i < n; i++) + { + +/* If both the characters + are same*/ + + if (s1.charAt(i) == s2.charAt(i)) + continue; + +/* Calculate the difference + between the ASCII values + of the characters*/ + + diff = ((int)(s2.charAt(i) - + s1.charAt(i)) + 26) % 26; + +/* If difference exceeds X*/ + + if (diff > x) + { + System.out.println(""NO""); + return; + } + } + System.out.println(""YES""); +} + +/*Driver Code*/ + +public static void main (String[] args) +{ + String s1 = ""you""; + String s2 = ""ara""; + + int x = 6; + +/* Function call*/ + + isConversionPossible(s1, s2, x); +} +} + + +"," '''Python3 implementation to check +that the given string can be +converted to another string +by circular clockwise shift''' + + + '''Function to check that the +string s1 can be converted +to s2 by clockwise circular +shift of all characters of +str1 atmost X times''' + +def isConversionPossible(s1, s2, x): + n = len(s1) + s1 = list(s1) + s2 = list(s2) + + + '''Check for all characters of + the strings whether the + difference between their + ascii values is less than + X or not''' + for i in range(n): + + ''' If both characters + are the same''' + + diff = ord(s2[i]) - ord(s1[i]) + if diff == 0: + continue + + ''' Condition to check if the + difference less than 0 then + find the circular shift by + adding 26 to it''' + + if diff < 0: + diff = diff + 26 + ''' If difference between + their ASCII values + exceeds X''' + + if diff > x: + return False + + return True + + + '''Driver Code''' + +if __name__ == ""__main__"": + s1 = ""you"" + s2 = ""ara"" + x = 6 + + ''' Function Call''' + + result = isConversionPossible(s1, s2, x) + + if result: + print(""YES"") + else: + print(""NO"") +" +Minimum sum of two numbers formed from digits of an array,"/*Java program to find minimum sum of two numbers +formed from all digits in a given array.*/ +import java.util.Arrays; +public class AQRQ {/* Returns sum of two numbers formed + from all digits in a[]*/ + + static int minSum(int a[], int n){ +/* sort the elements*/ + + Arrays.sort(a); + int num1 = 0; + int num2 = 0; + for(int i = 0;inextRight will be NULL if p is the right most child + at its level*/ + + if (p.right != null) + p.right.nextRight = (p.nextRight != null) ? p.nextRight.left : null; +/* Set nextRight for other nodes in pre order fashion*/ + + connectRecur(p.left); + connectRecur(p.right); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* Constructed binary tree is + 10 + / \ + 8 2 + / + 3 + */ + + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(2); + tree.root.left.left = new Node(3); +/* Populates nextRight pointer in all nodes*/ + + tree.connect(tree.root); +/* Let us check the values of nextRight pointers*/ + + System.out.println(""Following are populated nextRight pointers in "" + + ""the tree"" + + ""(-1 is printed if there is no nextRight)""); + int a = tree.root.nextRight != null ? tree.root.nextRight.data : -1; + System.out.println(""nextRight of "" + tree.root.data + "" is "" + + a); + int b = tree.root.left.nextRight != null ? tree.root.left.nextRight.data : -1; + System.out.println(""nextRight of "" + tree.root.left.data + "" is "" + + b); + int c = tree.root.right.nextRight != null ? tree.root.right.nextRight.data : -1; + System.out.println(""nextRight of "" + tree.root.right.data + "" is "" + + c); + int d = tree.root.left.left.nextRight != null ? tree.root.left.left.nextRight.data : -1; + System.out.println(""nextRight of "" + tree.root.left.left.data + "" is "" + + d); + } +}"," '''Python3 program to connect nodes at same +level using extended pre-order traversal ''' + + + '''A binary tree node''' + +class newnode: + def __init__(self, data): + self.data = data + self.left = self.right = self.nextRight = None '''Sets the nextRight of root and calls +connectRecur() for other nodes ''' + +def connect (p): + ''' Set the nextRight for root ''' + + p.nextRight = None + ''' Set the next right for rest of + the nodes (other than root) ''' + + connectRecur(p) + '''Set next right of all descendents of p. +Assumption: p is a compete binary tree ''' + +def connectRecur(p): + ''' Base case ''' + + if (not p): + return + ''' Set the nextRight pointer for p's + left child ''' + + if (p.left): + p.left.nextRight = p.right + ''' Set the nextRight pointer for p's right + child p.nextRight will be None if p is + the right most child at its level ''' + + if (p.right): + if p.nextRight: + p.right.nextRight = p.nextRight.left + else: + p.right.nextRight = None + ''' Set nextRight for other nodes in + pre order fashion ''' + + connectRecur(p.left) + connectRecur(p.right) + '''Driver Code''' + +if __name__ == '__main__': + ''' Constructed binary tree is + 10 + / \ + 8 2 + / + 3 ''' + + root = newnode(10) + root.left = newnode(8) + root.right = newnode(2) + root.left.left = newnode(3) + ''' Populates nextRight pointer in all nodes ''' + + connect(root) + ''' Let us check the values of nextRight pointers ''' + + print(""Following are populated nextRight"", + ""pointers in the tree (-1 is printed"", + ""if there is no nextRight)"") + print(""nextRight of"", root.data, ""is "", end = """") + if root.nextRight: + print(root.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.data, ""is "", end = """") + if root.left.nextRight: + print(root.left.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.right.data, ""is "", end = """") + if root.right.nextRight: + print(root.right.nextRight.data) + else: + print(-1) + print(""nextRight of"", root.left.left.data, ""is "", end = """") + if root.left.left.nextRight: + print(root.left.left.nextRight.data) + else: + print(-1)" +Find the element that appears once,"/*Java code to find the element +that occur only once*/ + +class GFG { +/* Method to find the element that occur only once*/ + + static int getSingle(int arr[], int n) + { + int ones = 0, twos = 0; + int common_bit_mask; + for (int i = 0; i < n; i++) { + /*""one & arr[i]"" gives the bits that are there in + both 'ones' and new element from arr[]. We + add these bits to 'twos' using bitwise OR*/ + + twos = twos | (ones & arr[i]); + /*""one & arr[i]"" gives the bits that are + there in both 'ones' and new element from arr[]. + We add these bits to 'twos' using bitwise OR*/ + + ones = ones ^ arr[i]; + /* The common bits are those bits which appear third time + So these bits should not be there in both 'ones' and 'twos'. + common_bit_mask contains all these bits as 0, so that the bits can + be removed from 'ones' and 'twos'*/ + + common_bit_mask = ~(ones & twos); + /*Remove common bits (the bits that appear third time) from 'ones'*/ + + ones &= common_bit_mask; + /*Remove common bits (the bits that appear third time) from 'twos'*/ + + twos &= common_bit_mask; + } + return ones; + } +/* Driver method*/ + + public static void main(String args[]) + { + int arr[] = { 3, 3, 2, 3 }; + int n = arr.length; + System.out.println(""The element with single occurrence is "" + getSingle(arr, n)); + } +}"," '''Python3 code to find the element that +appears once''' + + ''' Method to find the element that occur only once''' + +def getSingle(arr, n): + ones = 0 + twos = 0 + for i in range(n): + ''' one & arr[i]"" gives the bits that + are there in both 'ones' and new + element from arr[]. We add these + bits to 'twos' using bitwise OR''' + + twos = twos | (ones & arr[i]) + ''' one & arr[i]"" gives the bits that + are there in both 'ones' and new + element from arr[]. We add these + bits to 'twos' using bitwise OR''' + + ones = ones ^ arr[i] + ''' The common bits are those bits + which appear third time. So these + bits should not be there in both + 'ones' and 'twos'. common_bit_mask + contains all these bits as 0, so + that the bits can be removed from + 'ones' and 'twos''' + ''' + common_bit_mask = ~(ones & twos) + ''' Remove common bits (the bits that + appear third time) from 'ones''' + ''' + ones &= common_bit_mask + ''' Remove common bits (the bits that + appear third time) from 'twos''' + ''' + twos &= common_bit_mask + return ones + '''driver code''' + +arr = [3, 3, 2, 3] +n = len(arr) +print(""The element with single occurrence is "", + getSingle(arr, n))" +Squareroot(n)-th node in a Linked List,"/*Java program to find sqrt(n)'th node +of a linked list */ + +class GfG +{ +/*Linked list node */ + +static class Node +{ + int data; + Node next; +} +static Node head = null; +/*Function to get the sqrt(n)th +node of a linked list */ + +static int printsqrtn(Node head) +{ + Node sqrtn = null; + int i = 1, j = 1; +/* Traverse the list */ + + while (head != null) + { +/* check if j = sqrt(i) */ + + if (i == j * j) + { +/* for first node */ + + if (sqrtn == null) + sqrtn = head; + else + sqrtn = sqrtn.next; +/* increment j if j = sqrt(i) */ + + j++; + } + i++; + head=head.next; + } +/* return node's data */ + + return sqrtn.data; +} +static void print(Node head) +{ + while (head != null) + { + System.out.print( head.data + "" ""); + head = head.next; + } + System.out.println(); +} +/*function to add a new node at the +beginning of the list */ + +static void push( int new_data) +{ +/* allocate node */ + + Node new_node = new Node(); +/* put in the data */ + + new_node.data = new_data; +/* link the old list off the new node */ + + new_node.next = head; +/* move the head to point to the new node */ + + head = new_node; +} +/* Driver code*/ + +public static void main(String[] args) +{ + /* Start with the empty list */ + + push( 40); + push( 30); + push( 20); + push( 10); + System.out.print(""Given linked list is:""); + print(head); + System.out.print(""sqrt(n)th node is "" + + printsqrtn(head)); +} +}"," '''Python3 program to find sqrt(n)'th node +of a linked list +Node class ''' + +class Node: + ''' Function to initialise the node object ''' + + def __init__(self, data): + self.data = data + self.next = None + '''Function to get the sqrt(n)th +node of a linked list ''' + +def printsqrtn(head) : + sqrtn = None + i = 1 + j = 1 + ''' Traverse the list ''' + + while (head != None) : + ''' check if j = sqrt(i) ''' + + if (i == j * j) : + ''' for first node ''' + + if (sqrtn == None) : + sqrtn = head + else: + sqrtn = sqrtn.next + ''' increment j if j = sqrt(i) ''' + + j = j + 1 + i = i + 1 + head = head.next + ''' return node's data ''' + + return sqrtn.data +def print_1(head) : + while (head != None) : + print( head.data, end = "" "") + head = head.next + print("" "") + '''function to add a new node at the +beginning of the list ''' + +def push(head_ref, new_data) : + ''' allocate node ''' + + new_node = Node(0) + ''' put in the data ''' + + new_node.data = new_data + ''' link the old list off the new node ''' + + new_node.next = (head_ref) + ''' move the head to point to the new node ''' + + (head_ref) = new_node + return head_ref + '''Driver Code ''' + +if __name__=='__main__': + ''' Start with the empty list ''' + + head = None + head = push(head, 40) + head = push(head, 30) + head = push(head, 20) + head = push(head, 10) + print(""Given linked list is:"") + print_1(head) + print(""sqrt(n)th node is "", + printsqrtn(head))" +Program to find parity,"/*Java program to find parity +of an integer*/ + +import java.util.*; +import java.lang.*; +import java.io.*; +import java.math.BigInteger; +class GFG + { + /* Function to get parity of number n. + It returns 1 if n has odd parity, and + returns 0 if n has even parity */ + + static boolean getParity(int n) + { + boolean parity = false; + while(n != 0) + { + parity = !parity; + n = n & (n-1); + } + return parity; + } + /* Driver program to test getParity() */ + + public static void main (String[] args) + { + int n = 12; + System.out.println(""Parity of no "" + n + "" = "" + + (getParity(n)? ""odd"": ""even"")); + } +}"," '''Python3 code to get parity. + ''' '''Function to get parity of number n. +It returns 1 if n has odd parity, +and returns 0 if n has even parity''' + +def getParity( n ): + parity = 0 + while n: + parity = ~parity + n = n & (n - 1) + return parity + '''Driver program to test getParity()''' + +n = 7 +print (""Parity of no "", n,"" = "", + ( ""odd"" if getParity(n) else ""even""))" +Splitting starting N nodes into new Circular Linked List while preserving the old nodes,"/*Java implementation of the approach*/ + +public class CircularLinkedList { + + Node last; + + static class Node { + int data; + Node next; + }; + +/* Function to add a node to the empty list*/ + + public Node addToEmpty(int data) + { +/* If not empty*/ + + if (this.last != null) + return this.last; + +/* Creating a node dynamically*/ + + Node temp = new Node(); + +/* Assigning the data*/ + + temp.data = data; + this.last = temp; + +/* Creating the link*/ + + this.last.next = this.last; + + return last; + } + +/* Function to add a node to the + beginning of the list*/ + + public Node addBegin(int data) + { + +/* If list is empty*/ + + if (last == null) + return addToEmpty(data); + +/* Create node*/ + + Node temp = new Node(); + +/* Assign data*/ + + temp.data = data; + temp.next = this.last.next; + this.last.next = temp; + + return this.last; + } + +/* Function to traverse and print the list*/ + + public void traverse() + { + Node p; + +/* If list is empty*/ + + if (this.last == null) { + System.out.println(""List is empty.""); + return; + } + +/* Pointing to the first Node of the list*/ + + p = this.last.next; + +/* Traversing the list*/ + + do { + System.out.print(p.data + "" ""); + p = p.next; + } while (p != this.last.next); + + System.out.println(""""); + } + +/* Function to find the length of the CircularLinkedList*/ + + public int length() + { +/* Stores the length*/ + + int x = 0; + +/* List is empty*/ + + if (this.last == null) + return x; + +/* Iterator Node to traverse the List*/ + + Node itr = this.last.next; + while (itr.next != this.last.next) { + x++; + itr = itr.next; + } + +/* Return the length of the list*/ + + return (x + 1); + } + +/* Function to split the first k nodes into + a new CircularLinkedList and the remaining + nodes stay in the original CircularLinkedList*/ + + public Node split(int k) + { + +/* Empty Node for reference*/ + + Node pass = new Node(); + +/* Check if the list is empty + If yes, then return null*/ + + if (this.last == null) + return this.last; + +/* NewLast will contain the last node of + the new split list + itr to iterate the node till + the required node*/ + + Node newLast, itr = this.last; + for (int i = 0; i < k; i++) { + itr = itr.next; + } + +/* Update NewLast to the required node and + link the last to the start of rest of the list*/ + + newLast = itr; + pass.next = itr.next; + newLast.next = this.last.next; + this.last.next = pass.next; + +/* Return the last node of the required list*/ + + return newLast; + } + +/* Driver code*/ + + public static void main(String[] args) + { + CircularLinkedList clist = new CircularLinkedList(); + clist.last = null; + + clist.addToEmpty(12); + clist.addBegin(10); + clist.addBegin(8); + clist.addBegin(6); + clist.addBegin(4); + clist.addBegin(2); + System.out.println(""Original list:""); + clist.traverse(); + + int k = 4; + +/* Create a new list for the starting k nodes*/ + + CircularLinkedList clist2 = new CircularLinkedList(); + +/* Append the new last node into the new list*/ + + clist2.last = clist.split(k); + +/* Print the new lists*/ + + System.out.println(""The new lists are:""); + clist2.traverse(); + clist.traverse(); + } +} +"," '''Python3 implementation of the approach''' + + +class Node: + + def __init__(self, x): + + self.data = x + self.next = None + '''Function to add a node to the empty list''' + +def addToEmpty(last, data): + + ''' If not empty''' + + if (last != None): + return last + + ''' Assigning the data''' + + temp = Node(data) + last = temp + + ''' Creating the link''' + + last.next = last + + return last + + '''Function to add a node to the +beginning of the list''' + +def addBegin(last, data): + + ''' If list is empty''' + + if (last == None): + return addToEmpty(data) + + ''' Assign data''' + + + temp = Node(data) + temp.next = last.next + last.next = temp + + return last + '''Function to traverse and prthe list''' + +def traverse(last): + + ''' If list is empty''' + + if (last == None): + print(""List is empty."") + return + + ''' Pointing to the first Node of the list''' + + p = last.next + + ''' Traversing the list''' + + while True: + print(p.data, end = "" "") + p = p.next + + if p == last.next: + break + + print() + + '''Function to find the length of +the CircularLinkedList''' + +def length(last): + + ''' Stores the length''' + + x = 0 + + ''' List is empty''' + + if (last == None): + return x + + ''' Iterator Node to traverse the List''' + + itr = last.next + while (itr.next != last.next): + x += 1 + itr = itr.next + + ''' Return the length of the list''' + + return (x + 1) + + '''Function to split the first k nodes into +a new CircularLinkedList and the remaining +nodes stay in the original CircularLinkedList''' + +def split(last, k): + + ''' Empty Node for reference''' + + passs = Node(-1) + + ''' Check if the list is empty + If yes, then return NULL''' + + if (last == None): + return last + + ''' NewLast will contain the last node of + the new split list itr to iterate the + node till the required node''' + + itr = last + for i in range(k): + itr = itr.next + + ''' Update NewLast to the required node + and link the last to the start of + rest of the list''' + + newLast = itr + passs.next = itr.next + newLast.next = last.next + last.next = passs.next + + ''' Return the last node of the + required list''' + + return newLast + + '''Driver code''' + +if __name__ == '__main__': + + clist = None + + clist = addToEmpty(clist, 12) + clist = addBegin(clist, 10) + clist = addBegin(clist, 8) + clist = addBegin(clist, 6) + clist = addBegin(clist, 4) + clist = addBegin(clist, 2) + + print(""Original list:"", end = """") + traverse(clist) + + k = 4 + + ''' Append the new last node + into the new list''' + + clist2 = split(clist, k) + + ''' Print the new lists''' + + print(""The new lists are:"", end = """") + traverse(clist2) + traverse(clist) + + +" +Count subarrays where second highest lie before highest,"/*Java program to count number of distinct instance +where second highest number lie +before highest number in all subarrays.*/ + +import java.util.*; +class GFG +{ +static int MAXN = 100005; + +/*Pair class*/ + +static class pair +{ + int first, second; + public pair(int first, int second) + { + this.first = first; + this.second = second; + } +}/*Finding the next greater element of the array.*/ + +static void makeNext(int arr[], int n, int nextBig[]) +{ + Stack s = new Stack<>(); + for (int i = n - 1; i >= 0; i--) + { + nextBig[i] = i; + while (!s.empty() && s.peek().first < arr[i]) + s.pop(); + if (!s.empty()) + nextBig[i] = s.peek().second; + s.push(new pair(arr[i], i)); + } +} +/*Finding the previous greater element of the array.*/ + +static void makePrev(int arr[], int n, int prevBig[]) +{ + Stack s = new Stack<>(); + for (int i = 0; i < n; i++) + { + prevBig[i] = -1; + while (!s.empty() && s.peek().first < arr[i]) + s.pop(); + if (!s.empty()) + prevBig[i] = s.peek().second; + s.push(new pair(arr[i], i)); + } +} +/*Wrapper Function*/ + +static int wrapper(int arr[], int n) +{ + int []nextBig = new int[MAXN]; + int []prevBig = new int[MAXN]; + int []maxi = new int[MAXN]; + int ans = 0; +/* Finding previous largest element*/ + + makePrev(arr, n, prevBig); +/* Finding next largest element*/ + + makeNext(arr, n, nextBig); + for (int i = 0; i < n; i++) + if (nextBig[i] != i) + maxi[nextBig[i] - i] = Math.max(maxi[nextBig[i] - i], + i - prevBig[i]); + for (int i = 0; i < n; i++) + ans += maxi[i]; + return ans; +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = { 1, 3, 2, 4 }; + int n = arr.length; + System.out.println(wrapper(arr, n)); + } +}"," '''Python3 program to count number of distinct +instance where second highest number lie +before highest number in all subarrays.''' + +from typing import List +MAXN = 100005 + '''Finding the next greater element +of the array.''' + +def makeNext(arr: List[int], n: int, + nextBig: List[int]) -> None: + s = [] + for i in range(n - 1, -1, -1): + nextBig[i] = i + while len(s) and s[-1][0] < arr[i]: + s.pop() + if len(s): + nextBig[i] = s[-1][1] + s.append((arr[i], i)) '''Finding the previous greater +element of the array.''' + +def makePrev(arr: List[int], n: int, + prevBig: List[int]) -> None: + s = [] + for i in range(n): + prevBig[i] = -1 + while (len(s) and s[-1][0] < arr[i]): + s.pop() + if (len(s)): + prevBig[i] = s[-1][1] + s.append((arr[i], i)) '''Wrapper Function''' + +def wrapper(arr: List[int], n: int) -> int: + nextBig = [0] * MAXN + prevBig = [0] * MAXN + maxi = [0] * MAXN + ans = 0 + ''' Finding previous largest element''' + + makePrev(arr, n, prevBig) + ''' Finding next largest element''' + + makeNext(arr, n, nextBig) + for i in range(n): + if (nextBig[i] != i): + maxi[nextBig[i] - i] = max( + maxi[nextBig[i] - i], + i - prevBig[i]) + for i in range(n): + ans += maxi[i] + return ans + '''Driver Code''' + +if __name__ == ""__main__"": + arr = [ 1, 3, 2, 4 ] + n = len(arr) + print(wrapper(arr, n))" +Check if a binary tree is sorted level-wise or not,"/*Java program to determine whether +binary tree is level sorted or not. */ + +import java.util.*; +class GfG { +/*Structure of a tree node. */ + +static class Node { + int key; + Node left, right; +} +/*Function to create new tree node. */ + +static Node newNode(int key) +{ + Node temp = new Node(); + temp.key = key; + temp.left = null; + temp.right = null; + return temp; +} +/*Function to determine if +given binary tree is level sorted +or not. */ + +static int isSorted(Node root) +{ +/* to store maximum value of previous + level. */ + + int prevMax = Integer.MIN_VALUE; +/* to store minimum value of current + level. */ + + int minval; +/* to store maximum value of current + level. */ + + int maxval; +/* to store number of nodes in current + level. */ + + int levelSize; +/* queue to perform level order traversal. */ + + Queue q = new LinkedList (); + q.add(root); + while (!q.isEmpty()) { +/* find number of nodes in current + level. */ + + levelSize = q.size(); + minval = Integer.MAX_VALUE; + maxval = Integer.MIN_VALUE; +/* traverse current level and find + minimum and maximum value of + this level. */ + + while (levelSize > 0) { + root = q.peek(); + q.remove(); + levelSize--; + minval = Math.min(minval, root.key); + maxval = Math.max(maxval, root.key); + if (root.left != null) + q.add(root.left); + if (root.right != null) + q.add(root.right); + } +/* if minimum value of this level + is not greater than maximum + value of previous level then + given tree is not level sorted. */ + + if (minval <= prevMax) + return 0; +/* maximum value of this level is + previous maximum value for + next level. */ + + prevMax = maxval; + } + return 1; +} +/*Driver program */ + +public static void main(String[] args) +{ + /* + 1 + / + 4 + \ + 6 + / \ + 8 9 + / \ + 12 10 + */ + + Node root = newNode(1); + root.left = newNode(4); + root.left.right = newNode(6); + root.left.right.left = newNode(8); + root.left.right.right = newNode(9); + root.left.right.left.left = newNode(12); + root.left.right.right.right = newNode(10); + if (isSorted(root) == 1) + System.out.println(""Sorted""); + else + System.out.println(""Not sorted""); +} +}"," '''Python3 program to determine whether +binary tree is level sorted or not. ''' + +from queue import Queue + '''Function to create new tree node. ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + '''Function to determine if given binary +tree is level sorted or not. ''' + +def isSorted(root): + ''' to store maximum value of previous + level. ''' + + prevMax = -999999999999 + ''' to store minimum value of current + level. ''' + + minval = None + ''' to store maximum value of current + level. ''' + + maxval = None + ''' to store number of nodes in current + level. ''' + + levelSize = None + ''' queue to perform level order traversal. ''' + + q = Queue() + q.put(root) + while (not q.empty()): + ''' find number of nodes in current + level. ''' + + levelSize = q.qsize() + minval = 999999999999 + maxval = -999999999999 + ''' traverse current level and find + minimum and maximum value of + this level. ''' + + while (levelSize > 0): + root = q.queue[0] + q.get() + levelSize -= 1 + minval = min(minval, root.key) + maxval = max(maxval, root.key) + if (root.left): + q.put(root.left) + if (root.right): + q.put(root.right) + ''' if minimum value of this level + is not greater than maximum + value of previous level then + given tree is not level sorted. ''' + + if (minval <= prevMax): + return 0 + ''' maximum value of this level is + previous maximum value for + next level. ''' + + prevMax = maxval + return 1 + '''Driver Code ''' + +if __name__ == '__main__': + ''' + 1 + / + 4 + \ + 6 + / \ + 8 9 + / \ + 12 10 ''' + + root = newNode(1) + root.left = newNode(4) + root.left.right = newNode(6) + root.left.right.left = newNode(8) + root.left.right.right = newNode(9) + root.left.right.left.left = newNode(12) + root.left.right.right.right = newNode(10) + if (isSorted(root)): + print(""Sorted"") + else: + print(""Not sorted"")" +Queries to find distance between two nodes of a Binary tree,"/*Java program to find distance between +two nodes for multiple queries*/ + +import java.io.*; +import java.util.*; + +class GFG +{ + static int MAX = 100001; + + /* A tree node structure */ + + static class Node + { + int data; + Node left, right; + + Node(int data) + { + this.data = data; + this.left = this.right = null; + } + } + + static class Pair + { + T first; + V second; + + Pair() { + } + + Pair(T first, V second) + { + this.first = first; + this.second = second; + } + } + +/* Array to store level of each node*/ + + static int[] level = new int[MAX]; + +/* Utility Function to store level of all nodes*/ + + static void findLevels(Node root) + { + if (root == null) + return; + +/* queue to hold tree node with level*/ + + Queue> q = new LinkedList<>(); + +/* let root node be at level 0*/ + + q.add(new Pair(root, 0)); + + Pair p = new Pair(); + +/* Do level Order Traversal of tree*/ + + while (!q.isEmpty()) + { + p = q.poll(); + +/* Node p.first is on level p.second*/ + + level[p.first.data] = p.second; + +/* If left child exits, put it in queue + with current_level +1*/ + + if (p.first.left != null) + q.add(new Pair(p.first.left, + p.second + 1)); + +/* If right child exists, put it in queue + with current_level +1*/ + + if (p.first.right != null) + q.add(new Pair(p.first.right, + p.second + 1)); + } + } + +/* Stores Euler Tour*/ + + static int[] Euler = new int[MAX]; + +/* index in Euler array*/ + + static int idx = 0; + +/* Find Euler Tour*/ + + static void eulerTree(Node root) + { + +/* store current node's data*/ + + Euler[++idx] = root.data; + +/* If left node exists*/ + + if (root.left != null) + { + +/* traverse left subtree*/ + + eulerTree(root.left); + +/* store parent node's data*/ + + Euler[++idx] = root.data; + } + +/* If right node exists*/ + + if (root.right != null) + { +/* traverse right subtree*/ + + eulerTree(root.right); + +/* store parent node's data*/ + + Euler[++idx] = root.data; + } + } + +/* checks for visited nodes*/ + + static int[] vis = new int[MAX]; + +/* Stores level of Euler Tour*/ + + static int[] L = new int[MAX]; + +/* Stores indices of first occurrence + of nodes in Euler tour*/ + + static int[] H = new int[MAX]; + +/* Preprocessing Euler Tour for finding LCA*/ + + static void preprocessEuler(int size) + { + for (int i = 1; i <= size; i++) + { + L[i] = level[Euler[i]]; + +/* If node is not visited before*/ + + if (vis[Euler[i]] == 0) + { + +/* Add to first occurrence*/ + + H[Euler[i]] = i; + +/* Mark it visited*/ + + vis[Euler[i]] = 1; + } + } + } + +/* Stores values and positions*/ + + @SuppressWarnings(""unchecked"") + static Pair[] seg = + (Pair[]) new Pair[4 * MAX]; + +/* Utility function to find minimum of + pair type values*/ + + static Pair + min(Pair a, + Pair b) + { + if (a.first <= b.first) + return a; + return b; + } + +/* Utility function to build segment tree*/ + + static Pair buildSegTree(int low, + int high, int pos) + { + if (low == high) + { + seg[pos].first = L[low]; + seg[pos].second = low; + return seg[pos]; + } + int mid = low + (high - low) / 2; + buildSegTree(low, mid, 2 * pos); + buildSegTree(mid + 1, high, 2 * pos + 1); + + seg[pos] = min(seg[2 * pos], seg[2 * pos + 1]); + + return seg[pos]; + } + +/* Utility function to find LCA*/ + + static Pair LCA(int qlow, int qhigh, + int low, int high, int pos) + { + if (qlow <= low && qhigh >= high) + return seg[pos]; + + if (qlow > high || qhigh < low) + return new Pair + (Integer.MAX_VALUE, 0); + + int mid = low + (high - low) / 2; + + return min(LCA(qlow, qhigh, low, mid, 2 * pos), + LCA(qlow, qhigh, mid + 1, high, 2 * pos + 1)); + } + +/* Function to return distance between + two nodes n1 and n2*/ + + static int findDistance(int n1, int n2, int size) + { + +/* Maintain original Values*/ + + int prevn1 = n1, prevn2 = n2; + +/* Get First Occurrence of n1*/ + + n1 = H[n1]; + +/* Get First Occurrence of n2*/ + + n2 = H[n2]; + +/* Swap if low > high*/ + + if (n2 < n1) + { + int temp = n1; + n1 = n2; + n2 = temp; + } + +/* Get position of minimum value*/ + + int lca = LCA(n1, n2, 1, size, 1).second; + +/* Extract value out of Euler tour*/ + + lca = Euler[lca]; + +/* return calculated distance*/ + + return level[prevn1] + level[prevn2] - + 2 * level[lca]; + } + + static void preProcessing(Node root, int N) + { + for (int i = 0; i < 4 * MAX; i++) + { + seg[i] = new Pair<>(); + } + +/* Build Tree*/ + + eulerTree(root); + +/* Store Levels*/ + + findLevels(root); + +/* Find L and H array*/ + + preprocessEuler(2 * N - 1); + +/* Build segment Tree*/ + + buildSegTree(1, 2 * N - 1, 1); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + +/* Number of nodes*/ + + int N = 8; + + /* Constructing tree given in the above figure */ + + 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.right.left.right = new Node(8); + +/* Function to do all preprocessing*/ + + preProcessing(root, N); + + System.out.println(""Dist(4, 5) = "" + + findDistance(4, 5, 2 * N - 1)); + System.out.println(""Dist(4, 6) = "" + + findDistance(4, 6, 2 * N - 1)); + System.out.println(""Dist(3, 4) = "" + + findDistance(3, 4, 2 * N - 1)); + System.out.println(""Dist(2, 4) = "" + + findDistance(2, 4, 2 * N - 1)); + System.out.println(""Dist(8, 5) = "" + + findDistance(8, 5, 2 * N - 1)); + } +} + + +"," '''Python3 program to find distance between +two nodes for multiple queries''' + + +from collections import deque +from sys import maxsize as INT_MAX + +MAX = 100001 + + '''A tree node structure''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + '''Array to store level of each node''' + +level = [0] * MAX + + '''Utility Function to store level of all nodes''' + +def findLevels(root: Node): + global level + + if root is None: + return + + ''' queue to hold tree node with level''' + + q = deque() + + ''' let root node be at level 0''' + + q.append((root, 0)) + + ''' Do level Order Traversal of tree''' + + while q: + p = q[0] + q.popleft() + + ''' Node p.first is on level p.second''' + + level[p[0].data] = p[1] + + ''' If left child exits, put it in queue + with current_level +1''' + + if p[0].left: + q.append((p[0].left, p[1] + 1)) + + ''' If right child exists, put it in queue + with current_level +1''' + + if p[0].right: + q.append((p[0].right, p[1] + 1)) + + '''Stores Euler Tour''' + +Euler = [0] * MAX + + '''index in Euler array''' + +idx = 0 + + '''Find Euler Tour''' + +def eulerTree(root: Node): + global Euler, idx + idx += 1 + + ''' store current node's data''' + + Euler[idx] = root.data + + ''' If left node exists''' + + if root.left: + + ''' traverse left subtree''' + + eulerTree(root.left) + idx += 1 + + ''' store parent node's data''' + + Euler[idx] = root.data + + ''' If right node exists''' + + if root.right: + + ''' traverse right subtree''' + + eulerTree(root.right) + idx += 1 + + ''' store parent node's data''' + + Euler[idx] = root.data + + '''checks for visited nodes''' + +vis = [0] * MAX + + '''Stores level of Euler Tour''' + +L = [0] * MAX + + '''Stores indices of the first occurrence +of nodes in Euler tour''' + +H = [0] * MAX + + '''Preprocessing Euler Tour for finding LCA''' + +def preprocessEuler(size: int): + global L, H, vis + for i in range(1, size + 1): + L[i] = level[Euler[i]] + + ''' If node is not visited before''' + + if vis[Euler[i]] == 0: + + ''' Add to first occurrence''' + + H[Euler[i]] = i + + ''' Mark it visited''' + + vis[Euler[i]] = 1 + + '''Stores values and positions''' + +seg = [0] * (4 * MAX) +for i in range(4 * MAX): + seg[i] = [0, 0] + + '''Utility function to find minimum of +pair type values''' + +def minPair(a: list, b: list) -> list: + if a[0] <= b[0]: + return a + else: + return b + + '''Utility function to build segment tree''' + +def buildSegTree(low: int, high: int, + pos: int) -> list: + if low == high: + seg[pos][0] = L[low] + seg[pos][1] = low + return seg[pos] + + mid = low + (high - low) // 2 + buildSegTree(low, mid, 2 * pos) + buildSegTree(mid + 1, high, 2 * pos + 1) + + seg[pos] = min(seg[2 * pos], seg[2 * pos + 1]) + + '''Utility function to find LCA''' + +def LCA(qlow: int, qhigh: int, low: int, + high: int, pos: int) -> list: + if qlow <= low and qhigh >= high: + return seg[pos] + + if qlow > high or qhigh < low: + return [INT_MAX, 0] + + mid = low + (high - low) // 2 + + return minPair(LCA(qlow, qhigh, low, mid, 2 * pos), + LCA(qlow, qhigh, mid + 1, high, 2 * pos + 1)) + + '''Function to return distance between +two nodes n1 and n2''' + +def findDistance(n1: int, n2: int, size: int) -> int: + + ''' Maintain original Values''' + + prevn1 = n1 + prevn2 = n2 + + ''' Get First Occurrence of n1''' + + n1 = H[n1] + + ''' Get First Occurrence of n2''' + + n2 = H[n2] + + ''' Swap if low>high''' + + if n2 < n1: + n1, n2 = n2, n1 + + ''' Get position of minimum value''' + + lca = LCA(n1, n2, 1, size, 1)[1] + + ''' Extract value out of Euler tour''' + + lca = Euler[lca] + + ''' return calculated distance''' + + return level[prevn1] + level[prevn2] - 2 * level[lca] + +def preProcessing(root: Node, N: int): + + ''' Build Tree''' + + eulerTree(root) + + ''' Store Levels''' + + findLevels(root) + + ''' Find L and H array''' + + preprocessEuler(2 * N - 1) + + ''' Build sparse table''' + + buildSegTree(1, 2 * N - 1, 1) + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Number of nodes''' + + N = 8 + + ''' Constructing tree given in the above figure''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.right.left.right = Node(8) + + ''' Function to do all preprocessing''' + + preProcessing(root, N) + + print(""Dist(4, 5) ="", + findDistance(4, 5, 2 * N - 1)) + print(""Dist(4, 6) ="", + findDistance(4, 6, 2 * N - 1)) + print(""Dist(3, 4) ="", + findDistance(3, 4, 2 * N - 1)) + print(""Dist(2, 4) ="", + findDistance(2, 4, 2 * N - 1)) + print(""Dist(8, 5) ="", + findDistance(8, 5, 2 * N - 1)) + + +" +Program for Mean and median of an unsorted array,"/*Java program to find mean +and median of an array*/ + +import java.util.*; +class GFG +{ +/* Function for calculating mean*/ + + public static double findMean(int a[], int n) + { + int sum = 0; + for (int i = 0; i < n; i++) + sum += a[i]; + return (double)sum / (double)n; + } +/* Function for calculating median*/ + + public static double findMedian(int a[], int n) + { +/* First we sort the array*/ + + Arrays.sort(a); +/* check for even case*/ + + if (n % 2 != 0) + return (double)a[n / 2]; + return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; + } +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; + int n = a.length; +/* Function call*/ + + System.out.println(""Mean = "" + findMean(a, n)); + System.out.println(""Median = "" + findMedian(a, n)); + } +}"," '''Python3 program to find mean +and median of an array + ''' '''Function for calculating mean''' + +def findMean(a, n): + sum = 0 + for i in range(0, n): + sum += a[i] + return float(sum/n) + '''Function for calculating median''' + +def findMedian(a, n): + ''' First we sort the array''' + + sorted(a) + ''' check for even case''' + + if n % 2 != 0: + return float(a[int(n/2)]) + return float((a[int((n-1)/2)] + + a[int(n/2)])/2.0) + '''Driver code''' + +a = [1, 3, 4, 2, 7, 5, 8, 6] +n = len(a) + '''Function call''' + +print(""Mean ="", findMean(a, n)) +print(""Median ="", findMedian(a, n))" +Mobile Numeric Keypad Problem,"/*A Dynamic Programming based Java program to +count number of possible numbers of given length*/ + +class GFG +{ +/*Return count of all possible numbers of length n +in a given numeric keyboard*/ + +static int getCount(char keypad[][], int n) +{ + if(keypad == null || n <= 0) + return 0; + if(n == 1) + return 10; +/* left, up, right, down move from current location*/ + + int row[] = {0, 0, -1, 0, 1}; + int col[] = {0, -1, 0, 1, 0}; +/* taking n+1 for simplicity - count[i][j] will store + number count starting with digit i and length j*/ + + int [][]count = new int[10][n + 1]; + int i = 0, j = 0, k = 0, move = 0, + ro = 0, co = 0, num = 0; + int nextNum = 0, totalCount = 0; +/* count numbers starting with digit i + and of lengths 0 and 1*/ + + for (i = 0; i <= 9; i++) + { + count[i][0] = 0; + count[i][1] = 1; + } +/* Bottom up - Get number count of length 2, 3, 4, ... , n*/ + + for (k = 2; k <= n; k++) + { +/*Loop on keypad row*/ + +for (i = 0; i < 4; i++) + { +/*Loop on keypad column*/ + +for (j = 0; j < 3; j++) + { +/* Process for 0 to 9 digits*/ + + if (keypad[i][j] != '*' && + keypad[i][j] != '#') + { +/* Here we are counting the numbers starting with + digit keypad[i][j] and of length k keypad[i][j] + will become 1st digit, and we need to look for + (k-1) more digits*/ + + num = keypad[i][j] - '0'; + count[num][k] = 0; +/* move left, up, right, down from current location + and if new location is valid, then get number + count of length (k-1) from that new digit and + add in count we found so far*/ + + for (move = 0; move < 5; move++) + { + ro = i + row[move]; + co = j + col[move]; + if (ro >= 0 && ro <= 3 && co >= 0 && + co <= 2 && keypad[ro][co] != '*' && + keypad[ro][co] != '#') + { + nextNum = keypad[ro][co] - '0'; + count[num][k] += count[nextNum][k - 1]; + } + } + } + } + } + } +/* Get count of all possible numbers of length ""n"" + starting with digit 0, 1, 2, ..., 9*/ + + totalCount = 0; + for (i = 0; i <= 9; i++) + totalCount += count[i][n]; + return totalCount; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + char keypad[][] = {{'1','2','3'}, + {'4','5','6'}, + {'7','8','9'}, + {'*','0','#'}}; + System.out.printf(""Count for numbers of length %d: %d\n"", 1, + getCount(keypad, 1)); + System.out.printf(""Count for numbers of length %d: %d\n"", 2, + getCount(keypad, 2)); + System.out.printf(""Count for numbers of length %d: %d\n"", 3, + getCount(keypad, 3)); + System.out.printf(""Count for numbers of length %d: %d\n"", 4, + getCount(keypad, 4)); + System.out.printf(""Count for numbers of length %d: %d\n"", 5, + getCount(keypad, 5)); +} +}"," '''A Dynamic Programming based C program to count number of +possible numbers of given length''' + '''Return count of all possible numbers of length n +in a given numeric keyboard''' + +def getCount(keypad, n): + if (keypad == None or n <= 0): + return 0 + if (n == 1): + return 10 + ''' left, up, right, down move from current location''' + + row = [0, 0, -1, 0, 1] + col = [0, -1, 0, 1, 0] + ''' taking n+1 for simplicity - count[i][j] will store + number count starting with digit i and length j + count[10][n+1]''' + + count = [[0]*(n + 1)]*10 + i = 0 + j = 0 + k = 0 + move = 0 + ro = 0 + co = 0 + num = 0 + nextNum = 0 + totalCount = 0 + ''' count numbers starting with + digit i and of lengths 0 and 1''' + + for i in range(10): + count[i][0] = 0 + count[i][1] = 1 + ''' Bottom up - Get number + count of length 2, 3, 4, ... , n''' + + for k in range(2, n + 1): + '''Loop on keypad row''' + + + for i in range(4): + + '''Loop on keypad column''' + + for j in range(3): + ''' Process for 0 to 9 digits''' + + if (keypad[i][j] != '*' and keypad[i][j] != '#'): + ''' Here we are counting the numbers starting with + digit keypad[i][j] and of length k keypad[i][j] + will become 1st digit, and we need to look for + (k-1) more digits''' + + num = ord(keypad[i][j]) - 48 + count[num][k] = 0 + ''' move left, up, right, down from current location + and if new location is valid, then get number + count of length (k-1) from that new digit and + add in count we found so far''' + + for move in range(5): + ro = i + row[move] + co = j + col[move] + if (ro >= 0 and ro <= 3 and co >= 0 and co <= 2 and keypad[ro][co] != '*' and keypad[ro][co] != '#'): + nextNum = ord(keypad[ro][co]) - 48 + count[num][k] += count[nextNum][k - 1] + ''' Get count of all possible numbers of length ""n"" starting + with digit 0, 1, 2, ..., 9''' + + totalCount = 0 + for i in range(10): + totalCount += count[i][n] + return totalCount + '''Driver code''' + +if __name__ == ""__main__"": + keypad = [['1','2','3'], + ['4','5','6'], + ['7','8','9'], + ['*', '0', '#']] + print(""Count for numbers of length"", 1, "":"", getCount(keypad, 1)) + print(""Count for numbers of length"", 2, "":"", getCount(keypad, 2)) + print(""Count for numbers of length"", 3, "":"", getCount(keypad, 3)) + print(""Count for numbers of length"", 4, "":"", getCount(keypad, 4)) + print(""Count for numbers of length"", 5, "":"", getCount(keypad, 5)) +" +Number of siblings of a given Node in n-ary Tree,"/*Java program to find number +of siblings of a given node */ + +import java.util.*; +class GFG +{ +/*Represents a node of an n-ary tree */ + +static class Node +{ + int key; + Vector child; + Node(int data) + { + key = data; + child = new Vector(); + } +}; +/*Function to calculate number +of siblings of a given node */ + +static int numberOfSiblings(Node root, int x) +{ + if (root == null) + return 0; +/* Creating a queue and + pushing the root */ + + Queue q = new LinkedList<>(); + q.add(root); + while (q.size() > 0) + { +/* Dequeue an item from queue and + check if it is equal to x If YES, + then return number of children */ + + Node p = q.peek(); + q.remove(); +/* Enqueue all children of + the dequeued item */ + + for (int i = 0; i < p.child.size(); i++) + { +/* If the value of children + is equal to x, then return + the number of siblings */ + + if (p.child.get(i).key == x) + return p.child.size() - 1; + q.add(p.child.get(i)); + } + } + return -1; +} +/*Driver code*/ + +public static void main(String args[]) +{ +/* Creating a generic tree as shown in above figure */ + + Node root = new Node(50); + (root.child).add(new Node(2)); + (root.child).add(new Node(30)); + (root.child).add(new Node(14)); + (root.child).add(new Node(60)); + (root.child.get(0).child).add(new Node(15)); + (root.child.get(0).child).add(new Node(25)); + (root.child.get(0).child.get(1).child).add(new Node(70)); + (root.child.get(0).child.get(1).child).add(new Node(100)); + (root.child.get(1).child).add(new Node(6)); + (root.child.get(1).child).add(new Node(1)); + (root.child.get(2).child).add(new Node(7)); + (root.child.get(2).child.get(0).child).add(new Node(17)); + (root.child.get(2).child.get(0).child).add(new Node(99)); + (root.child.get(2).child.get(0).child).add(new Node(27)); + (root.child.get(3).child).add(new Node(16)); +/* Node whose number of + siblings is to be calculated */ + + int x = 100; +/* Function calling */ + + System.out.println( numberOfSiblings(root, x) ); +} +}"," '''Python3 program to find number +of siblings of a given node ''' + +from queue import Queue + '''Represents a node of an n-ary tree ''' + +class newNode: + def __init__(self,data): + self.child = [] + self.key = data + '''Function to calculate number +of siblings of a given node ''' + +def numberOfSiblings(root, x): + if (root == None): + return 0 + ''' Creating a queue and + pushing the root ''' + + q = Queue() + q.put(root) + while (not q.empty()): + ''' Dequeue an item from queue and + check if it is equal to x If YES, + then return number of children ''' + + p = q.queue[0] + q.get() + ''' Enqueue all children of + the dequeued item''' + + for i in range(len(p.child)): + ''' If the value of children + is equal to x, then return + the number of siblings ''' + + if (p.child[i].key == x): + return len(p.child) - 1 + q.put(p.child[i]) + '''Driver Code''' + +if __name__ == '__main__': + ''' Creating a generic tree as + shown in above figure ''' + + root = newNode(50) + (root.child).append(newNode(2)) + (root.child).append(newNode(30)) + (root.child).append(newNode(14)) + (root.child).append(newNode(60)) + (root.child[0].child).append(newNode(15)) + (root.child[0].child).append(newNode(25)) + (root.child[0].child[1].child).append(newNode(70)) + (root.child[0].child[1].child).append(newNode(100)) + (root.child[1].child).append(newNode(6)) + (root.child[1].child).append(newNode(1)) + (root.child[2].child).append(newNode(7)) + (root.child[2].child[0].child).append(newNode(17)) + (root.child[2].child[0].child).append(newNode(99)) + (root.child[2].child[0].child).append(newNode(27)) + (root.child[3].child).append(newNode(16)) + ''' Node whose number of + siblings is to be calculated ''' + + x = 100 + ''' Function calling ''' + + print(numberOfSiblings(root, x))" +Find length of the largest region in Boolean Matrix,"/*Java program to find the length of the largest +region in boolean 2D-matrix*/ + +import java.io.*; +import java.util.*; +class GFG { + static int ROW, COL, count; +/* A function to check if a given cell (row, col) + can be included in DFS*/ + + static boolean isSafe(int[][] M, int row, int col, + boolean[][] visited) + { +/* row number is in range, column number is in + range and value is 1 and not yet visited*/ + + return ( + (row >= 0) && (row < ROW) && (col >= 0) + && (col < COL) + && (M[row][col] == 1 && !visited[row][col])); + } +/* A utility function to do DFS for a 2D boolean + matrix. It only considers the 8 neighbours as + adjacent vertices*/ + + static void DFS(int[][] M, int row, int col, + boolean[][] visited) + { +/* These arrays are used to get row and column + numbers of 8 neighbours of a given cell*/ + + int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 }; + int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 }; +/* Mark this cell as visited*/ + + visited[row][col] = true; +/* Recur for all connected neighbours*/ + + for (int k = 0; k < 8; k++) + { + if (isSafe(M, row + rowNbr[k], col + colNbr[k], + visited)) + { +/* increment region length by one*/ + + count++; + DFS(M, row + rowNbr[k], col + colNbr[k], + visited); + } + } + } +/* The main function that returns largest length region + of a given boolean 2D matrix*/ + + static int largestRegion(int[][] M) + { +/* Make a boolean array to mark visited cells. + Initially all cells are unvisited*/ + + boolean[][] visited = new boolean[ROW][COL]; +/* Initialize result as 0 and traverse through the + all cells of given matrix*/ + + int result = 0; + for (int i = 0; i < ROW; i++) + { + for (int j = 0; j < COL; j++) + { +/* If a cell with value 1 is not*/ + + if (M[i][j] == 1 && !visited[i][j]) + { +/* visited yet, then new region found*/ + + count = 1; + DFS(M, i, j, visited); +/* maximum region*/ + + result = Math.max(result, count); + } + } + } + return result; + } +/* Driver code*/ + + public static void main(String args[]) + { + int M[][] = { { 0, 0, 1, 1, 0 }, + { 1, 0, 1, 1, 0 }, + { 0, 1, 0, 0, 0 }, + { 0, 0, 0, 0, 1 } }; + ROW = 4; + COL = 5; +/* Function call*/ + + System.out.println(largestRegion(M)); + } +}"," '''Python3 program to find the length of the +largest region in boolean 2D-matrix''' + + '''A function to check if a given cell +(row, col) can be included in DFS''' + +def isSafe(M, row, col, visited): + global ROW, COL ''' row number is in range, column number is in + range and value is 1 and not yet visited''' + + return ((row >= 0) and (row < ROW) and + (col >= 0) and (col < COL) and + (M[row][col] and not visited[row][col])) + '''A utility function to do DFS for a 2D +boolean matrix. It only considers +the 8 neighbours as adjacent vertices''' + +def DFS(M, row, col, visited, count): + ''' These arrays are used to get row and column + numbers of 8 neighbours of a given cell''' + + rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] + colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] + ''' Mark this cell as visited''' + + visited[row][col] = True + ''' Recur for all connected neighbours''' + + for k in range(8): + if (isSafe(M, row + rowNbr[k], + col + colNbr[k], visited)): + ''' increment region length by one''' + + count[0] += 1 + DFS(M, row + rowNbr[k], + col + colNbr[k], visited, count) + '''The main function that returns largest +length region of a given boolean 2D matrix''' + +def largestRegion(M): + global ROW, COL + ''' Make a bool array to mark visited cells. + Initially all cells are unvisited''' + + visited = [[0] * COL for i in range(ROW)] + ''' Initialize result as 0 and travesle + through the all cells of given matrix''' + + result = -999999999999 + for i in range(ROW): + for j in range(COL): + ''' If a cell with value 1 is not''' + + if (M[i][j] and not visited[i][j]): + ''' visited yet, then new region found''' + + count = [1] + DFS(M, i, j, visited, count) + ''' maximum region''' + + result = max(result, count[0]) + return result + '''Driver Code''' + +ROW = 4 +COL = 5 +M = [[0, 0, 1, 1, 0], + [1, 0, 1, 1, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 1]] + '''Function call''' + +print(largestRegion(M))" +Array range queries over range queries,"/*Java program to perform range queries +over range queries.*/ + +import java.util.*; +class GFG +{ +/* Function to execute type 1 query*/ + + static void type1(int[] arr, int start, int limit) + { +/* incrementing the array by 1 for type + 1 queries*/ + + for (int i = start; i <= limit; i++) + arr[i]++; + } +/* Function to execute type 2 query*/ + + static void type2(int[] arr, int[][] query, + int start, int limit) + { + for (int i = start; i <= limit; i++) + { +/* If the query is of type 1 function + call to type 1 query*/ + + if (query[i][0] == 1) + type1(arr, query[i][1], query[i][2]); +/* If the query is of type 2 recursive call + to type 2 query*/ + + else if (query[i][0] == 2) + type2(arr, query, query[i][1], + query[i][2]); + } + } +/* Driver Code*/ + + public static void main(String[] args) + { +/* Input size of array amd number of queries*/ + + int n = 5, m = 5; + int[] arr = new int[n + 1]; +/* Build query matrix*/ + + int[] temp = { 1, 1, 2, 1, 4, 5, 2, + 1, 2, 2, 1, 3, 2, 3, 4 }; + int[][] query = new int[6][4]; + int j = 0; + for (int i = 1; i <= m; i++) + { + query[i][0] = temp[j++]; + query[i][1] = temp[j++]; + query[i][2] = temp[j++]; + } +/* Perform queries*/ + + for (int i = 1; i <= m; i++) + if (query[i][0] == 1) + type1(arr, query[i][1], query[i][2]); + else if (query[i][0] == 2) + type2(arr, query, query[i][1], + query[i][2]); +/* printing the result*/ + + for (int i = 1; i <= n; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +}"," '''Python3 program to perform range +queries over range queries.''' + '''Function to execute type 1 query''' + +def type1(arr, start, limit): + ''' incrementing the array by 1 + for type 1 queries''' + + for i in range(start, limit + 1): + arr[i] += 1 + '''Function to execute type 2 query''' + +def type2(arr, query, start, limit): + for i in range(start, limit + 1): + ''' If the query is of type 1 + function call to type 1 query''' + + if (query[i][0] == 1): + type1(arr, query[i][1], query[i][2]) + ''' If the query is of type 2 + recursive call to type 2 query''' + + elif (query[i][0] == 2): + type2(arr, query, query[i][1], + query[i][2]) + '''Driver code''' + '''Input size of array amd +number of queries''' + +n = 5 +m = 5 +arr = [0 for i in range(n + 1)] + '''Build query matrix''' + +temp = [1, 1, 2, 1, 4, 5, 2, + 1, 2, 2, 1, 3, 2, 3, 4 ] +query = [[0 for i in range(3)] + for j in range(6)] +j = 0 +for i in range(1, m + 1): + query[i][0] = temp[j] + j += 1 + query[i][1] = temp[j] + j += 1 + query[i][2] = temp[j] + j += 1 + '''Perform queries''' + +for i in range(1, m + 1): + if (query[i][0] == 1): + type1(arr, query[i][1], + query[i][2]) + elif (query[i][0] == 2): + type2(arr, query, query[i][1], + query[i][2]) + '''printing the result''' + +for i in range(1, n + 1): + print(arr[i], end = "" "")" +Stepping Numbers,"/*A Java program to find all the Stepping Number in +range [n, m]*/ + +import java.util.*; +class Main +{ +/* Prints all stepping numbers reachable from num + and in range [n, m]*/ + + public static void bfs(int n,int m,int num) + { +/* Queue will contain all the stepping Numbers*/ + + Queue q = new LinkedList (); + q.add(num); + while (!q.isEmpty()) + { +/* Get the front element and pop from + the queue*/ + + int stepNum = q.poll(); +/* If the Stepping Number is in + the range [n,m] then display*/ + + if (stepNum <= m && stepNum >= n) + { + System.out.print(stepNum + "" ""); + } +/* If Stepping Number is 0 or greater + then m, no need to explore the neighbors*/ + + if (stepNum == 0 || stepNum > m) + continue; +/* Get the last digit of the currently + visited Stepping Number*/ + + int lastDigit = stepNum % 10; +/* There can be 2 cases either digit + to be appended is lastDigit + 1 or + lastDigit - 1*/ + + int stepNumA = stepNum * 10 + (lastDigit- 1); + int stepNumB = stepNum * 10 + (lastDigit + 1); +/* If lastDigit is 0 then only possible + digit after 0 can be 1 for a Stepping + Number*/ + + if (lastDigit == 0) + q.add(stepNumB); +/* If lastDigit is 9 then only possible + digit after 9 can be 8 for a Stepping + Number*/ + + else if (lastDigit == 9) + q.add(stepNumA); + else + { + q.add(stepNumA); + q.add(stepNumB); + } + } + } +/* Prints all stepping numbers in range [n, m] + using BFS.*/ + + public static void displaySteppingNumbers(int n,int m) + { +/* For every single digit Number 'i' + find all the Stepping Numbers + starting with i*/ + + for (int i = 0 ; i <= 9 ; i++) + bfs(n, m, i); + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 0, m = 21; +/* Display Stepping Numbers in + the range [n,m]*/ + + displaySteppingNumbers(n,m); + } +}"," '''A Python3 program to find all the Stepping Number from N=n +to m using BFS Approach''' + + '''Prints all stepping numbers reachable from num +and in range [n, m]''' + +def bfs(n, m, num) : ''' Queue will contain all the stepping Numbers''' + + q = [] + q.append(num) + while len(q) > 0 : + ''' Get the front element and pop from the queue''' + + stepNum = q[0] + q.pop(0); + ''' If the Stepping Number is in the range + [n, m] then display''' + + if (stepNum <= m and stepNum >= n) : + print(stepNum, end = "" "") + ''' If Stepping Number is 0 or greater than m, + no need to explore the neighbors''' + + if (num == 0 or stepNum > m) : + continue + ''' Get the last digit of the currently visited + Stepping Number''' + + lastDigit = stepNum % 10 + ''' There can be 2 cases either digit to be + appended is lastDigit + 1 or lastDigit - 1''' + + stepNumA = stepNum * 10 + (lastDigit- 1) + stepNumB = stepNum * 10 + (lastDigit + 1) + ''' If lastDigit is 0 then only possible digit + after 0 can be 1 for a Stepping Number''' + + if (lastDigit == 0) : + q.append(stepNumB) + ''' If lastDigit is 9 then only possible + digit after 9 can be 8 for a Stepping + Number''' + + elif (lastDigit == 9) : + q.append(stepNumA) + else : + q.append(stepNumA) + q.append(stepNumB) + '''Prints all stepping numbers in range [n, m] +using BFS.''' + +def displaySteppingNumbers(n, m) : + ''' For every single digit Number 'i' + find all the Stepping Numbers + starting with i''' + + for i in range(10) : + bfs(n, m, i) + ''' Driver code''' + +n, m = 0, 21 + '''Display Stepping Numbers in the +range [n,m]''' + +displaySteppingNumbers(n, m)" +Program for Identity Matrix,"/*Java program to print Identity Matrix*/ + +class GFG { + static int identity(int num) + { + int row, col; + for (row = 0; row < num; row++) + { + for (col = 0; col < num; col++) + { +/* Checking if row is equal to column*/ + + if (row == col) + System.out.print( 1+"" ""); + else + System.out.print( 0+"" ""); + } + System.out.println(); + } + return 0; + } +/* Driver Code*/ + + public static void main(String args[]) + { + int size = 5; + identity(size); + } +}"," '''Python code to print identity matrix +Function to print identity matrix''' + +def Identity(size): + for row in range(0, size): + for col in range(0, size): + ''' Here end is used to stay in same line''' + + if (row == col): + print(""1 "", end="" "") + else: + print(""0 "", end="" "") + print() + '''Driver Code ''' + +size = 5 +Identity(size)" +Consecutive steps to roof top,"/*Java code to find maximum +number of consecutive steps.*/ + +import java.io.*; + +class GFG { + +/* Function to count consecutive steps*/ + + static int find_consecutive_steps(int arr[], + int len) + { + int count = 0; + int maximum = 0; + + for (int index = 1; index < len; index++) { + +/* count the number of consecutive + increasing height building*/ + + if (arr[index] > arr[index - 1]) + count++; + else + { + maximum = Math.max(maximum, count); + count = 0; + } + } + + return Math.max(maximum, count); + } + +/* Driver code*/ + + public static void main (String[] args) { + + int arr[] = { 1, 2, 3, 4 }; + int len = arr.length; + + System.out.println(find_consecutive_steps(arr, + len)); + } +} + + +"," '''Python3 code to find maximum +number of consecutive steps''' + +import math + + '''Function to count consecutive steps''' + +def find_consecutive_steps(arr, len): + + count = 0; maximum = 0 + + for index in range(1, len): + + ''' count the number of consecutive + increasing height building''' + + if (arr[index] > arr[index - 1]): + count += 1 + + else: + maximum = max(maximum, count) + count = 0 + + return max(maximum, count) + + '''Driver code''' + +arr = [ 1, 2, 3, 4 ] +len = len(arr) +print(find_consecutive_steps(arr, len)) + + + +" +Sum of all elements between k1'th and k2'th smallest elements,"/*Java implementation of above approach*/ + +class GFG +{ +static int n = 7; +static void minheapify(int []a, int index) +{ + int small = index; + int l = 2 * index + 1; + int r = 2 * index + 2; + if (l < n && a[l] < a[small]) + small = l; + if (r < n && a[r] < a[small]) + small = r; + if (small != index) + { + int t = a[small]; + a[small] = a[index]; + a[index] = t; + minheapify(a, small); + } +} +/*Driver code*/ + +public static void main (String[] args) +{ + int i = 0; + int k1 = 3; + int k2 = 6; + int []a = { 20, 8, 22, 4, 12, 10, 14 }; + int ans = 0; + for (i = (n / 2) - 1; i >= 0; i--) + { + minheapify(a, i); + } +/* decreasing value by 1 because we want + min heapifying k times and it starts + from 0 so we have to decrease it 1 time*/ + + k1--; + k2--; +/* Step 1: Do extract minimum k1 times + (This step takes O(K1 Log n) time)*/ + + for (i = 0; i <= k1; i++) + { + a[0] = a[n - 1]; + n--; + minheapify(a, 0); + } + +/*Step 2: Do extract minimum k2 – k1 – 1 times and sum all + extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/ + + for (i = k1 + 1; i < k2; i++) + { + ans += a[0]; + a[0] = a[n - 1]; + n--; + minheapify(a, 0); + } + System.out.println(ans); +} +}"," '''Python 3 implementation of above approach''' + +n = 7 +def minheapify(a, index): + small = index + l = 2 * index + 1 + r = 2 * index + 2 + if (l < n and a[l] < a[small]): + small = l + if (r < n and a[r] < a[small]): + small = r + if (small != index): + (a[small], a[index]) = (a[index], a[small]) + minheapify(a, small) + '''Driver Code''' + +i = 0 +k1 = 3 +k2 = 6 +a = [ 20, 8, 22, 4, 12, 10, 14 ] +ans = 0 +for i in range((n //2) - 1, -1, -1): + minheapify(a, i) + '''decreasing value by 1 because we want +min heapifying k times and it starts +from 0 so we have to decrease it 1 time''' + +k1 -= 1 +k2 -= 1 + '''Step 1: Do extract minimum k1 times +(This step takes O(K1 Log n) time)''' + +for i in range(0, k1 + 1): + a[0] = a[n - 1] + n -= 1 + minheapify(a, 0) + '''Step 2: Do extract minimum k2 – k1 – 1 times and +sum all extracted elements. +(This step takes O ((K2 – k1) * Log n) time)*/''' + +for i in range(k1 + 1, k2) : + ans += a[0] + a[0] = a[n - 1] + n -= 1 + minheapify(a, 0) +print (ans)" +Count numbers that don't contain 3,"/*Java program to count numbers that not contain 3*/ + +import java.io.*; +class GFG +{ +/* Function that returns count of numbers which + are in range from 1 to n + and not contain 3 as a digit*/ + + static int count(int n) + { +/* Base cases (Assuming n is not negative)*/ + + if (n < 3) + return n; + if (n >= 3 && n < 10) + return n-1; +/* Calculate 10^(d-1) (10 raise to the power d-1) where d is + number of digits in n. po will be 100 for n = 578*/ + + int po = 1; + while (n/po > 9) + po = po*10; +/* find the most significant digit (msd is 5 for 578)*/ + + int msd = n/po; + if (msd != 3) +/* For 578, total will be 4*count(10^2 - 1) + 4 + count(78)*/ + + return count(msd)*count(po - 1) + count(msd) + count(n%po); + else +/* For 35, total will be equal to count(29)*/ + + return count(msd*po - 1); + } +/* Driver program*/ + + public static void main (String[] args) + { + int n = 578; + System.out.println(count(n)); + } +} +"," '''Python program to count numbers upto n that don't contain 3''' + + '''Returns count of numbers which are in range from 1 to n +and don't contain 3 as a digit''' + +def count(n): ''' Base Cases ( n is not negative)''' + + if n < 3: + return n + elif n >= 3 and n < 10: + return n-1 + ''' Calculate 10^(d-1) ( 10 raise to the power d-1 ) where d + is number of digits in n. po will be 100 for n = 578''' + + po = 1 + while n/po > 9: + po = po * 10 + ''' Find the MSD ( msd is 5 for 578 )''' + + msd = n/po + if msd != 3: + ''' For 578, total will be 4*count(10^2 - 1) + 4 + ccount(78)''' + + return count(msd) * count(po-1) + count(msd) + count(n%po) + else: + ''' For 35 total will be equal to count(29)''' + + return count(msd * po - 1) + '''Driver Program''' + +n = 578 +print count(n) +" +Find a triplet that sum to a given value,"/*Java program to find a triplet*/ + +class FindTriplet { +/* returns true if there is triplet with sum equal + to 'sum' present in A[]. Also, prints the triplet*/ + + boolean find3Numbers(int A[], int arr_size, int sum) + { + int l, r; +/* Fix the first element as A[i]*/ + + for (int i = 0; i < arr_size - 2; i++) { +/* Fix the second element as A[j]*/ + + for (int j = i + 1; j < arr_size - 1; j++) { +/* Now look for the third number*/ + + for (int k = j + 1; k < arr_size; k++) { + if (A[i] + A[j] + A[k] == sum) { + System.out.print(""Triplet is "" + A[i] + "", "" + A[j] + "", "" + A[k]); + return true; + } + } + } + } +/* If we reach here, then no triplet was found*/ + + return false; + } +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + FindTriplet triplet = new FindTriplet(); + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = A.length; + triplet.find3Numbers(A, arr_size, sum); + } +}"," '''Python3 program to find a triplet +that sum to a given value''' + + '''returns true if there is triplet with +sum equal to 'sum' present in A[]. +Also, prints the triplet''' + +def find3Numbers(A, arr_size, sum): ''' Fix the first element as A[i]''' + + for i in range( 0, arr_size-2): + ''' Fix the second element as A[j]''' + + for j in range(i + 1, arr_size-1): + ''' Now look for the third number''' + + for k in range(j + 1, arr_size): + if A[i] + A[j] + A[k] == sum: + print(""Triplet is"", A[i], + "", "", A[j], "", "", A[k]) + return True + ''' If we reach here, then no + triplet was found''' + + return False + '''Driver program to test above function ''' + +A = [1, 4, 45, 6, 10, 8] +sum = 22 +arr_size = len(A) +find3Numbers(A, arr_size, sum)" +Mean of range in array,"/*Java program to find floor value +of mean in range l to r*/ + +public class Main { +public static final int MAX = 1000005; + static int prefixSum[] = new int[MAX]; + +/* To calculate prefixSum of array*/ + + static void calculatePrefixSum(int arr[], int n) + { +/* Calculate prefix sum of array*/ + + prefixSum[0] = arr[0]; + for (int i = 1; i < n; i++) + prefixSum[i] = prefixSum[i - 1] + arr[i]; + } + +/* To return floor of mean + in range l to r*/ + + static int findMean(int l, int r) + { + if (l == 0) + return (int)Math.floor(prefixSum[r] / (r + 1)); + +/* Sum of elements in range l to + r is prefixSum[r] - prefixSum[l-1] + Number of elements in range + l to r is r - l + 1*/ + + return (int)Math.floor((prefixSum[r] - + prefixSum[l - 1]) / (r - l + 1)); + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + int arr[] = { 1, 2, 3, 4, 5 }; + int n = arr.length; + calculatePrefixSum(arr, n); + System.out.println(findMean(1, 2)); + System.out.println(findMean(1, 3)); + System.out.println(findMean(1, 4)); + } +} +"," '''Python3 program to find floor value +of mean in range l to r''' + +import math as mt + +MAX = 1000005 +prefixSum = [0 for i in range(MAX)] + + '''To calculate prefixSum of array''' + +def calculatePrefixSum(arr, n): + + ''' Calculate prefix sum of array''' + + prefixSum[0] = arr[0] + + for i in range(1,n): + prefixSum[i] = prefixSum[i - 1] + arr[i] + + '''To return floor of mean +in range l to r''' + +def findMean(l, r): + + if (l == 0): + return mt.floor(prefixSum[r] / (r + 1)) + + ''' Sum of elements in range l to + r is prefixSum[r] - prefixSum[l-1] + Number of elements in range + l to r is r - l + 1''' + + return (mt.floor((prefixSum[r] - + prefixSum[l - 1]) / + (r - l + 1))) + + '''Driver Code''' + +arr = [1, 2, 3, 4, 5] + +n = len(arr) + +calculatePrefixSum(arr, n) +print(findMean(0, 2)) +print(findMean(1, 3)) +print(findMean(0, 4)) + + +" +Count number of edges in an undirected graph,"/*Java program to count number of edge in +undirected graph*/ + +import java.io.*; +import java.util.*; +/*Adjacency list representation of graph*/ + +class Graph +{ + int V; + Vector[] adj; + Graph(int V) + { + this.V = V; + this.adj = new Vector[V]; + for (int i = 0; i < V; i++) + adj[i] = new Vector(); + }/* add edge to graph*/ + + void addEdge(int u, int v) + { + adj[u].add(v); + adj[v].add(u); + } +/* Returns count of edge in undirected graph*/ + + int countEdges() + { + int sum = 0; +/* traverse all vertex*/ + + for (int i = 0; i < V; i++) +/* add all edge that are linked to the + current vertex*/ + + sum += adj[i].size(); +/* The count of edge is always even because in + undirected graph every edge is connected + twice between two vertices*/ + + return sum / 2; + } +} +class GFG +{ +/* Driver Code*/ + + public static void main(String[] args) throws IOException + { + int V = 9; + Graph g = new Graph(V); +/* making above uhown graph*/ + + g.addEdge(0, 1); + g.addEdge(0, 7); + g.addEdge(1, 2); + g.addEdge(1, 7); + g.addEdge(2, 3); + g.addEdge(2, 8); + g.addEdge(2, 5); + g.addEdge(3, 4); + g.addEdge(3, 5); + g.addEdge(4, 5); + g.addEdge(5, 6); + g.addEdge(6, 7); + g.addEdge(6, 8); + g.addEdge(7, 8); + System.out.println(g.countEdges()); + } +}"," '''Python3 program to count number of +edge in undirected graph ''' + '''Adjacency list representation of graph ''' + +class Graph: + def __init__(self, V): + self.V = V + self.adj = [[] for i in range(V)] + ''' add edge to graph ''' + + def addEdge (self, u, v ): + self.adj[u].append(v) + self.adj[v].append(u) + ''' Returns count of edge in undirected graph ''' + + def countEdges(self): + Sum = 0 + ''' traverse all vertex ''' + + for i in range(self.V): + ''' add all edge that are linked + to the current vertex ''' + + Sum += len(self.adj[i]) + ''' The count of edge is always even + because in undirected graph every edge + is connected twice between two vertices ''' + + return Sum // 2 + '''Driver Code''' + +if __name__ == '__main__': + V = 9 + g = Graph(V) + ''' making above uhown graph ''' + + g.addEdge(0, 1 ) + g.addEdge(0, 7 ) + g.addEdge(1, 2 ) + g.addEdge(1, 7 ) + g.addEdge(2, 3 ) + g.addEdge(2, 8 ) + g.addEdge(2, 5 ) + g.addEdge(3, 4 ) + g.addEdge(3, 5 ) + g.addEdge(4, 5 ) + g.addEdge(5, 6 ) + g.addEdge(6, 7 ) + g.addEdge(6, 8 ) + g.addEdge(7, 8 ) + print(g.countEdges())" +Elements to be added so that all elements of a range are present in array,"/*java program for above implementation*/ + +import java.io.*; +import java.util.*; +public class GFG { +/* Function to count numbers to be added*/ + + static int countNum(int []arr, int n) + { + int count = 0; +/* Sort the array*/ + + Arrays.sort(arr); +/* Check if elements are consecutive + or not. If not, update count*/ + + for (int i = 0; i < n - 1; i++) + if (arr[i] != arr[i+1] && + arr[i] != arr[i + 1] - 1) + count += arr[i + 1] - arr[i] - 1; + return count; + } +/* Drivers code*/ + + static public void main (String[] args) + { + int []arr = { 3, 5, 8, 6 }; + int n = arr.length; + System.out.println(countNum(arr, n)); + } +}"," '''python program for above implementation + ''' '''Function to count numbers to be added''' + +def countNum(arr, n): + count = 0 + ''' Sort the array''' + + arr.sort() + ''' Check if elements are consecutive + or not. If not, update count''' + + for i in range(0, n-1): + if (arr[i] != arr[i+1] and + arr[i] != arr[i + 1] - 1): + count += arr[i + 1] - arr[i] - 1; + return count + '''Drivers code''' + +arr = [ 3, 5, 8, 6 ] +n = len(arr) +print(countNum(arr, n))" +Count items common to both the lists but with different prices,"/*Java implementation to count items common to both +the lists but with different prices*/ + +class GFG{ +/*details of an item*/ + +static class item +{ + String name; + int price; + public item(String name, int price) { + this.name = name; + this.price = price; + } +}; +/*function to count items common to both +the lists but with different prices*/ + +static int countItems(item list1[], int m, + item list2[], int n) +{ + int count = 0; +/* for each item of 'list1' check if it is in 'list2' + but with a different price*/ + + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + if ((list1[i].name.compareTo(list2[j].name) == 0) && + (list1[i].price != list2[j].price)) + count++; +/* required count of items*/ + + return count; +} +/*Driver code*/ + +public static void main(String[] args) +{ + item list1[] = {new item(""apple"", 60), new item(""bread"", 20), + new item(""wheat"", 50), new item(""oil"", 30)}; + item list2[] = {new item(""milk"", 20), new item(""bread"", 15), + new item(""wheat"", 40), new item(""apple"", 60)}; + int m = list1.length; + int n = list2.length; + System.out.print(""Count = "" + + countItems(list1, m, list2, n)); +} +}"," '''Python implementation to +count items common to both +the lists but with different +prices''' + '''function to count items +common to both +the lists but with different prices''' + +def countItems(list1, list2): + count = 0 + ''' for each item of 'list1' + check if it is in 'list2' + but with a different price''' + + for i in list1: + for j in list2: + if i[0] == j[0] and i[1] != j[1]: + count += 1 + ''' required count of items''' + + return count + '''Driver program to test above''' + +list1 = [(""apple"", 60), (""bread"", 20), + (""wheat"", 50), (""oil"", 30)] +list2 = [(""milk"", 20), (""bread"", 15), + (""wheat"", 40), (""apple"", 60)] +print(""Count = "", countItems(list1, list2))" +Print all triplets in sorted array that form AP,"/*Java program to print all +triplets in given array +that form Arithmetic +Progression*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Function to print + all triplets in + given sorted array + that forms AP*/ + + static void printAllAPTriplets(int []arr, + int n) + { + ArrayList s = + new ArrayList(); + for (int i = 0; + i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { +/* Use hash to find if + there is a previous + element with difference + equal to arr[j] - arr[i]*/ + + int diff = arr[j] - arr[i]; + boolean exists = + s.contains(arr[i] - diff); + if (exists) + System.out.println(arr[i] - diff + + "" "" + arr[i] + + "" "" + arr[j]); + } + s.add(arr[i]); + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int []arr = {2, 6, 9, 12, 17, + 22, 31, 32, 35, 42}; + int n = arr.length; + printAllAPTriplets(arr, n); + } +}"," '''Python program to print all +triplets in given array +that form Arithmetic +Progression + ''' '''Function to print +all triplets in +given sorted array +that forms AP''' + +def printAllAPTriplets(arr, n) : + s = []; + for i in range(0, n - 1) : + for j in range(i + 1, n) : + ''' Use hash to find if + there is a previous + element with difference + equal to arr[j] - arr[i]''' + + diff = arr[j] - arr[i]; + if ((arr[i] - diff) in arr) : + print (""{} {} {}"" . + format((arr[i] - diff), + arr[i], arr[j]), + end = ""\n""); + s.append(arr[i]); + '''Driver code''' + +arr = [2, 6, 9, 12, 17, + 22, 31, 32, 35, 42]; +n = len(arr); +printAllAPTriplets(arr, n);" +Find size of the largest '+' formed by all ones in a binary matrix,"/*Java program to find the size of the largest '+' +formed by all 1's in given binary matrix*/ + +import java.io.*; +class GFG { +/* size of binary square matrix*/ + + static int N = 10; +/* Function to find the size of the largest '+' + formed by all 1's in given binary matrix*/ + + static int findLargestPlus(int mat[][]) + { +/* left[j][j], right[i][j], top[i][j] and + bottom[i][j] store maximum number of + consecutive 1's present to the left, + right, top and bottom of mat[i][j] + including cell(i, j) respectively*/ + + int left[][] = new int[N][N]; + int right[][] = new int[N][N]; + int top[][] = new int[N][N]; + int bottom[][] = new int[N][N]; +/* initialize above four matrix*/ + + for (int i = 0; i < N; i++) { +/* initialize first row of top*/ + + top[0][i] = mat[0][i]; +/* initialize last row of bottom*/ + + bottom[N - 1][i] = mat[N - 1][i]; +/* initialize first column of left*/ + + left[i][0] = mat[i][0]; +/* initialize last column of right*/ + + right[i][N - 1] = mat[i][N - 1]; + } +/* fill all cells of above four matrix*/ + + for (int i = 0; i < N; i++) { + for (int j = 1; j < N; j++) { +/* calculate left matrix + (filled left to right)*/ + + if (mat[i][j] == 1) + left[i][j] = left[i][j - 1] + 1; + else + left[i][j] = 0; +/* calculate top matrix*/ + + if (mat[j][i] == 1) + top[j][i] = top[j - 1][i] + 1; + else + top[j][i] = 0; +/* calculate new value of j to + calculate value of bottom(i, j) + and right(i, j)*/ + + j = N - 1 - j; +/* calculate bottom matrix*/ + + if (mat[j][i] == 1) + bottom[j][i] = bottom[j + 1][i] + 1; + else + bottom[j][i] = 0; +/* calculate right matrix*/ + + if (mat[i][j] == 1) + right[i][j] = right[i][j + 1] + 1; + else + right[i][j] = 0; +/* revert back to old j*/ + + j = N - 1 - j; + } + } +/* n stores length of longest + found so far*/ + + int n = 0; +/* compute longest +*/ + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { +/* find minimum of left(i, j), + right(i, j), top(i, j), + bottom(i, j)*/ + + int len = Math.min(Math.min(top[i][j], + bottom[i][j]),Math.min(left[i][j], + right[i][j])); +/* largest + would be formed by a + cell that has maximum value*/ + + if (len > n) + n = len; + } + } +/* 4 directions of length n - 1 and 1 for + middle cell*/ + + if (n > 0) + return 4 * (n - 1) + 1; +/* matrix contains all 0's*/ + + return 0; + } + /* Driver function to test above functions */ + + public static void main(String[] args) + { + int mat[][] = { + { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, + { 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 }, + { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 }, + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }, + { 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 0, 1, 1 }, + { 1, 1, 0, 0, 1, 0, 1, 0, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 } + }; + System.out.println(findLargestPlus(mat)); + } +}"," '''Python 3 program to find the size +of the largest '+' formed by all +1's in given binary matrix''' + + '''size of binary square matrix''' + +N = 10 '''Function to find the size of the +largest '+' formed by all 1's in +given binary matrix''' + +def findLargestPlus(mat): + ''' left[j][j], right[i][j], top[i][j] and + bottom[i][j] store maximum number of + consecutive 1's present to the left, + right, top and bottom of mat[i][j] including + cell(i, j) respectively''' + + left = [[0 for x in range(N)] + for y in range(N)] + right = [[0 for x in range(N)] + for y in range(N)] + top = [[0 for x in range(N)] + for y in range(N)] + bottom = [[0 for x in range(N)] + for y in range(N)] + ''' initialize above four matrix''' + + for i in range(N): + ''' initialize first row of top''' + + top[0][i] = mat[0][i] + ''' initialize last row of bottom''' + + bottom[N - 1][i] = mat[N - 1][i] + ''' initialize first column of left''' + + left[i][0] = mat[i][0] + ''' initialize last column of right''' + + right[i][N - 1] = mat[i][N - 1] + ''' fill all cells of above four matrix''' + + for i in range(N): + for j in range(1, N): + ''' calculate left matrix (filled + left to right)''' + + if (mat[i][j] == 1): + left[i][j] = left[i][j - 1] + 1 + else: + left[i][j] = 0 + ''' calculate top matrix''' + + if (mat[j][i] == 1): + top[j][i] = top[j - 1][i] + 1 + else: + top[j][i] = 0 + ''' calculate new value of j to calculate + value of bottom(i, j) and right(i, j)''' + + j = N - 1 - j + ''' calculate bottom matrix''' + + if (mat[j][i] == 1): + bottom[j][i] = bottom[j + 1][i] + 1 + else: + bottom[j][i] = 0 + ''' calculate right matrix''' + + if (mat[i][j] == 1): + right[i][j] = right[i][j + 1] + 1 + else: + right[i][j] = 0 + ''' revert back to old j''' + + j = N - 1 - j + ''' n stores length of longest '+' + found so far''' + + n = 0 + ''' compute longest +''' + + for i in range(N): + for j in range(N): + ''' find minimum of left(i, j), + right(i, j), top(i, j), bottom(i, j)''' + + l = min(min(top[i][j], bottom[i][j]), + min(left[i][j], right[i][j])) + ''' largest + would be formed by + a cell that has maximum value''' + + if(l > n): + n = l + ''' 4 directions of length n - 1 and 1 + for middle cell''' + + if (n): + return 4 * (n - 1) + 1 + ''' matrix contains all 0's''' + + return 0 + '''Driver Code''' + +if __name__==""__main__"": + mat = [ [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], + [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], + [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ], + [ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ], + [ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ], + [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ], + [ 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 ], + [ 1, 0, 1, 1, 1, 1, 0, 0, 1, 1 ], + [ 1, 1, 0, 0, 1, 0, 1, 0, 0, 1 ], + [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ]] + print(findLargestPlus(mat))" +Count all distinct pairs with difference equal to k,"/*A simple Java program to +count pairs with difference k*/ + +import java.util.*; +import java.io.*; +class GFG { + static int countPairsWithDiffK(int arr[], + int n, int k) + { + int count = 0; +/* Pick all elements one by one*/ + + for (int i = 0; i < n; i++) + { +/* See if there is a pair + of this picked element*/ + + for (int j = i + 1; j < n; j++) + if (arr[i] - arr[j] == k || + arr[j] - arr[i] == k) + count++; + } + return count; + } +/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 5, 3, 4, 2 }; + int n = arr.length; + int k = 3; + System.out.println(""Count of pairs with given diff is "" + + countPairsWithDiffK(arr, n, k)); + } +}"," '''A simple program to count pairs with difference k''' + +def countPairsWithDiffK(arr, n, k): + count = 0 + ''' Pick all elements one by one''' + + for i in range(0, n): + ''' See if there is a pair of this picked element''' + + for j in range(i+1, n) : + if arr[i] - arr[j] == k or arr[j] - arr[i] == k: + count += 1 + return count + '''Driver program''' + +arr = [1, 5, 3, 4, 2] +n = len(arr) +k = 3 +print (""Count of pairs with given diff is "", + countPairsWithDiffK(arr, n, k))" +Group multiple occurrence of array elements ordered by first occurrence,"/*A simple Java program to group +multiple occurrences of individual +array elements*/ + +class GFG +{ +/* A simple method to group all occurrences + of individual elements*/ + + static void groupElements(int arr[], int n) + { +/* Initialize all elements as not visited*/ + + boolean visited[] = new boolean[n]; + for (int i = 0; i < n; i++) + { + visited[i] = false; + } +/* Traverse all elements*/ + + for (int i = 0; i < n; i++) + { +/* Check if this is first occurrence*/ + + if (!visited[i]) + { +/* If yes, print it and all + subsequent occurrences*/ + + System.out.print(arr[i] + "" ""); + for (int j = i + 1; j < n; j++) + { + if (arr[i] == arr[j]) + { + System.out.print(arr[i] + "" ""); + visited[j] = true; + } + } + } + } + } + /* Driver code */ + + public static void main(String[] args) + { + int arr[] = {4, 6, 9, 2, 3, 4, + 9, 6, 10, 4}; + int n = arr.length; + groupElements(arr, n); + } +}"," '''A simple Python 3 program to +group multiple occurrences of +individual array elements''' '''A simple method to group all +occurrences of individual elements''' + +def groupElements(arr, n): + ''' Initialize all elements + as not visited''' + + visited = [False] * n + for i in range(0, n): + visited[i] = False + ''' Traverse all elements''' + + for i in range(0, n): + ''' Check if this is + first occurrence''' + + if (visited[i] == False): + ''' If yes, print it and + all subsequent occurrences''' + + print(arr[i], end = "" "") + for j in range(i + 1, n): + if (arr[i] == arr[j]): + print(arr[i], end = "" "") + visited[j] = True + '''Driver Code''' + +arr = [4, 6, 9, 2, 3, + 4, 9, 6, 10, 4] +n = len(arr) +groupElements(arr, n)" +Zigzag (or diagonal) traversal of Matrix,"import java.util.*; +import java.io.*; +class GFG +{ + public static int R = 5, C = 4; + public static void diagonalOrder(int[][] arr, int n, int m) + { +/* we will use a 2D vector to + store the diagonals of our array + the 2D vector will have (n+m-1) + rows that is equal to the number of + diagnols*/ + + ArrayList> ans = new ArrayList>(n+m-1); + for(int i = 0; i < n + m - 1; i++) + { + ans.add(new ArrayList()); + } + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + (ans.get(i+j)).add(arr[i][j]); + } + } + for (int i = 0; i < ans.size(); i++) + { + for (int j = ans.get(i).size() - 1; j >= 0; j--) + { System.out.print(ans.get(i).get(j)+ "" ""); + } + System.out.println(); + } + } +/* Driver code*/ + + public static void main (String[] args) { + int n = 5, m = 4; + int[][] arr={ + { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 }, + { 17, 18, 19, 20 }, + }; +/* Function call*/ + + diagonalOrder(arr, n, m); + } +}","R = 5 +C = 5 +def diagonalOrder(arr, n, m): + ''' we will use a 2D vector to + store the diagonals of our array + the 2D vector will have (n+m-1) + rows that is equal to the number of + diagnols''' + + ans = [[] for i in range(n + m - 1)] + for i in range(m): + for j in range(n): + ans[i + j].append(arr[j][i]) + for i in range(len(ans)): + for j in range(len(ans[i])): + print(ans[i][j], end = "" "") + print() + '''Driver Code''' + +n = 5 +m = 4 +arr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]] '''Function call''' + + +diagonalOrder(arr, n, m)" +Remove nodes on root to leaf paths of length < K,"/*Java program to remove nodes on root to leaf paths of length < k*/ + +/* Class containing left and right child of current + node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; +/* Utility method that actually removes the nodes which are not + on the pathLen >= k. This method can change the root as well.*/ + + Node removeShortPathNodesUtil(Node node, int level, int k) + { +/* Base condition*/ + + if (node == null) + return null; +/* Traverse the tree in postorder fashion so that if a leaf + node path length is shorter than k, then that node and + all of its descendants till the node which are not + on some other path are removed.*/ + + node.left = removeShortPathNodesUtil(node.left, level + 1, k); + node.right = removeShortPathNodesUtil(node.right, level + 1, k); +/* If root is a leaf node and it's level is less than k then + remove this node. + This goes up and check for the ancestor nodes also for the + same condition till it finds a node which is a part of other + path(s) too.*/ + + if (node.left == null && node.right == null && level < k) + return null; +/* Return root;*/ + + return node; + } +/* Method which calls the utitlity method to remove the short path + nodes.*/ + + Node removeShortPathNodes(Node node, int k) + { + int pathLen = 0; + return removeShortPathNodesUtil(node, 1, k); + } +/* Method to print the tree in inorder fashion.*/ + + void printInorder(Node node) + { + if (node != null) + { + printInorder(node.left); + System.out.print(node.data + "" ""); + printInorder(node.right); + } + } +/* Driver program to test for samples*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + int k = 4; + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.left.left.left = new Node(7); + tree.root.right.right = new Node(6); + tree.root.right.right.left = new Node(8); + System.out.println(""The inorder traversal of original tree is : ""); + tree.printInorder(tree.root); + Node res = tree.removeShortPathNodes(tree.root, k); + System.out.println(""""); + System.out.println(""The inorder traversal of modified tree is : ""); + tree.printInorder(res); + } +}"," '''Python3 program to remove nodes on root +to leaf paths of length < K ''' + + '''New node of a tree ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Utility method that actually removes +the nodes which are not on the pathLen >= k. +This method can change the root as well. ''' + +def removeShortPathNodesUtil(root, level, k) : + ''' Base condition ''' + + if (root == None) : + return None + ''' Traverse the tree in postorder fashion + so that if a leaf node path length is + shorter than k, then that node and all + of its descendants till the node which + are not on some other path are removed. ''' + + root.left = removeShortPathNodesUtil(root.left, + level + 1, k) + root.right = removeShortPathNodesUtil(root.right, + level + 1, k) + ''' If root is a leaf node and it's level + is less than k then remove this node. + This goes up and check for the ancestor + nodes also for the same condition till + it finds a node which is a part of other + path(s) too. ''' + + if (root.left == None and + root.right == None and level < k) : + return None + ''' Return root ''' + + return root + '''Method which calls the utitlity method +to remove the short path nodes. ''' + +def removeShortPathNodes(root, k) : + pathLen = 0 + return removeShortPathNodesUtil(root, 1, k) + '''Method to print the tree in +inorder fashion. ''' + +def prInorder(root) : + if (root) : + prInorder(root.left) + print(root.data, end = "" "" ) + prInorder(root.right) + '''Driver Code ''' + +if __name__ == '__main__': + k = 4 + root = newNode(1) + root.left = newNode(2) + root.right = newNode(3) + root.left.left = newNode(4) + root.left.right = newNode(5) + root.left.left.left = newNode(7) + root.right.right = newNode(6) + root.right.right.left = newNode(8) + print(""Inorder Traversal of Original tree"" ) + prInorder(root) + print() + print(""Inorder Traversal of Modified tree"" ) + res = removeShortPathNodes(root, k) + prInorder(res)" +Program for Newton Raphson Method,"/*Java program for implementation of +Newton Raphson Method for solving +equations*/ + +class GFG { + static final double EPSILON = 0.001; +/* An example function whose solution + is determined using Bisection Method. + The function is x^3 - x^2 + 2*/ + + static double func(double x) + { + return x * x * x - x * x + 2; + } +/* Derivative of the above function + which is 3*x^x - 2*x*/ + + static double derivFunc(double x) + { + return 3 * x * x - 2 * x; + } +/* Function to find the root*/ + + static void newtonRaphson(double x) + { + double h = func(x) / derivFunc(x); + while (Math.abs(h) >= EPSILON) + { + h = func(x) / derivFunc(x); +/* x(i+1) = x(i) - f(x) / f'(x)*/ + + x = x - h; + } + System.out.print(""The value of the"" + + "" root is : "" + + Math.round(x * 100.0) / 100.0); + } +/* Driver code*/ + + public static void main (String[] args) + { +/* Initial values assumed*/ + + double x0 = -20; + newtonRaphson(x0); + } +}"," '''Python3 code for implementation of Newton +Raphson Method for solving equations''' + + '''An example function whose solution +is determined using Bisection Method. +The function is x^3 - x^2 + 2''' + +def func( x ): + return x * x * x - x * x + 2 '''Derivative of the above function +which is 3*x^x - 2*x''' + +def derivFunc( x ): + return 3 * x * x - 2 * x + '''Function to find the root''' + +def newtonRaphson( x ): + h = func(x) / derivFunc(x) + while abs(h) >= 0.0001: + h = func(x)/derivFunc(x) + ''' x(i+1) = x(i) - f(x) / f'(x)''' + + x = x - h + print(""The value of the root is : "", + ""%.4f""% x) + '''Driver program to test above''' + '''Initial values assumed''' + +x0 = -20 +newtonRaphson(x0)" +Program for Tower of Hanoi,"/*JAVA recursive function to +solve tower of hanoi puzzle*/ + +import java.util.*; +import java.io.*; +import java.math.*; +class GFG +{ +static void towerOfHanoi(int n, char from_rod, + char to_rod, char aux_rod) +{ + if (n == 1) + { + System.out.println(""Move disk 1 from rod ""+ + from_rod+"" to rod ""+to_rod); + return; + } + towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); + System.out.println(""Move disk ""+ n + "" from rod "" + + from_rod +"" to rod "" + to_rod ); + towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); +} +/*Driver code*/ + +public static void main(String args[]) +{ +/*Number of disks*/ + +int n = 4; +/*A, B and C are names of rods*/ + +towerOfHanoi(n, 'A', 'C', 'B'); +} +}"," '''Recursive Python function to solve tower of hanoi''' + +def TowerOfHanoi(n , from_rod, to_rod, aux_rod): + if n == 1: + print(""Move disk 1 from rod"",from_rod,""to rod"",to_rod) + return + TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) + print(""Move disk"",n,""from rod"",from_rod,""to rod"",to_rod) + TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) + '''Driver code''' + '''Number of disks''' + +n = 4 '''A, C, B are the name of rods''' +TowerOfHanoi(n, 'A', 'C', 'B')" +Find the length of largest subarray with 0 sum,"/*A Java program to find maximum length subarray with 0 sum*/ + +import java.util.HashMap; +class MaxLenZeroSumSub { +/* Returns length of the maximum length subarray with 0 sum*/ + + static int maxLen(int arr[]) + { +/* Creates an empty hashMap hM*/ + + HashMap hM = new HashMap(); +/*Initialize sum of elements*/ + +int sum = 0; +/*Initialize result*/ + +int max_len = 0; +/* Traverse through the given array*/ + + for (int i = 0; i < arr.length; i++) { +/* Add current element to sum*/ + + sum += arr[i]; + if (arr[i] == 0 && max_len == 0) + max_len = 1; + if (sum == 0) + max_len = i + 1; +/* Look this sum in hash table*/ + + Integer prev_i = hM.get(sum); + if (prev_i != null) + max_len = Math.max(max_len, i - prev_i); +/*Else put this sum in hash table*/ + +else + hM.put(sum, i); + } + return max_len; + } +/* Drive method*/ + + public static void main(String arg[]) + { + int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; + System.out.println(""Length of the longest 0 sum subarray is "" + + maxLen(arr)); + } +}"," '''A python program to find maximum length subarray +with 0 sum in o(n) time''' + + '''Returns the maximum length''' + +def maxLen(arr): ''' NOTE: Dictonary in python in implemented as Hash Maps + Create an empty hash map (dictionary)''' + + hash_map = {} + ''' Initialize sum of elements''' + + curr_sum = 0 + ''' Initialize result''' + + max_len = 0 + ''' Traverse through the given array''' + + for i in range(len(arr)): + ''' Add the current element to the sum''' + + curr_sum += arr[i] + if arr[i] is 0 and max_len is 0: + max_len = 1 + if curr_sum is 0: + max_len = i + 1 + ''' NOTE: 'in' operation in dictionary to search + key takes O(1). Look if current sum is seen + before''' + + if curr_sum in hash_map: + max_len = max(max_len, i - hash_map[curr_sum] ) + ''' else put this sum in dictionary''' + else: + hash_map[curr_sum] = i + return max_len + '''test array''' + +arr = [15, -2, 2, -8, 1, 7, 10, 13] +print ""Length of the longest 0 sum subarray is % d"" % maxLen(arr)" +Check if two arrays are equal or not,"/*Java program to find given two array +are equal or not*/ + +import java.io.*; +import java.util.*; +class GFG { +/* Returns true if arr1[0..n-1] and arr2[0..m-1] + contain same elements.*/ + + public static boolean areEqual(int arr1[], int arr2[]) + { + int n = arr1.length; + int m = arr2.length; +/* If lengths of array are not equal means + array are not equal*/ + + if (n != m) + return false; +/* Sort both arrays*/ + + Arrays.sort(arr1); + Arrays.sort(arr2); +/* Linearly compare elements*/ + + for (int i = 0; i < n; i++) + if (arr1[i] != arr2[i]) + return false; +/* If all elements were same.*/ + + return true; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr1[] = { 3, 5, 2, 5, 2 }; + int arr2[] = { 2, 3, 5, 5, 2 }; + if (areEqual(arr1, arr2)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +}"," '''Python3 program to find given +two array are equal or not + ''' '''Returns true if arr1[0..n-1] and +arr2[0..m-1] contain same elements.''' + +def areEqual(arr1, arr2, n, m): + ''' If lengths of array are not + equal means array are not equal''' + + if (n != m): + return False + ''' Sort both arrays''' + + arr1.sort() + arr2.sort() + ''' Linearly compare elements''' + + for i in range(0, n - 1): + if (arr1[i] != arr2[i]): + return False + ''' If all elements were same.''' + + return True + '''Driver Code''' + +arr1 = [3, 5, 2, 5, 2] +arr2 = [2, 3, 5, 5, 2] +n = len(arr1) +m = len(arr2) +if (areEqual(arr1, arr2, n, m)): + print(""Yes"") +else: + print(""No"")" +"Given an n x n square matrix, find sum of all sub-squares of size k x k","/*An efficient Java program to find +sum of all subsquares of size k x k*/ + +import java.io.*; +class GFG { +/*Size of given matrix*/ + +static int n = 5; +/*A O(n^2) function to find sum of all +sub-squares of size k x k in a given +square matrix of size n x n*/ + +static void printSumTricky(int mat[][], int k) { +/* k must be smaller than or equal to n*/ + + if (k > n) + return; +/* 1: PREPROCESSING + To store sums of all strips of size k x 1*/ + + int stripSum[][] = new int[n][n]; +/* Go column by column*/ + + for (int j = 0; j < n; j++) { +/* Calculate sum of first k x 1 + rectangle in this column*/ + + int sum = 0; + for (int i = 0; i < k; i++) + sum += mat[i][j]; + stripSum[0][j] = sum; +/* Calculate sum of remaining rectangles*/ + + for (int i = 1; i < n - k + 1; i++) { + sum += (mat[i + k - 1][j] - mat[i - 1][j]); + stripSum[i][j] = sum; + } + } +/* 2: CALCULATE SUM of Sub-Squares + using stripSum[][]*/ + + for (int i = 0; i < n - k + 1; i++) { +/* Calculate and print sum of first + subsquare in this row*/ + + int sum = 0; + for (int j = 0; j < k; j++) + sum += stripSum[i][j]; + System.out.print(sum + "" ""); +/* Calculate sum of remaining squares + in current row by removing the + leftmost strip of previous sub-square + and adding a new strip*/ + + for (int j = 1; j < n - k + 1; j++) { + sum += (stripSum[i][j + k - 1] - stripSum[i][j - 1]); + System.out.print(sum + "" ""); + } + System.out.println(); + } +} +/*Driver program to test above function*/ + +public static void main(String[] args) +{ + int mat[][] = {{1, 1, 1, 1, 1}, + {2, 2, 2, 2, 2}, + {3, 3, 3, 3, 3}, + {4, 4, 4, 4, 4}, + {5, 5, 5, 5, 5}, + }; + int k = 3; + printSumTricky(mat, k); +} +}"," '''An efficient Python3 program to find sum +of all subsquares of size k x k''' + + '''Size of given matrix''' + +n = 5 '''A O(n^2) function to find sum of all +sub-squares of size k x k in a given +square matrix of size n x n''' + +def printSumTricky(mat, k): + global n ''' k must be smaller than or + equal to n''' + + if k > n: + return + ''' 1: PREPROCESSING + To store sums of all strips of size k x 1''' + + stripSum = [[None] * n for i in range(n)] + ''' Go column by column''' + + for j in range(n): + ''' Calculate sum of first k x 1 + rectangle in this column''' + + Sum = 0 + for i in range(k): + Sum += mat[i][j] + stripSum[0][j] = Sum + ''' Calculate sum of remaining rectangles''' + + for i in range(1, n - k + 1): + Sum += (mat[i + k - 1][j] - + mat[i - 1][j]) + stripSum[i][j] = Sum + ''' 2: CALCULATE SUM of Sub-Squares + using stripSum[][]''' + + for i in range(n - k + 1): + ''' Calculate and prsum of first + subsquare in this row''' + + Sum = 0 + for j in range(k): + Sum += stripSum[i][j] + print(Sum, end = "" "") + ''' Calculate sum of remaining squares + in current row by removing the leftmost + strip of previous sub-square and adding + a new strip''' + + for j in range(1, n - k + 1): + Sum += (stripSum[i][j + k - 1] - + stripSum[i][j - 1]) + print(Sum, end = "" "") + print() + '''Driver Code''' + + +mat = [[1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4], + [5, 5, 5, 5, 5]] +k = 3 +printSumTricky(mat, k)" +Count all distinct pairs with difference equal to k,"/*A sorting base java program to +count pairs with difference k*/ + +import java.util.*; +import java.io.*; +class GFG { +/* +Standard binary search function */ + + static int binarySearch(int arr[], int low, + int high, int x) + { + if (high >= low) + { + int mid = low + (high - low) / 2; + if (x == arr[mid]) + return mid; + if (x > arr[mid]) + return binarySearch(arr, (mid + 1), + high, x); + else + return binarySearch(arr, low, + (mid - 1), x); + } + return -1; + } +/* Returns count of pairs with + difference k in arr[] of size n.*/ + + static int countPairsWithDiffK(int arr[], int n, int k) + { + int count = 0, i; +/* Sort array elements*/ + + Arrays.sort(arr); +/* code to remove duplicates from arr[]*/ + +/* Pick a first element point*/ + + for (i = 0; i < n - 1; i++) + if (binarySearch(arr, i + 1, n - 1, + arr[i] + k) != -1) + count++; + return count; + }/* Driver code*/ + + public static void main(String args[]) + { + int arr[] = { 1, 5, 3, 4, 2 }; + int n = arr.length; + int k = 3; + System.out.println(""Count of pairs with given diff is "" + + countPairsWithDiffK(arr, n, k)); + } +}"," '''A sorting based program to +count pairs with difference k''' + + '''Standard binary search function''' + +def binarySearch(arr, low, high, x): + if (high >= low): + mid = low + (high - low)//2 + if x == arr[mid]: + return (mid) + elif(x > arr[mid]): + return binarySearch(arr, (mid + 1), high, x) + else: + return binarySearch(arr, low, (mid -1), x) + return -1 '''Returns count of pairs with +difference k in arr[] of size n.''' + +def countPairsWithDiffK(arr, n, k): + count = 0 + '''Sort array elements''' + + arr.sort() + ''' code to remove + duplicates from arr[]''' + + ''' Pick a first element point''' + + for i in range (0, n - 2): + if (binarySearch(arr, i + 1, n - 1, + arr[i] + k) != -1): + count += 1 + return count '''Driver Code''' + +arr= [1, 5, 3, 4, 2] +n = len(arr) +k = 3 +print (""Count of pairs with given diff is "", + countPairsWithDiffK(arr, n, k))" +K Centers Problem | Set 1 (Greedy Approximate Algorithm),"/*Java program for the above approach*/ + +import java.util.*; +class GFG{ +static int maxindex(int[] dist, int n) +{ + int mi = 0; + for(int i = 0; i < n; i++) + { + if (dist[i] > dist[mi]) + mi = i; + } + return mi; +} +static void selectKcities(int n, int weights[][], + int k) +{ + int[] dist = new int[n]; + ArrayList centers = new ArrayList<>(); + for(int i = 0; i < n; i++) + { + dist[i] = Integer.MAX_VALUE; + } +/* Index of city having the + maximum distance to it's + closest center*/ + + int max = 0; + for(int i = 0; i < k; i++) + { + centers.add(max); + for(int j = 0; j < n; j++) + { +/* Updating the distance + of the cities to their + closest centers*/ + + dist[j] = Math.min(dist[j], + weights[max][j]); + } +/* Updating the index of the + city with the maximum + distance to it's closest center*/ + + max = maxindex(dist, n); + } +/* Printing the maximum distance + of a city to a center + that is our answer*/ + + System.out.println(dist[max]); +/* Printing the cities that + were chosen to be made + centers*/ + + for(int i = 0; i < centers.size(); i++) + { + System.out.print(centers.get(i) + "" ""); + } + System.out.print(""\n""); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int n = 4; + int[][] weights = new int[][]{ { 0, 4, 8, 5 }, + { 4, 0, 10, 7 }, + { 8, 10, 0, 9 }, + { 5, 7, 9, 0 } }; + int k = 2; +/* Function Call*/ + + selectKcities(n, weights, k); +} +}"," '''Python3 program for the above approach''' + +def maxindex(dist, n): + mi = 0 + for i in range(n): + if (dist[i] > dist[mi]): + mi = i + return mi +def selectKcities(n, weights, k): + dist = [0]*n + centers = [] + for i in range(n): + dist[i] = 10**9 + ''' index of city having the + maximum distance to it's + closest center''' + + max = 0 + for i in range(k): + centers.append(max) + for j in range(n): + ''' updating the distance + of the cities to their + closest centers''' + + dist[j] = min(dist[j], weights[max][j]) + ''' updating the index of the + city with the maximum + distance to it's closest center''' + + max = maxindex(dist, n) + ''' Printing the maximum distance + of a city to a center + that is our answer + print()''' + + print(dist[max]) + ''' Printing the cities that + were chosen to be made + centers''' + + for i in centers: + print(i, end = "" "") + '''Driver Code''' + +if __name__ == '__main__': + n = 4 + weights = [ [ 0, 4, 8, 5 ], + [ 4, 0, 10, 7 ], + [ 8, 10, 0, 9 ], + [ 5, 7, 9, 0 ] ] + k = 2 + ''' Function Call''' + + selectKcities(n, weights, k)" +Sum of all nodes in a binary tree,"/*Java Program to print sum of +all the elements of a binary tree*/ + +class GFG +{ +static class Node +{ + int key; + Node left, right; +} +/* utility that allocates a new + Node with the given key */ + +static Node newNode(int key) +{ + Node node = new Node(); + node.key = key; + node.left = node.right = null; + return (node); +} +/* Function to find sum + of all the elements*/ + +static int addBT(Node root) +{ + if (root == null) + return 0; + return (root.key + addBT(root.left) + + addBT(root.right)); +} +/*Driver Code*/ + +public static void main(String args[]) +{ + 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); + int sum = addBT(root); + System.out.println(""Sum of all the elements is: "" + sum); +} +}"," '''Python3 Program to print sum of all +the elements of a binary tree +Binary Tree Node ''' + + ''' utility that allocates a new Node +with the given key ''' + +class newNode: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Function to find sum of all the element ''' + +def addBT(root): + if (root == None): + return 0 + return (root.key + addBT(root.left) + + addBT(root.right)) + '''Driver Code ''' + +if __name__ == '__main__': + 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) + sum = addBT(root) + print(""Sum of all the nodes is:"", sum)" +Elements to be added so that all elements of a range are present in array,"/*Java implementation of the approach*/ + +import java.util.HashSet; +class GFG +{ +/*Function to count numbers to be added*/ + +static int countNum(int arr[], int n) +{ + HashSet s = new HashSet<>(); + int count = 0, + maxm = Integer.MIN_VALUE, + minm = Integer.MAX_VALUE; +/* Make a hash of elements + and store minimum and maximum element*/ + + for (int i = 0; i < n; i++) + { + s.add(arr[i]); + if (arr[i] < minm) + minm = arr[i]; + if (arr[i] > maxm) + maxm = arr[i]; + } +/* Traverse all elements from minimum + to maximum and count if it is not + in the hash*/ + + for (int i = minm; i <= maxm; i++) + if (!s.contains(i)) + count++; + return count; +} +/*Drivers code*/ + +public static void main(String[] args) +{ + int arr[] = { 3, 5, 8, 6 }; + int n = arr.length; + System.out.println(countNum(arr, n)); +} +}"," '''Function to count numbers to be added''' + +def countNum(arr, n): + s = dict() + count, maxm, minm = 0, -10**9, 10**9 + ''' Make a hash of elements and store + minimum and maximum element''' + + for i in range(n): + s[arr[i]] = 1 + if (arr[i] < minm): + minm = arr[i] + if (arr[i] > maxm): + maxm = arr[i] + ''' Traverse all elements from minimum + to maximum and count if it is not + in the hash''' + + for i in range(minm, maxm + 1): + if i not in s.keys(): + count += 1 + return count + '''Driver code''' + +arr = [3, 5, 8, 6 ] +n = len(arr) +print(countNum(arr, n))" +Product of maximum in first array and minimum in second,"/*Java program to find the +to calculate the product +of max element of first +array and min element of +second array*/ + +import java.util.*; +import java.lang.*; +class GfG +{ +/* Function to calculate + the product*/ + + public static int minMaxProduct(int arr1[], + int arr2[], + int n1, + int n2) + { +/* Sort the arrays to find the + maximum and minimum elements + in given arrays*/ + + Arrays.sort(arr1); + Arrays.sort(arr2); +/* Return product of maximum + and minimum.*/ + + return arr1[n1 - 1] * arr2[0]; + } +/* Driver Code*/ + + public static void main(String argc[]) + { + int [] arr1= new int []{ 10, 2, 3, + 6, 4, 1 }; + int [] arr2 = new int []{ 5, 1, 4, + 2, 6, 9 }; + int n1 = 6; + int n2 = 6; + System.out.println(minMaxProduct(arr1, + arr2, + n1, n2)); + } +}"," '''A Python program to find the to +calculate the product of max +element of first array and min +element of second array + ''' '''Function to calculate the product''' + +def minmaxProduct(arr1, arr2, n1, n2): + ''' Sort the arrays to find the + maximum and minimum elements + in given arrays''' + + arr1.sort() + arr2.sort() + ''' Return product of maximum + and minimum.''' + + return arr1[n1 - 1] * arr2[0] + '''Driver Program''' + +arr1 = [10, 2, 3, 6, 4, 1] +arr2 = [5, 1, 4, 2, 6, 9] +n1 = len(arr1) +n2 = len(arr2) +print(minmaxProduct(arr1, arr2, n1, n2))" +Count BST subtrees that lie in given range,"/*Java program to count subtrees +that lie in a given range*/ + +class GfG { +/* A BST node*/ + + static class node { + int data; + node left, right; + }; +/* int class*/ + + static class INT { + int a; + } +/* A utility function to check if data of root is + in range from low to high*/ + + static boolean inRange(node root, int low, int high) + { + return root.data >= low && root.data <= high; + } +/* A recursive function to get count + of nodes whose subtree is in range + from low to hgih. This function returns + true if nodes in subtree rooted under + 'root' are in range.*/ + + static boolean getCountUtil(node root, int low, + int high, INT count) + { +/* Base case*/ + + if (root == null) + return true; +/* Recur for left and right subtrees*/ + + boolean l = getCountUtil(root.left, + low, high, count); + boolean r = getCountUtil(root.right, + low, high, count); +/* If both left and right subtrees are + in range and current node is also in + range, then increment count and return true*/ + + if (l && r && inRange(root, low, high)) { + ++count.a; + return true; + } + return false; + } +/* A wrapper over getCountUtil(). + This function initializes count as 0 + and calls getCountUtil()*/ + + static INT getCount(node root, int low, int high) + { + INT count = new INT(); + count.a = 0; + getCountUtil(root, low, high, count); + return count; + } +/* Utility function to create new node*/ + + static node newNode(int data) + { + node temp = new node(); + temp.data = data; + temp.left = temp.right = null; + return (temp); + } +/* Driver code*/ + + public static void main(String args[]) + { +/* Let us con the BST shown in the above figure*/ + + node root = newNode(10); + root.left = newNode(5); + root.right = newNode(50); + root.left.left = newNode(1); + root.right.left = newNode(40); + root.right.right = newNode(100); + /* Let us construct BST shown in above example + 10 + / \ + 5 50 + / / \ + 1 40 100 */ + + int l = 5; + int h = 45; + System.out.println(""Count of subtrees in ["" + l + "", "" + + h + ""] is "" + getCount(root, l, h).a); + } +}"," '''Python3 program to count subtrees that +lie in a given range''' + + '''A utility function to check if data of +root is in range from low to high''' + +def inRange(root, low, high): + return root.data >= low and root.data <= high + '''A recursive function to get count of nodes +whose subtree is in range from low to high. +This function returns true if nodes in subtree +rooted under 'root' are in range.''' + +def getCountUtil(root, low, high, count): + ''' Base case''' + + if root == None: + return True + ''' Recur for left and right subtrees''' + + l = getCountUtil(root.left, low, high, count) + r = getCountUtil(root.right, low, high, count) + ''' If both left and right subtrees are in range + and current node is also in range, then + increment count and return true''' + + if l and r and inRange(root, low, high): + count[0] += 1 + return True + return False + '''A wrapper over getCountUtil(). This function +initializes count as 0 and calls getCountUtil()''' + +def getCount(root, low, high): + count = [0] + getCountUtil(root, low, high, count) + return count + '''Utility function to create new node''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Driver Code''' + +if __name__ == '__main__': + ''' Let us construct the BST shown in + the above figure''' + + root = newNode(10) + root.left = newNode(5) + root.right = newNode(50) + root.left.left = newNode(1) + root.right.left = newNode(40) + root.right.right = newNode(100) + ''' Let us constructed BST shown in above example + 10 + / \ + 5 50 + / / \ + 1 40 100''' + + l = 5 + h = 45 + print(""Count of subtrees in ["", l, "", "", h, ""] is "", + getCount(root, l, h))" +Compute modulus division by a power-of-2-number,"/*Java code for Compute modulus division by +a power-of-2-number*/ + +class GFG { +/* This function will return n % d. + d must be one of: 1, 2, 4, 8, 16, 32,*/ + + static int getModulo(int n, int d) + { + return ( n & (d-1) ); + } +/* Driver Code*/ + + public static void main(String[] args) + { + int n = 6; + /*d must be a power of 2*/ + + int d = 4; + System.out.println(n+"" moduo "" + d + + "" is "" + getModulo(n, d)); + } +}"," '''Python code to demonstrate +modulus division by power of 2''' + + '''This function will +return n % d. +d must be one of: +1, 2, 4, 8, 16, 32, …''' + +def getModulo(n, d): + return ( n & (d-1) ) '''Driver program to +test above function''' + +n = 6 + '''d must be a power of 2''' + +d = 4 +print(n,""moduo"",d,""is"", + getModulo(n, d))" +Find all possible binary trees with given Inorder Traversal,"/*Java program to find binary tree with given inorder +traversal*/ + +import java.util.Vector; +/* Class containing left and right child of current + node and key value*/ + +class Node { + int data; + Node left, right; + public Node(int item) { + data = item; + left = null; + right = null; + } +} +/* Class to print Level Order Traversal */ + +class BinaryTree { + Node root; +/* A utility function to do preorder traversal of BST*/ + + void preOrder(Node node) { + if (node != null) { + System.out.print(node.data + "" "" ); + preOrder(node.left); + preOrder(node.right); + } + } +/* Function for constructing all possible trees with + given inorder traversal stored in an array from + arr[start] to arr[end]. This function returns a + vector of trees.*/ + + Vector getTrees(int arr[], int start, int end) { +/* List to store all possible trees*/ + + Vector trees= new Vector(); + /* if start > end then subtree will be empty so + returning NULL in the list */ + + if (start > end) { + trees.add(null); + return trees; + } + /* Iterating through all values from start to end + for constructing left and right subtree + recursively */ + + for (int i = start; i <= end; i++) { + /* Constructing left subtree */ + + Vector ltrees = getTrees(arr, start, i - 1); + /* Constructing right subtree */ + + Vector rtrees = getTrees(arr, i + 1, end); + /* Now looping through all left and right subtrees + and connecting them to ith root below */ + + for (int j = 0; j < ltrees.size(); j++) { + for (int k = 0; k < rtrees.size(); k++) { +/* Making arr[i] as root*/ + + Node node = new Node(arr[i]); +/* Connecting left subtree*/ + + node.left = ltrees.get(j); +/* Connecting right subtree*/ + + node.right = rtrees.get(k); +/* Adding this tree to list*/ + + trees.add(node); + } + } + } + return trees; + } + /*Driver Program to test above functions*/ + +public static void main(String args[]) { + int in[] = {4, 5, 7}; + int n = in.length; + BinaryTree tree = new BinaryTree(); + Vector trees = tree.getTrees(in, 0, n - 1); + System.out.println(""Preorder traversal of different ""+ + "" binary trees are:""); + for (int i = 0; i < trees.size(); i++) { + tree.preOrder(trees.get(i)); + System.out.println(""""); + } + } +}"," '''Python program to find binary tree with given +inorder traversal''' + + '''Node Structure''' + +class Node: ''' Utility to create a new node''' + + def __init__(self , item): + self.key = item + self.left = None + self.right = None + '''A utility function to do preorder traversal of BST''' + +def preorder(root): + if root is not None: + print root.key, + preorder(root.left) + preorder(root.right) + '''Function for constructing all possible trees with +given inorder traversal stored in an array from +arr[start] to arr[end]. This function returns a +vector of trees.''' + +def getTrees(arr , start , end): + ''' List to store all possible trees''' + + trees = [] + ''' if start > end then subtree will be empty so + returning NULL in the list ''' + + if start > end : + trees.append(None) + return trees + ''' Iterating through all values from start to end + for constructing left and right subtree + recursively ''' + + for i in range(start , end+1): + ''' Constructing left subtree''' + + ltrees = getTrees(arr , start , i-1) + ''' Constructing right subtree''' + + rtrees = getTrees(arr , i+1 , end) + ''' Looping through all left and right subtrees + and connecting to ith root below''' + + for j in ltrees : + for k in rtrees : + ''' Making arr[i] as root''' + + node = Node(arr[i]) + ''' Connecting left subtree''' + + node.left = j + ''' Connecting right subtree''' + + node.right = k + ''' Adding this tree to list''' + + trees.append(node) + return trees + '''Driver program to test above function''' + +inp = [4 , 5, 7] +n = len(inp) +trees = getTrees(inp , 0 , n-1) +print ""Preorder traversals of different possible\ + Binary Trees are "" +for i in trees : + preorder(i); + print """"" +Find difference between sums of two diagonals,"/*JAVA Code for Find difference between sums +of two diagonals*/ + +class GFG { + public static int difference(int arr[][], int n) + { +/* Initialize sums of diagonals*/ + + int d1 = 0, d2 = 0; + for (int i = 0; i < n; i++) + { + d1 += arr[i][i]; + d2 += arr[i][n-i-1]; + } +/* Absolute difference of the sums + across the diagonals*/ + + return Math.abs(d1 - d2); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int n = 3; + int arr[][] = + { + {11, 2, 4}, + {4 , 5, 6}, + {10, 8, -12} + }; + System.out.print(difference(arr, n)); + } + }"," '''Python3 program to find the difference +between the sum of diagonal.''' + +def difference(arr, n): + ''' Initialize sums of diagonals''' + + d1 = 0 + d2 = 0 + for i in range(0, n): + d1 = d1 + arr[i][i] + d2 = d2 + arr[i][n - i - 1] + ''' Absolute difference of the sums + across the diagonals''' + + return abs(d1 - d2) + '''Driver Code''' + +n = 3 +arr = [[11, 2, 4], + [4 , 5, 6], + [10, 8, -12]] +print(difference(arr, n))" +Rearrange array such that even index elements are smaller and odd index elements are greater,"/*Java code to rearrange an array such +that even index elements are smaller +and odd index elements are greater +than their next.*/ + +class GFG { + + /*Rearrange*/ + + static void rearrange(int arr[], int n) + { + int temp; + for (int i = 0; i < n - 1; i++) { + if (i % 2 == 0 && arr[i] > arr[i + 1]) { + temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + } + if (i % 2 != 0 && arr[i] < arr[i + 1]) { + temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + } + } + }/* Utility that prints out an array in + a line */ + + static void printArray(int arr[], int size) + { + for (int i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + System.out.println(); + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 6, 4, 2, 1, 8, 3 }; + int n = arr.length; + System.out.print(""Before rearranging: \n""); + printArray(arr, n); + rearrange(arr, n); + System.out.print(""After rearranging: \n""); + printArray(arr, n); + } +}"," '''Python code to rearrange +an array such that +even index elements +are smaller and odd +index elements are +greater than their +next.''' + + '''Rearrange''' + +def rearrange(arr, n): + for i in range(n - 1): + if (i % 2 == 0 and arr[i] > arr[i + 1]): + temp = arr[i] + arr[i]= arr[i + 1] + arr[i + 1]= temp + if (i % 2 != 0 and arr[i] < arr[i + 1]): + temp = arr[i] + arr[i]= arr[i + 1] + arr[i + 1]= temp '''Utility that prints out an array in +a line''' + +def printArray(arr, size): + for i in range(size): + print(arr[i], "" "", end ="""") + print() + '''Driver code''' + +arr = [ 6, 4, 2, 1, 8, 3 ] +n = len(arr) +print(""Before rearranging: "") +printArray(arr, n) +rearrange(arr, n) +print(""After rearranging:"") +printArray(arr, n);" +Find Union and Intersection of two unsorted arrays,"/*Java program to find union and intersection +using similar Hashing Technique +without using any predefined Java Collections +Time Complexity best case & avg case = O(m+n) +Worst case = O(nlogn) +package com.arrays.math;*/ + +public class UnsortedIntersectionUnion { +/* Prints intersection of arr1[0..n1-1] and + arr2[0..n2-1]*/ + + public void findPosition(int a[], int b[]) + { + int v = (a.length + b.length); + int ans[] = new int[v]; + int zero1 = 0; + int zero2 = 0; + System.out.print(""Intersection : ""); +/* Iterate first array*/ + + for (int i = 0; i < a.length; i++) + zero1 = iterateArray(a, v, ans, i); +/* Iterate second array*/ + + for (int j = 0; j < b.length; j++) + zero2 = iterateArray(b, v, ans, j); + int zero = zero1 + zero2; + placeZeros(v, ans, zero); + printUnion(v, ans, zero); + } +/* Prints union of arr1[0..n1-1] and arr2[0..n2-1]*/ + + private void printUnion(int v, int[] ans, int zero) + { + int zero1 = 0; + System.out.print(""\nUnion : ""); + for (int i = 0; i < v; i++) { + if ((zero == 0 && ans[i] == 0) + || (ans[i] == 0 && zero1 > 0)) + continue; + if (ans[i] == 0) + zero1++; + System.out.print(ans[i] + "",""); + } + } + +/*placeZeroes function*/ + + private void placeZeros(int v, int[] ans, int zero) + { + if (zero == 2) { + System.out.println(""0""); + int d[] = { 0 }; + placeValue(d, ans, 0, 0, v); + } + if (zero == 1) { + int d[] = { 0 }; + placeValue(d, ans, 0, 0, v); + } + }/* Function to itreate array*/ + + private int iterateArray(int[] a, int v, int[] ans, + int i) + { + if (a[i] != 0) { + int p = a[i] % v; + placeValue(a, ans, i, p, v); + } + else + return 1; + return 0; + } +/*placeValue function*/ + + private void placeValue(int[] a, int[] ans, int i, + int p, int v) + { + p = p % v; + if (ans[p] == 0) + ans[p] = a[i]; + else { + if (ans[p] == a[i]) + System.out.print(a[i] + "",""); + else { +/* Hashing collision happened increment + position and do recursive call*/ + + p = p + 1; + placeValue(a, ans, i, p, v); + } + } + } +/* Driver code*/ + + public static void main(String args[]) + { + int a[] = { 7, 1, 5, 2, 3, 6 }; + int b[] = { 3, 8, 6, 20, 7 }; + UnsortedIntersectionUnion uiu + = new UnsortedIntersectionUnion(); + uiu.findPosition(a, b); + } +}"," '''Python3 program to find union and intersection +using similar Hashing Technique +without using any predefined Java Collections +Time Complexity best case & avg case = O(m+n) +Worst case = O(nlogn)''' + + '''Prints intersection of arr1[0..n1-1] and +arr2[0..n2-1]''' + +def findPosition(a, b): + v = len(a) + len(b); + ans = [0]*v; + zero1 = zero2 = 0; + print(""Intersection :"",end="" ""); ''' Iterate first array''' + + for i in range(len(a)): + zero1 = iterateArray(a, v, ans, i); + ''' Iterate second array''' + + for j in range(len(b)): + zero2 = iterateArray(b, v, ans, j); + zero = zero1 + zero2; + placeZeros(v, ans, zero); + printUnion(v, ans, zero); + '''Prints union of arr1[0..n1-1] and arr2[0..n2-1]''' + +def printUnion(v, ans,zero): + zero1 = 0; + print(""\nUnion :"",end="" ""); + for i in range(v): + if ((zero == 0 and ans[i] == 0) or + (ans[i] == 0 and zero1 > 0)): + continue; + if (ans[i] == 0): + zero1+=1; + print(ans[i],end="",""); + + '''placeZeroes function''' + +def placeZeros(v, ans, zero): + if (zero == 2): + print(""0""); + d = [0]; + placeValue(d, ans, 0, 0, v); + if (zero == 1): + d=[0]; + placeValue(d, ans, 0, 0, v); '''Function to itreate array''' + +def iterateArray(a,v,ans,i): + if (a[i] != 0): + p = a[i] % v; + placeValue(a, ans, i, p, v); + else: + return 1; + return 0; + + '''placeValue function''' + +def placeValue(a,ans,i,p,v): + p = p % v; + if (ans[p] == 0): + ans[p] = a[i]; + else: + if (ans[p] == a[i]): + print(a[i],end="",""); + else: ''' Hashing collision happened increment + position and do recursive call''' + + p = p + 1; + placeValue(a, ans, i, p, v); + '''Driver code''' + +a = [ 7, 1, 5, 2, 3, 6 ]; +b = [ 3, 8, 6, 20, 7 ]; +findPosition(a, b);" +Check whether a binary tree is a full binary tree or not | Iterative Approach,"/*Java implementation to check whether a binary +tree is a full binary tree or not*/ + +import java.util.*; +class GfG { +/*structure of a node of binary tree */ + +static class Node { + int data; + Node left, right; +} +/*function to get a new node */ + +static Node getNode(int data) +{ +/* allocate space */ + + Node newNode = new Node(); +/* put in the data */ + + newNode.data = data; + newNode.left = null; + newNode.right = null; + return newNode; +} +/*function to check whether a binary tree +is a full binary tree or not */ + +static boolean isFullBinaryTree(Node root) +{ +/* if tree is empty */ + + if (root == null) + return true; +/* queue used for level order traversal */ + + Queue q = new LinkedList (); +/* push 'root' to 'q' */ + + q.add(root); +/* traverse all the nodes of the binary tree + level by level until queue is empty */ + + while (!q.isEmpty()) { +/* get the pointer to 'node' at front + of queue */ + + Node node = q.peek(); + q.remove(); +/* if it is a leaf node then continue */ + + if (node.left == null && node.right == null) + continue; +/* if either of the child is not null and the + other one is null, then binary tree is not + a full binary tee */ + + if (node.left == null || node.right == null) + return false; +/* push left and right childs of 'node' + on to the queue 'q' */ + + q.add(node.left); + q.add(node.right); + } +/* binary tree is a full binary tee */ + + return true; +} +/*Driver program to test above */ + +public static void main(String[] args) +{ + Node root = getNode(1); + root.left = getNode(2); + root.right = getNode(3); + root.left.left = getNode(4); + root.left.right = getNode(5); + if (isFullBinaryTree(root)) + System.out.println(""Yes""); + else + System.out.println(""No""); +} +}"," '''Python3 program to find deepest +left leaf''' + + '''node class ''' + +class getNode: + '''put in the data ''' + + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''function to check whether a binary +tree is a full binary tree or not ''' + +def isFullBinaryTree( root) : + ''' if tree is empty ''' + + if (not root) : + return True + ''' queue used for level order + traversal ''' + + q = [] + ''' append 'root' to 'q' ''' + + q.append(root) + ''' traverse all the nodes of the + binary tree level by level + until queue is empty ''' + + while (not len(q)): + ''' get the pointer to 'node' + at front of queue ''' + + node = q[0] + q.pop(0) + ''' if it is a leaf node then continue ''' + + if (node.left == None and + node.right == None): + continue + ''' if either of the child is not None + and the other one is None, then + binary tree is not a full binary tee ''' + + if (node.left == None or + node.right == None): + return False + ''' append left and right childs + of 'node' on to the queue 'q' ''' + + q.append(node.left) + q.append(node.right) + ''' binary tree is a full binary tee ''' + + return True + '''Driver Code ''' + +if __name__ == '__main__': + root = getNode(1) + root.left = getNode(2) + root.right = getNode(3) + root.left.left = getNode(4) + root.left.right = getNode(5) + if (isFullBinaryTree(root)) : + print(""Yes"" ) + else: + print(""No"")" +Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer),"/*Java program to find lowest common ancestor using parent pointer*/ +import java.util.HashMap; +import java.util.Map; +/*A tree node*/ + +class Node +{ + int key; + Node left, right, parent; + Node(int key) + { + this.key = key; + left = right = parent = null; + } +} +class BinaryTree +{ + Node root, n1, n2, lca; + /* A utility function to insert a new node with + given key in Binary Search Tree */ + + Node insert(Node node, int key) + { + /* If the tree is empty, return a new node */ + + if (node == null) + return new Node(key); + /* Otherwise, recur down the tree */ + + if (key < node.key) + { + node.left = insert(node.left, key); + node.left.parent = node; + } + else if (key > node.key) + { + node.right = insert(node.right, key); + node.right.parent = node; + } + /* return the (unchanged) node pointer */ + + return node; + } +/* To find LCA of nodes n1 and n2 in Binary Tree*/ + + Node LCA(Node n1, Node n2) + { +/* Creata a map to store ancestors of n1*/ + + Map ancestors = new HashMap(); +/* Insert n1 and all its ancestors in map*/ + + while (n1 != null) + { + ancestors.put(n1, Boolean.TRUE); + n1 = n1.parent; + } +/* Check if n2 or any of its ancestors is in + map.*/ + + while (n2 != null) + { + if (ancestors.containsKey(n2) != ancestors.isEmpty()) + return n2; + n2 = n2.parent; + } + return null; + } +/* Driver method to test above functions*/ + + public static void main(String[] args) + { + BinaryTree tree = new BinaryTree(); + tree.root = tree.insert(tree.root, 20); + tree.root = tree.insert(tree.root, 8); + tree.root = tree.insert(tree.root, 22); + tree.root = tree.insert(tree.root, 4); + tree.root = tree.insert(tree.root, 12); + tree.root = tree.insert(tree.root, 10); + tree.root = tree.insert(tree.root, 14); + tree.n1 = tree.root.left.right.left; + tree.n2 = tree.root.left; + tree.lca = tree.LCA(tree.n1, tree.n2); + System.out.println(""LCA of "" + tree.n1.key + "" and "" + tree.n2.key + + "" is "" + tree.lca.key); + } +}", +Find the two repeating elements in a given array,"class RepeatElement +{/*Print Repeating function*/ + + void printRepeating(int arr[], int size) + { + int i, j; + System.out.println(""Repeated Elements are :""); + for (i = 0; i < size; i++) + { + for (j = i + 1; j < size; j++) + { + if (arr[i] == arr[j]) + System.out.print(arr[i] + "" ""); + } + } + }/*Driver Code*/ + + public static void main(String[] args) + { + RepeatElement repeat = new RepeatElement(); + int arr[] = {4, 2, 4, 5, 2, 3, 1}; + int arr_size = arr.length; + repeat.printRepeating(arr, arr_size); + } +}"," '''Python3 program to Find the two +repeating elements in a given array''' + + + '''Print Repeating function''' + +def printRepeating(arr, size): + print(""Repeating elements are "", + end = '') + for i in range (0, size): + for j in range (i + 1, size): + if arr[i] == arr[j]: + print(arr[i], end = ' ') '''Driver code''' + +arr = [4, 2, 4, 5, 2, 3, 1] +arr_size = len(arr) +printRepeating(arr, arr_size)" +XOR Linked List – A Memory Efficient Doubly Linked List | Set 2,, +Position of rightmost set bit,"/*Java program for above approach*/ + +import java.io.*; +class GFG{ +/*Function to find position of +rightmost set bit*/ + +public static int Last_set_bit(int n) +{ + int p = 1; +/* Iterate till number>0*/ + + while (n > 0) + { +/* Checking if last bit is set*/ + + if ((n & 1) > 0) + { + return p; + } +/* Increment position and + right shift number*/ + + p++; + n = n >> 1; + } +/* set bit not found.*/ + + return -1; +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int n = 18; +/* Function call*/ + + int pos = Last_set_bit(n); + if (pos != -1) + System.out.println(pos); + else + System.out.println(""0""); +} +}"," '''Python program for above approach''' '''Program to find position of +rightmost set bit''' + +def PositionRightmostSetbit( n): + p = 1 + ''' Iterate till number>0''' + + while(n > 0): + ''' Checking if last bit is set''' + + if(n&1): + return p + ''' Increment position and right shift number''' + + p += 1 + n = n>>1 + ''' set bit not found.''' + + return -1; + '''Driver Code''' + +n = 18 + '''Function call''' + +pos = PositionRightmostSetbit(n) +if(pos != -1): + print(pos) +else: + print(0)" +Swap bits in a given number,"class GFG +{ + static int swapBits(int num, int p1, int p2, int n) + { + int shift1, shift2, value1, value2; + while (n-- > 0) + { +/* Setting bit at p1 position to 1*/ + + shift1 = 1 << p1; +/* Setting bit at p2 position to 1*/ + + shift2 = 1 << p2; +/* value1 and value2 will have 0 if num + at the respective positions - p1 and p2 is 0.*/ + + value1 = ((num & shift1)); + value2 = ((num & shift2)); +/* check if value1 and value2 are different + i.e. at one position bit is set and other it is not*/ + + if ((value1 == 0 && value2 != 0) || + (value2 == 0 && value1 != 0)) + { +/* if bit at p1 position is set*/ + + if (value1 != 0) + { +/* unset bit at p1 position*/ + + num = num & (~shift1); +/* set bit at p2 position*/ + + num = num | shift2; + } +/* if bit at p2 position is set*/ + + else + { +/* set bit at p2 position*/ + + num = num & (~shift2); +/* unset bit at p2 position*/ + + num = num | shift1; + } + } + p1++; + p2++; + } +/* return final result*/ + + return num; + } +/* Driver code*/ + + public static void main(String[] args) + { + int res = swapBits(28, 0, 3, 2); + System.out.println(""Result = "" + res); + } +}","def swapBits(num, p1, p2, n): + shift1 = 0 + shift2 = 0 + value1 = 0 + value2 = 0 + while(n > 0): + ''' Setting bit at p1 position to 1''' + + shift1 = 1 << p1 + ''' Setting bit at p2 position to 1''' + + shift2 = 1 << p2 + ''' value1 and value2 will have 0 if num + at the respective positions - p1 and p2 is 0.''' + + value1 = ((num & shift1)) + value2 = ((num & shift2)) + ''' check if value1 and value2 are different + i.e. at one position bit is set and other it is not''' + + if((value1 == 0 and value2 != 0) or (value2 == 0 and value1 != 0)): + ''' if bit at p1 position is set''' + + if(value1 != 0): + ''' unset bit at p1 position''' + + num = num & (~shift1) + ''' set bit at p2 position''' + + num = num | shift2 + ''' if bit at p2 position is set''' + + else: + ''' set bit at p2 position''' + + num = num & (~shift2) + ''' unset bit at p2 position''' + + num = num | shift1 + p1 += 1 + p2 += 1 + n -= 1 + ''' return final result''' + + return num + '''Driver code''' + +res = swapBits(28, 0, 3, 2) +print(""Result ="", res)" +Rearrange positive and negative numbers with constant extra space,"/*Java implementation of the above approach*/ + +import java.io.*; +class GFG +{ + public static void RearrangePosNeg(int arr[]) + { + int i=0; + int j=arr.length-1; + while(true) + { +/* Loop until arr[i] < 0 and + still inside the array*/ + + while(arr[i]<0 && i 0 and + still inside the array*/ + + while(arr[j]>0 && j>=0) + j--; +/* if i is less than j*/ + + if(i 0 and + still inside the array''' + + while (arr[j] > 0 and j >= 0): + j-=1 + ''' if i is less than j''' + + if (i < j): + arr[i],arr[j] = arr[j],arr[i] + else: + break + '''Driver Code''' + +arr=[-12, 11, -13, -5, 6, -7, 5, -3, -6] +n=len(arr) +RearrangePosNeg(arr, n) +print(*arr)" +Vertical width of Binary tree | Set 2,"/* Java code to find the vertical width of a binary tree */ + +import java.io.*; +import java.util.*; +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* Function to fill hd in set. */ + + void fillSet(Node root,Set set,int hd) + { + if(root == null) return; + fillSet(root.left,set,hd - 1); + set.add(hd); + fillSet(root.right,set,hd + 1); + } + int verticalWidth(Node root) + { + Set set = new HashSet(); +/* Third parameter is horizontal distance */ + + fillSet(root,set,0); + return set.size(); + } + /* Driver program to test above functions */ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + /* + Constructed bunary tree is: + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 + */ + + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(8); + tree.root.right.right.left = new Node(6); + tree.root.right.right.right = new Node(7); + System.out.println(tree.verticalWidth(tree.root)); + } +}"," '''Python code to find vertical +width of a binary tree''' + + + ''' A binary tree node has data, +pointer to left child and a +pointer to right child ''' + +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to fill hd in set. ''' + +def fillSet(root, s, hd): + if (not root): + return + fillSet(root.left, s, hd - 1) + s.add(hd) + fillSet(root.right, s, hd + 1) +def verticalWidth(root): + s = set() + ''' Third parameter is horizontal + distance ''' + + fillSet(root, s, 0) + return len(s) + + ''' Driver Code''' + +if __name__ == '__main__': ''' Creating the above tree ''' + + root = Node(1) + root.left = Node(2) + root.right = Node(3) + root.left.left = Node(4) + root.left.right = Node(5) + root.right.left = Node(6) + root.right.right = Node(7) + root.right.left.right = Node(8) + root.right.right.right = Node(9) + print(verticalWidth(root))" +Form minimum number from given sequence,"/*Java program of above approach*/ + +import java.io.IOException; +public class Test +{ +/* Returns minimum number made from given sequence without repeating digits*/ + + static String getMinNumberForPattern(String seq) + { + int n = seq.length(); + if (n >= 9) + return ""-1""; + char result[] = new char[n + 1]; + int count = 1; +/* The loop runs for each input character as well as + one additional time for assigning rank to each remaining characters*/ + + for (int i = 0; i <= n; i++) + { + if (i == n || seq.charAt(i) == 'I') + { + for (int j = i - 1; j >= -1; j--) + { + result[j + 1] = (char) ((int) '0' + count++); + if (j >= 0 && seq.charAt(j) == 'I') + break; + } + } + } + return new String(result); + } +/*Driver Code*/ + + public static void main(String[] args) throws IOException + { + String inputs[] = { ""IDID"", ""I"", ""DD"", ""II"", ""DIDI"", ""IIDDD"", ""DDIDDIID"" }; + for(String input : inputs) + { + System.out.println(getMinNumberForPattern(input)); + } + } +}"," '''Python3 program of above approach''' + + '''Returns minimum number made from +given sequence without repeating digits''' + +def getMinNumberForPattern(seq): + n = len(seq) + if (n >= 9): + return ""-1"" + result = [None] * (n + 1) + count = 1 ''' The loop runs for each input character + as well as one additional time for + assigning rank to remaining characters''' + + for i in range(n + 1): + if (i == n or seq[i] == 'I'): + for j in range(i - 1, -2, -1): + result[j + 1] = int('0' + str(count)) + count += 1 + if(j >= 0 and seq[j] == 'I'): + break + return result + '''Driver Code''' + +if __name__ == '__main__': + inputs = [""IDID"", ""I"", ""DD"", ""II"", + ""DIDI"", ""IIDDD"", ""DDIDDIID""] + for Input in inputs: + print(*(getMinNumberForPattern(Input)))" +Doubly Linked List | Set 1 (Introduction and Insertion),"/* Given a node as prev_node, insert a new node after the given node */ + +public void InsertAfter(Node prev_Node, int new_data) +{ + + /*1. check if the given prev_node is NULL */ + + if (prev_Node == null) { + System.out.println(""The given previous node cannot be NULL ""); + return; + } + + /* 2. allocate node + * 3. put in the data */ + + Node new_node = new Node(new_data); + + /* 4. Make next of new node as next of prev_node */ + + new_node.next = prev_Node.next; + + /* 5. Make the next of prev_node as new_node */ + + prev_Node.next = new_node; + + /* 6. Make prev_node as previous of new_node */ + + new_node.prev = prev_Node; + + /* 7. Change previous of new_node's next node */ + + if (new_node.next != null) + new_node.next.prev = new_node; +} +"," '''Given a node as prev_node, insert +a new node after the given node''' + + +def insertAfter(self, prev_node, new_data): + + ''' 1. check if the given prev_node is NULL''' + + if prev_node is None: + print(""This node doesn't exist in DLL"") + return + + ''' 2. allocate node & 3. put in the data''' + + new_node = Node(data = new_data) + + ''' 4. Make next of new node as next of prev_node''' + + new_node.next = prev_node.next + + ''' 5. Make the next of prev_node as new_node''' + + prev_node.next = new_node + + ''' 6. Make prev_node as previous of new_node''' + + new_node.prev = prev_node + + ''' 7. Change previous of new_node's next node */''' + + if new_node.next is not None: + new_node.next.prev = new_node + + +" +Count of Array elements greater than all elements on its left and at least K elements on its right,"/*Java program to implement +the above appraoch*/ + +class GFG{ + +/*Structure of an AVL Tree Node*/ + +static class Node +{ + int key; + Node left; + Node right; + int height; + +/* Size of the tree rooted + with this Node*/ + + int size; + + public Node(int key) + { + this.key = key; + this.left = this.right = null; + this.size = this.height = 1; + } +}; + +/*Helper class to pass Integer +as referencee*/ + +static class RefInteger +{ + Integer value; + + public RefInteger(Integer value) + { + this.value = value; + } +} + +/*Utility function to get height +of the tree rooted with N*/ + +static int height(Node N) +{ + if (N == null) + return 0; + + return N.height; +} + +/*Utility function to find size of +the tree rooted with N*/ + +static int size(Node N) +{ + if (N == null) + return 0; + + return N.size; +} + +/*Utility function to get maximum +of two integers*/ + +static int max(int a, int b) +{ + return (a > b) ? a : b; +} + +/*Utility function to right rotate +subtree rooted with y*/ + +static Node rightRotate(Node y) +{ + Node x = y.left; + Node T2 = x.right; + +/* Perform rotation*/ + + x.right = y; + y.left = T2; + +/* Update heights*/ + + y.height = max(height(y.left), + height(y.right)) + 1; + x.height = max(height(x.left), + height(x.right)) + 1; + +/* Update sizes*/ + + y.size = size(y.left) + + size(y.right) + 1; + x.size = size(x.left) + + size(x.right) + 1; + +/* Return new root*/ + + return x; +} + +/*Utility function to left rotate +subtree rooted with x*/ + +static Node leftRotate(Node x) +{ + Node y = x.right; + Node T2 = y.left; + +/* Perform rotation*/ + + y.left = x; + x.right = T2; + +/* Update heights*/ + + x.height = max(height(x.left), + height(x.right)) + 1; + y.height = max(height(y.left), + height(y.right)) + 1; + +/* Update sizes*/ + + x.size = size(x.left) + + size(x.right) + 1; + y.size = size(y.left) + + size(y.right) + 1; + +/* Return new root*/ + + return y; +} + +/*Function to obtain Balance factor +of Node N*/ + +static int getBalance(Node N) +{ + if (N == null) + return 0; + + return height(N.left) - + height(N.right); +} + +/*Function to insert a new key to the +tree rooted with Node*/ + +static Node insert(Node Node, int key, + RefInteger count) +{ + +/* Perform the normal BST rotation*/ + + if (Node == null) + return (new Node(key)); + + if (key < Node.key) + Node.left = insert(Node.left, + key, count); + else + { + Node.right = insert(Node.right, + key, count); + +/* Update count of smaller elements*/ + + count.value = count.value + + size(Node.left) + 1; + } + +/* Update height and size of the ancestor*/ + + Node.height = max(height(Node.left), + height(Node.right)) + 1; + Node.size = size(Node.left) + + size(Node.right) + 1; + +/* Get the balance factor of the ancestor*/ + + int balance = getBalance(Node); + +/* Left Left Case*/ + + if (balance > 1 && key < Node.left.key) + return rightRotate(Node); + +/* Right Right Case*/ + + if (balance < -1 && key > Node.right.key) + return leftRotate(Node); + +/* Left Right Case*/ + + if (balance > 1 && key > Node.left.key) + { + Node.left = leftRotate(Node.left); + return rightRotate(Node); + } + +/* Right Left Case*/ + + if (balance < -1 && key < Node.right.key) + { + Node.right = rightRotate(Node.right); + return leftRotate(Node); + } + return Node; +} + +/*Function to generate an array which +contains count of smaller elements +on the right*/ + +static void constructLowerArray(int arr[], + RefInteger[] countSmaller, int n) +{ + int i, j; + Node root = null; + + for(i = 0; i < n; i++) + countSmaller[i] = new RefInteger(0); + +/* Insert all elements in the AVL Tree + and get the count of smaller elements*/ + + for(i = n - 1; i >= 0; i--) + { + root = insert(root, arr[i], + countSmaller[i]); + } +} + +/*Function to find the number +of elements which are greater +than all elements on its left +and K elements on its right*/ + +static int countElements(int A[], int n, + int K) +{ + int count = 0; + +/* Stores the count of smaller + elements on its right*/ + + RefInteger[] countSmaller = new RefInteger[n]; + constructLowerArray(A, countSmaller, n); + + int maxi = Integer.MIN_VALUE; + for(int i = 0; i <= (n - K - 1); i++) + { + if (A[i] > maxi && + countSmaller[i].value >= K) + { + count++; + maxi = A[i]; + } + } + return count; +} + +/*Driver Code*/ + +public static void main(String[] args) +{ + int A[] = { 2, 5, 1, 7, 3, 4, 0 }; + int n = A.length; + int K = 3; + + System.out.println(countElements(A, n, K)); +} +} + + +", +Check whether a binary tree is a full binary tree or not,"/*Java program to check if binay tree is full or not*/ + +/* Tree node structure */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree +{ + Node root; + /* this function checks if a binary tree is full or not */ + + boolean isFullTree(Node node) + { +/* if empty tree*/ + + if(node == null) + return true; +/* if leaf node*/ + + if(node.left == null && node.right == null ) + return true; +/* if both left and right subtrees are not null + the are full*/ + + if((node.left!=null) && (node.right!=null)) + return (isFullTree(node.left) && isFullTree(node.right)); +/* if none work*/ + + return false; + } +/* Driver program*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(20); + tree.root.right = new Node(30); + tree.root.left.right = new Node(40); + tree.root.left.left = new Node(50); + tree.root.right.left = new Node(60); + tree.root.left.left.left = new Node(80); + tree.root.right.right = new Node(70); + tree.root.left.left.right = new Node(90); + tree.root.left.right.left = new Node(80); + tree.root.left.right.right = new Node(90); + tree.root.right.left.left = new Node(80); + tree.root.right.left.right = new Node(90); + tree.root.right.right.left = new Node(80); + tree.root.right.right.right = new Node(90); + if(tree.isFullTree(tree.root)) + System.out.print(""The binary tree is full""); + else + System.out.print(""The binary tree is not full""); + } +}"," '''Python program to check whether given Binary tree is full or not +Tree node structure''' + + + ''' Constructor of the node class for creating the node''' +class Node: + def __init__(self , key): + self.key = key + self.left = None + self.right = None + '''Checks if the binary tree is full or not''' + +def isFullTree(root): + ''' If empty tree''' + + if root is None: + return True + ''' If leaf node''' + + if root.left is None and root.right is None: + return True + ''' If both left and right subtress are not None and + left and right subtress are full''' + + if root.left is not None and root.right is not None: + return (isFullTree(root.left) and isFullTree(root.right)) + ''' We reach here when none of the above if condiitions work''' + + return False + '''Driver Program''' + +root = Node(10); +root.left = Node(20); +root.right = Node(30); +root.left.right = Node(40); +root.left.left = Node(50); +root.right.left = Node(60); +root.right.right = Node(70); +root.left.left.left = Node(80); +root.left.left.right = Node(90); +root.left.right.left = Node(80); +root.left.right.right = Node(90); +root.right.left.left = Node(80); +root.right.left.right = Node(90); +root.right.right.left = Node(80); +root.right.right.right = Node(90); +if isFullTree(root): + print ""The Binary tree is full"" +else: + print ""Binary tree is not full""" +Doubly Linked List | Set 1 (Introduction and Insertion),"/* Given a node as prev_node, insert a new node after the given node */ + +public void InsertAfter(Node prev_Node, int new_data) +{ + /*1. check if the given prev_node is NULL */ + + if (prev_Node == null) { + System.out.println(""The given previous node cannot be NULL ""); + return; + } + /* 2. allocate node + * 3. put in the data */ + + Node new_node = new Node(new_data); + /* 4. Make next of new node as next of prev_node */ + + new_node.next = prev_Node.next; + /* 5. Make the next of prev_node as new_node */ + + prev_Node.next = new_node; + /* 6. Make prev_node as previous of new_node */ + + new_node.prev = prev_Node; + /* 7. Change previous of new_node's next node */ + + if (new_node.next != null) + new_node.next.prev = new_node; +}"," '''Given a node as prev_node, insert +a new node after the given node''' + +def insertAfter(self, prev_node, new_data): + ''' 1. check if the given prev_node is NULL''' + + if prev_node is None: + print(""This node doesn't exist in DLL"") + return + ''' 2. allocate node & 3. put in the data''' + + new_node = Node(data = new_data) + ''' 4. Make next of new node as next of prev_node''' + + new_node.next = prev_node.next + ''' 5. Make the next of prev_node as new_node''' + + prev_node.next = new_node + ''' 6. Make prev_node as previous of new_node''' + + new_node.prev = prev_node + ''' 7. Change previous of new_node's next node */''' + + if new_node.next is not None: + new_node.next.prev = new_node" +Unique cells in a binary matrix,"/*Efficient Java program to count unique +cells in a binary matrix*/ + +class GFG { + static final int MAX = 100; +/* Returns true if mat[i][j] is unique*/ + +static boolean isUnique(int mat[][], int i, int j, + int n, int m) +{ +/* checking in row calculating sumrow + will be moving column wise*/ + + int sumrow = 0; + for (int k = 0; k < m; k++) { + sumrow += mat[i][k]; + if (sumrow > 1) + return false; + } +/* checking in column calculating sumcol + will be moving row wise*/ + + int sumcol = 0; + for (int k = 0; k < n; k++) { + sumcol += mat[k][j]; + if (sumcol > 1) + return false; + } + return true; +} +static int countUnique(int mat[][], int n, int m) +{ + int uniquecount = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (mat[i][j]!=0 && + isUnique(mat, i, j, n, m)) + uniquecount++; + return uniquecount; +} +/*Driver code*/ + + static public void main(String[] args) { + int mat[][] = {{0, 1, 0, 0}, + {0, 0, 1, 0}, + {1, 0, 0, 1}}; + System.out.print(countUnique(mat, 3, 4)); + } +}"," '''Python3 program to count unique cells in +a matrix''' + +MAX = 100 + '''Returns true if mat[i][j] is unique''' + +def isUnique(mat, i, j, n, m): + ''' checking in row calculating sumrow + will be moving column wise''' + + sumrow = 0 + for k in range(m): + sumrow += mat[i][k] + if (sumrow > 1): + return False + ''' checking in column calculating sumcol + will be moving row wise''' + + sumcol = 0 + for k in range(n): + sumcol += mat[k][j] + if (sumcol > 1): + return False + return True +def countUnique(mat, n, m): + uniquecount = 0 + for i in range(n): + for j in range(m): + if (mat[i][j] and isUnique(mat, i, j, n, m)): + uniquecount += 1 + return uniquecount + '''Driver code''' + +mat = [[0, 1, 0, 0], + [0, 0, 1, 0], + [1, 0, 0, 1]] +print(countUnique(mat, 3, 4))" +Shortest distance between two nodes in BST,"/*Java program to find distance between +two nodes in BST*/ + +class GfG { +static class Node { + Node left, right; + int key; +} +static Node newNode(int key) +{ + Node ptr = new Node(); + ptr.key = key; + ptr.left = null; + ptr.right = null; + return ptr; +} +/*Standard BST insert function*/ + +static Node insert(Node root, int key) +{ + if (root == null) + root = newNode(key); + else if (root.key > key) + root.left = insert(root.left, key); + else if (root.key < key) + root.right = insert(root.right, key); + return root; +} +/*This function returns distance of x from +root. This function assumes that x exists +in BST and BST is not NULL.*/ + +static int distanceFromRoot(Node root, int x) +{ + if (root.key == x) + return 0; + else if (root.key > x) + return 1 + distanceFromRoot(root.left, x); + return 1 + distanceFromRoot(root.right, x); +} +/*Returns minimum distance beween a and b. +This function assumes that a and b exist +in BST.*/ + +static int distanceBetween2(Node root, int a, int b) +{ + if (root == null) + return 0; +/* Both keys lie in left*/ + + if (root.key > a && root.key > b) + return distanceBetween2(root.left, a, b); +/* Both keys lie in right +same path*/ + +if (root.key < a && root.key < b) + return distanceBetween2(root.right, a, b); +/* Lie in opposite directions (Root is + LCA of two nodes)*/ + + if (root.key >= a && root.key <= b) + return distanceFromRoot(root, a) + distanceFromRoot(root, b); + return 0; +} +/*This function make sure that a is smaller +than b before making a call to findDistWrapper()*/ + +static int findDistWrapper(Node root, int a, int b) +{ + int temp = 0; +if (a > b) + { + temp = a; + a = b; + b = temp; + } +return distanceBetween2(root, a, b); +} +/*Driver code*/ + +public static void main(String[] args) +{ + Node root = null; + root = insert(root, 20); + insert(root, 10); + insert(root, 5); + insert(root, 15); + insert(root, 30); + insert(root, 25); + insert(root, 35); + System.out.println(findDistWrapper(root, 5, 35)); +} +}"," '''Python3 program to find distance between +two nodes in BST''' + +class newNode: + def __init__(self, data): + self.key = data + self.left = None + self.right = None '''Standard BST insert function''' + +def insert(root, key): + if root == None: + root = newNode(key) + elif root.key > key: + root.left = insert(root.left, key) + elif root.key < key: + root.right = insert(root.right, key) + return root + '''This function returns distance of x from +root. This function assumes that x exists +in BST and BST is not NULL.''' + +def distanceFromRoot(root, x): + if root.key == x: + return 0 + elif root.key > x: + return 1 + distanceFromRoot(root.left, x) + return 1 + distanceFromRoot(root.right, x) + '''Returns minimum distance beween a and b. +This function assumes that a and b exist +in BST.''' + +def distanceBetween2(root, a, b): + if root == None: + return 0 + ''' Both keys lie in left''' + + if root.key > a and root.key > b: + return distanceBetween2(root.left, a, b) + ''' Both keys lie in right +same path''' + + if root.key < a and root.key < b: + return distanceBetween2(root.right, a, b) + ''' Lie in opposite directions + (Root is LCA of two nodes)''' + + if root.key >= a and root.key <= b: + return (distanceFromRoot(root, a) + + distanceFromRoot(root, b)) + '''This function make sure that a is smaller +than b before making a call to findDistWrapper()''' + +def findDistWrapper(root, a, b): + if a > b: + a, b = b, a + return distanceBetween2(root, a, b) + '''Driver code''' + +if __name__ == '__main__': + root = None + root = insert(root, 20) + insert(root, 10) + insert(root, 5) + insert(root, 15) + insert(root, 30) + insert(root, 25) + insert(root, 35) + a, b = 5, 55 + print(findDistWrapper(root, 5, 35))" +Find pair with greatest product in array,"/*Java program to find a pair +with product in given array.*/ + +import java.io.*; +class GFG{ +/*Function to find greatest number that us*/ + +static int findGreatest( int []arr , int n) +{ + int result = -1; + for (int i = 0; i < n ; i++) + for (int j = 0; j < n-1; j++) + for (int k = j+1 ; k < n ; k++) + if (arr[j] * arr[k] == arr[i]) + result = Math.max(result, arr[i]); + return result; +} +/* Driver code*/ + + static public void main (String[] args) + { + int []arr = {30, 10, 9, 3, 35}; + int n = arr.length; + System.out.println(findGreatest(arr, n)); + } +}"," '''Python 3 program to find a pair +with product in given array.''' + + '''Function to find greatest number''' + +def findGreatest( arr , n): + result = -1 + for i in range(n): + for j in range(n - 1): + for k in range(j + 1, n): + if (arr[j] * arr[k] == arr[i]): + result = max(result, arr[i]) + return result '''Driver code''' + +if __name__ == ""__main__"": + arr = [ 30, 10, 9, 3, 35] + n = len(arr) + print(findGreatest(arr, n))" +Count number of bits to be flipped to convert A to B,"/*Count number of bits to be flipped +to convert A into B*/ + +import java.util.*; +class Count { +/* Function that count set bits*/ + + public static int countSetBits(int n) + { + int count = 0; + while (n != 0) { + count++; + n &=(n-1); + } + return count; + } +/* Function that return count of + flipped number*/ + + public static int FlippedCount(int a, int b) + { +/* Return count of set bits in + a XOR b*/ + + return countSetBits(a ^ b); + } +/* Driver code*/ + + public static void main(String[] args) + { + int a = 10; + int b = 20; + System.out.print(FlippedCount(a, b)); + } +}"," '''Count number of bits to be flipped +to convert A into B + ''' '''Function that count set bits''' + +def countSetBits( n ): + count = 0 + while n: + count += 1 + n &= (n-1) + return count + '''Function that return count of +flipped number''' + +def FlippedCount(a , b): + ''' Return count of set bits in + a XOR b''' + + return countSetBits(a^b) + '''Driver code''' + +a = 10 +b = 20 +print(FlippedCount(a, b))" +Sort the biotonic doubly linked list,"/*Java implementation to sort the +biotonic doubly linked list*/ + +class GFG +{ +/*a node of the doubly linked list*/ + +static class Node +{ + int data; + Node next; + Node prev; +} +/*Function to reverse a Doubly Linked List*/ + +static Node reverse( Node head_ref) +{ + Node temp = null; + Node current = head_ref; +/* swap next and prev for all nodes + of doubly linked list*/ + + while (current != null) + { + temp = current.prev; + current.prev = current.next; + current.next = temp; + current = current.prev; + } +/* Before changing head, check for the cases + like empty list and list with only one node*/ + + if (temp != null) + head_ref = temp.prev; + return head_ref; +} +/*Function to merge two sorted doubly linked lists*/ + +static Node merge(Node first, Node second) +{ +/* If first linked list is empty*/ + + if (first == null) + return second; +/* If second linked list is empty*/ + + if (second == null) + return first; +/* Pick the smaller value*/ + + 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; + } +} +/*function to sort a biotonic doubly linked list*/ + +static Node sort(Node head) +{ +/* if list is empty or if it contains + a single node only*/ + + if (head == null || head.next == null) + return head; + Node current = head.next; + while (current != null) + { +/* if true, then 'current' is the first node + which is smaller than its previous node*/ + + if (current.data < current.prev.data) + break; +/* move to the next node*/ + + current = current.next; + } +/* if true, then list is already sorted*/ + + if (current == null) + return head; +/* spilt into two lists, one starting with 'head' + and other starting with 'current'*/ + + current.prev.next = null; + current.prev = null; +/* reverse the list starting with 'current'*/ + + current = reverse(current); +/* merge the two lists and return the + final merged doubly linked list*/ + + return merge(head, current); +} +/*Function to insert a node at the beginning +of the Doubly Linked List*/ + +static Node push( Node head_ref, int new_data) +{ +/* allocate node*/ + + Node new_node = new Node(); +/* put in the data*/ + + new_node.data = new_data; +/* since we are adding at the beginning, + prev is always null*/ + + new_node.prev = null; +/* link the old list off the new node*/ + + new_node.next = (head_ref); +/* change prev of head node to new node*/ + + if ((head_ref) != null) + (head_ref).prev = new_node; +/* move the head to point to the new node*/ + + (head_ref) = new_node; + return head_ref; +} +/*Function to print nodes in a given doubly +linked list*/ + +static void printList( Node head) +{ +/* if list is empty*/ + + if (head == null) + System.out.println(""Doubly Linked list empty""); + while (head != null) + { + System.out.print(head.data + "" ""); + head = head.next; + } +} +/*Driver Code*/ + +public static void main(String args[]) +{ + Node head = null; +/* Create the doubly linked list: + 2<.5<.7<.12<.10<.6<.4<.1*/ + + head = push(head, 1); + head = push(head, 4); + head = push(head, 6); + head = push(head, 10); + head = push(head, 12); + head = push(head, 7); + head = push(head, 5); + head = push(head, 2); + System.out.println(""Original Doubly linked list:n""); + printList(head); +/* sort the biotonic DLL*/ + + head = sort(head); + System.out.println(""\nDoubly linked list after sorting:n""); + printList(head); +} +}"," '''Python implementation to sort the +biotonic doubly linked list''' + + '''Node of a doubly linked list''' + +class Node: + def __init__(self, next = None, prev = None, + data = None): + self.next = next + self.prev = prev + self.data = data '''Function to reverse a Doubly Linked List''' + +def reverse( head_ref): + temp = None + current = head_ref + ''' swap next and prev for all nodes + of doubly linked list''' + + while (current != None): + temp = current.prev + current.prev = current.next + current.next = temp + current = current.prev + ''' Before changing head, check for the cases + like empty list and list with only one node''' + + if (temp != None): + head_ref = temp.prev + return head_ref + '''Function to merge two sorted doubly linked lists''' + +def merge( first, second): + ''' If first linked list is empty''' + + if (first == None): + return second + ''' If second linked list is empty''' + + if (second == None): + return first + ''' Pick the smaller value''' + + if (first.data < second.data): + first.next = merge(first.next, second) + first.next.prev = first + first.prev = None + return first + else: + second.next = merge(first, second.next) + second.next.prev = second + second.prev = None + return second + '''function to sort a biotonic doubly linked list''' + +def sort( head): + ''' if list is empty or if it contains + a single node only''' + + if (head == None or head.next == None): + return head + current = head.next + while (current != None) : + ''' if true, then 'current' is the first node + which is smaller than its previous node''' + + if (current.data < current.prev.data): + break + ''' move to the next node''' + + current = current.next + ''' if true, then list is already sorted''' + + if (current == None): + return head + ''' spilt into two lists, one starting with 'head' + and other starting with 'current' ''' + current.prev.next = None + current.prev = None + ''' reverse the list starting with 'current' ''' + current = reverse(current) + ''' merge the two lists and return the + final merged doubly linked list''' + + return merge(head, current) + '''Function to insert a node at the beginning +of the Doubly Linked List''' + +def push( head_ref, new_data): + ''' allocate node''' + + new_node =Node() + ''' put in the data''' + + new_node.data = new_data + ''' since we are adding at the beginning, + prev is always None''' + + new_node.prev = None + ''' link the old list off the new node''' + + new_node.next = (head_ref) + ''' change prev of head node to new node''' + + if ((head_ref) != None): + (head_ref).prev = new_node + ''' move the head to point to the new node''' + + (head_ref) = new_node + return head_ref + '''Function to print nodes in a given doubly +linked list''' + +def printList( head): + ''' if list is empty''' + + if (head == None): + print(""Doubly Linked list empty"") + while (head != None): + print(head.data, end= "" "") + head = head.next + '''Driver Code''' + +head = None + '''Create the doubly linked list: +2<.5<.7<.12<.10<.6<.4<.1''' + +head = push(head, 1) +head = push(head, 4) +head = push(head, 6) +head = push(head, 10) +head = push(head, 12) +head = push(head, 7) +head = push(head, 5) +head = push(head, 2) +print(""Original Doubly linked list:n"") +printList(head) + '''sort the biotonic DLL''' + +head = sort(head) +print(""\nDoubly linked list after sorting:"") +printList(head)" +Egg Dropping Puzzle | DP-11,"public class GFG { + /* Function to get minimum number of + trials needed in worst case with n + eggs and k floors */ + + static int eggDrop(int n, int k) + { +/* If there are no floors, then + no trials needed. OR if there + is one floor, one trial needed.*/ + + if (k == 1 || k == 0) + return k; +/* We need k trials for one egg + and k floors*/ + + if (n == 1) + return k; + int min = Integer.MAX_VALUE; + int x, res; +/* Consider all droppings from + 1st floor to kth floor and + return the minimum of these + values plus 1.*/ + + for (x = 1; x <= k; x++) { + res = Math.max(eggDrop(n - 1, x - 1), + eggDrop(n, k - x)); + if (res < min) + min = res; + } + return min + 1; + } +/* Driver code*/ + + public static void main(String args[]) + { + int n = 2, k = 10; + System.out.print(""Minimum number of "" + + ""trials in worst case with "" + + n + "" eggs and "" + k + + "" floors is "" + eggDrop(n, k)); + } + +}","import sys + '''Function to get minimum number of trials +needed in worst case with n eggs and k floors''' + +def eggDrop(n, k): + ''' If there are no floors, then no trials + needed. OR if there is one floor, one + trial needed.''' + + if (k == 1 or k == 0): + return k + ''' We need k trials for one egg + and k floors''' + + if (n == 1): + return k + min = sys.maxsize + ''' Consider all droppings from 1st + floor to kth floor and return + the minimum of these values plus 1.''' + + for x in range(1, k + 1): + res = max(eggDrop(n - 1, x - 1), + eggDrop(n, k - x)) + if (res < min): + min = res + return min + 1 + '''Driver Code''' + +if __name__ == ""__main__"": + n = 2 + k = 10 + print(""Minimum number of trials in worst case with"", + n, ""eggs and"", k, ""floors is"", eggDrop(n, k))" +Maximum equlibrium sum in an array,"/*Java program to find maximum equilibrium +sum.*/ + +import java.lang.Math.*; +import java.util.stream.*; +class GFG { +/* Function to find maximum equilibrium + sum.*/ + + static int findMaxSum(int arr[], int n) + { + int sum = IntStream.of(arr).sum(); + int prefix_sum = 0, + res = Integer.MIN_VALUE; + for (int i = 0; i < n; i++) + { + prefix_sum += arr[i]; + if (prefix_sum == sum) + res = Math.max(res, prefix_sum); + sum -= arr[i]; + } + return res; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int arr[] = { -2, 5, 3, 1, + 2, 6, -4, 2 }; + int n = arr.length; + System.out.print(findMaxSum(arr, n)); + } +}"," '''Python3 program to find +maximum equilibrium sum.''' + +import sys + '''Function to find +maximum equilibrium sum.''' + +def findMaxSum(arr,n): + ss = sum(arr) + prefix_sum = 0 + res = -sys.maxsize + for i in range(n): + prefix_sum += arr[i] + if prefix_sum == ss: + res = max(res, prefix_sum); + ss -= arr[i]; + return res + '''Driver code ''' + +if __name__==""__main__"": + arr = [ -2, 5, 3, 1, + 2, 6, -4, 2 ] + n = len(arr) + print(findMaxSum(arr, n))" +Smallest element repeated exactly ‘k’ times (not limited to small range),"/*Java program to find the smallest element +with frequency exactly k.*/ + +import java.util.*; +class GFG { + public static int smallestKFreq(int a[], int n, int k) + { + HashMap m = new HashMap(); +/* Map is used to store the count of + elements present in the array*/ + + for (int i = 0; i < n; i ++) + if (m.containsKey(a[i])) + m.put(a[i], m.get(a[i]) + 1); + else m.put(a[i], 1); +/* Traverse the map and find minimum + element with frequency k.*/ + + int res = Integer.MAX_VALUE; + Set s = m.keySet(); + for (int temp : s) + if (m.get(temp) == k) + res = Math.min(res, temp); + return (res != Integer.MAX_VALUE)? res : -1; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = { 2, 2, 1, 3, 1 }; + int k = 2; + System.out.println(smallestKFreq(arr, arr.length, k)); + } + }"," '''Python program to find the smallest element +with frequency exactly k. ''' +from collections import defaultdict +import sys + +def smallestKFreq(arr, n, k): + mp = defaultdict(lambda : 0) + ''' Map is used to store the count of + elements present in the array ''' + + for i in range(n): + mp[arr[i]] += 1 + ''' Traverse the map and find minimum + element with frequency k. ''' + + res = sys.maxsize + res1 = sys.maxsize + for key,values in mp.items(): + if values == k: + res = min(res, key) + return res if res != res1 else -1 + '''Driver code''' + +arr = [2, 2, 1, 3, 1] +k = 2 +n = len(arr) +print(smallestKFreq(arr, n, k))" +Find the smallest missing number,"/*Java Program for above approach*/ + +import java.io.*; +class GFG +{ +/* Program to find missing element*/ + + int findFirstMissing(int[] arr , int start , + int end, int first) + { + if (start < end) + { + int mid = (start+end)/2; + /** Index matches with value + at that index, means missing + element cannot be upto that point */ + + if (arr[mid] != mid+first) + return findFirstMissing(arr, start, + mid , first); + else + return findFirstMissing(arr, mid+1, + end , first); + } + return start+first; + } +/* Program to find Smallest + Missing in Sorted Array*/ + + int findSmallestMissinginSortedArray( + int[] arr) + { +/* Check if 0 is missing + in the array*/ + + if(arr[0] != 0) + return 0; +/* Check is all numbers 0 to n - 1 + are prsent in array*/ + + if(arr[arr.length-1] == arr.length - 1) + return arr.length; + int first = arr[0]; + return findFirstMissing(arr,0, + arr.length-1,first); + } +/* Driver program to test the above function*/ + + public static void main(String[] args) + { + GFG small = new GFG(); + int arr[] = {0, 1, 2, 3, 4, 5, 7}; + int n = arr.length; +/* Function Call*/ + + System.out.println(""First Missing element is : "" + + small.findSmallestMissinginSortedArray(arr)); + } +}"," '''Python3 program for above approach''' '''Function to find missing element ''' + +def findFirstMissing(arr, start, end, first): + if (start < end): + mid = int((start + end) / 2) + ''' Index matches with value + at that index, means missing + element cannot be upto that point''' + + if (arr[mid] != mid + first): + return findFirstMissing(arr, start, + mid, first) + else: + return findFirstMissing(arr, mid + 1, + end, first) + return start + first + '''Function to find Smallest +Missing in Sorted Array''' + +def findSmallestMissinginSortedArray(arr): + ''' Check if 0 is missing + in the array''' + + if (arr[0] != 0): + return 0 + ''' Check is all numbers 0 to n - 1 + are prsent in array''' + + if (arr[-1] == len(arr) - 1): + return len(arr) + first = arr[0] + return findFirstMissing(arr, 0, + len(arr) - 1, first) + '''Driver code''' + +arr = [ 0, 1, 2, 3, 4, 5, 7 ] +n = len(arr) + '''Function Call''' + +print(""First Missing element is :"", + findSmallestMissinginSortedArray(arr))" +Reverse tree path,"/*Java program to Reverse Tree path*/ + +import java.util.*; +class solution +{ +/*A Binary Tree Node*/ + +static class Node { + int data; + Node left, right; +}; +/*class for int values*/ + +static class INT { + int data; +}; +/*'data' is input. We need to reverse path from +root to data. +'level' is current level. +'temp' that stores path nodes. +'nextpos' used to pick next item for reversing.*/ + + static Node reverseTreePathUtil(Node root, int data, + Map temp, int level, INT nextpos) +{ +/* return null if root null*/ + + if (root == null) + return null; +/* Final condition + if the node is found then*/ + + if (data == root.data) { +/* store the value in it's level*/ + + temp.put(level,root.data); +/* change the root value with the current + next element of the map*/ + + root.data = temp.get(nextpos.data); +/* increment in k for the next element*/ + + nextpos.data++; + return root; + } +/* store the data in perticular level*/ + + temp.put(level,root.data); +/* We go to right only when left does not + contain given data. This way we make sure + that correct path node is stored in temp[]*/ + + Node left, right=null; + left = reverseTreePathUtil(root.left, data, temp, + level + 1, nextpos); + if (left == null) + right = reverseTreePathUtil(root.right, data, + temp, level + 1, nextpos); +/* If current node is part of the path, + then do reversing.*/ + + if (left!=null || right!=null) { + root.data = temp.get(nextpos.data); + nextpos.data++; + return (left!=null ? left : right); + } +/* return null if not element found*/ + + return null; +} +/*Reverse Tree path*/ + + static void reverseTreePath(Node root, int data) +{ +/* store per level data*/ + + Map< Integer, Integer> temp= new HashMap< Integer, Integer>(); +/* it is for replacing the data*/ + + INT nextpos=new INT(); + nextpos.data = 0; +/* reverse tree path*/ + + reverseTreePathUtil(root, data, temp, 0, nextpos); +} +/*INORDER*/ + +static void inorder(Node root) +{ + if (root != null) { + inorder(root.left); + System.out.print( root.data + "" ""); + inorder(root.right); + } +} +/*Utility function to create a new tree node*/ + + static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*Driver program to test above functions*/ + +public static void main(String args[]) +{ +/* Let us create binary tree shown in above diagram*/ + + Node root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + /* 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 */ + + int data = 4; +/* Reverse Tree Path*/ + + reverseTreePath(root, data); +/* Traverse inorder*/ + + inorder(root); +} +}"," '''Python3 program to Reverse Tree path''' + + '''A Binary Tree Node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None ''''data' is input. We need to reverse path from +root to data. + '''level' is current level. + '''temp' that stores path nodes. + '''nextpos' used to pick next item for reversing.''' + +def reverseTreePathUtil(root, data,temp, level, nextpos): + ''' return None if root None''' + + if (root == None): + return None, temp, nextpos; + ''' Final condition + if the node is found then''' + + if (data == root.data): + ''' store the value in it's level''' + + temp[level] = root.data; + ''' change the root value with the current + next element of the map''' + + root.data = temp[nextpos]; + ''' increment in k for the next element''' + + nextpos += 1 + return root, temp, nextpos; + ''' store the data in perticular level''' + + temp[level] = root.data; + ''' We go to right only when left does not + contain given data. This way we make sure + that correct path node is stored in temp[]''' + + right = None + left, temp, nextpos = reverseTreePathUtil(root.left, data, temp, + level + 1, nextpos); + if (left == None): + right, temp, nextpos = reverseTreePathUtil(root.right, data, + temp, level + 1, nextpos); + ''' If current node is part of the path, + then do reversing.''' + + if (left or right): + root.data = temp[nextpos]; + nextpos += 1 + return (left if left != None else right), temp, nextpos; + ''' return None if not element found''' + + return None, temp, nextpos; + '''Reverse Tree path''' + +def reverseTreePath(root, data): + ''' store per level data''' + + temp = dict() + ''' it is for replacing the data''' + + nextpos = 0; + ''' reverse tree path''' + + reverseTreePathUtil(root, data, temp, 0, nextpos); + '''INORDER''' + +def inorder(root): + if (root != None): + inorder(root.left); + print(root.data, end = ' ') + inorder(root.right); + '''Utility function to create a new tree node''' + +def newNode(data): + temp = Node(data) + return temp; + '''Driver code''' + +if __name__=='__main__': + ''' Let us create binary tree shown in above diagram''' + + root = newNode(7); + root.left = newNode(6); + root.right = newNode(5); + root.left.left = newNode(4); + root.left.right = newNode(3); + root.right.left = newNode(2); + root.right.right = newNode(1); + ''' 7 + / \ + 6 5 + / \ / \ + 4 3 2 1 ''' + + data = 4; + ''' Reverse Tree Path''' + + reverseTreePath(root, data); + ''' Traverse inorder''' + + inorder(root);" +Find the Missing Number,"/*Java implementation*/ + +class GFG +{ + +/* a represents the array + n : Number of elements in array a*/ + + static int getMissingNo(int a[], int n) + { + int total = 1; + for (int i = 2; i <= (n + 1); i++) + { + total += i; + total -= a[i - 2]; + } + return total; + } + +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 1, 2, 3, 5 }; + System.out.println(getMissingNo(arr, arr.length)); + } +} + + +"," '''a represents the array +n : Number of elements in array a''' + +def getMissingNo(a, n): + i, total = 0, 1 + + for i in range(2, n + 2): + total += i + total -= a[i - 2] + return total + + '''Driver Code''' + +arr = [1, 2, 3, 5] +print(getMissingNo(arr, len(arr))) + + +" +Find Second largest element in an array,"/*JAVA Code for Find Second largest +element in an array*/ + +class GFG { + /* Function to print the second largest + elements */ + + public static void print2largest(int arr[], + int arr_size) + { + int i, first, second; + /* There should be atleast two elements */ + + if (arr_size < 2) { + System.out.print("" Invalid Input ""); + return; + } + first = second = Integer.MIN_VALUE; + for (i = 0; i < arr_size; i++) { + /* If current element is smaller than + first then update both first and second */ + + if (arr[i] > first) { + second = first; + first = arr[i]; + } + /* If arr[i] is in between first and + second then update second */ + + else if (arr[i] > second && arr[i] != first) + second = arr[i]; + } + if (second == Integer.MIN_VALUE) + System.out.print(""There is no second largest"" + + "" element\n""); + else + System.out.print(""The second largest element"" + + "" is "" + second); + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int arr[] = { 12, 35, 1, 10, 34, 1 }; + int n = arr.length; + print2largest(arr, n); + } +}"," '''Python program to +find second largest +element in an array''' + + '''Function to print the +second largest elements''' + +def print2largest(arr, arr_size): ''' There should be atleast + two elements''' + + if (arr_size < 2): + print("" Invalid Input "") + return + first = second = -2147483648 + for i in range(arr_size): + ''' If current element is + smaller than first + then update both + first and second''' + + if (arr[i] > first): + second = first + first = arr[i] + ''' If arr[i] is in + between first and + second then update second''' + + elif (arr[i] > second and arr[i] != first): + second = arr[i] + if (second == -2147483648): + print(""There is no second largest element"") + else: + print(""The second largest element is"", second) + '''Driver program to test +above function''' + +arr = [12, 35, 1, 10, 34, 1] +n = len(arr) +print2largest(arr, n)" +Check for Integer Overflow,, +Longest consecutive sequence in Binary tree,"/*Java program to find longest consecutive +sequence in binary tree*/ + + +/* A binary tree node has data, pointer to left + child and a pointer to right child */ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class Result +{ + int res = 0; +} +class BinaryTree +{ + Node root;/* Utility method to return length of longest + consecutive sequence of tree */ + + private void longestConsecutiveUtil(Node root, int curlength, + int expected, Result res) + { + if (root == null) + return; +/* if root data has one more than its parent + then increase current length */ + + if (root.data == expected) + curlength++; + else + curlength = 1; +/* update the maximum by current length */ + + res.res = Math.max(res.res, curlength); +/* recursively call left and right subtree with + expected value 1 more than root data */ + + longestConsecutiveUtil(root.left, curlength, root.data + 1, res); + longestConsecutiveUtil(root.right, curlength, root.data + 1, res); + } +/* method returns length of longest consecutive + sequence rooted at node root */ + + int longestConsecutive(Node root) + { + if (root == null) + return 0; + Result res = new Result(); +/* call utility method with current length 0 */ + + longestConsecutiveUtil(root, 0, root.data, res); + return res.res; + } +/* Driver code*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(6); + tree.root.right = new Node(9); + tree.root.right.left = new Node(7); + tree.root.right.right = new Node(10); + tree.root.right.right.right = new Node(11); + System.out.println(tree.longestConsecutive(tree.root)); + } +}"," '''Python3 program to find longest consecutive +sequence in binary tree ''' + + '''A utility class to create a node ''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Utility method to return length of +longest consecutive sequence of tree ''' + +def longestConsecutiveUtil(root, curLength, + expected, res): + if (root == None): + return + ''' if root data has one more than its + parent then increase current length ''' + + if (root.data == expected): + curLength += 1 + else: + curLength = 1 + ''' update the maximum by current length ''' + + res[0] = max(res[0], curLength) + ''' recursively call left and right subtree + with expected value 1 more than root data ''' + + longestConsecutiveUtil(root.left, curLength, + root.data + 1, res) + longestConsecutiveUtil(root.right, curLength, + root.data + 1, res) + '''method returns length of longest consecutive +sequence rooted at node root ''' + +def longestConsecutive(root): + if (root == None): + return 0 + res = [0] + ''' call utility method with current length 0 ''' + + longestConsecutiveUtil(root, 0, root.data, res) + return res[0] + '''Driver Code''' + +if __name__ == '__main__': + root = newNode(6) + root.right = newNode(9) + root.right.left = newNode(7) + root.right.right = newNode(10) + root.right.right.right = newNode(11) + print(longestConsecutive(root))" +Find if given vertical level of binary tree is sorted or not,," '''Python program to determine whether +vertical level l of binary tree +is sorted or not.''' + +from collections import deque +from sys import maxsize +INT_MIN = -maxsize + '''Structure of a tree node.''' + +class Node: + def __init__(self, key): + self.key = key + self.left = None + self.right = None + '''Helper function to determine if +vertical level l of given binary +tree is sorted or not.''' + +def isSorted(root: Node, level: int) -> bool: + ''' If root is null, then the answer is an + empty subset and an empty subset is + always considered to be sorted.''' + + if root is None: + return True + ''' Variable to store previous + value in vertical level l.''' + + prevVal = INT_MIN + ''' Variable to store current level + while traversing tree vertically.''' + + currLevel = 0 + ''' Variable to store current node + while traversing tree vertically.''' + + currNode = Node(0) + ''' Declare queue to do vertical order + traversal. A pair is used as element + of queue. The first element in pair + represents the node and the second + element represents vertical level + of that node.''' + + q = deque() + ''' Insert root in queue. Vertical level + of root is 0.''' + + q.append((root, 0)) + ''' Do vertical order traversal until + all the nodes are not visited.''' + + while q: + currNode = q[0][0] + currLevel = q[0][1] + q.popleft() + ''' Check if level of node extracted from + queue is required level or not. If it + is the required level then check if + previous value in that level is less + than or equal to value of node.''' + + if currLevel == level: + if prevVal <= currNode.key: + prevVal = currNode.key + else: + return False + ''' If left child is not NULL then push it + in queue with level reduced by 1.''' + + if currNode.left: + q.append((currNode.left, currLevel - 1)) + ''' If right child is not NULL then push it + in queue with level increased by 1.''' + + if currNode.right: + q.append((currNode.right, currLevel + 1)) + ''' If the level asked is not present in the + given binary tree, that means that level + will contain an empty subset. Therefore answer + will be true.''' + + return True + '''Driver Code''' + +if __name__ == ""__main__"": + ''' /* + 1 + / \ + 2 5 + / \ + 7 4 + / + 6 + */''' + + root = Node(1) + root.left = Node(2) + root.right = Node(5) + root.left.left = Node(7) + root.left.right = Node(4) + root.left.right.left = Node(6) + level = -1 + if isSorted(root, level): + print(""Yes"") + else: + print(""No"")" +"Median of two sorted arrays with different sizes in O(log(min(n, m)))","/*Java code for finding median of the +given two sorted arrays that exists +in the merged array ((n+m) / 2 - +1 position)*/ + +import java.io.*; + +class GFG{ + +/*Function to find median +of given two sorted arrays*/ + +static int findMedianSortedArrays(int []a, int n, + int []b, int m) +{ + int min_index = 0, + max_index = n, i, j; + + while (min_index <= max_index) + { + i = (min_index + max_index) / 2; + j = ((n + m + 1) / 2) - i; + +/* If i = n, it means that + Elements from a[] in the + second half is an empty + set. If j = 0, it means + that Elements from b[] + in the first half is an + empty set. so it is + necessary to check that, + because we compare elements + from these two groups. + searching on right*/ + + if (i < n && j > 0 && + b[j - 1] > a[i]) + min_index = i + 1; + +/* If i = 0, it means that + Elements from a[] in the + first half is an empty set + and if j = m, it means that + Elements from b[] in the + second half is an empty set. + so it is necessary to check + that, because we compare + elements from these two + groups. searching on left*/ + + else if (i > 0 && j < m && + b[j] < a[i - 1]) + max_index = i - 1; + +/* We have found the + desired halves.*/ + + else + { + +/* This condition happens + when we don't have any + elements in the first + half from a[] so we + returning the last + element in b[] from + the first half.*/ + + if (i == 0) + return b[j - 1]; + +/* And this condition happens + when we don't have any + elements in the first half + from b[] so we returning the + last element in a[] from the + first half.*/ + + if (j == 0) + return a[i - 1]; + else + return maximum(a[i - 1], + b[j - 1]); + } + } + + System.out.print(""ERROR!!! "" + + ""returning\n""); + return 0; +} + +/*Function to find maximum*/ + +static int maximum(int a, int b) +{ + return a > b ? a : b; +} + +/*Driver code*/ + +public static void main(String[] args) +{ + int []a = {900}; + int []b = {10, 13, 14}; + int n = a.length; + int m = b.length; + +/* We need to define the smaller + array as the first parameter + to make sure that the time + complexity will be O(log(min(n,m)))*/ + + if (n < m) + System.out.print(""The median is: "" + + findMedianSortedArrays(a, n, + b, m)); + else + System.out.print(""The median is: "" + + findMedianSortedArrays(b, m, + a, n)); +} +} + + +"," '''Python 3 code for finding median +of the given two sorted arrays that +exists in the merged array +((n+m) / 2 - 1 position)''' + + + '''Function to find median of given +two sorted arrays''' + +def findMedianSortedArrays(a, n, b, m): + + min_index = 0 + max_index = n + + while (min_index <= max_index): + + i = (min_index + max_index) // 2 + j = ((n + m + 1) // 2) - i + + ''' if i = n, it means that Elements + from a[] in the second half is + an empty set. If j = 0, it means + that Elements from b[] in the first + half is an empty set. so it is necessary + to check that, because we compare elements + from these two groups. searching on right''' + + if (i < n and j > 0 and b[j - 1] > a[i]): + min_index = i + 1 + + ''' if i = 0, it means that Elements from + a[] in the first half is an empty set + and if j = m, it means that Elements + from b[] in the second half is an + a[] in the first half is an empty set + that, because we compare elements from + these two groups. searching on left''' + + elif (i > 0 and j < m and b[j] < a[i - 1]): + max_index = i - 1 + + ''' we have found the desired halves.''' + + else: + + ''' this condition happens when we don't have + any elements in the first half from a[] so + we returning the last element in b[] from + the first half.''' + + if (i == 0): + return b[j - 1] + + ''' and this condition happens when we don't + have any elements in the first half from + b[] so we returning the last element in + a[] from the first half.''' + + if (j == 0): + return a[i - 1] + else: + return maximum(a[i - 1], b[j - 1]) + + print(""ERROR!!! "" , ""returning\n"") + return 0 + + '''Function to find maximum''' + +def maximum(a, b) : + return a if a > b else b + + '''Driver code''' + +if __name__ == ""__main__"": + a = [900] + b = [10, 13, 14] + n = len(a) + m = len(b) + + ''' we need to define the smaller array + as the first parameter to make sure + that the time complexity will be + O(log(min(n,m)))''' + + if (n < m): + print( ""The median is: "", + findMedianSortedArrays(a, n, b, m)) + else: + print( ""The median is: "", + findMedianSortedArrays(b, m, a, n)) + + +" +Count number of triplets with product equal to given number,"/*Java program to count triplets with given +product m*/ + +class GFG { +/* Method to count such triplets*/ + + static int countTriplets(int arr[], int n, int m) + { + int count = 0; +/* Consider all triplets and count if + their product is equal to m*/ + + for (int i = 0; i < n - 2; i++) + for (int j = i + 1; j < n - 1; j++) + for (int k = j + 1; k < n; k++) + if (arr[i] * arr[j] * arr[k] == m) + count++; + return count; + } +/* Driver method*/ + + public static void main(String[] args) + { + int arr[] = { 1, 4, 6, 2, 3, 8 }; + int m = 24; + System.out.println(countTriplets(arr, arr.length, m)); + } +}"," '''Python3 program to count +triplets with given product m''' + + '''Method to count such triplets''' + +def countTriplets(arr, n, m): + count = 0 ''' Consider all triplets and count if + their product is equal to m''' + + for i in range (n - 2): + for j in range (i + 1, n - 1): + for k in range (j + 1, n): + if (arr[i] * arr[j] * arr[k] == m): + count += 1 + return count + '''Driver code''' + +if __name__ == ""__main__"": + arr = [1, 4, 6, 2, 3, 8] + m = 24 + print(countTriplets(arr, + len(arr), m))" +Sum of k smallest elements in BST,"/*Java program to find Sum Of All Elements smaller +than or equal t Kth Smallest Element In BST*/ + +import java.util.*; +class GFG{ +/* Binary tree Node */ + +static class Node +{ + int data; + int lCount; + int Sum ; + Node left; + Node right; +}; +/*utility function new Node of BST*/ + +static Node createNode(int data) +{ + Node new_Node = new Node(); + new_Node.left = null; + new_Node.right = null; + new_Node.data = data; + new_Node.lCount = 0 ; + new_Node.Sum = 0; + return new_Node; +} +/*A utility function to insert a new Node with +given key in BST and also maintain lcount ,Sum*/ + +static Node insert(Node root, int key) +{ +/* If the tree is empty, return a new Node*/ + + if (root == null) + return createNode(key); +/* Otherwise, recur down the tree*/ + + if (root.data > key) + { +/* increment lCount of current Node*/ + + root.lCount++; +/* increment current Node sum by adding + key into it*/ + + root.Sum += key; + root.left= insert(root.left , key); + } + else if (root.data < key ) + root.right= insert (root.right , key ); +/* return the (unchanged) Node pointer*/ + + return root; +} +static int temp_sum; +/*function return sum of all element smaller than and equal +to Kth smallest element*/ + +static void ksmallestElementSumRec(Node root, int k ) +{ + if (root == null) + return ; +/* if we fount k smallest element then break the function*/ + + if ((root.lCount + 1) == k) + { + temp_sum += root.data + root.Sum ; + return ; + } + else if (k > root.lCount) + { +/* store sum of all element smaller than current root ;*/ + + temp_sum += root.data + root.Sum; +/* decremented k and call right sub-tree*/ + + k = k -( root.lCount + 1); + ksmallestElementSumRec(root.right , k ); + } +/*call left sub-tree*/ + +else + ksmallestElementSumRec(root.left , k ); +} +/*Wrapper over ksmallestElementSumRec()*/ + +static void ksmallestElementSum(Node root, int k) +{ + temp_sum = 0; + ksmallestElementSumRec(root, k); +} +/* Driver program to test above functions */ + +public static void main(String[] args) +{ + /* 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 + */ + + Node root = null; + root = insert(root, 20); + root = insert(root, 8); + root = insert(root, 4); + root = insert(root, 12); + root = insert(root, 10); + root = insert(root, 14); + root = insert(root, 22); + int k = 3; + ksmallestElementSum(root, k); + System.out.println(temp_sum); +} +}"," '''Python3 program to find Sum Of All Elements +smaller than or equal t Kth Smallest Element In BST''' + '''utility function new Node of BST''' + +class createNode: + def __init__(self, data): + self.data = data + self.lCount = 0 + self.Sum = 0 + self.left = None + self.right = None '''A utility function to insert a new Node with +given key in BST and also maintain lcount ,Sum''' + +def insert(root, key): + ''' If the tree is empty, return a new Node''' + + if root == None: + return createNode(key) + ''' Otherwise, recur down the tree''' + + if root.data > key: + ''' increment lCount of current Node''' + + root.lCount += 1 + ''' increment current Node sum by + adding key into it''' + + root.Sum += key + root.left= insert(root.left , key) + elif root.data < key: + root.right= insert (root.right , key) + ''' return the (unchanged) Node pointer''' + + return root + '''function return sum of all element smaller +than and equal to Kth smallest element''' + +def ksmallestElementSumRec(root, k , temp_sum): + if root == None: + return + ''' if we fount k smallest element + then break the function''' + + if (root.lCount + 1) == k: + temp_sum[0] += root.data + root.Sum + return + elif k > root.lCount: + ''' store sum of all element smaller + than current root ;''' + + temp_sum[0] += root.data + root.Sum + ''' decremented k and call right sub-tree''' + + k = k -( root.lCount + 1) + ksmallestElementSumRec(root.right, + k, temp_sum) + '''call left sub-tree''' + + else: + ksmallestElementSumRec(root.left, + k, temp_sum) + '''Wrapper over ksmallestElementSumRec()''' + +def ksmallestElementSum(root, k): + Sum = [0] + ksmallestElementSumRec(root, k, Sum) + return Sum[0] + '''Driver Code''' + +if __name__ == '__main__': + ''' 20 + / \ + 8 22 + / \ + 4 12 + / \ + 10 14 + ''' + + root = None + root = insert(root, 20) + root = insert(root, 8) + root = insert(root, 4) + root = insert(root, 12) + root = insert(root, 10) + root = insert(root, 14) + root = insert(root, 22) + k = 3 + print(ksmallestElementSum(root, k))" +Counting sets of 1s and 0s in a binary matrix,"/*Java program to compute number of sets +in a binary matrix.*/ + +class GFG { +/*no of columns*/ + +static final int m = 3; +/*no of rows*/ + +static final int n = 2; +/*function to calculate the number of +non empty sets of cell*/ + +static long countSets(int a[][]) { +/* stores the final answer*/ + + long res = 0; +/* traverses row-wise*/ + + for (int i = 0; i < n; i++) { + int u = 0, v = 0; + for (int j = 0; j < m; j++) { + if (a[i][j] == 1) + u++; + else + v++; + } + res += Math.pow(2, u) - 1 + Math.pow(2, v) - 1; + } +/* traverses column wise*/ + + for (int i = 0; i < m; i++) { + int u = 0, v = 0; + for (int j = 0; j < n; j++) { + if (a[j][i] == 1) + u++; + else + v++; + } + res += Math.pow(2, u) - 1 + Math.pow(2, v) - 1; + } +/* at the end subtract n*m as no of + single sets have been added twice.*/ + + return res - (n * m); +} +/*Driver code*/ + +public static void main(String[] args) { + int a[][] = {{1, 0, 1}, {0, 1, 0}}; + System.out.print(countSets(a)); +} +}"," '''Python3 program to compute number of sets +in a binary matrix.''' + + '''no of columns''' + +m = 3 '''no of rows''' + +n = 2 + '''function to calculate the number of +non empty sets of cell''' + +def countSets(a): + ''' stores the final answer''' + + res = 0 + ''' traverses row-wise''' + + for i in range(n): + u = 0 + v = 0 + for j in range(m): + if a[i][j]: + u += 1 + else: + v += 1 + res += pow(2, u) - 1 + pow(2, v) - 1 + ''' traverses column wise''' + + for i in range(m): + u = 0 + v = 0 + for j in range(n): + if a[j][i]: + u += 1 + else: + v += 1 + res += pow(2, u) - 1 + pow(2, v) - 1 + ''' at the end subtract n*m as no of + single sets have been added twice.''' + + return res - (n*m) + '''Driver program to test the above function.''' + +a = [[1, 0, 1],[0, 1, 0]] +print(countSets(a)) +" +Total coverage of all zeros in a binary matrix,"/*Java program to get total +coverage of all zeros in +a binary matrix*/ + +import java .io.*; +class GFG +{ +static int R = 4; +static int C = 4; +/*Returns total coverage +of all zeros in mat[][]*/ + +static int getTotalCoverageOfMatrix(int [][]mat) +{ + int res = 0; +/* looping for all + rows of matrix*/ + + for (int i = 0; i < R; i++) + { +/* 1 is not seen yet*/ + + boolean isOne = false; +/* looping in columns from + left to right direction + to get left ones*/ + + for (int j = 0; j < C; j++) + { +/* If one is found + from left*/ + + if (mat[i][j] == 1) + isOne = true; +/* If 0 is found and we + have found a 1 before.*/ + + else if (isOne) + res++; + } +/* Repeat the above + process for right + to left direction.*/ + + isOne = false; + for (int j = C - 1; j >= 0; j--) + { + if (mat[i][j] == 1) + isOne = true; + else if (isOne) + res++; + } + } +/* Traversing across columms + for up and down directions.*/ + + for (int j = 0; j < C; j++) + { +/* 1 is not seen yet*/ + + boolean isOne = false; + for (int i = 0; i < R; i++) + { + if (mat[i][j] == 1) + isOne = true; + else if (isOne) + res++; + } + isOne = false; + for (int i = R - 1; i >= 0; i--) + { + if (mat[i][j] == 1) + isOne = true; + else if (isOne) + res++; + } + } + return res; +} +/*Driver code*/ + +static public void main (String[] args) +{ + int [][]mat = {{0, 0, 0, 0}, + {1, 0, 0, 1}, + {0, 1, 1, 0}, + {0, 1, 0, 0}}; +System.out.println( + getTotalCoverageOfMatrix(mat)); +} +}"," '''Python3 program to get total coverage of all zeros in +a binary matrix''' + +R = 4 +C = 4 + '''Returns total coverage of all zeros in mat[][]''' + +def getTotalCoverageOfMatrix(mat): + res = 0 + ''' looping for all rows of matrix''' + + for i in range(R): + '''1 is not seen yet''' + + isOne = False + ''' looping in columns from left to right + direction to get left ones''' + + for j in range(C): + ''' If one is found from left''' + + if (mat[i][j] == 1): + isOne = True + ''' If 0 is found and we have found + a 1 before.''' + + elif (isOne): + res += 1 + ''' Repeat the above process for right to + left direction.''' + + isOne = False + for j in range(C - 1, -1, -1): + if (mat[i][j] == 1): + isOne = True + elif (isOne): + res += 1 + ''' Traversing across columms for up and down + directions.''' + + for j in range(C): + '''1 is not seen yet''' + + isOne = False + for i in range(R): + if (mat[i][j] == 1): + isOne = True + elif (isOne): + res += 1 + isOne = False + for i in range(R - 1, -1, -1): + if (mat[i][j] == 1): + isOne = True + elif (isOne): + res += 1 + return res + '''Driver code''' + +mat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]] +print(getTotalCoverageOfMatrix(mat))" +Factor Tree of a given Number,"/*Java program to conFactor Tree for +a given number*/ + +import java.util.*; +class GFG +{ +/* Tree node*/ + + static class Node + { + Node left, right; + int key; + }; + static Node root; +/* Utility function to create a new tree Node*/ + + static Node newNode(int key) + { + Node temp = new Node(); + temp.key = key; + temp.left = temp.right = null; + return temp; + } +/* Constructs factor tree for given value and stores + root of tree at given reference.*/ + + static Node createFactorTree(Node node_ref, int v) + { + (node_ref) = newNode(v); +/* the number is factorized*/ + + for (int i = 2 ; i < v/2 ; i++) + { + if (v % i != 0) + continue; +/* If we found a factor, we conleft + and right subtrees and return. Since we + traverse factors starting from smaller + to greater, left child will always have + smaller factor*/ + + node_ref.left = createFactorTree(((node_ref).left), i); + node_ref.right = createFactorTree(((node_ref).right), v/i); + return node_ref; + } + return node_ref; + } +/* Iterative method to find the height of Binary Tree*/ + + static void printLevelOrder(Node root) + { +/* Base Case*/ + + if (root == null) return; + Queue q = new LinkedList<>(); + q.add(root); + while (q.isEmpty() == false) + { +/* Print front of queue and remove + it from queue*/ + + Node node = q.peek(); + System.out.print(node.key + "" ""); + q.remove(); + if (node.left != null) + q.add(node.left); + if (node.right != null) + q.add(node.right); + } + } +/* Driver program*/ + + public static void main(String[] args) + { +/* int val = 48;sample value*/ + + root = null; + root = createFactorTree(root, val); + System.out.println(""Level order traversal of ""+ + ""constructed factor tree""); + printLevelOrder(root); + } +}", +Find pair with greatest product in array,"/*Java program to find the largest product number*/ + +import java.util.*; +class GFG +{ +/* Function to find greatest number*/ + + static int findGreatest(int arr[], int n) + { +/* Store occurrences of all + elements in hash array*/ + + Map m = new HashMap<>(); + for (int i = 0; i < n; i++) + { + if (m.containsKey(arr[i])) + { + m.put(arr[i], m.get(arr[i]) + 1); + } + else + { + m.put(arr[i], m.get(arr[i])); + } + } +/* m[arr[i]]++; + Sort the array and traverse + all elements from end.*/ + + Arrays.sort(arr); + for (int i = n - 1; i > 1; i--) + { +/* For every element, check if there is another + element which divides it.*/ + + for (int j = 0; j < i && + arr[j] <= Math.sqrt(arr[i]); j++) + { + if (arr[i] % arr[j] == 0) + { + int result = arr[i] / arr[j]; +/* Check if the result value exists in array + or not if yes the return arr[i]*/ + + if (result != arr[j] && + m.get(result) == null|| m.get(result) > 0) + { + return arr[i]; + } +/* To handle the case like arr[i] = 4 + and arr[j] = 2*/ + + else if (result == arr[j] && m.get(result) > 1) + { + return arr[i]; + } + } + } + } + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = {17, 2, 1, 15, 30}; + int n = arr.length; + System.out.println(findGreatest(arr, n)); + } +}"," '''Python3 program to find the largest product number''' + +from math import sqrt + '''Function to find greatest number''' + +def findGreatest(arr, n): + ''' Store occurrences of all elements in hash + array''' + + m = dict() + for i in arr: + m[i] = m.get(i, 0) + 1 + ''' Sort the array and traverse all elements from + end.''' + + arr=sorted(arr) + for i in range(n - 1, 0, -1): + ''' For every element, check if there is another + element which divides it.''' + + j = 0 + while(j < i and arr[j] <= sqrt(arr[i])): + if (arr[i] % arr[j] == 0): + result = arr[i]//arr[j] + ''' Check if the result value exists in array + or not if yes the return arr[i]''' + + if (result != arr[j] and (result in m.keys() )and m[result] > 0): + return arr[i] + ''' To handle the case like arr[i] = 4 and + arr[j] = 2''' + + elif (result == arr[j] and (result in m.keys()) and m[result] > 1): + return arr[i] + j += 1 + return -1 + '''Drivers code''' + +arr= [17, 2, 1, 15, 30] +n = len(arr) +print(findGreatest(arr, n))" +Making elements of two arrays same with minimum increment/decrement,"/*Java program to find minimum +increment/decrement operations +to make array elements same.*/ + +import java.util.Arrays; +import java.io.*; + +class GFG +{ +static int MinOperation(int a[], + int b[], + int n) +{ +/* sorting both arrays + in ascending order*/ + + Arrays.sort(a); + Arrays.sort(b); + + +/* variable to store + the final result*/ + + int result = 0; + +/* After sorting both arrays + Now each array is in non- + decreasing order. Thus, + we will now compare each + element of the array and + do the increment or decrement + operation depending upon the + value of array b[].*/ + + for (int i = 0; i < n; ++i) + { + if (a[i] > b[i]) + result = result + + Math.abs(a[i] - b[i]); + + else if (a[i] < b[i]) + result = result + + Math.abs(a[i] - b[i]); + } + + return result; +} + +/*Driver code*/ + +public static void main (String[] args) +{ + int a[] = {3, 1, 1}; + int b[] = {1, 2, 2}; + int n = a.length; + System.out.println(MinOperation(a, b, n)); +} +} + + +"," '''Python 3 program to find minimum +increment/decrement operations to +make array elements same.''' + + +def MinOperation(a, b, n): + + ''' sorting both arrays in ascending order''' + + a.sort(reverse = False) + b.sort(reverse = False) + + ''' variable to store the final result''' + + result = 0 + + ''' After sorting both arrays. Now each + array is in non-decreasing order. + Thus, we will now compare each element + of the array and do the increment or + decrement operation depending upon + the value of array b[].''' + + for i in range(0, n, 1): + if (a[i] > b[i]): + result = result + abs(a[i] - b[i]) + + elif(a[i] < b[i]): + result = result + abs(a[i] - b[i]) + + return result + + '''Driver code''' + +if __name__ == '__main__': + a = [3, 1, 1] + b = [1, 2, 2] + n = len(a) + print(MinOperation(a, b, n)) + + +" +Count elements which divide all numbers in range L-R,"/*Java program to Count elements which +divides all numbers in range L-R*/ + +import java.io.*; +class GFG +{ +/*function to count element +Time complexity O(n^2) worst case*/ + +static int answerQuery(int a[], int n, + int l, int r) +{ +/* answer for query*/ + + int count = 0; +/* 0 based index*/ + + l = l - 1; +/* iterate for all elements*/ + + for (int i = l; i < r; i++) + { + int element = a[i]; + int divisors = 0; +/* check if the element divides + all numbers in range*/ + + for (int j = l; j < r; j++) + { +/* no of elements*/ + + if (a[j] % a[i] == 0) + divisors++; + else + break; + } +/* if all elements are divisible by a[i]*/ + + if (divisors == (r - l)) + count++; + } +/* answer for every query*/ + + return count; +} +/*Driver Code*/ + +public static void main (String[] args) +{ + int a[] = { 1, 2, 3, 5 }; + int n = a.length; + int l = 1, r = 4; + System.out.println( answerQuery(a, n, l, r)); + l = 2; r = 4; + System.out.println( answerQuery(a, n, l, r)); +} +}"," '''Python 3 program to Count elements which +divides all numbers in range L-R''' + + '''function to count element +Time complexity O(n^2) worst case''' + +def answerQuery(a, n, l, r): ''' answer for query''' + + count = 0 + ''' 0 based index''' + + l = l - 1 + ''' iterate for all elements''' + + for i in range(l, r, 1): + element = a[i] + divisors = 0 + ''' check if the element divides + all numbers in range''' + + for j in range(l, r, 1): + ''' no of elements''' + + if (a[j] % a[i] == 0): + divisors += 1 + else: + break + ''' if all elements are divisible + by a[i]''' + + if (divisors == (r - l)): + count += 1 + ''' answer for every query''' + + return count + '''Driver Code''' + +if __name__ =='__main__': + a = [1, 2, 3, 5] + n = len(a) + l = 1 + r = 4 + print(answerQuery(a, n, l, r)) + l = 2 + r = 4 + print(answerQuery(a, n, l, r))" +Count smaller elements on right side,"class CountSmaller +{ + void constructLowerArray(int arr[], int countSmaller[], int n) + { + int i, j; + +/* initialize all the counts in countSmaller array as 0*/ + + for (i = 0; i < n; i++) + countSmaller[i] = 0; + + for (i = 0; i < n; i++) + { + for (j = i + 1; j < n; j++) + { + if (arr[j] < arr[i]) + countSmaller[i]++; + } + } + } + + /* Utility function that prints out an array on a line */ + + void printArray(int arr[], int size) + { + int i; + for (i = 0; i < size; i++) + System.out.print(arr[i] + "" ""); + + System.out.println(""""); + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + CountSmaller small = new CountSmaller(); + int arr[] = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2}; + int n = arr.length; + int low[] = new int[n]; + small.constructLowerArray(arr, low, n); + small.printArray(low, n); + } +} +","def constructLowerArray (arr, countSmaller, n): + + ''' initialize all the counts in countSmaller array as 0''' + + for i in range(n): + countSmaller[i] = 0 + + for i in range(n): + for j in range(i + 1,n): + if (arr[j] < arr[i]): + countSmaller[i] += 1 + + '''Utility function that prints out an array on a line''' + +def printArray(arr, size): + for i in range(size): + print(arr[i],end="" "") + print() + + '''Driver code''' + +arr = [12, 10, 5, 4, 2, 20, 6, 1, 0, 2] +n = len(arr) +low = [0]*n +constructLowerArray(arr, low, n) +printArray(low, n) + + +" +Diameter of a Binary Tree,"/*Recursive Java program to find the diameter of a +Binary Tree*/ +/*Class containing left and right child of current +node and key value*/ + +class Node { + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +/*A utility class to pass heigh object*/ + +class Height { + int h; +} +/*Class to print the Diameter*/ + +class BinaryTree { + Node root; +/* define height =0 globally and call + diameterOpt(root,height) from main*/ + + int diameterOpt(Node root, Height height) + { +/* lh --> Height of left subtree + rh --> Height of right subtree*/ + + Height lh = new Height(), rh = new Height(); + +/* base condition- when binary tree is empty*/ + + if (root == null) { + height.h = 0;/*diameter is also 0*/ + +return 0; + } +/* + ldiameter --> diameter of left subtree + rdiameter --> Diameter of right subtree + Get the heights of left and right subtrees in lh and rh. + And store the returned values in ldiameter and ldiameter*/ + + int ldiameter = diameterOpt(root.left, lh); + int rdiameter = diameterOpt(root.right, rh); +/* Height of current node is max of heights of left + and right subtrees plus 1*/ + + height.h = Math.max(lh.h, rh.h) + 1; + return Math.max(lh.h + rh.h + 1, + Math.max(ldiameter, rdiameter)); + } +/* A wrapper over diameter(Node root)*/ + + int diameter() + { + Height height = new Height(); + return diameterOpt(root, height); + } +/* The function Compute the ""height"" of a tree. Height + is + the number f nodes along the longest path from the + root node down to the farthest leaf node.*/ + + static int height(Node node) + { +/* base case tree is empty*/ + + if (node == null) + return 0; +/* If tree is not empty then height = 1 + max of + left height and right heights*/ + + return (1 + + Math.max(height(node.left), + height(node.right))); + } +/* Driver Code*/ + + public static void main(String args[]) + { +/* creating a binary tree and entering the nodes*/ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); +/* Function Call*/ + + System.out.println( + ""The diameter of given binary tree is : "" + + tree.diameter()); + } +}"," '''Python3 program to find the diameter of a binary tree''' + '''A binary tree Node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = self.right = None '''utility class to pass height object''' + +class Height: + def __init(self): + self.h = 0 + '''Optimised recursive function to find diameter +of binary tree''' + +def diameterOpt(root, height): + ''' to store height of left and right subtree''' + + lh = Height() + rh = Height() + ''' base condition- when binary tree is empty''' + + if root is None: + height.h = 0 + + '''diameter is also 0''' + + return 0 ''' ldiameter --> diameter of left subtree + rdiamter --> diameter of right subtree + height of left subtree and right subtree is obtained from lh and rh + and returned value of function is stored in ldiameter and rdiameter''' + + ldiameter = diameterOpt(root.left, lh) + rdiameter = diameterOpt(root.right, rh) + ''' height of tree will be max of left subtree + height and right subtree height plus1''' + + height.h = max(lh.h, rh.h) + 1 + return max(lh.h + rh.h + 1, max(ldiameter, rdiameter)) + '''function to calculate diameter of binary tree''' + +def diameter(root): + height = Height() + return diameterOpt(root, height) + '''Driver Code''' + ''' +Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 + ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) + + '''Function Call''' + +print(diameter(root))" +Rank of an element in a stream,"/*Java program to find rank of an +element in a stream.*/ + +class GFG +{ +/*Driver code*/ + +public static void main(String[] args) +{ + int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; + int key = 20; + int arraySize = a.length; + int count = 0; + for(int i = 0; i < arraySize; i++) + { + if(a[i] <= key) + { + count += 1; + } + } + System.out.println(""Rank of "" + key + + "" in stream is: "" + (count - 1)); +} +}"," '''Python3 program to find rank of an +element in a stream.''' + '''Driver code''' + +if __name__ == '__main__': + a = [5, 1, 14, 4, 15, + 9, 7, 20, 11] + key = 20 + arraySize = len(a) + count = 0 + for i in range(arraySize): + if a[i] <= key: + count += 1 + print(""Rank of"", key, + ""in stream is:"", count - 1)" +Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String,"/*Java program for the above approach*/ + +import java.util.*; + +class GFG{ + +/*Function to find the maximum sum of +consecutive 0s present at the start +and end of any rotation of the string str*/ + +static void findMaximumZeros(String str, int n) +{ + +/* Stores the count of 0s*/ + + int c0 = 0; + for(int i = 0; i < n; ++i) + { + if (str.charAt(i) == '0') + c0++; + } + +/* If the frequency of '1' is 0*/ + + if (c0 == n) + { + +/* Print n as the result*/ + + System.out.print(n); + return; + } + +/* Stores the required sum*/ + + int mx = 0; + +/* Find the maximum consecutive + length of 0s present in the string*/ + + int cnt = 0; + + for(int i = 0; i < n; i++) + { + if (str.charAt(i) == '0') + cnt++; + else + { + mx = Math.max(mx, cnt); + cnt = 0; + } + } + +/* Update the overall maximum sum*/ + + mx = Math.max(mx, cnt); + +/* Find the number of 0s present at + the start and end of the string*/ + + int start = 0, end = n - 1; + cnt = 0; + +/* Update the count of 0s at the start*/ + + while (str.charAt(start) != '1' && start < n) + { + cnt++; + start++; + } + +/* Update the count of 0s at the end*/ + + while (str.charAt(end) != '1' && end >= 0) + { + cnt++; + end--; + } + +/* Update the maximum sum*/ + + mx = Math.max(mx, cnt); + +/* Print the result*/ + + System.out.println(mx); +} + +/*Driver Code*/ + +public static void main (String[] args) +{ + +/* Given string*/ + + String s = ""1001""; + +/* Store the size of the string*/ + + int n = s.length(); + + findMaximumZeros(s, n); +} +} + + +"," '''Python3 program for the above approach''' + + + '''Function to find the maximum sum of +consecutive 0s present at the start +and end of any rotation of the string str''' + +def findMaximumZeros(string, n): + + ''' Stores the count of 0s''' + + c0 = 0 + + for i in range(n): + if (string[i] == '0'): + c0 += 1 + + ''' If the frequency of '1' is 0''' + + if (c0 == n): + + ''' Print n as the result''' + + print(n, end = """") + return + + ''' Stores the required sum''' + + mx = 0 + + ''' Find the maximum consecutive + length of 0s present in the string''' + + cnt = 0 + + for i in range(n): + if (string[i] == '0'): + cnt += 1 + else: + mx = max(mx, cnt) + cnt = 0 + + ''' Update the overall maximum sum''' + + mx = max(mx, cnt) + + ''' Find the number of 0s present at + the start and end of the string''' + + start = 0 + end = n - 1 + cnt = 0 + + ''' Update the count of 0s at the start''' + + while (string[start] != '1' and start < n): + cnt += 1 + start += 1 + + ''' Update the count of 0s at the end''' + + while (string[end] != '1' and end >= 0): + cnt += 1 + end -= 1 + + ''' Update the maximum sum''' + + mx = max(mx, cnt) + + ''' Print the result''' + + print(mx, end = """") + + '''Driver Code''' + +if __name__ == ""__main__"": + + ''' Given string''' + + s = ""1001"" + + ''' Store the size of the string''' + + n = len(s) + + findMaximumZeros(s, n) + + +" +Least frequent element in an array,"/*Java program to find the least frequent element +in an array.*/ + +import java.io.*; +import java.util.*; + +class GFG { + + static int leastFrequent(int arr[], int n) + { + +/* Sort the array*/ + + Arrays.sort(arr); + +/* find the min frequency using + linear traversal*/ + + int min_count = n+1, res = -1; + int curr_count = 1; + + for (int i = 1; i < n; i++) { + if (arr[i] == arr[i - 1]) + curr_count++; + else { + if (curr_count < min_count) { + min_count = curr_count; + res = arr[i - 1]; + } + + curr_count = 1; + } + } + +/* If last element is least frequent*/ + + if (curr_count < min_count) + { + min_count = curr_count; + res = arr[n - 1]; + } + + return res; + } + +/* driver program*/ + + public static void main(String args[]) + { + int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; + int n = arr.length; + System.out.print(leastFrequent(arr, n)); + + } +} + + +"," '''Python 3 program to find the least +frequent element in an array.''' + + + +def leastFrequent(arr, n) : + + ''' Sort the array''' + + arr.sort() + + ''' find the min frequency using + linear traversal''' + + min_count = n + 1 + res = -1 + curr_count = 1 + for i in range(1, n) : + if (arr[i] == arr[i - 1]) : + curr_count = curr_count + 1 + else : + if (curr_count < min_count) : + min_count = curr_count + res = arr[i - 1] + + curr_count = 1 + + + ''' If last element is least frequent''' + + if (curr_count < min_count) : + min_count = curr_count + res = arr[n - 1] + + return res + + + '''Driver program''' + +arr = [1, 3, 2, 1, 2, 2, 3, 1] +n = len(arr) +print(leastFrequent(arr, n)) + + + +" +How to swap two numbers without using a temporary variable?,"/*Java program to swap two numbers*/ + +import java.io.*; +class GFG { + +/*Function to swap the numbers.*/ + + public static void swap(int a, int b) + {/* same as a = a + b*/ + + a = (a & b) + (a | b); +/* same as b = a - b*/ + + b = a + (~b) + 1; +/* same as a = a - b*/ + + a = a + (~b) + 1; + System.out.print(""After swapping: a = "" + a + + "", b = "" + b); + } + +/*Driver Code*/ + + public static void main(String[] args) + { + int a = 5, b = 10;/* Function Call*/ + + swap(a, b); + } +}"," '''Python3 program to swap two numbers''' + + '''Function to swap the numbers''' + +def swap(a, b): ''' Same as a = a + b''' + + a = (a & b) + (a | b) + ''' Same as b = a - b''' + + b = a + (~b) + 1 + ''' Same as a = a - b''' + + a = a + (~b) + 1 + print(""After Swapping: a = "", a, "", b = "", b) + '''Driver code''' + +a = 5 +b = 10 + '''Function call''' + +swap(a, b)" +Minimum number of distinct elements after removing m items,"/*Java program for Minimum number of +distinct elements after removing m items*/ + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +public class DistinctIds +{ +/* Function to find distintc id's*/ + + static int distinctIds(int arr[], int n, int mi) + { + Map m = new HashMap(); + int count = 0; + int size = 0; +/* Store the occurrence of ids*/ + + for (int i = 0; i < n; i++) + { + if (m.containsKey(arr[i]) == false) + { + m.put(arr[i], 1); + size++; + } + else m.put(arr[i], m.get(arr[i]) + 1); + }/* Start removing elements from the beginning*/ + + for (Entry mp:m.entrySet()) + { +/* Remove if current value is less than + or equal to mi*/ + + if (mp.getKey() <= mi) + { + mi -= mp.getKey(); + count++; + } +/* Return the remaining size*/ + + else return size - count; + } + return size - count; + } +/* Driver method to test above function*/ + + public static void main(String[] args) + { + int arr[] = {2, 3, 1, 2, 3, 3}; + int m = 3; + System.out.println(distinctIds(arr, arr.length, m)); + } +}"," '''Python program for above implementation''' + + '''Function to find distintc id's''' + +def distinctIds(arr, n, mi): + m = {} + v = [] + count = 0 ''' Store the occurrence of ids''' + + for i in range(n): + if arr[i] in m: + m[arr[i]] += 1 + else: + m[arr[i]] = 1 + ''' Store into the list value as key and vice-versa''' + + for i in m: + v.append([m[i],i]) + v.sort() + size = len(v) + ''' Start removing elements from the beginning''' + + for i in range(size): + ''' Remove if current value is less than + or equal to mi''' + + if (v[i][0] <= mi): + mi -= v[i][0] + count += 1 + '''Return the remaining size''' + + else: + return size - count + return size - count + '''Driver code''' + +arr = [ 2, 3, 1, 2, 3, 3 ] +n = len(arr) +m = 3 +print(distinctIds(arr, n, m))" +"Array Queries for multiply, replacements and product","/*Java program to solve three types of queries.*/ + +import java.io.*; +import java.util.*; +import java.util.Arrays; + +class GFG{ + +static Scanner sc= new Scanner(System.in); + +/*Vector of 1000 elements, +all set to 0*/ + +static int twos[] = new int[1000]; + +/*Vector of 1000 elements, +all set to 0*/ + +static int fives[] = new int[1000]; + +static int sum = 0; + +/*Function to check number of +trailing zeros in multiple of 2*/ + +static int returnTwos(int val) +{ + int count = 0; + while (val % 2 == 0 && val != 0) + { + val = val / 2; + count++; + } + return count; +} + +/*Function to check number of +trailing zeros in multiple of 5*/ + +static int returnFives(int val) +{ + int count = 0; + while (val % 5 == 0 && val != 0) + { + val = val / 5; + count++; + } + return count; +} + +/*Function to solve the queries received*/ + +static void solve_queries(int arr[], int n) +{ + int type = sc.nextInt(); + +/* If the query is of type 1.*/ + + if (type == 1) + { + int ql = sc.nextInt(); + int qr = sc.nextInt(); + int x = sc.nextInt(); + +/* Counting the number of + zeros in the given value of x*/ + + int temp = returnTwos(x); + int temp1 = returnFives(x); + + for(int i = ql - 1; i < qr; i++) + { + +/* The value x has been multiplied + to their respective indices*/ + + arr[i] = arr[i] * x; + +/* The value obtained above has been + added to their respective vectors*/ + + twos[i] += temp; + fives[i] += temp1; + } + } + +/* If the query is of type 2.*/ + + if (type == 2) + { + int ql = sc.nextInt(); + int qr = sc.nextInt(); + int y = sc.nextInt(); + +/* Counting the number of + zero in the given value of x*/ + + int temp = returnTwos(y); + int temp1 = returnFives(y); + + for(int i = ql - 1; i < qr; i++) + { + +/* The value y has been replaced + to their respective indices*/ + + arr[i] = (i - ql + 2) * y; + +/* The value obtained above has been + added to their respective vectors*/ + + twos[i] = returnTwos(i - ql + 2) + temp; + fives[i] = returnFives(i - ql + 2) + temp1; + } + } + +/* If the query is of type 2*/ + + if (type == 3) + { + int ql = sc.nextInt(); + int qr = sc.nextInt(); + int sumtwos = 0; + int sumfives = 0; + + for(int i = ql - 1; i < qr; i++) + { + +/* As the number of trailing zeros for + each case has been found for each array + element then we simply add those to + the respective index to a variable*/ + + sumtwos += twos[i]; + sumfives += fives[i]; + } + +/* Compare the number of zeros + obtained in the multiples of five and two + consider the minimum of them and add them*/ + + sum += Math.min(sumtwos, sumfives); + } +} + +/*Driver code*/ + +public static void main(String[] args) +{ + +/* Input the Size of array + and number of queries*/ + + int n = sc.nextInt(); + int m = sc.nextInt(); + + int arr[] = new int[n]; + for(int i = 0; i < n; i++) + { + arr[i] = sc.nextInt(); + twos[i] = returnTwos(arr[i]); + fives[i] = returnFives(arr[i]); + } + +/* Running the while loop + for m number of queries*/ + + while (m-- != 0) + { + solve_queries(arr, n); + } + System.out.println(sum); +} +} + + +"," '''Python3 program to solve three typees of queries.''' + + + '''vector of 1000 elements, +all set to 0''' + +twos = [0] * 1000 + + '''vector of 1000 elements, +all set to 0''' + +fives = [0] * 1000 + +sum = 0 + + '''Function to check number of +trailing zeros in multiple of 2''' + +def returnTwos(val): + + count = 0 + while (val % 2 == 0 and val != 0): + val = val // 2 + count += 1 + + return count + + '''Function to check number of +trailing zeros in multiple of 5''' + +def returnFives(val): + + count = 0 + while (val % 5 == 0 and val != 0): + val = val // 5 + count += 1 + + return count + + '''Function to solve the queries received''' + +def solve_queries(arr, n): + + global sum + arrr1 = list(map(int,input().split())) + typee = arrr1[0] + + ''' If the query is of typee 1.''' + + if (typee == 1): + ql, qr, x = arrr1[1], arrr1[2], arrr1[3] + + ''' Counting the number of + zeros in the given value of x''' + + temp = returnTwos(x) + temp1 = returnFives(x) + + i = ql - 1 + while(i < qr): + + ''' The value x has been multiplied + to their respective indices''' + + arr[i] = arr[i] * x + + ''' The value obtained above has been + added to their respective vectors''' + + twos[i] += temp + fives[i] += temp1 + i += 1 + + ''' If the query is of typee 2.''' + + if (typee == 2): + ql, qr, y = arrr1[1], arrr1[2], arrr1[3] + + ''' Counting the number of + zero in the given value of x''' + + temp = returnTwos(y) + temp1 = returnFives(y) + + i = ql - 1 + + while(i < qr): + + ''' The value y has been replaced + to their respective indices''' + + arr[i] = (i - ql + 2) * y + + ''' The value obtained above has been + added to their respective vectors''' + + twos[i] = returnTwos(i - ql + 2) + temp + fives[i] = returnFives(i - ql + 2) + temp1 + i += 1 + + ''' If the query is of typee 2''' + + if (typee == 3): + ql, qr = arrr1[1], arrr1[2] + sumtwos = 0 + sumfives = 0 + + i = ql - 1 + + while(i < qr): + + ''' As the number of trailing zeros for + each case has been found for each array + element then we simply add those to + the respective index to a variable''' + + sumtwos += twos[i] + sumfives += fives[i] + i += 1 + + ''' Compare the number of zeros + obtained in the multiples of five and two + consider the minimum of them and add them''' + + sum += min(sumtwos, sumfives) + + '''Driver code''' + + + '''Input the Size of array +and number of queries''' + +n, m = map(int, input().split()) +arr = list(map(int, input().split())) + +for i in range(n): + twos[i] = returnTwos(arr[i]) + fives[i] = returnFives(arr[i]) + + '''Running the while loop +for m number of queries''' + +while (m): + m -= 1 + solve_queries(arr, n) + +print(sum) + + +" +Find a number in minimum steps,"/*Java program to Find a +number in minimum steps*/ + +import java.util.*; +class GFG +{ + static Vector find(int n) + { +/* Steps sequence*/ + + Vector ans = new Vector<>(); +/* Current sum*/ + + int sum = 0; + int i = 1; +/* Sign of the number*/ + + int sign = (n >= 0 ? 1 : -1); + n = Math.abs(n); +/* Basic steps required to get + sum >= required value.*/ + + for (; sum < n;) + { + ans.add(sign * i); + sum += i; + i++; + } +/* If we have reached ahead to destination.*/ + + if (sum > sign * n) + { + /*If the last step was an odd number, + then it has following mechanism for + negating a particular number and + decreasing the sum to required number + Also note that it may require + 1 more step in order to reach the sum. */ + + if (i % 2 != 0) + { + sum -= n; + if (sum % 2 != 0) + { + ans.add(sign * i); + sum += i; + i++; + } + int a = ans.get((sum / 2) - 1); + ans.remove((sum / 2) - 1); + ans.add(((sum / 2) - 1), a*(-1)); + } + else + { + /* If the current time instance is even + and sum is odd than it takes + 2 more steps and few + negations in previous elements + to reach there. */ + + sum -= n; + if (sum % 2 != 0) + { + sum--; + ans.add(sign * i); + ans.add(sign * -1 * (i + 1)); + } + ans.add((sum / 2) - 1, ans.get((sum / 2) - 1) * -1); + } + } + return ans; + } +/* Driver Program*/ + + public static void main(String[] args) + { + int n = 20; + if (n == 0) + System.out.print(""Minimum number of Steps: 0\nStep sequence:\n0""); + else + { + Vector a = find(n); + System.out.print(""Minimum number of Steps: "" + + a.size()+ ""\nStep sequence:\n""); + for (int i : a) + System.out.print(i + "" ""); + } + } +}"," '''Python3 program to Find a +number in minimum steps''' + +def find(n): + ''' Steps sequence''' + + ans = [] + ''' Current sum''' + + Sum = 0 + i = 0 + ''' Sign of the number''' + + sign = 0 + if (n >= 0): + sign = 1 + else: + sign = -1 + n = abs(n) + i = 1 + ''' Basic steps required to get + sum >= required value.''' + + while (Sum < n): + ans.append(sign * i) + Sum += i + i += 1 + ''' If we have reached ahead to destination.''' + + if (Sum > sign * n): + ''' If the last step was an odd number, + then it has following mechanism for + negating a particular number and + decreasing the sum to required number + Also note that it may require + 1 more step in order to reach the sum.''' + + if (i % 2!=0): + Sum -= n + if (Sum % 2 != 0): + ans.append(sign * i) + Sum += i + i += 1 + ans[int(Sum / 2) - 1] *= -1 + else: + ''' If the current time instance is even + and sum is odd than it takes + 2 more steps and few + negations in previous elements + to reach there.''' + + Sum -= n + if (Sum % 2 != 0): + Sum -= 1 + ans.append(sign * i) + ans.append(sign * -1 * (i + 1)) + ans[int((sum / 2)) - 1] *= -1 + return ans + '''Driver code''' + +n = 20 +if (n == 0): + print(""Minimum number of Steps: 0\nStep sequence:\n0"") +else: + a = find(n) + print(""Minimum number of Steps:"", len(a)) + print(""Step sequence:"") + print(*a, sep = "" "")" +Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree,"/*Java program to construct full binary tree +using its preorder traversal and preorder +traversal of its mirror tree */ + +class GFG +{ +/*A Binary Tree Node */ + +static class Node +{ + int data; + Node left, right; +}; +static class INT +{ + int a; + INT(int a){this.a=a;} +} +/*Utility function to create a new tree node */ + +static Node newNode(int data) +{ + Node temp = new Node(); + temp.data = data; + temp.left = temp.right = null; + return temp; +} +/*A utility function to print inorder traversal +of a Binary Tree */ + +static void printInorder(Node node) +{ + if (node == null) + return; + printInorder(node.left); + System.out.printf(""%d "", node.data); + printInorder(node.right); +} +/*A recursive function to con Full binary tree +from pre[] and preM[]. preIndex is used to keep +track of index in pre[]. l is low index and h is high +index for the current subarray in preM[] */ + +static Node conBinaryTreeUtil(int pre[], int preM[], + INT preIndex, int l, int h, int size) +{ +/* Base case */ + + if (preIndex.a >= size || l > h) + return null; +/* The first node in preorder traversal is root. + So take the node at preIndex from preorder and + make it root, and increment preIndex */ + + Node root = newNode(pre[preIndex.a]); + ++(preIndex.a); +/* If the current subarry has only one element, + no need to recur */ + + if (l == h) + return root; +/* Search the next element of pre[] in preM[] */ + + int i; + for (i = l; i <= h; ++i) + if (pre[preIndex.a] == preM[i]) + break; +/* con left and right subtrees recursively */ + + if (i <= h) + { + root.left = conBinaryTreeUtil (pre, preM, + preIndex, i, h, size); + root.right = conBinaryTreeUtil (pre, preM, + preIndex, l + 1, i - 1, size); + } +/* return root */ + + return root; +} +/*function to con full binary tree +using its preorder traversal and preorder +traversal of its mirror tree */ + +static void conBinaryTree(Node root,int pre[], + int preMirror[], int size) +{ + INT preIndex = new INT(0); + int preMIndex = 0; + root = conBinaryTreeUtil(pre,preMirror, + preIndex, 0, size - 1, size); + printInorder(root); +} +/*Driver code*/ + +public static void main(String args[]) +{ + int preOrder[] = {1,2,4,5,3,6,7}; + int preOrderMirror[] = {1,3,7,6,2,5,4}; + int size = preOrder.length; + Node root = new Node(); + conBinaryTree(root,preOrder,preOrderMirror,size); +} +}"," '''Python3 program to construct full binary +tree using its preorder traversal and +preorder traversal of its mirror tree ''' + + '''Utility function to create a new tree node ''' + +class newNode: + def __init__(self,data): + self.data = data + self.left = self.right = None '''A utility function to print inorder +traversal of a Binary Tree ''' + +def prInorder(node): + if (node == None) : + return + prInorder(node.left) + print(node.data, end = "" "") + prInorder(node.right) + '''A recursive function to construct Full +binary tree from pre[] and preM[]. +preIndex is used to keep track of index +in pre[]. l is low index and h is high +index for the current subarray in preM[] ''' + +def constructBinaryTreeUtil(pre, preM, preIndex, + l, h, size): + ''' Base case ''' + + if (preIndex >= size or l > h) : + return None , preIndex + ''' The first node in preorder traversal + is root. So take the node at preIndex + from preorder and make it root, and + increment preIndex ''' + + root = newNode(pre[preIndex]) + preIndex += 1 + ''' If the current subarry has only + one element, no need to recur ''' + + if (l == h): + return root, preIndex + ''' Search the next element of + pre[] in preM[]''' + + i = 0 + for i in range(l, h + 1): + if (pre[preIndex] == preM[i]): + break + ''' construct left and right subtrees + recursively ''' + + if (i <= h): + root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, + i, h, size) + root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, + l + 1, i - 1, size) + ''' return root ''' + + return root, preIndex + '''function to construct full binary tree +using its preorder traversal and preorder +traversal of its mirror tree''' + +def constructBinaryTree(root, pre, preMirror, size): + preIndex = 0 + preMIndex = 0 + root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, + 0, size - 1, size) + prInorder(root) + '''Driver code ''' + +if __name__ ==""__main__"": + preOrder = [1, 2, 4, 5, 3, 6, 7] + preOrderMirror = [1, 3, 7, 6, 2, 5, 4] + size = 7 + root = newNode(0) + constructBinaryTree(root, preOrder, + preOrderMirror, size)" +Elements that occurred only once in the array,"/*Java implementation to find +elements that appeared only once*/ + +class GFG +{ +/*Function to find the elements that +appeared only once in the array*/ + +static void occurredOnce(int arr[], int n) +{ + int i = 1, len = n; + +/* Check if the first and last + element is equal. If yes, + remove those elements*/ + + if (arr[0] == arr[len - 1]) + { + i = 2; + len--; + } + +/* Start traversing the + remaining elements*/ + + for (; i < n; i++) + +/* Check if current element is + equal to the element at + immediate previous index + If yes, check the same + for next element*/ + + if (arr[i] == arr[i - 1]) + i++; + +/* Else print the current element*/ + + else + System.out.print(arr[i - 1] + "" ""); + +/* Check for the last element*/ + + if (arr[n - 1] != arr[0] && + arr[n - 1] != arr[n - 2]) + System.out.print(arr[n - 1]); +} + +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {7, 7, 8, 8, 9, + 1, 1, 4, 2, 2}; + int n = arr.length; + + occurredOnce(arr, n); +} +} + + +"," '''Python 3 implementation to find +elements that appeared only once''' + + + '''Function to find the elements that +appeared only once in the array''' + +def occurredOnce(arr, n): + i = 1 + len = n + + ''' Check if the first and + last element is equal + If yes, remove those elements''' + + if arr[0] == arr[len - 1]: + i = 2 + len -= 1 + + ''' Start traversing the + remaining elements''' + + while i < n: + + ''' Check if current element is + equal to the element at + immediate previous index + If yes, check the same for + next element''' + + if arr[i] == arr[i - 1]: + i += 1 + + ''' Else print the current element''' + + else: + print(arr[i - 1], end = "" "") + + i += 1 + + ''' Check for the last element''' + + if (arr[n - 1] != arr[0] and + arr[n - 1] != arr[n - 2]): + print(arr[n - 1]) + + '''Driver code''' + +if __name__ == ""__main__"": + arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] + n = len(arr) + + occurredOnce(arr, n) + + +" +"Given an array arr[], find the maximum j","/*Java program for the above approach*/ + +class FindMaximum { + /* For a given array arr[], + returns the maximum j-i such + that arr[j] > arr[i] */ + + int maxIndexDiff(int arr[], int n) + { + int maxDiff = -1; + int i, j; + + for (i = 0; i < n; ++i) { + for (j = n - 1; j > i; --j) { + if (arr[j] > arr[i] && maxDiff < (j - i)) + maxDiff = j - i; + } + } + + return maxDiff; + } + + /* Driver program to test above functions */ + + public static void main(String[] args) + { + FindMaximum max = new FindMaximum(); + int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 }; + int n = arr.length; + int maxDiff = max.maxIndexDiff(arr, n); + System.out.println(maxDiff); + } +} +"," '''Python3 program to find the maximum +j – i such that arr[j] > arr[i]''' + + + '''For a given array arr[], returns +the maximum j – i such that +arr[j] > arr[i]''' + + + +def maxIndexDiff(arr, n): + maxDiff = -1 + for i in range(0, n): + j = n - 1 + while(j > i): + if arr[j] > arr[i] and maxDiff < (j - i): + maxDiff = j - i + j -= 1 + + return maxDiff + + + '''driver code''' + +arr = [9, 2, 3, 4, 5, 6, 7, 8, 18, 0] +n = len(arr) +maxDiff = maxIndexDiff(arr, n) +print(maxDiff) + + +" +Sparse Table,"/*Java program to do range minimum query +using sparse table*/ + +import java.util.*; +class GFG +{ +static final int MAX = 500; +/*lookup[i][j] is going to store GCD of +arr[i..j]. Ideally lookup table +size should not be fixed and should be +determined using n Log n. It is kept +constant to keep code simple.*/ + +static int [][]table = new int[MAX][MAX]; +/*it builds sparse table.*/ + +static void buildSparseTable(int arr[], + int n) +{ +/* GCD of single element is + element itself*/ + + for (int i = 0; i < n; i++) + table[i][0] = arr[i]; +/* Build sparse table*/ + + for (int j = 1; j <= n; j++) + for (int i = 0; i <= n - (1 << j); i++) + table[i][j] = __gcd(table[i][j - 1], + table[i + (1 << (j - 1))][j - 1]); +} +/*Returns GCD of arr[L..R]*/ + +static int query(int L, int R) +{ +/* Find highest power of 2 that is + smaller than or equal to count of + elements in given range.For [2, 10], j = 3*/ + + int j = (int)Math.log(R - L + 1); +/* Compute GCD of last 2^j elements + with first 2^j elements in range. + For [2, 10], we find GCD of + arr[lookup[0][3]] and arr[lookup[3][3]],*/ + + return __gcd(table[L][j], + table[R - (1 << j) + 1][j]); +} +static int __gcd(int a, int b) +{ + return b == 0 ? a : __gcd(b, a % b); +} +/*Driver Code*/ + +public static void main(String[] args) +{ + int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; + int n = a.length; + buildSparseTable(a, n); + System.out.print(query(0, 2) + ""\n""); + System.out.print(query(1, 3) + ""\n""); + System.out.print(query(4, 5) + ""\n""); +} +}"," '''Python3 program to do range minimum +query using sparse table''' + +import math + ''' lookup[i][j] is going to store minimum + value in arr[i..j]. Ideally lookup table + size should not be fixed and should be + determined using n Log n. It is kept + constant to keep code simple.''' + + '''Fills lookup array lookup[][] in +bottom up manner.''' + +def buildSparseTable(arr, n): + ''' GCD of single element is element itself''' + + for i in range(0, n): + table[i][0] = arr[i] + ''' Build sparse table''' + + j = 1 + while (1 << j) <= n: + i = 0 + while i <= n - (1 << j): + table[i][j] = math.gcd(table[i][j - 1], + table[i + (1 << (j - 1))][j - 1]) + i += 1 + j += 1 + '''Returns minimum of arr[L..R]''' + +def query(L, R): + ''' Find highest power of 2 that is smaller + than or equal to count of elements in + given range. For [2, 10], j = 3''' + + j = int(math.log2(R - L + 1)) + ''' Compute GCD of last 2^j elements with + first 2^j elements in range. + For [2, 10], we find GCD of arr[lookup[0][3]] + and arr[lookup[3][3]],''' + + return math.gcd(table[L][j], + table[R - (1 << j) + 1][j]) + '''Driver Code''' + +if __name__ == ""__main__"": + a = [7, 2, 3, 0, 5, 10, 3, 12, 18] + n = len(a) + MAX = 500 + table = [[0 for i in range(MAX)] for j in range(MAX)] + buildSparseTable(a, n) + print(query(0, 2)) + print(query(1, 3)) + print(query(4, 5))" +Check whether Arithmetic Progression can be formed from the given array,"/*Java program to check if a given array +can form arithmetic progression*/ + +import java.util.Arrays; + +class GFG { + +/* Returns true if a permutation of + arr[0..n-1] can form arithmetic + progression*/ + + static boolean checkIsAP(int arr[], int n) + { + if (n == 1) + return true; + +/* Sort array*/ + + Arrays.sort(arr); + +/* After sorting, difference between + consecutive elements must be same.*/ + + int d = arr[1] - arr[0]; + for (int i = 2; i < n; i++) + if (arr[i] - arr[i-1] != d) + return false; + + return true; + } + +/* driver code*/ + + public static void main (String[] args) + { + int arr[] = { 20, 15, 5, 0, 10 }; + int n = arr.length; + + if(checkIsAP(arr, n)) + System.out.println(""Yes""); + else + System.out.println(""No""); + } +} + + +"," '''Python3 program to check if a given +array can form arithmetic progression''' + + + '''Returns true if a permutation of arr[0..n-1] +can form arithmetic progression''' + +def checkIsAP(arr, n): + if (n == 1): return True + + ''' Sort array''' + + arr.sort() + + ''' After sorting, difference between + consecutive elements must be same.''' + + d = arr[1] - arr[0] + for i in range(2, n): + if (arr[i] - arr[i-1] != d): + return False + + return True + + '''Driver code''' + +arr = [ 20, 15, 5, 0, 10 ] +n = len(arr) +print(""Yes"") if(checkIsAP(arr, n)) else print(""No"") + + +" +Sort an array according to absolute difference with given value,"/*Java program to sort an array according absolute +difference with x.*/ + +import java.io.*; +import java.util.*; +class GFG +{ +/* Function to sort an array according absolute + difference with x.*/ + + static void rearrange(int[] arr, int n, int x) + { + TreeMap> m = + new TreeMap<>(); +/* Store values in a map with the difference + with X as key*/ + + for (int i = 0; i < n; i++) + { + int diff = Math.abs(x - arr[i]); + if (m.containsKey(diff)) + { + ArrayList al = m.get(diff); + al.add(arr[i]); + m.put(diff, al); + } + else + { + ArrayList al = new + ArrayList<>(); + al.add(arr[i]); + m.put(diff,al); + } + } +/* Update the values of array*/ + + int index = 0; + for (Map.Entry entry : m.entrySet()) + { + ArrayList al = m.get(entry.getKey()); + for (int i = 0; i < al.size(); i++) + arr[index++] = al.get(i); + } + } +/* Function to print the array*/ + + static void printArray(int[] arr, int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + "" ""); + } +/* Driver code*/ + + public static void main(String args[]) + { + int[] arr = {10, 5, 3, 9 ,2}; + int n = arr.length; + int x = 7; + rearrange(arr, n, x); + printArray(arr, n); + } +}"," '''Python3 program to sort an +array according absolute +difference with x. + ''' '''Function to sort an array +according absolute difference +with x.''' + +def rearrange(arr, n, x): + m = {} + ''' Store values in a map + with the difference + with X as key''' + + for i in range(n): + m[arr[i]] = abs(x - arr[i]) + m = {k : v for k, v in sorted(m.items(), + key = lambda item : item[1])} + ''' Update the values of array''' + + i = 0 + for it in m.keys(): + arr[i] = it + i += 1 + '''Function to print the array''' + +def printArray(arr, n): + for i in range(n): + print(arr[i], end = "" "") + '''Driver code''' + +if __name__ == ""__main__"": + arr = [10, 5, 3, 9, 2] + n = len(arr) + x = 7 + rearrange(arr, n, x) + printArray(arr, n)" +Compute the minimum or maximum of two integers without branching,"/*JAVA implementation of above approach*/ + +class GFG +{ +static int CHAR_BIT = 4; +static int INT_BIT = 8; +/*Function to find minimum of x and y*/ + +static int min(int x, int y) +{ + return y + ((x - y) & ((x - y) >> + (INT_BIT * CHAR_BIT - 1))); +} +/*Function to find maximum of x and y*/ + +static int max(int x, int y) +{ + return x - ((x - y) & ((x - y) >> + (INT_BIT * CHAR_BIT - 1))); +} +/* Driver code */ + +public static void main(String[] args) +{ + int x = 15; + int y = 6; + System.out.println(""Minimum of ""+x+"" and ""+y+"" is ""+min(x, y)); + System.out.println(""Maximum of ""+x+"" and ""+y+"" is ""+max(x, y)); +} +}"," '''Python3 implementation of the approach''' + +import sys; +CHAR_BIT = 8; +INT_BIT = sys.getsizeof(int()); + '''Function to find minimum of x and y''' + +def Min(x, y): + return y + ((x - y) & ((x - y) >> + (INT_BIT * CHAR_BIT - 1))); + '''Function to find maximum of x and y''' + +def Max(x, y): + return x - ((x - y) & ((x - y) >> + (INT_BIT * CHAR_BIT - 1))); + '''Driver code''' + +x = 15; +y = 6; +print(""Minimum of"", x, ""and"", + y, ""is"", Min(x, y)); +print(""Maximum of"", x, ""and"", + y, ""is"", Max(x, y));" +How to check if a given array represents a Binary Heap?,"/*Java program to check whether a given array +represents a max-heap or not*/ + +class GFG +{ +/* Returns true if arr[i..n-1] + represents a max-heap*/ + + static boolean isHeap(int arr[], + int i, int n) + { +/* If a leaf node*/ + + if (i >= (n - 2) / 2) + { + return true; + } +/* If an internal node and + is greater than its + children, and same is + recursively true for the + children*/ + + if (arr[i] >= arr[2 * i + 1] + && arr[i] >= arr[2 * i + 2] + && isHeap(arr, 2 * i + 1, n) + && isHeap(arr, 2 * i + 2, n)) + { + return true; + } + return false; + } +/* Driver program*/ + + public static void main(String[] args) + { + int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; + int n = arr.length - 1; + if (isHeap(arr, 0, n)) { + System.out.println(""Yes""); + } + else { + System.out.println(""No""); + } + } +}"," '''Python3 program to check whether a +given array represents a max-heap or not + ''' '''Returns true if arr[i..n-1] +represents a max-heap''' + +def isHeap(arr, i, n): + '''If a leaf node''' + + if i >= int((n - 2) / 2): + return True + ''' If an internal node and is greater + than its children, and same is + recursively true for the children''' + + if(arr[i] >= arr[2 * i + 1] and + arr[i] >= arr[2 * i + 2] and + isHeap(arr, 2 * i + 1, n) and + isHeap(arr, 2 * i + 2, n)): + return True + return False + '''Driver Code''' + +if __name__ == '__main__': + arr = [90, 15, 10, 7, 12, 2, 7, 3] + n = len(arr) - 1 + if isHeap(arr, 0, n): + print(""Yes"") + else: + print(""No"")" +Program to cyclically rotate an array by one,"import java.util.Arrays; +public class Test +{ + static int arr[] = new int[]{1, 2, 3, 4, 5}; + + /*i and j pointing to first and last element respectively*/ + + static void rotate() + { + int i = 0, j = arr.length - 1; + while(i != j) + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + i++; + } + }/* Driver program */ + + public static void main(String[] args) + { + System.out.println(""Given Array is""); + System.out.println(Arrays.toString(arr)); + rotate(); + System.out.println(""Rotated Array is""); + System.out.println(Arrays.toString(arr)); + } +}"," + '''i and j pointing to first and last element respectively''' + +def rotate(arr, n): + i = 0 + j = n - 1 + while i != j: + arr[i], arr[j] = arr[j], arr[i] + i = i + 1 + pass '''Driver function''' + +arr= [1, 2, 3, 4, 5] +n = len(arr) +print (""Given array is"") +for i in range(0, n): + print (arr[i], end = ' ') +rotate(arr, n) +print (""\nRotated array is"") +for i in range(0, n): + print (arr[i], end = ' ')" +Count 1's in a sorted binary array,"/*Java program to count 1's in a sorted array*/ + +class CountOnes +{ + /* Returns counts of 1's in arr[low..high]. The + array is assumed to be sorted in non-increasing + order */ + + int countOnes(int arr[], int low, int high) + { + if (high >= low) + { +/* get the middle index*/ + + int mid = low + (high - low) / 2; + +/* check if the element at middle index is last + 1*/ + + if ((mid == high || arr[mid + 1] == 0) + && (arr[mid] == 1)) + return mid + 1; + +/* If element is not last 1, recur for right + side*/ + + if (arr[mid] == 1) + return countOnes(arr, (mid + 1), high); + +/* else recur for left side*/ + + return countOnes(arr, low, (mid - 1)); + } + return 0; + } + + /* Driver code */ + + public static void main(String args[]) + { + CountOnes ob = new CountOnes(); + int arr[] = { 1, 1, 1, 1, 0, 0, 0 }; + int n = arr.length; + System.out.println(""Count of 1's in given array is "" + + ob.countOnes(arr, 0, n - 1)); + } +} + +"," '''Python program to count one's in a boolean array''' + + + '''Returns counts of 1's in arr[low..high]. The array is +assumed to be sorted in non-increasing order''' + +def countOnes(arr,low,high): + + if high>=low: + + ''' get the middle index''' + + mid = low + (high-low)//2 + + ''' check if the element at middle index is last 1''' + + if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)): + return mid+1 + + ''' If element is not last 1, recur for right side''' + + if arr[mid]==1: + return countOnes(arr, (mid+1), high) + + ''' else recur for left side''' + + return countOnes(arr, low, mid-1) + + return 0 + + '''Driver Code''' + +arr=[1, 1, 1, 1, 0, 0, 0] +print (""Count of 1's in given array is"",countOnes(arr, 0 , len(arr)-1)) + + +" +Remove minimum number of elements such that no common element exist in both array,"/*JAVA Code to Remove minimum number of elements +such that no common element exist in both array*/ + +import java.util.*; +class GFG { +/* To find no elements to remove + so no common element exist*/ + + public static int minRemove(int a[], int b[], int n, + int m) + { +/* To store count of array element*/ + + HashMap countA = new HashMap< + Integer, Integer>(); + HashMap countB = new HashMap< + Integer, Integer>(); +/* Count elements of a*/ + + for (int i = 0; i < n; i++){ + if (countA.containsKey(a[i])) + countA.put(a[i], countA.get(a[i]) + 1); + else countA.put(a[i], 1); + } +/* Count elements of b*/ + + for (int i = 0; i < m; i++){ + if (countB.containsKey(b[i])) + countB.put(b[i], countB.get(b[i]) + 1); + else countB.put(b[i], 1); + } +/* Traverse through all common element, and + pick minimum occurrence from two arrays*/ + + int res = 0; + Set s = countA.keySet(); + for (int x : s) + if(countB.containsKey(x)) + res += Math.min(countB.get(x), + countA.get(x)); +/* To return count of minimum elements*/ + + return res; + } + /* Driver program to test above function */ + + public static void main(String[] args) + { + int a[] = { 1, 2, 3, 4 }; + int b[] = { 2, 3, 4, 5, 8 }; + int n = a.length; + int m = b.length; + System.out.println(minRemove(a, b, n, m)); + } +}"," '''Python3 program to find minimum +element to remove so no common +element exist in both array''' '''To find no elements to remove +so no common element exist''' + +def minRemove(a, b, n, m): + ''' To store count of array element''' + + countA = dict() + countB = dict() + ''' Count elements of a''' + + for i in range(n): + countA[a[i]] = countA.get(a[i], 0) + 1 + ''' Count elements of b''' + + for i in range(n): + countB[b[i]] = countB.get(b[i], 0) + 1 + ''' Traverse through all common + element, and pick minimum + occurrence from two arrays''' + + res = 0 + for x in countA: + if x in countB.keys(): + res += min(countA[x],countB[x]) + ''' To return count of + minimum elements''' + + return res + '''Driver Code''' + +a = [ 1, 2, 3, 4 ] +b = [2, 3, 4, 5, 8 ] +n = len(a) +m = len(b) +print(minRemove(a, b, n, m))" +Check if an array is sorted and rotated,"import java.io.*; + +class GFG { + +/* Function to check if an array is + Sorted and rotated clockwise*/ + + static boolean checkIfSortRotated(int arr[], int n) + { +/* Initializing two variables x,y as zero.*/ + + int x = 0, y = 0; + +/* Traversing array 0 to last element. + n-1 is taken as we used i+1.*/ + + for (int i = 0; i < n - 1; i++) { + if (arr[i] < arr[i + 1]) + x++; + else + y++; + } + +/* 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.*/ + + if (x == 1 || y == 1) { +/* Checking for last element with first.*/ + + if (arr[n - 1] < arr[0]) + x++; + else + y++; + +/* Checking for final result.*/ + + if (x == 1 || y == 1) + return true; + } +/* If still not true then definetly false.*/ + + return false; + } + +/* Driver code*/ + + public static void main(String[] args) + { + int arr[] = { 5, 1, 2, 3, 4 }; + + int n = arr.length; + +/* Function Call*/ + + boolean x = checkIfSortRotated(arr, n); + if (x == true) + System.out.println(""YES""); + else + System.out.println(""NO""); + } +} +", +Merge k sorted arrays | Set 1,"/*Java program to merge k sorted arrays of size n each.*/ + +import java.util.*; +class GFG{ + static final int n = 4; +/* Merge arr1[0..n1-1] and arr2[0..n2-1] into + arr3[0..n1+n2-1]*/ + + static void mergeArrays(int arr1[], int arr2[], int n1, + int n2, int arr3[]) + { + int i = 0, j = 0, k = 0; +/* Traverse both array*/ + + while (i q= new LinkedList(); +/* add root*/ + + q.add(root); +/* add delimiter*/ + + q.add(null); + while (q.size()>0) { + Node temp = q.peek(); + q.remove(); +/* if current is delimiter then insert another + for next diagonal and cout nextline*/ + + if (temp == null) { +/* if queue is empty return*/ + + if (q.size()==0) + return; +/* output nextline*/ + + System.out.println(); +/* add delimiter again*/ + + q.add(null); + } + else { + while (temp!=null) { + System.out.print( temp.data + "" ""); +/* if left child is present + add into queue*/ + + if (temp.left!=null) + q.add(temp.left); +/* current equals to right child*/ + + temp = temp.right; + } + } + } +} +/*Driver Code*/ + +public static void main(String args[]) +{ + Node root = newNode(8); + root.left = newNode(3); + root.right = newNode(10); + root.left.left = newNode(1); + root.left.right = newNode(6); + root.right.right = newNode(14); + root.right.right.left = newNode(13); + root.left.right.left = newNode(4); + root.left.right.right = newNode(7); + diagonalPrint(root); +} +}"," '''Python3 program to construct string from binary tree''' + + '''A binary tree node has data, pointer to left + child and a pointer to right child''' + +class Node: + def __init__(self,data): + self.val = data + self.left = None + self.right = None + '''Function to print diagonal view''' + +def diagonalprint(root): + ''' base case''' + + if root is None: + return + ''' queue of treenode''' + + q = [] + ''' Append root''' + + q.append(root) + ''' Append delimiter''' + + q.append(None) + while len(q) > 0: + temp = q.pop(0) + ''' If current is delimiter then insert another + for next diagonal and cout nextline''' + + if not temp: + ''' If queue is empty then return''' + + if len(q) == 0: + return + ''' Print output on nextline''' + + print(' ') + ''' append delimiter again''' + + q.append(None) + else: + while temp: + print(temp.val, end = ' ') + ''' If left child is present + append into queue''' + + if temp.left: + q.append(temp.left) + ''' current equals to right child''' + + temp = temp.right + '''Driver Code''' + +root = Node(8) +root.left = Node(3) +root.right = Node(10) +root.left.left = Node(1) +root.left.right = Node(6) +root.right.right = Node(14) +root.right.right.left = Node(13) +root.left.right.left = Node(4) +root.left.right.right = Node(7) +diagonalprint(root)" +Maximum possible difference of two subsets of an array,"/*Java find maximum +difference of subset sum*/ + +import java.util.*; +class GFG{ +/*Function for maximum subset diff*/ + +public static int maxDiff(int arr[], + int n) +{ + HashMap hashPositive = new HashMap<>(); + HashMap hashNegative = new HashMap<>(); + int SubsetSum_1 = 0, + SubsetSum_2 = 0; +/* Construct hash for + positive elements*/ + + for (int i = 0; i <= n - 1; i++) + { + if (arr[i] > 0) + { + if(hashPositive.containsKey(arr[i])) + { + hashPositive.replace(arr[i], + hashPositive.get(arr[i]) + 1); + } + else + { + hashPositive.put(arr[i], 1); + } + } + } +/* Calculate subset sum + for positive elements*/ + + for (int i = 0; i <= n - 1; i++) + { + if(arr[i] > 0 && + hashPositive.containsKey(arr[i])) + { + if(hashPositive.get(arr[i]) == 1) + { + SubsetSum_1 += arr[i]; + } + } + } +/* Construct hash for + negative elements*/ + + for (int i = 0; i <= n - 1; i++) + { + if (arr[i] < 0) + { + if(hashNegative.containsKey(Math.abs(arr[i]))) + { + hashNegative.replace(Math.abs(arr[i]), + hashNegative.get(Math.abs(arr[i])) + 1); + } + else + { + hashNegative.put(Math.abs(arr[i]), 1); + } + } + } +/* Calculate subset sum for + negative elements*/ + + for (int i = 0; i <= n - 1; i++) + { + if (arr[i] < 0 && + hashNegative.containsKey(Math.abs(arr[i]))) + { + if(hashNegative.get(Math.abs(arr[i])) == 1) + { + SubsetSum_2 += arr[i]; + } + } + } + return Math.abs(SubsetSum_1 - SubsetSum_2); +} +/*Driver code*/ + +public static void main(String[] args) +{ + int arr[] = {4, 2, -3, 3, + -2, -2, 8}; + int n = arr.length; + System.out.print(""Maximum Difference = "" + + maxDiff(arr, n)); +} +}"," '''Python3 find maximum difference of subset sum + ''' '''function for maximum subset diff''' + +def maxDiff(arr, n): + hashPositive = dict() + hashNegative = dict() + SubsetSum_1, SubsetSum_2 = 0, 0 + ''' construct hash for positive elements''' + + for i in range(n): + if (arr[i] > 0): + hashPositive[arr[i]] = \ + hashPositive.get(arr[i], 0) + 1 + ''' calculate subset sum for positive elements''' + + for i in range(n): + if (arr[i] > 0 and arr[i] in + hashPositive.keys() and + hashPositive[arr[i]] == 1): + SubsetSum_1 += arr[i] + ''' construct hash for negative elements''' + + for i in range(n): + if (arr[i] < 0): + hashNegative[abs(arr[i])] = \ + hashNegative.get(abs(arr[i]), 0) + 1 + ''' calculate subset sum for negative elements''' + + for i in range(n): + if (arr[i] < 0 and abs(arr[i]) in + hashNegative.keys() and + hashNegative[abs(arr[i])] == 1): + SubsetSum_2 += arr[i] + return abs(SubsetSum_1 - SubsetSum_2) + '''Driver Code''' + +arr = [4, 2, -3, 3, -2, -2, 8] +n = len(arr) +print(""Maximum Difference ="", maxDiff(arr, n))" +Random number generator in arbitrary probability distribution fashion,"/*Java program to generate random numbers +according to given frequency distribution*/ + +class GFG +{ +/*Utility function to find ceiling of r in arr[l..h]*/ + +static int findCeil(int arr[], int r, int l, int h) +{ + int mid; + while (l < h) + { +/*Same as mid = (l+h)/2*/ + +mid = l + ((h - l) >> 1); + if(r > arr[mid]) + l = mid + 1; + else + h = mid; + } + return (arr[l] >= r) ? l : -1; +} +/*The main function that returns a random number +from arr[] according to distribution array +defined by freq[]. n is size of arrays.*/ + +static int myRand(int arr[], int freq[], int n) +{ +/* Create and fill prefix array*/ + + int prefix[] = new int[n], i; + prefix[0] = freq[0]; + for (i = 1; i < n; ++i) + prefix[i] = prefix[i - 1] + freq[i]; +/* prefix[n-1] is sum of all frequencies. + Generate a random number with + value from 1 to this sum*/ + + int r = ((int)(Math.random()*(323567)) % prefix[n - 1]) + 1; +/* Find index of ceiling of r in prefix arrat*/ + + int indexc = findCeil(prefix, r, 0, n - 1); + return arr[indexc]; +} +/*Driver code*/ + +public static void main(String args[]) +{ + int arr[] = {1, 2, 3, 4}; + int freq[] = {10, 5, 20, 100}; + int i, n = arr.length; +/* Let us generate 10 random numbers accroding to + given distribution*/ + + for (i = 0; i < 5; i++) + System.out.println( myRand(arr, freq, n) ); +} +}"," '''Python3 program to generate random numbers +according to given frequency distribution''' + +import random + '''Utility function to find ceiling of r in arr[l..h]''' + +def findCeil(arr, r, l, h) : + while (l < h) : + '''Same as mid = (l+h)/2''' + + mid = l + ((h - l) >> 1); + if r > arr[mid] : + l = mid + 1 + else : + h = mid + if arr[l] >= r : + return l + else : + return -1 + '''The main function that returns a random number +from arr[] according to distribution array +defined by freq[]. n is size of arrays.''' + +def myRand(arr, freq, n) : + ''' Create and fill prefix array''' + + prefix = [0] * n + prefix[0] = freq[0] + for i in range(n) : + prefix[i] = prefix[i - 1] + freq[i] + ''' prefix[n-1] is sum of all frequencies. + Generate a random number with + value from 1 to this sum''' + + r = random.randint(0, prefix[n - 1]) + 1 + ''' Find index of ceiling of r in prefix arrat''' + + indexc = findCeil(prefix, r, 0, n - 1) + return arr[indexc] + '''Driver code''' + +arr = [1, 2, 3, 4] +freq = [10, 5, 20, 100] +n = len(arr) + '''Let us generate 10 random numbers accroding to +given distribution''' + +for i in range(5) : + print(myRand(arr, freq, n))" +Segregate 0s and 1s in an array,"/*Java code to segregate 0 and 1*/ + +import java.util.*; + +class GFG{ +/** +Method for segregation 0 and 1 given input array +*/ + +static void segregate0and1(int arr[]) { + int type0 = 0; + int type1 = arr.length - 1; + + while (type0 < type1) { + if (arr[type0] == 1) { + arr[type1] = arr[type1]+ arr[type0]; + arr[type0] = arr[type1]-arr[type0]; + arr[type1] = arr[type1]-arr[type0]; + type1--; + } else { + type0++; + } + } + + } +/*Driver program*/ + +public static void main(String[] args) { + + int[] array = {0, 1, 0, 1, 1, 1}; + + segregate0and1(array); + + for(int a : array){ + System.out.print(a+"" ""); + } + } +} +"," '''Python program to sort a +binary array in one pass''' + + + '''Function to put all 0s on +left and all 1s on right''' + +def segregate0and1(arr, size): + + type0 = 0 + type1 = size - 1 + + while(type0 < type1): + if(arr[type0] == 1): + (arr[type0], + arr[type1]) = (arr[type1], + arr[type0]) + type1 -= 1 + else: + type0 += 1 + + '''Driver Code''' + +arr = [0, 1, 0, 1, 1, 1] +arr_size = len(arr) +segregate0and1(arr, arr_size) +print(""Array after segregation is"", + end = "" "") +for i in range(0, arr_size): + print(arr[i], end = "" "") + + +" +Find the smallest and second smallest elements in an array,"/*Java program to find smallest and second smallest elements*/ + +import java.io.*; +class SecondSmallest +{ + /* Function to print first smallest and second smallest + elements */ + + static void print2Smallest(int arr[]) + { + int first, second, arr_size = arr.length; + /* There should be atleast two elements */ + + if (arr_size < 2) + { + System.out.println("" Invalid Input ""); + return; + } + first = second = Integer.MAX_VALUE; + for (int i = 0; i < arr_size ; i ++) + { + /* If current element is smaller than first + then update both first and second */ + + if (arr[i] < first) + { + second = first; + first = arr[i]; + } + /* If arr[i] is in between first and second + then update second */ + + else if (arr[i] < second && arr[i] != first) + second = arr[i]; + } + if (second == Integer.MAX_VALUE) + System.out.println(""There is no second"" + + ""smallest element""); + else + System.out.println(""The smallest element is "" + + first + "" and second Smallest"" + + "" element is "" + second); + } + /* Driver program to test above functions */ + + public static void main (String[] args) + { + int arr[] = {12, 13, 1, 10, 34, 1}; + print2Smallest(arr); + } +}"," '''Python program to find smallest and second smallest elements''' + +import sys + '''Function to print first smallest and second smallest + elements ''' + +def print2Smallest(arr): ''' There should be atleast two elements''' + + arr_size = len(arr) + if arr_size < 2: + print ""Invalid Input"" + return + first = second = sys.maxint + for i in range(0, arr_size): + ''' If current element is smaller than first then + update both first and second''' + + if arr[i] < first: + second = first + first = arr[i] + ''' If arr[i] is in between first and second then + update second''' + + elif (arr[i] < second and arr[i] != first): + second = arr[i]; + if (second == sys.maxint): + print ""No second smallest element"" + else: + print 'The smallest element is',first,'and' \ + ' second smallest element is',second + '''Driver function to test above function''' + +arr = [12, 13, 1, 10, 34, 1] +print2Smallest(arr)" +Program for addition of two matrices,"/*Java program for addition +of two matrices*/ + +class GFG +{ + static final int N = 4; +/* This function adds A[][] and B[][], and stores + the result in C[][]*/ + + static void add(int A[][], int B[][], int C[][]) + { + int i, j; + for (i = 0; i < N; i++) + for (j = 0; j < N; j++) + C[i][j] = A[i][j] + B[i][j]; + } +/* Driver code*/ + + public static void main (String[] args) + { + int A[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {4, 4, 4, 4}}; + int B[][] = { {1, 1, 1, 1}, + {2, 2, 2, 2}, + {3, 3, 3, 3}, + {4, 4, 4, 4}}; + int C[][] = new int[N][N]; + int i, j; + add(A, B, C); + System.out.print(""Result matrix is \n""); + for (i = 0; i < N; i++) + { + for (j = 0; j < N; j++) + System.out.print(C[i][j] + "" ""); + System.out.print(""\n""); + } + } +}"," '''Python3 program for addition +of two matrices''' + +N = 4 + '''This function adds A[][] +and B[][], and stores +the result in C[][]''' + +def add(A,B,C): + for i in range(N): + for j in range(N): + C[i][j] = A[i][j] + B[i][j] + '''driver code''' + +A = [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] +B= [ [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4]] +C=A[:][:] +add(A, B, C) +print(""Result matrix is"") +for i in range(N): + for j in range(N): + print(C[i][j], "" "", end='') + print()" +Equilibrium index of an array,"/*Java program to find equilibrium +index of an array*/ + +class EquilibriumIndex { +/*function to find the equilibrium index*/ + + int equilibrium(int arr[], int n) + { + int i, j; + int leftsum, rightsum; + /* Check for indexes one by one until + an equilibrium index is found */ + + for (i = 0; i < n; ++i) { + leftsum = 0; + rightsum = 0; /* get left sum */ + + + for (j = 0; j < i; j++) + leftsum += arr[j]; + /* get right sum */ + + for (j = i + 1; j < n; j++) + rightsum += arr[j]; + /* if leftsum and rightsum are same, + then we are done */ + + if (leftsum == rightsum) + return i; + } + /* return -1 if no equilibrium index is found */ + + return -1; + } +/* Driver code*/ + + public static void main(String[] args) + { + EquilibriumIndex equi = new EquilibriumIndex(); + int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; + int arr_size = arr.length; + System.out.println(equi.equilibrium(arr, arr_size)); + } +}"," '''Python program to find equilibrium +index of an array''' + + '''function to find the equilibrium index''' + +def equilibrium(arr): + leftsum = 0 + rightsum = 0 + n = len(arr) ''' Check for indexes one by one + until an equilibrium index is found''' + + for i in range(n): + leftsum = 0 + rightsum = 0 + ''' get left sum''' + + for j in range(i): + leftsum += arr[j] + ''' get right sum''' + + for j in range(i + 1, n): + rightsum += arr[j] + ''' if leftsum and rightsum are same, + then we are done''' + + if leftsum == rightsum: + return i + ''' return -1 if no equilibrium index is found''' + + return -1 + '''driver code''' + +arr = [-7, 1, 5, 2, -4, 3, 0] +print (equilibrium(arr))" +Length of the longest valid substring,"/*Java program to implement the above approach*/ + +import java.util.Scanner; +import java.util.Arrays; +class GFG { +/* Function to return the length + of the longest valid substring*/ + + public static int solve(String s, int n) + { +/* Variables for left and right + counter maxlength to store + the maximum length found so far*/ + + int left = 0, right = 0; + int maxlength = 0; +/* Iterating the string from left to right*/ + + for (int i = 0; i < n; i++) { +/* If ""("" is encountered, then + left counter is incremented + else right counter is incremented*/ + + if (s.charAt(i) == '(') + left++; + else + right++; +/* Whenever left is equal to right, + it signifies that the subsequence + is valid and*/ + + if (left == right) + maxlength = Math.max(maxlength, + 2 * right); +/* Reseting the counters when the + subsequence becomes invalid*/ + + else if (right > left) + left = right = 0; + } + left = right = 0; +/* Iterating the string from right to left*/ + + for (int i = n - 1; i >= 0; i--) { +/* If ""("" is encountered, then + left counter is incremented + else right counter is incremented*/ + + if (s.charAt(i) == '(') + left++; + else + right++; +/* Whenever left is equal to right, + it signifies that the subsequence + is valid and*/ + + if (left == right) + maxlength = Math.max(maxlength, + 2 * left); +/* Reseting the counters when the + subsequence becomes invalid*/ + + else if (left > right) + left = right = 0; + } + return maxlength; + } +/* Driver code*/ + + public static void main(String args[]) + { +/* Function call*/ + + System.out.print(solve(""((()()()()(((())"", 16)); + } +}"," '''Python3 program to implement the above approach''' + + '''Function to return the length of +the longest valid substring''' + +def solve(s, n): ''' Variables for left and right counter. + maxlength to store the maximum length found so far''' + + left = 0 + right = 0 + maxlength = 0 + ''' Iterating the string from left to right''' + + for i in range(n): + ''' If ""("" is encountered, + then left counter is incremented + else right counter is incremented''' + + if (s[i] == '('): + left += 1 + else: + right += 1 + ''' Whenever left is equal to right, it signifies + that the subsequence is valid and''' + + if (left == right): + maxlength = max(maxlength, 2 * right) + ''' Reseting the counters when the subsequence + becomes invalid''' + + elif (right > left): + left = right = 0 + left = right = 0 + ''' Iterating the string from right to left''' + + for i in range(n - 1, -1, -1): + ''' If ""("" is encountered, + then left counter is incremented + else right counter is incremented''' + + if (s[i] == '('): + left += 1 + else: + right += 1 + ''' Whenever left is equal to right, it signifies + that the subsequence is valid and''' + + if (left == right): + maxlength = max(maxlength, 2 * left) + ''' Reseting the counters when the subsequence + becomes invalid''' + + elif (left > right): + left = right = 0 + return maxlength + '''Driver code''' + '''Function call''' + +print(solve(""((()()()()(((())"", 16))" +Implementing Iterator pattern of a single Linked List,"import java.util.*; +class GFG +{ + + public static void main(String[] args) + { + +/* creating a list*/ + + ArrayList list = new ArrayList<>(); + +/* elements to be added at the end. + in the above created list.*/ + + list.add(1); + list.add(2); + list.add(3); + +/* elements of list are retrieved through iterator.*/ + + Iterator it = list.iterator(); + while (it.hasNext()) + { + System.out.print(it.next() + "" ""); + } + } +} + + +","if __name__=='__main__': + + ''' Creating a list''' + + list = [] + + ''' Elements to be added at the end. + in the above created list.''' + + list.append(1) + list.append(2) + list.append(3) + + ''' Elements of list are retrieved + through iterator.''' + + for it in list: + print(it, end = ' ') + + +" +Majority Element,"/* Program for finding out majority element in an array */ + +import java.util.HashMap; +class MajorityElement +{ + private static void findMajority(int[] arr) + { + HashMap map = new HashMap(); + for(int i = 0; i < arr.length; i++) { + if (map.containsKey(arr[i])) { + int count = map.get(arr[i]) +1; + if (count > arr.length /2) { + System.out.println(""Majority found :- "" + arr[i]); + return; + } else + map.put(arr[i], count); + } + else + map.put(arr[i],1); + } + System.out.println("" No Majority element""); + }/* Driver program to test the above functions */ + + public static void main(String[] args) + { + int a[] = new int[]{2,2,2,2,5,5,2,3,3}; +/* Function calling*/ + + findMajority(a); + } +}"," '''Python3 program for finding out majority +element in an array''' + +def findMajority(arr, size): + m = {} + for i in range(size): + if arr[i] in m: + m[arr[i]] += 1 + else: + m[arr[i]] = 1 + count = 0 + for key in m: + if m[key] > size / 2: + count = 1 + print(""Majority found :-"",key) + break + if(count == 0): + print(""No Majority element"") + '''Driver code''' + +arr = [2, 2, 2, 2, 5, 5, 2, 3, 3] +n = len(arr) + '''Function calling''' + +findMajority(arr, n)" +"Find number of pairs (x, y) in an array such that x^y > y^x","public static long countPairsBruteForce(long X[], long Y[], + int m, int n) +{ + long ans = 0; + for (int i = 0; i < m; i++) + for (int j = 0; j < n; j++) + if (Math.pow(X[i], Y[j]) > Math.pow(Y[j], X[i])) + ans++; + return ans; +}","def countPairsBruteForce(X, Y, m, n): + ans = 0 + for i in range(m): + for j in range(n): + if (pow(X[i], Y[j]) > pow(Y[j], X[i])): + ans += 1 + return ans" +Manacher's Algorithm,"/*Java program to implement Manacher's Algorithm */ + +import java.util.*; +class GFG +{ + static void findLongestPalindromicString(String text) + { + int N = text.length(); + if (N == 0) + return; +/*Position count*/ + +N = 2 * N + 1; +/*LPS Length Array*/ + +int[] L = new int[N + 1]; + L[0] = 0; + L[1] = 1; +/*centerPosition*/ + +int C = 1; +/*centerRightPosition*/ + +int R = 2; +/*currentRightPosition*/ + +int i = 0; +/*currentLeftPosition*/ + +int iMirror; + int maxLPSLength = 0; + int maxLPSCenterPosition = 0; + int start = -1; + int end = -1; + int diff = -1; +/* Uncomment it to print LPS Length array + printf(""%d %d "", L[0], L[1]);*/ + + for (i = 2; i < N; i++) + { +/* get currentLeftPosition iMirror + for currentRightPosition i*/ + + iMirror = 2 * C - i; + L[i] = 0; + diff = R - i; +/* If currentRightPosition i is within + centerRightPosition R*/ + + if (diff > 0) + L[i] = Math.min(L[iMirror], diff); +/* Attempt to expand palindrome centered at + currentRightPosition i. Here for odd positions, + we compare characters and if match then + increment LPS Length by ONE. If even position, + we just increment LPS by ONE without + any character comparison*/ + + while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && + (((i + L[i] + 1) % 2 == 0) || + (text.charAt((i + L[i] + 1) / 2) == + text.charAt((i - L[i] - 1) / 2)))) + { + L[i]++; + } +/*Track maxLPSLength*/ + +if (L[i] > maxLPSLength) + { + maxLPSLength = L[i]; + maxLPSCenterPosition = i; + } +/* If palindrome centered at currentRightPosition i + expand beyond centerRightPosition R, + adjust centerPosition C based on expanded palindrome.*/ + + if (i + L[i] > R) + { + C = i; + R = i + L[i]; + } +/* Uncomment it to print LPS Length array + printf(""%d "", L[i]);*/ + + } + start = (maxLPSCenterPosition - maxLPSLength) / 2; + end = start + maxLPSLength - 1; + System.out.printf(""LPS of string is %s : "", text); + for (i = start; i <= end; i++) + System.out.print(text.charAt(i)); + System.out.println(); + } +/* Driver Code*/ + + public static void main(String[] args) + { + String text = ""babcbabcbaccba""; + findLongestPalindromicString(text); + text = ""abaaba""; + findLongestPalindromicString(text); + text = ""abababa""; + findLongestPalindromicString(text); + text = ""abcbabcbabcba""; + findLongestPalindromicString(text); + text = ""forgeeksskeegfor""; + findLongestPalindromicString(text); + text = ""caba""; + findLongestPalindromicString(text); + text = ""abacdfgdcaba""; + findLongestPalindromicString(text); + text = ""abacdfgdcabba""; + findLongestPalindromicString(text); + text = ""abacdedcaba""; + findLongestPalindromicString(text); + } +}"," '''Python program to implement Manacher's Algorithm''' + +def findLongestPalindromicString(text): + N = len(text) + if N == 0: + return + '''Position count''' + + N = 2*N+1 + + '''LPS Length Array''' + + L = [0] * N + L[0] = 0 + L[1] = 1 '''centerPosition''' + + C = 1 + '''centerRightPosition''' + + R = 2 + '''currentRightPosition''' + + i = 0 + '''currentLeftPosition''' + + iMirror = 0 + maxLPSLength = 0 + maxLPSCenterPosition = 0 + start = -1 + end = -1 + diff = -1 + ''' Uncomment it to print LPS Length array + printf(""%d %d "", L[0], L[1]);''' + + for i in xrange(2,N): + ''' get currentLeftPosition iMirror for currentRightPosition i''' + + iMirror = 2*C-i + L[i] = 0 + diff = R - i + ''' If currentRightPosition i is within centerRightPosition R''' + + if diff > 0: + L[i] = min(L[iMirror], diff) + ''' Attempt to expand palindrome centered at currentRightPosition i + Here for odd positions, we compare characters and + if match then increment LPS Length by ONE + If even position, we just increment LPS by ONE without + any character comparison''' + + try: + while ((i + L[i]) < N and (i - L[i]) > 0) and \ + (((i + L[i] + 1) % 2 == 0) or \ + (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2])): + L[i]+=1 + except Exception as e: + pass + '''Track maxLPSLength''' + + if L[i] > maxLPSLength: + maxLPSLength = L[i] + maxLPSCenterPosition = i + ''' If palindrome centered at currentRightPosition i + expand beyond centerRightPosition R, + adjust centerPosition C based on expanded palindrome.''' + + if i + L[i] > R: + C = i + R = i + L[i] + ''' Uncomment it to print LPS Length array + printf(""%d "", L[i]);''' + + start = (maxLPSCenterPosition - maxLPSLength) / 2 + end = start + maxLPSLength - 1 + print ""LPS of string is "" + text + "" : "", + print text[start:end+1], + print ""\n"", + '''Driver program''' + +text1 = ""babcbabcbaccba"" +findLongestPalindromicString(text1) +text2 = ""abaaba"" +findLongestPalindromicString(text2) +text3 = ""abababa"" +findLongestPalindromicString(text3) +text4 = ""abcbabcbabcba"" +findLongestPalindromicString(text4) +text5 = ""forgeeksskeegfor"" +findLongestPalindromicString(text5) +text6 = ""caba"" +findLongestPalindromicString(text6) +text7 = ""abacdfgdcaba"" +findLongestPalindromicString(text7) +text8 = ""abacdfgdcabba"" +findLongestPalindromicString(text8) +text9 = ""abacdedcaba"" +findLongestPalindromicString(text9)" +Check if two numbers are bit rotations of each other or not,"/*Java program to check if two numbers are bit rotations +of each other.*/ + +class GFG { + +/*function to check if two numbers are equal +after bit rotation*/ + + static boolean isRotation(long x, long y) { +/* x64 has concatenation of x with itself.*/ + + long x64 = x | (x << 32); + + while (x64 >= y) { +/* comapring only last 32 bits*/ + + if (x64 == y) { + return true; + } + +/* right shift by 1 unit*/ + + x64 >>= 1; + } + return false; + } + +/*driver code to test above function*/ + + public static void main(String[] args) { + long x = 122; + long y = 2147483678L; + + if (isRotation(x, y) == false) { + System.out.println(""Yes""); + } else { + System.out.println(""No""); + } + } +} + + +"," '''Python3 program to check if two +numbers are bit rotations of each other.''' + + + '''function to check if two numbers +are equal after bit rotation''' + +def isRotation(x, y) : + + ''' x64 has concatenation of x + with itself.''' + + x64 = x | (x << 32) + + while (x64 >= y) : + + ''' comapring only last 32 bits''' + + if ((x64) == y) : + return True + + ''' right shift by 1 unit''' + + x64 >>= 1 + + return False + + '''Driver Code''' + +if __name__ == ""__main__"" : + + x = 122 + y = 2147483678 + + if (isRotation(x, y) == False) : + print(""yes"") + else : + print(""no"") + + +" +Count of n digit numbers whose sum of digits equals to given sum,"/*A Java program using recursive to count numbers +with sum of digits as given 'sum'*/ + +class sum_dig +{ +/* Recursive function to count 'n' digit numbers + with sum of digits as 'sum'. This function + considers leading 0's also as digits, that is + why not directly called*/ + + static int countRec(int n, int sum) + { +/* Base case*/ + + if (n == 0) + return sum == 0 ?1:0; + if (sum == 0) + return 1; +/* Initialize answer*/ + + int ans = 0; +/* Traverse through every digit and count + numbers beginning with it using recursion*/ + + for (int i=0; i<=9; i++) + if (sum-i >= 0) + ans += countRec(n-1, sum-i); + return ans; + } +/* This is mainly a wrapper over countRec. It + explicitly handles leading digit and calls + countRec() for remaining digits.*/ + + static int finalCount(int n, int sum) + { +/* Initialize final answer*/ + + int ans = 0; +/* Traverse through every digit from 1 to + 9 and count numbers beginning with it*/ + + for (int i = 1; i <= 9; i++) + if (sum-i >= 0) + ans += countRec(n-1, sum-i); + return ans; + } + /* Driver program to test above function */ + + public static void main (String args[]) + { + int n = 2, sum = 5; + System.out.println(finalCount(n, sum)); + } +}"," '''A python 3 program using recursive to count numbers +with sum of digits as given sum''' '''Recursive function to count 'n' digit +numbers with sum of digits as 'sum' +This function considers leading 0's +also as digits, that is why not +directly called''' + +def countRec(n, sum) : + ''' Base case''' + + if (n == 0) : + return (sum == 0) + if (sum == 0) : + return 1 + ''' Initialize answer''' + + ans = 0 + ''' Traverse through every digit and + count numbers beginning with it + using recursion''' + + for i in range(0, 10) : + if (sum-i >= 0) : + ans = ans + countRec(n-1, sum-i) + return ans + '''This is mainly a wrapper over countRec. It +explicitly handles leading digit and calls +countRec() for remaining digits.''' + +def finalCount(n, sum) : + ''' Initialize final answer''' + + ans = 0 + ''' Traverse through every digit from 1 to + 9 and count numbers beginning with it''' + + for i in range(1, 10) : + if (sum-i >= 0) : + ans = ans + countRec(n-1, sum-i) + return ans + '''Driver program''' + +n = 2 +sum = 5 +print(finalCount(n, sum))" +Count half nodes in a Binary tree (Iterative and Recursive),"/*Java program to count half nodes in a Binary Tree */ + +import java.util.*; +class GfG { +/*A binary tree Node has data, pointer to left +child and a pointer to right child */ + +static class Node +{ + int data; + Node left, right; +} +/*Function to get the count of half Nodes in +a binary tree */ + +static int gethalfCount(Node root) +{ + if (root == null) + return 0; + int res = 0; + if ((root.left == null && root.right != null) || + (root.left != null && root.right == null)) + res++; + res += (gethalfCount(root.left) + + gethalfCount(root.right)); + return res; +} +/* Helper function that allocates a new +Node with the given data and NULL left +and right pointers. */ + +static Node newNode(int data) +{ + Node node = new Node(); + node.data = data; + node.left = null; + node.right = null; + return (node); +} +/*Driver program */ + +public static void main(String[] args) +{ + /* 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree shown in + above example */ + + Node root = newNode(2); + root.left = newNode(7); + root.right = newNode(5); + root.left.right = newNode(6); + root.left.right.left = newNode(1); + root.left.right.right = newNode(11); + root.right.right = newNode(9); + root.right.right.left = newNode(4); + System.out.println(gethalfCount(root)); +} +}"," '''Python program to count half nodes in a binary tree''' + + '''A node structure''' + +class newNode: + def __init__(self, data): + self.data = data + self.left = self.right = None '''Function to get the count of half Nodes in a binary tree''' + +def gethalfCount(root): + if root == None: + return 0 + res = 0 + if(root.left == None and root.right != None) or \ + (root.left != None and root.right == None): + res += 1 + res += (gethalfCount(root.left) + \ + gethalfCount(root.right)) + return res + '''Driver program''' + + ''' 2 + / \ + 7 5 + \ \ + 6 9 + / \ / + 1 11 4 + Let us create Binary Tree shown in + above example ''' + +root = newNode(2) +root.left = newNode(7) +root.right = newNode(5) +root.left.right = newNode(6) +root.left.right.left = newNode(1) +root.left.right.right = newNode(11) +root.right.right = newNode(9) +root.right.right.left = newNode(4) +print(gethalfCount(root))" +Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction),"/*Java program to demonstrate working of +Square Root Decomposition.*/ + +import java.util.*; +class GFG +{ +static int MAXN = 10000; +static int SQRSIZE = 100; +/*original array*/ + +static int []arr = new int[MAXN]; +/*decomposed array*/ + +static int []block = new int[SQRSIZE]; +/*block size*/ + +static int blk_sz; +/*Time Complexity : O(1)*/ + +static void update(int idx, int val) +{ + int blockNumber = idx / blk_sz; + block[blockNumber] += val - arr[idx]; + arr[idx] = val; +} +/*Time Complexity : O(sqrt(n))*/ + +static int query(int l, int r) +{ + int sum = 0; + while (l < r && l % blk_sz != 0 && l != 0) + { +/* traversing first block in range*/ + + sum += arr[l]; + l++; + } + while (l+blk_sz <= r) + { +/* traversing completely + overlapped blocks in range*/ + + sum += block[l / blk_sz]; + l += blk_sz; + } + while (l <= r) + { +/* traversing last block in range*/ + + sum += arr[l]; + l++; + } + return sum; +} +/*Fills values in input[]*/ + +static void preprocess(int input[], int n) +{ +/* initiating block pointer*/ + + int blk_idx = -1; +/* calculating size of block*/ + + blk_sz = (int) Math.sqrt(n); +/* building the decomposed array*/ + + for (int i = 0; i < n; i++) + { + arr[i] = input[i]; + if (i % blk_sz == 0) + { +/* entering next block + incementing block pointer*/ + + blk_idx++; + } + block[blk_idx] += arr[i]; + } +} +/*Driver code*/ + +public static void main(String[] args) +{ +/* We have used separate array for input because + the purpose of this code is to explain SQRT + decomposition in competitive programming where + we have multiple inputs.*/ + + int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; + int n = input.length; + preprocess(input, n); + System.out.println(""query(3, 8) : "" + + query(3, 8)); + System.out.println(""query(1, 6) : "" + + query(1, 6)); + update(8, 0); + System.out.println(""query(8, 8) : "" + + query(8, 8)); +} +}"," '''Python 3 program to demonstrate working of Square Root +Decomposition.''' + +from math import sqrt +MAXN = 10000 +SQRSIZE = 100 + '''original array''' + +arr = [0]*(MAXN) + '''decomposed array''' + +block = [0]*(SQRSIZE) + '''block size''' + +blk_sz = 0 + '''Time Complexity : O(1)''' + +def update(idx, val): + blockNumber = idx // blk_sz + block[blockNumber] += val - arr[idx] + arr[idx] = val + '''Time Complexity : O(sqrt(n))''' + +def query(l, r): + sum = 0 + while (l < r and l % blk_sz != 0 and l != 0): + ''' traversing first block in range''' + + sum += arr[l] + l += 1 + while (l + blk_sz <= r): + ''' traversing completely overlapped blocks in range''' + + sum += block[l//blk_sz] + l += blk_sz + while (l <= r): + ''' traversing last block in range''' + + sum += arr[l] + l += 1 + return sum + '''Fills values in input[]''' + +def preprocess(input, n): + ''' initiating block pointer''' + + blk_idx = -1 + ''' calculating size of block''' + + global blk_sz + blk_sz = int(sqrt(n)) + ''' building the decomposed array''' + + for i in range(n): + arr[i] = input[i]; + if (i % blk_sz == 0): + ''' entering next block + incementing block pointer''' + + blk_idx += 1; + block[blk_idx] += arr[i] + '''Driver code''' + + '''We have used separate array for input because + the purpose of this code is to explain SQRT + decomposition in competitive programming where + we have multiple inputs.''' + +input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10] +n = len(input) +preprocess(input, n) +print(""query(3,8) : "",query(3, 8)) +print(""query(1,6) : "",query(1, 6)) +update(8, 0) +print(""query(8,8) : "",query(8, 8))" +Difference between sums of odd level and even level nodes of a Binary Tree,"/*Java program to find +difference between +sums of odd level +and even level nodes +of binary tree */ + +import java.io.*; +import java.util.*; +/*User defined node class*/ + +class Node { + int data; + Node left, right; +/* Constructor to create a new tree node*/ + + Node(int key) + { + data = key; + left = right = null; + } +} +class GFG { +/* return difference of + sums of odd level and even level */ + + static int evenOddLevelDifference(Node root) + { + if (root == null) + return 0; +/* create a queue for + level order traversal*/ + + Queue q = new LinkedList<>(); + q.add(root); + int level = 0; + int evenSum = 0, oddSum = 0; +/* traverse until the + queue is empty*/ + + while (q.size() != 0) { + int size = q.size(); + level++; +/* traverse for complete level */ + + while (size > 0) { + Node temp = q.remove(); +/* check if level no. + is even or odd and + accordingly update + the evenSum or oddSum */ + + if (level % 2 == 0) + evenSum += temp.data; + else + oddSum += temp.data; +/* check for left child */ + + if (temp.left != null) + q.add(temp.left); +/* check for right child */ + + if (temp.right != null) + q.add(temp.right); + size--; + } + } + return (oddSum - evenSum); + } +/* Driver code*/ + + public static void main(String args[]) + { +/* construct a tree*/ + + Node root = new Node(5); + root.left = new Node(2); + root.right = new Node(6); + root.left.left = new Node(1); + root.left.right = new Node(4); + root.left.right.left = new Node(3); + root.right.right = new Node(8); + root.right.right.right = new Node(9); + root.right.right.left = new Node(7); + System.out.println(""diffence between sums is "" + + evenOddLevelDifference(root)); + } +}"," '''Python3 program to find maximum product +of a level in Binary Tree''' + + '''Helper function that allocates a new +node with the given data and None +left and right poers. ''' + +class newNode: ''' Construct to create a new node ''' + + def __init__(self, key): + self.data = key + self.left = None + self.right = None + '''return difference of sums of odd +level and even level''' + +def evenOddLevelDifference(root): + if (not root): + return 0 + ''' create a queue for + level order traversal''' + + q = [] + q.append(root) + level = 0 + evenSum = 0 + oddSum = 0 + ''' traverse until the queue is empty''' + + while (len(q)): + size = len(q) + level += 1 + ''' traverse for complete level''' + + while(size > 0): + temp = q[0] + q.pop(0) ''' check if level no. is even or + odd and accordingly update + the evenSum or oddSum''' + + if(level % 2 == 0): + evenSum += temp.data + else: + oddSum += temp.data + ''' check for left child''' + + if (temp.left) : + q.append(temp.left) + ''' check for right child''' + + if (temp.right): + q.append(temp.right) + size -= 1 + return (oddSum - evenSum) + '''Driver Code ''' + +if __name__ == '__main__': + ''' + Let us create Binary Tree shown + in above example ''' + + root = newNode(5) + root.left = newNode(2) + root.right = newNode(6) + root.left.left = newNode(1) + root.left.right = newNode(4) + root.left.right.left = newNode(3) + root.right.right = newNode(8) + root.right.right.right = newNode(9) + root.right.right.left = newNode(7) + result = evenOddLevelDifference(root) + print(""Diffence between sums is"", result)" +Count frequencies of all elements in array in O(1) extra space and O(n) time,"/*Java program to print frequencies of all array +elements in O(1) extra space and O(n) time*/ + + +class CountFrequencies +{ +/* Function to find counts of all elements present in + arr[0..n-1]. The array elements must be range from + 1 to n*/ + + void findCounts(int arr[], int n) + { +/* Traverse all array elements*/ + + int i = 0; + while (i < n) + { +/* If this element is already processed, + then nothing to do*/ + + if (arr[i] <= 0) + { + i++; + continue; + } + +/* Find index corresponding to this element + For example, index for 5 is 4*/ + + int elementIndex = arr[i] - 1; + +/* If the elementIndex has an element that is not + processed yet, then first store that element + to arr[i] so that we don't lose anything.*/ + + if (arr[elementIndex] > 0) + { + arr[i] = arr[elementIndex]; + +/* After storing arr[elementIndex], change it + to store initial count of 'arr[i]'*/ + + arr[elementIndex] = -1; + } + else + { +/* If this is NOT first occurrence of arr[i], + then decrement its count.*/ + + arr[elementIndex]--; + +/* And initialize arr[i] as 0 means the element + 'i+1' is not seen so far*/ + + arr[i] = 0; + i++; + } + } + + System.out.println(""Below are counts of all elements""); + for (int j = 0; j < n; j++) + System.out.println(j+1 + ""->"" + Math.abs(arr[j])); + } + +/* Driver program to test above functions*/ + + public static void main(String[] args) + { + CountFrequencies count = new CountFrequencies(); + int arr[] = {2, 3, 3, 2, 5}; + count.findCounts(arr, arr.length); + + int arr1[] = {1}; + count.findCounts(arr1, arr1.length); + + int arr3[] = {4, 4, 4, 4}; + count.findCounts(arr3, arr3.length); + + int arr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1}; + count.findCounts(arr2, arr2.length); + + int arr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}; + count.findCounts(arr4, arr4.length); + + int arr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + count.findCounts(arr5, arr5.length); + + int arr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; + count.findCounts(arr6, arr6.length); + } +} + + +"," '''Python3 program to print frequencies of all array +elements in O(1) extra space and O(n) time''' + + + '''Function to find counts of all elements present in +arr[0..n-1]. The array elements must be range from +1 to n''' + +def findCounts(arr, n): + + ''' Traverse all array elements''' + + i = 0 + while i 0: + arr[i] = arr[elementIndex] + + ''' After storing arr[elementIndex], change it + to store initial count of 'arr[i]''' + ''' + arr[elementIndex] = -1 + + else: + + ''' If this is NOT first occurrence of arr[i], + then decrement its count.''' + + arr[elementIndex] -= 1 + + ''' And initialize arr[i] as 0 means the element + 'i+1' is not seen so far''' + + arr[i] = 0 + i += 1 + + print (""Below are counts of all elements"") + for i in range(0,n): + print (""%d -> %d""%(i+1, abs(arr[i]))) + print ("""") + + '''Driver program to test above function''' + +arr = [2, 3, 3, 2, 5] +findCounts(arr, len(arr)) + +arr1 = [1] +findCounts(arr1, len(arr1)) + +arr3 = [4, 4, 4, 4] +findCounts(arr3, len(arr3)) + +arr2 = [1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1] +findCounts(arr2, len(arr2)) + +arr4 = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] +findCounts(arr4, len(arr4)) + +arr5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] +findCounts(arr5, len(arr5)) + +arr6 = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] +findCounts(arr6, len(arr6)) + + +" +Subarrays with distinct elements,"/*Java program to calculate sum of lengths of subarrays +of distinct elements.*/ + +import java.util.*; +class geeks +{ +/* Returns sum of lengths of all subarrays + with distinct elements.*/ + + public static int sumoflength(int[] arr, int n) + { +/* For maintaining distinct elements.*/ + + Set s = new HashSet<>(); +/* Initialize ending point and result*/ + + int j = 0, ans = 0; +/* Fix starting point*/ + + for (int i = 0; i < n; i++) + { + while (j < n && !s.contains(arr[j])) + { + s.add(arr[i]); + j++; + } +/* Calculating and adding all possible length + subarrays in arr[i..j]*/ + + ans += ((j - i) * (j - i + 1)) / 2; +/* Remove arr[i] as we pick new stating point + from next*/ + + s.remove(arr[i]); + } + return ans; + } +/* Driver Code*/ + + public static void main(String[] args) + { + int[] arr = { 1, 2, 3, 4 }; + int n = arr.length; + System.out.println(sumoflength(arr, n)); + } +}"," '''Python 3 program to calculate sum of +lengths of subarrays of distinct elements.''' + '''Returns sum of lengths of all subarrays +with distinct elements.''' + +def sumoflength(arr, n): + ''' For maintaining distinct elements.''' + + s = [] + ''' Initialize ending point and result''' + + j = 0 + ans = 0 + ''' Fix starting point''' + + for i in range(n): + while (j < n and (arr[j] not in s)): + s.append(arr[j]) + j += 1 ''' Calculating and adding all possible + length subarrays in arr[i..j]''' + + ans += ((j - i) * (j - i + 1)) // 2 + ''' Remove arr[i] as we pick new + stating point from next''' + + s.remove(arr[i]) + return ans + '''Driven Code''' + +if __name__==""__main__"": + arr = [1, 2, 3, 4] + n = len(arr) + print(sumoflength(arr, n))" +Populate Inorder Successor for all nodes,"/*Java program to populate inorder traversal of all nodes*/ + + /*A binary tree node*/ + +class Node +{ + int data; + Node left, right, next; + Node(int item) + { + data = item; + left = right = next = null; + } +} +class BinaryTree +{ + Node root; + static Node next = null;/* Set next of p and all descendants of p by traversing them in + reverse Inorder */ + + void populateNext(Node node) + { +/* The first visited node will be the rightmost node + next of the rightmost node will be NULL*/ + + if (node != null) + { +/* First set the next pointer in right subtree*/ + + populateNext(node.right); +/* Set the next as previously visited node in reverse Inorder*/ + + node.next = next; +/* Change the prev for subsequent node*/ + + next = node; +/* Finally, set the next pointer in left subtree*/ + + populateNext(node.left); + } + } + /* Constructed binary tree is + 10 + / \ + 8 12 + / + 3 */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(10); + tree.root.left = new Node(8); + tree.root.right = new Node(12); + tree.root.left.left = new Node(3); +/* Populates nextRight pointer in all nodes*/ + + tree.populateNext(tree.root); +/* Let us see the populated values*/ + + Node ptr = tree.root.left.left; + while (ptr != null) + { +/* -1 is printed if there is no successor*/ + + int print = ptr.next != null ? ptr.next.data : -1; + System.out.println(""Next of "" + ptr.data + "" is: "" + print); + ptr = ptr.next; + } + } +}"," '''Python3 program to populate +inorder traversal of all nodes''' + + '''Tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + self.next = None +next = None '''Set next of p and all descendants of p +by traversing them in reverse Inorder''' + +def populateNext(p): + global next + + '''The first visited node will be the rightmost node + next of the rightmost node will be NULL''' + + if (p != None): ''' First set the next pointer + in right subtree''' + + populateNext(p.right) + ''' Set the next as previously visited node + in reverse Inorder''' + + p.next = next + ''' Change the prev for subsequent node''' + + next = p + ''' Finally, set the next pointer + in left subtree''' + + populateNext(p.left) + '''UTILITY FUNCTIONS +Helper function that allocates +a new node with the given data +and None left and right pointers.''' + +def newnode(data): + node = Node(0) + node.data = data + node.left = None + node.right = None + node.next = None + return(node) + '''Driver Code +Constructed binary tree is + 10 + / \ + 8 12 +/ +3''' + +root = newnode(10) +root.left = newnode(8) +root.right = newnode(12) +root.left.left = newnode(3) + '''Populates nextRight pointer +in all nodes''' + +p = populateNext(root) + '''Let us see the populated values''' + +ptr = root.left.left +while(ptr != None): + + ''' -1 is printed if there is no successor''' + out = 0 + if(ptr.next != None): + out = ptr.next.data + else: + out = -1 + print(""Next of"", ptr.data, ""is"", out) + ptr = ptr.next" +Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time),"/*Naive Java implementation to find LCA in a tree.*/ + +import java.io.*; +import java.util.*; + +class GFG +{ + static int MAXN = 1001; + +/* stores depth for each node*/ + + static int[] depth = new int[MAXN]; + +/* stores first parent for each node*/ + + static int[] parent = new int[MAXN]; + + @SuppressWarnings(""unchecked"") + static Vector[] adj = new Vector[MAXN]; + static + { + for (int i = 0; i < MAXN; i++) + adj[i] = new Vector<>(); + } + + static void addEdge(int u, int v) + { + adj[u].add(v); + adj[v].add(u); + } + + static void dfs(int cur, int prev) + { + +/* marking parent for each node*/ + + parent[cur] = prev; + +/* marking depth for each node*/ + + depth[cur] = depth[prev] + 1; + +/* propogating marking down the tree*/ + + for (int i = 0; i < adj[cur].size(); i++) + if (adj[cur].elementAt(i) != prev) + dfs(adj[cur].elementAt(i), cur); + } + + static void preprocess() + { + +/* a dummy node*/ + + depth[0] = -1; + +/* precalclating 1)depth. 2)parent. + for each node*/ + + dfs(1, 0); + } + +/* Time Complexity : O(Height of tree) + recursively jumps one node above + till both the nodes become equal*/ + + static int LCANaive(int u, int v) + { + if (u == v) + return u; + if (depth[u] > depth[v]) + { + int temp = u; + u = v; + v = temp; + } + v = parent[v]; + return LCANaive(u, v); + } + +/* Driver Code*/ + + public static void main(String[] args) + { + +/* adding edges to the tree*/ + + addEdge(1, 2); + addEdge(1, 3); + addEdge(1, 4); + addEdge(2, 5); + addEdge(2, 6); + addEdge(3, 7); + addEdge(4, 8); + addEdge(4, 9); + addEdge(9, 10); + addEdge(9, 11); + addEdge(7, 12); + addEdge(7, 13); + + preprocess(); + + System.out.println(""LCA(11,8) : "" + LCANaive(11, 8)); + System.out.println(""LCA(3,13) : "" + LCANaive(3, 13)); + } +} + + +"," '''Python3 implementation to +find LCA in a tree''' + +MAXN = 1001 + + '''stores depth for each node''' + +depth = [0 for i in range(MAXN)]; + + '''stores first parent for each node''' + +parent = [0 for i in range(MAXN)]; + +adj = [[] for i in range(MAXN)] + +def addEdge(u, v): + + adj[u].append(v); + adj[v].append(u); + +def dfs(cur, prev): + + ''' marking parent for + each node''' + + parent[cur] = prev; + + ''' marking depth for + each node''' + + depth[cur] = depth[prev] + 1; + + ''' propogating marking down + the tree''' + + for i in range(len(adj[cur])): + if (adj[cur][i] != prev): + dfs(adj[cur][i], cur); + +def preprocess(): + + ''' a dummy node''' + + depth[0] = -1; + + ''' precalculating 1)depth. + 2)parent. for each node''' + + dfs(1, 0); + + '''Time Complexity : O(Height of tree) +recursively jumps one node above +till both the nodes become equal''' + +def LCANaive(u, v): + + if (u == v): + return u; + + if (depth[u] > depth[v]): + u, v = v, u + + v = parent[v]; + return LCANaive(u, v); + + '''Driver code''' + +if __name__ == ""__main__"": + + ''' adding edges to the tree''' + + addEdge(1, 2); + addEdge(1, 3); + addEdge(1, 4); + addEdge(2, 5); + addEdge(2, 6); + addEdge(3, 7); + addEdge(4, 8); + addEdge(4, 9); + addEdge(9, 10); + addEdge(9, 11); + addEdge(7, 12); + addEdge(7, 13); + + preprocess(); + + print('LCA(11,8) : ' + + str(LCANaive(11, 8))) + print('LCA(3,13) : ' + + str(LCANaive(3, 13))) + + +" +Inorder Tree Traversal without Recursion,"/*non-recursive java program for inorder traversal*/ + +import java.util.Stack; +/* Class containing left and right child of +current node and key value*/ + +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} +/* Class to print the inorder traversal */ + +class BinaryTree +{ + Node root; + void inorder() + { + if (root == null) + return; + Stack s = new Stack(); + Node curr = root; +/* traverse the tree*/ + + while (curr != null || s.size() > 0) + { + /* Reach the left most Node of the + curr Node */ + + while (curr != null) + { + /* place pointer to a tree node on + the stack before traversing + the node's left subtree */ + + s.push(curr); + curr = curr.left; + } + /* Current must be NULL at this point */ + + curr = s.pop(); + System.out.print(curr.data + "" ""); + /* we have visited the node and its + left subtree. Now, it's right + subtree's turn */ + + curr = curr.right; + } + } + + /* Driver program to test above functions*/ + + public static void main(String args[]) + {/* creating a binary tree and entering + the nodes */ + + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.inorder(); + } +}"," '''Python program to do inorder traversal without recursion''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Iterative function for inorder tree traversal''' + +def inOrder(root): + current = root + stack = [] + done = 0 '''traverse the tree''' + + while True: + ''' Reach the left most Node of the current Node''' + + if current is not None: + ''' Place pointer to a tree node on the stack + before traversing the node's left subtree''' + + stack.append(current) + current = current.left + ''' BackTrack from the empty subtree and visit the Node + at the top of the stack; however, if the stack is + empty you are done''' + + elif(stack): + current = stack.pop() + print(current.data, end="" "") ''' We have visited the node and its left + subtree. Now, it's right subtree's turn''' + + current = current.right + else: + break + print() + '''Driver program to test above function''' + + '''Constructed binary tree is + 1 + / \ + 2 3 + / \ + 4 5 ''' + +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +inOrder(root)" +Swap all odd and even bits,"/*Java program to swap even +and odd bits of a given number*/ + +class GFG{ +/* Function to swap even + and odd bits*/ + + static int swapBits(int x) + { +/* Get all even bits of x*/ + + int even_bits = x & 0xAAAAAAAA; +/* Get all odd bits of x*/ + + int odd_bits = x & 0x55555555; +/* Right shift even bits*/ + + even_bits >>= 1; +/* Left shift odd bits*/ + + odd_bits <<= 1; +/* Combine even and odd bits*/ + + return (even_bits | odd_bits); + } +/* Driver program to test above function*/ + + public static void main(String[] args) + { +/*00010111*/ + +int x = 23; +/* Output is 43 (00101011)*/ + + System.out.println(swapBits(x)); + } +}"," '''Python 3 program to swap even +and odd bits of a given number''' + + '''Function for swapping even +and odd bits''' + +def swapBits(x) : ''' Get all even bits of x''' + + even_bits = x & 0xAAAAAAAA + ''' Get all odd bits of x''' + + odd_bits = x & 0x55555555 + ''' Right shift even bits''' + + even_bits >>= 1 + ''' Left shift odd bits''' + + odd_bits <<= 1 + ''' Combine even and odd bits''' + + return (even_bits | odd_bits) + '''Driver program''' + '''00010111''' + +x = 23 + '''Output is 43 (00101011)''' + +print(swapBits(x))" +Convert a given Binary Tree to Doubly Linked List | Set 2,"/*Java program to convert BTT to DLL using +simple inorder traversal*/ + +public class BinaryTreeToDLL +{ + +/*A tree node*/ + + static class node + { + int data; + node left, right; + public node(int data) + { + this.data = data; + } + } + static node prev;/* Standard Inorder traversal of tree*/ + + static void inorder(node root) + { + if (root == null) + return; + inorder(root.left); + System.out.print(root.data + "" ""); + inorder(root.right); + } + +/* Changes left pointers to work as previous + pointers in converted DLL The function + simply does inorder traversal of Binary + Tree and updates left pointer using + previously visited node*/ + + static void fixPrevptr(node root) + { + if (root == null) + return; + fixPrevptr(root.left); + root.left = prev; + prev = root; + fixPrevptr(root.right); + } +/* Changes right pointers to work + as next pointers in converted DLL*/ + + static node fixNextptr(node root) + { +/* Find the right most node in + BT or last node in DLL*/ + + while (root.right != null) + root = root.right; +/* Start from the rightmost node, traverse + back using left pointers. While traversing, + change right pointer of nodes*/ + + while (root != null && root.left != null) + { + node left = root.left; + left.right = root; + root = root.left; + } +/* The leftmost node is head of linked list, return it*/ + + return root; + } +/*The main function that converts +BST to DLL and returns head of DLL*/ + + static node BTTtoDLL(node root) + { + prev = null; +/* Set the previous pointer*/ + + fixPrevptr(root); +/* Set the next pointer and return head of DLL*/ + + return fixNextptr(root); + } +/* Traverses the DLL from left tor right*/ + + static void printlist(node root) + { + while (root != null) + { + System.out.print(root.data + "" ""); + root = root.right; + } + } +/*Driver code*/ + + public static void main(String[] args) + {/* Let us create the tree shown in above diagram*/ + + node root = new node(10); + root.left = new node(12); + root.right = new node(15); + root.left.left = new node(25); + root.left.right = new node(30); + root.right.left = new node(36); + System.out.println(""Inorder Tree Traversal""); + inorder(root); + node head = BTTtoDLL(root); + System.out.println(""\nDLL Traversal""); + printlist(head); + } +}"," '''A simple inorder traversal based program to convert a +Binary Tree to DLL''' + '''A Binary Tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''Standard Inorder traversal of tree''' + +def inorder(root): + if root is not None: + inorder(root.left) + print ""\t%d"" %(root.data), + inorder(root.right) + '''Changes left pointers to work as previous pointers +in converted DLL +The function simply does inorder traversal of +Binary Tree and updates +left pointer using previously visited node''' + +def fixPrevPtr(root): + if root is not None: + fixPrevPtr(root.left) + root.left = fixPrevPtr.pre + fixPrevPtr.pre = root + fixPrevPtr(root.right) + '''Changes right pointers to work as nexr pointers in +converted DLL''' + +def fixNextPtr(root): + prev = None + ''' Find the right most node in BT or last node in DLL''' + + while(root and root.right != None): + root = root.right + ''' Start from the rightmost node, traverse back using + left pointers + While traversing, change right pointer of nodes''' + + while(root and root.left != None): + prev = root + root = root.left + root.right = prev + ''' The leftmost node is head of linked list, return it''' + + return root + '''The main function that converts BST to DLL and returns +head of DLL''' + +def BTToDLL(root): + ''' Set the previous pointer''' + + fixPrevPtr(root) + ''' Set the next pointer and return head of DLL''' + + return fixNextPtr(root) + '''Traversses the DLL from left to right''' + +def printList(root): + while(root != None): + print ""\t%d"" %(root.data), + root = root.right + '''Driver program to test above function''' + + + ''' Let us create the tree + shown in above diagram''' + + +root = Node(10) +root.left = Node(12) +root.right = Node(15) +root.left.left = Node(25) +root.left.right = Node(30) +root.right.left = Node(36) +print ""\n\t\t Inorder Tree Traversal\n"" +inorder(root) +fixPrevPtr.pre = None +head = BTToDLL(root) +print ""\n\n\t\tDLL Traversal\n"" +printList(head)" +Boundary Traversal of binary tree,"/*Java program to print boundary traversal of binary tree*/ + +/* A binary tree node has data, pointer to left child +and a pointer to right child */ + +class Node { + int data; + Node left, right; + Node(int item) + { + data = item; + left = right = null; + } +} +class BinaryTree { + Node root; +/* A simple function to print leaf nodes of a binary tree*/ + + void printLeaves(Node node) + { + if (node == null) + return; + printLeaves(node.left); +/* Print it if it is a leaf node*/ + + if (node.left == null && node.right == null) + System.out.print(node.data + "" ""); + printLeaves(node.right); + } +/* A function to print all left boundary nodes, except a leaf node. + Print the nodes in TOP DOWN manner*/ + + void printBoundaryLeft(Node node) + { + if (node == null) + return; + if (node.left != null) { +/* to ensure top down order, print the node + before calling itself for left subtree*/ + + System.out.print(node.data + "" ""); + printBoundaryLeft(node.left); + } + else if (node.right != null) { + System.out.print(node.data + "" ""); + printBoundaryLeft(node.right); + } +/* do nothing if it is a leaf node, this way we avoid + duplicates in output*/ + + } +/* A function to print all right boundary nodes, except a leaf node + Print the nodes in BOTTOM UP manner*/ + + void printBoundaryRight(Node node) + { + if (node == null) + return; + if (node.right != null) { +/* to ensure bottom up order, first call for right + subtree, then print this node*/ + + printBoundaryRight(node.right); + System.out.print(node.data + "" ""); + } + else if (node.left != null) { + printBoundaryRight(node.left); + System.out.print(node.data + "" ""); + } +/* do nothing if it is a leaf node, this way we avoid + duplicates in output*/ + + } +/* A function to do boundary traversal of a given binary tree*/ + + void printBoundary(Node node) + { + if (node == null) + return; + System.out.print(node.data + "" ""); +/* Print the left boundary in top-down manner.*/ + + printBoundaryLeft(node.left); +/* Print all leaf nodes*/ + + printLeaves(node.left); + printLeaves(node.right); +/* Print the right boundary in bottom-up manner*/ + + printBoundaryRight(node.right); + } +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(20); + tree.root.left = new Node(8); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(12); + tree.root.left.right.left = new Node(10); + tree.root.left.right.right = new Node(14); + tree.root.right = new Node(22); + tree.root.right.right = new Node(25); + tree.printBoundary(tree.root); + } +}"," '''Python3 program for binary traversal of binary tree''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + '''A simple function to print leaf nodes of a Binary Tree''' + +def printLeaves(root): + if(root): + printLeaves(root.left) + ''' Print it if it is a leaf node''' + + if root.left is None and root.right is None: + print(root.data), + printLeaves(root.right) + '''A function to print all left boundary nodes, except a +leaf node. Print the nodes in TOP DOWN manner''' + +def printBoundaryLeft(root): + if(root): + if (root.left): + ''' to ensure top down order, print the node + before calling itself for left subtree''' + + print(root.data) + printBoundaryLeft(root.left) + elif(root.right): + print (root.data) + printBoundaryLeft(root.right) + ''' do nothing if it is a leaf node, this way we + avoid duplicates in output''' + '''A function to print all right boundary nodes, except +a leaf node. Print the nodes in BOTTOM UP manner''' + +def printBoundaryRight(root): + if(root): + if (root.right): + ''' to ensure bottom up order, first call for + right subtree, then print this node''' + + printBoundaryRight(root.right) + print(root.data) + elif(root.left): + printBoundaryRight(root.left) + print(root.data) + ''' do nothing if it is a leaf node, this way we + avoid duplicates in output''' + '''A function to do boundary traversal of a given binary tree''' + +def printBoundary(root): + if (root): + print(root.data) + ''' Print the left boundary in top-down manner''' + + printBoundaryLeft(root.left) + ''' Print all leaf nodes''' + + printLeaves(root.left) + printLeaves(root.right) + ''' Print the right boundary in bottom-up manner''' + + printBoundaryRight(root.right) + '''Driver program to test above function''' + +root = Node(20) +root.left = Node(8) +root.left.left = Node(4) +root.left.right = Node(12) +root.left.right.left = Node(10) +root.left.right.right = Node(14) +root.right = Node(22) +root.right.right = Node(25) +printBoundary(root)" +Mirror of matrix across diagonal,"/*Efficient Java program to find mirror of +matrix across diagonal.*/ + +import java.io.*; +class GFG { + static int MAX = 100; + static void imageSwap(int mat[][], int n) + { +/* traverse a matrix and swap + mat[i][j] with mat[j][i]*/ + + for (int i = 0; i < n; i++) + for (int j = 0; j <= i; j++) + mat[i][j] = mat[i][j] + mat[j][i] + - (mat[j][i] = mat[i][j]); + } +/* Utility function to print a matrix*/ + + static void printMatrix(int mat[][], int n) + { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + System.out.print( mat[i][j] + "" ""); + System.out.println(); + } + } +/* driver program to test above function*/ + + public static void main (String[] args) + { + int mat[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; + int n = 4; + imageSwap(mat, n); + printMatrix(mat, n); + } +}"," '''Efficient Python3 program to find mirror of +matrix across diagonal.''' + +from builtins import range +MAX = 100; +def imageSwap(mat, n): + ''' traverse a matrix and swap + mat[i][j] with mat[j][i]''' + + for i in range(n): + for j in range(i + 1): + t = mat[i][j]; + mat[i][j] = mat[j][i] + mat[j][i] = t + '''Utility function to pra matrix''' + +def printMatrix(mat, n): + for i in range(n): + for j in range(n): + print(mat[i][j], end="" ""); + print(); + '''Driver code''' + +if __name__ == '__main__': + mat = [1, 2, 3, 4], \ + [5, 6, 7, 8], \ + [9, 10, 11, 12], \ + [13, 14, 15, 16]; + n = 4; + imageSwap(mat, n); + printMatrix(mat, n);" +Extract Leaves of a Binary Tree in a Doubly Linked List,"/*Java program to extract leaf nodes from binary tree +using double linked list*/ + +/*A binay tree node*/ + +class Node +{ + int data; + Node left, right; + Node(int item) + { + data = item; + right = left = null; + } +} +/*Binary Tree class */ + +public class BinaryTree +{ + Node root; + Node head; + Node prev; /* The main function that links the list list to be traversed*/ + + public Node extractLeafList(Node root) + { + if (root == null) + return null; + if (root.left == null && root.right == null) + { + if (head == null) + { + head = root; + prev = root; + } + else + { + prev.right = root; + root.left = prev; + prev = root; + } + return null; + } + root.left = extractLeafList(root.left); + root.right = extractLeafList(root.right); + return root; + } +/*Utility function for printing tree in In-Order.*/ + + void inorder(Node node) + { + if (node == null) + return; + inorder(node.left); + System.out.print(node.data + "" ""); + inorder(node.right); + }/* Prints the DLL in both forward and reverse directions.*/ + + public void printDLL(Node head) + { + Node last = null; + while (head != null) + { + System.out.print(head.data + "" ""); + last = head; + head = head.right; + } + } + +/* Driver program to test above functions*/ + + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(1); + tree.root.left = new Node(2); + tree.root.right = new Node(3); + tree.root.left.left = new Node(4); + tree.root.left.right = new Node(5); + tree.root.right.right = new Node(6); + tree.root.left.left.left = new Node(7); + tree.root.left.left.right = new Node(8); + tree.root.right.right.left = new Node(9); + tree.root.right.right.right = new Node(10); + System.out.println(""Inorder traversal of given tree is : ""); + tree.inorder(tree.root); + tree.extractLeafList(tree.root); + System.out.println(""""); + System.out.println(""Extracted double link list is : ""); + tree.printDLL(tree.head); + System.out.println(""""); + System.out.println(""Inorder traversal of modified tree is : ""); + tree.inorder(tree.root); + } +}"," '''Python program to extract leaf nodes from binary tree +using double linked list''' + + '''A binary tree node''' + +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None '''Main function which extracts all leaves from given Binary Tree. +The function returns new root of Binary Tree (Note that +root may change if Binary Tree has only one node). +The function also sets *head_ref as head of doubly linked list. +left pointer of tree is used as prev in DLL +and right pointer is used as next''' + +def extractLeafList(root): + if root is None: + return None + if root.left is None and root.right is None: + root.right = extractLeafList.head + if extractLeafList.head is not None: + extractLeafList.head.left = root + extractLeafList.head = root + return None + root.right = extractLeafList(root.right) + root.left = extractLeafList(root.left) + return root + '''Utility function for printing tree in InOrder''' + +def printInorder(root): + if root is not None: + printInorder(root.left) + print root.data, + printInorder(root.right) + + '''Utility function for printing double linked list.''' + +def printList(head): + while(head): + if head.data is not None: + print head.data, + head = head.right '''Driver program to test above function''' + +extractLeafList.head = Node(None) +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.right = Node(6) +root.left.left.left = Node(7) +root.left.left.right = Node(8) +root.right.right.left = Node(9) +root.right.right.right = Node(10) +print ""Inorder traversal of given tree is:"" +printInorder(root) +root = extractLeafList(root) +print ""\nExtract Double Linked List is:"" +printList(extractLeafList.head) +print ""\nInorder traversal of modified tree is:"" +printInorder(root)"