├── .gitignore ├── Arrays └── Arrays.md ├── Backtracking └── Sudoku_Solver.md ├── CONTRIBUTING.md ├── Graph ├── 01_Introduction.md ├── 02_Graph Representation.md ├── 03_Connected component.md ├── 04_BFS Traversal.md ├── 05_DFS Traversal.md └── 06_Detect_Cycle.md ├── LICENSE ├── Linked List ├── 01_Linked_List.md ├── 02_Insert_in_Singly_Linked_List.md └── Linked List.md ├── Pattern ├── Pattern1.md ├── Pattern2.md ├── Pattern3.md ├── Pattern4.md ├── Pattern5.md ├── Pattern6.md └── Pattern7.md ├── Queues └── Queues.md ├── Readme.md ├── Recursion ├── 01_Introduction.md └── 02_Parameterised_Functional_Recursion.md ├── STL ├── Deque │ ├── Initialise.md │ ├── at() - Print_Elements.md │ ├── back() - Last_Element.md │ ├── empty() - Empty Check.md │ ├── front() - First_Element.md │ ├── pop_back() - Remove Element.md │ ├── pop_front() - Remove Element.md │ ├── push_back() - Add Element.md │ ├── push_front() - Add Element.md │ ├── size() - Deque Size.md │ └── swap() - Swap 2 Deque.md ├── Queue │ ├── 1-Initialise.md │ ├── back() - Last_Element.md │ ├── empty() - Queue_Empty_Check.md │ ├── front() - First_Element.md │ ├── pop() - Remove_Element.md │ ├── push() - Insert_Element.md │ ├── size() - Queue_Size.md │ └── swap() - Swap_2_Queue.md ├── STL.md ├── Stack │ ├── 1-Initialise.md │ ├── empty() - Stack_Empty_Check.md │ ├── pop() - Remove_Element.md │ ├── push() - Insert_Element.md │ ├── size() - Stack_Size.md │ ├── swap() - Swap_2_Stacks.md │ └── top() - Print_Top_Element.md └── Vectors │ ├── Initialise.md │ ├── Print.md │ ├── pop_back() - Remove Element.md │ ├── push_back() - Add Element.md │ └── size() - Size of Vector.md ├── Searching ├── Binary_Search.md ├── Binary_Search_Recursion.md ├── Linear_Search.md ├── Searching.md └── Searching_Peak_elementArray.md ├── Sorting ├── Bubble_Sort.md ├── Heap_Sort.md ├── Insertion_Sort.md ├── Merge_Sort.md ├── Quick_Sort.md ├── RandomizedQuick_Sort.md ├── Selection_Sort.md └── Sorting.md └── Tree ├── BFS_Traversal.md ├── Binary_Trees.md ├── Inorder_Traversal.md ├── Postorder_Traversal.md └── Preorder_Traversal.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore the outer .md files that are not in any folder 2 | .md 3 | 4 | #Ignore .exe files, .cpp files in whole repository 5 | *.exe 6 | *.cpp 7 | *.c 8 | 9 | # Ignore vscode settings (If any) and Temp folder 10 | .vscode 11 | temp -------------------------------------------------------------------------------- /Arrays/Arrays.md: -------------------------------------------------------------------------------- 1 | ## Arrays -------------------------------------------------------------------------------- /Backtracking/Sudoku_Solver.md: -------------------------------------------------------------------------------- 1 | ## Problem Statement 2 | 3 | Write a program to solve a Sudoku puzzle by filling the empty cells. 4 | 5 | A sudoku solution must satisfy all of the following rules: 6 | 7 | Each of the digits 1-9 must occur exactly once in each row. 8 | Each of the digits 1-9 must occur exactly once in each column. 9 | Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. 10 | The '.' character indicates empty cells. 11 | 12 | 13 | 14 | #### Example 1: 15 | 16 | ##### Input: board = 17 | 18 | [["5","3",".",".","7",".",".",".","."], 19 | 20 | ["6",".",".","1","9","5",".",".","."], 21 | 22 | [".","9","8",".",".",".",".","6","."], 23 | 24 | ["8",".",".",".","6",".",".",".","3"], 25 | 26 | ["4",".",".","8",".","3",".",".","1"], 27 | 28 | ["7",".",".",".","2",".",".",".","6"], 29 | 30 | [".","6",".",".",".",".","2","8","."], 31 | 32 | [".",".",".","4","1","9",".",".","5"], 33 | 34 | [".",".",".",".","8",".",".","7","9"]] 35 | 36 | 37 | ##### Output: 38 | 39 | [["5","3","4","6","7","8","9","1","2"], 40 | 41 | ["6","7","2","1","9","5","3","4","8"], 42 | 43 | ["1","9","8","3","4","2","5","6","7"], 44 | 45 | ["8","5","9","7","6","1","4","2","3"], 46 | 47 | ["4","2","6","8","5","3","7","9","1"], 48 | 49 | ["7","1","3","9","2","4","8","5","6"], 50 | 51 | ["9","6","1","5","3","7","2","8","4"], 52 | 53 | ["2","8","7","4","1","9","6","3","5"], 54 | 55 | ["3","4","5","2","8","6","1","7","9"]] 56 | 57 | 58 | 59 | ## Intuition:- 60 | 61 | - check if row == n,then we have completely filled our grid so return true 62 | - if current column == n-1,then we have to move to the next row by incrementing current row by 1 and making current column as 0. 63 | - else we have to move to the next right cell by keeping the row same and incrementing current column by 1. 64 | 65 | - If the current cell is already filled then we will simpliy move to the next cell. 66 | - Otherwise, we'll explore all the 9 possibilities. 67 | - Now for the current value we have to first check if it is valid or not ,for that we have to check if there isn't any same value present in the current row and in the current column and in the current sub grid. 68 | - if its not present in the current row ,current column and current sub grid then it is a valid value for the current cell,so return true. 69 | - if the above conditions doesn't holds then return false and explore the other possibilities. 70 | - Once we have found that its a valid value then update the current cell's value to the current value. 71 | - Even after exploring all the 9 possibilities,if we haven't got a value to fill a cell ,then return false and undo the changes and explore other possibilities. 72 | 73 | 74 | #### 1. Time Complexity = O(9^n* n) or O(exponential) ,since we are having 9 possibilities for each cell. 75 | #### 2. Space Complexity = can't say exactly but somewhat equals to O(n^2). 76 | 77 | 78 | 79 | 80 | 81 | 82 | ```cpp 83 | 84 | 85 | class Solution { 86 | public: 87 | 88 | //function to check if the current value is present or not in the ROW 89 | bool isRowValid(vector>&board,int currVal,int currRow,int n) 90 | { 91 | //iterating over the current row 92 | //to check if current value is present or not 93 | //if it isn't present then its a valid value for the current row 94 | //therefore return true 95 | //else return false 96 | for(int col = 0;col>&board,int currVal,int currCol,int n) 107 | { 108 | //iterating over the current col to check if current val is present or not 109 | //if it isn't present then it means its a valid value for the current col 110 | //and hence return true 111 | //else return false; 112 | for(int row = 0; row>&board,int currVal,int currRow,int currCol,int n) 123 | { 124 | //finding the starting cordinates of the current subgrid 125 | int startRow = 3*(currRow/3); 126 | int startCol = 3*(currCol/3); 127 | 128 | //iterating over the current sub grid 129 | //to check if current vaule is present or not 130 | //if it isn't present we'll return true 131 | //else false 132 | for(int row = startRow; row<=startRow+2;row++) 133 | { 134 | for(int col = startCol; col<=startCol+2;col++) 135 | { 136 | if(board[row][col] == char(currVal+'0')) 137 | return false; 138 | } 139 | } 140 | return true; 141 | } 142 | 143 | 144 | //function to check if the current value is valid or not 145 | bool isValid(vector>&board,int currVal,int currRow,int currCol,int n) 146 | { 147 | //if the current row is valid i.e. the current value isn't present in the current row 148 | //if the current col is vaild i.e. the current value isn't present in the current column 149 | //and if it isn't present in the current sub grid 150 | //then it means we can fill the current value in the current cell 151 | //so return true 152 | if(isRowValid(board,currVal,currRow,n) && isColValid(board,currVal,currCol,n) && 153 | isSubGridValid(board,currVal,currRow,currCol,n)) 154 | return true; 155 | 156 | //return false otherwise 157 | else 158 | return false; 159 | } 160 | 161 | 162 | //function to solve the sudoko 163 | bool sudokoSolver(vector>& board,int currRow,int currCol,int n) 164 | { 165 | //if we have reached n 166 | //i.e. we have filled the board completely 167 | //return true 168 | if(currRow == n) 169 | return true; 170 | 171 | int nextRow = -1; 172 | int nextCol = -1; 173 | 174 | 175 | //if we have not yet reached the end of the current row 176 | //then we can still move one step right by keeping the row same & incrementing the col 177 | if(currCol != n-1) 178 | { 179 | nextRow = currRow; 180 | nextCol = currCol + 1; 181 | } 182 | 183 | 184 | //if we have reached the end of the current row .i.e. currCol == n-1 185 | //then we have to go to the next row and the 0-th column 186 | else 187 | { 188 | nextRow = currRow+1; 189 | nextCol = 0; 190 | } 191 | 192 | //if board[currRow][currCol] != "." ,i.e. the current cell isn't empty 193 | //if current cell is already filled then we just have to move to the next cell 194 | if(board[currRow][currCol] != '.') 195 | return sudokoSolver(board,nextRow,nextCol,n); 196 | 197 | //if the current cell isn't filled 198 | //we'll explore all the 9 possibilities 199 | for(int currVal = 1;currVal<=9;currVal++) 200 | { 201 | //check if the current Value is valid 202 | //i.e. whether we can fill the current cell with the current value or not 203 | if(isValid(board,currVal,currRow,currCol,n)) 204 | { 205 | //if the current value is valid 206 | //then update current cell's value with current value 207 | //and move to the next cell 208 | board[currRow][currCol] = char(currVal+'0'); 209 | //if the current configuration leads to the complete filling of the sudoko 210 | //then return true 211 | if(sudokoSolver(board,nextRow,nextCol,n)) 212 | return true; 213 | 214 | //if the current configuration doesn't leads to the complete filling of the sudoko 215 | //then undo the change 216 | board[currRow][currCol] = '.'; //line 58 217 | } 218 | } 219 | //if we haven't got any valid value to fill the current cell after traversing the entire for loop 220 | //that means the previous changes we did wasn't valid ,so return false 221 | //after this return statement controls goes to line 58 222 | return false; 223 | } 224 | 225 | 226 | //control starts from here 227 | void solveSudoku(vector>& board) 228 | { 229 | sudokoSolver(board,0,0,board.size()); 230 | } 231 | }; 232 | 233 | 234 | 235 | ``` 236 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Hey coders and learners, 4 | We are very much pleased to have you onboard with our journey. 5 | 6 | ### Read this entire file to know how to start contributing in our repository. 7 | 8 | Steps to contribute your code in any of the mentioned dsa folder: 9 | 1. [Star](https://help.github.com/en/articles/about-stars) :star: the repository. 10 | 2. [Fork](https://help.github.com/en/articles/fork-a-repo) the repository into your github account. 11 | 3. Clone the repository into your local system by using git clone command OR edit it online on github website. 12 | 4. Make a new Branch with the command `git checkout -b new_branch_name` and make changes in that branch only. 13 | 5. Write necessary code in your preferred folder, Add that topic in the parent folder's **.md** file (Example : If I've done code of Linear Search in Searching Folder, Add Linear Search under Searching Algorithm section in `Searching.md` file). 14 | 6. Always use [Coding Style](https://github.com/aaryahjolia/dsa_competitive-coding/blob/main/Contribution_Guidelines.md#coding-style) when writing a code. 15 | 7. Commit the code with a meaningful description. 16 | 8. [Push](https://help.github.com/en/articles/pushing-to-a-remote) the code to your cloned repository on your github account. 17 | 9. Submit a [Pull Request](https://help.github.com/en/articles/about-pull-requests) with your updated repository into our repository. 18 | 10. That's all! You've done your Open Source Contribution. Just wait for us to merge your code into main repository. 19 | 20 | 21 | We are thankful to all the people showing interest in our repository. 22 | 23 | --- 24 | 25 | # Coding style 26 | 27 | Follow this coding Scheme throughout your contribution: 28 | 29 | 1. File naming: 30 | If you are demonstrating `linear search` in `searching`, name your file **`Linear_Search.md`** and save it in the `Searching` directory. 31 | Remember to name your file in Pascal Case (First letter capital) with `_` in between. Ex: `Merge_Sort.md`. 32 | 33 | 2. In every **.md** file, You need to have a Description, the code, and the time complexities. 34 | 35 | 3. Add Opening braces for loops, conditional statements,etc. on the same line. 36 | ```cpp 37 | int main() 38 | { 39 | // ❌ 40 | } 41 | 42 | int main(){ 43 | // ✔️. 44 | } 45 | ``` 46 | 47 | 4. Indentation : 48 | Use only one indenting format for the whole program. 49 | Use **1 Tab** or **4 Spaces**. 50 | 51 | 5. Add appropriate comments wherever necessary to explain the code. 52 | > Programs wth NO Comments at all will not be merged. 53 | 54 | 6. Expression should be readable, Use 1 space between different tokens. 55 | ```cpp 56 | a=a+b // ❌ 57 | a = a + b // ✔️. 58 | ``` 59 | 60 | 7. Always add braces in a for/while loop, even if it's a one-liner loop. 61 | ```cpp 62 | for (int i = 0; i < 10 ; i++) 63 | cout << i << " "; // ❌ 64 | 65 | for (int i = 0; i < 10; i++){ 66 | cout << i << " "; // ✔️. 67 | } 68 | ``` 69 | 70 | 8. You **MUST** use `using namespace std;` at beginning so that you don't have to write `std::` every time (Moreover some coders also don't know how to use `std::`, so it will be easy to understand). 71 | 72 | 9. **MUST** use `#include ` as competitive coders use that only (If you were unaware about it, This header file load all other header files so you don't have to include them seperately). 73 | 74 | 10. Don't include `.exe` files or any other files than `.cpp` (It's totally OK if you are going to contribute through Git as [.gitignore](.gitignore) file will ignore .exe files when pushing the code). 75 | -------------------------------------------------------------------------------- /Graph/01_Introduction.md: -------------------------------------------------------------------------------- 1 | # **Graphs** 2 | 3 | ## Some Common Terms 4 | 1. **Node/Vertex**: A node (or vertex) of a graph is one of the objects that are connected together. 5 | 2. **Edges**: It is one of the connections between the nodes (or vertices) of the network. 6 | 3. **Edge Weight**: Weight assigned to the edge is called edge weight. (Assume 1 if no edge weight is given). 7 | 4. **Path**: A sequence of node of vertex connected with each other such that none of the node is repeated or visited twice in the graph. 8 | 5. **Cyclic**: If the graph contains a cycle (We can come back to same node after traversing the graph is called a cyclic graph). The opposite of a cyclic graph is an acyclic graph. 9 | 6. **Weight / Cost**: If the edge is assigned a numerical value, The value is called the edge's weight or cost. 10 | 7. **Degree**: The number of edges connected with neighbouring nodes. 11 | 12 | -> **IMP**: Sum of Degrees = 2 * No. of Edges 13 | 14 | There are primarily 2 types of graph: 15 | ## 1. Undirected Graph 16 | 17 | Example: 18 | ![Undirected](https://user-images.githubusercontent.com/82600388/193063117-753b42ab-0695-44db-9f3e-d569b049b87f.png) 19 | 20 | 21 | Here, We can say that there is an edge between 2 and 3 & between 3 and 2 as undirected graph can be traversed through both the sides. 22 | 23 | **Degree**: The number of edges connected with the node or vertex. 24 | Ex: Degree(2) = 2 25 | Degree(1) = 2 26 | 27 | **Relation between Degree and Edges** 28 | Total Degrees = 2 * Edges 29 | 30 | **Path**: 1 2 3 4 (One possibility) 31 | 32 | **Cyclic property**: It is an undirected cyclic graph (1->2->3->1 is a cycle) 33 | 34 | ## 2. Directed Graph 35 | 36 | Example: 37 | ![Directed](https://user-images.githubusercontent.com/82600388/193063186-c7141c2b-e2e4-45b3-94a6-9bb542d53ad9.png) 38 | 39 | Here, We can say that there is an edge between 1 and 2 but there is not edge between 2 and 1 as directed graph only traverse in the direction of edge. 40 | 41 | **Indegree**: The number of edges incoming to that node or vertex. 42 | Ex: Indegree(2) = 2 43 | **Outdegree**: The number of edges outgoing to that node or vertex. 44 | Ex: Outdegree(2) = 0 45 | 46 | **Path**: 1 3 4 (One possibility) 47 | 48 | **Cyclic**: It's a directed cyclic graph (3->4->3 is a cycle). -------------------------------------------------------------------------------- /Graph/02_Graph Representation.md: -------------------------------------------------------------------------------- 1 | # Graph Representation in C++ 2 | 3 | ### Input: n, m, m lines representing edges 4 | 5 | n: No. of vertices 6 | m: No. of edges 7 | The next m lines will have 2 vertex inputs. 8 | 9 | ### Input Example: 10 | 11 | ``` 12 | 5 4 13 | 14 | 1 2 15 | 1 3 16 | 1 4 17 | 1 5 18 | 19 | Here, it means the graph has 5 vertices, 4 edge and First vertex is connected with every other vertex. 20 | ``` 21 | 22 | ## There are 2 ways to store the graph inputs. 23 | 24 | ## 1. Adjacency matrix 25 | 26 | -> Here, We'll create a (n+1)\*(n+1) matrix and we will mark 1 if there is an edge between both the index of that matrix, else 0. 27 | -> For Directed/Weighted graph, Add weight instead of 1 in the matrix. 28 | 29 | Code: 30 | 31 | ```cpp 32 | int n,m; 33 | cin>>n>>m; 34 | int adj[n+1][n+1]; 35 | for(int i=0;i>u>>v; 38 | adj[u][v]=1; 39 | adj[v][u]=1; 40 | } 41 | ``` 42 | 43 | ### Time Complexity: O(M) 44 | ### Space Complexity: O(N^2) 45 | 46 | ## 2. Adjacency List 47 | 48 | We have 3 possibilities in this, Directed, Undirected and Weighted Graph. 49 | 50 | ## A. Undirected Graph 51 | 52 | -> Here, We'll create a vector list of n+1 nodes and we'll add the nodes connected with that node in that node's individual list. 53 | -> Compared to adjacency matrix, We can easily say neighbours of a particular node in this method. 54 | 55 | Code: 56 | 57 | ```cpp 58 | int n,m; 59 | cin>>n>>m; 60 | vector adj[n+1]; 61 | for(int i=0;i>u>>v; 64 | adj[u].push_back(v); 65 | adj[v].push_back(u); 66 | } 67 | ``` 68 | 69 | Time Complexity: O(M) 70 | Space Complexity: O(2*Edges) (As we are storing edges twice) 71 | 72 | ## B. Directed Graph (edge u->v) 73 | 74 | -> We will store only one edge as it's directed graph. 75 | 76 | Code: 77 | ```cpp 78 | for(int i=0;i v 81 | cin>>u>>v; 82 | adj[u].push_back(v); 83 | } 84 | ``` 85 | 86 | Space Complexity: O(Edges) (As we are storing edges only once) 87 | 88 | ## C. Weighted Graph 89 | 90 | -> We will also add weight when storing the sibling node. 91 | -> We will use ```pair``` insted of only ```int``` in vector to store weight and sibling node in the pair of vector. 92 | 93 | Code (Weight with undirected graph): 94 | ```cpp 95 | for(int i=0;i>u>>v>>weight; 98 | adj[u].push_back({v, weight}); 99 | adj[v].push_back({u, weight}); 100 | } 101 | ``` 102 | 103 | ## In General, Space complexity is better in Adjacency list method. 104 | -------------------------------------------------------------------------------- /Graph/03_Connected component.md: -------------------------------------------------------------------------------- 1 | # Connected Components in Graph 2 | 3 | The graph can have different components which may not be connected as shown in image below, But they need to be counted when we are traversing a graph. 4 | 5 | ![Connected Components in Graph](https://media.geeksforgeeks.org/wp-content/uploads/20200421194558/Count-of-Connected-Components.png) 6 | 7 | 8 | To count such nodes when traversing, Create another visited array of nodes and from that array, Call traversing algorithms like DFS or BFS. 9 | 10 | Representation: 11 | ```cpp 12 | vector vis(n+1, 0); 13 | for(int i=0;i Also called Level wise traversal. 4 | -> The starting node will be specified in the question, take 0 otherwise (Graph can be 0-indexed or 1-indexed, Remember to code wisely). 5 | -> The nodes which are equidistant from parent node are said to be in level-1 and likewise. 6 | -> First print elements in level-0, then level-1 and so on. 7 | 8 | Code: (For Undirected Graph) 9 | ```cpp 10 | // Assuming inputs are taken in adjacency list 11 | vector adj[n+1]; 12 | 13 | queue q; 14 | vector vis(n+1,0); 15 | vector bfs; 16 | int sn=0; // Starting node 17 | 18 | q.push(sn); 19 | vis[sn]=1; 20 | 21 | while(!q.empty()){ 22 | int node = q.front(); 23 | q.pop(); 24 | bfs.push_back(node); 25 | for(auto it : adj[node]){ 26 | if(!vis[it]){ 27 | q.push(it); 28 | vis[it]=1; 29 | } 30 | } 31 | } 32 | 33 | return bfs; 34 | ``` 35 | 36 | ### Complexities: 37 | 38 | Time Complexity: O(V + 2E). (While loop will run for V vertex, for loop will run for degrees of that vertex and degree=2×edges). 39 | Space Complexity: O(3*N) ~ O(N). (2 Vector and 1 queue) -------------------------------------------------------------------------------- /Graph/05_DFS Traversal.md: -------------------------------------------------------------------------------- 1 | # DFS (Depth first search) traversal technique 2 | 3 | -> Uses Recursion for Depth traversal. 4 | 5 | Code: 6 | ```cpp 7 | void dfst(int node, vectoradj[], vector &visited, vector &dfs){ 8 | visited[node]=1; 9 | dfs.push_back(node); 10 | for(auto it : adj[node]){ 11 | if(!visited[it]){ 12 | dfst(it, adj, visited, dfs); 13 | } 14 | } 15 | } 16 | 17 | vector dfsOfGraph(int V, vector adj[]){ 18 | vector visited (V,0); 19 | vector dfs; 20 | int sn = 0; // starting node 21 | 22 | dfst(sn, adj, v, dfs); 23 | return dfs; 24 | } 25 | 26 | ``` 27 | 28 | ### Complexities: 29 | 30 | Time Complexity: O(N)+O(2E) (Recursion function call for O(N) and the for loop will run for all degrees and summation of degrees is 2×Edges) 31 | Space Complexity: O(3*N) ~ O(N). (2 Vector and recursion stack will have O(N) as worst case in case of linear graph like 1->2->3->4->...) -------------------------------------------------------------------------------- /Graph/06_Detect_Cycle.md: -------------------------------------------------------------------------------- 1 | # Detect Cycle in a Graph (BFS & DFS methods) 2 | 3 | Check for cycle in a graph and return ```true``` if the graph contains cycle. A cycle is formed when we start our journey from a particular node and return back to the same node after traversing atleast 1 node in between. 4 | 5 | ## 1. Using BFS -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Aarya Ahjolia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Linked List/01_Linked_List.md: -------------------------------------------------------------------------------- 1 | ## Singly Linked List 2 | 3 | Linked List is a linear Data structure. 4 | It'structure is like as follows: 5 | 6 | ![Linked List Image](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/12/screen-shot-2018-04-12-at-152754.png) 7 | 8 | Linked List is made up of nodes wher each node contains a data field and a reference field (pointer), this is true for singly linked list. 9 | There are 2 reference field and 1 data field in doubly linked list. 10 | 11 | Node Structure: 12 | ```cpp 13 | struct SinglyListNode { 14 | int val; 15 | SinglyListNode *next; 16 | SinglyListNode(int x){ 17 | val = x; 18 | next = NULL; 19 | } 20 | }; 21 | ``` 22 | 23 | The first node or the starting node is generally referred to as head. 24 | 25 | ### Operations 26 | We can't access random elements like an array, so if I have to access the last element of linekd list, I'll have to traverse till the last of linked list and the effective TC becomes ```O(N)``` where N is the size of linked list. -------------------------------------------------------------------------------- /Linked List/02_Insert_in_Singly_Linked_List.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aaryahjolia/dsa_competitive-coding/9d4c47b20dbc402f578374ed5e50ff072d84d486/Linked List/02_Insert_in_Singly_Linked_List.md -------------------------------------------------------------------------------- /Linked List/Linked List.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aaryahjolia/dsa_competitive-coding/9d4c47b20dbc402f578374ed5e50ff072d84d486/Linked List/Linked List.md -------------------------------------------------------------------------------- /Pattern/Pattern1.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make * pattern by using while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int row, n; 12 | cout << "Enter the number: "; 13 | cin >> n; 14 | row=1; 15 | 16 | // This loop descire the row which will go till the value of n 17 | while(row<=n){ 18 | int col=1; 19 | 20 | // This loop run firstly for col till col<=n then again till row<=n 21 | while(col<=row){ 22 | 23 | // Print * for col<=n in each row loop 24 | cout << "* "; 25 | col++; 26 | } 27 | cout << endl; 28 | row++; 29 | } 30 | return 0; 31 | } 32 | ``` 33 | 34 | ## Output 35 | ``` 36 | * 37 | * * 38 | * * * 39 | ``` 40 | 41 | ## GFG URL CODE 42 | https://ide.geeksforgeeks.org/21afee75-c704-4fe7-a2dc-92c5f20eaa98 -------------------------------------------------------------------------------- /Pattern/Pattern2.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make square Alphabet pattern by using while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int row, n; 12 | cout << "Enter the number: "; 13 | cin >> n; 14 | row = 1; 15 | 16 | // Declared ch = A for starting 17 | char ch = 'A'; 18 | while(row<=n){ 19 | int col = 1; 20 | while(col<=n){ 21 | 22 | // char(ch + (col - 1)) is the formula for printing next alphabet 23 | cout << char(ch + (col - 1)) << " "; 24 | col++; 25 | } 26 | cout << endl; 27 | ch++; 28 | row++; 29 | } 30 | return 0; 31 | } 32 | ``` 33 | 34 | ## Output 35 | ``` 36 | A B C 37 | B C D 38 | C D E 39 | ``` 40 | 41 | ## GFG IDE CODE 42 | https://ide.geeksforgeeks.org/7518d39c-1fa6-4c6b-a71e-bf94e16bd94f -------------------------------------------------------------------------------- /Pattern/Pattern3.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make triangle Alphabet pattern by using while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int row, n; 12 | cout << "Enter the number: "; 13 | cin >> n; 14 | row = 1; 15 | char ch = 'A'; 16 | while(row<=n){ 17 | int col = 1; 18 | while(col <= row){ 19 | // Formula for getting next alphabet in each iterate 20 | cout << char(ch + (col - 1)) << " "; 21 | col++; 22 | } 23 | cout << endl; 24 | ch++; 25 | row++; 26 | } 27 | return 0; 28 | } 29 | ``` 30 | 31 | ## Output 32 | ``` 33 | A 34 | B C 35 | C D E 36 | D E F G 37 | ``` 38 | 39 | ## GFG IDE CODE 40 | https://ide.geeksforgeeks.org/46017047-3878-4098-8e60-e979b2b39980 -------------------------------------------------------------------------------- /Pattern/Pattern4.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make pattern of triangle using numbers or stars by while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int row, n; 12 | cout << "Enter the number: "; 13 | cin >> n; 14 | row = 1; 15 | while(row<=n){ 16 | // Print space for putting the number in middle 17 | int space = n - row; 18 | while(space){ 19 | cout << " "; 20 | space--; 21 | } 22 | 23 | // Print 1st triangle 24 | int col = 1; 25 | while(col<=row){ 26 | cout << col; 27 | // cout << "*"; // for priniting stars 28 | col++; 29 | } 30 | 31 | // Print 2nd triangle 32 | int num = row - 1; 33 | while(num){ 34 | cout << num; 35 | // cout << "*"; // for printing stars 36 | num--; 37 | } 38 | cout << endl; 39 | row++; 40 | } 41 | return 0; 42 | } 43 | ``` 44 | 45 | ## Output 46 | ``` 47 | 1 48 | 121 49 | 12321 50 | 1234321 51 | ``` 52 | 53 | ## GF IDE CODE 54 | https://ide.geeksforgeeks.org/cfaf9649-f1cf-4b8f-95b9-bd8d3459caf7 -------------------------------------------------------------------------------- /Pattern/Pattern5.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make pattern of square using numbers and stars by while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | int main(){ 11 | int row,n; 12 | cout << "Enter the number: "; 13 | cin >> n; 14 | row = 1; 15 | while(row<=n){ 16 | // triangle 1 17 | int tri_one = n - row + 1; 18 | int col = 1; 19 | while(col<=tri_one){ 20 | cout << col++; 21 | } 22 | 23 | // triangle 2 24 | int star = (row - 1) * 2; 25 | while(star){ 26 | cout << "*"; 27 | star--; 28 | } 29 | 30 | // triangle 3 31 | int tri_three = n - row + 1; 32 | while(tri_three){ 33 | cout << tri_three--; 34 | } 35 | cout << endl; 36 | row++; 37 | } 38 | return 0; 39 | } 40 | ``` 41 | 42 | ## Output 43 | ``` 44 | 1234554321 45 | 1234**4321 46 | 123****321 47 | 12******21 48 | 1********1 49 | ``` 50 | 51 | ## GFG IDE CODE 52 | https://ide.geeksforgeeks.org/a341dbe2-68f7-4d6b-9ce0-b06f61c6d20e -------------------------------------------------------------------------------- /Pattern/Pattern6.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make * pattern by using while loop 3 | 4 | ## Code 5 | ```cpp 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | class Solution { 12 | public: 13 | vector yShapedPattern(int N) { 14 | int space = N - 1; 15 | vector ans; 16 | for (int i = 1; i <= N/2; i++) 17 | { 18 | string temp; 19 | for (int j = 1; j <= i - 1; j++) 20 | { 21 | temp+=" "; 22 | } 23 | temp+="*"; 24 | for (int j = 1; j <= space; j++) 25 | { 26 | temp+=" "; 27 | } 28 | temp+="*"; 29 | for (int j = 1; j <= i - 1; j++) 30 | { 31 | temp+=" "; 32 | } 33 | space -= 2; 34 | ans.push_back(temp); 35 | } 36 | space = N/2; 37 | for (int i = 1; i <= N/2; i++) 38 | { 39 | string temp; 40 | for (int j = 1; j <= space; j++) 41 | { 42 | temp+=" "; 43 | } 44 | temp+="*"; 45 | for (int j = 1; j <= space; j++) 46 | { 47 | temp+=" "; 48 | } 49 | ans.push_back(temp); 50 | } 51 | return ans; 52 | } 53 | }; 54 | 55 | int main() 56 | { 57 | int t; 58 | cin >> t; 59 | while(t--) 60 | { 61 | int N; 62 | cin >> N; 63 | Solution ob; 64 | vector v = ob.yShapedPattern(N); 65 | for(int i = 0; i < v.size(); i++) 66 | cout << v[i] << endl; 67 | } 68 | return 0; 69 | } 70 | ``` 71 | ## Input 72 | ``` 73 | N = 8 74 | ``` 75 | ## Output 76 | ``` 77 | * * 78 | * * 79 | * * 80 | * * 81 | * 82 | * 83 | * 84 | * 85 | ``` 86 | 87 | ## GFG URL CODE 88 | [https://ide.geeksforgeeks.org/21afee75-c704-4fe7-a2dc-92c5f20eaa98](https://ide.geeksforgeeks.org/1333c2c2-783f-48ca-885b-4553f946fe45) 89 | -------------------------------------------------------------------------------- /Pattern/Pattern7.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | In this code you will find how you can make Hour-glass Pattern by using while loop 3 | 4 | ## code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | // Function definition 11 | void pattern(int rows_no){ 12 | //code for printing first invert number pyramid 13 | int row = 1; 14 | while(row<=rows_no){ 15 | //printing spaces 16 | int space = row-1; 17 | while(space){ 18 | cout << " "; 19 | space -= 1; 20 | } 21 | int col = 1; 22 | //printing rows count 23 | int count = row; 24 | while(col<=rows_no - row + 1){ 25 | cout << count << " "; 26 | col += 1; 27 | count += 1; 28 | } 29 | cout << " " << endl; 30 | row += 1; 31 | } 32 | //code for printing second number pyramid 33 | row = 2; 34 | while(row<=rows_no){ 35 | int space = rows_no-row; 36 | //printing spaces 37 | while(space){ 38 | cout << " "; 39 | space -= 1; 40 | } 41 | // printing cols count 42 | int col = 1; 43 | int count = rows_no - row + 1; 44 | while(col<=row){ 45 | cout << count << " "; 46 | col += 1; 47 | count += 1; 48 | } 49 | cout << " " << endl; 50 | row += 1; 51 | } 52 | } 53 | 54 | // Driver code 55 | int main(){ 56 | // taking rows value from the user 57 | int rows_no = 7; 58 | 59 | pattern(rows_no); 60 | return 0; 61 | } 62 | 63 | ``` 64 | 65 | ## Output 66 | ``` 67 | 1 2 3 4 5 6 7 68 | 2 3 4 5 6 7 69 | 3 4 5 6 7 70 | 4 5 6 7 71 | 5 6 7 72 | 6 7 73 | 7 74 | 6 7 75 | 5 6 7 76 | 4 5 6 7 77 | 3 4 5 6 7 78 | 2 3 4 5 6 7 79 | 1 2 3 4 5 6 7 80 | ``` 81 | 82 | ## GFG IDE CODE 83 | https://ide.geeksforgeeks.org/ -------------------------------------------------------------------------------- /Queues/Queues.md: -------------------------------------------------------------------------------- 1 | # What are queues? 2 | 3 | Queues are lists where insertion is done at the end while the deletion is done at the front end. It follows the first in first out order(FIFO). 4 | 5 | # Operations on queue 6 | 7 | 1. Enqueue- Inserts the element at the rear end of the list. 8 | 2. Dequeue- Deletes an element from the beginning of the list. 9 | 10 | # Priority Queue 11 | 12 | Priority Queue is a queue where the elements of it have an associated priority with it. 13 | Every item has a priority associated with it. 14 | An element with high priority is dequeued before an element with low priority. 15 | If two elements have the same priority, they are served according to their order in the queue. 16 | 17 | # Types of Priority Queue 18 | 19 | 1. Ascending Queue- In ascending order priority queue, the element with a lower priority value is given a higher priority in the priority list. 20 | 21 | 2. Descending Queue- The root node is the maximum element in a max heap, as you may know. It will also remove the element with the highest priority first. 22 | 23 | # Operations in a Priority Queue 24 | 25 | 1. Insertion- When the element is inserted in a Priority Queue it is checked if the element is in the correct order or not. If not, elements are swapped. 26 | 2. Deletion- Maximum element from the Max Heap is deleted. 27 | 3. Peek- Returns the maximum element from Max Heap or the minimum element from Min Heap. 28 | 29 | # Circular Queue 30 | 31 | Circular Queue is a special version of queue where the last element of the queue is connected to the first element of the queue forming a circle. 32 | 33 | # Operations on Circular Queue 34 | 35 | 1. Front- Get the front item from queue. 36 | 2. Rear- Get the last item from queue. 37 | 3. Enqueue- This function is used to insert an element into the circular queue at rear position. 38 | 4. Dequeue- This function is used to delete an element from the circular queue from fron position. 39 | 40 | Ref. Taken- GeeksForGeeks -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 |
2 |

