├── Recursion ├── factorialUsingRecursion.java ├── nCr.java ├── sumOfNNumbers.java ├── countDigitsInANumber.java ├── sumOfDigits.java ├── euclidGCD.java ├── printOneToN.java ├── nthFibonacci.java ├── binaryExponentiation.java ├── printArrayRecursive.java ├── checkPalindromeNumber.java └── towerOfHanoiMoveCount.java ├── BinaryTree ├── heightOfBinaryTree.java ├── inOrder.java ├── postOrder.java ├── preOrder.java ├── levelOrderTraversal.java └── topView.java ├── String ├── countWords.java ├── reverseString.java ├── toLowerCase.java ├── toUpperCase.java ├── checkAnagram.java ├── panagramCheck.java ├── missingPanagram.java ├── anagramSearch.java └── stringValidation.java ├── Arrays ├── checkIfArrayIsSorted.java ├── leftRotateByOne.java ├── getLargestElementIndex.java ├── kadanesAlgorithm.java ├── deleteElement.java ├── rotateArrayDTimes.java ├── moveZerosToEnd.java ├── shiftAllNegativeToLeft.java ├── combinationOfKElements.java ├── removeDuplicatesFromSortedArray.java ├── insertion.java ├── nextPermutaion.java ├── allPermutationOfArray.java ├── rowsWithMaxOnes.java ├── setMatrixZeroes.java ├── spiralPrintMatrix.java ├── largeFactorial.java └── maxNonNegativeSubArray.java ├── BinarySearchTree ├── searchBST.java ├── insertBST.java ├── rangeSum.java └── deleteBST.java ├── Stack ├── reverseArray.java ├── checkBalancedParanthesis.java ├── postfixEvaluation.java ├── ArrayImplementation │ └── ArrayStack.java ├── infixToPostfix.java └── LinkedListImplementation │ └── LinkedListStack.java ├── Sorting ├── insertionSort.java ├── selectionSort.java ├── mergeTwoSortedArrays.java ├── bubbleSort.java ├── quickSort.java └── mergeSort.java ├── DynamicProgramming ├── BottomUp │ ├── nthFibonacci.java │ ├── nCr.java │ ├── gridTraveler.java │ └── knapsackProblem.java └── TopDown │ ├── nCr.java │ ├── nthFibonacci.java │ ├── knapsackProblem.java │ └── paintingHousesProblem.java ├── Searching ├── iterativeBinarySearch.java ├── squareRoot.java ├── recursiveBinarySearch.java ├── iterativeFirstOccurenceBinarySearch.java ├── recursiveFirstOccurenceBinarySearch.java └── majorityElement.java ├── Hashing ├── nonRepeatingCharacter.java └── countNonRepeatedElements.java ├── Queue ├── rotateDeQueue.java └── TwoStackQueue.java ├── BinaryHeap ├── kThLargest.java ├── kThSmallest.java ├── HeapSort.java └── MinHeap.java ├── Graph ├── DFS.java ├── DFSDisconnected.java ├── BFS.java ├── BFSDisconnected.java ├── CountConnectedComponents.java ├── topologicalSortDFS.java ├── AdjacencyList.java └── Kruskals.java ├── Backtracking ├── combinationOfKElements.java ├── generateParentheses.java ├── allPermutationOfArray.java ├── combinationTargetSum.java ├── printAnagrams.java └── wordBreak.java ├── DisjointSet └── DisjointSet.java ├── LinkedList ├── CircularLinkedList.java ├── DoublyLinkedList.java └── SinglyLinkedList.java ├── Trie └── Trie.java └── README.md /Recursion/factorialUsingRecursion.java: -------------------------------------------------------------------------------- 1 | public static int fact(int n) { 2 | if(n == 0) return 1; 3 | return n * fact(n - 1); 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/nCr.java: -------------------------------------------------------------------------------- 1 | public static int nCr(int n,int r) { 2 | if(n == r || r == 0) return 1; 3 | return nCr(n-1, r-1) + nCr(n-1, r); 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/sumOfNNumbers.java: -------------------------------------------------------------------------------- 1 | public static int recursiveSum(int n) { 2 | if(n == 0) return 0; 3 | return n + recursiveSum(n - 1); 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/countDigitsInANumber.java: -------------------------------------------------------------------------------- 1 | public static int countDigits(int n) { 2 | if(n < 10) return 1; 3 | return 1 + countDigits(n / 10); 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/sumOfDigits.java: -------------------------------------------------------------------------------- 1 | public static int sumOfDigits(int n) { 2 | if(n < 10) return n; 3 | return (n % 10) + sumOfDigits(n / 10); 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/euclidGCD.java: -------------------------------------------------------------------------------- 1 | public static int gcd(int a, int b){ 2 | if(a == 0) return b; 3 | if(b == 0) return a; 4 | return gcd(b, a % b); 5 | } 6 | -------------------------------------------------------------------------------- /Recursion/printOneToN.java: -------------------------------------------------------------------------------- 1 | public static void printOneToN(int n) { 2 | if(n == 0) return; 3 | printOneToN(n - 1); 4 | System.out.print(n + " "); 5 | } 6 | -------------------------------------------------------------------------------- /BinaryTree/heightOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | static int height(Node root) { 2 | if(root == null) return 0; 3 | return Math.max(height(root.left), height(root.right)) + 1; 4 | } 5 | -------------------------------------------------------------------------------- /Recursion/nthFibonacci.java: -------------------------------------------------------------------------------- 1 | static long fibonacci(int n) { 2 | if(n == 1) return 1; 3 | if(n == 2) return 1; 4 | return fibonacci(n-1) + fibonacci(n-2); 5 | } 6 | -------------------------------------------------------------------------------- /BinaryTree/inOrder.java: -------------------------------------------------------------------------------- 1 | static void inorder(Node root) { 2 | if(root == null) return; 3 | inorder(root.left); 4 | System.out.println(root.data); 5 | inorder(root.right); 6 | } 7 | -------------------------------------------------------------------------------- /BinaryTree/postOrder.java: -------------------------------------------------------------------------------- 1 | static void postorder(Node root) { 2 | if(root == null) return; 3 | postorder(root.left); 4 | postorder(root.right); 5 | System.out.println(root.data); 6 | } 7 | -------------------------------------------------------------------------------- /BinaryTree/preOrder.java: -------------------------------------------------------------------------------- 1 | static void preorder(Node root) { 2 | if(root == null) return; 3 | System.out.println(root.data); 4 | preorder(root.left); 5 | preorder(root.right); 6 | } 7 | -------------------------------------------------------------------------------- /String/countWords.java: -------------------------------------------------------------------------------- 1 | public static int countWords(String str) { 2 | int count = 1; 3 | for(int i=0;i root.data) return search(root.right, x); 5 | else return search(root.left, x); 6 | } 7 | -------------------------------------------------------------------------------- /Arrays/getLargestElementIndex.java: -------------------------------------------------------------------------------- 1 | public static int getLargestElementIndex(int[] a) { 2 | int res = 0; 3 | for(int i = 1; i < a.length; i++) { 4 | if(a[i] > a[res]) res = i; 5 | } 6 | return res; 7 | } 8 | -------------------------------------------------------------------------------- /String/reverseString.java: -------------------------------------------------------------------------------- 1 | public static String reverseWord(String str) { 2 | StringBuilder res = new StringBuilder(); 3 | for(int i=str.length()-1;i>=0;i--) { 4 | res.append(str.charAt(i)); 5 | } 6 | return res.toString(); 7 | } 8 | -------------------------------------------------------------------------------- /Stack/reverseArray.java: -------------------------------------------------------------------------------- 1 | public static void reverseArray(int n, int arr[]) { 2 | Stack s = new Stack<>(); 3 | for(int i : arr) { 4 | s.push(i); 5 | } 6 | for(int i=0;i= 0 && a[j] > key) { 6 | a[j + 1] = a[j]; 7 | j--; 8 | } 9 | a[j + 1] = key; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /DynamicProgramming/BottomUp/nthFibonacci.java: -------------------------------------------------------------------------------- 1 | static int fib(int n) { 2 | if(n == 1) return 0; 3 | if(n == 2) return 1; 4 | int[] dp = new int[n + 1]; 5 | dp[1] = 0; 6 | dp[2] = 1; 7 | for(int i=3;i<=n;i++) { 8 | dp[i] = dp[i-1] + dp[i-2]; 9 | } 10 | return dp[n]; 11 | } 12 | -------------------------------------------------------------------------------- /String/checkAnagram.java: -------------------------------------------------------------------------------- 1 | public static boolean isAnagram(String s1,String s2) { 2 | int[] ch = new int[26]; 3 | for(int i=0;i x) high = mid - 1; 8 | else low = mid + 1; 9 | } 10 | return -1; 11 | } 12 | -------------------------------------------------------------------------------- /DynamicProgramming/TopDown/nCr.java: -------------------------------------------------------------------------------- 1 | static int nCr(int n, int r) { 2 | return nCr(n, r, new int[n+1][r+1]); 3 | } 4 | 5 | static int nCr(int n, int r, int[][] dp) { 6 | if(n == r || r == 0) return 1; 7 | if(dp[n][r] != 0) return dp[n][r]; 8 | int ans = nCr(n-1, r-1) + nCr(n-1, r); 9 | dp[n][r] = ans; 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /DynamicProgramming/TopDown/nthFibonacci.java: -------------------------------------------------------------------------------- 1 | static int fib(int n) { 2 | return fib(n, new int[n + 1]); 3 | } 4 | 5 | static int fib(int n, int[] dp) { 6 | if(n == 1) return 0; 7 | if(n == 2) return 1; 8 | if(dp[n] != 0) return dp[n]; 9 | int res = fib(n - 1, dp) + fib(n - 2, dp); 10 | dp[n] = res; 11 | return res; 12 | } 13 | -------------------------------------------------------------------------------- /DynamicProgramming/BottomUp/nCr.java: -------------------------------------------------------------------------------- 1 | static int nCr(int n, int r) { 2 | int[][] dp = new int[n+1][r+1]; 3 | for(int i=0;i<=n;i++) { 4 | dp[i][0] = 1; 5 | if(i <= r) dp[i][i] = 1; 6 | } 7 | for(int i=1;i<=n;i++) { 8 | for(int j=1;j<=r;j++) { 9 | dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; 10 | } 11 | } 12 | return dp[n][r]; 13 | } 14 | -------------------------------------------------------------------------------- /Hashing/nonRepeatingCharacter.java: -------------------------------------------------------------------------------- 1 | static char nonRepeatingCharacter(String s) { 2 | int[] a = new int[26]; 3 | 4 | for(int i=0;i x) high = mid - 1; 8 | else { 9 | low = mid + 1; 10 | ans = mid; 11 | } 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /BinaryTree/levelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | static void levelOrder(Node root) { 2 | Queue q = new LinkedList<>(); 3 | q.add(root); 4 | while(!q.isEmpty()) { 5 | Node curr = q.poll(); 6 | System.out.print(curr.data + " "); 7 | if(curr.left != null) q.add(curr.left); 8 | if(curr.right != null) q.add(curr.right); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Queue/rotateDeQueue.java: -------------------------------------------------------------------------------- 1 | public static void left_Rotate_Deq_ByK(ArrayDeque deque, int n, int k) { 2 | while(k-- != 0) { 3 | deque.addLast(deque.pollFirst()); 4 | } 5 | } 6 | 7 | public static void right_Rotate_Deq_ByK(ArrayDeque deque, int n, int k) { 8 | while(k-- != 0) { 9 | deque.addFirst(deque.pollLast()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Arrays/deleteElement.java: -------------------------------------------------------------------------------- 1 | public static int deleteElement(int[] a, int size, int element) { 2 | int i; 3 | for(i = 0; i < size; i++) { 4 | if(a[i] == element) break; 5 | } 6 | if(i == size) return size; 7 | for(int j = i; j < size - 1; j++) { 8 | a[j] = a[j + 1]; 9 | } 10 | return (size - 1); 11 | } 12 | -------------------------------------------------------------------------------- /BinarySearchTree/insertBST.java: -------------------------------------------------------------------------------- 1 | Node insert(Node root, int key) { 2 | Node newNode = new Node(key); 3 | if(root == null) { 4 | root = newNode; 5 | return root; 6 | } 7 | if(key == root.data) return root; 8 | else if(key > root.data) root.right = insert(root.right, key); 9 | else root.left = insert(root.left, key); 10 | return root; 11 | } 12 | -------------------------------------------------------------------------------- /Recursion/towerOfHanoiMoveCount.java: -------------------------------------------------------------------------------- 1 | public long toh(int N, int from, int to, int aux) { 2 | long moves = 0L; 3 | if (N >= 1) { 4 | moves += toh(N - 1, from, aux, to); 5 | System.out.println("move disk " + N + " from rod " + from + " to rod " + to); 6 | moves++; 7 | moves += toh(N - 1, aux, to, from); 8 | } 9 | return moves; 10 | } 11 | -------------------------------------------------------------------------------- /Arrays/rotateArrayDTimes.java: -------------------------------------------------------------------------------- 1 | static void reverse(int[] a, int i, int j) { 2 | while(i < j) { 3 | int temp = a[i]; 4 | a[i] = a[j]; 5 | a[j] = temp; 6 | i++; 7 | j--; 8 | } 9 | } 10 | 11 | static void rotateArr(int arr[], int d, int n) { 12 | reverse(arr, 0, d-1); 13 | reverse(arr, d, n-1); 14 | reverse(arr, 0, n-1); 15 | } 16 | -------------------------------------------------------------------------------- /DynamicProgramming/BottomUp/gridTraveler.java: -------------------------------------------------------------------------------- 1 | static long gridTraveler(int m, int n) { 2 | long[][] dp = new long[m+1][n+1]; 3 | for(int i=1;i<=m;i++) dp[i][1] = 1; 4 | for(int j=1;j<=n;j++) dp[1][j] = 1; 5 | for(int i=2;i<=m;i++) { 6 | for(int j=2;j<=n;j++) { 7 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 8 | } 9 | } 10 | return dp[m][n]; 11 | } 12 | -------------------------------------------------------------------------------- /BinaryHeap/kThLargest.java: -------------------------------------------------------------------------------- 1 | public static int KthLargest(int arr[], int n, int k) { 2 | PriorityQueue pq = new PriorityQueue<>(); 3 | for(int i=0;i pq.peek()) { 8 | pq.poll(); 9 | pq.add(arr[i]); 10 | } 11 | } 12 | return pq.peek(); 13 | } 14 | -------------------------------------------------------------------------------- /BinaryHeap/kThSmallest.java: -------------------------------------------------------------------------------- 1 | public static int kthSmallest(int arr[], int n, int k){ 2 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 3 | for(int i=0;i= l && root.data <= r) ans += root.data; 12 | if(root.data > l) dfs(root.left, l, r); 13 | if(root.data < r) dfs(root.right, l, r); 14 | } 15 | -------------------------------------------------------------------------------- /Graph/DFS.java: -------------------------------------------------------------------------------- 1 | static void DFS(List> adj, int source, boolean[] visited) { 2 | visited[source] = true; 3 | System.out.print(source + " "); 4 | for(int u : adj.get(source)) { 5 | if(!visited[u]) { 6 | DFS(adj, u, visited); 7 | } 8 | } 9 | } 10 | 11 | static void DFS(List> adj, int n, int source) { 12 | boolean[] visited = new boolean[n]; 13 | DFS(adj, source, visited); 14 | } 15 | -------------------------------------------------------------------------------- /Searching/recursiveBinarySearch.java: -------------------------------------------------------------------------------- 1 | static int binarySearch(int[] a, int x) { 2 | return binarySearch(a, x, 0, a.length - 1); 3 | } 4 | 5 | static int binarySearch(int[] a, int x, int low, int high) { 6 | if(low > high) return -1; 7 | int mid = (low + high) / 2; 8 | if(a[mid] == x) return mid; 9 | else if(a[mid] > x) return binarySearch(a, x, low, mid - 1); 10 | else return binarySearch(a, x, mid + 1, high); 11 | } 12 | -------------------------------------------------------------------------------- /Sorting/mergeTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | static void merge(int[] a, int[] b) { 2 | int m = a.length; 3 | int n = b.length; 4 | int i = 0, j = 0; 5 | while(i < m && j < n) { 6 | if(a[i] < b[j]) { 7 | System.out.print(a[i++] + " "); 8 | } else { 9 | System.out.print(b[j++] + " "); 10 | } 11 | } 12 | while(i < m) System.out.print(a[i++] + " "); 13 | while(j < n) System.out.print(b[j++] + " "); 14 | } 15 | -------------------------------------------------------------------------------- /Arrays/moveZerosToEnd.java: -------------------------------------------------------------------------------- 1 | public static void swap(int[] a, int i, int j) { 2 | int temp = a[i]; 3 | a[i] = a[j]; 4 | a[j] = temp; 5 | } 6 | 7 | public static void moveZeroToEnd(int[] a) { 8 | int count = 0; 9 | for(int i = 0; i < a.length; i++) { 10 | if(a[i] != 0) { 11 | swap(a, i, count); 12 | count++; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Sorting/bubbleSort.java: -------------------------------------------------------------------------------- 1 | static void bubbleSort(int[] a) { 2 | for(int i=0;i a[j+1]) { 6 | swap(a, j, j + 1); 7 | swapped = true; 8 | } 9 | } 10 | if(!swapped) break; 11 | } 12 | } 13 | 14 | static void swap(int[] a, int x, int y) { 15 | int temp = a[x]; 16 | a[x] = a[y]; 17 | a[y] = temp; 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/shiftAllNegativeToLeft.java: -------------------------------------------------------------------------------- 1 | static void shiftNegative(int[] a) { 2 | int l = 0, r = a.length - 1; 3 | while(l <= r) { 4 | if(a[l] < 0 && a[r] < 0) { 5 | l++; 6 | } else if(a[l] > 0 && a[r] < 0) { 7 | int temp = a[l]; 8 | a[l] = a[r]; 9 | a[r] = temp; 10 | r--; 11 | l++; 12 | } else if(a[l] > 0 && a[r] > 0) { 13 | r--; 14 | } else { 15 | r--; 16 | l++; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DynamicProgramming/BottomUp/knapsackProblem.java: -------------------------------------------------------------------------------- 1 | static int knapsack(int[] w, int[] v, int weight) { 2 | int n = w.length; 3 | int[][] dp = new int[n + 1][weight + 1]; 4 | for(int i=1;i<=n;i++) { 5 | for(int j=1;j<=weight;j++) { 6 | if(w[i - 1] <= j) { 7 | dp[i][j] = Math.max((v[i - 1] + dp[i - 1][j - w[i - 1]]), dp[i - 1][j]); 8 | } else { 9 | dp[i][j] = dp[i - 1][j]; 10 | } 11 | } 12 | } 13 | return dp[n][weight]; 14 | } 15 | -------------------------------------------------------------------------------- /Graph/DFSDisconnected.java: -------------------------------------------------------------------------------- 1 | static void DFS(List> adj, int source, boolean[] visited) { 2 | visited[source] = true; 3 | System.out.print(source + " "); 4 | for(int u : adj.get(source)) { 5 | if(!visited[u]) { 6 | DFS(adj, u, visited); 7 | } 8 | } 9 | } 10 | 11 | static void DFS(List> adj, int n) { 12 | boolean[] visited = new boolean[n]; 13 | for(int i=0;i(), 0); 3 | } 4 | 5 | static void combination(int[] a, int k, HashSet set, int start) { 6 | if(set.size() == k) { 7 | System.out.println(set); 8 | return; 9 | } 10 | if(start == a.length) return; 11 | for(int i=start;i x) { 10 | high = mid - 1; 11 | } 12 | else { 13 | low = mid + 1; 14 | } 15 | } 16 | return -1; 17 | } 18 | -------------------------------------------------------------------------------- /Backtracking/combinationOfKElements.java: -------------------------------------------------------------------------------- 1 | static void combination(int[] a, int k) { 2 | combination(a, k, new HashSet(), 0); 3 | } 4 | 5 | static void combination(int[] a, int k, HashSet set, int start) { 6 | if(set.size() == k) { 7 | System.out.println(set); 8 | return; 9 | } 10 | if(start == a.length) return; 11 | for(int i=start;i map = new HashMap<>(); 3 | for(int i : arr) { 4 | if(map.get(i) != null) { 5 | map.put(i, map.get(i) + 1); 6 | } else { 7 | map.put(i, 1); 8 | } 9 | } 10 | int count = 0; 11 | for(Map.Entry e : map.entrySet()) { 12 | if(e.getValue() == 1) count++; 13 | } 14 | return count; 15 | } 16 | -------------------------------------------------------------------------------- /Arrays/removeDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | public static int removeDuplicateFromSortedArray(int[] a, int n) { 2 | int[] temp = new int[n]; 3 | temp[0] = a[0]; 4 | int res = 1; 5 | for(int i = 1; i < n; i++) { 6 | if(temp[res - 1] != a[i]) { 7 | temp[res] = a[i]; 8 | res++; 9 | } 10 | } 11 | for(int i = 0; i < res; i++) { 12 | a[i] = temp[i]; 13 | } 14 | return res; 15 | } 16 | -------------------------------------------------------------------------------- /String/panagramCheck.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string s. You need to find if the string is a panagram or not. 3 | A panagram contains all the letters of english alphabet at least once. 4 | */ 5 | 6 | public static boolean isPanagram(String str) { 7 | String s = str.toLowerCase(); 8 | int[] ch = new int[26]; 9 | for(int i=0;i> adj, int n, int source) { 2 | boolean[] visited = new boolean[n + 1]; 3 | Queue q = new LinkedList<>(); 4 | visited[source] = true; 5 | q.add(source); 6 | while(!q.isEmpty()) { 7 | int u = q.poll(); 8 | System.out.print(u + " "); 9 | for(int v: adj.get(u)) { 10 | if(!visited[v]) { 11 | visited[v] = true; 12 | q.add(v); 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Arrays/insertion.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | I/P : a[] = {5, 10, 20, _, _} 4 | 5 | element = 7 6 | pos = 2 7 | 8 | O/P : a[] = {5, 7, 10, 20, _} 9 | 10 | */ 11 | 12 | 13 | public static int insert(int[] a, int size, int element, int pos, int capacity) { 14 | if(size == capacity) 15 | return size; 16 | int idx = pos - 1; 17 | for(int i = size - 1; i >= idx; i--) { 18 | a[i + 1] = a[i]; 19 | } 20 | a[idx] = element; 21 | return size + 1; 22 | } 23 | -------------------------------------------------------------------------------- /Backtracking/generateParentheses.java: -------------------------------------------------------------------------------- 1 | public static List generateParenthesis(int n) { 2 | List ans = new ArrayList<>(); 3 | backtrack(ans, "", 0, 0, n); 4 | return ans; 5 | } 6 | 7 | public static void backtrack(List ans, String curr, int open, int close, int max) { 8 | if(curr.length() == 2 * max) { 9 | ans.add(curr); 10 | return; 11 | } 12 | if(open < max) backtrack(ans, curr + "(", open + 1, close, max); 13 | if(close < open) backtrack(ans, curr + ")", open , close + 1, max); 14 | } 15 | -------------------------------------------------------------------------------- /Queue/TwoStackQueue.java: -------------------------------------------------------------------------------- 1 | class StackQueue { 2 | Stack s1 = new Stack(); 3 | Stack s2 = new Stack(); 4 | 5 | /* The method insert to push element 6 | into the queue */ 7 | void Push(int x) { 8 | s1.push(x); 9 | } 10 | 11 | 12 | /* The method remove which return the 13 | element popped out of the queue*/ 14 | int Pop() { 15 | if(s1.isEmpty() && s2.isEmpty()) return -1; 16 | if(s2.isEmpty()) { 17 | while(!s1.isEmpty()) s2.push(s1.pop()); 18 | } 19 | return s2.pop(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Arrays/nextPermutaion.java: -------------------------------------------------------------------------------- 1 | static void nextPermutation(int[] a) { 2 | if(a == null || a.length == 1) return; 3 | int i = a.length - 2; 4 | while(i >= 0 && a[i] >= a[i + 1]) i--; 5 | if(i >= 0) { 6 | int j = a.length - 1; 7 | while(a[j] <= a[i]) j--; 8 | swap(a, i, j); 9 | } 10 | reverse(a, i + 1, a.length - 1); 11 | } 12 | 13 | static void swap(int[] a, int i, int j) { 14 | int temp = a[i]; 15 | a[i] = a[j]; 16 | a[j] = temp; 17 | } 18 | 19 | static void reverse(int[] a, int start, int end) { 20 | while(start < end) swap(a, start++, end--); 21 | } 22 | -------------------------------------------------------------------------------- /Arrays/allPermutationOfArray.java: -------------------------------------------------------------------------------- 1 | static void permutation(int[] a) { 2 | permutation(a, new ArrayList(), new boolean[a.length]); 3 | } 4 | 5 | static void permutation(int[] a, ArrayList partial, boolean[] used) { 6 | if(partial.size() == a.length) { 7 | System.out.println(Arrays.toString(partial.toArray())); 8 | return; 9 | } 10 | for(int i=0;i(), new boolean[a.length]); 3 | } 4 | 5 | static void permutation(int[] a, ArrayList partial, boolean[] used) { 6 | if(partial.size() == a.length) { 7 | System.out.println(Arrays.toString(partial.toArray())); 8 | return; 9 | } 10 | for(int i=0;i high) return -1; 7 | int mid = (low + high) / 2; 8 | if(a[mid] == x) { 9 | if(mid != 0 && a[mid - 1] == x) return binarySearchFirstOccurence(a, x, low, mid - 1); 10 | return mid; 11 | } 12 | else if(a[mid] > x) return binarySearchFirstOccurence(a, x, low, mid - 1); 13 | else return binarySearchFirstOccurence(a, x, mid + 1, high); 14 | } 15 | -------------------------------------------------------------------------------- /Sorting/quickSort.java: -------------------------------------------------------------------------------- 1 | static void swap(int[] a, int i, int j) { 2 | int temp = a[i]; 3 | a[i] = a[j]; 4 | a[j] = temp; 5 | } 6 | 7 | static int partition(int[] a, int l, int r) { 8 | int pivot = a[r]; 9 | int i = l - 1; 10 | for(int j=l;j(), 0); 4 | } 5 | 6 | static void combinationSum(int[] a, int target, int sum, List partial, int start) { 7 | if(sum == target) { 8 | System.out.println(Arrays.toString(partial.toArray())); 9 | return; 10 | } 11 | for(int i=start;i target || i > start && a[i - 1] == a[i]) { 14 | continue; 15 | } 16 | partial.add(c); 17 | combinationSum(a, target, sum + c, partial, i + 1); 18 | partial.remove(partial.size() - 1); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Backtracking/printAnagrams.java: -------------------------------------------------------------------------------- 1 | static void printAnagrams(String s) { 2 | printAnagrams(s, new StringBuilder(), new boolean[s.length()]); 3 | } 4 | 5 | static void printAnagrams(String s, StringBuilder partial, boolean[] used) { 6 | if(partial.length() == s.length()) { 7 | System.out.println(partial.toString()); 8 | return; 9 | } 10 | for(int i=0;i 0){ 18 | partial.deleteCharAt(partial.length() - 1); 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /String/missingPanagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string s. You need to find the missing characters in the string to make a panagram. 3 | Note: The output characters will be lowercase and lexicographically sorted. 4 | */ 5 | 6 | public static String missingPanagram(String str) { 7 | String s = str.toLowerCase(); 8 | int[] ch = new int[26]; 9 | for(int i=0;i stack = new ArrayDeque<>(); 3 | for(int i=0;i> adj, int source, boolean[] visited) { 2 | Queue q = new LinkedList<>(); 3 | visited[source] = true; 4 | q.add(source); 5 | while(!q.isEmpty()) { 6 | int u = q.poll(); 7 | System.out.print(u + " "); 8 | for(int v: adj.get(u)) { 9 | if(!visited[v]) { 10 | visited[v] = true; 11 | q.add(v); 12 | } 13 | } 14 | } 15 | } 16 | 17 | static void BFSDisconnected(List> adj, int n) { 18 | boolean[] visited = new boolean[n + 1]; 19 | for(int i=0;i stack = new Stack<>(); 3 | for(int i=0;i> adj, int source, boolean[] visited) { 2 | Queue q = new LinkedList<>(); 3 | visited[source] = true; 4 | q.add(source); 5 | while(!q.isEmpty()) { 6 | int u = q.poll(); 7 | for(int v: adj.get(u)) { 8 | if(!visited[v]) { 9 | visited[v] = true; 10 | q.add(v); 11 | } 12 | } 13 | } 14 | } 15 | 16 | static int CountConnected(List> adj, int n) { 17 | int count = 0; 18 | boolean[] visited = new boolean[n + 1]; 19 | for(int i=0;i dict) { 13 | wordBreak(s, dict, new ArrayList()); 14 | } 15 | 16 | private static void wordBreak(String s, Set dict, ArrayList partial) { 17 | if(s.length() == 0) { 18 | System.out.println(Arrays.toString(partial.toArray())); 19 | return; 20 | } 21 | for(int i=0;i x) { 6 | root.left = deleteNode(root.left, x); 7 | } else { 8 | if(root.left == null) return root.right; 9 | else if(root.right == null) return root.right; 10 | else { 11 | Node succ = getSuccessor(root); 12 | root.data = succ.data; 13 | root.right = deleteNode(root.right, succ.data); 14 | } 15 | } 16 | return root; 17 | } 18 | 19 | static Node getSuccessor(Node root) { 20 | Node curr = root.right; 21 | while(curr != null && curr.left != null) { 22 | curr = curr.left; 23 | } 24 | return curr; 25 | } 26 | -------------------------------------------------------------------------------- /Searching/majorityElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an array A of N elements. 4 | Find the majority element in the array. 5 | A majority element in an array A of size N is an element that appears more than N/2 times in the array. 6 | 7 | */ 8 | 9 | 10 | static int majorityElement(int a[], int size) { 11 | int majIndex = 0, count = 1; 12 | for(int i=1;i size / 2) return a[majIndex]; 29 | else return -1; 30 | } 31 | -------------------------------------------------------------------------------- /Arrays/rowsWithMaxOnes.java: -------------------------------------------------------------------------------- 1 | int rowWithMax1s(int arr[][], int n, int m) { 2 | int maxOne = -1, index = -1; 3 | for(int i=0;i maxOne) { 8 | maxOne = oneCount; 9 | index = i; 10 | } 11 | } 12 | return index; 13 | } 14 | 15 | int firstOne(int[] a) { 16 | int low = 0, high = a.length - 1; 17 | while(low <= high) { 18 | int mid = (low + high) / 2; 19 | if(a[mid] == 1) { 20 | if(mid == 0 || a[mid - 1] != 1) return mid; 21 | else high = mid - 1; 22 | } else { 23 | low = mid + 1; 24 | } 25 | } 26 | return -1; 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/setMatrixZeroes.java: -------------------------------------------------------------------------------- 1 | static void setZeroes(int[][] a) { 2 | boolean isCol = false; 3 | for(int i=0;i l) { 7 | int m = l + (r - l) / 2; 8 | mergeSort(a, l, m); 9 | mergeSort(a, m + 1, r); 10 | merge(a, l, r, m); 11 | } 12 | } 13 | 14 | static void merge(int[] a, int l, int r, int m) { 15 | int[] left = new int[m - l + 1]; 16 | int[] right = new int[r - m]; 17 | for(int i=0;i down) break; 16 | for(int i=right;i>=left;i--) { 17 | System.out.print(a[down][i] + " "); 18 | } 19 | down--; 20 | if(right < left) break; 21 | for(int i=down;i>=top;i--) { 22 | System.out.print(a[i][left] + " "); 23 | } 24 | left++; 25 | } 26 | return res; 27 | } 28 | -------------------------------------------------------------------------------- /DynamicProgramming/TopDown/knapsackProblem.java: -------------------------------------------------------------------------------- 1 | static int knapsack(int[] w, int[] v, int weight) { 2 | int[][] dp = new int[weight + 1][w.length + 1]; 3 | for(int i=0;i<=weight;i++) { 4 | for(int j=0;j<=w.length;j++) { 5 | dp[i][j] = -1; 6 | } 7 | } 8 | return knapsack(w, v, weight, w.length - 1, dp); 9 | } 10 | 11 | static int knapsack(int[] w, int[] v, int weight, int i, int[][] dp) { 12 | if(i == -1 || weight == 0) return 0; 13 | if(dp[weight][i] != -1) return dp[weight][i]; 14 | if(w[i] <= weight) { 15 | int include = v[i] + knapsack(w, v, weight - w[i], i - 1, dp); 16 | int exclude = knapsack(w, v, weight, i - 1, dp); 17 | dp[weight][i] = Math.max(include, exclude); 18 | return dp[weight][i]; 19 | } else { 20 | dp[weight][i] = knapsack(w, v, weight, i - 1, dp); 21 | return dp[weight][i]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /BinaryHeap/HeapSort.java: -------------------------------------------------------------------------------- 1 | class HeapSort { 2 | 3 | public static void sort(int[] a) { 4 | int n = a.length; 5 | for(int i=(n-1)/2;i>=0;i--) { 6 | heapify(a, n, i); 7 | } 8 | for(int i=n-1;i>0;i--) { 9 | int temp = a[0]; 10 | a[0] = a[i]; 11 | a[i] = temp; 12 | heapify(a, i, 0); 13 | } 14 | } 15 | 16 | public static void heapify(int[] a, int n, int i) { 17 | int largest = i; 18 | int l = 2 * i + 1; 19 | int r = 2 * i + 2; 20 | if(l < n && a[largest] < a[l]) largest = l; 21 | if(r < n && a[largest] < a[r]) largest = r; 22 | if(largest != i) { 23 | int temp = a[i]; 24 | a[i] = a[largest]; 25 | a[largest] = temp; 26 | heapify(a, n, largest); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /DisjointSet/DisjointSet.java: -------------------------------------------------------------------------------- 1 | class DisjointSet { 2 | int[] parent; 3 | int[] rank; 4 | 5 | DisjointSet(int n) { 6 | parent = new int[n]; 7 | rank = new int[n]; 8 | for(int i = 0; i < n; i++) { 9 | parent[i] = i; 10 | } 11 | } 12 | 13 | int findParent(int v) { 14 | if(v == parent[v]) { 15 | return v; 16 | } 17 | return parent[v] = findParent(parent[v]); 18 | } 19 | 20 | void union(int u, int v) { 21 | u = findParent(u); 22 | v = findParent(v); 23 | if(u != v) { 24 | if(rank[u] < rank[v]) { 25 | parent[u] = v; 26 | } else if(rank[u] > rank[v]) { 27 | parent[v] = u; 28 | } else { 29 | parent[u] = v; 30 | rank[v]++; 31 | } 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Arrays/largeFactorial.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public String solve(int A) { 4 | int[] res = new int[500]; 5 | int resSize = 1; 6 | res[0] = 1; 7 | for(int i = 2; i <= A; i++) { 8 | resSize = multiply(i, res, resSize); 9 | } 10 | StringBuilder factorial = new StringBuilder(); 11 | for(int i = resSize - 1; i >= 0; i--) { 12 | factorial.append(res[i]); 13 | } 14 | return factorial.toString(); 15 | } 16 | 17 | int multiply(int x, int[] res, int resSize) { 18 | int carry = 0; 19 | for(int i = 0; i < resSize; i++) { 20 | int prod = res[i] * x + carry; 21 | res[i] = prod % 10; 22 | carry = prod / 10; 23 | } 24 | while(carry != 0) { 25 | res[resSize] = carry % 10; 26 | carry /= 10; 27 | resSize++; 28 | } 29 | return resSize; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BinaryTree/topView.java: -------------------------------------------------------------------------------- 1 | static class QueueObj{ 2 | Node node; 3 | int hd; 4 | QueueObj(Node node, int hd) { 5 | this.node = node; 6 | this.hd = hd; 7 | } 8 | } 9 | 10 | static void topView(Node root) { 11 | Queue q = new LinkedList<>(); 12 | Map map = new TreeMap<>(); 13 | if (root == null) { 14 | return; 15 | } else { 16 | q.add(new QueueObj(root, 0)); 17 | } 18 | while(!q.isEmpty()) { 19 | QueueObj temp = q.poll(); 20 | if(!map.containsKey(temp.hd)) { 21 | map.put(temp.hd, temp.node); 22 | } 23 | if(temp.node.left != null) { 24 | q.add(new QueueObj(temp.node.left, temp.hd - 1)); 25 | } 26 | if(temp.node.right != null) { 27 | q.add(new QueueObj(temp.node.right, temp.hd + 1)); 28 | } 29 | } 30 | for(Map.Entry e : map.entrySet()) { 31 | System.out.print(e.getValue().data + " "); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Graph/topologicalSortDFS.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | //Function to return list containing vertices in Topological order. 4 | static int[] topoSort(int V, ArrayList> adj) { 5 | boolean[] visited = new boolean[V]; 6 | Stack stack = new Stack<>(); 7 | for(int i = 0; i < V; i++) { 8 | if(!visited[i]) { 9 | dfs(adj, i, stack, visited); 10 | } 11 | } 12 | int[] topoSort = new int[stack.size()]; 13 | int i = 0; 14 | while(!stack.isEmpty()) { 15 | topoSort[i++] = stack.pop(); 16 | } 17 | return topoSort; 18 | } 19 | 20 | static void dfs(ArrayList> adj, int source, Stack stack, boolean[] visited) { 21 | visited[source] = true; 22 | for(int i : adj.get(source)) { 23 | if(!visited[i]) { 24 | dfs(adj, i, stack, visited); 25 | } 26 | } 27 | stack.push(source); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Graph/AdjacencyList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class AdjacencyList { 4 | 5 | static void addEdge(ArrayList> adj, int u, int v) { 6 | adj.get(u).add(v); 7 | adj.get(v).add(u); 8 | } 9 | 10 | static void printGraph(ArrayList> adj, int v) { 11 | for(int i=0;i> adj = new ArrayList<>(); 22 | for(int i=0;i()); 24 | } 25 | addEdge(adj, 0, 1); 26 | addEdge(adj, 0, 2); 27 | addEdge(adj, 1, 2); 28 | addEdge(adj, 1, 3); 29 | printGraph(adj, v); 30 | } 31 | } 32 | 33 | /* 34 | 35 | Graph: 36 | 37 | [0] ------- [1] ------ [3] 38 | \ / 39 | \ / 40 | \ / 41 | [2] 42 | 43 | */ 44 | -------------------------------------------------------------------------------- /Stack/infixToPostfix.java: -------------------------------------------------------------------------------- 1 | public static String infixToPostfix(String exp) { 2 | Stack st = new Stack<>(); 3 | StringBuilder res = new StringBuilder(); 4 | for(int i=0;i maxset(ArrayList A) { 18 | ArrayList res = new ArrayList<>(); 19 | 20 | long sum = 0; 21 | long maxSum = 0; 22 | int left = 0, right = 0, savedLeft = -1, savedRight = -1; 23 | 24 | for(int i = 0; i < A.size(); i++) { 25 | if(A.get(i) >= 0) { 26 | sum += A.get(i); 27 | if(sum > maxSum || (sum == maxSum && savedRight - savedLeft < right - left)) { 28 | maxSum = sum; 29 | savedLeft = left; 30 | savedRight = right; 31 | } 32 | } else { 33 | left = i + 1; 34 | sum = 0; 35 | } 36 | right++; 37 | } 38 | if(savedLeft == -1) return res; 39 | for(int i = savedLeft; i <= savedRight; i++) { 40 | res.add(A.get(i)); 41 | } 42 | return res; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LinkedList/CircularLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class CircularLinkedList { 3 | 4 | static class Node { 5 | E data; 6 | Node next; 7 | 8 | public Node(E data) { 9 | this.data = data; 10 | this.next = null; 11 | } 12 | } 13 | 14 | private Node head = null; 15 | private Node tail = null; 16 | 17 | void addFirst(E data) { 18 | Node newNode = new Node(data); 19 | if(head == null) { 20 | newNode.next = newNode; 21 | head = newNode; 22 | tail = newNode; 23 | return; 24 | } 25 | tail.next = newNode; 26 | newNode.next = head; 27 | head = newNode; 28 | } 29 | 30 | void addLast(E data) { 31 | Node newNode = new Node(data); 32 | if(head == null) { 33 | newNode.next = newNode; 34 | head = newNode; 35 | tail = newNode; 36 | return; 37 | } 38 | tail.next = newNode; 39 | newNode.next = head; 40 | tail = newNode; 41 | } 42 | 43 | void deleteFirst() { 44 | if(head == null) return; 45 | tail.next = head.next; 46 | head = head.next; 47 | } 48 | 49 | void deleteKthNode(int k) { 50 | if(head == null) return; 51 | if(k == 1) { 52 | head.data = head.next.data; 53 | head.next = head.next.next; 54 | return; 55 | } 56 | Node curr = head; 57 | for(int i=0;i curr = head; 66 | do { 67 | System.out.print(curr.data + " "); 68 | curr = curr.next; 69 | } while(curr != head); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /DynamicProgramming/TopDown/paintingHousesProblem.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | There is a row of N houses, each house can be painted with one of the 3 colors: RED, BLUE, GREEN. The cost of painting each house with a certain color is different. 4 | You have to paint all houses such that no adjacent houses have the same color. Find the minimum cost of painting all houses. 5 | 6 | */ 7 | 8 | 9 | static final int RED = 0, BLUE = 1, GREEN = 2; 10 | 11 | static int minCost(int[][] cost) { 12 | int[][] dp = new int[cost.length][cost[0].length]; 13 | for(int[] row : dp) { 14 | Arrays.fill(row, -1); 15 | } 16 | int costRed = minCost(cost, 0, RED, dp); 17 | int costBlue = minCost(cost, 0, BLUE, dp); 18 | int costGreen = minCost(cost, 0, GREEN, dp); 19 | return Math.min(costRed, Math.min(costBlue, costGreen)); 20 | } 21 | 22 | static int minCost(int[][] cost, int i, int color, int[][] dp) { 23 | if(i == cost.length) return 0; 24 | if(dp[i][color] != -1) { 25 | return dp[i][color]; 26 | } 27 | switch(color) { 28 | case RED: { 29 | int costBlue = minCost(cost, i + 1, BLUE, dp); 30 | int costGreen = minCost(cost, i + 1, GREEN, dp); 31 | return dp[i][color] = cost[i][RED] + Math.min(costGreen, costBlue); 32 | } 33 | case BLUE: { 34 | int costRed = minCost(cost, i + 1, RED, dp); 35 | int costGreen = minCost(cost, i + 1, GREEN, dp); 36 | return dp[i][color] = cost[i][RED] + Math.min(costGreen, costRed); 37 | } 38 | case GREEN: { 39 | int costRed = minCost(cost, i + 1, RED, dp); 40 | int costBlue = minCost(cost, i + 1, BLUE, dp); 41 | return dp[i][color] = cost[i][RED] + Math.min(costBlue, costRed); 42 | } 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Trie/Trie.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | Node[] links; 3 | boolean end; 4 | 5 | public Node() { 6 | links = new Node[26]; 7 | end = false; 8 | } 9 | 10 | public boolean containsKey(char c) { 11 | return (links[c - 'a'] != null); 12 | } 13 | 14 | public Node get(char c) { 15 | return links[c - 'a']; 16 | } 17 | 18 | public void put(char c, Node node) { 19 | links[c - 'a'] = node; 20 | } 21 | 22 | public void setEnd() { 23 | end = true; 24 | } 25 | 26 | public boolean isEnd() { 27 | return end; 28 | } 29 | } 30 | 31 | class Trie { 32 | 33 | Node root; 34 | 35 | public Trie() { 36 | root = new Node(); 37 | } 38 | 39 | public void insert(String word) { 40 | Node curr = root; 41 | for(int i = 0; i < word.length(); i++) { 42 | char c = word.charAt(i); 43 | if(!curr.containsKey(c)) { 44 | curr.put(c, new Node()); 45 | } 46 | curr = curr.get(c); 47 | } 48 | curr.setEnd(); 49 | } 50 | 51 | public boolean search(String word) { 52 | Node curr = root; 53 | for(int i = 0; i < word.length(); i++) { 54 | char c = word.charAt(i); 55 | if(!curr.containsKey(c)) return false; 56 | curr = curr.get(c); 57 | } 58 | return curr.isEnd(); 59 | } 60 | 61 | public boolean startsWith(String prefix) { 62 | Node curr = root; 63 | for(int i = 0; i < prefix.length(); i++) { 64 | char c = prefix.charAt(i); 65 | if(!curr.containsKey(c)) return false; 66 | curr = curr.get(c); 67 | } 68 | return true; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /LinkedList/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class DoublyLinkedList { 2 | 3 | static class Node { 4 | E data; 5 | Node next, prev; 6 | Node(E data) { 7 | this.data = data; 8 | this.next = null; 9 | this.prev = null; 10 | } 11 | } 12 | 13 | private Node head = null; 14 | 15 | void addFirst(E data) { 16 | Node newNode = new Node(data); 17 | if(head == null) { 18 | head = newNode; 19 | return; 20 | } 21 | newNode.next = head; 22 | head.prev = newNode; 23 | head = newNode; 24 | } 25 | 26 | void addLast(E data) { 27 | Node newNode = new Node(data); 28 | if(head == null) { 29 | head = newNode; 30 | return; 31 | } 32 | Node temp = head; 33 | while(temp.next != null) { 34 | temp = temp.next; 35 | } 36 | temp.next = newNode; 37 | newNode.prev = temp; 38 | } 39 | 40 | void reverse() { 41 | if(head == null || head.next == null) return; 42 | Node prev = null, curr = head; 43 | while(curr != null) { 44 | prev = curr.prev; 45 | curr.prev = curr.next; 46 | curr.next = prev; 47 | curr = curr.prev; 48 | } 49 | head = prev.prev; 50 | } 51 | 52 | void deleteFirst() { 53 | if(head == null) return; 54 | if(head.next == null) { 55 | head = null; 56 | return; 57 | } 58 | head = head.next; 59 | head.prev = null; 60 | } 61 | 62 | void deleteLast() { 63 | if(head == null) return; 64 | if(head.next == null) { 65 | head = null; 66 | return; 67 | } 68 | Node temp = head; 69 | while(temp.next != null) { 70 | temp = temp.next; 71 | } 72 | temp.prev.next = null; 73 | } 74 | 75 | void printList() { 76 | if(head == null) return; 77 | Node temp = head; 78 | while(temp != null) { 79 | System.out.print(temp.data + " "); 80 | temp = temp.next; 81 | } 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /BinaryHeap/MinHeap.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MinHeap { 4 | 5 | private int capacity; 6 | private int size; 7 | private int[] a; 8 | 9 | public MinHeap(int capacity) { 10 | this.capacity = capacity; 11 | this.size = 0; 12 | this.a = new int[capacity]; 13 | } 14 | 15 | private int leftChildIndex(int i) { 16 | return 2 * i + 1; 17 | } 18 | 19 | private int rightChildIndex(int i) { 20 | return 2 * i + 2; 21 | } 22 | 23 | private int parentIndex(int i) { 24 | return (i - 1) / 2; 25 | } 26 | 27 | private boolean hasLeft(int i) { 28 | return leftChildIndex(i) < size; 29 | } 30 | 31 | private boolean hasRight(int i) { 32 | return rightChildIndex(i) < size; 33 | } 34 | 35 | private boolean hasParent(int i) { 36 | return parentIndex(i) >= 0; 37 | } 38 | 39 | private int leftChild(int i) { 40 | return a[leftChildIndex(i)]; 41 | } 42 | 43 | private int rightChild(int i) { 44 | return a[rightChildIndex(i)]; 45 | } 46 | 47 | private int parent(int i) { 48 | return a[parentIndex(i)]; 49 | } 50 | 51 | private void swap(int i, int j) { 52 | int temp = a[i]; 53 | a[i] = a[j]; 54 | a[j] = temp; 55 | } 56 | 57 | private void ensureCapacity() { 58 | if(size == capacity) { 59 | a = Arrays.copyOf(a, capacity * 2); 60 | capacity *= 2; 61 | } 62 | } 63 | 64 | public int peek() { 65 | if(size == 0) throw new IllegalStateException(); 66 | return a[0]; 67 | } 68 | 69 | public int poll() { 70 | if(size == 0) throw new IllegalStateException(); 71 | int item = a[0]; 72 | a[0] = a[size - 1]; 73 | size--; 74 | heapifyDown(); 75 | return item; 76 | } 77 | 78 | public void add(int x) { 79 | ensureCapacity(); 80 | a[size++] = x; 81 | heapifyUp(); 82 | } 83 | 84 | private void heapifyUp() { 85 | int index = size - 1; 86 | while(hasParent(index) && a[index] < parent(index)) { 87 | swap(index, parentIndex(index)); 88 | index = parentIndex(index); 89 | } 90 | } 91 | 92 | private void heapifyDown() { 93 | int index = 0; 94 | while(hasLeft(index)) { 95 | int minChildIndex = leftChildIndex(index); 96 | if(hasRight(index) && rightChild(index) < leftChild(index)) { 97 | minChildIndex = rightChildIndex(index); 98 | } 99 | if(a[index] < a[minChildIndex]) { 100 | break; 101 | } else { 102 | swap(index, minChildIndex); 103 | } 104 | index = minChildIndex; 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /Graph/Kruskals.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | import java.util.Scanner; 4 | 5 | public class Kruskals { 6 | 7 | static class Edge { 8 | int source; 9 | int dest; 10 | int weight; 11 | 12 | public Edge(int s, int d, int w) { 13 | this.source = s; 14 | this.dest = d; 15 | this.weight = w; 16 | } 17 | } 18 | 19 | // Union-Find Algorithm. 20 | static int findParent(int v, int[] parent) { 21 | if(parent[v] == v) { 22 | return v; 23 | } 24 | return findParent(parent[v], parent); 25 | } 26 | 27 | static void kruskals(Edge[] input, int n, int E) { 28 | // Sort the edges in ascending order of Weights. 29 | Arrays.sort(input, Comparator.comparingInt(o -> o.weight)); 30 | 31 | Edge[] output = new Edge[n - 1]; 32 | 33 | // Array for Union-Find Cycle Detection Algorithm. 34 | int[] parent = new int[n]; 35 | for(int i = 0; i < n; i++) { 36 | parent[i] = i; 37 | } 38 | 39 | int count = 0; 40 | int i = 0; 41 | 42 | while(count != n - 1) { 43 | Edge currentEdge = input[i]; 44 | 45 | // Use Union-Find Algorithm for detecting cycle in a graph. 46 | int sourceParent = findParent(currentEdge.source, parent); 47 | int destParent = findParent(currentEdge.dest, parent); 48 | 49 | // Add current graph into the output only if it does not create a cycle. 50 | if(sourceParent != destParent) { 51 | output[count] = currentEdge; 52 | count++; 53 | parent[sourceParent] = destParent; 54 | } 55 | i++; 56 | } 57 | 58 | // Print the edges of the MST. 59 | for(i = 0; i < n - 1; i++) { 60 | if(output[i].source < output[i].dest) { 61 | System.out.println(output[i].source + " " + output[i].dest + " " + output[i].weight); 62 | } else { 63 | System.out.println(output[i].dest + " " + output[i].source + " " + output[i].weight); 64 | } 65 | } 66 | } 67 | 68 | public static void main(String[] args) { 69 | Scanner sc = new Scanner(System.in); 70 | int n = sc.nextInt(); 71 | int E = sc.nextInt(); 72 | 73 | Edge[] input = new Edge[E]; 74 | 75 | for (int i = 0; i < E; i++) { 76 | int s = sc.nextInt(); 77 | int d = sc.nextInt(); 78 | int w = sc.nextInt(); 79 | input[i] = new Edge(s, d, w); 80 | } 81 | 82 | kruskals(input, n, E); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /LinkedList/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class SinglyLinkedList { 3 | 4 | static class Node { 5 | E data; 6 | Node next; 7 | 8 | public Node(E data) { 9 | this.data = data; 10 | this.next = null; 11 | } 12 | } 13 | 14 | private Node head = null; 15 | 16 | // Check if the linked list is empty. 17 | boolean isEmpty() { 18 | return head == null; 19 | } 20 | 21 | // Return the size of the list. 22 | int size() { 23 | if (this.isEmpty()) 24 | return 0; 25 | int count = 0; 26 | Node temp = head; 27 | while (temp != null) { 28 | temp = temp.next; 29 | count++; 30 | } 31 | return count; 32 | } 33 | 34 | // Add an element in the end. 35 | void add(E data) { 36 | if (this.isEmpty()) { 37 | this.addFirst(data); 38 | return; 39 | } 40 | this.addLast(data); 41 | } 42 | 43 | // Add an element in the beginning. 44 | void addFirst(E data) { 45 | Node newNode = new Node(data); 46 | if (this.isEmpty()) { 47 | head = newNode; 48 | return; 49 | } 50 | newNode.next = head; 51 | head = newNode; 52 | } 53 | 54 | // Add an element in the end. 55 | void addLast(E data) { 56 | Node newNode = new Node(data); 57 | if (this.isEmpty()) { 58 | this.addFirst(data); 59 | return; 60 | } 61 | Node temp = head; 62 | while (temp.next != null) { 63 | temp = temp.next; 64 | } 65 | temp.next = newNode; 66 | } 67 | 68 | // Insert at a given index. 69 | void insert(int index, E data) { 70 | if (isEmpty() || this.size() <= index) { 71 | throw new IndexOutOfBoundsException("Index " + index + " out of bounds"); 72 | } 73 | Node temp = head; 74 | Node newNode = new Node(data); 75 | for (int i = 0; i < index - 1; i++) { 76 | temp = temp.next; 77 | } 78 | newNode.next = temp.next; 79 | temp.next = newNode; 80 | } 81 | 82 | // Delete the last element from the linked list. 83 | void deleteLast() { 84 | if (this.isEmpty()) 85 | return; 86 | Node temp = head; 87 | while (temp.next.next != null) { 88 | temp = temp.next; 89 | } 90 | temp.next = null; 91 | } 92 | 93 | // Delete the first element from the linked list. 94 | void deleteFirst() { 95 | if (this.isEmpty()) 96 | return; 97 | head = head.next; 98 | } 99 | 100 | // Print the linked list. 101 | void printList() { 102 | if (this.isEmpty()) 103 | return; 104 | Node temp = head; 105 | while (temp != null) { 106 | System.out.print(temp.data + " "); 107 | temp = temp.next; 108 | } 109 | } 110 | 111 | // Search for an element in the list. 112 | boolean linearSearch(E data) { 113 | if (this.isEmpty()) 114 | return false; 115 | Node temp = head; 116 | while (temp != null) { 117 | if (temp.data == data) 118 | return true; 119 | temp = temp.next; 120 | } 121 | return false; 122 | } 123 | 124 | // Return the middle element of the list. 125 | E getMiddleElement() { 126 | if(this.isEmpty()) 127 | return null; 128 | Node slow = head, fast = head; 129 | while(fast != null && fast.next != null) { 130 | slow = slow.next; 131 | fast = fast.next.next; 132 | } 133 | return slow.data; 134 | } 135 | 136 | // Return nTh node from the end. 137 | E getNthNodeFromEnd(int n) { 138 | if(this.isEmpty()) 139 | return null; 140 | Node first = head, second = head; 141 | for(int i=0;i curr = head; 155 | Node prev = null; 156 | while(curr != null) { 157 | Node next = curr.next; 158 | curr.next = prev; 159 | prev = curr; 160 | curr = next; 161 | } 162 | head = prev; 163 | } 164 | 165 | // Given a sorted linked list, Remove all duplicates. 166 | void removeDuplicatesFromSorted() { 167 | if(this.isEmpty()) 168 | return; 169 | Node curr = head; 170 | while(curr != null && curr.next != null) { 171 | if(curr.data == curr.next.data) { 172 | curr.next = curr.next.next; 173 | } else { 174 | curr = curr.next; 175 | } 176 | } 177 | } 178 | 179 | // Delete node at given index 180 | void delete(int pos) { 181 | if(this.isEmpty()) 182 | return; 183 | if(pos == 1) { 184 | head = head.next; 185 | return; 186 | } 187 | Node temp = head; 188 | for(int i=0;i