├── .cpp ├── Array ├── AverageInTheArray.cpp ├── Largest_Special_sum.cpp ├── Max_in_subarray.cpp ├── Merge-2-Sorted-Arrays.cpp ├── arr.c ├── floodfillalgo.cpp ├── kadane_algorithm.cpp ├── peakelementarray.cpp ├── reversearray.cpp ├── rotaion_2d_array.cpp └── two_sum.cpp ├── Ford-Fulkerson Algorithm.cpp ├── Graphs ├── Dijkstra's Algorithm .cpp ├── Floyd-Warshall.cpp ├── Kruskalsalgorithm.cpp └── Traveling Salesman Problem.cpp ├── Leetcode ├── 1009. Complement of Base 10.cpp ├── 15. 3Sum.cpp ├── 1922. Count Good Numbers.cpp ├── 264. Ugly Number II.cpp ├── 273Integer to English Words.cpp ├── 274. H-Index.cpp ├── 289. Game of Life.cpp ├── 297. Serialize and Deserialize Binary Tree.cpp ├── 3.LongestSubstringWithoutRepeatingCharacters.cpp ├── 347-Top K frequent Elements ├── 367. Valid Perfect Square.cpp ├── 37Sudoku Solver.cpp ├── 4. Median of Two Sorted Arrays.cpp ├── 42TrappingRainWater.cpp ├── 5.LongestPalindromicSubstring.cpp ├── 785-Is Graph Bipartite ├── 84LargestRectangleinHistogram.cpp ├── DungeonGame.cpp ├── Max_subarray_sum.cpp └── rottenOranges.cpp ├── Linked List ├── LRU_Cache.cpp └── Priyanshu linked_list.cpp ├── Math ├── Create-Factorial-of-number.cpp ├── Matrix Chain Multiplication.cpp ├── armstrong.cpp ├── fibonacci_no.cpp ├── odd_even.cpp ├── pascal_triangle2.cpp ├── prime_no.cpp ├── reversenumber.cpp └── sieveOfEratosthenes.cpp ├── README.md ├── Searching ├── Binary.cpp └── Linearsearch.cpp ├── Sort elements by frequency.cpp ├── Sorting ├── BeadSort.cpp ├── Bucketsort.cpp ├── Heapsort.cpp ├── MergeSort.cpp ├── Selection_sort.cpp ├── Topological_Sorting.cpp ├── Treesort.cpp ├── bubblesort.cpp ├── cyclicSort.cpp ├── exponential.cpp ├── insertion.cpp ├── median_trwo_sorted_array.cpp ├── quicksort.cpp └── shellSort.cpp ├── Sortvector.Cpp ├── Tree ├── binarytree.cpp └── minheighttree.cpp └── swap.cpp /.cpp: -------------------------------------------------------------------------------- 1 | // Cpp program to find second largest element in an array 2 | 3 | #include 4 | using namespace std; 5 | 6 | /* Function to print the second largest elements */ 7 | void print2largest(int arr[], int arr_size) 8 | { 9 | int i, first, second; 10 | /* There should be atleast two elements */ 11 | if (arr_size < 2) { 12 | printf(" Invalid Input "); 13 | return; 14 | } 15 | // sort the array 16 | sort(arr, arr + arr_size); 17 | // start from second last element as the largest element 18 | // is at last 19 | for (i = arr_size - 2; i >= 0; i--) { 20 | // if the element is not equal to largest element 21 | if (arr[i] != arr[arr_size - 1]) { 22 | printf("The second largest element is %d\n",arr[i]); 23 | return; 24 | } 25 | } 26 | printf("There is no second largest element\n"); 27 | } 28 | 29 | /* Driver code*/ 30 | int main() 31 | { 32 | int arr[] = { 12, 35, 1, 10, 34, 1 }; 33 | int n = sizeof(arr) / sizeof(arr[0]); 34 | print2largest(arr, n); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Array/AverageInTheArray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to calculate average of array elements 2 | #include 3 | using namespace std; 4 | 5 | // Function that return average of an array. 6 | double average(int a[], int n) 7 | { 8 | // Find sum of array element 9 | int sum = 0; 10 | for (int i=0; i 2 | using namespace std; 3 | /* if the total numbers are 12,3,2,4,1 4 | then the special sum will be calculated from first index like 5 | a[0]=a[0]+(a[1]+a[2])+(a[3]+a[4]+a[5])+(a[6]+a[7]+a[8]+a[9])... 6 | a[1]=a[1]+(a[2]+a[3])+(a[4]+a[5]+a[6])+(a[7]+a[8]+a[9]+a[10])... 7 | if there is any index which does not exist then that part of sum will not be calculated for example if a[5] does not exit then this part (a[4]+a[5]+a[6])+(a[7]+a[8]+a[9]+a[10])... will not be calculated*/ 8 | int calculateSpecialSum(int arr[], int n, int index) { 9 | int specialSum = arr[index]; 10 | for (int i = index + 2; i < n; i += 2) { 11 | specialSum += arr[i]; 12 | } 13 | return specialSum; 14 | } 15 | 16 | int main() { 17 | int n, arr[20]; 18 | cout << "Enter the number of elements: "; 19 | cin >> n; 20 | cout << "Enter the elements: "; 21 | for (int i = 0; i < n; i++) { 22 | cin >> arr[i]; 23 | } 24 | 25 | int bestIndex = -1; // Initialize to an invalid index 26 | int maxSpecialSum = 0; 27 | 28 | for (int i = 0; i < n; i++) { 29 | int specialSum = calculateSpecialSum(arr, n, i); 30 | if (specialSum > maxSpecialSum) { 31 | maxSpecialSum = specialSum; 32 | bestIndex = i; 33 | } 34 | } 35 | 36 | if (bestIndex == -1) { 37 | cout << "No valid index found." << endl; 38 | } else { 39 | cout << "The largest special sum is: " << maxSpecialSum+1 << " at index " << bestIndex << endl; 40 | } 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Array/Max_in_subarray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for the above approach 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Method to find the maximum for each 7 | // and every contiguous subarray of size K. 8 | void printKMax(int arr[], int N, int K) 9 | { 10 | int j, max; 11 | 12 | for (int i = 0; i <= N - K; i++) { 13 | max = arr[i]; 14 | 15 | for (j = 1; j < K; j++) { 16 | if (arr[i + j] > max) 17 | max = arr[i + j]; 18 | } 19 | cout << max << " "; 20 | } 21 | } 22 | 23 | // Driver's code 24 | int main() 25 | { 26 | int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 27 | int N = sizeof(arr) / sizeof(arr[0]); 28 | int K = 3; 29 | 30 | // Function call 31 | printKMax(arr, N, K); 32 | return 0; 33 | } 34 | 35 | // This code is contributed by rathbhupendra 36 | -------------------------------------------------------------------------------- /Array/Merge-2-Sorted-Arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | void merge(int arr1[], int n, int arr2[], int m, int arr3[]){ 6 | 7 | int i=0, j=0, k=0; 8 | 9 | while (i 2 | int main(){ 3 | // int i = 5; 4 | // printf("the value after i++ is %d\n", ++i); 5 | // // i++ //---> phle print phir increment 6 | // // ++i;// --->pehle increment phir print kre 7 | // printf("the value after i is %d\n", i); 8 | int a=10; 9 | for(int i=0;i 3 | using namespace std; 4 | // Dimensions of paint screen 5 | #define M 8 6 | #define N 8 7 | 8 | // A recursive function to replace previous color 'prevC' at '(x, y)' 9 | // and all surrounding pixels of (x, y) with new color 'newC' and 10 | void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC) 11 | { 12 | if (x < 0 || x >= M || y < 0 || y >= N) 13 | return; 14 | if (screen[x][y] != prevC) 15 | return; 16 | if (screen[x][y] == newC) 17 | return; 18 | // Replace the color at (x, y) 19 | screen[x][y] = newC; 20 | // Recur for north, east, south and west 21 | floodFillUtil(screen, x+1, y, prevC, newC); 22 | floodFillUtil(screen, x-1, y, prevC, newC); 23 | floodFillUtil(screen, x, y+1, prevC, newC); 24 | floodFillUtil(screen, x, y-1, prevC, newC); 25 | } 26 | // It mainly finds the previous color on (x, y) and 27 | // calls floodFillUtil() 28 | void floodFill(int screen[][N], int x, int y, int newC) 29 | { 30 | int prevC = screen[x][y]; 31 | if(prevC==newC) return; 32 | floodFillUtil(screen, x, y, prevC, newC); 33 | } 34 | int main() 35 | { 36 | int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, 37 | {1, 1, 1, 1, 1, 1, 0, 0}, 38 | {1, 0, 0, 1, 1, 0, 1, 1}, 39 | {1, 2, 2, 2, 2, 0, 1, 0}, 40 | {1, 1, 1, 2, 2, 0, 1, 0}, 41 | {1, 1, 1, 2, 2, 2, 2, 0}, 42 | {1, 1, 1, 1, 1, 2, 1, 1}, 43 | {1, 1, 1, 1, 1, 2, 2, 1}, 44 | }; 45 | int x = 4, y = 4, newC = 3; 46 | floodFill(screen, x, y, newC); 47 | 48 | cout << "Updated screen after call to floodFill: \n"; 49 | for (int i=0; i 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0; 9 | 10 | for (int i = 0; i < size; i++) { 11 | max_ending_here = max_ending_here + a[i]; 12 | if (max_so_far < max_ending_here) 13 | max_so_far = max_ending_here; 14 | 15 | if (max_ending_here < 0) 16 | max_ending_here = 0; 17 | } 18 | return max_so_far; 19 | } 20 | 21 | // Driver Code 22 | int main() 23 | { 24 | int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; 25 | int n = sizeof(a) / sizeof(a[0]); 26 | 27 | // Function Call 28 | int max_sum = maxSubArraySum(a, n); 29 | cout << "Maximum contiguous sum is " << max_sum; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Array/peakelementarray.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find a peak element 2 | #include 3 | using namespace std; 4 | 5 | // Find the peak element in the array 6 | int findPeak(int arr[], int n) 7 | { 8 | // first or last element is peak element 9 | if (n == 1) 10 | return 0; 11 | if (arr[0] >= arr[1]) 12 | return 0; 13 | if (arr[n - 1] >= arr[n - 2]) 14 | return n - 1; 15 | 16 | // check for every other element 17 | for (int i = 1; i < n - 1; i++) { 18 | 19 | // check if the neighbors are smaller 20 | if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) 21 | return i; 22 | } 23 | } 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | int arr[] = { 1, 3, 20, 4, 1, 0 }; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | cout << "Index of a peak point is " << findPeak(arr, n); 31 | return 0; 32 | } 33 | 34 | // This code is contributed by Aditya Kumar (adityakumar129) 35 | -------------------------------------------------------------------------------- /Array/reversearray.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to reverse an array 2 | #include 3 | using namespace std; 4 | 5 | /* Function to reverse arr[] from start to end*/ 6 | void rvereseArray(int arr[], int start, int end) 7 | { 8 | while (start < end) 9 | { 10 | int temp = arr[start]; 11 | arr[start] = arr[end]; 12 | arr[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | 18 | /* Utility function to print an array */ 19 | void printArray(int arr[], int size) 20 | { 21 | for (int i = 0; i < size; i++) 22 | cout << arr[i] << " "; 23 | 24 | cout << endl; 25 | } 26 | 27 | /* Driver function to test above functions */ 28 | int main() 29 | { 30 | int arr[] = {1, 2, 3, 4, 5, 6}; 31 | 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | 34 | // To print original array 35 | printArray(arr, n); 36 | 37 | // Function calling 38 | rvereseArray(arr, 0, n-1); 39 | 40 | cout << "Reversed array is" << endl; 41 | 42 | // To print the Reversed array 43 | printArray(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Array/rotaion_2d_array.cpp: -------------------------------------------------------------------------------- 1 | //rotating by 90 degree 2 | #include 3 | using namespace std; 4 | #include 5 | #include 6 | void rotation(vector > &v){ 7 | int b=v.size(); 8 | for(int i=0;i>r; 21 | cout<<"enter the coloumn : "; 22 | cin>>c; 23 | vector > a(r,vector(c)); 24 | for(int i=0;i>a[i][j]; 28 | } 29 | } 30 | cout<<"the array is : "< 10 | #include 11 | using namespace std; 12 | 13 | int main() 14 | { 15 | int nums[10000]; 16 | int a,target, sum, c, d; 17 | 18 | cout<<"The number of digits you want to provide is?" << endl; 19 | cin>> a; 20 | 21 | cout<< "Enter the target value \n"; 22 | cin>> target; 23 | 24 | for (int i = 0; i > nums[i]; 28 | } 29 | 30 | 31 | for (int j = 0; j < a; j++) 32 | { 33 | for (int t = 0; t+j < a ; t++) 34 | { 35 | sum = nums[j] + nums[j+t]; 36 | 37 | if (sum == target) 38 | { 39 | cout<<"The requierd output is ["<< j <<", "<< j+t << "]"; 40 | } 41 | else; 42 | } 43 | } 44 | 45 | 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Ford-Fulkerson Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | const int V = 6; 9 | 10 | int graph[V][V] = { 11 | {0, 16, 13, 0, 0, 0}, 12 | {0, 0, 10, 12, 0, 0}, 13 | {0, 4, 0, 0, 14, 0}, 14 | {0, 0, 9, 0, 0, 20}, 15 | {0, 0, 0, 7, 0, 4}, 16 | {0, 0, 0, 0, 0, 0} 17 | }; 18 | 19 | bool bfs(int rGraph[V][V], int source, int sink, vector& parent) { 20 | vector visited(V, false); 21 | queue q; 22 | q.push(source); 23 | visited[source] = true; 24 | 25 | while (!q.empty()) { 26 | int u = q.front(); 27 | q.pop(); 28 | 29 | for (int v = 0; v < V; v++) { 30 | if (!visited[v] && rGraph[u][v] > 0) { 31 | q.push(v); 32 | parent[v] = u; 33 | visited[v] = true; 34 | } 35 | } 36 | } 37 | 38 | return visited[sink]; 39 | } 40 | 41 | int fordFulkerson(int source, int sink) { 42 | int rGraph[V][V]; 43 | for (int i = 0; i < V; i++) { 44 | for (int j = 0; j < V; j++) { 45 | rGraph[i][j] = graph[i][j]; 46 | } 47 | } 48 | 49 | vector parent(V, -1); 50 | int maxFlow = 0; 51 | 52 | while (bfs(rGraph, source, sink, parent)) { 53 | int pathFlow = INT_MAX; 54 | for (int v = sink; v != source; v = parent[v]) { 55 | int u = parent[v]; 56 | pathFlow = min(pathFlow, rGraph[u][v]); 57 | } 58 | 59 | for (int v = sink; v != source; v = parent[v]) { 60 | int u = parent[v]; 61 | rGraph[u][v] -= pathFlow; 62 | rGraph[v][u] += pathFlow; 63 | } 64 | 65 | maxFlow += pathFlow; 66 | } 67 | 68 | return maxFlow; 69 | } 70 | 71 | int main() { 72 | int source = 0; 73 | int sink = 5; 74 | int maxFlow = fordFulkerson(source, sink); 75 | 76 | cout << "Maximum Flow: " << maxFlow << endl; 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Graphs/Dijkstra's Algorithm .cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | const int V = 6; // Number of vertices 6 | 7 | int minDistance(int dist[], bool visited[]) { 8 | int min = INT_MAX, min_index; 9 | for (int v = 0; v < V; v++) 10 | if (!visited[v] && dist[v] <= min) 11 | min = dist[v], min_index = v; 12 | return min_index; 13 | } 14 | 15 | void dijkstra(int graph[V][V], int start) { 16 | int dist[V]; 17 | bool visited[V]; 18 | 19 | for (int i = 0; i < V; i++) 20 | dist[i] = INT_MAX, visited[i] = false; 21 | 22 | dist[start] = 0; 23 | 24 | for (int count = 0; count < V - 1; count++) { 25 | int u = minDistance(dist, visited); 26 | visited[u] = true; 27 | 28 | for (int v = 0; v < V; v++) 29 | if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) 30 | dist[v] = dist[u] + graph[u][v]; 31 | } 32 | 33 | std::cout << "Shortest distances from vertex " << start << ":\n"; 34 | for (int i = 0; i < V; i++) 35 | std::cout << start << " -> " << i << " = " << dist[i] << "\n"; 36 | } 37 | 38 | int main() { 39 | int graph[V][V] = {{0, 1, 4, 0, 0, 0}, 40 | {0, 0, 4, 2, 7, 0}, 41 | {0, 0, 0, 0, 5, 0}, 42 | {0, 0, 0, 0, 0, 3}, 43 | {0, 0, 0, 0, 0, 1}, 44 | {0, 0, 0, 0, 0, 0}}; 45 | 46 | dijkstra(graph, 0); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Graphs/Floyd-Warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int INF = 99999; // Infinity or a sufficiently large value to represent absence of an edge 7 | 8 | void floydWarshall(vector>& graph, int V) { 9 | // Initialize the distance matrix with the graph's adjacency matrix 10 | vector> dist(V, vector(V)); 11 | 12 | for (int i = 0; i < V; i++) { 13 | for (int j = 0; j < V; j++) { 14 | dist[i][j] = graph[i][j]; 15 | } 16 | } 17 | 18 | // Find the shortest paths 19 | for (int k = 0; k < V; k++) { 20 | for (int i = 0; i < V; i++) { 21 | for (int j = 0; j < V; j++) { 22 | if (dist[i][k] + dist[k][j] < dist[i][j]) { 23 | dist[i][j] = dist[i][k] + dist[k][j]; 24 | } 25 | } 26 | } 27 | } 28 | 29 | // Print the shortest path distances 30 | for (int i = 0; i < V; i++) { 31 | for (int j = 0; j < V; j++) { 32 | if (dist[i][j] == INF) { 33 | cout << "INF\t"; 34 | } else { 35 | cout << dist[i][j] << "\t"; 36 | } 37 | } 38 | cout << endl; 39 | } 40 | } 41 | 42 | int main() { 43 | int V = 4; // Number of vertices 44 | vector> graph = { 45 | {0, 3, INF, 7}, 46 | {8, 0, 2, INF}, 47 | {5, INF, 0, 1}, 48 | {2, INF, INF, 0} 49 | }; 50 | 51 | floydWarshall(graph, V); 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Graphs/Kruskalsalgorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Edge { 8 | int src, dest, weight; 9 | }; 10 | 11 | class Graph { 12 | private: 13 | int V; 14 | vector edges; 15 | 16 | public: 17 | Graph(int vertices) : V(vertices) {} 18 | 19 | void addEdge(int src, int dest, int weight) { 20 | edges.push_back({src, dest, weight}); 21 | } 22 | 23 | int findParent(vector& parent, int vertex) { 24 | if (parent[vertex] == -1) 25 | return vertex; 26 | return findParent(parent, parent[vertex]); 27 | } 28 | 29 | void unionVertices(vector& parent, int x, int y) { 30 | int rootX = findParent(parent, x); 31 | int rootY = findParent(parent, y); 32 | parent[rootX] = rootY; 33 | } 34 | 35 | void kruskalMST() { 36 | // Sort edges by weight 37 | sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) { 38 | return a.weight < b.weight; 39 | }); 40 | 41 | vector parent(V, -1); 42 | vector mst; 43 | 44 | for (const Edge& edge : edges) { 45 | int rootSrc = findParent(parent, edge.src); 46 | int rootDest = findParent(parent, edge.dest); 47 | 48 | if (rootSrc != rootDest) { 49 | mst.push_back(edge); 50 | unionVertices(parent, rootSrc, rootDest); 51 | } 52 | } 53 | 54 | cout << "Minimum Spanning Tree (Kruskal's Algorithm):\n"; 55 | for (const Edge& edge : mst) { 56 | cout << edge.src << " - " << edge.dest << " : " << edge.weight << "\n"; 57 | } 58 | } 59 | }; 60 | 61 | int main() { 62 | Graph g(6); // Number of vertices 63 | 64 | // Adding edges with weights 65 | g.addEdge(0, 1, 4); 66 | g.addEdge(0, 2, 4); 67 | g.addEdge(1, 2, 2); 68 | g.addEdge(1, 3, 5); 69 | g.addEdge(2, 3, 1); 70 | g.addEdge(2, 4, 3); 71 | g.addEdge(3, 4, 7); 72 | 73 | g.kruskalMST(); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Graphs/Traveling Salesman Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | const int INF = numeric_limits::max(); 9 | 10 | int tsp(vector>& graph, int start, int mask, vector>& dp) { 11 | int n = graph.size(); 12 | 13 | if (mask == (1 << n) - 1) { 14 | return graph[start][0]; 15 | } 16 | 17 | if (dp[start][mask] != -1) { 18 | return dp[start][mask]; 19 | } 20 | 21 | int minCost = INF; 22 | 23 | for (int next = 0; next < n; next++) { 24 | if ((mask & (1 << next)) == 0 && graph[start][next] != 0) { 25 | int newMask = mask | (1 << next); 26 | int cost = graph[start][next] + tsp(graph, next, newMask, dp); 27 | minCost = min(minCost, cost); 28 | } 29 | } 30 | 31 | dp[start][mask] = minCost; 32 | return minCost; 33 | } 34 | 35 | int main() { 36 | vector> graph = { 37 | {0, 29, 20, 21}, 38 | {29, 0, 15, 17}, 39 | {20, 15, 0, 28}, 40 | {21, 17, 28, 0} 41 | }; 42 | 43 | int n = graph.size(); 44 | vector> dp(n, vector(1 << n, -1)); 45 | 46 | int start = 0; 47 | int mask = 1; // Start with the first city 48 | int minCost = tsp(graph, start, mask, dp); 49 | 50 | cout << "Minimum TSP cost: " << minCost << endl; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Leetcode/1009. Complement of Base 10.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bitwiseComplement(int n) { 4 | int m = n; 5 | int mask = 0; 6 | 7 | if(n == 0) 8 | return 1; 9 | 10 | while(m!=0){ 11 | mask = (mask << 1) | 1; 12 | m = m >> 1; 13 | } 14 | 15 | int ans = (~n) & mask; 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Leetcode/15. 3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | //a+b+c=0 5 | //b+c=-a 6 | sort(nums.begin(),nums.end()); 7 | vector>ans; 8 | for(int i=0;i0 && nums[i]!=nums[i-1])){ 10 | int l=i+1, h=nums.size()-1; 11 | int sum=0-nums[i]; 12 | while(ltemp={nums[i], nums[l], nums[h]}; 15 | ans.push_back(temp); 16 | 17 | while(l dp; 7 | long long ans = power20(n/2LL, dp); 8 | 9 | if (n & 1LL) { 10 | ans = ((ans%MOD) * 5LL)%MOD; 11 | } 12 | 13 | return (int)ans%MOD; 14 | } 15 | 16 | long long power20(long long n, unordered_map &dp) { 17 | if(dp[n]!=0LL) { 18 | return dp[n]; 19 | } 20 | 21 | if (n == 0LL) { 22 | return (dp[0LL] = 1LL); 23 | } 24 | if (n == 1LL) { 25 | return (dp[1LL] = 20LL); 26 | } 27 | 28 | long long ans = 1LL, comp = 1LL; 29 | while (comp) { 30 | if (n & comp) { 31 | ans = ((ans%MOD) * 20LL)%MOD; 32 | ans = ((ans%MOD) * (power20(comp - 1, dp)%MOD))%MOD; 33 | } 34 | comp = comp << 1; 35 | } 36 | 37 | return (dp[n] = (ans%MOD)); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode/264. Ugly Number II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | vector dp(n); 5 | dp[0]=1; 6 | int x=0, y=0, z=0; 7 | for(int i=1; i> mp={ 3 | {1000000000,"Billion"},{1000000,"Million"},{1000,"Thousand"},{100,"Hundred"},{90,"Ninety"},{80,"Eighty"},{70,"Seventy"},{60,"Sixty"},{50,"Fifty"},{40,"Forty"},{30,"Thirty"},{20,"Twenty"},{19,"Nineteen"},{18,"Eighteen"},{17,"Seventeen"},{16,"Sixteen"},{15,"Fifteen"},{14,"Fourteen"},{13,"Thirteen"},{12,"Twelve"},{11,"Eleven"},{10,"Ten"},{9,"Nine"},{8,"Eight"},{7,"Seven"},{6,"Six"},{5,"Five"},{4,"Four"},{3,"Three"},{2,"Two"},{1,"One"},{0,"Zero"}}; 4 | public: 5 | string numberToWords(int num) { 6 | for(auto it:mp){ 7 | if(num>=it.first){ 8 | string a=""; 9 | if(num>=100){ 10 | a=numberToWords(num/it.first)+" "; 11 | } 12 | string b=it.second; 13 | string c=""; 14 | if(num!=0&&(num%it.first)!=0) 15 | c=" "+numberToWords(num%it.first); 16 | return a+b+c; 17 | } 18 | } 19 | return ""; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode/274. H-Index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | // Step 1 5 | sort(citations.begin(), citations.end()); 6 | // Step 2 7 | int h = citations.size(); 8 | // Step 3 9 | for (int i = 0; i < citations.size(); i++) { 10 | // Step 4 11 | if (citations[i] >= h) { 12 | // Step 5: 13 | return h; 14 | } 15 | else { 16 | // Step 6: 17 | if (h == 1 && citations[i] != 0) 18 | return 1; 19 | h--; 20 | } 21 | } 22 | return h; 23 | } 24 | }; -------------------------------------------------------------------------------- /Leetcode/289. Game of Life.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNeighbours(vector>& board, int row,int col){ 4 | int n=board.size(); 5 | int m=board[0].size(); 6 | int delrow[8]={0,1,0,-1,1,1,-1,-1}; 7 | int delcol[8]={1,0,-1,0,-1,1,1,-1}; 8 | int count=0; 9 | for(int i=0;i<8;i++){ 10 | int nrow=delrow[i]+row; 11 | int ncol=delcol[i]+col; 12 | if(nrow>=0 && nrow=0 && ncol>& board) { 19 | int n=board.size(); 20 | int m=board[0].size(); 21 | vector> curr = board; 22 | for(int i=0;i3) && board[i][j]==1){ 25 | board[i][j]=0; 26 | } 27 | else if(countNeighbours(curr,i,j)==3 && board[i][j]==0){ 28 | board[i][j]=1; 29 | } 30 | else if((countNeighbours(curr,i,j)==2 || countNeighbours(curr,i,j)==3) && board[i][j]==1){ 31 | board[i][j]=1; 32 | } 33 | } 34 | } 35 | } 36 | }; -------------------------------------------------------------------------------- /Leetcode/297. Serialize and Deserialize Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Codec { 2 | public: 3 | 4 | // Encodes a tree to a single string. 5 | string serialize(TreeNode* root) { 6 | if (!root) return "#,"; 7 | return to_string(root->val)+","+ serialize(root->left) + serialize(root->right); 8 | } 9 | 10 | // Decodes your encoded data to tree. 11 | TreeNode* deserialize(string data) { 12 | if (data == "#,") return nullptr; 13 | stringstream s(data); 14 | return helper(s); 15 | } 16 | 17 | TreeNode* helper (stringstream & s) { 18 | string str; 19 | getline(s, str, ','); 20 | if (str == "#") return nullptr; 21 | TreeNode* root = new TreeNode (stoi(str)); 22 | root->left = helper(s); 23 | root->right = helper(s); 24 | return root; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Leetcode/3.LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | int i=0, j=0; 5 | int maxi=0; 6 | setst; 7 | while(jmaxi) maxi=j-i+1; 11 | st.insert(s[j]); 12 | j++; 13 | } 14 | else{ 15 | st.erase(s[i]); 16 | i++; 17 | } 18 | } 19 | return maxi; 20 | } 21 | }; -------------------------------------------------------------------------------- /Leetcode/347-Top K frequent Elements: -------------------------------------------------------------------------------- 1 | Intuition 2 | In these problem we have to find k elements which appeared most frequantly. 3 | 4 | Approach 5 | This code is an implementation of a solution to the "Top K Frequent Elements" problem. Given an array of integers nums and an integer k, the task is to return the top k frequent elements in the array. 6 | The implementation uses a combination of unordered_map, multimap, and a vector to solve the problem efficiently. 7 | The unordered_map mp is used to count the frequency of each element in the nums array. The key represents the element, and the value represents its frequency. 8 | The code then creates a multimap m to store the frequency-element pairs from the mp map. The multimap is used to sort the pairs in descending order of frequency. The key represents the frequency, and the value represents the element. 9 | Next, a vector ans of size k is created to store the top k frequent elements. The initial values of the vector elements are set to 0. 10 | The code iterates over the pairs in the m multimap. It assigns the elements to the ans vector in descending order of frequency. The variable cnt keeps track of the current position in the ans vector. The loop breaks once cnt reaches k. 11 | Finally, the ans vector, containing the top k frequent elements, is returned as the solution to the problem. 12 | 13 | Complexity 14 | Time complexity:O(nlogn)O(n log n)O(nlogn) 15 | Space complexity:O(n)O(n)O(n) 16 | 17 | 18 | Code 19 | class Solution { 20 | public: 21 | vector topKFrequent(vector& nums, int k) { 22 | vectorans(k,0); 23 | unordered_mapmp; 24 | for(auto &i:nums){ 25 | mp[i]++; 26 | } 27 | multimap>m; 28 | for(auto &j:mp){ 29 | m.insert({j.second,j.first}); 30 | } 31 | int cnt=0; 32 | for(auto &i:m){ 33 | ans[cnt]=i.second; 34 | cnt++; 35 | if(cnt==k)break; 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode/367. Valid Perfect Square.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPerfectSquare(int num) { 4 | if (num < 2) { 5 | return true; 6 | } 7 | 8 | long long left = 1; 9 | long long right = num; 10 | 11 | while (left <= right) { 12 | long long mid = left + (right - left) / 2; 13 | long long square = mid * mid; 14 | 15 | if (square == num) { 16 | return true; 17 | } else if (square < num) { 18 | left = mid + 1; 19 | } else { 20 | right = mid - 1; 21 | } 22 | } 23 | 24 | return false; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /Leetcode/37Sudoku Solver.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool helpmeValid(vector>& board, int row, int col, char x) 4 | { 5 | for(int i=0;i<9;i++) 6 | { 7 | if (board[i][col] == x) return false; 8 | if (board[row][i] == x) return false; 9 | 10 | //formula: 11 | if (board[3 * (row/3) + i/3][3 * (col/3) + i%3] == x) return false; 12 | } 13 | return true; 14 | } 15 | 16 | 17 | bool helpme(vector>& board) 18 | { 19 | for (int i=0;i>& board) 43 | { 44 | helpme(board); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode/4. Median of Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | int n = nums1.size(); 5 | int m = nums2.size(); 6 | 7 | // Merge the arrays into a single sorted array. 8 | vector merged; 9 | for (int i = 0; i < n; i++) { 10 | merged.push_back(nums1[i]); 11 | } 12 | for (int i = 0; i < m; i++) { 13 | merged.push_back(nums2[i]); 14 | } 15 | 16 | // Sort the merged array. 17 | sort(merged.begin(), merged.end()); 18 | 19 | // Calculate the total number of elements in the merged array. 20 | int total = merged.size(); 21 | 22 | if (total % 2 == 1) { 23 | // If the total number of elements is odd, return the middle element as the median. 24 | return static_cast(merged[total / 2]); 25 | } else { 26 | // If the total number of elements is even, calculate the average of the two middle elements as the median. 27 | int middle1 = merged[total / 2 - 1]; 28 | int middle2 = merged[total / 2]; 29 | return (static_cast(middle1) + static_cast(middle2)) / 2.0; 30 | } 31 | } 32 | }; -------------------------------------------------------------------------------- /Leetcode/42TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int n = height.size(); 5 | int lmax = height[0]; 6 | int rmax = height[n-1]; 7 | int lpos = 1; 8 | int rpos = n-2; 9 | int water = 0; 10 | while(lpos <= rpos) 11 | { 12 | if(height[lpos] >= lmax) 13 | { 14 | lmax = height[lpos]; 15 | lpos++; 16 | } 17 | else if(height[rpos] >= rmax) 18 | { 19 | rmax = height[rpos]; 20 | rpos--; 21 | } 22 | else if(lmax <= rmax && height[lpos] < lmax) 23 | { 24 | water += lmax - height[lpos]; 25 | lpos++; 26 | } 27 | else 28 | { 29 | water += rmax - height[rpos]; 30 | rpos--; 31 | } 32 | 33 | } 34 | return water; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Leetcode/5.LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool check(int i, int j, string &s){ 4 | while(i max){ 22 | max=j-i+1; 23 | starting_index=i; 24 | } 25 | } 26 | } 27 | } 28 | return s.substr(starting_index,max); 29 | } 30 | }; -------------------------------------------------------------------------------- /Leetcode/785-Is Graph Bipartite: -------------------------------------------------------------------------------- 1 | Intuition 2 | Int these quostion we use concept of graph coloring using two colorss.If we are able to color the graph by only two colors than we can say that graph is bipartite. 3 | 4 | Approach 5 | This code implements a solution to the "Is Graph Bipartite?" problem. The problem asks whether it is possible to divide a given undirected graph into two sets such that every edge of the graph connects a vertex from one set to a vertex in the other set. 6 | The implementation uses a modified breadth-first search (BFS) approach to traverse the graph and determine if it can be bipartite. It uses a queue q to store the vertices to be processed. 7 | The main function isBipartite initializes a vector vis of the same size as the graph, representing the visited status of each vertex. The values in vis are initialized to 0, indicating that no vertices have been visited yet. 8 | The function then iterates over each vertex in the graph. If a vertex has not been visited (vis[i] == 0), it is assigned to the first set by setting vis[i] to 1. The adjacent vertices of the current vertex i are added to the queue q, and their visited status is set to -1, indicating they belong to the second set. 9 | The function then calls the fun function, passing the graph g, the visited vector vis, and the queue q. The fun function performs a modified BFS to check if the graph is bipartite. 10 | In the fun function, while the queue q is not empty, it dequeues a vertex i. If the visited status of i is 1, it iterates over its adjacent vertices. If any adjacent vertex j is also assigned to the first set (vis[j] == 1), it means there is an edge within the same set, violating the bipartite property, so the function returns false. If j is not visited (vis[j] == 0), it assigns it to the second set by setting vis[j] to -1 and enqueues j. 11 | If the visited status of i is -1, it performs a similar check but for vertices assigned to the second set. If any adjacent vertex j is assigned to the second set (vis[j] == -1), it returns false. If j is not visited (vis[j] == 0), it assigns it to the first set by setting vis[j] to 1 and enqueues j. 12 | If the loop completes without any issues, it means the graph can be bipartite, and the function returns true. 13 | Overall, the code checks if a given graph is bipartite by assigning vertices to two sets and performing a modified BFS to validate the bipartite property. 14 | 15 | Complexity 16 | Time complexity:O(V+E)O(V + E)O(V+E) 17 | The time complexity of the code is O(V+E)O(V + E)O(V+E), where V is the number of vertices in the graph and E is the number of edges. This is because the code performs a modified BFS traversal of the graph, visiting each vertex and its adjacent vertices once. In the worst case, all vertices and edges of the graph will be visited. 18 | 19 | Space complexity: O(V)O(V)O(V) 20 | The space complexity of the code is O(V)O(V)O(V), where V is the number of vertices in the graph. This is because the code uses additional space to store the visited status of each vertex in the vis vector, which has a size equal to the number of vertices. Additionally, the code uses a queue to store the vertices to be processed during the BFS traversal. The maximum number of vertices that can be in the queue at any point is V. Therefore, the overall space complexity is O(V)O(V)O(V). 21 | 22 | 23 | Code 24 | class Solution { 25 | public: 26 | bool fun(vector>&g, vector&vis,queue&q){ 27 | while(!q.empty()){ 28 | int i=q.front(); 29 | q.pop(); 30 | if(vis[i]==1){ 31 | for(auto &j:g[i]){ 32 | if(vis[j]==1){ 33 | return false; 34 | } 35 | if(vis[j]==0){ 36 | vis[j]=-1; 37 | q.push(j); 38 | } 39 | } 40 | } 41 | else if(vis[i]==-1){ 42 | for(auto &j:g[i]){ 43 | if(vis[j]==-1){ 44 | return false; 45 | } 46 | if(vis[j]==0){ 47 | vis[j]=1; 48 | q.push(j); 49 | } 50 | } 51 | } 52 | } 53 | return true; 54 | } 55 | bool isBipartite(vector>& g) { 56 | vectorvis(g.size(),0); 57 | queueq; 58 | for(int i=0;i nextSmallerElement(vector &heights, int n){ 4 | vector next(n); 5 | stack st; 6 | st.push(-1); 7 | for(int i = n-1; i>=0; i--){ 8 | while(st.top() != -1 && heights[st.top()] >= heights[i]) 9 | { 10 | st.pop(); 11 | } 12 | next[i] = st.top(); 13 | st.push(i); 14 | } 15 | return next; 16 | } 17 | 18 | vector prevSmallerElement(vector &heights, int n){ 19 | vector prev(n); 20 | stack st; 21 | st.push(-1); 22 | for(int i = 0; i < n; i++){ 23 | while(st.top() != -1 && heights[st.top()] >= heights[i]){ 24 | st.pop(); 25 | } 26 | prev[i] = st.top(); 27 | st.push(i); 28 | } 29 | return prev; 30 | } 31 | 32 | int largestRectangleArea(vector& heights) { 33 | int n = heights.size(); 34 | vector next(n); 35 | vector prev(n); 36 | next = nextSmallerElement(heights, n); 37 | prev = prevSmallerElement(heights, n); 38 | int area = INT_MIN; 39 | for(int i = 0; i < n; i++){ 40 | int l = heights[i]; 41 | if(next[i] == -1) 42 | next[i] = n; 43 | int b = next[i] - prev[i] - 1; 44 | int newarea = l*b; 45 | area = max(area, newarea); 46 | } 47 | return area; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Leetcode/DungeonGame.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculateMinimumHP(vector > &dungeon) { 4 | int M = dungeon.size(); 5 | int N = dungeon[0].size(); 6 | // hp[i][j] represents the min hp needed at position (i, j) 7 | // Add dummy row and column at bottom and right side 8 | vector > hp(M + 1, vector(N + 1, INT_MAX)); 9 | hp[M][N - 1] = 1; 10 | hp[M - 1][N] = 1; 11 | for (int i = M - 1; i >= 0; i--) { 12 | for (int j = N - 1; j >= 0; j--) { 13 | int need = min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j]; 14 | hp[i][j] = need <= 0 ? 1 : need; 15 | } 16 | } 17 | return hp[0][0]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode/Max_subarray_sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * This is solution of the question on leetcode 3 | * (https://leetcode.com/problems/maximum-subarray/description/) 4 | * 5 | * NOTE: This is of O(n) time complexity. Hence not ideal for large datasets. 6 | * 7 | * @author abhishek14104(https://github.com/Abhishek14104) 8 | */ 9 | 10 | 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | int main(void) 16 | { 17 | int count; 18 | cin >> count; 19 | 20 | int nums[count]; 21 | for (int i = 0; i < count; i++) 22 | cin >> nums[i]; 23 | 24 | int currsum[count+1]; 25 | currsum[0] = 0; 26 | for(int i = 0; i 3 | #include 4 | using namespace std; 5 | 6 | const int R = 3; 7 | const int C = 5; 8 | // Check if i, j is under the array limits of row and column 9 | bool issafe(int i, int j) 10 | { 11 | if (i >= 0 && i < R && j >= 0 && j < C) 12 | return true; 13 | return false; 14 | } 15 | int rotOranges(int v[R][C]) 16 | { 17 | bool changed = false; 18 | int no = 2; 19 | while (true) { 20 | for (int i = 0; i < R; i++) { 21 | for (int j = 0; j < C; j++) { 22 | // Rot all other oranges present at 23 | // (i+1, j), (i, j-1), (i, j+1), (i-1, j) 24 | if (v[i][j] == no) { 25 | if (issafe(i + 1, j) 26 | && v[i + 1][j] == 1) { 27 | v[i + 1][j] = v[i][j] + 1; 28 | changed = true; 29 | } 30 | if (issafe(i, j + 1) 31 | && v[i][j + 1] == 1) { 32 | v[i][j + 1] = v[i][j] + 1; 33 | changed = true; 34 | } 35 | if (issafe(i - 1, j) 36 | && v[i - 1][j] == 1) { 37 | v[i - 1][j] = v[i][j] + 1; 38 | changed = true; 39 | } 40 | if (issafe(i, j - 1) 41 | && v[i][j - 1] == 1) { 42 | v[i][j - 1] = v[i][j] + 1; 43 | changed = true; 44 | } 45 | } 46 | } 47 | } 48 | // if no rotten orange found it means all 49 | // oranges rottened now 50 | if (!changed) 51 | break; 52 | changed = false; 53 | no++; 54 | } 55 | for (int i = 0; i < R; i++) { 56 | for (int j = 0; j < C; j++) { 57 | 58 | // if any orange is found to be 59 | // not rotten then ans is not possible 60 | if (v[i][j] == 1) 61 | return -1; 62 | } 63 | } 64 | // Because initial value for a rotten 65 | // orange was 2 66 | return no - 2; 67 | } 68 | int main() 69 | { 70 | int v[R][C] = { { 2, 1, 0, 2, 1 }, 71 | { 1, 0, 1, 2, 1 }, 72 | { 1, 0, 0, 2, 1 } }; 73 | 74 | cout << "Max time incurred: " << rotOranges(v); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Linked List/LRU_Cache.cpp: -------------------------------------------------------------------------------- 1 | // LRU Cache 2 | // https://practice.geeksforgeeks.org/problems/lru-cache/1# 3 | 4 | #include 5 | using namespace std; 6 | 7 | class LRUCache { 8 | public: 9 | class Node { 10 | public: 11 | int key; 12 | int val; 13 | Node* next; 14 | Node* prev; 15 | Node(int _key, int _val) { 16 | key = _key; 17 | val = _val; 18 | } 19 | }; 20 | 21 | Node* head = new Node(-1,-1); 22 | Node* tail = new Node(-1,-1); 23 | 24 | int cap; 25 | unordered_mapm; 26 | 27 | LRUCache(int capacity) { 28 | cap = capacity; 29 | head->next = tail; 30 | tail->prev = head; 31 | } 32 | 33 | void addNode(Node* newNode) { 34 | Node* temp = head->next; 35 | newNode->next = temp; 36 | newNode->prev = head; 37 | head->next = newNode; 38 | temp->prev = newNode; 39 | } 40 | 41 | void deleteNode(Node* delNode) { 42 | Node* delprev = delNode->prev; 43 | Node* delnext = delNode->next; 44 | delprev->next = delnext; 45 | delnext->prev = delprev; 46 | } 47 | 48 | int get(int key_) { 49 | if (m.find(key_) != m.end()) { 50 | Node* resNode = m[key_]; 51 | int res = resNode->val; 52 | m.erase(key_); 53 | deleteNode(resNode); 54 | addNode(resNode); 55 | m[key_] = head->next; 56 | return res; 57 | } 58 | 59 | return -1; 60 | } 61 | 62 | void put(int key_, int value) { 63 | if(m.find(key_) != m.end()) { 64 | Node* existingNode = m[key_]; 65 | m.erase(key_); 66 | deleteNode(existingNode); 67 | } 68 | if(m.size() == cap) { 69 | m.erase(tail->prev->key); 70 | deleteNode(tail->prev); 71 | } 72 | 73 | addNode(new Node(key_, value)); 74 | m[key_] = head->next; 75 | } 76 | }; 77 | 78 | /** 79 | * Your LRUCache object will be instantiated and called as such: 80 | * LRUCache* obj = new LRUCache(capacity); 81 | * int param_1 = obj->get(key); 82 | * obj->put(key,value); 83 | */ 84 | -------------------------------------------------------------------------------- /Linked List/Priyanshu linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Node { 4 | public: 5 | int data; 6 | Node* next; 7 | 8 | Node(int data) : data(data), next(nullptr) {} 9 | }; 10 | 11 | class LinkedList { 12 | public: 13 | Node* head; 14 | 15 | LinkedList() : head(nullptr) {} 16 | 17 | // Function to add a node at the end of the linked list 18 | void append(int data) { 19 | Node* newNode = new Node(data); 20 | if (!head) { 21 | head = newNode; 22 | return; 23 | } 24 | 25 | Node* current = head; 26 | while (current->next) { 27 | current = current->next; 28 | } 29 | 30 | current->next = newNode; 31 | } 32 | 33 | // Function to display the linked list 34 | void display() { 35 | Node* current = head; 36 | while (current) { 37 | std::cout << current->data << " -> "; 38 | current = current->next; 39 | } 40 | std::cout << "nullptr" << std::endl; 41 | } 42 | 43 | // Function to perform selection sort on the linked list 44 | void selectionSort() { 45 | Node* current = head; 46 | 47 | while (current) { 48 | Node* min = current; 49 | Node* temp = current->next; 50 | 51 | while (temp) { 52 | if (temp->data < min->data) { 53 | min = temp; 54 | } 55 | temp = temp->next; 56 | } 57 | 58 | // Swap the data of 'current' and 'min' 59 | int tempData = current->data; 60 | current->data = min->data; 61 | min->data = tempData; 62 | 63 | current = current->next; 64 | } 65 | } 66 | }; 67 | 68 | int main() { 69 | LinkedList list; 70 | list.append(64); 71 | list.append(34); 72 | list.append(25); 73 | list.append(12); 74 | list.append(22); 75 | 76 | std::cout << "Original linked list: "; 77 | list.display(); 78 | 79 | list.selectionSort(); 80 | 81 | std::cout << "Linked list after selection sort: "; 82 | list.display(); 83 | 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /Math/Create-Factorial-of-number.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Cpp program for factorial of a number 3 | #include 4 | using namespace std; 5 | 6 | // function to find factorial of given number 7 | unsigned int factorial(unsigned int n) 8 | { 9 | int res = 1, i; 10 | for (i = 2; i <= n; i++) 11 | res *= i; 12 | return res; 13 | } 14 | 15 | // Driver code 16 | int main() 17 | { 18 | int num = 5; 19 | cout << "Factorial of " 20 | << num << " is " 21 | << factorial(num) << endl; 22 | return 0; 23 | } 24 | //Contributed by Saptash Chaubey 25 | -------------------------------------------------------------------------------- /Math/Matrix Chain Multiplication.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int matrixChainMultiplication(vector dimensions) { 7 | int n = dimensions.size() - 1; 8 | vector> dp(n, vector(n, 0)); 9 | 10 | for (int len = 2; len <= n; len++) { 11 | for (int i = 0; i < n - len + 1; i++) { 12 | int j = i + len - 1; 13 | dp[i][j] = INT_MAX; 14 | 15 | for (int k = i; k < j; k++) { 16 | int cost = dp[i][k] + dp[k + 1][j] + dimensions[i] * dimensions[k + 1] * dimensions[j + 1]; 17 | if (cost < dp[i][j]) { 18 | dp[i][j] = cost; 19 | } 20 | } 21 | } 22 | } 23 | 24 | return dp[0][n - 1]; 25 | } 26 | 27 | int main() { 28 | vector dimensions = {10, 30, 5, 60}; 29 | int minCost = matrixChainMultiplication(dimensions); 30 | cout << "Minimum number of multiplications: " << minCost << endl; 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Math/armstrong.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int num, originalNum, remainder, n = 0, result = 0, power; 8 | cout << "Enter an integer: "; 9 | cin >> num; 10 | 11 | originalNum = num; 12 | 13 | while (originalNum != 0) { 14 | originalNum /= 10; 15 | ++n; 16 | } 17 | originalNum = num; 18 | 19 | while (originalNum != 0) { 20 | remainder = originalNum % 10; 21 | 22 | // pow() returns a double value 23 | // round() returns the equivalent int 24 | power = round(pow(remainder, n)); 25 | result += power; 26 | originalNum /= 10; 27 | } 28 | 29 | if (result == num) 30 | cout << num << " is an Armstrong number."; 31 | else 32 | cout << num << " is not an Armstrong number."; 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Math/fibonacci_no.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fib(int n) { 5 | if(n == 0 || n == 1) { 6 | return n; 7 | } 8 | return fib(n-1) + fib(n-2); 9 | } 10 | 11 | // prints the nth fibonacci number 12 | int main() { 13 | int n; 14 | cin >> n; 15 | cout << fib(n) << endl; 16 | return 0; 17 | } -------------------------------------------------------------------------------- /Math/odd_even.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | int a,b; 4 | printf("Enter a number\n"); 5 | scanf("%d", &a); 6 | if(a%2 == 0){ 7 | printf("%d is even\n"); 8 | 9 | } 10 | else{ 11 | printf("%d is odd\n"); 12 | } 13 | return 0; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Math/pascal_triangle2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | int main(){ 5 | int n; 6 | cout<<"enter the rows : "; 7 | cin>>n; 8 | vector > v(n,vector(n,1)); 9 | for(int i=0;i 2 | using namespace std; 3 | 4 | void prime(int n) { 5 | int i; 6 | for(i=2;i> n; 21 | prime(n); 22 | return 0; 23 | } -------------------------------------------------------------------------------- /Math/reversenumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | int n, reversed_number = 0, remainder; 7 | 8 | cout << "Enter an integer: "; 9 | cin >> n; 10 | 11 | while(n != 0) { 12 | remainder = n % 10; 13 | reversed_number = reversed_number * 10 + remainder; 14 | n /= 10; 15 | } 16 | 17 | cout << "Reversed Number = " << reversed_number; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Math/sieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //this is a more efficient way to print the prime numbers upto 'n'; 5 | 6 | int main(void){ 7 | int n; 8 | cin >> n; 9 | 10 | 11 | int arr[n]; 12 | 13 | for(int i = 1; i<=n ; i++) 14 | { 15 | arr[i-1] = 0; 16 | } 17 | 18 | for (int i = 2; i*i <= n; i++) 19 | { 20 | if (arr[i-1] == 0) 21 | { 22 | int j = i*i; 23 | int c = i+1; 24 | while(j <= n){ 25 | arr[j-1] = 1; 26 | j = i*c; 27 | c++; 28 | } 29 | } 30 | } 31 | 32 | for(int i = 0; i < n; i++) 33 | { 34 | if(arr[i] == 0) 35 | cout << i+1 << " "; 36 | } 37 | cout << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest2023 2 | here you can contribute dsa question in cpp 3 | -------------------------------------------------------------------------------- /Searching/Binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int binarysearch(vector&v,int target){ 6 | int l = 0; 7 | int h = v.size()-1; 8 | while(l<=h){ 9 | int mid = (l+h)/2; 10 | if(v[mid]==target) return mid; 11 | else if(v[mid]v={2,3,76,34,28,26,18}; 20 | // sort(v.begin(),v.end()); 21 | // int target ; 22 | // cin>>target; 23 | // cout<>n>>target; 29 | // vectorv; 30 | // for(int i=0;i>x; 33 | // v.push_back(x); 34 | // } 35 | // cout< 5 | 6 | 7 | 8 | int search(int arr[], int N, int x) 9 | { 10 | 11 | for (int i = 0; i < N; i++) 12 | 13 | if (arr[i] == x) 14 | 15 | return i; 16 | 17 | return -1; 18 | } 19 | 20 | 21 | // Driver code 22 | 23 | int main(void) 24 | { 25 | 26 | int arr[] = { 2, 3, 4, 10, 40 }; 27 | 28 | int x = 10; 29 | 30 | int N = sizeof(arr) / sizeof(arr[0]); 31 | 32 | 33 | 34 | // Function call 35 | 36 | int result = search(arr, N, x); 37 | 38 | (result == -1) 39 | 40 | ? printf("Element is not present in array") 41 | 42 | : printf("Element is present at index %d", result); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Sort elements by frequency.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Used for sorting by frequency. And if frequency is same, 5 | // then by appearance 6 | bool sortByVal(const pair& a, 7 | const pair& b) 8 | { 9 | 10 | // If frequency is same then sort by index 11 | if (a.second == b.second) 12 | return a.first < b.first; 13 | 14 | return a.second > b.second; 15 | } 16 | 17 | // function to sort elements by frequency 18 | vectorsortByFreq(int a[], int n) 19 | { 20 | 21 | vectorres; 22 | 23 | unordered_map m; 24 | 25 | vector > v; 26 | 27 | for (int i = 0; i < n; ++i) { 28 | 29 | // Map m is used to keep track of count 30 | // of elements in array 31 | m[a[i]]++; 32 | } 33 | 34 | // Copy map to vector 35 | copy(m.begin(), m.end(), back_inserter(v)); 36 | 37 | // Sort the element of array by frequency 38 | sort(v.begin(), v.end(), sortByVal); 39 | 40 | for (int i = 0; i < v.size(); ++i) 41 | while(v[i].second--) 42 | { 43 | res.push_back(v[i].first); 44 | } 45 | 46 | return res; 47 | } 48 | 49 | // Driver program 50 | int main() 51 | { 52 | 53 | int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; 54 | int n = sizeof(a) / sizeof(a[0]); 55 | vectorres; 56 | res = sortByFreq(a, n); 57 | 58 | for(int i = 0;i < res.size(); i++) 59 | cout< 3 | #include 4 | 5 | #define BEAD(i, j) beads[i * max + j] 6 | 7 | // function to perform the above algorithm 8 | void beadSort(int *a, int len) { 9 | // Find the maximum element 10 | int max = a[0]; 11 | for (int i = 1; i < len; i++) 12 | if (a[i] > max) 13 | max = a[i]; 14 | 15 | // allocating memory 16 | unsigned char *beads = new unsigned char[max * len]; 17 | memset(beads, 0, static_cast(max) * len); 18 | 19 | // mark the beads 20 | for (int i = 0; i < len; i++) 21 | for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; 22 | 23 | for (int j = 0; j < max; j++) { 24 | // count how many beads are on each post 25 | int sum = 0; 26 | for (int i = 0; i < len; i++) { 27 | sum += BEAD(i, j); 28 | BEAD(i, j) = 0; 29 | } 30 | 31 | // Move beads down 32 | for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; 33 | } 34 | 35 | // Put sorted values in array using beads 36 | for (int i = 0; i < len; i++) { 37 | int j; 38 | for (j = 0; j < max && BEAD(i, j); j++) { 39 | } 40 | 41 | a[i] = j; 42 | } 43 | delete[] beads; 44 | } 45 | 46 | // driver function to test the algorithm 47 | int main() { 48 | int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; 49 | int len = sizeof(a) / sizeof(a[0]); 50 | 51 | beadSort(a, len); 52 | 53 | for (int i = 0; i < len; i++) printf("%d ", a[i]); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Sorting/Bucketsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an 2 | // array using bucket sort 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // Function to sort arr[] of 10 | // size n using bucket sort 11 | 12 | void bucketSort(float arr[], int n) 13 | { 14 | 15 | 16 | // 1) Create n empty buckets 17 | 18 | vector b[n]; 19 | 20 | 21 | // 2) Put array elements 22 | 23 | // in different buckets 24 | 25 | for (int i = 0; i < n; i++) { 26 | 27 | 28 | // Index in bucket 29 | 30 | int bi = n * arr[i]; 31 | 32 | b[bi].push_back(arr[i]); 33 | 34 | } 35 | 36 | 37 | // 3) Sort individual buckets 38 | 39 | for (int i = 0; i < n; i++) 40 | 41 | sort(b[i].begin(), b[i].end()); 42 | 43 | 44 | // 4) Concatenate all buckets into arr[] 45 | 46 | int index = 0; 47 | 48 | for (int i = 0; i < n; i++) 49 | 50 | for (int j = 0; j < b[i].size(); j++) 51 | 52 | arr[index++] = b[i][j]; 53 | } 54 | 55 | // Driver program to test above function 56 | 57 | int main() 58 | { 59 | 60 | float arr[] 61 | 62 | = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 63 | 64 | int n = sizeof(arr) / sizeof(arr[0]); 65 | 66 | bucketSort(arr, n); 67 | 68 | 69 | cout << "Sorted array is \n"; 70 | 71 | for (int i = 0; i < n; i++) 72 | 73 | cout << arr[i] << " "; 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /Sorting/Heapsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Function to heapify a subtree rooted at a given index in the vector 5 | void heapify(std::vector& arr, int n, int root) { 6 | int largest = root; // Initialize the largest as the root 7 | int left = 2 * root + 1; // Index of the left child 8 | int right = 2 * root + 2; // Index of the right child 9 | 10 | // If the left child is larger than the root 11 | if (left < n && arr[left] > arr[largest]) 12 | largest = left; 13 | 14 | // If the right child is larger than the largest so far 15 | if (right < n && arr[right] > arr[largest]) 16 | largest = right; 17 | 18 | // If the largest is not the root, swap the root and the largest 19 | if (largest != root) { 20 | std::swap(arr[root], arr[largest]); 21 | 22 | // Recursively heapify the affected sub-tree 23 | heapify(arr, n, largest); 24 | } 25 | } 26 | 27 | // Main function to perform heap sort 28 | void heapSort(std::vector& arr) { 29 | int n = arr.size(); 30 | 31 | // Build a max heap 32 | for (int i = n / 2 - 1; i >= 0; i--) 33 | heapify(arr, n, i); 34 | 35 | // Extract elements from the heap one by one 36 | for (int i = n - 1; i > 0; i--) { 37 | // Move the current root (largest element) to the end 38 | std::swap(arr[0], arr[i]); 39 | 40 | // Call heapify on the reduced heap 41 | heapify(arr, i, 0); 42 | } 43 | } 44 | 45 | int main() { 46 | std::vector arr = {12, 11, 13, 5, 6, 7}; 47 | 48 | std::cout << "Original array: "; 49 | for (int num : arr) { 50 | std::cout << num << " "; 51 | } 52 | std::cout << std::endl; 53 | 54 | heapSort(arr); 55 | 56 | std::cout << "Sorted array: "; 57 | for (int num : arr) { 58 | std::cout << num << " "; 59 | } 60 | std::cout << std::endl; 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Sorting/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int *arr, int l, int mid, int r) { 5 | 6 | int n1 = mid-l+1; 7 | int n2 = r-mid; 8 | int a[n1]; 9 | int b[n2]; 10 | 11 | for(int i = 0; i < mid-l+1; i++) a[i] = arr[l+i]; 12 | for(int i = 0; i < r-mid; i++) b[i] = arr[mid+1+i]; 13 | 14 | int i = 0; 15 | int j = 0; 16 | int k = l; 17 | 18 | while(i < n1 && j < n2) { 19 | if (a[i] < b[j]) { 20 | arr[k] = a[i]; 21 | k++; i++; 22 | } 23 | else { 24 | arr[k] = b[j]; 25 | k++; j++; 26 | } 27 | } 28 | 29 | while(i < n1) { 30 | arr[k] = a[i]; 31 | k++; i++; 32 | } 33 | 34 | while(j < n2) { 35 | arr[k] = b[j]; 36 | k++; j++; 37 | } 38 | } 39 | 40 | void MergeSort(int *arr, int l, int r) { 41 | if (l < r) 42 | { 43 | int mid = (l+r)/2; 44 | MergeSort(arr, l, mid); 45 | MergeSort(arr, mid+1, r); 46 | 47 | merge(arr, l, mid, r); 48 | } 49 | 50 | } 51 | 52 | 53 | int main(void) { 54 | int arr[] = {6,3,9,4,5,2,8,7,1}; 55 | int l = 0; 56 | int r = sizeof(arr)/sizeof(arr[0]); 57 | MergeSort(arr,l,r-1); 58 | 59 | for(int i = 0; i < r; i++) { 60 | cout << arr[i] << " "; 61 | } 62 | } -------------------------------------------------------------------------------- /Sorting/Selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 29 | int arr[n]; //create an array with given number of elements 30 | cout << "Enter elements:" << endl; 31 | for(int i = 0; i> arr[i]; 33 | } 34 | cout << "Array before Sorting: "; 35 | display(arr, n); 36 | selectionSort(arr, n); 37 | cout << "Array after Sorting: "; 38 | display(arr, n); 39 | } 40 | -------------------------------------------------------------------------------- /Sorting/Topological_Sorting.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to print topological 2 | // sorting of a DAG 3 | #include 4 | using namespace std; 5 | 6 | // Class to represent a graph 7 | class Graph { 8 | // No. of vertices' 9 | int V; 10 | 11 | // Pointer to an array containing adjacency listsList 12 | list* adj; 13 | 14 | // A function used by topologicalSort 15 | void topologicalSortUtil(int v, bool visited[], 16 | stack& Stack); 17 | 18 | public: 19 | // Constructor 20 | Graph(int V); 21 | 22 | // function to add an edge to graph 23 | void addEdge(int v, int w); 24 | 25 | // prints a Topological Sort of 26 | // the complete graph 27 | void topologicalSort(); 28 | }; 29 | 30 | Graph::Graph(int V) 31 | { 32 | this->V = V; 33 | adj = new list[V]; 34 | } 35 | 36 | void Graph::addEdge(int v, int w) 37 | { 38 | // Add w to v’s list. 39 | adj[v].push_back(w); 40 | } 41 | 42 | // A recursive function used by topologicalSort 43 | void Graph::topologicalSortUtil(int v, bool visited[], 44 | stack& Stack) 45 | { 46 | // Mark the current node as visited. 47 | visited[v] = true; 48 | 49 | // Recur for all the vertices 50 | // adjacent to this vertex 51 | list::iterator i; 52 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 53 | if (!visited[*i]) 54 | topologicalSortUtil(*i, visited, Stack); 55 | 56 | // Push current vertex to stack 57 | // which stores result 58 | Stack.push(v); 59 | } 60 | 61 | // The function to do Topological Sort. 62 | // It uses recursive topologicalSortUtil() 63 | void Graph::topologicalSort() 64 | { 65 | stack Stack; 66 | 67 | // Mark all the vertices as not visited 68 | bool* visited = new bool[V]; 69 | for (int i = 0; i < V; i++) 70 | visited[i] = false; 71 | 72 | // Call the recursive helper function 73 | // to store Topological 74 | // Sort starting from all 75 | // vertices one by one 76 | for (int i = 0; i < V; i++) 77 | if (visited[i] == false) 78 | topologicalSortUtil(i, visited, Stack); 79 | 80 | // Print contents of stack 81 | while (Stack.empty() == false) { 82 | cout << Stack.top() << " "; 83 | Stack.pop(); 84 | } 85 | 86 | delete [] visited; 87 | } 88 | 89 | // Driver Code 90 | int main() 91 | { 92 | // Create a graph given in the above diagram 93 | Graph g(6); 94 | g.addEdge(5, 2); 95 | g.addEdge(5, 0); 96 | g.addEdge(4, 0); 97 | g.addEdge(4, 1); 98 | g.addEdge(2, 3); 99 | g.addEdge(3, 1); 100 | 101 | cout << "Following is a Topological Sort of the given " 102 | "graph \n"; 103 | 104 | // Function Call 105 | g.topologicalSort(); 106 | 107 | return 0; 108 | } 109 | -------------------------------------------------------------------------------- /Sorting/Treesort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Tree Sort 2 | #include 3 | 4 | 5 | 6 | using namespace std; 7 | 8 | 9 | 10 | struct Node 11 | { 12 | 13 | int key; 14 | 15 | struct Node *left, *right; 16 | }; 17 | 18 | 19 | // A utility function to create a new BST Node 20 | 21 | struct Node *newNode(int item) 22 | { 23 | 24 | struct Node *temp = new Node; 25 | 26 | temp->key = item; 27 | 28 | temp->left = temp->right = NULL; 29 | 30 | return temp; 31 | } 32 | 33 | 34 | // Stores inorder traversal of the BST 35 | // in arr[] 36 | 37 | void storeSorted(Node *root, int arr[], int &i) 38 | { 39 | 40 | if (root != NULL) 41 | 42 | { 43 | 44 | storeSorted(root->left, arr, i); 45 | 46 | arr[i++] = root->key; 47 | 48 | storeSorted(root->right, arr, i); 49 | 50 | } 51 | } 52 | 53 | 54 | /* A utility function to insert a new 55 | 56 | Node with given key in BST */ 57 | 58 | Node* insert(Node* node, int key) 59 | { 60 | 61 | /* If the tree is empty, return a new Node */ 62 | 63 | if (node == NULL) return newNode(key); 64 | 65 | 66 | 67 | /* Otherwise, recur down the tree */ 68 | 69 | if (key < node->key) 70 | 71 | node->left = insert(node->left, key); 72 | 73 | else if (key > node->key) 74 | 75 | node->right = insert(node->right, key); 76 | 77 | 78 | 79 | /* return the (unchanged) Node pointer */ 80 | 81 | return node; 82 | } 83 | 84 | 85 | // This function sorts arr[0..n-1] using Tree Sort 86 | 87 | void treeSort(int arr[], int n) 88 | { 89 | 90 | struct Node *root = NULL; 91 | 92 | 93 | 94 | // Construct the BST 95 | 96 | root = insert(root, arr[0]); 97 | 98 | for (int i=1; i 3 | using namespace std; 4 | 5 | // An optimized version of Bubble Sort 6 | void bubbleSort(int arr[], int n) 7 | { 8 | int i, j; 9 | bool swapped; 10 | for (i = 0; i < n - 1; i++) { 11 | swapped = false; 12 | for (j = 0; j < n - i - 1; j++) { 13 | if (arr[j] > arr[j + 1]) { 14 | swap(arr[j], arr[j + 1]); 15 | swapped = true; 16 | } 17 | } 18 | 19 | // If no two elements were swapped 20 | // by inner loop, then break 21 | if (swapped == false) 22 | break; 23 | } 24 | } 25 | 26 | // Function to print an array 27 | void printArray(int arr[], int size) 28 | { 29 | int i; 30 | for (i = 0; i < size; i++) 31 | cout << " " << arr[i]; 32 | } 33 | 34 | // Driver program to test above functions 35 | int main() 36 | { 37 | int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; 38 | int N = sizeof(arr) / sizeof(arr[0]); 39 | bubbleSort(arr, N); 40 | cout << "Sorted array: \n"; 41 | printArray(arr, N); 42 | return 0; 43 | } 44 | // This code is contributed by shivanisinghss2110 45 | -------------------------------------------------------------------------------- /Sorting/cyclicSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement cycle sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Function sort the array using Cycle sort 7 | 8 | void cycleSort(int arr[], int n) 9 | { 10 | 11 | // count number of memory writes 12 | 13 | int writes = 0; 14 | 15 | 16 | // traverse array elements and put it to on 17 | 18 | // the right place 19 | 20 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 21 | 22 | // initialize item as starting point 23 | 24 | int item = arr[cycle_start]; 25 | 26 | 27 | // Find position where we put the item. We basically 28 | 29 | // count all smaller elements on right side of item. 30 | 31 | int pos = cycle_start; 32 | 33 | for (int i = cycle_start + 1; i < n; i++) 34 | 35 | if (arr[i] < item) 36 | 37 | pos++; 38 | 39 | 40 | // If item is already in correct position 41 | 42 | if (pos == cycle_start) 43 | 44 | continue; 45 | 46 | 47 | // ignore all duplicate elements 48 | 49 | while (item == arr[pos]) 50 | 51 | pos += 1; 52 | 53 | 54 | // put the item to it's right position 55 | 56 | if (pos != cycle_start) { 57 | 58 | swap(item, arr[pos]); 59 | 60 | writes++; 61 | 62 | } 63 | 64 | 65 | // Rotate rest of the cycle 66 | 67 | while (pos != cycle_start) { 68 | 69 | pos = cycle_start; 70 | 71 | 72 | // Find position where we put the element 73 | 74 | for (int i = cycle_start + 1; i < n; i++) 75 | 76 | if (arr[i] < item) 77 | 78 | pos += 1; 79 | 80 | 81 | // ignore all duplicate elements 82 | 83 | while (item == arr[pos]) 84 | 85 | pos += 1; 86 | 87 | 88 | // put the item to it's right position 89 | 90 | if (item != arr[pos]) { 91 | 92 | swap(item, arr[pos]); 93 | 94 | writes++; 95 | 96 | } 97 | 98 | } 99 | 100 | } 101 | 102 | 103 | // Number of memory writes or swaps 104 | 105 | // cout << writes << endl ; 106 | } 107 | 108 | // Driver program to test above function 109 | 110 | int main() 111 | { 112 | 113 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 114 | 115 | int n = sizeof(arr) / sizeof(arr[0]); 116 | 117 | cycleSort(arr, n); 118 | 119 | 120 | cout << "After sort : " << endl; 121 | 122 | for (int i = 0; i < n; i++) 123 | 124 | cout << arr[i] << " "; 125 | 126 | return 0;} 127 | -------------------------------------------------------------------------------- /Sorting/exponential.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find an element x in a 2 | // sorted array using Exponential search. 3 | #include 4 | using namespace std; 5 | 6 | int binarySearch(int arr[], int, int, int); 7 | 8 | // Returns position of first occurrence of 9 | // x in array 10 | int exponentialSearch(int arr[], int n, int x) 11 | { 12 | // If x is present at first location itself 13 | if (arr[0] == x) 14 | return 0; 15 | 16 | // Find range for binary search by 17 | // repeated doubling 18 | int i = 1; 19 | while (i < n && arr[i] <= x) 20 | i = i*2; 21 | 22 | // Call binary search for the found range. 23 | return binarySearch(arr, i/2, 24 | min(i, n-1), x); 25 | } 26 | 27 | // A recursive binary search function. It returns 28 | // location of x in given array arr[l..r] is 29 | // present, otherwise -1 30 | int binarySearch(int arr[], int l, int r, int x) 31 | { 32 | if (r >= l) 33 | { 34 | int mid = l + (r - l)/2; 35 | 36 | // If the element is present at the middle 37 | // itself 38 | if (arr[mid] == x) 39 | return mid; 40 | 41 | // If element is smaller than mid, then it 42 | // can only be present n left subarray 43 | if (arr[mid] > x) 44 | return binarySearch(arr, l, mid-1, x); 45 | 46 | // Else the element can only be present 47 | // in right subarray 48 | return binarySearch(arr, mid+1, r, x); 49 | } 50 | 51 | // We reach here when element is not present 52 | // in array 53 | return -1; 54 | } 55 | 56 | // Driver code 57 | int main(void) 58 | { 59 | int arr[] = {2, 3, 4, 10, 40}; 60 | int n = sizeof(arr)/ sizeof(arr[0]); 61 | int x = 10; 62 | int result = exponentialSearch(arr, n, x); 63 | (result == -1)? cout <<"Element is not present in array" 64 | : cout <<"Element is present at index " << result; 65 | return 0; 66 | } 67 | 68 | // this code is contributed by shivanisinghss2110 69 | -------------------------------------------------------------------------------- /Sorting/insertion.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort an array using 7 | // insertion sort 8 | void insertionSort(int arr[], int n) 9 | { 10 | int i, key, j; 11 | for (i = 1; i < n; i++) { 12 | key = arr[i]; 13 | j = i - 1; 14 | 15 | // Move elements of arr[0..i-1], 16 | // that are greater than key, 17 | // to one position ahead of their 18 | // current position 19 | while (j >= 0 && arr[j] > key) { 20 | arr[j + 1] = arr[j]; 21 | j = j - 1; 22 | } 23 | arr[j + 1] = key; 24 | } 25 | } 26 | 27 | // A utility function to print an array 28 | // of size n 29 | void printArray(int arr[], int n) 30 | { 31 | int i; 32 | for (i = 0; i < n; i++) 33 | cout << arr[i] << " "; 34 | cout << endl; 35 | } 36 | 37 | // Driver code 38 | int main() 39 | { 40 | int arr[] = { 12, 11, 13, 5, 6 }; 41 | int N = sizeof(arr) / sizeof(arr[0]); 42 | 43 | insertionSort(arr, N); 44 | printArray(arr, N); 45 | 46 | return 0; 47 | } 48 | // This is code is contributed by rathbhupendra 49 | -------------------------------------------------------------------------------- /Sorting/median_trwo_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | if (A.size() > B.size()) 5 | return findMedianSortedArrays(B, A); 6 | 7 | int nA = A.size(), nB = B.size(); 8 | int l = 0, r = nA; 9 | 10 | while (l <= r) { 11 | int cutA = (l + r) / 2; 12 | int cutB = (nA + nB + 1) / 2 - cutA; 13 | 14 | int maxLeftA = (cutA == 0) ? INT_MIN : A[cutA - 1]; 15 | int minRightA = (cutA == nA) ? INT_MAX : A[cutA]; 16 | int maxLeftB = (cutB == 0) ? INT_MIN : B[cutB - 1]; 17 | int minRightB = (cutB == nB) ? INT_MAX : B[cutB]; 18 | 19 | if (maxLeftA <= minRightB && maxLeftB <= minRightA) { 20 | if ((nA + nB) % 2 == 0) return 21 | (max(maxLeftA, maxLeftB)+min(minRightA,minRightB))/2.0; 22 | else return max(maxLeftA, maxLeftB); 23 | } 24 | else if (maxLeftA > minRightB) 25 | r = cutA - 1; 26 | else 27 | l = cutA + 1; 28 | } 29 | return 0.0; 30 | } 31 | 32 | }; 33 | -------------------------------------------------------------------------------- /Sorting/quicksort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Implementation of the Quick Sort Algorithm. 2 | #include 3 | using namespace std; 4 | 5 | int partition(int arr[], int start, int end) 6 | { 7 | 8 | int pivot = arr[start]; 9 | 10 | int count = 0; 11 | for (int i = start + 1; i <= end; i++) { 12 | if (arr[i] <= pivot) 13 | count++; 14 | } 15 | 16 | // Giving pivot element its correct position 17 | int pivotIndex = start + count; 18 | swap(arr[pivotIndex], arr[start]); 19 | 20 | // Sorting left and right parts of the pivot element 21 | int i = start, j = end; 22 | 23 | while (i < pivotIndex && j > pivotIndex) { 24 | 25 | while (arr[i] <= pivot) { 26 | i++; 27 | } 28 | 29 | while (arr[j] > pivot) { 30 | j--; 31 | } 32 | 33 | if (i < pivotIndex && j > pivotIndex) { 34 | swap(arr[i++], arr[j--]); 35 | } 36 | } 37 | 38 | return pivotIndex; 39 | } 40 | 41 | void quickSort(int arr[], int start, int end) 42 | { 43 | 44 | // base case 45 | if (start >= end) 46 | return; 47 | 48 | // partitioning the array 49 | int p = partition(arr, start, end); 50 | 51 | // Sorting the left part 52 | quickSort(arr, start, p - 1); 53 | 54 | // Sorting the right part 55 | quickSort(arr, p + 1, end); 56 | } 57 | 58 | int main() 59 | { 60 | 61 | int arr[] = { 9, 3, 4, 2, 1, 8 }; 62 | int n = 6; 63 | 64 | quickSort(arr, 0, n - 1); 65 | 66 | for (int i = 0; i < n; i++) { 67 | cout << arr[i] << " "; 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Sorting/shellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Function of Shell Sort 7 | void shellSort(vector &arr) 8 | { 9 | int n = arr.size(); 10 | 11 | // Starting with a large gap and reducing it until it becomes 1 12 | for (int gap = n / 2; gap > 0; gap /= 2) 13 | { 14 | // Performing insertion sort for elements at the gap intervals 15 | for (int i = gap; i < n; i++) 16 | { 17 | int temp = arr[i]; 18 | int j; 19 | 20 | // Shift elements that are greater than temp by gap positions 21 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 22 | { 23 | arr[j] = arr[j - gap]; 24 | } 25 | 26 | // Placing temp in its correct position 27 | arr[j] = temp; 28 | } 29 | } 30 | } 31 | 32 | int main() 33 | { 34 | // Given Vector Array 35 | vector arr = {3, 3, 1, 0, 8, 2, 7, 4, 5}; 36 | 37 | cout << "Original Array: "; 38 | for (int num : arr) 39 | { 40 | cout << num << " "; 41 | } 42 | 43 | shellSort(arr); 44 | 45 | cout << "\nSorted Array: "; 46 | for (int num : arr) 47 | { 48 | cout << num << " "; 49 | } 50 | 51 | return 0; 52 | } 53 | 54 | // What is Shell Sort Algorithm? 55 | // Shell Sort works by gradually sorting elements that are far apart, and then reducing the gap between elements to achieve a more refined sorting until the gap becomes 1, which is essentially an insertion sort. This combination of sorting with large gaps and smaller gaps results in a more efficient sorting algorithm than a simple insertion sort for larger datasets. 56 | 57 | // How does the Shell Sort Algorithm works? 58 | 59 | // 1. Here, 'shellSort' is the main function that performs the Shell Sort algorithm on a vector of integers. 60 | // 2. It takes the input array by reference to modify it in place. 61 | // 3. The variable n stores the size of the array. 62 | // 4. The outer loop iterates over decreasing gap sizes starting with n/2 and reducing it by half in each iteration until 'gap' becomes 1. 63 | // 5. The inner loop performs an insertion sort for elements at gap intervals. 64 | // 6. For each element at index i, it is compared and swapped with elements that are 'gap' positions before it, until the correct position is found. 65 | // 7. The elements are shifted by 'gap' positions until the element 'temp' is placed in its correct sorted position. 66 | // 8. The main function demonstrates the sorting by initializing a vector with some values, calling shellSort, and then printing the sorted array. 67 | -------------------------------------------------------------------------------- /Sortvector.Cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to demonstrate sorting in vector 3 | // of pair according to 2nd element of pair 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Driver function to sort the vector elements 9 | // by second element of pairs 10 | 11 | bool sortbysec(const pair &a, 12 | 13 | const pair &b) 14 | { 15 | 16 | return (a.second < b.second); 17 | } 18 | 19 | 20 | int main() 21 | { 22 | 23 | // declaring vector of pairs 24 | 25 | vector< pair > vect; 26 | 27 | 28 | // Initialising 1st and 2nd element of pairs 29 | 30 | // with array values 31 | 32 | int arr[] = {10, 20, 5, 40 }; 33 | 34 | int arr1[] = {30, 60, 20, 50}; 35 | 36 | int n = sizeof(arr)/sizeof(arr[0]); 37 | 38 | 39 | // Entering values in vector of pairs 40 | 41 | for (int i=0; i q; 18 | q.push(root); 19 | 20 | while(!q.empty()){ 21 | int size = q.size(); 22 | minDepth++; 23 | 24 | while(size--){ 25 | TreeNode* cur = q.front(); 26 | q.pop(); 27 | if(cur->left) 28 | q.push(cur->left); 29 | if(cur->right) 30 | q.push(cur->right); 31 | if(cur->left == NULL && cur->right == NULL) 32 | return minDepth; 33 | } 34 | } 35 | return minDepth; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Tree/minheighttree.cpp: -------------------------------------------------------------------------------- 1 | // C++ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | // This class represents a undirected graph using adjacency list representation 10 | class Graph 11 | { 12 | public: 13 | int V; 14 | // Pointer to an array containing adjacency lists 15 | list *adj; 16 | // Vector which stores degree of all vertices 17 | vector degree; 18 | Graph(int V); // Constructor 19 | void addEdge(int v, int w); // To add an edge 20 | // function to get roots which give minimum height 21 | vector rootForMinimumHeight(); 22 | }; 23 | // Constructor of graph, initializes adjacency list and 24 | // degree vector 25 | Graph::Graph(int V) 26 | { 27 | this->V = V; 28 | adj = new list[V]; 29 | for (int i = 0; i < V; i++) 30 | degree.push_back(0); 31 | } 32 | // addEdge method adds vertex to adjacency list and increases 33 | // degree by 1 34 | void Graph::addEdge(int v, int w) 35 | { 36 | adj[v].push_back(w); 37 | adj[w].push_back(v); 38 | degree[v]++; // increment degree of v by 1 39 | degree[w]++; // increment degree of w by 1 40 | } 41 | // Method to return roots which gives minimum height to tree 42 | vector Graph::rootForMinimumHeight() 43 | { 44 | queue q; 45 | // first enqueue all leaf nodes in queue 46 | for (int i = 0; i < V; i++) 47 | if (degree[i] == 1) 48 | q.push(i); 49 | // loop until total vertex remains less than 2 50 | while (V > 2) 51 | { 52 | int popEle = q.size(); 53 | V -= popEle; // popEle number of vertices will be popped 54 | for (int i = 0; i < popEle; i++) 55 | { 56 | int t = q.front(); 57 | q.pop(); 58 | // for each neighbour, decrease its degree and 59 | // if it become leaf, insert into queue 60 | for (auto j = adj[t].begin(); j != adj[t].end(); j++) 61 | { 62 | degree[*j]--; 63 | if (degree[*j] == 1) 64 | q.push(*j); 65 | } 66 | } 67 | } 68 | // copying the result from queue to result vector 69 | vector res; 70 | while (!q.empty()) 71 | { 72 | res.push_back(q.front()); 73 | q.pop(); 74 | } 75 | return res; 76 | } 77 | int main() 78 | { 79 | Graph g(6); 80 | g.addEdge(0, 3); 81 | g.addEdge(1, 3); 82 | g.addEdge(2, 3); 83 | g.addEdge(4, 3); 84 | g.addEdge(5, 4); 85 | vector res = g.rootForMinimumHeight(); 86 | for (int i = 0; i < res.size(); i++) 87 | cout << res[i] << " "; 88 | cout << endl; 89 | } 90 | -------------------------------------------------------------------------------- /swap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int num1, num2, temp; 7 | 8 | cout << "Enter the first number: "; 9 | cin >> num1; 10 | 11 | cout << "Enter the second number: "; 12 | cin >> num2; 13 | 14 | cout << "The first number is " << num1 << endl; 15 | cout << "The second number is " << num2 << endl; 16 | 17 | temp = num1; 18 | num1 = num2; 19 | num2 = temp; 20 | 21 | cout << "The numbers have been swapped" << endl; 22 | cout << "The first number is " << num1 << endl; 23 | cout << "The second number is " << num2 << endl; 24 | 25 | return 0; 26 | } --------------------------------------------------------------------------------