DSA & Competitive Coding

3 | 4 | 5 | visitor count 6 | Stars Badge 7 | Forks Badge 8 | 9 | 10 | This repository contains all the Data Structures and Algorithms concepts and their implementation in several ways, programming questions from websites like codeforces, hackerrank and Interview questions. 11 | 12 | 13 | # Contribute 14 | [![Open Source Love svg1](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badges/) 15 | This is a freindly repository available for open source contributions. You can add and improve any code, your contribution is welcomed ❤️! 16 | PS : Don't forget to follow [Contribution Guidelines](CONTRIBUTING.md) 17 | 18 | # Currently Used Language 19 | C++ 20 |
21 | 22 |

Project Admin ⚡

23 |

24 | 25 |

26 | 27 | [Aarya Ahjolia](https://github.com/aaryahjolia) 28 | 29 |

30 |

31 |
32 | 36 | 37 |
38 | 39 | # Part of Open Source Programs 40 | 41 | ### [Hack Club RAIT SOC](https://soc.hackclubrait.co/) 42 | 43 | ![1632670084686](https://user-images.githubusercontent.com/80090908/179052180-5067b5fe-9c98-421e-b818-ae4bd7976ca8.jpg) 44 | 45 |
46 | 47 | ## Give it a 🌟 if you ❤ this project. 48 | 49 | ### Happy Coding 👨‍💻 50 |
51 | -------------------------------------------------------------------------------- /Recursion/01_Introduction.md: -------------------------------------------------------------------------------- 1 | # Recursion 2 | 3 | When a Function call itselfs until a specified condition met is called Recursion. 4 | 5 | If the condition is not there, It will be infinite recursion. 6 | 7 | A stack is maintained and the function is pushed whenever it is called, so in case of infinite recursion, the stack will overflow and it is called Segmentation error or Stack overflow error. 8 | The space used in the stack is called the stack space. 9 | 10 | The specified condition on which the recursive function stops calling itself is called the Base condition. 11 | 12 | Recursion Tree: 13 | Function calls are represented in form of smaller functions. 14 | ![Recursion Tree Image](https://media.geeksforgeeks.org/wp-content/uploads/20210608083944/img-300x172.PNG) 15 | 16 | Main keywords: 17 | 1. Recursion definition 18 | 2. Base Case 19 | 3. Stack overflow / Stack space 20 | 4. Recursion tree -------------------------------------------------------------------------------- /Recursion/02_Parameterised_Functional_Recursion.md: -------------------------------------------------------------------------------- 1 | ## 1. Parameterised Recursion 2 | 3 | When the operations are done through parameters only, then it is called parameterised recursion. 4 | 5 | Example of Sum of N numbers: 6 | ```cpp 7 | #include 8 | using namespace std; 9 | 10 | void calculateSum (int i, int sum){ 11 | if(i<1){ 12 | cout<>n; 21 | calculateSum(n, 0); 22 | return 0; 23 | } 24 | ``` 25 | 26 | ## 2. Functional Recursion 27 | 28 | When we want the function to return some values, then it is called functional recursion. 29 | 30 | ```cpp 31 | 32 | ``` -------------------------------------------------------------------------------- /STL/Deque/Initialise.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Deque also known as double-ended queues, are indexed sequence containers part of the STL. The benefit of a deque is that it has the ability to expand and contract at both the ends (front and back) 3 | 4 | ## Different Ways to Initialise a deque 5 | 6 | ### Note : deque need an additional include. 7 | ```cpp 8 | #include 9 | ``` 10 | But Everything will be included when we include , so no need to import vector if we import all modules. 11 | 12 | ### Supported Datatypes : 13 | int, char, string , etc. 14 | 15 | ### 1. 0 sized deque 16 | 17 | ```cpp 18 | // Creates a zero sized deque of int 19 | deque name; 20 | ``` 21 | 22 | ### 2. n-sized deque 23 | 24 | ```cpp 25 | // Creates a n sized vector of int 26 | deque name1(n); 27 | ``` 28 | 29 | ### 3. Creating copy of deque 30 | 31 | ```cpp 32 | // 1st way - Creates a copy of deque name1 by iterating 33 | deque name3(name1.begin(),name1.end()); 34 | 35 | // 2nd way - Directly copying whole deque from name3 36 | deque name4(name3); 37 | ``` 38 | 39 | ### 4. n-sized deque with default value m 40 | 41 | ```cpp 42 | // Creates a n sized deque of int with default value m 43 | deque name5(n,m); 44 | ``` 45 | 46 | ### 5. Deque with pre defined values 47 | 48 | ```cpp 49 | // Creates a deque with user values 50 | deque name6 = {1,2,3,4,5,6}; 51 | ``` -------------------------------------------------------------------------------- /STL/Deque/at() - Print_Elements.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Deque can be printed/displayed through 2 methods. 3 | 4 | ## Method 1 - For Loop till total size of deque 5 | 6 | ```cpp 7 | deque first = {1,2,3,4,5,6}; 8 | // Printing all values (Like an array) 9 | for(int i=0;i first = {1,2,3,4,5,6}; 23 | // Printing all values using iterator 24 | for(auto it=name.begin();it!=first.end();it++){ 25 | cout << *it << " "; 26 | } 27 | ``` 28 | 29 | ### Output 30 | ```cpp 31 | 1 2 3 4 5 6 32 | ``` -------------------------------------------------------------------------------- /STL/Deque/back() - Last_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Deque's last element can be printed/displayed through back() method. The last element means the one which is inserted last. 3 | 4 | ## Display last Element of deque 5 | 6 | ```cpp 7 | deque name; 8 | // Inserting element for example purpose 9 | name.push_back(10); 10 | name.push_back(12); 11 | // Printing value(s) of last element 12 | cout << "Last Element : " << name.back() ; 13 | ``` 14 | 15 | ### Output 16 | ```cpp 17 | Last Element : 12 18 | ``` 19 | 20 | ### You can also do some operations on Last element 21 | 22 | ```cpp 23 | name.back()-=3; 24 | cout << name.back() ; 25 | ``` 26 | 27 | ### Output 28 | ```cpp 29 | 9 30 | ``` -------------------------------------------------------------------------------- /STL/Deque/empty() - Empty Check.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | You can know whether the deque is empty or not using empty() method. We use this method for printing all the element of deque with loop. 3 | 4 | ## To Know whether deque is empty or not 5 | 6 | ```cpp 7 | deque name; 8 | // Checking if queue is empty or not 9 | // (Returns 1 if empty, else 0) 10 | cout << name.empty() ; 11 | ``` 12 | 13 | ### Output 14 | ```cpp 15 | 1 16 | ``` -------------------------------------------------------------------------------- /STL/Deque/front() - First_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Deque's first element can be printed/displayed through front() method. 3 | 4 | ## Display First Element of deque 5 | 6 | ```cpp 7 | deque name; 8 | // Inserting element for example purpose 9 | name.push_back(10); 10 | name.push_back(12); 11 | // Printing value(s) of last element 12 | cout << "First Element : " << name.front() ; 13 | ``` 14 | 15 | ### Output 16 | ```cpp 17 | First Element : 10 18 | ``` 19 | 20 | ### You can also do some operations on Last element 21 | 22 | ```cpp 23 | name.front()-=3; 24 | cout << name.front() ; 25 | ``` 26 | 27 | ### Output 28 | ```cpp 29 | 7 30 | ``` -------------------------------------------------------------------------------- /STL/Deque/pop_back() - Remove Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be removed from last using pop_back method, remember it will remove the last element. 3 | 4 | ## Method 5 | ```cpp 6 | deque first = {1,2,4,6}; 7 | // popping (removing) elements 8 | first.pop_back(); // 6 removed 9 | first.pop_back(); // 4 removed 10 | ``` 11 | 12 | ### Deque now contains 13 | ```cpp 14 | 1 2 15 | ``` -------------------------------------------------------------------------------- /STL/Deque/pop_front() - Remove Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be removed from first using pop_front method, remember it will remove the First element. 3 | 4 | ## Method 5 | ```cpp 6 | deque first = {1,2,4,6}; 7 | // popping (removing) elements 8 | first.pop_front(); // 1 removed 9 | first.pop_front(); // 2 removed 10 | ``` 11 | 12 | ### Deque now contains 13 | ```cpp 14 | 4 6 15 | ``` -------------------------------------------------------------------------------- /STL/Deque/push_back() - Add Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be inserted from last using push_back method or emplace_back method. 3 | 4 | ## Method 5 | ```cpp 6 | deque first = {1,2}; 7 | // Pushing (adding) element 4 and then 6 8 | first.push_back(4); 9 | first.emplace_back(6); 10 | ``` 11 | 12 | ### Deque now contains 13 | ```cpp 14 | 1 2 4 6 15 | ``` -------------------------------------------------------------------------------- /STL/Deque/push_front() - Add Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be inserted from front using push_front method or emplace_front method. 3 | 4 | ## Method 5 | ```cpp 6 | deque first = {1,2}; 7 | // Pushing (adding) element 4 and then 6 8 | first.push_front(4); 9 | first.emplace_front(6); 10 | ``` 11 | 12 | ### Deque now contains 13 | ```cpp 14 | 6 4 1 2 15 | ``` -------------------------------------------------------------------------------- /STL/Deque/size() - Deque Size.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can determine number of elements in deque using size() method. 3 | 4 | ## Stack's size 5 | 6 | ```cpp 7 | deque name; 8 | // Inserting data 1,2,3 9 | name.push(1); 10 | name.push(2); 11 | name.push(3); 12 | 13 | // Printing size of stack 14 | cout << name.size() ; 15 | ``` 16 | 17 | ### Output 18 | ```cpp 19 | 3 20 | ``` -------------------------------------------------------------------------------- /STL/Deque/swap() - Swap 2 Deque.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can swap contents of 2 deque using swap() method. 3 | 4 | ## Swap 2 stack's content 5 | 6 | ```cpp 7 | deque name; 8 | deque name2; 9 | // Inserting example data 1,2,3 in name (size:3) 10 | name.push(1); name.push(2); name.push(3); 11 | // Inserting example data 12,13 in name2 (size:2) 12 | name2.push(12); name2.push(13); 13 | 14 | // Swap 2 deque 15 | name.swap(name2); 16 | 17 | cout << name.size() << " " << name2.size() ; 18 | ``` 19 | 20 | ### Output 21 | ```cpp 22 | 2 3 23 | ``` -------------------------------------------------------------------------------- /STL/Queue/1-Initialise.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Queues are like array only but it works on principle of FIFO (First In First Out) so the element that is first inserted will be deleted first and no other elements from middle or last. 3 | 4 | ## Way(s) to Initialise a queue 5 | 6 | ### Note : Queue need an additional include. 7 | ```cpp 8 | #include 9 | ``` 10 | But Everything will be included when we include , so no need to import queue if we import all modules. 11 | 12 | ### Supported Datatypes : 13 | int, char, string 14 | 15 | ### 1. 0 sized queue 16 | 17 | ```cpp 18 | // Creates a zero sized queue of int 19 | queue name; 20 | ``` 21 | 22 | ### 2. Creating copy of queue 23 | 24 | ```cpp 25 | // Directly copy whole queue from name 26 | queue name2(name); 27 | // We can also copy elements from deque also by providing it's variable name as argument 28 | ``` -------------------------------------------------------------------------------- /STL/Queue/back() - Last_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Queue's last element can be printed/displayed through back() method. The last element means the one which is inserted last. 3 | 4 | ## Display last Element of queue 5 | 6 | ```cpp 7 | queue name; 8 | // Inserting element for example purpose 9 | name.push(10); 10 | name.push(12); 11 | // Printing value(s) of last element 12 | cout << "Last Element : " << name.back() ; 13 | ``` 14 | 15 | ### Output 16 | ```cpp 17 | Last Element : 12 18 | ``` 19 | 20 | ### You can also do some operations on Last element 21 | 22 | ```cpp 23 | name.back()-=3; 24 | cout << name.back() ; 25 | ``` 26 | 27 | ### Output 28 | ```cpp 29 | 9 30 | ``` -------------------------------------------------------------------------------- /STL/Queue/empty() - Queue_Empty_Check.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | You can know whether the queue is empty or not using empty() method. We use this method for printing all the element of queue with loop (See last code of this file). 3 | 4 | ## To Know whether queue is empty or not 5 | 6 | ```cpp 7 | queue name; 8 | // Checking if queue is empty or not 9 | // (Returns 1 if empty, else 0) 10 | cout << name.empty() ; 11 | ``` 12 | 13 | ### Output 14 | ```cpp 15 | 1 16 | ``` 17 | 18 | ### We use this method to iterate whole queue (You need to pop elements, so queue will be empty at last) 19 | 20 | ```cpp 21 | // Iterating queue by printing front element and removing elements 22 | queue name; 23 | // Example data 24 | name.push(2); 25 | name.push(4); 26 | name.push(6); 27 | 28 | // Iterate queue, Print all elements 29 | while(!name.empty()){ 30 | cout << name.front() << endl; 31 | name.pop(); 32 | } 33 | ``` 34 | 35 | ### Output 36 | ```cpp 37 | 2 38 | 4 39 | 6 40 | ``` -------------------------------------------------------------------------------- /STL/Queue/front() - First_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Queue's First element can be printed/displayed through front() method. The first element means the one which was inserted first. 3 | 4 | ## Display first Element of queue 5 | 6 | ```cpp 7 | queue name; 8 | // Inserting element for example purpose 9 | name.push(10); 10 | name.push(12); 11 | // Printing value(s) of first element 12 | cout << "First Element : " << name.front() ; 13 | ``` 14 | 15 | ### Output 16 | ```cpp 17 | First Element : 10 18 | ``` 19 | 20 | ### You can also do some operations on First element 21 | 22 | ```cpp 23 | name.front()-=3; 24 | cout << name.front() ; 25 | ``` 26 | 27 | ### Output 28 | ```cpp 29 | 7 30 | ``` -------------------------------------------------------------------------------- /STL/Queue/pop() - Remove_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be removed from First using pop method, remember it will remove the first element inserted only. 3 | 4 | ## Method 5 | ```cpp 6 | queue first; 7 | // Adding Element for demo 8 | first.push(1); 9 | first.push(2); 10 | first.push(4); 11 | first.push(6); 12 | 13 | // popping (removing) elements 14 | first.pop(); // 1 removed 15 | first.pop(); // 2 removed 16 | ``` 17 | 18 | ### Queue now contains 19 | ```cpp 20 | 4 6 21 | ``` -------------------------------------------------------------------------------- /STL/Queue/push() - Insert_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be inserted from last using push() or emplace() method. 3 | 4 | ## Method 5 | ```cpp 6 | queue first; 7 | // Pushing (adding) element 4 and then 6 8 | first.push(4); 9 | first.emplace(6); 10 | ``` 11 | 12 | ### Queue now contains 13 | ```cpp 14 | 4 6 15 | ``` -------------------------------------------------------------------------------- /STL/Queue/size() - Queue_Size.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can determine number of elements in queue using size() method. 3 | 4 | ## Queue's size 5 | 6 | ```cpp 7 | queue name; 8 | // Inserting data 1,2,3 9 | name.push(1); 10 | name.push(2); 11 | name.push(3); 12 | 13 | // Printing size of queue 14 | cout << name.size() ; 15 | ``` 16 | 17 | ### Output 18 | ```cpp 19 | 3 20 | ``` -------------------------------------------------------------------------------- /STL/Queue/swap() - Swap_2_Queue.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can swap contents of 2 queue using swap() method. 3 | 4 | ## Swap 2 queue's content 5 | 6 | ```cpp 7 | queue name; 8 | queue name2; 9 | // Inserting example data 1,2,3 in name (size:3) 10 | name.push(1); name.push(2); name.push(3); 11 | // Inserting example data 12,13 in name2 (size:2) 12 | name2.push(12); name2.push(13); 13 | 14 | // Swap 2 queue 15 | name.swap(name2); 16 | 17 | cout << name.size() << " " << name2.size() ; 18 | ``` 19 | 20 | ### Output 21 | ```cpp 22 | 2 3 23 | ``` -------------------------------------------------------------------------------- /STL/STL.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aaryahjolia/dsa_competitive-coding/9d4c47b20dbc402f578374ed5e50ff072d84d486/STL/STL.md -------------------------------------------------------------------------------- /STL/Stack/1-Initialise.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Stack are container which stores elements in bottom-top movement and you can only remove the top most (Last element). So, it uses LIFO structure (Last In, First Out). 3 | 4 | ## Different Ways to Initialise a stack 5 | 6 | ### Note : Stack need an additional include. 7 | ```cpp 8 | #include 9 | ``` 10 | But Everything will be included when we include , so no need to import vector if we import all modules. 11 | 12 | ### Supported Datatypes : 13 | int, char, string 14 | 15 | ### 1. 0 sized stack 16 | 17 | ```cpp 18 | // Creates a zero sized stack of int 19 | stack name; 20 | ``` 21 | 22 | ### 2. Creating copy of stack 23 | 24 | ```cpp 25 | // Directly copy whole stack from name 26 | stack name2(name); 27 | // We can also copy elements from deque also by providing it's variable name as argument 28 | ``` -------------------------------------------------------------------------------- /STL/Stack/empty() - Stack_Empty_Check.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | You can know whether the stack is empty or not using empty() method. We use this method for printing all the element of stack (See last code of this file). 3 | 4 | ## To Know whether stack is empty or not 5 | 6 | ```cpp 7 | stack name; 8 | // Checking if stack is empty or not 9 | // (Returns 1 if empty, else 0) 10 | cout << name.empty() ; 11 | ``` 12 | 13 | ### Output 14 | ```cpp 15 | 1 16 | ``` 17 | 18 | ### We use this method to iterate whole stack (You need to pop elements, so stack will be empty at last) 19 | 20 | ```cpp 21 | // Iterating stack by printing and removing elements 22 | stack name; 23 | // Example data 24 | name.push(2); 25 | name.push(4); 26 | name.push(6); 27 | 28 | // Iterate stack, Print all elements 29 | while(!name.empty()){ 30 | cout << name.top() << endl; 31 | name.pop(); 32 | } 33 | ``` 34 | 35 | ### Output 36 | ```cpp 37 | 6 38 | 4 39 | 2 40 | ``` -------------------------------------------------------------------------------- /STL/Stack/pop() - Remove_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be removed from last using pop method, remember it will remove the last element only. 3 | 4 | ## Method 5 | ```cpp 6 | stack first; 7 | // Adding Element for demo 8 | first.push(1); 9 | first.push(2); 10 | first.push(4); 11 | first.push(6); 12 | 13 | // popping (removing) elements 14 | first.pop(); // 6 removed 15 | first.pop(); // 4 removed 16 | ``` 17 | 18 | ### Stack now contains 19 | ```cpp 20 | 2 21 | 1 22 | ``` -------------------------------------------------------------------------------- /STL/Stack/push() - Insert_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be inserted from last using push() or emplace() method. 3 | 4 | ## Method 5 | ```cpp 6 | stack first; 7 | // Pushing (adding) element 4 and then 6 8 | first.push(4); 9 | first.emplace(6); 10 | ``` 11 | 12 | ### Stack now contains 13 | ```cpp 14 | 6 // Top (Last) Element 15 | 4 16 | ``` -------------------------------------------------------------------------------- /STL/Stack/size() - Stack_Size.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can determine number of elements in stack using size() method. 3 | 4 | ## Stack's size 5 | 6 | ```cpp 7 | stack name; 8 | // Inserting data 1,2,3 9 | name.push(1); 10 | name.push(2); 11 | name.push(3); 12 | 13 | // Printing size of stack 14 | cout << name.size() ; 15 | ``` 16 | 17 | ### Output 18 | ```cpp 19 | 3 20 | ``` -------------------------------------------------------------------------------- /STL/Stack/swap() - Swap_2_Stacks.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | We can swap contents of 2 stack using swap() method. 3 | 4 | ## Swap 2 stack's content 5 | 6 | ```cpp 7 | stack name; 8 | stack name2; 9 | // Inserting example data 1,2,3 in name (size:3) 10 | name.push(1); name.push(2); name.push(3); 11 | // Inserting example data 12,13 in name2 (size:2) 12 | name2.push(12); name2.push(13); 13 | 14 | // Swap 2 stacks 15 | name.swap(name2); 16 | 17 | cout << name.size() << " " << name2.size() ; 18 | ``` 19 | 20 | ### Output 21 | ```cpp 22 | 2 3 23 | ``` -------------------------------------------------------------------------------- /STL/Stack/top() - Print_Top_Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Stack's top element can be printed/displayed through top() method. 3 | 4 | ## Display Top Element of stack 5 | 6 | ```cpp 7 | stack name; 8 | // Inserting element for example purpose 9 | name.push(10); 10 | // Printing value(s) 11 | cout << "Top Element : " << name.top() ; 12 | ``` 13 | 14 | ### Output 15 | ```cpp 16 | Top Element : 10 17 | ``` 18 | 19 | ### You can also do some operations on top element 20 | 21 | ```cpp 22 | // In above 'name' stack : 23 | name.top()-=3; 24 | cout << name.top() ; 25 | ``` 26 | 27 | ### Output 28 | ```cpp 29 | 7 30 | ``` -------------------------------------------------------------------------------- /STL/Vectors/Initialise.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Vector are also called as dynamic arrays. It work like arrays and it is part of containers. 3 | 4 | ## Different Ways to Initialise a vector 5 | 6 | ### Note : Vectors need an additional include. 7 | ```cpp 8 | #include 9 | ``` 10 | But Everything will be included when we include , so no need to import vector if we import all modules. 11 | 12 | ### Supported Datatypes : 13 | char, uchar, short, ushort, int, uint, float, long, and ulong 14 | 15 | ### 1. 0 sized vector 16 | 17 | ```cpp 18 | // Creates a zero sized vector of int 19 | vector name; 20 | ``` 21 | 22 | ### 2. n-sized vector 23 | 24 | ```cpp 25 | // Creates a n sized vector of int 26 | vector name1(n); 27 | ``` 28 | 29 | ### 3. Creating copy of vector 30 | 31 | ```cpp 32 | // 1st way - Creates a copy of vector name1 by iterating 33 | vector name3(name1.begin(),name1.end()); 34 | 35 | // 2nd way - Directly copying whole vector from name3 36 | vector name4(name3); 37 | ``` 38 | 39 | ### 4. n-sized vector with default value m 40 | 41 | ```cpp 42 | // Creates a n sized vector of int with default value m 43 | vector name5(n,m); 44 | ``` 45 | 46 | ### 5. Vector with pre defined values 47 | 48 | ```cpp 49 | // Creates a vector with user values 50 | vector name6 = {1,2,3,4,5,6}; 51 | ``` -------------------------------------------------------------------------------- /STL/Vectors/Print.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Vector can be printed/displayed through 2 methods. 3 | 4 | ## Method 1 - For Loop till total size of vector 5 | 6 | ```cpp 7 | vector first = {1,2,3,4,5,6}; 8 | // Printing all values (Like an array) 9 | for(int i=0;i first = {1,2,3,4,5,6}; 23 | // Printing all values using iterator 24 | for(auto it=name.begin();it!=first.end();it++){ 25 | cout << *it << " "; 26 | } 27 | ``` 28 | 29 | ### Output 30 | ```cpp 31 | 1 2 3 4 5 6 32 | ``` -------------------------------------------------------------------------------- /STL/Vectors/pop_back() - Remove Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be removed from last using pop_back method, remember it will remove the last element. 3 | 4 | ## Method 5 | ```cpp 6 | vector first = {1,2,4,6}; 7 | // popping (removing) elements 8 | first.pop_back(); // 6 removed 9 | first.pop_back(); // 4 removed 10 | ``` 11 | 12 | ### Vector now contains 13 | ```cpp 14 | 1 2 15 | ``` -------------------------------------------------------------------------------- /STL/Vectors/push_back() - Add Element.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Element can be inserted from last using push_back method. 3 | 4 | ## Method 5 | ```cpp 6 | vector first = {1,2}; 7 | // Pushing (adding) element 4 and then 6 8 | first.push_back(4); 9 | first.push_back(6); 10 | ``` 11 | 12 | ### Vector now contains 13 | ```cpp 14 | 1 2 4 6 15 | ``` -------------------------------------------------------------------------------- /STL/Vectors/size() - Size of Vector.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Vector sizes are same as that of current number of elements stored in vector. 3 | 4 | ## Method 5 | ```cpp 6 | vector first = {1,2,3,4,5,6}; 7 | // Displaying size of vector with .size() method 8 | cout << first.size() << endl; 9 | ``` 10 | 11 | ### Output 12 | ```cpp 13 | 6 14 | ``` -------------------------------------------------------------------------------- /Searching/Binary_Search.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Binary search finds an element in a sorted array with Loops. 3 | 4 | ## Code 5 | ```cpp 6 | #include 7 | using namespace std; 8 | 9 | // Function for Binary Search 10 | int BinarySearch(int array[], int size, int to_find){ 11 | // Defining high and low that are last and first element respectively 12 | int low=0,high=size-1; 13 | // Loop till low<=high or loop till there is no element range left to examine mid 14 | while(low<=high){ 15 | // Calculating mid element keeping overflow in mind 16 | int mid=low+(high-low)/2; 17 | // If middle element is same as element to find, return index 18 | if(array[mid]==to_find){ 19 | return mid; 20 | } 21 | // If middle element is greater than element to find, reducing high element to search in left side array 22 | else if(array[mid]>to_find){ 23 | high=mid-1; 24 | } 25 | // else the element to find will be on right most array, so changing low element 26 | else{ 27 | low=mid+1; 28 | } 29 | } 30 | //If nothing found, return -1 31 | return -1; 32 | } 33 | 34 | int main(){ 35 | // Taking size and array elements 36 | cout<<"Enter size of Array:"<>size; 39 | int array[size]; 40 | cout<<"Enter elements:"<>array[i]; 44 | } 45 | cout<<"Enter element to search:"<>to_find_element; 48 | // Calling function with array, its size and element to find as arguments 49 | int index=BinarySearch(array,size,to_find_element); 50 | // Checking if index found and printing appropriate message 51 | if(index==-1){ 52 | cout<<"Element is not present in array!"< 7 | using namespace std; 8 | 9 | // Function for Binary Search with recursion 10 | int BinarySearchRecursion(int array[], int size, int to_find, int min_range, int max_range){ 11 | // Calculating mid element keeping overflow in mind 12 | int mid=min_range+(max_range-min_range)/2; 13 | // If middle element is same as element to find, return index 14 | if(array[mid]==to_find){ 15 | return mid; 16 | } 17 | // If middle element is greater than element to find, calling same function but with a lower max_range (left array from middle element) 18 | else if(array[mid]>to_find){ 19 | return BinarySearchRecursion(array,size,to_find,0,mid-1); 20 | } 21 | // else calling same function but with a higher min_range (right array from middle element) 22 | else{ 23 | return BinarySearchRecursion(array,size,to_find,mid+1,max_range); 24 | } 25 | //If nothing found, return -1 26 | return -1; 27 | } 28 | 29 | int main(){ 30 | // Taking size and array elements 31 | cout<<"Enter size of Array:"<>size; 34 | int array[size]; 35 | cout<<"Enter elements:"<>array[i]; 39 | } 40 | cout<<"Enter element to search:"<>to_find_element; 43 | // Calling function with array, its size, element to find, first element and last element as arguments 44 | int index=BinarySearchRecursion(array,size,to_find_element,0,size-1); 45 | // Checking if index found and printing appropriate message 46 | if(index==-1){ 47 | cout<<"Element is not present in array!"< 7 | using namespace std; 8 | 9 | // Function for Linear Search 10 | int LinearSearch(int array[],int size,int to_find){ 11 | // For loop to iterate over all elements 12 | for(int i=0;i>size; 25 | int array[size]; 26 | cout<<"Enter elements:"<>array[i]; 29 | } 30 | cout<<"Enter element to search:"<>to_find_element; 33 | // Calling function with array, its size and element to find as arguments 34 | int index=LinearSearch(array,size,to_find_element); 35 | // Checking if index found and printing appropriate message 36 | if(index==-1){ 37 | cout<<"Element is not present in array!"< 8 | using namespace std; 9 | 10 | // Find the peak element in the array 11 | int findPeak(int arr[], int n) 12 | { 13 | // first or last element is peak element 14 | if (n == 1) 15 | return 0; 16 | if (arr[0] >= arr[1]) 17 | return 0; 18 | if (arr[n - 1] >= arr[n - 2]) 19 | return n - 1; 20 | 21 | // check for every other element 22 | for (int i = 1; i < n - 1; i++) { 23 | 24 | // check if the neighbors are smaller 25 | if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) 26 | return i; 27 | } 28 | } 29 | 30 | // Driver Code 31 | int main() 32 | { 33 | int arr[] = { 1, 3, 20, 4, 1, 0 }; 34 | int n = sizeof(arr) / sizeof(arr[0]); 35 | cout << "Index of a peak point is " << findPeak(arr, n); 36 | return 0; 37 | } 38 | ``` 39 | 40 | 41 | ## Complexities 42 | ### Time complexity : 43 | Worst Case : O(log n) 44 | ### Space complexity : 45 | O(1) 46 | -------------------------------------------------------------------------------- /Sorting/Bubble_Sort.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | Bubble sort is used to sort arrays using principle of big bubble (whole array) eventually becoming small bubble by filtering big values at end of an array. 3 | 4 | ## Code 5 | ```cpp 6 | 7 | #include 8 | using namespace std; 9 | 10 | // Bubble Sort Logic 11 | void bubble_sort(int ar[],int n){ 12 | // First loop for every element from end to start (Big bubble to small) 13 | for(int i=n-1;i>=0;--i){ 14 | // Loop to identify big value and swap it till the end so array can be sorted 15 | for(int j=0;jar[j+1]){ 17 | swap(ar[j],ar[j+1]); 18 | } 19 | } 20 | } 21 | } 22 | 23 | //Sorting Algorithm Boiler code to take input of array, call the sorting function and print the array. 24 | int main(){ 25 | cout<<"Enter size of array : "; 26 | int size; 27 | cin>>size; 28 | int ar[size]; 29 | for(int i=0;i>ar[i]; 32 | } 33 | cout<<"Before Sort : "< 8 | using namespace std; 9 | 10 | // heapify function to swap values to make a max heap binary tree (Tree in which the root element will be larger than child nodes). 11 | void heapify(int ar[],int n,int i){ 12 | int largest=i; 13 | // Left and right child of tree when arranged as tree from array 14 | int left=2*i+1; 15 | int right=2*i+2; 16 | if(ar[left]>ar[largest] && leftar[largest] && right=0;--i){ 33 | heapify(ar,n,i); 34 | } 35 | 36 | // Swap 0th element to last element as 0th will be largest value according to max heap tree and run heapify again except on swapped element, Hence array will be sorted. 37 | for(int i=n-1;i>=0;--i){ 38 | swap(ar[0],ar[i]); 39 | heapify(ar,i,0); 40 | } 41 | } 42 | 43 | //Sorting Algorithm Boiler code to take input of array, call the sorting function and print the array. 44 | int main(){ 45 | cout<<"Enter size of array : "; 46 | int size; 47 | cin>>size; 48 | int ar[size]; 49 | for(int i=0;i>ar[i]; 52 | } 53 | cout<<"Before Sort : "< 7 | using namespace std; 8 | 9 | // Insertion Sort Logic 10 | void insertion_sort(int ar[],int n){ 11 | // Loop to start from 1st index as first element is sorted 12 | for(int i=1;itemp && j-1>=0){ 17 | ar[j]=ar[j-1]; 18 | j--; 19 | } 20 | // Finally placing element at proper index 21 | ar[j]=temp; 22 | } 23 | } 24 | 25 | // Sorting Algorithm Boiler code to take input of array, call the sorting function and print the array. 26 | int main(){ 27 | cout<<"Enter size of array : "; 28 | int size; 29 | cin>>size; 30 | int ar[size]; 31 | for(int i=0;i>ar[i]; 34 | } 35 | cout<<"Before Sort : "< 7 | using namespace std; 8 | 9 | // Merge Sort Logic 10 | // Function to sort 2 sub arrays 11 | void merge(int ar[],int low,int mid,int high){ 12 | int i,j,k,b[1000]; 13 | // Initialising i to low, j to midth element, and k to low. 14 | // low to mid is 1 array, mid+1 to high is another array 15 | // k will be used as index to store sorted array in b 16 | i=low; 17 | k=low; 18 | j=mid+1; 19 | // Loop till any of the array is completed traversing and storing lowest value in b 20 | while(i<=mid && j<=high){ 21 | if(ar[i]>ar[j]){ 22 | b[k]=ar[j]; 23 | j++; 24 | k++; 25 | } 26 | else{ 27 | b[k]=ar[i]; 28 | i++; 29 | k++; 30 | } 31 | } 32 | // Loop to store elements left in array 1 (low to mid) 33 | while(i<=mid){ 34 | b[k]=ar[i]; 35 | i++; 36 | k++; 37 | } 38 | // Loop to store elements left in array 2 (mid+1 to high) 39 | while(j<=high){ 40 | b[k]=ar[j]; 41 | j++; 42 | k++; 43 | } 44 | // At last, storing array b to original array ar 45 | for(int e=low;e<=high;e++){ 46 | ar[e]=b[e]; 47 | } 48 | } 49 | 50 | // Function to partition array in 2 parts and merge them 51 | void sort(int ar[],int low,int high){ 52 | // Base condition to stop recursion when array has only 1 element left 53 | if(low>size; 69 | int ar[size]; 70 | for(int i=0;i>ar[i]; 73 | } 74 | cout<<"Before Sort : "< 7 | using namespace std; 8 | 9 | // Quick Sort Logic 10 | // Function to return pivot index 11 | int partition(int ar[],int low,int high){ 12 | // Initially pivot point will be first element of array i.e.low 13 | int pivot=ar[low]; 14 | int i=low+1; 15 | int j=high; 16 | 17 | // Looping till i and j don't cross each other 18 | while(i<=j){ 19 | // Looping to find biggest element from starting index 20 | while(ar[i]<=pivot){ 21 | i++; 22 | } 23 | // Looping to find smallest element from last index 24 | while(ar[j]>pivot){ 25 | j--; 26 | } 27 | // Swap both element as to make array look like smaller on left, bigger on right 28 | if(i>size; 55 | int ar[size]; 56 | for(int i=0;i>ar[i]; 59 | } 60 | cout<<"Before Sort : "< 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | int partition(int arr[], int low, int high) 14 | { 15 | // pivot 16 | int pivot = arr[high]; 17 | 18 | // Index of smaller element 19 | int i = (low - 1); 20 | 21 | for (int j = low; j <= high - 1; j++) 22 | { 23 | // If current element is smaller 24 | // than or equal to pivot 25 | if (arr[j] <= pivot) { 26 | 27 | // increment index of 28 | // smaller element 29 | i++; 30 | swap(arr[i], arr[j]); 31 | } 32 | } 33 | swap(arr[i + 1], arr[high]); 34 | return (i + 1); 35 | } 36 | 37 | // Generates Random Pivot, swaps pivot with 38 | // end element and calls the partition function 39 | int partition_r(int arr[], int low, int high) 40 | { 41 | // Generate a random number in between 42 | // low .. high 43 | srand(time(NULL)); 44 | int random = low + rand() % (high - low); 45 | 46 | // Swap A[random] with A[high] 47 | swap(arr[random], arr[high]); 48 | 49 | return partition(arr, low, high); 50 | } 51 | 52 | /* The main function that implements 53 | QuickSort 54 | arr[] --> Array to be sorted, 55 | low --> Starting index, 56 | high --> Ending index */ 57 | void quickSort(int arr[], int low, int high) 58 | { 59 | if (low < high) { 60 | 61 | /* pi is partitioning index, 62 | arr[p] is now 63 | at right place */ 64 | int pi = partition_r(arr, low, high); 65 | 66 | // Separately sort elements before 67 | // partition and after partition 68 | quickSort(arr, low, pi - 1); 69 | quickSort(arr, pi + 1, high); 70 | } 71 | } 72 | 73 | /* Function to print an array */ 74 | void printArray(int arr[], int size) 75 | { 76 | int i; 77 | for (i = 0; i < size; i++) 78 | cout< 7 | using namespace std; 8 | 9 | // Selection Sort Logic 10 | void selection_sort(int ar[],int n){ 11 | // Loop for traversing array to swap smallest value with the current element of loop 12 | for(int i=0;iar[j]){ 18 | elem=j; 19 | } 20 | } 21 | // Swapping smallest element (elem) with current element of loop (i) 22 | swap(ar[elem],ar[i]); 23 | } 24 | } 25 | 26 | // Sorting Algorithm Boiler code to take input of array, call the sorting function and print the array. 27 | int main(){ 28 | cout<<"Enter size of array : "; 29 | int size; 30 | cin>>size; 31 | int ar[size]; 32 | for(int i=0;i>ar[i]; 35 | } 36 | cout<<"Before Sort : "<> levelOrder(Node* root){ 26 | vector> ans; 27 | if(root == NULL) return ans; 28 | queue q; 29 | q.push(root); 30 | while(!q.empty()) { 31 | int size = q.size(); 32 | vector level; 33 | for(int i = 0; ileft != NULL) q.push(node->left); 37 | if(node->right != NULL) q.push(node->right); 38 | level.push_back(node->data); 39 | } 40 | ans.push_back(level); 41 | } 42 | return ans; 43 | } 44 | ``` 45 | ## Time and Space Complexity : 46 | 47 | For both the cases 48 | * Time Complexity: O(n) 49 | * Space Complexity: O(n) 50 | 51 | ### Next Step -------------------------------------------------------------------------------- /Tree/Binary_Trees.md: -------------------------------------------------------------------------------- 1 | ## Types of Binary Trees 2 | 3 | 1. Full BT : Either 0 or 2 Childrens 4 | 2. Complete BT : All levels are completely filled (except last level) and Last level has all nodes as left as posible. 5 | 3. Perfect BT : All Leaf nodes are at same level. 6 | 4. Balanced BT : Height of tree is at max log(n) where n is number of nodes. 7 | 5. Degenerate BT : Every node should have a single child only (Just as a Linked list). 8 | 9 | ## Initialise a Binary Tree in C++ 10 | 11 | ```cpp 12 | class Node{ 13 | public: 14 | int data; 15 | Node* left; 16 | Node* right; 17 | 18 | Node(int value){ 19 | this->data = value; 20 | this->left = this->right = NULL; 21 | } 22 | }; 23 | ``` 24 | ### Run Code 25 | 26 | https://ide.geeksforgeeks.org/9721e25e-94d6-4f3a-89be-133386753efc 27 | 28 | ### Next Step 29 | 30 | [Inorder Traversal](./Inorder_Traversal.md) -------------------------------------------------------------------------------- /Tree/Inorder_Traversal.md: -------------------------------------------------------------------------------- 1 | # Inorder Traversal (DFS) 2 | In this traversal approach, the left subtree is visited first, then the root, and finally the right subtree. 3 | (Left, Root, Right) 4 | 5 | ## Example 6 | 7 | ![Binary_Tree](https://user-images.githubusercontent.com/82600388/184525938-cba5ca0d-8d65-41da-9447-b948c0091a34.png) 8 | 9 | Inorder Traversal : 10 | ``` 11 | 1 3 4 6 7 8 10 13 14 12 | ``` 13 | 14 | ## Recursive Approach : 15 | ### Algorithm : 16 | 1. Call Inorder to traverse the left subtree 17 | 2. Print the root 18 | 3. Call Inorder to traverse the right subtree 19 | 20 | ```cpp 21 | void inorder(Node* root) 22 | { 23 | if (root == nullptr) { 24 | return; 25 | } 26 | inorder(root->left); 27 | cout << root->data << " "; 28 | inorder(root->right); 29 | } 30 | ``` 31 | 32 | ## Iterative Approach : 33 | ### Algorithm : 34 | 1) Begin by making an empty stack S. 35 | 2) Make the current node root. 36 | 3) Move the current node to S and set current = current->left until current is NULL. 37 | 4) If current is NULL and the stack is not empty, 38 | * Remove the top item from the stack. 39 | * Print the popped item by setting current to popped item->right. 40 | * Proceed to step 3. 41 | 1) If current is NULL and the stack is empty, we are finished. 42 | 43 | ```cpp 44 | class Solution { 45 | public: 46 | vector inorderTraversal(Node* root) { 47 | stack stck; 48 | while(root || !stck.empty()){ 49 | while (root) { 50 | stck.push(root); 51 | root = root->left; 52 | } 53 | root = stck.top(); 54 | stck.pop(); 55 | cout<data<<" "; 56 | root = root->right; 57 | } 58 | } 59 | }; 60 | ``` 61 | ## Time and Space Complexity : 62 | 63 | For both the cases, 64 | * Time Complexity: O(n) 65 | * Space Complexity: O(n) 66 | 67 | ### Next Step 68 | 69 | [Postorder Traversal](./Postorder_Traversal.md) -------------------------------------------------------------------------------- /Tree/Postorder_Traversal.md: -------------------------------------------------------------------------------- 1 | # Postorder Traversal (DFS) 2 | This traversal method visits the root node last, hence the name. We go through the left subtree first, then the right subtree, and lastly the root node. 3 | (Left, Right, Root) 4 | 5 | ## Example 6 | 7 | ![Binary_Tree](https://user-images.githubusercontent.com/82600388/184525938-cba5ca0d-8d65-41da-9447-b948c0091a34.png) 8 | 9 | Postorder Traversal : 10 | ``` 11 | 1 4 7 6 3 10 13 14 10 8 12 | ``` 13 | 14 | ## Recursive Approach : 15 | ### Algorithm : 16 | 1. Call Postorder to traverse the left subtree 17 | 2. Call Postorder to traverse the right subtree 18 | 3. Print the root. 19 | 20 | ```cpp 21 | void postorder(Node* root) 22 | { 23 | if (root == nullptr) { 24 | return; 25 | } 26 | postorder(root->left); 27 | postorder(root->right); 28 | cout << root->data << " "; 29 | } 30 | ``` 31 | 32 | ## Iterative Approach : 33 | ### Algorithm : 34 | 1. Begin with an empty stack. 35 | 2. Perform the following when root is not NULL. 36 | * Push root's right child to the stack, followed by root. 37 | * Make root the left child of root. 38 | 39 | 3. Select an item from the stack and make it the root. 40 | * Remove the right child from the stack, push the root back, and set root as the root's right child if the popped item has a right child and the right child is at the top of the stack. 41 | * Alternatively, output root's data and set root to NULL. 42 | 43 | 4. Steps 2 and 3 must be repeated as long as the stack is not empty. 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | vector postorderTraversal(Node* root) { 49 | if (!root) return {}; 50 | vector ans; 51 | stack stck; 52 | stck.push(root); 53 | while (!stck.empty()){ 54 | Node* node = stck.top(); 55 | if (node->left){ 56 | stck.push(node->left); 57 | node->left = nullptr; 58 | } 59 | else if (node->right){ 60 | stck.push(node->right); 61 | node->right = nullptr; 62 | } 63 | else{ 64 | ans.push_back(node->val); 65 | stck.pop(); 66 | } 67 | } 68 | return ans; 69 | } 70 | }; 71 | ``` 72 | ## Time and Space Complexity : 73 | 74 | For both the cases 75 | * Time Complexity: O(n) 76 | * Space Complexity: O(n) 77 | 78 | ### Next Step 79 | 80 | [Preorder Traversal](./Preorder_Traversal.md) -------------------------------------------------------------------------------- /Tree/Preorder_Traversal.md: -------------------------------------------------------------------------------- 1 | # Preorder Traversal (DFS) 2 | The root node is visited first, followed by the left subtree, and ultimately the right subtree in this traversal strategy. 3 | (Root, Left, Right) 4 | 5 | ## Example 6 | 7 | ![Binary_Tree](https://user-images.githubusercontent.com/82600388/184525938-cba5ca0d-8d65-41da-9447-b948c0091a34.png) 8 | 9 | Preorder Traversal : 10 | ``` 11 | 8 3 1 6 4 7 10 14 13 12 | ``` 13 | 14 | ## Recursive Approach : 15 | ### Algorithm : 16 | 1. Print the root. 17 | 2. Call Preorder to traverse the left subtree 18 | 3. Call Preorder to traverse the right subtree 19 | 20 | ```cpp 21 | void preorder(Node* root) 22 | { 23 | if (root == nullptr) { 24 | return; 25 | } 26 | cout << root->data << " "; 27 | preorder(root->left); 28 | preorder(root->right); 29 | } 30 | ``` 31 | 32 | ## Iterative Approach 33 | ### Algorithm : 34 | Make an empty stack and add the root node to it. 35 | While is not empty, perform the following. 36 | 1. Pop a stack item and print it. 37 | 2. Stack by pushing the right child of a popped item. 38 | 3. Stack the left offspring of a popped item. 39 | 4. To ensure that the left subtree is processed first, the right child is pushed before the left child. 40 | 41 | ```cpp 42 | void preorderIterative(Node* root) 43 | { 44 | if(root==NULL) 45 | return; 46 | stackstck; 47 | stck.push(root); 48 | while(!stck.empty()){ 49 | root=stck.top(); 50 | stck.pop(); 51 | cout << root->data << " "; 52 | if(root->right!=NULL) 53 | stck.push(root->right); 54 | if(root->left!=NULL) 55 | stck.push(root->left); 56 | } 57 | } 58 | ``` 59 | ## Time and Space Complexity : 60 | 61 | For both the cases 62 | * Time Complexity: O(n) 63 | * Space Complexity: O(n) 64 | 65 | ### Next Step 66 | 67 | [BFS Traversal](./BFS_Traversal.md) --------------------------------------------------------------------------------