├── .github └── pull_request_template.md ├── 3Sum ├── README.md └── ThreeSum.java ├── Adding evens └── Adding Evens.py ├── Array Operations └── ArrayOperations.c ├── Array └── spiralPrint.cpp ├── BFS └── BreadthFirstSearch.py ├── BMI Calculator └── BMI Calculator.py ├── Bellmanford Algo ├── BellmanFordImplementation.java ├── bellman.cpp.txt └── readme.md.txt ├── Binary Search ├── BinarySearch.java ├── BinarySearch.py ├── BinarySearch_Recursive.c ├── BinarySearch_Recursive.py ├── BinarySearch_iterative.c ├── BinarySearch_using_recursion.java └── README.md ├── Binary Tree └── main.py ├── Bubble Sort ├── BubbleSort.java └── README.md ├── Check BST └── checkBinaryTreeAsBST.java ├── Contributing.md ├── DFS ├── DFS in graphs │ ├── DFSTraversal.java │ └── readme.md ├── DFS in trees │ ├── DFS_iterative.java │ ├── DFS_recursion.java │ ├── Node.java │ └── readme.md └── dfs_matrix │ └── pacific.cpp ├── Dijkstra └── DijkstraExample.java ├── Duplicate Elements └── SearchDuplicateElements.java ├── Dynamic_Programming └── pathsinmatrix2.cpp ├── Factorial ├── Factorial.dart ├── Factorial.java └── README.md ├── Fenwick Tree └── fenwick.cpp ├── Fibonacci ├── Fibonacci-Series.cpp ├── Fibonacci-Series.py ├── Fibonacci.java ├── Fibonacci_Series.c ├── README.md └── fibonacci.c ├── Generate a strong password └── Password_Generator.py ├── Heap Sort ├── Heap_Sort.c └── README.md ├── Huffman_string_compression └── huff.js ├── Intersection of Two Arrays └── intersactionoftwoarraysII.java ├── Is It Leap Year └── Leap Year.py ├── Kedane's Algorithm ├── README.md └── kedanes.py ├── Length of Last Word └── Solution.java ├── Level Order Traversal └── LevelOrderTraversal.java ├── Linear Search ├── LinearSearch.java ├── README.md └── linearsearch.py ├── LinkedList Operations ├── Reversing-linked-list.java └── linkedlistOperations.c ├── Longest Common Prefix └── Solution.java ├── Longest Common Sub String └── longest_common_substring.cpp ├── Longest K unique characters substring ├── README.md └── longest_k_unique_characters_substring.cpp ├── Matrix Operations └── MatrixOperations.c ├── Median of 2 sorted arrays └── medianof2sortedarray.cpp ├── Merge Sort ├── MergeSort.c ├── README.md ├── merge-sort.java └── merge-sort.py ├── Merge Sorted Arrays ├── MergeSortedArrays.class └── MergeSortedArrays.java ├── N Queens ├── N_Queens.java └── queen.cpp ├── Odd Even └── odd_even.java ├── Plus One └── Solution.java ├── Queue └── Queue_using_2_stacks.cpp ├── Quick Sort ├── QuickSort.py ├── README.md └── quickSort.java ├── README.md ├── Rock,paper and scissors └── Rock, Paper and Scissors.py ├── Search Insertion Position └── Solution.java ├── Search in a BST ├── SearchBST.java └── main.py ├── Searching in Rotated Sorted Array └── SearchInRotatedSortedArray.java ├── Selection Sort ├── README.md └── SelectionSort.java ├── Set Matrix Zero └── naive.java ├── Square Root of a Number └── SquareRootOfNum.java ├── The Sieve Of Eratosthenes └── TheSieveOfEratosthenes.py ├── Topological Sort └── topological.java ├── Two Sum IV - Input is a BST └── sum.cpp ├── Two Sum ├── README.md └── Two_Sum.cpp ├── banner.png ├── implementation of stack ├── Arraystack.c ├── LinkedListStack.c └── stack.py └── prime number checker └── Prime number checker.py /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Issue Number 2 | - Put Your Issue Number here 3 | ## Issue Description 4 | - Describe the Issue 5 | ## Proposed Change 6 | - Describe the Change 7 | ## Additional Info (Optional) 8 | - Any Additional Information 9 | ## Checklist 10 | - [ ] Testing 11 | - [ ] Documentations 12 | - [ ] I have read the [CONTRIBUTING](../Contributing.md) guidelines 13 | - [ ] Added explanation of the Code in a README file 14 | -------------------------------------------------------------------------------- /3Sum/README.md: -------------------------------------------------------------------------------- 1 |

Three Sum

2 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 3 | 4 | Notice that the solution set must not contain duplicate triplets. 5 | 6 | 7 | ***Example 1:*** 8 |
 9 | Input: nums = [-1,0,1,2,-1,-4]
