├── .github └── workflows │ ├── build_test.yml │ ├── congrats.yml │ ├── greetings.yml │ ├── pull_request_template.md │ ├── ruff.yml │ └── test.yml ├── Array └── bitManipulation.java ├── BST ├── README.md └── bst_formation.java ├── Backtracking └── Sudoku.java ├── Graphs ├── BFS_graph.java ├── BellmanFord.java ├── DFS_graph.java ├── DisjointSetUnion.java ├── FloydWarshall.java ├── Graph.class ├── GraphUsingArrayList.java ├── ImplementingGraphs.class ├── ImplementingGraphs.java ├── Prims_Algo.java ├── README.md ├── adjacent_ListGraphs.java ├── bellman_ford.java ├── bfs_apna.java ├── cycle_detection.java ├── dfs_apna.java ├── dijkstra.java ├── grabh_by_linkedList.java ├── graph.java ├── graph_apna.java ├── kahns_Algo.java ├── maxPath_inMaze.java ├── print_full_path.java └── topological_sorting.java ├── HashMap ├── MajorityElement.java ├── Min_window_substring.java ├── distict_element_window.java ├── hashmap.java ├── hashset.java ├── intersection_of_array.java ├── itenerary.java ├── remove_adjacent_duplicates.java ├── subarray_sum_equal_to_K.java └── union_of_two_arrays.java ├── Heap ├── HeapSort.java ├── NRopes.java ├── NearbyCars.java ├── apna_heap.java ├── median_of_runningStreamOfInteger.java └── sliding_window_median.java ├── LL ├── LL1.java ├── README.md ├── circular_LL.java ├── detect_remove_cycle_LL.java ├── doubly_circular_LL.java ├── palindrome_LL.java └── reverse_LinkedList.java ├── Leetcode ├── AllCombinations.java ├── Flatten_multilevelArray.java ├── IntersectionOfArray.java ├── Kadane_algo.java ├── Palindrome_fixedLength.java ├── Queue_using_twostacks.java ├── SlidingWindowMaximum_Array.java ├── Stack_using_twoQueue.java ├── SudokuSolver.java ├── ThreeSum.java ├── Tiles_placement.java ├── TrappingWater.java ├── TwoSum.java ├── birthday_celevratuions.java ├── moving_avg_fromDataStream.java ├── stock2_buySell.java ├── stock_buySell.java └── stringsandPaswords.java ├── MathsforDSA ├── SieveofEratosthenes.java ├── factorial.java ├── fibonacci.java ├── isSquareFul.java ├── permutation_II.java └── x_n_power.java ├── Priority_Queue ├── Kth_largest_element.java └── connect_N_ropes.java ├── Queue ├── CircularArrayQueue.java ├── QueueUsingStacks.java ├── Queue_byArray.java ├── Queue_byCircularArray.java ├── Queue_byTwoStacks.java ├── Queue_withArray.java ├── README.md └── queue_byLinkedlist.java ├── README.md ├── Reflection-API ├── README.md ├── SetterGetterGenerator.java ├── TestCase.java └── tmp.data ├── Search ├── README.md ├── binarySearch2.java ├── binary_search.java ├── exponentialSearch.java ├── linear_Search.java └── search_sorted_rotatedArray.java ├── Stack ├── LargestRect_in_Histogram.java ├── README.md ├── gameOfTwoStacks.java ├── max_Rectangle.java ├── nextLargest.java ├── nextSmallest.java ├── previousLargest.java ├── previousSmaller.java └── stack_methods.java ├── String ├── Min_window_substring.java ├── addStrings.java ├── fibonacci.java ├── first_last_occurence_string.java ├── integerToEnglishword.java ├── longestubtrings.java ├── remove_adjacent_duplicates.java ├── rev_string.java ├── stringbuilder.java ├── validParenthesis.java └── x_at_end_ofString.java ├── Threads ├── Multithreading_LambdaExpression.java ├── README.md └── ThreadDemo.java ├── Trees ├── Binary_treePaths.java ├── DeleteNodes_returnForest.java ├── Floor_Ceil_ofBST.java ├── Height_of_Tree.java ├── Insert_into_a_Binary_Search_Tree.java ├── LCA_OfBinaryTree_LowestCommonancestor.java ├── Left_Right_viewOfTree.java ├── LeveOrder_Traversal_inBinaryTree.java ├── Max_Min_ina_Tree.java ├── README.md ├── Search_in_a_Binary_Search_Tree.java ├── TopView_ofTree.java ├── VerticalOrder_Traversal_BinaryTree.java ├── binaryTree_to_Linkedlist_preorderTraversal.java ├── binaryTree_to_dublyLinkedList.java ├── count_the_nodes.java ├── diameterOfTree.java ├── diameter_of_binaryTree.java ├── height_of_tree_apna.java ├── kk_BST.java ├── segment_tree ├── subtree_of_tree.java ├── sum_of_nodes.java ├── tree_apna.java ├── trees.java └── valid_BST.java ├── Trie ├── concatinate_word_problem.java ├── trie_1.java └── wordbreak_problem.java ├── pom.xml └── sorting ├── Insertion_sort.java ├── MergeSort.class ├── MergeSort.java ├── QuickSort.java ├── QuickSort_middle.java ├── README.md ├── Selection_sort.java ├── boolean_isSorted.java ├── bubble_sort.java ├── bubblesort.java ├── insertionsort.java ├── recursion1.java ├── selectionsort.java └── shell_sort.java /.github/workflows/build_test.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | 3 | on: [push, pull_request] 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - name: Set up JDK 17 10 | uses: actions/setup-java@v2 11 | with: 12 | java-version: 17 13 | distribution: 'adopt' 14 | - name: Build with Maven 15 | run: mvn --batch-mode --update-snapshots verify 16 | -------------------------------------------------------------------------------- /.github/workflows/congrats.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Merged 2 | 3 | # on: 4 | # pull_request: 5 | # types: 6 | # - closed 7 | jobs: 8 | notify: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | 15 | - name: Add comment 16 | run: | 17 | if [ "${{ github.event.pull_request.merged }}" == "true" ]; then 18 | Congratulations :) 19 | pull_request_number=${{ github.event.pull_request.number }} 20 | comment_body=":tada: Congratulations! The pull request #${pull_request_number} has been merged successfully! :tada:" 21 | echo "${comment_body}" | gh pr review --approve --comment --body - 22 | fi 23 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: "Thanks for raising your first issue" 16 | pr-message: "Congrats🙌 on your first pull request" 17 | -------------------------------------------------------------------------------- /.github/workflows/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | ## Pull Request Description 3 | 4 | **Title:** [Add a brief one-line title here] 5 | 6 | ### Description 7 | [Provide a concise description of the changes made in this pull request.] 8 | 9 | ### Related Issue 10 | [Reference the related issue or task using its number or link.] 11 | 12 | ### Changes Made 13 | - [Briefly list the specific code changes made.] 14 | 15 | ### Screenshots (if applicable) 16 | [Include any relevant screenshots or images here.] 17 | 18 | - [ ] Fixed Bug/issues 19 | - [ ] Added algo/questions_answers/docs 20 | - [ ] This pull request is all my own work -- I have not plagiarized it. 21 | - [ ] All filenames are in PascalCase. 22 | - [ ] All functions and variable names follow Java naming conventions. 23 | - [ ] All test cases have passed. 24 | - [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. 25 | -------------------------------------------------------------------------------- /.github/workflows/ruff.yml: -------------------------------------------------------------------------------- 1 | name: ruff 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | branches: 8 | - main 9 | jobs: 10 | ruff: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - run: pip install --user ruff 15 | - run: ruff --output-format=github . 16 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Syntax Check 2 | on: 3 | pull_request: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | syntax-check: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@v2 13 | 14 | - name: Set up JDK 15 | uses: actions/setup-java@v1 16 | with: 17 | java-version: '11' 18 | 19 | - name: Build with Maven 20 | run: mvn -B clean verify 21 | 22 | - name: Check for syntax errors 23 | run: mvn -B compile 24 | -------------------------------------------------------------------------------- /Array/bitManipulation.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class bitManipulation { 4 | public static void main(String[] args) { 5 | // get bit 6 | int n =5; 7 | int pos = 2; 8 | int bitMask = 1<(); 23 | } 24 | } 25 | 26 | private int E; 27 | public void addEdge(int u, int v) { 28 | adj[u].add(v); 29 | adj[v].add(u); 30 | E++; 31 | } 32 | 33 | public String toString() { 34 | StringBuilder sb = new StringBuilder(); 35 | sb.append(V + " vertices, " + E + " edges " + "\n"); 36 | for(int v = 0; v < V; v++) { 37 | sb.append(v + ": "); 38 | for(int w : adj[v]) { 39 | sb.append(w + " "); 40 | } 41 | sb.append("\n"); 42 | } 43 | return sb.toString(); 44 | } 45 | private int V; 46 | private LinkedList[ ] adj; 47 | public void bfs(int s){ 48 | boolean[] visited = new boolean[V]; 49 | Queue q = new LinkedList<>(); 50 | visited[s] = true; 51 | q.offer(s); 52 | 53 | while (!q.isEmpty()){ 54 | int u = q.poll(); 55 | System.out.println(u+" "); 56 | 57 | for (int v : adj[u]) { 58 | if (!visited[v]){ 59 | visited[v]=true; 60 | q.offer(v); 61 | } 62 | } 63 | } 64 | 65 | } 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Graphs/BellmanFord.java: -------------------------------------------------------------------------------- 1 | // --------------------------------BELLMAN FORD'S ALGORITHM--------------------------------------------- 2 | // BASICALLY USED TO FIND SHORTEST PATH OF ALL NODES FROM SOURCE NODE IN A GRAPH 3 | // REQUIREMENTS:- A DISTANCE ARRAY 4 | // CONCEPTS:- DISTANCE ARRAY -> This Array will store the distances of nodes from source node. 5 | // WIKI:- https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm 6 | 7 | import java.util.*; 8 | 9 | public class BellmanFord { 10 | public static void main(String[] args) { 11 | int vertex = 3; 12 | int edge = 4; 13 | // example -----> [[0,1,5],[1,0,3],[1,2,-1],[2,0,1]] 14 | ArrayList> ls = new ArrayList<>(); 15 | int[][] arr = { { 0, 1, 5 }, { 1, 0, 3 }, { 1, 2, -1 }, { 2, 0, 1 } }; 16 | for (int i = 0; i < edge; i++) { 17 | ArrayList tmp = new ArrayList(); 18 | tmp.add(arr[i][0]); // edge from this node 19 | tmp.add(arr[i][1]); // edge to this node 20 | tmp.add(arr[i][2]); // weight of this edge 21 | ls.add(tmp); 22 | } 23 | int source = 2; // Our Source Node 24 | int[] ans = bellman_ford(vertex, ls, source); 25 | // Printing our result(Optional) 26 | for (int i = 0; i < ans.length; i++) 27 | System.out.print(ans[i] + " "); 28 | // Answer would come out as [1,6,0] 29 | } 30 | 31 | static int[] bellman_ford(int vertex, ArrayList> ls, int S) { 32 | int[] dist = new int[vertex]; 33 | for (int i = 0; i < vertex; i++) { 34 | if (S == i) 35 | dist[i] = 0; 36 | else 37 | dist[i] = Integer.MAX_VALUE; // we will put infinite initially in all distances 38 | } 39 | 40 | for (int i = 0; i < vertex - 1; i++) { 41 | for (int j = 0; j < ls.size(); j++) { 42 | int u = ls.get(j).get(0); 43 | int v = ls.get(j).get(1); 44 | int dis = ls.get(j).get(2); 45 | if (dist[u] != Integer.MAX_VALUE && dist[u] + dis < dist[v]) 46 | dist[v] = dist[u] + dis; 47 | } 48 | } 49 | 50 | for (int j = 0; j < ls.size(); j++) { 51 | int u = ls.get(j).get(0); 52 | int v = ls.get(j).get(1); 53 | int dis = ls.get(j).get(2); 54 | if (dist[u] != Integer.MAX_VALUE && dist[u] + dis < dist[v]) 55 | return new int[] { -1 }; 56 | } 57 | return dist; 58 | } 59 | } -------------------------------------------------------------------------------- /Graphs/DFS_graph.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Stack; 5 | 6 | public class DFS_graph { 7 | public static void main(String[] args) { 8 | 9 | } 10 | public DFS_graph(int nodes) { 11 | this.V = nodes; 12 | this.E = 0; 13 | this.adj = new LinkedList[nodes]; 14 | for(int v = 0; v < V; v++) { 15 | adj[v] = new LinkedList<>(); 16 | } 17 | } 18 | 19 | private int E; 20 | public void addEdge(int u, int v) { 21 | adj[u].add(v); 22 | adj[v].add(u); 23 | E++; 24 | } 25 | 26 | public String toString() { 27 | StringBuilder sb = new StringBuilder(); 28 | sb.append(V + " vertices, " + E + " edges " + "\n"); 29 | for(int v = 0; v < V; v++) { 30 | sb.append(v + ": "); 31 | for(int w : adj[v]) { 32 | sb.append(w + " "); 33 | } 34 | sb.append("\n"); 35 | } 36 | return sb.toString(); 37 | } 38 | private int V; 39 | private LinkedList[ ] adj; 40 | 41 | private int vertices; 42 | public void dfs(int s){ 43 | boolean[] visited = new boolean[vertices]; 44 | Stack stack = new Stack<>(); 45 | stack.push(s); 46 | while (!stack.isEmpty()){ 47 | int u = stack.pop(); 48 | if (!visited[u]){ 49 | visited[u] = true; 50 | System.out.println(u); 51 | for (int v : adj[u]) { 52 | if (!visited[v]){ 53 | stack.push(v); 54 | } 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /Graphs/DisjointSetUnion.java: -------------------------------------------------------------------------------- 1 | // A Disjoint-Set Union (DSU) data structure, also known as a Union-Find data structure, is a data structure that helps manage a collection of disjoint sets. It provides two primary operations: union and find. 2 | 3 | // DSU is efficient, especially when using path compression and union-by-rank heuristics. The time complexity for the Find operation is nearly constant on average, making it a valuable tool for solving problems that involve partitioning elements into disjoint sets. 4 | 5 | // reference https://cp-algorithms.com/data_structures/disjoint_set_union.html 6 | 7 | import java.io.*; 8 | import java.util.*; 9 | class DisjointSet { 10 | List rank = new ArrayList<>(); 11 | List parent = new ArrayList<>(); 12 | public DisjointSet(int n) { 13 | for (int i = 0; i <= n; i++) { 14 | rank.add(0); 15 | parent.add(i); 16 | } 17 | } 18 | 19 | public int findUPar(int node) { 20 | if (node == parent.get(node)) { 21 | return node; 22 | } 23 | int ulp = findUPar(parent.get(node)); 24 | parent.set(node, ulp); 25 | return parent.get(node); 26 | } 27 | 28 | public void unionByRank(int u, int v) { 29 | int ulp_u = findUPar(u); 30 | int ulp_v = findUPar(v); 31 | if (ulp_u == ulp_v) return; 32 | if (rank.get(ulp_u) < rank.get(ulp_v)) { 33 | parent.set(ulp_u, ulp_v); 34 | } else if (rank.get(ulp_v) < rank.get(ulp_u)) { 35 | parent.set(ulp_v, ulp_u); 36 | } else { 37 | parent.set(ulp_v, ulp_u); 38 | int rankU = rank.get(ulp_u); 39 | rank.set(ulp_u, rankU + 1); 40 | } 41 | } 42 | 43 | } 44 | 45 | class Main { 46 | public static void main (String[] args) { 47 | DisjointSet ds = new DisjointSet(7); 48 | ds.unionByRank(1, 2); 49 | ds.unionByRank(2, 3); 50 | ds.unionByRank(4, 5); 51 | ds.unionByRank(6, 7); 52 | ds.unionByRank(5, 6); 53 | 54 | // if 3 and 7 same or not 55 | if (ds.findUPar(3) == ds.findUPar(7)) { 56 | System.out.println("Same"); 57 | } else 58 | System.out.println("Not Same"); 59 | 60 | ds.unionByRank(3, 7); 61 | if (ds.findUPar(3) == ds.findUPar(7)) { 62 | System.out.println("Same"); 63 | } else 64 | System.out.println("Not Same"); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Graphs/FloydWarshall.java: -------------------------------------------------------------------------------- 1 | // --------------------------------FLOYD WARSHALL's ALGORITHM--------------------------------------------- 2 | // BASICALLY USED TO FIND SHORTEST PATH BETWEEN EACH AND EVERY NODE IN A GRAPH 3 | // WIKI:- https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm 4 | 5 | import java.util.*; 6 | 7 | public class FloydWarshall { 8 | public static void main(String[] args) { 9 | // example -----> [[0,1,43],[1,0,6],[-1,-1,0]] 10 | int[][] matrix = { { 0, 1, 43 }, { 1, 0, 6 }, { -1, -1, 0 } }; 11 | shortest_distance(matrix); // Calling our function to implement algo 12 | 13 | // Printing our result(Optional) 14 | for (int i = 0; i < matrix.length; i++) { 15 | for (int j = 0; j < matrix.length; j++) { 16 | System.out.print(matrix[i][j] + " "); 17 | } 18 | System.out.println(); 19 | } 20 | // Answer would come out as {{0,1,7},{1,0,6},{-1,-1,0}} 21 | } 22 | 23 | static void shortest_distance(int[][] matrix) { 24 | int n = matrix.length; 25 | for (int i = 0; i < n; i++) { // We are going through each and every node here 26 | for (int j = 0; j < n; j++) { 27 | if (matrix[i][j] == -1) 28 | matrix[i][j] = Integer.MAX_VALUE; 29 | } 30 | } 31 | 32 | for (int via = 0; via < n; via++) { 33 | for (int i = 0; i < n; i++) { 34 | for (int j = 0; j < n; j++) { 35 | if (matrix[i][via] != Integer.MAX_VALUE && matrix[via][j] != Integer.MAX_VALUE) 36 | matrix[i][j] = Math.min(matrix[i][via] + matrix[via][j], matrix[i][j]); 37 | } 38 | } 39 | } 40 | 41 | for (int i = 0; i < n; i++) { 42 | for (int j = 0; j < n; j++) { 43 | if (matrix[i][j] == Integer.MAX_VALUE) 44 | matrix[i][j] = -1; 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Graphs/Graph.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan472000/Java-DSA-InterviewPrep/f1631cff54adf2170e99816233ac5fd9e832c2ec/Graphs/Graph.class -------------------------------------------------------------------------------- /Graphs/GraphUsingArrayList.java: -------------------------------------------------------------------------------- 1 | //Wikipedia: https://en.wikipedia.org/wiki/Graph_(abstract_data_type) 2 | //GFG: https://www.geeksforgeeks.org/graph-representation-using-java-arraylist/ 3 | //Implementing graph using java 4 | //Implemented adjacency list using arraylist 5 | //for undirected unweighted graph 6 | 7 | package Graphs; 8 | 9 | import java.util.*; 10 | 11 | public class GraphUsingArrayList 12 | { 13 | 14 | //storing edges(source and destination) in the list 15 | static void addEdge(ArrayList > graph, int s, int d) 16 | { 17 | graph.get(s).add(d); 18 | graph.get(d).add(s); 19 | } 20 | 21 | static void printAdjacencyList(ArrayList > graph) 22 | { 23 | for (int i = 0; i < graph.size(); i++) { 24 | //Printing the vertex 25 | System.out.println("Adjacency list of " + i); 26 | for (int j = 0; j < graph.get(i).size(); j++) { 27 | //printing neighbours vertices 28 | System.out.print(graph.get(i).get(j) + " "); 29 | } 30 | System.out.println(); 31 | } 32 | } 33 | 34 | //creating graph by adding edges 35 | public static void createGraph(ArrayList > graph, int v) 36 | { 37 | for (int i = 0; i < v ; i++) 38 | graph.add(new ArrayList()); 39 | 40 | // adding edges 41 | addEdge(graph, 0, 1); 42 | addEdge(graph, 0, 4); 43 | addEdge(graph, 1, 2); 44 | addEdge(graph, 1, 3); 45 | addEdge(graph, 1, 4); 46 | addEdge(graph, 2, 3); 47 | addEdge(graph, 3, 4); 48 | 49 | } 50 | 51 | public static void main(String[] args) 52 | { 53 | //creating a graph of 5 vertices 54 | int v = 5; 55 | ArrayList > graph = new ArrayList >(v); 56 | createGraph(graph,v); 57 | printAdjacencyList(graph); 58 | } 59 | } -------------------------------------------------------------------------------- /Graphs/ImplementingGraphs.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan472000/Java-DSA-InterviewPrep/f1631cff54adf2170e99816233ac5fd9e832c2ec/Graphs/ImplementingGraphs.class -------------------------------------------------------------------------------- /Graphs/ImplementingGraphs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Java program to implement an undirected graph using an adjacency list. 3 | 4 | Description: 5 | This program defines a Graph class with methods to represent and manipulate an undirected graph. 6 | The graph is represented using an adjacency list, where each vertex is associated with a list of its neighbors. 7 | 8 | Class Descriptions: 9 | - Graph: Represents the graph with methods to add edges and print the adjacency list. 10 | - ImplementingGraphs: Contains the main method to demonstrate the usage of the Graph class. 11 | 12 | Relevant Links: 13 | - Graph Theory: https://en.wikipedia.org/wiki/Graph_theory 14 | - Graph (Discrete Mathematics): https://en.wikipedia.org/wiki/Graph_(discrete_mathematics) 15 | - Adjacency List: https://en.wikipedia.org/wiki/Adjacency_list 16 | 17 | 18 | */ 19 | 20 | import java.util.*; 21 | 22 | 23 | class Graph { 24 | private int V; 25 | private Map> adjacencyList; 26 | 27 | // Constructor 28 | public Graph(int V) { 29 | this.V = V; 30 | this.adjacencyList = new HashMap<>(); 31 | for (int i = 0; i < V; i++) { 32 | adjacencyList.put(i, new ArrayList<>()); 33 | } 34 | } 35 | 36 | // Add an edge to the graph 37 | public void addEdge(int v, int w) { 38 | adjacencyList.get(v).add(w); 39 | adjacencyList.get(w).add(v); 40 | } 41 | 42 | 43 | // Print the graph 44 | public void printGraph() { 45 | for (Map.Entry> entry : adjacencyList.entrySet()) { 46 | int vertex = entry.getKey(); 47 | List neighbors = entry.getValue(); 48 | System.out.print("Vertex " + vertex + " is connected to: "); 49 | for (Integer neighbor : neighbors) { 50 | System.out.print(neighbor + " "); 51 | } 52 | System.out.println(); 53 | } 54 | } 55 | } 56 | 57 | public class ImplementingGraphs { 58 | public static void main(String[] args) { 59 | // Create a graph with 5 vertices 60 | Graph graph = new Graph(5); 61 | 62 | 63 | graph.addEdge(0, 1); 64 | graph.addEdge(0, 4); 65 | graph.addEdge(1, 2); 66 | graph.addEdge(1, 3); 67 | graph.addEdge(1, 4); 68 | graph.addEdge(2, 3); 69 | graph.addEdge(3, 4); 70 | 71 | 72 | graph.printGraph(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Graphs/Prims_Algo.java: -------------------------------------------------------------------------------- 1 | // --------------------------------PRIM'S ALGORITHM--------------------------------------------- 2 | // BASICALLY USED TO FIND OUT THE MST SUM OR THE MST TREE 3 | // REQUIREMENTS:- PRIORITY QUEUE AND A vertexISITED ARRAY 4 | // CONCEPTS:- vertexISITED ARRAY -> This Array will tell whether a node is visited or not. 5 | // WIKI:- https://en.wikipedia.org/wiki/Prim%27s_algorithm 6 | 7 | import java.util.*; 8 | 9 | class Pair { // A class pair is required here which contains node and it's distance from 10 | // starting node 11 | int node; 12 | int distance; 13 | 14 | Pair(int nod, int dist) { 15 | node = nod; 16 | distance = dist; 17 | } 18 | } 19 | 20 | public class Prims_Algo { 21 | public static void main(String[] args) { 22 | int vertex = 3; 23 | int edge = 3; 24 | // example -----> [[0,1,5],[1,2,3],[0,2,1]] 25 | int[][] arr = { { 0, 1, 5 }, { 1, 2, 3 }, { 0, 2, 1 } }; 26 | int ans = prims(vertex, edge, arr); 27 | // Printing our result(Optional) 28 | System.out.print(ans); 29 | // Answer would come out as 4 30 | } 31 | 32 | static int prims(int vertex, int edge, int mat[][]) { // vertex =no. of vertices ,E =no. of mat ,mat =mat of each 33 | // node 34 | ArrayList> arr = new ArrayList<>(); 35 | for (int i = 0; i < vertex; i++) 36 | arr.add(new ArrayList<>()); 37 | for (int i = 0; i < edge; i++) { 38 | int parent = mat[i][0]; 39 | int current = mat[i][1]; 40 | int wt = mat[i][2]; 41 | 42 | arr.get(parent).add(new Pair(current, wt)); 43 | arr.get(current).add(new Pair(parent, wt)); 44 | } 45 | 46 | PriorityQueue qu = new PriorityQueue<>((a, b) -> a.distance - b.distance); // Sort w.r.t their distances 47 | int[] visited = new int[vertex]; 48 | int sum = 0; 49 | qu.add(new Pair(0, 0)); 50 | 51 | while (!qu.isEmpty()) { 52 | Pair curr = qu.poll(); 53 | int vaal = curr.node; 54 | int dist = curr.distance; 55 | 56 | if (visited[vaal] != 0) 57 | continue; 58 | visited[vaal] = 1; 59 | sum += dist; 60 | 61 | for (int i = 0; i < arr.get(vaal).size(); i++) { 62 | int dis = arr.get(vaal).get(i).distance; 63 | int vl = arr.get(vaal).get(i).node; 64 | if (visited[vl] == 0) 65 | qu.add(new Pair(vl, dis)); 66 | } 67 | } 68 | 69 | return sum; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Graphs/README.md: -------------------------------------------------------------------------------- 1 | # Graph Algorithms 2 | A graph is a unique data structure in programming that consists of finite sets of nodes or vertices and a set of edges, 3 | that connect these vertices to them. At this moment, adjacent vertices can be called those vertices, 4 | that are connected to the same edge with each other. 5 | In simple terms, a graph is a visual representation of vertices and edges sharing some connection or relationship. 6 | 7 | # Types of Graphs 8 | 9 | - **Order:** Order defines the total number of vertices present in the graph. 10 | - **Size:** Size defines the number of edges present in the graph. 11 | - **Self-loop:** Self-loop refers to edges that connect a vertex to itself. 12 | - **Isolated vertex:** An isolated vertex is a vertex that is not connected to any other vertices in the graph. 13 | - **Vertex degree:** Vertex degree is defined as the number of edges incident to a vertex in a graph. 14 | - **Weighted graph:** A weighted graph is a graph where vertices have associated values or weights 15 | - **Unweighted graph:** An unweighted graph is a graph where vertices have no associated values or weights. 16 | - **Directed graph:** A directed graph is a graph where edges have a direction indicator, 17 | meaning they go from one vertex to another in a specific direction. 18 | - **Undirected graph:** An undirected graph is a graph where edges have no specified direction; 19 | they simply connect two vertices without indicating a specific direction. 20 | 21 | ![](https://www.differencebetween.com/wp-content/uploads/2011/05/DifferenceBetween_Directed_UnDirected_Graphs1.jpg) 22 | 23 | This section contains a lot of important algorithms that help us to use Graph algorithms in various scenarios. 24 | 25 | ## References 26 | * 27 | * 28 | -------------------------------------------------------------------------------- /Graphs/adjacent_ListGraphs.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class adjacent_ListGraphs { 6 | public static void main(String[] args) { 7 | int v= 5; 8 | int e =10; 9 | 10 | int a[][] = new int[v+1][v+1]; 11 | ArrayList> adj = new ArrayList<>(); 12 | for (int i = 0; i <= v ; i++) { 13 | adj.add(new ArrayList()); 14 | } 15 | } 16 | static void addEdge(int a[][],int source , int dest){ 17 | a[source][dest] = 1; 18 | a[dest][source] = 1; 19 | } 20 | static void addEdge(ArrayList> adj,int source,int dest){ 21 | adj.get(source).add(dest); 22 | adj.get(dest).add(source); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Graphs/bellman_ford.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /* 4 | * edges: vector of vectors which represents the graph 5 | * S: source vertex to start traversing graph with 6 | * V: number of vertices 7 | */ 8 | //https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm 9 | 10 | class Solution { 11 | static int[] bellman_ford(int V, 12 | ArrayList> edges, int S) { 13 | int[] dist = new int[V]; 14 | for (int i = 0; i < V; i++) dist[i] = (int)(1e8); 15 | dist[S] = 0; 16 | // V x E 17 | for (int i = 0; i < V - 1; i++) { 18 | for (ArrayList it : edges) { 19 | int u = it.get(0); 20 | int v = it.get(1); 21 | int wt = it.get(2); 22 | if (dist[u] != 1e8 && dist[u] + wt < dist[v]) { 23 | dist[v] = dist[u] + wt; 24 | } 25 | } 26 | } 27 | // Nth relaxation to check negative cycle 28 | for (ArrayList it : edges) { 29 | int u = it.get(0); 30 | int v = it.get(1); 31 | int wt = it.get(2); 32 | if (dist[u] != 1e8 && dist[u] + wt < dist[v]) { 33 | int temp[] = new int[1]; 34 | temp[0] = -1; 35 | return temp; 36 | } 37 | } 38 | return dist; 39 | } 40 | } 41 | 42 | public class tUf { 43 | public static void main(String[] args) { 44 | int V = 6; 45 | int S = 0; 46 | ArrayList> edges = new ArrayList<>() { 47 | { 48 | add(new ArrayList(Arrays.asList(3, 2, 6))); 49 | add(new ArrayList(Arrays.asList(5, 3, 1))); 50 | add(new ArrayList(Arrays.asList(0, 1, 5))); 51 | add(new ArrayList(Arrays.asList(1, 5, -3))); 52 | add(new ArrayList(Arrays.asList(1, 2, -2))); 53 | add(new ArrayList(Arrays.asList(3, 4, -2))); 54 | add(new ArrayList(Arrays.asList(2, 4, 3))); 55 | } 56 | }; 57 | 58 | 59 | 60 | int[] dist = Solution.bellman_ford(V, edges, S); 61 | for (int i = 0; i < V; i++) { 62 | System.out.print(dist[i] + " "); 63 | } 64 | System.out.println(""); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Graphs/bfs_apna.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.Queue; 6 | 7 | public class bfs_apna { 8 | public static class edge{ 9 | int src; 10 | int dest; 11 | public edge(int s, int d){ 12 | this.src = s; 13 | this.dest = d; 14 | } 15 | } 16 | 17 | public static void createGraph(ArrayList graph[]){ 18 | for (int i = 0; i < graph.length; i++) { 19 | graph[i] = new ArrayList(); 20 | } 21 | 22 | graph[0].add(new edge(0,1)); 23 | graph[0].add(new edge(0,2)); 24 | 25 | graph[1].add(new edge(1,0)); 26 | graph[1].add(new edge(1,3)); 27 | 28 | graph[2].add(new edge(2,0)); 29 | graph[2].add(new edge(2,4)); 30 | 31 | graph[3].add(new edge(3,1)); 32 | graph[3].add(new edge(3,4)); 33 | graph[3].add(new edge(3,5)); 34 | 35 | graph[4].add(new edge(4,2)); 36 | graph[4].add(new edge(4,3)); 37 | graph[4].add(new edge(4,5)); 38 | 39 | graph[5].add(new edge(5,3)); 40 | graph[5].add(new edge(5,4)); 41 | graph[5].add(new edge(5,6)); 42 | 43 | graph[5].add(new edge(6,5)); 44 | 45 | } 46 | public static void bfs(ArrayList graph[],int V){ 47 | Queue q = new LinkedList<>(); 48 | boolean vis[] = new boolean[V]; 49 | q.add(0); 50 | while (!q.isEmpty()){ 51 | int curr = q.remove(); 52 | if(vis[curr] == false){ 53 | System.out.print(curr+" "); 54 | vis[curr] = true; 55 | 56 | for (int i = 0; i < graph[curr].size(); i++) { 57 | edge e = graph[curr].get(i); 58 | q.add(e.dest); 59 | } 60 | } 61 | } 62 | } 63 | // for disconnected graphs 64 | public static void bfs(ArrayList graph[], int V, boolean vis[], int start){ 65 | Queue q = new LinkedList<>(); 66 | 67 | q.add(start); 68 | 69 | while(!q.isEmpty()){ 70 | int curr = q.remove(); 71 | if (vis[curr] == false){ 72 | System.out.print(curr+" "); 73 | vis[curr] = true; 74 | 75 | for (int i = 0; i < graph[curr].size(); i++) { 76 | edge e = graph[curr].get(i); 77 | q.add(e.dest); 78 | } 79 | } 80 | } 81 | } 82 | public static void main(String[] args) { 83 | int V = 7; 84 | ArrayList graph[] = new ArrayList[V]; 85 | createGraph(graph); 86 | bfs(graph,V); 87 | System.out.println(); 88 | 89 | // for disconnected graph or can be used for every graph other than disconnected graph 90 | boolean vis[] = new boolean[V]; 91 | for (int i = 0; i < V; i++) { 92 | if (vis[i] == false){ 93 | bfs(graph,V,vis,i); 94 | } 95 | } 96 | System.out.println(); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Graphs/cycle_detection.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class cycle_detection { 6 | public static class edge { 7 | int src; 8 | int dest; 9 | 10 | public edge(int s, int d) { 11 | this.src = s; 12 | this.dest = d; 13 | } 14 | } 15 | public static void createGraph(ArrayList graph[]) { 16 | for (int i = 0; i < graph.length; i++) { 17 | graph[i] = new ArrayList(); 18 | } 19 | graph[0].add(new edge(0,2)); 20 | graph[1].add(new edge(1,0)); 21 | graph[2].add(new edge(2,3)); 22 | graph[3].add(new edge(3,0)); 23 | } 24 | public static boolean cyclic(ArrayList graph[],boolean vis[], int curr, boolean rec[]){ 25 | vis[curr] = true; 26 | rec[curr] = true; 27 | for (int i = 0; i < graph[curr].size(); i++) { 28 | edge e = graph[curr].get(i); 29 | if(rec[e.dest]){ // cyclic 30 | return true; 31 | } else if (!vis[e.dest]) { 32 | if(cyclic(graph,vis,e.dest,rec)) 33 | return true; 34 | } 35 | } 36 | rec[curr] = false; 37 | return false; 38 | } 39 | public static void main(String[] args) { 40 | int V = 4; 41 | ArrayList graph[] = new ArrayList[V]; 42 | createGraph(graph); 43 | 44 | System.out.println(cyclic(graph, new boolean[V],0,new boolean[V])); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Graphs/dfs_apna.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class dfs_apna { 6 | public static class edge{ 7 | int src; 8 | int dest; 9 | public edge(int s, int d){ 10 | this.src = s; 11 | this.dest = d; 12 | } 13 | } 14 | public static void createGraph(ArrayList graph[]){ 15 | for (int i = 0; i < graph.length; i++) { 16 | graph[i] = new ArrayList(); 17 | } 18 | 19 | graph[0].add(new edge(0,1)); 20 | graph[0].add(new edge(0,2)); 21 | 22 | graph[1].add(new edge(1,0)); 23 | graph[1].add(new edge(1,3)); 24 | 25 | graph[2].add(new edge(2,0)); 26 | graph[2].add(new edge(2,4)); 27 | 28 | graph[3].add(new edge(3,1)); 29 | graph[3].add(new edge(3,4)); 30 | graph[3].add(new edge(3,5)); 31 | 32 | graph[4].add(new edge(4,2)); 33 | graph[4].add(new edge(4,3)); 34 | graph[4].add(new edge(4,5)); 35 | 36 | graph[5].add(new edge(5,3)); 37 | graph[5].add(new edge(5,4)); 38 | graph[5].add(new edge(5,6)); 39 | 40 | graph[5].add(new edge(6,5)); 41 | 42 | } 43 | 44 | // O(V+E) V = vertices and E = edges 45 | public static void dfs(ArrayList graph[], int curr,boolean vis[]){ 46 | System.out.print(curr+" "); 47 | vis[curr] = true; 48 | 49 | for (int i = 0; i < graph[curr].size(); i++) { 50 | edge e = graph[curr].get(i); 51 | if (vis[e.dest] == false) 52 | dfs(graph,e.dest,vis); 53 | } 54 | } 55 | public static void main(String[] args) { 56 | int V = 7; 57 | ArrayList graph[] = new ArrayList[V]; 58 | boolean vis[] = new boolean[V]; 59 | createGraph(graph); 60 | dfs(graph,0,vis); 61 | System.out.println(); 62 | 63 | // for disconnected graph or can be used for every graph other than disconnected graph 64 | // comment 58 line to run below 65 | for (int i = 0; i < V; i++) { 66 | if (vis[i] == false){ 67 | dfs(graph,0,vis); 68 | } 69 | } 70 | System.out.println(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Graphs/grabh_by_linkedList.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class grabh_by_linkedList { 6 | public static void main(String[] args) { 7 | grabh_by_linkedList g = new grabh_by_linkedList(4); 8 | g.addEdge(0,1); 9 | } 10 | private LinkedList[] adj; 11 | private int V;//no. of vertices 12 | private int E;//no. of edges 13 | 14 | public grabh_by_linkedList(int nodes){ 15 | this.V = nodes; 16 | this.E = 0; 17 | this.adj = new LinkedList[nodes]; 18 | for (int v = 0; v < V; v++) { 19 | adj[v] = new LinkedList<>(); 20 | } 21 | } 22 | 23 | public void addEdge(int u , int v){ 24 | adj[u].add(v); 25 | adj[v].add(u); 26 | E++; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Graphs/graph.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | public class graph { 4 | public static void main(String[] args) { 5 | graph g = new graph(4); 6 | g.addEdge(0,1); 7 | g.addEdge(1,2); 8 | g.addEdge(2,3); 9 | g.addEdge(3,0); 10 | System.out.println(g); 11 | } 12 | 13 | public String toSTring(){ 14 | StringBuilder sb = new StringBuilder(); 15 | sb.append(V+"vertices , "+" "+U+"edges"+"\n"); 16 | for (int v = 0; v graph[]){ 17 | for (int i = 0; i < graph.length; i++) { 18 | graph[i] = new ArrayList(); 19 | } 20 | 21 | graph[0].add(new Edge(0,2,2)); 22 | 23 | graph[1].add(new Edge(1,2,10)); 24 | graph[1].add(new Edge(1,3,0)); 25 | 26 | graph[2].add(new Edge(2,0,2)); 27 | graph[2].add(new Edge(2,1,10)); 28 | graph[2].add(new Edge(2,3,-1)); 29 | 30 | graph[3].add(new Edge(3,1,0)); 31 | graph[3].add(new Edge(3,2,-1)); 32 | } 33 | public static void main(String[] args) { 34 | int V = 4; 35 | 36 | ArrayList graph[] = new ArrayList[V]; 37 | createGraph(graph); 38 | 39 | //print 2's neighbour 40 | for (int i = 0; i < graph[2].size(); i++) { 41 | Edge e = graph[2].get(i); 42 | System.out.println(e.dest+" has weight "+e.wt); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Graphs/kahns_Algo.java: -------------------------------------------------------------------------------- 1 | // --------------------------------KAHN'S ALGORITHM--------------------------------------------- 2 | // BASICALLY BREADTH FIRST SEARCH APPROACH TO FIND TOPOLOGICAL SORT FOR DIRECTED ACYCLIC GRAPH 3 | // REQUIREMENTS:- QUEUE AND A INDEGREE ARRAY 4 | // CONCEPTS:- INDERGREE ARRAY -> Array containing total number of edges directed towards a node in a graph. 5 | // WIKI:- https://en.wikipedia.org/wiki/Topological_sorting 6 | 7 | import java.util.*; 8 | 9 | public class kahns_Algo { 10 | public static void main(String[] args) { 11 | int vertex = 6; 12 | ArrayList> adj = new ArrayList<>(); 13 | int[][] mat = { {}, { 3 }, { 3 }, {}, { 0, 1 }, { 2, 0 } }; // There is an directed edge from index to all given 14 | // elements in that index 15 | for (int i = 0; i < 6; i++) { 16 | ArrayList temp = new ArrayList(); 17 | for (int j = 0; j < mat[i].length; j++) 18 | temp.add(mat[i][j]); 19 | adj.add(temp); 20 | } 21 | int[] ans = kahn(vertex, adj); 22 | // Printing our result(Optional) 23 | for (int i = 0; i < ans.length; i++) 24 | System.out.print(ans[i] + " "); 25 | // Answer is 4 5 1 2 0 3 here 26 | } 27 | 28 | static int[] kahn(int vertex, ArrayList> adj) { // vertex =no. of vertices ,adj =Adjacency matrix 29 | // containing edges between vertices 30 | Queue qu = new LinkedList<>(); 31 | int[] indeg = new int[vertex]; 32 | int[] ans = new int[vertex]; // Final Array containing our topological sort 33 | 34 | for (int i = 0; i < vertex; i++) { 35 | for (int j : adj.get(i)) 36 | indeg[j]++; 37 | } 38 | 39 | for (int i = 0; i < vertex; i++) { 40 | if (indeg[i] == 0) 41 | qu.offer(i); 42 | } 43 | 44 | int cnt = 0; 45 | while (!qu.isEmpty()) { 46 | int curr = qu.poll(); 47 | ans[cnt++] = curr; 48 | 49 | for (int i : adj.get(curr)) { 50 | --indeg[i]; 51 | if (indeg[i] == 0) 52 | qu.offer(i); 53 | } 54 | } 55 | 56 | return ans; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Graphs/maxPath_inMaze.java: -------------------------------------------------------------------------------- 1 | public class maxPath_inMaze { 2 | public static void main(String[] args) { 3 | System.out.println(maxPath(0,0,3,3)); 4 | } 5 | public static int maxPath(int i,int j,int n,int m){ 6 | if(i==n || j==m) return 0; 7 | if(i == n-1 && j == m-1) return 1; 8 | 9 | int downward = maxPath(i+1,j,n,m); 10 | int right = maxPath(i,j+1,n,m); 11 | return downward+right; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Graphs/print_full_path.java: -------------------------------------------------------------------------------- 1 | package Graphs; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class print_full_path { 6 | public static class edge { 7 | int src; 8 | int dest; 9 | 10 | public edge(int s, int d) { 11 | this.src = s; 12 | this.dest = d; 13 | } 14 | } 15 | 16 | public static void createGraph(ArrayList graph[]) { 17 | for (int i = 0; i < graph.length; i++) { 18 | graph[i] = new ArrayList(); 19 | } 20 | 21 | graph[0].add(new edge(0, 1)); 22 | graph[0].add(new edge(0, 2)); 23 | 24 | graph[1].add(new edge(1, 0)); 25 | graph[1].add(new edge(1, 3)); 26 | 27 | graph[2].add(new edge(2, 0)); 28 | graph[2].add(new edge(2, 4)); 29 | 30 | graph[3].add(new edge(3, 1)); 31 | graph[3].add(new edge(3, 4)); 32 | graph[3].add(new edge(3, 5)); 33 | 34 | graph[4].add(new edge(4, 2)); 35 | graph[4].add(new edge(4, 3)); 36 | graph[4].add(new edge(4, 5)); 37 | 38 | graph[5].add(new edge(5, 3)); 39 | graph[5].add(new edge(5, 4)); 40 | graph[5].add(new edge(5, 6)); 41 | 42 | graph[5].add(new edge(6, 5)); 43 | 44 | } 45 | //O(V^V) where V = vertices 46 | public static void printAllPath(ArrayList graph[],boolean vis[], int curr,String path, int tar){ 47 | if (curr == tar){ 48 | System.out.println(path); 49 | return; 50 | } 51 | for (int i = 0; i < graph[curr].size(); i++) { 52 | edge e = graph[curr].get(i); 53 | if (!vis[e.dest]){ 54 | vis[curr] = true; 55 | printAllPath(graph,vis,e.dest,path+e.dest,tar); 56 | vis[curr] = false; 57 | } 58 | } 59 | } 60 | public static void main(String[] args) { 61 | int V = 7; 62 | ArrayList graph[] = new ArrayList[V]; 63 | createGraph(graph); 64 | 65 | int src=0, tar=5; 66 | printAllPath(graph,new boolean[V],src,"0",tar); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Graphs/topological_sorting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | // More about this sorting : https://en.wikipedia.org/wiki/Topological_sorting 3 | 4 | // This class represents a directed graph using adjacency 5 | // list representation 6 | class topological_sorting 7 | { 8 | private int V; // No. of vertices 9 | private LinkedList adj[]; // Adjacency List 10 | 11 | //Constructor 12 | topological_sorting(int v) 13 | { 14 | V = v; 15 | adj = new LinkedList[v]; 16 | for (int i=0; i it = adj[v].iterator(); 35 | while (it.hasNext()) 36 | { 37 | i = it.next(); 38 | if (!visited[i]) 39 | topologicalSortUtil(i, visited, stack); 40 | } 41 | 42 | // Push current vertex to stack which stores result 43 | stack.push(new Integer(v)); 44 | } 45 | 46 | // The function to do Topological Sort. It uses 47 | // recursive topologicalSortUtil() 48 | void topologicalSort() 49 | { 50 | Stack stack = new Stack(); 51 | 52 | // Mark all the vertices as not visited 53 | boolean visited[] = new boolean[V]; 54 | for (int i = 0; i < V; i++) 55 | visited[i] = false; 56 | 57 | // Call the recursive helper function to store 58 | // Topological Sort starting from all vertices 59 | // one by one 60 | for (int i = 0; i < V; i++) 61 | if (visited[i] == false) 62 | topologicalSortUtil(i, visited, stack); 63 | 64 | // Print contents of stack 65 | while (stack.empty()==false) 66 | System.out.print(stack.pop() + " "); 67 | } 68 | 69 | // Main method 70 | public static void main(String args[]) 71 | { 72 | topological_sorting g = new topological_sorting(6); 73 | g.addEdge(5, 2); 74 | g.addEdge(5, 0); 75 | g.addEdge(4, 0); 76 | g.addEdge(4, 1); 77 | g.addEdge(2, 3); 78 | g.addEdge(3, 1); 79 | 80 | System.out.println("Topological sort of the given graph"); 81 | g.topologicalSort(); 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /HashMap/Min_window_substring.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class Min_window_substring { 4 | public static void main(String[] args) { 5 | String s1 = "timetopractice"; 6 | String s2 = "toc"; 7 | String s = solutions(s1,s2); 8 | System.out.println(s); 9 | } 10 | static String solutions(String s1, String s2){ 11 | String ans = " " ; 12 | HashMap map2 = new HashMap<>(); 13 | for (int i = 0; i< s2.length(); i++) { 14 | char ch = s2.charAt(i); 15 | map2.put(ch, map2.getOrDefault(ch,0) + 1); 16 | } 17 | 18 | int mct = 0; 19 | int dmct = s2.length(); 20 | 21 | HashMap map1 = new HashMap<>(); 22 | int i =-1; 23 | int j=-1; 24 | 25 | while(true){ 26 | boolean f1 = false; 27 | boolean f2 = false; 28 | //acquire 29 | while (i < s1.length()-1 && mct disinct(int a[],int window){ 10 | ArrayList list = new ArrayList<>(); 11 | HashSet hs = new HashSet<>(); 12 | for (int x:a) { 13 | hs.add(x); 14 | } 15 | for (int i = 0; i < a.length; i++) { 16 | for (int j = i; j < i+4; j++) { 17 | 18 | } 19 | } 20 | return list; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /HashMap/hashmap.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Iterator; 3 | import java.util.Map; 4 | 5 | class hashmap{ 6 | public static void main(String[] args) { 7 | //System.out.println("hi there"); 8 | HashMap map = new HashMap<>(); 9 | map.put(1, 11); 10 | map.put(2, 22); 11 | map.put(3, 33); 12 | map.put(4, 44); 13 | System.out.println(map); 14 | 15 | for(Map.Entry e : map.entrySet()){ 16 | System.out.println(e.getKey()); 17 | System.out.println(e.getValue()); 18 | } 19 | while(!map.isEmpty()){ 20 | map.put(0,map.getOrDefault(0,1)); 21 | } 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /HashMap/hashset.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan472000/Java-DSA-InterviewPrep/f1631cff54adf2170e99816233ac5fd9e832c2ec/HashMap/hashset.java -------------------------------------------------------------------------------- /HashMap/intersection_of_array.java: -------------------------------------------------------------------------------- 1 | package HashMap; 2 | 3 | import java.util.HashSet; 4 | 5 | public class intersection_of_array { 6 | public static int intersection(int[] a,int[] b) { 7 | HashSet set = new HashSet<>(); 8 | int count = 0; 9 | for (int i = 0; i < a.length; i++) { 10 | set.add(a[i]); 11 | } 12 | 13 | for (int j = 0; j < b.length; j++) { 14 | if (set.contains(b[j])) { 15 | count++; 16 | set.remove(b[j]); 17 | } 18 | } 19 | return count; //give count of common elements 20 | } 21 | 22 | 23 | public static void main(String[] args) { 24 | int[] nums = {1,2,5,1,3,1,5,1}; 25 | int[] nums1 = {9,5,5,8}; 26 | System.out.println(intersection(nums,nums1)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /HashMap/itenerary.java: -------------------------------------------------------------------------------- 1 | package HashMap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class itenerary { 6 | public static String getStart(HashMap tick){ 7 | HashMap revmap = new HashMap<>(); 8 | for (String key:tick.keySet()) { 9 | revmap.put(tick.get(key),key); 10 | } 11 | for (String key: tick.keySet()) { 12 | if (revmap.containsKey(key)) 13 | return key; 14 | } 15 | return null; 16 | } 17 | public static void main(String[] args) { 18 | HashMap map = new HashMap<>(); 19 | map.put( "chennai","bengaluru"); 20 | map.put("mumbai","delhi"); 21 | map.put("goa","chennai"); 22 | map.put("delhi","goa"); 23 | 24 | String start = getStart(map); 25 | // System.out.println(start+"-----"); 26 | while (map.containsKey(start)){ 27 | // System.out.println("-----"); 28 | System.out.println(start); 29 | start = map.get(start); 30 | } 31 | // System.out.println("-------"); 32 | System.out.println(start); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /HashMap/remove_adjacent_duplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class remove_adjacent_duplicates { 5 | public static void main(String[] args) { 6 | String s = "pbbcggttciiippooaais"; 7 | System.out.println(removeDuplicates(s, 2)); 8 | } 9 | 10 | public static String removeDuplicates(String s, int k) { 11 | // Map map = new HashMap<>(); 12 | // String finalres =""; 13 | // char[] charr = s.toCharArray(); 14 | // for (Character c : charr) { 15 | // map.put(c, map.getOrDefault(c, 0)+1); 16 | // } 17 | // for (Map.Entry e : map.entrySet()) { 18 | //// for (int i = 0; i < e.getValue(); i++) { 19 | //// System.out.println(e + " --" + i); 20 | //// } 21 | //// if(e.getValue() != k ){ 22 | //// for (int i = 0; i < e.getValue() ; i++) { 23 | //// finalres+=e.getKey(); 24 | //// } 25 | //// } 26 | // finalres+=e.getKey(); 27 | // } 28 | // return finalres; 29 | int count = 1; 30 | for (int i = 0; i < s.length(); i++) { 31 | if (s.charAt(i) == s.charAt(i - 1)) { 32 | count++; 33 | } else count = 1; 34 | 35 | if (count == k) { 36 | String reduce = s.substring(0, i - k + 1) + s.substring(i + 1); 37 | return removeDuplicates(reduce, k); 38 | } 39 | }return s; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /HashMap/subarray_sum_equal_to_K.java: -------------------------------------------------------------------------------- 1 | package HashMap; 2 | 3 | import java.util.HashMap; 4 | 5 | public class subarray_sum_equal_to_K { 6 | public static int subsum(int[] a,int k){ 7 | int ans =0; 8 | HashMap map = new HashMap<>(); 9 | map.put(0,1); 10 | int sum=0; 11 | for (int i = 0; i < a.length; i++) { 12 | sum+=a[i]; 13 | if (map.containsKey(sum-k)){ 14 | ans+=map.get(sum-k); 15 | } 16 | map.put(sum, map.getOrDefault(sum,0)+1); 17 | } 18 | return ans; 19 | } 20 | public static void main(String[] args) { 21 | int[] arr = {10,2,-2,-20,10}; 22 | int k = -10; 23 | 24 | HashMap map = new HashMap<>(); 25 | 26 | map.put(0,1); 27 | int ans = 0; 28 | int sum =0 ; 29 | for (int i = 0; i < arr.length; i++) { 30 | sum+=arr[i]; 31 | 32 | if (map.containsKey(sum-k)){ 33 | //System.out.println(sum-k); 34 | ans+=map.get(sum-k); 35 | } 36 | if (map.containsKey(sum)){ 37 | map.put(sum,map.get(sum)+1); 38 | }else { 39 | map.put(sum,1); 40 | } 41 | } 42 | System.out.println("----------"); 43 | System.out.println(ans); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /HashMap/union_of_two_arrays.java: -------------------------------------------------------------------------------- 1 | package HashMap; 2 | 3 | import java.util.HashSet; 4 | 5 | public class union_of_two_arrays { 6 | public static int printUnion(int[] a,int[] b){ 7 | HashSet set = new HashSet<>(); 8 | 9 | for (int i = 0; i < a.length; i++) { 10 | set.add(a[i]); 11 | } 12 | for (int i = 0; i < b.length; i++) { 13 | set.add(b[i]); 14 | } 15 | System.out.println(set); // print all elements present in hashset 16 | return set.size(); 17 | } 18 | public static void main(String[] args) { 19 | int[] nums = {2,5,1,3,1,5,1}; 20 | int[] nums1 = {9,5,5,8}; 21 | System.out.println(printUnion(nums,nums1)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Heap/HeapSort.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | 3 | public class HeapSort { 4 | public static void heapSort(int arr[]){ // maxheap as maxIdx is taken 5 | //step-1: build maxheap 6 | int n = arr.length; 7 | for (int i = n/2; i >=0; i--) { 8 | heapify(arr,i,n); 9 | } 10 | //step-2: push target at end 11 | for (int i = n-1; i >0 ; i--) { 12 | // swap (largest-first with last) 13 | int temp = arr[0]; 14 | arr[0] = arr[i]; 15 | arr[i] = temp; 16 | 17 | heapify(arr,0,i); 18 | } 19 | } 20 | 21 | private static void heapify(int arr[],int i, int size) { 22 | int left = 2*i+1; 23 | int right = 2*i+2; 24 | int maxIdx = i; 25 | if (left < size && arr[left] > arr[maxIdx]) maxIdx = left; 26 | if (right < size && arr[right] > arr[maxIdx]) maxIdx=right; 27 | 28 | if (maxIdx != i){ 29 | //swap 30 | int temp = arr[i]; 31 | arr[i] = arr[maxIdx]; 32 | arr[maxIdx] = temp; 33 | 34 | heapify(arr,i,size); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | int arr[] = {1,2,4,5,3,1}; 40 | heapSort(arr); 41 | 42 | // print 43 | for (int i = 0; i < arr.length; i++) { 44 | System.out.print(arr[i]+" "); 45 | } 46 | System.out.println(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Heap/NRopes.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class NRopes { 6 | public static void main(String[] args) { 7 | int ropes[] = {2,3,3,4,6}; 8 | 9 | PriorityQueue pq = new PriorityQueue<>(); 10 | for (int i = 0; i < ropes.length; i++) { 11 | pq.add(ropes[i]); 12 | } 13 | 14 | int cost = 0; 15 | while (pq.size() > 1){ 16 | int min = pq.remove(); 17 | int min2 = pq.remove(); 18 | cost += min+min2; 19 | pq.add(min+min2); 20 | } 21 | System.out.println("cost of connecting ropes = "+cost); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Heap/NearbyCars.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class NearbyCars { 6 | public static class Point implements Comparable{ 7 | int x,y,distSq,idx; 8 | public Point(int x, int y, int distSq, int idx){ 9 | this.x=x; 10 | this.y=y; 11 | this.distSq=distSq; 12 | this.idx = idx; 13 | } 14 | 15 | @Override 16 | public int compareTo(Point p2) { 17 | return this.distSq-p2.distSq; 18 | } 19 | } 20 | public static void main(String[] args) { 21 | int pts[][] = {{3,3},{5,-1},{-2,4}}; 22 | int k = 2; 23 | 24 | PriorityQueue pq = new PriorityQueue<>(); 25 | for (int i = 0; i < pts.length ; i++) { 26 | int distSq = pts[i][0]*pts[i][0] + pts[i][1]*pts[i][1]; 27 | pq.add(new Point(pts[i][0],pts[i][1],distSq,i)); 28 | } 29 | //nearest k cars 30 | for (int i = 0; i < k; i++) { 31 | System.out.println("C"+pq.remove().idx); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Heap/apna_heap.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class apna_heap { 6 | static class Heap{ //min heap only 7 | ArrayList arr = new ArrayList<>(); 8 | 9 | public void add(int data){// O(log(n)) 10 | // add at last 11 | arr.add(data); 12 | int x = arr.size()-1;//x is child index 13 | int par = (x-1)/2;// parent index 14 | 15 | while(arr.get(x) < arr.get(par)){ // O(log(n)) 16 | //swap 17 | int temp = arr.get(x); 18 | arr.set(x,arr.get(par)); 19 | arr.set(par,temp); 20 | 21 | x = par; 22 | par = (x-1)/2; 23 | } 24 | } 25 | 26 | public int peek(){ 27 | return arr.get(0); 28 | } 29 | private void heapify(int i){ 30 | int left = 2*i+1; 31 | int right = 2*i+2; 32 | int minIdx = i; 33 | 34 | if (left < arr.size() && arr.get(minIdx) > arr.get(left)){ 35 | minIdx = left; 36 | } 37 | if (right < arr.size() && arr.get(minIdx) > arr.get(right)){ 38 | minIdx = right; 39 | } 40 | if (minIdx != i){ 41 | // swap 42 | int temp = arr.get(i); 43 | arr.set(i,arr.get(minIdx)); 44 | arr.set(minIdx,temp); 45 | 46 | heapify(minIdx); 47 | } 48 | } 49 | public int remove(){ 50 | int data = arr.get(0); 51 | // step-1: swap first and last 52 | int temp = arr.get(0); 53 | arr.set(0,arr.get(arr.size()-1)); 54 | arr.set(arr.size()-1,temp); 55 | 56 | // step-2: delete last 57 | arr.remove(arr.size()-1); 58 | 59 | //step-3: heapify 60 | heapify(0); 61 | return data; 62 | } 63 | public boolean isEmpty(){ 64 | return arr.size() == 0; 65 | } 66 | 67 | } 68 | 69 | public static void main(String[] args) { 70 | Heap h = new Heap(); 71 | h.add(3); 72 | h.add(4); 73 | h.add(5); 74 | h.add(1 ); 75 | while (!h.isEmpty()){ // heap sort 76 | System.out.println(h.peek()); 77 | h.remove(); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Heap/median_of_runningStreamOfInteger.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | import java.util.*; 3 | 4 | public class median_of_runningStreamOfInteger { 5 | public static void main(String[] args) { 6 | median_of_runningStreamOfInteger obj = new median_of_runningStreamOfInteger(); 7 | obj.insertNum(3); 8 | obj.insertNum(1); 9 | System.out.println(median()); 10 | obj.insertNum(5); 11 | System.out.println(median()); 12 | } 13 | public static PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 14 | public static PriorityQueue minHeap = new PriorityQueue<>(); 15 | 16 | public static void insertNum(int num){ 17 | if (maxHeap.isEmpty() || maxHeap.peek() >= num) 18 | maxHeap.add(num); 19 | else 20 | minHeap.add(num); 21 | 22 | if (maxHeap.size() > minHeap.size()+1) 23 | minHeap.add(maxHeap.poll()); 24 | else if (maxHeap.size() < minHeap.size()) { 25 | maxHeap.add(minHeap.poll()); 26 | } 27 | } 28 | public static double median(){ 29 | if (maxHeap.size() == minHeap.size()) 30 | return (maxHeap.peek()+ minHeap.peek())/2; 31 | return maxHeap.peek(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Heap/sliding_window_median.java: -------------------------------------------------------------------------------- 1 | package Heap; 2 | 3 | public class sliding_window_median { 4 | 5 | public static void main(String[] args) { 6 | int a[] = {1,3,-1,-3,5,3,6,7}; 7 | int k =3; 8 | 9 | } 10 | public static double median(int a[],int k){ 11 | int b[] = new int[a.length]; 12 | int c[] = new int[3]; 13 | for (int x:a) { 14 | a[x] = b[x]; 15 | } 16 | for (int i = 0,j=i+k; i <= a.length-k ; i++,j++) { 17 | if (j <= a.length){ 18 | 19 | } 20 | 21 | }return 2.8; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LL/LL1.java: -------------------------------------------------------------------------------- 1 | package LL; 2 | 3 | public class LL1 { 4 | Node head; 5 | private int size; 6 | LL1(){ 7 | this.size = 0; 8 | } 9 | public static void main(String[] args) { 10 | LL1 list = new LL1(); 11 | list.addFirst("a"); 12 | list.addFirst("ab"); 13 | list.addLast("zzzz"); 14 | list.printall(); 15 | 16 | //list.deleteFirst(); 17 | //list.printall(); 18 | 19 | //System.out.println(list.getSize()); 20 | 21 | list.head = list.reverse(list.head); 22 | list.printall(); 23 | } 24 | public static Node reverse(Node head){ 25 | if (head == null || head.next==null) 26 | return head; 27 | Node newHead = reverse(head.next); 28 | head.next.next = head; 29 | head.next = null; 30 | 31 | return newHead; 32 | /*Node current = head; 33 | Node previous = null; 34 | Node next = null; 35 | 36 | while(current != null){ 37 | next = current.next; 38 | current.next = previous; 39 | previous = current; 40 | current = next; 41 | 42 | } 43 | return previous;*/ 44 | 45 | } 46 | public int getSize(){ 47 | 48 | return size; 49 | } 50 | public void deleteFirst(){ 51 | if (head == null){ 52 | System.out.print("list is empty"); 53 | return; 54 | } 55 | size--; 56 | head = head.next; 57 | 58 | } 59 | public void deleteLast(){ 60 | if (head == null){ 61 | System.out.print("list is empty"); 62 | return; 63 | } 64 | size--; 65 | if (head.next == null){ 66 | head = null; 67 | return; 68 | } 69 | Node secondLast = head; 70 | Node lastNode = head; 71 | while(lastNode.next != null){ 72 | lastNode = lastNode.next; 73 | secondLast = secondLast.next; 74 | } 75 | secondLast.next = null; 76 | } 77 | public void addLast(String data){ 78 | Node newNode = new Node(data); 79 | //Node head = null; 80 | if (head == null){ 81 | head = newNode; 82 | return; 83 | } 84 | Node currNode = head; 85 | while (currNode.next != null){ 86 | currNode = currNode.next; 87 | } 88 | currNode.next = newNode; 89 | } 90 | 91 | public void printall(){ 92 | if (head == null){ 93 | System.out.print("no list"); 94 | } 95 | Node currNode= head; 96 | while (currNode != null){ 97 | System.out.print(currNode.data+"-->"); 98 | currNode =currNode.next; 99 | } 100 | System.out.print("nulll"); 101 | System.out.println(); 102 | } 103 | public void addFirst(String data){ 104 | Node newNode = new Node(data); 105 | //Node head = null; 106 | if (head == null){ 107 | head = newNode; 108 | return; 109 | } 110 | newNode.next= head; 111 | head = newNode; 112 | } 113 | class Node{ 114 | String data; 115 | Node next; 116 | Node(String data){ 117 | this.data = data; 118 | this.next = next; 119 | size++; 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /LL/README.md: -------------------------------------------------------------------------------- 1 | # Linked List Data Structure Algorithms 2 | Linked List is a linear data structure that includes a series of connected nodes. 3 | Linked List can be defined as the nodes that are randomly stored in the memory. 4 | A node in the linked list contains two parts, i.e., first is the data part and second is the address part. 5 | The last node of the list contains a pointer to the null. After array, linked list is the second most used data structure. 6 | In a Linked List, every link contains a connection to another link. 7 | 8 | ## Types of Linked Lists 9 | - Singly Linked List 10 | - Doubly Linked List 11 | - Circular Linked List 12 | - Circular Doubly Linked List 13 | 14 | ![](https://static.javatpoint.com/ds/images/ds-linked-list.png) 15 | 16 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 17 | 18 | ## References 19 | * 20 | * 21 | -------------------------------------------------------------------------------- /LL/circular_LL.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A circular linked list is a data structure in Java where the last node of the list points back to the first node, 4 | forming a closed loop or circle. Circular linked lists have some advantages, such as constant-time insertion, 5 | deletion at both the beginning and end of the list. They are useful for applications that require continuous looping, 6 | like managing tasks in a round-robin scheduling algorithm. 7 | 8 | Wikipedia : https://en.wikipedia.org/wiki/Linked_list#Circular_linked_list 9 | 10 | */ 11 | 12 | class Node { 13 | int data; 14 | Node next; 15 | public Node(int data) { 16 | this.data = data; 17 | this.next = null; 18 | } 19 | } 20 | 21 | class CircularLinkedList { 22 | Node head; 23 | public CircularLinkedList() { 24 | head = null; 25 | } 26 | 27 | // Add a new node to the end of the circular linked list 28 | public void append(int data) { 29 | Node newNode = new Node(data); 30 | if (head == null) { 31 | head = newNode; 32 | head.next = head; // Make it circular 33 | } else { 34 | Node current = head; 35 | while (current.next != head) { 36 | current = current.next; 37 | } 38 | current.next = newNode; 39 | newNode.next = head; // Make it circular 40 | } 41 | } 42 | 43 | // Display the circular linked list 44 | public void display() { 45 | if (head == null) { 46 | System.out.println("Circular Linked List is empty"); 47 | return; 48 | } 49 | Node current = head; 50 | do { 51 | System.out.print(current.data + " "); 52 | current = current.next; 53 | } while (current != head); 54 | System.out.println(); 55 | } 56 | } 57 | 58 | public class Main { 59 | public static void main(String[] args) { 60 | CircularLinkedList cll = new CircularLinkedList(); 61 | cll.append(1); 62 | cll.append(2); 63 | cll.append(3); 64 | cll.append(4); 65 | 66 | System.out.println("Circular Linked List:"); 67 | cll.display(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /LL/detect_remove_cycle_LL.java: -------------------------------------------------------------------------------- 1 | package LL; 2 | import LL.LL1.*; 3 | public class detect_remove_cycle_LL { 4 | private static Node head; 5 | public static void main(String[] args) { 6 | LL1 list = new LL1(); 7 | list.addFirst("1"); 8 | list.addLast("2"); 9 | list.addLast("3"); 10 | list.addLast("4"); 11 | list.addLast("5"); 12 | list.addLast("3"); 13 | list.printall(); 14 | list.head= detect_Node(list.head); 15 | list.printall(); 16 | } 17 | public void printall(){ 18 | if (head == null){ 19 | System.out.print("no list"); 20 | } 21 | Node currNode= head; 22 | while (currNode != null){ 23 | System.out.print(currNode.data+"-->"); 24 | currNode =currNode.next; 25 | } 26 | //System.out.print("nulll"); 27 | System.out.println(); 28 | } 29 | static Node detect(Node head){ 30 | Node slow = head; 31 | Node fast = head; 32 | while (fast != null && fast.next != null){ 33 | slow = slow.next; 34 | fast = fast.next.next; 35 | 36 | if (slow == fast){ 37 | System.out.println("detected"); 38 | return slow;} 39 | } 40 | return null; 41 | } 42 | static Node detect_Node(Node head){ 43 | Node meet = detect(head); 44 | System.out.println("after detect"); 45 | Node start = head; 46 | while(start != meet){ 47 | start = start.next; 48 | meet = meet.next; 49 | }return start; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /LL/doubly_circular_LL.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A doubly circular linked list in Java is a type of linked list where each node contains a data element and two references: 4 | one to the next node and another to the previous node. Unlike a singly linked list, where nodes only point to the next node, 5 | in a doubly circular linked list, the last node points back to the first node, creating a closed loop or circle. 6 | 7 | Javapoint : https://www.javatpoint.com/circular-doubly-linked-list# 8 | */ 9 | 10 | class Node { 11 | int data; 12 | Node next; 13 | Node prev; 14 | 15 | public Node(int data) { 16 | this.data = data; 17 | this.next = null; 18 | this.prev = null; 19 | } 20 | } 21 | 22 | class DoublyCircularLinkedList { 23 | private Node head; 24 | private Node tail; 25 | 26 | public DoublyCircularLinkedList() { 27 | head = null; 28 | tail = null; 29 | } 30 | 31 | // Check if the list is empty 32 | public boolean isEmpty() { 33 | return head == null; 34 | } 35 | 36 | // Add a node to the end of the list 37 | public void add(int data) { 38 | Node newNode = new Node(data); 39 | if (isEmpty()) { 40 | head = newNode; 41 | tail = newNode; 42 | } else { 43 | tail.next = newNode; 44 | newNode.prev = tail; 45 | tail = newNode; 46 | } 47 | tail.next = head; 48 | head.prev = tail; 49 | } 50 | 51 | // Display the list 52 | public void display() { 53 | if (isEmpty()) { 54 | System.out.println("The list is empty."); 55 | return; 56 | } 57 | Node current = head; 58 | do { 59 | System.out.print(current.data + " <-> "); 60 | current = current.next; 61 | } while (current != head); 62 | System.out.println(); 63 | } 64 | } 65 | 66 | public class Main { 67 | public static void main(String[] args) { 68 | DoublyCircularLinkedList list = new DoublyCircularLinkedList(); 69 | 70 | list.add(1); 71 | list.add(2); 72 | list.add(3); 73 | list.add(4); 74 | 75 | System.out.println("Doubly Circular Linked List:"); 76 | list.display(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /LL/palindrome_LL.java: -------------------------------------------------------------------------------- 1 | package LL; 2 | import LL.LL1.*; 3 | 4 | public class palindrome_LL { 5 | public static void main(String[] args) { 6 | LL1 list = new LL1(); 7 | list.addFirst("4"); 8 | list.addFirst("1"); 9 | list.addFirst("4"); 10 | System.out.println(palindrome(list.head)); 11 | list.printall(); 12 | } 13 | static Node middle(Node head){ 14 | Node slow = head; 15 | Node fast = head; 16 | while (fast != null && fast.next != null){ 17 | slow = slow.next; 18 | fast = fast.next.next; 19 | } 20 | return slow; 21 | } 22 | static boolean palindrome(Node head){ 23 | if (head == null) 24 | return true; 25 | Node mid = middle(head); 26 | Node last = LL1.reverse(mid.next); 27 | Node curr = head; 28 | while (last != null){ 29 | if (last.data != curr.data) 30 | return false; 31 | last = last.next; 32 | curr = curr.next; 33 | }return true; 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /LL/reverse_LinkedList.java: -------------------------------------------------------------------------------- 1 | package LL; 2 | 3 | public class reverse_LinkedList { 4 | private int size; 5 | class Node{ 6 | String data; 7 | Node next; 8 | Node(String data){ 9 | this.data = data; 10 | this.next = next; 11 | size++; 12 | } 13 | } 14 | Node reverse(Node head){ 15 | Node cur = head; 16 | Node prev = null; 17 | while(cur != null){ 18 | Node temp = cur.next; 19 | cur.next = prev; 20 | prev = cur; 21 | cur = temp; 22 | } 23 | return prev; 24 | } 25 | public boolean isPalindrome(Node head) { 26 | if(head == null && head.next == null) 27 | return true; 28 | 29 | Node mid = middle(head); 30 | Node last = reverse(mid); 31 | Node curr = head; 32 | while( last != null){ 33 | if(last.data != curr.data) 34 | { return false;} 35 | else{last = last.next; 36 | curr = curr.next;} 37 | }return true; 38 | 39 | } 40 | public Node reverseRecursion(Node head){ 41 | if(head == null || head.next == null) 42 | return head; 43 | Node newHead = reverse(head.next); 44 | head.next.next = head; 45 | head.next = null; 46 | return newHead; 47 | } 48 | public Node middle(Node head){ 49 | Node fast = head; 50 | Node slow = head; 51 | while(fast != null && fast.next != null){ 52 | 53 | slow = slow.next; 54 | fast = fast.next.next; 55 | } 56 | return slow; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Leetcode/AllCombinations.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.*; 6 | 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | 9 | /* 10 | This class generates all possible combinations of length k from a set of integers 1 to n. 11 | */ 12 | public class AllCombinations { 13 | 14 | /** 15 | Generates all possible combinations of k numbers out of 1...n. 16 | @param n The maximum number to consider for the combinations. 17 | @param k The size of each combination. 18 | @return A list of all possible combinations of k numbers out of 1....n. 19 | */ 20 | public static List> generateCombinations(int n, int k) { 21 | List> result = new ArrayList<>(); 22 | backtrack(result, new ArrayList<>(), 1, n, k); 23 | return result; 24 | } 25 | 26 | /** 27 | 28 | Helper method to generate all possible combinations of k numbers out of 1....n. 29 | @param result A list to store all the generated combinations. 30 | @param temp A temporary list to store each combination during the recursive process. 31 | @param start The starting number to consider for the current combination. 32 | @param n The maximum number to consider for the combinations. 33 | @param k The size of each combination. 34 | */ 35 | private static void backtrack(List> result, List temp, int start, int n, int k) { 36 | if (temp.size() == k) { 37 | result.add(new ArrayList<>(temp)); 38 | return; 39 | } 40 | for (int i = start; i <= n; i++) { 41 | temp.add(i); 42 | backtrack(result, temp, i + 1, n, k); 43 | temp.remove(temp.size() - 1); 44 | } 45 | } 46 | @Test 47 | public void testGenerateCombinations() { 48 | List> expected = List.of( 49 | List.of(1, 2, 3), 50 | List.of(1, 2, 4), 51 | List.of(1, 2, 5), 52 | List.of(1, 3, 4), 53 | List.of(1, 3, 5), 54 | List.of(1, 4, 5), 55 | List.of(2, 3, 4), 56 | List.of(2, 3, 5), 57 | List.of(2, 4, 5), 58 | List.of(3, 4, 5) 59 | ); 60 | List> actual = AllCombinations.generateCombinations(5, 3); 61 | assertEquals(expected, actual); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Leetcode/Flatten_multilevelArray.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Queue; 5 | 6 | public class Flatten_multilevelArray { 7 | // public static void main(String[] args) { 8 | 9 | // } 10 | static class Node { 11 | public int val; 12 | public Node prev; 13 | public Node next; 14 | public Node child; 15 | Node(){ 16 | this.val = val; 17 | this.next = next; 18 | this.prev = prev; 19 | this.child = child; 20 | } 21 | }; 22 | public Node flatten(Node head) { 23 | Node curr = head; 24 | Queue q = new ArrayDeque<>(); 25 | while (head != null){ 26 | if (head.child != null){ 27 | if (head.next != null)q.add(head.next); 28 | head.next = head.child; 29 | head.next.prev = head; 30 | head.child = null; 31 | } else if (head.next == null && !q.isEmpty()) { 32 | head.next = q.remove(); 33 | head.next.prev = head; 34 | } 35 | head = head.next; 36 | } 37 | return curr; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode/IntersectionOfArray.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | 4 | import java.util.HashSet; 5 | 6 | public class IntersectionOfArray { 7 | 8 | // This method takes two integer arrays, 'a' and 'b', as input and finds the count of common elements. 9 | // It uses a HashSet to keep track of elements in array 'a' and uses it to compare with elements in array 'b'. 10 | public static int intersection(int[] a, int[] b) { 11 | HashSet set = new HashSet<>(); 12 | int count = 0; 13 | for (int i = 0; i < a.length; i++) { 14 | set.add(a[i]); 15 | } 16 | 17 | for (int j = 0; j < b.length; j++) { 18 | if (set.contains(b[j])) { 19 | count++; 20 | set.remove(b[j]); 21 | } 22 | } 23 | return count; // give count of common elements 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Leetcode/Kadane_algo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * maximum continuos sub-array 3 | * */ 4 | public class Kadane_algo { 5 | public static void main(String[] args) { 6 | int a[] = {-3,4,-1,-2,1,5,-3}; 7 | int b[] = {1,2,3,-2,5}; 8 | System.out.print(kadane(b)); 9 | } 10 | static int max_sum=0; 11 | static int cur_sum=0; 12 | static int kadane(int[] a){ 13 | for (int i = 0; i < a.length ; i++) { 14 | cur_sum = cur_sum + a[i]; 15 | 16 | if (cur_sum > max_sum) 17 | { 18 | max_sum = cur_sum; 19 | } 20 | if (cur_sum < 0){ 21 | cur_sum=0; 22 | } 23 | } 24 | return max_sum; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Leetcode/Palindrome_fixedLength.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | public class Palindrome_fixedLength { 4 | public static void main(String[] args) { 5 | int[] queries = {1,2,3,4,5,90};int intLength = 3; 6 | System.out.println(palindrome(1222222221)); 7 | System.out.println(kthPalindrome(queries,intLength)); 8 | } 9 | public static long[] kthPalindrome(int[] queries, int intLength) { 10 | long[] ans = new long[queries.length]; 11 | int m = 0,n=0; 12 | for(long i =(long) Math.pow(10,intLength) ; i <=(long)(Math.pow(10,intLength+1)-1);i++){ 13 | //System.out.println("sdfghj"); 14 | if(n < queries.length && i == queries[n] && palindrome(i)==true){ 15 | ans[m] = i; 16 | System.out.println(i); 17 | m++; 18 | }n++; 19 | }return ans; 20 | } 21 | public static boolean palindrome(long x){ 22 | long temp = x; 23 | long ans = 0; 24 | while(x > 0){ 25 | long a = x % 10; 26 | ans = (ans * 10) + a; 27 | x = x/10; 28 | } 29 | 30 | return (ans == temp ? true : false); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Leetcode/Queue_using_twostacks.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.Stack; 4 | 5 | public class Queue_using_twostacks { 6 | public static void main(String[] args) { 7 | MyQueue m = new MyQueue(); 8 | m.pushQ(1); 9 | m.pushQ(2); 10 | m.pushQ(3); 11 | m.popQ(); 12 | 13 | 14 | 15 | 16 | } 17 | public static class MyQueue { 18 | static Stack st1 = new Stack<>(); 19 | static Stack st2 = new Stack<>(); 20 | 21 | static void pushQ(int data) { 22 | st1.push(data); 23 | System.out.println(data); 24 | } 25 | 26 | 27 | static int popQ() { 28 | while (!st1.isEmpty()) { 29 | st2.push(st1.pop()); 30 | } 31 | int ans = st2.pop(); 32 | while (!st2.isEmpty()) { 33 | st1.push(st2.pop()); 34 | } 35 | System.out.println(ans + " deleted"); 36 | return ans; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Leetcode/SlidingWindowMaximum_Array.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | public class SlidingWindowMaximum_Array { 4 | public static void main(String[] args) { 5 | int[] a ={1,3,-1,-3,5,3,6,7}; 6 | int k = 3; 7 | System.out.println(SlidingWindowMax(a,a.length,k)); 8 | } 9 | 10 | public static int[] SlidingWindowMax(int[] a,int n,int k){ 11 | int max; 12 | int[] ans = new int[a.length - k + 1]; 13 | for (int i = 0; i < n-k+1 ; i++) { 14 | max = a[i]; 15 | for (int j = 1; j < k; j++) { 16 | if(a[i+j] > max) 17 | max = a[i+j]; 18 | } 19 | ans[i] = max; 20 | System.out.println("m " +max); 21 | System.out.println("n "+ans[i]); 22 | } 23 | return ans; 24 | } 25 | } 26 | /* int n = nums.length; 27 | if (n == 0 || k == 0) { 28 | return new int[0]; 29 | } 30 | 31 | int numOfWindow = n - k + 1; 32 | int[] result = new int[numOfWindow]; // number of windows 33 | 34 | for (int start = 0; start < numOfWindow; ++start) { 35 | int end = start + k - 1; 36 | int maxVal = nums[start]; 37 | for (int i = start + 1; i <= end; ++i) { 38 | if (nums[i] > maxVal) { // update 39 | maxVal = nums[i]; 40 | } 41 | } 42 | result[start] = maxVal; 43 | } 44 | 45 | return result;*/ -------------------------------------------------------------------------------- /Leetcode/Stack_using_twoQueue.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Queue; 5 | 6 | public class Stack_using_twoQueue { 7 | public static void main(String[] args) { 8 | MyStack m = new MyStack(); 9 | m.pushS(1); 10 | m.pushS(2); 11 | m.pushS(3); 12 | m.popS(); 13 | 14 | 15 | } 16 | 17 | public static class MyStack{ 18 | static Queue q1 = new ArrayDeque<>(); 19 | static Queue q2 = new ArrayDeque<>(); 20 | static void pushS(int data){ 21 | while (!q1.isEmpty()){ 22 | q2.add(q1.remove()); 23 | } 24 | q1.add(data); 25 | System.out.println(data); 26 | while (!q2.isEmpty()){ 27 | q1.add(q2.remove()); 28 | } 29 | } 30 | static void popS(){ 31 | System.out.println(q1.remove()+ " deleted"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Leetcode/SudokuSolver.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class SudokuSolver { 7 | public boolean isValidSudoku(char[][] board) { 8 | Set seen = new HashSet(); 9 | for (int i=0; i<9; ++i) { 10 | for (int j=0; j<9; ++j) { 11 | char number = board[i][j]; 12 | if (number != '.') 13 | if (!seen.add(number + " in row " + i) || 14 | !seen.add(number + " in column " + j) || 15 | !seen.add(number + " in block " + i/3 + "-" + j/3)) 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | } 22 | // alternative is there in below but not getting answers 23 | // class Solution { 24 | // public boolean isSafe(char[][] board, int row, int col, int number){ 25 | // //row & column 26 | // for(int i=0;i> threeSum(int[] nums) { 10 | Arrays.sort(nums); 11 | List> res = new ArrayList<>(); 12 | 13 | for(int i = 0; i < nums.length-2; i++){ 14 | if(i ==0 || (i>0 && nums[i]!=nums[i-1])){ 15 | int low = i+1; 16 | int high = nums.length-1; 17 | int sum = 0-nums[i]; 18 | 19 | while(low < high){ 20 | if(nums[low] + nums[high] == sum){ 21 | res.add(Arrays.asList(nums[i],nums[low],nums[high])); 22 | while(low < high && nums[low] == nums[low+1]) low++; 23 | while(low < high && nums[high]== nums[high-1]) high--; 24 | low++; 25 | high--; 26 | } else if (nums[low] + nums[high] > sum){ 27 | high--; 28 | } else { 29 | low++; 30 | } 31 | } 32 | } 33 | } 34 | return res; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Leetcode/Tiles_placement.java: -------------------------------------------------------------------------------- 1 | public class Tiles_placement { 2 | public static void main(String[] args) { 3 | System.out.println(tilesPlacement(2,2)); 4 | } 5 | public static int tilesPlacement(int n,int m){ 6 | if(n==m) return 2; 7 | if(n= 0; i-- ) { 20 | right[i] = Math.max(right[i+1],a[i]); 21 | } 22 | 23 | for (int i = 0; i < n; i++) { 24 | ans+= Math.min(left[i],right[i]) - a[i]; 25 | } 26 | return ans; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Leetcode/TwoSum.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | public class TwoSum { 4 | 5 | // public static int[] twosum(int a[], int target){ 6 | // int[] res = new int[7]; 7 | // for (int i = 0; i < a.length; i++) { 8 | // for (int j = i+1; j < a.length; j++) { 9 | // if(a[i]+a[j] == target) 10 | // { 11 | // System.out.println(new int[]{i,j}); 12 | // return new int[]{i,j};} 13 | // } 14 | // } 15 | // 16 | // throw new IllegalArgumentException("no"); 17 | // } 18 | public static int[] twoSum(int[] nums, int target) { 19 | 20 | for (int i = 0; i < nums.length; i++) { 21 | for (int j = i+1; j < nums.length; j++) { 22 | int comp = target - nums[i]; 23 | 24 | if(comp == nums[j]){ 25 | return new int[]{i,j}; 26 | // if(nums[i]+nums[j] == target) return new int[]{i,j}; 27 | } 28 | } 29 | } 30 | throw new IllegalArgumentException("no"); 31 | 32 | } 33 | public static void main(String[] args) { 34 | int[] nums = {2,7,5,1,1}; 35 | twoSum(nums,9); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Leetcode/birthday_celevratuions.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Stack; 5 | 6 | public class birthday_celevratuions { 7 | public static void main(String[] args) { 8 | int a[]={4,8,2,8,9}; 9 | System.out.println(birthday(a)); 10 | 11 | } 12 | 13 | static int birthday(int a[]){ 14 | int count=0; 15 | //ArrayList b = new ArrayList<>(); 16 | Stack stack = new Stack<>(); 17 | for (int i = 0; i < a.length; i++) { 18 | if (!stack.contains(a[i])){ 19 | stack.add(a[i]); 20 | count++; 21 | } 22 | else { 23 | if (stack.contains(a[i])) 24 | { 25 | count--; 26 | } 27 | } 28 | } 29 | 30 | 31 | return count; 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Leetcode/moving_avg_fromDataStream.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class moving_avg_fromDataStream { 7 | public static void main(String[] args) { 8 | moving_avg_fromDataStream obj = new moving_avg_fromDataStream(3); 9 | double m = obj.next(4); 10 | double n = obj.next(4); 11 | double w = obj.next(4);double y = obj.next(0); 12 | 13 | } 14 | private static Queue queue; 15 | private static int maxsize; 16 | private static double sum; 17 | public moving_avg_fromDataStream(int size){ 18 | queue = new LinkedList<>(); 19 | maxsize = size; 20 | sum = 0; 21 | } 22 | public static double next(int val){ 23 | if (queue.size() == maxsize){ 24 | sum -= queue.remove(); 25 | } 26 | queue.add(val); 27 | sum += val; 28 | System.out.println(sum/queue.size()); 29 | return sum/queue.size(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Leetcode/stock2_buySell.java: -------------------------------------------------------------------------------- 1 | public class stock2_buySell { 2 | public static void main(String[] args) { 3 | int b[] = {5,2,7,3,6,1,2,4}; 4 | System.out.println(stock(b)); 5 | } 6 | static int max_profit=0; 7 | static int final_profit=0; 8 | static int stock(int a[]){ 9 | for (int i = 1; i < a.length; i++) { 10 | if( a[i] > a[i-1]){ 11 | max_profit= a[i] - a[i-1]; 12 | final_profit = final_profit + max_profit; 13 | } 14 | } 15 | return final_profit; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Leetcode/stock_buySell.java: -------------------------------------------------------------------------------- 1 | public class stock_buySell { 2 | public static void main(String[] args) { 3 | int a[] = {3,1,4,8,9,2,5}; 4 | System.out.println(); 5 | System.out.print(stocks(a)); 6 | } 7 | //static int max_profit=0; 8 | //static int min_soFar=0; 9 | static int stocks(int a[]){ 10 | int max_profit=0; 11 | int min_soFar=a[0]; 12 | for (int i = 0; i < a.length; i++) { 13 | min_soFar = Math.min(min_soFar,a[i]); 14 | int profit = a[i] - min_soFar; 15 | max_profit = Math.max(max_profit,profit); 16 | } 17 | return max_profit; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Leetcode/stringsandPaswords.java: -------------------------------------------------------------------------------- 1 | package Leetcode; 2 | 3 | import java.util.HashMap; 4 | 5 | 6 | public class stringsandPaswords { 7 | public static void main(String[] args) { 8 | String a = "password"; 9 | String b = "pss$w#rd"; 10 | String c= "abc123"; 11 | String d = "$abc&123"; 12 | System.out.println(defstring(a,b)); 13 | } 14 | 15 | static int defstring(String oldpass , String newpass){ 16 | int count=0,m=0; 17 | HashMap map = new HashMap<>(); 18 | if (oldpass.length()==newpass.length()){ 19 | for (int i = 0;i < newpass.length();i++){ 20 | char ch = oldpass.charAt(i); 21 | map.put(ch , map.getOrDefault(ch,0) ); 22 | } 23 | 24 | for (char c : map.keySet() ) { 25 | int i =0; 26 | if (newpass.charAt(i)==c) { 27 | i++; 28 | continue; 29 | } 30 | else { 31 | count++; 32 | i++; 33 | } 34 | } 35 | }else { 36 | return newpass.length()-oldpass.length(); 37 | } 38 | 39 | 40 | return count*2; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /MathsforDSA/SieveofEratosthenes.java: -------------------------------------------------------------------------------- 1 | /* Description: 2 | The Sieve of Eratosthenes is a method to find all prime numbers up to a given limit 3 | Make a list of numbers from 2 to your limit. 4 | Start with the first number (2) and mark it as prime. 5 | Cross out all multiples of 2 in the list. 6 | Move to the next unmarked number (3) and mark it as prime. 7 | Cross out all multiples of 3 in the list. 8 | Repeat steps 4 and 5 until you've checked numbers up to the square root of the limit. 9 | The remaining unmarked numbers are all prime. 10 | For example, if you want to find primes up to 30, you'll get: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. It's an efficient way to find prime numbers. 11 | Want to know more here is the wikipedia link https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes */ 12 | // Time complexity is O(n) how? check it out https://www.geeksforgeeks.org/how-is-the-time-complexity-of-sieve-of-eratosthenes-is-nloglogn/ 13 | // and Space complexity is O(n). 14 | public class SieveOfEranthatosis { 15 | public static void main(String[] args) { 16 | int n = 40; 17 | boolean[] arr = new boolean[n+1]; 18 | sieve(n, arr); 19 | } 20 | // false is prime and true is non prime 21 | static void sieve(int n, boolean[] prime) { 22 | for (int i = 2; i*i <=n ; i++) { 23 | if (!prime[i]){ 24 | for (int j =i*2 ; j <=n; j+=i) { 25 | prime[j] = true; 26 | } 27 | } 28 | } 29 | for (int i = 2; i < prime.length ; i++) { 30 | if (!prime[i]){ 31 | System.out.println(i); 32 | } 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /MathsforDSA/factorial.java: -------------------------------------------------------------------------------- 1 | // More on Factorial : https://en.wikipedia.org/wiki/Factorial 2 | 3 | public class factorial { 4 | 5 | // Driver Code 6 | public static void main(String[] args) { 7 | tests(); // Call the tests method to run factorial tests 8 | } 9 | 10 | //Test Cases 11 | //More on Assert : https://www.geeksforgeeks.org/assertions-in-java/ 12 | public static void tests() { 13 | assert fact(1) == 1; 14 | assert fact(5) == 120; 15 | assert fact(0) == 1; 16 | assert fact ("asg") == 0; 17 | System.out.println("Successfully Passed Test Cases!"); // Successfull Message print 18 | } 19 | 20 | //Recursive method to calculate Factorial 21 | public static int fact(int n) { 22 | if(Character.isDigit(n) == false) 23 | return 0; 24 | if(n == 0)return 1; 25 | return n * fact(n-1); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /MathsforDSA/fibonacci.java: -------------------------------------------------------------------------------- 1 | // More on Fibonacci Series : https://en.wikipedia.org/wiki/Fibonacci_sequence 2 | // This class calculates Fibonacci numbers using an iterative approach. 3 | public class fibonacci{ 4 | 5 | public static int fibonacci_sequence(int n) { 6 | 7 | int num1 = 0, num2 = 1, count = 0; 8 | if (n <= 1) { 9 | return n; 10 | } 11 | // Calculate the Fibonacci number iteratively 12 | while(count> res = new ArrayList<>(); 14 | if(nums.length == 0 || nums == null) return count; 15 | Arrays.sort(nums); 16 | boolean[] used = new boolean[nums.length]; 17 | List permutations = new ArrayList<>(); 18 | helper(permutations,nums,used,-1); 19 | return count; 20 | } 21 | private static boolean isSquare(int a, int b){ 22 | double res = Math.sqrt(a+b); 23 | boolean finalres = (res - Math.floor(res)) == 0; 24 | return finalres; 25 | } 26 | private static void helper(List temp, int[] nums, boolean[] used, int lastNumb) { 27 | if (temp.size() == nums.length) count++; 28 | else { 29 | for (int i = 0; i < nums.length; i++) { 30 | if(used[i]) continue; 31 | if(lastNumb!=-1){ 32 | if (isSquare(nums[i],lastNumb)==false) 33 | continue; 34 | } 35 | used[i] = true; 36 | temp.add(nums[i]); 37 | helper(temp,nums,used,lastNumb); 38 | temp.remove(temp.size()-1); 39 | used[i] = false; 40 | while(i+1> permutunique(int[] nums){ 11 | List> res = new ArrayList<>(); 12 | if(nums.length == 0 || nums == null) 13 | return res; 14 | Arrays.sort(nums); 15 | boolean[] used = new boolean[nums.length]; 16 | List permutations = new ArrayList<>(); 17 | helper(nums,permutations,used,res); 18 | return res; 19 | } 20 | public static void helper(int[] nums, List permutations, boolean[] used,List> res){ 21 | if(permutations.size() == nums.length){ 22 | res.add(new ArrayList<>(permutations)); 23 | return; 24 | }else { 25 | for (int i = 0; i < nums.length; i++) { 26 | if (used[i]) continue; 27 | used[i] = true; 28 | permutations.add(nums[i]); 29 | helper(nums,permutations,used,res); 30 | permutations.remove(permutations.size() - 1); 31 | used[i] = false; 32 | while(i+1> subsets(int[] nums) { 21 | List> result = new ArrayList<>(); 22 | result.add(new ArrayList<>()); 23 | for(int n : nums){ 24 | int size = result.size(); 25 | for(int i=0; i subset = new ArrayList<>(result.get(i)); 27 | subset.add(n); 28 | result.add(subset); 29 | } 30 | } 31 | return result; 32 | } 33 | */ -------------------------------------------------------------------------------- /Priority_Queue/Kth_largest_element.java: -------------------------------------------------------------------------------- 1 | package Priority_Queue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class Kth_largest_element { 6 | public static void main(String[] args) { 7 | int a[] = {3,2,4,5,61,12}; 8 | 9 | System.out.println(largest(a,3)); 10 | } 11 | public static int largest(int a[],int k){ 12 | PriorityQueue pq = new PriorityQueue<>(); 13 | for (int i = 0; i < k; i++) { 14 | pq.add(a[i]); 15 | } 16 | for (int i = k; i < a.length; i++) { 17 | if (pq.peek() < a[i]){ 18 | pq.remove(); 19 | pq.add(a[i]); 20 | } 21 | } 22 | return pq.peek(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Priority_Queue/connect_N_ropes.java: -------------------------------------------------------------------------------- 1 | package Priority_Queue; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class connect_N_ropes { 6 | public static void main(String[] args) { 7 | int a[] = {2,5,4,8,6,9}; 8 | System.out.println(minCost(a)); 9 | } 10 | public static int minCost(int a[]){ 11 | PriorityQueue pq = new PriorityQueue<>(); 12 | for (int i = 0; i < a.length; i++) { 13 | pq.add(a[i]); 14 | } 15 | int ans = 0; 16 | while(pq.size() > 1){ 17 | int first = pq.poll(); 18 | int second = pq.poll(); 19 | int sum = 0; 20 | sum = first + second; 21 | ans = ans + sum; 22 | } 23 | return ans; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Queue/CircularArrayQueue.java: -------------------------------------------------------------------------------- 1 | package Queue; 2 | 3 | public class CircularArrayQueue { 4 | public static void main(String[] args) { 5 | 6 | } 7 | private static int[] a; 8 | private static int n; 9 | private static int front = -1,rear = -1; 10 | public CircularArrayQueue(int n){ 11 | this.n = n; 12 | a = new int[n]; 13 | } 14 | static void enqueue(int data){ 15 | if ((rear+1)%n == front) // checking queue is full 16 | return; 17 | if (front == -1){ 18 | front = 0; 19 | rear = (rear+1)%n; // using to increment by 1 , make 0 from -1 , so on... 20 | a[rear] = data; 21 | } 22 | } 23 | static int dequeue() throws Exception{ 24 | if (front == -1) // checking queue is empty 25 | throw new Exception(); 26 | int result = a[front]; 27 | if (front == rear) // only one element is present 28 | front = rear = -1; // making them pointing at one element only 29 | else 30 | front = (front+1)%n; // use to increment by 1 , here front is increased by 1 . 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Queue/QueueUsingStacks.java: -------------------------------------------------------------------------------- 1 | package Queue; 2 | 3 | import java.util.Stack; 4 | 5 | public class QueueUsingStacks { 6 | public static void main(String[] args) { 7 | 8 | } 9 | private Stack first; 10 | private Stack second; 11 | public QueueUsingStacks(){ 12 | first = new Stack<>(); 13 | second = new Stack<>(); 14 | } 15 | public void add(int item){ 16 | first.push(item); 17 | } 18 | public int remove(){ 19 | while (!first.isEmpty()){ 20 | second.push(first.pop()); 21 | } 22 | int removed = second.pop(); 23 | 24 | while (!second.isEmpty()){ 25 | first.push(second.pop()); 26 | } 27 | return removed; 28 | } 29 | 30 | public boolean isEmpty(){ 31 | return first.isEmpty(); 32 | } 33 | 34 | public void efficientAdd(int item) throws Exception{ 35 | while (!first.isEmpty()){ 36 | second.push(first.pop()); 37 | } 38 | first.push(item); 39 | while(!second.isEmpty()) 40 | first.push(second.pop()); 41 | } 42 | public int efficientPeek() throws Exception{ 43 | return first.peek(); 44 | } 45 | public int peek() throws Exception{ 46 | while (!first.isEmpty()){ 47 | second.push(first.pop()); 48 | } 49 | int peek = second.peek(); 50 | 51 | while (!second.isEmpty()){ 52 | first.push(second.pop()); 53 | } 54 | return peek; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Queue/Queue_byArray.java: -------------------------------------------------------------------------------- 1 | package Queue; 2 | 3 | public class Queue_byArray { 4 | int a[]; 5 | int capacity; 6 | int rear; 7 | public Queue_byArray(int n){ 8 | capacity = n; 9 | a = new int[n]; 10 | rear = -1; 11 | } 12 | void enqueue(int data) throws Exception { 13 | if (rear == capacity-1)//overflow 14 | { 15 | throw new Exception(); 16 | } 17 | rear++; 18 | a[rear] = data; 19 | } 20 | int dequeue() throws Exception { 21 | if (rear == -1) //empty 22 | { 23 | throw new Exception(); 24 | } 25 | int result = a[0]; 26 | for (int i = 0; i < rear ; i++) { 27 | a[i] = a[i+1]; 28 | } 29 | rear--; 30 | return result; 31 | } 32 | int getFront() throws Exception { 33 | if (rear == -1)//empty 34 | { 35 | throw new Exception(); 36 | } 37 | return a[0]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Queue/Queue_byCircularArray.java: -------------------------------------------------------------------------------- 1 | public class Queue_byCircularArray { 2 | static class Queue{ 3 | static int arr[]; 4 | static int size; 5 | static int rear = -1; 6 | static int front = -1; 7 | Queue(int n){ 8 | arr = new int[n]; 9 | this.size = n; 10 | } 11 | public static boolean isEmpty(){ 12 | return rear == -1 && front == -1; 13 | } 14 | public static boolean isFull(){ 15 | return (rear+1)%size == front; 16 | } 17 | public static void add(int data){ 18 | if(isFull()){ 19 | System.out.println("full queue"); 20 | return; 21 | } 22 | // for adding very first element 23 | if(front == -1) 24 | front = 0; 25 | 26 | rear = (rear+1)%size; 27 | arr[rear] = data; 28 | } 29 | public static int remove(){ 30 | if (isEmpty()){ 31 | System.out.println("empty queue"); 32 | return -1; 33 | } 34 | int result = arr[front]; 35 | // single element condition 36 | if(rear == front) {rear=front=-1;} 37 | else {front = (front+1)%size;} 38 | 39 | return result; 40 | } 41 | public static int peek(){ 42 | if(isEmpty()){ 43 | System.out.println("empty queue"); 44 | return -1; 45 | } 46 | return arr[front]; 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | Queue q = new Queue(5); 52 | q.add(0); 53 | q.add(1); 54 | q.add(2); 55 | q.add(3); 56 | //q.remove(); 57 | while(!q.isEmpty()){ 58 | System.out.println(q.peek()); 59 | q.remove(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Queue/Queue_byTwoStacks.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Queue_byTwoStacks { 4 | public static class Queue_stack{ 5 | static Stack s1 = new Stack<>(); 6 | static Stack s2 = new Stack<>(); 7 | 8 | public static boolean isEmpty(){ 9 | return s1.isEmpty(); 10 | } 11 | public static void add(int data){ 12 | while(!s1.isEmpty()){ 13 | s2.push(s1.pop()); 14 | } 15 | s1.push(data); 16 | 17 | while(!s2.isEmpty()){ 18 | s1.push(s2.pop()); 19 | } 20 | } 21 | public static int remove(){ 22 | if(isEmpty()){ 23 | System.out.println("empty queue"); 24 | return -1; 25 | } 26 | return s1.pop(); 27 | } 28 | public static int peek(){ 29 | if(isEmpty()){ 30 | System.out.println("empty queue"); 31 | return -1; 32 | } 33 | return s1.peek(); 34 | } 35 | } 36 | public static void main(String[] args) { 37 | Queue_stack q = new Queue_stack(); 38 | q.add(1); 39 | q.add(2); 40 | q.add(3); 41 | q.add(4); 42 | while(!q.isEmpty()){ 43 | System.out.println(q.peek()); 44 | q.remove(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Queue/Queue_withArray.java: -------------------------------------------------------------------------------- 1 | public class Queue_withArray { 2 | static class Queue{ 3 | static int arr[]; 4 | static int size; 5 | static int rear = -1; 6 | 7 | Queue(int n){ 8 | arr = new int[n]; 9 | this.size = n; 10 | } 11 | public static boolean isEmpty(){ 12 | return rear == -1; 13 | } 14 | 15 | //enqueue 16 | public static void add(int data){ 17 | if(rear == size-1){ 18 | System.out.println("full queue"); 19 | return; 20 | } 21 | rear++; 22 | arr[rear] = data; 23 | } 24 | public static int remove(){ 25 | if(isEmpty()){ 26 | System.out.println("empty queue"); 27 | return -1; 28 | } 29 | int front = arr[0]; 30 | for (int i = 0; i < rear; i++) { 31 | arr[i] = arr[i+1]; 32 | } 33 | rear--; 34 | return front; 35 | } 36 | public static int peek(){ 37 | if(isEmpty()){ 38 | System.out.println("empty queue"); 39 | return -1; 40 | } 41 | return arr[0]; 42 | } 43 | 44 | } 45 | 46 | public static void main(String[] args) { 47 | Queue q = new Queue(5); 48 | q.add(1); 49 | q.add(2); 50 | q.add(3); 51 | q.add(4); 52 | q.remove(); // to remove 1 53 | while(!q.isEmpty()){ 54 | System.out.println(q.peek()); 55 | q.remove(); 56 | } 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Queue/README.md: -------------------------------------------------------------------------------- 1 | # Queue Data Structure 2 | 3 | A queue is another kind of linear data structure that is used to store elements, 4 | just like any other data structure but in a particular manner. 5 | In simple words, we can say that the queue is a type of data structure in the Java programming language that stores elements of the same kind. 6 | The components in a queue are stored in a FIFO (First In, First Out) behavior. 7 | There are two ends in the queue collection, i.e., front & rear. Queue has two ends that is front and rear. 8 | 9 | ![](https://static.javatpoint.com/core/images/java-queue.png) 10 | 11 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 12 | 13 | ## Types Of Queues 14 | * Input Restricted Queue (this is a Simple Queue) 15 | * Output Restricted Queue (this is also a Simple Queue) 16 | * Circular Queue 17 | * Double Ended Queue (Deque) 18 | * Priority Queue 19 | - Ascending Priority Queue 20 | - Descending Priority Queue 21 | 22 | ## Reference 23 | * 24 | * 25 | -------------------------------------------------------------------------------- /Queue/queue_byLinkedlist.java: -------------------------------------------------------------------------------- 1 | public class Queue_byLinkedList { 2 | static class Node{ 3 | int data; 4 | Node next; 5 | Node(int data){ 6 | this.data = data; 7 | next = null; 8 | } 9 | } 10 | static class Queue{ 11 | static Node head = null; 12 | static Node tail = null; 13 | 14 | public static boolean isEmpty(){ 15 | return head == null && tail == null; 16 | } 17 | public static void add(int data){ 18 | Node newNode = new Node(data); 19 | if(tail == null) { 20 | tail=head=newNode; 21 | return; 22 | } 23 | tail.next = newNode; 24 | tail = newNode; // assigning newNode as value to tail 25 | } 26 | public static int remove(){ 27 | if (isEmpty()){ 28 | System.out.println("empty queue"); 29 | return -1; 30 | } 31 | int front = head.data; 32 | if(head == tail) tail = null; 33 | 34 | head = head.next; 35 | return front; 36 | } 37 | public static int peek(){ 38 | if (isEmpty()){ 39 | System.out.println("empty queue"); 40 | return -1; 41 | } 42 | return head.data; 43 | } 44 | } 45 | public static void main(String[] args) { 46 | Queue q = new Queue(); 47 | q.add(0); 48 | q.add(1); 49 | q.add(2); 50 | q.add(3); 51 | //q.remove(); 52 | while(!q.isEmpty()){ 53 | System.out.println(q.peek()); 54 | q.remove(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms in Java 2 | 3 | This is a collection of my implementations of various Data Structures and Algorithms in Java. These implementations are intended to help us learn and practice the concepts of Data Structures and Algorithms. 4 | 5 |
6 | 7 |
8 | 9 | ## Table of Contents 10 | 11 | 1. [Data Structures](#datastructure) 12 | 2. [Algorithms](#algo) 13 | 3. [Usage](#usage) 14 | 4. [Contributing](#contributing) 15 | 16 | 17 | 18 | ## Data Structures 19 | 20 | The following data structures are currently implemented in this repo: 21 | 22 | - Array 23 | - ArrayList 24 | - Sorting 25 | - String 26 | - Linked List 27 | - Stack 28 | - Threads 29 | - Queue 30 | - Priority Queue 31 | - Heap 32 | - Hash Map 33 | - Tree 34 | - Binary Search Tree 35 | - Graph 36 | 37 | 38 | 39 | 40 | 41 | Each data structure has its own folder containing its implementation, along with relevant tests.
42 | This repository also includes important LeetCode problems and mathematical content that is beneficial for understanding data structures and algorithms. 43 | 44 | 45 | 46 | 47 | ## Algorithms 48 | 49 | The following algorithms are currently implemented in this repo: 50 | 51 | ### Sorting Algorithms: 52 | 53 | - Bubble Sort 54 | - Selection Sort 55 | - Insertion Sort 56 | - Merge Sort 57 | - Quick Sort 58 | - Searching Algorithms: 59 | - Linear Search 60 | - Binary Search 61 | 62 | Each algorithm has its own folder containing its implementation, along with relevant tests. 63 | 64 | 65 | 66 | ## Usage 67 | 68 | To use any of the implementations, clone this repo and import the relevant Java files into your project. Each implementation is self-contained in a single Java file, so it should be easy to use. 69 | 70 | To run the tests for any implementation, navigate to its folder and run the relevant test file. For example, to run the tests for the Linked List implementation, navigate to the "linked-list" folder and run the "LinkedListTest.java" file. 71 | 72 | 73 | 74 | ## Contributing 75 | 76 | I welcome contributions to this repo! If you find a bug or have an improvement to suggest, please feel free to open an issue or submit a pull request. 77 | -------------------------------------------------------------------------------- /Reflection-API/README.md: -------------------------------------------------------------------------------- 1 | Hello everyone! You might be familiar with the terms “setters” and “getters”. If you’ve ever used an IDE, it’s easy to generate these methods for a data member by simply right-clicking and selecting the “generate” option. However, have you ever wondered how this process actually works? What’s the magic behind the scenes that allows us to avoid writing repetitive code for each member’s setter and getter? In this document, we’ll create our own setter and getter generator using the Java programming language. 2 | 3 | 4 | Note:- You will need to have prior knowledge of file handling in Java and a basic understanding of how to take input as command-line arguments. 5 | 6 | You can ask the user whether they want to generate a constructor for the class or not. 7 | 8 | We will use the power of reflection. Reflection is a mechanism in Java that allows you to inspect and manipulate classes, methods, fields, and other elements of the language’s type system at runtime. 9 | 10 | # How to compile and run? 11 | 12 | ## For compilation:- 13 | `javac SetterGetterGenerator.java` 14 | 15 | ## For execution:- 16 | `java SetterGetterGenerator class_name` OR `java SetterGetterGenerator class_name “constructor =true/false”` 17 | 18 | For detailed explanation visit: https://medium.com/@rsssaket99/setter-getter-generator-f7bb2b8a67d2 19 | 20 | Hope you liked it. -------------------------------------------------------------------------------- /Reflection-API/TestCase.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | 4 | class Batch { 5 | 6 | } 7 | 8 | class Student { 9 | private int rollNumber; 10 | private String firstName; 11 | private String lastName; 12 | private Batch batch; 13 | private String city; 14 | private String state; 15 | private String country; 16 | private int courseCode; 17 | private Date dateOfBirth; 18 | private BigDecimal feePaid; 19 | private boolean isIndian; 20 | private boolean isAdult; 21 | private int hieght; 22 | public Student() 23 | { 24 | this.rollNumber=0; 25 | this.firstName=""; 26 | this.lastName=""; 27 | this.batch=null; 28 | this.city=""; 29 | this.state=""; 30 | this.country=""; 31 | this.courseCode=0; 32 | this.dateOfBirth=null; 33 | this.feePaid=null; 34 | this.isIndian=false; 35 | this.isAdult=false; 36 | this.hieght=0; 37 | } 38 | public void setRollNumber(int rollNumber) 39 | { 40 | this.rollNumber=rollNumber; 41 | } 42 | public int getRollNumber() 43 | { 44 | return this.rollNumber; 45 | } 46 | public void setFirstName(java.lang.String firstName) 47 | { 48 | this.firstName=firstName; 49 | } 50 | public java.lang.String getFirstName() 51 | { 52 | return this.firstName; 53 | } 54 | public void setLastName(java.lang.String lastName) 55 | { 56 | this.lastName=lastName; 57 | } 58 | public java.lang.String getLastName() 59 | { 60 | return this.lastName; 61 | } 62 | public void setBatch(Batch batch) 63 | { 64 | this.batch=batch; 65 | } 66 | public Batch getBatch() 67 | { 68 | return this.batch; 69 | } 70 | public void setCity(java.lang.String city) 71 | { 72 | this.city=city; 73 | } 74 | public java.lang.String getCity() 75 | { 76 | return this.city; 77 | } 78 | public void setState(java.lang.String state) 79 | { 80 | this.state=state; 81 | } 82 | public java.lang.String getState() 83 | { 84 | return this.state; 85 | } 86 | public void setCountry(java.lang.String country) 87 | { 88 | this.country=country; 89 | } 90 | public java.lang.String getCountry() 91 | { 92 | return this.country; 93 | } 94 | public void setCourseCode(int courseCode) 95 | { 96 | this.courseCode=courseCode; 97 | } 98 | public int getCourseCode() 99 | { 100 | return this.courseCode; 101 | } 102 | public void setDateOfBirth(java.util.Date dateOfBirth) 103 | { 104 | this.dateOfBirth=dateOfBirth; 105 | } 106 | public java.util.Date getDateOfBirth() 107 | { 108 | return this.dateOfBirth; 109 | } 110 | public void setFeePaid(java.math.BigDecimal feePaid) 111 | { 112 | this.feePaid=feePaid; 113 | } 114 | public java.math.BigDecimal getFeePaid() 115 | { 116 | return this.feePaid; 117 | } 118 | public void setIsIndian(boolean isIndian) 119 | { 120 | this.isIndian=isIndian; 121 | } 122 | public boolean getIsIndian() 123 | { 124 | return this.isIndian; 125 | } 126 | public void setIsAdult(boolean isAdult) 127 | { 128 | this.isAdult=isAdult; 129 | } 130 | public boolean getIsAdult() 131 | { 132 | return this.isAdult; 133 | } 134 | public void setHieght(int hieght) 135 | { 136 | this.hieght=hieght; 137 | } 138 | public int getHieght() 139 | { 140 | return this.hieght; 141 | } 142 | 143 | 144 | } -------------------------------------------------------------------------------- /Reflection-API/tmp.data: -------------------------------------------------------------------------------- 1 | public void setRollNumber(int rollNumber) 2 | { 3 | this.rollNumber=rollNumber; 4 | } 5 | public int getRollNumber() 6 | { 7 | return this.rollNumber; 8 | } 9 | public void setFirstName(java.lang.String firstName) 10 | { 11 | this.firstName=firstName; 12 | } 13 | public java.lang.String getFirstName() 14 | { 15 | return this.firstName; 16 | } 17 | public void setLastName(java.lang.String lastName) 18 | { 19 | this.lastName=lastName; 20 | } 21 | public java.lang.String getLastName() 22 | { 23 | return this.lastName; 24 | } 25 | public void setBatch(Batch batch) 26 | { 27 | this.batch=batch; 28 | } 29 | public Batch getBatch() 30 | { 31 | return this.batch; 32 | } 33 | public void setCity(java.lang.String city) 34 | { 35 | this.city=city; 36 | } 37 | public java.lang.String getCity() 38 | { 39 | return this.city; 40 | } 41 | public void setState(java.lang.String state) 42 | { 43 | this.state=state; 44 | } 45 | public java.lang.String getState() 46 | { 47 | return this.state; 48 | } 49 | public void setCountry(java.lang.String country) 50 | { 51 | this.country=country; 52 | } 53 | public java.lang.String getCountry() 54 | { 55 | return this.country; 56 | } 57 | public void setCourseCode(int courseCode) 58 | { 59 | this.courseCode=courseCode; 60 | } 61 | public int getCourseCode() 62 | { 63 | return this.courseCode; 64 | } 65 | public void setDateOfBirth(java.util.Date dateOfBirth) 66 | { 67 | this.dateOfBirth=dateOfBirth; 68 | } 69 | public java.util.Date getDateOfBirth() 70 | { 71 | return this.dateOfBirth; 72 | } 73 | public void setFeePaid(java.math.BigDecimal feePaid) 74 | { 75 | this.feePaid=feePaid; 76 | } 77 | public java.math.BigDecimal getFeePaid() 78 | { 79 | return this.feePaid; 80 | } 81 | public void setIsIndian(boolean isIndian) 82 | { 83 | this.isIndian=isIndian; 84 | } 85 | public boolean getIsIndian() 86 | { 87 | return this.isIndian; 88 | } 89 | public void setIsAdult(boolean isAdult) 90 | { 91 | this.isAdult=isAdult; 92 | } 93 | public boolean getIsAdult() 94 | { 95 | return this.isAdult; 96 | } 97 | public void setHieght(int hieght) 98 | { 99 | this.hieght=hieght; 100 | } 101 | public int getHieght() 102 | { 103 | return this.hieght; 104 | } 105 | -------------------------------------------------------------------------------- /Search/README.md: -------------------------------------------------------------------------------- 1 | # Searching Algorithms 2 | Searching algorithms are methods or procedures used to find a specific item or element within a collection of data. 3 | These algorithms are widely used in computer science and are crucial for tasks like searching for a particular record in a database, 4 | finding an element in a sorted list, or locating a file on a computer. 5 | 6 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 7 | 8 | ## References 9 | * 10 | * 11 | -------------------------------------------------------------------------------- /Search/binarySearch2.java: -------------------------------------------------------------------------------- 1 | package Search; 2 | 3 | public class binarySearch2 { 4 | public static void main(String[] args) { 5 | int a[] = {1,2,3,6,78,89}; // should be infinite sorted array 6 | System.out.println(search2(a,89)); 7 | } 8 | static int search2(int a[],int target){ 9 | int low=0; 10 | int high=1; 11 | while (a[high] < target){ 12 | low = high; 13 | high = 2*high; 14 | } 15 | return search(a,target,low,high); 16 | } 17 | static int search(int a[],int target,int low,int high){ 18 | while(low < high){ 19 | int mid = (low+high)/2; 20 | if(a[mid] == target){ 21 | return mid; 22 | } 23 | if (a[mid] < target){ 24 | low = mid+1; 25 | } 26 | if (a[mid] > target){ 27 | high = mid-1; 28 | } 29 | }return -1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Search/binary_search.java: -------------------------------------------------------------------------------- 1 | package Search; 2 | 3 | public class binary_search { 4 | public static void main(String[] args) { 5 | int a[] = {1,2,3,6,78,89}; 6 | System.out.println(search(a,89)); 7 | } 8 | static int search(int a[],int target) { 9 | 10 | int low = 0; 11 | int high = a.length - 1; 12 | while (low <= high) { 13 | int mid = (low + high) / 2; 14 | if (target == a[mid]) { 15 | return mid; 16 | } 17 | if (target > a[mid]) { 18 | low = mid + 1; 19 | } 20 | if (target < a[mid]) { 21 | high = mid - 1; 22 | } 23 | 24 | }return -1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Search/exponentialSearch.java: -------------------------------------------------------------------------------- 1 | /*Exponential Search Description:it is a searching algorithm that is used to find a specific element 2 | within a sorted array or list. 3 | It works by first identifying a range in which the target element is likely to be located 4 | and then performing a binary search within that range. 5 | Exponential search is particularly useful when dealing with very large data sets or 6 | when the target element is far from the beginning of the array. 7 | for more information:https://en.wikipedia.org/wiki/Exponential_search */ 8 | 9 | 10 | public class ExponentialSearch { 11 | public static int exponentialSearch(int[] arr, int target) { 12 | int n = arr.length; 13 | 14 | // If the target is the first element, return 0 15 | if (arr[0] == target) { 16 | return 0; 17 | } 18 | int i = 1;// Find the range for binary search 19 | while (i < n && arr[i] <= target) { 20 | i *= 2; 21 | } 22 | 23 | // Perform binary search within the found range 24 | return binarySearch(arr, target, i / 2, Math.min(i, n - 1)); 25 | } 26 | 27 | private static int binarySearch(int[] arr, int target, int left, int right) { 28 | while (left <= right) { 29 | int mid = left + (right - left) / 2; 30 | 31 | if (arr[mid] == target) { 32 | return mid; // Element found 33 | } else if (arr[mid] < target) { 34 | left = mid + 1; // Search the right half 35 | } else { 36 | right = mid - 1; // Search the left half 37 | } 38 | } 39 | 40 | return -1; // Element not found 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] arr = {2, 4, 6, 8, 10, 12, 14, 15, 18, 20}; 45 | int target = 11; 46 | int index = exponentialSearch(arr, target); 47 | 48 | if (index != -1) { 49 | System.out.println("Element found at index " + index); 50 | } else { 51 | System.out.println("Element not found in the array"); 52 | } 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Search/linear_Search.java: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Linear search is also called as sequential search algorithm. 4 | It is the simplest searching algorithm. In Linear search, 5 | we simply traverse the list completely and match each element of the list with the item whose location is to be found. 6 | If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL. 7 | 8 | Wikipedia: https://en.wikipedia.org/wiki/Linear_search 9 | */ 10 | class LinearSearch { 11 | static int linearSearch(int a[], int n, int val) { 12 | // Going through array sequencially 13 | for (int i = 0; i < n; i++) 14 | { 15 | if (a[i] == val) 16 | return i+1; 17 | } 18 | return -1; 19 | } 20 | public static void main(String args[]) { 21 | int a[] = {5, -5, 3, 40, 9}; // given array 22 | int val = 3; // value to be searched 23 | int n = a.length; // size of array 24 | int res = linearSearch(a, n, val); // Store result 25 | System.out.println(); 26 | System.out.print("The elements of the array are - "); 27 | for (int i = 0; i < n; i++) 28 | System.out.print(" " + a[i]); 29 | System.out.println(); 30 | System.out.println("Element to be searched is - " + val); 31 | if (res == -1) 32 | System.out.println("Element is not present in the array"); 33 | else 34 | System.out.println("Element is present at " + res +" position of array"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Search/search_sorted_rotatedArray.java: -------------------------------------------------------------------------------- 1 | package Search; 2 | 3 | public class search_sorted_rotatedArray { 4 | public static void main(String[] args) { 5 | int a[]={20,30,40,50,60,5,10}; 6 | int s = search(a,60); 7 | System.out.println(s); 8 | } 9 | static int search(int a[],int target){ 10 | int low =0; 11 | int high = a.length-1; 12 | 13 | while(low <= high){ 14 | int mid = (low+high)/2; 15 | 16 | if (a[mid]==target){ 17 | return mid; 18 | } 19 | // for left side 20 | if(a[low]=a[low] && targeta[mid] && target<=a[high]) 30 | { 31 | low = mid+1; 32 | }else { 33 | high = mid-1; 34 | } 35 | } 36 | 37 | }return -1; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Stack/LargestRect_in_Histogram.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class LargestRect_in_Histogram { 6 | public static void main(String[] args) { 7 | int[] a = {2,1,5,6,2,3}; 8 | System.out.println(maxArea(a)); 9 | } 10 | static int maxArea(int[] a){ 11 | int maxAns = 0; 12 | int ps[] = preSmall(a); 13 | int ns[] = nxtSmall(a); 14 | for (int i = 0; i < a.length; i++) { 15 | int curr = (ns[i] - ps[i] - 1) * a[i]; 16 | maxAns = Math.max(maxAns,curr); 17 | } 18 | return maxAns; 19 | } 20 | 21 | static int[] preSmall(int[] a){ 22 | int[] ps = new int[a.length]; 23 | Stack s1 = new Stack<>(); 24 | for (int i = 0; i < a.length; i++) { 25 | while (!s1.isEmpty() && a[s1.peek()] >= a[i]){ 26 | s1.pop(); 27 | } 28 | if (s1.isEmpty()) 29 | ps[i] = -1; 30 | else 31 | ps[i] = s1.peek(); 32 | s1.push(i); 33 | System.out.println("ps"+ps[i]); 34 | } 35 | 36 | return ps; 37 | } 38 | static int[] nxtSmall(int[] a){ 39 | int[] ns = new int[a.length]; 40 | Stack s2 = new Stack<>(); 41 | for (int i = a.length-1; i >= 0; i--) { 42 | while (!s2.isEmpty() && a[s2.peek()] >= a[i]){ 43 | s2.pop(); 44 | } 45 | if (s2.isEmpty()) 46 | ns[i] = a.length; 47 | else 48 | ns[i] = s2.peek(); 49 | s2.push(i); 50 | System.out.println("ns"+ns[i]); 51 | } 52 | return ns; 53 | } 54 | } 55 | /* 56 | * class Solution { 57 | public int largestRectangleArea(int[] heights) { 58 | int ans = 0; 59 | int cl =1 , cr = 1; 60 | for(int i=0;i= 0 && heights[left] >= heights[i] ){ 64 | left--; 65 | cl++; 66 | } 67 | while( right < heights.length && heights[right] >= heights[i] ){ 68 | right++; 69 | cr++; 70 | } 71 | ///int maxm = Math.max(cl,cr); 72 | int maxm = (right - left - 1); 73 | int as = maxm * heights[i]; 74 | if(as > ans){ 75 | ans = as; 76 | } 77 | } 78 | return ans; 79 | 80 | } 81 | } 82 | * */ -------------------------------------------------------------------------------- /Stack/README.md: -------------------------------------------------------------------------------- 1 | # Stack Algorithms 2 | Stack is a linear data structure that follows a particular order in which the operations are performed. 3 | The order may be LIFO(Last In First Out) or FILO(First In Last Out). 4 | 5 | LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. 6 | 7 | ![](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20221219100314/stack.drawio2.png) 8 | 9 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 10 | 11 | ## References 12 | * 13 | * 14 | -------------------------------------------------------------------------------- /Stack/gameOfTwoStacks.java: -------------------------------------------------------------------------------- 1 | //package Stack; 2 | // 3 | //public class gameOfTwoStacks { 4 | // public static void main(String[] args) { 5 | // int[] a = {1,2,3,4,5}; 6 | // int[] b = {6,7,8,9}; 7 | // } 8 | // public int solution(int x,int[] a,int[] b){ 9 | // return twostack(x,a,b,0,0)-1; 10 | // } 11 | // public static int twostack(int x,int[] a,int[] b,int sum,int count){ 12 | // if (sum > x) return count; 13 | // } 14 | // 15 | //} 16 | -------------------------------------------------------------------------------- /Stack/max_Rectangle.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import static Stack.LargestRect_in_Histogram.maxArea; 4 | 5 | public class max_Rectangle { 6 | public static void main(String[] args) { 7 | int[][] matrix = {{1,0,1,0,0},{1,0,1,1,1},{1,1,1,1,1},{1,0,0,1,0}}; 8 | int[][] m = {{0}}; 9 | System.out.println(largestArea(m)); 10 | } 11 | static int largestArea(int[][] a){ 12 | int currRow[] = a[0]; 13 | int maxAns = maxArea(currRow); 14 | 15 | for (int i = 1; i < a.length; i++) { 16 | for (int j = 0; j < a[0].length; j++) { 17 | if (a[i][j] == 1){ 18 | currRow[j]+=1; 19 | }else 20 | currRow[j] = 0; 21 | } 22 | int currAns = maxArea(currRow); 23 | maxAns = Math.max(maxAns,currAns); 24 | } 25 | return maxAns; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Stack/nextLargest.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class nextLargest { 6 | public static void main(String[] args) { 7 | int[] a = {3,4,23,7,6,2,1,98}; 8 | nextLarge(a); 9 | } 10 | static void nextLarge(int[] a){ 11 | Stack s = new Stack<>(); 12 | for (int i = a.length-1; i >= 0; i--) { 13 | while (!s.isEmpty() && s.peek()<=a[i]) 14 | { 15 | s.pop(); 16 | } 17 | if (s.isEmpty()) 18 | { 19 | System.out.println("-1"); 20 | }else { 21 | System.out.println(s.peek()); 22 | } 23 | 24 | s.push(a[i]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Stack/nextSmallest.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class nextSmallest { 6 | 7 | 8 | public static void main(String[] args) { 9 | int[] a = {3,4,23,7,6,2,1,98}; 10 | nextSmall(a); 11 | } 12 | static void nextSmall(int[] a){ 13 | Stack s =new Stack<>(); 14 | for (int i = a.length-1; i >= 0; i--) { 15 | while (!s.isEmpty() && s.peek()>=a[i]){ 16 | s.pop(); 17 | } 18 | if (s.isEmpty()){ 19 | System.out.println("-1"); 20 | }else { 21 | System.out.println(s.peek() ); 22 | } 23 | s.push(a[i]); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Stack/previousLargest.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class previousLargest { 6 | public static void main(String[] args) { 7 | int[] a = {3,4,23,7,6,2,1,98}; 8 | prevLargest(a); 9 | } 10 | static void prevLargest(int[] a){ 11 | Stack s = new Stack<>(); 12 | for (int i = 0; i < a.length; i++) { 13 | while (!s.isEmpty() && s.peek()<=a[i]){ 14 | s.pop(); 15 | } 16 | if (s.isEmpty()){ 17 | System.out.println("-1"); 18 | }else { 19 | System.out.println(s.peek()); 20 | } 21 | s.push(a[i]); 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Stack/previousSmaller.java: -------------------------------------------------------------------------------- 1 | package Stack; 2 | 3 | import java.util.Stack; 4 | 5 | public class previousSmaller { 6 | public static void main(String[] args) { 7 | int[] a = {3,4,23,7,6,2,1,98}; 8 | prevSmaller(a); 9 | } 10 | static void prevSmaller(int[] a){ 11 | Stack st = new Stack<>(); 12 | for (int i = 0; i < a.length; i++) { 13 | while (!st.isEmpty() && st.peek()>=a[i]){ 14 | st.pop(); 15 | } 16 | if (st.isEmpty()){ 17 | System.out.println("-1"); 18 | }else { 19 | System.out.println(st.peek()); 20 | } 21 | st.push(a[i]); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Stack/stack_methods.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class stack_methods { 4 | public static void main(String[] args) { 5 | Stack s = new Stack<>(); 6 | s.push(1); 7 | s.push(2); 8 | s.push(3); 9 | pushAtBottom(4,s); 10 | 11 | reverse(s); 12 | while(!s.isEmpty()){ 13 | System.out.println(s.peek()); 14 | s.pop(); 15 | } 16 | } 17 | public static void pushAtBottom(int data, Stack s){ 18 | if(s.isEmpty()){ 19 | s.push(data); 20 | return; 21 | } 22 | int top = s.pop(); 23 | pushAtBottom(data,s); 24 | s.push(top); 25 | } 26 | public static void reverse(Stack s){ 27 | if (s.isEmpty()){ 28 | return; 29 | } 30 | int top = s.pop(); 31 | reverse(s); 32 | pushAtBottom(top,s); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /String/Min_window_substring.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class Min_window_substring { 4 | public static void main(String[] args) { 5 | String s1 = "timetopractice"; 6 | String s2 = "toc"; 7 | String s = solutions(s1,s2); 8 | System.out.println(s); 9 | } 10 | static String solutions(String s1, String s2){ 11 | String ans = " " ; 12 | HashMap map2 = new HashMap<>(); 13 | for (int i = 0; i< s2.length(); i++) { 14 | char ch = s2.charAt(i); 15 | map2.put(ch, map2.getOrDefault(ch,0) + 1); 16 | } 17 | 18 | int mct = 0; 19 | int dmct = s2.length(); 20 | 21 | HashMap map1 = new HashMap<>(); 22 | int i =-1; 23 | int j=-1; 24 | 25 | while(true){ 26 | boolean f1 = false; 27 | boolean f2 = false; 28 | //acquire 29 | while (i < s1.length()-1 && mct= num2.length() ? num1 : num2; 14 | String small = num1.length() < num2.length() ? num1 : num2; 15 | StringBuilder sb = new StringBuilder(); 16 | int sum = 0; 17 | for (int i = 0; i < big.length(); i++) { 18 | int b = big.charAt(big.length() - i - 1) - '0'; 19 | int s = i < small.length() ? (small.charAt(small.length() - i - 1) - '0') : 0; 20 | sum += b + s; 21 | sb.append(sum % 10); 22 | sum /= 10; 23 | } 24 | if (sum > 0) sb.append(sum); 25 | return sb.reverse().toString(); 26 | } 27 | } -------------------------------------------------------------------------------- /String/fibonacci.java: -------------------------------------------------------------------------------- 1 | public class fibonacci { 2 | public static void main(String[] args) { 3 | int n = 2; 4 | System.out.println(fibo(n)); 5 | } 6 | public static int fibo(int n){ 7 | if(n<=1) return n; 8 | System.out.println("current n : "+n); 9 | return fibo(n-1) + fibo(n-2); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /String/first_last_occurence_string.java: -------------------------------------------------------------------------------- 1 | public class first_last_occurence_string { 2 | public static void main(String[] args) { 3 | String s = "rohanann"; 4 | findOccur(s, 0, 'a'); 5 | } 6 | public static int first = -1; 7 | public static int last = -1; 8 | public static void findOccur(String str,int idx,char element){ 9 | if(idx == str.length()){ 10 | System.out.println(first); 11 | System.out.println(last); 12 | return; 13 | } 14 | char currChar = str.charAt(idx); 15 | if(currChar == element){ 16 | if(first == -1) 17 | first = idx; 18 | else last = idx; 19 | } 20 | findOccur(str, idx+1, element); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /String/integerToEnglishword.java: -------------------------------------------------------------------------------- 1 | /* 2 | Convert a non-negative integer num to its English words representation. 3 | 4 | Example 1: 5 | Input: num = 123 6 | Output: "One Hundred Twenty Three" 7 | 8 | Example 2: 9 | Input: num = 12345 10 | Output: "Twelve Thousand Three Hundred Forty Five" 11 | 12 | Tag-Hard 13 | */ 14 | class Solution { 15 | 16 | private final String[] belowTwenty = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", 17 | "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; 18 | private final String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; 19 | 20 | public String numberToWords(int num) { 21 | if (num == 0) { 22 | return "Zero"; 23 | } 24 | return helper(num); 25 | } 26 | 27 | private String helper(int num) { 28 | StringBuilder result = new StringBuilder(); 29 | if (num < 20) { 30 | result.append(belowTwenty[num]); 31 | } else if (num < 100) { 32 | result.append(tens[num / 10]).append(" ").append(belowTwenty[num % 10]); 33 | } else if (num < 1000) { 34 | result.append(helper(num / 100)).append(" Hundred ").append(helper(num % 100)); 35 | } else if (num < 1000000) { 36 | result.append(helper(num / 1000)).append(" Thousand ").append(helper(num % 1000)); 37 | } else if (num < 1000000000) { 38 | result.append(helper(num / 1000000)).append(" Million ").append(helper(num % 1000000)); 39 | } else { 40 | result.append(helper(num / 1000000000)).append(" Billion ").append(helper(num % 1000000000)); 41 | } 42 | return result.toString().trim(); 43 | } 44 | } -------------------------------------------------------------------------------- /String/longestubtrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, find the length of the longest 3 | substring without repeating characters. 4 | 5 | Example 1: 6 | Input: s = "abcabcbb" 7 | Output: 3 8 | Explanation: The answer is "abc", with the length of 3. 9 | 10 | Example 2: 11 | Input: s = "bbbbb" 12 | Output: 1 13 | Explanation: The answer is "b", with the length of 1. 14 | 15 | Tag- Medium 16 | */ 17 | class Solution { 18 | public int lengthOfLongestSubstring(String s) { 19 | Setset=new HashSet<>(); 20 | int maxLength=0; 21 | int left=0; 22 | for(int right=0;right map = new HashMap<>(); 12 | // String finalres =""; 13 | // char[] charr = s.toCharArray(); 14 | // for (Character c : charr) { 15 | // map.put(c, map.getOrDefault(c, 0)+1); 16 | // } 17 | // for (Map.Entry e : map.entrySet()) { 18 | //// for (int i = 0; i < e.getValue(); i++) { 19 | //// System.out.println(e + " --" + i); 20 | //// } 21 | //// if(e.getValue() != k ){ 22 | //// for (int i = 0; i < e.getValue() ; i++) { 23 | //// finalres+=e.getKey(); 24 | //// } 25 | //// } 26 | // finalres+=e.getKey(); 27 | // } 28 | // return finalres; 29 | int count = 1; 30 | for (int i = 0; i < s.length(); i++) { 31 | if (s.charAt(i) == s.charAt(i - 1)) { 32 | count++; 33 | } else count = 1; 34 | 35 | if (count == k) { 36 | String reduce = s.substring(0, i - k + 1) + s.substring(i + 1); 37 | return removeDuplicates(reduce, k); 38 | } 39 | }return s; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /String/rev_string.java: -------------------------------------------------------------------------------- 1 | public class rev_string { 2 | public static void main(String[] args) { 3 | String n = "rohan"; 4 | printrevStr(n, n.length()-1); 5 | } 6 | public static void printrevStr(String a, int idx){ 7 | if(idx == 0){ 8 | System.out.println(a.charAt(idx)); 9 | return; 10 | } 11 | System.out.println(a.charAt(idx)); 12 | printrevStr(a, idx-1); 13 | } 14 | } -------------------------------------------------------------------------------- /String/stringbuilder.java: -------------------------------------------------------------------------------- 1 | public class stringbuilder { 2 | public static void main(String[] args) { 3 | StringBuilder sb = new StringBuilder("rohan"); 4 | 5 | for (int i = 0; i < sb.length()/2; i++) { 6 | int front = i; 7 | int back = sb.length() - 1 - i; 8 | 9 | char frontChar = sb.charAt(front); 10 | char backChar = sb.charAt(back); 11 | 12 | sb.setCharAt(front, backChar); 13 | sb.setCharAt(back, frontChar); 14 | } 15 | System.out.println(sb); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /String/validParenthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s of '(' , ')' and lowercase English characters. 3 | our task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. 4 | 5 | Example 1: 6 | Input: s = "a)b(c)d" 7 | Output: "ab(c)d" 8 | 9 | Example 2: 10 | Input: s = "))((" 11 | Output: "" 12 | Explanation: An empty string is also valid. 13 | 14 | Tag- Medium 15 | */ 16 | 17 | class Solution { 18 | public String minRemoveToMakeValid(String s) { 19 | Stack stack = new Stack<>(); 20 | for(int i=0;i set = new HashSet<>(stack); 37 | for(int i=0;i { 18 | 19 | for (int i = 0; i < 5; i++) { 20 | System.out.print("PL "); 21 | try { 22 | Thread.sleep(500); 23 | } catch (Exception e) {} 24 | } 25 | 26 | }; 27 | obj1.start(); 28 | obj2.start(); 29 | 30 | 31 | // Thread class has start() but Runnable interface doesnt have start() 32 | //for Runnable interface we need to make object of Thread and pass obj of class in it 33 | Thread t1 = new Thread(obj1); 34 | Thread t2 = new Thread(obj2); 35 | t1.start(); 36 | t2.start(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Threads/README.md: -------------------------------------------------------------------------------- 1 | # Threads In Java 2 | A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in a different stack frame. 3 | A process may contain multiple threads. Threads share the process resources, but still, they execute independently. 4 | 5 | Following are some questions asked on threads : 6 | - What is the thread? 7 | - Differentiate between process and thread? 8 | - What do you understand by inter-thread communication? 9 | - What is multithreading? 10 | 11 | ## References 12 | * 13 | * 14 | -------------------------------------------------------------------------------- /Threads/ThreadDemo.java: -------------------------------------------------------------------------------- 1 | package Threads; 2 | class Hi extends Thread{ 3 | public void show(){ 4 | for (int i = 0; i < 5; i++) { 5 | System.out.print("Hi"); 6 | try{Thread.sleep(500);}catch (Exception e){} 7 | } 8 | } 9 | } 10 | class Hello extends Thread implements Runnable{ 11 | public void run(){ 12 | for (int i = 0; i < 5; i++) { 13 | System.out.print("Hello"); 14 | try{Thread.sleep(500);}catch (Exception e){} 15 | } 16 | } 17 | } 18 | public class ThreadDemo { 19 | public static void main(String[] args) { 20 | Hi obj1 = new Hi(); 21 | Hello obj2 = new Hello(); 22 | 23 | obj1.show(); 24 | //obj2.show(); 25 | 26 | obj1.start(); 27 | obj2.start(); 28 | 29 | // Thread class has start() but Runnable interface doesnt have start() 30 | //for Runnable interface we need to make object of Thread and pass obj of class in it 31 | Thread t1 = new Thread(obj1); 32 | Thread t2 = new Thread(obj2); 33 | t1.start(); 34 | t2.start(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Trees/Binary_treePaths.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Binary_treePaths { 7 | public static void main(String[] args) { 8 | 9 | } 10 | static class Node{ 11 | int data; 12 | Node left,right; 13 | Node(int data){ 14 | this.data = data; 15 | } 16 | } 17 | static List BinaryTreePaths(Node root){ 18 | List result = new ArrayList<>(); 19 | if (root == null ) return result; 20 | 21 | String curr_paths = Integer.toString(root.data); 22 | if (root.left == null && root.right == null ) result.add(curr_paths); 23 | 24 | if (root.left != null) dfs(root.left,curr_paths,result); 25 | if (root.right != null) dfs(root.right,curr_paths,result); 26 | 27 | 28 | return result; 29 | } 30 | 31 | private static void dfs(Node node, String curr_paths, List result) { 32 | curr_paths += "->"+ node.data; 33 | 34 | if (node.left == null && node.right == null){ 35 | result.add(curr_paths); 36 | return; 37 | } 38 | if (node.left != null ) dfs(node.left, curr_paths,result); 39 | if (node.right != null ) dfs(node.right,curr_paths,result); 40 | 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Trees/DeleteNodes_returnForest.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | public class DeleteNodes_returnForest { 9 | public static void main(String[] args) { 10 | //System.out.println(Integer.); 11 | 12 | } 13 | static class TreeNode{ 14 | int val; 15 | TreeNode left,right; 16 | TreeNode(int val){ 17 | this.val = val; 18 | this.left = left; 19 | this.right =right; 20 | } 21 | } 22 | public List delNodes(TreeNode root, int[] to_delete) { 23 | List remaining = new ArrayList<>(); 24 | Set toDelete = new HashSet<>(); 25 | for (int i:to_delete) { 26 | toDelete.add(i); 27 | } 28 | removeNode(root, toDelete,remaining); 29 | if (!toDelete.contains(root.val)){ 30 | remaining.add(root); 31 | } 32 | return remaining; 33 | } 34 | 35 | private TreeNode removeNode(TreeNode root, Set toDelete, List remaining) { 36 | if (root == null) 37 | return null; 38 | root.left = removeNode(root.left,toDelete,remaining); 39 | root.right = removeNode(root.right,toDelete,remaining); 40 | if (toDelete.contains(root.val)){ 41 | if (root.left != null) 42 | remaining.add(root.left); 43 | if (root.right != null) 44 | remaining.add(root.right); 45 | return null; 46 | } 47 | return root; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Trees/Floor_Ceil_ofBST.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class Floor_Ceil_ofBST { 4 | class Node{ 5 | int data; 6 | Node left,right; 7 | Node(int data){ 8 | this.data = data; 9 | } 10 | } 11 | public int floor(Node root, int key){ 12 | int ans = Integer.MAX_VALUE; 13 | while (root != null){ 14 | if (root.data == key || root == null) return root.data; 15 | else if (root.data > key) { 16 | root = root.left; 17 | }else { 18 | ans = root.data; 19 | root = root.right; 20 | } 21 | } 22 | return ans; 23 | } 24 | public int ceil(Node root, int key){ 25 | int ans = Integer.MIN_VALUE; 26 | while (root != null){ 27 | if (root.data == key || root == null) return root.data; 28 | else if (root.data > key) { 29 | ans = root.data; 30 | root = root.left; 31 | }else { 32 | root = root.right; 33 | } 34 | } 35 | return ans; 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Trees/Height_of_Tree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.Scanner; 4 | 5 | class TreeNode { 6 | int data; 7 | TreeNode left; 8 | TreeNode right; 9 | 10 | public TreeNode(int data) { 11 | this.data = data; 12 | this.left = null; 13 | this.right = null; 14 | } 15 | } 16 | 17 | public class HeightOfTree { 18 | static Scanner sc = new Scanner(System.in); 19 | 20 | public static void main(String[] args) { 21 | TreeNode root = createTree(); 22 | int treeHeight = height(root); 23 | System.out.println("Height of the tree is: " + treeHeight); 24 | } 25 | 26 | static TreeNode createTree() { 27 | System.out.print("Enter data (-1 to exit): "); 28 | int data = sc.nextInt(); 29 | 30 | if (data == -1) { 31 | return null; 32 | } 33 | 34 | TreeNode root = new TreeNode(data); 35 | 36 | System.out.println("Enter left child of " + data + ": "); 37 | root.left = createTree(); 38 | 39 | System.out.println("Enter right child of " + data + ": "); 40 | root.right = createTree(); 41 | 42 | return root; 43 | } 44 | 45 | static int height(TreeNode root) { 46 | if (root == null) { 47 | return 0; 48 | } 49 | 50 | int leftHeight = height(root.left); 51 | int rightHeight = height(root.right); 52 | 53 | return Math.max(leftHeight, rightHeight) + 1; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Trees/Insert_into_a_Binary_Search_Tree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class Insert_into_a_Binary_Search_Tree { 4 | public static void main(String[] args) { 5 | 6 | } 7 | static class Node{ 8 | int data; 9 | Node left,right; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | public Node insertIntoBST(Node root, int val) { 15 | if (root == null ) return new Node(val); 16 | 17 | if (root.data > val) 18 | root.left = insertIntoBST(root.left,val); 19 | else if (root.data < val) 20 | root.right = insertIntoBST(root.right, val); 21 | 22 | return root; 23 | 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Trees/LCA_OfBinaryTree_LowestCommonancestor.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class LCA_OfBinaryTree_LowestCommonancestor { 4 | public static void main(String[] args) { 5 | 6 | } 7 | public class TreeNode { 8 | int val; 9 | TreeNode left; 10 | TreeNode right; 11 | TreeNode() {} 12 | TreeNode(int val) { this.val = val; } 13 | TreeNode(int val, TreeNode left, TreeNode right) { 14 | this.val = val; 15 | this.left = left; 16 | this.right = right; 17 | }} 18 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 19 | if( root == p || root == q || root == null) return root; 20 | TreeNode left = lowestCommonAncestor( root.left, p, q); 21 | TreeNode right = lowestCommonAncestor( root.right, p, q); 22 | if(left == null) 23 | return right; 24 | else if (right == null) 25 | return left; 26 | else 27 | return root; 28 | 29 | 30 | // below codes need some edge cases otherwise it is showing parameter is null as it finds p or q or root as null 31 | /*if( p.val < root.val && q.val < root.val) 32 | return lowestCommonAncestor(root.left,p,q); 33 | else if( p.val > root.val && q.val > root.val) 34 | return lowestCommonAncestor(root.right,p,q); 35 | else return root; */ 36 | 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Trees/Left_Right_viewOfTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Queue; 7 | 8 | public class Left_Right_viewOfTree { 9 | public static void main(String[] args) { 10 | 11 | } 12 | static class Node{ 13 | int data; 14 | Node left,right; 15 | Node(int data){ 16 | this.data = data; 17 | } 18 | } 19 | static List rightSideViewTree(Node root){ 20 | 21 | Queue q = new LinkedList<>(); 22 | List l = new ArrayList<>(); 23 | 24 | if (root == null) return l; 25 | q.offer(root); 26 | while(!q.isEmpty()){ 27 | int level = q.size(); 28 | for (int i = 0; i < level; i++) { 29 | Node curr = q.remove(); 30 | if(i == level-1) 31 | l.add(curr.data); 32 | if(curr.left != null) 33 | q.add(curr.left); 34 | if(curr.right != null) 35 | q.add(curr.right); 36 | 37 | } 38 | }return l; 39 | } 40 | 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Trees/LeveOrder_Traversal_inBinaryTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Queue; 7 | 8 | public class LeveOrder_Traversal_inBinaryTree { 9 | public static void main(String[] args) { 10 | 11 | } 12 | static class Node{ 13 | int data; 14 | Node left,right; 15 | Node(int data){ 16 | this.data = data; 17 | } 18 | } 19 | 20 | // O(n^2) Solution 21 | static void printLevelorder(Node root , int level ){ 22 | if (root == null) return; 23 | if (level == 1) System.out.println( root.data+""); 24 | if (level > 1){ 25 | printLevelorder(root.left , level-1); 26 | printLevelorder(root.right , level-1); 27 | } 28 | } 29 | 30 | // Optimized Solution 31 | static void LevelOrder(Node root){ 32 | Queue q =new LinkedList<>(); 33 | q.add(root); 34 | 35 | while (!q.isEmpty()){ 36 | Node curr = q.poll(); 37 | 38 | if (curr == null) { 39 | if (q.isEmpty()) return; 40 | q.add(null); 41 | continue; 42 | } 43 | 44 | System.out.println(curr.data); 45 | if (curr.left != null) q.add(curr.left); 46 | if (curr.right != null) q.add(curr.right); 47 | } 48 | } 49 | 50 | // Leetcode solution where return tpe is List> 51 | static List> levelOrde(Node root){ 52 | Queue q = new LinkedList(); 53 | List> anslist = new LinkedList>(); 54 | if (root == null) return anslist; 55 | q.offer(root); 56 | 57 | while (!q.isEmpty()){ 58 | int level = q.size(); 59 | List sublist = new LinkedList(); 60 | for (int i = 0; i < level; i++) { 61 | if (q.peek().left != null ) q.offer(q.peek().left); 62 | if (q.peek().right != null) q.offer(q.peek().right); 63 | sublist.add(q.poll().data); 64 | 65 | }anslist.add(sublist); 66 | }return anslist; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Trees/Max_Min_ina_Tree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Max_Min_ina_Tree { 6 | static Scanner sc ; 7 | public static void main(String[] args) { 8 | sc = new Scanner(System.in); 9 | } 10 | static class Node{ 11 | int data; 12 | Node left,right; 13 | Node(int data){ 14 | this.data = data; 15 | } 16 | } 17 | static Node createTree(){ 18 | Node root = null; 19 | System.out.println("enter the root : " ); 20 | int data = sc.nextInt(); 21 | 22 | if (data == -1) return null; 23 | 24 | System.out.println("enter the left : "+data); 25 | root.left = createTree(); 26 | System.out.println("enter the right : "+data); 27 | root.right = createTree(); 28 | 29 | 30 | return root; 31 | } 32 | 33 | static int maximum(Node root){ 34 | if (root == null){ 35 | return Integer.MIN_VALUE; 36 | } 37 | return Math.max(root.data, Math.max(maximum(root.left),maximum(root.right))); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Trees/README.md: -------------------------------------------------------------------------------- 1 | # Tree Data Structure Algorithms 2 | A tree data structure is a hierarchical structure that is used to represent & organize data in a way that is easy to navigate and search. 3 | It is a collection of nodes that are connected by edges and has a hierarchical relationship between the nodes. 4 | 5 | The topmost node of the tree is called the root, and the nodes below it are called the child nodes. 6 | Each node can have multiple child nodes, and these child nodes can also have their own child nodes, forming a recursive structure. 7 | 8 | ![](https://media.geeksforgeeks.org/wp-content/uploads/20221124153129/Treedatastructure.png) 9 | 10 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 11 | 12 | # References 13 | * 14 | * 15 | -------------------------------------------------------------------------------- /Trees/Search_in_a_Binary_Search_Tree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class Search_in_a_Binary_Search_Tree { 4 | public static void main(String[] args) { 5 | 6 | } 7 | static class Node{ 8 | int data; 9 | Node left,right; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | static Node searchBST(Node root, int val) { 15 | if (root == null || root.data == val) return root; 16 | 17 | if (root.data > val ) return searchBST(root.left, val); 18 | 19 | return searchBST(root.right,val); 20 | 21 | // OR 22 | /* while (root != null) 23 | { 24 | if ( val < root.val ) root = root.left; 25 | else if ( val > root.val ) root = root.right; 26 | else return root; 27 | } 28 | return root;*/ 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Trees/TopView_ofTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.security.KeyPair; 4 | import java.security.PrivateKey; 5 | import java.util.*; 6 | 7 | public class TopView_ofTree { 8 | public static void main(String[] args) { 9 | 10 | } 11 | class Node { 12 | int data; 13 | Node left,right; 14 | Node(int data){ 15 | this.data = data; 16 | } 17 | } 18 | /*static ArrayList topViewTree(Node root){ 19 | Queue q = new ArrayDeque<>(); 20 | Map map = new TreeMap<>(); 21 | 22 | //q.offer(new KeyPair(root,0)); 23 | 24 | }*/ 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Trees/VerticalOrder_Traversal_BinaryTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.security.KeyPair; 4 | import java.util.*; 5 | 6 | public class VerticalOrder_Traversal_BinaryTree { 7 | public static void main(String[] args) { 8 | 9 | } 10 | class Node { 11 | int data; 12 | Node left,right; 13 | Node(int data){ 14 | this.data = data; 15 | } 16 | } 17 | 18 | /*public ArrayList verticalOrder(Node root){ 19 | Queue q = new ArrayDeque<>(); 20 | Map> map = new TreeMap<>(); 21 | 22 | q.add(new KeyPair(0,root)); 23 | }*/ 24 | } 25 | -------------------------------------------------------------------------------- /Trees/binaryTree_to_Linkedlist_preorderTraversal.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.Stack; 4 | 5 | public class binaryTree_to_Linkedlist_preorderTraversal { 6 | static class Node{ 7 | int data; 8 | 9 | Node left,right; 10 | Node(int data){ 11 | this.data = data; 12 | } 13 | } 14 | // Flatten Binary Tree to Linked List 15 | static void treetoLL(Node root){ 16 | if (root == null) return; 17 | Stack s = new Stack<>(); 18 | s.push(root); 19 | 20 | while(!s.isEmpty()){ 21 | Node curr = s.pop(); 22 | if (curr.left != null){ 23 | s.push(curr.left); 24 | } 25 | if (curr.right != null ){ 26 | s.push(curr.right); 27 | } 28 | if (!s.isEmpty()){ 29 | curr.right = s.peek(); 30 | } 31 | curr.left = null; 32 | } 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Trees/binaryTree_to_dublyLinkedList.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class binaryTree_to_dublyLinkedList { 4 | public static void main(String[] args) { 5 | 6 | } 7 | 8 | static class Node{ 9 | int data; 10 | Node left,right; 11 | Node(int data){ 12 | this.data = data; 13 | } 14 | } 15 | static Node prev=null,head=null; 16 | static void converttoDLL(Node root){ 17 | if (root == null) return; 18 | 19 | converttoDLL(root.left); 20 | if (prev == null) head = root; 21 | else { 22 | root.left = prev; 23 | prev.right = root; 24 | } 25 | prev = root; 26 | converttoDLL(root.right); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Trees/count_the_nodes.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class count_the_nodes { 4 | public static void main(String[] args) { 5 | int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 6 | tree_apna.BinaryTree tree = new tree_apna.BinaryTree(); 7 | tree_apna.Node root = tree.buildTree(nodes); 8 | System.out.println(countNodes(root)); 9 | } 10 | public static int countNodes(tree_apna.Node root){ 11 | if (root == null) return 0; 12 | int leftnode = countNodes(root.left); 13 | int rightnode = countNodes(root.right); 14 | return 1+leftnode+rightnode; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Trees/diameterOfTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | 4 | public class diameterOfTree { 5 | public static void main(String[] args) { 6 | int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 7 | tree_apna.BinaryTree tree = new tree_apna.BinaryTree(); 8 | tree_apna.Node root = tree.buildTree(nodes); 9 | System.out.println(diameteroftree(root)); 10 | System.out.println("-----------"); 11 | System.out.println(diameter2(root).diam); 12 | } 13 | 14 | private static int diameteroftree(tree_apna.Node root) { 15 | if (root == null) return 0; 16 | int diam1 =diameteroftree(root.left); 17 | int diam2 = diameteroftree(root.right); 18 | int diam3 = height_of_tree_apna.heightOfNodes(root.left)+height_of_tree_apna.heightOfNodes(root.right)+1; 19 | 20 | return Math.max(diam3,Math.max(diam1,diam2)); //O(n^2) 21 | 22 | } 23 | 24 | //O(n) 25 | static class TreeInfo{ 26 | int ht; 27 | int diam; 28 | TreeInfo(int ht,int diam){ 29 | this.ht = ht; 30 | this.diam = diam; 31 | } 32 | } 33 | public static TreeInfo diameter2(tree_apna.Node root) 34 | { 35 | if (root == null) return new TreeInfo(0,0); 36 | TreeInfo left = diameter2((root.left)); 37 | TreeInfo right = diameter2(root.right); 38 | 39 | int myheight = Math.max(left.ht,right.ht)+1; 40 | 41 | int diam1 = left.diam; 42 | int diam2 = right.diam; 43 | int diam3 = left.ht+right.ht+1; 44 | 45 | int mydiam = Math.max(diam3,Math.max(diam1,diam2)); 46 | 47 | TreeInfo res = new TreeInfo(myheight,mydiam); 48 | return res; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Trees/diameter_of_binaryTree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class diameter_of_binaryTree { 4 | static class Node{ 5 | int data; 6 | 7 | Node left,right; 8 | Node(int data){ 9 | this.data = data; 10 | } 11 | } 12 | 13 | static int diameter(Node root){ 14 | if (root == null ) return 0; 15 | 16 | int dl = diameter(root.left); 17 | int dr = diameter(root.right); 18 | 19 | int curr = height(root.left) + height(root.right) + 1; 20 | return Math.max(curr, Math.max(dl,dr)); 21 | } 22 | static int height(Node root){ 23 | if (root == null ) return 0; 24 | return 1+Math.max(height(root.left), height(root.right)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Trees/height_of_tree_apna.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class height_of_tree_apna { 4 | public static void main(String[] args) { 5 | int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 6 | tree_apna.BinaryTree tree = new tree_apna.BinaryTree(); 7 | tree_apna.Node root = tree.buildTree(nodes); 8 | System.out.println(heightOfNodes(root)); 9 | } 10 | 11 | static int heightOfNodes(tree_apna.Node root) { 12 | if (root == null) return 0; 13 | 14 | int leftheight = heightOfNodes(root.left); 15 | int rightheight = heightOfNodes(root.right); 16 | 17 | return Math.max(leftheight,rightheight)+1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Trees/kk_BST.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.Scanner; 4 | 5 | public class kk_BST { 6 | public kk_BST(){ 7 | 8 | } 9 | 10 | private static class Node{ 11 | int value; 12 | Node left; 13 | Node right; 14 | 15 | public Node (int value){ 16 | this.value=value; 17 | } 18 | } 19 | private Node root; 20 | // insert elements 21 | public void populate(Scanner scanner){ 22 | System.out.println("enter the root node: "); 23 | int value = scanner.nextInt(); 24 | root = new Node(value); 25 | populate(scanner,root); 26 | } 27 | private void populate(Scanner scanner, Node node){ 28 | System.out.println("do u want to enter left of :"+node.value); 29 | boolean left = scanner.nextBoolean(); 30 | if(left){ 31 | System.out.println("enter the value of the left of "+node .value); 32 | int value = scanner.nextInt(); 33 | node.left = new Node(value); 34 | populate(scanner, node.left); 35 | } 36 | System.out.println("do u want to enter right of :"+node.value); 37 | boolean right = scanner.nextBoolean(); 38 | if(right){ 39 | System.out.println("enter the value of the right of "+node .value); 40 | int value = scanner.nextInt(); 41 | node.right = new Node(value); 42 | populate(scanner, node.right); 43 | } 44 | } 45 | 46 | // public void display(){ 47 | // display(root); 48 | // } 49 | // private display(Node node,String indent){ 50 | // if (node != null){return;} 51 | // System.out.println(indent+node.value); 52 | //// display(node.left+indent+"/t"); 53 | //// display(node.right+indent+"/t"); 54 | // } 55 | } 56 | -------------------------------------------------------------------------------- /Trees/subtree_of_tree.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class subtree_of_tree { 4 | private static boolean subtreeoftree(tree_apna.Node root,tree_apna.Node subroot){ 5 | if (subroot == null) return true; 6 | if (root == null) return false; 7 | if (root.data == subroot.data){ 8 | if (isIdentical(root,subroot)) return true; 9 | } 10 | 11 | return subtreeoftree(root.left,subroot) || subtreeoftree(root.right,subroot); 12 | } 13 | 14 | private static boolean isIdentical(tree_apna.Node root, tree_apna.Node subroot) { 15 | if (root == null && subroot == null) return true; 16 | if (root == null || subroot == null) return false; 17 | 18 | if(root.data == subroot.data) return isIdentical(root.left,subroot.left) && isIdentical(root.right,subroot.right); 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Trees/sum_of_nodes.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class sum_of_nodes { 4 | public static void main(String[] args) { 5 | int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 6 | tree_apna.BinaryTree tree = new tree_apna.BinaryTree(); 7 | tree_apna.Node root = tree.buildTree(nodes); 8 | System.out.println(sumOfNodes(root)); 9 | } 10 | public static int sumOfNodes(tree_apna.Node root){ 11 | if (root == null) return 0; 12 | 13 | int leftsum = sumOfNodes(root.left); 14 | int rightsum = sumOfNodes(root.right); 15 | 16 | return leftsum+rightsum+root.data; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Trees/tree_apna.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class tree_apna { 7 | public static class Node{ 8 | int data; 9 | Node left; 10 | Node right; 11 | Node(int data){ 12 | this.data = data; 13 | this.left = null; 14 | this.right = null; 15 | } 16 | } 17 | static class BinaryTree{ 18 | static int idx = -1; 19 | public static Node buildTree(int nodes[]){ 20 | idx++; 21 | if(nodes[idx] == -1) return null; 22 | 23 | Node newNode = new Node(nodes[idx]); 24 | newNode.left = buildTree(nodes); 25 | newNode.right = buildTree(nodes); 26 | return newNode; 27 | } 28 | } 29 | public static void preorder(Node root){ 30 | if(root == null) return; 31 | System.out.print(root.data+" "); 32 | preorder(root.left); 33 | preorder(root.right); 34 | 35 | } 36 | 37 | public static void inOrder(Node root){ 38 | if(root == null) return; 39 | inOrder(root.left); 40 | System.out.print(root.data+" "); 41 | inOrder(root.right); 42 | } 43 | public static void postOrder(Node root){ 44 | if (root == null) return; 45 | postOrder(root.left); 46 | postOrder(root.right); 47 | System.out.print(root.data+" "); 48 | } 49 | public static void levelOrder(Node root){ 50 | if (root == null) return; 51 | Queue q = new LinkedList<>(); 52 | q.add(root); 53 | q.add(null); 54 | 55 | while(!q.isEmpty()){ 56 | Node currNode = q.remove(); 57 | if (currNode == null){ 58 | System.out.println(); 59 | if (q.isEmpty()) break; 60 | else q.add(null); 61 | }else { 62 | System.out.print(currNode.data+" "); 63 | if (currNode.left != null) q.add(currNode.left); 64 | if (currNode.right != null) q.add(currNode.right); 65 | 66 | } 67 | } 68 | } 69 | public static void main(String[] args) { 70 | //tree_apna tree = new tree_apna(); 71 | int nodes[] = {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 72 | BinaryTree tree = new BinaryTree(); 73 | Node root = tree.buildTree(nodes); 74 | System.out.println(root.data); 75 | System.out.println("------------"); 76 | preorder(root); 77 | System.out.println(); 78 | System.out.println("------------"); 79 | inOrder(root); 80 | System.out.println(); 81 | System.out.println("------------"); 82 | postOrder(root); 83 | System.out.println(); 84 | System.out.println("------------"); 85 | levelOrder(root); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /Trees/trees.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | import java.util.Scanner; 3 | public class trees { 4 | static Scanner sc; 5 | public static void main(String[] args) { 6 | sc = new Scanner(System.in); 7 | createTree(); 8 | } 9 | static class Node{ 10 | Node left,right; 11 | public int data; 12 | Node(int data){ 13 | this.data = data; 14 | } 15 | } 16 | static Node createTree(){ 17 | Node root = null; 18 | System.out.println("Enter data : "); 19 | int data = sc.nextInt(); 20 | 21 | if (data == -1) return null; 22 | 23 | root = new Node(data); 24 | 25 | System.out.println("enter for Left : "+ data); 26 | root.left = createTree(); 27 | 28 | System.out.println("Enter for Right : "+ data); 29 | root.right = createTree(); 30 | 31 | 32 | return root; 33 | } 34 | static void inOrder(Node root){ 35 | if (root == null ) return; 36 | inOrder(root.left); 37 | System.out.println(root.data+" "); 38 | inOrder(root.right); 39 | } 40 | static void preOrder(Node root){ 41 | if (root == null ) return; 42 | System.out.println(root.data+" "); 43 | preOrder(root.left); 44 | preOrder(root.right); 45 | } 46 | static void postOrder(Node root){ 47 | if (root == null ) return; 48 | postOrder(root.left); 49 | postOrder(root.right); 50 | System.out.println(root.data+" "); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Trees/valid_BST.java: -------------------------------------------------------------------------------- 1 | package Trees; 2 | 3 | public class valid_BST { 4 | public static void main(String[] args) { 5 | 6 | } 7 | static class Node{ 8 | Node left,right; 9 | public int data; 10 | Node(int data){ 11 | this.data = data; 12 | this.left = left; 13 | this.right = right; 14 | } 15 | } 16 | 17 | public boolean isValidBST(Node root){ 18 | return validate(root, null ,null); 19 | } 20 | public boolean validate(Node root, Integer max, Integer min){ 21 | if (root == null) 22 | return true; 23 | else if (max!= null && root.data>=max || min!=null && root.data < min) { 24 | return false; 25 | }else { 26 | return validate(root.left,root.data,min)&&validate(root.right,max,root.data); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Trie/concatinate_word_problem.java: -------------------------------------------------------------------------------- 1 | //Problem Link: https://leetcode.com/problems/concatenated-words/description/ 2 | package Trie; 3 | 4 | class concatinate_word_problem { 5 | class Trie{ 6 | Trie[] children; 7 | boolean isWord; 8 | 9 | public Trie(){ 10 | children = new Trie[26]; 11 | isWord = false; 12 | } 13 | } 14 | Trie root = new Trie(); 15 | 16 | private void buildTrie(String word){ 17 | Trie trie = root; 18 | 19 | for(char c : word.toCharArray()){ 20 | if(trie.children[c-'a'] == null){ 21 | trie.children[c-'a'] = new Trie(); 22 | } 23 | trie = trie.children[c-'a']; 24 | } 25 | trie.isWord = true; 26 | } 27 | 28 | private boolean searchWord(String words, int count){ 29 | Trie node = root; 30 | for(int i=0; i< words.length(); i++){ 31 | char c = words.charAt(i); 32 | if(node.children[c-'a'] == null) return false; 33 | node = node.children[c-'a']; 34 | if(node.isWord && searchWord(words.substring(i+1),count+1)) return true; 35 | } 36 | count++; 37 | return (count >1 && node.isWord) ? true : false; 38 | } 39 | public List findAllConcatenatedWordsInADict(String[] words) { 40 | Arrays.sort(words, (a,b)-> a.length()-b.length()); 41 | ArrayList result = new ArrayList<>(); 42 | 43 | for(String word : words){ 44 | if(searchWord(word, 0)){ 45 | result.add(word); 46 | } 47 | else buildTrie(word); 48 | } 49 | return result; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Trie/trie_1.java: -------------------------------------------------------------------------------- 1 | package Trie; 2 | 3 | public class trie_1 { 4 | static class Node{ 5 | Node[] children; 6 | boolean eow; //end of word 7 | public Node(){ 8 | children = new Node[26]; 9 | for (int i = 0; i < 26; i++) { 10 | children[i] = null; 11 | } 12 | eow = false; 13 | } 14 | } 15 | static Node root = new Node(); 16 | public static void insert(String word){ 17 | Node curr = root; 18 | for (int i = 0; i < word.length(); i++) { 19 | int idx = word.charAt(i)-'a'; // to get index 20 | 21 | if (curr.children[idx] == null) 22 | curr.children[idx] = new Node(); // add new node 23 | if (i == word.length()-1) 24 | curr.children[idx].eow = true; 25 | curr = curr.children[idx]; 26 | } 27 | } 28 | public static boolean search(String key){ // O(L) : L = key length 29 | Node curr = root; 30 | for (int i = 0; i < key.length(); i++) { 31 | int idx = key.charAt(i)-'a'; 32 | Node node = curr.children[idx]; // use node or root.children 33 | 34 | if (node == null) 35 | return false; 36 | if (i == key.length()-1 && node.eow == false) 37 | return false; 38 | curr = curr.children[idx]; 39 | } 40 | return true; 41 | } 42 | public static boolean wordbreak(String key){ 43 | if (key.length() == 0) return true; 44 | for (int i = 0; i < key.length(); i++) { 45 | String first = key.substring(0,i); 46 | String second = key.substring(i); 47 | if(search(first) && wordbreak(second)) return true; 48 | } 49 | return false; 50 | } 51 | public static void main(String[] args) { 52 | String words[] = {"the","a","there","their","any"}; 53 | String key = "the"; 54 | for (int i = 0; i < words.length; i++) { 55 | insert(words[i]); 56 | } 57 | 58 | System.out.println(search("thor")); 59 | System.out.println(wordbreak(key)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | com.thealgorithms 7 | Java 8 | 1.0-SNAPSHOT 9 | jar 10 | 11 | 12 | UTF-8 13 | 17 14 | 17 15 | 3.23.1 16 | 17 | 18 | 19 | 20 | 21 | org.junit 22 | junit-bom 23 | 5.8.2 24 | pom 25 | import 26 | 27 | 28 | 29 | 30 | 31 | 32 | org.junit.jupiter 33 | junit-jupiter 34 | 5.9.0 35 | test 36 | 37 | 38 | org.assertj 39 | assertj-core 40 | ${assertj.version} 41 | 42 | 43 | org.junit.jupiter 44 | junit-jupiter-api 45 | 5.9.0 46 | test 47 | 48 | 49 | 50 | 51 | 52 | 53 | maven-surefire-plugin 54 | 2.22.2 55 | 56 | 57 | org.apache.maven.plugins 58 | maven-compiler-plugin 59 | 3.10.1 60 | 61 | 17 62 | 17 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /sorting/Insertion_sort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class Insertion_sort { 4 | public static void main(String[] args) { 5 | int a[] = {-1,2,3,4,2,2,34,12,-45,0}; 6 | insertion(a); 7 | } 8 | static void insertion(int a[]){ 9 | for (int i = 1; i < a.length; i++) { 10 | int temp = a[i]; 11 | int j = i-1; 12 | while (j >= 0 && a[j]>temp){ 13 | a[j+1] = a[j]; 14 | j--; 15 | } 16 | a[j+1] = temp; 17 | } 18 | for (int i = 0; i < a.length; i++) { 19 | System.out.print(" "+a[i]); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /sorting/MergeSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohan472000/Java-DSA-InterviewPrep/f1631cff54adf2170e99816233ac5fd9e832c2ec/sorting/MergeSort.class -------------------------------------------------------------------------------- /sorting/MergeSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class MergeSort{ 4 | 5 | //To merge two sorted arrays 6 | public static void merge2array(int[] arr,int startIndex,int endIndex){ 7 | int mid = (startIndex+endIndex)/2; 8 | int i = startIndex; 9 | int j=mid+1; 10 | 11 | int[] ans = new int[endIndex-startIndex+1]; 12 | int ansIndex = 0; 13 | 14 | while(i<=mid && j<=endIndex){ 15 | if(arr[i]=endIndex){ 39 | return; 40 | } 41 | int mid = (startIndex+endIndex) / 2; 42 | mergeSort(arr,startIndex,mid); //Sort first half of array 43 | mergeSort(arr,mid+1,endIndex); //Sort second half of array 44 | merge2array(arr,startIndex,endIndex); //Merge two sorted arrays 45 | } 46 | 47 | //Helper function 48 | public static void mergeSort(int[] arr){ 49 | mergeSort(arr,0,arr.length-1); 50 | } 51 | 52 | public static void main(String[] args) { 53 | int[] arr = {9,8,10,7,6,8}; 54 | mergeSort(arr); 55 | System.out.println(Arrays.toString(arr)); 56 | } 57 | } -------------------------------------------------------------------------------- /sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import javax.swing.plaf.synth.SynthTextAreaUI; 4 | 5 | import static sorting.bubble_sort.swap; 6 | 7 | public class QuickSort { 8 | public static void main(String[] args) { 9 | int a[] = {3,1,2,67,34,-1}; 10 | quickSort(a,0,a.length-1); 11 | for (int i = 0; i < a.length; i++) { 12 | System.out.print(" "+a[i]); 13 | } 14 | System.out.print("-------------------------------------------------"); 15 | System.out.println(); 16 | quick(a,0,a.length-1); 17 | for (int i = 0; i < a.length; i++) { 18 | System.out.print(" "+a[i]); 19 | } 20 | } 21 | static void quickSort(int a[],int low , int high){ 22 | if (low < high){ 23 | int j = partition(a,low , high); 24 | System.out.println(j); 25 | quickSort(a,low,j-1); 26 | quickSort(a,j+1,high); 27 | } 28 | 29 | } 30 | static void quick(int a[] , int low, int high){ 31 | int j = partition_middle(a,low ,high); 32 | 33 | if (low < j-1){ 34 | quick(a,low,j-1); 35 | 36 | } 37 | if (j < high){ 38 | quick(a,j,high); 39 | } 40 | } 41 | static int partition_one(int a[], int low , int high){ 42 | /*int pivot = a[low]; 43 | int i = low; 44 | int j = high; 45 | while (i < j){ 46 | do{ 47 | i++; 48 | }while(a[i] <= pivot); 49 | do { 50 | j--; 51 | }while(a[j] > pivot); 52 | if (i < j){ 53 | swap(a,a[i],a[j]);} 54 | } 55 | swap(a,low,j); 56 | System.out.println(j); 57 | return j; */ 58 | return 2; 59 | } 60 | static int partition_middle(int a[], int low, int high){ 61 | int pivot = (low + high)/2; 62 | while( low <= high){ 63 | if(a[low] < a[pivot]){ 64 | low++; 65 | } 66 | if(a[high] > a[pivot]){ 67 | high--; 68 | } 69 | if(low <= high){ 70 | swap(a,a[low],a[high]); 71 | low++; 72 | high--; 73 | } 74 | } 75 | return low; 76 | } 77 | static int partition(int arr[], int low, int high) 78 | { 79 | int pivot = arr[high]; 80 | int i = (low-1); // index of smaller element 81 | for (int j=low; j a[pivot]){ 32 | high--; 33 | } 34 | if(low <= high){ 35 | int temp = a[low]; 36 | a[low] = a[high]; 37 | a[high] = temp; 38 | low++; 39 | high--; 40 | } 41 | } 42 | return low; 43 | } 44 | 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /sorting/README.md: -------------------------------------------------------------------------------- 1 | # Sorting Algorithms 2 | A sorting algorithm is a method for reorganizing a large number of items into a specific order. 3 | Such as alphabetical, highest-to-lowest value or shortest-to-longest distance. Sorting algorithms take lists of items as input data, 4 | perform specific operations on those lists and deliver ordered arrays as output. 5 | 6 | This section contains a lot of important algorithms that help us to use sorting algorithms in various scenarios. 7 | ## References 8 | * 9 | * 10 | -------------------------------------------------------------------------------- /sorting/Selection_sort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import static sorting.bubble_sort.swap; 4 | 5 | public class Selection_sort { 6 | public static void main(String[] args) { 7 | int a[] = {-1,2,3,4,2,2,34,12,-45,0}; 8 | selection(a); 9 | 10 | } 11 | static void selection(int a[]){ 12 | for (int i = 0; i < a.length-1; i++) { 13 | int min = i; 14 | for (int j = i+1; j < a.length; j++) { 15 | if(a[j] < a[min]){ 16 | min = j; 17 | } 18 | } 19 | if(min != i){ 20 | swap(a,min,i); 21 | } 22 | } 23 | for (int i = 0; i < a.length; i++) { 24 | System.out.print(" "+a[i]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sorting/boolean_isSorted.java: -------------------------------------------------------------------------------- 1 | public class boolean_isSorted { 2 | public static void main(String[] args) { 3 | int arr[] = {1,2,2,3,4}; 4 | System.out.println(isSorted(arr, 0)); 5 | } 6 | public static boolean isSorted(int arr[], int idx){ 7 | if(idx == arr.length-1) 8 | return true; 9 | // if(arr[idx] < arr[idx+1]){ 10 | // // array is sorted till now 11 | // return isSorted(arr, idx+1); 12 | // }else return false; 13 | if(arr[idx] > arr[idx+1]) 14 | return false; 15 | return isSorted(arr, idx+1); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /sorting/bubble_sort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class bubble_sort { 4 | public static void main(String[] args) { 5 | int a[] = {3,4,2,3,6,7,8,-1}; 6 | bubble(a); 7 | } 8 | static void bubble(int a[]){ 9 | for (int i = 0; i < a.length - 1; i++) { 10 | for (int j = 0; j < a.length-i-1; j++) { 11 | if(a[j+1] < a[j]){ 12 | swap(a,j+1,j); 13 | } 14 | } 15 | } 16 | for (int i = 0; i < a.length ; i++) { 17 | System.out.print(a[i]); 18 | } 19 | } 20 | static void swap(int a[],int i, int j){ 21 | int temp = a[i]; 22 | a[i] = a[j]; 23 | a[j] = temp; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /sorting/bubblesort.java: -------------------------------------------------------------------------------- 1 | public class bubblesort { 2 | public static void main(String[] args) { 3 | int arr[] = {3,5,2,1,9,4}; 4 | 5 | //bubble sort 6 | for (int i = 0; i < arr.length; i++) { 7 | for (int j = 0; j < arr.length-i-1; j++) { 8 | if(arr[j] > arr[j+1]){ 9 | //swap 10 | int temp = arr[j]; 11 | arr[j] = arr[j+1]; 12 | arr[j+1] = temp; 13 | } 14 | } 15 | } 16 | printArray(arr); 17 | } 18 | public static void printArray(int[] a){ 19 | for (int i : a) { 20 | System.out.println(i); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /sorting/insertionsort.java: -------------------------------------------------------------------------------- 1 | 2 | public class insertionsort { 3 | public static void main(String[] args) { 4 | int arr[] = {7,6,9,2,5,1}; 5 | for (int i = 1; i < arr.length; i++) { 6 | int current = arr[i]; 7 | int j = i-1; 8 | while(j>=0 && current < arr[j]){ 9 | arr[j+1] = arr[j]; 10 | j--; 11 | } 12 | //place to current position of arr[i] 13 | arr[j+1] = current; 14 | } 15 | printArray(arr); 16 | } 17 | public static void printArray(int[] a){ 18 | for (int i : a) { 19 | System.out.println(i); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /sorting/recursion1.java: -------------------------------------------------------------------------------- 1 | public class recursion1 { 2 | public static void main(String[] args) { 3 | printSum(1, 5, 0); 4 | } 5 | public static void printSum(int i, int n, int sum){ 6 | if(i == n){ 7 | sum+=i; 8 | System.out.println(sum); 9 | return; 10 | } 11 | sum+=i; 12 | printSum(i+1, n, sum); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sorting/selectionsort.java: -------------------------------------------------------------------------------- 1 | 2 | public class selectionsort { 3 | public static void main(String[] args) { 4 | int arr[] = {3,2,4,9,1,5}; 5 | for (int i = 0; i < arr.length-1; i++) { 6 | int smallest = i; 7 | for (int j = i+1; j < arr.length; j++) { 8 | if(arr[smallest] > arr[j]){ 9 | smallest = j; 10 | } 11 | } 12 | //swap 13 | int temp = arr[smallest]; 14 | arr[smallest] = arr[i]; 15 | arr[i] = temp; 16 | } 17 | printArray(arr); 18 | } 19 | public static void printArray(int[] a){ 20 | for (int i : a) { 21 | System.out.println(i); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /sorting/shell_sort.java: -------------------------------------------------------------------------------- 1 | /* This class demonstrates a Shell Sort algorithm. 2 | Description: 3 | Shell Sort is an efficient and adaptive sorting algorithm that is an extension of the Insertion Sort algorithm. 4 | It works by dividing the array into smaller subarrays and then sorting these subarrays using the Insertion Sort method. 5 | The key idea behind Shell Sort is to compare and swap elements that are far apart, gradually reducing the gap between elements until the entire array is sorted. 6 | * For more information, see:https://en.wikipedia.org/wiki/Shellsort */ 7 | 8 | public class shell_sort { 9 | 10 | public static void shellSort(int[] arr) { 11 | int n = arr.length; 12 | 13 | // Start with a large gap and reduce it 14 | for (int gap = n / 2; gap > 0; gap /= 2) { 15 | //The gap is reduced using the expression gap /= 2 16 | //in the outer loop 17 | 18 | for (int i = gap; i < n; i++) {// Perform an insertion sort for elements at each gap 19 | int temp = arr[i]; 20 | int j; 21 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { 22 | arr[j] = arr[j - gap]; 23 | } 24 | arr[j] = temp; 25 | } 26 | } 27 | } 28 | 29 | public static void printArray(int[] arr) { 30 | for (int num : arr) { 31 | System.out.print(num + " "); 32 | } 33 | System.out.println(); 34 | } 35 | 36 | public static void main(String[] args) { 37 | int[] arr = {12, 34, 54, 2, 3}; 38 | System.out.println("Original array:"); 39 | printArray(arr); 40 | 41 | shellSort(arr); 42 | 43 | System.out.println("Sorted array:"); 44 | printArray(arr); 45 | } 46 | } 47 | --------------------------------------------------------------------------------