├── .gitignore ├── AndQueries.java ├── Armstrong.java ├── ArrayList.java ├── AutomorphicNumber.java ├── BellmanFordAlgoImplement.java ├── BinarySearchExample.java ├── BinarySearchTree.java ├── BooleanMatrix.java ├── BubbleSort.java ├── Bubble_sort.java ├── CONTRIBUTING.md ├── CalculateNthFibonacciNumber ├── CatalanNumbers.java ├── CeaserCipher.java ├── Check_Digit_Code.java ├── Check_Even_Fibonacci.java ├── CocktailSort.java ├── ColumnNameForGivenColumnNumber.java ├── ColumnNameFromGivenColumnNumber.java ├── CountingSort.java ├── Currency_Converter.java ├── Custom HashMap Implementation.java ├── Dijkstra's Shortest Path Algorithm.java ├── DijkstraAlgorithm.java ├── DijkstraShortestPath.java ├── EmailMasker.java ├── EmailMaskerOptimised.java ├── EvenOdd.java ├── FibonacciSeries.java ├── FindTotalNumberOfNodesInBST.java ├── FloodFillAlgorithm.java ├── FloydWarshall.java ├── Goldbach.java ├── Hanoi1.java ├── Hanoi2.java ├── HeapSort.java ├── InsertionSort ├── JAVA SOLUTION ├── Circularlinkedlist.java ├── DoublyLinkedLists.java ├── LongesPalindromicSubstring.java └── SinglyLinkedList.java ├── Java-problem-2023.iml ├── Kadane.java ├── Knapsack.java ├── KruskalsAlgorithm.c ├── LeeAlgorithmOptimized.java ├── LinearSearchRecursion.java ├── LinkedListReversal.java ├── LongestCommonSubsequenceWithSumK.java ├── MergeSort.java ├── OTPGenerator.java ├── Palindrome.java ├── Pascal's_Triangle.java ├── Pattern132.java ├── PermutationSequence.java ├── PigeonholeSort.java ├── PrimeAdam.java ├── PrimsAlgorithm.java ├── PrintMazePaths.java ├── PrintMazePathsOptimized.java ├── Q_5.java ├── QuickSort.java ├── README.md ├── RadixSort.java ├── RadixSortOptimized.java ├── Rearrange.java ├── Reverse.java ├── Reverse_Stack.java ├── RightTrianglePattern.java ├── Rotate_array.java ├── SelectionSort ├── ShellSort ├── SimulatedAnnealing.java ├── SlidingWindowMaximum.java ├── Stack.java ├── StackUsingArray.java ├── StackUsingQueue.java ├── StringPalindrome.java ├── Strings.java ├── SubArrayZeroSum.java ├── SubsequencesSumK.java ├── SumOfPrime.java ├── ThreadPriorityExample.java ├── ThreadSynchronizationExample.java ├── ThreeSum.java ├── TimSortJava ├── TopologicalSortOptimized.java ├── Tower_of_Hanoi.java ├── Vstarpattern.java ├── WordBreak.java ├── all_subsequences_with_sum_equal_k.java ├── apalimdrome.java ├── binarysearch_rec.java ├── bit_manipn.java ├── bubblesort.java ├── complexNo.java ├── graph └── algorithms │ ├── BellmanFordAlgorithm.java │ ├── DijkstrasAlgorithmMST.java │ ├── DijkstrasAlgorithmSP.java │ ├── FloodFill.java │ ├── FloodFillMruganka.java │ ├── FloydWarshallAlgorithm.java │ ├── KruskalsAlgorithm.java │ ├── KruskalsMST.java │ ├── LeesAlgorithm.java │ ├── LeesAlgorithm_Mruganka.cpp │ └── PrimsAlgorithm.java ├── heapsort.java ├── impr_selec.java ├── java └── solution │ ├── BellmanFord.java │ ├── ConcatinateWords.java │ ├── Dijkstra.java │ ├── Fibonacci.java │ ├── FindOccouranceIndicesInArray.java │ ├── KadaneAlgorithm.java │ ├── Knapsack.java │ ├── MedianOfSortedArrays.java │ ├── Nqueens.java │ ├── Removeduplicate.java │ ├── Subsets.java │ ├── SudokuSolver.java │ ├── Topologicalsort.java │ ├── Topview.java │ ├── Trapingrainwater.java │ ├── UnionIntersection.java │ ├── ValidParenthesis.java │ ├── bubble_sort │ └── intersectionOfTwoArrays.java ├── longest_common_subsequence_with_sum_k.java ├── matrixAdd.java ├── overloading.java ├── q6.java ├── rabin_carp_algorithm.java ├── reverse.java ├── selectionSort.java └── stack_linked.java /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Eclipse 3 | *.class 4 | target/ 5 | .project 6 | .classpath 7 | .settings 8 | .factorypath 9 | .attach* 10 | 11 | # Package Files # 12 | *.jar 13 | *.war 14 | *.ear 15 | 16 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 17 | hs_err_pid* 18 | 19 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 20 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 21 | 22 | .idea/ 23 | .idea/**/*.xml 24 | .idea/*.xml 25 | 26 | .idea/.gitignore 27 | .idea/codeStyles/Project.xml 28 | .idea/codeStyles/codeStyleConfig.xml 29 | .idea/compiler.xml 30 | .idea/encodings.xml 31 | .idea/jarRepositories.xml 32 | .idea/misc.xml 33 | .idea/vcs.xml 34 | 35 | # User-specific stuff 36 | .idea/**/workspace.xml 37 | .idea/**/tasks.xml 38 | .idea/**/usage.statistics.xml 39 | .idea/**/dictionaries 40 | .idea/**/shelf 41 | 42 | # AWS User-specific 43 | .idea/**/aws.xml 44 | 45 | # Generated files 46 | .idea/**/contentModel.xml 47 | 48 | # Sensitive or high-churn files 49 | .idea/**/dataSources/ 50 | .idea/**/dataSources.ids 51 | .idea/**/dataSources.local.xml 52 | .idea/**/sqlDataSources.xml 53 | .idea/**/dynamic.xml 54 | .idea/**/uiDesigner.xml 55 | .idea/**/dbnavigator.xml 56 | 57 | # Gradle 58 | .idea/**/gradle.xml 59 | .idea/**/libraries 60 | 61 | # Gradle and Maven with auto-import 62 | # When using Gradle or Maven with auto-import, you should exclude module files, 63 | # since they will be recreated, and may cause churn. Uncomment if using 64 | # auto-import. 65 | # .idea/artifacts 66 | # .idea/compiler.xml 67 | # .idea/jarRepositories.xml 68 | # .idea/modules.xml 69 | # .idea/*.iml 70 | # .idea/modules 71 | # *.iml 72 | # *.ipr 73 | 74 | # CMake 75 | cmake-build-*/ 76 | 77 | # Mongo Explorer plugin 78 | .idea/**/mongoSettings.xml 79 | 80 | # File-based project format 81 | *.iws 82 | 83 | # IntelliJ 84 | out/ 85 | 86 | # mpeltonen/sbt-idea plugin 87 | .idea_modules/ 88 | 89 | # JIRA plugin 90 | atlassian-ide-plugin.xml 91 | 92 | # Cursive Clojure plugin 93 | .idea/replstate.xml 94 | 95 | # SonarLint plugin 96 | .idea/sonarlint/ 97 | 98 | # Crashlytics plugin (for Android Studio and IntelliJ) 99 | com_crashlytics_export_strings.xml 100 | crashlytics.properties 101 | crashlytics-build.properties 102 | fabric.properties 103 | 104 | # Editor-based Rest Client 105 | .idea/httpRequests 106 | 107 | # Android studio 3.1+ serialized cache file 108 | .idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /AndQueries.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Ninja likes performing bitwise AND operations. He is given an array 'ARR' 3 | * of size 'N' and needs to perform 'N' queries. For each query, 1 <= 'i' <= 'N', 4 | * he needs to calculate the bitwise AND of all the array elements in the prefix 5 | * of length 'i'. After that, his task is to print the bitwise AND of all the 'N' 6 | * query results. 7 | * Since Ninja leads a busy life, he has asked you to help him complete this task. 8 | */ 9 | public class AndQueries { 10 | public static int andQueries(int arr[], int n) { 11 | int op = Integer.MAX_VALUE; 12 | int series = Integer.MAX_VALUE; 13 | for (int i = 0; i < n; i++) { 14 | series = series & arr[i]; 15 | 16 | op = op & series; 17 | } 18 | 19 | return op; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Armstrong.java: -------------------------------------------------------------------------------- 1 | // Java program to determine whether 2 | // the number is Armstrong number or not 3 | public class Armstrong { 4 | 5 | // Function to calculate x raised 6 | // to the power y 7 | int power(int x, long y) 8 | { 9 | if (y == 0) 10 | return 1; 11 | if (y % 2 == 0) 12 | return power(x, y / 2) * power(x, y / 2); 13 | return x * power(x, y / 2) * power(x, y / 2); 14 | } 15 | 16 | // Function to calculate order of the number 17 | int order(int x) 18 | { 19 | int n = 0; 20 | while (x != 0) { 21 | n++; 22 | x = x / 10; 23 | } 24 | return n; 25 | } 26 | 27 | // Function to check whether the given 28 | // number is Armstrong number or not 29 | boolean isArmstrong(int x) 30 | { 31 | // Calling order function 32 | int n = order(x); 33 | int temp = x, sum = 0; 34 | while (temp != 0) { 35 | int r = temp % 10; 36 | sum = sum + power(r, n); 37 | temp = temp / 10; 38 | } 39 | 40 | // If satisfies Armstrong condition 41 | return (sum == x); 42 | } 43 | 44 | // Driver Code 45 | public static void main(String[] args) 46 | { 47 | Armstrong ob = new Armstrong(); 48 | int x = 153; 49 | System.out.println(ob.isArmstrong(x)); 50 | x = 1253; 51 | System.out.println(ob.isArmstrong(x)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.ArrayList; 3 | class Arraylist{ 4 | public static void main(String[] args){ 5 | ArrayList al = new ArrayList<>(); 6 | al.add(1); 7 | al.add(2); 8 | al.add(3); 9 | System.out.println(al); 10 | Collections.sort(a1); 11 | for(String str: a1){ 12 | System.out.print(" "+str); 13 | }} 14 | -------------------------------------------------------------------------------- /AutomorphicNumber.java: -------------------------------------------------------------------------------- 1 | // Java program to check if a number is Automorphic 2 | 3 | class AutomorphicNumber { 4 | // Function to check Automorphic number 5 | static boolean isAutomorphic(int N) 6 | { 7 | // Store the square 8 | if(N < 0) N = -N; 9 | int sq = N * N; 10 | 11 | // Start Comparing digits 12 | while (N > 0) { 13 | // Return false, if any digit of N doesn't 14 | // match with its square's digits from last 15 | if (N % 10 != sq % 10) 16 | return false; 17 | 18 | // Reduce N and square 19 | N /= 10; 20 | sq /= 10; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | // Driver method 27 | public static void main(String[] args) 28 | { 29 | int N = 5; 30 | 31 | System.out.println(isAutomorphic(N) ? "Automorphic" : "Not Automorphic"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /BellmanFordAlgoImplement.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | 3 | // A class to represent a connected, directed and weighted 4 | // graph 5 | class BellmanFordAlgoImplement { 6 | 7 | // A class to represent a weighted edge in graph 8 | class Edge { 9 | int src, dest, weight; 10 | Edge() { src = dest = weight = 0; } 11 | }; 12 | 13 | int V, E; 14 | Edge edge[]; 15 | 16 | // Creates a graph with V vertices and E edges 17 | BellmanFordAlgoImplement(int v, int e) 18 | { 19 | V = v; 20 | E = e; 21 | edge = new Edge[e]; 22 | for (int i = 0; i < e; ++i) 23 | edge[i] = new Edge(); 24 | } 25 | 26 | // The main function that finds shortest distances from 27 | // src to all other vertices using Bellman-Ford 28 | // algorithm. The function also detects negative weight 29 | // cycle 30 | void BellmanFord(BellmanFordAlgoImplement graph, int src) 31 | { 32 | int V = graph.V, E = graph.E; 33 | int dist[] = new int[V]; 34 | 35 | // Step 1: Initialize distances from src to all 36 | // other vertices as INFINITE 37 | for (int i = 0; i < V; ++i) 38 | dist[i] = Integer.MAX_VALUE; 39 | dist[src] = 0; 40 | 41 | // Step 2: Relax all edges |V| - 1 times. A simple 42 | // shortest path from src to any other vertex can 43 | // have at-most |V| - 1 edges 44 | for (int i = 1; i < V; ++i) { 45 | for (int j = 0; j < E; ++j) { 46 | int u = graph.edge[j].src; 47 | int v = graph.edge[j].dest; 48 | int weight = graph.edge[j].weight; 49 | if (dist[u] != Integer.MAX_VALUE 50 | && dist[u] + weight < dist[v]) 51 | dist[v] = dist[u] + weight; 52 | } 53 | } 54 | 55 | // Step 3: check for negative-weight cycles. The 56 | // above step guarantees shortest distances if graph 57 | // doesn't contain negative weight cycle. If we get 58 | // a shorter path, then there is a cycle. 59 | for (int j = 0; j < E; ++j) { 60 | int u = graph.edge[j].src; 61 | int v = graph.edge[j].dest; 62 | int weight = graph.edge[j].weight; 63 | if (dist[u] != Integer.MAX_VALUE 64 | && dist[u] + weight < dist[v]) { 65 | System.out.println( 66 | "Graph contains negative weight cycle"); 67 | return; 68 | } 69 | } 70 | printArr(dist, V); 71 | } 72 | 73 | // A utility function used to print the solution 74 | void printArr(int dist[], int V) 75 | { 76 | System.out.println("Vertex Distance from Source"); 77 | for (int i = 0; i < V; ++i) 78 | System.out.println(i + "\t\t" + dist[i]); 79 | } 80 | 81 | // Driver's code 82 | public static void main(String[] args) 83 | { 84 | int V = 5; // Number of vertices in graph 85 | int E = 8; // Number of edges in graph 86 | 87 | BellmanFordAlgoImplement graph = new BellmanFordAlgoImplement(V, E); 88 | 89 | // add edge 0-1 (or A-B in above figure) 90 | graph.edge[0].src = 0; 91 | graph.edge[0].dest = 1; 92 | graph.edge[0].weight = -1; 93 | 94 | // add edge 0-2 (or A-C in above figure) 95 | graph.edge[1].src = 0; 96 | graph.edge[1].dest = 2; 97 | graph.edge[1].weight = 4; 98 | 99 | // add edge 1-2 (or B-C in above figure) 100 | graph.edge[2].src = 1; 101 | graph.edge[2].dest = 2; 102 | graph.edge[2].weight = 3; 103 | 104 | // add edge 1-3 (or B-D in above figure) 105 | graph.edge[3].src = 1; 106 | graph.edge[3].dest = 3; 107 | graph.edge[3].weight = 2; 108 | 109 | // add edge 1-4 (or B-E in above figure) 110 | graph.edge[4].src = 1; 111 | graph.edge[4].dest = 4; 112 | graph.edge[4].weight = 2; 113 | 114 | // add edge 3-2 (or D-C in above figure) 115 | graph.edge[5].src = 3; 116 | graph.edge[5].dest = 2; 117 | graph.edge[5].weight = 5; 118 | 119 | // add edge 3-1 (or D-B in above figure) 120 | graph.edge[6].src = 3; 121 | graph.edge[6].dest = 1; 122 | graph.edge[6].weight = 1; 123 | 124 | // add edge 4-3 (or E-D in above figure) 125 | graph.edge[7].src = 4; 126 | graph.edge[7].dest = 3; 127 | graph.edge[7].weight = -3; 128 | 129 | // Function call 130 | graph.BellmanFord(graph, 0); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /BinarySearchExample.java: -------------------------------------------------------------------------------- 1 | class BinarySearchExample{ 2 | public static void binarySearch(int arr[], int first, int last, int key){ 3 | if (arr == null) { 4 | System.out.println("Input array is null."); 5 | return; 6 | } 7 | 8 | if (first < 0 || last >= arr.length || first > last) { 9 | System.out.println("Invalid search interval."); 10 | return; 11 | } 12 | int mid = (first + last)/2; 13 | while( first <= last ){ 14 | if ( arr[mid] < key ){ 15 | first = mid + 1; 16 | }else if ( arr[mid] == key ){ 17 | System.out.println("Element is found at index: " + mid); 18 | break; 19 | }else{ 20 | last = mid - 1; 21 | } 22 | mid = (first + last)/2; 23 | } 24 | if ( first > last ){ 25 | System.out.println("Element is not found!"); 26 | } 27 | } 28 | public static void main(String args[]){ 29 | int arr[] = {10,20,30,40,50}; 30 | int key = 30; 31 | int last=arr.length-1; 32 | binarySearch(arr,0,last,key); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | public class BinarySearchTree { 2 | //Represent the node of binary tree 3 | public static class Node{ 4 | int data; 5 | Node left; 6 | Node right; 7 | public Node(int data){ 8 | //Assign data to the new node, set left and right children to null 9 | this.data = data; 10 | this.left = null; 11 | this.right = null; 12 | } 13 | } 14 | //Represent the root of binary tree 15 | public Node root; 16 | public BinarySearchTree(){ 17 | root = null; 18 | } 19 | //factorial() will calculate the factorial of given number 20 | public int factorial(int num) { 21 | int fact = 1; 22 | if(num == 0) 23 | return 1; 24 | else { 25 | while(num > 1) { 26 | fact = fact * num; 27 | num--; 28 | } 29 | return fact; 30 | } 31 | } 32 | //numOfBST() will calculate the total number of possible BST by calculating Catalan Number for given key 33 | public int numOfBST(int key) { 34 | int catalanNumber = factorial(2 * key)/(factorial(key + 1) * factorial(key)); 35 | return catalanNumber; 36 | } 37 | public static void main(String[] args) { 38 | BinarySearchTree bt = new BinarySearchTree(); 39 | //Display total number of possible binary search tree with key 5 40 | System.out.println("Total number of possible Binary Search Trees with given key: " + bt.numOfBST(5)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /BooleanMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Boolean Matrix 3 | Link Of Problem - https://practice.geeksforgeeks.org/problems/boolean-matrix-problem-1587115620/1 4 | */ 5 | 6 | class BooleanMatrix 7 | { 8 | //Function to modify the matrix such that if a matrix cell matrix[i][j] 9 | //is 1 then all the cells in its ith row and jth column will become 1. 10 | void booleanMatrix(int matrix[][]) 11 | { 12 | // code here 13 | int R = matrix.length; 14 | int C = matrix[0].length; 15 | boolean row[] = new boolean[R]; 16 | boolean col[] = new boolean[C]; 17 | int i ,j ; 18 | for(i=0;i arr[j+1]){ 16 | int temp = arr[j]; 17 | arr[j]= arr[j+1]; 18 | arr[j+1]= temp; 19 | } 20 | } 21 | } 22 | System.out.println("sorted array is "); 23 | for(int i = 0;i arr[j + 1]) { 16 | 17 | // Swap arr[j] and arr[j+1] 18 | temp = arr[j]; 19 | arr[j] = arr[j + 1]; 20 | arr[j + 1] = temp; 21 | swapped = true; 22 | } 23 | } 24 | 25 | // If no two elements were 26 | // swapped by inner loop, then break 27 | if (swapped == false) 28 | break; 29 | } 30 | } 31 | 32 | // Function to print an array 33 | static void printArray(int arr[], int size) 34 | { 35 | int i; 36 | for (i = 0; i < size; i++) 37 | System.out.print(arr[i] + " "); 38 | System.out.println(); 39 | } 40 | 41 | // Driver program 42 | public static void main(String args[]) 43 | { 44 | int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; 45 | int n = arr.length; 46 | bubbleSort(arr, n); 47 | System.out.println("Sorted array: "); 48 | printArray(arr, n); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Java problem open source 2 | 3 | Thank you for taking the time to contribute to our project! We appreciate your help. Here’s how you can get started: 4 | 5 | ## How to Contribute 6 | 7 | 1. **Fork the repository**: Click on the "Fork" button at the top of this repository and clone your fork locally. 8 | 2. **Create a branch**: Create a new feature or bugfix branch with a meaningful name. 9 | ```bash 10 | git checkout -b feature/new-feature 11 | ``` 12 | 3. **Make your changes**: Make sure your changes are well documented and follow best practices. 13 | 4. **Test your changes**: Ensure all tests pass after making changes, and write new tests if necessary. 14 | 5. **Push your changes**: 15 | ```bash 16 | git push origin feature/new-feature 17 | ``` 18 | 6. **Create a Pull Request**: Submit a pull request to the main repository and briefly describe the changes you’ve made. 19 | 20 | ## Issues 21 | If you encounter any bugs or have feature suggestions, feel free to open an issue on GitHub. 22 | 23 | ## Code Style 24 | Ensure that your code follows the style guidelines used by the project. Make sure to run linters and formatters as needed. 25 | 26 | ## Reporting Bugs 27 | If you find any bugs, please create an issue with: 28 | - A clear and descriptive title 29 | - Steps to reproduce 30 | - Expected and actual behavior 31 | 32 | ## Pull Request Checklist 33 | Before submitting, make sure that: 34 | - Your code passes all tests 35 | - Your code adheres to the coding style of the project 36 | - You’ve included clear commit messages 37 | -------------------------------------------------------------------------------- /CalculateNthFibonacciNumber: -------------------------------------------------------------------------------- 1 | public class FibonacciCalculator { 2 | 3 | public static int calculateFibonacci(int n) { 4 | // Base case: Fibonacci numbers at positions 0 and 1 are 0 and 1,respectively, also, the Fibonnaci Sequence don't work with negative numbers 5 | if (n == 0) { 6 | return 0; 7 | } else if (n == 1) { 8 | return 1; 9 | } else if (n < 0){ 10 | throw new IllegalArgumentException("Input should be a non-negative integer.") 11 | } 12 | 13 | // Recursive case: sum of the previous two Fibonacci numbers 14 | return calculateFibonacci(n - 1) + calculateFibonacci(n - 2); 15 | } 16 | 17 | public static void main(String[] args) { 18 | int position = 0; 19 | int fibonacciNumber = calculateFibonacci(position); 20 | System.out.println("The Fibonacci number at position " + position + " is: " + fibonacciNumber); 21 | position = 3; 22 | fibonacciNumber = calculateFibonacci(position); 23 | System.out.println("\nThe Fibonacci number at position " + position + " is: " + fibonacciNumber); 24 | position = 9; 25 | fibonacciNumber = calculateFibonacci(position); 26 | System.out.println("\nThe Fibonacci number at position " + position + " is: " + fibonacciNumber); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /CatalanNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Calculate Catalan Numbers 3 | */ 4 | public final class CatalanNumbers { 5 | private CatalanNumbers() { 6 | } 7 | 8 | /** 9 | * Calculate the nth Catalan number using a recursive formula. 10 | * 11 | * @param n the index of the Catalan number to compute 12 | * @return the nth Catalan number 13 | */ 14 | public static long catalan(final int n) { 15 | if (n < 0) { 16 | throw new IllegalArgumentException("Index must be non-negative"); 17 | } 18 | return factorial(2 * n) / (factorial(n + 1) * factorial(n)); 19 | } 20 | 21 | /** 22 | * Calculate the factorial of a number. 23 | * 24 | * @param n the number to compute the factorial for 25 | * @return the factorial of n 26 | */ 27 | private static long factorial(final int n) { 28 | if (n == 0 || n == 1) { 29 | return 1; 30 | } 31 | long result = 1; 32 | for (int i = 2; i <= n; i++) { 33 | result *= i; 34 | } 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /CeaserCipher.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class CaeserCipher 3 | { 4 | String s; //declaration 5 | public CaeserCipher() //default constructor to initialise s 6 | { 7 | s=""; 8 | } 9 | void input() //input text 10 | { 11 | Scanner sc=new Scanner(System.in); 12 | System.out.println("enter text"); 13 | s=sc.nextLine(); 14 | } 15 | void encrpyt() 16 | { 17 | int L; //declaration 18 | char ch; 19 | String s1=""; 20 | L=s.length(); 21 | if(L>3 && L<100) 22 | { 23 | for(int i=0;i='A' && ch<='M' || ch>='a' && ch<='m') 27 | s1=s1+(char)(ch+13); 28 | else 29 | if(ch>='N' && ch<='Z' || ch>='n' && ch<='z') 30 | s1=s1+(char)(ch-13); 31 | else 32 | s1=s1+ch; 33 | } 34 | System.out.println("Encrypted text="+s1); //printing 35 | } 36 | else 37 | System.out.print("INVALID LENGTH"); 38 | } 39 | public static void main() 40 | { 41 | CaeserCipher ob=new CaeserCipher(); //creating object ob 42 | ob.input(); //calling function 43 | ob.encrpyt(); //calling function 44 | } 45 | } 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Check_Digit_Code.java: -------------------------------------------------------------------------------- 1 | public class IsDigitsOnly { 2 | 3 | public static void main(String[] args) { 4 | String str = "1234567890"; 5 | boolean isDigitsOnly = true; 6 | for (char c : str.toCharArray()) { 7 | if (!Character.isDigit(c)) { 8 | isDigitsOnly = false; 9 | break; 10 | } 11 | } 12 | System.out.println(isDigitsOnly); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Check_Even_Fibonacci.java: -------------------------------------------------------------------------------- 1 | // Java Program to find even sum of 2 | // fibonacci Series Till number N 3 | import java.io.*; 4 | 5 | class geeksforgeeks { 6 | 7 | // Computing the value of first fibonacci series 8 | // and storing the sum of even indexed numbers 9 | static int Fib_Even_Sum(int N) 10 | { 11 | if (N <= 0) 12 | return 0; 13 | 14 | int fib[] = new int[2 * N + 1]; 15 | fib[0] = 0; 16 | fib[1] = 1; 17 | 18 | // Initializing the sum 19 | int s = 0; 20 | 21 | // Adding remaining numbers 22 | for (int j = 2; j <= 2 * N; j++) { 23 | fib[j] = fib[j - 1] + fib[j - 2]; 24 | 25 | // Only considering even indexes 26 | if (j % 2 == 0) 27 | s += fib[j]; 28 | } 29 | 30 | return s; 31 | } 32 | 33 | // The Driver code 34 | public static void main(String[] args) 35 | { 36 | int N = 11; 37 | 38 | // Prints the sum of even-indexed numbers 39 | System.out.println( 40 | "Even sum of fibonacci series till number " + N 41 | + " is: " + +Fib_Even_Sum(N)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /CocktailSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Cocktail Sort 2 | public class CocktailSort 3 | { 4 | void cocktailSort(int a[]) 5 | { 6 | boolean swapped = true; 7 | int start = 0; 8 | int end = a.length; 9 | 10 | while (swapped == true) 11 | { 12 | // reset the swapped flag on entering the 13 | // loop, because it might be true from a 14 | // previous iteration. 15 | swapped = false; 16 | 17 | // loop from bottom to top same as 18 | // the bubble sort. 19 | for (int i = start; i < end - 1; ++i) 20 | { 21 | if (a[i] > a[i + 1]) { 22 | int temp = a[i]; 23 | a[i] = a[i + 1]; 24 | a[i + 1] = temp; 25 | swapped = true; 26 | } 27 | } 28 | 29 | // if nothing moved, then array is sorted. 30 | if (swapped == false) 31 | break; 32 | 33 | // otherwise, reset the swapped flag so that it 34 | // can be used in the next stage 35 | swapped = false; 36 | 37 | // move the end point back by one, because 38 | // item at the end is in its rightful spot 39 | end = end - 1; 40 | 41 | // from top to bottom, doing the 42 | // same comparison as in the previous stage 43 | for (int i = end - 1; i >= start; i--) 44 | { 45 | if (a[i] > a[i + 1]) 46 | { 47 | int temp = a[i]; 48 | a[i] = a[i + 1]; 49 | a[i + 1] = temp; 50 | swapped = true; 51 | } 52 | } 53 | 54 | // increase the starting point, because 55 | // the last stage would have moved the next 56 | // smallest number to its rightful spot. 57 | start = start + 1; 58 | } 59 | } 60 | 61 | /* Prints the array */ 62 | void printArray(int a[]) 63 | { 64 | int n = a.length; 65 | for (int i = 0; i < n; i++) 66 | System.out.print(a[i] + " "); 67 | System.out.println(); 68 | } 69 | 70 | // Driver code 71 | public static void main(String[] args) 72 | { 73 | CocktailSort ob = new CocktailSort(); 74 | int a[] = { 5, 1, 4, 2, 8, 0, 2 }; 75 | ob.cocktailSort(a); 76 | System.out.println("Sorted array"); 77 | ob.printArray(a); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /ColumnNameForGivenColumnNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class ColumnNameForGivenColumnNumber 4 | { 5 | //Function to return list of integers that form the boundary 6 | //traversal of the matrix in a clockwise manner. 7 | static ArrayList boundaryTraversal(int matrix[][], int n, int m) 8 | { 9 | // code here 10 | ArrayList al = new ArrayList(); 11 | for (int i = 0; i < m; i++) { 12 | al.add(matrix[0][i]); 13 | } 14 | for (int i = 1; i < n; i++) { 15 | al.add(matrix[i][m - 1]); 16 | } 17 | // Check if there is more than one row in the matrix 18 | if (n > 1) { 19 | for (int i = m - 2; i >= 0; i--) { 20 | al.add(matrix[n - 1][i]); 21 | } 22 | } 23 | // Check if there is more than one column in the matrix 24 | if (m > 1) { 25 | for (int i = n - 2; i > 0; i--) { 26 | al.add(matrix[i][0]); 27 | } 28 | } 29 | return al; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ColumnNameFromGivenColumnNumber.java: -------------------------------------------------------------------------------- 1 | // GFG problem 2 | // Link: https://practice.geeksforgeeks.org/problems/column-name-from-a-given-column-number4244/1 3 | 4 | // Solution: 5 | 6 | //{ Driver Code Starts 7 | //Initial Template for Java 8 | 9 | import java.util.*; 10 | import java.lang.*; 11 | class ColumnNameFromGivenColumnNumber 12 | { 13 | public static void main (String[] args) 14 | { 15 | 16 | Scanner sc = new Scanner(System.in); 17 | int t = sc.nextInt(); 18 | 19 | while(t-- > 0) 20 | { 21 | long n = sc.nextLong(); 22 | System.out.println (new Solution().colName (n)); 23 | } 24 | 25 | } 26 | } 27 | // } Driver Code Ends 28 | 29 | class Solution 30 | { 31 | String colName (long n) 32 | { 33 | // your code here 34 | String op = ""; 35 | char alpha[] = new char[26]; 36 | alpha[0] = 'A'; 37 | for (int i = 1; i < 26; i++) 38 | alpha[i] = (char) ((int) alpha[i - 1] + 1); 39 | 40 | while (n > 0) 41 | { 42 | long rem = (n - 1) % 26; 43 | op = alpha[(int) rem] + op; 44 | n = (n - 1) / 26; 45 | } 46 | return op; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /CountingSort.java: -------------------------------------------------------------------------------- 1 | public class CountingSort { 2 | static void countSortNaive(int arr[], int k, int n) { 3 | int[] count = new int[k]; 4 | for (int i = 0; i < k; i++) { 5 | count[i] = 0; 6 | } 7 | for (int i = 0; i < n; i++) { 8 | count[arr[i]]++; 9 | } 10 | int index = 0; 11 | for (int i = 0; i < k; i++) { 12 | for (int j = 0; j < count[i]; j++) { 13 | arr[index] = i; 14 | index++; 15 | } 16 | } 17 | for (int i = 0; i < n; i++) { 18 | System.out.print(arr[i] + " "); 19 | } 20 | } 21 | 22 | static void countSortEfficient(int arr[], int k, int n) { 23 | int[] count = new int[k]; 24 | for (int i = 0; i < k; i++) { 25 | count[i] = 0; 26 | } 27 | for (int i = 0; i < n; i++) { 28 | count[arr[i]]++; 29 | } 30 | for (int i = 1; i < k; i++) { 31 | count[i] = count[i - 1] + count[i]; 32 | } 33 | int[] res = new int[n]; 34 | for (int i = n - 1; i >= 0; i--) { 35 | // res[count[arr[i]] - 1] = arr[i]; 36 | // count[arr[i]]--; 37 | // res[--count[arr[i]]]; 38 | 39 | res[--count[arr[i]]] = arr[i]; 40 | } 41 | for (int i = 0; i < n; i++) { 42 | arr[i] = res[i]; 43 | System.out.print(arr[i] + " "); 44 | } 45 | } 46 | 47 | public static void main(String args[]) { 48 | int arr[] = { 5, 6, 5, 2 }; 49 | int n = 4; 50 | int k = 7; 51 | countSortEfficient(arr, k, n); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Custom HashMap Implementation.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | 3 | class MyHashMap { 4 | private static class Entry { 5 | K key; 6 | V value; 7 | 8 | Entry(K key, V value) { 9 | this.key = key; 10 | this.value = value; 11 | } 12 | } 13 | 14 | private LinkedList>[] table; 15 | private int size; 16 | private static final int INITIAL_CAPACITY = 16; 17 | private static final float LOAD_FACTOR = 0.75f; 18 | 19 | @SuppressWarnings("unchecked") 20 | public MyHashMap() { 21 | table = new LinkedList[INITIAL_CAPACITY]; 22 | for (int i = 0; i < INITIAL_CAPACITY; i++) { 23 | table[i] = new LinkedList<>(); 24 | } 25 | size = 0; 26 | } 27 | 28 | private int getIndex(K key) { 29 | return key == null ? 0 : Math.abs(key.hashCode() % table.length); 30 | } 31 | 32 | public void put(K key, V value) { 33 | int index = getIndex(key); 34 | LinkedList> bucket = table[index]; 35 | 36 | for (Entry entry : bucket) { 37 | if (entry.key.equals(key)) { 38 | entry.value = value; // Replace existing value 39 | return; 40 | } 41 | } 42 | 43 | bucket.add(new Entry<>(key, value)); 44 | size++; 45 | 46 | if ((float) size / table.length > LOAD_FACTOR) { 47 | resize(); 48 | } 49 | } 50 | 51 | public V get(K key) { 52 | int index = getIndex(key); 53 | LinkedList> bucket = table[index]; 54 | 55 | for (Entry entry : bucket) { 56 | if (entry.key.equals(key)) { 57 | return entry.value; 58 | } 59 | } 60 | 61 | return null; // Not found 62 | } 63 | 64 | public void remove(K key) { 65 | int index = getIndex(key); 66 | LinkedList> bucket = table[index]; 67 | 68 | for (Entry entry : bucket) { 69 | if (entry.key.equals(key)) { 70 | bucket.remove(entry); 71 | size--; 72 | return; 73 | } 74 | } 75 | } 76 | 77 | public boolean containsKey(K key) { 78 | return get(key) != null; 79 | } 80 | 81 | public int size() { 82 | return size; 83 | } 84 | 85 | @SuppressWarnings("unchecked") 86 | private void resize() { 87 | LinkedList>[] oldTable = table; 88 | table = new LinkedList[oldTable.length * 2]; 89 | for (int i = 0; i < table.length; i++) { 90 | table[i] = new LinkedList<>(); 91 | } 92 | size = 0; 93 | 94 | for (LinkedList> bucket : oldTable) { 95 | for (Entry entry : bucket) { 96 | put(entry.key, entry.value); // Rehash entries into the new table 97 | } 98 | } 99 | } 100 | 101 | public static void main(String[] args) { 102 | MyHashMap map = new MyHashMap<>(); 103 | map.put("one", 1); 104 | map.put("two", 2); 105 | System.out.println(map.get("one")); // Should print 1 106 | System.out.println(map.containsKey("two")); // Should print true 107 | map.remove("one"); 108 | System.out.println(map.get("one")); // Should print null 109 | System.out.println(map.size()); // Should print 1 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /Dijkstra's Shortest Path Algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class DijkstraAlgorithm { 4 | private static final int INF = Integer.MAX_VALUE; 5 | 6 | public static void dijkstra(int[][] graph, int source) { 7 | int vertices = graph.length; 8 | int[] distance = new int[vertices]; 9 | boolean[] visited = new boolean[vertices]; 10 | 11 | for (int i = 0; i < vertices; i++) { 12 | distance[i] = INF; 13 | visited[i] = false; 14 | } 15 | 16 | distance[source] = 0; 17 | 18 | for (int i = 0; i < vertices - 1; i++) { 19 | int minDistance = findMinDistance(distance, visited); 20 | visited[minDistance] = true; 21 | 22 | for (int j = 0; j < vertices; j++) { 23 | if (!visited[j] && graph[minDistance][j] != 0 && distance[minDistance] != INF 24 | && distance[minDistance] + graph[minDistance][j] < distance[j]) { 25 | distance[j] = distance[minDistance] + graph[minDistance][j]; 26 | } 27 | } 28 | } 29 | 30 | printShortestPaths(distance); 31 | } 32 | 33 | private static int findMinDistance(int[] distance, boolean[] visited) { 34 | int minDistance = INF; 35 | int minIndex = -1; 36 | int vertices = distance.length; 37 | 38 | for (int i = 0; i < vertices; i++) { 39 | if (!visited[i] && distance[i] < minDistance) { 40 | minDistance = distance[i]; 41 | minIndex = i; 42 | } 43 | } 44 | return minIndex; 45 | } 46 | 47 | private static void printShortestPaths(int[] distance) { 48 | int vertices = distance.length; 49 | System.out.println("Vertex \t Shortest Distance from Source"); 50 | for (int i = 0; i < vertices; i++) { 51 | System.out.println(i + " \t " + distance[i]); 52 | } 53 | } 54 | 55 | public static void main(String[] args) { 56 | int[][] graph = { 57 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 58 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 59 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 60 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 61 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 62 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 63 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 64 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 65 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 66 | }; 67 | 68 | dijkstra(graph, 0); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /DijkstraAlgorithm.java: -------------------------------------------------------------------------------- 1 | // A Java program for Dijkstra's single source shortest path 2 | // algorithm. The program is for adjacency matrix 3 | // representation of the graph 4 | import java.io.*; 5 | import java.lang.*; 6 | import java.util.*; 7 | 8 | class ShortestPath { 9 | // A utility function to find the vertex with minimum 10 | // distance value, from the set of vertices not yet 11 | // included in shortest path tree 12 | static final int V = 9; 13 | int minDistance(int dist[], Boolean sptSet[]) 14 | { 15 | // Initialize min value 16 | int min = Integer.MAX_VALUE, min_index = -1; 17 | 18 | for (int v = 0; v < V; v++) 19 | if (sptSet[v] == false && dist[v] <= min) { 20 | min = dist[v]; 21 | min_index = v; 22 | } 23 | 24 | return min_index; 25 | } 26 | 27 | // A utility function to print the constructed distance 28 | // array 29 | void printSolution(int dist[]) 30 | { 31 | System.out.println( 32 | "Vertex \t\t Distance from Source"); 33 | for (int i = 0; i < V; i++) 34 | System.out.println(i + " \t\t " + dist[i]); 35 | } 36 | 37 | // Function that implements Dijkstra's single source 38 | // shortest path algorithm for a graph represented using 39 | // adjacency matrix representation 40 | void dijkstra(int graph[][], int src) 41 | { 42 | int dist[] = new int[V]; // The output array. 43 | // dist[i] will hold 44 | // the shortest distance from src to i 45 | 46 | // sptSet[i] will true if vertex i is included in 47 | // shortest path tree or shortest distance from src 48 | // to i is finalized 49 | Boolean sptSet[] = new Boolean[V]; 50 | 51 | // Initialize all distances as INFINITE and stpSet[] 52 | // as false 53 | for (int i = 0; i < V; i++) { 54 | dist[i] = Integer.MAX_VALUE; 55 | sptSet[i] = false; 56 | } 57 | 58 | // Distance of source vertex from itself is always 0 59 | dist[src] = 0; 60 | 61 | // Find shortest path for all vertices 62 | for (int count = 0; count < V - 1; count++) { 63 | // Pick the minimum distance vertex from the set 64 | // of vertices not yet processed. u is always 65 | // equal to src in first iteration. 66 | int u = minDistance(dist, sptSet); 67 | 68 | // Mark the picked vertex as processed 69 | sptSet[u] = true; 70 | 71 | // Update dist value of the adjacent vertices of 72 | // the picked vertex. 73 | for (int v = 0; v < V; v++) 74 | 75 | // Update dist[v] only if is not in sptSet, 76 | // there is an edge from u to v, and total 77 | // weight of path from src to v through u is 78 | // smaller than current value of dist[v] 79 | if (!sptSet[v] && graph[u][v] != 0 80 | && dist[u] != Integer.MAX_VALUE 81 | && dist[u] + graph[u][v] < dist[v]) 82 | dist[v] = dist[u] + graph[u][v]; 83 | } 84 | 85 | // print the constructed distance array 86 | printSolution(dist); 87 | } 88 | 89 | // Driver's code 90 | public static void main(String[] args) 91 | { 92 | /* Let us create the example graph discussed above 93 | */ 94 | int graph[][] 95 | = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, 96 | { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, 97 | { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, 98 | { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, 99 | { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, 100 | { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, 101 | { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, 102 | { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, 103 | { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; 104 | ShortestPath t = new ShortestPath(); 105 | t.dijkstra(graph, 0); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /DijkstraShortestPath.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class DijkstraShortestPath { 4 | public void dijkstra(int[][] graph, int src) { 5 | int V = graph.length; 6 | int[] dist = new int[V]; 7 | boolean[] sptSet = new boolean[V]; 8 | Arrays.fill(dist, Integer.MAX_VALUE); 9 | 10 | dist[src] = 0; 11 | 12 | for (int count = 0; count < V - 1; count++) { 13 | int u = minDistance(dist, sptSet); 14 | sptSet[u] = true; 15 | 16 | for (int v = 0; v < V; v++) { 17 | if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { 18 | dist[v] = dist[u] + graph[u][v]; 19 | } 20 | } 21 | } 22 | 23 | printSolution(dist); 24 | } 25 | 26 | private int minDistance(int[] dist, boolean[] sptSet) { 27 | int minDist = Integer.MAX_VALUE; 28 | int minIndex = -1; 29 | 30 | for (int v = 0; v < dist.length; v++) { 31 | if (!sptSet[v] && dist[v] <= minDist) { 32 | minDist = dist[v]; 33 | minIndex = v; 34 | } 35 | } 36 | return minIndex; 37 | } 38 | 39 | private void printSolution(int[] dist) { 40 | System.out.println("Vertex \t\t Distance from Source"); 41 | for (int i = 0; i < dist.length; i++) { 42 | System.out.println(i + " \t\t " + dist[i]); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int V = 9; // The number of vertices 48 | int[][] graph = { 49 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 50 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 51 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 52 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 53 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 54 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 55 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 56 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 57 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 58 | }; 59 | 60 | DijkstraShortestPath shortestPath = new DijkstraShortestPath(); 61 | shortestPath.dijkstra(graph, 0); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /EmailMasker.java: -------------------------------------------------------------------------------- 1 | public class EmailMasker { 2 | 3 | private static final String ATSIGN = "@"; 4 | private static final char DOT_CHAR = '.'; 5 | private static final char ASTERISK_CHAR = '*'; 6 | private static final int ONE = 1; 7 | 8 | /** 9 | * String input: abc.abc@abc.om 10 | * String output: a**.**c@abc.com 11 | */ 12 | public String maskEmail(String email) { 13 | StringBuilder sb = new StringBuilder(email); 14 | int beforeAtIndexPos = sb.indexOf(ATSIGN) - ONE; 15 | for (int i = ONE; i < beforeAtIndexPos; i++) { 16 | if (sb.charAt(i) != DOT_CHAR) { 17 | sb.setCharAt(i, ASTERISK_CHAR); 18 | } 19 | } 20 | return sb.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /EmailMaskerOptimised.java: -------------------------------------------------------------------------------- 1 | public class EmailMaskerOptimised { 2 | public static String maskEmail(String email) { 3 | if (email == null || email.isEmpty()) { 4 | return email; 5 | } 6 | 7 | int atIndex = email.indexOf('@'); 8 | if (atIndex <= 0) { 9 | return email; 10 | } 11 | 12 | // Get the local part and domain of the email 13 | String localPart = email.substring(0, atIndex); 14 | String domain = email.substring(atIndex); 15 | 16 | int length = localPart.length(); 17 | int maskLength = Math.max(length / 2, 1); // Mask at least half of the characters 18 | int startIndex = (length - maskLength) / 2; // Start masking from the middle of the local part 19 | 20 | StringBuilder maskedLocalPart = new StringBuilder(localPart); 21 | for (int i = startIndex; i < startIndex + maskLength; i++) { 22 | maskedLocalPart.setCharAt(i, '*'); 23 | } 24 | 25 | // Return the masked email 26 | return maskedLocalPart.append(domain).toString(); 27 | } 28 | 29 | public static void main(String[] args) { 30 | String email1 = "john.doe@example.com"; 31 | String email2 = "johndoe@example.com"; 32 | String email3 = "johndoe@"; 33 | 34 | System.out.println("Original Email: " + email1); 35 | System.out.println("Masked Email: " + maskEmail(email1)); 36 | System.out.println(); 37 | 38 | System.out.println("Original Email: " + email2); 39 | System.out.println("Masked Email: " + maskEmail(email2)); 40 | System.out.println(); 41 | 42 | System.out.println("Original Email: " + email3); 43 | System.out.println("Masked Email: " + maskEmail(email3)); 44 | System.out.println(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /EvenOdd.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class EvenOdd { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner reader = new Scanner(System.in); 8 | 9 | System.out.print("Enter a number: "); 10 | int num = reader.nextInt(); 11 | 12 | if(num % 2 == 0) 13 | System.out.println(num + " is even"); 14 | else 15 | System.out.println(num + " is odd"); 16 | } 17 | } -------------------------------------------------------------------------------- /FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | public class FibonacciSeries { 2 | public static void main(String[] args) { 3 | int n = 10; // Change this value to generate a different number of Fibonacci numbers 4 | generateFibonacciSeries(n); 5 | } 6 | 7 | public static void generateFibonacciSeries(int n) { 8 | long first = 0, second = 1; 9 | 10 | System.out.println("Fibonacci Series of " + n + " numbers:"); 11 | 12 | for (int i = 0; i < n; i++) { 13 | System.out.print(first + " "); 14 | 15 | long next = first + second; 16 | first = second; 17 | second = next; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /FindTotalNumberOfNodesInBST.java: -------------------------------------------------------------------------------- 1 | // Java program for the above approach 2 | import java.io.*; 3 | 4 | class FindTotalNumberOfNodesInBST { 5 | // tree node 6 | static class node 7 | { 8 | public int data; 9 | public node left, right; 10 | public node(){ 11 | data = 0; 12 | left = right = null; 13 | } 14 | 15 | } 16 | 17 | // Function to get the count of nodes 18 | // in complete binary tree 19 | static int totalNodes(node root) 20 | { 21 | if (root == null) 22 | return 0; 23 | 24 | int l = totalNodes(root.left); 25 | int r = totalNodes(root.right); 26 | 27 | return 1 + l + r; 28 | } 29 | 30 | // Helper function to allocate a new node 31 | // with the given data 32 | static node newNode(int data) 33 | { 34 | node temp = new node(); 35 | temp.data = data; 36 | temp.left = temp.right = null; 37 | return temp; 38 | } 39 | 40 | 41 | // Driver Code 42 | public static void main(String args[]) 43 | { 44 | node root = newNode(1); 45 | root.left = newNode(2); 46 | root.right = newNode(3); 47 | root.left.left = newNode(4); 48 | root.left.right = newNode(5); 49 | root.right.left = newNode(9); 50 | root.right.right = newNode(8); 51 | root.left.left.left = newNode(6); 52 | root.left.left.right = newNode(7); 53 | System.out.println(totalNodes(root)); 54 | 55 | } 56 | } 57 | 58 | // This code is contributed by poojaagarwal2. 59 | -------------------------------------------------------------------------------- /FloodFillAlgorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.awt.Point; 3 | public class FloodFillAlgorithm 4 | { 5 | static boolean isValid(int[][] screen, int m, int n, int x, int y, int prevC, int newC) 6 | { 7 | if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC 8 | || screen[x][y]== newC) 9 | return false; 10 | return true; 11 | } 12 | 13 | 14 | 15 | static void floodFill(int[][] screen, int m, int n, int x, int y, int prevC, int newC) 16 | { 17 | Vector queue = new Vector(); 18 | 19 | 20 | queue.add(new Point(x, y)); 21 | 22 | screen[x][y] = newC; 23 | 24 | 25 | while(queue.size() > 0) 26 | { 27 | Point currPixel = queue.get(queue.size() - 1); 28 | queue.remove(queue.size() - 1); 29 | 30 | int posX = currPixel.x; 31 | int posY = currPixel.y; 32 | 33 | 34 | if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) 35 | { 36 | 37 | screen[posX + 1][posY] = newC; 38 | queue.add(new Point(posX + 1, posY)); 39 | } 40 | 41 | if(isValid(screen, m, n, posX-1, posY, prevC, newC)) 42 | { 43 | screen[posX-1][posY]= newC; 44 | queue.add(new Point(posX-1, posY)); 45 | } 46 | 47 | if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) 48 | { 49 | screen[posX][posY + 1]= newC; 50 | queue.add(new Point(posX, posY + 1)); 51 | } 52 | 53 | if(isValid(screen, m, n, posX, posY-1, prevC, newC)) 54 | { 55 | screen[posX][posY-1]= newC; 56 | queue.add(new Point(posX, posY-1)); 57 | } 58 | } 59 | } 60 | 61 | public static void main(String[] args) { 62 | int[][] screen ={ 63 | {1, 1, 1, 1, 1, 1, 1, 1}, 64 | {1, 1, 1, 1, 1, 1, 0, 0}, 65 | {1, 0, 0, 1, 1, 0, 1, 1}, 66 | {1, 2, 2, 2, 2, 0, 1, 0}, 67 | {1, 1, 1, 2, 2, 0, 1, 0}, 68 | {1, 1, 1, 2, 2, 2, 2, 0}, 69 | {1, 1, 1, 1, 1, 2, 1, 1}, 70 | {1, 1, 1, 1, 1, 2, 2, 1}}; 71 | 72 | // Row of the display 73 | int m = screen.length; 74 | 75 | int n = screen.length; 76 | 77 | int x = 4; 78 | int y = 4; 79 | 80 | 81 | int prevC = screen[x][y]; 82 | 83 | 84 | int newC = 3; 85 | floodFill(screen, m, n, x, y, prevC, newC); 86 | 87 | 88 | for(int i = 0; i < m; i++) 89 | { 90 | for(int j = 0; j < n; j++) 91 | { 92 | System.out.print(screen[i][j] + " "); 93 | } 94 | System.out.println(); 95 | } 96 | } 97 | } 98 | 99 | -------------------------------------------------------------------------------- /FloydWarshall.java: -------------------------------------------------------------------------------- 1 | // Floyd Warshall Algorithm in Java 2 | 3 | class FloydWarshall { 4 | final static int INF = 9999, nV = 4; 5 | 6 | // Implementing floyd warshall algorithm 7 | void floydWarshall(int graph[][]) { 8 | int matrix[][] = new int[nV][nV]; 9 | int i, j, k; 10 | 11 | for (i = 0; i < nV; i++) 12 | for (j = 0; j < nV; j++) 13 | matrix[i][j] = graph[i][j]; 14 | 15 | // Adding vertices individually 16 | for (k = 0; k < nV; k++) { 17 | for (i = 0; i < nV; i++) { 18 | for (j = 0; j < nV; j++) { 19 | if (matrix[i][k] + matrix[k][j] < matrix[i][j]) 20 | matrix[i][j] = matrix[i][k] + matrix[k][j]; 21 | } 22 | } 23 | } 24 | printMatrix(matrix); 25 | } 26 | 27 | void printMatrix(int matrix[][]) { 28 | for (int i = 0; i < nV; ++i) { 29 | for (int j = 0; j < nV; ++j) { 30 | if (matrix[i][j] == INF) 31 | System.out.print("INF "); 32 | else 33 | System.out.print(matrix[i][j] + " "); 34 | } 35 | System.out.println(); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | int graph[][] = { { 0, 3, INF, 5 }, { 2, 0, INF, 4 }, { INF, 1, 0, INF }, { INF, INF, 2, 0 } }; 41 | FloydWarshall a = new FloydWarshall(); 42 | a.floydWarshall(graph); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Goldbach.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Goldbach 3 | { 4 | int N; //declaration 5 | public Goldbach() //default constructor to initialise N 6 | { 7 | N=0; 8 | } 9 | void input() //to input N 10 | { 11 | Scanner sc=new Scanner(System.in); 12 | System.out.println("Enter a number"); 13 | N=sc.nextInt(); 14 | } 15 | int prime(int n) //to check for prime 16 | { 17 | int c=0; 18 | for(int i=1;i<=n;i++) 19 | { 20 | if(n%i==0) 21 | c++; 22 | } 23 | return c; 24 | } 25 | void sum() 26 | { 27 | if(N%2==0) 28 | { 29 | if(N>9 && N<50) 30 | { 31 | for(int i=3;i<=N/2;i++) 32 | { 33 | for(int j=3;j<=N;j++) 34 | { 35 | if(i+j==N && prime(i)==2 && prime(j)==2) 36 | { 37 | System.out.println("Prime pairs are="+i+" "+j); //printing the odd prime pairs 38 | } 39 | } 40 | } 41 | } 42 | else 43 | System.out.print("Invalid input,Number out of range"); 44 | } 45 | else 46 | System.out.print("Invalid input,number is Odd"); 47 | } 48 | public static void main() 49 | { 50 | Goldbach ob=new Goldbach(); //creating object 51 | ob.input(); //calling 52 | ob.sum(); //calling 53 | } 54 | } -------------------------------------------------------------------------------- /Hanoi1.java: -------------------------------------------------------------------------------- 1 | class Hanoi1 { 2 | public static void cycleSort(int arr[], int n) 3 | { 4 | if (arr == null || n <= 0) { 5 | System.out.println("Input array is null or empty."); 6 | return; 7 | } 8 | int writes = 0; 9 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 10 | 11 | int item = arr[cycle_start]; 12 | int pos = cycle_start; 13 | for (int i = cycle_start + 1; i < n; i++) 14 | if (arr[i] < item) 15 | pos++; 16 | if (pos == cycle_start) 17 | continue; 18 | while (item == arr[pos]) 19 | pos += 1; 20 | if (pos != cycle_start) { 21 | int temp = item; 22 | item = arr[pos]; 23 | arr[pos] = temp; 24 | writes++; 25 | } 26 | while (pos != cycle_start) { 27 | pos = cycle_start; 28 | for (int i = cycle_start + 1; i < n; i++) 29 | if (arr[i] < item) 30 | pos += 1; 31 | while (item == arr[pos]) 32 | pos += 1; 33 | if (item != arr[pos]) { 34 | int temp = item; 35 | item = arr[pos]; 36 | arr[pos] = temp; 37 | writes++; 38 | } 39 | } 40 | } 41 | } 42 | public static void main(String[] args) 43 | { 44 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 45 | int n = arr.length; 46 | cycleSort(arr, n); 47 | 48 | System.out.println("After sort : "); 49 | for (int i = 0; i < n; i++) 50 | System.out.print(arr[i] + " "); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Hanoi2.java: -------------------------------------------------------------------------------- 1 | class Hanoi2 2 | { 3 | // Java recursive function to solve tower of hanoi puzzle 4 | static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 5 | { 6 | if (n == 1) 7 | { 8 | System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); 9 | return; 10 | } 11 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 12 | System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); 13 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 14 | } 15 | 16 | // Driver method 17 | public static void main(String args[]) 18 | { 19 | int n = 4; // Number of disks 20 | towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /HeapSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class HeapSort { 3 | public void sort(int arr[]) 4 | { 5 | int N = arr.length; 6 | 7 | for (int i = N / 2 - 1; i >= 0; i--) 8 | heapify(arr, N, i); 9 | 10 | for (int i = N - 1; i > 0; i--) { 11 | 12 | int x = arr[0]; 13 | arr[0] = arr[i]; 14 | arr[i] = x; 15 | 16 | heapify(arr, i, 0); 17 | } 18 | } 19 | 20 | void heapify(int arr[], int N, int i) 21 | { 22 | int largest = i; 23 | int l = 2 * i + 1; 24 | int r = 2 * i + 2; 25 | 26 | if (l < N && arr[l] > arr[largest]) 27 | largest = l; 28 | 29 | if (r < N && arr[r] > arr[largest]) 30 | largest = r; 31 | 32 | if (largest != i) { 33 | int swap = arr[i]; 34 | arr[i] = arr[largest]; 35 | arr[largest] = swap; 36 | 37 | heapify(arr, N, largest); 38 | } 39 | } 40 | static void printArray(int arr[]) 41 | { 42 | int N = arr.length; 43 | 44 | for (int i = 0; i < N; ++i) 45 | System.out.print(arr[i] + " "); 46 | System.out.println(); 47 | } 48 | 49 | public static void main(String args[]) 50 | { 51 | int i, n, arr[]; 52 | 53 | Scanner s = new Scanner(System.in); 54 | System.out.println("Enter no. of elements in aray:"); 55 | n = s.nextInt(); 56 | 57 | arr = new int[n]; 58 | 59 | System.out.println("Enter " + n + " integers:"); 60 | 61 | for (i = 0;iarray[j]. 17 | while (j >= 0 && key < array[j]) { 18 | array[j + 1] = array[j]; 19 | --j; 20 | } 21 | 22 | // Place key at after the element just smaller than it. 23 | array[j + 1] = key; 24 | } 25 | } 26 | 27 | // Driver code 28 | public static void main(String args[]) { 29 | int[] data = { 9, 5, 1, 4, 3 }; 30 | InsertionSort is = new InsertionSort(); 31 | is.insertionSort(data); 32 | System.out.println("Sorted Array in Ascending Order: "); 33 | System.out.println(Arrays.toString(data)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /JAVA SOLUTION/Circularlinkedlist.java: -------------------------------------------------------------------------------- 1 | class CircularLinkedList { 2 | static class Node { 3 | int data; 4 | Node next; 5 | 6 | Node(int data) { 7 | this.data = data; 8 | this.next = null; 9 | } 10 | } 11 | 12 | Node head = null; 13 | Node tail = null; 14 | 15 | // Add node to the end 16 | public void add(int data) { 17 | Node newNode = new Node(data); 18 | if (head == null) { 19 | head = newNode; 20 | tail = newNode; 21 | tail.next = head; 22 | } else { 23 | tail.next = newNode; 24 | tail = newNode; 25 | tail.next = head; 26 | } 27 | } 28 | 29 | // Display the list 30 | public void display() { 31 | Node current = head; 32 | if (head != null) { 33 | do { 34 | System.out.print(current.data + " "); 35 | current = current.next; 36 | } while (current != head); 37 | } 38 | System.out.println(); 39 | } 40 | 41 | public static void main(String[] args) { 42 | CircularLinkedList list = new CircularLinkedList(); 43 | list.add(1); 44 | list.add(2); 45 | list.add(3); 46 | list.display(); // Output: 1 2 3 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /JAVA SOLUTION/DoublyLinkedLists.java: -------------------------------------------------------------------------------- 1 | class DoublyLinkedList { 2 | // Node class for doubly linked list 3 | class Node { 4 | int data; 5 | Node prev; 6 | Node next; 7 | 8 | // Constructor to create a new node 9 | Node(int data) { 10 | this.data = data; 11 | this.prev = null; 12 | this.next = null; 13 | } 14 | } 15 | 16 | // Head and tail pointers of the list 17 | Node head, tail = null; 18 | 19 | // Method to add a node at the end of the list 20 | public void addNode(int data) { 21 | Node newNode = new Node(data); 22 | 23 | // If the list is empty 24 | if (head == null) { 25 | head = tail = newNode; 26 | } else { 27 | tail.next = newNode; 28 | newNode.prev = tail; 29 | tail = newNode; 30 | } 31 | } 32 | 33 | // Method to display nodes from the beginning 34 | public void displayForward() { 35 | if (head == null) { 36 | System.out.println("The list is empty"); 37 | return; 38 | } 39 | 40 | Node current = head; 41 | System.out.print("Doubly Linked List (forward): "); 42 | while (current != null) { 43 | System.out.print(current.data + " "); 44 | current = current.next; 45 | } 46 | System.out.println(); 47 | } 48 | 49 | // Method to display nodes from the end (backward) 50 | public void displayBackward() { 51 | if (tail == null) { 52 | System.out.println("The list is empty"); 53 | return; 54 | } 55 | 56 | Node current = tail; 57 | System.out.print("Doubly Linked List (backward): "); 58 | while (current != null) { 59 | System.out.print(current.data + " "); 60 | current = current.prev; 61 | } 62 | System.out.println(); 63 | } 64 | 65 | // Method to delete a node from the list 66 | public void deleteNode(int data) { 67 | if (head == null) { 68 | System.out.println("The list is empty"); 69 | return; 70 | } 71 | 72 | Node current = head; 73 | while (current != null && current.data != data) { 74 | current = current.next; 75 | } 76 | 77 | // Node to delete is not found 78 | if (current == null) { 79 | System.out.println("Node with data " + data + " not found."); 80 | return; 81 | } 82 | 83 | // If the node to delete is the head node 84 | if (current == head) { 85 | head = head.next; 86 | if (head != null) { 87 | head.prev = null; 88 | } 89 | } 90 | // If the node to delete is the tail node 91 | else if (current == tail) { 92 | tail = tail.prev; 93 | tail.next = null; 94 | } 95 | // If the node is in the middle 96 | else { 97 | current.prev.next = current.next; 98 | current.next.prev = current.prev; 99 | } 100 | 101 | System.out.println("Node with data " + data + " deleted."); 102 | } 103 | 104 | // Main method to demonstrate the doubly linked list 105 | public static void main(String[] args) { 106 | DoublyLinkedList dll = new DoublyLinkedList(); 107 | 108 | // Adding nodes to the list 109 | dll.addNode(10); 110 | dll.addNode(20); 111 | dll.addNode(30); 112 | dll.addNode(40); 113 | dll.addNode(50); 114 | 115 | // Displaying the list forward and backward 116 | dll.displayForward(); 117 | dll.displayBackward(); 118 | 119 | // Deleting a node 120 | dll.deleteNode(30); 121 | 122 | // Displaying the list again 123 | dll.displayForward(); 124 | dll.displayBackward(); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /JAVA SOLUTION/LongesPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | //Problem Link: https://leetcode.com/problems/longest-palindromic-substring/ 2 | //Mancher's Algorithm - T.C-->O(n) 3 | 4 | class Solution { 5 | private int maxLength = 0; 6 | private int start = 0; 7 | public String longestPalindrome(String s) { 8 | if (s == null || s.length() < 2) { 9 | return s; 10 | } 11 | for (int i = 0; i < s.length(); i++) { 12 | extendPalindrome(s, i, i); // Check for odd-length palindrome 13 | extendPalindrome(s, i, i + 1); // Check for even-length palindrome 14 | if(maxLength == s.length())return s.substring(start, start + maxLength);; 15 | } 16 | return s.substring(start, start + maxLength); 17 | } 18 | private void extendPalindrome(String s, int left, int right) { 19 | while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { 20 | left--; 21 | right++; 22 | } 23 | // Calculate length of palindrome and update start and maxLength 24 | int length = right - left - 1; 25 | if (length > maxLength) { 26 | maxLength = length; 27 | start = left + 1; 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /JAVA SOLUTION/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // Implementation of singly linkedList in java 4 | public class SinglyLinkedList { 5 | private Node head; 6 | private Node tail; 7 | private int size; 8 | 9 | public SinglyLinkedList() { 10 | this.size = 0; 11 | } 12 | 13 | private class Node { 14 | private int value; 15 | private Node next; 16 | 17 | public Node(int value) { 18 | this.value = value; 19 | } 20 | 21 | public Node(int value, Node next) { 22 | this.value = value; 23 | this.next = next; 24 | } 25 | } 26 | 27 | // code to insert element at first 28 | public void insertFirst(int val) { 29 | Node node = new Node(val); 30 | node.next = head; 31 | head = node; 32 | if (tail == null) { 33 | tail = head; 34 | } 35 | size += 1; 36 | } 37 | 38 | // code to insert element at last 39 | public void insertLast(int val) { 40 | if (tail == null) { 41 | insertFirst(val); 42 | return; 43 | } 44 | Node node = new Node(val); 45 | tail.next = node; 46 | tail = node; 47 | size++; 48 | } 49 | 50 | // code to insert an element at random index 51 | public void insertRandom(int val, int idx) { 52 | if (idx == 0) { 53 | insertFirst(val); 54 | return; 55 | } 56 | if (idx == size) { 57 | insertLast(val); 58 | return; 59 | } 60 | 61 | Node temp = head; 62 | for (int i = 0; i < idx - 1; i++) { 63 | temp = temp.next; 64 | } 65 | Node node = new Node(val, temp.next); 66 | temp.next = node; 67 | size++; 68 | } 69 | 70 | //--------------------------------------------------------------- 71 | // display method to display the linkedlist 72 | public void display() { 73 | Node temp = head; 74 | while (temp != null) { 75 | System.out.print(temp.value + "->"); 76 | temp = temp.next; 77 | } 78 | System.out.println("Null"); 79 | } 80 | 81 | //--------------------------------------------------------------- 82 | // pointing to a particular node 83 | public Node get(int idx) { 84 | Node node = head; 85 | for (int i = 0; i < idx; i++) { 86 | node = node.next; 87 | } 88 | return node; 89 | } 90 | 91 | // delete first 92 | public int deleteFirst() { 93 | int val = head.value; 94 | head = head.next; 95 | if (head == null) { 96 | tail = null; 97 | } 98 | size--; 99 | return val; 100 | } 101 | 102 | // delete last 103 | public int deleteLast() { 104 | if (size <= 1) { 105 | return deleteFirst(); 106 | } 107 | Node secondLast = get(size - 2); 108 | int val = tail.value; 109 | tail = secondLast; 110 | tail.next = null; 111 | size--; 112 | return val; 113 | } 114 | 115 | // delete random 116 | public int deleteRandom(int index) { 117 | if (index == 0) { 118 | return deleteFirst(); 119 | } 120 | if (index == size - 1) { 121 | return deleteLast(); 122 | } 123 | Node prev = get(index - 1); 124 | int val = prev.next.value; 125 | prev.next = prev.next.next; 126 | size--; 127 | return val; 128 | } 129 | 130 | // search operation in linkedList 131 | public Node search(int value) { 132 | Node node = head; 133 | while (node != null) { 134 | if (node.value == value) { 135 | return node; 136 | } 137 | node = node.next; 138 | } 139 | return null; 140 | } 141 | 142 | public static void main(String[] args) { 143 | SinglyLinkedList list = new SinglyLinkedList(); 144 | list.insertFirst(31); 145 | list.insertFirst(1); 146 | list.insertFirst(2000); 147 | list.insertLast(11); 148 | list.insertLast(3); 149 | list.insertLast(2001); 150 | list.insertRandom(143, 3); 151 | list.display(); 152 | 153 | list.deleteFirst(); 154 | list.deleteLast(); 155 | System.out.println(list.deleteRandom(2)); 156 | list.display(); 157 | System.out.println(list.size); 158 | System.out.println(list.search(11)); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /Java-problem-2023.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | -------------------------------------------------------------------------------- /Kadane.java: -------------------------------------------------------------------------------- 1 | // Java program to print largest contiguous array sum 2 | 3 | class Kadane { 4 | // Driver Code 5 | public static void main(String[] args) 6 | { 7 | int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; 8 | System.out.println("Maximum contiguous sum is " 9 | + maxSubArraySum(a)); 10 | } 11 | 12 | // Function Call 13 | static int maxSubArraySum(int a[]) 14 | { 15 | int size = a.length; 16 | int max_so_far = Integer.MIN_VALUE, max_ending_here 17 | = 0; 18 | 19 | for (int i = 0; i < size; i++) { 20 | max_ending_here = max_ending_here + a[i]; 21 | if (max_so_far < max_ending_here) 22 | max_so_far = max_ending_here; 23 | if (max_ending_here < 0) 24 | max_ending_here = 0; 25 | } 26 | return max_so_far; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Knapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Knapsack { 3 | 4 | 5 | static int max(int a, int b) 6 | { return (a > b) ? a : b; } 7 | 8 | static int knapSack(int W, int wt[], int val[], int n) 9 | { 10 | int i, w; 11 | int K[][] = new int[n + 1][W + 1]; 12 | 13 | for (i = 0; i<= n; i++) 14 | { 15 | for (w = 0; w<= W; w++) 16 | { 17 | if (i == 0 || w == 0) 18 | K[i][w] = 0; 19 | 20 | else if (wt[i - 1]<= w) 21 | K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); 22 | 23 | else 24 | K[i][w] = K[i - 1][w]; 25 | } 26 | } 27 | 28 | return K[n][W]; 29 | } 30 | 31 | public static void main(String args[]) 32 | { 33 | int i, x, W, val[], wt[]; 34 | 35 | Scanner s = new Scanner(System.in); 36 | System.out.println("Enter capacity:"); 37 | W = s.nextInt(); 38 | 39 | System.out.println("Enter no. of items:"); 40 | x = s.nextInt(); 41 | 42 | val = new int[x]; 43 | 44 | System.out.println("Enter " + x + " items:"); 45 | 46 | for (i = 0;i 5 | using namespace std; 6 | 7 | // Creating shortcut for an integer pair 8 | typedef pair iPair; 9 | 10 | // Structure to represent a graph 11 | struct BellmanFordAlgoImplement 12 | { 13 | int V, E; 14 | vector< pair > edges; 15 | 16 | // Constructor 17 | BellmanFordAlgoImplement(int V, int E) 18 | { 19 | this->V = V; 20 | this->E = E; 21 | } 22 | 23 | // Utility function to add an edge 24 | void addEdge(int u, int v, int w) 25 | { 26 | edges.push_back({w, {u, v}}); 27 | } 28 | 29 | // Function to find MST using Kruskal's 30 | // MST algorithm 31 | int kruskalMST(); 32 | }; 33 | 34 | // To represent Disjoint Sets 35 | struct DisjointSets 36 | { 37 | int *parent, *rnk; 38 | int n; 39 | 40 | // Constructor. 41 | DisjointSets(int n) 42 | { 43 | // Allocate memory 44 | this->n = n; 45 | parent = new int[n+1]; 46 | rnk = new int[n+1]; 47 | 48 | // Initially, all vertices are in 49 | // different sets and have rank 0. 50 | for (int i = 0; i <= n; i++) 51 | { 52 | rnk[i] = 0; 53 | 54 | //every element is parent of itself 55 | parent[i] = i; 56 | } 57 | } 58 | 59 | // Find the parent of a node 'u' 60 | // Path Compression 61 | int find(int u) 62 | { 63 | /* Make the parent of the nodes in the path 64 | from u--> parent[u] point to parent[u] */ 65 | if (u != parent[u]) 66 | parent[u] = find(parent[u]); 67 | return parent[u]; 68 | } 69 | 70 | // Union by rank 71 | void merge(int x, int y) 72 | { 73 | x = find(x), y = find(y); 74 | 75 | /* Make tree with smaller height 76 | a subtree of the other tree */ 77 | if (rnk[x] > rnk[y]) 78 | parent[y] = x; 79 | else // If rnk[x] <= rnk[y] 80 | parent[x] = y; 81 | 82 | if (rnk[x] == rnk[y]) 83 | rnk[y]++; 84 | } 85 | }; 86 | 87 | /* Functions returns weight of the MST*/ 88 | 89 | int BellmanFordAlgoImplement::kruskalMST() 90 | { 91 | int mst_wt = 0; // Initialize result 92 | 93 | // Sort edges in increasing order on basis of cost 94 | sort(edges.begin(), edges.end()); 95 | 96 | // Create disjoint sets 97 | DisjointSets ds(V); 98 | 99 | // Iterate through all sorted edges 100 | vector< pair >::iterator it; 101 | for (it=edges.begin(); it!=edges.end(); it++) 102 | { 103 | int u = it->second.first; 104 | int v = it->second.second; 105 | 106 | int set_u = ds.find(u); 107 | int set_v = ds.find(v); 108 | 109 | // Check if the selected edge is creating 110 | // a cycle or not (Cycle is created if u 111 | // and v belong to same set) 112 | if (set_u != set_v) 113 | { 114 | // Current edge will be in the MST 115 | // so print it 116 | cout << u << " - " << v << endl; 117 | 118 | // Update MST weight 119 | mst_wt += it->first; 120 | 121 | // Merge two sets 122 | ds.merge(set_u, set_v); 123 | } 124 | } 125 | 126 | return mst_wt; 127 | } 128 | 129 | // Driver program to test above functions 130 | int main() 131 | { 132 | /* Let us create above shown weighted 133 | and undirected graph */ 134 | int V = 9, E = 14; 135 | BellmanFordAlgoImplement g(V, E); 136 | 137 | // making above shown graph 138 | g.addEdge(0, 1, 4); 139 | g.addEdge(0, 7, 8); 140 | g.addEdge(1, 2, 8); 141 | g.addEdge(1, 7, 11); 142 | g.addEdge(2, 3, 7); 143 | g.addEdge(2, 8, 2); 144 | g.addEdge(2, 5, 4); 145 | g.addEdge(3, 4, 9); 146 | g.addEdge(3, 5, 14); 147 | g.addEdge(4, 5, 10); 148 | g.addEdge(5, 6, 2); 149 | g.addEdge(6, 7, 1); 150 | g.addEdge(6, 8, 6); 151 | g.addEdge(7, 8, 7); 152 | 153 | cout << "Edges of MST are \n"; 154 | int mst_wt = g.kruskalMST(); 155 | 156 | cout << "\nWeight of MST is " << mst_wt; 157 | 158 | return 0; 159 | } 160 | -------------------------------------------------------------------------------- /LeeAlgorithmOptimized.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | 4 | public class LeeAlgorithmOptimized { 5 | 6 | private static final int[] dx = {-1, 0, 1, 0}; // Array to represent movements in the x-axis 7 | private static final int[] dy = {0, 1, 0, -1}; // Array to represent movements in the y-axis 8 | 9 | private static boolean isValid(int[][] matrix, int row, int col, boolean[][] visited) { 10 | int numRows = matrix.length; 11 | int numCols = matrix[0].length; 12 | // Check if the position is within the matrix bounds and not visited before 13 | return (row >= 0 && row < numRows && col >= 0 && col < numCols && matrix[row][col] == 0 && !visited[row][col]); 14 | } 15 | 16 | public static void leeAlgorithm(int[][] matrix, int startX, int startY) { 17 | int numRows = matrix.length; 18 | int numCols = matrix[0].length; 19 | boolean[][] visited = new boolean[numRows][numCols]; 20 | Queue queueX = new LinkedList<>(); 21 | Queue queueY = new LinkedList<>(); 22 | 23 | queueX.add(startX); // Initialize the queues with the start position 24 | queueY.add(startY); 25 | visited[startX][startY] = true; 26 | 27 | while (!queueX.isEmpty()) { 28 | int x = queueX.poll(); // Get the current position 29 | int y = queueY.poll(); 30 | 31 | for (int i = 0; i < 4; i++) { 32 | int newX = x + dx[i]; // Calculate the new position 33 | int newY = y + dy[i]; 34 | 35 | if (isValid(matrix, newX, newY, visited)) { 36 | queueX.add(newX); // Add the new position to the queue 37 | queueY.add(newY); 38 | visited[newX][newY] = true; 39 | matrix[newX][newY] = -1; // Mark the position as visited 40 | } 41 | } 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | int[][] matrix = { 47 | {0, 0, 0, 0, 0}, 48 | {0, 1, 1, 1, 0}, 49 | {0, 1, 0, 0, 0}, 50 | {0, 1, 1, 1, 0}, 51 | {0, 0, 0, 0, 0} 52 | }; 53 | 54 | int startX = 1; 55 | int startY = 1; 56 | 57 | leeAlgorithm(matrix, startX, startY); 58 | 59 | // Print the modified matrix after running the algorithm 60 | for (int i = 0; i < matrix.length; i++) { 61 | for (int j = 0; j < matrix[0].length; j++) { 62 | System.out.print(matrix[i][j] + " "); 63 | } 64 | System.out.println(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /LinearSearchRecursion.java: -------------------------------------------------------------------------------- 1 | public class LinearSearchRecursion { 2 | 3 | private static boolean LinerSearch(int[] arr, int index, int key) { 4 | 5 | // base case 6 | if(index == arr.length-1) 7 | return false; 8 | 9 | if(arr[index] == key) 10 | return true; 11 | 12 | //processing 13 | 14 | //recursion 15 | boolean remainigPart = LinerSearch(arr,index+1,key); //tail recursion if fast 16 | return remainigPart; 17 | 18 | } 19 | 20 | public static void main(args[] String){ 21 | int arr[] = {1,3,2,5,9}; 22 | //int size = arr.length; 23 | int key = 5; 24 | 25 | boolean ans = LinerSearch(arr,0,key); 26 | System.out.println(ans); 27 | } 28 | -------------------------------------------------------------------------------- /LinkedListReversal.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode(int val) { 6 | this.val = val; 7 | } 8 | } 9 | 10 | public class LinkedListReversal { 11 | public ListNode reverse(ListNode head) { 12 | ListNode prev = null; 13 | ListNode current = head; 14 | 15 | while (current != null) { 16 | ListNode nextTemp = current.next; 17 | current.next = prev; 18 | prev = current; 19 | current = nextTemp; 20 | } 21 | 22 | return prev; 23 | } 24 | 25 | public void printList(ListNode head) { 26 | ListNode current = head; 27 | while (current != null) { 28 | System.out.print(current.val + " "); 29 | current = current.next; 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | ListNode head = new ListNode(1); 35 | head.next = new ListNode(2); 36 | head.next.next = new ListNode(3); 37 | head.next.next.next = new ListNode(4); 38 | head.next.next.next.next = new ListNode(5); 39 | 40 | LinkedListReversal reversal = new LinkedListReversal(); 41 | 42 | System.out.println("Original List:"); 43 | reversal.printList(head); 44 | System.out.println(); 45 | 46 | ListNode reversedHead = reversal.reverse(head); 47 | 48 | System.out.println("Reversed List:"); 49 | reversal.printList(reversedHead); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /LongestCommonSubsequenceWithSumK.java: -------------------------------------------------------------------------------- 1 | // Java code to implement the approach 2 | 3 | class LongestCommonSubsequenceWithSumK { 4 | 5 | static int solve(int a[], int b[], int i, int j, int sum) 6 | { 7 | if (sum == 0) 8 | return 0; 9 | if (sum < 0) 10 | return Integer.MIN_VALUE; 11 | 12 | if (i == 0 || j == 0) { 13 | if (sum == 0) 14 | return 0; 15 | else 16 | return Integer.MIN_VALUE; 17 | } 18 | 19 | // If values are same then we can include this 20 | // or also can't include this 21 | if (a[i - 1] == b[j - 1]) 22 | return Math.max( 23 | 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), 24 | solve(a, b, i - 1, j - 1, sum)); 25 | 26 | return Math.max(solve(a, b, i - 1, j, sum), 27 | solve(a, b, i, j - 1, sum)); 28 | } 29 | 30 | // Driver code 31 | public static void main (String[] args) { 32 | int a[] = { 9, 11, 2, 1, 6, 2, 7 }; 33 | int b[] = { 1, 2, 6, 9, 2, 3, 11, 7 }; 34 | int n = a.length; 35 | int m = b.length; 36 | int sum = 18; 37 | 38 | int ans = solve(a, b, n, m, sum); 39 | if (ans >= 0) 40 | System.out.print(ans); 41 | else 42 | System.out.print(-1); 43 | } 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /MergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class MergeSort { 3 | 4 | void mergesort(int arr[], int l, int m, int r) 5 | 6 | { 7 | int n1 = m - l + 1; 8 | int n2 = r - m; 9 | int L[] = new int[n1]; 10 | int R[] = new int[n2]; 11 | 12 | for (int i = 0; i < n1; ++i) { 13 | L[i] = arr[l + i]; 14 | } 15 | 16 | for (int j = 0; j < n2; ++j) { 17 | R[j] = arr[m + 1 + j]; 18 | } 19 | int i = 0, j = 0; 20 | int k = l; 21 | 22 | while (i < n1 && j < n2) { 23 | 24 | if (L[i] <= R[j]) { 25 | arr[k] = L[i]; 26 | i++; 27 | } 28 | else { 29 | arr[k] = R[j]; 30 | j++; 31 | } 32 | k++; 33 | 34 | } 35 | while (i < n1) { 36 | 37 | arr[k] = L[i]; 38 | i++; 39 | k++; 40 | } 41 | while (j < n2) { 42 | arr[k] = R[j]; 43 | j++; 44 | k++; 45 | } 46 | 47 | } 48 | void sort(int arr[], int l, int r) 49 | 50 | { 51 | if (l < r) { 52 | int m = l + (r - l) / 2; 53 | sort(arr, l, m); 54 | sort(arr, m + 1, r); 55 | mergesort(arr, l, m, r); 56 | } 57 | 58 | } 59 | 60 | static void printArray(int arr[]) 61 | 62 | { 63 | 64 | int n = arr.length; 65 | for (int i = 0; i < n; ++i) { 66 | System.out.print(arr[i] + " "); 67 | } 68 | 69 | System.out.println(); 70 | 71 | } 72 | public static void main(String args[]) 73 | { 74 | int i, n, x, arr[]; 75 | 76 | Scanner s = new Scanner(System.in); 77 | System.out.println("Enter no. of elements in aray:"); 78 | n = s.nextInt(); 79 | 80 | arr = new int[n]; 81 | 82 | System.out.println("Enter " + n + " integers:"); 83 | 84 | for (i = 0;i0){ 8 | r=n%10; 9 | sum=(sum*10)+r; 10 | n=n/10; 11 | } 12 | if(temp==sum) 13 | System.out.println("palindrome number "); 14 | else 15 | System.out.println("not palindrome"); 16 | } 17 | } -------------------------------------------------------------------------------- /Pascal's_Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | public static int nCr(int n, int r) { 5 | long res = 1; 6 | // calculating nCr: 7 | for (int i = 0; i < r; i++) { 8 | res = res * (n - i); 9 | res = res / (i + 1); 10 | } 11 | return (int) res; 12 | } 13 | 14 | public static int[][] pascalTriangle(int N) { 15 | int[][] ans = new int[N][]; 16 | for (int row = 0; row < N; row++) { 17 | ans[row] = new int[row + 1]; 18 | for (int col = 0; col <= row; col++) { 19 | ans[row][col] = nCr(row, col); 20 | } 21 | } 22 | return ans; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Pattern132.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j]. 3 | Return true if there is a 132 pattern in nums, otherwise, return false. 4 | 5 | Test Case I: 6 | Input: nums = [1,2,3,4] 7 | Output: false 8 | Explanation: There is no 132 pattern in the sequence. 9 | 10 | Test Case II: 11 | Input: nums = [3,1,4,2] 12 | Output: true 13 | Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. 14 | */ 15 | 16 | import java.util.*; 17 | 18 | public class Pattern132 { 19 | private static boolean find132pattern(int[] nums) { 20 | int n = nums.length; 21 | if (n < 3) 22 | return false; 23 | Deque decreasingStack = new ArrayDeque<>(n); 24 | int maxThirdElement = Integer.MIN_VALUE; 25 | for (int i = n - 1; i >= 0; i--) { 26 | int currentNumber = nums[i]; 27 | if (currentNumber < maxThirdElement) 28 | return true; 29 | while (!decreasingStack.isEmpty() && decreasingStack.peek() < currentNumber) { 30 | maxThirdElement = decreasingStack.pop(); 31 | } 32 | decreasingStack.push(currentNumber); 33 | } 34 | return false; 35 | } 36 | public static void main(String[] args){ 37 | Scanner sc = new Scanner(System.in); 38 | int n; 39 | System.out.println("Enter the size of the array: "); 40 | n = sc.nextInt(); 41 | int[] nums = new int[n]; 42 | System.out.println("Enter the elements of the array: "); 43 | for(int i=0; i max) 18 | max = arr[a]; 19 | if(arr[a] < min) 20 | min = arr[a]; 21 | } 22 | 23 | range = max - min + 1; 24 | int[] phole = new int[range]; 25 | Arrays.fill(phole, 0); 26 | 27 | for(i = 0; i0) 35 | arr[index++]=j+min; 36 | 37 | } 38 | 39 | public static void main(String[] args) 40 | { 41 | PigeonholeSort sort = new PigeonholeSort(); 42 | int[] arr = {8, 3, 2, 7, 4, 6, 8}; 43 | 44 | System.out.print("Sorted order is : "); 45 | 46 | sort.pigeonhole_sort(arr,arr.length); 47 | 48 | for(int i=0 ; i0) 30 | { 31 | s=s*10+(no%10); 32 | no=no/10; 33 | } 34 | p=s*s; 35 | while(p>0) 36 | { 37 | s1=s1*10+(p%10); 38 | p=p/10; 39 | } 40 | return s1; 41 | } 42 | void print() //printing prime-adam numbers between m and n 43 | { 44 | int c=0; //declaration 45 | for(int i=m;i<=n;i++) 46 | { 47 | if((prime(i)==2) && ((adam(i))==(i*i))) 48 | { 49 | System.out.print(i+" "); 50 | c++; 51 | } 52 | } 53 | System.out.println(); 54 | System.out.print("FREQUENCY OF PRIME-ADAM INTEGERS IS="+c); 55 | } 56 | public static void main() 57 | { 58 | PrimeAdam ob=new PrimeAdam(); //creating object ob 59 | ob.input(); //calling function 60 | ob.print(); //calling function 61 | } 62 | } 63 | 64 | 65 | -------------------------------------------------------------------------------- /PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.PriorityQueue; 3 | 4 | class Pair { 5 | int node; 6 | int distance; 7 | 8 | Pair(int distance, int node) { 9 | this.node = node; 10 | this.distance = distance; 11 | } 12 | } 13 | 14 | class PrimsAlgorithm { 15 | static int spanningTree(int V, ArrayList>> adj) { 16 | PriorityQueue pq = new PriorityQueue<>((x, y) -> x.distance - y.distance); 17 | 18 | int[] vis = new int[V]; 19 | 20 | pq.add(new Pair(0, 0)); 21 | 22 | int sum = 0; 23 | 24 | while (pq.size() > 0) { 25 | int wt = pq.peek().distance; 26 | int node = pq.peek().node; 27 | pq.remove(); 28 | 29 | if (vis[node] == 1) 30 | continue; 31 | vis[node] = 1; 32 | sum = sum + wt; 33 | 34 | for (int i = 0; i < adj.get(node).size(); i++) { 35 | int edw = adj.get(node).get(i).get(1); 36 | int adjNode = adj.get(node).get(i).get(0); 37 | 38 | // if(edw == 0) continue; 39 | if (vis[adjNode] == 0) { 40 | pq.add(new Pair(edw, adjNode)); 41 | } 42 | } 43 | } 44 | return sum; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /PrintMazePaths.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers, n and m, representing the number of rows and columns in a maze, the objective is to identify and list all possible paths to navigate from the top-left corner to the bottom-right corner of the maze. 3 | 4 | There are specific constraints to be considered: 5 | Two types of moves are allowed: 6 | 'h' - Signifying a horizontal move, allowing one step to the right. 7 | 'v' - Signifying a vertical move, enabling one step downward. 8 | This program generates and presents a comprehensive list of all valid paths that conform to these constraints for maze traversal. 9 | 10 | Sample Input 11 | 3 12 | 3 13 | 14 | Sample Output 15 | [hhvv, hvhv, hvvh, vhhv, vhvh, vvhh] 16 | 17 | */ 18 | 19 | import java.util.*; 20 | 21 | public class PrintMazePaths { 22 | static void generate(int i, int j, int n, int m, String curr, ArrayList ans){ 23 | if(i==n-1 && j==m-1){ 24 | ans.add(curr); 25 | return; 26 | } 27 | if(i==n || j==m){ 28 | return; 29 | } 30 | generate(i, j+1, n, m, curr+'h', ans); 31 | generate(i+1, j, n, m, curr+'v', ans); 32 | } 33 | public static void main(String[] args) { 34 | Scanner sc=new Scanner(System.in); 35 | int n=sc.nextInt(); 36 | int m=sc.nextInt(); 37 | ArrayList ans=new ArrayList(); 38 | String curr=""; 39 | int i=0, j=0; 40 | generate(i, j, n, m, curr, ans); 41 | System.out.println(ans); 42 | } 43 | } 44 | 45 | //TC:O(2^(n*m)) 46 | //SC: O(n*m) 47 | -------------------------------------------------------------------------------- /PrintMazePathsOptimized.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class PrintMazePathsOptimized { 4 | static void generatePaths(int n, int m) { 5 | ArrayList[][] dp = new ArrayList[n][m]; 6 | 7 | // Initialize the last row and last column 8 | for (int i = 0; i < n; i++) { 9 | dp[i][m - 1] = new ArrayList<>(); 10 | dp[i][m - 1].add("h".repeat(n - i)); 11 | } 12 | for (int j = 0; j < m; j++) { 13 | dp[n - 1][j] = new ArrayList<>(); 14 | dp[n - 1][j].add("v".repeat(m - j)); 15 | } 16 | 17 | // Fill in the DP table 18 | for (int i = n - 2; i >= 0; i--) { 19 | for (int j = m - 2; j >= 0; j--) { 20 | dp[i][j] = new ArrayList<>(); 21 | dp[i][j].addAll(appendChar("h", dp[i][j + 1])); 22 | dp[i][j].addAll(appendChar("v", dp[i + 1][j])); 23 | } 24 | } 25 | 26 | // The result is in dp[0][0] 27 | System.out.println(dp[0][0]); 28 | } 29 | 30 | static ArrayList appendChar(String ch, ArrayList list) { 31 | ArrayList result = new ArrayList<>(); 32 | for (String str : list) { 33 | result.add(ch + str); 34 | } 35 | return result; 36 | } 37 | 38 | public static void main(String[] args) { 39 | int n = 3; 40 | int m = 3; 41 | generatePaths(n, m); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Q_5.java: -------------------------------------------------------------------------------- 1 | public class Q_5{ 2 | public static void main(String args[]) 3 | { 4 | int fl1=0; 5 | int fl2=0; 6 | int p[]=new int[101]; 7 | p[0]=0; 8 | p[1]=0; 9 | for(int i=2;i<=100;i++){ 10 | fl2=0; 11 | for(int j=2;j 20 | 21 |
22 | (Follow me on github - this motivates me to review & merge pull requests quicker.) 23 | 24 | ### Step#3: [Fork](https://github.com/AkashMarkad/Hacktoberfest-2024/fork) and clone the repository. 25 | 26 | ### Step#4: Send in your valuable projects/code to this repository in order to complete it. Please make sure you are making a valid contribution to the open source. 27 | 28 | ### Step#5: Add your files `git add -A` 29 | 30 | ### Step#6 Commit your changes `git commit -m "commit message here"` 31 | 32 | ### Step#7: Push to your fork `git push` and [submit a pull request]. 33 | 34 | ### Step#8: Pat your self on the back and wait for your pull request to be reviewed and merged. 35 | 36 | ## Are you a Software Developer💻? 37 | This repo is open to contributions (in the form of questions) from Software Developers. 38 | 39 | Enjoy Coding and Keep contributing to open source. 40 | 41 | (PS- Add your name to contributors.md in the format [ Your_Name ] (Your_Profile_Link)) 42 | 43 | Contribute some good codes, don't submit HelloWorld programs or your contribution will be marked as INVALID/SPAM. 44 | -------------------------------------------------------------------------------- /RadixSort.java: -------------------------------------------------------------------------------- 1 | // Radix Sort implementation 2 | 3 | import java.util.Arrays; 4 | 5 | public class RadixSort { 6 | private static final int BASE = 10; 7 | public static void main(String[] args) { 8 | int[] arr = new int[]{1, -2, -456, 803, 1000, -2033, -9, 0, 10}; 9 | long startTime = System.currentTimeMillis(); 10 | System.out.println("Original Array: " + Arrays.toString(arr)); 11 | radixSort(arr); 12 | long endTime = System.currentTimeMillis(); 13 | System.out.println("Sorted Array: " + Arrays.toString(arr) + "\nTime taken: " + 14 | ((endTime-startTime)*0.001)+" seconds"); 15 | } 16 | private static void radixSort(int[] arr){ 17 | if(arr.length==0) 18 | return; 19 | // Initialising these arrays for sorting the negative and the positive elements separately. 20 | int[] positive = Arrays.stream(arr).filter(i -> i>=0).toArray(); 21 | int[] negative = Arrays.stream(arr).filter(i -> i<0).toArray(); 22 | if(positive.length>0){ 23 | int max = positive[0]; 24 | // Find the maximum value present 25 | for (int j : positive) { 26 | max = Math.max(max, j); 27 | } 28 | // Looping through the elements and applying Counting Sort based on the number of digits 29 | // present in the maximum element 30 | for(int exp=1; max/exp>0; exp*=10){ 31 | countingSort(positive, positive.length, exp); 32 | } 33 | } 34 | if(negative.length>0){ 35 | // Converting the negative elements in the array to positive for sorting purpose 36 | for(int i=0; i0; exp*=BASE){ 47 | countingSort(negative, negative.length, exp); 48 | } 49 | } 50 | int index = 0; 51 | // Including the negative elements in the reverse order since (-9 < -1) & 52 | // the negative elements were sorted based on the absolute values of the elements in the array 53 | for (int i= negative.length-1; i>=0; i--) { 54 | arr[index++] = -negative[i]; 55 | } 56 | // Appending the positive elements after the negative elements in the array 57 | for (int j : positive) { 58 | arr[index++] = j; 59 | } 60 | } 61 | private static void countingSort(int[] arr, int n, int exp){ 62 | // Initialising the count array with size = BASE 63 | int[] count = new int[BASE]; 64 | // Initialising the output array with size = number of elements in positive or negative array 65 | int[] output = new int[n]; 66 | // Counting the frequency of the numbers < BASE i.e. from [0..9] in this case 67 | for (int j : arr) { 68 | count[(j / exp) % BASE]++; 69 | } 70 | // Calculate cumulative count 71 | for(int i=1; i=0; i--){ 76 | output[count[(arr[i]/exp)%BASE]-1] = arr[i]; 77 | count[(arr[i]/exp)%BASE]--; 78 | } 79 | // Copying the array elements present in output array to the original array 80 | System.arraycopy(output, 0, arr, 0, n); 81 | } 82 | } 83 | 84 | /* 85 | Time Complexity: O(d*(n+b)), d = number of digits 86 | n = number of elements in the array 87 | b = the base of the number system being used which is 10 here, 88 | this can be taken as 20, 30 anything based on the range of elements present, 89 | but the larger the base the more space will be required. 90 | Auxiliary Space Complexity: O(n+b), n = number of elements 91 | b = base of the number system being used which is 10 here 92 | */ -------------------------------------------------------------------------------- /RadixSortOptimized.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class RadixSortOptimized { 6 | public static void radixSort(Object[] arr) { 7 | if (arr == null || arr.length == 0) { 8 | return; 9 | } 10 | 11 | // Find the maximum value to determine the number of digits 12 | double max = (double) arr[0]; 13 | for (Object item : arr) { 14 | if ((double) item > max) { 15 | max = (double) item; 16 | } 17 | } 18 | 19 | // Perform counting sort for each digit position 20 | int exp = 1; 21 | List[] buckets = new ArrayList[10]; 22 | for (int i = 0; i < buckets.length; i++) { 23 | buckets[i] = new ArrayList<>(); 24 | } 25 | 26 | while (max / exp >= 1) { 27 | // Place elements into buckets based on the current digit 28 | for (Object item : arr) { 29 | int index = (int) (((double) item / exp) % 10); 30 | buckets[index].add(item); 31 | } 32 | 33 | // Copy elements from buckets back to the original array 34 | int currentIndex = 0; 35 | for (List bucket : buckets) { 36 | for (Object item : bucket) { 37 | arr[currentIndex++] = item; 38 | } 39 | bucket.clear(); 40 | } 41 | 42 | // Move to the next digit position 43 | exp *= 10; 44 | } 45 | } 46 | 47 | public static void main(String[] args) { 48 | // Example usage with both integers and non-integers 49 | Object[] arr = {5, 2.3, 10.1, 3.7, 8, 1.2, 4.5}; 50 | 51 | System.out.println("Before sorting: " + Arrays.toString(arr)); 52 | 53 | radixSort(arr); 54 | 55 | System.out.println("After sorting: " + Arrays.toString(arr)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Rearrange.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Rearrange{ 4 | 5 | //creating scanner object to take input 6 | static Scanner sc = new Scanner(System.in); 7 | 8 | //Declaring instance/class variables 9 | static String wrd , newwrd; 10 | 11 | //Default constructor 12 | Rearrange(){ 13 | wrd = ""; 14 | newwrd = ""; 15 | } 16 | 17 | //Function to accept the word from user. 18 | void readword(){ 19 | System.out.println("Enter Any Word : "); 20 | wrd = sc.next(); 21 | wrd = wrd.trim().toUpperCase(); 22 | } 23 | 24 | //to calculate the freqeuncy of vowels and consonants in given input/word 25 | void freq_vow_con(){ 26 | char c; 27 | int v=0 , co = 0; 28 | for( int i = 0 ; i s, int data) { 7 | // at every level -> upar jate hue element ko remove 8 | if (s.isEmpty()) { 9 | s.push(data); 10 | return; 11 | } 12 | int top = s.pop(); 13 | pushAtBottom(s, data); 14 | s.push(top); 15 | } 16 | 17 | public static void reverseStack(Stack s){ 18 | if(s.isEmpty()){ 19 | return; 20 | } 21 | int top = s.pop(); //removing of top 22 | reverseStack(s); //next call 23 | pushAtBottom(s, top); //stack insert from bottom 24 | } 25 | 26 | public static void printStack(Stack s){ 27 | while(!s.isEmpty()){ 28 | System.out.println(s.pop()); 29 | } 30 | } 31 | public static void main(String[] args) { 32 | Stack s= new Stack<>(); 33 | s.push(1); 34 | s.push(2); 35 | s.push(3); 36 | // 3 2 1 37 | reverseStack(s); 38 | printStack(s); 39 | // 1 2 3 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /RightTrianglePattern.java: -------------------------------------------------------------------------------- 1 | public class RightTrianglePattern 2 | { 3 | public static void main(String args[]) 4 | { 5 | int i, j, row=6; 6 | for(i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting"); 51 | printArray(arr); 52 | 53 | ShellSort ob = new ShellSort(); 54 | ob.sort(arr); 55 | 56 | System.out.println("Array after sorting"); 57 | printArray(arr); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /SlidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Deque; 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class SlidingWindowMaximum { 7 | 8 | // Function to find maximum element in every sliding window of size k 9 | public static List maxSlidingWindow(int[] nums, int k) { 10 | List result = new ArrayList<>(); 11 | if (nums == null || nums.length == 0) { 12 | return result; 13 | } 14 | 15 | Deque deque = new LinkedList<>(); 16 | 17 | for (int i = 0; i < nums.length; i++) { 18 | if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) { 19 | deque.pollFirst(); 20 | } 21 | while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { 22 | deque.pollLast(); 23 | } 24 | deque.offerLast(i); 25 | if (i >= k - 1) { 26 | result.add(nums[deque.peekFirst()]); 27 | } 28 | } 29 | return result; 30 | } 31 | 32 | public static void main(String[] args) { 33 | int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 }; 34 | int k = 3; 35 | 36 | List result = maxSlidingWindow(nums, k); 37 | System.out.println("Maximum elements in each sliding window of size " + k + ": " + result); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /StackUsingArray.java: -------------------------------------------------------------------------------- 1 | public class StackUsingArray { 2 | private int maxSize; 3 | private int top; 4 | private int[] stackArray; 5 | 6 | public StackUsingArray(int size) { 7 | maxSize = size; 8 | stackArray = new int[maxSize]; 9 | top = -1; 10 | } 11 | 12 | public void push(int value) { 13 | if (isFull()) { 14 | System.out.println("Stack is full. Cannot push " + value); 15 | } else { 16 | stackArray[++top] = value; 17 | System.out.println("Pushed " + value + " onto the stack"); 18 | } 19 | } 20 | 21 | public int pop() { 22 | if (isEmpty()) { 23 | System.out.println("Stack is empty. Cannot pop."); 24 | return -1; 25 | } else { 26 | int poppedValue = stackArray[top--]; 27 | System.out.println("Popped " + poppedValue + " from the stack"); 28 | return poppedValue; 29 | } 30 | } 31 | 32 | public int peek() { 33 | if (isEmpty()) { 34 | System.out.println("Stack is empty. Cannot peek."); 35 | return -1; 36 | } else { 37 | return stackArray[top]; 38 | } 39 | } 40 | 41 | public boolean isEmpty() { 42 | return top == -1; 43 | } 44 | 45 | public boolean isFull() { 46 | return top == maxSize - 1; 47 | } 48 | 49 | public int size() { 50 | return top + 1; 51 | } 52 | 53 | public static void main(String[] args) { 54 | StackUsingArray stack = new StackUsingArray(5); 55 | 56 | stack.push(1); 57 | stack.push(2); 58 | stack.push(3); 59 | 60 | System.out.println("Stack size: " + stack.size()); 61 | System.out.println("Top element: " + stack.peek()); 62 | stack.pop(); 63 | System.out.println("Popped. New top element: " + stack.peek()); 64 | 65 | stack.pop(); 66 | stack.pop(); 67 | stack.pop(); 68 | 69 | System.out.println("Is stack empty? " + stack.isEmpty()); 70 | } 71 | } -------------------------------------------------------------------------------- /StackUsingQueue.java: -------------------------------------------------------------------------------- 1 | /* Java Program to implement a stack using 2 | two queue */ 3 | import java.util.*; 4 | 5 | class StackUsingQueue { 6 | 7 | static class Stack { 8 | // Two inbuilt queues 9 | static Queue q1 10 | = new LinkedList(); 11 | static Queue q2 12 | = new LinkedList(); 13 | 14 | // To maintain current number of 15 | // elements 16 | static int curr_size; 17 | 18 | static void push(int x) 19 | { 20 | // Push x first in empty q2 21 | q2.add(x); 22 | 23 | // Push all the remaining 24 | // elements in q1 to q2. 25 | while (!q1.isEmpty()) { 26 | q2.add(q1.peek()); 27 | q1.remove(); 28 | } 29 | 30 | // swap the names of two queues 31 | Queue q = q1; 32 | q1 = q2; 33 | q2 = q; 34 | } 35 | 36 | static void pop() 37 | { 38 | 39 | // if no elements are there in q1 40 | if (q1.isEmpty()) 41 | return; 42 | q1.remove(); 43 | } 44 | 45 | static int top() 46 | { 47 | if (q1.isEmpty()) 48 | return -1; 49 | return q1.peek(); 50 | } 51 | 52 | static int size() { return q1.size(); } 53 | } 54 | 55 | // driver code 56 | public static void main(String[] args) 57 | { 58 | Stack s = new Stack(); 59 | s.push(1); 60 | s.push(2); 61 | s.push(3); 62 | 63 | System.out.println("current size: " + s.size()); 64 | System.out.println(s.top()); 65 | s.pop(); 66 | System.out.println(s.top()); 67 | s.pop(); 68 | System.out.println(s.top()); 69 | 70 | System.out.println("current size: " + s.size()); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /StringPalindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class StringPalindrome { 3 | public static boolean isPalindrome(String str) { 4 | String reverse = new StringBuilder(str).reverse().toString(); 5 | return str.equals(reverse); 6 | } 7 | 8 | public static void main(String[] args) { 9 | String str = "racecar"; 10 | boolean isPal = isPalindrome(str); 11 | System.out.println("String: " + str); 12 | System.out.println("Is Palindrome? " + isPal); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Strings.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Strings { 4 | public static void main(String args[]){ 5 | Scanner sc = new Scanner(System.in); 6 | System.out.println("Enter name"); 7 | String name = sc.nextLine(); 8 | System.out.println("Your name is "+name); 9 | 10 | //concatenation 11 | System.out.println("Enter first name"); 12 | String first = sc.next(); 13 | System.out.println("Enter last name"); 14 | String last = sc.next(); 15 | String fullname = first+" "+last; 16 | System.out.println("Your full name is"+fullname); 17 | System.out.println(fullname.length()); 18 | 19 | //charAt 20 | 21 | for (int i = 0; i < fullname.length(); i++) { 22 | System.out.println(fullname.charAt(i)); 23 | } 24 | 25 | 26 | //comparison function 27 | 28 | if (first.compareTo(last)==0){ 29 | System.out.println("Equal"); 30 | } else if (first.compareTo(last)>0){ 31 | System.out.println("Strings are not equal and greater than other name"); 32 | }else { 33 | System.out.println("Strings are not equal and second string is greater than 1st string"); 34 | } 35 | 36 | //Substring 37 | 38 | String Sub = fullname.substring(5, fullname.length()); 39 | System.out.println(Sub); 40 | 41 | 42 | //Check for substring existence 43 | System.out.println("Enter substring you want to check"); 44 | String x = sc.next(); 45 | if (name.contains(x)) { 46 | System.out.println("Substring Found"); 47 | } 48 | 49 | 50 | //Replace Substrings 51 | System.out.println("Enter string you want to replace with"); 52 | String y = sc.next(); 53 | String replacedStr = name.replace(x, y); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /SubArrayZeroSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class SubArrayZeroSum { 3 | public static int[] find(int arr[]){ 4 | Map sumMap=new HashMap<>(); 5 | } 6 | public static void main(String[] args) { 7 | int arr[]={4,5,3,-3,2,-2}; 8 | int final[]=find(arr); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /SubsequencesSumK.java: -------------------------------------------------------------------------------- 1 | //Question : Find all subsequences with sum equals to K 2 | 3 | import java.util.*; 4 | public class SubsequencesSumK 5 | { 6 | 7 | // Function to find the subsequences 8 | // with given sum 9 | public static void subSequenceSum( 10 | ArrayList> ans, 11 | int a[], ArrayList temp, 12 | int k, int start) 13 | { 14 | // Here we have used ArrayList 15 | // of ArrayList in Java for 16 | // implementation of Jagged Array 17 | 18 | // if k < 0 then the sum of 19 | // the current subsequence 20 | // in temp is greater than K 21 | if(start > a.length || k < 0) 22 | return ; 23 | 24 | // if(k==0) means that the sum 25 | // of this subsequence 26 | // is equal to K 27 | if(k == 0) 28 | { 29 | ans.add( 30 | new ArrayList(temp) 31 | ); 32 | return ; 33 | } 34 | else { 35 | for (int i = start; 36 | i < a.length; i++) { 37 | 38 | // Adding a new 39 | // element into temp 40 | temp.add(a[i]); 41 | 42 | // After selecting an 43 | // element from the 44 | // array we subtract K 45 | // by that value 46 | subSequenceSum(ans, a, 47 | temp, k - a[i],i+1); 48 | 49 | // Remove the lastly 50 | // added element 51 | temp.remove(temp.size() - 1); 52 | } 53 | } 54 | } 55 | 56 | // Driver Code 57 | public static void main(String args[]) 58 | { 59 | int arr[] = {5, 12, 3, 17, 1, 60 | 18, 15, 3, 17}; 61 | int k = 6; 62 | ArrayList> ans; 63 | ans= new ArrayList< 64 | ArrayList>(); 65 | subSequenceSum(ans, arr, 66 | new ArrayList(), k, 0); 67 | 68 | // Loop to print the subsequences 69 | for(int i = 0; i < ans.size(); 70 | i++){ 71 | for(int j = 0; 72 | j < ans.get(i).size(); j++){ 73 | System.out.print( 74 | ans.get(i).get(j)); 75 | System.out.print(" "); 76 | } 77 | System.out.println(); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /SumOfPrime.java: -------------------------------------------------------------------------------- 1 | public class SumOfPrime { 2 | public static void main(String[] args) { 3 | int sum=0; 4 | for(int i=2;i<10;i++){ 5 | int num=i; 6 | int count=0; 7 | for(int j=1;j<=num;j++){ 8 | if(num%j==0){ 9 | count++; 10 | } 11 | } 12 | if(count==2) sum+=num; 13 | } 14 | System.out.println(sum); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ThreadPriorityExample.java: -------------------------------------------------------------------------------- 1 | public class ThreadPriorityExample { 2 | 3 | public static void main(String[] args) { 4 | Thread thread1 = new Thread(() -> { 5 | System.out.println("Thread 1 with priority " + Thread.MAX_PRIORITY + " is running..."); 6 | try { 7 | Thread.sleep(1000); 8 | } catch (InterruptedException e) { 9 | e.printStackTrace(); 10 | } 11 | }); 12 | thread1.setPriority(Thread.MAX_PRIORITY); 13 | 14 | Thread thread2 = new Thread(() -> { 15 | System.out.println("Thread 2 with priority " + Thread.MAX_PRIORITY + " is running..."); 16 | try { 17 | Thread.sleep(1000); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | }); 22 | thread2.setPriority(Thread.MAX_PRIORITY); 23 | 24 | Thread thread3 = new Thread(() -> { 25 | System.out.println("Thread 3 with priority " + Thread.NORM_PRIORITY + " is running..."); 26 | }); 27 | thread3.setPriority(Thread.NORM_PRIORITY); 28 | 29 | Thread thread4 = new Thread(() -> { 30 | System.out.println("Thread 4 with priority " + Thread.NORM_PRIORITY + " is running..."); 31 | }); 32 | thread4.setPriority(Thread.NORM_PRIORITY); 33 | 34 | Thread thread5 = new Thread(() -> { 35 | System.out.println("Thread 5 with priority " + Thread.MIN_PRIORITY + " is running..."); 36 | }); 37 | thread5.setPriority(Thread.MIN_PRIORITY); 38 | 39 | thread1.start(); 40 | thread2.start(); 41 | thread3.start(); 42 | thread4.start(); 43 | thread5.start(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ThreadSynchronizationExample.java: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicInteger; 2 | 3 | public class ThreadSynchronizationExample { 4 | 5 | private static final int NUM_THREADS = 10; 6 | 7 | public static void main(String[] args) { 8 | AtomicInteger counter = new AtomicInteger(0); 9 | 10 | for (int i = 0; i < NUM_THREADS; i++) { 11 | Thread thread = new Thread(() -> { 12 | for (int j = 0; j < 1000; j++) { 13 | counter.incrementAndGet(); 14 | } 15 | }); 16 | thread.start(); 17 | } 18 | 19 | try { 20 | for (Thread thread : Thread.getAllStackTraces().keySet()) { 21 | thread.join(); 22 | } 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | 27 | System.out.println("Final counter value: " + counter.get()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ThreeSum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class ThreeSum { 6 | public static List> threeSum(int[] nums) { 7 | Arrays.sort(nums); 8 | List> triplets = new ArrayList<>(); 9 | 10 | for (int i = 0; i < nums.length - 2; i++) { 11 | if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { 12 | int start = i + 1; 13 | int end = nums.length - 1; 14 | int target = -nums[i]; 15 | 16 | while (start < end) { 17 | if (nums[start] + nums[end] == target) { 18 | triplets.add(Arrays.asList(nums[i], nums[start], nums[end])); 19 | 20 | while (start < end && nums[start] == nums[start + 1]) start++; 21 | while (start < end && nums[end] == nums[end - 1]) end--; 22 | 23 | start++; 24 | end--; 25 | } else if (nums[start] + nums[end] < target) { 26 | start++; 27 | } else { 28 | end--; 29 | } 30 | } 31 | } 32 | } 33 | return triplets; 34 | } 35 | public static void main(String[] args) { 36 | int nums[]= {-1,0,1,2,-1,-4}; 37 | System.out.println(threeSum(nums)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /TimSortJava: -------------------------------------------------------------------------------- 1 | class TimSort { 2 | static int RUN = 32; 3 | int min(int a, int b) 4 | { 5 | if(a= beg && temp <= a[j]) 22 | { 23 | a[j+1] = a[j]; 24 | jj = j-1; 25 | } 26 | a[j+1] = temp; 27 | } 28 | } 29 | /* Function to merge the sorted runs */ 30 | void merge(int a[], int beg, int mid, int end) 31 | { 32 | int i, j, k; 33 | int n1 = mid - beg + 1; 34 | int n2 = end - mid; 35 | //temporary arrays 36 | int[] LeftArray = new int [n1]; 37 | int[] RightArray = new int [n2]; 38 | /* copy data to temp arrays */ 39 | for (i = 0; i < n1; i++) 40 | LeftArray[i] = a[beg + i]; 41 | for (j = 0; j < n2; j++) 42 | RightArray[j] = a[mid + 1 + j]; 43 | i = 0; 44 | j = 0; 45 | k = beg; 46 | while (i < n1 && j < n2) 47 | { 48 | if(LeftArray[i] <= RightArray[j]) 49 | { 50 | a[k] = LeftArray[i]; 51 | i++; 52 | } 53 | else 54 | { 55 | a[k] = RightArray[j]; 56 | j++; 57 | } 58 | k++; 59 | } 60 | while (i adj[]; 7 | 8 | public Graph(int V) { 9 | this.V = V; 10 | adj = new ArrayList[V]; 11 | for (int i = 0; i < V; i++) { 12 | adj[i] = new ArrayList<>(); 13 | } 14 | } 15 | 16 | public void addEdge(int src, int dest) { 17 | adj[src].add(dest); 18 | } 19 | 20 | public List topologicalSort() { 21 | Stack stack = new Stack<>(); 22 | boolean[] visited = new boolean[V]; 23 | 24 | for (int i = 0; i < V; i++) { 25 | if (!visited[i]) { 26 | topologicalSortUtil(i, visited, stack); 27 | } 28 | } 29 | 30 | List result = new ArrayList<>(); 31 | while (!stack.isEmpty()) { 32 | result.add(stack.pop()); 33 | } 34 | 35 | return result; 36 | } 37 | 38 | private void topologicalSortUtil(int v, boolean[] visited, Stack stack) { 39 | visited[v] = true; 40 | for (Integer neighbor : adj[v]) { 41 | if (!visited[neighbor]) { 42 | topologicalSortUtil(neighbor, visited, stack); 43 | } 44 | } 45 | stack.push(v); 46 | } 47 | } 48 | 49 | public static void main(String[] args) { 50 | int V = 6; 51 | Graph graph = new Graph(V); 52 | 53 | graph.addEdge(4, 0); 54 | graph.addEdge(4, 1); 55 | graph.addEdge(1, 0); 56 | graph.addEdge(2, 3); 57 | graph.addEdge(3, 1); 58 | graph.addEdge(5, 0); 59 | graph.addEdge(5, 2); 60 | 61 | List result = graph.topologicalSort(); 62 | for (Integer vertex : result) { 63 | System.out.print(vertex + " "); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Tower_of_Hanoi.java: -------------------------------------------------------------------------------- 1 | // Java recursive program to solve tower of hanoi puzzle 2 | 3 | class HacktoberFest 4 | { 5 | // Java recursive function to solve tower of hanoi puzzle 6 | static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 7 | { 8 | if (n == 1) 9 | { 10 | System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); 11 | return; 12 | } 13 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 14 | System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); 15 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 16 | } 17 | 18 | // Driver method 19 | public static void main(String args[]) 20 | { 21 | int n = 4; // Number of disks 22 | towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Vstarpattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | public class Vstarpattern{ 4 | public static void main(String[] args){ 5 | for(int i=5;i>=1;i--){ 6 | for(int j=5;j>i;j--){ 7 | System.out.print(" "); 8 | } 9 | for(int k =1;k<(i*2);k++) 10 | { 11 | if(k>1 && k<(i*2)-1) 12 | { 13 | System.out.print(" "); 14 | } 15 | else{ 16 | System.out.print("*"); 17 | 18 | } 19 | }System.out.println(); 20 | }}} 21 | -------------------------------------------------------------------------------- /WordBreak.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.List; 3 | import java.util.Set; 4 | 5 | public class WordBreak { 6 | public static boolean wordBreak(String s, List wordDict) { 7 | Set wordSet = new HashSet<>(wordDict); 8 | int n = s.length(); 9 | boolean[] dp = new boolean[n + 1]; 10 | dp[0] = true; 11 | 12 | for (int i = 1; i <= n; i++) { 13 | for (int j = 0; j < i; j++) { 14 | if (dp[j] && wordSet.contains(s.substring(j, i))) { 15 | dp[i] = true; 16 | break; 17 | } 18 | } 19 | } 20 | 21 | return dp[n]; 22 | } 23 | 24 | public static void main(String[] args) { 25 | String s = "leetcode"; 26 | List wordDict = List.of("leet", "code"); 27 | 28 | boolean result = wordBreak(s, wordDict); 29 | if (result) { 30 | System.out.println("The string can be segmented into valid words."); 31 | } else { 32 | System.out.println("The string cannot be segmented into valid words."); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /all_subsequences_with_sum_equal_k.java: -------------------------------------------------------------------------------- 1 | //Question : Find all subsequences with sum equals to K 2 | 3 | import java.util.*; 4 | public class SubsequenceSumK 5 | { 6 | 7 | // Function to find the subsequences 8 | // with given sum 9 | public static void subSequenceSum( 10 | ArrayList> ans, 11 | int a[], ArrayList temp, 12 | int k, int start) 13 | { 14 | // Here we have used ArrayList 15 | // of ArrayList in Java for 16 | // implementation of Jagged Array 17 | 18 | // if k < 0 then the sum of 19 | // the current subsequence 20 | // in temp is greater than K 21 | if(start > a.length || k < 0) 22 | return ; 23 | 24 | // if(k==0) means that the sum 25 | // of this subsequence 26 | // is equal to K 27 | if(k == 0) 28 | { 29 | ans.add( 30 | new ArrayList(temp) 31 | ); 32 | return ; 33 | } 34 | else { 35 | for (int i = start; 36 | i < a.length; i++) { 37 | 38 | // Adding a new 39 | // element into temp 40 | temp.add(a[i]); 41 | 42 | // After selecting an 43 | // element from the 44 | // array we subtract K 45 | // by that value 46 | subSequenceSum(ans, a, 47 | temp, k - a[i],i+1); 48 | 49 | // Remove the lastly 50 | // added element 51 | temp.remove(temp.size() - 1); 52 | } 53 | } 54 | } 55 | 56 | // Driver Code 57 | public static void main(String args[]) 58 | { 59 | int arr[] = {5, 12, 3, 17, 1, 60 | 18, 15, 3, 17}; 61 | int k = 6; 62 | ArrayList> ans; 63 | ans= new ArrayList< 64 | ArrayList>(); 65 | subSequenceSum(ans, arr, 66 | new ArrayList(), k, 0); 67 | 68 | // Loop to print the subsequences 69 | for(int i = 0; i < ans.size(); 70 | i++){ 71 | for(int j = 0; 72 | j < ans.get(i).size(); j++){ 73 | System.out.print( 74 | ans.get(i).get(j)); 75 | System.out.print(" "); 76 | } 77 | System.out.println(); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /apalimdrome.java: -------------------------------------------------------------------------------- 1 | class PalindromeExample{ 2 | public static void main(String args[]){ 3 | int r,sum=0,temp; 4 | int n=454;//It is the number variable to be checked for palindrome 5 | 6 | temp=n; 7 | while(n>0){ 8 | r=n%10; //getting remainder 9 | sum=(sum*10)+r; 10 | n=n/10; 11 | } 12 | if(temp==sum) 13 | System.out.println("palindrome number "); 14 | else 15 | System.out.println("not palindrome"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /binarysearch_rec.java: -------------------------------------------------------------------------------- 1 | class BinarySearchRecursion { 2 | 3 | 4 | int binarySearch(int arr[], int l, int r, int x) 5 | { 6 | if (r >= l) { 7 | int mid = l + (r - l) / 2; 8 | if (arr[mid] == x) 9 | return mid; 10 | if (arr[mid] > x) 11 | return binarySearch(arr, l, mid - 1, x); 12 | return binarySearch(arr, mid + 1, r, x); 13 | } 14 | 15 | 16 | return -1; 17 | } 18 | 19 | 20 | public static void main(String args[]) 21 | { 22 | BinarySearch ob = new BinarySearch(); 23 | int arr[] = { 2, 3, 4, 10, 40 }; 24 | int n = arr.length; 25 | int x = 10; 26 | int result = ob.binarySearch(arr, 0, n - 1, x); 27 | if (result == -1) 28 | System.out.println( 29 | "Element is not present in array"); 30 | else 31 | System.out.println( 32 | "Element is present at index " + result); 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /bit_manipn.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | import javax.swing.event.DocumentEvent.ElementChange; 4 | 5 | public class bit_manipn { 6 | //**Get bit 7 | // public static void main(String[] args){ 8 | // int n=5; 9 | // int pos=2; 10 | // int bitmask=1< arr[j+1]){ 16 | int temp = arr[j]; 17 | arr[j]= arr[j+1]; 18 | arr[j+1]= temp; 19 | } 20 | } 21 | } 22 | System.out.println("sorted array is "); 23 | for(int i = 0;i edges, int V, int start) { 18 | int[] dist = new int[V]; 19 | Arrays.fill(dist, Integer.MAX_VALUE); 20 | dist[start] = 0; 21 | 22 | for (int i = 0; i < V - 1; i++) { 23 | for (Edge edge : edges) { 24 | int u = edge.src; 25 | int v = edge.dest; 26 | int w = edge.weight; 27 | 28 | if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { 29 | dist[v] = dist[u] + w; 30 | } 31 | } 32 | } 33 | 34 | // Check for negative-weight cycles 35 | for (Edge edge : edges) { 36 | int u = edge.src; 37 | int v = edge.dest; 38 | int w = edge.weight; 39 | 40 | if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { 41 | System.out.println("Graph contains a negative-weight cycle."); 42 | return; 43 | } 44 | } 45 | 46 | System.out.println("Shortest Distances from Node " + start + ":"); 47 | for (int i = 0; i < V; i++) { 48 | System.out.println("Node " + i + ": " + dist[i]); 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | int V = 5; 54 | List edges = new ArrayList<>(); 55 | edges.add(new Edge(0, 1, 4)); 56 | edges.add(new Edge(0, 2, 3)); 57 | edges.add(new Edge(1, 2, -2)); 58 | edges.add(new Edge(1, 3, 2)); 59 | edges.add(new Edge(1, 4, 3)); 60 | edges.add(new Edge(3, 2, 5)); 61 | edges.add(new Edge(3, 1, 1)); 62 | edges.add(new Edge(4, 3, -4)); 63 | 64 | int startNode = 0; 65 | 66 | bellmanFord(edges, V, startNode); 67 | } 68 | } 69 | 70 | /* 71 | The provided Java program implements the Bellman-Ford algorithm to find the shortest distances from a given starting node to all other nodes in a directed graph. Here's a description of the program: 72 | 73 | BellmanFordAlgorithm Class: 74 | 75 | This is the main class that contains the bellmanFord method for performing the Bellman-Ford algorithm and the main method to demonstrate its usage. 76 | Edge Class: 77 | 78 | The Edge class is a nested class used to represent edges in the graph. Each edge has a source node (src), a destination node (dest), and a weight (weight) associated with it. 79 | bellmanFord Method: 80 | 81 | The bellmanFord method takes three parameters: a list of Edge objects representing the graph's edges (edges), the number of vertices (V), and the starting node (start) from which the shortest distances are to be calculated. 82 | It initializes an array dist to store the shortest distances from the starting node to all other nodes. Initially, all distances are set to Integer.MAX_VALUE except for the starting node, which is set to 0. 83 | The method then performs the Bellman-Ford algorithm by iterating over the vertices V - 1 times (where V is the number of vertices). In each iteration, it relaxes the edges by checking if there is a shorter path to a vertex through the current vertex. If a shorter path is found, it updates the distance. 84 | After the main loop, the method checks for the presence of negative-weight cycles by iterating over the edges again. If a shorter path is found, it indicates the existence of a negative-weight cycle in the graph. 85 | Finally, it prints the shortest distances from the starting node to all other nodes. 86 | main Method: 87 | 88 | The main method is the entry point of the program. 89 | It creates a graph with 5 vertices and initializes a list of Edge objects (edges) to represent the graph's edges. 90 | Each Edge object in the edges list represents a directed edge with its source, destination, and weight. 91 | It specifies the starting node (startNode) from which to find the shortest distances. 92 | It calls the bellmanFord method with the graph's edges, the number of vertices, and the starting node as arguments to calculate and display the shortest distances. 93 | Overall, this program demonstrates the Bellman-Ford algorithm for finding the shortest distances in a weighted directed graph. It also checks for the presence of negative-weight cycles, which can affect the correctness of the shortest path calculations. 94 | */ 95 | -------------------------------------------------------------------------------- /graph/algorithms/DijkstrasAlgorithmMST.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms; 2 | 3 | import java.util.*; 4 | 5 | public class DijkstrasAlgorithmMST { 6 | 7 | public static void dijkstra(int[][] graph, int start) { 8 | int V = graph.length; 9 | int[] dist = new int[V]; 10 | Arrays.fill(dist, Integer.MAX_VALUE); 11 | dist[start] = 0; 12 | 13 | boolean[] visited = new boolean[V]; 14 | 15 | for (int count = 0; count < V - 1; count++) { 16 | int u = minDistance(dist, visited); 17 | visited[u] = true; 18 | 19 | for (int v = 0; v < V; v++) { 20 | if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE 21 | && dist[u] + graph[u][v] < dist[v]) { 22 | dist[v] = dist[u] + graph[u][v]; 23 | } 24 | } 25 | } 26 | 27 | System.out.println("Shortest Distances from Node " + start + ":"); 28 | for (int i = 0; i < V; i++) { 29 | System.out.println("Node " + i + ": " + dist[i]); 30 | } 31 | } 32 | 33 | public static int minDistance(int[] dist, boolean[] visited) { 34 | int V = dist.length; 35 | int minDist = Integer.MAX_VALUE; 36 | int minIndex = -1; 37 | 38 | for (int v = 0; v < V; v++) { 39 | if (!visited[v] && dist[v] < minDist) { 40 | minDist = dist[v]; 41 | minIndex = v; 42 | } 43 | } 44 | 45 | return minIndex; 46 | } 47 | 48 | public static void main(String[] args) { 49 | int[][] graph = { 50 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 51 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 52 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 53 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 54 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 55 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 56 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 57 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 58 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 59 | }; 60 | 61 | int startNode = 0; 62 | 63 | dijkstra(graph, startNode); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /graph/algorithms/DijkstrasAlgorithmSP.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms; 2 | 3 | import java.util.*; 4 | 5 | public class DijkstrasAlgorithmSP { 6 | 7 | public static void dijkstra(int[][] graph, int start) { 8 | int V = graph.length; 9 | int[] dist = new int[V]; 10 | Arrays.fill(dist, Integer.MAX_VALUE); 11 | dist[start] = 0; 12 | 13 | boolean[] visited = new boolean[V]; 14 | 15 | for (int count = 0; count < V - 1; count++) { 16 | int u = minDistance(dist, visited); 17 | visited[u] = true; 18 | 19 | for (int v = 0; v < V; v++) { 20 | if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE 21 | && dist[u] + graph[u][v] < dist[v]) { 22 | dist[v] = dist[u] + graph[u][v]; 23 | } 24 | } 25 | } 26 | 27 | System.out.println("Shortest Distances from Node " + start + ":"); 28 | for (int i = 0; i < V; i++) { 29 | System.out.println("Node " + i + ": " + dist[i]); 30 | } 31 | } 32 | 33 | public static int minDistance(int[] dist, boolean[] visited) { 34 | int V = dist.length; 35 | int minDist = Integer.MAX_VALUE; 36 | int minIndex = -1; 37 | 38 | for (int v = 0; v < V; v++) { 39 | if (!visited[v] && dist[v] < minDist) { 40 | minDist = dist[v]; 41 | minIndex = v; 42 | } 43 | } 44 | 45 | return minIndex; 46 | } 47 | 48 | public static void main(String[] args) { 49 | int[][] graph = { 50 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 51 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 52 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 53 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 54 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 55 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 56 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 57 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 58 | {0, 0, 2, 0, 0, 0, 6, 7, 0} 59 | }; 60 | 61 | int startNode = 0; 62 | 63 | dijkstra(graph, startNode); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /graph/algorithms/FloodFillMruganka.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms;/*Given a 2D screen arr[][] where each arr[i][j] is an integer representing the color of that pixel, also given the location of a pixel (X, Y) and a color C, the task is to replace the color of the given pixel and all the adjacent same-colored pixels with the given color.*/ 2 | 3 | // Java implementation of the approach 4 | import java.util.*; 5 | import java.awt.Point; 6 | public class FloodFillMruganka 7 | { 8 | // Function that returns true if 9 | // the given pixel is valid 10 | static boolean isValid(int[][] screen, int m, int n, int x, int y, int prevC, int newC) 11 | { 12 | if(x < 0 || x >= m || y < 0 || y >= n || screen[x][y] != prevC 13 | || screen[x][y]== newC) 14 | return false; 15 | return true; 16 | } 17 | 18 | 19 | // FloodFill function 20 | static void floodFill(int[][] screen, int m, int n, int x, int y, int prevC, int newC) 21 | { 22 | Vector queue = new Vector(); 23 | 24 | // Append the position of starting 25 | // pixel of the component 26 | queue.add(new Point(x, y)); 27 | 28 | // Color the pixel with the new color 29 | screen[x][y] = newC; 30 | 31 | // While the queue is not empty i.e. the 32 | // whole component having prevC color 33 | // is not colored with newC color 34 | while(queue.size() > 0) 35 | { 36 | // Dequeue the front node 37 | Point currPixel = queue.get(queue.size() - 1); 38 | queue.remove(queue.size() - 1); 39 | 40 | int posX = currPixel.x; 41 | int posY = currPixel.y; 42 | 43 | // Check if the adjacent 44 | // pixels are valid 45 | if(isValid(screen, m, n, posX + 1, posY, prevC, newC)) 46 | { 47 | // Color with newC 48 | // if valid and enqueue 49 | screen[posX + 1][posY] = newC; 50 | queue.add(new Point(posX + 1, posY)); 51 | } 52 | 53 | if(isValid(screen, m, n, posX-1, posY, prevC, newC)) 54 | { 55 | screen[posX-1][posY]= newC; 56 | queue.add(new Point(posX-1, posY)); 57 | } 58 | 59 | if(isValid(screen, m, n, posX, posY + 1, prevC, newC)) 60 | { 61 | screen[posX][posY + 1]= newC; 62 | queue.add(new Point(posX, posY + 1)); 63 | } 64 | 65 | if(isValid(screen, m, n, posX, posY-1, prevC, newC)) 66 | { 67 | screen[posX][posY-1]= newC; 68 | queue.add(new Point(posX, posY-1)); 69 | } 70 | } 71 | } 72 | 73 | public static void main(String[] args) { 74 | int[][] screen ={ 75 | {1, 1, 1, 1, 1, 1, 1, 1}, 76 | {1, 1, 1, 1, 1, 1, 0, 0}, 77 | {1, 0, 0, 1, 1, 0, 1, 1}, 78 | {1, 2, 2, 2, 2, 0, 1, 0}, 79 | {1, 1, 1, 2, 2, 0, 1, 0}, 80 | {1, 1, 1, 2, 2, 2, 2, 0}, 81 | {1, 1, 1, 1, 1, 2, 1, 1}, 82 | {1, 1, 1, 1, 1, 2, 2, 1}}; 83 | 84 | // Row of the display 85 | int m = screen.length; 86 | 87 | // Column of the display 88 | int n = screen.length; 89 | 90 | // Co-ordinate provided by the user 91 | int x = 4; 92 | int y = 4; 93 | 94 | // Current color at that co-ordinate 95 | int prevC = screen[x][y]; 96 | 97 | // New color that has to be filled 98 | int newC = 3; 99 | floodFill(screen, m, n, x, y, prevC, newC); 100 | 101 | // Printing the updated screen 102 | for(int i = 0; i < m; i++) 103 | { 104 | for(int j = 0; j < n; j++) 105 | { 106 | System.out.print(screen[i][j] + " "); 107 | } 108 | System.out.println(); 109 | } 110 | } 111 | } 112 | 113 | -------------------------------------------------------------------------------- /graph/algorithms/FloydWarshallAlgorithm.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms; 2 | 3 | public class FloydWarshallAlgorithm { 4 | 5 | public static void floydWarshall(int[][] graph) { 6 | int V = graph.length; 7 | int[][] dist = new int[V][V]; 8 | 9 | for (int i = 0; i < V; i++) { 10 | for (int j = 0; j < V; j++) { 11 | dist[i][j] = graph[i][j]; 12 | } 13 | } 14 | 15 | for (int k = 0; k < V; k++) { 16 | for (int i = 0; i < V; i++) { 17 | for (int j = 0; j < V; j++) { 18 | if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE 19 | && dist[i][k] + dist[k][j] < dist[i][j]) { 20 | dist[i][j] = dist[i][k] + dist[k][j]; 21 | } 22 | } 23 | } 24 | } 25 | 26 | System.out.println("Shortest Distances between all pairs of nodes:"); 27 | for (int i = 0; i < V; i++) { 28 | for (int j = 0; j < V; j++) { 29 | if (dist[i][j] == Integer.MAX_VALUE) { 30 | System.out.print("INF\t"); 31 | } else { 32 | System.out.print(dist[i][j] + "\t"); 33 | } 34 | } 35 | System.out.println(); 36 | } 37 | } 38 | 39 | public static void main(String[] args) { 40 | int V = 4; 41 | int[][] graph = { 42 | {0, 5, Integer.MAX_VALUE, 10}, 43 | {Integer.MAX_VALUE, 0, 3, Integer.MAX_VALUE}, 44 | {Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1}, 45 | {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0} 46 | }; 47 | 48 | floydWarshall(graph); 49 | } 50 | } 51 | /*This Java program implements the Floyd-Warshall algorithm to find the shortest distances between all pairs of nodes in a weighted directed graph. Here's a concise description of its key components and functionality: 52 | 53 | floydWarshall method: 54 | 55 | Computes the shortest distances between all pairs of nodes in a given graph. 56 | Initializes a 2D array dist to store the shortest distances between nodes. 57 | Iterates through all pairs of nodes and initializes dist with the initial edge weights from the graph. 58 | Performs the Floyd-Warshall algorithm by considering each intermediate vertex and updating the shortest distances as needed. 59 | Prints the shortest distances between all pairs of nodes. 60 | main method: 61 | 62 | Specifies the number of vertices V and initializes a 2D array graph representing the weighted directed graph. 63 | Calls the floydWarshall method to compute and print the shortest distances between all pairs of nodes in the graph. 64 | The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of vertices in a weighted graph, including both positive and negative edge weights. It is suitable for finding the shortest paths in dense graphs or when the graph's structure changes over time.*/ 65 | 66 | -------------------------------------------------------------------------------- /graph/algorithms/KruskalsAlgorithm.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms; 2 | 3 | import java.util.*; 4 | 5 | class Edge implements Comparable { 6 | int src, dest, weight; 7 | 8 | public Edge(int src, int dest, int weight) { 9 | this.src = src; 10 | this.dest = dest; 11 | this.weight = weight; 12 | } 13 | 14 | @Override 15 | public int compareTo(Edge other) { 16 | return this.weight - other.weight; 17 | } 18 | } 19 | 20 | public class KruskalsAlgorithm { 21 | 22 | public static List kruskalsMST(List edges, int V) { 23 | Collections.sort(edges); 24 | 25 | List mst = new ArrayList<>(); 26 | int[] parent = new int[V]; 27 | Arrays.fill(parent, -1); 28 | 29 | for (Edge edge : edges) { 30 | int srcParent = find(parent, edge.src); 31 | int destParent = find(parent, edge.dest); 32 | 33 | if (srcParent != destParent) { 34 | mst.add(edge); 35 | union(parent, srcParent, destParent); 36 | } 37 | } 38 | 39 | return mst; 40 | } 41 | 42 | public static int find(int[] parent, int vertex) { 43 | if (parent[vertex] == -1) { 44 | return vertex; 45 | } 46 | return find(parent, parent[vertex]); 47 | } 48 | 49 | public static void union(int[] parent, int src, int dest) { 50 | int srcParent = find(parent, src); 51 | int destParent = find(parent, dest); 52 | parent[srcParent] = destParent; 53 | } 54 | 55 | public static void main(String[] args) { 56 | int V = 4; 57 | List edges = new ArrayList<>(); 58 | edges.add(new Edge(0, 1, 10)); 59 | edges.add(new Edge(0, 2, 6)); 60 | edges.add(new Edge(0, 3, 5)); 61 | edges.add(new Edge(1, 3, 15)); 62 | edges.add(new Edge(2, 3, 4)); 63 | 64 | List mst = kruskalsMST(edges, V); 65 | 66 | System.out.println("Minimum Spanning Tree Edges:"); 67 | for (Edge edge : mst) { 68 | System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight); 69 | } 70 | } 71 | } 72 | 73 | 74 | /* The provided Java code implements Kruskal's algorithm, a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, undirected graph. Here's a short description of the code: 75 | 76 | 1. `Edge` Class: 77 | - Represents an edge in the graph with attributes `src` (source vertex), `dest` (destination vertex), and `weight` (edge weight). 78 | - Implements the `Comparable` interface to enable sorting edges based on their weights. 79 | 80 | 2. `KruskalsAlgorithm` Class: 81 | - Contains the main Kruskal's algorithm implementation. 82 | 83 | 3. `kruskalsMST` Method: 84 | - Takes a list of edges (`edges`) and the number of vertices (`V`) as input. 85 | - Sorts the list of edges in ascending order based on their weights. 86 | - Initializes an empty list `mst` to store the MST and an array `parent` to keep track of disjoint sets (initialized with -1). 87 | - Iterates through the sorted edges: 88 | - For each edge, it finds the parents of the source and destination vertices using the `find` method. 89 | - If the source and destination vertices do not belong to the same set (i.e., their parents are different), the edge is added to the MST (`mst`), and the sets are merged using the `union` method. 90 | 91 | 4. `find` Method: 92 | - Takes an array `parent` and a vertex as input. 93 | - Recursively finds the representative (parent) of a set by following the parent pointers until it reaches a vertex with a parent of -1 (representative of the set). 94 | 95 | 5. `union` Method: 96 | - Takes an array `parent`, source vertex `src`, and destination vertex `dest`. 97 | - Finds the parents of both vertices using the `find` method and makes one vertex the parent of the other by updating the `parent` array. 98 | 99 | 6. `main` Method: 100 | - Initializes the number of vertices (`V`) and a list of edges (`edges`) representing the graph. 101 | - Calls the `kruskalsMST` method to find the MST. 102 | - Prints the edges of the Minimum Spanning Tree, along with their weights. 103 | 104 | In summary, this code demonstrates the Kruskal's algorithm to find the Minimum Spanning Tree of a graph, and it prints the edges of the MST as the final output. The algorithm works by iteratively selecting edges with the smallest weights while avoiding cycles to construct a tree that spans all vertices with the minimum total weight. */ 105 | -------------------------------------------------------------------------------- /graph/algorithms/KruskalsMST.java: -------------------------------------------------------------------------------- 1 | package graph.algorithms;/* How to find MST using Kruskal’s algorithm? */ 2 | // Java program for Kruskal's algorithm 3 | 4 | import java.util.ArrayList; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class KruskalsMST { 9 | 10 | // Defines edge structure 11 | static class Edge { 12 | int src, dest, weight; 13 | 14 | public Edge(int src, int dest, int weight) 15 | { 16 | this.src = src; 17 | this.dest = dest; 18 | this.weight = weight; 19 | } 20 | } 21 | 22 | // Defines subset element structure 23 | static class Subset { 24 | int parent, rank; 25 | 26 | public Subset(int parent, int rank) 27 | { 28 | this.parent = parent; 29 | this.rank = rank; 30 | } 31 | } 32 | 33 | // Starting point of program execution 34 | public static void main(String[] args) 35 | { 36 | int V = 4; 37 | List graphEdges = new ArrayList( 38 | List.of(new Edge(0, 1, 10), new Edge(0, 2, 6), 39 | new Edge(0, 3, 5), new Edge(1, 3, 15), 40 | new Edge(2, 3, 4))); 41 | 42 | // Sort the edges in non-decreasing order 43 | // (increasing with repetition allowed) 44 | graphEdges.sort(new Comparator() { 45 | @Override public int compare(Edge o1, Edge o2) 46 | { 47 | return o1.weight - o2.weight; 48 | } 49 | }); 50 | 51 | kruskals(V, graphEdges); 52 | } 53 | 54 | // Function to find the MST 55 | private static void kruskals(int V, List edges) 56 | { 57 | int j = 0; 58 | int noOfEdges = 0; 59 | 60 | // Allocate memory for creating V subsets 61 | Subset subsets[] = new Subset[V]; 62 | 63 | // Allocate memory for results 64 | Edge results[] = new Edge[V]; 65 | 66 | // Create V subsets with single elements 67 | for (int i = 0; i < V; i++) { 68 | subsets[i] = new Subset(i, 0); 69 | } 70 | 71 | // Number of edges to be taken is equal to V-1 72 | while (noOfEdges < V - 1) { 73 | 74 | // Pick the smallest edge. And increment 75 | // the index for next iteration 76 | Edge nextEdge = edges.get(j); 77 | int x = findRoot(subsets, nextEdge.src); 78 | int y = findRoot(subsets, nextEdge.dest); 79 | 80 | // If including this edge doesn't cause cycle, 81 | // include it in result and increment the index 82 | // of result for next edge 83 | if (x != y) { 84 | results[noOfEdges] = nextEdge; 85 | union(subsets, x, y); 86 | noOfEdges++; 87 | } 88 | 89 | j++; 90 | } 91 | 92 | // Print the contents of result[] to display the 93 | // built MST 94 | System.out.println( 95 | "Following are the edges of the constructed MST:"); 96 | int minCost = 0; 97 | for (int i = 0; i < noOfEdges; i++) { 98 | System.out.println(results[i].src + " -- " 99 | + results[i].dest + " == " 100 | + results[i].weight); 101 | minCost += results[i].weight; 102 | } 103 | System.out.println("Total cost of MST: " + minCost); 104 | } 105 | 106 | // Function to unite two disjoint sets 107 | private static void union(Subset[] subsets, int x, 108 | int y) 109 | { 110 | int rootX = findRoot(subsets, x); 111 | int rootY = findRoot(subsets, y); 112 | 113 | if (subsets[rootY].rank < subsets[rootX].rank) { 114 | subsets[rootY].parent = rootX; 115 | } 116 | else if (subsets[rootX].rank 117 | < subsets[rootY].rank) { 118 | subsets[rootX].parent = rootY; 119 | } 120 | else { 121 | subsets[rootY].parent = rootX; 122 | subsets[rootX].rank++; 123 | } 124 | } 125 | 126 | // Function to find parent of a set 127 | private static int findRoot(Subset[] subsets, int i) 128 | { 129 | if (subsets[i].parent == i) 130 | return subsets[i].parent; 131 | 132 | subsets[i].parent 133 | = findRoot(subsets, subsets[i].parent); 134 | return subsets[i].parent; 135 | } 136 | } 137 | // This code is contributed by Salvino D'sa 138 | -------------------------------------------------------------------------------- /graph/algorithms/LeesAlgorithm_Mruganka.cpp: -------------------------------------------------------------------------------- 1 | /*The algorithm is a breadth-first based algorithm that uses queues to store the steps. */ 2 | 3 | int dl[] = {-1, 0, 1, 0}; // these arrays will help you travel in the 4 directions more easily 4 | int dc[] = {0, 1, 0, -1}; 5 | 6 | queue X, Y; // the queues used to get the positions in the matrix 7 | 8 | X.push(start_x); //initialize the queues with the start position 9 | Y.push(start_y); 10 | 11 | void lee() 12 | { 13 | int x, y, xx, yy; 14 | while(!X.empty()) // while there are still positions in the queue 15 | { 16 | x = X.front(); // set the current position 17 | y = Y.front(); 18 | for(int i = 0; i < 4; i++) 19 | { 20 | xx = x + dl[i]; // travel in an adiacent cell from the current position 21 | yy = y + dc[i]; 22 | if('position is valid') //here you should insert whatever conditions should apply for your position (xx, yy) 23 | { 24 | X.push(xx); // add the position to the queue 25 | Y.push(yy); 26 | mat[xx][yy] = -1; // you usually mark that you have been to this position in the matrix 27 | } 28 | 29 | } 30 | 31 | X.pop(); // eliminate the first position, as you have no more use for it 32 | Y.pop(); 33 | 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /graph/algorithms/PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class PrimAlgorithm { 4 | 5 | // Helper class to represent an edge in the graph 6 | static class Edge { 7 | int vertex; 8 | int weight; 9 | 10 | Edge(int vertex, int weight) { 11 | this.vertex = vertex; 12 | this.weight = weight; 13 | } 14 | } 15 | 16 | // Prim's Algorithm implementation using a priority queue (min-heap) 17 | public static List primsAlgorithm(Map> graph, int startVertex) { 18 | List mst = new ArrayList<>(); // List to store the edges of the Minimum Spanning Tree 19 | Set visited = new HashSet<>(); // Set to track visited vertices 20 | PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(edge -> edge[2])); // (parent, vertex, weight) 21 | 22 | minHeap.add(new int[]{-1, startVertex, 0}); // Add startVertex with a weight of 0 and no parent 23 | 24 | while (!minHeap.isEmpty()) { 25 | int[] currentEdge = minHeap.poll(); 26 | int parent = currentEdge[0]; 27 | int vertex = currentEdge[1]; 28 | int weight = currentEdge[2]; 29 | 30 | if (visited.contains(vertex)) continue; 31 | 32 | visited.add(vertex); 33 | if (parent != -1) { 34 | mst.add(new int[]{parent, vertex, weight}); // Add edge to MST 35 | } 36 | 37 | // Explore all neighbors of the current vertex 38 | for (Edge neighbor : graph.get(vertex)) { 39 | if (!visited.contains(neighbor.vertex)) { 40 | minHeap.add(new int[]{vertex, neighbor.vertex, neighbor.weight}); 41 | } 42 | } 43 | } 44 | 45 | return mst; 46 | } 47 | 48 | // Test cases 49 | public static void main(String[] args) { 50 | // Graph with 2 vertices 51 | Map> smallGraph = new HashMap<>(); 52 | smallGraph.put(0, Arrays.asList(new Edge(1, 10))); 53 | smallGraph.put(1, Arrays.asList(new Edge(0, 10))); 54 | 55 | // Graph with 3 vertices 56 | Map> smallGraph2 = new HashMap<>(); 57 | smallGraph2.put(0, Arrays.asList(new Edge(1, 10), new Edge(2, 5))); 58 | smallGraph2.put(1, Arrays.asList(new Edge(0, 10), new Edge(2, 15))); 59 | smallGraph2.put(2, Arrays.asList(new Edge(0, 5), new Edge(1, 15))); 60 | 61 | // Large dense graph with 6 vertices 62 | Map> denseGraph = new HashMap<>(); 63 | denseGraph.put(0, Arrays.asList(new Edge(1, 4), new Edge(2, 3), new Edge(3, 2))); 64 | denseGraph.put(1, Arrays.asList(new Edge(0, 4), new Edge(2, 5), new Edge(4, 8))); 65 | denseGraph.put(2, Arrays.asList(new Edge(0, 3), new Edge(1, 5), new Edge(4, 6))); 66 | denseGraph.put(3, Arrays.asList(new Edge(0, 2), new Edge(5, 7))); 67 | denseGraph.put(4, Arrays.asList(new Edge(1, 8), new Edge(2, 6), new Edge(5, 9))); 68 | denseGraph.put(5, Arrays.asList(new Edge(3, 7), new Edge(4, 9))); 69 | 70 | // Graph with duplicate edge weights 71 | Map> duplicateWeightsGraph = new HashMap<>(); 72 | duplicateWeightsGraph.put(0, Arrays.asList(new Edge(1, 10), new Edge(2, 10))); 73 | duplicateWeightsGraph.put(1, Arrays.asList(new Edge(0, 10), new Edge(2, 5))); 74 | duplicateWeightsGraph.put(2, Arrays.asList(new Edge(0, 10), new Edge(1, 5))); 75 | 76 | // Run the algorithm on different test cases 77 | List mstSmallGraph = primsAlgorithm(smallGraph, 0); 78 | List mstSmallGraph2 = primsAlgorithm(smallGraph2, 0); 79 | List mstDenseGraph = primsAlgorithm(denseGraph, 0); 80 | List mstDuplicateWeights = primsAlgorithm(duplicateWeightsGraph, 0); 81 | 82 | // Print results 83 | printMST(mstSmallGraph, "Small Graph (2 vertices)"); 84 | printMST(mstSmallGraph2, "Small Graph (3 vertices)"); 85 | printMST(mstDenseGraph, "Large Dense Graph (6 vertices)"); 86 | printMST(mstDuplicateWeights, "Graph with Duplicate Edge Weights"); 87 | } 88 | 89 | // Helper function to print the MST 90 | public static void printMST(List mst, String graphName) { 91 | System.out.println("MST for " + graphName + ":"); 92 | for (int[] edge : mst) { 93 | System.out.println("Edge from " + edge[0] + " to " + edge[1] + " with weight " + edge[2]); 94 | } 95 | System.out.println(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /heapsort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class HeapSort { 3 | public void sort(int arr[]) 4 | { 5 | int N = arr.length; 6 | 7 | for (int i = N / 2 - 1; i >= 0; i--) 8 | heapify(arr, N, i); 9 | 10 | for (int i = N - 1; i > 0; i--) { 11 | 12 | int x = arr[0]; 13 | arr[0] = arr[i]; 14 | arr[i] = x; 15 | 16 | heapify(arr, i, 0); 17 | } 18 | } 19 | 20 | void heapify(int arr[], int N, int i) 21 | { 22 | int largest = i; 23 | int l = 2 * i + 1; 24 | int r = 2 * i + 2; 25 | 26 | if (l < N && arr[l] > arr[largest]) 27 | largest = l; 28 | 29 | if (r < N && arr[r] > arr[largest]) 30 | largest = r; 31 | 32 | if (largest != i) { 33 | int swap = arr[i]; 34 | arr[i] = arr[largest]; 35 | arr[largest] = swap; 36 | 37 | heapify(arr, N, largest); 38 | } 39 | } 40 | static void printArray(int arr[]) 41 | { 42 | int N = arr.length; 43 | 44 | for (int i = 0; i < N; ++i) 45 | System.out.print(arr[i] + " "); 46 | System.out.println(); 47 | } 48 | 49 | public static void main(String args[]) 50 | { 51 | int i, n, arr[]; 52 | 53 | Scanner s = new Scanner(System.in); 54 | System.out.println("Enter no. of elements in aray:"); 55 | n = s.nextInt(); 56 | 57 | arr = new int[n]; 58 | 59 | System.out.println("Enter " + n + " integers:"); 60 | 61 | for (i = 0;i max) 12 | { 13 | max = arr[k]; 14 | max_i = k; 15 | } 16 | 17 | else if (arr[k] < min) 18 | { 19 | min = arr[k]; 20 | min_i = k; 21 | } 22 | } 23 | 24 | 25 | swaptemp(arr, i, min_i); 26 | 27 | 28 | if (arr[min_i] == max) 29 | swaptemp(arr, j, min_i); 30 | else 31 | swaptemp(arr, j, max_i); 32 | } 33 | } 34 | 35 | static int[] swaptemp(int []arr, int i, int j) 36 | { 37 | int temp = arr[i]; 38 | arr[i] = arr[j]; 39 | arr[j] = temp; 40 | return arr; 41 | } 42 | 43 | 44 | public static void main(String[] args) 45 | { 46 | int arr[] = { 23, 78, 45, 8, 32, 56, 1 }; 47 | int n = arr.length; 48 | minimprove(arr, n); 49 | System.out.printf("Sorted array:\n"); 50 | for (int i = 0; i < n; i++) 51 | System.out.print(arr[i] + " "); 52 | System.out.println(""); 53 | } 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /java/solution/BellmanFord.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | import java.util.*; 4 | public class BellmanFord { 5 | //---------------EDGE CLASS------------------- 6 | static class edge{ 7 | int src; 8 | int dest; 9 | int wt; 10 | 11 | public edge(int s, int d, int w){ 12 | this.src = s; 13 | this.dest = d; 14 | this.wt = w; 15 | } 16 | } 17 | //--------------CREATE GRAPH-------------------- 18 | static void creategaph(ArrayList graph []){ 19 | for(int i=0;i(); 21 | } 22 | graph[0].add(new edge(0, 1, 2)); 23 | graph[0].add(new edge(0, 2, 4)); 24 | 25 | graph[1].add(new edge(1, 2, -4)); 26 | 27 | graph[2].add(new edge(2, 3, 2)); 28 | 29 | graph[3].add(new edge(3, 4, 4)); 30 | 31 | graph[4].add(new edge(4, 1, -1)); 32 | 33 | 34 | } 35 | 36 | public static void bellman(ArrayList[] graph, int src){ 37 | int dist[] = new int[graph.length]; 38 | for(int i=0;i[] graph = new ArrayList[V]; //null -> empty arraylist 79 | creategaph(graph); 80 | 81 | int src = 0; 82 | bellman(graph, src); 83 | 84 | 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /java/solution/ConcatinateWords.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | class concatinate_word_problem { 6 | class Trie{ 7 | Trie[] children; 8 | boolean isWord; 9 | 10 | public Trie(){ 11 | children = new Trie[26]; 12 | isWord = false; 13 | } 14 | } 15 | Trie root = new Trie(); 16 | 17 | private void buildTrie(String word){ 18 | Trie trie = root; 19 | 20 | for(char c : word.toCharArray()){ 21 | if(trie.children[c-'a'] == null){ 22 | trie.children[c-'a'] = new Trie(); 23 | } 24 | trie = trie.children[c-'a']; 25 | } 26 | trie.isWord = true; 27 | } 28 | 29 | private boolean searchWord(String words, int count){ 30 | Trie node = root; 31 | for(int i=0; i< words.length(); i++){ 32 | char c = words.charAt(i); 33 | if(node.children[c-'a'] == null) return false; 34 | node = node.children[c-'a']; 35 | if(node.isWord && searchWord(words.substring(i+1),count+1)) return true; 36 | } 37 | count++; 38 | return (count >1 && node.isWord) ? true : false; 39 | } 40 | public List findAllConcatenatedWordsInADict(String[] words) { 41 | Arrays.sort(words, (a, b)-> a.length()-b.length()); 42 | ArrayList result = new ArrayList<>(); 43 | 44 | for(String word : words){ 45 | if(searchWord(word, 0)){ 46 | result.add(word); 47 | } 48 | else buildTrie(word); 49 | } 50 | return result; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /java/solution/Dijkstra.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | import java.util.*; 4 | public class Dijkstra { 5 | static class Edge{ 6 | int src; 7 | int dest; 8 | int wt; 9 | 10 | public Edge(int s, int d , int w){ 11 | this.src=s; 12 | this.dest= d; 13 | this.wt= w; 14 | 15 | } 16 | } 17 | public static void creategraph(ArrayList[] graph) { 18 | 19 | for(int i=0;i(); 21 | 22 | } 23 | 24 | graph[0].add(new Edge(0, 1,2)); 25 | graph[0].add(new Edge(0, 2, 4)); 26 | 27 | graph[1].add(new Edge(1, 3, 7)); 28 | graph[1].add(new Edge(1, 2,1)); 29 | 30 | graph[2].add(new Edge(2, 4 , 3)); 31 | 32 | graph[3].add(new Edge(3, 5, 1)); 33 | 34 | graph[4].add(new Edge(4, 3,2)); 35 | graph[4].add(new Edge(4, 5,5)); 36 | 37 | 38 | } 39 | static class Pair implements Comparable{ 40 | int n; 41 | int path; 42 | public Pair(int n , int path){ 43 | this.n= n; 44 | this.path= path; 45 | } 46 | 47 | @Override 48 | public int compareTo(Pair p2){ 49 | return this.path - p2.path; 50 | } 51 | } 52 | public static void ShortestPath( ArrayList[] graph, int src) { 53 | int dist[]= new int[graph.length]; 54 | for(int i=0;i pq= new PriorityQueue<>(); 62 | pq.add(new Pair(src, 0)); 63 | //loop 64 | while(!pq.isEmpty()) { 65 | Pair curr= pq.remove(); 66 | if(!vis[curr.n]){ 67 | vis[curr.n] = true; 68 | for(int i=0;i[] graph= new ArrayList[V]; 93 | creategraph(graph); 94 | int src=0; 95 | ShortestPath(graph, src); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /java/solution/Fibonacci.java: -------------------------------------------------------------------------------- 1 | /** 2 | * In this implementation, the fibonacci function takes an integer n as input and returns the n-th Fibonacci number. 3 | * The function uses recursion to calculate the Fibonacci number by summing the two preceding numbers in the sequence. 4 | */ 5 | 6 | public class Fibonacci { 7 | 8 | public static int fibonacci(int n) { 9 | if (n <= 1) { 10 | return n; 11 | } 12 | return fibonacci(n - 1) + fibonacci(n - 2); 13 | } 14 | 15 | public static void main(String[] args) { 16 | int n = 10; 17 | for (int i =0; i <= n; i++) { 18 | System.out.println(fibonacci(i) + " "); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/solution/FindOccouranceIndicesInArray.java: -------------------------------------------------------------------------------- 1 | package java.solution;//Problem Statement: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/?envType=daily-question&envId=2023-10-09 2 | // Topic: Binary Search 3 | 4 | class Solution { 5 | //flag == true ====> we are searching first occurrence else otherwise 6 | public int[] searchRange(int[] nums, int target) { 7 | return new int[] {helper(nums, target, true), helper(nums, target, false)}; 8 | } 9 | private int helper(int[] nums, int target, boolean flag) { 10 | int start =0; 11 | int ans =-1; 12 | int end =nums.length -1; 13 | 14 | while(start<= end) { 15 | int mid = start + (end - start)/2; 16 | if(target < nums[mid]) { 17 | end = mid -1; 18 | } 19 | else if(target > nums[mid]){ 20 | start = mid +1; 21 | } 22 | else { 23 | ans = mid; 24 | if(flag) { 25 | end = mid -1; 26 | } 27 | else{ 28 | start = mid +1; 29 | } 30 | } 31 | } 32 | return ans; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /java/solution/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | public class KadaneAlgorithm { 2 | public static int maxSubarraySum(int[] nums) { 3 | if (nums.length == 0) { 4 | return 0; 5 | } 6 | 7 | int maxEndingHere = nums[0]; 8 | int maxSoFar = nums[0]; 9 | 10 | for (int i = 1; i < nums.length; i++) { 11 | // Calculate the maximum sum ending at the current element 12 | maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]); 13 | 14 | // Update the maximum sum if the current subarray is greater 15 | maxSoFar = Math.max(maxSoFar, maxEndingHere); 16 | } 17 | 18 | return maxSoFar; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 23 | int maxSum = maxSubarraySum(nums); 24 | System.out.println("Maximum Subarray Sum: " + maxSum); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/solution/Knapsack.java: -------------------------------------------------------------------------------- 1 | /* The time complexity of this dynamic programming solution is O(n * capacity), 2 | * where n is the number of items and capacity is the capacity of the knapsack. 3 | */ 4 | 5 | public class Knapsack { 6 | 7 | public static int knapsack(int[] weights, int[] values, int capacity) { 8 | int n = weights.length; 9 | int[][] dp = new int[n + 1][capacity + 1]; 10 | 11 | for (int i = 1; i <= n; i++) { 12 | for (int w = 1; w <= capacity; w++) { 13 | if (weights[i - 1] <= w) { 14 | dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]); 15 | } else { 16 | dp[i][w] = dp[i - 1][w]; 17 | } 18 | } 19 | } 20 | 21 | return dp[n][capacity]; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] weights = {2, 3, 4, 5}; 26 | int[] values = {3, 4, 5, 6}; 27 | int capacity = 5; 28 | 29 | int maxValue = knapsack(weights, values, capacity); 30 | System.out.println("Maximum value that can be obtained: " + maxValue); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/solution/MedianOfSortedArrays.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | class MedianOfSortedArrays { 4 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 5 | int n = nums1.length; 6 | int m = nums2.length; 7 | int i=0, j=0; 8 | int idx =0; 9 | double[] arr = new double[n +m]; 10 | 11 | while(i < n && j < m) { 12 | if(nums1[i] < nums2[j]) { 13 | arr[idx++] = nums1[i++]; 14 | } 15 | else { 16 | arr[idx++] = nums2[j++]; 17 | } 18 | } 19 | while(i < n) { 20 | arr[idx++] = nums1[i++]; 21 | } 22 | while(j < m) { 23 | arr[idx++] = nums2[j++]; 24 | } 25 | int len = arr.length; 26 | int mid = len/2; 27 | return len%2 == 1 ? arr[mid] : (arr[mid] + arr[mid -1]) /2; 28 | } 29 | } 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /java/solution/Nqueens.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | public class Nqueens { 4 | 5 | public static boolean issafe(char board[][], int row, int col){ 6 | //vertical 7 | for(int i=row-1;i>=0;i--){ 8 | if(board[i][col]=='Q'){ 9 | return false; 10 | } 11 | } 12 | //diagonal left up 13 | for(int i=row-1, j=col-1;i>=0 && j>=0;i--, j--){ 14 | if(board[i][j]=='Q'){ 15 | return false; 16 | } 17 | } 18 | //diagonal right up 19 | for(int i=row-1, j=col+1; i>=0 && j[] graph) { 16 | 17 | for(int i=0;i(); 19 | 20 | } 21 | //0- vertex 22 | graph[4].add(new Edge(4, 0)); 23 | graph[4].add(new Edge(4, 1)); 24 | //1- vertex 25 | graph[1].add(new Edge(1, 0)); 26 | //2- vertex 27 | graph[2].add(new Edge(2, 3)); 28 | //3- vertex 29 | graph[3].add(new Edge(3, 1)); 30 | graph[5].add(new Edge(5, 0)); 31 | graph[5].add(new Edge(5, 2)); 32 | 33 | } 34 | 35 | public static void Topsort(ArrayList[] graph){ 36 | boolean vis[]= new boolean[graph.length]; 37 | Stack s= new Stack<>(); 38 | for(int i=0;i[] graph, int curr , boolean vis[], Stack s) { 49 | vis[curr]=true; 50 | for(int i=0;i[] graph= new ArrayList[V]; 64 | creategraph(graph); 65 | Topsort(graph); 66 | 67 | } 68 | } 69 | 70 | -------------------------------------------------------------------------------- /java/solution/Topview.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | import java.util.*; 4 | import java.util.LinkedList; 5 | 6 | public class Topview { 7 | static class Node { 8 | int data; 9 | Node left, right; 10 | 11 | public Node(int data) { 12 | this.data = data; 13 | this.left = null; 14 | this.right = null; 15 | } 16 | } 17 | 18 | static class QueueInfo { 19 | Node node; 20 | int hd; 21 | 22 | public QueueInfo(Node node, int hd) { 23 | this.node = node; 24 | this.hd = hd; 25 | } 26 | } 27 | 28 | public static void topView(Node root) { 29 | if(root == null) { 30 | return; 31 | } 32 | HashMap map = new HashMap<>(); 33 | Queue q = new LinkedList<>(); 34 | q.add(new QueueInfo(root, 0)); 35 | q.add(null); 36 | int min = 0, max = 0; 37 | 38 | while(!q.isEmpty()) { 39 | QueueInfo curr = q.remove(); 40 | if(curr == null) { 41 | if(q.isEmpty()) { 42 | break; 43 | } else { 44 | q.add(null); 45 | } 46 | } else { 47 | 48 | //check if HD is encountered for 1st time 49 | if(!map.containsKey(curr.hd)) { 50 | map.put(curr.hd, curr.node); 51 | } 52 | 53 | if(curr.node.left != null) { 54 | q.add(new QueueInfo(curr.node.left, curr.hd-1)); 55 | min = Math.min(min, curr.hd-1); 56 | } 57 | 58 | if(curr.node.right != null) { 59 | q.add(new QueueInfo(curr.node.right, curr.hd+1)); 60 | max = Math.max(max, curr.hd+1); 61 | } 62 | } 63 | } 64 | 65 | for(int i=min; i<=max; i++) { 66 | System.out.print(map.get(i).data+" "); 67 | } 68 | System.out.println(); 69 | } 70 | public static void main(String args[]) { 71 | /* 72 | 1 73 | / \ 74 | 2 3 75 | / \ / \ 76 | 4 5 6 7 77 | expected output : 4 2 1 3 7 78 | */ 79 | Node root = new Node(1); 80 | root.left = new Node(2); 81 | root.right = new Node(3); 82 | root.left.left = new Node(4); 83 | root.left.right = new Node(5); 84 | root.right.left = new Node(6); 85 | root.right.right = new Node(7); 86 | 87 | /* 88 | 1 89 | / \ 90 | 2 3 91 | \ 92 | 4 93 | \ 94 | 5 95 | \ 96 | 6 97 | expected output : 2 1 3 6 98 | */ 99 | Node root2 = new Node(1); 100 | root2.left = new Node(2); 101 | root2.right = new Node(3); 102 | root2.left.right = new Node(4); 103 | root2.left.right.right = new Node(5); 104 | root2.left.right.right.right = new Node(6); 105 | 106 | 107 | topView(root); 108 | topView(root2); 109 | } 110 | } -------------------------------------------------------------------------------- /java/solution/Trapingrainwater.java: -------------------------------------------------------------------------------- 1 | package java.solution; 2 | 3 | //import java.util.*; 4 | public class Trapingrainwater { 5 | public static int Trappedwater(int height[]){ 6 | int n=height.length; 7 | int maxleftheight[]= new int[n]; 8 | // calculate left max boundary -array 9 | maxleftheight[0]=height[0]; 10 | for(int i=1;i=0;i--){ 18 | maxrightheight[i]=Math.max(height[i], maxrightheight[i+1]); 19 | } 20 | int trappedwater=0; 21 | //calculate trapped water 22 | for(int i=1;i set = new HashSet<>(); 10 | //union 11 | for(int i=0;i s= new Stack<>(); 9 | for(int i=0;i arr[j + 1]) { 10 | 11 | // Swap arr[j] and arr[j+1] 12 | 13 | int temp = arr[j]; 14 | 15 | arr[j] = arr[j + 1]; 16 | 17 | arr[j + 1] = temp; 18 | 19 | } 20 | 21 | } 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /java/solution/intersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | //QUESTION: 2 | //find intersection between this to arrays: 3 | // arr1={7,3,9}; 4 | // arr2={6,3,9,2,9,4}; 5 | 6 | import java.util.*; 7 | 8 | public class intersectionOfTwoArrays { 9 | public static HashSet intersection(int arr1[], int arr2[]) { 10 | HashSet set1 = new HashSet<>(); 11 | HashSet set2 = new HashSet<>(); 12 | HashSet result = new HashSet<>(); 13 | for (int i = 0; i < arr1.length; i++) { 14 | set1.add(arr1[i]); 15 | } 16 | for (int j = 0; j < arr2.length; j++) { 17 | set2.add(arr2[j]); 18 | } 19 | for (Integer num : set1) { 20 | if (set2.contains(num)) { 21 | result.add(num); 22 | } 23 | } 24 | return result; 25 | } 26 | 27 | public static void main(String[] args) { 28 | int arr1[] = { 7, 3, 9 }; 29 | int arr2[] = { 6, 3, 9, 2, 9, 4 }; 30 | HashSet intersectionSet = intersection(arr1, arr2); 31 | 32 | System.out.println("Intersection of the two arrays:"); 33 | for (Integer num : intersectionSet) { 34 | System.out.print(num + " "); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /longest_common_subsequence_with_sum_k.java: -------------------------------------------------------------------------------- 1 | // Java code to implement the approach 2 | import java.io.*; 3 | class answer { 4 | 5 | static int solve(int a[], int b[], int i, int j, int sum) 6 | { 7 | if (sum == 0) 8 | return 0; 9 | if (sum < 0) 10 | return Integer.MIN_VALUE; 11 | 12 | if (i == 0 || j == 0) { 13 | if (sum == 0) 14 | return 0; 15 | else 16 | return Integer.MIN_VALUE; 17 | } 18 | 19 | // If values are same then we can include this 20 | // or also can't include this 21 | if (a[i - 1] == b[j - 1]) 22 | return Math.max( 23 | 1 + solve(a, b, i - 1, j - 1, sum - a[i - 1]), 24 | solve(a, b, i - 1, j - 1, sum)); 25 | 26 | return Math.max(solve(a, b, i - 1, j, sum), 27 | solve(a, b, i, j - 1, sum)); 28 | } 29 | 30 | // Driver code 31 | public static void main (String[] args) { 32 | int a[] = { 9, 11, 2, 1, 6, 2, 7 }; 33 | int b[] = { 1, 2, 6, 9, 2, 3, 11, 7 }; 34 | int n = a.length; 35 | int m = b.length; 36 | int sum = 18; 37 | 38 | int ans = solve(a, b, n, m, sum); 39 | if (ans >= 0) 40 | System.out.print(ans); 41 | else 42 | System.out.print(-1); 43 | } 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /matrixAdd.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | public class matrixAdd { 4 | public static void main(String[] args) { 5 | int m,n; 6 | Scanner s = new Scanner(System.in); 7 | System.out.println("Enter the rows of matrix: "); 8 | m = s.nextInt(); 9 | System.out.println("Enter the columns of matrix: "); 10 | n = s.nextInt(); 11 | 12 | int a[][] = new int[m][n]; 13 | int b[][] = new int[m][n]; 14 | int c[][] = new int[m][n]; 15 | 16 | System.out.println("Enter the elements of 1st matrix "); 17 | for(int i=0;i pattern 9 | txt -> text 10 | q -> A prime number 11 | */ 12 | static void search(String pat, String txt, int q) 13 | { 14 | int M = pat.length(); 15 | int N = txt.length(); 16 | int i, j; 17 | int p = 0; // hash value for pattern 18 | int t = 0; // hash value for txt 19 | int h = 1; 20 | 21 | // The value of h would be "pow(d, M-1)%q" 22 | for (i = 0; i < M - 1; i++) 23 | h = (h * d) % q; 24 | 25 | // Calculate the hash value of pattern and first 26 | // window of text 27 | for (i = 0; i < M; i++) { 28 | p = (d * p + pat.charAt(i)) % q; 29 | t = (d * t + txt.charAt(i)) % q; 30 | } 31 | 32 | // Slide the pattern over text one by one 33 | for (i = 0; i <= N - M; i++) { 34 | 35 | // Check the hash values of current window of 36 | // text and pattern. If the hash values match 37 | // then only check for characters one by one 38 | if (p == t) { 39 | /* Check for characters one by one */ 40 | for (j = 0; j < M; j++) { 41 | if (txt.charAt(i + j) != pat.charAt(j)) 42 | break; 43 | } 44 | 45 | // if p == t and pat[0...M-1] = txt[i, i+1, 46 | // ...i+M-1] 47 | if (j == M) 48 | System.out.println( 49 | "Pattern found at index " + i); 50 | } 51 | 52 | // Calculate hash value for next window of text: 53 | // Remove leading digit, add trailing digit 54 | if (i < N - M) { 55 | t = (d * (t - txt.charAt(i) * h) 56 | + txt.charAt(i + M)) 57 | % q; 58 | 59 | // We might get negative value of t, 60 | // converting it to positive 61 | if (t < 0) 62 | t = (t + q); 63 | } 64 | } 65 | } 66 | 67 | /* Driver Code */ 68 | public static void main(String[] args) 69 | { 70 | String txt = "GEEKS FOR GEEKS"; 71 | String pat = "GEEK"; 72 | 73 | // A prime number 74 | int q = 101; 75 | 76 | // Function Call 77 | search(pat, txt, q); 78 | } 79 | } 80 | 81 | -------------------------------------------------------------------------------- /reverse.java: -------------------------------------------------------------------------------- 1 | public class ReverseString { 2 | public static void main(String[] args) { 3 | String original = "Hello, World!"; 4 | String reversed = ""; 5 | 6 | for (int i = original.length() - 1; i >= 0; i--) { 7 | reversed += original.charAt(i); 8 | } 9 | 10 | System.out.println("Reversed: " + reversed); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /selectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class selectionSort { 4 | public static void main(String[] args) { 5 | int []arr={4,1,3,9,7}; 6 | selectionArr(arr); 7 | System.out.println(Arrays.toString(arr)); 8 | 9 | } 10 | static void selectionArr(int[]arr){ 11 | for (int i = 0; i < arr.length; i++) { 12 | //find the max item in the remaining array and swap it with correct index 13 | int last=arr.length-i-1; 14 | int maxInd=getMaxInd(arr,0,last); 15 | swap(arr, maxInd, last); 16 | } 17 | } 18 | static int getMaxInd(int[]arr,int start,int last){ 19 | int max=start; 20 | for (int i = start; i<=last; i++) { 21 | if(arr[max] "); 119 | } 120 | } 121 | } 122 | } 123 | --------------------------------------------------------------------------------