10 | Output: [[-1,-1,2],[-1,0,1]]
11 | Explanation: 
12 | nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
13 | nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
14 | nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
15 | The distinct triplets are [-1,0,1] and [-1,-1,2].
16 | Notice that the order of the output and the order of the triplets does not matter.
17 | 
18 | 19 | 20 | ***Example 2:*** 21 |
22 | Input: nums = [0,1,1]
23 | Output: []
24 | Explanation: The only possible triplet does not sum up to 0.
25 | 
26 | 27 | ***Example 3:*** 28 |
29 | Input: nums = [0,0,0]
30 | Output: [[0,0,0]]
31 | Explanation: The only possible triplet sums up to 0.
32 |  
33 | 34 | ***Constraints:*** 35 | 36 | 3 <= nums.length <= 3000
37 | -105 <= nums[i] <= 105 -------------------------------------------------------------------------------- /3Sum/ThreeSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> threeSum(int[] nums) { 3 | //Declare a answer arrayList 4 | List> ans = new ArrayList<>(); 5 | //Sort the Array 6 | Arrays.sort(nums); 7 | int n =nums.length; 8 | for(int i=0;i0 && nums[i]!=nums[i-1]){ 10 | //Take low variable and initialise it to next of i 11 | int low = i+1; 12 | //Take high variable and initialise it to end of array 13 | int high = n-1; 14 | while(low //Header file Standard Input and Output 3 | #include //Header file for Dynamic Memory Allocation 4 | #include //Header file for Standard Library Functions 5 | void arrayprint(int arr[],int n) //Function for printing the Array 6 | { 7 | int i; 8 | for(i=0;i "); 29 | printf("\nEnter 1 to Perform array operation"); 30 | printf("\nEnter 2 to exit\n"); 31 | scanf("%d",&choice1); 32 | if(choice1==1) 33 | { 34 | printf("\nHow many elements do you want to enter => "); 35 | scanf("%d",&n); 36 | arr=(int*)malloc(n*sizeof(int)); //Dynamic Memory Allocation for the array 37 | if(arr==NULL) 38 | { 39 | printf("\nUnable to Allocate memory !!!\n"); 40 | exit(1); 41 | } 42 | printf("\nEnter values for the array => \n"); //Asking for user input 43 | for(i=0;i "); 60 | scanf("%d",&newelement); 61 | arr[0]=newelement; 62 | n=n+1; 63 | printf("\nElement Inserted successfully\n"); 64 | } 65 | else 66 | { 67 | printf("\nEnter the element to be inserted => "); 68 | scanf("%d",&newelement); 69 | printf("\nEnter the position where the element will be inserted => "); 70 | scanf("%d",&newelementposition); 71 | if(newelement<=0||newelementposition>n+1) 72 | { 73 | printf("\nElement cannot be entered there !!!\n"); 74 | break; 75 | } 76 | else 77 | { 78 | n++; 79 | arr = (int*)realloc(arr,n); //Dynamic Memory Allocation for the array 80 | if(arr==NULL) 81 | { 82 | printf("\nUnable to Allocate memory !!!\n"); 83 | exit(1); 84 | } 85 | for (i = n - 1; i>=newelementposition; i--) 86 | arr[i] = arr[i - 1]; 87 | arr[newelementposition - 1] = newelement; 88 | printf("\nElement Inserted successfully\n"); 89 | } 90 | } 91 | break; 92 | case 2://Deletion 93 | if(n==0) 94 | printf("\nArray is empty!!!\n"); 95 | else 96 | { 97 | printf("\nEnter the element to be deleted => "); 98 | scanf("%d",&elementd); 99 | pos=arraysearch(arr,n,elementd); 100 | if(pos==-1) 101 | { 102 | printf("\nElement not found\n"); 103 | break; 104 | } 105 | else 106 | for(i=pos;i "); 125 | scanf("%d",&elements); 126 | pos=arraysearch(arr,n,elements); 127 | if(pos==-1) 128 | printf("\nElement not found\n"); 129 | else 130 | printf("\nElement found at position => %d\n",pos+1); 131 | } 132 | break; 133 | case 5://Exit 134 | choice2=5; 135 | break; 136 | default:printf("\nInvalid input\n"); 137 | } 138 | }while(choice2!=5); 139 | } 140 | else choice1=0; 141 | }while(choice1!=0); 142 | free(arr); 143 | return 0; //Main function ends 144 | } 145 | -------------------------------------------------------------------------------- /Array/spiralPrint.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) { 4 | 5 | vector ans; 6 | int row = matrix.size(); //? 7 | int col = matrix[0].size(); 8 | 9 | // These are indexes---> 10 | int startingRow = 0; 11 | int endingCol = col - 1; 12 | int endingRow = row - 1; 13 | int startingCol = 0; 14 | 15 | int count = 0; 16 | int total = row * col; 17 | while (count < total) 18 | { 19 | // Printing Starting row: 20 | for (int index = startingCol; count < total && index <= endingCol; index++) 21 | { 22 | ans.push_back(matrix[startingRow][index]); 23 | count++; 24 | } 25 | startingRow++; 26 | 27 | // Printing ending column: 28 | for (int index = startingRow; count < total && index <= endingRow; index++) 29 | { 30 | ans.push_back(matrix[index][endingCol]); 31 | count++; 32 | } 33 | endingCol--; 34 | 35 | // Printing ending row: 36 | for (int index = endingCol; count < total && index >= startingCol; index--) 37 | { 38 | ans.push_back(matrix[endingRow][index]); 39 | count++; 40 | } 41 | endingRow--; 42 | 43 | // Printing starting column: 44 | for (int index = endingRow; count < total && index >= startingRow; index--) 45 | { 46 | ans.push_back(matrix[index][startingCol]); 47 | count++; 48 | } 49 | startingCol++; 50 | } 51 | 52 | return ans; 53 | } 54 | }; -------------------------------------------------------------------------------- /BFS/BreadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Graph: 3 | def __init__(self): 4 | self.graph = defaultdict(list) 5 | def addEdge(self,u,v): 6 | self.graph[u].append(v) 7 | def BFS(self, s): 8 | visited = [False] * (max(self.graph) + 1) 9 | queue = [] 10 | queue.append(s) 11 | visited[s] = True 12 | while queue: 13 | s = queue.pop(0) 14 | print (s, end = " ") 15 | for i in self.graph[s]: 16 | if visited[i] == False: 17 | queue.append(i) 18 | visited[i] = True 19 | g = Graph() 20 | g.addEdge(0, 1) 21 | g.addEdge(0, 2) 22 | g.addEdge(1, 2) 23 | g.addEdge(2, 0) 24 | g.addEdge(2, 3) 25 | g.addEdge(3, 3) 26 | print ("Following is Breadth First Traversal" 27 | " (starting from vertex 2)") 28 | g.BFS(2) 29 | -------------------------------------------------------------------------------- /BMI Calculator/BMI Calculator.py: -------------------------------------------------------------------------------- 1 | w = float(input("Enter your weight:")) 2 | h = float(input("Enter your height:")) 3 | 4 | BMI = round(w/h**2) 5 | 6 | if BMI < 18.5: 7 | print(f"Your BMI is {BMI}, you are underweight.") 8 | elif BMI < 25: 9 | print(f"Your BMI is {BMI}, you have a normal weight.") 10 | elif BMI < 30: 11 | print(f"Your BMI is {BMI}, you are overweight.") 12 | elif BMI < 35: 13 | print(f"Your BMI is {BMI}, you are obese.") 14 | else: 15 | print(f"Your BMI is {BMI}, you are clinically obese.") -------------------------------------------------------------------------------- /Bellmanford Algo/BellmanFordImplementation.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | class Graph 4 | { 5 | //vertices of the graph 6 | private int V; 7 | //edges in the graph 8 | private List edges; 9 | //creating a constructor of the Graph class and generating getters and setters 10 | public Graph(int v) 11 | { 12 | V = v; 13 | edges = new ArrayList(); 14 | } 15 | public int getV() 16 | { 17 | return V; 18 | } 19 | public void setV(int v) 20 | { 21 | V = v; 22 | } 23 | public List getEdges() 24 | { 25 | return edges; 26 | } 27 | public void setEdges(List edges) 28 | { 29 | this.edges = edges; 30 | } 31 | public void addEdge(int u, int v, int w) 32 | { 33 | Edge e = new Edge(u, v, w); 34 | edges.add(e); 35 | } 36 | } 37 | class Edge 38 | { 39 | //it is the source vertex 40 | private int u; 41 | //it is the destination vertex 42 | private int v; 43 | //it denotes the weight on edge 44 | private int w; 45 | //generating getters and setters 46 | public int getU() 47 | { 48 | return u; 49 | } 50 | public void setU(int u) 51 | { 52 | this.u = u; 53 | } 54 | public int getV() 55 | { 56 | return v; 57 | } 58 | public void setV(int v) 59 | { 60 | this.v = v; 61 | } 62 | public int getW() 63 | { 64 | return w; 65 | } 66 | public void setW(int w) 67 | { 68 | this.w = w; 69 | } 70 | //creating constructor of the Edge class 71 | public Edge(int u, int v, int w) 72 | { 73 | this.u = u; 74 | this.v = v; 75 | this.w = w; 76 | } 77 | } 78 | public class BellmanFordImplementation 79 | { 80 | public static void main(String args[]) 81 | { 82 | Graph g = createGraph(); 83 | int distance[] = new int[g.getV()]; 84 | boolean hasNegativeCycle = getShortestPaths(g, 1, distance); 85 | if(!hasNegativeCycle) 86 | { 87 | System.out.println("Vertex \t: Distance"); 88 | for(int i = 1; i < distance.length; i++) 89 | System.out.println("\t"+i + " " + "\t\t"+(distance[i] == Integer.MAX_VALUE ? "-" : distance[i])); 90 | } 91 | else 92 | { 93 | System.out.println("Negative cycle exists in the graph, no solution found!!!"); 94 | } 95 | } 96 | private static Graph createGraph() 97 | { 98 | int v = 7; 99 | //creating a graph having 7 vertices 100 | Graph g = new Graph(v); 101 | //adding edges to the graph 102 | g.addEdge(1, 2, 4); 103 | g.addEdge(1, 4, 9); 104 | g.addEdge(2, 3, -1); 105 | g.addEdge(3, 6, 3); 106 | g.addEdge(4, 3, 2); 107 | g.addEdge(4, 5, -5); 108 | g.addEdge(5, 6, 0); 109 | //returns graph 110 | return g; 111 | } 112 | //Bellman-Ford logic 113 | public static boolean getShortestPaths(Graph g, int source, int[] distance) 114 | { 115 | int V = g.getV(); 116 | //initializing distances from source to other vertices 117 | for(int i = 1; i < V; i++) 118 | { 119 | distance[i] = Integer.MAX_VALUE; 120 | } 121 | //source vertex initialize to 0 122 | distance[source] = 0; 123 | //relaxing edges 124 | for(int i = 1; i < V; i++) 125 | { 126 | //iterate over edges 127 | for(Edge e: g.getEdges()) 128 | { 129 | int u = e.getU(), v = e.getV(), w = e.getW(); 130 | if(distance[u] != Integer.MAX_VALUE && distance[v] > distance[u] + w) 131 | { 132 | //calculates distance 133 | distance[v] = distance[u] + w; 134 | } 135 | } 136 | } 137 | //checks if there exist negative cycles in graph G 138 | for(Edge e: g.getEdges()) 139 | { 140 | int u = e.getU(), v = e.getV(), w = e.getW(); 141 | if(distance[u] != Integer.MAX_VALUE && distance[v] > distance[u] + w) 142 | { 143 | return true; 144 | } 145 | } 146 | return false; 147 | } 148 | } -------------------------------------------------------------------------------- /Bellmanford Algo/bellman.cpp.txt: -------------------------------------------------------------------------------- 1 | // A C++ program for Bellman-Ford's single source 2 | // shortest path algorithm. 3 | #include 4 | using namespace std; 5 | 6 | // a structure to represent a weighted edge in graph 7 | struct Edge { 8 | int src, dest, weight; 9 | }; 10 | 11 | // a structure to represent a connected, directed and 12 | // weighted graph 13 | struct Graph { 14 | // V-> Number of vertices, E-> Number of edges 15 | int V, E; 16 | 17 | // graph is represented as an array of edges. 18 | struct Edge* edge; 19 | }; 20 | 21 | // Creates a graph with V vertices and E edges 22 | struct Graph* createGraph(int V, int E) 23 | { 24 | struct Graph* graph = new Graph; 25 | graph->V = V; 26 | graph->E = E; 27 | graph->edge = new Edge[E]; 28 | return graph; 29 | } 30 | 31 | // A utility function used to print the solution 32 | void printArr(int dist[], int n) 33 | { 34 | printf("Vertex Distance from Source\n"); 35 | for (int i = 0; i < n; ++i) 36 | printf("%d \t\t %d\n", i, dist[i]); 37 | } 38 | 39 | // The main function that finds shortest distances from src 40 | // to all other vertices using Bellman-Ford algorithm. The 41 | // function also detects negative weight cycle 42 | void BellmanFord(struct Graph* graph, int src) 43 | { 44 | int V = graph->V; 45 | int E = graph->E; 46 | int dist[V]; 47 | 48 | // Step 1: Initialize distances from src to all other 49 | // vertices as INFINITE 50 | for (int i = 0; i < V; i++) 51 | dist[i] = INT_MAX; 52 | dist[src] = 0; 53 | 54 | // Step 2: Relax all edges |V| - 1 times. A simple 55 | // shortest path from src to any other vertex can have 56 | // at-most |V| - 1 edges 57 | for (int i = 1; i <= V - 1; i++) { 58 | for (int j = 0; j < E; j++) { 59 | int u = graph->edge[j].src; 60 | int v = graph->edge[j].dest; 61 | int weight = graph->edge[j].weight; 62 | if (dist[u] != INT_MAX 63 | && dist[u] + weight < dist[v]) 64 | dist[v] = dist[u] + weight; 65 | } 66 | } 67 | 68 | // Step 3: check for negative-weight cycles. The above 69 | // step guarantees shortest distances if graph doesn't 70 | // contain negative weight cycle. If we get a shorter 71 | // path, then there is a cycle. 72 | for (int i = 0; i < E; i++) { 73 | int u = graph->edge[i].src; 74 | int v = graph->edge[i].dest; 75 | int weight = graph->edge[i].weight; 76 | if (dist[u] != INT_MAX 77 | && dist[u] + weight < dist[v]) { 78 | printf("Graph contains negative weight cycle"); 79 | return; // If negative cycle is detected, simply 80 | // return 81 | } 82 | } 83 | 84 | printArr(dist, V); 85 | 86 | return; 87 | } 88 | 89 | // Driver's code 90 | int main() 91 | { 92 | /* Let us create the graph given in above example */ 93 | int V = 5; // Number of vertices in graph 94 | int E = 8; // Number of edges in graph 95 | struct Graph* graph = createGraph(V, E); 96 | 97 | // add edge 0-1 (or A-B in above figure) 98 | graph->edge[0].src = 0; 99 | graph->edge[0].dest = 1; 100 | graph->edge[0].weight = -1; 101 | 102 | // add edge 0-2 (or A-C in above figure) 103 | graph->edge[1].src = 0; 104 | graph->edge[1].dest = 2; 105 | graph->edge[1].weight = 4; 106 | 107 | // add edge 1-2 (or B-C in above figure) 108 | graph->edge[2].src = 1; 109 | graph->edge[2].dest = 2; 110 | graph->edge[2].weight = 3; 111 | 112 | // add edge 1-3 (or B-D in above figure) 113 | graph->edge[3].src = 1; 114 | graph->edge[3].dest = 3; 115 | graph->edge[3].weight = 2; 116 | 117 | // add edge 1-4 (or B-E in above figure) 118 | graph->edge[4].src = 1; 119 | graph->edge[4].dest = 4; 120 | graph->edge[4].weight = 2; 121 | 122 | // add edge 3-2 (or D-C in above figure) 123 | graph->edge[5].src = 3; 124 | graph->edge[5].dest = 2; 125 | graph->edge[5].weight = 5; 126 | 127 | // add edge 3-1 (or D-B in above figure) 128 | graph->edge[6].src = 3; 129 | graph->edge[6].dest = 1; 130 | graph->edge[6].weight = 1; 131 | 132 | // add edge 4-3 (or E-D in above figure) 133 | graph->edge[7].src = 4; 134 | graph->edge[7].dest = 3; 135 | graph->edge[7].weight = -3; 136 | 137 | // Function call 138 | BellmanFord(graph, 0); 139 | 140 | return 0; 141 | } 142 | -------------------------------------------------------------------------------- /Bellmanford Algo/readme.md.txt: -------------------------------------------------------------------------------- 1 | Bellman-Ford Algorithm 2 | It is a single-source shortest path (minimum weight) algorithm very similar to Dijkstra's algorithm. It can be applied in a graph if we want to find the shortest path. Note that it deals with the negative edge weights. The limitation of the algorithm is that there should not be negative cycles (a cycle whose sum of edges produces a negative value) in the graph. Consider the following graph with cycle. 3 | 4 | Bellman-Ford Algorithm Java 5 | The runtime complexity of the algorithm is O(v*e) and space complexity is O(v). One should use the algorithm if the graph has negative edge weights. -------------------------------------------------------------------------------- /Binary Search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | 3 | public static int binarySearch(int[] arr, int target) { 4 | int start = 0; 5 | int end = arr.length-1; 6 | 7 | while(start <= end) { 8 | int mid = start + (end - start) / 2; 9 | 10 | if (arr[mid] == target) { 11 | return mid; 12 | } else if (arr[mid] > target) { 13 | end = mid - 1; 14 | } else { 15 | start = mid + 1; 16 | } 17 | } 18 | 19 | return -1; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] arr = {1, 2, 3, 4, 5, 6, 7, 8 , 9}; 24 | int target = 5; 25 | System.out.println(binarySearch(arr, target)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Binary Search/BinarySearch.py: -------------------------------------------------------------------------------- 1 | # Iterative Binary Search Function 2 | # It returns index of x in given array arr if present, 3 | # else returns -1 4 | def binary_search(arr, x): 5 | low = 0 6 | high = len(arr) - 1 7 | mid = 0 8 | 9 | while low <= high: 10 | 11 | mid = (high + low) // 2 12 | 13 | # If x is greater, ignore left half 14 | if arr[mid] < x: 15 | low = mid + 1 16 | 17 | # If x is smaller, ignore right half 18 | elif arr[mid] > x: 19 | high = mid - 1 20 | 21 | # means x is present at mid 22 | else: 23 | return mid 24 | 25 | # If we reach here, then the element was not present 26 | return -1 27 | 28 | 29 | # Test array 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binary_search(arr, x) 35 | 36 | if result != -1: 37 | print("Element is present at index", str(result)) 38 | else: 39 | print("Element is not present in array") 40 | -------------------------------------------------------------------------------- /Binary Search/BinarySearch_Recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | int recursiveBinarySearch(int array[], int start_index, int end_index, int element){ 3 | if (end_index >= start_index){ 4 | int middle = start_index + (end_index - start_index )/2; 5 | if (array[middle] == element) 6 | return middle; 7 | if (array[middle] > element) 8 | return recursiveBinarySearch(array, start_index, middle-1, element); 9 | return recursiveBinarySearch(array, middle+1, end_index, element); 10 | } 11 | return -1; 12 | } 13 | int main(void){ 14 | int array[] = {1, 4, 7, 9, 16, 56, 70}; 15 | int n = 7; 16 | int element = 9; 17 | int found_index = recursiveBinarySearch(array, 0, n-1, element); 18 | if(found_index == -1 ) { 19 | printf("Element not found in the array "); 20 | } 21 | else { 22 | printf("Element found at index : %d",found_index); 23 | } 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Binary Search/BinarySearch_Recursive.py: -------------------------------------------------------------------------------- 1 | # Python 3 program for recursive binary search. 2 | # Modifications needed for the older Python 2 are found in comments. 3 | 4 | # Returns index of x in arr if present, else -1 5 | def binary_search(arr, low, high, x): 6 | 7 | # Check base case 8 | if high >= low: 9 | 10 | mid = (high + low) // 2 11 | 12 | # If element is present at the middle itself 13 | if arr[mid] == x: 14 | return mid 15 | 16 | # If element is smaller than mid, then it can only 17 | # be present in left subarray 18 | elif arr[mid] > x: 19 | return binary_search(arr, low, mid - 1, x) 20 | 21 | # Else the element can only be present in right subarray 22 | else: 23 | return binary_search(arr, mid + 1, high, x) 24 | 25 | else: 26 | # Element is not present in the array 27 | return -1 28 | 29 | # Test array 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binary_search(arr, 0, len(arr)-1, x) 35 | 36 | if result != -1: 37 | print("Element is present at index", str(result)) 38 | else: 39 | print("Element is not present in array") 40 | -------------------------------------------------------------------------------- /Binary Search/BinarySearch_iterative.c: -------------------------------------------------------------------------------- 1 | #include 2 | int iterativeBinarySearch(int array[], int start_index, int end_index, int element){ 3 | while (start_index <= end_index){ 4 | int middle = start_index + (end_index- start_index )/2; 5 | if (array[middle] == element) 6 | return middle; 7 | if (array[middle] < element) 8 | start_index = middle + 1; 9 | else 10 | end_index = middle - 1; 11 | } 12 | return -1; 13 | } 14 | int main(void){ 15 | int array[] = {1, 4, 7, 9, 16, 56, 70}; 16 | int n = 7; 17 | int element = 16; 18 | int found_index = iterativeBinarySearch(array, 0, n-1, element); 19 | if(found_index == -1 ) { 20 | printf("Element not found in the array "); 21 | } 22 | else { 23 | printf("Element found at index : %d",found_index); 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Binary Search/BinarySearch_using_recursion.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class BinarySearch_using_recursion { 5 | public static void main(String[] args) { 6 | int[] arr = { 1, 2, 3, 4, 5, 6 }; 7 | System.out.println(searcher(arr, 3, 0, arr.length - 1)); 8 | } 9 | 10 | static int searcher(int arr[], int target, int start, int end) { 11 | // checking if array is empty 12 | if (start > end) { 13 | return -1; 14 | } 15 | // calculating middle index of array 16 | int mid = start + (end - start) / 2; 17 | // if target found then return the index of answer 18 | if (arr[mid] == target) { 19 | return mid; 20 | } 21 | // checking if the first element of array is less than mid element 22 | if (arr[start] <= arr[mid]) { 23 | // checking if target is less than middle and equal to middle element 24 | // also target is less than first element 25 | if (target <= arr[mid] && target >= arr[start]) { 26 | // calling function so that it check the left part of array which is smaller 27 | // than middle element 28 | return searcher(arr, target, start, mid - 1); 29 | } else { 30 | // calling function so that it check the right part of array which is greater 31 | // than middle element 32 | return searcher(arr, target, mid + 1, end); 33 | } 34 | } 35 | // checking if target is greater than middle element and target is less than 36 | // last element of array 37 | if (target >= arr[mid] && target <= arr[end]) { 38 | // searching on right side of array 39 | return searcher(arr, target, mid + 1, end); 40 | } 41 | // searching on left side of array 42 | return searcher(arr, target, start, mid - 1); 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /Binary Search/README.md: -------------------------------------------------------------------------------- 1 | ## Binary Search algorithm 2 | 3 | #### This is an algorithm used to search a particular target element in a sorted array/list. 4 | ##### Time Complexity: O(log n) 5 | ##### Auxiliary Space: O(log n) 6 | 7 | #### Main steps: 8 | * Take the array and the target element. 9 | * Initialize the **start** as first index and **end** as last index of the array/list. 10 | * Run a loop as long as your **start <= end**. 11 | * Calculate the **middle index** of the array between **start** and **end**. 12 | * Now check if the **element at middle index** is either **equal/smaller/greater** than the **target** element . 13 | * If the **middle element** is **equal** to the target, **return the middle index**. 14 | * If the **middle element** is **larger** than the target element, set **end** as **middle - 1** and search in the first half of the array. 15 | * If the **middle element** is **smaller** than the target element, set **start** as **middle + 1** and search in the second half of the array. 16 | * Keep repeating the above steps as long as **start <= end**. 17 | * If the loop breaks and the **element is not found**, return **-1** 18 | -------------------------------------------------------------------------------- /Binary Tree/main.py: -------------------------------------------------------------------------------- 1 | tree = [None] * 10 2 | def root(key): 3 | if tree[0] != None: 4 | print("Tree already had root") 5 | else: 6 | tree[0] = key 7 | def set_left(key, parent): 8 | if tree[parent] == None: 9 | print("Can't set child at", (parent * 2) + 1, ", no parent found") 10 | else: 11 | tree[(parent * 2) + 1] = key 12 | def set_right(key, parent): 13 | if tree[parent] == None: 14 | print("Can't set child at", (parent * 2) + 2, ", no parent found") 15 | else: 16 | tree[(parent * 2) + 2] = key 17 | def print_tree(): 18 | for i in range(10): 19 | if tree[i] != None: 20 | print(tree[i], end="") 21 | else: 22 | print("-", end="") 23 | print() 24 | root('A') 25 | set_right('C', 0) 26 | set_left('D', 1) 27 | set_right('E', 1) 28 | set_right('F', 2) 29 | print_tree() 30 | -------------------------------------------------------------------------------- /Bubble Sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class BubbleSort{ 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] arr = {5, 1, 4, 2, 8}; 8 | bubblesort(arr,arr.length - 1,0); 9 | System.out.println(Arrays.toString(arr)); 10 | } 11 | static void bubblesort(int arr[], int end, int start){ 12 | //we check if last index is greater than first index 13 | if(end < start){ 14 | return; 15 | } 16 | //This loop will execute if first index is less than last index. this loop will swap biggest element of array with last then for second biggest it will swap with second last element and so on ... 17 | if(start <= end){ 18 | //this condition is comparing element and swaping them 19 | if(arr[start] > arr[start+1]){ 20 | int tmp = arr[start]; 21 | arr[start] = arr[start+1]; 22 | arr[start+1] = tmp; 23 | } 24 | //if element is at right place then just check for next element 25 | else{ 26 | 27 | bubblesort(arr,end,start+1); 28 | 29 | } 30 | 31 | } 32 | // this will sort unsorted array and ignore sorted array 33 | bubblesort(arr,end-1,0); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Bubble Sort/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort 2 | Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. 3 | 4 | __How does Bubble Sort Work?__ 5 | - Input: arr[] = {5, 1, 4, 2, 8} 6 | 7 | ***First Pass:*** 8 |
 9 | Bubble sort starts with very first two elements, comparing them to check which one is greater.
10 | ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. 
11 | ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4 
12 | ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2 
13 | ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
14 | 
15 | 16 | ***Second Pass:*** 17 |
18 | Now, during second iteration it should look like this:
19 | ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) 
20 | ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 
21 | ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
22 | ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 ) 
23 | 
24 | 25 | ***Third Pass:*** 26 |
27 | Now, the array is already sorted, but our algorithm does not know if it is completed.
28 | The algorithm needs one whole pass without any swap to know it is sorted.
29 | ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
30 | ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
31 | ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
32 | ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
33 | 
34 | -------------------------------------------------------------------------------- /Check BST/checkBinaryTreeAsBST.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 | public boolean isValidBST(TreeNode root) { 18 | return checkBST(root, Long.MAX_VALUE, Long.MIN_VALUE); 19 | } 20 | 21 | public boolean checkBST(TreeNode root, long maxval, long minval){ 22 | if(root == null) return true; 23 | 24 | // if(root.left == null && root.right == null && (root.val == Integer.MAX_VALUE || root.val == Integer.MIN_VALUE)) return true; 25 | 26 | else if(root.val >= maxval || root.val <= minval) return false; 27 | 28 | else{ 29 | return checkBST(root.right, maxval, root.val) && checkBST(root.left, root.val, minval); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | While on one hand our repository is a good place for beginners to contribute something useful to open source, on the other hand it is also a good place for experienced people to contribute something useful to open source. We welcome contributions from everyone.
3 | However some people tend to spam the repository with irrelevant pull requests and get one PR for hacktoberfest and other such open source events. We do not want that to happen. So we have a few guidelines that we would like you to follow.
4 | __In case we find your PR not relevant or spam, we will mark it as invalid and it will not be counted towards hacktoberfest.__ -------------------------------------------------------------------------------- /DFS/DFS in graphs/DFSTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class DFSTraversal { 4 | private LinkedList adj[]; /*adjacency list representation*/ 5 | private boolean visited[]; 6 | 7 | /* Creation of the graph */ 8 | DFSTraversal(int V) /*'V' is the number of vertices in the graph*/ 9 | { 10 | adj = new LinkedList[V]; 11 | visited = new boolean[V]; 12 | 13 | for (int i = 0; i < V; i++) 14 | adj[i] = new LinkedList(); 15 | } 16 | 17 | /* Adding an edge to the graph */ 18 | void insertEdge(int src, int dest) { 19 | adj[src].add(dest); 20 | } 21 | 22 | void DFS(int vertex) { 23 | visited[vertex] = true; /*Mark the current node as visited*/ 24 | System.out.print(vertex + " "); 25 | 26 | Iterator it = adj[vertex].listIterator(); 27 | while (it.hasNext()) { 28 | int n = it.next(); 29 | if (!visited[n]) 30 | DFS(n); 31 | } 32 | } 33 | 34 | public static void main(String args[]) { 35 | DFSTraversal graph = new DFSTraversal(8); 36 | 37 | graph.insertEdge(0, 1); 38 | graph.insertEdge(0, 2); 39 | graph.insertEdge(0, 3); 40 | graph.insertEdge(1, 3); 41 | graph.insertEdge(2, 4); 42 | graph.insertEdge(3, 5); 43 | graph.insertEdge(3, 6); 44 | graph.insertEdge(4, 7); 45 | graph.insertEdge(4, 5); 46 | graph.insertEdge(5, 2); 47 | 48 | System.out.println("Depth First Traversal for the graph is:"); 49 | graph.DFS(0); 50 | } 51 | } -------------------------------------------------------------------------------- /DFS/DFS in graphs/readme.md: -------------------------------------------------------------------------------- 1 | # DFS in Graph Data structure 2 | 3 | ![alt text](https://www.tutorialspoint.com/data_structures_algorithms/images/depth_first_traversal.jpg) 4 | 5 | ### Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration. 6 | 7 | As in the example given above, DFS algorithm traverses from S to A to D to G to E to B first, then to F and lastly to C. It employs the following rules. 8 | 9 | Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack. 10 | 11 | Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack, which do not have adjacent vertices.) 12 | 13 | Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty. 14 | -------------------------------------------------------------------------------- /DFS/DFS in trees/DFS_iterative.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class DFS_iterative{ 4 | public static void main(String args[]){ 5 | Node n1 = new Node(1); 6 | Node n2 = new Node(2); 7 | Node n3 = new Node(3); 8 | Node n4 = new Node(4); 9 | Node n5 = new Node(5); 10 | Node n6 = new Node(6); 11 | Node n7 = new Node(7); 12 | 13 | 14 | n1.left = n2; 15 | n1.right = n3; 16 | n2.left = n4; 17 | n2.right = n5; 18 | n3.left = n6; 19 | n3.right = n7; 20 | /* 21 | n1 22 | / \ 23 | n2 n3 24 | / \ / \ 25 | n4 n5 n6 n7 26 | */ 27 | 28 | Stack stack = new Stack<>(); 29 | stack.add(n1); 30 | 31 | while(!stack.isEmpty()){ 32 | Node visited = stack.pop(); 33 | System.out.print(visited.data+" "); 34 | if(visited.right!=null) stack.push(visited.right); 35 | if(visited.left != null) stack.push(visited.left); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /DFS/DFS in trees/DFS_recursion.java: -------------------------------------------------------------------------------- 1 | public class DFS_recursion { 2 | public static void main(String args[]){ 3 | Node n1 = new Node(1); 4 | Node n2 = new Node(2); 5 | Node n3 = new Node(3); 6 | Node n4 = new Node(4); 7 | Node n5 = new Node(5); 8 | Node n6 = new Node(6); 9 | Node n7 = new Node(7); 10 | 11 | 12 | n1.left = n2; 13 | n1.right = n3; 14 | n2.left = n4; 15 | n2.right = n5; 16 | n3.left = n6; 17 | n3.right = n7; 18 | /* 19 | n1 20 | / \ 21 | n2 n3 22 | / \ / \ 23 | n4 n5 n6 n7 24 | */ 25 | DFS(n1); 26 | } 27 | static void DFS(Node n){ 28 | if(n==null) 29 | return; 30 | System.out.print(n.data+" "); 31 | DFS(n.left); 32 | DFS(n.right); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /DFS/DFS in trees/Node.java: -------------------------------------------------------------------------------- 1 | public class Node { 2 | int data; 3 | Node left,right; 4 | 5 | Node(int data){ 6 | this.data = data; 7 | this.left = null; 8 | this.right = null; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /DFS/DFS in trees/readme.md: -------------------------------------------------------------------------------- 1 | # Depth First Search using Tree Data Strucutres 2 | 3 | 4 | ### Depth-first search 5 | 6 | DFS (Depth-first search) is technique used for traversing tree or graph. Here backtracking is used for traversal. In this traversal first the deepest node is visited and then backtracks to it’s parent node if no sibling of that node exist. 7 | 8 | ### DFS Traversal of a Graph vs Tree 9 | 10 | In graph, there might be cycles and dis-connectivity. Unlike graph, tree does not contain cycle and always connected. So DFS of a tree is relatively easier. We can simply begin from a node, then traverse its adjacent (or children) without caring about cycles. And if we begin from a single node (root), and traverse this way, it is guaranteed that we traverse the whole tree as there is no dis-connectivity, 11 | -------------------------------------------------------------------------------- /DFS/dfs_matrix/pacific.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int m,n; 4 | 5 | bool s(vector>& ocean, int i, int j, vector>& ht){ 6 | 7 | if (i<0 || j<0 || i==m || j==n || ht[i][j]==100004) return false; 8 | if (ocean[i][j]) return true; 9 | 10 | int k = ht[i][j]; 11 | ht[i][j]=100004; 12 | bool zz = false; 13 | if (i>0 && ht[i-1][j]<=k) zz = zz || s(ocean,i-1,j,ht); 14 | if (j>0 && ht[i][j-1]<=k) zz = zz || s(ocean,i,j-1,ht); 15 | if (i> pacificAtlantic(vector>& ht) { 25 | m = ht.size(); 26 | n = ht[0].size(); 27 | vector> pac(m, vector (n,false)); 28 | vector> atl(m, vector (n,false)); 29 | for (int i=0; i> res; 38 | for (int i=0; i> &grid,vector>> &dp,int k,long long sum) 5 | { 6 | if(i<0 || j<0 || i>=m || j>=n) 7 | return 0; 8 | sum = (sum + grid[i][j]) % k; 9 | if(i==m-1 && j==n-1) 10 | { 11 | if(sum==0) 12 | return 1; 13 | return 0; 14 | } 15 | if(dp[i][j][sum]!=-1) 16 | return dp[i][j][sum]; 17 | int right=fun(i,j+1,m,n,grid,dp,k,sum)%mod; 18 | int down=fun(i+1,j,m,n,grid,dp,k,sum)%mod; 19 | return dp[i][j][sum]=(right+down)%mod; 20 | } 21 | int numberOfPaths(vector>& grid, int k) { 22 | int m=grid.size(); 23 | int n=grid[0].size(); 24 | vector>> dp(m + 1, vector> (n + 1, vector (k + 1, -1))); 25 | return fun(0,0,m,n,grid,dp,k,0LL); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Factorial/Factorial.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | factorial(int a) { 4 | if (a == 1) { 5 | return 1; 6 | } 7 | return a * factorial(a - 1); 8 | } 9 | 10 | void main() { 11 | stdout.write("Enter a no.: "); 12 | int a = int.parse(stdin.readLineSync().toString()); 13 | int ans = factorial(a); 14 | print(ans); 15 | } 16 | -------------------------------------------------------------------------------- /Factorial/Factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class Main { 3 | public static void main(String args[]){ 4 | int j, factorial=1, number; 5 | System.out.println("Enter the number to which you need to find the factorial:"); 6 | Scanner sc = new Scanner(System.in); 7 | number = sc.nextInt(); 8 | 9 | for(j = 1; j<=number; j++) { 10 | factorial = factorial * j; 11 | } 12 | System.out.println("Factorial of the given number is:: "+factorial); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Factorial/README.md: -------------------------------------------------------------------------------- 1 |

Finding the Factorial of a number

2 |

Factorial of a number refers to finding the product of all the numbers withing a given range.

3 |

Algorithm

4 |
    5 |
  • Step 1: Start
  • 6 |
  • Step 2: Ask the user to enter a number.
  • 7 |
  • Step 3: Take the user input and store it in a variable.
  • 8 |
  • Step 4: Start multiplying from 1 till the number provided as user input.
  • 9 |
  • Step 5: Print the value of the product obtained.
  • 10 |
  • Step 6: End
  • 11 |
12 |

Space And Time Complexity

13 |
    14 |
  • Space Complexity : O(1) -> Here '1' represents constant space.
  • 15 |
  • Time Complexity : O(n) -> Here 'n' is the number given by the user.
  • 16 |
2 | 3 | using namespace std; 4 | 5 | #define ar array 6 | #define ll long long 7 | 8 | const int MAX_N = 2e5 + 1; 9 | const int MOD = 1e9 + 7; 10 | const int INF = 1e9; 11 | const ll LINF = 1e18; 12 | 13 | #define LSOne(S) ((S) & (-S)) 14 | 15 | int n, q; 16 | ll ft[MAX_N]; 17 | 18 | void update(int x, int v) 19 | { 20 | for (; x <= n; x += LSOne(x)) 21 | ft[x] += v; 22 | } 23 | 24 | ll sum(int x) 25 | { 26 | ll res = 0; 27 | for (; x; x -= LSOne(x)) 28 | res += ft[x]; 29 | return res; 30 | } 31 | 32 | ll rsq(int l, int r) 33 | { 34 | return sum(r) - sum(l - 1); 35 | } 36 | 37 | void solve() 38 | { 39 | cin >> n >> q; 40 | for (int i = 1; i <= n; i++) 41 | { 42 | int x; 43 | cin >> x; 44 | update(i, x); 45 | } 46 | while (q--) 47 | { 48 | int t; 49 | cin >> t; 50 | if (t == 1) 51 | { 52 | int x, v; 53 | cin >> x >> v; 54 | update(x, v - rsq(x, x)); 55 | } 56 | else 57 | { 58 | int l, r; 59 | cin >> l >> r; 60 | cout << rsq(l, r) << "\n"; 61 | } 62 | } 63 | } 64 | 65 | int main() 66 | { 67 | ios_base::sync_with_stdio(0); 68 | cin.tie(0); 69 | cout.tie(0); 70 | // freopen("input.txt", "r", stdin); 71 | // freopen("output.txt", "w", stdout); 72 | 73 | int tc; 74 | tc = 1; 75 | for (int t = 1; t <= tc; t++) 76 | { 77 | // cout << "Case #" << t << ": "; 78 | solve(); 79 | } 80 | } -------------------------------------------------------------------------------- /Fibonacci/Fibonacci-Series.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int number; 7 | int num1 = 0, num2=1 , temp=0; 8 | 9 | 10 | cout << "Enter No. of integers you want to print for fibonacci series: "; 11 | cin >> number ; 12 | cout << num1 << " " << num2 << " "; 13 | for (int i = 2 ; i < number ; i++) 14 | { 15 | temp=num1+num2; 16 | cout << temp << " "; 17 | num1=num2; 18 | num2=temp; 19 | } 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Fibonacci/Fibonacci-Series.py: -------------------------------------------------------------------------------- 1 | def fibo(n): 2 | if n <= 1: 3 | return n 4 | else: 5 | return(fibo(n-1) + fibo(n-2)) 6 | 7 | terms = int(input('no of terms you want ')) 8 | 9 | """ check if the number of terms is valid """ 10 | if terms <= 0: 11 | print("Plese enter a positive integer") 12 | else: 13 | print("Fibonacci sequence:") 14 | for i in range(terms): 15 | print(fibo(i)) -------------------------------------------------------------------------------- /Fibonacci/Fibonacci.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | public static void main(String[] args) { 3 | int ans = fibo(50); 4 | System.out.println(ans); 5 | } 6 | 7 | static int fibo(int n) { 8 | // base condition 9 | if (n < 2) { 10 | return n; 11 | } 12 | return fibo(n-1) + fibo(n-2); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Fibonacci/Fibonacci_Series.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n1 = 0, n2 = 1, n3, i, number; 5 | printf("Enter the number of elements:"); 6 | scanf("%d", &number); 7 | printf("\n%d %d", n1, n2); 8 | for (i = 2; i < number; ++i) 9 | { 10 | n3 = n1 + n2; 11 | printf(" %d", n3); 12 | n1 = n2; 13 | n2 = n3; 14 | } 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Fibonacci/README.md: -------------------------------------------------------------------------------- 1 | ### Fibonacci Sequence 2 | #### A Fibonacci Sequence is a sequence starting from "0 , 1" and in which the succeeding term is the sum of preceding two terms. 3 | #### 0,1,1,2,3,5,8,13..... and so on. 4 | 5 | ### Steps to Print Fibonacci Sequence: 6 | * Take Input from the User about number of elements and store in variable "number". 7 | * Declare variables "num1=0" and "num2=1" , the first two elemnts of the sequence. 8 | * Declare a temporary variable "temp=0". 9 | * Print 0 and 1 which are starting two elements of sequence. 10 | * Using a for loop starting from 2 , because we already printed first two elements. 11 | * Inside loop , assign temp=num1+num2 and Print out temp with a space using " ". 12 | * Assign Num1=Num2 and Num2=temp. 13 | * Loop will print out the remaining elements of the sequence. 14 | 15 | -------------------------------------------------------------------------------- /Fibonacci/fibonacci.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | 4 | int i, n; 5 | 6 | // initialize first and second terms 7 | int t1 = 0, t2 = 1; 8 | 9 | // initialize the next term (3rd term) 10 | int nextTerm = t1 + t2; 11 | 12 | // get no. of terms from user 13 | printf("Enter the number of terms: "); 14 | scanf("%d", &n); 15 | 16 | // print the first two terms t1 and t2 17 | printf("Fibonacci Series: %d, %d, ", t1, t2); 18 | 19 | // print 3rd to nth terms 20 | for (i = 3; i <= n; ++i) { 21 | printf("%d, ", nextTerm); 22 | t1 = t2; 23 | t2 = nextTerm; 24 | nextTerm = t1 + t2; 25 | } 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Generate a strong password/Password_Generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | letters = ["a","b","c","d","e","f","g","h","i","j","k" 4 | ,"l","m","n","o","p","q","r","s","t","u","v","w","x","y", 5 | "z",'A','B','C','D','E','F','G','H','I','J','K','L','M', 6 | 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] 7 | numbers = ["0",'1','2','3','4','5','6','7','8','9'] 8 | symbols = ['!','@','#',"$","%","^","&",'*',"(",")","+","_","-"] 9 | 10 | print("Welcome to the PyPassword Generator!") 11 | nr_letters= int(input("How many letters would you like in your password? \n")) 12 | nr_numbers= int(input("How many numbers would you like in your password? \n")) 13 | nr_symbols= int(input("How many symbols would you like in your password? \n")) 14 | 15 | string = num = symbl ="" 16 | for i in range (0, nr_letters): 17 | string += letters[random.randint(0, len(letters)-1)] 18 | 19 | for j in range (0, nr_numbers): 20 | num += numbers[random.randint(0, len(numbers)-1)] 21 | 22 | for k in range (0, nr_symbols): 23 | symbl += symbols[random.randint(0, len(symbols)-1)] 24 | 25 | easy = string + num + symbl 26 | print(f"The easy password is {easy}") 27 | 28 | password = [] 29 | for l in range (0, nr_letters): 30 | password.append(random.choice(letters)) 31 | 32 | for m in range (0, nr_numbers): 33 | password += random.choice(numbers) 34 | 35 | for n in range (0, nr_symbols): 36 | password += random.choice(symbols) 37 | 38 | random.shuffle(password) 39 | 40 | hard ="" 41 | for p in password: 42 | hard += p 43 | print(f"The hard password is {hard}") -------------------------------------------------------------------------------- /Heap Sort/Heap_Sort.c: -------------------------------------------------------------------------------- 1 | // Heap Sort in C 2 | 3 | #include 4 | 5 | // Function to swap the the position of two elements 6 | void swap(int *a, int *b) { 7 | int temp = *a; 8 | *a = *b; 9 | *b = temp; 10 | } 11 | 12 | void heapify(int arr[], int n, int i) { 13 | // Find largest among root, left child and right child 14 | int largest = i; 15 | int left = 2 * i + 1; 16 | int right = 2 * i + 2; 17 | 18 | if (left < n && arr[left] > arr[largest]) 19 | largest = left; 20 | 21 | if (right < n && arr[right] > arr[largest]) 22 | largest = right; 23 | 24 | // Swap and continue heapifying if root is not largest 25 | if (largest != i) { 26 | swap(&arr[i], &arr[largest]); 27 | heapify(arr, n, largest); 28 | } 29 | } 30 | 31 | // Main function to do heap sort 32 | void heapSort(int arr[], int n) { 33 | // Build max heap 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapify(arr, n, i); 36 | 37 | // Heap sort 38 | for (int i = n - 1; i >= 0; i--) { 39 | swap(&arr[0], &arr[i]); 40 | 41 | // Heapify root element to get highest element at root again 42 | heapify(arr, i, 0); 43 | } 44 | } 45 | 46 | // Print an array 47 | void printArray(int arr[], int n) { 48 | for (int i = 0; i < n; ++i) 49 | printf("%d ", arr[i]); 50 | printf("\n"); 51 | } 52 | 53 | // Driver code 54 | int main() { 55 | int arr[] = {1, -12, -9, 5, 65, 17}; 56 | int n = sizeof(arr) / sizeof(arr[0]); 57 | 58 | heapSort(arr, n); 59 | 60 | printf("Sorted array is \n"); 61 | printArray(arr, n); 62 | } -------------------------------------------------------------------------------- /Heap Sort/README.md: -------------------------------------------------------------------------------- 1 | # Heap Sort # 2 | Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements. 3 | * Heap sort is an in-place algorithm. 4 | * Its typical implementation is not stable, but can be made stable. 5 | * Typically 2-3 times slower than well-implemented QuickSort. 6 | * The reason for slowness is a lack of locality of reference. 7 | 8 | # Algorithm # 9 | * First convert the array into heap data structure using heapify, than one by one delete the root node of the Max-heap and replace it with the last node in the heap and then heapify the root of the heap. Repeat this process until size of heap is greater than 1. 10 | 11 | ### Follow the given steps to solve the problem: ### 12 | 13 | * Build a max heap from the input data. 14 | * At this point, the maximum element is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of the heap by 1. 15 | * Finally, heapify the root of the tree. 16 | * Repeat step 2 while the size of the heap is greater than 1. 17 | 18 | # Time Complexity # 19 | * Time Complexity of Heap Sort is O(N log N) -------------------------------------------------------------------------------- /Huffman_string_compression/huff.js: -------------------------------------------------------------------------------- 1 | class node{ 2 | left = null; 3 | right = null; 4 | data = null; 5 | frq = null; 6 | } 7 | 8 | let fr = {P : 11 ,R : 7,E : 14,Q : 8,A: 9,I : 5,O : 3} 9 | 10 | // let fr = { 11 | // b : 2, 12 | // e: 3, 13 | // c : 5,f : 7,d : 13,a : 70 14 | 15 | // } 16 | 17 | fr = Array.from(Object.entries(fr)); 18 | 19 | fr.sort((a,b)=>{return a[1]-b[1]}); 20 | 21 | var queue = []; 22 | 23 | fr.forEach(e=>{ 24 | n = new node(); 25 | n.data = e[0]; 26 | n.frq = e[1]; 27 | queue.push(n); 28 | }); 29 | 30 | console.log(queue,'tt'); 31 | 32 | ans = null; 33 | 34 | 35 | while(queue.length>1){ 36 | var a=queue.splice(0,1)[0]; 37 | var b=queue.splice(0,1)[0]; 38 | var z = new node(); 39 | z.left=a; 40 | z.right=b; 41 | z.data='z'; 42 | z.frq=a.frq+b.frq; 43 | if(a.frqb.frq){ 48 | z.left = b; 49 | z.right = a; 50 | } 51 | queue.splice(0,0,z); 52 | console.log(queue,queue.length); 53 | } 54 | console.log(queue[0]); 55 | 56 | rec=(str,node)=>{ 57 | if(node.data!='z')console.log(str,node.data); 58 | else{ 59 | rec(str+'0',node.left); 60 | rec(str+'1',node.right); 61 | } 62 | } 63 | 64 | rec('',queue[0]); -------------------------------------------------------------------------------- /Intersection of Two Arrays/intersactionoftwoarraysII.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class intersactionoftwoarraysII { 6 | public static void main(String[] args) { 7 | int[] nums1={1,2,2,1}; 8 | int[] nums2={2,2}; 9 | Arrays.sort(nums1); 10 | Arrays.sort(nums2); 11 | List list=new ArrayList<>(); 12 | int i=0,j=0; 13 | while(i " , maxSubArraySum(arr,len(arr))) -------------------------------------------------------------------------------- /Length of Last Word/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | String z=s.trim(); 4 | String word=z.substring(z.lastIndexOf(' ')+1); 5 | return word.length(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Level Order Traversal/LevelOrderTraversal.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 | public List> levelOrder(TreeNode root) { 18 | List> res = new ArrayList<>(); 19 | Queue queue = new LinkedList(); 20 | 21 | if(root == null)return res; 22 | 23 | queue.offer(root); 24 | 25 | while(queue.size() != 0){ 26 | int size = queue.size(); 27 | List wrap = new ArrayList<>(); 28 | 29 | for(int i = 0; i < size; i++){ 30 | if(queue.peek().left != null){queue.offer(queue.peek().left);} 31 | if(queue.peek().right != null){queue.offer(queue.peek().right);} 32 | 33 | wrap.add(queue.poll().val); 34 | } 35 | 36 | res.add(wrap); 37 | } 38 | 39 | return res; 40 | } 41 | } -------------------------------------------------------------------------------- /Linear Search/LinearSearch.java: -------------------------------------------------------------------------------- 1 | // Java code for linearly search x in arr[]. If x 2 | // is present then return its location, otherwise 3 | // return -1 4 | class LinearSearch { 5 | // This function returns index of element x in arr[] 6 | static int search(int arr[], int n, int x) 7 | { 8 | for (int i = 0; i < n; i++) { 9 | // Return the index of the element if the element 10 | // is found 11 | if (arr[i] == x) 12 | return i; 13 | } 14 | 15 | // return -1 if the element is not found 16 | return -1; 17 | } 18 | 19 | public static void main(String[] args) 20 | { 21 | int[] arr = { 3, 4, 1, 7, 5 }; 22 | int n = arr.length; 23 | 24 | int x = 4; 25 | 26 | int index = search(arr, n, x); 27 | if (index == -1) 28 | System.out.println("Element is not present in the array"); 29 | else 30 | System.out.println("Element found at position " + index); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Linear Search/README.md: -------------------------------------------------------------------------------- 1 | # Linear Search # 2 | Is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, 3 | otherwise the search continues till the end of the data set.It is the easiest searching algorithm. 4 | 5 | 6 | # Algorithm # 7 | * Step 1: Start 8 | * Step 2: Declare an array and search element as key. 9 | * Step 3: Traverse the array until the number is found. 10 | * Step 4: If the key element is found, return the index position of the array element 11 | * Step 5: If the key element is not found, return -1 12 | * Step 6: Stop. 13 | 14 | # Space And Time Complexity 15 | * Space Complexity of Linear Search is O(1). 16 | It means that the amount of memory your algorithm consumes doesn't depend on the input. The algorithm should use the same amount of memory for all inputs. 17 | So, the linear search only need one element need(that is the variable you used to compare with all the elements in the array), 18 | so no matter how big or small your array is, the algorithm only consumes the same amount of memory for all input, and thus is space complexity is O(1) 19 | 20 | * Time Complexity of Linear Search is O(n). -------------------------------------------------------------------------------- /Linear Search/linearsearch.py: -------------------------------------------------------------------------------- 1 | def linear_Search(list1, n, key): 2 | 3 | for i in range(0, n): 4 | if (list1[i] == key): 5 | return i 6 | return -1 7 | 8 | 9 | list1 = [1 ,3, 5, 4, 7, 9] 10 | key = 7 11 | 12 | n = len(list1) 13 | res = linear_Search(list1, n, key) 14 | if(res == -1): 15 | print("Element not found") 16 | else: 17 | print("Element found at index: ", res) 18 | -------------------------------------------------------------------------------- /LinkedList Operations/Reversing-linked-list.java: -------------------------------------------------------------------------------- 1 | //Reversing the linked list 2 | 3 | /*-------Reversing a Linked List Using Iterative Approach----------*/ 4 | 5 | 6 | public class LinkedListIterative 7 | { 8 | 9 | static LinkedListNode head; 10 | static class LinkedListNode 11 | { 12 | 13 | int val; 14 | LinkedListNode next; 15 | 16 | // constructor of the class LinkedListNode 17 | LinkedListNode(int no) 18 | { 19 | val = no; 20 | next = null; 21 | } 22 | } 23 | 24 | // Method for reversing the linked list 25 | LinkedListNode reverse(LinkedListNode node) 26 | { 27 | // doing the initialization 28 | // of as per the steps defined 29 | LinkedListNode previous = null; 30 | LinkedListNode curr = node; 31 | LinkedListNode next = null; 32 | 33 | 34 | while (curr != null) 35 | { 36 | next = curr.next; 37 | curr.next = previous; 38 | previous = curr; 39 | curr = next; 40 | } 41 | node = previous; 42 | return node; 43 | } 44 | 45 | // displays the content of the linked list 46 | void printList(LinkedListNode nde) 47 | { 48 | while (nde != null) 49 | { 50 | System.out.print(nde.val + " "); 51 | nde = nde.next; 52 | } 53 | } 54 | 55 | // main method 56 | public static void main(String argvs[]) 57 | { 58 | // creating an object of the class LinkedListIterative 59 | LinkedListIterative listObj = new LinkedListIterative(); 60 | 61 | // 4 -> NULL 62 | listObj.head = new LinkedListNode(4); 63 | 64 | // 4 -> 6 -> NULL 65 | listObj.head.next = new LinkedListNode(6); 66 | 67 | // 4 -> 6 -> 7 -> NULL 68 | listObj.head.next.next = new LinkedListNode(7); 69 | 70 | // 4 -> 6 -> 7 -> 1-> NULL 71 | listObj.head.next.next.next = new LinkedListNode(1); 72 | 73 | // 4 -> 6 -> 7 -> 1-> 5 -> NULL 74 | listObj.head.next.next.next.next = new LinkedListNode(5); 75 | 76 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> NULL 77 | listObj.head.next.next.next.next.next = new LinkedListNode(8); 78 | 79 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> 3 -> NULL 80 | listObj.head.next.next.next.next.next.next = new LinkedListNode(3); 81 | 82 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> 3 -> 2 -> NULL 83 | listObj.head.next.next.next.next.next.next.next = new LinkedListNode(2); 84 | 85 | 86 | System.out.println("The Linked list before reversal is: "); 87 | listObj.printList(head); 88 | head = listObj.reverse(head); 89 | System.out.println("\n"); 90 | System.out.println("After reversal, the linked list is: "); 91 | listObj.printList(head); 92 | } 93 | } 94 | 95 | 96 | 97 | 98 | 99 | /*-------Reversing a Linked List Using Recursive Approach----------*/ 100 | 101 | 102 | 103 | public class LinkedListRecursive 104 | { 105 | 106 | static LinkedListNode head; 107 | 108 | static class LinkedListNode 109 | { 110 | // for containing the value of the node 111 | int val; 112 | 113 | // the next pointer points to the other node of the list or null 114 | LinkedListNode next; 115 | 116 | // constructor of the class 117 | LinkedListNode(int d) 118 | { 119 | // assigning the values 120 | val = d; 121 | next = null; 122 | } 123 | } 124 | 125 | // method where actual reversing of the list takes place 126 | public LinkedListNode reverseList(LinkedListNode head) 127 | { 128 | // if the head is null or the list 129 | // contains only one element then reversing the list 130 | // does not have any impact on the list. Therefore, we 131 | // can return the original list without performing any operation 132 | if (head == null || head.next == null) 133 | { 134 | return head; 135 | } 136 | 137 | // reverse the rest (r) of the list and place 138 | // the first element of the list at the last 139 | LinkedListNode r = reverseList(head.next); 140 | head.next.next = head; 141 | 142 | 143 | head.next = null; 144 | 145 | // fixing the head pointer 146 | return r; 147 | } 148 | 149 | /* Method to display the linked list */ 150 | public void printList(LinkedListNode h) 151 | { 152 | LinkedListNode t = h; 153 | while (t != null) 154 | { 155 | System.out.print(t.val + " "); 156 | 157 | // moving to the next node 158 | t = t.next; 159 | } 160 | 161 | System.out.println(); 162 | } 163 | 164 | 165 | // main method 166 | public static void main(String argvs[]) 167 | { 168 | // creating an object of the class LinkedListRecursive 169 | LinkedListRecursive listObj = new LinkedListRecursive(); 170 | 171 | // 4 -> NULL 172 | listObj.head = new LinkedListNode(4); 173 | 174 | // 4 -> 6 -> NULL 175 | listObj.head.next = new LinkedListNode(6); 176 | 177 | // 4 -> 6 -> 7 -> NULL 178 | listObj.head.next.next = new LinkedListNode(7); 179 | 180 | // 4 -> 6 -> 7 -> 1-> NULL 181 | listObj.head.next.next.next = new LinkedListNode(1); 182 | 183 | // 4 -> 6 -> 7 -> 1-> 5 -> NULL 184 | listObj.head.next.next.next.next = new LinkedListNode(5); 185 | 186 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> NULL 187 | listObj.head.next.next.next.next.next = new LinkedListNode(8); 188 | 189 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> 3 -> NULL 190 | listObj.head.next.next.next.next.next.next = new LinkedListNode(3); 191 | 192 | // 4 -> 6 -> 7 -> 1-> 5 -> 8 -> 3 -> 2 -> NULL 193 | listObj.head.next.next.next.next.next.next.next = new LinkedListNode(2); 194 | 195 | 196 | System.out.println("The Linked list before reversal is: "); 197 | listObj.printList(head); 198 | head = listObj.reverseList(head); 199 | System.out.println(" "); 200 | System.out.println("After reversal, the linked list is: "); 201 | listObj.printList(head); 202 | } 203 | } 204 | 205 | 206 | 207 | 208 | -------------------------------------------------------------------------------- /LinkedList Operations/linkedlistOperations.c: -------------------------------------------------------------------------------- 1 | //c program to perform all Linked List operations 2 | #include //Header file Standard Input and Output 3 | #include //Header file for Standard Library Functions 4 | #include //Header file for Dynamic Memory Allocation 5 | struct node // Node Creation 6 | { 7 | int data; 8 | struct node *next; 9 | }; 10 | struct node *head; 11 | void createnode (int d) //Function for Creating nodes 12 | { 13 | struct node *ptr, *temp; 14 | ptr = (struct node *) malloc (sizeof (struct node)); 15 | if (ptr == NULL) 16 | printf ("\nNode creation failed !!!\n"); 17 | else 18 | { 19 | ptr->data = d; 20 | ptr->next = NULL; 21 | if (head == NULL) 22 | head = ptr; 23 | else 24 | { 25 | temp = head; 26 | while (temp->next != NULL) 27 | { 28 | temp = temp->next; 29 | } 30 | temp->next = ptr; 31 | } 32 | } 33 | } 34 | 35 | void deletenode (int pos) //Function for Deleting nodes 36 | { 37 | int i; 38 | pos = pos - 1; 39 | struct node *ptr, *temp; 40 | if (head == NULL) 41 | { 42 | printf ("\nThe node is empty !!!\n"); 43 | } 44 | else 45 | { 46 | if (pos == 0) 47 | { 48 | ptr = head; 49 | printf ("\nValue at node %d was %d\n", pos + 1, ptr->data); 50 | head = ptr->next; 51 | free (ptr); 52 | } 53 | else 54 | { 55 | ptr = head; 56 | for (i = 0; i < pos; i++) 57 | { 58 | temp = ptr; 59 | if (ptr == NULL) 60 | { 61 | printf ("\nPosition out of bound !!!\n"); 62 | return; 63 | } 64 | ptr = ptr->next; 65 | } 66 | temp->next = ptr->next; 67 | printf ("\nValue at node %d was %d\n", pos + 1, ptr->data); 68 | free (ptr); 69 | } 70 | } 71 | } 72 | 73 | void reverse() //Function for Reversing a linkedlist 74 | { 75 | struct node *cur, *nxt, *prv = NULL; 76 | cur = head; 77 | if (head == NULL) 78 | { 79 | printf ("\nThe node is empty !!!\n"); 80 | } 81 | else 82 | { 83 | while (cur != NULL) 84 | { 85 | nxt = cur->next; 86 | cur->next = prv; 87 | prv = cur; 88 | cur = nxt; 89 | } 90 | head = prv; 91 | } 92 | printf ("\nList reversed successfully\n"); 93 | } 94 | 95 | void search (int d) //Function for Searching a node 96 | { 97 | int i = 1, flag = 0; 98 | struct node *ptr; 99 | if (head == NULL) 100 | { 101 | printf ("\nThe node is empty !!!\n"); 102 | } 103 | else 104 | { 105 | ptr = head; 106 | while (ptr != NULL) 107 | { 108 | if (ptr->data == d) 109 | { 110 | printf ("\nValue found at position %d\n", i); 111 | flag = 1; 112 | break; 113 | } 114 | ptr = ptr->next; 115 | i++; 116 | } 117 | if (flag == 0) 118 | printf ("\nValue not found in list !!!\n"); 119 | } 120 | } 121 | 122 | void printdata() //Function for Printing the linkedlist 123 | { 124 | int i = 1; 125 | struct node *ptr; 126 | if (head == NULL) 127 | { 128 | printf ("\nThe node is empty !!!\n"); 129 | } 130 | else 131 | { 132 | ptr = head; 133 | while (ptr != NULL) 134 | { 135 | printf ("\nValue of node %d is %d\n", i, ptr->data); 136 | i++; 137 | ptr = ptr->next; 138 | } 139 | } 140 | } 141 | 142 | int count () //Function for Counting total number of nodes 143 | { 144 | struct node *ptr; 145 | int c = 0; 146 | ptr = head; 147 | while (ptr != NULL) 148 | { 149 | ptr = ptr->next; 150 | c++; 151 | } 152 | return c; 153 | } 154 | 155 | void anypos (int d, int p) //Function for Inserting nodes at any position 156 | { 157 | int c, i; 158 | p = p - 1; 159 | struct node *ptr, *temp; 160 | c = count (); 161 | ptr = (struct node *) malloc (sizeof (struct node)); 162 | ptr->data = d; 163 | ptr->next = NULL; 164 | if (c < p || c < 1) 165 | { 166 | printf ("\nInvalid position !!!\n"); 167 | return; 168 | } 169 | else 170 | { 171 | if (p == 0) 172 | { 173 | ptr->next = head; 174 | head = ptr; 175 | } 176 | else 177 | { 178 | temp = head; 179 | for (i = 0; i < p - 1; i++) 180 | { 181 | temp = temp->next; 182 | } 183 | ptr->next = temp->next; 184 | temp->next = ptr; 185 | } 186 | } 187 | } 188 | 189 | int main() //Main function begins 190 | { 191 | int choice, i = 1, data, pos; 192 | while (i != 7) //Providing different LinkedList operations 193 | { 194 | printf("\nEnter your choice\n"); 195 | printf ("\nEnter 1 to Create a node\n"); 196 | printf ("\nEnter 2 to Delete a node\n"); 197 | printf ("\nEnter 3 to Search a node\n"); 198 | printf ("\nEnter 4 to Print all nodes\n"); 199 | printf ("\nEnter 5 to Reverse the list\n"); 200 | printf ("\nEnter 6 to Insert node at any position of the list\n"); 201 | printf ("\nEnter 7 to Exit \n"); 202 | scanf ("%d", &choice); 203 | switch(choice) 204 | { 205 | case 1: 206 | printf ("\nEnter data for the node => \n"); 207 | scanf ("%d", &data); 208 | createnode (data); 209 | break; 210 | case 2: 211 | printf ("\nEnter position of the node to be deleted => \n"); 212 | scanf ("%d", &data); 213 | deletenode (data); 214 | break; 215 | case 3: 216 | printf ("\nEnter data to be searched => \n"); 217 | scanf ("%d", &data); 218 | search (data); 219 | break; 220 | case 4: 221 | printdata (); 222 | break; 223 | case 5: 224 | reverse (); 225 | break; 226 | case 6: 227 | printf ("\nEnter position of the node => \n"); 228 | scanf ("%d", &pos); 229 | printf ("\nEnter data for the node => \n"); 230 | scanf ("%d", &data); 231 | anypos (data, pos); 232 | break; 233 | case 7: 234 | i = 7; 235 | break; 236 | } 237 | } 238 | return 0; //Main function ends 239 | } 240 | -------------------------------------------------------------------------------- /Longest Common Prefix/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestCommonPrefix(String[] s) { 3 | for(int i=0;is[j+1].length()) 8 | { 9 | String t=s[j]; 10 | s[j]=s[j+1]; 11 | s[j+1]=t; 12 | } 13 | } 14 | } 15 | for(int i=s[0].length();i>=0;i--) 16 | { 17 | String w=s[0].substring(0,i); 18 | boolean f=true; 19 | for(int j=1;j 8 | Output: 7
9 | Explanation: "cbebebe" is the longest 10 | substring with K distinct characters.
11 | 12 | Example 2: 13 | 14 | Input: 15 | S = "aaaa", K = 2
16 | Output: -1
17 | Explanation: There's no substring with K 18 | distinct characters. 19 | 20 | Constraints:
21 | 1 ≤ |S| ≤ 105
22 | 1 ≤ K ≤ 105
23 | 24 | ### Main steps to solve :
25 | 1.Create a map of char as key and integer as value.
26 | 2.Then,we will iterate through string using two pointers,the two pointers will tell us when the size of window is less ,equal or greater than K.
27 | 3.When window size hits k,we will save the ans which is the size of map,as size of map will tell us k distinct characters.
28 | 4.If window size exceeds k,then we will remove calculation for leftmost pointer until size is greater than k. 29 | -------------------------------------------------------------------------------- /Longest K unique characters substring/longest_k_unique_characters_substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int longestKSubstr(string s, int k) 4 | { 5 | unordered_map un; 6 | int i = 0,j = 0,maxLen = -1; 7 | while(jk) 19 | { 20 | //removing the calculation of i until there size of map is greater than k 21 | while(un.size()>k) 22 | { 23 | un[s[i]]--; 24 | if(un[s[i]] == 0)//if frequency of ith character becomes 0,erase that character from map 25 | un.erase(s[i]); 26 | ++i; 27 | } 28 | ++j; 29 | } 30 | } 31 | return maxLen; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Matrix Operations/MatrixOperations.c: -------------------------------------------------------------------------------- 1 | //C program to perform all Matrix operations 2 | #include //Header file Standard Input and Output 3 | void printmatrix(int rows, int columns, int matrix[][rows]) //Function for printing the Matrix 4 | { 5 | int i,j; //Variable declaration 6 | for(i=0;i "); //Dimension of the array 62 | scanf("%d",&rows); 63 | columns=rows; //Since it is a square matrix number of rows and columns are equal 64 | int matrix1[rows][columns]; //Memory allocation for Matrix1 65 | int matrix2[rows][columns]; //Memory allocation for Matrix2 66 | printf("Enter data for the first matrix -> \n"); //Taking user input for the First Matrix 67 | for(i=0;i \n"); //Taking user input for the Second Matrix 75 | for(i=0;i \n"); //Printing the Matrix 1 for user confirmation 83 | printmatrix(rows,columns,matrix1); //Calling the print function 84 | printf("Inserted data for the Second matrix -> \n"); //Printing the Matrix 2 for user confirmation 85 | printmatrix(rows,columns,matrix2); //Calling the print function 86 | do //Providing different Matrix operations 87 | { 88 | printf("\nEnter 1 to perform Addition of Matrix => \n"); 89 | printf("\nEnter 2 to perform Subtraction of Matrix => \n"); 90 | printf("\nEnter 3 to perform Multiplication of Matrix => \n"); 91 | printf("\nEnter 4 to Exit => \n"); 92 | scanf("%d",&choice); 93 | switch(choice) 94 | { 95 | case 1:addition(rows,columns,matrix1,matrix2); 96 | break; 97 | case 2:subtraction(rows,columns,matrix1,matrix2); 98 | break; 99 | case 3:multiplication(rows,columns,matrix1,matrix2); 100 | break; 101 | case 4:choice=4; 102 | break; 103 | default: 104 | printf("Invalid choice!!!"); 105 | break; 106 | } 107 | } 108 | while(choice!=4); 109 | return 0; //Main function ends 110 | } 111 | -------------------------------------------------------------------------------- /Median of 2 sorted arrays/medianof2sortedarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /* VECTOR LIBRARAY*/ 3 | #include 4 | /* INT_MAX & INT_MIN */ 5 | #include 6 | using namespace std; 7 | 8 | 9 | double mediann(vector&a,vector&b){ 10 | /* SIZE OF ARRAY-1 */ 11 | int m = a.size(); 12 | /* SIZE OF ARRAY-2 */ 13 | int n = b.size(); 14 | /* WE APPLY BINARY SEARCH ON ARRAY OF LESS SIZE TO MINIMIZE THE TIME */ 15 | if(m > n) 16 | return mediann(b,a); 17 | /* LEFT & RIGHT END OF THE ARRAY */ 18 | int l = 0,r = m; 19 | while(l <= r){ 20 | /* DIVIDING INTO LEFT SECTION*/ 21 | int partx = l + (r - l)/2; 22 | /* DIVING INTO RIGHT SECTION */ 23 | int party=(m+n+1)/2 - partx; 24 | /* SO HERE IN THIS QUESTION ARRAYS ARE SORTED 25 | SO WE CAN USE THIS AS A CONDITION MAXIMUM OF THE ARRAYS 26 | WILL ON RIGHT SIDE & MINIMUM ON THE LEFT SIDE & 27 | BUT IN CASE OF CORNER CASE WHICH IS THE LAST 28 | OR FIRST ELEMENT. IN CASE OF FIRST ELEMENT ITS 29 | INT_MIN AND IN CASE OF LAST ELEMENT ITS INT_MAX TO CO 30 | MAPRE WITH */ 31 | int maxlx = (partx == 0)? INT_MIN : a[partx-1]; 32 | int minrx = (partx == m)? INT_MAX : a[partx]; 33 | int maxly = (party == 0)? INT_MIN : b[party-1]; 34 | int minry = (party==n)?INT_MAX:b[party]; 35 | /* SO IF FIND THE MINIMUM AND MAXIMUM NUMBER 36 | IN BOTH THE HALVES THEN RETURN THE 37 | SUM OF MAXIMUM(OF LEFT & RIGHT PORTION) & 38 | MINIMUM(OF LEFT & RIGHT) / 2 WHICH IS THE MEDIAN OF 39 | THE 2 ARRAYS */ 40 | if(maxlx <= minry && maxly <= minrx){ 41 | if((m + n) % 2 == 0) 42 | return (double)(max (maxlx , maxly)+ min(minrx , minry)) / 2; 43 | else 44 | return (double)(max(maxlx,maxly)); 45 | /* WE HAVE TO MOVE TO CENTER OF THE ARRAYS FOR GETTING THE MEDIAN */ 46 | }else if(maxlx > minry) 47 | r = partx - 1; 48 | else 49 | l= partx + 1; 50 | } 51 | return -1.0; 52 | } 53 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 54 | double ans; 55 | /* CALLING THE FUNCTION FOR GETTING THE MEDIAN */ 56 | ans = mediann(nums1,nums2); 57 | return ans; 58 | } 59 | int main(){ 60 | vector nums1{1,3}; 61 | vector nums2{2}; 62 | double ans = findMedianSortedArrays(nums1,nums2); 63 | printf("%lf is the median of the arrays",ans); 64 | } -------------------------------------------------------------------------------- /Merge Sort/MergeSort.c: -------------------------------------------------------------------------------- 1 | /* C program for Merge Sort */ 2 | #include 3 | #include 4 | 5 | // Merges two subarrays of arr[]. 6 | // First subarray is arr[l..m] 7 | // Second subarray is arr[m+1..r] 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | int i, j, k; 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | /* create temp arrays */ 15 | int L[n1], R[n2]; 16 | 17 | /* Copy data to temp arrays L[] and R[] */ 18 | for (i = 0; i < n1; i++) 19 | L[i] = arr[l + i]; 20 | for (j = 0; j < n2; j++) 21 | R[j] = arr[m + 1 + j]; 22 | 23 | /* Merge the temp arrays back into arr[l..r]*/ 24 | i = 0; // Initial index of first subarray 25 | j = 0; // Initial index of second subarray 26 | k = l; // Initial index of merged subarray 27 | while (i < n1 && j < n2) { 28 | if (L[i] <= R[j]) { 29 | arr[k] = L[i]; 30 | i++; 31 | } 32 | else { 33 | arr[k] = R[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | /* Copy the remaining elements of L[], if there 40 | are any */ 41 | while (i < n1) { 42 | arr[k] = L[i]; 43 | i++; 44 | k++; 45 | } 46 | 47 | /* Copy the remaining elements of R[], if there 48 | are any */ 49 | while (j < n2) { 50 | arr[k] = R[j]; 51 | j++; 52 | k++; 53 | } 54 | } 55 | 56 | /* l is for left index and r is right index of the 57 | sub-array of arr to be sorted */ 58 | void mergeSort(int arr[], int l, int r) 59 | { 60 | if (l < r) { 61 | // Same as (l+r)/2, but avoids overflow for 62 | // large l and h 63 | int m = l + (r - l) / 2; 64 | 65 | // Sort first and second halves 66 | mergeSort(arr, l, m); 67 | mergeSort(arr, m + 1, r); 68 | 69 | merge(arr, l, m, r); 70 | } 71 | } 72 | 73 | /* UTILITY FUNCTIONS */ 74 | /* Function to print an array */ 75 | void printArray(int A[], int size) 76 | { 77 | int i; 78 | for (i = 0; i < size; i++) 79 | printf("%d ", A[i]); 80 | printf("\n"); 81 | } 82 | 83 | /* Driver code */ 84 | int main() //Main Function 85 | { 86 | //Reading Values 87 | int n; 88 | printf("Enter number of elements in the array = "); 89 | scanf("%d", &n); 90 | int a[n]; 91 | printf("Enter the array:\n"); 92 | for (int i = 0; i < n; i++) //Loop 1 93 | { 94 | scanf("%d", &a[i]); 95 | } 96 | printf("Given Array:\n"); 97 | printArray(a, n); 98 | mergeSort(a, 0, n - 1); 99 | printf("Array after sorting:\n"); 100 | printArray(a, n); 101 | } 102 | -------------------------------------------------------------------------------- /Merge Sort/README.md: -------------------------------------------------------------------------------- 1 | # Merge Sort # 2 | The Merge Sort algorithm is a sorting algorithm that is based on the Divide and Conquer paradigm. In this algorithm, the array is initially divided into two equal halves and then they are combined in a sorted manner. 3 | 4 | 5 | # Merge Sort Working Process: # 6 | Think of it as a recursive algorithm continuously splits the array in half until it cannot be further divided. This means that if the array becomes empty or has only one element left, the dividing will stop, i.e. it is the base case to stop the recursion. If the array has multiple elements, split the array into halves and recursively invoke the merge sort on each of the halves. Finally, when both halves are sorted, the merge operation is applied. Merge operation is the process of taking two smaller sorted arrays and combining them to eventually make a larger one. 7 | 8 | # Algorithm # 9 | * Step 1: Start 10 | * Step 2: Declare array and left, right, mid variable 11 | * Step 3: Perform merge function. 12 | if left > right 13 | return 14 | mid= (left+right)/2 15 | mergesort(array, left, mid) 16 | mergesort(array, mid+1, right) 17 | merge(array, left, mid, right) 18 | * Step 4: Stop. 19 | 20 | # Time Complexity # 21 | * Time Complexity of Merge Sort is O(N log(N)) -------------------------------------------------------------------------------- /Merge Sort/merge-sort.java: -------------------------------------------------------------------------------- 1 | // Merge sort in Java 2 | 3 | class MergeSort { 4 | 5 | // Merge two subarrays L and M into arr 6 | void merge(int arr[], int p, int q, int r) { 7 | 8 | // Create L ← A[p..q] and M ← A[q+1..r] 9 | int n1 = q - p + 1; 10 | int n2 = r - q; 11 | 12 | int L[] = new int[n1]; 13 | int M[] = new int[n2]; 14 | 15 | for (int i = 0; i < n1; i++) 16 | L[i] = arr[p + i]; 17 | for (int j = 0; j < n2; j++) 18 | M[j] = arr[q + 1 + j]; 19 | 20 | // Maintain current index of sub-arrays and main array 21 | int i, j, k; 22 | i = 0; 23 | j = 0; 24 | k = p; 25 | 26 | // Until we reach either end of either L or M, pick larger among 27 | // elements L and M and place them in the correct position at A[p..r] 28 | while (i < n1 && j < n2) { 29 | if (L[i] <= M[j]) { 30 | arr[k] = L[i]; 31 | i++; 32 | } else { 33 | arr[k] = M[j]; 34 | j++; 35 | } 36 | k++; 37 | } 38 | 39 | // When we run out of elements in either L or M, 40 | // pick up the remaining elements and put in A[p..r] 41 | while (i < n1) { 42 | arr[k] = L[i]; 43 | i++; 44 | k++; 45 | } 46 | 47 | while (j < n2) { 48 | arr[k] = M[j]; 49 | j++; 50 | k++; 51 | } 52 | } 53 | 54 | // Divide the array into two subarrays, sort them and merge them 55 | void mergeSort(int arr[], int l, int r) { 56 | if (l < r) { 57 | 58 | // m is the point where the array is divided into two subarrays 59 | int m = (l + r) / 2; 60 | 61 | mergeSort(arr, l, m); 62 | mergeSort(arr, m + 1, r); 63 | 64 | // Merge the sorted subarrays 65 | merge(arr, l, m, r); 66 | } 67 | } 68 | 69 | // Print the array 70 | static void printArray(int arr[]) { 71 | int n = arr.length; 72 | for (int i = 0; i < n; ++i) 73 | System.out.print(arr[i] + " "); 74 | System.out.println(); 75 | } 76 | 77 | // Driver program 78 | public static void main(String args[]) { 79 | int arr[] = { 6, 5, 12, 10, 9, 1 }; 80 | 81 | MergeSort ob = new MergeSort(); 82 | ob.mergeSort(arr, 0, arr.length - 1); 83 | 84 | System.out.println("Sorted array:"); 85 | printArray(arr); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Merge Sort/merge-sort.py: -------------------------------------------------------------------------------- 1 | """ implementation of merge sort in python """ 2 | def MergeArr(array_1,array_2,array): 3 | i =0 4 | j= 0 5 | k= 0 6 | 7 | while (i arr2[ptr2]){ 35 | int temp = arr1[ptr1]; 36 | arr1[ptr1] = arr2[ptr2]; 37 | arr2[ptr2] = temp; 38 | } 39 | 40 | Arrays.sort(arr2); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /N Queens/N_Queens.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class N_Queens { 4 | public static void main(String[] args) { 5 | System.out.println("Enter the value of 'N':"); 6 | int n = new Scanner(System.in).nextInt(); 7 | for(int i=0; i=0){ // Checking Vertically 30 | if(board[row][col]) // Checking the column above (row,col) 31 | return false; 32 | if(--ld>=0 && board[row][ld]) // Checking left diagonal 33 | return false; 34 | if(++rd 2 | using namespace std; 3 | bool check(int row,int col,vector &vc) 4 | { 5 | int n=vc.size(); 6 | int r=row; 7 | int c=col; 8 | while(r>=0 && c>=0) 9 | { 10 | if(vc[r][c]=='Q') 11 | return false; 12 | c--; 13 | r--; 14 | } 15 | r=row; 16 | c=col; 17 | while(c>=0) 18 | { 19 | if(vc[r][c]=='Q') 20 | return false; 21 | c--; 22 | } 23 | r=row; 24 | c=col; 25 | while(r=0) 26 | { 27 | if(vc[r][c]=='Q') 28 | return false; 29 | r++; 30 | c--; 31 | } 32 | return true; 33 | 34 | } 35 | void solve(int col,int n,vector &vc,vector> &ans) 36 | { 37 | if(col==n) 38 | { 39 | ans.push_back(vc); 40 | return; 41 | } 42 | for(int row=0;row> solveNQueens(int n) { 53 | vector> ans; 54 | vector vc; 55 | string s(n,'.'); 56 | for(int i=0;i>n; 65 | vector> vc=solveQueens(n); 66 | for(auto it:vc){ 67 | for(auto i:it) 68 | cout<=0;i--) 7 | { 8 | digits[i]=digits[i]+c; 9 | if(digits[i]>9) 10 | { 11 | digits[i]=0; 12 | c=1; 13 | } 14 | else 15 | { 16 | c=0; 17 | break; 18 | } 19 | } 20 | if(c!=1) 21 | { 22 | return digits; 23 | } 24 | else 25 | { 26 | int a[]=new int[digits.length+1]; 27 | a[0]=c; 28 | for(int j=1;j 2 | using namespace std; 3 | 4 | 5 | class stack1 6 | { 7 | public: 8 | int *arr; 9 | int topChar; 10 | int top; 11 | stack1() 12 | { 13 | 14 | } 15 | stack1(int n) 16 | { 17 | top = -1; 18 | arr = new int[n]; 19 | } 20 | void push(char ele) 21 | { 22 | top++; 23 | arr[top] = ele; 24 | } 25 | int pop() 26 | { 27 | if(top == -1) 28 | return '0'; 29 | else 30 | { 31 | topChar = arr[top]; 32 | top--; 33 | //cout<>ch; 64 | 65 | if(ch == 1) 66 | { 67 | cout<<"\nEnter the element : "; 68 | cin>>num; 69 | if(obj1.isEmpty()) 70 | obj1.push(num); 71 | else 72 | { 73 | while(!obj1.isEmpty()) 74 | { 75 | //cout<<"Peek element : "< 19 | Input List: [7, 6, 5, 4, 3, 2, 1] 20 | 2. The function will compare and partition each element around the chosen pivot. Hover over numbers for more information... 21 | 22 | Partition0: [7, 6, 5, 4, 3, 2, 1] 23 | / \ 24 | [3, 2, 1, 4] [7, 6, 5] 25 | 3. If the value is less than the pivot, the value will shift to the left partition, and if the value is greater than the pivot, the value will shift to the right partition. 26 | 27 | Partition1: [3, 2, 1, 4] [7, 6, 5] 28 | / \ / \ 29 | [1, 2] [3, 4] [5, 6] [7] 30 | 4. This occurs recursively, and a new pivot is selected to sort the sub-partitions. 31 | 32 | Partition2: [1, 2] [3, 4] [5, 6] 33 | / \ / \ / \ 34 | [1] [2] [3] [4] [5] [6] 35 | 5. This continues until the base case, where partitions are of length zero or one. 36 | 37 | [1] [2] [3] [4] [5] [6] [7] 38 | \ \ \ | / / / 39 | Output List: [1, 2, 3, 4, 5, 6, 7] 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Quick Sort/quickSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class quickSort{ 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] arr = {3,4,2,1}; 8 | quick(arr, 0, arr.length-1); 9 | System.out.println(Arrays.toString(arr)); 10 | 11 | } 12 | static void quick(int[] arr, int low, int high){ 13 | if(low >= high){ 14 | return; 15 | } 16 | int start = low; 17 | int end = high; 18 | int mid = low + (high - low) / 2; 19 | int pivot = arr[mid]; 20 | 21 | while(start <= end){ 22 | while(arr[start] < pivot){ 23 | start++; 24 | } 25 | while(arr[end] > pivot){ 26 | end--; 27 | } 28 | if(start <= end){ 29 | int tmp = arr[start]; 30 | arr[start] = arr[end]; 31 | arr[end] = tmp; 32 | start++; 33 | end--; 34 | } 35 | } 36 | 37 | quick(arr,low,end); 38 | quick(arr,start,high); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSA 2 | ## About 3 | This Repository's sole purpose is to help beginners and as well as experienced people contribute to Open Source Programming. The repository consists of a large number of Data Structures and Algorithms implemented in more than one language. The repository also contains some of the competitive program solutions. 4 | 5 | ## How to Contribute 6 | - Read the [Contributing Guidelines](Contributing.md) before making a PR. 7 | - Check for existing issues or create your own issues and wait for it to be assigned to you. 8 | - Fork the repository 9 | - Clone the forked repository to your local machine 10 | - Create a folder with the name of the data structure or algorithm or solution to a question you want to add if it is not present. 11 | - Add the code to that folder 12 | - Add a README.md file to the folder explaining the code 13 | - Open the command prompt and cd into the repository folder 14 | - Run the following Commands 15 | ``` 16 | git add . 17 | git commit -m"" 18 | git push 19 | ``` 20 | - Come back to Github and Open a Pull Request 21 | - While making Pull Request maintain the template provided to you 22 | - We will check if its a valid pull request and merge it 23 | 24 | ## To get a detailed explanation of the above steps refer to the following videos 25 | * [Intro to GitHub](https://youtu.be/wTTek8P2VB4) 26 | * [How to Create a Repository](https://youtu.be/o6T5F7-SOAo) 27 | * [Cloning a Repository](https://youtu.be/oYselL5G280) 28 | * [Contributing to a Project](https://youtu.be/4vq07q7g2xE) 29 | 30 | ### If you find this repository Helpful consider leaving :star: 31 | -------------------------------------------------------------------------------- /Rock,paper and scissors/Rock, Paper and Scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | print("Welcome to Rock-Paper-Scissors game!") 4 | print("Enter 1 for Rock, 2 for Paper and 3 for Scissors.") 5 | user_choice = int(input("What do you choose? ")) 6 | 7 | computer_choice = random.randint(1,3) 8 | print(f"Computer chose {computer_choice}") 9 | 10 | if computer_choice == user_choice: 11 | print("This is a draw") 12 | elif ((user_choice == 1 and computer_choice == 2) or (user_choice == 2 and computer_choice == 3) or (user_choice == 3 and computer_choice == 1)): 13 | print("you lose.") 14 | elif ((computer_choice == 1 and user_choice == 2) or (computer_choice == 2 and user_choice == 3) or (computer_choice == 3 and user_choice == 1)): 15 | print("You win!") 16 | else: 17 | print("You typed an invalid number!") -------------------------------------------------------------------------------- /Search Insertion Position/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] a, int target) { 3 | int mid=0; 4 | int l=0; 5 | int h=a.length-1; 6 | while(l<=h) 7 | { 8 | mid=(l+h)/2; 9 | // System.out.println(mid); 10 | if(a[mid]==target) 11 | { 12 | return mid; 13 | } 14 | else if(a[mid]>target) 15 | { 16 | h=mid-1; 17 | } 18 | else 19 | { 20 | l=mid+1; 21 | } 22 | } 23 | 24 | if(a[mid] root.key) 47 | root.right = insertRec(root.right, key); 48 | 49 | /* return the (unchanged) node pointer */ 50 | return root; 51 | } 52 | 53 | // This method mainly calls InorderRec() 54 | void inorder() { inorderRec(root); } 55 | 56 | // A utility function to 57 | // do inorder traversal of BST 58 | void inorderRec(Node root) 59 | { 60 | if (root != null) { 61 | inorderRec(root.left); 62 | System.out.println(root.key); 63 | inorderRec(root.right); 64 | } 65 | } 66 | 67 | // Driver Code 68 | public static void main(String[] args) 69 | { 70 | BinarySearchTree tree = new BinarySearchTree(); 71 | 72 | /* Let us create following BST 73 | 50 74 | / \ 75 | 30 70 76 | / \ / \ 77 | 20 40 60 80 */ 78 | tree.insert(50); 79 | tree.insert(30); 80 | tree.insert(20); 81 | tree.insert(40); 82 | tree.insert(70); 83 | tree.insert(60); 84 | tree.insert(80); 85 | 86 | // print inorder traversal of the BST 87 | tree.inorder(); 88 | } 89 | } 90 | // This code is contributed by Ankur Narain Verma 91 | -------------------------------------------------------------------------------- /Search in a BST/main.py: -------------------------------------------------------------------------------- 1 | def search(root,key): 2 | if root is None or root.val == key: 3 | return root 4 | if root.val < key: 5 | return search(root.right,key) 6 | return search(root.left,key) 7 | -------------------------------------------------------------------------------- /Searching in Rotated Sorted Array/SearchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SearchInRotatedSortedArray { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.println("Enter the length of the array: "); 7 | int n = sc.nextInt(); 8 | int[] nums = new int[n]; 9 | System.out.println("Enter the elements of the Rotated Array: "); 10 | for(int i=0; i m ) { 33 | if( target > sEle ) { 34 | if( m > sEle ) 35 | start = mid + 1; 36 | else 37 | end = mid - 1; 38 | } 39 | else 40 | start = mid + 1; 41 | } 42 | else if( target < m ) { 43 | if( target > sEle ) 44 | end = mid - 1; 45 | else { 46 | if( m > sEle) 47 | start = mid + 1; 48 | else 49 | end = mid - 1; 50 | } 51 | } 52 | else { 53 | System.out.println("Element found at index: "+mid); 54 | return ; 55 | } 56 | } 57 | System.out.println("Element not found!"); 58 | } 59 | } -------------------------------------------------------------------------------- /Selection Sort/README.md: -------------------------------------------------------------------------------- 1 | The __selection sort__ algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.
2 | The algorithm maintains two subarrays in a given array.
3 | - The subarray which already sorted. 4 | - The remaining subarray was unsorted. 5 | 6 | In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 7 | -------------------------------------------------------------------------------- /Selection Sort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | class SelectionSort 2 | { 3 | void sort(int arr[]) 4 | { 5 | int n = arr.length; 6 | 7 | for (int i = 0; i < n-1; i++) 8 | { 9 | int min_idx = i; 10 | for (int j = i+1; j < n; j++) 11 | if (arr[j] < arr[min_idx]) 12 | min_idx = j; 13 | 14 | int temp = arr[min_idx]; 15 | arr[min_idx] = arr[i]; 16 | arr[i] = temp; 17 | } 18 | } 19 | void printArray(int arr[]) 20 | { 21 | int n = arr.length; 22 | for (int i=0; inumber) 25 | end = mid-1; 26 | else if(mid*midtarget) 43 | end = mid - precision; 44 | else if(mid*mid > adj; 14 | 15 | // Constructor 16 | Graph(int v) 17 | { 18 | V = v; 19 | adj = new ArrayList >(v); 20 | for (int i = 0; i < v; ++i) 21 | adj.add(new ArrayList()); 22 | } 23 | 24 | // Function to add an edge into the graph 25 | void addEdge(int v, int w) { adj.get(v).add(w); } 26 | 27 | // A recursive function used by topologicalSort 28 | void topologicalSortUtil(int v, boolean visited[], 29 | Stack stack) 30 | { 31 | // Mark the current node as visited. 32 | visited[v] = true; 33 | Integer i; 34 | 35 | // Recur for all the vertices adjacent 36 | // to thisvertex 37 | Iterator it = adj.get(v).iterator(); 38 | while (it.hasNext()) { 39 | i = it.next(); 40 | if (!visited[i]) 41 | topologicalSortUtil(i, visited, stack); 42 | } 43 | 44 | // Push current vertex to stack 45 | // which stores result 46 | stack.push(new Integer(v)); 47 | } 48 | 49 | // The function to do Topological Sort. 50 | // It uses recursive topologicalSortUtil() 51 | void topologicalSort() 52 | { 53 | Stack stack = new Stack(); 54 | 55 | // Mark all the vertices as not visited 56 | boolean visited[] = new boolean[V]; 57 | for (int i = 0; i < V; i++) 58 | visited[i] = false; 59 | 60 | // Call the recursive helper 61 | // function to store 62 | // Topological Sort starting 63 | // from all vertices one by one 64 | for (int i = 0; i < V; i++) 65 | if (visited[i] == false) 66 | topologicalSortUtil(i, visited, stack); 67 | 68 | // Print contents of stack 69 | while (stack.empty() == false) 70 | System.out.print(stack.pop() + " "); 71 | } 72 | 73 | // Driver code 74 | public static void main(String args[]) 75 | { 76 | // Create a graph given in the above diagram 77 | Graph g = new Graph(6); 78 | g.addEdge(5, 2); 79 | g.addEdge(5, 0); 80 | g.addEdge(4, 0); 81 | g.addEdge(4, 1); 82 | g.addEdge(2, 3); 83 | g.addEdge(3, 1); 84 | 85 | System.out.println("Following is a Topological " 86 | + "sort of the given graph"); 87 | // Function Call 88 | g.topologicalSort(); 89 | } 90 | } 91 | // This code is contributed by Aakash Hasija 92 | -------------------------------------------------------------------------------- /Two Sum IV - Input is a BST/sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector vc; 15 | void inorder(TreeNode* root) 16 | { 17 | if(root==nullptr) 18 | return; 19 | inorder(root->left); 20 | vc.push_back(root->val); 21 | inorder(root->right); 22 | } 23 | bool findTarget(TreeNode* root, int k) { 24 | inorder(root); 25 | int l=0,h=vc.size()-1; 26 | while(lk) 31 | h--; 32 | else 33 | l++; 34 | } 35 | return false; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Two Sum/README.md: -------------------------------------------------------------------------------- 1 |

1. Two Sum

Easy


Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

2 | 3 |

You may assume that each input would have exactly one solution, and you may not use the same element twice.

4 | 5 |

You can return the answer in any order.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: nums = [2,7,11,15], target = 9
11 | Output: [0,1]
12 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: nums = [3,2,4], target = 6
18 | Output: [1,2]
19 | 
20 | 21 |

Example 3:

22 | 23 |
Input: nums = [3,3], target = 6
24 | Output: [0,1]
25 | 
26 | 27 |

 

28 |

Constraints:

29 | 30 |
    31 |
  • 2 <= nums.length <= 104
  • 32 |
  • -109 <= nums[i] <= 109
  • 33 |
  • -109 <= target <= 109
  • 34 |
  • Only one valid answer exists.
  • 35 |
36 | 37 |

 

38 | Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?
-------------------------------------------------------------------------------- /Two Sum/Two_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | 5 | // unordered_map (key: value , mapped: index) 6 | unordered_map map; 7 | 8 | // a vector to store indices as the answer 9 | vector ans; 10 | 11 | // getting size of he input 12 | int n = nums.size(); 13 | 14 | // iterating over the input 15 | for(int i=0; i target - a = b; 18 | // thus if b is found then push their indices to ans vector 19 | if(map.find(target - nums[i]) != map.end()){ 20 | 21 | ans.push_back(i); 22 | ans.push_back(map[target - nums[i]]); 23 | } 24 | // else give the index of the value in the map. 25 | else { 26 | map[nums[i]] = i; 27 | } 28 | } 29 | // returning the ans vector 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abirbhattacharya82/DSA/52a6c0c3084d04fa2a3f3ea32203242ae1c9f1c9/banner.png -------------------------------------------------------------------------------- /implementation of stack/Arraystack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define N 10 4 | int stack[N]; 5 | int top = -1; 6 | 7 | void push() 8 | { 9 | int x; 10 | printf("Enter data: "); 11 | scanf("%d",&x); 12 | if(top == N-1) 13 | { 14 | printf("underflow"); 15 | } 16 | else 17 | { 18 | top++; 19 | stack[top]=x; 20 | } 21 | } 22 | 23 | void pop() 24 | { 25 | int item; 26 | if(top == -1) 27 | { 28 | printf("underflow"); 29 | } 30 | else 31 | { 32 | item=stack[top]; 33 | top--; 34 | printf("popped item %d",item); 35 | } 36 | } 37 | 38 | void peek() 39 | { 40 | if(top==-1) 41 | { 42 | printf("underflow"); 43 | } 44 | else 45 | { 46 | printf("%d",stack[top]); 47 | } 48 | } 49 | 50 | void display() 51 | { 52 | int i; 53 | for(i=top;i>=0;i--) 54 | { 55 | printf("%d\n",stack[i]); 56 | } 57 | } 58 | 59 | int main() 60 | { 61 | int ch; 62 | do 63 | { 64 | printf("Enter Choice:1.Push 2.Pop 3.peek 4.display :"); 65 | scanf("%d",&ch); 66 | switch (ch) 67 | { 68 | case 1:push(); 69 | break; 70 | case 2:pop(); 71 | break; 72 | case 3:peek(); 73 | break; 74 | case 4:display(); 75 | break; 76 | default:printf("invalid choice"); 77 | break; 78 | } 79 | } 80 | while (ch!=0); 81 | return 0; 82 | } -------------------------------------------------------------------------------- /implementation of stack/LinkedListStack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *link; 8 | }; 9 | struct node *top=0; 10 | 11 | void push() 12 | { 13 | int x; 14 | printf("Enter data: "); 15 | scanf("%d",&x); 16 | struct node *newnode=malloc(sizeof(struct node)); 17 | newnode->data=x; 18 | newnode->link=top; 19 | top=newnode; 20 | } 21 | 22 | void display() 23 | { 24 | 25 | struct node *temp; 26 | temp=top; 27 | if(top==0) 28 | { 29 | printf("Stack is empty: "); 30 | } 31 | else 32 | { 33 | while(temp!=0) 34 | { 35 | printf("%d",temp->data); 36 | temp=temp->link; 37 | } 38 | } 39 | } 40 | 41 | void peek() 42 | { 43 | if(top==0) 44 | { 45 | printf("Stack is Empty"); 46 | } 47 | else 48 | { 49 | printf("top elements is %d",top->data); 50 | } 51 | } 52 | 53 | void pop() 54 | { 55 | struct node *temp; 56 | temp=top; 57 | if(top==0) 58 | { 59 | printf("Stack is Empty"); 60 | } 61 | else 62 | { 63 | printf("%d",top->data); 64 | top=top->link; 65 | free(temp); 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | int ch; 72 | do 73 | { 74 | printf("Enter Choice:1.Push 2.Pop 3.peek 4.display :"); 75 | scanf("%d",&ch); 76 | switch (ch) 77 | { 78 | case 1:push(); 79 | break; 80 | case 2:pop(); 81 | break; 82 | case 3:peek(); 83 | break; 84 | case 4:display(); 85 | break; 86 | default:printf("invalid choice"); 87 | break; 88 | } 89 | } 90 | while (ch!=0); 91 | return 0; 92 | 93 | } 94 | 95 | -------------------------------------------------------------------------------- /implementation of stack/stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self,s): 3 | self.data = [] 4 | self.size=s 5 | self.top = -1 6 | def push(self, element): 7 | self.data.append(element) 8 | self.top = self.top + 1 9 | def pop(self): 10 | popped_element = None 11 | if(self.top>-1): 12 | popped_element = self.data.pop() 13 | self.top = self.top - 1 14 | return popped_element 15 | def peek(self): 16 | return self.data[self.top] 17 | def isEmpty(self): 18 | if len(self.data) == 0: 19 | return 1 20 | return 0 21 | def isFull(self): 22 | if len(self.data) == self.size : 23 | return 1 24 | else: 25 | return 0 26 | 27 | if __name__ == "__main__": 28 | 29 | test_cases=int(input()) # number of test cases 30 | size=int(input()) # size of Stack 31 | stack=Stack(size) # creating new stack object 32 | 33 | while(test_cases>0): 34 | instruction=input().split() 35 | val=0 36 | if len(instruction)>1: 37 | val=int(instruction[1]) 38 | 39 | instruction=int(instruction[0]) 40 | ##### 41 | # Instruction 1 means Push 42 | # Instruction 2 means Pop 43 | # Instruction 3 means Peek 44 | # Instruction 4 means isEmpty 45 | # Instruction 5 means isFull 46 | ##### 47 | 48 | if(instruction==1): 49 | print(f'push:{val}') 50 | stack.push(val) 51 | 52 | elif (instruction==2): 53 | print(f'pop:{stack.pop()}') 54 | 55 | elif (instruction==3): 56 | print(f'peek:{stack.peek()}') 57 | 58 | elif(instruction==4): 59 | print(f'isEmpty:{stack.isEmpty()}') 60 | 61 | elif(instruction==5): 62 | print(f'isFull:{stack.isFull()}') 63 | 64 | test_cases=test_cases-1 65 | -------------------------------------------------------------------------------- /prime number checker/Prime number checker.py: -------------------------------------------------------------------------------- 1 | def prime_checker(n): 2 | prime = True 3 | for i in range (2, n): 4 | if n % i == 0: 5 | prime = False 6 | if prime: 7 | print("Prime number") 8 | else: 9 | print("Not a Prime number") 10 | 11 | number = int(input("Check this number: ")) 12 | prime_checker(n = number) --------------------------------------------------------------------------------