├── .gitignore ├── CODE_OF_CONDUCT.md ├── Contributing.md ├── Graphs ├── BellmanFord.java ├── Bipartite.java ├── DijkstraAlgo.java ├── Floyd-Warshall-Algo.java ├── Graphs.java ├── Kosaraju’s_Algo.java ├── KruskalsAlgo.java └── PrimsAlgo.java ├── LICENSE.md ├── LinkedList ├── C++ │ ├── doublyLinkedList.cpp │ ├── palindrome check in linkedlist │ ├── singlyCIrcularLinkedList.cpp │ └── singlyLinkedList.cpp ├── C │ ├── Add-two-polynomials-using-linked-list.c │ ├── Circular-Linked-List.c │ ├── doubly_linked_list.c │ ├── linkedList.c │ └── linkedList.h ├── JAVA │ ├── FloydCycleDetection.java │ ├── InsertGCDInLinkedList.java │ ├── IntersectionOfTwoLinkedLists.java │ ├── LinkedListNode.java │ ├── MergeSort_LinkedList.java │ ├── Problems │ │ ├── README.md │ │ └── addNumbersLeetcode.java │ ├── doublyLinkedListCombined.java │ ├── isPalindrome.java │ └── linkedListCombined.java └── python │ ├── Circular_LinkedList.py │ ├── Double LinkedList_combined.py │ ├── Double_Circular_Linkedlist.py │ ├── Reverse_Nodes_in_K_Group.py │ ├── Rotate_Linkedlist.py │ ├── insert_at_position.py │ ├── merge_sort.py │ ├── merge_sorted_list.py │ └── middle _element.py ├── Queue ├── C++ │ ├── arrayImplementation.cpp │ ├── circularQueue.cpp │ ├── deque.cpp │ ├── implementQueue.cpp │ └── linkedListImplementation.cpp ├── C │ ├── ArrayImplementation.h │ ├── Arrayimplementation.c │ ├── linkedListImplementation.c │ └── linkedListImplementation.h └── JAVA │ ├── BinaryNumbersUsingQueue.java │ ├── Maximumreversedrubarraypob.java │ ├── QueueUsingArray.java │ ├── QueueUsingArrayList.java │ ├── QueueUsingLL.java │ └── QueueUsingStack.java ├── README.md ├── Recursion ├── Euclidean_GCD.py ├── N_Queens.py ├── Subset_sum_1.py ├── Subset_sum_2.py ├── Subsets.java ├── Sudoko_solver.py ├── TowerOfHanoi.java └── is_palindrome ├── Searching_Algorithm ├── C++ │ ├── a_star_search.cpp │ ├── beam_search.cpp │ └── binary-search │ │ ├── combined.cpp │ │ ├── first-occurrence.cpp │ │ ├── iterative.cpp │ │ ├── last-occurrence.cpp │ │ ├── problem-1.cpp │ │ └── recursive.cpp ├── C │ └── Interpolation_search.c ├── JAVA │ ├── BinarySearch_UsingRecursion.java │ ├── Binary_Search.java │ ├── Binary_Searching_2D_Array.java │ ├── Linear_Search.java │ ├── Linear_search_2D_Array.java │ ├── Order_Agnoistic_Binary_search.java │ └── SearchRotatedArray.java └── PYTHON │ ├── BinarySearch_UsingRecursion.py │ ├── interpolation_search.py │ └── ternarySearch.py ├── Singleton_Class └── JAVA │ ├── type-1.java │ └── type-2.java ├── Some_important_algos ├── AllPalindromicPermutations.java ├── Anagram.java ├── CPUSchedullingForProcessAllocation.c ├── Exponentiation.java ├── KMP_algorithm.java ├── Keypad_Problems.java ├── LongestPalindromeInString.java ├── Python │ └── Bresenhams Algorithm.py ├── Return_Subsequence_String.java ├── Reversing_Array.java └── Sieve_of_Eratosthenes.java ├── Sorting Algorithms (Recursion) ├── BubbleSort.cpp ├── InsertionSort.cpp ├── LinearSearch.cpp ├── MergeSort.cpp ├── QuickSort.cpp └── SelectionSort.cpp ├── Sorting_Algorithm ├── C++ │ ├── bubble-sort.cpp │ ├── bucket-sort.cpp │ ├── count_sort.cpp │ ├── insertion-sort.cpp │ ├── merge-sort.cpp │ ├── quick-sort.cpp │ ├── radix_sort.cpp │ └── selection-sort.cpp ├── C │ ├── bubble_sort.c │ ├── combo_search_sort.c │ ├── insertion_sort.c │ └── selection_sort.c ├── JAVA │ ├── Bubble_sort.java │ ├── CountSort.java │ ├── Cycle_sort.java │ ├── HeapSort.java │ ├── Insertion_sort.java │ ├── MergeSort.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── Selection_sort.java │ └── ShellSort └── PYTHON │ ├── MergeSort.py │ ├── bubbleSort.py │ ├── quickSort.py │ └── selectionSort.py ├── Stack ├── C++ │ ├── arrayImplementation.cpp │ ├── checkBalancedParentheses.cpp │ ├── evaluatePostfix.cpp │ ├── evaluatePrefix.cpp │ ├── infixToPostfix.cpp │ └── linkedListImplementation.cpp ├── C │ ├── array based implementation │ │ ├── main.c │ │ ├── stack.c │ │ └── stack.h │ └── linked list based implementation │ │ ├── main.c │ │ ├── stack.c │ │ └── stack.h ├── JAVA │ ├── 123Pattern.java │ ├── BalancedParanthesis.java │ ├── BasicStack.java │ ├── CheckRedundantBrackets.java │ ├── CustomStack.java │ ├── DistanceNearestGreaterElementOnRight.java │ ├── DistanceNearestSmallerElementOnLeft.java │ ├── DistanceNearestSmallerElementOnRight.java │ ├── DistanceOfNearestGreaterElementOnLeft.java │ ├── DynamicStack.java │ ├── KnapSackTopDown.java │ ├── MinimumBracketReversal.java │ ├── NearestGreaterElementOnLeft.java │ ├── NearestGreaterElementOnRight.java │ ├── NearestGreaterIndexOnRight.java │ ├── NearestGreatestIndexOnLeft.java │ ├── NearestSmallerElementOnLeft.java │ ├── NearestSmallerElementOnRight.java │ ├── NearestSmallerIndexOnLeft.java │ ├── NearestSmallerIndexOnRight.java │ ├── NextGreaterToLeft.java │ ├── StackUsingArray.java │ ├── StackUsingArrayList.java │ ├── StackUsingLL.java │ ├── StackUsingQueue.java │ ├── Tower_of_Hanoi.java │ ├── infixToPrefix.java │ ├── infixTopostfix.java │ └── multipleStacks.java └── PYTHON │ ├── Queue_using_Stack.py │ └── Stack_using_Queue.py ├── ThreadedBinaryTree.c ├── Tree ├── C++ │ ├── BinaryTree │ │ ├── BinaryTree.cpp │ │ └── BoundryTraversal.cpp │ ├── Right_View_in_Binary_Tree.cpp │ ├── avlTree.cpp │ ├── checkBSTorNOT.cpp │ ├── findHeight.cpp │ ├── findMinMaxFromBST.cpp │ ├── implementBST.cpp │ └── treeTraversal.cpp ├── JAVA │ ├── verticalOrderTraversal.java │ ├── BST.java │ ├── BSTdeletereturn.java │ ├── BinaryTreeNode.java │ ├── MaxHeapImp.java │ ├── RangeSumOfBST.java │ ├── TreeNode.java │ ├── all-nodes-distance-k-in-binary-tree │ ├── findBSTheight.java │ ├── flatten_binary_tree_to_linkedlist │ ├── implementBST.java │ └── zig-zag level order traversal └── Python │ └── Binary_Tree_Maximum_Path_Sum.py ├── Trial.java ├── Tries_and_Huffman_Coding └── Trie.java └── owest-common-ancestor-of-a-binary-tree /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | Trial.java 3 | *classpath 4 | .project 5 | .settings 6 | .classpath 7 | .project 8 | .out 9 | .exe 10 | .vscode 11 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Thank you for considering contributing to the "Data Structures and Algorithms" repository! We welcome contributions from the community to help improve and expand our collection of data structures and algorithms implementations. 4 | 5 | Please take a moment to review these guidelines before getting started: 6 | 7 | ## Code of Conduct 8 | Before contributing, please read and adhere to the [Code of Conduct](https://github.com/N0vice17/DataStructures-And-Algorithm/blob/master/CODE_OF_CONDUCT.md). We expect all contributors to follow these guidelines to ensure a positive and inclusive community. 9 | 10 | ## How to Contribute 11 | 12 | 1. Fork the repository to your own GitHub account. 13 | 14 | 2. Clone the repository from your account to your local machine: 15 | ```bash 16 | git clone https://github.com/your-username/DataStructures-And-Algorithm.git 17 | ``` 18 | 19 | 3. Create a new branch for your work: 20 | ```bash 21 | git checkout -b your-branch-name 22 | ``` 23 | 24 | 4. Make sure the branch is up to date with the `master` branch of the base repository. 25 | 26 | 5. Add codes, or make suitable changes in this branch. 27 | 28 | 6. After you have made your additions, execute the following lines from the terminal. 29 | ```bash 30 | $ git add -A 31 | 32 | $ git commit -m "What you have changed write here" 33 | 34 | $ git fetch --all --prune 35 | 36 | $ git push -u origin master 37 | ``` 38 | 39 | 7. Once the changes have been committed, your are all set for creating a pull request. 40 | 41 | 8. Create a pull request from this branch to the `master` branch of the root directory, and request any one of the assigned reviewers to review your changes. 42 | 43 | 9. The PR will be merged once the changes get approved. 44 | 45 | ## Conclusion 46 | 47 | Your contributions to the "Data Structures and Algorithms" repository are highly appreciated. 48 | By following these guidelines and collaborating with our community, you are helping us build a valuable resource for developers and learners alike. 49 | Together, we can make this repository a hub for quality implementations and explanations of various data structures and algorithms. 50 | 51 | Thank you for your dedication to improving this project. Your efforts are instrumental in making "Data Structures and Algorithms" a valuable resource for the programming community. 52 | 53 | Happy coding!! 54 | -------------------------------------------------------------------------------- /Graphs/BellmanFord.java: -------------------------------------------------------------------------------- 1 | /*Given a weighted, directed and connected graph of V vertices and E edges, 2 | Find the shortest distance of all the vertex's from the source vertex S. 3 | If a vertices can't be reach from the S then marking the distance as 10^8. 4 | If the Graph contains a negative cycle then return an array consisting of only -1. 5 | Implemented the Bellman-Ford Algorithm which gives distance from source to all the vertex(containing neg edge wt) 6 | */ 7 | 8 | import java.util.*; 9 | public class BellmanFord { 10 | public static void main(String args[]){ 11 | ArrayList> adj=new ArrayList<>(); 12 | Scanner sc=new Scanner(System.in); 13 | int nodes=sc.nextInt(); //enter no of nodes in the graph 14 | int edges=sc.nextInt(); //enter no of edges in the graph 15 | int source=sc.nextInt(); //enter the source 16 | for(int i=0;i l=new ArrayList<>(); 18 | for(int j=0;j<3;j++)l.add(sc.nextInt()); 19 | adj.add(new ArrayList<>(l)); 20 | } 21 | int distn[]=bellman_ford(nodes,adj,source); 22 | for(int i=0;i> edges, int s) { 28 | int distn[]=new int[V]; 29 | Arrays.fill(distn,(int)1e8); 30 | distn[s]=0; 31 | for(int i=0;i p:edges){ 33 | int u=p.get(0); 34 | int v=p.get(1); 35 | int wt=p.get(2); 36 | if(distn[u]!=(int)1e8 && distn[u]+wt p:edges){ 42 | int u=p.get(0); 43 | int v=p.get(1); 44 | int wt=p.get(2); 45 | if(distn[u]!=(int)1e8 && distn[u]+wt 55 | 3 56 | 4 57 | 2 58 | 0 1 5 //u v w means there is an edge from u to v with weight of w 59 | 1 0 3 60 | 1 2 -1 61 | 2 0 1 62 | 63 | --graph intution-- 64 | 0--(5)-->1 65 | 0<--(3)---1--(-1)-->2--(1)-->0 66 | 67 | 68 | o/p--> 69 | Shortest Distance from 2 to 0 is: 1 70 | Shortest Distance from 2 to 1 is: 6 71 | Shortest Distance from 2 to 2 is: 0 72 | 73 | Time Complexity: O(V*E) where V and E are no of vertices and edges respectively 74 | Space Complexity: O(V) 75 | 76 | */ -------------------------------------------------------------------------------- /Graphs/Bipartite.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given an adjacency list of a graph adj of V no. of vertices having 0 based index. Check whether the graph is bipartite or not. 3 | 4 | If we are able to colour a graph with two colours such that no adjacent nodes have the same colour, it is called a bipartite graph. 5 | */ 6 | 7 | import java.util.*; 8 | 9 | class Solution 10 | { 11 | private boolean dfs(int node, int col, int color[], 12 | ArrayList>adj) { 13 | 14 | color[node] = col; 15 | 16 | // traverse adjacent nodes 17 | for(int it : adj.get(node)) { 18 | // if uncoloured 19 | if(color[it] == -1) { 20 | if(dfs(it, 1 - col, color, adj) == false) return false; 21 | } 22 | // if previously coloured and have the same colour 23 | else if(color[it] == col) { 24 | return false; 25 | } 26 | } 27 | 28 | return true; 29 | } 30 | public boolean isBipartite(int V, ArrayList>adj) 31 | { 32 | int color[] = new int[V]; 33 | for(int i = 0;i> adj = new ArrayList < > (); 47 | for (int i = 0; i < 4; i++) { 48 | adj.add(new ArrayList < > ()); 49 | } 50 | adj.get(0).add(2); 51 | adj.get(2).add(0); 52 | adj.get(0).add(3); 53 | adj.get(3).add(0); 54 | adj.get(1).add(3); 55 | adj.get(3).add(1); 56 | adj.get(2).add(3); 57 | adj.get(3).add(2); 58 | 59 | Solution obj = new Solution(); 60 | boolean ans = obj.isBipartite(4, adj); 61 | if(ans) 62 | System.out.println("1"); 63 | else System.out.println("0"); 64 | } 65 | 66 | } 67 | 68 | /* 69 | Output: 0 70 | 71 | Time Complexity: O(V + 2E), Where V = Vertices, 2E is for total degrees as we traverse all adjacent nodes. 72 | 73 | Space Complexity: O(3V) ~ O(V), Space for DFS stack space, colour array and an adjacency list. 74 | */ 75 | -------------------------------------------------------------------------------- /Graphs/DijkstraAlgo.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class DijkstraAlgo { 5 | public static int minvertex(boolean visited[], int distance[]) { 6 | int minvertex = Integer.MAX_VALUE; 7 | for (int i = 0; i < visited.length; i++) { 8 | if (!visited[i] && (minvertex == Integer.MAX_VALUE || distance[i] < distance[minvertex])) { 9 | minvertex = i; 10 | } 11 | } 12 | return minvertex; 13 | } 14 | 15 | public static void Dijkstra(int[][] arr) { 16 | boolean visited[] = new boolean[arr.length]; 17 | int distance[] = new int[arr.length]; 18 | for (int i = 0; i < arr.length; i++) { 19 | visited[i] = false; 20 | distance[i] = Integer.MAX_VALUE; 21 | } 22 | distance[0] = 0; 23 | for (int i = 0; i < arr.length; i++) { 24 | int minvert = minvertex(visited, distance); 25 | visited[minvert] = true; 26 | for (int j = 0; j < arr.length; j++) { 27 | if (!visited[j] && arr[minvert][j] != 0 && distance[minvert] + arr[minvert][j] < distance[j]) { 28 | distance[j] = distance[minvert] + arr[minvert][j]; 29 | } 30 | } 31 | } 32 | System.out.println("Printing the minimum Distance From the Source of Every vertex"); 33 | for (int i = 0; i < arr.length; i++) { 34 | System.out.println(i + " " + distance[i]); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | Scanner input = new Scanner(System.in); 40 | int v = input.nextInt(); 41 | int e = input.nextInt(); 42 | int arr[][] = new int[v][v]; 43 | for (int i = 0; i < e; i++) { 44 | int vertex1 = input.nextInt(); 45 | int vertex2 = input.nextInt(); 46 | int weight = input.nextInt(); 47 | arr[vertex1][vertex2] = weight; 48 | arr[vertex2][vertex1] = weight; 49 | } 50 | Dijkstra(arr); 51 | } 52 | } -------------------------------------------------------------------------------- /Graphs/Floyd-Warshall-Algo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: - 3 | The problem is to find the shortest distances between every pair of vertices in a given edge-weighted directed graph. The graph is represented as an adjacency matrix of size n*n. Matrix[i][j] denotes the weight of the edge from i to j. If Matrix[i][j]=-1, it means there is no edge from i to j. 4 | */ 5 | 6 | import java.util.*; 7 | class Solution { 8 | public void shortest_distance(int[][] matrix) { 9 | int n = matrix.length; 10 | for (int i = 0; i < n; i++) { 11 | for (int j = 0; j < n; j++) { 12 | if (matrix[i][j] == -1) { 13 | matrix[i][j] = (int)(1e9); 14 | } 15 | if (i == j) matrix[i][j] = 0; 16 | } 17 | } 18 | 19 | for (int k = 0; k < n; k++) { 20 | for (int i = 0; i < n; i++) { 21 | for (int j = 0; j < n; j++) { 22 | matrix[i][j] = Math.min(matrix[i][j], 23 | matrix[i][k] + matrix[k][j]); 24 | } 25 | } 26 | } 27 | 28 | for (int i = 0; i < n; i++) { 29 | for (int j = 0; j < n; j++) { 30 | if (matrix[i][j] == (int)(1e9)) { 31 | matrix[i][j] = -1; 32 | } 33 | } 34 | } 35 | } 36 | } 37 | 38 | public class tUf { 39 | public static void main(String[] args) { 40 | int V = 4; 41 | int[][] matrix = new int[V][V]; 42 | 43 | for (int i = 0; i < V; i++) { 44 | for (int j = 0; j < V; j++) { 45 | matrix[i][j] = -1; 46 | } 47 | } 48 | 49 | matrix[0][1] = 2; 50 | matrix[1][0] = 1; 51 | matrix[1][2] = 3; 52 | matrix[3][0] = 3; 53 | matrix[3][1] = 5; 54 | matrix[3][2] = 4; 55 | 56 | Solution obj = new Solution(); 57 | obj.shortest_distance(matrix); 58 | 59 | for (int i = 0; i < V; i++) { 60 | for (int j = 0; j < V; j++) { 61 | System.out.print(matrix[i][j] + " "); 62 | } 63 | System.out.println(""); 64 | } 65 | } 66 | } 67 | 68 | /* 69 | Output: 70 | 71 | 0 2 5 -1 72 | 1 0 3 -1 73 | -1 -1 0 -1 74 | 3 5 4 0 75 | 76 | Time Complexity: O(V3), as we have three nested loops each running for V times, where V = no. of vertices. 77 | 78 | Space Complexity: O(V2), where V = no. of vertices. This space complexity is due to storing the adjacency matrix of the given graph. 79 | */ 80 | -------------------------------------------------------------------------------- /Graphs/Kosaraju’s_Algo.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | 5 | 6 | //User function Template for Java 7 | 8 | 9 | class Solution { 10 | private void dfs(int node, int []vis, ArrayList> adj, 11 | Stack st) { 12 | vis[node] = 1; 13 | for (Integer it : adj.get(node)) { 14 | if (vis[it] == 0) { 15 | dfs(it, vis, adj, st); 16 | } 17 | } 18 | st.push(node); 19 | } 20 | private void dfs3(int node, int[] vis, ArrayList> adjT) { 21 | vis[node] = 1; 22 | for (Integer it : adjT.get(node)) { 23 | if (vis[it] == 0) { 24 | dfs3(it, vis, adjT); 25 | } 26 | } 27 | } 28 | //Function to find number of strongly connected components in the graph. 29 | public int kosaraju(int V, ArrayList> adj) { 30 | int[] vis = new int[V]; 31 | Stack st = new Stack(); 32 | for (int i = 0; i < V; i++) { 33 | if (vis[i] == 0) { 34 | dfs(i, vis, adj, st); 35 | } 36 | } 37 | 38 | ArrayList> adjT = new ArrayList>(); 39 | for (int i = 0; i < V; i++) { 40 | adjT.add(new ArrayList()); 41 | } 42 | for (int i = 0; i < V; i++) { 43 | vis[i] = 0; 44 | for (Integer it : adj.get(i)) { 45 | // i -> it 46 | // it -> i 47 | adjT.get(it).add(i); 48 | } 49 | } 50 | int scc = 0; 51 | while (!st.isEmpty()) { 52 | int node = st.peek(); 53 | st.pop(); 54 | if (vis[node] == 0) { 55 | scc++; 56 | dfs3(node, vis, adjT); 57 | } 58 | } 59 | return scc; 60 | } 61 | } 62 | 63 | class Main { 64 | public static void main (String[] args) { 65 | int n = 5; 66 | int[][] edges = { 67 | {1, 0}, {0, 2}, 68 | {2, 1}, {0, 3}, 69 | {3, 4} 70 | }; 71 | ArrayList> adj = new ArrayList<>(); 72 | for (int i = 0; i < n; i++) { 73 | adj.add(new ArrayList()); 74 | } 75 | for (int i = 0; i < n; i++) { 76 | adj.get(edges[i][0]).add(edges[i][1]); 77 | } 78 | Solution obj = new Solution(); 79 | int ans = obj.kosaraju(n, adj); 80 | System.out.println("The number of strongly connected components is: " + ans); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Graphs/KruskalsAlgo.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | class Edge implements Comparable { 5 | public int vertex1, vertex2, weight; 6 | 7 | public Edge(int vertex1, int vertex2, int weight) { 8 | this.vertex1 = vertex1; 9 | this.vertex2 = vertex2; 10 | this.weight = weight; 11 | } 12 | 13 | public int compareTo(Edge o) { 14 | if (weight == o.weight) { 15 | return 0; 16 | } 17 | if (weight > o.weight) { 18 | return 1; 19 | } 20 | return -1; 21 | } 22 | 23 | } 24 | 25 | public class KruskalsAlgo { 26 | public static int union(int vert, int parents[]) { 27 | if (parents[vert] == vert) { 28 | return vert; 29 | } 30 | return union(parents[vert], parents); 31 | } 32 | 33 | public static void kruskal(Edge arr[], int length) { 34 | ArrayList ans = new ArrayList<>(); 35 | int parents[] = new int[arr.length]; 36 | for (int i = 0; i < parents.length; i++) { 37 | parents[i] = i; 38 | } 39 | Arrays.sort(arr); 40 | int count = 0, ind = 0; 41 | while (count != length - 1) { 42 | int vert1 = union(arr[ind].vertex1, parents); 43 | int vert2 = union(arr[ind].vertex2, parents); 44 | if (vert1 != vert2) { 45 | ans.add(arr[ind]); 46 | parents[vert1] = vert2; 47 | count += 1; 48 | } 49 | ind += 1; 50 | } 51 | for (Edge it : ans) { 52 | System.out.println(it.vertex1 + " " + it.vertex2 + " " + it.weight); 53 | } 54 | } 55 | 56 | public static void main(String[] args) { 57 | Scanner input = new Scanner(System.in); 58 | int v = input.nextInt(); 59 | int e = input.nextInt(); 60 | Edge arr[] = new Edge[e]; 61 | for (int i = 0; i < arr.length; i++) { 62 | int vertex1 = input.nextInt(); 63 | int vertex2 = input.nextInt(); 64 | int weight = input.nextInt(); 65 | Edge inputvert = new Edge(vertex1, vertex2, weight); 66 | arr[i] = inputvert; 67 | } 68 | System.out.println("Printing the MST"); 69 | kruskal(arr, v); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Graphs/PrimsAlgo.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class PrimsAlgo { 5 | public static int minvertex(boolean[] visited, int weight[]) { 6 | int minvertex = -1; 7 | for (int i = 0; i < visited.length; i++) { 8 | if (!visited[i] && (minvertex == -1 || weight[i] < weight[minvertex])) { 9 | minvertex = i; 10 | } 11 | } 12 | return minvertex; 13 | } 14 | 15 | public static void Prim(int[][] arr) { 16 | boolean visited[] = new boolean[arr.length]; 17 | int parent[] = new int[arr.length]; 18 | int weight[] = new int[arr.length]; 19 | for (int i = 1; i < arr.length; i++) { 20 | weight[i] = Integer.MAX_VALUE; 21 | } 22 | parent[0] = -1; 23 | weight[0] = 0; 24 | for (int i = 0; i < arr.length; i++) { 25 | int minvert = minvertex(visited, weight); 26 | visited[minvert] = true; 27 | for (int j = 0; j < arr.length; j++) { 28 | if (arr[minvert][j] != 0 && !visited[j]) { 29 | if (weight[j] > arr[minvert][j]) { 30 | parent[j] = minvert; 31 | weight[j] = arr[minvert][j]; 32 | } 33 | } 34 | } 35 | } 36 | System.out.println("Printing the MST"); 37 | for (int i = 1; i < arr.length; i++) { 38 | System.out.println(i + " " + parent[i] + " " + weight[i]); 39 | } 40 | } 41 | 42 | public static void main(String[] args) { 43 | Scanner input = new Scanner(System.in); 44 | int v = input.nextInt(); 45 | int e = input.nextInt(); 46 | int[][] arr = new int[v][v]; 47 | for (int i = 0; i < e; i++) { 48 | int vertex1 = input.nextInt(); 49 | int vertex2 = input.nextInt(); 50 | int weight = input.nextInt(); 51 | arr[vertex1][vertex2] = weight; 52 | arr[vertex2][vertex1] = weight; 53 | } 54 | Prim(arr); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /LinkedList/C++/palindrome check in linkedlist: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Node{ 5 | public: 6 | int val; 7 | Node *next; 8 | }; 9 | Node* newnode(int val){ 10 | Node *head=new Node; 11 | head->val=val; 12 | head->next=NULL; 13 | return head; 14 | } 15 | Node findmiddle(Node head){ 16 | Node *slow=head,*fast=head; 17 | while(fast!=NULL&&fast->next!=NULL){ 18 | fast=fast->next->next; 19 | slow=slow->next; 20 | } 21 | return slow; 22 | } 23 | Node *reverse(Node *head){ 24 | Node *curr=head,*prev=NULL,*future=NULL; 25 | while(curr!=NULL){ 26 | future=curr->next; 27 | curr->next=prev; 28 | prev=curr; 29 | curr=future; 30 | } 31 | return prev; 32 | } 33 | bool ispal(Node *head1,Node *head2){ 34 | while(head1!=NULL&&head2!=NULL){ 35 | if(head1->val!=head2->val) return false; 36 | else if(head1->val==head2->val){ 37 | head1=head1->next; 38 | head2=head2->next; 39 | } 40 | } 41 | return true; 42 | } 43 | int main() { 44 | int n; 45 | cin>>n; 46 | int data; 47 | cin>>data; 48 | Node *head=newnode(data); 49 | Node *tail=head; 50 | for(int i=0;i>data; 52 | tail->next=newnode(data); 53 | tail=tail->next; 54 | } 55 | Node *head1=head; 56 | Node *mid=findmiddle(head); 57 | Node *head2=reverse(mid); 58 | bool compare=ispal(head1,head2); 59 | if(compare==true) cout<<"true"<data != x) 6 | p = p->next; 7 | return (p); 8 | } 9 | 10 | void linked_list_insert(Node *p, Node *q) 11 | { 12 | p->next = q->next; 13 | q->next = p; 14 | } 15 | 16 | void linked_list_delete(Node *p) 17 | { 18 | p->next = p->next->next; 19 | } 20 | 21 | void linked_list_insert_at(Node *p, Node *q, int position) 22 | { 23 | if (position == 0) 24 | return (linked_list_insert(q, p)); 25 | 26 | int i = 0; 27 | while (i < position && q) 28 | q = q->next; 29 | return (linked_list_insert(p, q)); 30 | } 31 | 32 | void linked_list_delete_at(Node *p, int position) 33 | { 34 | if (position == 0) 35 | return; 36 | 37 | int i = 0; 38 | while (i < position && p) 39 | p = p->next; 40 | 41 | if (p && p->next) 42 | return (linked_list_delete(p)); 43 | } 44 | -------------------------------------------------------------------------------- /LinkedList/C/linkedList.h: -------------------------------------------------------------------------------- 1 | #ifndef LINKEDLIST_H 2 | #define LINKEDLIST_H 3 | 4 | typedef struct Node 5 | { 6 | 7 | int data; 8 | struct Node *next; 9 | 10 | } Node; 11 | 12 | /* 13 | * Given an integer x and a node p, 14 | * return the address of the first node 15 | * where data is x or NULL if it doens't exists. 16 | */ 17 | Node *linked_list_search(int x, Node *p); 18 | 19 | /* 20 | * Given two nodes p and q, 21 | * inserts p between q and q.next 22 | */ 23 | void linked_list_insert(Node *p, Node *q); 24 | void linked_list_insert_at(Node *p, Node *q, int position); 25 | 26 | /* 27 | * Given a node p, removes p.next from the list 28 | */ 29 | void linked_list_delete(Node *p); 30 | void linked_list_delete_at(Node *p, int position); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /LinkedList/JAVA/InsertGCDInLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given the head of a linked list head, in which each node contains an integer value. 3 | 4 | Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them. 5 | 6 | Return the linked list after insertion. 7 | 8 | The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | 15 | Input: head = [18,6,10,3] 16 | Output: [18,6,6,2,10,1,3] 17 | Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes). 18 | - We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes. 19 | - We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes. 20 | - We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes. 21 | There are no more adjacent nodes, so we return the linked list. 22 | */ 23 | 24 | public class InsertGCDInLinkedList { 25 | static int findGCD(int n1, int n2) { 26 | int rem = n1%n2; 27 | while(rem > 0) { 28 | n1 = n2; 29 | n2 = rem; 30 | rem = n1%n2; 31 | } 32 | 33 | return n2; 34 | } 35 | public ListNode insertGreatestCommonDivisors(ListNode head) { 36 | if(head == null || head.next == null) return head; 37 | 38 | ListNode temp = head; 39 | 40 | while(temp.next != null) { 41 | int gcd = findGCD(temp.data, temp.next.data); 42 | ListNode n = new ListNode(gcd, temp.next); 43 | temp.next = n; 44 | temp = temp.next.next; 45 | } 46 | 47 | return head; 48 | } 49 | 50 | } 51 | 52 | class ListNode { 53 | int data; 54 | ListNode next; 55 | 56 | public ListNode() {} 57 | 58 | public ListNode(int data) { 59 | this.data = data; 60 | this.next = null; 61 | } 62 | 63 | public ListNode(int data, ListNode next) { 64 | this.data = data; 65 | this.next = next; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /LinkedList/JAVA/MergeSort_LinkedList.java: -------------------------------------------------------------------------------- 1 | public class MergeSort_LinkedList { 2 | public static LinkedListNode merge(LinkedListNode left, LinkedListNode right){ 3 | if(left==null){ 4 | return right; 5 | } 6 | if(right==null){ 7 | return left; 8 | } 9 | LinkedListNode ans=new LinkedListNode(-1); 10 | LinkedListNode temp=ans; 11 | while(left!=null&&right!=null){ 12 | if(left.data<=right.data){ 13 | temp.next=left; 14 | temp=left; 15 | left=left.next; 16 | } 17 | else{ 18 | temp.next=right; 19 | temp=right; 20 | right=right.next; 21 | } 22 | } 23 | while(left!=null){ 24 | temp.next=left; 25 | temp=left; 26 | left=left.next; 27 | } 28 | while(right!=null){ 29 | temp.next=right; 30 | temp=right; 31 | right=right.next; 32 | } 33 | ans=ans.next; 34 | return ans; 35 | } 36 | public static LinkedListNode MergeSort(LinkedListNode head){ 37 | if(head==null||head.next==null){ 38 | return head; 39 | } 40 | LinkedListNode slow=head; 41 | LinkedListNode fast=head; 42 | while(fast.next!=null&&fast.next.next!=null){ 43 | slow=slow.next; 44 | fast=fast.next.next; 45 | } 46 | LinkedListNode left=head; 47 | LinkedListNode right=slow.next; 48 | slow.next=null; 49 | left=MergeSort(left); 50 | right=MergeSort(right); 51 | LinkedListNode result=merge(left,right); 52 | return result; 53 | } 54 | public static void main(String[]args){ 55 | LinkedListNode six=new LinkedListNode(1,null); 56 | LinkedListNode five=new LinkedListNode(2,six); 57 | LinkedListNode four=new LinkedListNode(3,five); 58 | LinkedListNode three=new LinkedListNode(4,four); 59 | LinkedListNode two=new LinkedListNode(5,three); 60 | LinkedListNode one=new LinkedListNode(6,two); 61 | LinkedListNode head=MergeSort(one); 62 | LinkedListNode.printList(head); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /LinkedList/JAVA/Problems/README.md: -------------------------------------------------------------------------------- 1 | # Problem 2 | You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 3 | 4 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 5 | 6 | ### Example 1 7 | ![Example Image 1](https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg) 8 | 9 | ```md 10 | 11 | **Input**: l1 = [2,4,3], l2 = [5,6,4] 12 | **Output**: [7,0,8] 13 | **Explanation**: 342 + 465 = 807. 14 | 15 | ``` 16 | 17 | ### Example 2 18 | 19 | ```md 20 | 21 | **Input**: l1 = [0], l2 = [0] 22 | **Output**: [0] 23 | 24 | ``` 25 | 26 | ### Example 3 27 | 28 | ```md 29 | 30 | **Input**: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 31 | **Output**: [8,9,9,9,0,0,0,1] 32 | 33 | ``` 34 | 35 | ### Constraints 36 | - The number of nodes in each linked list is in the range `[1, 100]`. 37 | - `0 <= Node.val <= 9` 38 | - It is guaranteed that the list represents a number that does not have leading zeros. 39 | 40 | -------------------------------------------------------------------------------- /LinkedList/JAVA/Problems/addNumbersLeetcode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public class ListNode { 13 | public int val; 14 | public ListNode next; 15 | 16 | public ListNode() { 17 | 18 | } 19 | 20 | public ListNode(int val) { 21 | this.val = val; 22 | } 23 | 24 | ListNode(int val, ListNode next) { 25 | this.val = val; 26 | this.next = next; 27 | } 28 | } 29 | 30 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 31 | ListNode temp1 = new ListNode(0); 32 | ListNode temp2 = temp1; 33 | int carryOver = 0; 34 | while (l1 != null || l2 != null) { 35 | int digit1 = (l1 != null) ? l1.val : 0; 36 | int digit2 = (l2 != null) ? l2.val : 0; 37 | int sum = carryOver + digit1 + digit2; 38 | carryOver = sum / 10; 39 | temp2.next = new ListNode(sum % 10); 40 | temp2 = temp2.next; 41 | if (l1 != null) 42 | l1 = l1.next; 43 | if (l2 != null) 44 | l2 = l2.next; 45 | } 46 | if (carryOver > 0) 47 | temp2.next = new ListNode(carryOver); 48 | return temp1.next; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LinkedList/JAVA/isPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given the head of a singly linked list, return true if it is a palindrome. 3 | 4 | Examples: 5 | 6 | Example 1: 7 | Input: head = [1,2,3,3,2,1] 8 | Output: 9 | true 10 | Explanation: If we read elements from left to right, we get [1,2,3,3,2,1]. When we read elements from right to left, we get [1,2,3,3,2,1]. Both ways list remains same and hence, the given linked list is palindrome. 11 | */ 12 | 13 | import java.util.*; 14 | class Node { 15 | int num; 16 | Node next; 17 | Node(int val) { 18 | num = val; 19 | next = null; 20 | } 21 | } 22 | class TUF{ 23 | static Node insertNode(Node head,int val) { 24 | Node newNode = new Node(val); 25 | if(head == null) { 26 | head = newNode; 27 | return head; 28 | } 29 | 30 | Node temp = head; 31 | while(temp.next != null) temp = temp.next; 32 | 33 | temp.next = newNode; 34 | return head; 35 | } 36 | 37 | static Node reverse(Node ptr) { 38 | Node pre=null; 39 | Node nex=null; 40 | while(ptr!=null) { 41 | nex = ptr.next; 42 | ptr.next = pre; 43 | pre=ptr; 44 | ptr=nex; 45 | } 46 | return pre; 47 | } 48 | 49 | static boolean isPalindrome(Node head) { 50 | if(head==null||head.next==null) return true; 51 | 52 | Node slow = head; 53 | Node fast = head; 54 | 55 | while(fast.next!=null&&fast.next.next!=null) { 56 | slow = slow.next; 57 | fast = fast.next.next; 58 | } 59 | 60 | slow.next = reverse(slow.next); 61 | slow = slow.next; 62 | Node dummy = head; 63 | 64 | while(slow!=null) { 65 | if(dummy.num != slow.num) return false; 66 | dummy = dummy.next; 67 | slow = slow.next; 68 | } 69 | return true; 70 | } 71 | 72 | public static void main(String args[]) { 73 | Node head = null; 74 | head=insertNode(head,1); 75 | head=insertNode(head,2); 76 | head=insertNode(head,3); 77 | head=insertNode(head,2); 78 | head=insertNode(head,1); 79 | if(isPalindrome(head)==true) 80 | System.out.println("True"); 81 | else 82 | System.out.println("False"); 83 | 84 | } 85 | } 86 | 87 | /* 88 | Output: True 89 | 90 | Time Complexity: O(N/2)+O(N/2)+O(N/2) 91 | 92 | Reason: O(N/2) for finding the middle element, reversing the list from the middle element, and traversing again to find palindrome respectively. 93 | 94 | Space Complexity: O(1) 95 | 96 | Reason: No extra data structures are used. 97 | */ 98 | -------------------------------------------------------------------------------- /LinkedList/python/Reverse_Nodes_in_K_Group.py: -------------------------------------------------------------------------------- 1 | # Title: 92. Reverse Linked List II 2 | # Difficulty: Medium 3 | # Problem: https://leetcode.com/problems/reverse-linked-list-ii/description/ 4 | 5 | ## Changing the values of the node 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode: 9 | # def __init__(self, val=0, next=None): 10 | # self.val = val 11 | # self.next = next 12 | class Solution: 13 | def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 14 | # create a dummy head for cases with left = 1 15 | dummy = ListNode(next=head) 16 | 17 | # reach the left node 18 | counter = left - 1 19 | node = head 20 | while counter: 21 | node = node.next 22 | counter -= 1 23 | 24 | # store the values of the node between left and right (inclusive) 25 | values = [] 26 | start = node 27 | counter = right - left + 1 28 | while counter: 29 | values.append(node.val) 30 | node = node.next 31 | counter -= 1 32 | 33 | # fill the reversed values 34 | counter = right - left + 1 35 | while counter: 36 | start.val = values[counter-1] 37 | start = start.next 38 | counter -= 1 39 | 40 | return dummy.next 41 | 42 | ## Changing the nodes 43 | 44 | # Definition for singly-linked list. 45 | # class ListNode: 46 | # def __init__(self, val=0, next=None): 47 | # self.val = val 48 | # self.next = next 49 | class Solution: 50 | def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 51 | if not head: 52 | return None 53 | cur, prev = head, None 54 | while left >1: 55 | prev = cur 56 | cur = cur.next 57 | left -= 1 58 | right -=1 59 | tail, con = cur, prev 60 | 61 | while right: 62 | cur.next, prev, cur = prev, cur, cur.next 63 | right -=1 64 | 65 | if con: 66 | con.next = prev 67 | else: 68 | head = prev 69 | tail.next = cur 70 | return head 71 | -------------------------------------------------------------------------------- /LinkedList/python/Rotate_Linkedlist.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data 4 | self.next = None 5 | 6 | 7 | def rotate(head,k): 8 | 9 | last = head 10 | temp = head 11 | 12 | 13 | if head == None or k == 0: 14 | return head 15 | 16 | 17 | while last.next != None: 18 | last = last.next 19 | 20 | 21 | while k: 22 | 23 | head = head.next 24 | 25 | 26 | temp.next = None 27 | 28 | 29 | last.next = temp 30 | last = temp 31 | 32 | 33 | temp = head 34 | k -= 1 35 | return head 36 | 37 | def printList(head): 38 | temp = head 39 | while temp: 40 | print(temp.data, end = ' ') 41 | temp = temp.next 42 | print() 43 | 44 | def push(head,new_data): 45 | 46 | new_node = Node(new_data) 47 | 48 | 49 | new_node.next = head 50 | 51 | 52 | head = new_node 53 | return head 54 | 55 | head = None 56 | 57 | for i in range(60,0,-10): 58 | head = push(head,i) 59 | 60 | print("Given linked list: ") 61 | printList(head) 62 | head = rotate(head,4) 63 | 64 | print("Rotated linked list: ") 65 | printList(head) -------------------------------------------------------------------------------- /LinkedList/python/insert_at_position.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def insert_at_position(head, value, position): 7 | new_node = ListNode(value) 8 | 9 | # Insert at the beginning if the position is 1 10 | if position == 1: 11 | new_node.next = head 12 | return new_node 13 | 14 | current = head 15 | count = 1 16 | 17 | # Traverse the linked list to find the position before insertion 18 | while current and count < position - 1: 19 | current = current.next 20 | count += 1 21 | 22 | # Check if the position is out of bounds 23 | if not current: 24 | print(f"Position {position} is out of bounds.") 25 | return head 26 | 27 | # Insert the new node at the specified position 28 | new_node.next = current.next 29 | current.next = new_node 30 | 31 | return head 32 | 33 | def print_linked_list(head): 34 | current = head 35 | while current: 36 | print(current.val, end=" -> ") 37 | current = current.next 38 | print("None") 39 | 40 | # Input: Read a list of numbers separated by spaces 41 | input_list = input("Enter a list of numbers separated by spaces: ").split() 42 | input_list = [int(x) for x in input_list] 43 | 44 | # Create a linked list from the input: 1 -> 2 -> 4 -> 5 45 | head = None 46 | current = None 47 | for val in input_list: 48 | if not head: 49 | head = ListNode(val) 50 | current = head 51 | else: 52 | current.next = ListNode(val) 53 | current = current.next 54 | 55 | print("\nOriginal Linked List:") 56 | print_linked_list(head) 57 | 58 | # Input: Read the value and position to insert 59 | insert_value = int(input("Enter the value to insert: ")) 60 | insert_position = int(input("Enter the position to insert: ")) 61 | 62 | # Insert the value at the specified position 63 | new_head = insert_at_position(head, insert_value, insert_position) 64 | print("\nLinked List After Insertion:") 65 | print_linked_list(new_head) 66 | -------------------------------------------------------------------------------- /LinkedList/python/merge_sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Author: hariom09090 3 | ''' 4 | 5 | def merge_sort(arr): 6 | # Base case: if the list has more than one element 7 | if len(arr) > 1: 8 | mid = len(arr) // 2 9 | 10 | # Divide the list into two halves 11 | left_half = arr[:mid] 12 | right_half = arr[mid:] 13 | 14 | # Recursively apply merge_sort to both halves 15 | merge_sort(left_half) 16 | merge_sort(right_half) 17 | 18 | i = j = k = 0 19 | 20 | while i < len(left_half) and j < len(right_half): 21 | if left_half[i] < right_half[j]: 22 | arr[k] = left_half[i] 23 | i += 1 24 | else: 25 | arr[k] = right_half[j] 26 | j += 1 27 | k += 1 28 | 29 | # Check if any elements were left 30 | while i < len(left_half): 31 | arr[k] = left_half[i] 32 | i += 1 33 | k += 1 34 | 35 | while j < len(right_half): 36 | arr[k] = right_half[j] 37 | j += 1 38 | k += 1 39 | 40 | if __name__ == "__main__": 41 | input_list = input("Enter a list of numbers separated by spaces: ").split() 42 | input_list = [int(x) for x in input_list] 43 | 44 | merge_sort(input_list) 45 | 46 | print("Sorted list:", input_list) 47 | -------------------------------------------------------------------------------- /LinkedList/python/merge_sorted_list.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def merge_sorted_lists(l1, l2): 7 | # Create a dummy node to simplify the code 8 | dummy = ListNode() 9 | current = dummy 10 | 11 | while l1 and l2: 12 | if l1.val < l2.val: 13 | current.next = l1 14 | l1 = l1.next 15 | else: 16 | current.next = l2 17 | l2 = l2.next 18 | current = current.next 19 | 20 | # Attach any remaining elements from l1 or l2 21 | if l1: 22 | current.next = l1 23 | if l2: 24 | current.next = l2 25 | 26 | return dummy.next 27 | 28 | def print_linked_list(head): 29 | current = head 30 | while current: 31 | print(current.val, end=" -> ") 32 | current = current.next 33 | print("None") 34 | 35 | # Input: Read two lists of sorted numbers separated by spaces 36 | input_list1 = input("Enter the first sorted list of numbers separated by spaces: ").split() 37 | input_list2 = input("Enter the second sorted list of numbers separated by spaces: ").split() 38 | 39 | # Convert input to integer lists 40 | list1 = [int(x) for x in input_list1] 41 | list2 = [int(x) for x in input_list2] 42 | 43 | # Create two sorted linked lists from the input 44 | l1 = None 45 | l2 = None 46 | 47 | # Create the first linked list (l1) 48 | for val in list1: 49 | if not l1: 50 | l1 = ListNode(val) 51 | current = l1 52 | else: 53 | current.next = ListNode(val) 54 | current = current.next 55 | 56 | # Create the second linked list (l2) 57 | for val in list2: 58 | if not l2: 59 | l2 = ListNode(val) 60 | current = l2 61 | else: 62 | current.next = ListNode(val) 63 | current = current.next 64 | 65 | print("\nSorted Linked List 1:") 66 | print_linked_list(l1) 67 | 68 | print("\nSorted Linked List 2:") 69 | print_linked_list(l2) 70 | 71 | # Merge the two sorted linked lists 72 | merged_list = merge_sorted_lists(l1, l2) 73 | print("\nMerged Sorted Linked List:") 74 | print_linked_list(merged_list) 75 | -------------------------------------------------------------------------------- /LinkedList/python/middle _element.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def find_middle(head): 7 | if not head: 8 | return None 9 | 10 | slow_ptr = head 11 | fast_ptr = head 12 | 13 | # Use the slow and fast pointer technique to find the middle element 14 | while fast_ptr and fast_ptr.next: 15 | slow_ptr = slow_ptr.next 16 | fast_ptr = fast_ptr.next.next 17 | 18 | return slow_ptr 19 | 20 | def print_linked_list(head): 21 | current = head 22 | while current: 23 | print(current.val, end=" -> ") 24 | current = current.next 25 | print("None") 26 | 27 | # Input: Read a list of numbers separated by spaces 28 | input_list = input("Enter a list of numbers separated by spaces: ").split() 29 | input_list = [int(x) for x in input_list] 30 | 31 | # Create a linked list from the input 32 | head = None 33 | current = None 34 | for val in input_list: 35 | if not head: 36 | head = ListNode(val) 37 | current = head 38 | else: 39 | current.next = ListNode(val) 40 | current = current.next 41 | 42 | print("\nOriginal Linked List:") 43 | print_linked_list(head) 44 | 45 | # Find the middle element of the linked list 46 | middle_node = find_middle(head) 47 | if middle_node: 48 | print("\nMiddle Element:", middle_node.val) 49 | else: 50 | print("\nList is empty") 51 | -------------------------------------------------------------------------------- /Queue/C++/arrayImplementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define n 10 3 | using namespace std; 4 | class Queue 5 | { 6 | int arr[n]; 7 | int front = -1, rear = -1; 8 | public: 9 | bool isEmpty() 10 | { 11 | return (front == -1 && rear == -1); 12 | } 13 | bool isFull() 14 | { 15 | return (((rear + 1) % n) == front); 16 | } 17 | void enqueue(int data) 18 | { 19 | if (isFull()) 20 | exit(1); 21 | if (isEmpty()) 22 | front = rear = 0; 23 | else 24 | rear = (rear + 1) % n; 25 | arr[rear] = data; 26 | } 27 | void dequeue() 28 | { 29 | if (isEmpty()) 30 | exit(2); 31 | else if (front == rear) 32 | rear = front = -1; 33 | else 34 | front = (front + 1) % n; 35 | } 36 | int peek() 37 | { 38 | if (front == -1) 39 | exit(3); 40 | return arr[front]; 41 | } 42 | }; 43 | int main() 44 | { 45 | Queue q; 46 | q.enqueue(1); 47 | q.enqueue(2); 48 | q.enqueue(3); 49 | q.dequeue(); 50 | cout << q.peek(); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Queue/C++/circularQueue.cpp: -------------------------------------------------------------------------------- 1 | class CircularQueue{ 2 | int *arr; 3 | int front; 4 | int rear; 5 | int size; 6 | 7 | public: 8 | // Initialize your data structure. 9 | CircularQueue(int n){ 10 | size = n; 11 | arr = new int[size]; 12 | front = rear = -1; 13 | } 14 | 15 | // Enqueues 'X' into the queue. Returns true if it gets pushed into the stack, and false otherwise. 16 | bool enqueue(int value){ 17 | //to check whther queue is full 18 | if( (front == 0 && rear == size-1) || (rear == (front-1)%(size-1) ) ) { 19 | //cout << "Queue is Full"; 20 | return false; 21 | } 22 | else if(front == -1) //first element to push 23 | { 24 | front = rear = 0; 25 | 26 | } 27 | else if(rear == size-1 && front != 0) { 28 | rear = 0; //to maintain cyclic nature 29 | } 30 | else 31 | {//normal flow 32 | rear++; 33 | } 34 | //push inside the queue 35 | arr[rear] = value; 36 | 37 | return true; 38 | } 39 | 40 | // Dequeues top element from queue. Returns -1 if the stack is empty, otherwise returns the popped element. 41 | int dequeue(){ 42 | if(front == -1){//to check queue is empty 43 | //cout << "Queue is Empty " << endl; 44 | return -1; 45 | } 46 | int ans = arr[front]; 47 | arr[front] = -1; 48 | if(front == rear) { //single element is present 49 | front = rear = -1; 50 | } 51 | else if(front == size - 1) { 52 | front = 0; //to maintain cyclic nature 53 | } 54 | else 55 | {//normal flow 56 | front++; 57 | } 58 | return ans; 59 | } 60 | }; -------------------------------------------------------------------------------- /Queue/C++/implementQueue.cpp: -------------------------------------------------------------------------------- 1 | class Queue { 2 | 3 | int* arr; 4 | int qfront; 5 | int rear; 6 | int size; 7 | 8 | public: 9 | Queue() { 10 | size = 100001; 11 | arr = new int[size]; 12 | qfront = 0; 13 | rear = 0; 14 | } 15 | 16 | /*----------------- Public Functions of Queue -----------------*/ 17 | 18 | bool isEmpty() { 19 | if(qfront == rear) { 20 | return true; 21 | } 22 | else 23 | { 24 | return false; 25 | } 26 | } 27 | 28 | void enqueue(int data) { 29 | if(rear == size) 30 | cout << "Queue is Full" << endl; 31 | else 32 | { 33 | arr[rear] = data; 34 | rear++; 35 | } 36 | } 37 | 38 | int dequeue() { 39 | if(qfront == rear) { 40 | return -1; 41 | } 42 | else 43 | { int ans = arr[qfront]; 44 | arr[qfront] = -1; 45 | qfront++; 46 | if(qfront==rear){ 47 | qfront = 0; 48 | rear = 0; 49 | } 50 | return ans; 51 | } 52 | } 53 | 54 | int front() { 55 | if(qfront == rear) { 56 | return -1; 57 | } 58 | else 59 | { 60 | return arr[qfront]; 61 | } 62 | } 63 | }; -------------------------------------------------------------------------------- /Queue/C++/linkedListImplementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | Node(int data) 9 | { 10 | this -> data = data; 11 | this -> next = nullptr; 12 | } 13 | }; 14 | class Queue 15 | { 16 | Node *front = nullptr, *rear = nullptr; 17 | public: 18 | void enqueue(int data) 19 | { 20 | Node *newNode = new Node(data); 21 | if (!front && !rear) 22 | front = rear = newNode; 23 | else 24 | { 25 | rear -> next = newNode; 26 | rear = newNode; 27 | } 28 | } 29 | void dequeue() 30 | { 31 | if (!front) 32 | exit(1); 33 | Node *temp = front; 34 | if (front == rear) 35 | front = rear = nullptr; 36 | else 37 | front = front -> next; 38 | delete temp; 39 | } 40 | int peek() 41 | { 42 | if (!front) 43 | exit(2); 44 | return front -> data; 45 | } 46 | }; 47 | int main() 48 | { 49 | Queue q; 50 | q.enqueue(1); 51 | q.enqueue(2); 52 | q.enqueue(3); 53 | q.dequeue(); 54 | cout << q.peek(); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Queue/C/ArrayImplementation.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUE_ARRAY_IMPLEMENTATION_H 2 | # define QUEUE_ARRAY_IMPLEMENTATION_H 3 | 4 | #define QUEUE_SIZE 100 5 | 6 | typedef struct 7 | { 8 | int array[QUEUE_SIZE]; 9 | int head; 10 | int tail; 11 | } Queue; 12 | 13 | Queue *queue_build(void); 14 | 15 | void queue_enqueue(int data, Queue *queue); 16 | 17 | int queue_dequeue(Queue *queue); 18 | 19 | void queue_destroy(Queue *queue); 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /Queue/C/Arrayimplementation.c: -------------------------------------------------------------------------------- 1 | #include "ArrayImplementation.h" 2 | #include 3 | 4 | Queue *queue_build(void) 5 | { 6 | Queue *queue; 7 | 8 | queue = (Queue *) malloc(sizeof (Queue)); 9 | queue->head = 0; 10 | queue->tail = 0; 11 | 12 | return (queue); 13 | } 14 | 15 | void queue_enqueue(int data, Queue *queue) 16 | { 17 | queue->array[queue->tail] = data; 18 | queue->tail += 1; 19 | } 20 | 21 | int queue_dequeue(Queue *queue) 22 | { 23 | int garbage; 24 | 25 | garbage = queue->array[queue->head]; 26 | queue->head += 1; 27 | return (garbage); 28 | } 29 | 30 | void queue_destroy(Queue *queue) 31 | { 32 | free(queue); 33 | } 34 | -------------------------------------------------------------------------------- /Queue/C/linkedListImplementation.c: -------------------------------------------------------------------------------- 1 | #include "linkedListImplementation.h" 2 | #include 3 | 4 | Queue *queue_build(void) 5 | { 6 | Queue *queue; 7 | 8 | queue = (Queue *) malloc(sizeof (Queue)); 9 | queue->head = NULL; 10 | queue->tail = NULL; 11 | 12 | return (queue); 13 | } 14 | 15 | Node *node_build(int data) 16 | { 17 | Node *node; 18 | 19 | node = (Node *) malloc(sizeof (Node)); 20 | node->data = data; 21 | node->next = NULL; 22 | 23 | return (node); 24 | } 25 | 26 | void queue_enqueue(int data, Queue *queue) 27 | { 28 | Node *node; 29 | node = node_build(data); 30 | 31 | if (!queue->head) 32 | { 33 | queue->head = node; 34 | queue->tail = node; 35 | return; 36 | } 37 | 38 | queue->tail->next = node; 39 | queue->tail = node; 40 | } 41 | 42 | int queue_dequeue(Queue *queue) 43 | { 44 | Node *node_garbage; 45 | int int_garbage; 46 | 47 | node_garbage = queue->head; 48 | int_garbage = queue->head->data; 49 | 50 | queue->head = queue->head->next; 51 | 52 | free(node_garbage); 53 | return (int_garbage); 54 | } 55 | 56 | void queue_destroy(Queue *queue) 57 | { 58 | while(queue->head) 59 | queue_dequeue(queue); 60 | 61 | free(queue); 62 | } 63 | -------------------------------------------------------------------------------- /Queue/C/linkedListImplementation.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUE_LINKED_LIST_IMPLEMENTATION_H 2 | #define QUEUE_LINKED_LIST_IMPLEMENTATION_H 3 | 4 | #include "../../LinkedList/C/linkedList.h" 5 | 6 | typedef struct 7 | { 8 | 9 | Node *head; 10 | Node *tail; 11 | 12 | } Queue; 13 | 14 | Queue *queue_build(void); 15 | 16 | void queue_enqueue(int data, Queue *queue); 17 | 18 | int queue_dequeue(Queue *queue); 19 | 20 | void queue_destroy(Queue *queue); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /Queue/JAVA/BinaryNumbersUsingQueue.java: -------------------------------------------------------------------------------- 1 | // Program to Generate Binary Numbers from 1 to n using Queue 2 | 3 | import java.util.*; 4 | import java.util.LinkedList; 5 | 6 | class Generate { 7 | public static String[] generateNumbers(int n) { 8 | String num[] = new String[n]; 9 | Queue q = new LinkedList(); 10 | q.offer("1"); 11 | for (int i = 0; i < n; i++) { 12 | num[i] = q.poll(); 13 | String num1 = num[i] + "0"; 14 | String num2 = num[i] + "1"; 15 | q.offer(num1); 16 | q.offer(num2); 17 | } 18 | return num; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Scanner sc = new Scanner(System.in); 23 | int n = sc.nextInt(); 24 | String result[] = generateNumbers(n); 25 | for (String num : result) 26 | System.out.println(num + "\t"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Queue/JAVA/Maximumreversedrubarraypob.java: -------------------------------------------------------------------------------- 1 | public class MaximumReversedSubarray { 2 | 3 | // reverse an array 4 | private static void reverseArray(int[] arr) { 5 | int start = 0; 6 | int end = arr.length - 1; 7 | 8 | while (start < end) { 9 | //elements start and end indices 10 | int temp = arr[start]; 11 | arr[start] = arr[end]; 12 | arr[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | 18 | // find the maximum subarray sum 19 | private static int maxSubArraySum(int[] nums) { 20 | int maxEndingHere = nums[0]; 21 | int maxSoFar = nums[0]; 22 | 23 | for (int i = 1; i < nums.length; i++) { 24 | maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]); 25 | maxSoFar = Math.max(maxSoFar, maxEndingHere); 26 | } 27 | 28 | return maxSoFar; 29 | } 30 | 31 | //maximum subarray sum in a reversed array 32 | public static int maxReversedSubarraySum(int[] arr) { 33 | reverseArray(arr); 34 | return maxSubArraySum(arr); 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[] array = {1, -3, 4, -2, -1, 6}; 39 | int result = maxReversedSubarraySum(array); 40 | 41 | System.out.println("Maximum reversed subarray sum: " + result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Queue/JAVA/QueueUsingArray.java: -------------------------------------------------------------------------------- 1 | public class QueueUsingArray { 2 | private int arr[]; 3 | private int size; 4 | private int front; 5 | private int rear; 6 | 7 | public QueueUsingArray() { 8 | arr = new int[10]; 9 | front = -1; 10 | rear = -1; 11 | } 12 | 13 | public QueueUsingArray(int capacity) { 14 | arr = new int[capacity]; 15 | front = -1; 16 | rear = -1; 17 | } 18 | 19 | public boolean isEmpty() { 20 | return size == 0; 21 | } 22 | 23 | public int size() { 24 | return size; 25 | } 26 | 27 | public int front() { 28 | if (isEmpty()) { 29 | return -1; 30 | } 31 | return arr[front]; 32 | } 33 | 34 | public void enqueue(int element) { 35 | if (size == arr.length) { 36 | rear = -1; 37 | int temp[] = arr; 38 | arr = new int[2 * temp.length]; 39 | int index = 0; 40 | for (int i = front; i < temp.length; i++) { 41 | arr[index] = temp[i]; 42 | index++; 43 | } 44 | for (int i = 0; i < front - 1; i++) { 45 | arr[index] = temp[i]; 46 | index++; 47 | } 48 | front = 0; 49 | rear = temp.length - 1; 50 | } 51 | if (front == -1) { 52 | front = front + 1; 53 | } 54 | rear = rear + 1; 55 | arr[rear] = element; 56 | size = size + 1; 57 | } 58 | 59 | public int dequeue() { 60 | if (size == 0) { 61 | return -1; 62 | } 63 | int temp = arr[front]; 64 | front = front + 1; 65 | if (front == arr.length) { 66 | front = 0; 67 | } 68 | size = size - 1; 69 | if (size == 0) { 70 | front = -1; 71 | rear = -1; 72 | } 73 | return temp; 74 | } 75 | 76 | public void print() { 77 | for (int i = front; i <= rear; i++) { 78 | System.out.print(arr[i] + " "); 79 | } 80 | System.out.println(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Queue/JAVA/QueueUsingArrayList.java: -------------------------------------------------------------------------------- 1 | package Queue.JAVA; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class QueueUsingArrayList { 7 | List queue = new ArrayList<>(); 8 | 9 | public boolean isEmpty(){ 10 | return queue.isEmpty(); 11 | } 12 | 13 | public void enqueue(int val){ 14 | queue.add(val); 15 | } 16 | 17 | public int dequeue(){ 18 | if(isEmpty()){ 19 | System.out.println("Queue is Empty"); 20 | } 21 | return queue.remove(0); 22 | } 23 | 24 | public int peek(){ 25 | if(isEmpty()){ 26 | System.out.println("Queue is Empty"); 27 | } 28 | return queue.get(0); 29 | } 30 | 31 | public void display(){ 32 | if(isEmpty()){ 33 | System.out.println("Queue is Empty"); 34 | } 35 | for(int i=0; i head; 5 | LinkedListNode rear; 6 | int size; 7 | 8 | public QueueUsingLL() { 9 | head = null; 10 | rear = null; 11 | size = 0; 12 | } 13 | 14 | public int size() { 15 | return size; 16 | } 17 | 18 | public boolean isEmpty() { 19 | return size == 0; 20 | } 21 | 22 | public int front() { 23 | return head.data; 24 | } 25 | 26 | public void enqueue(int element) { 27 | LinkedListNode temp = new LinkedListNode(element); 28 | if (head == null) { 29 | head = temp; 30 | rear = temp; 31 | rear.next = null; 32 | } else { 33 | rear.next = temp; 34 | rear = temp; 35 | rear.next = null; 36 | } 37 | size++; 38 | } 39 | 40 | public int dequeue() { 41 | if (size == 0) { 42 | return -1; 43 | } else { 44 | int data = head.data; 45 | if (head.next == null) { 46 | head = null; 47 | rear = null; 48 | } else { 49 | head = head.next; 50 | } 51 | size--; 52 | return data; 53 | } 54 | } 55 | 56 | public void print() { 57 | if (head == null) { 58 | System.out.println("Queue Is Empty"); 59 | } else { 60 | LinkedListNode temp = head; 61 | while (temp != null) { 62 | System.out.print(temp.data + " "); 63 | temp = temp.next; 64 | } 65 | } 66 | System.out.println(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Queue/JAVA/QueueUsingStack.java: -------------------------------------------------------------------------------- 1 | package Queue.JAVA; 2 | 3 | import java.util.Stack; 4 | 5 | public class QueueUsingStack { 6 | Stack enqueueStack = new Stack<>(); 7 | Stack dequeueStack = new Stack<>(); 8 | 9 | public boolean isEmpty() { 10 | return enqueueStack.isEmpty() && dequeueStack.isEmpty(); 11 | } 12 | 13 | public void enqueue(int val) { 14 | enqueueStack.push(val); 15 | } 16 | 17 | private void transferElements() { 18 | while (!enqueueStack.isEmpty()) { 19 | dequeueStack.push(enqueueStack.pop()); 20 | } 21 | } 22 | 23 | public int dequeue() { 24 | if (isEmpty()) { 25 | System.out.println("Queue is Empty"); 26 | } 27 | if (dequeueStack.isEmpty()) { 28 | transferElements(); 29 | } 30 | return dequeueStack.pop(); 31 | } 32 | 33 | public int peek(){ 34 | if(isEmpty()){ 35 | System.out.println("Queue is Empty"); 36 | } 37 | if (dequeueStack.isEmpty()) { 38 | transferElements(); 39 | } 40 | return dequeueStack.peek(); 41 | } 42 | 43 | public void display() { 44 | if (isEmpty()) { 45 | System.out.println("Queue is Empty"); 46 | return; 47 | } 48 | 49 | if (!dequeueStack.isEmpty()) { 50 | for (int i = dequeueStack.size() - 1; i >= 0; i--) { 51 | System.out.print(dequeueStack.get(i) + " "); 52 | } 53 | } else { 54 | for (int i = 0; i < enqueueStack.size(); i++) { 55 | System.out.print(enqueueStack.get(i) + " "); 56 | } 57 | } 58 | System.out.println(); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![visitors](https://visitor-badge.laobi.icu/badge?page_id=N0vice17.DataStructures-And-Algorithm) 2 | # Welcome to Data Structure and Algorithm 3 | This is an Open Source Respository focused on **Data Strucutre and Algorithms**. Whenever you are stuck at any kind of problem feel free to look into this repo. 4 | 5 | 6 | # Steps to follow for Contributing: 7 | 8 | Contributions are always welcome. Feel free to contribute as much as you want. Read the [Contribution Guidelines](https://github.com/N0vice17/DataStructures-And-Algorithm/blob/master/Contributing.md) here. 9 | 10 | ### Reviewers of the Repository 11 | **C** 12 | | [IndranjanaChatterjee](https://github.com/IndranjanaChatterjee) | [N0vice17](https://github.com/N0vice17) | 13 | |---|---| 14 | 15 | **Java** 16 | | [Agnik7](https://github.com/Agnik7) | [N0vice17](https://github.com/N0vice17) | 17 | |---|---| 18 | 19 | **Python** 20 | | [Agnik7](https://github.com/Agnik7) | [IndranjanaChatterjee](https://github.com/IndranjanaChatterjee) | 21 | |---|---| 22 | 23 | **Other languages** 24 | | [N0vice17](https://github.com/N0vice17) | [Agnik7](https://github.com/Agnik7) | [IndranjanaChatterjee](https://github.com/IndranjanaChatterjee) | 25 | |---|---|---| 26 | 27 | # Help Us to Grow 😁 28 | We are open to any type of contribution that is made by you in any language. Please do Contribute. 29 | If you have any query, you can discuss it by creating an Issue. 30 | # The Contributors of this Wonderful Project 😎 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Recursion/Euclidean_GCD.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | if a == 0: 3 | return b 4 | 5 | return gcd(b % a, a) 6 | 7 | if __name__ == "__main__": 8 | a = int(input("Enter the value of a :")) 9 | b = int(input("Enter the value of b :")) 10 | print("gcd(", a, ",", b, ") = ", gcd(a, b)) 11 | -------------------------------------------------------------------------------- /Recursion/N_Queens.py: -------------------------------------------------------------------------------- 1 | # Optimal way to implement NQueens problem using recursion 2 | from typing import List 3 | class Solution: 4 | def solve(self, col, board, ans, leftrow, upperDiagonal, lowerDiagonal, n): 5 | if col == n: 6 | ans.append(board[:]) 7 | return 8 | 9 | for row in range(n): 10 | if leftrow[row] == 0 and lowerDiagonal[row + col] == 0 and upperDiagonal[n - 1 + col - row] == 0: 11 | board[row] = board[row][:col] + 'Q' + board[row][col + 1:] 12 | leftrow[row] = 1 13 | lowerDiagonal[row + col] = 1 14 | upperDiagonal[n - 1 + col - row] = 1 15 | self.solve(col + 1, board, ans, leftrow, upperDiagonal, lowerDiagonal, n) 16 | board[row] = board[row][:col] + '.' + board[row][col + 1:] 17 | leftrow[row] = 0 18 | lowerDiagonal[row + col] = 0 19 | upperDiagonal[n - 1 + col - row] = 0 20 | 21 | def solveNQueens(self, n: int) -> List[List[str]]: 22 | ans = [] 23 | board = ['.' * n for _ in range(n)] 24 | leftrow = [0] * n 25 | upperDiagonal = [0] * (2 * n - 1) 26 | lowerDiagonal = [0] * (2 * n - 1) 27 | self.solve(0, board, ans, leftrow, upperDiagonal, lowerDiagonal, n) 28 | return ans 29 | 30 | if __name__ == "__main__": 31 | n = int(input("Enter the number of queens: ")) 32 | solution = Solution() 33 | result = solution.solveNQueens(n) 34 | print("Solutions for N-Queens:") 35 | for solution in result: 36 | for row in solution: 37 | print(row) 38 | print() 39 | -------------------------------------------------------------------------------- /Recursion/Subset_sum_1.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def combinationSum2(arr: List[int], n: int, target: int) -> List[List[int]]: 4 | def solve(ind, target): 5 | if target == 0: 6 | ans.append(ds[:]) 7 | return 8 | for i in range(ind, len(arr)): 9 | if i > ind and arr[i - 1] == arr[i]: 10 | continue 11 | if arr[i] > target: 12 | break 13 | ds.append(arr[i]) 14 | solve(i + 1, target - arr[i]) 15 | ds.pop() 16 | 17 | arr.sort() 18 | ans = [] 19 | ds = [] 20 | solve(0, target) 21 | return ans 22 | 23 | if __name__ == "__main__": 24 | arr = [10, 1, 2, 7, 6, 5] 25 | target = 8 26 | result = combinationSum2(arr, len(arr), target) 27 | print("Combinations that sum to", target, "are:") 28 | print(result) 29 | -------------------------------------------------------------------------------- /Recursion/Subset_sum_2.py: -------------------------------------------------------------------------------- 1 | #optimal way to solve rather than using sets 2 | from typing import List 3 | 4 | def subsetsWithDup(nums: List[int]) -> List[List[int]]: 5 | def findSubsets(ind): 6 | ans.append(ds[:]) 7 | for i in range(ind, len(nums)): 8 | if i != ind and nums[i] == nums[i - 1]: 9 | continue 10 | ds.append(nums[i]) 11 | findSubsets(i + 1) 12 | ds.pop() 13 | 14 | nums.sort() 15 | ans = [] 16 | ds = [] 17 | findSubsets(0) 18 | return ans 19 | 20 | if __name__ == "__main__": 21 | nums = [1, 2, 2] 22 | result = subsetsWithDup(nums) 23 | print("Subsets with duplicates are:") 24 | print(result) 25 | -------------------------------------------------------------------------------- /Recursion/Subsets.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Subsets { 4 | public List> subsets(int[] nums) { 5 | List> ans = new ArrayList<>(); 6 | List temp = new ArrayList<>(); 7 | solve(0,nums,nums.length,temp,ans); 8 | return ans; 9 | } 10 | 11 | public static void solve(int i, int nums[], int n, List temp, List> ans){ 12 | if(i==n){ 13 | ans.add(new ArrayList<>(temp)); 14 | return; 15 | } 16 | temp.add(nums[i]); 17 | solve(i+1,nums,n,temp,ans); 18 | temp.remove(temp.size()-1); 19 | solve(i+1,nums,n,temp,ans); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Recursion/Sudoko_solver.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def is_possible(board, row, col, num): 4 | # Check row 5 | if num in board[row]: 6 | return False 7 | 8 | # Check column 9 | if num in [board[i][col] for i in range(9)]: 10 | return False 11 | 12 | # Check 3x3 subgrid 13 | start_row, start_col = 3 * (row // 3), 3 * (col // 3) 14 | for i in range(start_row, start_row + 3): 15 | for j in range(start_col, start_col + 3): 16 | if board[i][j] == num: 17 | return False 18 | 19 | return True 20 | 21 | def solve_sudoku(board): 22 | for i in range(9): 23 | for j in range(9): 24 | if board[i][j] == 0: 25 | for num in range(1, 10): 26 | if is_possible(board, i, j, num): 27 | board[i][j] = num 28 | if solve_sudoku(board): 29 | return True 30 | board[i][j] = 0 31 | return False 32 | return True 33 | 34 | if __name__ == "__main__": 35 | board = [ 36 | [5, 3, 0, 0, 7, 0, 0, 0, 0], 37 | [6, 0, 0, 1, 9, 5, 0, 0, 0], 38 | [0, 9, 8, 0, 0, 0, 0, 6, 0], 39 | [8, 0, 0, 0, 6, 0, 0, 0, 3], 40 | [4, 0, 0, 8, 0, 3, 0, 0, 1], 41 | [7, 0, 0, 0, 2, 0, 0, 0, 6], 42 | [0, 6, 0, 0, 0, 0, 2, 8, 0], 43 | [0, 0, 0, 4, 1, 9, 0, 0, 5], 44 | [0, 0, 0, 0, 8, 0, 0, 7, 9] 45 | ] 46 | 47 | if solve_sudoku(board): 48 | print("Sudoku Solution:") 49 | for row in board: 50 | print(row) 51 | else: 52 | print("No solution exists.") 53 | -------------------------------------------------------------------------------- /Recursion/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | public class TowerOfHanoi { 2 | public static void move(int n, char source, char auxiliary, char destination) { 3 | if (n == 1) { 4 | System.out.println("Move disk 1 from " + source + " to " + destination); 5 | } else { 6 | move(n - 1, source, destination, auxiliary); 7 | System.out.println("Move disk " + n + " from " + source + " to " + destination); 8 | move(n - 1, auxiliary, source, destination); 9 | } 10 | } 11 | 12 | public static void main(String[] args) { 13 | int numberOfDisks = 3; // Example number of disks 14 | move(numberOfDisks, 'A', 'B', 'C'); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Recursion/is_palindrome: -------------------------------------------------------------------------------- 1 | 2 | def is_palindrome(string): 3 | if len(string) <= 1: 4 | return True 5 | elif string[0] != string[-1]: 6 | return False 7 | else: 8 | return is_palindrome(string[1:-1]) 9 | 10 | string = input("Enter a string: ") 11 | print(is_palindrome(string)) 12 | -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/combined.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findFLOccurrence(int *, int, int, int); 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) 13 | cin >> arr[i]; 14 | 15 | int key; 16 | cin >> key; 17 | 18 | cout << findFLOccurrence(arr, n, key, 1) << " " << findFLOccurrence(arr, n, key, 0) << endl; 19 | 20 | return 0; 21 | } 22 | 23 | int findFLOccurrence(int arr[], int n, int key, int check) 24 | { 25 | int low = 0, high = n - 1, result = n - 1; 26 | while (low <= high) 27 | { 28 | int mid = low + (high - low) / 2; 29 | if (arr[mid] == key) 30 | { 31 | result = mid; 32 | if (check) 33 | high = mid - 1; 34 | else 35 | low = mid + 1; 36 | } 37 | else if (key < arr[mid]) 38 | high = mid - 1; 39 | else 40 | low = mid + 1; 41 | } 42 | return result; 43 | } -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/first-occurrence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findFirstOccurrence(int *, int, int); 5 | 6 | int main() 7 | { 8 | int n; // array size 9 | cin >> n; 10 | int arr[n]; // array declaration 11 | 12 | for (int i = 0; i < n; i++) // input array elements 13 | cin >> arr[i]; 14 | 15 | int key; // element we want to find 16 | cin >> key; 17 | 18 | cout << findFirstOccurrence(arr, n, key) << endl; 19 | return 0; 20 | } 21 | 22 | int findFirstOccurrence(int arr[], int n, int key) 23 | { 24 | int low = 0, high = n - 1, result = -1; 25 | while (low <= high) 26 | { 27 | int mid = low + (high - low) / 2; // calculating mid index 28 | if (arr[mid] == key) 29 | { 30 | result = mid; // key found 31 | high = mid - 1; 32 | } 33 | else if (key < mid) 34 | high = mid - 1; // updating high pointer 35 | else 36 | low = mid + 1; // updating low pointer 37 | } 38 | return result; 39 | } 40 | -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int *, int, int); 5 | 6 | int main() 7 | { 8 | int n; // size of array 9 | cin >> n; 10 | int arr[n]; // array declaration 11 | 12 | for (int i = 0; i < n; i++) // input array elements 13 | cin >> arr[i]; 14 | 15 | int key; // element we want to find 16 | cin >> key; 17 | 18 | cout << binarySearch(arr, n, key); 19 | 20 | return 0; 21 | } 22 | 23 | int binarySearch(int *arr, int n, int key) 24 | { 25 | int low = 0, high = n - 1; 26 | 27 | while (low <= high) 28 | { 29 | int mid = low + (high - low) / 2; // calculating the mid index 30 | 31 | if (arr[mid] == key) 32 | return mid; // key found 33 | else if (key < arr[mid]) 34 | high = mid - 1; // updating the high pointer 35 | else 36 | low = mid + 1; // updating the low pointer 37 | } 38 | 39 | return -1; // key not found 40 | } -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/last-occurrence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findLastOccurrence(int *, int, int); 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) 13 | cin >> arr[i]; 14 | 15 | int key; 16 | cin >> key; 17 | 18 | cout << findLastOccurrence(arr, n, key) << endl; 19 | return 0; 20 | } 21 | 22 | int findLastOccurrence(int arr[], int n, int key) 23 | { 24 | int low = 0, high = n - 1, result = -1; 25 | while (low <= high) 26 | { 27 | int mid = low + (high - low) / 2; 28 | if (arr[mid] == key) 29 | { 30 | result = mid; 31 | low = mid + 1; 32 | } 33 | else if (key < mid) 34 | high = mid - 1; 35 | else 36 | low = mid + 1; 37 | } 38 | return result; 39 | } -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/problem-1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findTotalOccurrence(int *, int, int, bool); 5 | 6 | int main() 7 | { 8 | int n; // size of array 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) // input array elements 13 | cin >> arr[i]; 14 | 15 | int key; // element we want to find 16 | cin >> key; 17 | 18 | cout << findTotalOccurrence(arr, n, key, false) - findTotalOccurrence(arr, n, key, true) + 1 << endl; 19 | 20 | return 0; 21 | } 22 | 23 | int findTotalOccurrence(int arr[], int n, int key, bool check) 24 | { 25 | int low = 0, high = n - 1, result = -1; 26 | while (low <= high) 27 | { 28 | int mid = low + (high - low) / 2; // calculating the mid index 29 | if (arr[mid] == key) 30 | { 31 | result = mid; // key found 32 | if (check) // if check value is true 33 | high = mid - 1; 34 | else // if check value is false 35 | low = mid + 1; 36 | } 37 | else if (key < arr[mid]) 38 | high = mid - 1; // updating the high pointer 39 | else 40 | low = mid + 1; // updating the low pointer 41 | } 42 | return result; 43 | } 44 | -------------------------------------------------------------------------------- /Searching_Algorithm/C++/binary-search/recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int *, int, int, int); 5 | 6 | int main() 7 | { 8 | int n; // size of array 9 | cin >> n; 10 | int arr[n]; // array declaration 11 | 12 | for (int i = 0; i < n; i++) // input array elements 13 | cin >> arr[i]; 14 | 15 | int key; // element we want to find 16 | cin >> key; 17 | 18 | cout << binarySearch(arr, 0, n - 1, key); 19 | 20 | return 0; 21 | } 22 | 23 | int binarySearch(int *arr, int low, int high, int key) 24 | { 25 | if (low > high) 26 | return -1; // key not found 27 | 28 | int mid = low + (high - low) / 2; // calculating the mid index 29 | 30 | if (arr[mid] == key) 31 | return mid; // element found 32 | 33 | if (key < arr[mid]) 34 | return binarySearch(arr, low, mid - 1, key); 35 | 36 | return binarySearch(arr, mid + 1, high, key); // if (key > arr[mid]) 37 | } -------------------------------------------------------------------------------- /Searching_Algorithm/C/Interpolation_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | void print(int arr[],int n) 3 | { 4 | int i; 5 | for(i=0;iele_search) 18 | { 19 | high=pos-1; 20 | } 21 | else if(arr[pos] ei) { 6 | return -1; 7 | } 8 | int mid = si + (ei - si) / 2; 9 | if (arr[mid] == num) { 10 | return mid; 11 | } else if (ei > mid) { 12 | return binarysearch(arr, num, mid + 1, ei); 13 | } else { 14 | return binarysearch(arr, num, si, mid - 1); 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner input = new Scanner(System.in); 20 | int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 }; 21 | int k = 6; 22 | System.out.println(binarysearch(arr, k, 0, arr.length - 1)); 23 | input.close(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/Binary_Search.java: -------------------------------------------------------------------------------- 1 | 2 | class Binary_Search { 3 | public static int search(int[] arr, int element) { 4 | int Start = 0; 5 | int End = arr.length - 1; 6 | while (Start <= End) { 7 | int mid = Start + (End - Start) / 2; 8 | if (arr[mid] == element) { 9 | return mid; 10 | } else if (element < arr[mid]) { 11 | End = mid - 1; 12 | } else if (element > arr[mid]) { 13 | Start = mid + 1; 14 | } 15 | } 16 | return -1; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 21 | int element = 3; 22 | System.out.println(search(arr, element)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/Binary_Searching_2D_Array.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Binary_Searching_2D_Array { 4 | static int[] search(int[][] arr, int element) { 5 | int row = 0; 6 | int coloumn = arr.length - 1; 7 | while (row < arr.length && coloumn >= 0) { 8 | if (arr[row][coloumn] == element) { 9 | return new int[] { row, coloumn }; 10 | } else if (element > arr[row][coloumn]) { 11 | row++; 12 | } else if (element < arr[row][coloumn]) { 13 | coloumn--; 14 | } 15 | } 16 | return new int[] { -1, -1 }; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[][] arr = { { 10, 20, 30, 40 }, { 11, 25, 35, 45 }, { 28, 29, 37, 49 }, { 33, 34, 38, 50 } }; 21 | int element = 28; 22 | System.out.println(Arrays.toString(search(arr, element))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/Linear_Search.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Linear_Search { 4 | public static int search(int[] arr, int element) { 5 | for (int i = 0; i < arr.length; i++) { 6 | if (arr[i] == element) { 7 | return i; 8 | } 9 | } 10 | return -1; 11 | } 12 | 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | int element = input.nextInt(); 16 | int[] arr = { 2, 3, 4, 5, 68 }; 17 | int Search = search(arr, element); 18 | System.out.println(Search); 19 | input.close(); 20 | } 21 | } -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/Linear_search_2D_Array.java: -------------------------------------------------------------------------------- 1 | class Linear_search_2D_Array { 2 | public static int search(int[][] arr, int element) { 3 | for (int i = 0; i < arr.length; i++) { 4 | for (int j = 0; j < arr[i].length; j++) { 5 | if (arr[i][j] == element) { 6 | return 1; 7 | } 8 | } 9 | } 10 | return 0; 11 | } 12 | 13 | public static void main(String[] args) { 14 | int[][] arr = { { 19, 29, 39, 49 }, 15 | { 56, 66, 76, 86 }, 16 | { 99, 10, 11, 12 } }; 17 | int element = 10; 18 | System.out.println(search(arr, element)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/Order_Agnoistic_Binary_search.java: -------------------------------------------------------------------------------- 1 | 2 | class Order_Agnoistic_Binary_search { 3 | public static void order(int[] arr, int element) { 4 | int Start = 0; 5 | int End = arr.length - 1; 6 | if (arr[Start] > arr[End]) { 7 | System.out.println(Descending(arr, element)); 8 | } else { 9 | System.out.println(Ascending(arr, element)); 10 | } 11 | } 12 | 13 | public static int Ascending(int[] arr, int element) { 14 | int low = 0; 15 | int high = arr.length - 1; 16 | while (low <= high) { 17 | int mid = (low + high) / 2; 18 | if (arr[mid] == element) { 19 | return mid; 20 | } else if (element > arr[mid]) { 21 | low = mid + 1; 22 | } else if (element < arr[mid]) { 23 | high = mid - 1; 24 | } 25 | } 26 | return -1; 27 | } 28 | 29 | public static int Descending(int[] arr, int element) { 30 | int low = 0; 31 | int high = arr.length - 1; 32 | while (low <= high) { 33 | int mid = (low + high) / 2; 34 | if (arr[mid] == element) { 35 | return mid; 36 | } else if (element > arr[mid]) { 37 | high = mid - 1; 38 | } else if (element < arr[mid]) { 39 | low = mid + 1; 40 | } 41 | } 42 | return -1; 43 | } 44 | 45 | public static void main(String[] args) { 46 | int[] arr = { 97, 96, 95, 94, 123, 2, -13 }; 47 | int element = -13; 48 | order(arr, element); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Searching_Algorithm/JAVA/SearchRotatedArray.java: -------------------------------------------------------------------------------- 1 | public class SearchRotatedArray { 2 | public static void main(String[] args){ 3 | int[] nums = {4,5,6,7,0,1,2}; 4 | System.out.println(findPivot(nums)); 5 | } 6 | 7 | static int search(int[] nums, int target){ 8 | int pivot = findPivot(nums); 9 | 10 | if(pivot == -1){ 11 | return binarySearch(nums, target, 0, nums.length-1); 12 | } 13 | 14 | if(nums[pivot]==target){ 15 | return pivot; 16 | } 17 | 18 | if(target >= nums[0]){ 19 | return binarySearch(nums, target, 0, pivot-1); 20 | } 21 | 22 | return binarySearch(nums, target, pivot+1, nums.length-1); 23 | 24 | } 25 | 26 | static int findPivot(int[] nums){ 27 | int start = 0; 28 | int end = nums.length-1; 29 | while(startnums[mid+1]){ 32 | return mid; 33 | } 34 | 35 | if(mid>start && nums[mid] arr[mid]){ 57 | start = mid + 1; 58 | } 59 | else{ 60 | return mid; 61 | } 62 | } 63 | return -1; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Searching_Algorithm/PYTHON/BinarySearch_UsingRecursion.py: -------------------------------------------------------------------------------- 1 | def binarySearch(arr,num,start,end): 2 | if start > end: 3 | return -1 4 | mid = start + (end-start)//2 5 | if arr[mid] == num: 6 | return mid 7 | elif end > mid: 8 | return binarysearch(arr, num, mid + 1, end) 9 | else: 10 | return binarysearch(arr, num, start, mid - 1) 11 | 12 | if __name__ == "__main__": 13 | n = int(input("Enter number of elements: ")) 14 | array=[] 15 | print("Enter the elements:") 16 | for i in range(n): 17 | x = int(input("")) 18 | array.append(x) 19 | num = int(input("Enter the element to search: ")) 20 | pos = binarySearch(array, num, 0, len(array)-1) 21 | if pos == -1: 22 | print("Element is not present in the array") 23 | else: 24 | print(f"Element found at position {pos} in the array") 25 | 26 | 27 | -------------------------------------------------------------------------------- /Searching_Algorithm/PYTHON/interpolation_search.py: -------------------------------------------------------------------------------- 1 | def interpolation_search(arr, target): 2 | """ 3 | Perform interpolation search to find the target element in a sorted array. 4 | 5 | Args: 6 | arr (list): The sorted list to search in. 7 | target (int): The element to search for. 8 | 9 | Returns: 10 | int: The index of the target element in the array, or -1 if not found. 11 | """ 12 | left, right = 0, len(arr) - 1 13 | 14 | while left <= right and arr[left] <= target <= arr[right]: 15 | if left == right: 16 | if arr[left] == target: 17 | return left 18 | return -1 19 | pos = left + ((target - arr[left]) * (right - left) // (arr[right] - arr[left])) 20 | 21 | if arr[pos] == target: 22 | return pos 23 | if arr[pos] < target: 24 | left = pos + 1 25 | else: 26 | right = pos - 1 27 | 28 | return -1 29 | 30 | if __name__ == "__main__": 31 | 32 | # Test case 33 | test_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 34 | target_element = 11 35 | result = interpolation_search(test_array, target_element) 36 | 37 | if result == -1: 38 | print(f"Element {target_element} is not present in the array") 39 | else: 40 | print(f"Element {target_element} found at position {result} in the array") 41 | -------------------------------------------------------------------------------- /Searching_Algorithm/PYTHON/ternarySearch.py: -------------------------------------------------------------------------------- 1 | def ternary_search(arr, target): 2 | left, right = 0, len(arr) - 1 3 | 4 | while left <= right: 5 | 6 | third = (right - left) // 3 7 | mid1 = left + third 8 | mid2 = right - third 9 | 10 | if arr[mid1] == target: 11 | return mid1 12 | if arr[mid2] == target: 13 | return mid2 14 | 15 | if target < arr[mid1]: 16 | right = mid1 - 1 17 | elif target > arr[mid2]: 18 | left = mid2 + 1 19 | else: 20 | left = mid1 + 1 21 | right = mid2 - 1 22 | 23 | return -1 # Target not found 24 | 25 | 26 | arr = [1, 2, 36, 54, 59, 60, 77, 88, 93, 1000] 27 | target = 93 28 | result = ternary_search(arr, target) 29 | 30 | if result != -1: 31 | print(f"Element {target} found at index {result}") 32 | else: 33 | print(f"Element {target} not found in the array") 34 | -------------------------------------------------------------------------------- /Singleton_Class/JAVA/type-1.java: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | static int count = 0; // object counter 3 | int id; // instance variable 4 | 5 | private Singleton(int id) { // private constructor 6 | this.id = id; 7 | } 8 | 9 | static Singleton createObject(int id) { 10 | if (1 == count) { // if one object is already created 11 | System.out.println("This is a singleton class! Cannot create more objects!"); 12 | return null; 13 | } 14 | 15 | else { 16 | System.out.println("Object has been created!"); 17 | count++; // increment object counter 18 | return new Singleton(id); // return new object 19 | } 20 | } 21 | } 22 | 23 | class Main { 24 | public static void main(String[] args) { 25 | Singleton obj1 = Singleton.createObject(1); 26 | Singleton obj2 = Singleton.createObject(2); 27 | Singleton obj3 = Singleton.createObject(3); 28 | 29 | System.out.println(obj1.id); 30 | System.out.println(obj2.id); 31 | System.out.println(obj3.id); 32 | } 33 | } -------------------------------------------------------------------------------- /Singleton_Class/JAVA/type-2.java: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | private static Singleton instance = null; // private static instance 3 | int id; // instance variable 4 | 5 | private Singleton(int id) { // private constructor 6 | this.id = id; 7 | } 8 | 9 | static Singleton createObject(int id) { 10 | if (null == instance) // if no object is created 11 | instance = new Singleton(id); // create new instance and store it 12 | return instance; // return the instance 13 | } 14 | } 15 | 16 | class Main { 17 | public static void main(String[] args) { 18 | Singleton obj1 = Singleton.createObject(1); 19 | Singleton obj2 = Singleton.createObject(2); 20 | Singleton obj3 = Singleton.createObject(3); 21 | 22 | System.out.println(obj1.id); 23 | System.out.println(obj2.id); 24 | System.out.println(obj3.id); 25 | } 26 | } -------------------------------------------------------------------------------- /Some_important_algos/AllPalindromicPermutations.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class AllPallindromicPermutations { 5 | 6 | public static void generatepw(int cs, int ts, HashMap fmap, Character oddc, String asf) { 7 | if(cs == ts){ 8 | if(oddc != null){ 9 | asf += oddc; 10 | } 11 | String s = reverse(asf); 12 | asf += s; 13 | 14 | System.out.println(asf); 15 | return; 16 | } 17 | for(char ch : fmap.keySet()){ 18 | if(fmap.get(ch) != 0){ 19 | fmap.put(ch, fmap.get(ch) - 1); 20 | generatepw(cs+1, ts, fmap, oddc, asf+ch); 21 | fmap.put(ch, fmap.get(ch) + 1); 22 | } 23 | } 24 | } 25 | 26 | public static String reverse(String str){ 27 | String s = ""; 28 | for(int i = str.length() -1; i >= 0; i--){ 29 | char ch = str.charAt(i); 30 | s += ch; 31 | } 32 | return s; 33 | } 34 | 35 | 36 | public static void main(String[] args) { 37 | Scanner scn = new Scanner(System.in); 38 | String str = scn.next(); 39 | HashMap fmap = new HashMap<>(); 40 | for (int i = 0; i < str.length(); i++) { 41 | char ch = str.charAt(i); 42 | fmap.put(ch, fmap.getOrDefault(ch, 0) + 1); 43 | } 44 | 45 | char oddc = '1'; 46 | int len = 0; 47 | HashMap halfmap = new HashMap<>(); 48 | for (char ch : fmap.keySet()){ 49 | if(fmap.get(ch) == 1){ 50 | oddc = ch; 51 | continue; 52 | } 53 | 54 | else{ 55 | if(fmap.get(ch) % 2 != 0){ 56 | oddc = ch; 57 | } 58 | halfmap.put(ch, fmap.get(ch) / 2); 59 | len += halfmap.get(ch); 60 | } 61 | } 62 | 63 | generatepw(0, len, halfmap, oddc == '1' ? null : oddc, ""); 64 | 65 | 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /Some_important_algos/Anagram.java: -------------------------------------------------------------------------------- 1 | // JAVA program to check if two strings 2 | // are anagrams of each other 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class Anagram { 7 | 8 | static int NO_OF_CHARS = 256; 9 | 10 | /* function to check whether two strings 11 | are anagram of each other */ 12 | static boolean areAnagram(char str1[], char str2[]) 13 | { 14 | // Create 2 count arrays and initialize 15 | // all values as 0 16 | int count1[] = new int[NO_OF_CHARS]; 17 | Arrays.fill(count1, 0); 18 | int count2[] = new int[NO_OF_CHARS]; 19 | Arrays.fill(count2, 0); 20 | int i; 21 | 22 | // For each character in input strings, 23 | // increment count in the corresponding 24 | // count array 25 | for (i = 0; i < str1.length && i < str2.length; 26 | i++) { 27 | count1[str1[i]]++; 28 | count2[str2[i]]++; 29 | } 30 | 31 | // If both strings are of different length. 32 | // Removing this condition will make the program 33 | // fail for strings like "aaca" and "aca" 34 | if (str1.length != str2.length) 35 | return false; 36 | 37 | // Compare count arrays 38 | for (i = 0; i < NO_OF_CHARS; i++) 39 | if (count1[i] != count2[i]) 40 | return false; 41 | 42 | return true; 43 | } 44 | 45 | /* Driver code*/ 46 | public static void main(String args[]) 47 | { 48 | char str1[] = ("gram").toCharArray(); 49 | char str2[] = ("arm").toCharArray(); 50 | 51 | // Function call 52 | if (areAnagram(str1, str2)) 53 | System.out.println("The two strings are" 54 | + " anagram of each other"); 55 | else 56 | System.out.println("The two strings are not" 57 | + " anagram of each other"); 58 | } 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /Some_important_algos/Exponentiation.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | import java.util.*; 4 | 5 | public class Exponentiation { 6 | // Normal Exponentiation 7 | public static long exponent(int a, int b) { 8 | if (b == 0) { 9 | return 1; 10 | } 11 | if (b % 2 == 0) { 12 | long temp = exponent(a, b / 2); 13 | return (temp * temp); 14 | } else { 15 | long temp = (exponent(a, (b - 1) / 2) * exponent(a, (b - 1) / 2)); 16 | return (a * temp); 17 | } 18 | } 19 | 20 | // Exponentiation with modulo 21 | public static long exponent1(int a, int b, int c) { 22 | if (b == 0) { 23 | return a % c; 24 | } 25 | if (b % 2 == 0) { 26 | long temp = exponent1(a, b / 2, c); 27 | return (temp * temp % c); 28 | } else { 29 | long temp = (exponent1(a, (b - 1) / 2, c) * exponent1(a, (b - 1) / 2, c)) % c; 30 | return (a * temp % c); 31 | } 32 | } 33 | 34 | public static void main(String[] agrs) { 35 | Scanner input = new Scanner(System.in); 36 | System.out.println(exponent(2, 63)); 37 | // System.out.println(exponent1(3,4,5)); 38 | input.close(); 39 | } 40 | } -------------------------------------------------------------------------------- /Some_important_algos/KMP_algorithm.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | import java.util.*; 4 | 5 | public class KMP_algorithm { 6 | public static int[] Array(String str) { 7 | int index = 0; 8 | int[] arr = new int[str.length()]; 9 | for (int i = 1; i <= str.length() - 1; i++) { 10 | if (str.charAt(i) == str.charAt(index)) { 11 | arr[i] = index + 1; 12 | index++; 13 | } else { 14 | if (index != 0) { 15 | index = arr[index - 1]; 16 | arr[i] = index + 1; 17 | } else { 18 | arr[i] = 0; 19 | } 20 | } 21 | } 22 | return arr; 23 | } 24 | 25 | public static boolean KMP(String str, String str1) { 26 | int lps[] = Array(str1); 27 | int i = 0; 28 | int j = 0; 29 | while (i < str.length() && j < str1.length()) { 30 | if (str.charAt(i) == str.charAt(j)) { 31 | i++; 32 | j++; 33 | } else { 34 | if (j != 0) { 35 | j = lps[j - 1]; 36 | } else { 37 | i++; 38 | } 39 | } 40 | } 41 | if (j == str1.length()) { 42 | return true; 43 | } 44 | return false; 45 | } 46 | 47 | public static void main(String[] args) { 48 | Scanner input = new Scanner(System.in); 49 | String str = input.next(); 50 | String str1 = input.next(); 51 | System.out.println(KMP(str, str1)); 52 | input.close(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Some_important_algos/Keypad_Problems.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | public class Keypad_Problems { 4 | public static String getString(int num) { 5 | if (num == 2) { 6 | return "abc"; 7 | } 8 | if (num == 3) { 9 | return "def"; 10 | } 11 | if (num == 4) { 12 | return "ghi"; 13 | } 14 | if (num == 5) { 15 | return "jkl"; 16 | } 17 | if (num == 6) { 18 | return "mno"; 19 | } 20 | if (num == 7) { 21 | return "pqrs"; 22 | } 23 | if (num == 8) { 24 | return "tuv"; 25 | } 26 | if (num == 9) { 27 | return "wxyz"; 28 | } 29 | return ""; 30 | } 31 | 32 | public static String[] keystring(int num) { 33 | if (num == 0) { 34 | String[] arr = new String[1]; 35 | arr[0] = ""; 36 | return arr; 37 | } 38 | String[] smalloutput = keystring(num / 10); 39 | String length = getString(num % 10); 40 | String[] output = new String[smalloutput.length * length.length()]; 41 | int index = 0; 42 | for (int i = 0; i < smalloutput.length; i++) { 43 | for (int j = 0; j < length.length(); j++) { 44 | output[index] = smalloutput[i] + length.charAt(j); 45 | index++; 46 | } 47 | } 48 | return output; 49 | } 50 | 51 | public static void printkeystring(int num, String output) { 52 | if (num == 0) { 53 | System.out.println(output); 54 | return; 55 | } 56 | String get = getString(num % 10); 57 | for (int i = 0; i < get.length(); i++) { 58 | printkeystring(num / 10, (get.charAt(i) + output)); 59 | } 60 | } 61 | 62 | public static void main(String[] args) { 63 | printkeystring(23, ""); 64 | // String []arr=keystring(23); 65 | // for(int i=0;i i) { 17 | palindromeSize[i] = Math.min(palindromeSize[mirror], r - i); 18 | } 19 | while (i + 1 + palindromeSize[i] < chars.length && i - 1 - palindromeSize[i] >= 0 20 | && chars[i + 1 + palindromeSize[i]] == chars[i - 1 - palindromeSize[i]]) { 21 | palindromeSize[i]++; 22 | } 23 | 24 | if (i + palindromeSize[i] > r) { 25 | c = i; 26 | r = i + palindromeSize[i]; 27 | } 28 | 29 | if (palindromeSize[i] > maxPalindrome) { 30 | maxPalindrome = palindromeSize[i]; 31 | maxPalindromeCenter = i; 32 | } 33 | } 34 | return s.substring(maxPalindromeCenter - maxPalindrome, maxPalindromeCenter + maxPalindrome).replace("*", ""); 35 | } 36 | 37 | public static void main(String[] args) { 38 | String longestPalindrome = new LongestPalindromeInString().longestPalindrome("babad"); 39 | System.out.println(longestPalindrome); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Some_important_algos/Python/Bresenhams Algorithm.py: -------------------------------------------------------------------------------- 1 | #Bresenhams Algorithm 2 | 3 | def bresenham(x1, y1, x2, y2): 4 | x, y = x1, y1 5 | dx = x2 - x1 6 | dy = y2 - y1 7 | 8 | xx, yy = [], [] 9 | 10 | print(x, y) 11 | 12 | xx.append(x) 13 | yy.append(y) 14 | 15 | p = 2*dy - dx 16 | 17 | for i in range(0,dx): 18 | x+=1 19 | 20 | if p<0: 21 | p = p + 2*dy 22 | else: 23 | y+=1 24 | p = p + 2*dy - 2*dx 25 | 26 | print(x, y) 27 | 28 | xx.append(x) 29 | yy.append(y) 30 | 31 | return xx, yy 32 | 33 | xx, yy = bresenham(20, 10, 30, 18) 34 | 35 | #Plotting the points 36 | 37 | import matplotlib.pyplot as plt 38 | import numpy as np 39 | 40 | def plot_line(xx, yy): 41 | plt.scatter(xx, yy, label = "points", color= "red", marker= "x", s=30) 42 | plt.axis([min(xx), max(xx)+1, min(yy), max(yy)+1]) 43 | plt.title('Bresenhams Algorithm Plot') 44 | plt.grid() 45 | plt.show() 46 | 47 | plot_line(xx, yy) -------------------------------------------------------------------------------- /Some_important_algos/Return_Subsequence_String.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | import java.lang.Character.Subset; 4 | import java.util.*; 5 | 6 | public class Return_Subsequence_String { 7 | public static String[] subsequence(String str) { 8 | if (str.length() == 0) { 9 | String output[] = new String[1]; 10 | output[0] = ""; 11 | return output; 12 | } 13 | String[] output = subsequence(str.substring(1)); 14 | String[] output1 = new String[2 * output.length]; 15 | for (int i = 0; i < output.length; i++) { 16 | output1[i] = output[i]; 17 | } 18 | for (int i = 0; i < output.length; i++) { 19 | output1[output.length + i] = str.charAt(0) + output[i]; 20 | } 21 | return output1; 22 | } 23 | 24 | public static void printsubsequence(String original, String helper) { 25 | if (original.length() == 0) { 26 | System.out.println(helper); 27 | return; 28 | } 29 | printsubsequence(original.substring(1), helper); 30 | printsubsequence(original.substring(1), helper + original.charAt(0)); 31 | } 32 | 33 | public static void subsets(int start, int arr[], ArrayList helper) { 34 | if (start == arr.length) { 35 | for (int i = 0; i < helper.size(); i++) { 36 | System.out.print(helper.get(i) + " "); 37 | } 38 | System.out.println(); 39 | return; 40 | } 41 | helper.add(arr[start]); 42 | subsets(start + 1, arr, helper); 43 | helper.remove(helper.size() - 1); 44 | subsets(start + 1, arr, helper); 45 | } 46 | 47 | public static void main(String[] args) { 48 | int arr[] = { 5, 12, 3, 17, 1, 18, 15, 3, 17 }; 49 | ArrayList helper = new ArrayList<>(); 50 | subsets(0, arr, helper); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Some_important_algos/Reversing_Array.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Reversing_Array { 6 | static void swap(int[] arr, int index1, int index2) { 7 | int temp = arr[index1]; 8 | arr[index1] = arr[index2]; 9 | arr[index2] = temp; 10 | } 11 | 12 | static void reverse(int[] arr) { 13 | int start = 0; 14 | int end = arr.length - 1; 15 | while (start < end) { 16 | swap(arr, start, end); 17 | start++; 18 | end--; 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 24 | reverse(arr); 25 | System.out.println(Arrays.toString(arr)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Some_important_algos/Sieve_of_Eratosthenes.java: -------------------------------------------------------------------------------- 1 | package Some_important_algos; 2 | 3 | import java.util.*; 4 | 5 | public class Sieve_of_Eratosthenes { 6 | /* 7 | * This is one of the efficient way to find the number of prime numbers between 8 | * 1 and n(as given by the user) 9 | * The time complexity of this solution is O(Nlog(logN)) 10 | */ 11 | public static boolean sieve(int num) { 12 | int[] arr = new int[10000001]; 13 | arr[1] = 1; 14 | for (int i = 2; i * i <= arr.length; i++) { 15 | if (arr[i] == 0) { 16 | for (int j = 2 * i; j <= arr.length - 1; j += i) { 17 | arr[j] = 1; 18 | } 19 | } 20 | } 21 | if (arr[num] == 1) { 22 | return false; 23 | } else { 24 | return true; 25 | } 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(sieve(7)); 30 | } 31 | } -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SortArray(int* arr , int size){ 5 | //base case 6 | if(size == 0 || size == 1) return; 7 | 8 | for (size_t i = 0; i < size - 1; i++) 9 | { 10 | if(arr[i] > arr[i+1]){ 11 | swap(arr[i], arr[i+1]); 12 | } 13 | } 14 | 15 | SortArray(arr,size-1); 16 | 17 | } 18 | 19 | int main(int argc, char const *argv[]) 20 | { 21 | int arr[] = {1,5,3,8,6,9,4}; 22 | for (size_t i = 0; i < 7; i++) 23 | { 24 | cout << arr[i] << " "; 25 | } 26 | cout << endl << endl; 27 | SortArray(arr, 7); 28 | for (size_t i = 0; i < 7; i++) 29 | { 30 | cout << arr[i] << " "; 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void InsertionSort(int *arr, int size){ 5 | for (size_t i = 1; i < size; i++) 6 | { 7 | int temp = arr[i]; 8 | int j = i -1; 9 | while(arr[j] > temp){ 10 | arr[j+1] = arr[j]; 11 | j--; 12 | } 13 | arr[j+1] = temp; 14 | } 15 | 16 | } 17 | 18 | void InsertionSortRecursive(int * arr, int size){ 19 | 20 | if(size == 0 || size == 1) return; 21 | InsertionSortRecursive(arr,size-1); 22 | int temp = arr[size-1]; 23 | int j = size -2; 24 | while(arr[j] > temp){ 25 | arr[j+1] = arr[j]; 26 | j--; 27 | } 28 | arr[j+1] = temp; 29 | 30 | } 31 | 32 | int main(int argc, char const *argv[]) 33 | { 34 | int arr[] = {1,5,3,8,6,9,4}; 35 | for (size_t i = 0; i < 7; i++) 36 | { 37 | cout << arr[i] << " "; 38 | } 39 | cout << endl << endl; 40 | InsertionSortRecursive(arr, 7); 41 | for (size_t i = 0; i < 7; i++) 42 | { 43 | cout << arr[i] << " "; 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool linearSearch(int arr[], int size, int key){ 6 | 7 | if(size == 0) return false; 8 | 9 | if(arr[0] == key){ 10 | return true; 11 | 12 | } 13 | else{ 14 | bool rest = linearSearch(arr+1,size -1, key); 15 | return rest; 16 | } 17 | } 18 | 19 | int main(int argc, char const *argv[]) 20 | { 21 | int arr[5] = {3,5,1,2,6}; 22 | int size = 5; 23 | int key = 26; 24 | bool ans = linearSearch(arr, size, key); 25 | 26 | if(ans ){ 27 | cout << "Present " << endl; 28 | } 29 | else{ 30 | cout << "absent " << endl; 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int* arr, int s, int e){ 5 | int mid = s + (e-s)/2; 6 | 7 | int len1 = mid - s + 1; 8 | int len2 = e - mid; 9 | 10 | int *first = new int[len1]; 11 | int *second = new int[len2]; 12 | 13 | //copy values 14 | int mainArrayIndex = s; 15 | for(int i=0; i=e) 55 | return; 56 | 57 | int mid = s+(e-s)/2; 58 | MergeSort(arr,s,mid); 59 | MergeSort(arr,mid + 1,e); 60 | 61 | merge(arr,s,e); 62 | 63 | } 64 | 65 | int main(int argc, char const *argv[]) 66 | { 67 | int arr[] = {1,5,3,8,6,9,4}; 68 | for (size_t i = 0; i < 7; i++) 69 | { 70 | cout << arr[i] << " "; 71 | } 72 | cout << endl << endl; 73 | MergeSort(arr, 0,7); 74 | for (size_t i = 0; i < 7; i++) 75 | { 76 | cout << arr[i] << " "; 77 | } 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int partition(int* arr, int s, int e){ 5 | 6 | int temp = arr[s]; 7 | int count = 0; 8 | for (size_t x = s+1; x <= e; x++) 9 | { 10 | if(arr[x] <= temp) count++; 11 | } 12 | int pivot = s + count; 13 | // cout<< arr[pivot] << " "; 14 | swap(arr[pivot],arr[s]); 15 | int i = s, j = e; 16 | while(i < pivot && j > pivot){ 17 | while(arr[i] <= arr[pivot]) 18 | { 19 | i++; 20 | } 21 | 22 | while(arr[j] > arr[pivot]) { 23 | j--; 24 | } 25 | if(i < pivot && j > pivot){ 26 | swap(arr[i++], arr[j--]); 27 | } 28 | } 29 | return pivot; 30 | } 31 | 32 | void QuickSort(int* arr, int s, int e){ 33 | 34 | if(s>=e) return; 35 | 36 | int p = partition(arr,s,e); 37 | // cout << endl; 38 | 39 | QuickSort(arr,s,p-1); 40 | QuickSort(arr,p+1,e); 41 | } 42 | 43 | 44 | int main(int argc, char const *argv[]) 45 | { 46 | int arr[] = {1,5,3,8,6,9,4}; 47 | for (size_t i = 0; i < 7; i++) 48 | { 49 | cout << arr[i] << " "; 50 | } 51 | cout << endl << endl; 52 | QuickSort(arr, 0, 6); 53 | for (size_t i = 0; i < 7; i++) 54 | { 55 | cout << arr[i] << " "; 56 | } 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Sorting Algorithms (Recursion)/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void SelectionSortRecursive(int *arr, int size){ 5 | 6 | if(size == 0 || size == 1){ 7 | return; 8 | } 9 | int min = INT16_MAX; 10 | for (size_t i = 0; i < size; i++) 11 | { 12 | if(arr[i] < arr[min]) min = i; 13 | } 14 | swap(arr[0],arr[min]); 15 | SelectionSortRecursive(arr+1,size-1); 16 | 17 | } 18 | 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | int arr[] = {1,5,3,8,6,9,4}; 23 | for (size_t i = 0; i < 7; i++) 24 | { 25 | cout << arr[i] << " "; 26 | } 27 | cout << endl << endl; 28 | SelectionSortRecursive(arr, 7); 29 | for (size_t i = 0; i < 7; i++) 30 | { 31 | cout << arr[i] << " "; 32 | } 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/bubble-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubbleSort(int *, int); 5 | 6 | int main() 7 | { 8 | int n; // size 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) // input elements 13 | cin >> arr[i]; 14 | 15 | bubbleSort(arr, n); 16 | 17 | for (auto i : arr) // output 18 | cout << i << " "; 19 | 20 | cout << endl; 21 | 22 | return 0; 23 | } 24 | 25 | void bubbleSort(int *arr, int n) 26 | { 27 | for (int pass = 1; pass <= n - 1; pass++) // running passes 28 | { 29 | bool flag = false; // no swapping happened 30 | 31 | for (int i = 0; i <= n - pass - 1; i++) // traversing 32 | { 33 | if (arr[i] > arr[i + 1]) // for ascending order sorting 34 | { 35 | flag = true; // swapping happened 36 | 37 | // swap 38 | int temp = arr[i]; 39 | arr[i] = arr[i + 1]; 40 | arr[i + 1] = temp; 41 | } 42 | } 43 | 44 | if (!flag) // if (false == flag) i.e. if there is no swapping 45 | break; // no need for any more passes 46 | } 47 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/bucket-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | void bucketSort(std::vector& arr) { 5 | int n = arr.size(); 6 | if (n <= 0) return; 7 | 8 | //minimum and maximum values 9 | double min_val = *std::min_element(arr.begin(), arr.end()); 10 | double max_val = *std::max_element(arr.begin(), arr.end()); 11 | 12 | // Create buckets 13 | int num_buckets = n; 14 | std::vector> buckets(num_buckets); 15 | 16 | // Distribute elements into buckets 17 | for (int i = 0; i < n; i++) { 18 | int bucket_index = static_cast((arr[i] - min_val) / (max_val - min_val) * (num_buckets - 1)); 19 | buckets[bucket_index].push_back(arr[i]); 20 | } 21 | 22 | // Sort bucket 23 | for (int i = 0; i < num_buckets; i++) { 24 | std::sort(buckets[i].begin(), buckets[i].end()); 25 | } 26 | 27 | // Concatenate sorted buckets 28 | int index = 0; 29 | for (int i = 0; i < num_buckets; i++) { 30 | for (int j = 0; j < buckets[i].size(); j++) { 31 | arr[index++] = buckets[i][j]; 32 | } 33 | } 34 | } 35 | 36 | int main() { 37 | std::vector arr = {2,4,46,3,14,56,24}; 38 | 39 | std::cout << "Original array: "; 40 | for (double num : arr) { 41 | std::cout << num << " "; 42 | } 43 | std::cout << std::endl; 44 | 45 | bucketSort(arr); 46 | 47 | std::cout << "Sorted array: "; 48 | for (double num : arr) { 49 | std::cout << num << " "; 50 | } 51 | std::cout << std::endl; 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/count_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Function to perform Counting Sort 8 | void countingSort(vector& arr) { 9 | if (arr.empty()) { 10 | return; // Nothing to sort 11 | } 12 | 13 | // Find the maximum element in the array 14 | int max_val = *max_element(arr.begin(), arr.end()); 15 | 16 | // Create a count array to store the count of each element 17 | vector count(max_val + 1, 0); 18 | 19 | // Count the occurrences of each element 20 | for (int num : arr) { 21 | count[num]++; 22 | } 23 | 24 | // Reconstruct the sorted array 25 | int index = 0; 26 | for (int i = 0; i <= max_val; ++i) { 27 | while (count[i] > 0) { 28 | arr[index] = i; 29 | index++; 30 | count[i]--; 31 | } 32 | } 33 | } 34 | 35 | int main() { 36 | vector arr = {4, 2, 2, 8, 3, 3, 1}; 37 | 38 | cout << "Original array: "; 39 | for (int num : arr) { 40 | cout << num << " "; 41 | } 42 | cout << endl; 43 | 44 | countingSort(arr); 45 | 46 | cout << "Sorted array: "; 47 | for (int num : arr) { 48 | cout << num << " "; 49 | } 50 | cout << endl; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/insertion-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void insertionSort(int *, int); 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) 13 | cin >> arr[i]; 14 | 15 | insertionSort(arr, n); 16 | 17 | for (int i : arr) 18 | cout << i << " "; 19 | 20 | return 0; 21 | } 22 | 23 | void insertionSort(int arr[], int n) 24 | { 25 | for (int i = 1; i < n; i++) 26 | { 27 | int current = arr[i]; 28 | int j = i - 1; 29 | while (arr[j] > current && j >= 0) 30 | { 31 | arr[j + 1] = arr[j]; 32 | j--; 33 | } 34 | arr[j + 1] = current; 35 | } 36 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/merge-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int *, int, int *, int, int *, int); 5 | void mergeSort(int *, int); 6 | 7 | int main() 8 | { 9 | int n; // size of input array 10 | cin >> n; 11 | int arr[n]; 12 | 13 | for (int i = 0; i < n; i++) // input elements 14 | cin >> arr[i]; 15 | 16 | mergeSort(arr, n); 17 | 18 | for (auto i : arr) // output 19 | cout << i << " "; 20 | 21 | cout << endl; 22 | 23 | return 0; 24 | } 25 | 26 | void mergeSort(int *arr, int n) 27 | { 28 | if (n < 2) // base condition 29 | return; 30 | 31 | int mid = n / 2; 32 | int left[mid]; // creating left array 33 | int right[n - mid]; // creating right array 34 | 35 | for (int i = 0; i < mid; i++) // filling left array 36 | left[i] = arr[i]; 37 | for (int i = mid; i < n; i++) // filling right array 38 | right[i - mid] = arr[i]; 39 | 40 | mergeSort(left, mid); // merge sort left array 41 | mergeSort(right, n - mid); // merge sort right array 42 | 43 | merge(left, mid, right, n - mid, arr, n); // merge the sorted arrays back 44 | } 45 | 46 | void merge(int *left, int nL, int *right, int nR, int *arr, int n) 47 | { 48 | int i = 0, j = 0, k = 0; 49 | 50 | while (i < nL && j < nR) 51 | { 52 | if (left[i] <= right[j]) 53 | { 54 | arr[k] = left[i]; 55 | i++; 56 | // k++; 57 | } 58 | else 59 | { 60 | arr[k] = right[j]; 61 | j++; 62 | // k++; 63 | } 64 | k++; // irrespective of condititon 65 | } 66 | 67 | // to copy leftover element(s) 68 | while (i < nL) // to handle left array 69 | { 70 | arr[k] = left[i]; 71 | i++; 72 | k++; 73 | } 74 | while (j < nR) // to handle right array 75 | { 76 | arr[k] = right[j]; 77 | j++; 78 | k++; 79 | } 80 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/quick-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // to use swap() 3 | using namespace std; 4 | 5 | void quickSort(int[], int, int); 6 | 7 | int partition(int[], int, int); 8 | 9 | int main() 10 | { 11 | int n; 12 | cin >> n; 13 | int arr[n]; 14 | 15 | for (int i = 0; i < n; i++) 16 | cin >> arr[i]; // input array elements 17 | 18 | quickSort(arr, 0, n - 1); 19 | 20 | for (int i : arr) 21 | cout << i << " "; // printing array elements 22 | 23 | return 0; 24 | } 25 | 26 | void quickSort(int arr[], int low, int high) 27 | { 28 | if (low < high) // base condition 29 | { 30 | int PI = partition(arr, low, high); 31 | quickSort(arr, low, PI - 1); // recursive call 32 | quickSort(arr, PI + 1, high); // recursive call 33 | } 34 | } 35 | 36 | int partition(int arr[], int low, int high) 37 | { 38 | int pivot = arr[high]; 39 | int PI = low - 1; 40 | for (int i = low; i < high; i++) 41 | if (arr[i] < pivot) 42 | swap(arr[i], arr[++PI]); 43 | swap(arr[high], arr[++PI]); 44 | return PI; 45 | } 46 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int getMax(int arr[], int n){ 6 | int mx = arr[0]; 7 | for (int i = 1; i < n; i++) 8 | if (arr[i] > mx) 9 | mx = arr[i]; 10 | return mx; 11 | } 12 | 13 | 14 | 15 | 16 | void countSort(int arr[], int n, int exp){ 17 | 18 | int output[n]; 19 | int i, count[10] = { 0 }; 20 | 21 | 22 | for (i = 0; i < n; i++) 23 | count[(arr[i] / exp) % 10]++; 24 | 25 | 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i - 1]; 28 | 29 | for (i = n - 1; i >= 0; i--) { 30 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 31 | count[(arr[i] / exp) % 10]--; 32 | } 33 | 34 | for (i = 0; i < n; i++) 35 | arr[i] = output[i]; 36 | } 37 | 38 | 39 | 40 | 41 | void radixsort(int arr[], int n){ 42 | int m = getMax(arr, n); 43 | for (int exp = 1; m / exp > 0; exp *= 10) 44 | countSort(arr, n, exp); 45 | } 46 | 47 | 48 | 49 | 50 | void print(int arr[], int n){ 51 | for (int i = 0; i < n; i++) 52 | cout << arr[i] << " "; 53 | } 54 | 55 | 56 | 57 | 58 | int main(){ 59 | int arr[] = { 543, 986, 217, 765, 329 }; 60 | int n = sizeof(arr) / sizeof(arr[0]); 61 | 62 | // Function Call 63 | radixsort(arr, n); 64 | print(arr, n); 65 | return 0; 66 | } 67 | 68 | 69 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C++/selection-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void selectionSort(int *, int); 5 | 6 | int main() 7 | { 8 | int n; 9 | cin >> n; 10 | int arr[n]; 11 | 12 | for (int i = 0; i < n; i++) 13 | cin >> arr[i]; 14 | 15 | selectionSort(arr, n); 16 | 17 | for (int i : arr) 18 | cout << i << " "; 19 | 20 | return 0; 21 | } 22 | 23 | void selectionSort(int arr[], int n) 24 | { 25 | for (int i = 0; i < n - 1; i++) // selecting the first element of the unsorted array 26 | for (int j = i + 1; j < n; j++) // traversing the remaining array 27 | if (arr[j] < arr[i]) 28 | { 29 | int temp = arr[i]; 30 | arr[i] = arr[j]; // swapping 31 | arr[j] = temp; 32 | } 33 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/C/bubble_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void bubbleSort(int arr[], int n) { 4 | int temp; 5 | int swapped; 6 | 7 | for (int i = 0; i < n - 1; i++) { 8 | swapped = 0; // Flag to optimize the algorithm 9 | 10 | for (int j = 0; j < n - i - 1; j++) { 11 | if (arr[j] > arr[j + 1]) { 12 | // Swap arr[j] and arr[j+1] 13 | temp = arr[j]; 14 | arr[j] = arr[j + 1]; 15 | arr[j + 1] = temp; 16 | swapped = 1; // Set the flag to indicate a swap occurred 17 | } 18 | } 19 | 20 | // If no two elements were swapped in inner loop, the array is already sorted. 21 | if (swapped == 0) { 22 | break; 23 | } 24 | } 25 | } 26 | 27 | int main() { 28 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | 31 | printf("Original array: "); 32 | for (int i = 0; i < n; i++) { 33 | printf("%d ", arr[i]); 34 | } 35 | 36 | bubbleSort(arr, n); 37 | 38 | printf("\nSorted array: "); 39 | for (int i = 0; i < n; i++) { 40 | printf("%d ", arr[i]); 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C/insertion_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void insertionSort(int arr[], int n) { 4 | int i, key, j; 5 | for (i = 1; i < n; i++) { 6 | key = arr[i]; 7 | j = i - 1; 8 | 9 | // Move elements of arr[0..i-1] that are greater than key 10 | // to one position ahead of their current position 11 | while (j >= 0 && arr[j] > key) { 12 | arr[j + 1] = arr[j]; 13 | j = j - 1; 14 | } 15 | arr[j + 1] = key; 16 | } 17 | } 18 | 19 | int main() { 20 | int arr[] = {64, 34, 25,99, 12, 22, 11, 90}; 21 | int n = sizeof(arr) / sizeof(arr[0]); 22 | 23 | printf("Original array: "); 24 | for (int i = 0; i < n; i++) { 25 | printf("%d ", arr[i]); 26 | } 27 | 28 | insertionSort(arr, n); 29 | 30 | printf("\nSorted array: "); 31 | for (int i = 0; i < n; i++) { 32 | printf("%d ", arr[i]); 33 | } 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Sorting_Algorithm/C/selection_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void selectionSort(int arr[], int n) { 4 | int i, j, minIndex, temp; 5 | for (i = 0; i < n - 1; i++) { 6 | // Find the minimum element in the unsorted part of the array 7 | minIndex = i; 8 | for (j = i + 1; j < n; j++) { 9 | if (arr[j] < arr[minIndex]) { 10 | minIndex = j; 11 | } 12 | } 13 | 14 | // Swap the found minimum element with the first element 15 | temp = arr[i]; 16 | arr[i] = arr[minIndex]; 17 | arr[minIndex] = temp; 18 | } 19 | } 20 | 21 | int main() { 22 | int arr[] = {64, 34, 25, 12, 22, 11, 90,40}; 23 | int n = sizeof(arr) / sizeof(arr[0]); 24 | 25 | printf("Original array: "); 26 | for (int i = 0; i < n; i++) { 27 | printf("%d ", arr[i]); 28 | } 29 | 30 | selectionSort(arr, n); 31 | 32 | printf("\nSorted array: "); 33 | for (int i = 0; i < n; i++) { 34 | printf("%d ", arr[i]); 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/Bubble_sort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class Bubble_sort { 5 | public static void main(String[] args) { 6 | int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 7 | for (int i = 0; i < arr.length; i++) { 8 | for (int j = 0; j < arr.length - i - 1; j++) { 9 | if (arr[j] > arr[j + 1]) { 10 | int temp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = temp; 13 | } 14 | } 15 | } 16 | System.out.println(Arrays.toString(arr)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/CountSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class CountSort { 4 | 5 | public static void countSort(int[] arr) { 6 | if (arr == null || arr.length <= 1) { 7 | return; // Nothing to sort 8 | } 9 | 10 | // Find the maximum element in the array 11 | int maxVal = Arrays.stream(arr).max().getAsInt(); 12 | 13 | // Create a count array to store the count of each element 14 | int[] count = new int[maxVal + 1]; 15 | 16 | // Count the occurrences of each element 17 | for (int num : arr) { 18 | count[num]++; 19 | } 20 | 21 | // Reconstruct the sorted array 22 | int index = 0; 23 | for (int i = 0; i <= maxVal; i++) { 24 | while (count[i] > 0) { 25 | arr[index] = i; 26 | index++; 27 | count[i]--; 28 | } 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | int[] arr = {4, 2, 2, 8, 3, 3, 1}; 34 | 35 | System.out.print("Original array: "); 36 | for (int num : arr) { 37 | System.out.print(num + " "); 38 | } 39 | System.out.println(); 40 | 41 | countSort(arr); 42 | 43 | System.out.print("Sorted array: "); 44 | for (int num : arr) { 45 | System.out.print(num + " "); 46 | } 47 | System.out.println(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/Cycle_sort.java: -------------------------------------------------------------------------------- 1 | //What is Cycle sort 2 | //When we are given numbers from 1 to N (not necessarily exactly from 1 to N) we use cycle sort. 3 | //It sorts the entire array in one single pass. 4 | //The basic idea behind cycle sort is the sorted array will contain elements on their correct index. 5 | //For eg. - elements from 1 to 5 will be on index 0 to 4 in the sorted array. 6 | //Advantages are :- It sorts the array in-place and does not require additional memory for temporary variables. 7 | 8 | //Here is the link for leetcode question which is solved using cycle sort. 9 | //https://leetcode.com/problems/missing-number/ 10 | 11 | 12 | public class CycleSort { 13 | 14 | public static void swap(int arr[],int start,int end) 15 | { 16 | int temp=arr[start]; 17 | arr[start]=arr[end]; 18 | arr[end]=temp; 19 | } 20 | 21 | public static void cycleSort(int arr[]) 22 | { 23 | int i=0; 24 | while(i= 0; i--) { 31 | downheapify(arr, i, arr.length); 32 | } 33 | for (int i = arr.length - 1; i >= 0; i--) { 34 | int temp = arr[i]; 35 | arr[i] = arr[0]; 36 | arr[0] = temp; 37 | downheapify(arr, 0, i); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | int[] arr = { 1, 2, 3, 4, 5 }; 43 | Heapsort(arr); 44 | for (int i = arr.length - 1; i >= 0; i--) { 45 | System.out.print(arr[i] + " "); 46 | } 47 | System.out.println(); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/Insertion_sort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class Insertion_sort { 5 | public static void Sort(int[] arr) { 6 | for (int i = 0; i < arr.length - 1; i++) { 7 | for (int j = i + 1; j > 0; j--) { 8 | if (arr[j] < arr[j - 1]) { 9 | swap(arr, j, j - 1); 10 | } else { 11 | break; 12 | } 13 | } 14 | } 15 | } 16 | 17 | public static void swap(int[] arr, int index1, int index2) { 18 | int temp = arr[index2]; 19 | arr[index2] = arr[index1]; 20 | arr[index1] = temp; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int[] arr = { 5, 4, 3, 2, 1 }; 25 | Sort(arr); 26 | System.out.println(Arrays.toString(arr)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/MergeSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class MergeSort { 5 | public static void merge(int a[], int b[], int c[]) { 6 | int i = 0; 7 | int j = 0; 8 | int k = 0; 9 | while (i < a.length && j < b.length) { 10 | if (a[i] <= b[j]) { 11 | c[k] = a[i]; 12 | i++; 13 | k++; 14 | } else { 15 | c[k] = b[j]; 16 | j++; 17 | k++; 18 | } 19 | } 20 | if (i < a.length) { 21 | while (i < a.length) { 22 | c[k] = a[i]; 23 | i++; 24 | k++; 25 | } 26 | } 27 | if (j < b.length) { 28 | while (j < b.length) { 29 | c[k] = b[j]; 30 | j++; 31 | k++; 32 | } 33 | } 34 | } 35 | 36 | public static void mergesort(int arr[]) { 37 | if (arr.length <= 1) { 38 | return; 39 | } 40 | int[] a = new int[arr.length / 2]; 41 | int[] b = new int[arr.length - a.length]; 42 | for (int i = 0; i < arr.length / 2; i++) { 43 | a[i] = arr[i]; 44 | } 45 | for (int i = arr.length / 2; i < arr.length; i++) { 46 | b[i - arr.length / 2] = arr[i]; 47 | } 48 | mergesort(a); 49 | mergesort(b); 50 | merge(a, b, arr); 51 | } 52 | 53 | public static void main(String[] args) { 54 | int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 55 | System.out.println("Before Sorting:"); 56 | System.out.println(Arrays.toString(arr)); 57 | mergesort(arr); 58 | System.out.println("After Sorting:"); 59 | System.out.println(Arrays.toString(arr)); 60 | } 61 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/QuickSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class QuickSort { 5 | public static int partition(int arr[], int s, int e) { 6 | int pivotelement = arr[s]; 7 | int count = 0; 8 | for (int i = s + 1; i <= e; i++) { 9 | if (arr[i] < pivotelement) { 10 | count++; 11 | } 12 | } 13 | int temp = arr[s + count]; 14 | arr[s + count] = arr[s]; 15 | arr[s] = temp; 16 | int i = s; 17 | int j = e; 18 | while (i < j) { 19 | if (arr[i] < pivotelement) { 20 | i++; 21 | } else if (arr[j] >= pivotelement) { 22 | j--; 23 | } else { 24 | temp = arr[i]; 25 | arr[i] = arr[j]; 26 | arr[j] = temp; 27 | i++; 28 | j--; 29 | } 30 | } 31 | return s + count; 32 | } 33 | 34 | public static void quicksort(int[] arr, int s, int e) { 35 | if (s >= e) { 36 | return; 37 | } 38 | int pivotindex = partition(arr, s, e); 39 | quicksort(arr, s, pivotindex - 1); 40 | quicksort(arr, pivotindex + 1, e); 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 45 | quicksort(arr, 0, arr.length - 1); 46 | System.out.println(Arrays.toString(arr)); 47 | } 48 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/RadixSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class RadixSort { 4 | 5 | 6 | void countingSort(int array[], int size, int place) { 7 | int[] output = new int[size + 1]; 8 | int max = array[0]; 9 | for (int i = 1; i < size; i++) { 10 | if (array[i] > max) 11 | max = array[i]; 12 | } 13 | int[] count = new int[max + 1]; 14 | 15 | for (int i = 0; i < max; ++i) 16 | count[i] = 0; 17 | 18 | 19 | for (int i = 0; i < size; i++) 20 | count[(array[i] / place) % 10]++; 21 | 22 | 23 | for (int i = 1; i < 10; i++) 24 | count[i] += count[i - 1]; 25 | 26 | 27 | for (int i = size - 1; i >= 0; i--) { 28 | output[count[(array[i] / place) % 10] - 1] = array[i]; 29 | count[(array[i] / place) % 10]--; 30 | } 31 | 32 | for (int i = 0; i < size; i++) 33 | array[i] = output[i]; 34 | } 35 | 36 | 37 | int getMax(int array[], int n) { 38 | int max = array[0]; 39 | for (int i = 1; i < n; i++) 40 | if (array[i] > max) 41 | max = array[i]; 42 | return max; 43 | } 44 | 45 | 46 | void radixSort(int array[], int size) { 47 | // Get max element 48 | int max = getMax(array, size); 49 | 50 | for (int place = 1; max / place > 0; place *= 10) 51 | countingSort(array, size, place); 52 | } 53 | 54 | 55 | public static void main(String args[]) { 56 | int[] arr = { 12,87,98,123,99,467}; 57 | int size = arr.length; 58 | RadixSort rs = new RadixSort(); 59 | rs.radixSort(arr, size); 60 | System.out.println("Sorted Array "); 61 | System.out.println(Arrays.toString(arr)); 62 | } 63 | } -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/Selection_sort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class Selection_sort { 5 | public static void main(String[] args) { 6 | int[] arr = { 3, 5, 6, 1, 2 }; 7 | for (int i = 0; i < arr.length; i++) { 8 | int min = Integer.MAX_VALUE; 9 | int index = 0; 10 | for (int j = i; j < arr.length; j++) { 11 | if (arr[j] < min) { 12 | min = arr[j]; 13 | index = j; 14 | } 15 | } 16 | int temp = arr[i]; 17 | arr[i] = arr[index]; 18 | arr[index] = temp; 19 | } 20 | System.out.println(Arrays.toString(arr)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Sorting_Algorithm/JAVA/ShellSort: -------------------------------------------------------------------------------- 1 | // Java implementation of ShellSort 2 | class ShellSort 3 | { 4 | /* An utility function to print array of size n*/ 5 | static void printArray(int arr[]) 6 | { 7 | int n = arr.length; 8 | for (int i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting"); 51 | printArray(arr); 52 | 53 | ShellSort ob = new ShellSort(); 54 | ob.sort(arr); 55 | 56 | System.out.println("Array after sorting"); 57 | printArray(arr); 58 | } 59 | } 60 | /*This code is contributed by Rajat Mishra */ 61 | -------------------------------------------------------------------------------- /Sorting_Algorithm/PYTHON/MergeSort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(arr): 2 | if len(arr) > 1: 3 | mid = len(arr)//2 # Finding the mid of the array 4 | L = arr[:mid] # Dividing the array elements 5 | R = arr[mid:] # Into 2 halves 6 | mergeSort(L) # Sorting the first half 7 | mergeSort(R) # Sorting the second half 8 | i = j = k = 0 9 | while i < len(L) and j < len(R): # Copy data to temp arrays L[] and R[] 10 | if L[i] <= R[j]: 11 | arr[k] = L[i] 12 | i += 1 13 | else: 14 | arr[k] = R[j] 15 | j += 1 16 | k += 1 17 | while i < len(L): # Checking if any element was left 18 | arr[k] = L[i] 19 | i += 1 20 | k += 1 21 | while j < len(R): 22 | arr[k] = R[j] 23 | j += 1 24 | k += 1 25 | 26 | # Code to print the list 27 | def printList(arr): 28 | for i in range(len(arr)): 29 | print(arr[i], end=" ") 30 | print() 31 | 32 | # Driver Code 33 | if __name__ == '__main__': 34 | arr = [12, 11, 13, 5, 6, 7] 35 | print("Given array is") 36 | printList(arr) 37 | mergeSort(arr) 38 | print("\nSorted array is ") 39 | printList(arr) 40 | 41 | """ 42 | Output: 43 | Given array is 44 | 12 11 13 5 6 7 45 | 46 | Sorted array is 47 | 5 6 7 11 12 13 48 | """ -------------------------------------------------------------------------------- /Sorting_Algorithm/PYTHON/bubbleSort.py: -------------------------------------------------------------------------------- 1 | def sort(arr): 2 | ''' 3 | Method to perform bubble sort to sort an array in ascending order. 4 | 5 | Args: arr (List) 6 | 7 | Returns: Sorted array (List) 8 | ''' 9 | for i in range (len(arr)-1): 10 | for j in range(len(arr)-i-1): 11 | if arr[j] > arr[j+1] : 12 | arr[j],arr[j+1] = arr[j+1],arr[j] 13 | return arr 14 | 15 | if __name__ == "__main__": 16 | n = int(input("Enter number of elements: ")) 17 | array=[] 18 | print("Enter the elements:") 19 | for i in range(n): 20 | x = int(input("")) 21 | array.append(x) 22 | print(f"Original array: {array}") 23 | array = sort(array) 24 | print(f"Array after bubble sort: {array}") 25 | 26 | 27 | """ 28 | Output: 29 | 30 | Enter number of elements: 5 31 | Enter the elements: 32 | 1 33 | 6 34 | 10 35 | 4 36 | 3 37 | Original array: [1, 6, 10, 4, 3] 38 | Array after bubble sort: [1, 3, 4, 6, 10] 39 | """ 40 | -------------------------------------------------------------------------------- /Sorting_Algorithm/PYTHON/quickSort.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def quickSort(self, arr, s, e): 3 | if s >= e: 4 | return 5 | p = self.partition(arr, s, e) 6 | self.quickSort(arr, s, p - 1) 7 | self.quickSort(arr, p + 1, e) 8 | 9 | def partition(self, arr, s, e): 10 | pivot = arr[s] 11 | count = 0 12 | 13 | for i in range(s + 1, e + 1): 14 | if arr[i] < pivot: 15 | count += 1 16 | 17 | pivot_index = s + count 18 | arr[s], arr[pivot_index] = arr[pivot_index], arr[s] 19 | 20 | i, j = s, e 21 | while i < pivot_index and j > pivot_index: 22 | while arr[i] < pivot: 23 | i += 1 24 | while arr[j] > pivot: 25 | j -= 1 26 | if i < pivot_index and j > pivot_index: 27 | arr[i], arr[j] = arr[j], arr[i] 28 | i += 1 29 | j -= 1 30 | 31 | return pivot_index 32 | 33 | 34 | def printlist(arr): 35 | for num in arr: 36 | print(num, end=" ") 37 | print() 38 | 39 | 40 | 41 | 42 | n = int(input()) 43 | arr = list(map(int, input().split())) 44 | solution = Solution() 45 | solution.quickSort(arr, 0, n - 1) 46 | printlist(arr) 47 | -------------------------------------------------------------------------------- /Sorting_Algorithm/PYTHON/selectionSort.py: -------------------------------------------------------------------------------- 1 | def sort(arr): 2 | ''' 3 | Method to perform selection sort to sort an array in ascending order. 4 | 5 | Args: arr (List) 6 | 7 | Returns: Sorted array (List) 8 | ''' 9 | for i in range (len(arr)): 10 | for j in range(i+1,len(arr)): 11 | if arr[i] > arr[j] : 12 | arr[i],arr[j] = arr[j],arr[i] 13 | return arr 14 | 15 | if __name__ == "__main__": 16 | n = int(input("Enter number of elements: ")) 17 | array=[] 18 | print("Enter the elements:") 19 | for i in range(n): 20 | x = int(input("")) 21 | array.append(x) 22 | print(f"Original array: {array}") 23 | array = sort(array) 24 | print(f"Array after selection sort: {array}") 25 | 26 | 27 | """ 28 | Output: 29 | 30 | Enter number of elements: 5 31 | Enter the elements: 32 | 1 33 | 6 34 | 10 35 | 4 36 | 3 37 | Original array: [1, 6, 10, 4, 3] 38 | Array after selection sort: [1, 3, 4, 6, 10] 39 | """ 40 | -------------------------------------------------------------------------------- /Stack/C++/arrayImplementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define size 10 4 | class Stack 5 | { 6 | int arr[size]; 7 | int top = -1; 8 | public: 9 | void push(int data) 10 | { 11 | if (top == size - 1) 12 | { 13 | cout << "Stack overflow !" << endl << "Exiting..." << endl; 14 | exit(1); 15 | } 16 | arr[++top] = data; 17 | } 18 | void pop() 19 | { 20 | if (top == -1) 21 | { 22 | cout << "Stack underflow !" << endl << "Exiting..." << endl; 23 | exit(2); 24 | } 25 | top--; 26 | } 27 | int peek() 28 | { 29 | if (top == -1) 30 | { 31 | cout << "Stack empty !" << endl << "Exiting..." << endl; 32 | exit(3); 33 | } 34 | return arr[top]; 35 | } 36 | bool isEmpty() 37 | { 38 | if (top == -1) 39 | return true; 40 | return false; 41 | } 42 | void display() 43 | { 44 | if (isEmpty()) 45 | cout << "Stack empty !"; 46 | else 47 | for (int i = 0; i <= top; i++) 48 | cout << arr[i] << " "; 49 | cout << endl; 50 | } 51 | 52 | }; 53 | int main() 54 | { 55 | Stack s; 56 | s.push(1); 57 | s.push(2); 58 | s.display(); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Stack/C++/checkBalancedParentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool checkValidPair(char opening, char closing) 5 | { 6 | if ((opening == '(' && closing == ')') || (opening == '{' && closing == '}') || (opening == '[' && closing == ']')) 7 | return true; 8 | return false; 9 | } 10 | bool checkParenthesesBalanced(string expression) 11 | { 12 | stack s; 13 | for (int i = 0; i < expression.length(); i++) 14 | if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[') 15 | s.push(expression[i]); 16 | else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']') 17 | if (s.empty() || !checkValidPair(s.top(), expression[i])) 18 | return false; 19 | else 20 | s.pop(); 21 | return s.empty() ? true : false; 22 | } 23 | int main() 24 | { 25 | string expression; 26 | cin >> expression; 27 | if (checkParenthesesBalanced(expression)) 28 | cout << "Balanced"; 29 | else 30 | cout << "Not balanced"; 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Stack/C++/evaluatePostfix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int performOperation(char operation, int operand1, int operand2) 5 | { 6 | if (operation == '+') 7 | return operand1 + operand2; 8 | else if (operation == '-') 9 | return operand1 - operand2; 10 | else if (operation == '*') 11 | return operand1 * operand2; 12 | else if (operation == '/') 13 | return operand1 / operand2; 14 | else 15 | exit(1); 16 | } 17 | bool isValidOperator(char ch) 18 | { 19 | return (ch == '+' || ch == '-' || ch == '*' || ch == '/') ? true : false; 20 | } 21 | bool isValidNumber(char ch) 22 | { 23 | return (ch >= '0' && ch <= '9') ? true : false; 24 | } 25 | int evaluatePostfix(string expression) 26 | { 27 | stack s; 28 | for (int i = 0; i < expression.length(); i++) 29 | { 30 | if (expression[i] == ' ' || expression[i] == ',') 31 | continue; 32 | else if (isValidOperator(expression[i])) 33 | { 34 | int operand2 = s.top(); 35 | s.pop(); 36 | int operand1 = s.top(); 37 | s.pop(); 38 | s.push(performOperation(expression[i], operand1, operand2)); 39 | } 40 | else if(isValidNumber(expression[i])) 41 | { 42 | int operand = 0; 43 | while (i < expression.length() && isValidNumber(expression[i])) 44 | { 45 | operand = (operand * 10) + (expression[i] - '0'); 46 | i++; 47 | } 48 | i--; 49 | s.push(operand); 50 | } 51 | } 52 | return s.top(); 53 | } 54 | int main() 55 | { 56 | string expression; 57 | getline(cin, expression); 58 | cout << evaluatePostfix(expression); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Stack/C++/evaluatePrefix.cpp: -------------------------------------------------------------------------------- 1 | //This code works for single digit values only. Ex : '+ 2 6' 2 | #include 3 | #include 4 | using namespace std; 5 | int performOperation(char operation, int operand1, int operand2) 6 | { 7 | if (operation == '+') 8 | return operand1 + operand2; 9 | else if (operation == '-') 10 | return operand1 - operand2; 11 | else if (operation == '*') 12 | return operand1 * operand2; 13 | else if (operation == '/') 14 | return operand1 / operand2; 15 | else 16 | exit(1); 17 | } 18 | bool isValidOperator(char ch) 19 | { 20 | return (ch == '+' || ch == '-' || ch == '*' || ch == '/') ? true : false; 21 | } 22 | bool isValidNumber(char ch) 23 | { 24 | return (ch >= '0' && ch <= '9') ? true : false; 25 | } 26 | int evaluatePrefix(string expression) 27 | { 28 | stack s; 29 | for (int i = expression.length() - 1; i >= 0; i--) 30 | { 31 | if (expression[i] == ' ' || expression[i] == ',') 32 | continue; 33 | else if (isValidOperator(expression[i])) 34 | { 35 | int operand1 = s.top(); 36 | s.pop(); 37 | int operand2 = s.top(); 38 | s.pop(); 39 | s.push(performOperation(expression[i], operand1, operand2)); 40 | } 41 | else if (isValidNumber(expression[i])) 42 | s.push(expression[i] - '0'); 43 | } 44 | return s.top(); 45 | } 46 | int main() 47 | { 48 | string expression; 49 | getline(cin, expression); 50 | cout << evaluatePrefix(expression); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Stack/C++/infixToPostfix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool isRightAssociative(char op) 5 | { 6 | return (op == '^') ? true : false; 7 | } 8 | int getOperatorWeight(char op) 9 | { 10 | int weight = -1; 11 | switch (op) 12 | { 13 | case '+': 14 | case '-': 15 | weight = 1; 16 | break; 17 | case '*': 18 | case '/': 19 | weight = 2; 20 | break; 21 | case '^': 22 | weight = 3; 23 | } 24 | return weight; 25 | } 26 | bool hasHigherPrecedence(char op1, char op2) 27 | { 28 | int operator1Weight = getOperatorWeight(op1); 29 | int operator2Weight = getOperatorWeight(op2); 30 | if (operator1Weight == operator2Weight) 31 | return isRightAssociative(op1) ? false : true; 32 | return (operator1Weight > operator2Weight) ? true : false; 33 | } 34 | bool isClosingParentheses(char ch) 35 | { 36 | return (ch == ')' || ch == '}' || ch == ']') ? true : false; 37 | } 38 | bool isOpeningParentheses(char ch) 39 | { 40 | return (ch == '(' || ch == '{' || ch == '[') ? true : false; 41 | } 42 | bool isOperator(char ch) 43 | { 44 | return (ch == '+' || ch == '-' || ch == '*' || ch == '/') ? true : false; 45 | } 46 | bool isOperand(char ch) 47 | { 48 | return ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) ? true : false; 49 | } 50 | string infixToPostfix(string expression) 51 | { 52 | stack s; 53 | string postfix; 54 | for (int i = 0; i < expression.length(); i++) 55 | { 56 | if (expression[i] == ' ' || expression[i] == ',') 57 | continue; 58 | else if (isOperand(expression[i])) 59 | postfix += expression[i]; 60 | else if (isOperator(expression[i])) 61 | { 62 | while (!s.empty() && !isOpeningParentheses(s.top()) && hasHigherPrecedence(s.top(), expression[i])) 63 | { 64 | postfix += s.top(); 65 | s.pop(); 66 | } 67 | s.push(expression[i]); 68 | } 69 | else if (isOpeningParentheses(expression[i])) 70 | s.push(expression[i]); 71 | else if (isClosingParentheses) 72 | { 73 | while (!s.empty() && !isOpeningParentheses(s.top())) 74 | { 75 | postfix += s.top(); 76 | s.pop(); 77 | } 78 | s.pop(); 79 | } 80 | } 81 | while (!s.empty()) 82 | { 83 | postfix += s.top(); 84 | s.pop(); 85 | } 86 | return postfix; 87 | } 88 | int main() 89 | { 90 | string expression; 91 | getline(cin, expression); 92 | cout << infixToPostfix(expression); 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /Stack/C++/linkedListImplementation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | Node(int data) 9 | { 10 | this -> data = data; 11 | this -> next = nullptr; 12 | } 13 | }; 14 | class Stack 15 | { 16 | Node *top = nullptr; 17 | public: 18 | void push(int data) 19 | { 20 | Node *newNode = new Node(data); 21 | newNode -> next = top; 22 | top = newNode; 23 | } 24 | void pop() 25 | { 26 | if (!top) 27 | { 28 | cout << "Stack underflow !" << endl; 29 | exit(1); 30 | } 31 | Node *temp = top; 32 | top = top -> next; 33 | delete temp; 34 | } 35 | int peek() 36 | { 37 | if (!top) 38 | { 39 | cout << "Stack empty !" << endl; 40 | exit(2); 41 | } 42 | return top -> data; 43 | } 44 | bool isEmpty() 45 | { 46 | if (!top) 47 | return true; 48 | return false; 49 | } 50 | }; 51 | int main() 52 | { 53 | Stack s; 54 | s.push(3); 55 | s.push(2); 56 | s.push(1); 57 | s.pop(); 58 | cout << s.peek(); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Stack/C/array based implementation/main.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | #define create(stack) Stack*stack=create() 3 | 4 | int main() 5 | { 6 | create(stack); 7 | 8 | for (int i = 1; i <= 10; push(stack, i++)); 9 | pop(stack); 10 | pop(stack); 11 | pop(stack); 12 | top(stack); 13 | 14 | return 0; 15 | } -------------------------------------------------------------------------------- /Stack/C/array based implementation/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | #include 3 | #define length(arr) (sizeof (arr) / sizeof *(arr)) 4 | 5 | struct Stack 6 | { 7 | int arr[10]; 8 | int top; 9 | }; 10 | 11 | Stack *create(void) 12 | { 13 | Stack *stack = malloc(sizeof(Stack)); 14 | if (!stack) 15 | return NULL; 16 | stack->top = -1; 17 | return stack; 18 | } 19 | 20 | inline static _Bool overflow(Stack *stack) 21 | { 22 | return length(stack->arr) - 1 == stack->top; 23 | } 24 | 25 | inline static _Bool underflow(Stack *stack) 26 | { 27 | return -1 == stack->top; 28 | } 29 | 30 | int printf(const char *, ...); 31 | 32 | void push(Stack *stack, int data) 33 | { 34 | if (overflow(stack)) 35 | printf("Stack overflow!\n"); 36 | else 37 | stack->arr[++(stack->top)] = data; 38 | } 39 | 40 | void pop(Stack *stack) 41 | { 42 | if (underflow(stack)) 43 | printf("Stack underflow!\n"); 44 | else 45 | printf("%d\n", stack->arr[(stack->top)--]); 46 | } 47 | 48 | void top(Stack *stack) 49 | { 50 | if (underflow(stack)) 51 | printf("Stack underflow!\n"); 52 | else 53 | printf("%d\n", stack->arr[stack->top]); 54 | } -------------------------------------------------------------------------------- /Stack/C/array based implementation/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | typedef struct Stack Stack; 5 | Stack *create(void); 6 | void push(Stack *, int); 7 | void pop(Stack *); 8 | void top(Stack *); 9 | 10 | #endif -------------------------------------------------------------------------------- /Stack/C/linked list based implementation/main.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | #define create(stack) Stack*stack=create() 3 | 4 | int main() 5 | { 6 | create(stack); 7 | 8 | for (int i = 1; i <= 10; push(stack, i++)); 9 | pop(stack); 10 | pop(stack); 11 | pop(stack); 12 | top(stack); 13 | 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Stack/C/linked list based implementation/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | #include 3 | #define capacity 10 4 | 5 | struct Node 6 | { 7 | int data; 8 | Node *next; 9 | }; 10 | 11 | struct Stack 12 | { 13 | Node *top; 14 | int count; 15 | }; 16 | 17 | Stack *create(void) 18 | { 19 | Stack *stack = malloc(sizeof(Stack)); 20 | if (!stack) 21 | return NULL; 22 | stack->top = NULL; 23 | stack->count = 0; 24 | return stack; 25 | } 26 | 27 | inline static _Bool overflow(Stack *stack) 28 | { 29 | return capacity == stack->count; 30 | } 31 | 32 | inline static _Bool underflow(Stack *stack) 33 | { 34 | return !stack->count; 35 | } 36 | 37 | int printf(const char *, ...); 38 | 39 | void push(Stack *stack, int data) 40 | { 41 | if (overflow(stack)) 42 | printf("Stack overflow!\n"); 43 | else 44 | { 45 | Node *newNode = malloc(sizeof(Node)); 46 | if (!newNode) 47 | return; 48 | if (!stack->count) // for the first inserted node 49 | newNode->next = NULL; 50 | newNode->data = data; 51 | newNode->next = stack->top; 52 | stack->top = newNode; 53 | stack->count++; 54 | } 55 | } 56 | 57 | void pop(Stack *stack) 58 | { 59 | if (underflow(stack)) 60 | printf("Stack underflow!\n"); 61 | else 62 | { 63 | printf("%d\n", stack->top->data); 64 | 65 | Node *del = stack->top; 66 | stack->top = stack->top->next; 67 | free(del); 68 | stack->count--; 69 | } 70 | } 71 | 72 | void top(Stack *stack) 73 | { 74 | if (underflow(stack)) 75 | printf("Stack underflow!\n"); 76 | else 77 | printf("%d\n", stack->top->data); 78 | } -------------------------------------------------------------------------------- /Stack/C/linked list based implementation/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | typedef struct Node Node; 5 | typedef struct Stack Stack; 6 | Stack *create(void); 7 | void push(Stack *, int); 8 | void pop(Stack *); 9 | void top(Stack *); 10 | 11 | #endif -------------------------------------------------------------------------------- /Stack/JAVA/123Pattern.java: -------------------------------------------------------------------------------- 1 | 2 | //Leetcode solution 3 | import java.util.*; 4 | 5 | class Solution { 6 | public boolean find132pattern(int[] nums) { 7 | if (nums.length < 3) 8 | return false; 9 | 10 | int[] minI = new int[nums.length]; 11 | minI[0] = nums[0]; 12 | 13 | for (int i = 1; i < nums.length; i++) { 14 | minI[i] = Math.min(minI[i - 1], nums[i]); 15 | } 16 | 17 | Stack stack = new Stack<>(); 18 | 19 | for (int j = nums.length - 1; j >= 0; j--) { 20 | if (nums[j] > minI[j]) { 21 | while (!stack.isEmpty() && stack.peek() <= minI[j]) { 22 | stack.pop(); 23 | } 24 | 25 | if (!stack.isEmpty() && stack.peek() < nums[j]) { 26 | return true; 27 | } 28 | 29 | stack.push(nums[j]); 30 | } 31 | } 32 | return false; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Stack/JAVA/BalancedParanthesis.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class BalancedParanthesis { 5 | public static boolean helper(String str) { 6 | Stack stack = new Stack<>(); 7 | for (int i = 0; i < str.length(); i++) { 8 | Character c = str.charAt(i); 9 | if (c == '(' || c == '[' || c == '{') { 10 | stack.push(c); 11 | // System.out.println(stack.toString()); 12 | } else { 13 | if (stack.isEmpty()) { 14 | return false; 15 | } else { 16 | if (stack.peek() == '(' && c == ')' || stack.peek() == '{' && c == '}' 17 | || stack.peek() == '[' && c == ']') { 18 | stack.pop(); 19 | } else { 20 | return false; 21 | } 22 | } 23 | } 24 | } 25 | return stack.isEmpty(); 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner input = new Scanner(System.in); 30 | String str = input.next(); 31 | System.out.println(helper(str)); 32 | input.close(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Stack/JAVA/BasicStack.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Stack; 3 | 4 | public class BasicStack { 5 | public static void main(String[] args) { 6 | Stack stack = new Stack<>(); 7 | stack.push(23); 8 | stack.push(1); 9 | stack.push(67); 10 | stack.push(100); 11 | 12 | System.out.println(stack.pop()); 13 | System.out.println(stack.pop()); 14 | System.out.println(stack.pop()); 15 | System.out.println(stack.pop()); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Stack/JAVA/CheckRedundantBrackets.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class CheckRedundantBrackets { 5 | /* 6 | * For a given expression in the form of a string, find if there exist any 7 | * redundant brackets or not. It is given that the expression contains only 8 | * rounded brackets or parenthesis and the input expression will always be 9 | * balanced. 10 | * A pair of the bracket is said to be redundant when a sub-expression is 11 | * surrounded by unnecessary or needless brackets. 12 | */ 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | String str = input.next(); 16 | Stack stack = new Stack<>(); 17 | boolean a = true; 18 | for (int i = 0; i < str.length(); i++) { 19 | char c = str.charAt(i); 20 | if (c != ')') { 21 | stack.push(c); 22 | } else { 23 | System.out.println(stack); 24 | int count = 0; 25 | while (stack.peek() != '(') { 26 | count++; 27 | stack.pop(); 28 | } 29 | if (count > 1) { 30 | a = false; 31 | } else if (count == 0 || count == 1) { 32 | a = true; 33 | break; 34 | } 35 | count = 0; 36 | stack.pop(); 37 | } 38 | } 39 | System.out.println(a); 40 | input.close(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Stack/JAVA/CustomStack.java: -------------------------------------------------------------------------------- 1 | 2 | public class CustomStack { 3 | protected int[] data; 4 | private static final int DEFAULT_SIZE = 10; 5 | 6 | int ptr = -1; 7 | 8 | public CustomStack() { 9 | this(DEFAULT_SIZE); 10 | } 11 | 12 | public CustomStack(int size) { 13 | this.data = new int[size]; 14 | } 15 | 16 | public boolean push(int item) { 17 | if (isFull()) { 18 | System.out.println("Stack is Full"); 19 | return false; 20 | } 21 | ptr++; 22 | data[ptr] = item; 23 | return true; 24 | } 25 | 26 | public int pop() throws Exception { 27 | if (isEmpty()) { 28 | throw new Exception("cannot pop from an empty stack"); 29 | } 30 | int removed = data[ptr]; 31 | ptr--; 32 | return removed; 33 | } 34 | 35 | public int peek() throws Exception { 36 | if (isEmpty()) { 37 | throw new Exception("cannot pop from an empty stack"); 38 | } 39 | return data[ptr]; 40 | } 41 | 42 | public boolean isFull() { 43 | return ptr == data.length - 1; // pointer is at last index 44 | } 45 | 46 | public boolean isEmpty() { 47 | return ptr == -1; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Stack/JAVA/DistanceNearestGreaterElementOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class DistanceNearestGreaterElementOnRight { 6 | public static void main(String[] args) { 7 | int arr[]=new int[]{4, 5, 2, 10, 8}; 8 | System.out.println(Arrays.toString(distanceNearestGreaterElementOnRight(arr))); 9 | } 10 | public static int[] distanceNearestGreaterElementOnRight(int[] arr) { 11 | Stack stack = new Stack<>(); 12 | int[] result = new int[arr.length]; 13 | 14 | for (int i = arr.length-1; i >= 0; i--) { 15 | while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) { 16 | stack.pop(); 17 | } 18 | if (stack.isEmpty()) { 19 | result[i] = -1; 20 | } else { 21 | result[i] = stack.peek()-i; 22 | } 23 | stack.push(i); 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Stack/JAVA/DistanceNearestSmallerElementOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class DistanceNearestSmallerElementOnLeft { 7 | public static void main(String[] args) { 8 | int arr[]=new int[]{4, 5, 2, 10, 8}; 9 | System.out.println(Arrays.toString(distanceNearestSmallerElementOnLeft(arr))); 10 | } 11 | public static int[] distanceNearestSmallerElementOnLeft(int[] arr) { 12 | Stack stack = new Stack<>(); 13 | int[] result = new int[arr.length]; 14 | 15 | for (int i = 0; i < arr.length; i++) { 16 | while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { 20 | result[i] = -1; 21 | } else { 22 | result[i] = i-stack.peek(); 23 | } 24 | stack.push(i); 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/DistanceNearestSmallerElementOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class DistanceNearestSmallerElementOnRight { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(distanceNearestSmallerElementOnRight(arr))); 9 | } 10 | 11 | public static int[] distanceNearestSmallerElementOnRight(int[] arr) { 12 | Stack stack = new Stack<>(); 13 | int[] result = new int[arr.length]; 14 | 15 | for (int i = arr.length - 1; i >= 0; i--) { 16 | while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { 20 | result[i] = -1; 21 | } else { 22 | result[i] = stack.peek() - i; 23 | } 24 | stack.push(i); 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/DistanceOfNearestGreaterElementOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class DistanceOfNearestGreaterElementOnLeft { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(distanceOfNearestGreaterElementOnLeft(arr))); 9 | } 10 | 11 | public static int[] distanceOfNearestGreaterElementOnLeft(int[] arr) { 12 | Stack stack = new Stack<>(); 13 | int[] result = new int[arr.length]; 14 | 15 | for (int i = 0; i < arr.length; i++) { 16 | while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { 20 | result[i] = -1; 21 | } else { 22 | result[i] = i - stack.peek(); 23 | } 24 | stack.push(i); 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/DynamicStack.java: -------------------------------------------------------------------------------- 1 | 2 | public class DynamicStack extends CustomStack { 3 | public DynamicStack() { 4 | super(); 5 | } 6 | 7 | public DynamicStack(int size) { 8 | super(size); 9 | } 10 | 11 | @Override 12 | public boolean push(int item) { 13 | if (this.isFull()) { 14 | // double the array size 15 | int[] temp = new int[data.length * 2]; 16 | 17 | // copy all the previous item in new data. 18 | 19 | for (int i = 0; i < data.length; i++) { 20 | temp[i] = data[i]; 21 | } 22 | data = temp; 23 | } 24 | return super.push(item); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Stack/JAVA/KnapSackTopDown.java: -------------------------------------------------------------------------------- 1 | class KnapSackTopDown { 2 | public static int knapsack(int[] weights, int[] values, int capacity) { 3 | int n = weights.length; 4 | int[][] dp = new int[n + 1][capacity + 1]; 5 | 6 | for (int i = 1; i <= n; i++) { 7 | for (int j = 1; j <= capacity; j++) { 8 | if (weights[i - 1] <= j) { 9 | dp[i][j] = Math.max(values[i - 1] + dp[i - 1][j - weights[i - 1]], dp[i - 1][j]); 10 | } else { 11 | dp[i][j] = dp[i - 1][j]; 12 | } 13 | } 14 | } 15 | 16 | return dp[n][capacity]; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] values = {10, 20, 30, 40}; 21 | int[] weights = {30, 10, 40, 20}; 22 | int capacity = 40; 23 | 24 | int maxProfit = knapsack(weights, values, capacity); 25 | System.out.println("Maximum profit: " + maxProfit); 26 | } 27 | } -------------------------------------------------------------------------------- /Stack/JAVA/MinimumBracketReversal.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | /*For a given expression in the form of a string, find the minimum number of brackets that can be reversed in order to make the expression balanced. The expression will only contain curly brackets.If the expression can't be balanced, return -1. */ 5 | public class MinimumBracketReversal { 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | String str = input.next(); 9 | Stack stack = new Stack<>(); 10 | if (str.length() % 2 == 0) { 11 | for (int i = 0; i < str.length(); i++) { 12 | char c = str.charAt(i); 13 | if (c == '{') { 14 | stack.push(c); 15 | } else { 16 | if (stack.isEmpty() == false) { 17 | if (stack.peek() == '{') { 18 | stack.pop(); 19 | } else { 20 | stack.push(c); 21 | } 22 | } else { 23 | stack.push(c); 24 | } 25 | } 26 | } 27 | char c1 = ' '; 28 | char c2 = ' '; 29 | int count = 0; 30 | while (!stack.isEmpty()) { 31 | c1 = stack.peek(); 32 | stack.pop(); 33 | c2 = stack.peek(); 34 | stack.pop(); 35 | if (c1 == c2) { 36 | count = count + 1; 37 | } else { 38 | count = count + 2; 39 | } 40 | } 41 | System.out.println(count); 42 | } else { 43 | System.out.println(-1); 44 | } 45 | input.close(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestGreaterElementOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class NearestGreaterElementOnLeft { 7 | public static void main(String[] args) { 8 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 9 | System.out.println(Arrays.toString(nearestGreaterElementOnLeft(arr))); 10 | } 11 | 12 | public static int[] nearestGreaterElementOnLeft(int[] arr) { 13 | int[] res = new int[arr.length]; 14 | Stack stack = new Stack<>(); 15 | 16 | for (int i = 0; i < arr.length; i++) { 17 | while (!stack.isEmpty() && stack.peek() <= arr[i]) { 18 | stack.pop(); 19 | } 20 | if (stack.isEmpty()) { // res[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; 21 | res[i] = -1; 22 | } else { 23 | res[i] = stack.peek(); 24 | } 25 | stack.push(arr[i]); 26 | } 27 | return res; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestGreaterElementOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestGreaterElementOnRight { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(nearestGreaterElementOnRight(arr))); 9 | } 10 | 11 | public static int[] nearestGreaterElementOnRight(int[] arr) { 12 | int[] res = new int[arr.length]; 13 | Stack stack = new Stack<>(); 14 | 15 | for (int i = arr.length - 1; i >= 0; i--) { 16 | while (!stack.isEmpty() && stack.peek() <= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { // res[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; 20 | res[i] = -1; 21 | } else { 22 | res[i] = stack.peek(); 23 | } 24 | stack.push(arr[i]); 25 | } 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestGreaterIndexOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestGreaterIndexOnRight { 6 | public static void main(String[] args) { 7 | int arr[]=new int[]{4, 5, 2, 10, 8}; 8 | System.out.println(Arrays.toString(nearestSmallerIndexOnRight(arr))); 9 | } 10 | public static int[] nearestSmallerIndexOnRight(int[] arr) { 11 | Stack stack = new Stack<>(); 12 | int[] result = new int[arr.length]; 13 | 14 | for (int i = arr.length-1; i >= 0; i--) { 15 | while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) { 16 | stack.pop(); 17 | } 18 | if (stack.isEmpty()) { 19 | result[i] = -1; 20 | } else { 21 | result[i] = stack.peek(); 22 | } 23 | stack.push(i); 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestGreatestIndexOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestGreatestIndexOnLeft { 6 | public static void main(String[] args) { 7 | int arr[]=new int[]{4, 5, 2, 10, 8}; 8 | System.out.println(Arrays.toString(nearestGreatestIndexOnLeft(arr))); 9 | } 10 | public static int[] nearestGreatestIndexOnLeft(int[] arr) { 11 | Stack stack = new Stack<>(); 12 | int[] result = new int[arr.length]; 13 | 14 | for (int i = 0; i < arr.length; i++) { 15 | while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) { 16 | stack.pop(); 17 | } 18 | if (stack.isEmpty()) { 19 | result[i] = -1; 20 | } else { 21 | result[i] = stack.peek(); 22 | } 23 | stack.push(i); 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestSmallerElementOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestSmallerElementOnLeft { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(nearestSmallerElementOnLeft(arr))); 9 | } 10 | 11 | public static int[] nearestSmallerElementOnLeft(int[] arr) { 12 | int[] res = new int[arr.length]; 13 | Stack stack = new Stack<>(); 14 | 15 | for (int i = 0; i < arr.length; i++) { 16 | while (!stack.isEmpty() && stack.peek() >= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { // res[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; 20 | res[i] = -1; 21 | } else { 22 | res[i] = stack.peek(); 23 | } 24 | stack.push(arr[i]); 25 | } 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestSmallerElementOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class NearestSmallerElementOnRight { 7 | public static void main(String[] args) { 8 | int arr[]=new int[]{4, 5, 2, 10, 8}; 9 | System.out.println(Arrays.toString(nearestSmallerElementOnRight(arr))); 10 | } 11 | 12 | public static int[] nearestSmallerElementOnRight(int[] arr) { 13 | int[] res = new int[arr.length]; 14 | Stack stack = new Stack<>(); 15 | 16 | for (int i = arr.length-1; i >= 0; i--) { 17 | while (!stack.isEmpty() && stack.peek() >= arr[i]) { 18 | stack.pop(); 19 | } 20 | if(stack.isEmpty()){ //res[i] = stack.isEmpty() ? -1 : arr[stack.peek()]; 21 | res[i]=-1; 22 | } 23 | else{ 24 | res[i]=stack.peek(); 25 | } 26 | stack.push(arr[i]); 27 | } 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestSmallerIndexOnLeft.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestSmallerIndexOnLeft { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(nearestSmallerIndexOnLeft(arr))); 9 | } 10 | 11 | public static int[] nearestSmallerIndexOnLeft(int[] arr) { 12 | Stack stack = new Stack<>(); 13 | int[] result = new int[arr.length]; 14 | 15 | for (int i = 0; i < arr.length; i++) { 16 | while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { 20 | result[i] = -1; 21 | } else { 22 | result[i] = stack.peek(); 23 | } 24 | stack.push(i); 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/NearestSmallerIndexOnRight.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Stack; 4 | 5 | public class NearestSmallerIndexOnRight { 6 | public static void main(String[] args) { 7 | int arr[] = new int[] { 4, 5, 2, 10, 8 }; 8 | System.out.println(Arrays.toString(nearestSmallerIndexOnRight(arr))); 9 | } 10 | 11 | public static int[] nearestSmallerIndexOnRight(int[] arr) { 12 | Stack stack = new Stack<>(); 13 | int[] result = new int[arr.length]; 14 | 15 | for (int i = arr.length - 1; i >= 0; i--) { 16 | while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) { 17 | stack.pop(); 18 | } 19 | if (stack.isEmpty()) { 20 | result[i] = -1; 21 | } else { 22 | result[i] = stack.peek(); 23 | } 24 | stack.push(i); 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Stack/JAVA/NextGreaterToLeft.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class NextGreaterToLeft { 4 | public static void main(String[] args) { 5 | int[] arr = { 1, 3, 2, 4 }; 6 | ArrayList result = NGR(arr); 7 | System.out.println(result); 8 | } 9 | 10 | public static ArrayList NGR(int[] arr) { 11 | Stack st = new Stack<>(); 12 | ArrayList ans = new ArrayList<>(); 13 | 14 | int n = arr.length; 15 | for (int i = 0; i < n; i++) { 16 | // Check if the stack is empty before calling peek 17 | if (st.empty()) { 18 | ans.add(-1); 19 | } else if (st.peek() > arr[i]) { 20 | ans.add(st.peek()); 21 | } else { 22 | while (!st.empty() && st.peek() <= arr[i]) { 23 | st.pop(); 24 | } 25 | if (st.empty()) { 26 | ans.add(-1); 27 | } else { 28 | ans.add(st.peek()); 29 | } 30 | } 31 | st.push(arr[i]); 32 | } 33 | Collections.reverse(ans); 34 | return ans; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Stack/JAVA/StackUsingArray.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUsingArray { 3 | private int arr[]; 4 | private int topIndex; 5 | 6 | public StackUsingArray() { 7 | arr = new int[2]; 8 | topIndex = -1; 9 | } 10 | 11 | public StackUsingArray(int size) { 12 | arr = new int[size]; 13 | topIndex = -1; 14 | } 15 | 16 | public int size() { 17 | return topIndex + 1; 18 | } 19 | 20 | public void print() { 21 | for (int i = 0; i <= topIndex; i++) { 22 | System.out.print(arr[i] + " "); 23 | } 24 | } 25 | 26 | public boolean isEmpty() { 27 | return topIndex == -1; 28 | } 29 | 30 | public void push(int element) { 31 | if (topIndex == arr.length - 1) { 32 | doublecapacity(); 33 | } 34 | topIndex = topIndex + 1; 35 | arr[topIndex] = element; 36 | } 37 | 38 | private void doublecapacity() { 39 | int[] temp = arr; 40 | arr = new int[2 * temp.length]; 41 | for (int i = 0; i < temp.length; i++) { 42 | arr[i] = temp[i]; 43 | } 44 | } 45 | 46 | public void pop() { 47 | topIndex--; 48 | } 49 | 50 | public int top() { 51 | return arr[topIndex]; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Stack/JAVA/StackUsingArrayList.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class StackUsingArrayList { 6 | List stack = new ArrayList<>(); 7 | 8 | public boolean isEmpty() { 9 | return stack.isEmpty(); 10 | } 11 | 12 | public void push(int val) { 13 | stack.add(val); 14 | } 15 | 16 | public int pop() { 17 | if (isEmpty()) { 18 | System.out.println("Stack is Empty"); 19 | return -1; 20 | } 21 | return stack.remove(stack.size() - 1); 22 | } 23 | 24 | public int peek() { 25 | if (isEmpty()) { 26 | System.out.println("Stack is Empty"); 27 | return -1; 28 | } 29 | return stack.get(stack.size() - 1); 30 | } 31 | 32 | public void display() { 33 | if (isEmpty()) { 34 | System.out.println("Stack is Empty"); 35 | } 36 | for (int i = stack.size() - 1; i >= 0; i--) { 37 | System.out.print(stack.get(i) + " "); 38 | } 39 | System.out.println(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Stack/JAVA/StackUsingLL.java: -------------------------------------------------------------------------------- 1 | 2 | import LinkedList.JAVA.*; 3 | 4 | public class StackUsingLL { 5 | LinkedListNode head; 6 | int size; 7 | 8 | public StackUsingLL() { 9 | head = null; 10 | size = 0; 11 | } 12 | 13 | public boolean isEmpty() { 14 | return size == 0; 15 | } 16 | 17 | public void push(int element) { 18 | LinkedListNode temp1 = new LinkedListNode(element); 19 | temp1.next = head; 20 | head = temp1; 21 | size++; 22 | } 23 | 24 | public void pop() { 25 | head = head.next; 26 | size--; 27 | } 28 | 29 | public int top() { 30 | if (size == 0) { 31 | return -1; 32 | } else { 33 | return head.data; 34 | } 35 | } 36 | 37 | public int size() { 38 | return size; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Stack/JAVA/StackUsingQueue.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | 5 | public class StackUsingQueue { 6 | Queue queue = new LinkedList<>(); 7 | 8 | public boolean isEmpty() { 9 | return queue.isEmpty(); 10 | } 11 | 12 | public void push(int val) { 13 | queue.offer(val); 14 | for (int i = 1; i < queue.size(); i++) { 15 | queue.add(queue.remove()); 16 | } 17 | } 18 | 19 | public int pop() { 20 | return queue.remove(); 21 | } 22 | 23 | public int peek() { 24 | return queue.peek(); 25 | } 26 | 27 | public void display() { 28 | for (Integer item : queue) { 29 | System.out.print(item + " "); 30 | } 31 | System.out.println(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Stack/JAVA/Tower_of_Hanoi.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Tower_Of_Hanoi 3 | { 4 | 5 | static void towerOfHanoi(int n, char from_rod,char aux_rod ,char to_rod) 6 | { 7 | if (n == 1) 8 | { 9 | System.out.println("Move disk from rod " + from_rod + " to rod " + to_rod); 10 | return; 11 | } 12 | towerOfHanoi(n-1, from_rod, to_rod, aux_rod); 13 | towerOfHanoi(1, from_rod, aux_rod, to_rod); 14 | towerOfHanoi(n-1, aux_rod,from_rod,to_rod); 15 | } 16 | 17 | 18 | public static void main(String args[]) 19 | { 20 | Scanner in=new Scanner(System.in); 21 | System.out.println("Enter the number of disks"); 22 | int n=in.nextInt(); // Number of disks 23 | towerOfHanoi(n,'A','B','C'); // A, B and C are names of rods 24 | } 25 | } -------------------------------------------------------------------------------- /Stack/JAVA/infixTopostfix.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class infixTopostfix { 5 | int sp; 6 | char ch[]; 7 | int i; 8 | 9 | infixTopostfix(int n) { 10 | ch = new char[n]; 11 | sp = -1; 12 | } 13 | 14 | void convert(char c[]) { 15 | 16 | char result[] = new char[c.length]; 17 | int k = 0; 18 | char s, s2; 19 | for (i = 0; i < c.length; i++) { 20 | s = c[i]; 21 | if (check(s)) { 22 | result[k++] = s; 23 | 24 | } else { 25 | while (sp != -1 && (order(s) <= order(ch[sp])) && s != '(') { 26 | s2 = pop(); 27 | if (s2 == '(') { 28 | break; 29 | 30 | } else if (s2 != '(') { 31 | result[k++] = s2; 32 | } 33 | } 34 | if (s != ')') { 35 | push(s); 36 | } 37 | 38 | } 39 | 40 | } 41 | while (sp != -1) { 42 | result[k++] = pop(); 43 | } 44 | 45 | for (i = 0; i < k; i++) { 46 | if (result[i] != '(' && result[i] != ')') { 47 | System.out.print(result[i]); 48 | } 49 | } 50 | 51 | } 52 | 53 | boolean check(char p) { 54 | return ((p >= '0' && p <= '9') || (p >= 'a' && p <= 'z') || (p >= 'A' && p <= 'Z')); 55 | } 56 | 57 | int order(char t) { 58 | switch (t) { 59 | case '(': 60 | case ')': 61 | return 0; 62 | case '+': 63 | case '-': 64 | return 1; 65 | case '*': 66 | case '/': 67 | return 2; 68 | case '$': 69 | return 3; 70 | default: 71 | System.out.println("invalid"); 72 | return (-1); 73 | 74 | } 75 | } 76 | 77 | void push(char a) { 78 | sp++; 79 | ch[sp] = a; 80 | } 81 | 82 | char pop() { 83 | return (ch[sp--]); 84 | } 85 | 86 | public static void main(String args[]) { 87 | Scanner in = new Scanner(System.in); 88 | System.out.println("Enter the expression"); 89 | String expre; 90 | expre = in.next(); 91 | char cc[] = expre.toCharArray(); 92 | infixTopostfix ob = new infixTopostfix(cc.length); 93 | ob.convert(cc); 94 | 95 | } 96 | } -------------------------------------------------------------------------------- /Stack/JAVA/multipleStacks.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class multipleStacks { 5 | int topA, topB, stack[]; 6 | 7 | multipleStacks(int max)// parameterised constructor 8 | { 9 | topA = -1; 10 | topB = max; 11 | stack = new int[max]; 12 | } 13 | 14 | void pushA(int n)// pushing into A 15 | { 16 | if (topA == topB - 1)// checking for overflowing 17 | { 18 | System.out.println("Stack A Overflows"); 19 | } else { 20 | ++topA; 21 | stack[topA] = n; 22 | } 23 | } 24 | 25 | void pushB(int n)// pushing into stack B 26 | { 27 | if (topB - 1 == topA)// checking for overflowing 28 | { 29 | System.out.println("Stack B Overflows"); 30 | } else { 31 | --topB; 32 | stack[topB] = n; 33 | } 34 | } 35 | 36 | int popA()// poping from A 37 | { 38 | if (topA == -1) { 39 | System.out.println("Stack A underflows"); 40 | return (-999); 41 | } else { 42 | int value; 43 | value = stack[topA]; 44 | --topA; 45 | return (value); 46 | } 47 | } 48 | 49 | int popB()// poping from B 50 | { 51 | if (topB == stack.length) { 52 | System.out.println("Stack B underflows"); 53 | return (-999); 54 | } else { 55 | int value; 56 | value = stack[topB]; 57 | ++topB; 58 | return (value); 59 | } 60 | } 61 | 62 | void displayA() { 63 | if (topA == -1) { 64 | System.out.println("Stack A is empty"); 65 | } 66 | int i; 67 | System.out.println("Stack A"); 68 | for (i = topA; i >= 0; i--) { 69 | System.out.println(stack[i]); 70 | } 71 | } 72 | 73 | void displayB() { 74 | if (topB == stack.length) { 75 | System.out.println("Stack B is empty"); 76 | } 77 | int i; 78 | System.out.println("Stack B"); 79 | for (i = topB; i < stack.length; i++) { 80 | System.out.println(stack[i]); 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /Stack/PYTHON/Queue_using_Stack.py: -------------------------------------------------------------------------------- 1 | # Implementation on Queue using stack 2 | import queue 3 | from queue import LifoQueue 4 | class Queue: 5 | def __init__(self): 6 | self.input = LifoQueue() 7 | self.output = LifoQueue() 8 | 9 | 10 | def push(self, data: int) -> None: 11 | # Pop out all elements from the stack input 12 | while not self.input.empty(): 13 | self.output.put(self.input.get()) 14 | # Insert the desired element in the stack input 15 | print("The element pushed is", data) 16 | self.input.put(data) 17 | # Pop out elements from the stack output and push them into the stack input 18 | while not self.output.empty(): 19 | self.input.put(self.output.get()) 20 | 21 | 22 | # Pop the element from the Queue 23 | def pop(self) -> int: 24 | if self.input.qsize() == 0: 25 | print("Stack is empty") 26 | exit(0) 27 | val = self.input.get() 28 | return val 29 | 30 | 31 | def Top(self) -> int: 32 | if self.input.qsize() == 0: 33 | print("Stack is empty") 34 | exit(0) 35 | return self.input.queue[-1] 36 | 37 | 38 | def size(self) -> int: 39 | return self.input.qsize() -------------------------------------------------------------------------------- /Stack/PYTHON/Stack_using_Queue.py: -------------------------------------------------------------------------------- 1 | #Implementation of Stack using Queue 2 | from queue import Queue 3 | class Stack: 4 | def __init__(self): 5 | self.q = Queue() 6 | 7 | 8 | def push(self, x): 9 | s = self.q.qsize() 10 | self.q.put(x) 11 | for i in range(s): 12 | self.q.put(self.q.get()) 13 | 14 | 15 | def pop(self): 16 | n = self.q.get() 17 | return n 18 | 19 | 20 | def top(self): 21 | return self.q.queue[0] 22 | 23 | 24 | def size(self): 25 | return self.q.qsize() 26 | -------------------------------------------------------------------------------- /Tree/C++/Right_View_in_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | // Title: 199. Binary Tree Right Side View 2 | // Difficulty: Medium 3 | // Problem: https://leetcode.com/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=leetcode-75 4 | 5 | // Definition for a binary tree node. 6 | // struct TreeNode { 7 | // int val; 8 | // TreeNode *left; 9 | // TreeNode *right; 10 | // TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | // TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | // TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | // }; 14 | 15 | class Solution { 16 | public: 17 | vector rightSideView(TreeNode* root) { 18 | vector result; 19 | dfs(root, 1, result); 20 | return result; 21 | } 22 | 23 | private: 24 | void dfs(TreeNode* node, int currLevel, vector& result) { 25 | if (node) { 26 | if (currLevel > result.size()) { 27 | result.push_back(node->val); 28 | } 29 | dfs(node->right, currLevel + 1, result); 30 | dfs(node->left, currLevel + 1, result); 31 | } 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Tree/C++/checkBSTorNOT.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *left, *right; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | this->left = this->right = nullptr; 13 | } 14 | }; 15 | class BST 16 | { 17 | Node *root = nullptr; 18 | void insertNodeinBST(Node *&root, int data) 19 | { 20 | if (!root) 21 | root = new Node(data); 22 | else if (data < root->data) 23 | insertNodeinBST(root->left, data); 24 | else 25 | insertNodeinBST(root->right, data); 26 | } 27 | bool isBinarySearchTree(Node *root, int minValue, int maxValue) 28 | { 29 | if (!root) 30 | return true; 31 | if (root->data > minValue && root->data < maxValue && 32 | isBinarySearchTree(root->left, minValue, root->data) && 33 | isBinarySearchTree(root->right, root->data, maxValue) 34 | ) 35 | return true; 36 | return false; 37 | } 38 | public: 39 | void insert(int data) 40 | { 41 | insertNodeinBST(root, data); 42 | } 43 | bool checkValidBST() 44 | { 45 | return isBinarySearchTree(root, INT_MIN, INT_MAX); 46 | } 47 | }; 48 | int main() 49 | { 50 | BST t; 51 | t.insert(15); 52 | t.insert(10); 53 | t.insert(20); 54 | t.insert(25); 55 | t.insert(8); 56 | t.insert(12); 57 | cout << t.checkValidBST(); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Tree/C++/findHeight.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *left, *right; 8 | Node(int data) 9 | { 10 | this->data = data; 11 | this->left = this->right = nullptr; 12 | } 13 | }; 14 | class BST 15 | { 16 | Node *root = nullptr; 17 | void insertNode(Node *&root, int data) 18 | { 19 | if (!root) 20 | root = new Node(data); 21 | else if (data <= root->data) 22 | insertNode(root->left, data); 23 | else 24 | insertNode(root->right, data); 25 | } 26 | int calculateHeightBST(Node *root) 27 | { 28 | if (!root) 29 | return -1; 30 | return max(calculateHeightBST(root->left), calculateHeightBST(root->right)) + 1; 31 | } 32 | public: 33 | void insert(int data) 34 | { 35 | insertNode(root, data); 36 | } 37 | int findHeight() 38 | { 39 | return calculateHeightBST(root); 40 | } 41 | }; 42 | int main() 43 | { 44 | BST t; 45 | t.insert(5); 46 | t.insert(3); 47 | t.insert(8); 48 | t.insert(2); 49 | cout << t.findHeight(); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Tree/C++/findMinMaxFromBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *left, *right; 8 | Node(int data) 9 | { 10 | this->data = data; 11 | this->left = this->right = nullptr; 12 | } 13 | }; 14 | class BST 15 | { 16 | Node *root = nullptr; 17 | void insertNode(Node *&root, int data) 18 | { 19 | if (!root) 20 | root = new Node(data); 21 | else if (data <= root->data) 22 | insertNode(root->left, data); 23 | else 24 | insertNode(root->right, data); 25 | } 26 | int findMinBST(Node *root) 27 | { 28 | if (!root) 29 | exit(1); 30 | else if (root->left == nullptr) 31 | return root->data; 32 | else 33 | return findMinBST(root->left); 34 | } 35 | int findMaxBST(Node *root) 36 | { 37 | if (!root) 38 | exit(1); 39 | else if (root->right == nullptr) 40 | return root->data; 41 | else 42 | return findMaxBST(root->right); 43 | } 44 | public: 45 | void insert(int data) 46 | { 47 | insertNode(root, data); 48 | } 49 | int findMin() 50 | { 51 | return findMinBST(root); 52 | } 53 | int findMax() 54 | { 55 | return findMaxBST(root); 56 | } 57 | }; 58 | int main() 59 | { 60 | BST t; 61 | t.insert(15); 62 | t.insert(10); 63 | t.insert(20); 64 | t.insert(25); 65 | t.insert(8); 66 | t.insert(12); 67 | cout << t.findMin() << " " << t.findMax(); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Tree/C++/implementBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *left, *right; 8 | Node(int data) 9 | { 10 | this->data = data; 11 | this->left = this->right = nullptr; 12 | } 13 | }; 14 | class BST 15 | { 16 | Node *root = nullptr; 17 | void insertNode(Node *&root, int data){ 18 | if (!root) 19 | root = new Node(data); 20 | else if (data <= root->data) 21 | insertNode(root->left, data); 22 | else 23 | insertNode(root->right, data); 24 | } 25 | bool searchNode(Node *root, int data) 26 | { 27 | if (!root) 28 | return false; 29 | else if (root->data == data) 30 | return true; 31 | else if (data <= root->data) 32 | return searchNode(root->left, data); 33 | else 34 | return searchNode(root->right, data); 35 | } 36 | public: 37 | void insert(int data) 38 | { 39 | insertNode(root, data); 40 | } 41 | bool search(int data) 42 | { 43 | return searchNode(root, data); 44 | } 45 | }; 46 | int main() 47 | { 48 | BST t; 49 | t.insert(15); 50 | t.insert(10); 51 | t.insert(20); 52 | t.insert(25); 53 | t.insert(8); 54 | t.insert(12); 55 | cout << t.search(15) << endl; 56 | cout << t.search(31) << endl; 57 | cout << t.search(20) << endl; 58 | cout << t.search(7) << endl; 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Tree/C++/treeTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *left, *right; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | this->left = this->right = nullptr; 13 | } 14 | }; 15 | class BST 16 | { 17 | Node *root = nullptr; 18 | void insertNodeBST(Node *&root, int data) 19 | { 20 | if (!root) 21 | root = new Node(data); 22 | else if (data <= root->data) 23 | insertNodeBST(root->left, data); 24 | else 25 | insertNodeBST(root->right, data); 26 | } 27 | void performLevelOrderTraversal(Node *root) //BFS for tree traversal 28 | { 29 | if (!root) 30 | return; 31 | queue q; 32 | q.push(root); 33 | while (!q.empty()) 34 | { 35 | Node *current = q.front(); 36 | cout << current->data << " "; 37 | if (current->left) 38 | q.push(current->left); 39 | if (current->right) 40 | q.push(current->right); 41 | q.pop(); 42 | } 43 | cout << endl; 44 | } 45 | void preorder(Node *root) 46 | { 47 | if (!root) 48 | return; 49 | cout << root->data << " "; 50 | preorder(root->left); 51 | preorder(root->right); 52 | } 53 | void inorder(Node *root) 54 | { 55 | if (!root) 56 | return; 57 | preorder(root->left); 58 | cout << root->data << " "; 59 | preorder(root->right); 60 | } 61 | void postorder(Node *root) 62 | { 63 | if (!root) 64 | return; 65 | preorder(root->left); 66 | preorder(root->right); 67 | cout << root->data << " "; 68 | } 69 | public: 70 | void insert(int data) 71 | { 72 | insertNodeBST(root, data); 73 | } 74 | void levelOrderTraversal() 75 | { 76 | cout << "Level order : "; 77 | performLevelOrderTraversal(root); 78 | } 79 | void depthFirstTraversal() 80 | { 81 | cout << "Preorder : "; 82 | preorder(root); 83 | cout << endl; 84 | cout << "Inorder : "; 85 | inorder(root); 86 | cout << endl; 87 | cout << "Postorder : "; 88 | postorder(root); 89 | cout << endl; 90 | } 91 | 92 | }; 93 | int main() 94 | { 95 | BST t; 96 | t.insert(5); 97 | t.insert(3); 98 | t.insert(8); 99 | t.insert(2); 100 | t.levelOrderTraversal(); 101 | t.depthFirstTraversal(); 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /Tree/JAVA/ verticalOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | 18 | class pair 19 | { 20 | int r; 21 | int c; 22 | TreeNode y; 23 | pair(int r,int c,TreeNode y) 24 | { 25 | this.r=r; 26 | this.c=c; 27 | this.y=y; 28 | } 29 | } 30 | 31 | public List> verticalTraversal(TreeNode root) { 32 | List> res=new ArrayList<>(); 33 | if(root==null) return res; 34 | Map> map=new TreeMap<>(); 35 | PriorityQueue q=new PriorityQueue<>( 36 | (pair1,pair2)-> (pair1.r!=pair2.r)? pair1.r-pair2.r:pair1.y.val-pair2.y.val 37 | ); 38 | q.offer(new pair(0,0,root)); 39 | while(!q.isEmpty()) 40 | { 41 | List temp; 42 | int r=q.peek().r; 43 | int c=q.peek().c; 44 | TreeNode curr=q.peek().y; 45 | q.poll(); 46 | if(map.containsKey(c)) 47 | { 48 | temp=map.get(c); 49 | temp.add(curr.val); 50 | map.put(c,temp); 51 | } 52 | else 53 | { 54 | temp=new ArrayList<>(); 55 | temp.add(curr.val); 56 | map.put(c,temp); 57 | } 58 | if(curr.left!=null) q.offer(new pair(r+1,c-1,curr.left)); 59 | if(curr.right!=null) q.offer(new pair(r+1,c+1,curr.right)); 60 | } 61 | 62 | map.forEach((k,v)->{ 63 | res.add(v); 64 | }); 65 | return res; 66 | 67 | } 68 | } -------------------------------------------------------------------------------- /Tree/JAVA/BSTdeletereturn.java: -------------------------------------------------------------------------------- 1 | 2 | public class BSTdeletereturn { 3 | BinaryTreeNode root; 4 | boolean deleted; 5 | 6 | public BSTdeletereturn(BinaryTreeNode root, boolean deleted) { 7 | this.root = root; 8 | this.deleted = deleted; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Tree/JAVA/RangeSumOfBST.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode() {} 6 | TreeNode(int val) { this.val = val; } 7 | TreeNode(int val, TreeNode left, TreeNode right) { 8 | this.val = val; 9 | this.left = left; 10 | this.right = right; 11 | } 12 | } 13 | 14 | class Solution { 15 | ArrayList traverse(TreeNode root,int low,int high,ArrayList sum) { 16 | if (root == null) 17 | return sum; 18 | 19 | ArrayList temp1=traverse(root.left,low,high,sum); 20 | 21 | ArrayList temp2=traverse(root.right,low,high,sum); 22 | 23 | sum.add(root.val); 24 | return sum; 25 | } 26 | int rangeSumBST(TreeNode root, int low, int high) { 27 | ArrayList r=new ArrayList<>(); 28 | int sum=0; 29 | ArrayList res=traverse(root,low,high,r); 30 | for(int i:res) { 31 | if(i>=low && i<=high) 32 | sum+=i; 33 | } 34 | return sum; 35 | } 36 | } -------------------------------------------------------------------------------- /Tree/JAVA/all-nodes-distance-k-in-binary-tree: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode(int x) { val = x; } 6 | } 7 | 8 | class Solution { 9 | 10 | private void parentTrack(TreeNode root,HashMap map){ 11 | 12 | if(root==null) 13 | return; 14 | 15 | if(root.left!=null) { 16 | map.put(root.left,root); 17 | parentTrack(root.left,map); 18 | } 19 | 20 | if(root.right!=null){ 21 | map.put(root.right,root); 22 | parentTrack(root.right,map); 23 | 24 | } 25 | } 26 | 27 | public List distanceK(TreeNode root, TreeNode target, int k) { 28 | 29 | 30 | List list=new ArrayList<>(); 31 | HashMap map = new HashMap(); 32 | 33 | if(root==null) 34 | return list; 35 | 36 | map.put(root,null); 37 | parentTrack(root,map); 38 | 39 | Queue queue=new LinkedList<>(); 40 | HashSet set=new HashSet<>(); 41 | 42 | queue.add(target); 43 | set.add(target); 44 | int dist=0; 45 | while(!(queue.isEmpty())){ 46 | 47 | 48 | int levelsum=queue.size(); 49 | 50 | if(k==dist) 51 | break; 52 | 53 | dist++; 54 | 55 | for(int i=0;i> zigzagLevelOrder(TreeNode root) { 16 | 17 | Queue queue = new LinkedList<>(); 18 | List> listOfLists = new ArrayList>(); 19 | 20 | if(root==null) 21 | return listOfLists; 22 | 23 | queue.add(root); 24 | boolean odd=true; 25 | while(!(queue.isEmpty())){ 26 | 27 | int levelsum=queue.size(); 28 | // to use addFirst method we have to use Linked list 29 | LinkedList list = new LinkedList<>(); 30 | for(int i=0;i int: 13 | self.max = float('-inf') 14 | # transverse throught the tree and update the self.max value 15 | self.transverse(root) 16 | return self.max 17 | 18 | def transverse(self, node: Optional[TreeNode]) -> int: 19 | # no node means path sum is 0 20 | if not node: 21 | return 0 22 | 23 | # find the max sum for left and right nodes 24 | left = self.transverse(node.left) 25 | right = self.transverse(node.right) 26 | 27 | # compare the different paths 28 | self.max = max(self.max, left + right + node.val, node.val + max(left, right, 0)) 29 | 30 | # return a path that starts at the node 31 | return node.val + max(left, right, 0) 32 | -------------------------------------------------------------------------------- /Trial.java: -------------------------------------------------------------------------------- 1 | import Tree.*; 2 | import LinkedList.*; 3 | import Tries_and_Huffman_Coding.*; 4 | import java.util.*; 5 | import Graphs.*; 6 | public class Trial{ 7 | public static void main(String[]args){ 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /owest-common-ancestor-of-a-binary-tree: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode(int x) { val = x; } 6 | } 7 | 8 | class Solution { 9 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 10 | 11 | if(root==null||root==p||root==q)return root; 12 | TreeNode left=lowestCommonAncestor(root.left, p,q); 13 | TreeNode right=lowestCommonAncestor(root.right, p,q); 14 | 15 | if(left!=null&&right!=null)return root; 16 | 17 | if(left!=null) 18 | return left; 19 | 20 | else 21 | return right; 22 | 23 | 24 | } 25 | } 26 | --------------------------------------------------------------------------------