query
stringlengths
8
111
lang1
stringlengths
51
7.86k
lang2
stringlengths
91
6.16k
Count number of triplets with product equal to given number
/*Java program to count triplets with given product m*/ class GFG { /* Method to count such triplets*/ static int countTriplets(int arr[], int n, int m) { int count = 0; /* Consider all triplets and count if their product is equal to m*/ for (int i = 0; i < n - 2; i++) for (int j = i + 1; j < n - 1; j++) for (int k = j + 1; k < n; k++) if (arr[i] * arr[j] * arr[k] == m) count++; return count; } /* Driver method*/ public static void main(String[] args) { int arr[] = { 1, 4, 6, 2, 3, 8 }; int m = 24; System.out.println(countTriplets(arr, arr.length, m)); } }
'''Python3 program to count triplets with given product m''' '''Method to count such triplets''' def countTriplets(arr, n, m): count = 0 ''' Consider all triplets and count if their product is equal to m''' for i in range (n - 2): for j in range (i + 1, n - 1): for k in range (j + 1, n): if (arr[i] * arr[j] * arr[k] == m): count += 1 return count '''Driver code''' if __name__ == "__main__": arr = [1, 4, 6, 2, 3, 8] m = 24 print(countTriplets(arr, len(arr), m))
Sum of k smallest elements in BST
/*Java program to find Sum Of All Elements smaller than or equal t Kth Smallest Element In BST*/ import java.util.*; class GFG{ /* Binary tree Node */ static class Node { int data; int lCount; int Sum ; Node left; Node right; }; /*utility function new Node of BST*/ static Node createNode(int data) { Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0 ; new_Node.Sum = 0; return new_Node; } /*A utility function to insert a new Node with given key in BST and also maintain lcount ,Sum*/ static Node insert(Node root, int key) { /* If the tree is empty, return a new Node*/ if (root == null) return createNode(key); /* Otherwise, recur down the tree*/ if (root.data > key) { /* increment lCount of current Node*/ root.lCount++; /* increment current Node sum by adding key into it*/ root.Sum += key; root.left= insert(root.left , key); } else if (root.data < key ) root.right= insert (root.right , key ); /* return the (unchanged) Node pointer*/ return root; } static int temp_sum; /*function return sum of all element smaller than and equal to Kth smallest element*/ static void ksmallestElementSumRec(Node root, int k ) { if (root == null) return ; /* if we fount k smallest element then break the function*/ if ((root.lCount + 1) == k) { temp_sum += root.data + root.Sum ; return ; } else if (k > root.lCount) { /* store sum of all element smaller than current root ;*/ temp_sum += root.data + root.Sum; /* decremented k and call right sub-tree*/ k = k -( root.lCount + 1); ksmallestElementSumRec(root.right , k ); } /*call left sub-tree*/ else ksmallestElementSumRec(root.left , k ); } /*Wrapper over ksmallestElementSumRec()*/ static void ksmallestElementSum(Node root, int k) { temp_sum = 0; ksmallestElementSumRec(root, k); } /* Driver program to test above functions */ public static void main(String[] args) { /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; ksmallestElementSum(root, k); System.out.println(temp_sum); } }
'''Python3 program to find Sum Of All Elements smaller than or equal t Kth Smallest Element In BST''' '''utility function new Node of BST''' class createNode: def __init__(self, data): self.data = data self.lCount = 0 self.Sum = 0 self.left = None self.right = None '''A utility function to insert a new Node with given key in BST and also maintain lcount ,Sum''' def insert(root, key): ''' If the tree is empty, return a new Node''' if root == None: return createNode(key) ''' Otherwise, recur down the tree''' if root.data > key: ''' increment lCount of current Node''' root.lCount += 1 ''' increment current Node sum by adding key into it''' root.Sum += key root.left= insert(root.left , key) elif root.data < key: root.right= insert (root.right , key) ''' return the (unchanged) Node pointer''' return root '''function return sum of all element smaller than and equal to Kth smallest element''' def ksmallestElementSumRec(root, k , temp_sum): if root == None: return ''' if we fount k smallest element then break the function''' if (root.lCount + 1) == k: temp_sum[0] += root.data + root.Sum return elif k > root.lCount: ''' store sum of all element smaller than current root ;''' temp_sum[0] += root.data + root.Sum ''' decremented k and call right sub-tree''' k = k -( root.lCount + 1) ksmallestElementSumRec(root.right, k, temp_sum) '''call left sub-tree''' else: ksmallestElementSumRec(root.left, k, temp_sum) '''Wrapper over ksmallestElementSumRec()''' def ksmallestElementSum(root, k): Sum = [0] ksmallestElementSumRec(root, k, Sum) return Sum[0] '''Driver Code''' if __name__ == '__main__': ''' 20 / \ 8 22 / \ 4 12 / \ 10 14 ''' root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = 3 print(ksmallestElementSum(root, k))
Counting sets of 1s and 0s in a binary matrix
/*Java program to compute number of sets in a binary matrix.*/ class GFG { /*no of columns*/ static final int m = 3; /*no of rows*/ static final int n = 2; /*function to calculate the number of non empty sets of cell*/ static long countSets(int a[][]) { /* stores the final answer*/ long res = 0; /* traverses row-wise*/ for (int i = 0; i < n; i++) { int u = 0, v = 0; for (int j = 0; j < m; j++) { if (a[i][j] == 1) u++; else v++; } res += Math.pow(2, u) - 1 + Math.pow(2, v) - 1; } /* traverses column wise*/ for (int i = 0; i < m; i++) { int u = 0, v = 0; for (int j = 0; j < n; j++) { if (a[j][i] == 1) u++; else v++; } res += Math.pow(2, u) - 1 + Math.pow(2, v) - 1; } /* at the end subtract n*m as no of single sets have been added twice.*/ return res - (n * m); } /*Driver code*/ public static void main(String[] args) { int a[][] = {{1, 0, 1}, {0, 1, 0}}; System.out.print(countSets(a)); } }
'''Python3 program to compute number of sets in a binary matrix.''' '''no of columns''' m = 3 '''no of rows''' n = 2 '''function to calculate the number of non empty sets of cell''' def countSets(a): ''' stores the final answer''' res = 0 ''' traverses row-wise''' for i in range(n): u = 0 v = 0 for j in range(m): if a[i][j]: u += 1 else: v += 1 res += pow(2, u) - 1 + pow(2, v) - 1 ''' traverses column wise''' for i in range(m): u = 0 v = 0 for j in range(n): if a[j][i]: u += 1 else: v += 1 res += pow(2, u) - 1 + pow(2, v) - 1 ''' at the end subtract n*m as no of single sets have been added twice.''' return res - (n*m) '''Driver program to test the above function.''' a = [[1, 0, 1],[0, 1, 0]] print(countSets(a))
Total coverage of all zeros in a binary matrix
/*Java program to get total coverage of all zeros in a binary matrix*/ import java .io.*; class GFG { static int R = 4; static int C = 4; /*Returns total coverage of all zeros in mat[][]*/ static int getTotalCoverageOfMatrix(int [][]mat) { int res = 0; /* looping for all rows of matrix*/ for (int i = 0; i < R; i++) { /* 1 is not seen yet*/ boolean isOne = false; /* looping in columns from left to right direction to get left ones*/ for (int j = 0; j < C; j++) { /* If one is found from left*/ if (mat[i][j] == 1) isOne = true; /* If 0 is found and we have found a 1 before.*/ else if (isOne) res++; } /* Repeat the above process for right to left direction.*/ isOne = false; for (int j = C - 1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } /* Traversing across columms for up and down directions.*/ for (int j = 0; j < C; j++) { /* 1 is not seen yet*/ boolean isOne = false; for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R - 1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res; } /*Driver code*/ static public void main (String[] args) { int [][]mat = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}}; System.out.println( getTotalCoverageOfMatrix(mat)); } }
'''Python3 program to get total coverage of all zeros in a binary matrix''' R = 4 C = 4 '''Returns total coverage of all zeros in mat[][]''' def getTotalCoverageOfMatrix(mat): res = 0 ''' looping for all rows of matrix''' for i in range(R): '''1 is not seen yet''' isOne = False ''' looping in columns from left to right direction to get left ones''' for j in range(C): ''' If one is found from left''' if (mat[i][j] == 1): isOne = True ''' If 0 is found and we have found a 1 before.''' elif (isOne): res += 1 ''' Repeat the above process for right to left direction.''' isOne = False for j in range(C - 1, -1, -1): if (mat[i][j] == 1): isOne = True elif (isOne): res += 1 ''' Traversing across columms for up and down directions.''' for j in range(C): '''1 is not seen yet''' isOne = False for i in range(R): if (mat[i][j] == 1): isOne = True elif (isOne): res += 1 isOne = False for i in range(R - 1, -1, -1): if (mat[i][j] == 1): isOne = True elif (isOne): res += 1 return res '''Driver code''' mat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]] print(getTotalCoverageOfMatrix(mat))
Factor Tree of a given Number
/*Java program to conFactor Tree for a given number*/ import java.util.*; class GFG { /* Tree node*/ static class Node { Node left, right; int key; }; static Node root; /* Utility function to create a new tree Node*/ static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return temp; } /* Constructs factor tree for given value and stores root of tree at given reference.*/ static Node createFactorTree(Node node_ref, int v) { (node_ref) = newNode(v); /* the number is factorized*/ for (int i = 2 ; i < v/2 ; i++) { if (v % i != 0) continue; /* If we found a factor, we conleft and right subtrees and return. Since we traverse factors starting from smaller to greater, left child will always have smaller factor*/ node_ref.left = createFactorTree(((node_ref).left), i); node_ref.right = createFactorTree(((node_ref).right), v/i); return node_ref; } return node_ref; } /* Iterative method to find the height of Binary Tree*/ static void printLevelOrder(Node root) { /* Base Case*/ if (root == null) return; Queue<Node > q = new LinkedList<>(); q.add(root); while (q.isEmpty() == false) { /* Print front of queue and remove it from queue*/ Node node = q.peek(); System.out.print(node.key + " "); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } } /* Driver program*/ public static void main(String[] args) { /* int val = 48;sample value*/ root = null; root = createFactorTree(root, val); System.out.println("Level order traversal of "+ "constructed factor tree"); printLevelOrder(root); } }
null
Find pair with greatest product in array
/*Java program to find the largest product number*/ import java.util.*; class GFG { /* Function to find greatest number*/ static int findGreatest(int arr[], int n) { /* Store occurrences of all elements in hash array*/ Map<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], m.get(arr[i])); } } /* m[arr[i]]++; Sort the array and traverse all elements from end.*/ Arrays.sort(arr); for (int i = n - 1; i > 1; i--) { /* For every element, check if there is another element which divides it.*/ for (int j = 0; j < i && arr[j] <= Math.sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; /* Check if the result value exists in array or not if yes the return arr[i]*/ if (result != arr[j] && m.get(result) == null|| m.get(result) > 0) { return arr[i]; } /* To handle the case like arr[i] = 4 and arr[j] = 2*/ else if (result == arr[j] && m.get(result) > 1) { return arr[i]; } } } } return -1; } /* Driver code*/ public static void main(String[] args) { int arr[] = {17, 2, 1, 15, 30}; int n = arr.length; System.out.println(findGreatest(arr, n)); } }
'''Python3 program to find the largest product number''' from math import sqrt '''Function to find greatest number''' def findGreatest(arr, n): ''' Store occurrences of all elements in hash array''' m = dict() for i in arr: m[i] = m.get(i, 0) + 1 ''' Sort the array and traverse all elements from end.''' arr=sorted(arr) for i in range(n - 1, 0, -1): ''' For every element, check if there is another element which divides it.''' j = 0 while(j < i and arr[j] <= sqrt(arr[i])): if (arr[i] % arr[j] == 0): result = arr[i]//arr[j] ''' Check if the result value exists in array or not if yes the return arr[i]''' if (result != arr[j] and (result in m.keys() )and m[result] > 0): return arr[i] ''' To handle the case like arr[i] = 4 and arr[j] = 2''' elif (result == arr[j] and (result in m.keys()) and m[result] > 1): return arr[i] j += 1 return -1 '''Drivers code''' arr= [17, 2, 1, 15, 30] n = len(arr) print(findGreatest(arr, n))
Making elements of two arrays same with minimum increment/decrement
/*Java program to find minimum increment/decrement operations to make array elements same.*/ import java.util.Arrays; import java.io.*; class GFG { static int MinOperation(int a[], int b[], int n) { /* sorting both arrays in ascending order*/ Arrays.sort(a); Arrays.sort(b); /* variable to store the final result*/ int result = 0; /* After sorting both arrays Now each array is in non- decreasing order. Thus, we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b[].*/ for (int i = 0; i < n; ++i) { if (a[i] > b[i]) result = result + Math.abs(a[i] - b[i]); else if (a[i] < b[i]) result = result + Math.abs(a[i] - b[i]); } return result; } /*Driver code*/ public static void main (String[] args) { int a[] = {3, 1, 1}; int b[] = {1, 2, 2}; int n = a.length; System.out.println(MinOperation(a, b, n)); } }
'''Python 3 program to find minimum increment/decrement operations to make array elements same.''' def MinOperation(a, b, n): ''' sorting both arrays in ascending order''' a.sort(reverse = False) b.sort(reverse = False) ''' variable to store the final result''' result = 0 ''' After sorting both arrays. Now each array is in non-decreasing order. Thus, we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b[].''' for i in range(0, n, 1): if (a[i] > b[i]): result = result + abs(a[i] - b[i]) elif(a[i] < b[i]): result = result + abs(a[i] - b[i]) return result '''Driver code''' if __name__ == '__main__': a = [3, 1, 1] b = [1, 2, 2] n = len(a) print(MinOperation(a, b, n))
Count elements which divide all numbers in range L-R
/*Java program to Count elements which divides all numbers in range L-R*/ import java.io.*; class GFG { /*function to count element Time complexity O(n^2) worst case*/ static int answerQuery(int a[], int n, int l, int r) { /* answer for query*/ int count = 0; /* 0 based index*/ l = l - 1; /* iterate for all elements*/ for (int i = l; i < r; i++) { int element = a[i]; int divisors = 0; /* check if the element divides all numbers in range*/ for (int j = l; j < r; j++) { /* no of elements*/ if (a[j] % a[i] == 0) divisors++; else break; } /* if all elements are divisible by a[i]*/ if (divisors == (r - l)) count++; } /* answer for every query*/ return count; } /*Driver Code*/ public static void main (String[] args) { int a[] = { 1, 2, 3, 5 }; int n = a.length; int l = 1, r = 4; System.out.println( answerQuery(a, n, l, r)); l = 2; r = 4; System.out.println( answerQuery(a, n, l, r)); } }
'''Python 3 program to Count elements which divides all numbers in range L-R''' '''function to count element Time complexity O(n^2) worst case''' def answerQuery(a, n, l, r): ''' answer for query''' count = 0 ''' 0 based index''' l = l - 1 ''' iterate for all elements''' for i in range(l, r, 1): element = a[i] divisors = 0 ''' check if the element divides all numbers in range''' for j in range(l, r, 1): ''' no of elements''' if (a[j] % a[i] == 0): divisors += 1 else: break ''' if all elements are divisible by a[i]''' if (divisors == (r - l)): count += 1 ''' answer for every query''' return count '''Driver Code''' if __name__ =='__main__': a = [1, 2, 3, 5] n = len(a) l = 1 r = 4 print(answerQuery(a, n, l, r)) l = 2 r = 4 print(answerQuery(a, n, l, r))
Count smaller elements on right side
class CountSmaller { void constructLowerArray(int arr[], int countSmaller[], int n) { int i, j; /* initialize all the counts in countSmaller array as 0*/ for (i = 0; i < n; i++) countSmaller[i] = 0; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (arr[j] < arr[i]) countSmaller[i]++; } } } /* Utility function that prints out an array on a line */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(""); } /* Driver program to test above functions*/ public static void main(String[] args) { CountSmaller small = new CountSmaller(); int arr[] = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2}; int n = arr.length; int low[] = new int[n]; small.constructLowerArray(arr, low, n); small.printArray(low, n); } }
def constructLowerArray (arr, countSmaller, n): ''' initialize all the counts in countSmaller array as 0''' for i in range(n): countSmaller[i] = 0 for i in range(n): for j in range(i + 1,n): if (arr[j] < arr[i]): countSmaller[i] += 1 '''Utility function that prints out an array on a line''' def printArray(arr, size): for i in range(size): print(arr[i],end=" ") print() '''Driver code''' arr = [12, 10, 5, 4, 2, 20, 6, 1, 0, 2] n = len(arr) low = [0]*n constructLowerArray(arr, low, n) printArray(low, n)
Diameter of a Binary Tree
/*Recursive Java program to find the diameter of a Binary Tree*/ /*Class containing left and right child of current node and key value*/ class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } /*A utility class to pass heigh object*/ class Height { int h; } /*Class to print the Diameter*/ class BinaryTree { Node root; /* define height =0 globally and call diameterOpt(root,height) from main*/ int diameterOpt(Node root, Height height) { /* lh --> Height of left subtree rh --> Height of right subtree*/ Height lh = new Height(), rh = new Height(); /* base condition- when binary tree is empty*/ if (root == null) { height.h = 0;/*diameter is also 0*/ return 0; } /* ldiameter --> diameter of left subtree rdiameter --> Diameter of right subtree Get the heights of left and right subtrees in lh and rh. And store the returned values in ldiameter and ldiameter*/ int ldiameter = diameterOpt(root.left, lh); int rdiameter = diameterOpt(root.right, rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ height.h = Math.max(lh.h, rh.h) + 1; return Math.max(lh.h + rh.h + 1, Math.max(ldiameter, rdiameter)); } /* A wrapper over diameter(Node root)*/ int diameter() { Height height = new Height(); return diameterOpt(root, height); } /* The function Compute the "height" of a tree. Height is the number f nodes along the longest path from the root node down to the farthest leaf node.*/ static int height(Node node) { /* base case tree is empty*/ if (node == null) return 0; /* If tree is not empty then height = 1 + max of left height and right heights*/ return (1 + Math.max(height(node.left), height(node.right))); } /* Driver Code*/ public static void main(String args[]) { /* creating a binary tree and entering the nodes*/ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Function Call*/ System.out.println( "The diameter of given binary tree is : " + tree.diameter()); } }
'''Python3 program to find the diameter of a binary tree''' '''A binary tree Node''' class Node: def __init__(self, data): self.data = data self.left = self.right = None '''utility class to pass height object''' class Height: def __init(self): self.h = 0 '''Optimised recursive function to find diameter of binary tree''' def diameterOpt(root, height): ''' to store height of left and right subtree''' lh = Height() rh = Height() ''' base condition- when binary tree is empty''' if root is None: height.h = 0 '''diameter is also 0''' return 0 ''' ldiameter --> diameter of left subtree rdiamter --> diameter of right subtree height of left subtree and right subtree is obtained from lh and rh and returned value of function is stored in ldiameter and rdiameter''' ldiameter = diameterOpt(root.left, lh) rdiameter = diameterOpt(root.right, rh) ''' height of tree will be max of left subtree height and right subtree height plus1''' height.h = max(lh.h, rh.h) + 1 return max(lh.h + rh.h + 1, max(ldiameter, rdiameter)) '''function to calculate diameter of binary tree''' def diameter(root): height = Height() return diameterOpt(root, height) '''Driver Code''' ''' Constructed binary tree is 1 / \ 2 3 / \ 4 5 ''' root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) '''Function Call''' print(diameter(root))
Rank of an element in a stream
/*Java program to find rank of an element in a stream.*/ class GFG { /*Driver code*/ public static void main(String[] args) { int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = a.length; int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } System.out.println("Rank of " + key + " in stream is: " + (count - 1)); } }
'''Python3 program to find rank of an element in a stream.''' '''Driver code''' if __name__ == '__main__': a = [5, 1, 14, 4, 15, 9, 7, 20, 11] key = 20 arraySize = len(a) count = 0 for i in range(arraySize): if a[i] <= key: count += 1 print("Rank of", key, "in stream is:", count - 1)
Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
/*Java program for the above approach*/ import java.util.*; class GFG{ /*Function to find the maximum sum of consecutive 0s present at the start and end of any rotation of the string str*/ static void findMaximumZeros(String str, int n) { /* Stores the count of 0s*/ int c0 = 0; for(int i = 0; i < n; ++i) { if (str.charAt(i) == '0') c0++; } /* If the frequency of '1' is 0*/ if (c0 == n) { /* Print n as the result*/ System.out.print(n); return; } /* Stores the required sum*/ int mx = 0; /* Find the maximum consecutive length of 0s present in the string*/ int cnt = 0; for(int i = 0; i < n; i++) { if (str.charAt(i) == '0') cnt++; else { mx = Math.max(mx, cnt); cnt = 0; } } /* Update the overall maximum sum*/ mx = Math.max(mx, cnt); /* Find the number of 0s present at the start and end of the string*/ int start = 0, end = n - 1; cnt = 0; /* Update the count of 0s at the start*/ while (str.charAt(start) != '1' && start < n) { cnt++; start++; } /* Update the count of 0s at the end*/ while (str.charAt(end) != '1' && end >= 0) { cnt++; end--; } /* Update the maximum sum*/ mx = Math.max(mx, cnt); /* Print the result*/ System.out.println(mx); } /*Driver Code*/ public static void main (String[] args) { /* Given string*/ String s = "1001"; /* Store the size of the string*/ int n = s.length(); findMaximumZeros(s, n); } }
'''Python3 program for the above approach''' '''Function to find the maximum sum of consecutive 0s present at the start and end of any rotation of the string str''' def findMaximumZeros(string, n): ''' Stores the count of 0s''' c0 = 0 for i in range(n): if (string[i] == '0'): c0 += 1 ''' If the frequency of '1' is 0''' if (c0 == n): ''' Print n as the result''' print(n, end = "") return ''' Stores the required sum''' mx = 0 ''' Find the maximum consecutive length of 0s present in the string''' cnt = 0 for i in range(n): if (string[i] == '0'): cnt += 1 else: mx = max(mx, cnt) cnt = 0 ''' Update the overall maximum sum''' mx = max(mx, cnt) ''' Find the number of 0s present at the start and end of the string''' start = 0 end = n - 1 cnt = 0 ''' Update the count of 0s at the start''' while (string[start] != '1' and start < n): cnt += 1 start += 1 ''' Update the count of 0s at the end''' while (string[end] != '1' and end >= 0): cnt += 1 end -= 1 ''' Update the maximum sum''' mx = max(mx, cnt) ''' Print the result''' print(mx, end = "") '''Driver Code''' if __name__ == "__main__": ''' Given string''' s = "1001" ''' Store the size of the string''' n = len(s) findMaximumZeros(s, n)
Least frequent element in an array
/*Java program to find the least frequent element in an array.*/ import java.io.*; import java.util.*; class GFG { static int leastFrequent(int arr[], int n) { /* Sort the array*/ Arrays.sort(arr); /* find the min frequency using linear traversal*/ int min_count = n+1, res = -1; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } /* If last element is least frequent*/ if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } /* driver program*/ public static void main(String args[]) { int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.length; System.out.print(leastFrequent(arr, n)); } }
'''Python 3 program to find the least frequent element in an array.''' def leastFrequent(arr, n) : ''' Sort the array''' arr.sort() ''' find the min frequency using linear traversal''' min_count = n + 1 res = -1 curr_count = 1 for i in range(1, n) : if (arr[i] == arr[i - 1]) : curr_count = curr_count + 1 else : if (curr_count < min_count) : min_count = curr_count res = arr[i - 1] curr_count = 1 ''' If last element is least frequent''' if (curr_count < min_count) : min_count = curr_count res = arr[n - 1] return res '''Driver program''' arr = [1, 3, 2, 1, 2, 2, 3, 1] n = len(arr) print(leastFrequent(arr, n))
How to swap two numbers without using a temporary variable?
/*Java program to swap two numbers*/ import java.io.*; class GFG { /*Function to swap the numbers.*/ public static void swap(int a, int b) {/* same as a = a + b*/ a = (a & b) + (a | b); /* same as b = a - b*/ b = a + (~b) + 1; /* same as a = a - b*/ a = a + (~b) + 1; System.out.print("After swapping: a = " + a + ", b = " + b); } /*Driver Code*/ public static void main(String[] args) { int a = 5, b = 10;/* Function Call*/ swap(a, b); } }
'''Python3 program to swap two numbers''' '''Function to swap the numbers''' def swap(a, b): ''' Same as a = a + b''' a = (a & b) + (a | b) ''' Same as b = a - b''' b = a + (~b) + 1 ''' Same as a = a - b''' a = a + (~b) + 1 print("After Swapping: a = ", a, ", b = ", b) '''Driver code''' a = 5 b = 10 '''Function call''' swap(a, b)
Minimum number of distinct elements after removing m items
/*Java program for Minimum number of distinct elements after removing m items*/ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class DistinctIds { /* Function to find distintc id's*/ static int distinctIds(int arr[], int n, int mi) { Map<Integer, Integer> m = new HashMap<Integer, Integer>(); int count = 0; int size = 0; /* Store the occurrence of ids*/ for (int i = 0; i < n; i++) { if (m.containsKey(arr[i]) == false) { m.put(arr[i], 1); size++; } else m.put(arr[i], m.get(arr[i]) + 1); }/* Start removing elements from the beginning*/ for (Entry<Integer, Integer> mp:m.entrySet()) { /* Remove if current value is less than or equal to mi*/ if (mp.getKey() <= mi) { mi -= mp.getKey(); count++; } /* Return the remaining size*/ else return size - count; } return size - count; } /* Driver method to test above function*/ public static void main(String[] args) { int arr[] = {2, 3, 1, 2, 3, 3}; int m = 3; System.out.println(distinctIds(arr, arr.length, m)); } }
'''Python program for above implementation''' '''Function to find distintc id's''' def distinctIds(arr, n, mi): m = {} v = [] count = 0 ''' Store the occurrence of ids''' for i in range(n): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 ''' Store into the list value as key and vice-versa''' for i in m: v.append([m[i],i]) v.sort() size = len(v) ''' Start removing elements from the beginning''' for i in range(size): ''' Remove if current value is less than or equal to mi''' if (v[i][0] <= mi): mi -= v[i][0] count += 1 '''Return the remaining size''' else: return size - count return size - count '''Driver code''' arr = [ 2, 3, 1, 2, 3, 3 ] n = len(arr) m = 3 print(distinctIds(arr, n, m))
Array Queries for multiply, replacements and product
/*Java program to solve three types of queries.*/ import java.io.*; import java.util.*; import java.util.Arrays; class GFG{ static Scanner sc= new Scanner(System.in); /*Vector of 1000 elements, all set to 0*/ static int twos[] = new int[1000]; /*Vector of 1000 elements, all set to 0*/ static int fives[] = new int[1000]; static int sum = 0; /*Function to check number of trailing zeros in multiple of 2*/ static int returnTwos(int val) { int count = 0; while (val % 2 == 0 && val != 0) { val = val / 2; count++; } return count; } /*Function to check number of trailing zeros in multiple of 5*/ static int returnFives(int val) { int count = 0; while (val % 5 == 0 && val != 0) { val = val / 5; count++; } return count; } /*Function to solve the queries received*/ static void solve_queries(int arr[], int n) { int type = sc.nextInt(); /* If the query is of type 1.*/ if (type == 1) { int ql = sc.nextInt(); int qr = sc.nextInt(); int x = sc.nextInt(); /* Counting the number of zeros in the given value of x*/ int temp = returnTwos(x); int temp1 = returnFives(x); for(int i = ql - 1; i < qr; i++) { /* The value x has been multiplied to their respective indices*/ arr[i] = arr[i] * x; /* The value obtained above has been added to their respective vectors*/ twos[i] += temp; fives[i] += temp1; } } /* If the query is of type 2.*/ if (type == 2) { int ql = sc.nextInt(); int qr = sc.nextInt(); int y = sc.nextInt(); /* Counting the number of zero in the given value of x*/ int temp = returnTwos(y); int temp1 = returnFives(y); for(int i = ql - 1; i < qr; i++) { /* The value y has been replaced to their respective indices*/ arr[i] = (i - ql + 2) * y; /* The value obtained above has been added to their respective vectors*/ twos[i] = returnTwos(i - ql + 2) + temp; fives[i] = returnFives(i - ql + 2) + temp1; } } /* If the query is of type 2*/ if (type == 3) { int ql = sc.nextInt(); int qr = sc.nextInt(); int sumtwos = 0; int sumfives = 0; for(int i = ql - 1; i < qr; i++) { /* As the number of trailing zeros for each case has been found for each array element then we simply add those to the respective index to a variable*/ sumtwos += twos[i]; sumfives += fives[i]; } /* Compare the number of zeros obtained in the multiples of five and two consider the minimum of them and add them*/ sum += Math.min(sumtwos, sumfives); } } /*Driver code*/ public static void main(String[] args) { /* Input the Size of array and number of queries*/ int n = sc.nextInt(); int m = sc.nextInt(); int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); twos[i] = returnTwos(arr[i]); fives[i] = returnFives(arr[i]); } /* Running the while loop for m number of queries*/ while (m-- != 0) { solve_queries(arr, n); } System.out.println(sum); } }
'''Python3 program to solve three typees of queries.''' '''vector of 1000 elements, all set to 0''' twos = [0] * 1000 '''vector of 1000 elements, all set to 0''' fives = [0] * 1000 sum = 0 '''Function to check number of trailing zeros in multiple of 2''' def returnTwos(val): count = 0 while (val % 2 == 0 and val != 0): val = val // 2 count += 1 return count '''Function to check number of trailing zeros in multiple of 5''' def returnFives(val): count = 0 while (val % 5 == 0 and val != 0): val = val // 5 count += 1 return count '''Function to solve the queries received''' def solve_queries(arr, n): global sum arrr1 = list(map(int,input().split())) typee = arrr1[0] ''' If the query is of typee 1.''' if (typee == 1): ql, qr, x = arrr1[1], arrr1[2], arrr1[3] ''' Counting the number of zeros in the given value of x''' temp = returnTwos(x) temp1 = returnFives(x) i = ql - 1 while(i < qr): ''' The value x has been multiplied to their respective indices''' arr[i] = arr[i] * x ''' The value obtained above has been added to their respective vectors''' twos[i] += temp fives[i] += temp1 i += 1 ''' If the query is of typee 2.''' if (typee == 2): ql, qr, y = arrr1[1], arrr1[2], arrr1[3] ''' Counting the number of zero in the given value of x''' temp = returnTwos(y) temp1 = returnFives(y) i = ql - 1 while(i < qr): ''' The value y has been replaced to their respective indices''' arr[i] = (i - ql + 2) * y ''' The value obtained above has been added to their respective vectors''' twos[i] = returnTwos(i - ql + 2) + temp fives[i] = returnFives(i - ql + 2) + temp1 i += 1 ''' If the query is of typee 2''' if (typee == 3): ql, qr = arrr1[1], arrr1[2] sumtwos = 0 sumfives = 0 i = ql - 1 while(i < qr): ''' As the number of trailing zeros for each case has been found for each array element then we simply add those to the respective index to a variable''' sumtwos += twos[i] sumfives += fives[i] i += 1 ''' Compare the number of zeros obtained in the multiples of five and two consider the minimum of them and add them''' sum += min(sumtwos, sumfives) '''Driver code''' '''Input the Size of array and number of queries''' n, m = map(int, input().split()) arr = list(map(int, input().split())) for i in range(n): twos[i] = returnTwos(arr[i]) fives[i] = returnFives(arr[i]) '''Running the while loop for m number of queries''' while (m): m -= 1 solve_queries(arr, n) print(sum)
Find a number in minimum steps
/*Java program to Find a number in minimum steps*/ import java.util.*; class GFG { static Vector<Integer> find(int n) { /* Steps sequence*/ Vector<Integer> ans = new Vector<>(); /* Current sum*/ int sum = 0; int i = 1; /* Sign of the number*/ int sign = (n >= 0 ? 1 : -1); n = Math.abs(n); /* Basic steps required to get sum >= required value.*/ for (; sum < n;) { ans.add(sign * i); sum += i; i++; } /* If we have reached ahead to destination.*/ if (sum > sign * n) { /*If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum. */ if (i % 2 != 0) { sum -= n; if (sum % 2 != 0) { ans.add(sign * i); sum += i; i++; } int a = ans.get((sum / 2) - 1); ans.remove((sum / 2) - 1); ans.add(((sum / 2) - 1), a*(-1)); } else { /* If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there. */ sum -= n; if (sum % 2 != 0) { sum--; ans.add(sign * i); ans.add(sign * -1 * (i + 1)); } ans.add((sum / 2) - 1, ans.get((sum / 2) - 1) * -1); } } return ans; } /* Driver Program*/ public static void main(String[] args) { int n = 20; if (n == 0) System.out.print("Minimum number of Steps: 0\nStep sequence:\n0"); else { Vector<Integer> a = find(n); System.out.print("Minimum number of Steps: " + a.size()+ "\nStep sequence:\n"); for (int i : a) System.out.print(i + " "); } } }
'''Python3 program to Find a number in minimum steps''' def find(n): ''' Steps sequence''' ans = [] ''' Current sum''' Sum = 0 i = 0 ''' Sign of the number''' sign = 0 if (n >= 0): sign = 1 else: sign = -1 n = abs(n) i = 1 ''' Basic steps required to get sum >= required value.''' while (Sum < n): ans.append(sign * i) Sum += i i += 1 ''' If we have reached ahead to destination.''' if (Sum > sign * n): ''' If the last step was an odd number, then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum.''' if (i % 2!=0): Sum -= n if (Sum % 2 != 0): ans.append(sign * i) Sum += i i += 1 ans[int(Sum / 2) - 1] *= -1 else: ''' If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there.''' Sum -= n if (Sum % 2 != 0): Sum -= 1 ans.append(sign * i) ans.append(sign * -1 * (i + 1)) ans[int((sum / 2)) - 1] *= -1 return ans '''Driver code''' n = 20 if (n == 0): print("Minimum number of Steps: 0\nStep sequence:\n0") else: a = find(n) print("Minimum number of Steps:", len(a)) print("Step sequence:") print(*a, sep = " ")
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
/*Java program to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree */ class GFG { /*A Binary Tree Node */ static class Node { int data; Node left, right; }; static class INT { int a; INT(int a){this.a=a;} } /*Utility function to create a new tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } /*A utility function to print inorder traversal of a Binary Tree */ static void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.printf("%d ", node.data); printInorder(node.right); } /*A recursive function to con Full binary tree from pre[] and preM[]. preIndex is used to keep track of index in pre[]. l is low index and h is high index for the current subarray in preM[] */ static Node conBinaryTreeUtil(int pre[], int preM[], INT preIndex, int l, int h, int size) { /* Base case */ if (preIndex.a >= size || l > h) return null; /* The first node in preorder traversal is root. So take the node at preIndex from preorder and make it root, and increment preIndex */ Node root = newNode(pre[preIndex.a]); ++(preIndex.a); /* If the current subarry has only one element, no need to recur */ if (l == h) return root; /* Search the next element of pre[] in preM[] */ int i; for (i = l; i <= h; ++i) if (pre[preIndex.a] == preM[i]) break; /* con left and right subtrees recursively */ if (i <= h) { root.left = conBinaryTreeUtil (pre, preM, preIndex, i, h, size); root.right = conBinaryTreeUtil (pre, preM, preIndex, l + 1, i - 1, size); } /* return root */ return root; } /*function to con full binary tree using its preorder traversal and preorder traversal of its mirror tree */ static void conBinaryTree(Node root,int pre[], int preMirror[], int size) { INT preIndex = new INT(0); int preMIndex = 0; root = conBinaryTreeUtil(pre,preMirror, preIndex, 0, size - 1, size); printInorder(root); } /*Driver code*/ public static void main(String args[]) { int preOrder[] = {1,2,4,5,3,6,7}; int preOrderMirror[] = {1,3,7,6,2,5,4}; int size = preOrder.length; Node root = new Node(); conBinaryTree(root,preOrder,preOrderMirror,size); } }
'''Python3 program to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree ''' '''Utility function to create a new tree node ''' class newNode: def __init__(self,data): self.data = data self.left = self.right = None '''A utility function to print inorder traversal of a Binary Tree ''' def prInorder(node): if (node == None) : return prInorder(node.left) print(node.data, end = " ") prInorder(node.right) '''A recursive function to construct Full binary tree from pre[] and preM[]. preIndex is used to keep track of index in pre[]. l is low index and h is high index for the current subarray in preM[] ''' def constructBinaryTreeUtil(pre, preM, preIndex, l, h, size): ''' Base case ''' if (preIndex >= size or l > h) : return None , preIndex ''' The first node in preorder traversal is root. So take the node at preIndex from preorder and make it root, and increment preIndex ''' root = newNode(pre[preIndex]) preIndex += 1 ''' If the current subarry has only one element, no need to recur ''' if (l == h): return root, preIndex ''' Search the next element of pre[] in preM[]''' i = 0 for i in range(l, h + 1): if (pre[preIndex] == preM[i]): break ''' construct left and right subtrees recursively ''' if (i <= h): root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, i, h, size) root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, l + 1, i - 1, size) ''' return root ''' return root, preIndex '''function to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree''' def constructBinaryTree(root, pre, preMirror, size): preIndex = 0 preMIndex = 0 root, x = constructBinaryTreeUtil(pre, preMirror, preIndex, 0, size - 1, size) prInorder(root) '''Driver code ''' if __name__ =="__main__": preOrder = [1, 2, 4, 5, 3, 6, 7] preOrderMirror = [1, 3, 7, 6, 2, 5, 4] size = 7 root = newNode(0) constructBinaryTree(root, preOrder, preOrderMirror, size)
Elements that occurred only once in the array
/*Java implementation to find elements that appeared only once*/ class GFG { /*Function to find the elements that appeared only once in the array*/ static void occurredOnce(int arr[], int n) { int i = 1, len = n; /* Check if the first and last element is equal. If yes, remove those elements*/ if (arr[0] == arr[len - 1]) { i = 2; len--; } /* Start traversing the remaining elements*/ for (; i < n; i++) /* Check if current element is equal to the element at immediate previous index If yes, check the same for next element*/ if (arr[i] == arr[i - 1]) i++; /* Else print the current element*/ else System.out.print(arr[i - 1] + " "); /* Check for the last element*/ if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) System.out.print(arr[n - 1]); } /*Driver code*/ public static void main(String args[]) { int arr[] = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.length; occurredOnce(arr, n); } }
'''Python 3 implementation to find elements that appeared only once''' '''Function to find the elements that appeared only once in the array''' def occurredOnce(arr, n): i = 1 len = n ''' Check if the first and last element is equal If yes, remove those elements''' if arr[0] == arr[len - 1]: i = 2 len -= 1 ''' Start traversing the remaining elements''' while i < n: ''' Check if current element is equal to the element at immediate previous index If yes, check the same for next element''' if arr[i] == arr[i - 1]: i += 1 ''' Else print the current element''' else: print(arr[i - 1], end = " ") i += 1 ''' Check for the last element''' if (arr[n - 1] != arr[0] and arr[n - 1] != arr[n - 2]): print(arr[n - 1]) '''Driver code''' if __name__ == "__main__": arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] n = len(arr) occurredOnce(arr, n)
Given an array arr[], find the maximum j
/*Java program for the above approach*/ class FindMaximum { /* For a given array arr[], returns the maximum j-i such that arr[j] > arr[i] */ int maxIndexDiff(int arr[], int n) { int maxDiff = -1; int i, j; for (i = 0; i < n; ++i) { for (j = n - 1; j > i; --j) { if (arr[j] > arr[i] && maxDiff < (j - i)) maxDiff = j - i; } } return maxDiff; } /* Driver program to test above functions */ public static void main(String[] args) { FindMaximum max = new FindMaximum(); int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 }; int n = arr.length; int maxDiff = max.maxIndexDiff(arr, n); System.out.println(maxDiff); } }
'''Python3 program to find the maximum j – i such that arr[j] > arr[i]''' '''For a given array arr[], returns the maximum j – i such that arr[j] > arr[i]''' def maxIndexDiff(arr, n): maxDiff = -1 for i in range(0, n): j = n - 1 while(j > i): if arr[j] > arr[i] and maxDiff < (j - i): maxDiff = j - i j -= 1 return maxDiff '''driver code''' arr = [9, 2, 3, 4, 5, 6, 7, 8, 18, 0] n = len(arr) maxDiff = maxIndexDiff(arr, n) print(maxDiff)
Sparse Table
/*Java program to do range minimum query using sparse table*/ import java.util.*; class GFG { static final int MAX = 500; /*lookup[i][j] is going to store GCD of arr[i..j]. Ideally lookup table size should not be fixed and should be determined using n Log n. It is kept constant to keep code simple.*/ static int [][]table = new int[MAX][MAX]; /*it builds sparse table.*/ static void buildSparseTable(int arr[], int n) { /* GCD of single element is element itself*/ for (int i = 0; i < n; i++) table[i][0] = arr[i]; /* Build sparse table*/ for (int j = 1; j <= n; j++) for (int i = 0; i <= n - (1 << j); i++) table[i][j] = __gcd(table[i][j - 1], table[i + (1 << (j - 1))][j - 1]); } /*Returns GCD of arr[L..R]*/ static int query(int L, int R) { /* Find highest power of 2 that is smaller than or equal to count of elements in given range.For [2, 10], j = 3*/ int j = (int)Math.log(R - L + 1); /* Compute GCD of last 2^j elements with first 2^j elements in range. For [2, 10], we find GCD of arr[lookup[0][3]] and arr[lookup[3][3]],*/ return __gcd(table[L][j], table[R - (1 << j) + 1][j]); } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } /*Driver Code*/ public static void main(String[] args) { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = a.length; buildSparseTable(a, n); System.out.print(query(0, 2) + "\n"); System.out.print(query(1, 3) + "\n"); System.out.print(query(4, 5) + "\n"); } }
'''Python3 program to do range minimum query using sparse table''' import math ''' lookup[i][j] is going to store minimum value in arr[i..j]. Ideally lookup table size should not be fixed and should be determined using n Log n. It is kept constant to keep code simple.''' '''Fills lookup array lookup[][] in bottom up manner.''' def buildSparseTable(arr, n): ''' GCD of single element is element itself''' for i in range(0, n): table[i][0] = arr[i] ''' Build sparse table''' j = 1 while (1 << j) <= n: i = 0 while i <= n - (1 << j): table[i][j] = math.gcd(table[i][j - 1], table[i + (1 << (j - 1))][j - 1]) i += 1 j += 1 '''Returns minimum of arr[L..R]''' def query(L, R): ''' Find highest power of 2 that is smaller than or equal to count of elements in given range. For [2, 10], j = 3''' j = int(math.log2(R - L + 1)) ''' Compute GCD of last 2^j elements with first 2^j elements in range. For [2, 10], we find GCD of arr[lookup[0][3]] and arr[lookup[3][3]],''' return math.gcd(table[L][j], table[R - (1 << j) + 1][j]) '''Driver Code''' if __name__ == "__main__": a = [7, 2, 3, 0, 5, 10, 3, 12, 18] n = len(a) MAX = 500 table = [[0 for i in range(MAX)] for j in range(MAX)] buildSparseTable(a, n) print(query(0, 2)) print(query(1, 3)) print(query(4, 5))
Check whether Arithmetic Progression can be formed from the given array
/*Java program to check if a given array can form arithmetic progression*/ import java.util.Arrays; class GFG { /* Returns true if a permutation of arr[0..n-1] can form arithmetic progression*/ static boolean checkIsAP(int arr[], int n) { if (n == 1) return true; /* Sort array*/ Arrays.sort(arr); /* After sorting, difference between consecutive elements must be same.*/ int d = arr[1] - arr[0]; for (int i = 2; i < n; i++) if (arr[i] - arr[i-1] != d) return false; return true; } /* driver code*/ public static void main (String[] args) { int arr[] = { 20, 15, 5, 0, 10 }; int n = arr.length; if(checkIsAP(arr, n)) System.out.println("Yes"); else System.out.println("No"); } }
'''Python3 program to check if a given array can form arithmetic progression''' '''Returns true if a permutation of arr[0..n-1] can form arithmetic progression''' def checkIsAP(arr, n): if (n == 1): return True ''' Sort array''' arr.sort() ''' After sorting, difference between consecutive elements must be same.''' d = arr[1] - arr[0] for i in range(2, n): if (arr[i] - arr[i-1] != d): return False return True '''Driver code''' arr = [ 20, 15, 5, 0, 10 ] n = len(arr) print("Yes") if(checkIsAP(arr, n)) else print("No")
Sort an array according to absolute difference with given value
/*Java program to sort an array according absolute difference with x.*/ import java.io.*; import java.util.*; class GFG { /* Function to sort an array according absolute difference with x.*/ static void rearrange(int[] arr, int n, int x) { TreeMap<Integer, ArrayList<Integer>> m = new TreeMap<>(); /* Store values in a map with the difference with X as key*/ for (int i = 0; i < n; i++) { int diff = Math.abs(x - arr[i]); if (m.containsKey(diff)) { ArrayList<Integer> al = m.get(diff); al.add(arr[i]); m.put(diff, al); } else { ArrayList<Integer> al = new ArrayList<>(); al.add(arr[i]); m.put(diff,al); } } /* Update the values of array*/ int index = 0; for (Map.Entry entry : m.entrySet()) { ArrayList<Integer> al = m.get(entry.getKey()); for (int i = 0; i < al.size(); i++) arr[index++] = al.get(i); } } /* Function to print the array*/ static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } /* Driver code*/ public static void main(String args[]) { int[] arr = {10, 5, 3, 9 ,2}; int n = arr.length; int x = 7; rearrange(arr, n, x); printArray(arr, n); } }
'''Python3 program to sort an array according absolute difference with x. ''' '''Function to sort an array according absolute difference with x.''' def rearrange(arr, n, x): m = {} ''' Store values in a map with the difference with X as key''' for i in range(n): m[arr[i]] = abs(x - arr[i]) m = {k : v for k, v in sorted(m.items(), key = lambda item : item[1])} ''' Update the values of array''' i = 0 for it in m.keys(): arr[i] = it i += 1 '''Function to print the array''' def printArray(arr, n): for i in range(n): print(arr[i], end = " ") '''Driver code''' if __name__ == "__main__": arr = [10, 5, 3, 9, 2] n = len(arr) x = 7 rearrange(arr, n, x) printArray(arr, n)
Compute the minimum or maximum of two integers without branching
/*JAVA implementation of above approach*/ class GFG { static int CHAR_BIT = 4; static int INT_BIT = 8; /*Function to find minimum of x and y*/ static int min(int x, int y) { return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /*Function to find maximum of x and y*/ static int max(int x, int y) { return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /* Driver code */ public static void main(String[] args) { int x = 15; int y = 6; System.out.println("Minimum of "+x+" and "+y+" is "+min(x, y)); System.out.println("Maximum of "+x+" and "+y+" is "+max(x, y)); } }
'''Python3 implementation of the approach''' import sys; CHAR_BIT = 8; INT_BIT = sys.getsizeof(int()); '''Function to find minimum of x and y''' def Min(x, y): return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); '''Function to find maximum of x and y''' def Max(x, y): return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); '''Driver code''' x = 15; y = 6; print("Minimum of", x, "and", y, "is", Min(x, y)); print("Maximum of", x, "and", y, "is", Max(x, y));
How to check if a given array represents a Binary Heap?
/*Java program to check whether a given array represents a max-heap or not*/ class GFG { /* Returns true if arr[i..n-1] represents a max-heap*/ static boolean isHeap(int arr[], int i, int n) { /* If a leaf node*/ if (i >= (n - 2) / 2) { return true; } /* If an internal node and is greater than its children, and same is recursively true for the children*/ if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false; } /* Driver program*/ public static void main(String[] args) { int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; int n = arr.length - 1; if (isHeap(arr, 0, n)) { System.out.println("Yes"); } else { System.out.println("No"); } } }
'''Python3 program to check whether a given array represents a max-heap or not ''' '''Returns true if arr[i..n-1] represents a max-heap''' def isHeap(arr, i, n): '''If a leaf node''' if i >= int((n - 2) / 2): return True ''' If an internal node and is greater than its children, and same is recursively true for the children''' if(arr[i] >= arr[2 * i + 1] and arr[i] >= arr[2 * i + 2] and isHeap(arr, 2 * i + 1, n) and isHeap(arr, 2 * i + 2, n)): return True return False '''Driver Code''' if __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2, 7, 3] n = len(arr) - 1 if isHeap(arr, 0, n): print("Yes") else: print("No")
Program to cyclically rotate an array by one
import java.util.Arrays; public class Test { static int arr[] = new int[]{1, 2, 3, 4, 5}; /*i and j pointing to first and last element respectively*/ static void rotate() { int i = 0, j = arr.length - 1; while(i != j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } }/* Driver program */ public static void main(String[] args) { System.out.println("Given Array is"); System.out.println(Arrays.toString(arr)); rotate(); System.out.println("Rotated Array is"); System.out.println(Arrays.toString(arr)); } }
'''i and j pointing to first and last element respectively''' def rotate(arr, n): i = 0 j = n - 1 while i != j: arr[i], arr[j] = arr[j], arr[i] i = i + 1 pass '''Driver function''' arr= [1, 2, 3, 4, 5] n = len(arr) print ("Given array is") for i in range(0, n): print (arr[i], end = ' ') rotate(arr, n) print ("\nRotated array is") for i in range(0, n): print (arr[i], end = ' ')
Count 1's in a sorted binary array
/*Java program to count 1's in a sorted array*/ class CountOnes { /* Returns counts of 1's in arr[low..high]. The array is assumed to be sorted in non-increasing order */ int countOnes(int arr[], int low, int high) { if (high >= low) { /* get the middle index*/ int mid = low + (high - low) / 2; /* check if the element at middle index is last 1*/ if ((mid == high || arr[mid + 1] == 0) && (arr[mid] == 1)) return mid + 1; /* If element is not last 1, recur for right side*/ if (arr[mid] == 1) return countOnes(arr, (mid + 1), high); /* else recur for left side*/ return countOnes(arr, low, (mid - 1)); } return 0; } /* Driver code */ public static void main(String args[]) { CountOnes ob = new CountOnes(); int arr[] = { 1, 1, 1, 1, 0, 0, 0 }; int n = arr.length; System.out.println("Count of 1's in given array is " + ob.countOnes(arr, 0, n - 1)); } }
'''Python program to count one's in a boolean array''' '''Returns counts of 1's in arr[low..high]. The array is assumed to be sorted in non-increasing order''' def countOnes(arr,low,high): if high>=low: ''' get the middle index''' mid = low + (high-low)//2 ''' check if the element at middle index is last 1''' if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)): return mid+1 ''' If element is not last 1, recur for right side''' if arr[mid]==1: return countOnes(arr, (mid+1), high) ''' else recur for left side''' return countOnes(arr, low, mid-1) return 0 '''Driver Code''' arr=[1, 1, 1, 1, 0, 0, 0] print ("Count of 1's in given array is",countOnes(arr, 0 , len(arr)-1))
Remove minimum number of elements such that no common element exist in both array
/*JAVA Code to Remove minimum number of elements such that no common element exist in both array*/ import java.util.*; class GFG { /* To find no elements to remove so no common element exist*/ public static int minRemove(int a[], int b[], int n, int m) { /* To store count of array element*/ HashMap<Integer, Integer> countA = new HashMap< Integer, Integer>(); HashMap<Integer, Integer> countB = new HashMap< Integer, Integer>(); /* Count elements of a*/ for (int i = 0; i < n; i++){ if (countA.containsKey(a[i])) countA.put(a[i], countA.get(a[i]) + 1); else countA.put(a[i], 1); } /* Count elements of b*/ for (int i = 0; i < m; i++){ if (countB.containsKey(b[i])) countB.put(b[i], countB.get(b[i]) + 1); else countB.put(b[i], 1); } /* Traverse through all common element, and pick minimum occurrence from two arrays*/ int res = 0; Set<Integer> s = countA.keySet(); for (int x : s) if(countB.containsKey(x)) res += Math.min(countB.get(x), countA.get(x)); /* To return count of minimum elements*/ return res; } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 1, 2, 3, 4 }; int b[] = { 2, 3, 4, 5, 8 }; int n = a.length; int m = b.length; System.out.println(minRemove(a, b, n, m)); } }
'''Python3 program to find minimum element to remove so no common element exist in both array''' '''To find no elements to remove so no common element exist''' def minRemove(a, b, n, m): ''' To store count of array element''' countA = dict() countB = dict() ''' Count elements of a''' for i in range(n): countA[a[i]] = countA.get(a[i], 0) + 1 ''' Count elements of b''' for i in range(n): countB[b[i]] = countB.get(b[i], 0) + 1 ''' Traverse through all common element, and pick minimum occurrence from two arrays''' res = 0 for x in countA: if x in countB.keys(): res += min(countA[x],countB[x]) ''' To return count of minimum elements''' return res '''Driver Code''' a = [ 1, 2, 3, 4 ] b = [2, 3, 4, 5, 8 ] n = len(a) m = len(b) print(minRemove(a, b, n, m))
Check if an array is sorted and rotated
import java.io.*; class GFG { /* Function to check if an array is Sorted and rotated clockwise*/ static boolean checkIfSortRotated(int arr[], int n) { /* Initializing two variables x,y as zero.*/ int x = 0, y = 0; /* Traversing array 0 to last element. n-1 is taken as we used i+1.*/ for (int i = 0; i < n - 1; i++) { if (arr[i] < arr[i + 1]) x++; else y++; } /* If till now both x,y are greater then 1 means array is not sorted. If both any of x,y is zero means array is not rotated.*/ if (x == 1 || y == 1) { /* Checking for last element with first.*/ if (arr[n - 1] < arr[0]) x++; else y++; /* Checking for final result.*/ if (x == 1 || y == 1) return true; } /* If still not true then definetly false.*/ return false; } /* Driver code*/ public static void main(String[] args) { int arr[] = { 5, 1, 2, 3, 4 }; int n = arr.length; /* Function Call*/ boolean x = checkIfSortRotated(arr, n); if (x == true) System.out.println("YES"); else System.out.println("NO"); } }
null
Merge k sorted arrays | Set 1
/*Java program to merge k sorted arrays of size n each.*/ import java.util.*; class GFG{ static final int n = 4; /* Merge arr1[0..n1-1] and arr2[0..n2-1] into arr3[0..n1+n2-1]*/ static void mergeArrays(int arr1[], int arr2[], int n1, int n2, int arr3[]) { int i = 0, j = 0, k = 0; /* Traverse both array*/ while (i<n1 && j <n2) { /* Check if current element of first array is smaller than current element of second array. If yes, store first array element and increment first array index. Otherwise do same with second array*/ if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++]; else arr3[k++] = arr2[j++]; } /* Store remaining elements of first array*/ while (i < n1) arr3[k++] = arr1[i++]; /* Store remaining elements of second array*/ while (j < n2) arr3[k++] = arr2[j++]; } /* A utility function to print array elements*/ static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) System.out.print(arr[i]+ " "); } /* 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.*/ static void mergeKArrays(int arr[][], int i, int j, int output[]) { /* if one array is in range*/ if(i == j) { for(int p = 0; p < n; p++) output[p] = arr[i][p]; return; } /* if only two arrays are left them merge them*/ if(j - i == 1) { mergeArrays(arr[i], arr[j], n, n, output); return; } /* output arrays*/ int []out1 = new int[n*(((i + j) / 2) - i + 1)]; int []out2 = new int[n*(j - ((i + j) / 2))]; /* divide the array into halves*/ mergeKArrays(arr, i, (i + j) / 2, out1); mergeKArrays(arr, (i + j) / 2 + 1, j, out2); /* merge the output array*/ mergeArrays(out1, out2, n * (((i + j) / 2) - i + 1), n * (j - ((i + j) / 2)), output); } /* Driver program to test above functions*/ public static void main(String[] args) { /* Change n at the top to change number of elements in an array*/ int arr[][] = {{2, 6, 12, 34}, {1, 9, 20, 1000}, {23, 34, 90, 2000}}; int k = arr.length; int []output = new int[n*k]; mergeKArrays(arr,0,2, output); System.out.print("Merged array is " +"\n"); printArray(output, n*k); } }
null
Swap Nodes in Binary tree of every k'th level
/*Java program swap nodes */ class GFG { /*A Binary Tree Node */ static class Node { int data; Node left, right; }; /*function to create a new tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp; } /*A utility function swap left- node & right node of tree of every k'th level */ static void swapEveryKLevelUtil( Node root, int level, int k) { /* base case */ if (root== null || (root.left==null && root.right==null) ) return ; /* if current level + 1 is present in swap vector then we swap left & right node */ if ( (level + 1) % k == 0) { Node temp=root.left; root.left=root.right; root.right=temp; } /* Recur for left and right subtrees */ swapEveryKLevelUtil(root.left, level+1, k); swapEveryKLevelUtil(root.right, level+1, k); } /*This function mainly calls recursive function swapEveryKLevelUtil() */ static void swapEveryKLevel(Node root, int k) { /* call swapEveryKLevelUtil function with initial level as 1. */ swapEveryKLevelUtil(root, 1, k); } /*Utility method for inorder tree traversal */ static void inorder(Node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } /*Driver Code */ public static void main(String args[]) { /* 1 / \ 2 3 / / \ 4 7 8 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.right = newNode(8); root.right.left = newNode(7); int k = 2; System.out.println("Before swap node :"); inorder(root); swapEveryKLevel(root, k); System.out.println("\nAfter swap Node :" ); inorder(root); } }
'''Python program to swap nodes A binary tree node''' ''' constructor to create a new node ''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None '''A utility function swap left node and right node of tree of every k'th level ''' def swapEveryKLevelUtil(root, level, k): ''' Base Case ''' if (root is None or (root.left is None and root.right is None ) ): return ''' If current level+1 is present in swap vector then we swap left and right node''' if (level+1)%k == 0: root.left, root.right = root.right, root.left ''' Recur for left and right subtree''' swapEveryKLevelUtil(root.left, level+1, k) swapEveryKLevelUtil(root.right, level+1, k) '''This function mainly calls recursive function swapEveryKLevelUtil''' def swapEveryKLevel(root, k): ''' Call swapEveryKLevelUtil function with initial level as 1''' swapEveryKLevelUtil(root, 1, k) '''Method to find the inorder tree travesal''' def inorder(root): if root is None: return inorder(root.left) print root.data, inorder(root.right) '''Driver code''' ''' 1 / \ 2 3 / / \ 4 7 8 ''' root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.right = Node(8) root.right.left = Node(7) k = 2 print "Before swap node :" inorder(root) swapEveryKLevel(root, k) print "\nAfter swap Node : " inorder(root)
Iterative diagonal traversal of binary tree
/*Java program to con string from binary tree*/ import java.util.*; class solution { /*A binary tree node has data, pointer to left child and a pointer to right child*/ static class Node { int data; Node left, right; }; /*Helper function that allocates a new node*/ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } /*Iterative function to print diagonal view*/ static void diagonalPrint(Node root) { /* base case*/ if (root == null) return; /* inbuilt queue of Treenode*/ Queue<Node> q= new LinkedList<Node>(); /* add root*/ q.add(root); /* add delimiter*/ q.add(null); while (q.size()>0) { Node temp = q.peek(); q.remove(); /* if current is delimiter then insert another for next diagonal and cout nextline*/ if (temp == null) { /* if queue is empty return*/ if (q.size()==0) return; /* output nextline*/ System.out.println(); /* add delimiter again*/ q.add(null); } else { while (temp!=null) { System.out.print( temp.data + " "); /* if left child is present add into queue*/ if (temp.left!=null) q.add(temp.left); /* current equals to right child*/ temp = temp.right; } } } } /*Driver Code*/ public static void main(String args[]) { Node root = newNode(8); root.left = newNode(3); root.right = newNode(10); root.left.left = newNode(1); root.left.right = newNode(6); root.right.right = newNode(14); root.right.right.left = newNode(13); root.left.right.left = newNode(4); root.left.right.right = newNode(7); diagonalPrint(root); } }
'''Python3 program to construct string from binary tree''' '''A binary tree node has data, pointer to left child and a pointer to right child''' class Node: def __init__(self,data): self.val = data self.left = None self.right = None '''Function to print diagonal view''' def diagonalprint(root): ''' base case''' if root is None: return ''' queue of treenode''' q = [] ''' Append root''' q.append(root) ''' Append delimiter''' q.append(None) while len(q) > 0: temp = q.pop(0) ''' If current is delimiter then insert another for next diagonal and cout nextline''' if not temp: ''' If queue is empty then return''' if len(q) == 0: return ''' Print output on nextline''' print(' ') ''' append delimiter again''' q.append(None) else: while temp: print(temp.val, end = ' ') ''' If left child is present append into queue''' if temp.left: q.append(temp.left) ''' current equals to right child''' temp = temp.right '''Driver Code''' root = Node(8) root.left = Node(3) root.right = Node(10) root.left.left = Node(1) root.left.right = Node(6) root.right.right = Node(14) root.right.right.left = Node(13) root.left.right.left = Node(4) root.left.right.right = Node(7) diagonalprint(root)
Maximum possible difference of two subsets of an array
/*Java find maximum difference of subset sum*/ import java.util.*; class GFG{ /*Function for maximum subset diff*/ public static int maxDiff(int arr[], int n) { HashMap<Integer, Integer> hashPositive = new HashMap<>(); HashMap<Integer, Integer> hashNegative = new HashMap<>(); int SubsetSum_1 = 0, SubsetSum_2 = 0; /* Construct hash for positive elements*/ for (int i = 0; i <= n - 1; i++) { if (arr[i] > 0) { if(hashPositive.containsKey(arr[i])) { hashPositive.replace(arr[i], hashPositive.get(arr[i]) + 1); } else { hashPositive.put(arr[i], 1); } } } /* Calculate subset sum for positive elements*/ for (int i = 0; i <= n - 1; i++) { if(arr[i] > 0 && hashPositive.containsKey(arr[i])) { if(hashPositive.get(arr[i]) == 1) { SubsetSum_1 += arr[i]; } } } /* Construct hash for negative elements*/ for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0) { if(hashNegative.containsKey(Math.abs(arr[i]))) { hashNegative.replace(Math.abs(arr[i]), hashNegative.get(Math.abs(arr[i])) + 1); } else { hashNegative.put(Math.abs(arr[i]), 1); } } } /* Calculate subset sum for negative elements*/ for (int i = 0; i <= n - 1; i++) { if (arr[i] < 0 && hashNegative.containsKey(Math.abs(arr[i]))) { if(hashNegative.get(Math.abs(arr[i])) == 1) { SubsetSum_2 += arr[i]; } } } return Math.abs(SubsetSum_1 - SubsetSum_2); } /*Driver code*/ public static void main(String[] args) { int arr[] = {4, 2, -3, 3, -2, -2, 8}; int n = arr.length; System.out.print("Maximum Difference = " + maxDiff(arr, n)); } }
'''Python3 find maximum difference of subset sum ''' '''function for maximum subset diff''' def maxDiff(arr, n): hashPositive = dict() hashNegative = dict() SubsetSum_1, SubsetSum_2 = 0, 0 ''' construct hash for positive elements''' for i in range(n): if (arr[i] > 0): hashPositive[arr[i]] = \ hashPositive.get(arr[i], 0) + 1 ''' calculate subset sum for positive elements''' for i in range(n): if (arr[i] > 0 and arr[i] in hashPositive.keys() and hashPositive[arr[i]] == 1): SubsetSum_1 += arr[i] ''' construct hash for negative elements''' for i in range(n): if (arr[i] < 0): hashNegative[abs(arr[i])] = \ hashNegative.get(abs(arr[i]), 0) + 1 ''' calculate subset sum for negative elements''' for i in range(n): if (arr[i] < 0 and abs(arr[i]) in hashNegative.keys() and hashNegative[abs(arr[i])] == 1): SubsetSum_2 += arr[i] return abs(SubsetSum_1 - SubsetSum_2) '''Driver Code''' arr = [4, 2, -3, 3, -2, -2, 8] n = len(arr) print("Maximum Difference =", maxDiff(arr, n))
Random number generator in arbitrary probability distribution fashion
/*Java program to generate random numbers according to given frequency distribution*/ class GFG { /*Utility function to find ceiling of r in arr[l..h]*/ static int findCeil(int arr[], int r, int l, int h) { int mid; while (l < h) { /*Same as mid = (l+h)/2*/ mid = l + ((h - l) >> 1); if(r > arr[mid]) l = mid + 1; else h = mid; } return (arr[l] >= r) ? l : -1; } /*The main function that returns a random number from arr[] according to distribution array defined by freq[]. n is size of arrays.*/ static int myRand(int arr[], int freq[], int n) { /* Create and fill prefix array*/ int prefix[] = new int[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; /* prefix[n-1] is sum of all frequencies. Generate a random number with value from 1 to this sum*/ int r = ((int)(Math.random()*(323567)) % prefix[n - 1]) + 1; /* Find index of ceiling of r in prefix arrat*/ int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc]; } /*Driver code*/ public static void main(String args[]) { int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = arr.length; /* Let us generate 10 random numbers accroding to given distribution*/ for (i = 0; i < 5; i++) System.out.println( myRand(arr, freq, n) ); } }
'''Python3 program to generate random numbers according to given frequency distribution''' import random '''Utility function to find ceiling of r in arr[l..h]''' def findCeil(arr, r, l, h) : while (l < h) : '''Same as mid = (l+h)/2''' mid = l + ((h - l) >> 1); if r > arr[mid] : l = mid + 1 else : h = mid if arr[l] >= r : return l else : return -1 '''The main function that returns a random number from arr[] according to distribution array defined by freq[]. n is size of arrays.''' def myRand(arr, freq, n) : ''' Create and fill prefix array''' prefix = [0] * n prefix[0] = freq[0] for i in range(n) : prefix[i] = prefix[i - 1] + freq[i] ''' prefix[n-1] is sum of all frequencies. Generate a random number with value from 1 to this sum''' r = random.randint(0, prefix[n - 1]) + 1 ''' Find index of ceiling of r in prefix arrat''' indexc = findCeil(prefix, r, 0, n - 1) return arr[indexc] '''Driver code''' arr = [1, 2, 3, 4] freq = [10, 5, 20, 100] n = len(arr) '''Let us generate 10 random numbers accroding to given distribution''' for i in range(5) : print(myRand(arr, freq, n))
Segregate 0s and 1s in an array
/*Java code to segregate 0 and 1*/ import java.util.*; class GFG{ /** Method for segregation 0 and 1 given input array */ static void segregate0and1(int arr[]) { int type0 = 0; int type1 = arr.length - 1; while (type0 < type1) { if (arr[type0] == 1) { arr[type1] = arr[type1]+ arr[type0]; arr[type0] = arr[type1]-arr[type0]; arr[type1] = arr[type1]-arr[type0]; type1--; } else { type0++; } } } /*Driver program*/ public static void main(String[] args) { int[] array = {0, 1, 0, 1, 1, 1}; segregate0and1(array); for(int a : array){ System.out.print(a+" "); } } }
'''Python program to sort a binary array in one pass''' '''Function to put all 0s on left and all 1s on right''' def segregate0and1(arr, size): type0 = 0 type1 = size - 1 while(type0 < type1): if(arr[type0] == 1): (arr[type0], arr[type1]) = (arr[type1], arr[type0]) type1 -= 1 else: type0 += 1 '''Driver Code''' arr = [0, 1, 0, 1, 1, 1] arr_size = len(arr) segregate0and1(arr, arr_size) print("Array after segregation is", end = " ") for i in range(0, arr_size): print(arr[i], end = " ")
Find the smallest and second smallest elements in an array
/*Java program to find smallest and second smallest elements*/ import java.io.*; class SecondSmallest { /* Function to print first smallest and second smallest elements */ static void print2Smallest(int arr[]) { int first, second, arr_size = arr.length; /* There should be atleast two elements */ if (arr_size < 2) { System.out.println(" Invalid Input "); return; } first = second = Integer.MAX_VALUE; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Integer.MAX_VALUE) System.out.println("There is no second" + "smallest element"); else System.out.println("The smallest element is " + first + " and second Smallest" + " element is " + second); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); } }
'''Python program to find smallest and second smallest elements''' import sys '''Function to print first smallest and second smallest elements ''' def print2Smallest(arr): ''' There should be atleast two elements''' arr_size = len(arr) if arr_size < 2: print "Invalid Input" return first = second = sys.maxint for i in range(0, arr_size): ''' If current element is smaller than first then update both first and second''' if arr[i] < first: second = first first = arr[i] ''' If arr[i] is in between first and second then update second''' elif (arr[i] < second and arr[i] != first): second = arr[i]; if (second == sys.maxint): print "No second smallest element" else: print 'The smallest element is',first,'and' \ ' second smallest element is',second '''Driver function to test above function''' arr = [12, 13, 1, 10, 34, 1] print2Smallest(arr)
Program for addition of two matrices
/*Java program for addition of two matrices*/ class GFG { static final int N = 4; /* This function adds A[][] and B[][], and stores the result in C[][]*/ static void add(int A[][], int B[][], int C[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j]; } /* Driver code*/ public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int C[][] = new int[N][N]; int i, j; add(A, B, C); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(C[i][j] + " "); System.out.print("\n"); } } }
'''Python3 program for addition of two matrices''' N = 4 '''This function adds A[][] and B[][], and stores the result in C[][]''' def add(A,B,C): for i in range(N): for j in range(N): C[i][j] = A[i][j] + B[i][j] '''driver code''' A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B= [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] C=A[:][:] add(A, B, C) print("Result matrix is") for i in range(N): for j in range(N): print(C[i][j], " ", end='') print()
Equilibrium index of an array
/*Java program to find equilibrium index of an array*/ class EquilibriumIndex { /*function to find the equilibrium index*/ int equilibrium(int arr[], int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { leftsum = 0; rightsum = 0; /* get left sum */ for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } /* Driver code*/ public static void main(String[] args) { EquilibriumIndex equi = new EquilibriumIndex(); int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = arr.length; System.out.println(equi.equilibrium(arr, arr_size)); } }
'''Python program to find equilibrium index of an array''' '''function to find the equilibrium index''' def equilibrium(arr): leftsum = 0 rightsum = 0 n = len(arr) ''' Check for indexes one by one until an equilibrium index is found''' for i in range(n): leftsum = 0 rightsum = 0 ''' get left sum''' for j in range(i): leftsum += arr[j] ''' get right sum''' for j in range(i + 1, n): rightsum += arr[j] ''' if leftsum and rightsum are same, then we are done''' if leftsum == rightsum: return i ''' return -1 if no equilibrium index is found''' return -1 '''driver code''' arr = [-7, 1, 5, 2, -4, 3, 0] print (equilibrium(arr))
Length of the longest valid substring
/*Java program to implement the above approach*/ import java.util.Scanner; import java.util.Arrays; class GFG { /* Function to return the length of the longest valid substring*/ public static int solve(String s, int n) { /* Variables for left and right counter maxlength to store the maximum length found so far*/ int left = 0, right = 0; int maxlength = 0; /* Iterating the string from left to right*/ for (int i = 0; i < n; i++) { /* If "(" is encountered, then left counter is incremented else right counter is incremented*/ if (s.charAt(i) == '(') left++; else right++; /* Whenever left is equal to right, it signifies that the subsequence is valid and*/ if (left == right) maxlength = Math.max(maxlength, 2 * right); /* Reseting the counters when the subsequence becomes invalid*/ else if (right > left) left = right = 0; } left = right = 0; /* Iterating the string from right to left*/ for (int i = n - 1; i >= 0; i--) { /* If "(" is encountered, then left counter is incremented else right counter is incremented*/ if (s.charAt(i) == '(') left++; else right++; /* Whenever left is equal to right, it signifies that the subsequence is valid and*/ if (left == right) maxlength = Math.max(maxlength, 2 * left); /* Reseting the counters when the subsequence becomes invalid*/ else if (left > right) left = right = 0; } return maxlength; } /* Driver code*/ public static void main(String args[]) { /* Function call*/ System.out.print(solve("((()()()()(((())", 16)); } }
'''Python3 program to implement the above approach''' '''Function to return the length of the longest valid substring''' def solve(s, n): ''' Variables for left and right counter. maxlength to store the maximum length found so far''' left = 0 right = 0 maxlength = 0 ''' Iterating the string from left to right''' for i in range(n): ''' If "(" is encountered, then left counter is incremented else right counter is incremented''' if (s[i] == '('): left += 1 else: right += 1 ''' Whenever left is equal to right, it signifies that the subsequence is valid and''' if (left == right): maxlength = max(maxlength, 2 * right) ''' Reseting the counters when the subsequence becomes invalid''' elif (right > left): left = right = 0 left = right = 0 ''' Iterating the string from right to left''' for i in range(n - 1, -1, -1): ''' If "(" is encountered, then left counter is incremented else right counter is incremented''' if (s[i] == '('): left += 1 else: right += 1 ''' Whenever left is equal to right, it signifies that the subsequence is valid and''' if (left == right): maxlength = max(maxlength, 2 * left) ''' Reseting the counters when the subsequence becomes invalid''' elif (left > right): left = right = 0 return maxlength '''Driver code''' '''Function call''' print(solve("((()()()()(((())", 16))
Implementing Iterator pattern of a single Linked List
import java.util.*; class GFG { public static void main(String[] args) { /* creating a list*/ ArrayList<Integer> list = new ArrayList<>(); /* elements to be added at the end. in the above created list.*/ list.add(1); list.add(2); list.add(3); /* elements of list are retrieved through iterator.*/ Iterator<Integer> it = list.iterator(); while (it.hasNext()) { System.out.print(it.next() + " "); } } }
if __name__=='__main__': ''' Creating a list''' list = [] ''' Elements to be added at the end. in the above created list.''' list.append(1) list.append(2) list.append(3) ''' Elements of list are retrieved through iterator.''' for it in list: print(it, end = ' ')
Majority Element
/* Program for finding out majority element in an array */ import java.util.HashMap; class MajorityElement { private static void findMajority(int[] arr) { HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < arr.length; i++) { if (map.containsKey(arr[i])) { int count = map.get(arr[i]) +1; if (count > arr.length /2) { System.out.println("Majority found :- " + arr[i]); return; } else map.put(arr[i], count); } else map.put(arr[i],1); } System.out.println(" No Majority element"); }/* Driver program to test the above functions */ public static void main(String[] args) { int a[] = new int[]{2,2,2,2,5,5,2,3,3}; /* Function calling*/ findMajority(a); } }
'''Python3 program for finding out majority element in an array''' def findMajority(arr, size): m = {} for i in range(size): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 count = 0 for key in m: if m[key] > size / 2: count = 1 print("Majority found :-",key) break if(count == 0): print("No Majority element") '''Driver code''' arr = [2, 2, 2, 2, 5, 5, 2, 3, 3] n = len(arr) '''Function calling''' findMajority(arr, n)
Find number of pairs (x, y) in an array such that x^y > y^x
public static long countPairsBruteForce(long X[], long Y[], int m, int n) { long ans = 0; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (Math.pow(X[i], Y[j]) > Math.pow(Y[j], X[i])) ans++; return ans; }
def countPairsBruteForce(X, Y, m, n): ans = 0 for i in range(m): for j in range(n): if (pow(X[i], Y[j]) > pow(Y[j], X[i])): ans += 1 return ans
Manacher's Algorithm
/*Java program to implement Manacher's Algorithm */ import java.util.*; class GFG { static void findLongestPalindromicString(String text) { int N = text.length(); if (N == 0) return; /*Position count*/ N = 2 * N + 1; /*LPS Length Array*/ int[] L = new int[N + 1]; L[0] = 0; L[1] = 1; /*centerPosition*/ int C = 1; /*centerRightPosition*/ int R = 2; /*currentRightPosition*/ int i = 0; /*currentLeftPosition*/ int iMirror; int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; /* Uncomment it to print LPS Length array printf("%d %d ", L[0], L[1]);*/ for (i = 2; i < N; i++) { /* get currentLeftPosition iMirror for currentRightPosition i*/ iMirror = 2 * C - i; L[i] = 0; diff = R - i; /* If currentRightPosition i is within centerRightPosition R*/ if (diff > 0) L[i] = Math.min(L[iMirror], diff); /* Attempt to expand palindrome centered at currentRightPosition i. Here for odd positions, we compare characters and if match then increment LPS Length by ONE. If even position, we just increment LPS by ONE without any character comparison*/ while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } /*Track maxLPSLength*/ if (L[i] > maxLPSLength) { maxLPSLength = L[i]; maxLPSCenterPosition = i; } /* If palindrome centered at currentRightPosition i expand beyond centerRightPosition R, adjust centerPosition C based on expanded palindrome.*/ if (i + L[i] > R) { C = i; R = i + L[i]; } /* Uncomment it to print LPS Length array printf("%d ", L[i]);*/ } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; System.out.printf("LPS of string is %s : ", text); for (i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println(); } /* Driver Code*/ public static void main(String[] args) { String text = "babcbabcbaccba"; findLongestPalindromicString(text); text = "abaaba"; findLongestPalindromicString(text); text = "abababa"; findLongestPalindromicString(text); text = "abcbabcbabcba"; findLongestPalindromicString(text); text = "forgeeksskeegfor"; findLongestPalindromicString(text); text = "caba"; findLongestPalindromicString(text); text = "abacdfgdcaba"; findLongestPalindromicString(text); text = "abacdfgdcabba"; findLongestPalindromicString(text); text = "abacdedcaba"; findLongestPalindromicString(text); } }
'''Python program to implement Manacher's Algorithm''' def findLongestPalindromicString(text): N = len(text) if N == 0: return '''Position count''' N = 2*N+1 '''LPS Length Array''' L = [0] * N L[0] = 0 L[1] = 1 '''centerPosition''' C = 1 '''centerRightPosition''' R = 2 '''currentRightPosition''' i = 0 '''currentLeftPosition''' iMirror = 0 maxLPSLength = 0 maxLPSCenterPosition = 0 start = -1 end = -1 diff = -1 ''' Uncomment it to print LPS Length array printf("%d %d ", L[0], L[1]);''' for i in xrange(2,N): ''' get currentLeftPosition iMirror for currentRightPosition i''' iMirror = 2*C-i L[i] = 0 diff = R - i ''' If currentRightPosition i is within centerRightPosition R''' if diff > 0: L[i] = min(L[iMirror], diff) ''' Attempt to expand palindrome centered at currentRightPosition i Here for odd positions, we compare characters and if match then increment LPS Length by ONE If even position, we just increment LPS by ONE without any character comparison''' try: while ((i + L[i]) < N and (i - L[i]) > 0) and \ (((i + L[i] + 1) % 2 == 0) or \ (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2])): L[i]+=1 except Exception as e: pass '''Track maxLPSLength''' if L[i] > maxLPSLength: maxLPSLength = L[i] maxLPSCenterPosition = i ''' If palindrome centered at currentRightPosition i expand beyond centerRightPosition R, adjust centerPosition C based on expanded palindrome.''' if i + L[i] > R: C = i R = i + L[i] ''' Uncomment it to print LPS Length array printf("%d ", L[i]);''' start = (maxLPSCenterPosition - maxLPSLength) / 2 end = start + maxLPSLength - 1 print "LPS of string is " + text + " : ", print text[start:end+1], print "\n", '''Driver program''' text1 = "babcbabcbaccba" findLongestPalindromicString(text1) text2 = "abaaba" findLongestPalindromicString(text2) text3 = "abababa" findLongestPalindromicString(text3) text4 = "abcbabcbabcba" findLongestPalindromicString(text4) text5 = "forgeeksskeegfor" findLongestPalindromicString(text5) text6 = "caba" findLongestPalindromicString(text6) text7 = "abacdfgdcaba" findLongestPalindromicString(text7) text8 = "abacdfgdcabba" findLongestPalindromicString(text8) text9 = "abacdedcaba" findLongestPalindromicString(text9)
Check if two numbers are bit rotations of each other or not
/*Java program to check if two numbers are bit rotations of each other.*/ class GFG { /*function to check if two numbers are equal after bit rotation*/ static boolean isRotation(long x, long y) { /* x64 has concatenation of x with itself.*/ long x64 = x | (x << 32); while (x64 >= y) { /* comapring only last 32 bits*/ if (x64 == y) { return true; } /* right shift by 1 unit*/ x64 >>= 1; } return false; } /*driver code to test above function*/ public static void main(String[] args) { long x = 122; long y = 2147483678L; if (isRotation(x, y) == false) { System.out.println("Yes"); } else { System.out.println("No"); } } }
'''Python3 program to check if two numbers are bit rotations of each other.''' '''function to check if two numbers are equal after bit rotation''' def isRotation(x, y) : ''' x64 has concatenation of x with itself.''' x64 = x | (x << 32) while (x64 >= y) : ''' comapring only last 32 bits''' if ((x64) == y) : return True ''' right shift by 1 unit''' x64 >>= 1 return False '''Driver Code''' if __name__ == "__main__" : x = 122 y = 2147483678 if (isRotation(x, y) == False) : print("yes") else : print("no")
Count of n digit numbers whose sum of digits equals to given sum
/*A Java program using recursive to count numbers with sum of digits as given 'sum'*/ class sum_dig { /* Recursive function to count 'n' digit numbers with sum of digits as 'sum'. This function considers leading 0's also as digits, that is why not directly called*/ static int countRec(int n, int sum) { /* Base case*/ if (n == 0) return sum == 0 ?1:0; if (sum == 0) return 1; /* Initialize answer*/ int ans = 0; /* Traverse through every digit and count numbers beginning with it using recursion*/ for (int i=0; i<=9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* This is mainly a wrapper over countRec. It explicitly handles leading digit and calls countRec() for remaining digits.*/ static int finalCount(int n, int sum) { /* Initialize final answer*/ int ans = 0; /* Traverse through every digit from 1 to 9 and count numbers beginning with it*/ for (int i = 1; i <= 9; i++) if (sum-i >= 0) ans += countRec(n-1, sum-i); return ans; } /* Driver program to test above function */ public static void main (String args[]) { int n = 2, sum = 5; System.out.println(finalCount(n, sum)); } }
'''A python 3 program using recursive to count numbers with sum of digits as given sum''' '''Recursive function to count 'n' digit numbers with sum of digits as 'sum' This function considers leading 0's also as digits, that is why not directly called''' def countRec(n, sum) : ''' Base case''' if (n == 0) : return (sum == 0) if (sum == 0) : return 1 ''' Initialize answer''' ans = 0 ''' Traverse through every digit and count numbers beginning with it using recursion''' for i in range(0, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans '''This is mainly a wrapper over countRec. It explicitly handles leading digit and calls countRec() for remaining digits.''' def finalCount(n, sum) : ''' Initialize final answer''' ans = 0 ''' Traverse through every digit from 1 to 9 and count numbers beginning with it''' for i in range(1, 10) : if (sum-i >= 0) : ans = ans + countRec(n-1, sum-i) return ans '''Driver program''' n = 2 sum = 5 print(finalCount(n, sum))
Count half nodes in a Binary tree (Iterative and Recursive)
/*Java program to count half nodes in a Binary Tree */ import java.util.*; class GfG { /*A binary tree Node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; } /*Function to get the count of half Nodes in a binary tree */ static int gethalfCount(Node root) { if (root == null) return 0; int res = 0; if ((root.left == null && root.right != null) || (root.left != null && root.right == null)) res++; res += (gethalfCount(root.left) + gethalfCount(root.right)); return res; } /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } /*Driver program */ public static void main(String[] args) { /* 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example */ Node root = newNode(2); root.left = newNode(7); root.right = newNode(5); root.left.right = newNode(6); root.left.right.left = newNode(1); root.left.right.right = newNode(11); root.right.right = newNode(9); root.right.right.left = newNode(4); System.out.println(gethalfCount(root)); } }
'''Python program to count half nodes in a binary tree''' '''A node structure''' class newNode: def __init__(self, data): self.data = data self.left = self.right = None '''Function to get the count of half Nodes in a binary tree''' def gethalfCount(root): if root == None: return 0 res = 0 if(root.left == None and root.right != None) or \ (root.left != None and root.right == None): res += 1 res += (gethalfCount(root.left) + \ gethalfCount(root.right)) return res '''Driver program''' ''' 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example ''' root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.right.left = newNode(1) root.left.right.right = newNode(11) root.right.right = newNode(9) root.right.right.left = newNode(4) print(gethalfCount(root))
Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction)
/*Java program to demonstrate working of Square Root Decomposition.*/ import java.util.*; class GFG { static int MAXN = 10000; static int SQRSIZE = 100; /*original array*/ static int []arr = new int[MAXN]; /*decomposed array*/ static int []block = new int[SQRSIZE]; /*block size*/ static int blk_sz; /*Time Complexity : O(1)*/ static void update(int idx, int val) { int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val; } /*Time Complexity : O(sqrt(n))*/ static int query(int l, int r) { int sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { /* traversing first block in range*/ sum += arr[l]; l++; } while (l+blk_sz <= r) { /* traversing completely overlapped blocks in range*/ sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { /* traversing last block in range*/ sum += arr[l]; l++; } return sum; } /*Fills values in input[]*/ static void preprocess(int input[], int n) { /* initiating block pointer*/ int blk_idx = -1; /* calculating size of block*/ blk_sz = (int) Math.sqrt(n); /* building the decomposed array*/ for (int i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { /* entering next block incementing block pointer*/ blk_idx++; } block[blk_idx] += arr[i]; } } /*Driver code*/ public static void main(String[] args) { /* We have used separate array for input because the purpose of this code is to explain SQRT decomposition in competitive programming where we have multiple inputs.*/ int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = input.length; preprocess(input, n); System.out.println("query(3, 8) : " + query(3, 8)); System.out.println("query(1, 6) : " + query(1, 6)); update(8, 0); System.out.println("query(8, 8) : " + query(8, 8)); } }
'''Python 3 program to demonstrate working of Square Root Decomposition.''' from math import sqrt MAXN = 10000 SQRSIZE = 100 '''original array''' arr = [0]*(MAXN) '''decomposed array''' block = [0]*(SQRSIZE) '''block size''' blk_sz = 0 '''Time Complexity : O(1)''' def update(idx, val): blockNumber = idx // blk_sz block[blockNumber] += val - arr[idx] arr[idx] = val '''Time Complexity : O(sqrt(n))''' def query(l, r): sum = 0 while (l < r and l % blk_sz != 0 and l != 0): ''' traversing first block in range''' sum += arr[l] l += 1 while (l + blk_sz <= r): ''' traversing completely overlapped blocks in range''' sum += block[l//blk_sz] l += blk_sz while (l <= r): ''' traversing last block in range''' sum += arr[l] l += 1 return sum '''Fills values in input[]''' def preprocess(input, n): ''' initiating block pointer''' blk_idx = -1 ''' calculating size of block''' global blk_sz blk_sz = int(sqrt(n)) ''' building the decomposed array''' for i in range(n): arr[i] = input[i]; if (i % blk_sz == 0): ''' entering next block incementing block pointer''' blk_idx += 1; block[blk_idx] += arr[i] '''Driver code''' '''We have used separate array for input because the purpose of this code is to explain SQRT decomposition in competitive programming where we have multiple inputs.''' input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10] n = len(input) preprocess(input, n) print("query(3,8) : ",query(3, 8)) print("query(1,6) : ",query(1, 6)) update(8, 0) print("query(8,8) : ",query(8, 8))
Difference between sums of odd level and even level nodes of a Binary Tree
/*Java program to find difference between sums of odd level and even level nodes of binary tree */ import java.io.*; import java.util.*; /*User defined node class*/ class Node { int data; Node left, right; /* Constructor to create a new tree node*/ Node(int key) { data = key; left = right = null; } } class GFG { /* return difference of sums of odd level and even level */ static int evenOddLevelDifference(Node root) { if (root == null) return 0; /* create a queue for level order traversal*/ Queue<Node> q = new LinkedList<>(); q.add(root); int level = 0; int evenSum = 0, oddSum = 0; /* traverse until the queue is empty*/ while (q.size() != 0) { int size = q.size(); level++; /* traverse for complete level */ while (size > 0) { Node temp = q.remove(); /* check if level no. is even or odd and accordingly update the evenSum or oddSum */ if (level % 2 == 0) evenSum += temp.data; else oddSum += temp.data; /* check for left child */ if (temp.left != null) q.add(temp.left); /* check for right child */ if (temp.right != null) q.add(temp.right); size--; } } return (oddSum - evenSum); } /* Driver code*/ public static void main(String args[]) { /* construct a tree*/ Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); System.out.println("diffence between sums is " + evenOddLevelDifference(root)); } }
'''Python3 program to find maximum product of a level in Binary Tree''' '''Helper function that allocates a new node with the given data and None left and right poers. ''' class newNode: ''' Construct to create a new node ''' def __init__(self, key): self.data = key self.left = None self.right = None '''return difference of sums of odd level and even level''' def evenOddLevelDifference(root): if (not root): return 0 ''' create a queue for level order traversal''' q = [] q.append(root) level = 0 evenSum = 0 oddSum = 0 ''' traverse until the queue is empty''' while (len(q)): size = len(q) level += 1 ''' traverse for complete level''' while(size > 0): temp = q[0] q.pop(0) ''' check if level no. is even or odd and accordingly update the evenSum or oddSum''' if(level % 2 == 0): evenSum += temp.data else: oddSum += temp.data ''' check for left child''' if (temp.left) : q.append(temp.left) ''' check for right child''' if (temp.right): q.append(temp.right) size -= 1 return (oddSum - evenSum) '''Driver Code ''' if __name__ == '__main__': ''' Let us create Binary Tree shown in above example ''' root = newNode(5) root.left = newNode(2) root.right = newNode(6) root.left.left = newNode(1) root.left.right = newNode(4) root.left.right.left = newNode(3) root.right.right = newNode(8) root.right.right.right = newNode(9) root.right.right.left = newNode(7) result = evenOddLevelDifference(root) print("Diffence between sums is", result)
Count frequencies of all elements in array in O(1) extra space and O(n) time
/*Java program to print frequencies of all array elements in O(1) extra space and O(n) time*/ class CountFrequencies { /* Function to find counts of all elements present in arr[0..n-1]. The array elements must be range from 1 to n*/ void findCounts(int arr[], int n) { /* Traverse all array elements*/ int i = 0; while (i < n) { /* If this element is already processed, then nothing to do*/ if (arr[i] <= 0) { i++; continue; } /* Find index corresponding to this element For example, index for 5 is 4*/ int elementIndex = arr[i] - 1; /* If the elementIndex has an element that is not processed yet, then first store that element to arr[i] so that we don't lose anything.*/ if (arr[elementIndex] > 0) { arr[i] = arr[elementIndex]; /* After storing arr[elementIndex], change it to store initial count of 'arr[i]'*/ arr[elementIndex] = -1; } else { /* If this is NOT first occurrence of arr[i], then decrement its count.*/ arr[elementIndex]--; /* And initialize arr[i] as 0 means the element 'i+1' is not seen so far*/ arr[i] = 0; i++; } } System.out.println("Below are counts of all elements"); for (int j = 0; j < n; j++) System.out.println(j+1 + "->" + Math.abs(arr[j])); } /* Driver program to test above functions*/ public static void main(String[] args) { CountFrequencies count = new CountFrequencies(); int arr[] = {2, 3, 3, 2, 5}; count.findCounts(arr, arr.length); int arr1[] = {1}; count.findCounts(arr1, arr1.length); int arr3[] = {4, 4, 4, 4}; count.findCounts(arr3, arr3.length); int arr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1}; count.findCounts(arr2, arr2.length); int arr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}; count.findCounts(arr4, arr4.length); int arr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; count.findCounts(arr5, arr5.length); int arr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; count.findCounts(arr6, arr6.length); } }
'''Python3 program to print frequencies of all array elements in O(1) extra space and O(n) time''' '''Function to find counts of all elements present in arr[0..n-1]. The array elements must be range from 1 to n''' def findCounts(arr, n): ''' Traverse all array elements''' i = 0 while i<n: ''' If this element is already processed, then nothing to do''' if arr[i] <= 0: i += 1 continue ''' Find index corresponding to this element For example, index for 5 is 4''' elementIndex = arr[i] - 1 ''' If the elementIndex has an element that is not processed yet, then first store that element to arr[i] so that we don't lose anything.''' if arr[elementIndex] > 0: arr[i] = arr[elementIndex] ''' After storing arr[elementIndex], change it to store initial count of 'arr[i]''' ''' arr[elementIndex] = -1 else: ''' If this is NOT first occurrence of arr[i], then decrement its count.''' arr[elementIndex] -= 1 ''' And initialize arr[i] as 0 means the element 'i+1' is not seen so far''' arr[i] = 0 i += 1 print ("Below are counts of all elements") for i in range(0,n): print ("%d -> %d"%(i+1, abs(arr[i]))) print ("") '''Driver program to test above function''' arr = [2, 3, 3, 2, 5] findCounts(arr, len(arr)) arr1 = [1] findCounts(arr1, len(arr1)) arr3 = [4, 4, 4, 4] findCounts(arr3, len(arr3)) arr2 = [1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1] findCounts(arr2, len(arr2)) arr4 = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] findCounts(arr4, len(arr4)) arr5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] findCounts(arr5, len(arr5)) arr6 = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] findCounts(arr6, len(arr6))
Subarrays with distinct elements
/*Java program to calculate sum of lengths of subarrays of distinct elements.*/ import java.util.*; class geeks { /* Returns sum of lengths of all subarrays with distinct elements.*/ public static int sumoflength(int[] arr, int n) { /* For maintaining distinct elements.*/ Set<Integer> s = new HashSet<>(); /* Initialize ending point and result*/ int j = 0, ans = 0; /* Fix starting point*/ for (int i = 0; i < n; i++) { while (j < n && !s.contains(arr[j])) { s.add(arr[i]); j++; } /* Calculating and adding all possible length subarrays in arr[i..j]*/ ans += ((j - i) * (j - i + 1)) / 2; /* Remove arr[i] as we pick new stating point from next*/ s.remove(arr[i]); } return ans; } /* Driver Code*/ public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(sumoflength(arr, n)); } }
'''Python 3 program to calculate sum of lengths of subarrays of distinct elements.''' '''Returns sum of lengths of all subarrays with distinct elements.''' def sumoflength(arr, n): ''' For maintaining distinct elements.''' s = [] ''' Initialize ending point and result''' j = 0 ans = 0 ''' Fix starting point''' for i in range(n): while (j < n and (arr[j] not in s)): s.append(arr[j]) j += 1 ''' Calculating and adding all possible length subarrays in arr[i..j]''' ans += ((j - i) * (j - i + 1)) // 2 ''' Remove arr[i] as we pick new stating point from next''' s.remove(arr[i]) return ans '''Driven Code''' if __name__=="__main__": arr = [1, 2, 3, 4] n = len(arr) print(sumoflength(arr, n))
Populate Inorder Successor for all nodes
/*Java program to populate inorder traversal of all nodes*/ /*A binary tree node*/ class Node { int data; Node left, right, next; Node(int item) { data = item; left = right = next = null; } } class BinaryTree { Node root; static Node next = null;/* Set next of p and all descendants of p by traversing them in reverse Inorder */ void populateNext(Node node) { /* The first visited node will be the rightmost node next of the rightmost node will be NULL*/ if (node != null) { /* First set the next pointer in right subtree*/ populateNext(node.right); /* Set the next as previously visited node in reverse Inorder*/ node.next = next; /* Change the prev for subsequent node*/ next = node; /* Finally, set the next pointer in left subtree*/ populateNext(node.left); } } /* Constructed binary tree is 10 / \ 8 12 / 3 */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); /* Populates nextRight pointer in all nodes*/ tree.populateNext(tree.root); /* Let us see the populated values*/ Node ptr = tree.root.left.left; while (ptr != null) { /* -1 is printed if there is no successor*/ int print = ptr.next != null ? ptr.next.data : -1; System.out.println("Next of " + ptr.data + " is: " + print); ptr = ptr.next; } } }
'''Python3 program to populate inorder traversal of all nodes''' '''Tree node''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.next = None next = None '''Set next of p and all descendants of p by traversing them in reverse Inorder''' def populateNext(p): global next '''The first visited node will be the rightmost node next of the rightmost node will be NULL''' if (p != None): ''' First set the next pointer in right subtree''' populateNext(p.right) ''' Set the next as previously visited node in reverse Inorder''' p.next = next ''' Change the prev for subsequent node''' next = p ''' Finally, set the next pointer in left subtree''' populateNext(p.left) '''UTILITY FUNCTIONS Helper function that allocates a new node with the given data and None left and right pointers.''' def newnode(data): node = Node(0) node.data = data node.left = None node.right = None node.next = None return(node) '''Driver Code Constructed binary tree is 10 / \ 8 12 / 3''' root = newnode(10) root.left = newnode(8) root.right = newnode(12) root.left.left = newnode(3) '''Populates nextRight pointer in all nodes''' p = populateNext(root) '''Let us see the populated values''' ptr = root.left.left while(ptr != None): ''' -1 is printed if there is no successor''' out = 0 if(ptr.next != None): out = ptr.next.data else: out = -1 print("Next of", ptr.data, "is", out) ptr = ptr.next
Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time)
/*Naive Java implementation to find LCA in a tree.*/ import java.io.*; import java.util.*; class GFG { static int MAXN = 1001; /* stores depth for each node*/ static int[] depth = new int[MAXN]; /* stores first parent for each node*/ static int[] parent = new int[MAXN]; @SuppressWarnings("unchecked") static Vector<Integer>[] adj = new Vector[MAXN]; static { for (int i = 0; i < MAXN; i++) adj[i] = new Vector<>(); } static void addEdge(int u, int v) { adj[u].add(v); adj[v].add(u); } static void dfs(int cur, int prev) { /* marking parent for each node*/ parent[cur] = prev; /* marking depth for each node*/ depth[cur] = depth[prev] + 1; /* propogating marking down the tree*/ for (int i = 0; i < adj[cur].size(); i++) if (adj[cur].elementAt(i) != prev) dfs(adj[cur].elementAt(i), cur); } static void preprocess() { /* a dummy node*/ depth[0] = -1; /* precalclating 1)depth. 2)parent. for each node*/ dfs(1, 0); } /* Time Complexity : O(Height of tree) recursively jumps one node above till both the nodes become equal*/ static int LCANaive(int u, int v) { if (u == v) return u; if (depth[u] > depth[v]) { int temp = u; u = v; v = temp; } v = parent[v]; return LCANaive(u, v); } /* Driver Code*/ public static void main(String[] args) { /* adding edges to the tree*/ addEdge(1, 2); addEdge(1, 3); addEdge(1, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(4, 8); addEdge(4, 9); addEdge(9, 10); addEdge(9, 11); addEdge(7, 12); addEdge(7, 13); preprocess(); System.out.println("LCA(11,8) : " + LCANaive(11, 8)); System.out.println("LCA(3,13) : " + LCANaive(3, 13)); } }
'''Python3 implementation to find LCA in a tree''' MAXN = 1001 '''stores depth for each node''' depth = [0 for i in range(MAXN)]; '''stores first parent for each node''' parent = [0 for i in range(MAXN)]; adj = [[] for i in range(MAXN)] def addEdge(u, v): adj[u].append(v); adj[v].append(u); def dfs(cur, prev): ''' marking parent for each node''' parent[cur] = prev; ''' marking depth for each node''' depth[cur] = depth[prev] + 1; ''' propogating marking down the tree''' for i in range(len(adj[cur])): if (adj[cur][i] != prev): dfs(adj[cur][i], cur); def preprocess(): ''' a dummy node''' depth[0] = -1; ''' precalculating 1)depth. 2)parent. for each node''' dfs(1, 0); '''Time Complexity : O(Height of tree) recursively jumps one node above till both the nodes become equal''' def LCANaive(u, v): if (u == v): return u; if (depth[u] > depth[v]): u, v = v, u v = parent[v]; return LCANaive(u, v); '''Driver code''' if __name__ == "__main__": ''' adding edges to the tree''' addEdge(1, 2); addEdge(1, 3); addEdge(1, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(4, 8); addEdge(4, 9); addEdge(9, 10); addEdge(9, 11); addEdge(7, 12); addEdge(7, 13); preprocess(); print('LCA(11,8) : ' + str(LCANaive(11, 8))) print('LCA(3,13) : ' + str(LCANaive(3, 13)))
Inorder Tree Traversal without Recursion
/*non-recursive java program for inorder traversal*/ import java.util.Stack; /* Class containing left and right child of current node and key value*/ class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } /* Class to print the inorder traversal */ class BinaryTree { Node root; void inorder() { if (root == null) return; Stack<Node> s = new Stack<Node>(); Node curr = root; /* traverse the tree*/ while (curr != null || s.size() > 0) { /* Reach the left most Node of the curr Node */ while (curr != null) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ s.push(curr); curr = curr.left; } /* Current must be NULL at this point */ curr = s.pop(); System.out.print(curr.data + " "); /* we have visited the node and its left subtree. Now, it's right subtree's turn */ curr = curr.right; } } /* Driver program to test above functions*/ public static void main(String args[]) {/* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.inorder(); } }
'''Python program to do inorder traversal without recursion''' '''A binary tree node''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None '''Iterative function for inorder tree traversal''' def inOrder(root): current = root stack = [] done = 0 '''traverse the tree''' while True: ''' Reach the left most Node of the current Node''' if current is not None: ''' Place pointer to a tree node on the stack before traversing the node's left subtree''' stack.append(current) current = current.left ''' BackTrack from the empty subtree and visit the Node at the top of the stack; however, if the stack is empty you are done''' elif(stack): current = stack.pop() print(current.data, end=" ") ''' We have visited the node and its left subtree. Now, it's right subtree's turn''' current = current.right else: break print() '''Driver program to test above function''' '''Constructed binary tree is 1 / \ 2 3 / \ 4 5 ''' root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) inOrder(root)
Swap all odd and even bits
/*Java program to swap even and odd bits of a given number*/ class GFG{ /* Function to swap even and odd bits*/ static int swapBits(int x) { /* Get all even bits of x*/ int even_bits = x & 0xAAAAAAAA; /* Get all odd bits of x*/ int odd_bits = x & 0x55555555; /* Right shift even bits*/ even_bits >>= 1; /* Left shift odd bits*/ odd_bits <<= 1; /* Combine even and odd bits*/ return (even_bits | odd_bits); } /* Driver program to test above function*/ public static void main(String[] args) { /*00010111*/ int x = 23; /* Output is 43 (00101011)*/ System.out.println(swapBits(x)); } }
'''Python 3 program to swap even and odd bits of a given number''' '''Function for swapping even and odd bits''' def swapBits(x) : ''' Get all even bits of x''' even_bits = x & 0xAAAAAAAA ''' Get all odd bits of x''' odd_bits = x & 0x55555555 ''' Right shift even bits''' even_bits >>= 1 ''' Left shift odd bits''' odd_bits <<= 1 ''' Combine even and odd bits''' return (even_bits | odd_bits) '''Driver program''' '''00010111''' x = 23 '''Output is 43 (00101011)''' print(swapBits(x))
Convert a given Binary Tree to Doubly Linked List | Set 2
/*Java program to convert BTT to DLL using simple inorder traversal*/ public class BinaryTreeToDLL { /*A tree node*/ static class node { int data; node left, right; public node(int data) { this.data = data; } } static node prev;/* Standard Inorder traversal of tree*/ static void inorder(node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } /* Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node*/ static void fixPrevptr(node root) { if (root == null) return; fixPrevptr(root.left); root.left = prev; prev = root; fixPrevptr(root.right); } /* Changes right pointers to work as next pointers in converted DLL*/ static node fixNextptr(node root) { /* Find the right most node in BT or last node in DLL*/ while (root.right != null) root = root.right; /* Start from the rightmost node, traverse back using left pointers. While traversing, change right pointer of nodes*/ while (root != null && root.left != null) { node left = root.left; left.right = root; root = root.left; } /* The leftmost node is head of linked list, return it*/ return root; } /*The main function that converts BST to DLL and returns head of DLL*/ static node BTTtoDLL(node root) { prev = null; /* Set the previous pointer*/ fixPrevptr(root); /* Set the next pointer and return head of DLL*/ return fixNextptr(root); } /* Traverses the DLL from left tor right*/ static void printlist(node root) { while (root != null) { System.out.print(root.data + " "); root = root.right; } } /*Driver code*/ public static void main(String[] args) {/* Let us create the tree shown in above diagram*/ node root = new node(10); root.left = new node(12); root.right = new node(15); root.left.left = new node(25); root.left.right = new node(30); root.right.left = new node(36); System.out.println("Inorder Tree Traversal"); inorder(root); node head = BTTtoDLL(root); System.out.println("\nDLL Traversal"); printlist(head); } }
'''A simple inorder traversal based program to convert a Binary Tree to DLL''' '''A Binary Tree node''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None '''Standard Inorder traversal of tree''' def inorder(root): if root is not None: inorder(root.left) print "\t%d" %(root.data), inorder(root.right) '''Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node''' def fixPrevPtr(root): if root is not None: fixPrevPtr(root.left) root.left = fixPrevPtr.pre fixPrevPtr.pre = root fixPrevPtr(root.right) '''Changes right pointers to work as nexr pointers in converted DLL''' def fixNextPtr(root): prev = None ''' Find the right most node in BT or last node in DLL''' while(root and root.right != None): root = root.right ''' Start from the rightmost node, traverse back using left pointers While traversing, change right pointer of nodes''' while(root and root.left != None): prev = root root = root.left root.right = prev ''' The leftmost node is head of linked list, return it''' return root '''The main function that converts BST to DLL and returns head of DLL''' def BTToDLL(root): ''' Set the previous pointer''' fixPrevPtr(root) ''' Set the next pointer and return head of DLL''' return fixNextPtr(root) '''Traversses the DLL from left to right''' def printList(root): while(root != None): print "\t%d" %(root.data), root = root.right '''Driver program to test above function''' ''' Let us create the tree shown in above diagram''' root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) print "\n\t\t Inorder Tree Traversal\n" inorder(root) fixPrevPtr.pre = None head = BTToDLL(root) print "\n\n\t\tDLL Traversal\n" printList(head)
Boundary Traversal of binary tree
/*Java program to print boundary traversal of binary tree*/ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinaryTree { Node root; /* A simple function to print leaf nodes of a binary tree*/ void printLeaves(Node node) { if (node == null) return; printLeaves(node.left); /* Print it if it is a leaf node*/ if (node.left == null && node.right == null) System.out.print(node.data + " "); printLeaves(node.right); } /* A function to print all left boundary nodes, except a leaf node. Print the nodes in TOP DOWN manner*/ void printBoundaryLeft(Node node) { if (node == null) return; if (node.left != null) { /* to ensure top down order, print the node before calling itself for left subtree*/ System.out.print(node.data + " "); printBoundaryLeft(node.left); } else if (node.right != null) { System.out.print(node.data + " "); printBoundaryLeft(node.right); } /* do nothing if it is a leaf node, this way we avoid duplicates in output*/ } /* A function to print all right boundary nodes, except a leaf node Print the nodes in BOTTOM UP manner*/ void printBoundaryRight(Node node) { if (node == null) return; if (node.right != null) { /* to ensure bottom up order, first call for right subtree, then print this node*/ printBoundaryRight(node.right); System.out.print(node.data + " "); } else if (node.left != null) { printBoundaryRight(node.left); System.out.print(node.data + " "); } /* do nothing if it is a leaf node, this way we avoid duplicates in output*/ } /* A function to do boundary traversal of a given binary tree*/ void printBoundary(Node node) { if (node == null) return; System.out.print(node.data + " "); /* Print the left boundary in top-down manner.*/ printBoundaryLeft(node.left); /* Print all leaf nodes*/ printLeaves(node.left); printLeaves(node.right); /* Print the right boundary in bottom-up manner*/ printBoundaryRight(node.right); } /* Driver program to test above functions*/ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(8); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); tree.root.right = new Node(22); tree.root.right.right = new Node(25); tree.printBoundary(tree.root); } }
'''Python3 program for binary traversal of binary tree''' '''A binary tree node''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None '''A simple function to print leaf nodes of a Binary Tree''' def printLeaves(root): if(root): printLeaves(root.left) ''' Print it if it is a leaf node''' if root.left is None and root.right is None: print(root.data), printLeaves(root.right) '''A function to print all left boundary nodes, except a leaf node. Print the nodes in TOP DOWN manner''' def printBoundaryLeft(root): if(root): if (root.left): ''' to ensure top down order, print the node before calling itself for left subtree''' print(root.data) printBoundaryLeft(root.left) elif(root.right): print (root.data) printBoundaryLeft(root.right) ''' do nothing if it is a leaf node, this way we avoid duplicates in output''' '''A function to print all right boundary nodes, except a leaf node. Print the nodes in BOTTOM UP manner''' def printBoundaryRight(root): if(root): if (root.right): ''' to ensure bottom up order, first call for right subtree, then print this node''' printBoundaryRight(root.right) print(root.data) elif(root.left): printBoundaryRight(root.left) print(root.data) ''' do nothing if it is a leaf node, this way we avoid duplicates in output''' '''A function to do boundary traversal of a given binary tree''' def printBoundary(root): if (root): print(root.data) ''' Print the left boundary in top-down manner''' printBoundaryLeft(root.left) ''' Print all leaf nodes''' printLeaves(root.left) printLeaves(root.right) ''' Print the right boundary in bottom-up manner''' printBoundaryRight(root.right) '''Driver program to test above function''' root = Node(20) root.left = Node(8) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) root.right = Node(22) root.right.right = Node(25) printBoundary(root)
Mirror of matrix across diagonal
/*Efficient Java program to find mirror of matrix across diagonal.*/ import java.io.*; class GFG { static int MAX = 100; static void imageSwap(int mat[][], int n) { /* traverse a matrix and swap mat[i][j] with mat[j][i]*/ for (int i = 0; i < n; i++) for (int j = 0; j <= i; j++) mat[i][j] = mat[i][j] + mat[j][i] - (mat[j][i] = mat[i][j]); } /* Utility function to print a matrix*/ static void printMatrix(int mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print( mat[i][j] + " "); System.out.println(); } } /* driver program to test above function*/ public static void main (String[] args) { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int n = 4; imageSwap(mat, n); printMatrix(mat, n); } }
'''Efficient Python3 program to find mirror of matrix across diagonal.''' from builtins import range MAX = 100; def imageSwap(mat, n): ''' traverse a matrix and swap mat[i][j] with mat[j][i]''' for i in range(n): for j in range(i + 1): t = mat[i][j]; mat[i][j] = mat[j][i] mat[j][i] = t '''Utility function to pra matrix''' def printMatrix(mat, n): for i in range(n): for j in range(n): print(mat[i][j], end=" "); print(); '''Driver code''' if __name__ == '__main__': mat = [1, 2, 3, 4], \ [5, 6, 7, 8], \ [9, 10, 11, 12], \ [13, 14, 15, 16]; n = 4; imageSwap(mat, n); printMatrix(mat, n);
Extract Leaves of a Binary Tree in a Doubly Linked List
/*Java program to extract leaf nodes from binary tree using double linked list*/ /*A binay tree node*/ class Node { int data; Node left, right; Node(int item) { data = item; right = left = null; } } /*Binary Tree class */ public class BinaryTree { Node root; Node head; Node prev; /* The main function that links the list list to be traversed*/ public Node extractLeafList(Node root) { if (root == null) return null; if (root.left == null && root.right == null) { if (head == null) { head = root; prev = root; } else { prev.right = root; root.left = prev; prev = root; } return null; } root.left = extractLeafList(root.left); root.right = extractLeafList(root.right); return root; } /*Utility function for printing tree in In-Order.*/ void inorder(Node node) { if (node == null) return; inorder(node.left); System.out.print(node.data + " "); inorder(node.right); }/* Prints the DLL in both forward and reverse directions.*/ public void printDLL(Node head) { Node last = null; while (head != null) { System.out.print(head.data + " "); last = head; head = head.right; } } /* Driver program to test above functions*/ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); tree.root.left.left.right = new Node(8); tree.root.right.right.left = new Node(9); tree.root.right.right.right = new Node(10); System.out.println("Inorder traversal of given tree is : "); tree.inorder(tree.root); tree.extractLeafList(tree.root); System.out.println(""); System.out.println("Extracted double link list is : "); tree.printDLL(tree.head); System.out.println(""); System.out.println("Inorder traversal of modified tree is : "); tree.inorder(tree.root); } }
'''Python program to extract leaf nodes from binary tree using double linked list''' '''A binary tree node''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None '''Main function which extracts all leaves from given Binary Tree. The function returns new root of Binary Tree (Note that root may change if Binary Tree has only one node). The function also sets *head_ref as head of doubly linked list. left pointer of tree is used as prev in DLL and right pointer is used as next''' def extractLeafList(root): if root is None: return None if root.left is None and root.right is None: root.right = extractLeafList.head if extractLeafList.head is not None: extractLeafList.head.left = root extractLeafList.head = root return None root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) return root '''Utility function for printing tree in InOrder''' def printInorder(root): if root is not None: printInorder(root.left) print root.data, printInorder(root.right) '''Utility function for printing double linked list.''' def printList(head): while(head): if head.data is not None: print head.data, head = head.right '''Driver program to test above function''' extractLeafList.head = Node(None) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) root.left.left.left = Node(7) root.left.left.right = Node(8) root.right.right.left = Node(9) root.right.right.right = Node(10) print "Inorder traversal of given tree is:" printInorder(root) root = extractLeafList(root) print "\nExtract Double Linked List is:" printList(extractLeafList.head) print "\nInorder traversal of modified tree is:" printInorder(root)