query
stringlengths
8
111
lang1
stringlengths
51
7.86k
lang2
stringlengths
91
6.16k
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 <node > Q = new LinkedList<>(); Stack <node > 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); } }
null
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
null
null
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<Integer> 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); } }
null
Find the two numbers with odd occurrences in an unsorted array
null
null
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<Integer> 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 "<s> <e>" where <s> and <e> 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 + " |"); } } }
null
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<Node> 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<Node> myQueue = new LinkedList<>(); /* Maintain a stack for printing nodes in reverse order after they are popped out from queue.*/ Stack<Node> 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<Integer, Integer> 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); } }
null
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<Integer> set = new HashSet<>(); /* Traverse the input array*/ for (int i=0; i<arr.length; i++) { /* If already present n hash, then we found a duplicate within k distance*/ if (set.contains(arr[i])) return true; /* Add this item to hashset*/ set.add(arr[i]); /* Remove the k+1 distant item*/ if (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"); } }
null
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<Integer> 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<Integer,Integer> 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<Integer,Integer> 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<arr.length; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } /* Initialize result as 0 rotation sum*/ int maxVal = currVal; /* Try all rotations one by one and find the maximum rotation sum.*/ for (int j=1; j<arr.length; j++) { currVal = currVal + arrSum-arr.length*arr[arr.length-j]; if (currVal > 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); } }
null
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<Integer>[] 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<Integer> 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
null
'''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<Vector <Integer>> vec = new Vector<Vector <Integer>>(); /* initialize*/ for (int i = 1; i <= l; i++) vec.add(new Vector<Integer>()); /* 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<Integer, Integer> hM = new HashMap<Integer, Integer>(); /* Traverse the array elements, and store count for every element in HashMap*/ for (int i=0; i<arr.length; i++) { /* Check if element is already in HashMap*/ Integer prevCount = hM.get(arr[i]); if (prevCount == null) prevCount = 0; /* Increment count of element element in HashMap*/ hM.put(arr[i], prevCount + 1); } /* Traverse array again*/ for (int i=0; i<arr.length; i++) { /* Check if this is first occurrence*/ Integer count = hM.get(arr[i]); if (count != null) { /* If yes, then print the element 'count' times*/ for (int j=0; j<count; j++) System.out.print(arr[i] + " "); /* And remove the element from HashMap.*/ hM.remove(arr[i]); } } } /* Driver method to test above method*/ public static void main (String[] args) { int arr[] = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr); } }
'''Python3 program to group multiple occurrences of individual array elements''' '''A hashing based method to group all occurrences of individual elements''' def orderedGroup(arr): ''' Creates an empty hashmap''' hM = {} ''' Traverse the array elements, and store count for every element in HashMap''' for i in range(0, len(arr)): ''' Increment count of elements in HashMap''' hM[arr[i]] = hM.get(arr[i], 0) + 1 ''' Traverse array again''' for i in range(0, len(arr)): ''' Check if this is first occurrence''' count = hM.get(arr[i], None) if count != None: ''' If yes, then print the element 'count' times''' for j in range(0, count): print(arr[i], end = " ") ''' And remove the element from HashMap.''' del hM[arr[i]] '''Driver Code''' if __name__ == "__main__": arr = [10, 5, 3, 10, 10, 4, 1, 3] orderedGroup(arr)
Count full nodes in a Binary tree (Iterative and Recursive)
/*Java program to count full 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 full nodes of Tree */ class BinaryTree { Node root; /* Function to get the count of full Nodes in a binary tree*/ int getfullCount() { /* If tree is empty*/ if (root==null) return 0; /* Initialize empty queue.*/ Queue<Node> queue = new LinkedList<Node>(); /* 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); } }
null
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<NodeDetails> q = new LinkedList<NodeDetails>(); /* 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<Integer> S = new Stack<Integer>(); /* 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"); } } }
null
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<Node> 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<Integer> head1, LinkedList<Integer> head2, int x) { int count = 0; /* traverse the 1st linked list*/ Iterator<Integer> itr1 = head1.iterator(); while(itr1.hasNext()) { /* for each node of 1st list traverse the 2nd list*/ Iterator<Integer> 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<Integer> head1 = new LinkedList<>(Arrays.asList(arr1)); LinkedList<Integer> 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<Node> q = new LinkedList<Node> (); 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<Integer, Integer> 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
null
null
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<Node> 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<Integer, pair> 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<Integer, pair> twoSum(int[] nums) { Map<Integer, pair> 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<Integer, pair> 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); } }
null
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<Integer, Integer> um = new HashMap<Integer, Integer>(); /* 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
null
'''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<n;++i) { for(int j=0;j<i;++j) { int temp = arr[i][j]; arr[i][j]=arr[j][i]; arr[j][i]=temp; } } /* Second rotation with respect to middle column*/ for(int i=0;i<n;++i) { for(int j=0;j<n/2;++j) { int temp =arr[i][j]; arr[i][j] = arr[i][n-j-1]; arr[i][n-j-1]=temp; } } } /* 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); } }
null
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++) { for (int j = 0; j < n; j++) { /* finding sum of primary diagonal*/ if (i == j) d1 += arr[i][j]; /* finding sum of secondary diagonal*/ if (i == n - j - 1) d2 += arr[i][j]; } } /* 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): for j in range(0, n): ''' finding sum of primary diagonal''' if (i == j): d1 += arr[i][j] ''' finding sum of secondary diagonal''' if (i == n - j - 1): d2 += arr[i][j] ''' 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))
Find a peak element
/*A Java program to find a peak element*/ import java.util.*; class GFG{ /*Find the peak element in the array*/ static int findPeak(int arr[], int 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(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); } }
null
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
null
'''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)