├── .gitignore ├── AESencryption.java ├── Algorithms ├── Anagram.java ├── ArrayRotation.java ├── BalancedBrackets.java ├── BubbleSort.java ├── EqualSumPartition.java ├── Factorial.java ├── Gcd.java ├── Huffman.java ├── KadaneAlgorithm.java ├── Kernighan'sAlgorithm_22.java ├── LeapYear.java ├── LongestPallindromicSubsequenc.java ├── PascalTriangle.java ├── Pattern Search Algorithm( Naive algorithm) ├── PrimsAlgorithm.java ├── SeiveOfEratosthenes.java ├── SubsetsOfArray.java ├── SuffixArray.java ├── matrixProblems.java ├── number_swapping.java └── recursiveBinarysearch.java ├── Backtracking.java ├── Bipartite.java ├── Boggle.java ├── EulerTour.java ├── Graph ├── BFS │ └── BFS.java ├── BFSgraph.java ├── Cyclic_detection ├── DFS │ └── DFS.java ├── DFSgraph.java ├── Description ├── Graph.java ├── Single_source_Shortest Path └── k_cores.java ├── Interview Questions └── Questions.md ├── KMP_String_Matching.java ├── Minimum_spanning_tree.java ├── Queue └── Queue.java ├── README.md ├── Searching ├── BinarySearch.java ├── Exponential Search ├── JumpSearch.java ├── linearSearch.java └── recursiveBinarysearch.java ├── Sorting ├── Bubble.java ├── BubbleSort.java ├── CocktailSort.java ├── CountingSort.java ├── Frequency_Sort.java ├── Insertion.java ├── InsertionSort.java ├── IterativeMergeSort.java ├── RadixSort.java ├── Randomized_Quick_Sort.java ├── Selection.java ├── TopologicalSort.java ├── heap sort.java ├── merge sort.java ├── partition.java ├── quick sort.java ├── selectionSort.java └── shellSort.java ├── Stack └── Stack.java ├── Tree ├── AVLtree.java ├── BFSTree.java ├── Lowest Common Ancestor.java ├── Second_Minimum_In_Binary_Tree.java └── binarySearchTree │ ├── Bst.java │ └── TreeNode.java ├── binaryPalindrome.java ├── linkedList ├── CircularLinkedList.java ├── DoubleLinkedList ├── LinkedListasQueue.java ├── ListNode.java ├── SinglyLinkedList.java └── removeNthNodeFromEnd.java └── maximumsumsubbarray.java /.gitignore: -------------------------------------------------------------------------------- 1 | tmp 2 | dist 3 | dump.rdb 4 | .idea 5 | /.idea 6 | /.idea_modules 7 | /.classpath 8 | /.project 9 | /.settings 10 | /RUNNING_PID 11 | /.DS_Store 12 | 13 | /coverage -------------------------------------------------------------------------------- /AESencryption.java: -------------------------------------------------------------------------------- 1 | import java.io.UnsupportedEncodingException; 2 | import java.security.MessageDigest; 3 | import java.security.NoSuchAlgorithmException; 4 | import java.util.Arrays; 5 | import java.util.Base64; 6 | 7 | import javax.crypto.Cipher; 8 | import javax.crypto.spec.SecretKeySpec; 9 | 10 | public class AES { 11 | 12 | private static SecretKeySpec secretKey; 13 | private static byte[] key; 14 | 15 | public static void setKey(String myKey) 16 | { 17 | MessageDigest sha = null; 18 | try { 19 | key = myKey.getBytes("UTF-8"); 20 | sha = MessageDigest.getInstance("SHA-1"); 21 | key = sha.digest(key); 22 | key = Arrays.copyOf(key, 16); 23 | secretKey = new SecretKeySpec(key, "AES"); 24 | } 25 | catch (NoSuchAlgorithmException e) { 26 | e.printStackTrace(); 27 | } 28 | catch (UnsupportedEncodingException e) { 29 | e.printStackTrace(); 30 | } 31 | } 32 | 33 | public static String encrypt(String strToEncrypt, String secret) 34 | { 35 | try 36 | { 37 | setKey(secret); 38 | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 39 | cipher.init(Cipher.ENCRYPT_MODE, secretKey); 40 | return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); 41 | } 42 | catch (Exception e) 43 | { 44 | System.out.println("Error while encrypting: " + e.toString()); 45 | } 46 | return null; 47 | } 48 | 49 | public static String decrypt(String strToDecrypt, String secret) 50 | { 51 | try 52 | { 53 | setKey(secret); 54 | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); 55 | cipher.init(Cipher.DECRYPT_MODE, secretKey); 56 | return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); 57 | } 58 | catch (Exception e) 59 | { 60 | System.out.println("Error while decrypting: " + e.toString()); 61 | } 62 | return null; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Algorithms/Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class Anagram 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | String a = sc.next(); 11 | String b = sc.next(); 12 | boolean isAnagram = true; 13 | int al[] = new int[256]; 14 | for(char c:a.toCharArray()){ 15 | int index = (int)c; 16 | al[index]++; 17 | } 18 | for(char c:b.toCharArray()){ 19 | int index = (int)c; 20 | al[index]--; 21 | } 22 | for(int i=0;i<256;i++){ 23 | if(al[i]!=0){ 24 | isAnagram=false; 25 | break; 26 | } 27 | } 28 | if (isAnagram){ 29 | System.out.println("Anagram"); 30 | } 31 | else{ 32 | System.out.println("Not Anagram"); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Algorithms/ArrayRotation.java: -------------------------------------------------------------------------------- 1 | class ArrayRotation { 2 | public static void main(String[] args) { 3 | 4 | //Making scanner class for user input 5 | Scanner sc = new Scanner(System.in); 6 | 7 | //Taking user input for n that determine the number of times an array should be rotated. 8 | int n = sc.nextInt(); 9 | 10 | //Taking user input for d that is the size of the array. 11 | int d = sc.nextInt(); 12 | 13 | //Taking array by user of size d 14 | int [] arr = new int [d]; 15 | for(int i = 0;i < d; i++) { 16 | arr[i] = sc.nextInt(); 17 | } 18 | 19 | 20 | //Rotate the given array by n times 21 | for(int i = 0; i < n; i++){ 22 | int j, temp; 23 | //Stores the last element of array in temp 24 | temp = arr[arr.length-1]; 25 | 26 | for(j = arr.length-1; j > 0; j--){ 27 | //Shifting element of the array by one position 28 | arr[j] = arr[j-1]; 29 | } 30 | //storing temp in last of array 31 | arr[0] = temp; 32 | } 33 | 34 | System.out.println(); 35 | 36 | //Displays array after rotation 37 | for(int e: arr){ 38 | System.out.print(e); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/BalancedBrackets.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class BalancedBrackets{ 4 | 5 | public static String balancedBracket(String exp){ 6 | 7 | Stack s = new Stack(); 8 | int flag =0; 9 | 10 | for(int i=0; i arr[j]){ 14 | //swap elements 15 | temp = arr[j-1]; 16 | arr[j-1] = arr[j]; 17 | arr[j] = temp; 18 | } 19 | } 20 | 21 | } 22 | 23 | for(int i=0; i < arr.length; i++){ 24 | System.out.print(arr[i] + " "); 25 | } 26 | 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/EqualSumPartition.java: -------------------------------------------------------------------------------- 1 | /* PROBLEM STATEMENT : DIVIDE THE ARRAY INTO TWO PARTITION OF EQUAL SUM. 2 | //Key Points : 3 | 1 : THE PROBLEM IS SIMILAR TO THE SUBSET SUM PROBLEM WITH A LIITLE MODIFICATION 4 | ARRAY ARR(2s) 5 | / \ 6 | / \ 7 | / \ 8 | Partition 1 Partition 2 9 | Sum : s Sum : s 10 | 2 : WE CONCLUDE THAT THE SUM OF ARRAY SHOULD BE EVEN TO BE ABLE TO PARTIONED. 11 | 3 : IT IS SIMILAR TO SUBSET SUM PROBLEM AS WE NEED TO FIND A SUBSET OF SUM sum/2. 12 | */ 13 | public class EqualSumPartition { 14 | 15 | //***********************************************Recursive Approach********************************************************** 16 | private static boolean solveRecursively(int arr[], int i, int sum) { 17 | //If at some point we have (sum == 0) it means we have found a subset of given sum in the array.So we return true 18 | if (sum == 0) { 19 | return true; 20 | } 21 | //The i == 0 will get executed only when we have no more elements left in the array and we couldnt find the required sum. So we return false; 22 | if (i == 0) { 23 | return false; 24 | } 25 | //If the given element is valid i.e it is less than our required sum. We solve the problem recursively. We have two possible choice: 26 | //Include the element OR exclude it. 27 | if (arr[i - 1] <= sum) { 28 | return solveRecursively(arr, i - 1, sum - arr[i - 1]) | solveRecursively(arr, i - 1, sum); 29 | } else { 30 | return solveRecursively(arr, i - 1, sum); //As the element is invalid we do not include 31 | } 32 | } 33 | 34 | //***********************************************Dynamic Programming Approach********************************************************** 35 | private static boolean solveUsingDp(int arr[], int sum) { 36 | //The bottom up dynamic programming approach is similar to the subset sum problem. 37 | //The state dp[i][j] will be true if there a subset of first i items with sum value = j. 38 | boolean dp[][] = new boolean[arr.length + 1][sum + 1]; 39 | for (int i = 0; i < arr.length + 1; i++) { 40 | for (int j = 0; j < sum + 1; j++) { 41 | if (i == 0 || j == 0) //base case. Evident from our recurive approah 42 | { 43 | if (i == 0) // the case when there are no it 44 | { 45 | dp[i][j] = false; 46 | } 47 | if (j == 0) { 48 | dp[i][j] = true; //The case when sum = 0. We always have a empty subset {} with sum 0. 49 | } 50 | } else { 51 | if (arr[i - 1] <= j) //If the element is valid. We will find subset of sum j by including or excluding the ith item 52 | { 53 | dp[i][j] = dp[i - 1][j - arr[i - 1]] | dp[i - 1][j]; 54 | } else { 55 | dp[i][j] = dp[i - 1][j]; //We dont include the ith item as its invalid 56 | } 57 | } 58 | 59 | } 60 | } 61 | return dp[arr.length][sum]; 62 | } 63 | 64 | public static void main(String[] args) { 65 | 66 | int arr[] = {1, 2, 3, 6}, sum = 0; 67 | 68 | //We find the sum of each element of array. 69 | for (int i = 0; i < arr.length; i++) { 70 | sum += arr[i]; 71 | } 72 | //As explained at top : A partition with equal sum would only exist when the sum is an even number 73 | if (sum % 2 != 0) { 74 | System.out.println(0); 75 | } else { 76 | System.out.println(solveRecursively(arr, arr.length, sum / 2)); //Recursive Approach 77 | System.out.println(solveUsingDp(arr, sum / 2)); //Bottom up dynamic programming approach. 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Algorithms/Factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Factorial{ 3 | 4 | public static void main(String args[]) 5 | { 6 | Scanner s=new Scanner(System.in); 7 | int n=s.nextInt(); 8 | long f=1; 9 | 10 | for(int i=1;i<=n;i++) 11 | f=f*i; 12 | System.out.println(f); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/Gcd.java: -------------------------------------------------------------------------------- 1 | public class Gcd 2 | { 3 | // Recursive function to return gcd of a and b 4 | static int gcd(int a, int b) 5 | { 6 | 7 | if (a == 0) 8 | return b; 9 | if (b == 0) 10 | return a; 11 | 12 | // base case 13 | if (a == b) 14 | return a; 15 | 16 | // a is greater 17 | if (a > b) 18 | return gcd(a-b, b); 19 | return gcd(a, b-a); 20 | } 21 | 22 | // Driver method 23 | public static void main(String[] args) 24 | { 25 | 26 | System.out.println(gcd(40,5)); 27 | System.out.println(gcd(48,56)); 28 | 29 | 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Huffman.java: -------------------------------------------------------------------------------- 1 | // Huffman Coding Algorithm 2 | 3 | import java.util.*; //importing all the classes from the "utility" at a time 4 | 5 | class Node { 6 | int element; 7 | char c; 8 | Node left; 9 | Node right; 10 | } 11 | 12 | class ImplementComparator implements Comparator { 13 | public int compare(Node x, Node y) { 14 | return x.element - y.element; 15 | } 16 | } 17 | 18 | // class implementing the Huffman Algorithm 19 | public class Huffman { 20 | 21 | public static void outCode(Node r, String s) { 22 | if (r.left == null && r.right == null && Character.isLetter(r.c)) { 23 | 24 | System.out.println(r.c + " | " + s); 25 | 26 | return; 27 | } 28 | outCode(r.left, s + "0"); 29 | outCode(r.right, s + "1"); 30 | } 31 | 32 | public static void main(String[] args) { // main method: the execution of the program starts from here 33 | 34 | int n = 4; 35 | char[] cArray = { 'A', 'B', 'C', 'D' }; 36 | int[] cf = { 5, 1, 6, 3 }; 37 | 38 | PriorityQueue k = new PriorityQueue(n, new ImplementComparator()); 39 | 40 | for (int i = 0; i < n; i++) { 41 | Node t = new Node(); 42 | 43 | t.c = cArray[i]; 44 | t.element = cf[i]; 45 | 46 | t.left = null; 47 | t.right = null; 48 | 49 | k.add(t); 50 | } 51 | 52 | Node r = null; 53 | 54 | while (k.size() > 1) { 55 | 56 | Node x = k.peek(); 57 | k.poll(); 58 | 59 | Node y = k.peek(); 60 | k.poll(); 61 | 62 | Node f = new Node(); 63 | 64 | f.element = x.element + y.element; 65 | f.c = '-'; 66 | f.left = x; 67 | f.right = y; 68 | r = f; 69 | 70 | k.add(f); 71 | } 72 | System.out.println(" Char|Huffman code "); 73 | System.out.println("--------------------"); 74 | outCode(r, ""); 75 | } 76 | } -------------------------------------------------------------------------------- /Algorithms/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | //task of finding the largest possible sum of a contiguous subarray, within a given one-dimensional array A[1…n] of numbers. 2 | 3 | class KadaneAlgorithm { 4 | 5 | static void maxSubArraySum(int a[], int size) 6 | { 7 | int max_so_far = Integer.MIN_VALUE, 8 | max_ending_here = 0,start = 0, 9 | end = 0, s = 0; 10 | 11 | for (int i = 0; i < size; i++) 12 | { 13 | max_ending_here += a[i]; 14 | 15 | if (max_so_far < max_ending_here) 16 | { 17 | max_so_far = max_ending_here; 18 | start = s; 19 | end = i; 20 | } 21 | 22 | if (max_ending_here < 0) 23 | { 24 | max_ending_here = 0; 25 | s = i + 1; 26 | } 27 | } 28 | System.out.println("Maximum contiguous sum is " 29 | + max_so_far); 30 | System.out.println("Starting index " + start); 31 | System.out.println("Ending index " + end); 32 | } 33 | 34 | // Driver code 35 | public static void main(String[] args) 36 | { 37 | int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; 38 | int n = a.length; 39 | maxSubArraySum(a, n); 40 | } 41 | } -------------------------------------------------------------------------------- /Algorithms/Kernighan'sAlgorithm_22.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | 4 | class SetCountBits { 5 | /* Function to get no of set 6 | bits in binary representation 7 | of passed binary no. */ 8 | 9 | static int SetCountBits(int n) 10 | { 11 | int count = 0; 12 | while (n != 0) { 13 | n = n & (n-1); 14 | count++; 15 | } 16 | return count; 17 | } 18 | 19 | // main class 20 | public static void main(String args[]) 21 | { 22 | int i = 9; 23 | System.out.println(countSetBits(i)); 24 | } 25 | } 26 | 27 | // time complexity of this code is O(logn) 28 | // explanation for time complexity 29 | /* n = 9 30 | we can write 9 in binary form as (1001) 31 | count = 0 32 | 33 | Since 9 > 0, subtract by 1 and do bitwise & with (9-1) 34 | n = 9&8 (1001 & 1000) 35 | n = 8 36 | count = 1 37 | 38 | Since 8 > 0, subtract by 1 and do bitwise & with (8-1) 39 | n = 8&7 (1000 & 0111) 40 | n = 0 41 | count = 2 42 | 43 | Since n = 0, return count which is 2 now. 44 | */ 45 | -------------------------------------------------------------------------------- /Algorithms/LeapYear.java: -------------------------------------------------------------------------------- 1 | package Algorithms; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LeapYear { 6 | 7 | public static void main(String[] args){ 8 | 9 | Scanner scan = new Scanner(System.in); 10 | int year = scan.nextInt(); 11 | 12 | if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 13 | System.out.println("Leap"); 14 | } else { 15 | System.out.println("Regular"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/LongestPallindromicSubsequenc.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class LongestPallindromicSubsequenc{ 6 | 7 | int max(int a, int b) 8 | { 9 | return (a>b ? a:b); 10 | } 11 | 12 | int LCS(int n, char[] arr, char[] b){ 13 | 14 | int[][] dp=new int[n+1][n+1]; 15 | 16 | for(int i=0;i0){ 41 | String str=sc.next(); 42 | int n=str.length(); 43 | char[] arr=str.toCharArray(); 44 | char[] b=new char[n]; 45 | 46 | for(int i=0;i=1;k--){ 16 | System.out.print(" "); 17 | } 18 | for(int j=0;j<=i;j++){ 19 | System.out.print(m[j]+" "); 20 | } 21 | System.out.println(); 22 | p--; 23 | for(int j=i+1;j>0;j--){ 24 | m[j] = m[j] + m[j-1]; 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Algorithms/Pattern Search Algorithm( Naive algorithm): -------------------------------------------------------------------------------- 1 | //Naive Pattern Searching :- Slide the pattern over text one by one and check for a match. 2 | // If a match is found, then slides by 1 again to check for subsequent matches. 3 | 4 | //java program for Naive Pattern Searching 5 | 6 | 7 | public class NaiveSearch { 8 | 9 | public static void search(String txt, String pat) 10 | { 11 | int M = pat.length(); 12 | int N = txt.length(); 13 | 14 | for (int i = 0; i <= N - M; i++) { 15 | 16 | int j; 17 | for (j = 0; j < M; j++) 18 | if (txt.charAt(i + j) != pat.charAt(j)) 19 | break; 20 | 21 | if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] 22 | System.out.println("Pattern found at index " + i); 23 | } 24 | } 25 | 26 | public static void main(String[] args) 27 | { 28 | String txt = "AABAACAADAABAAABAA"; 29 | String pat = "AABA"; 30 | search(txt, pat); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Algorithms/PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | // A Java program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | // The program is for adjacency matrix representation of the graph 3 | 4 | import java.util.*; 5 | import java.lang.*; 6 | import java.io.*; 7 | 8 | class MST { 9 | // Number of vertices in the graph 10 | private static final int V = 5; 11 | 12 | // A utility function to find the vertex with minimum key 13 | // value, from the set of vertices not yet included in MST 14 | int minKey(int key[], Boolean mstSet[]) 15 | { 16 | // Initialize min value 17 | int min = Integer.MAX_VALUE, min_index = -1; 18 | 19 | for (int v = 0; v < V; v++) 20 | if (mstSet[v] == false && key[v] < min) { 21 | min = key[v]; 22 | min_index = v; 23 | } 24 | 25 | return min_index; 26 | } 27 | 28 | // A utility function to print the constructed MST stored in 29 | // parent[] 30 | void printMST(int parent[], int graph[][]) 31 | { 32 | System.out.println("Edge \tWeight"); 33 | for (int i = 1; i < V; i++) 34 | System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); 35 | } 36 | 37 | // Function to construct and print MST for a graph represented 38 | // using adjacency matrix representation 39 | void primMST(int graph[][]) 40 | { 41 | // Array to store constructed MST 42 | int parent[] = new int[V]; 43 | 44 | // Key values used to pick minimum weight edge in cut 45 | int key[] = new int[V]; 46 | 47 | // To represent set of vertices included in MST 48 | Boolean mstSet[] = new Boolean[V]; 49 | 50 | // Initialize all keys as INFINITE 51 | for (int i = 0; i < V; i++) { 52 | key[i] = Integer.MAX_VALUE; 53 | mstSet[i] = false; 54 | } 55 | 56 | // Always include first 1st vertex in MST. 57 | key[0] = 0; // Make key 0 so that this vertex is 58 | // picked as first vertex 59 | parent[0] = -1; // First node is always root of MST 60 | 61 | // The MST will have V vertices 62 | for (int count = 0; count < V - 1; count++) { 63 | // Pick thd minimum key vertex from the set of vertices 64 | // not yet included in MST 65 | int u = minKey(key, mstSet); 66 | 67 | // Add the picked vertex to the MST Set 68 | mstSet[u] = true; 69 | 70 | // Update key value and parent index of the adjacent 71 | // vertices of the picked vertex. Consider only those 72 | // vertices which are not yet included in MST 73 | for (int v = 0; v < V; v++) 74 | 75 | // graph[u][v] is non zero only for adjacent vertices of m 76 | // mstSet[v] is false for vertices not yet included in MST 77 | // Update the key only if graph[u][v] is smaller than key[v] 78 | if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { 79 | parent[v] = u; 80 | key[v] = graph[u][v]; 81 | } 82 | } 83 | 84 | // print the constructed MST 85 | printMST(parent, graph); 86 | } 87 | 88 | public static void main(String[] args) 89 | { 90 | /* Let us create the following graph 91 | 2 3 92 | (0)--(1)--(2) 93 | | / \ | 94 | 6| 8/ \5 |7 95 | | / \ | 96 | (3)-------(4) 97 | 9 */ 98 | MST t = new MST(); 99 | int graph[][] = new int[][] { { 0, 2, 0, 6, 0 }, 100 | { 2, 0, 3, 8, 5 }, 101 | { 0, 3, 0, 0, 7 }, 102 | { 6, 8, 0, 0, 9 }, 103 | { 0, 5, 7, 9, 0 } }; 104 | 105 | // Print the solution 106 | t.primMST(graph); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Algorithms/SeiveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | public class SeiveOfEratosthenes 6 | { 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner sc = new Scanner(System.in); 10 | int n = sc.nextInt(); 11 | boolean prime[] = new boolean[n+1]; 12 | for(int i=0;i0){ 19 | System.out.print(arr[j]+" "); 20 | } 21 | } 22 | System.out.println("}"); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Algorithms/SuffixArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | public class SuffixArray { 5 | private static final StringBuilder STRING_BUILDER = new StringBuilder(); 6 | private static final char DEFAULT_END_SEQ_CHAR = '$'; 7 | private final char endSeqChar; 8 | private String string; 9 | private ArrayList suffixArray; 10 | private ArrayList KMRarray; 11 | public SuffixArray(CharSequence sequence) { 12 | this(sequence, DEFAULT_END_SEQ_CHAR); 13 | } 14 | public SuffixArray(CharSequence sequence, char endChar) { 15 | endSeqChar = endChar; 16 | string = buildStringWithEndChar(sequence); 17 | } 18 | public ArrayList getSuffixArray() { 19 | if (suffixArray == null) 20 | KMRalgorithm(); 21 | return suffixArray; 22 | } 23 | public ArrayList getKMRarray() { 24 | if (KMRarray == null) 25 | KMRalgorithm(); 26 | return KMRarray; 27 | } 28 | public String getString(){ 29 | return string; 30 | } 31 | private void KMRalgorithm() { 32 | final int length = string.length(); 33 | ArrayList KMRinvertedList = new ArrayList(); 34 | ArrayList KMR = getBasicKMR(length); 35 | int radius = 1; 36 | while (radius < length) { 37 | KMRinvertedList = getKMRinvertedList(KMR, radius, length); 38 | KMR = getKMR(KMRinvertedList, length); 39 | radius *= 2; 40 | } 41 | KMRarray = new ArrayList(KMR.subList(0, length)); 42 | suffixArray = new ArrayList(); 43 | for (KMRsWithIndex kmr : KMRinvertedList) { 44 | suffixArray.add(new Integer(kmr.index)); 45 | } 46 | } 47 | private ArrayList getKMR(ArrayList KMRinvertedList, int length) { 48 | final ArrayList KMR = new ArrayList(length*2); 49 | for (int i=0; i<2*length; i++) 50 | KMR.add(new Integer(-1)); 51 | int counter = 0; 52 | for (int i=0; i0 && substringsAreEqual(KMRinvertedList, i)) 54 | counter++; 55 | KMR.set(KMRinvertedList.get(i).index, new Integer(counter)); 56 | } 57 | return KMR; 58 | } 59 | private boolean substringsAreEqual(ArrayList KMRinvertedList, int i) { 60 | return (KMRinvertedList.get(i-1).beginKMR.equals(KMRinvertedList.get(i).beginKMR) == false) || 61 | (KMRinvertedList.get(i-1).endKMR.equals(KMRinvertedList.get(i).endKMR) == false); 62 | } 63 | private ArrayList getKMRinvertedList(ArrayList KMR, int radius, int length) { 64 | final ArrayList KMRinvertedList = new ArrayList(); 65 | for (int i=0; i() { 69 | @Override 70 | public int compare(KMRsWithIndex A, KMRsWithIndex B) { 71 | if (A.beginKMR.equals(B.beginKMR) == false) 72 | return A.beginKMR.compareTo(B.beginKMR); 73 | if (A.endKMR.equals(B.endKMR) == false) 74 | return A.endKMR.compareTo(B.endKMR); 75 | return A.index.compareTo(B.index); 76 | } 77 | } 78 | ); 79 | return KMRinvertedList; 80 | } 81 | private ArrayList getBasicKMR(int length) { 82 | final ArrayList result = new ArrayList(length*2); 83 | final char[] characters = string.toCharArray(); 84 | for (int i=0; i-1;i--) 158 | { 159 | for(j=col-1;j>-1;j--) 160 | System.out.print(arr[j][i]+" "); 161 | System.out.println(); 162 | } 163 | } 164 | public static void vertD(double[][] arr,int row,int col) 165 | { 166 | int i,j; 167 | for(i=0;i-1;j--) 170 | System.out.print(arr[i][j]+" "); 171 | System.out.println(); 172 | } 173 | } 174 | public static void horiD(double[][] arr,int row,int col) 175 | { 176 | int i,j; 177 | for(i=row-1;i>-1;i--) 178 | { 179 | for(j=0;j= 0 && x < N && y >= 0 25 | && y < N && maze[x][y] == 1); 26 | } 27 | 28 | 29 | boolean solveMaze(int maze[][]) 30 | { 31 | int sol[][] = new int[N][N]; 32 | 33 | if (solveMazeUtil(maze, 0, 0, sol) == false) { 34 | System.out.print("Solution doesn't exist"); 35 | return false; 36 | } 37 | 38 | printSolution(sol); 39 | return true; 40 | } 41 | 42 | boolean solveMazeUtil(int maze[][], int x, int y, 43 | int sol[][]) 44 | { 45 | // if (x, y is goal) return true 46 | if (x == N - 1 && y == N - 1 47 | && maze[x][y] == 1) { 48 | sol[x][y] = 1; 49 | return true; 50 | } 51 | 52 | 53 | if (isSafe(maze, x, y) == true) { 54 | / 55 | sol[x][y] = 1; 56 | 57 | 58 | if (solveMazeUtil(maze, x + 1, y, sol)) 59 | return true; 60 | 61 | if (solveMazeUtil(maze, x, y + 1, sol)) 62 | return true; 63 | 64 | 65 | sol[x][y] = 0; 66 | return false; 67 | } 68 | 69 | return false; 70 | } 71 | 72 | public static void main(String args[]) 73 | { 74 | RatMaze rat = new RatMaze(); 75 | int maze[][] = { { 1, 0, 0, 0 }, 76 | { 1, 1, 0, 1 }, 77 | { 0, 1, 0, 0 }, 78 | { 1, 1, 1, 1 } }; 79 | 80 | N = maze.length; 81 | rat.solveMaze(maze); 82 | } 83 | } -------------------------------------------------------------------------------- /Bipartite.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Bipartite { 4 | 5 | public int[] color; 6 | public boolean[] marked; 7 | public LinkedListqueue = new LinkedList(); 8 | 9 | Bipartite(Graph g,int s) { 10 | 11 | color = new int[g.V()]; 12 | marked = new boolean[g.V()]; 13 | 14 | for ( int i = 0 ; i= 0 && col >= 0 && !visited[row][col]) 31 | findWordsUtil(boggle, visited, row, col, str); 32 | 33 | str = "" + str.charAt(str.length() - 1); 34 | visited[i][j] = false; 35 | } 36 | 37 | static void findWords(char[][] boggle) 38 | { 39 | boolean[][] visited = new boolean[M][N]; 40 | String str = ""; 41 | 42 | for (int i = 0; i < M; i++) 43 | for (int j = 0; j < N; j++) 44 | findWordsUtil(boggle, visited, i, j, str); 45 | } 46 | 47 | // Driver program to test above function 48 | public static void main(String[] args) 49 | { 50 | char[][] boggle = { { 'G', 'I', 'Z' }, 51 | { 'U', 'E', 'K' }, 52 | { 'Q', 'S', 'E' } }; 53 | 54 | System.out.println("Following words of dictionary are present"); 55 | findWords(boggle); 56 | } 57 | } -------------------------------------------------------------------------------- /EulerTour.java: -------------------------------------------------------------------------------- 1 | public class EulerTour { 2 | 3 | private int[] degree; 4 | 5 | EulerTour(Graph g, int s) { 6 | degree = new int[g.V()]; 7 | int count; 8 | 9 | for (int i = 0; i < g.V(); i++) { 10 | count = 0; 11 | for (int w : g.adj(i)) { 12 | count++; 13 | } 14 | degree[i] = count; 15 | } 16 | } 17 | 18 | int findingEulerPath(Graph g) { 19 | 20 | for (int j = 0; j < g.V(); j++) { 21 | if (degree[j] % 2 == 1) 22 | return 0; 23 | } 24 | 25 | return 1; 26 | } 27 | 28 | public static void main(String args[]) { 29 | Graph g = new Graph(4); 30 | g.addEdge(0, 1); 31 | g.addEdge(0, 3); 32 | g.addEdge(1, 3); 33 | g.addEdge(1, 2); 34 | 35 | EulerTour e = new EulerTour(g, 0); 36 | int res = e.findingEulerPath(g); 37 | 38 | if (res == 0) { 39 | System.out.println("No"); 40 | } else { 41 | System.out.println("Yes"); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Graph/BFS/BFS.java: -------------------------------------------------------------------------------- 1 | //Breadth First Search or BFS for a Graph 2 | //------------TIME COMPLEXITY = O(V+E), SPACE COMPLEXITY = O(V) ----------------- 3 | 4 | // Java program to print BFS traversal from a given source vertex. 5 | // BFS(int s) traverses vertices reachable from s. 6 | import java.io.*; 7 | import java.util.*; 8 | 9 | // This class represents a directed graph using adjacency list 10 | // representation 11 | class Graph 12 | { 13 | private int V; // No. of vertices 14 | private LinkedList adj[]; //Adjacency Lists 15 | 16 | // Constructor 17 | Graph(int v) 18 | { 19 | V = v; 20 | adj = new LinkedList[v]; 21 | for (int i=0; i queue = new LinkedList(); 40 | 41 | // Mark the current node as visited and enqueue it 42 | visited[s]=true; 43 | queue.add(s); 44 | 45 | while (queue.size() != 0) 46 | { 47 | // Dequeue a vertex from queue and print it 48 | s = queue.poll(); 49 | System.out.print(s+" "); 50 | 51 | // Get all adjacent vertices of the dequeued vertex s 52 | // If a adjacent has not been visited, then mark it 53 | // visited and enqueue it 54 | Iterator i = adj[s].listIterator(); 55 | while (i.hasNext()) 56 | { 57 | int n = i.next(); 58 | if (!visited[n]) 59 | { 60 | visited[n] = true; 61 | queue.add(n); 62 | } 63 | } 64 | } 65 | } 66 | 67 | // Driver method to 68 | public static void main(String args[]) 69 | { 70 | Graph g = new Graph(4); 71 | 72 | g.addEdge(0, 1); 73 | g.addEdge(0, 2); 74 | g.addEdge(1, 2); 75 | g.addEdge(2, 0); 76 | g.addEdge(2, 3); 77 | g.addEdge(3, 3); 78 | 79 | System.out.println("Following is Breadth First Traversal "+ 80 | "(starting from vertex 2)"); 81 | 82 | g.BFS(2); 83 | } 84 | } -------------------------------------------------------------------------------- /Graph/BFSgraph.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Stack; 3 | 4 | import sun.misc.Queue; 5 | 6 | public class BFSgraph { 7 | 8 | private boolean[] marked; 9 | private int[] edgeTo; 10 | private int s; 11 | public Queueque = new Queue<>(); 12 | 13 | DFSgraph(Graph g, int s) { 14 | marked = new boolean[g.V()]; 15 | edgeTo = new int[g.V()]; 16 | this.s = s; 17 | 18 | bfs(g, s); 19 | } 20 | 21 | public void bfs(Graph g, int v) { 22 | que.push(v); 23 | 24 | while(que.isEmpty()) 25 | { 26 | int vert = que.pop(); 27 | marked[vert] = true; 28 | for(int w : g.adj(vert)) 29 | { 30 | if(!marked[w]) { 31 | que.push(w); 32 | edgeTo[w] = v; 33 | } 34 | } 35 | } 36 | } 37 | 38 | public void printEle(int d) { 39 | int i = d; 40 | while(i != s) { 41 | System.out.println(i); 42 | i = edgeTo[i]; 43 | } 44 | } 45 | 46 | 47 | public static void main(String args[]) { 48 | Graph g = new Graph(7); 49 | g.addEdge(0, 1); 50 | g.addEdge(0, 2); 51 | g.addEdge(0, 5); 52 | g.addEdge(0, 6); 53 | g.addEdge(5, 3); 54 | g.addEdge(5, 4); 55 | g.addEdge(3, 4); 56 | g.addEdge(4, 6); 57 | 58 | BFSgraph d = new BFSgraph(g, 0); 59 | d.printEle(3); 60 | } 61 | } -------------------------------------------------------------------------------- /Graph/Cyclic_detection: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | /* Name of the class has to be "Main" only if the class is public. */ 6 | class Codechef 7 | { 8 | 9 | void add(List> l,int u,int v,boolean bi) 10 | { 11 | l.get(u).add(v); 12 | if(bi) 13 | { 14 | l.get(v).add(u); 15 | } 16 | } 17 | 18 | void dfs(ArrayList> l,int n,int s) 19 | { 20 | boolean visit[]=new boolean [n]; 21 | Stack st= new Stack<>(); 22 | Arrays.fill(visit,false); 23 | visit[s]=true; 24 | st.push(s); 25 | 26 | while(!st.empty()) 27 | { 28 | int nn=st.peek(); 29 | System.out.print(nn+" "); 30 | st.pop(); 31 | for(int i=0;i> l,int n,int s) 43 | { 44 | boolean visit[]=new boolean[n]; 45 | LinkedList que=new LinkedList(); 46 | for(int i=0;i i=l.Iterator(); 60 | for (int j = 0; j < l.get(s).size(); j++) { 61 | //while(i.hasNext()) 62 | //{ 63 | int nn=l.get(s).get(j); 64 | if(!visit[nn]){ 65 | visit[nn]=true; 66 | que.add(nn);} 67 | } 68 | 69 | } 70 | } 71 | 72 | 73 | boolean isCyclic(ArrayList> l,int n,int s) 74 | { 75 | boolean visit[]=new boolean[n]; 76 | int parent[]=new int [n]; 77 | LinkedList que=new LinkedList(); 78 | for(int i=0;i i=l.Iterator(); 92 | for (int j = 0; j < l.get(s).size(); j++) { 93 | //while(i.hasNext()) 94 | //{ 95 | int nn=l.get(s).get(j); 96 | if (visit[nn]==true && parent[s]!=nn) 97 | { 98 | return true; 99 | } 100 | else if(!visit[nn]){ 101 | visit[nn]=true; 102 | parent[nn]=s; 103 | que.add(nn);} 104 | } 105 | 106 | } 107 | return false; 108 | } 109 | 110 | void print(List> l) 111 | { 112 | 113 | for (int i = 0; i < l.size(); i++) { 114 | System.out.print(i+"-->"); 115 | // System.out.print("head"); 116 | for (int j = 0; j < l.get(i).size(); j++) { 117 | System.out.print(" "+l.get(i).get(j)); 118 | } 119 | System.out.println(); 120 | } 121 | } 122 | public static void main (String[] args) throws java.lang.Exception 123 | { 124 | // your code goes here 125 | Scanner sc=new Scanner(System.in); 126 | int v; 127 | v=sc.nextInt(); 128 | ArrayList> l=new ArrayList>(v); 129 | 130 | for(int i=0;i()); 133 | } 134 | Codechef ob=new Codechef(); 135 | ob.add(l,1,2,true); 136 | ob.add(l,1,3,true); 137 | ob.add(l,1,7,true); 138 | 139 | ob.add(l,2,5,true); 140 | ob.add(l,3,5,true); 141 | 142 | ob.add(l,7,6,true); 143 | ob.add(l,6,5,true); 144 | 145 | ob.print(l); 146 | System.out.println(" BFS "); 147 | ob.bfs(l,v,1); 148 | System.out.println(" DFS "); 149 | ob.dfs(l,v,1); 150 | 151 | System.out.println(ob.isCyclic(l,v,1)); 152 | 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /Graph/DFS/DFS.java: -------------------------------------------------------------------------------- 1 | //Depth First Search or DFS for a Graph 2 | //------------TIME COMPLEXITY = O(V+E), SPACE COMPLEXITY = O(V) ----------------- 3 | 4 | // Java program to print DFS traversal from a given given graph 5 | import java.io.*; 6 | import java.util.*; 7 | 8 | // This class represents a directed graph using adjacency list 9 | // representation 10 | class Graph 11 | { 12 | private int V; // No. of vertices 13 | 14 | // Array of lists for Adjacency List Representation 15 | private LinkedList adj[]; 16 | 17 | // Constructor 18 | Graph(int v) 19 | { 20 | V = v; 21 | adj = new LinkedList[v]; 22 | for (int i=0; i i = adj[v].listIterator(); 41 | while (i.hasNext()) 42 | { 43 | int n = i.next(); 44 | if (!visited[n]) 45 | DFSUtil(n, visited); 46 | } 47 | } 48 | 49 | // The function to do DFS traversal. It uses recursive DFSUtil() 50 | void DFS(int v) 51 | { 52 | // Mark all the vertices as not visited(set as 53 | // false by default in java) 54 | boolean visited[] = new boolean[V]; 55 | 56 | // Call the recursive helper function to print DFS traversal 57 | DFSUtil(v, visited); 58 | } 59 | 60 | public static void main(String args[]) 61 | { 62 | Graph g = new Graph(4); 63 | 64 | g.addEdge(0, 1); 65 | g.addEdge(0, 2); 66 | g.addEdge(1, 2); 67 | g.addEdge(2, 0); 68 | g.addEdge(2, 3); 69 | g.addEdge(3, 3); 70 | 71 | System.out.println("Following is Depth First Traversal "+ 72 | "(starting from vertex 2)"); 73 | 74 | g.DFS(2); 75 | } 76 | } -------------------------------------------------------------------------------- /Graph/DFSgraph.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Stack; 3 | 4 | public class DFSgraph { 5 | 6 | private boolean[] marked; 7 | private int[] edgeTo; 8 | private int s; 9 | public Stack stk = new Stack<>(); 10 | 11 | DFSgraph(Graph g, int s) { 12 | marked = new boolean[g.V()]; 13 | edgeTo = new int[g.V()]; 14 | this.s = s; 15 | 16 | dfs(g, s); 17 | } 18 | 19 | public void dfs(Graph g, int v) { 20 | marked[v] = true; 21 | for (int w : g.adj(v)) { 22 | if (!marked[w]) { 23 | dfs(g, w); 24 | edgeTo[w] = v; 25 | } 26 | } 27 | } 28 | 29 | public void printEle(int d) { 30 | stk.push(d); 31 | do { 32 | stk.push(edgeTo[d]); 33 | d = edgeTo[d]; 34 | } while (d != s); 35 | 36 | while (!stk.isEmpty()) { 37 | System.out.println(stk.pop()); 38 | } 39 | 40 | } 41 | 42 | public static void main(String args[]) { 43 | Graph g = new Graph(7); 44 | g.addEdge(0, 1); 45 | g.addEdge(0, 2); 46 | g.addEdge(0, 5); 47 | g.addEdge(0, 6); 48 | g.addEdge(5, 3); 49 | g.addEdge(5, 4); 50 | g.addEdge(3, 4); 51 | g.addEdge(4, 6); 52 | 53 | DFSgraph d = new DFSgraph(g, 0); 54 | d.printEle(3); 55 | } 56 | } -------------------------------------------------------------------------------- /Graph/Description: -------------------------------------------------------------------------------- 1 | 1) Find k-cores of an undirected graph 2 | 3 | Given a graph G and an integer K, K-cores of the graph are connected components that are left after all vertices of degree less than k have been removed. 4 | 5 | 2) Count all possible paths between two vertices 6 | 7 | Count the total number of ways or paths that exist between two vertices in a directed graph. 8 | These paths don’t contain a cycle, the simple enough reason is that a cycle contains an infinite number of paths and hence they create a problem 9 | -------------------------------------------------------------------------------- /Graph/Graph.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | 3 | public class Graph { 4 | private int V; 5 | private int E; 6 | private LinkedList[] adj; 7 | 8 | public Graph(int V) { 9 | this.V = V; 10 | this.E = 0; 11 | 12 | this.adj = new LinkedList[this.V]; 13 | for(int i = 0; i < V; i++) { 14 | this.adj[i] = new LinkedList<>(); 15 | } 16 | } 17 | 18 | public void addEdge(int s, int d) { 19 | this.adj[s].add(d); 20 | this.adj[d].add(s); 21 | this.E++; 22 | } 23 | 24 | public LinkedList adj(int v) { 25 | return this.adj[v]; 26 | } 27 | 28 | public int V() { 29 | return this.V; 30 | } 31 | 32 | public int E() { 33 | return this.E; 34 | } 35 | } -------------------------------------------------------------------------------- /Graph/Single_source_Shortest Path: -------------------------------------------------------------------------------- 1 | // BFS and DFS Algorithim 2 | /* package codechef; // don't place package name! */ 3 | 4 | import java.util.*; 5 | import java.lang.*; 6 | import java.io.*; 7 | 8 | /* Name of the class has to be "Main" only if the class is public. */ 9 | class Codechef 10 | { 11 | 12 | void add(List> l,int u,int v,boolean bi) 13 | { 14 | l.get(u).add(v); 15 | if(bi) 16 | { 17 | l.get(v).add(u); 18 | } 19 | } 20 | 21 | void sssp(ArrayList> l,int n,int s,int destination) 22 | { 23 | boolean visit[]=new boolean[n]; 24 | LinkedList que=new LinkedList(); 25 | int dist[]=new int [n]; 26 | for(int i=0;i i=l.Iterator(); 41 | for (int j = 0; j < l.get(s).size(); j++) { 42 | //while(i.hasNext()) 43 | //{ 44 | int nn=l.get(s).get(j); 45 | if(!visit[nn]){ 46 | visit[nn]=true; 47 | dist[nn]=dist[s]+1; 48 | que.add(nn);} 49 | } 50 | 51 | } 52 | System.out.println(dist[destination]); 53 | } 54 | 55 | 56 | void print(List> l) 57 | { 58 | 59 | for (int i = 0; i < l.size(); i++) { 60 | System.out.print(i+"-->"); 61 | // System.out.print("head"); 62 | for (int j = 0; j < l.get(i).size(); j++) { 63 | System.out.print(" "+l.get(i).get(j)); 64 | } 65 | System.out.println(); 66 | } 67 | } 68 | public static void main (String[] args) throws java.lang.Exception 69 | { 70 | // your code goes here 71 | Scanner sc=new Scanner(System.in); 72 | int v; 73 | v=sc.nextInt(); 74 | ArrayList> l=new ArrayList>(v); 75 | 76 | for(int i=0;i()); 79 | } 80 | Codechef ob=new Codechef(); 81 | ob.add(l,1,2,true); 82 | ob.add(l,1,3,true); 83 | ob.add(l,1,7,true); 84 | 85 | ob.add(l,2,5,true); 86 | ob.add(l,3,5,true); 87 | 88 | ob.add(l,7,6,true); 89 | ob.add(l,6,5,true); 90 | 91 | ob.print(l); 92 | System.out.println(" SSP "); 93 | ob.sssp(l,v,0,5); 94 | //System.out.println(" BFS "); 95 | // ob.bfs(l,v,1); 96 | //System.out.println(" DFS "); 97 | //ob.dfs(l,v,1); 98 | 99 | //System.out.println(ob.isCyclic(l,v,1)); 100 | 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Graph/k_cores.java: -------------------------------------------------------------------------------- 1 | // Java program to find K-Cores of a graph 2 | import java.util.*; 3 | 4 | class k_cores 5 | { 6 | 7 | // This class represents a undirected graph using adjacency 8 | // list representation 9 | static class Graph 10 | { 11 | int V; // No. of vertices 12 | 13 | // Pointer to an array containing adjacency lists 14 | Vector[] adj; 15 | 16 | @SuppressWarnings("unchecked") 17 | Graph(int V) 18 | { 19 | this.V = V; 20 | this.adj = new Vector[V]; 21 | 22 | for (int i = 0; i < V; i++) 23 | adj[i] = new Vector<>(); 24 | } 25 | 26 | // function to add an edge to graph 27 | void addEdge(int u, int v) 28 | { 29 | this.adj[u].add(v); 30 | this.adj[v].add(u); 31 | } 32 | 33 | // A recursive function to print DFS starting from v. 34 | // It returns true if degree of v after processing is less 35 | // than k else false 36 | // It also updates degree of adjacent if degree of v 37 | // is less than k. And if degree of a processed adjacent 38 | // becomes less than k, then it reduces of degree of v also, 39 | boolean DFSUtil(int v, boolean[] visited, int[] vDegree, int k) 40 | { 41 | 42 | // Mark the current node as visited and print it 43 | visited[v] = true; 44 | 45 | // Recur for all the vertices adjacent to this vertex 46 | for (int i : adj[v]) 47 | { 48 | 49 | // degree of v is less than k, then degree of adjacent 50 | // must be reduced 51 | if (vDegree[v] < k) 52 | vDegree[i]--; 53 | 54 | // If adjacent is not processed, process it 55 | if (!visited[i]) 56 | { 57 | 58 | // If degree of adjacent after processing becomes 59 | // less than k, then reduce degree of v also. 60 | if (DFSUtil(i, visited, vDegree, k)) 61 | vDegree[v]--; 62 | } 63 | } 64 | 65 | // Return true if degree of v is less than k 66 | return (vDegree[v] < k); 67 | } 68 | 69 | // Prints k cores of an undirected graph 70 | void printKCores(int k) 71 | { 72 | 73 | // INITIALIZATION 74 | // Mark all the vertices as not visited and not 75 | // processed. 76 | boolean[] visited = new boolean[V]; 77 | boolean[] processed = new boolean[V]; 78 | Arrays.fill(visited, false); 79 | Arrays.fill(processed, false); 80 | 81 | int mindeg = Integer.MAX_VALUE; 82 | int startvertex = 0; 83 | 84 | // Store degrees of all vertices 85 | int[] vDegree = new int[V]; 86 | for (int i = 0; i < V; i++) 87 | { 88 | vDegree[i] = adj[i].size(); 89 | 90 | if (vDegree[i] < mindeg) 91 | { 92 | mindeg = vDegree[i]; 93 | startvertex = i; 94 | } 95 | } 96 | DFSUtil(startvertex, visited, vDegree, k); 97 | 98 | // DFS traversal to update degrees of all 99 | // vertices. 100 | for (int i = 0; i < V; i++) 101 | if (!visited[i]) 102 | DFSUtil(i, visited, vDegree, k); 103 | 104 | // PRINTING K CORES 105 | System.out.println("K-Cores : "); 106 | for (int v = 0; v < V; v++) 107 | { 108 | 109 | // Only considering those vertices which have degree 110 | // >= K after BFS 111 | if (vDegree[v] >= k) 112 | { 113 | System.out.printf("\n[%d]", v); 114 | 115 | // Traverse adjacency list of v and print only 116 | // those adjacent which have vDegree >= k after 117 | // BFS. 118 | for (int i : adj[v]) 119 | if (vDegree[i] >= k) 120 | System.out.printf(" -> %d", i); 121 | } 122 | } 123 | } 124 | } 125 | 126 | // Driver Code 127 | public static void main(String[] args) 128 | { 129 | 130 | // Create a graph given in the above diagram 131 | int k = 3; 132 | Graph g1 = new Graph(9); 133 | g1.addEdge(0, 1); 134 | g1.addEdge(0, 2); 135 | g1.addEdge(1, 2); 136 | g1.addEdge(1, 5); 137 | g1.addEdge(2, 3); 138 | g1.addEdge(2, 4); 139 | g1.addEdge(2, 5); 140 | g1.addEdge(2, 6); 141 | g1.addEdge(3, 4); 142 | g1.addEdge(3, 6); 143 | g1.addEdge(3, 7); 144 | g1.addEdge(4, 6); 145 | g1.addEdge(4, 7); 146 | g1.addEdge(5, 6); 147 | g1.addEdge(5, 8); 148 | g1.addEdge(6, 7); 149 | g1.addEdge(6, 8); 150 | g1.printKCores(k); 151 | 152 | System.out.println(); 153 | 154 | Graph g2 = new Graph(13); 155 | g2.addEdge(0, 1); 156 | g2.addEdge(0, 2); 157 | g2.addEdge(0, 3); 158 | g2.addEdge(1, 4); 159 | g2.addEdge(1, 5); 160 | g2.addEdge(1, 6); 161 | g2.addEdge(2, 7); 162 | g2.addEdge(2, 8); 163 | g2.addEdge(2, 9); 164 | g2.addEdge(3, 10); 165 | g2.addEdge(3, 11); 166 | g2.addEdge(3, 12); 167 | g2.printKCores(k); 168 | } 169 | } 170 | 171 | -------------------------------------------------------------------------------- /Interview Questions/Questions.md: -------------------------------------------------------------------------------- 1 | # This file is all about the interview question asked in java. 2 | Keep on adding the interview questions. 3 | 4 | 5 | ### Q1 - Explain public static void main(String args[]) in Java. 6 | A1- 7 | > main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args). 8 | * public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class. 9 | * static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 10 | * void: It is the return type of the method. Void defines the method which will not returnss any value. 11 | * main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs. 12 | * String args[]: It is the parameter passed to the main method. 13 | 14 | ### Q2 - Is java Pass by value or Pass by reference? 15 | A2- 16 | > Java is strictly Pass by Value. This can be best explained by a swap() function in java. 17 | ```java 18 | public static void swap(int n1, int n2) 19 | { 20 | int temp=n1; 21 | n1=n2; 22 | n2=temp; 23 | } 24 | 25 | public static void main(String[] args) 26 | { 27 | int a = 10; 28 | int b = 20; 29 | swap(a,b); 30 | System.out.print(a,b); 31 | 32 | //output will be 10 20 33 | } 34 | ``` 35 | 36 | ### Q3- Can we declare the main method of our class as private? 37 | 38 | A3- 39 | > In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won't get any compilation error however, it will not get executed and will give a runtime error. 40 | 41 | ### Q4- Is there any way to skip Finally block of exception even if some exception occurs in the exception block? 42 | 43 | A4- 44 | > If an exception is raised in `Try` block, control passes to `catch` block if it exists otherwise to finally block. `Finally` block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block: 45 | 46 | ```System.exit(0);``` 47 | 48 | ### Q5- What is System class? 49 | 50 | A5- 51 | > System.class is a final class provided by java.lang package. It contains several useful class fields and methods. The purpose of System class is to provide access to system 52 | resources. 53 | 54 | ### Q6- What is the difference between Singleton class and Static class? 55 | 56 | A6- 57 | * A static class in Java has only static methods. It is a container of functions. It is created based on procedural programming design. Singleton class is a pattern in Object Oriented Design. 58 | * A Singletonclass has only one instance of an object in JVM. This pattern is 59 | implemented in such a way that there is always only one instance of 60 | that class present in JVM. 61 | 62 | ### Q7 - What are Wrapper classes in Java? 63 | A7- 64 | > Java has concept of Wrapper classes to allow primitive types to be 65 | accessed as objects. Primitive types like boolean, int, double, float 66 | etc. have corresponding Wrappers classes – Boolean, Integer, 67 | Double, Float etc. 68 | Many of these Wrapper classes are in java.lang package. 69 | Java 5.0 has launched the concept of Autoboxing and Unboxing in 70 | Java for Wrapper classes. 71 | ```java 72 | public class WrapperTest { 73 | public static void main(String args[]) { 74 | 75 | int count=50; //Converting int into Integer 76 | Integer i=Integer.valueOf(count);//converting int into Integer 77 | Integer j=a;//autoboxing, now compiler will write 78 | Integer.valueOf(count) internally 79 | System.out.println(count+" "+i+" "+j); 80 | } 81 | } 82 | 83 | 84 | ### Q7- You have 10 balls and a scale, find the heaviest ball in the least interations. 85 | 86 | A6- 87 | > Seperate the balls into two groups of 5 and place each group on the scale. Take balls from the heaviest side, put 1 on the side and weigh two on each side. If even, heaviest one is on the side. If the scale dips weigh those balls. Least amount of iterations is 3. 88 | > It's a logic puzzle to see how you willl troubleshoot through a problem. 89 | 90 | -------------------------------------------------------------------------------- /KMP_String_Matching.java: -------------------------------------------------------------------------------- 1 | public class KMP_String_Matching { 2 | public static void KMPSearch(String pat, String txt) 3 | { 4 | int M = pat.length(); 5 | int N = txt.length(); 6 | 7 | 8 | int lps[] = new int[M]; 9 | int j = 0; // index for pat[] 10 | 11 | 12 | computeLPSArray(pat, M, lps); 13 | 14 | int i = 0; // index for txt[] 15 | while (i < N) { 16 | if (pat.charAt(j) == txt.charAt(i)) { 17 | j++; 18 | i++; 19 | } 20 | if (j == M) { 21 | System.out.println("Found pattern " 22 | + "at index " + (i - j)); 23 | j = lps[j - 1]; 24 | } 25 | 26 | 27 | else if (i < N && pat.charAt(j) != txt.charAt(i)) { 28 | // Do not match lps[0..lps[j-1]] characters, 29 | // they will match anyway 30 | if (j != 0) 31 | j = lps[j - 1]; 32 | else 33 | i = i + 1; 34 | } 35 | } 36 | } 37 | 38 | void computeLPSArray(String pat, int M, int lps[]) 39 | { 40 | 41 | int len = 0; 42 | int i = 1; 43 | lps[0] = 0; // lps[0] is always 0 44 | 45 | 46 | while (i < M) { 47 | if (pat.charAt(i) == pat.charAt(len)) { 48 | len++; 49 | lps[i] = len; 50 | i++; 51 | } 52 | else // (pat[i] != pat[len]) 53 | { 54 | 55 | if (len != 0) { 56 | len = lps[len - 1]; 57 | 58 | 59 | } 60 | else // if (len == 0) 61 | { 62 | lps[i] = len; 63 | i++; 64 | } 65 | } 66 | } 67 | } 68 | 69 | 70 | public static void main(String args[]) 71 | { 72 | String txt = "ABABDABACDABABCABAB"; 73 | String pat = "ABABCABAB"; 74 | new KMP_String_Matching().KMPSearch(pat, txt); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Minimum_spanning_tree.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.LinkedList; 3 | import java.util.TreeSet; 4 | import java.util.Comparator; 5 | 6 | public class Minimum_spanning_tree { 7 | class node1 { 8 | 9 | // Stores destination vertex in adjacency list 10 | int dest; 11 | 12 | // Stores weight of a vertex in the adjacency list 13 | int weight; 14 | 15 | // Constructor 16 | node1(int a, int b) 17 | { 18 | dest = a; 19 | weight = b; 20 | } 21 | } 22 | static class Graph { 23 | 24 | // Number of vertices in the graph 25 | int V; 26 | 27 | // List of adjacent nodes of a given vertex 28 | LinkedList[] adj; 29 | 30 | // Constructor 31 | Graph(int e) 32 | { 33 | V = e; 34 | adj = new LinkedList[V]; 35 | for (int o = 0; o < V; o++) 36 | adj[o] = new LinkedList<>(); 37 | } 38 | } 39 | 40 | // class to represent a node in PriorityQueue 41 | // Stores a vertex and its corresponding 42 | // key value 43 | class node { 44 | int vertex; 45 | int key; 46 | } 47 | 48 | // Comparator class created for PriorityQueue 49 | // returns 1 if node0.key > node1.key 50 | // returns 0 if node0.key < node1.key and 51 | // returns -1 otherwise 52 | class comparator implements Comparator { 53 | 54 | @Override 55 | public int compare(node node0, node node1) 56 | { 57 | return node0.key - node1.key; 58 | } 59 | } 60 | 61 | // method to add an edge 62 | // between two vertices 63 | void addEdge(Graph graph, int src, int dest, int weight) 64 | { 65 | 66 | node1 node0 = new node1(dest, weight); 67 | node1 node = new node1(src, weight); 68 | graph.adj[src].addLast(node0); 69 | graph.adj[dest].addLast(node); 70 | } 71 | 72 | // method used to find the mst 73 | void prims_mst(Graph graph) 74 | { 75 | 76 | // Whether a vertex is in PriorityQueue or not 77 | Boolean[] mstset = new Boolean[graph.V]; 78 | node[] e = new node[graph.V]; 79 | 80 | // Stores the parents of a vertex 81 | int[] parent = new int[graph.V]; 82 | 83 | for (int o = 0; o < graph.V; o++) 84 | e[o] = new node(); 85 | 86 | for (int o = 0; o < graph.V; o++) { 87 | 88 | // Initialize to false 89 | mstset[o] = false; 90 | 91 | // Initialize key values to infinity 92 | e[o].key = Integer.MAX_VALUE; 93 | e[o].vertex = o; 94 | parent[o] = -1; 95 | } 96 | 97 | // Include the source vertex in mstset 98 | mstset[0] = true; 99 | 100 | // Set key value to 0 101 | // so that it is extracted first 102 | // out of PriorityQueue 103 | e[0].key = 0; 104 | 105 | // Use TreeSet instead of PriorityQueue as the remove function of the PQ is O(n) in java. 106 | TreeSet queue = new TreeSet(new comparator()); 107 | 108 | for (int o = 0; o < graph.V; o++) 109 | queue.add(e[o]); 110 | 111 | // Loops until the queue is not empty 112 | while (!queue.isEmpty()) { 113 | 114 | // Extracts a node with min key value 115 | node node0 = queue.pollFirst(); 116 | 117 | // Include that node into mstset 118 | mstset[node0.vertex] = true; 119 | 120 | // For all adjacent vertex of the extracted vertex V 121 | for (node1 iterator : graph.adj[node0.vertex]) { 122 | 123 | // If V is in queue 124 | if (mstset[iterator.dest] == false) { 125 | // If the key value of the adjacent vertex is 126 | // more than the extracted key 127 | // update the key value of adjacent vertex 128 | // to update first remove and add the updated vertex 129 | if (e[iterator.dest].key > iterator.weight) { 130 | queue.remove(e[iterator.dest]); 131 | e[iterator.dest].key = iterator.weight; 132 | queue.add(e[iterator.dest]); 133 | parent[iterator.dest] = node0.vertex; 134 | } 135 | } 136 | } 137 | } 138 | 139 | // Prints the vertex pair of mst 140 | for (int o = 1; o < graph.V; o++) 141 | System.out.println(parent[o] + " " 142 | + "-" 143 | + " " + o); 144 | } 145 | 146 | public static void main(String[] args) 147 | { 148 | int V = 9; 149 | 150 | Graph graph = new Graph(V); 151 | 152 | prims e = new prims(); 153 | 154 | e.addEdge(graph, 0, 1, 4); 155 | e.addEdge(graph, 0, 7, 8); 156 | e.addEdge(graph, 1, 2, 8); 157 | e.addEdge(graph, 1, 7, 11); 158 | e.addEdge(graph, 2, 3, 7); 159 | e.addEdge(graph, 2, 8, 2); 160 | e.addEdge(graph, 2, 5, 4); 161 | e.addEdge(graph, 3, 4, 9); 162 | e.addEdge(graph, 3, 5, 14); 163 | e.addEdge(graph, 4, 5, 10); 164 | e.addEdge(graph, 5, 6, 2); 165 | e.addEdge(graph, 6, 7, 1); 166 | e.addEdge(graph, 6, 8, 6); 167 | e.addEdge(graph, 7, 8, 7); 168 | 169 | // Method invoked 170 | e.prims_mst(graph); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /Queue/Queue.java: -------------------------------------------------------------------------------- 1 | class Queue 2 | { 3 | int front, rear, size; 4 | int capacity; 5 | int array[]; 6 | 7 | public Queue(int capacity) { 8 | this.capacity = capacity; 9 | front = this.size = 0; 10 | rear = capacity - 1; 11 | array = new int[this.capacity]; 12 | 13 | } 14 | 15 | 16 | boolean isFull(Queue queue) 17 | { return (queue.size == queue.capacity); 18 | } 19 | 20 | 21 | boolean isEmpty(Queue queue) 22 | { return (queue.size == 0); } 23 | 24 | 25 | void enqueue( int item) 26 | { 27 | if (isFull(this)) 28 | System.out.println("Queue capacity reached"); 29 | this.rear = (this.rear + 1)%this.capacity; 30 | this.array[this.rear] = item; 31 | this.size = this.size + 1; 32 | } 33 | 34 | 35 | void dequeue() 36 | { 37 | if (isEmpty(this)) 38 | System.out.println("The queue is empty"); 39 | this.front = (this.front + 1)%this.capacity; 40 | this.size = this.size - 1; 41 | } 42 | 43 | 44 | int front() 45 | { 46 | if (isEmpty(this)) 47 | return Integer.MIN_VALUE; 48 | 49 | return this.array[this.front]; 50 | } 51 | 52 | 53 | int rear() 54 | { 55 | if (isEmpty(this)) 56 | return Integer.MIN_VALUE; 57 | 58 | return this.array[this.rear]; 59 | } 60 | 61 | public static void main(String[] args) 62 | { 63 | Queue q=new Queue(10); 64 | q.enqueue(5); 65 | q.enqueue(7); 66 | q.enqueue(4); 67 | q.enqueue(3); 68 | System.out.println("front is "+q.front()); 69 | q.dequeue(); 70 | q.dequeue(); 71 | q.dequeue(); 72 | q.dequeue(); 73 | q.dequeue(); 74 | } 75 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Algorithms ☕ 2 | 3 | ![](https://img.shields.io/badge/Java-Algos-red) ![](https://img.shields.io/badge/Hacktoberfest-2020-brightgreen) ![](https://img.shields.io/github/issues/anku580/Java-Algorithms) ![](https://img.shields.io/github/issues-pr-closed/anku580/Java-Algorithms)![](https://img.shields.io/github/stars/anku580/Java-Algorithms?style=social) ![](https://img.shields.io/github/forks/anku580/Java-Algorithms?style=social) 4 | 5 | ### 👋 Hi coders !!! 6 | 7 | This Hactoberfest, we have brought you this repo where you can contribute your Java Algorithms. So, contribute here and get a chance to win Hacktoberfest Tees. 👕 8 |
9 | 10 | ### Algos added till now.. 11 | 12 | * [Binary Search Tree](/binarySearchTree/TreeNode.java) 13 | * [Linked List](/linkedList/ListNode.java) 14 | * [BFS Graph](/BFSgraph.java) 15 | * [Bipartite](/Bipartite.java) 16 | * [Bubble Sort](/BubbleSort.java) 17 | * [DFS Graph](/DFSgraph.java) 18 | * [Euler Tour](/EulerTour.java) 19 | * [Factorial](/Factorial.java) 20 | * [Greates Common Divisor](Gcd.java) 21 | * [Graph](Graph.java) 22 | * [Insertion Sort](InsertionSort.java) 23 | * [Prims Algo](/PrimsAlgorithm.java) 24 | * [Randomised Quick Sort](/Randomized_Quick_Sort.java) 25 | * [Selection Sort](selectionSort.java) 26 | 27 | 28 | ### Happy Coding 👩‍💻👨‍💻 -------------------------------------------------------------------------------- /Searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package Searching; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | public class BinarySearch { 5 | static Scanner sc=new Scanner(System.in); 6 | public static void main(String[] args) { 7 | // TODO Auto-generated method stub 8 | int n=sc.nextInt();//size of array 9 | int array[]=new int[n];//array declaration 10 | for(int i=0;iui)break; 23 | else if(search>array[curin]) 24 | li=curin+1; 25 | else 26 | ui=curin-1; 27 | } 28 | if(found)System.out.println("Yes"); 29 | else 30 | System.out.println("No"); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Searching/Exponential Search: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class EXP 4 | { 5 | 6 | static int exponentialSearch(int arr[], 7 | int n, int x) 8 | { 9 | 10 | if (arr[0] == x) 11 | return 0; 12 | 13 | 14 | int i = 1; 15 | while (i < n && arr[i] <= x) 16 | i = i*2; 17 | 18 | 19 | return Arrays.binarySearch(arr, i/2, 20 | Math.min(i, n), x); 21 | } 22 | 23 | 24 | public static void main(String args[]) 25 | { 26 | int arr[] = {2, 3, 4, 10, 40}; 27 | int x = 10; 28 | int result = exponentialSearch(arr, arr.length, x); 29 | 30 | System.out.println((result < 0) ? 31 | "Element is not present in array" : 32 | "Element is present at index " + 33 | result); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Searching/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package searching; 2 | import java.util.*; 3 | public class JumpSearch 4 | { 5 | public static void main( String args[]) 6 | { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Enter the size of the array"); 9 | int n = sc.nextInt(); 10 | int[] a = new int[n]; 11 | System.out.println("Enter the elements of the sorted array"); 12 | for(int i=0; iui)return -1; 10 | if(array[curindex]==key)return key; 11 | else if(key>array[curindex])return search(array,key,curindex+1,ui); 12 | else 13 | return search(array,key,li,curindex-1); 14 | } 15 | public static void main(String[] args) { 16 | // TODO Auto-generated method stub 17 | int n=sc.nextInt(); 18 | int array[]=new int[n]; 19 | for(int i=0;i1;i--) { 8 | for(int j=0;jarray[j+1]) { 10 | int temp=array[j]; 11 | array[j]=array[j+1]; 12 | array[j+1]=temp; 13 | } 14 | } 15 | } 16 | } 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | int n=sc.nextInt(); 20 | int[] array=new int[n]; 21 | for(int i=0;i arr[j+1]) 13 | { 14 | // swap temp and arr[i] 15 | int temp = arr[j]; 16 | arr[j] = arr[j+1]; 17 | arr[j+1] = temp; 18 | swapped=true; 19 | } 20 | if(!swapped){ 21 | break; 22 | } 23 | } 24 | } 25 | 26 | /* Prints the array */ 27 | void printArray(int arr[]) 28 | { 29 | int n = arr.length; 30 | for (int i=0; i inputArrays[i + 1]) { 16 | int temp = inputArrays[i]; 17 | inputArrays[i] = inputArrays[i + 1]; 18 | inputArrays[i + 1] = temp; 19 | swapped = Boolean.TRUE; 20 | } 21 | } 22 | 23 | if (!swapped) { 24 | break; 25 | } 26 | 27 | swapped = Boolean.FALSE; 28 | end--; 29 | 30 | for (int i = end - 1; i >= start; i--) { 31 | if (inputArrays[i] > inputArrays[i + 1]) { 32 | int temp = inputArrays[i]; 33 | inputArrays[i] = inputArrays[i + 1]; 34 | inputArrays[i + 1] = temp; 35 | swapped = Boolean.TRUE; 36 | } 37 | } 38 | 39 | start++; 40 | } 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Sorting/CountingSort.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Arrays; 4 | 5 | class CountSort{ 6 | public static void main(String[] args) throws Exception { 7 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | System.out.println("Enter the size of Array to be sorted"); 9 | int n = Integer.parseInt(br.readLine()); 10 | System.out.println("Enter the Array to be sorted"); 11 | int[] arr = new int[n]; 12 | String[] integerStrings = br.readLine().split(" "); 13 | for (int i = 0; i < arr.length; i++) { 14 | arr[i] = Integer.parseInt(integerStrings[i]); 15 | } 16 | int k = 60; 17 | 18 | countingSort(arr, k); 19 | 20 | System.out.println("Sorted Array :- "); 21 | System.out.println(Arrays.toString(arr)); 22 | 23 | } 24 | 25 | static void countingSort(int[] input, int k) { 26 | // create buckets 27 | int count[] = new int[k + 1]; 28 | 29 | for (int i : input) { 30 | count[i]++; 31 | } 32 | 33 | int ndx = 0; 34 | for (int i = 0; i < count.length; i++) { 35 | while (0 < count[i]) { 36 | input[ndx++] = i; 37 | count[i]--; 38 | } 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Sorting/Frequency_Sort.java: -------------------------------------------------------------------------------- 1 | /* 2 | This class implements sorting Strings based on their frequency. 3 | The frequency is stored in the HashMap> 4 | Where the ArrayList contains three items - Scores, Id, Correction 5 | */ 6 | import java.io.*; 7 | import java.util.HashMap; 8 | import java.util.Comparator; 9 | import java.util.ArrayList; 10 | public class PlaylistSort implements Comparator{ 11 | int SCORES_INDEX = 0; 12 | int TIE_INDEX = 2; 13 | private HashMap> frequency = new HashMap>(); 14 | public PlaylistSort(HashMap> arr) { 15 | frequency = arr; 16 | } 17 | public int compare(String s1, String s2) { 18 | if(frequency.get(s1).get(SCORES_INDEX) < frequency.get(s2).get(SCORES_INDEX)) { 19 | return 1; 20 | } 21 | else if(frequency.get(s1).get(SCORES_INDEX) > frequency.get(s2).get(SCORES_INDEX)) { 22 | return -1; 23 | } 24 | else { 25 | //If two playlists have the same score, we need to break the tie..so we compare the tie scores.. 26 | if((frequency.get(s1).get(TIE_INDEX)) < (frequency.get(s2).get(TIE_INDEX))) { 27 | return 1; 28 | } 29 | else if((frequency.get(s1).get(TIE_INDEX)) > (frequency.get(s2).get(TIE_INDEX))) { 30 | return -1; 31 | } 32 | else { 33 | return 0; 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Sorting/Insertion.java: -------------------------------------------------------------------------------- 1 | package Sorting; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Insertion { 6 | static Scanner sc=new Scanner(System.in); 7 | public static void sort(int [] array) { 8 | int n=array.length,j; 9 | for(int i=1;i=0 && temp 0 && temp < arr[j-1]) 16 | { 17 | arr[j] = arr[j-1]; 18 | j = j-1; 19 | } 20 | arr[j] = temp; 21 | } 22 | } 23 | 24 | public static void main(String[] args) 25 | { 26 | Scanner scan = new Scanner( System.in ); 27 | System.out.println("Insertion Sort Test\n"); 28 | int n, i; 29 | 30 | System.out.println("Enter number of integer elements"); 31 | n = scan.nextInt(); 32 | 33 | int arr[] = new int[ n ]; 34 | 35 | System.out.println("\nEnter "+ n +" integer elements"); 36 | for (i = 0; i < n; i++) 37 | arr[i] = scan.nextInt(); 38 | 39 | sort(arr); 40 | 41 | System.out.println("\nElements after sorting "); 42 | for (i = 0; i < n; i++) 43 | System.out.print(arr[i]+" "); 44 | System.out.println(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Sorting/IterativeMergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class IterativeMergeSort { 4 | 5 | // Utility function to find minimum of two integers 6 | public static int min(int x, int y) { 7 | return (x < y) ? x : y; 8 | } 9 | 10 | /** 11 | * Java method to merge two sub-arrays of arr[] which are arr[l..m] and 12 | * arr[m+1..r] 13 | * 14 | * @param int[] arr : array to be sorted 15 | * @param int l : starting index 16 | * @param int m : mid index 17 | * @param int r : end index 18 | */ 19 | public static void merge(int[] arr, int l, int m, int r) { 20 | int n1 = m - l + 1; 21 | int n2 = r - m; 22 | int[] L = new int[n1]; 23 | int[] R = new int[n2]; 24 | for (int i = 0; i < n1; i++) { 25 | L[i] = arr[l + i]; 26 | } 27 | for (int j = 0; j < n2; j++) { 28 | R[j] = arr[m + 1 + j]; 29 | } 30 | int i = 0, j = 0; 31 | int k = l; 32 | while (i < n1 && j < n2) { 33 | if (L[i] <= R[j]) { 34 | arr[k] = L[i]; 35 | i++; 36 | } else { 37 | arr[k] = R[j]; 38 | j++; 39 | } 40 | k++; 41 | } 42 | while (i < n1) { 43 | arr[k] = L[i]; 44 | i++; 45 | k++; 46 | } 47 | while (j < n2) { 48 | arr[k] = R[j]; 49 | j++; 50 | k++; 51 | } 52 | } 53 | 54 | /** 55 | * Java method to sort array using mergeSort 56 | * 57 | * @param int[] arr : array to be sorted 58 | * @param int n : length of array 59 | */ 60 | public static void mergeSort(int[] arr, int n) { 61 | int curr_size; 62 | int left_start; 63 | for (curr_size = 1; curr_size < (n - 1); curr_size = 2 * curr_size) { 64 | for (left_start = 0; left_start < (n - 1); left_start += 2 * curr_size) { 65 | int mid = min(left_start + curr_size - 1, n - 1); 66 | int right_end = min(left_start + 2 * curr_size - 1, n - 1); 67 | merge(arr, left_start, mid, right_end); 68 | } 69 | } 70 | } 71 | 72 | public static void main(String[] args) { 73 | int[] arr = { 44, 65, 87, 23, 541, 654, 32 }; 74 | System.out.println("Original array : " + Arrays.toString(arr)); 75 | mergeSort(arr, arr.length); 76 | System.out.println("Sorted array : " + Arrays.toString(arr)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Sorting/RadixSort.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.*; 4 | 5 | class Radix { 6 | 7 | static int getMax(int arr[], int n) 8 | { 9 | int mx = arr[0]; 10 | for (int i = 1; i < n; i++) 11 | if (arr[i] > mx) 12 | mx = arr[i]; 13 | return mx; 14 | } 15 | 16 | static void countSort(int arr[], int n, int exp) 17 | { 18 | int output[] = new int[n]; // output array 19 | int i; 20 | int count[] = new int[10]; 21 | Arrays.fill(count, 0); 22 | 23 | for (i = 0; i < n; i++) 24 | count[(arr[i] / exp) % 10]++; 25 | 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i - 1]; 28 | 29 | for (i = n - 1; i >= 0; i--) { 30 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 31 | count[(arr[i] / exp) % 10]--; 32 | } 33 | 34 | for (i = 0; i < n; i++) 35 | arr[i] = output[i]; 36 | } 37 | 38 | static void radixSort(int arr[], int n) { 39 | int m = getMax(arr, n); 40 | 41 | for (int exp = 1; m / exp > 0; exp *= 10) 42 | countSort(arr, n, exp); 43 | } 44 | 45 | 46 | public static void main(String[] args) throws Exception { 47 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 48 | int n = Integer.parseInt(br.readLine()); 49 | int arr[] = new int[n]; 50 | String[] integerStrings = br.readLine().split(" "); 51 | for (int i = 0; i < arr.length; i++) { 52 | arr[i] = Integer.parseInt(integerStrings[i]); 53 | } 54 | radixSort(arr, n); 55 | for (int i = 0; i < n; i++) 56 | System.out.print(arr[i] + " "); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Sorting/Randomized_Quick_Sort.java: -------------------------------------------------------------------------------- 1 | /* 2 | This class is used to implement the Randomized quick sort algorithm in Java. 3 | Written by - Amrit Raj 4 | */ 5 | class QuickSort{ 6 | /* 7 | This function is used to partation the sort space.. 8 | Arguments - int array of elements to sort, int begining index, int ending 9 | Index.. 10 | Return - Nothing.. 11 | */ 12 | public void sort(int arr[], int beg, int end){ 13 | //The end case to leave out of recurssion.. 14 | if(beg >= end){ 15 | return; 16 | } 17 | 18 | //Partation index ind.. 19 | int ind = partation(arr, beg, end); 20 | //Calling the left sub - sort space.. 21 | sort(arr, beg, ind-1); 22 | //Calling the right sub - sort space.. 23 | sort(arr, ind+1, end); 24 | } 25 | /* 26 | This method is used to find the partation index based on the assumption 27 | that last element is the pivot.. 28 | Arguments - int array for which the index is to be found, int beginning of 29 | the array, int end - Last index of the passed array.. 30 | Returns - an int denoting the point of paration.. 31 | */ 32 | public int partation(int arr[], int beg, int end){ 33 | //If the array has only one element.. 34 | if(beg == end){ 35 | return end; 36 | } 37 | else{ 38 | //Finding the random index in range.. 39 | int tempInd = rand(beg, end); 40 | //Swapping the element at the random index with the last element.. 41 | swap(arr, tempInd, end); 42 | //Making the new last element as the pivot.. 43 | int pivot = arr[end]; 44 | //Current index to swap values.. 45 | int ind = beg - 1; 46 | //Finding all the elements smaller than the pivot.. 47 | for(int i = beg; i < end; i++){ 48 | if(arr[i] < pivot){ 49 | //Swapping the elements smaller than pivot to left of 50 | //pivot.. 51 | ind++; 52 | swap(arr, ind, i); 53 | } 54 | } 55 | //Swapping the pivot to it's correct place 56 | ind++; 57 | 58 | swap(arr, ind, end); 59 | return ind; 60 | } 61 | } 62 | /* 63 | This method generates a random number in a given range 64 | Arguments - int beg, int end 65 | Returns - a random int in the range of end - beg + 1 66 | */ 67 | public int rand(int beg, int end){ 68 | int range = end - beg + 1; 69 | int show = (int)(Math.random() * range) + beg; 70 | return show; 71 | } 72 | /* 73 | This method is used as a utility function to swap two numbers in an array.. 74 | Arguments - int array of elements, int index1, int index2 75 | Returns - Nothing, inplace swapping.. 76 | */ 77 | public void swap(int arr[], int a, int b){ 78 | int temp = arr[a]; 79 | arr[a] = arr[b]; 80 | arr[b] = temp; 81 | } 82 | } 83 | /* 84 | This class is used to check the QuickSort class. 85 | */ 86 | class Demo{ 87 | public static void main(String args[]){ 88 | //A dummy array to be sorted.. 89 | int sampleArray[] = {10, 7, 8, 9, 5, 1, 5}; 90 | QuickSort sorter = new QuickSort(); 91 | //Printing the original array.. 92 | System.out.println("Array before sorting:- "); 93 | printer(sampleArray, sampleArray.length); 94 | //Sorting the array using quicksort.. 95 | sorter.sort(sampleArray, 0, sampleArray.length-1); 96 | 97 | //Printing the sorted array.. 98 | System.out.println("Array after sorting:- "); 99 | printer(sampleArray, sampleArray.length); 100 | } 101 | /* 102 | A utility function to print the array linearly.. 103 | Arguments - An array to be printed, and an int with length of array 104 | Return - Nothing.. 105 | */ 106 | public static void printer(int arr[], int n){ 107 | StringBuffer br = new StringBuffer(); 108 | for(int i = 0; i < n; i++){ 109 | br.append(arr[i]+" "); 110 | } 111 | System.out.println(br); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Sorting/Selection.java: -------------------------------------------------------------------------------- 1 | package Sorting; 2 | import java.util.Scanner; 3 | public class Selection { 4 | static Scanner sc=new Scanner(System.in); 5 | public static void sort(int array[]) { 6 | int n=array.length;int min; 7 | for(int i=0;i 0) { 12 | ArrayList> list = new ArrayList<>(); 13 | String st[] = read.readLine().trim().split("\\s+"); 14 | int edg = Integer.parseInt(st[0]); 15 | int nov = Integer.parseInt(st[1]); 16 | 17 | for (int i = 0; i < nov + 1; i++) 18 | list.add(i, new ArrayList()); 19 | 20 | String s[] = read.readLine().trim().split("\\s+"); 21 | int p = 0; 22 | for (int i = 1; i <= edg; i++) { 23 | int u = Integer.parseInt(s[p++]); 24 | int v = Integer.parseInt(s[p++]); 25 | list.get(u).add(v); 26 | } 27 | 28 | int[] res = new TopologicalSortUtil().topoSort(list, nov); 29 | 30 | if (check(list, nov, res) == true) 31 | System.out.println("1"); 32 | else 33 | System.out.println("0"); 34 | } 35 | } 36 | static boolean check(ArrayList> list, int V, int[] res) { 37 | int[] map = new int[V]; 38 | for (int i = 0; i < V; i++) { 39 | map[res[i]] = i; 40 | } 41 | for (int i = 0; i < V; i++) { 42 | for (int v : list.get(i)) { 43 | if (map[i] > map[v]) return false; 44 | } 45 | } 46 | return true; 47 | } 48 | } 49 | 50 | class TopologicalSortUtil { 51 | static int[] topoSort(ArrayList> adj, int N) { 52 | int[] indegree = new int[N]; 53 | for(int i=0; i temp = adj.get(i); 55 | for(int node : temp) { 56 | indegree[node]++; 57 | } 58 | } 59 | Queue q = new LinkedList<>(); 60 | for(int i=0; i result = new ArrayList<>(); 67 | while(!q.isEmpty()) { 68 | int u = q.poll(); 69 | result.add(u); 70 | for(int node : adj.get(u)) { 71 | if(--indegree[node] == 0) { 72 | q.add(node); 73 | } 74 | } 75 | visited++; 76 | } 77 | int[] arr = new int[result.size()]; 78 | for(int i=0; i= 0; i--) 10 | heapify(arr, n, i); 11 | 12 | // One by one extract an element from heap 13 | for (int i=n-1; i>0; i--) 14 | { 15 | // Move current root to end 16 | int temp = arr[0]; 17 | arr[0] = arr[i]; 18 | arr[i] = temp; 19 | 20 | // call max heapify on the reduced heap 21 | heapify(arr, i, 0); 22 | } 23 | } 24 | 25 | // To heapify a subtree rooted with node i which is 26 | // an index in arr[]. n is size of heap 27 | void heapify(int arr[], int n, int i) 28 | { 29 | int largest = i; // Initialize largest as root 30 | int l = 2*i + 1; // left = 2*i + 1 31 | int r = 2*i + 2; // right = 2*i + 2 32 | 33 | // If left child is larger than root 34 | if (l < n && arr[l] > arr[largest]) 35 | largest = l; 36 | 37 | // If right child is larger than largest so far 38 | if (r < n && arr[r] > arr[largest]) 39 | largest = r; 40 | 41 | // If largest is not root 42 | if (largest != i) 43 | { 44 | int swap = arr[i]; 45 | arr[i] = arr[largest]; 46 | arr[largest] = swap; 47 | 48 | // Recursively heapify the affected sub-tree 49 | heapify(arr, n, largest); 50 | } 51 | } 52 | // Driver program 53 | public static void main(String args[]) 54 | { 55 | int arr[] = {12, 11, 13, 5, 6, 7}; 56 | int n = arr.length; 57 | int i; 58 | HeapSort ob = new HeapSort(); 59 | ob.sort(arr); 60 | 61 | System.out.println("Sorted array is"); 62 | for (i=0; ijava PartitionApp 4 | //////////////////////////////////////////////////////////////// 5 | class ArrayPar 6 | { 7 | private long[] theArray; // ref to array theArray 8 | private int nElems; // number of data items 9 | //-------------------------------------------------------------- 10 | public ArrayPar(int max) // constructor 11 | { 12 | theArray = new long[max]; // create the array 13 | nElems = 0; // no items yet 14 | } 15 | //-------------------------------------------------------------- 16 | public void insert(long value) // put element into array 17 | { 18 | theArray[nElems] = value; // insert it 19 | nElems++; // increment size 20 | } 21 | //-------------------------------------------------------------- 22 | public int size() // return number of items 23 | { return nElems; } 24 | //-------------------------------------------------------------- 25 | public void display() // displays array contents 26 | { 27 | System.out.print("A="); 28 | for(int j=0; j left && // find smaller item 44 | theArray[--rightPtr] > pivot) 45 | ; // (nop) 46 | if(leftPtr >= rightPtr) // if pointers cross, 47 | break; // partition done 48 | else // not crossed, so 49 | swap(leftPtr, rightPtr); // swap elements 50 | } // end while(true) 51 | return leftPtr; // return partition 52 | } // end partitionIt() 53 | //-------------------------------------------------------------- 54 | public void swap(int dex1, int dex2) // swap two elements 55 | { 56 | long temp; 57 | temp = theArray[dex1]; // A into temp 58 | theArray[dex1] = theArray[dex2]; // B into A 59 | theArray[dex2] = temp; // temp into B 60 | } // end swap() 61 | //-------------------------------------------------------------- 62 | } // end class ArrayPar 63 | //////////////////////////////////////////////////////////////// 64 | class PartitionApp 65 | { 66 | public static void main(String[] args) 67 | { 68 | int maxSize = 16; // array size 69 | ArrayPar arr; // reference to array 70 | arr = new ArrayPar(maxSize); // create the array 71 | 72 | for(int j=0; j Array to be sorted, 39 | low --> Starting index, 40 | high --> Ending index */ 41 | void sort(int arr[], int low, int high) 42 | { 43 | if (low < high) 44 | { 45 | /* pi is partitioning index, arr[pi] is 46 | now at right place */ 47 | int pi = partition(arr, low, high); 48 | 49 | // Recursively sort elements before 50 | // partition and after partition 51 | sort(arr, low, pi-1); 52 | sort(arr, pi+1, high); 53 | } 54 | } 55 | 56 | /* A utility function to print array of size n */ 57 | static void printArray(int arr[]) 58 | { 59 | int n = arr.length; 60 | for (int i=0; i arr) 9 | { 10 | int n = arr.size(); 11 | for (int i = 0; i < n-1; i++) 12 | { 13 | int min_idx = i; 14 | for (int j = i+1; j < n; j++) 15 | if (arr.get(j) < arr.get(min_idx)) 16 | min_idx = j; 17 | 18 | int temp = arr.get(min_idx); 19 | arr.set(min_idx, arr.get(i)); 20 | arr.set(i,temp); 21 | } 22 | } 23 | 24 | public static void main(String args[]) throws IOException 25 | { 26 | SelectionSort obj = new SelectionSort(); 27 | String pathToFile = "./Sorting/unsorted.txt"; 28 | File unsorted = new File(pathToFile); 29 | Scanner sc = new Scanner(unsorted); 30 | sc.useDelimiter(","); 31 | ArrayList arr = new ArrayList(); 32 | while(sc.hasNext()){ 33 | arr.add(sc.nextInt()); 34 | } 35 | obj.sorting(arr); 36 | System.out.println("Sorted array"); 37 | 38 | System.out.println( arr); 39 | sc.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Sorting/shellSort.java: -------------------------------------------------------------------------------- 1 | // shellSort.java 2 | // demonstrates shell sort 3 | // to run this program: C>java ShellSortApp 4 | //-------------------------------------------------------------- 5 | class ArraySh 6 | { 7 | private long[] theArray; // ref to array theArray 8 | private int nElems; // number of data items 9 | //-------------------------------------------------------------- 10 | public ArraySh(int max) // constructor 11 | { 12 | theArray = new long[max]; // create the array 13 | nElems = 0; // no items yet 14 | } 15 | //-------------------------------------------------------------- 16 | public void insert(long value) // put element into array 17 | { 18 | theArray[nElems] = value; // insert it 19 | nElems++; // increment size 20 | } 21 | //-------------------------------------------------------------- 22 | public void display() // displays array contents 23 | { 24 | System.out.print("A="); 25 | for(int j=0; j0) // decreasing h, until h=1 40 | { 41 | // h-sort the file 42 | for(outer=h; outer h-1 && theArray[inner-h] >= temp) 48 | { 49 | theArray[inner] = theArray[inner-h]; 50 | inner -= h; 51 | } 52 | theArray[inner] = temp; 53 | } // end for 54 | h = (h-1) / 3; // decrease h 55 | } // end while(h>0) 56 | } // end shellSort() 57 | //-------------------------------------------------------------- 58 | } // end class ArraySh 59 | //////////////////////////////////////////////////////////////// 60 | class ShellSortApp 61 | { 62 | public static void main(String[] args) 63 | { 64 | int maxSize = 10; // array size 65 | ArraySh arr; 66 | arr = new ArraySh(maxSize); // create the array 67 | 68 | for(int j=0; j stack) 10 | { 11 | for(int i = 0; i < 5; i++) 12 | { 13 | stack.push(i); 14 | } 15 | } 16 | 17 | 18 | static void stack_pop(Stack stack) 19 | { 20 | System.out.println("Pop Operation:"); 21 | 22 | for(int i = 0; i < 5; i++) 23 | { 24 | Integer y = (Integer) stack.pop(); 25 | System.out.println(y); 26 | } 27 | } 28 | 29 | 30 | static void stack_peek(Stack stack) 31 | { 32 | Integer element = (Integer) stack.peek(); 33 | System.out.println("Element on stack top: " + element); 34 | } 35 | 36 | 37 | static void stack_search(Stack stack, int element) 38 | { 39 | Integer pos = (Integer) stack.search(element); 40 | 41 | if(pos == -1) 42 | System.out.println("Element not found"); 43 | else 44 | System.out.println("Element is found at position: " + pos); 45 | } 46 | 47 | 48 | public static void main (String[] args) 49 | { 50 | Stack stack = new Stack(); 51 | 52 | stack_push(stack); 53 | stack_pop(stack); 54 | stack_push(stack); 55 | stack_peek(stack); 56 | stack_search(stack, 2); 57 | stack_search(stack, 6); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Tree/AVLtree.java: -------------------------------------------------------------------------------- 1 | // Java program for insertion in AVL Tree 2 | class Node { 3 | int key, height; 4 | Node left, right; 5 | 6 | Node(int d) { 7 | key = d; 8 | height = 1; 9 | } 10 | } 11 | 12 | class AVLTree { 13 | 14 | Node root; 15 | 16 | // A utility function to get the height of the tree 17 | int height(Node N) { 18 | if (N == null) 19 | return 0; 20 | 21 | return N.height; 22 | } 23 | 24 | // A utility function to get maximum of two integers 25 | int max(int a, int b) { 26 | return (a > b) ? a : b; 27 | } 28 | 29 | // A utility function to right rotate subtree rooted with y 30 | // See the diagram given above. 31 | Node rightRotate(Node y) { 32 | Node x = y.left; 33 | Node T2 = x.right; 34 | 35 | // Perform rotation 36 | x.right = y; 37 | y.left = T2; 38 | 39 | // Update heights 40 | y.height = max(height(y.left), height(y.right)) + 1; 41 | x.height = max(height(x.left), height(x.right)) + 1; 42 | 43 | // Return new root 44 | return x; 45 | } 46 | 47 | // A utility function to left rotate subtree rooted with x 48 | // See the diagram given above. 49 | Node leftRotate(Node x) { 50 | Node y = x.right; 51 | Node T2 = y.left; 52 | 53 | // Perform rotation 54 | y.left = x; 55 | x.right = T2; 56 | 57 | // Update heights 58 | x.height = max(height(x.left), height(x.right)) + 1; 59 | y.height = max(height(y.left), height(y.right)) + 1; 60 | 61 | // Return new root 62 | return y; 63 | } 64 | 65 | // Get Balance factor of node N 66 | int getBalance(Node N) { 67 | if (N == null) 68 | return 0; 69 | 70 | return height(N.left) - height(N.right); 71 | } 72 | 73 | Node insert(Node node, int key) { 74 | 75 | /* 1. Perform the normal BST insertion */ 76 | if (node == null) 77 | return (new Node(key)); 78 | 79 | if (key < node.key) 80 | node.left = insert(node.left, key); 81 | else if (key > node.key) 82 | node.right = insert(node.right, key); 83 | else // Duplicate keys not allowed 84 | return node; 85 | 86 | /* 2. Update height of this ancestor node */ 87 | node.height = 1 + max(height(node.left), 88 | height(node.right)); 89 | 90 | /* 3. Get the balance factor of this ancestor 91 | node to check whether this node became 92 | unbalanced */ 93 | int balance = getBalance(node); 94 | 95 | // If this node becomes unbalanced, then there 96 | // are 4 cases Left Left Case 97 | if (balance > 1 && key < node.left.key) 98 | return rightRotate(node); 99 | 100 | // Right Right Case 101 | if (balance < -1 && key > node.right.key) 102 | return leftRotate(node); 103 | 104 | // Left Right Case 105 | if (balance > 1 && key > node.left.key) { 106 | node.left = leftRotate(node.left); 107 | return rightRotate(node); 108 | } 109 | 110 | // Right Left Case 111 | if (balance < -1 && key < node.right.key) { 112 | node.right = rightRotate(node.right); 113 | return leftRotate(node); 114 | } 115 | 116 | /* return the (unchanged) node pointer */ 117 | return node; 118 | } 119 | 120 | // A utility function to print preorder traversal 121 | // of the tree. 122 | // The function also prints height of every node 123 | void preOrder(Node node) { 124 | if (node != null) { 125 | System.out.print(node.key + " "); 126 | preOrder(node.left); 127 | preOrder(node.right); 128 | } 129 | } 130 | 131 | public static void main(String[] args) { 132 | AVLTree tree = new AVLTree(); 133 | 134 | /* Constructing tree given in the above figure */ 135 | tree.root = tree.insert(tree.root, 10); 136 | tree.root = tree.insert(tree.root, 20); 137 | tree.root = tree.insert(tree.root, 30); 138 | tree.root = tree.insert(tree.root, 40); 139 | tree.root = tree.insert(tree.root, 50); 140 | tree.root = tree.insert(tree.root, 25); 141 | 142 | /* The constructed AVL Tree would be 143 | 30 144 | / \ 145 | 20 40 146 | / \ \ 147 | 10 25 50 148 | */ 149 | System.out.println("Preorder traversal" + 150 | " of constructed tree is : "); 151 | tree.preOrder(tree.root); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /Tree/BFSTree.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | import java.util.Queue; 5 | 6 | class TreeNode 7 | { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | 12 | TreeNode(int val) 13 | { 14 | this.val = val; 15 | left = null; 16 | right = null; 17 | } 18 | } 19 | public class BFSTree { 20 | public List BFStraversal(TreeNode tree) 21 | { 22 | Queue queue = new LinkedList<>(); 23 | 24 | List list = new ArrayList<>(); 25 | 26 | if(tree == null) 27 | { 28 | return list; 29 | } 30 | 31 | queue.add(tree); 32 | 33 | while(!queue.isEmpty()) 34 | { 35 | TreeNode t = queue.poll(); 36 | list.add(t.val); 37 | 38 | if(t.left != null) 39 | { 40 | queue.add(t.left); 41 | } 42 | if(t.right != null) 43 | { 44 | queue.add(t.right); 45 | } 46 | } 47 | 48 | return list; 49 | 50 | } 51 | } 52 | 53 | class BFSTreeDemo 54 | { 55 | public static void main(String[] args) { 56 | 57 | 58 | BFSTree b = new BFSTree(); 59 | TreeNode tree = null; 60 | tree = new TreeNode(10); 61 | tree.left = new TreeNode(11); 62 | tree.right = new TreeNode(15); 63 | tree.left.left = new TreeNode(16); 64 | tree.right.right = new TreeNode(17); 65 | tree.left.right= new TreeNode(19); 66 | tree.right.left = new TreeNode(20); 67 | System.out.println(b.BFStraversal(tree)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Tree/Lowest Common Ancestor.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class Node { 5 | Node left; 6 | Node right; 7 | int data; 8 | 9 | Node(int data) { 10 | this.data = data; 11 | left = null; 12 | right = null; 13 | } 14 | } 15 | 16 | class Solution { 17 | 18 | /* 19 | class Node 20 | int data; 21 | Node left; 22 | Node right; 23 | */ 24 | public static Node lca(Node root, int v1, int v2) { 25 | // Write your code here. 26 | if(root == null) return null; 27 | 28 | if(root.data > v1 && root.data > v2) return lca(root.left, v1, v2); 29 | if(root.data < v1 && root.data < v2) return lca(root.right, v1, v2); 30 | 31 | return root; 32 | } 33 | 34 | public static Node insert(Node root, int data) { 35 | if(root == null) { 36 | return new Node(data); 37 | } else { 38 | Node cur; 39 | if(data <= root.data) { 40 | cur = insert(root.left, data); 41 | root.left = cur; 42 | } else { 43 | cur = insert(root.right, data); 44 | root.right = cur; 45 | } 46 | return root; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Scanner scan = new Scanner(System.in); 52 | int t = scan.nextInt(); 53 | Node root = null; 54 | while(t-- > 0) { 55 | int data = scan.nextInt(); 56 | root = insert(root, data); 57 | } 58 | int v1 = scan.nextInt(); 59 | int v2 = scan.nextInt(); 60 | scan.close(); 61 | Node ans = lca(root,v1,v2); 62 | System.out.println(ans.data); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Tree/Second_Minimum_In_Binary_Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | This code has been written by - Amrit Raj 3 | 4 | This is a functional code with the following specifications:- 5 | Arguments - Root node of the Tree defined by class TreeNode 6 | Return - An int signifying the second minimum node in the given tree. In case 7 | it is not found, it returns -1 8 | */ 9 | 10 | public int findSecondMinimumValue(TreeNode root) { 11 | //A queue to store the nodes.. 12 | Queue q = new ArrayDeque<>(); 13 | if (root == null) 14 | return -1; 15 | int min = root.val; 16 | int secondMin = Integer.MAX_VALUE; 17 | boolean found = false; 18 | 19 | q.add(root); 20 | while (!q.isEmpty()) { 21 | int size = q.size(); 22 | for (int i = 0; i < size; i++) { 23 | TreeNode node = q.poll(); 24 | if (node.val > min) { 25 | secondMin = Math.min(node.val, secondMin); 26 | found = true; 27 | continue; 28 | } 29 | //Left subtree.. 30 | if (node.left != null && node.left.val <= secondMin) 31 | q.add(node.left); 32 | //Right Subtree 33 | if (node.right != null && node.right.val <= secondMin) 34 | q.add(node.right); 35 | } 36 | } 37 | //Returning second min, else -1... 38 | return found? secondMin : -1; 39 | } 40 | -------------------------------------------------------------------------------- /Tree/binarySearchTree/Bst.java: -------------------------------------------------------------------------------- 1 | public class Bst 2 | { 3 | public class TreeNode 4 | { 5 | int val; 6 | TreeNode left; 7 | TreeNode right; 8 | TreeNode(int val) 9 | { 10 | this.val = val; 11 | this.right=null; 12 | this.left=null; 13 | } 14 | 15 | TreeNode(int val, TreeNode left, TreeNode right) 16 | { 17 | this.val = val; 18 | this.left = left; 19 | this.right = right; 20 | } 21 | } 22 | 23 | TreeNode root; 24 | 25 | public void insert(int data) 26 | { 27 | this.root=insertnode(this.root,data); 28 | } 29 | 30 | private TreeNode insertnode(TreeNode root,int data) 31 | { 32 | if (root == null) 33 | { 34 | root=new TreeNode(data); 35 | return root; 36 | } 37 | else if (data < root.val) 38 | root.left=insertnode(root.left, data); 39 | else if (data > root.val) 40 | root.right=insertnode(root.right, data); 41 | return root; 42 | } 43 | 44 | public Boolean search(int data) 45 | { 46 | TreeNode node=searchnode(this.root,data); 47 | return node!=null; 48 | } 49 | 50 | private TreeNode searchnode(TreeNode root,int data) 51 | { 52 | if (root==null || root.val==data) 53 | return root; 54 | if (root.val>data) 55 | return searchnode(root.left,data); 56 | return searchnode(root.right, data); 57 | } 58 | 59 | public static void main(String[] args) 60 | { 61 | Bst bst=new Bst(); 62 | bst.insert(8); 63 | bst.insert(3); 64 | bst.insert(10); 65 | bst.insert(1); 66 | bst.insert(14); 67 | bst.insert(6); 68 | bst.insert(4); 69 | System.out.println(bst.search(14)?"Found":"Not Found"); 70 | } 71 | } -------------------------------------------------------------------------------- /Tree/binarySearchTree/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode() { 7 | } 8 | 9 | TreeNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | TreeNode(int val, TreeNode left, TreeNode right) { 14 | this.val = val; 15 | this.left = left; 16 | this.right = right; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /binaryPalindrome.java: -------------------------------------------------------------------------------- 1 | class binaryPalindrome 2 | { 3 | 4 | static int isKthBitSet(long x, long k) 5 | { 6 | int rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0; 7 | return rslt; 8 | } 9 | 10 | static int isPalindrome( long x) 11 | { 12 | long l = 1; // Initialize left position 13 | long r = (Integer.SIZE/8 )* 8; // initialize right position 14 | 15 | 16 | while (l < r) 17 | { 18 | if (isKthBitSet(x, l) != isKthBitSet(x, r)) 19 | { 20 | return 0; 21 | } 22 | l++; r--; 23 | } 24 | return 1; 25 | } 26 | 27 | public static void main (String[] args) 28 | { 29 | long x = 1 << 15 + 1 << 16 ; 30 | System.out.println(isPalindrome(x)); 31 | 32 | x = (1 << 31) + 1 ; 33 | System.out.println(isPalindrome(x)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /linkedList/CircularLinkedList.java: -------------------------------------------------------------------------------- 1 | public class CreateList { 2 | //Represents the node of list. 3 | public class Node{ 4 | int data; 5 | Node next; 6 | public Node(int data) { 7 | this.data = data; 8 | } 9 | } 10 | 11 | //Declaring head and tail pointer as null. 12 | public Node head = null; 13 | public Node tail = null; 14 | 15 | //This function will add the new node at the end of the list. 16 | public void add(int data){ 17 | //Create new node 18 | Node newNode = new Node(data); 19 | //Checks if the list is empty. 20 | if(head == null) { 21 | //If list is empty, both head and tail would point to new node. 22 | head = newNode; 23 | tail = newNode; 24 | newNode.next = head; 25 | } 26 | else { 27 | //tail will point to new node. 28 | tail.next = newNode; 29 | //New node will become new tail. 30 | tail = newNode; 31 | //Since, it is circular linked list tail will point to head. 32 | tail.next = head; 33 | } 34 | } 35 | 36 | //Displays all the nodes in the list 37 | public void display() { 38 | Node current = head; 39 | if(head == null) { 40 | System.out.println("List is empty"); 41 | } 42 | else { 43 | System.out.println("Nodes of the circular linked list: "); 44 | do{ 45 | //Prints each node by incrementing pointer. 46 | System.out.print(" "+ current.data); 47 | current = current.next; 48 | }while(current != head); 49 | System.out.println(); 50 | } 51 | } 52 | 53 | public static void main(String[] args) { 54 | CreateList cl = new CreateList(); 55 | //Adds data to the list 56 | cl.add(1); 57 | cl.add(2); 58 | cl.add(3); 59 | cl.add(4); 60 | //Displays all the nodes present in the list 61 | cl.display(); 62 | 63 | /*output Nodes of the circular linked list: 64 | 1 2 3 4 */ 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /linkedList/DoubleLinkedList: -------------------------------------------------------------------------------- 1 | // A complete working Java program to demonstrate all 2 | 3 | // Class for Doubly Linked List 4 | public class DLL { 5 | Node head; // head of list 6 | 7 | /* Doubly Linked list Node*/ 8 | class Node { 9 | int data; 10 | Node prev; 11 | Node next; 12 | 13 | // Constructor to create a new node 14 | // next and prev is by default initialized as null 15 | Node(int d) { data = d; } 16 | } 17 | 18 | // Adding a node at the front of the list 19 | public void push(int new_data) 20 | { 21 | /* 1. allocate node 22 | * 2. put in the data */ 23 | Node new_Node = new Node(new_data); 24 | 25 | /* 3. Make next of new node as head and previous as NULL */ 26 | new_Node.next = head; 27 | new_Node.prev = null; 28 | 29 | /* 4. change prev of head node to new node */ 30 | if (head != null) 31 | head.prev = new_Node; 32 | 33 | /* 5. move the head to point to the new node */ 34 | head = new_Node; 35 | } 36 | 37 | /* Given a node as prev_node, insert a new node after the given node */ 38 | public void InsertAfter(Node prev_Node, int new_data) 39 | { 40 | 41 | /*1. check if the given prev_node is NULL */ 42 | if (prev_Node == null) { 43 | System.out.println("The given previous node cannot be NULL "); 44 | return; 45 | } 46 | 47 | /* 2. allocate node 48 | * 3. put in the data */ 49 | Node new_node = new Node(new_data); 50 | 51 | /* 4. Make next of new node as next of prev_node */ 52 | new_node.next = prev_Node.next; 53 | 54 | /* 5. Make the next of prev_node as new_node */ 55 | prev_Node.next = new_node; 56 | 57 | /* 6. Make prev_node as previous of new_node */ 58 | new_node.prev = prev_Node; 59 | 60 | /* 7. Change previous of new_node's next node */ 61 | if (new_node.next != null) 62 | new_node.next.prev = new_node; 63 | } 64 | 65 | // Add a node at the end of the list 66 | void append(int new_data) 67 | { 68 | /* 1. allocate node 69 | * 2. put in the data */ 70 | Node new_node = new Node(new_data); 71 | 72 | Node last = head; /* used in step 5*/ 73 | 74 | /* 3. This new node is going to be the last node, so 75 | * make next of it as NULL*/ 76 | new_node.next = null; 77 | 78 | /* 4. If the Linked List is empty, then make the new 79 | * node as head */ 80 | if (head == null) { 81 | new_node.prev = null; 82 | head = new_node; 83 | return; 84 | } 85 | 86 | /* 5. Else traverse till the last node */ 87 | while (last.next != null) 88 | last = last.next; 89 | 90 | /* 6. Change the next of last node */ 91 | last.next = new_node; 92 | 93 | /* 7. Make last node as previous of new node */ 94 | new_node.prev = last; 95 | } 96 | 97 | // This function prints contents of linked list starting from the given node 98 | public void printlist(Node node) 99 | { 100 | Node last = null; 101 | System.out.println("Traversal in forward Direction"); 102 | while (node != null) { 103 | System.out.print(node.data + " "); 104 | last = node; 105 | node = node.next; 106 | } 107 | System.out.println(); 108 | System.out.println("Traversal in reverse direction"); 109 | while (last != null) { 110 | System.out.print(last.data + " "); 111 | last = last.prev; 112 | } 113 | } 114 | 115 | /* Driver program to test above functions*/ 116 | public static void main(String[] args) 117 | { 118 | /* Start with the empty list */ 119 | DLL dll = new DLL(); 120 | 121 | // Insert 6. So linked list becomes 6->NULL 122 | dll.append(6); 123 | 124 | // Insert 7 at the beginning. So linked list becomes 7->6->NULL 125 | dll.push(7); 126 | 127 | // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL 128 | dll.push(1); 129 | 130 | // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL 131 | dll.append(4); 132 | 133 | // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL 134 | dll.InsertAfter(dll.head.next, 8); 135 | 136 | System.out.println("Created DLL is: "); 137 | dll.printlist(dll.head); 138 | } 139 | } 140 | 141 | -------------------------------------------------------------------------------- /linkedList/LinkedListasQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | class Main { 5 | public static void main(String[] args) { 6 | Queue languages = new LinkedList<>(); 7 | 8 | // add elements 9 | languages.add("Python"); 10 | languages.add("Java"); 11 | languages.add("C"); 12 | System.out.println("LinkedList: " + languages); 13 | 14 | // access the first element 15 | String str1 = languages.peek(); 16 | System.out.println("Accessed Element: " + str1); 17 | 18 | // access and remove the first element 19 | String str2 = languages.poll(); 20 | System.out.println("Removed Element: " + str2); 21 | System.out.println("LinkedList after poll(): " + languages); 22 | 23 | // add element at the end 24 | languages.offer("Swift"); 25 | System.out.println("LinkedList after offer(): " + languages); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /linkedList/ListNode.java: -------------------------------------------------------------------------------- 1 | public class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode() { 6 | } 7 | 8 | ListNode(int val) { 9 | this.val = val; 10 | this.next = null; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | 18 | 19 | public static ListNode createArray(int[] a) { 20 | 21 | if (a.length == 0) { 22 | return null; 23 | } 24 | 25 | ListNode root = new ListNode(a[0]); 26 | ListNode cur = root; 27 | 28 | for (int j = 1; j < a.length; j++) { 29 | ListNode temp = new ListNode(a[j]); 30 | cur.next = temp; 31 | cur = cur.next; 32 | } 33 | 34 | return root; 35 | } 36 | } -------------------------------------------------------------------------------- /linkedList/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class SinglyLinkedList 2 | { 3 | class Node 4 | { 5 | int data; 6 | Node next; 7 | 8 | public Node(int data) 9 | { 10 | this.data=data; 11 | this.next=null; 12 | size++; 13 | } 14 | } 15 | 16 | Node head; 17 | Node tail; 18 | int size; 19 | 20 | public SinglyLinkedList() 21 | { 22 | head=null; 23 | tail=null; 24 | size=0; 25 | } 26 | 27 | public void InsertAtTail(int data) 28 | { 29 | Node node =new Node(data); 30 | if(this.head==null) 31 | { 32 | this.head=node; 33 | this.tail=node; 34 | } 35 | else 36 | this.tail.next=node; 37 | this.tail=node; 38 | } 39 | 40 | public void InstertAtHead(int data) 41 | { 42 | Node node=new Node(data); 43 | node.next=head; 44 | head=node; 45 | if(this.tail==null) 46 | this.tail=node; 47 | } 48 | 49 | Boolean isEmpty() 50 | { 51 | return head==null; 52 | } 53 | 54 | public void displayNodes() 55 | { 56 | if(this.isEmpty()) 57 | System.out.println("The list is empty"); 58 | Node temp=this.head; 59 | while(temp.next!=null) 60 | { 61 | System.out.print(temp.data+"->"); 62 | temp=temp.next; 63 | } 64 | System.out.print("end"); 65 | } 66 | public static void main(String[] args) 67 | { 68 | SinglyLinkedList l =new SinglyLinkedList(); 69 | l.InstertAtHead(5); 70 | l.InsertAtTail(6); 71 | l.InstertAtHead(4); 72 | System.out.println("Size of Linked List is: "+l.size); 73 | l.InsertAtTail(3); 74 | l.displayNodes(); 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /linkedList/removeNthNodeFromEnd.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode removeNthFromEnd(ListNode head, int n) { 13 | ListNode cur = head; 14 | int len = 0; 15 | while(cur!=null){ 16 | len++; 17 | cur = cur.next; 18 | } 19 | 20 | len = len - n; 21 | if(len == 0){ 22 | head = head.next; 23 | return head; 24 | } 25 | cur = head; 26 | ListNode prev = null; 27 | for(int i = 0;i