├── .DS_Store ├── C# └── Sorts │ └── BubbleSort.cs ├── C++ ├── Algorithms │ ├── Backtracking │ │ ├── nKnighttour.cpp │ │ └── n_queens_matrix.cpp │ ├── Kadane_Algorithm.cpp │ ├── Searching │ │ └── search+sort.cpp │ ├── binary_search.cpp │ └── factorial.cpp ├── Array │ ├── MaxValueSubArray.cpp │ ├── MaxValueSubArray.exe │ ├── palindromeString.cpp │ ├── palindromeString.exe │ ├── printingAllSubArray.exe │ ├── sortInsertion.exe │ ├── sumOfAllSubArrays.cpp │ └── sumOfAllSubArrays.exe ├── Binary Tree │ ├── Bottom view of tree.cpp │ ├── Construct binary trees from inorder preorder traversal.cpp │ ├── Diameter of tree.cpp │ ├── Find LCA in BT.cpp │ ├── Height of tree.cpp │ ├── Largest subtree sum in tree.cpp │ ├── Left view of tree.cpp │ ├── Level order traversal.cpp │ ├── Minimum swaps require to convert binary tree to BST.cpp │ ├── Mirror of tree.cpp │ ├── Print all K sum path in BT.cpp │ ├── Reverse level order traversal.cpp │ ├── Right view of tree.cpp │ ├── Top view of tree.cpp │ └── Trees isomorphism problem.cpp ├── Dynamic Programming │ ├── 0-1 knapsack.cpp │ ├── Binomial cofficient.cpp │ ├── Coin change.cpp │ ├── Equal subset sum.cpp │ ├── LC subsequences.cpp │ ├── LC substring.cpp │ ├── Longest Increasing Subsequence.cpp │ ├── Longest palindromic subsequence.cpp │ ├── Longest repeated subsequence.cpp │ ├── Minimum number of deletion in a string to make it a palindrome.cpp │ └── Permutation coefficient problem.cpp ├── Hashing │ ├── Count_Frequency_of_Element.cpp │ └── Questions │ │ └── Ques1.cpp ├── Heap │ ├── Maxheap minheap using array and recursion.cpp │ ├── Maximum of all subarray of size K.cpp │ ├── Merge K sorted linklist.cpp │ ├── Merge k sorted array.cpp │ ├── Merge two binary maxheaps.cpp │ ├── Reorganize strings.cpp │ ├── Sort array using heap HEAPSORT.cpp │ ├── kth largest element in array.cpp │ ├── kth largest sum continuous subarrays.cpp │ └── kth smallest and kth largest in unsorted array.cpp ├── Linked LIst │ ├── Circular LinkedList │ │ ├── deletion_in_CircularLL.cpp │ │ ├── insertion._in_CircularLL.cpp │ │ └── traver_in_circularLL.cpp │ ├── Doubly Linked List │ │ ├── deletion_in_DoublyLinkedList.cpp │ │ ├── deletion_in_DoublyLinkedlist2.cpp │ │ ├── insertion_in_DoublyLinkedList.cpp │ │ └── insetion_in_DoublyLinkedList2.cpp │ ├── Question │ │ ├── CheckLinkedListisPalindrome.cpp │ │ ├── Circularlinkedlist.cpp │ │ ├── Detect Loop in LinkedList.cpp │ │ ├── Detect loop in a linked list.cpp │ │ ├── Detect_Loop_in_Linked_List_Without_Floyd_Algorithm.cpp │ │ ├── Find middle node.cpp │ │ ├── Insertion and Deletion in Doubly Linked List.cpp │ │ ├── LRU.cpp │ │ ├── Nth_node_from_the_end.cpp │ │ ├── Queue AlgorithmLinkedListOperations.cpp │ │ ├── ReverseALinkedList.cpp │ │ ├── ReverseLinkedList.cpp │ │ ├── StackFromLinkedList.cpp │ │ ├── Stock_span_problem.cpp │ │ ├── add_two_numbers.cpp │ │ ├── delete_head_without_head_pointer.cpp │ │ ├── doubly_linked_list.cpp │ │ ├── insertAtTail.cpp │ │ ├── insertAthead.cpp │ │ ├── kReverse.cpp │ │ ├── lenghOfLinkedList.cpp │ │ ├── linked list.cpp │ │ ├── merge_sort_linked_list.cpp │ │ ├── move element to start in linked list.cpp │ │ └── quick_sort_linked_list.cpp │ ├── Singly Linked List │ │ ├── ArrayReversalSinglyLL.cpp │ │ ├── Reverse_K_nodes_in_a_Linked_list.cpp │ │ ├── Reverse_LinkedList.cpp │ │ ├── deletion_in_LinkedList.cpp │ │ ├── deletion_in_LinkedListed2.cpp │ │ ├── deletion_of_linkedList.cpp │ │ ├── insertion_in_LinkedList2.cpp │ │ ├── insertion_in_Linkedlist.cpp │ │ ├── insertion_in_ll_classwork.cpp │ │ ├── insertion_in_ll_classwork2.cpp │ │ ├── linkedlist1.cpp │ │ └── traversal_of_LinkedList.cpp │ └── XOR Memory Efficient LinkedList │ │ ├── Operation1.cpp │ │ ├── Operation2.cpp │ │ ├── test.cpp │ │ └── traverse.cpp ├── Priority Queue │ └── heaps.cpp ├── Questions │ └── ABit++Codeforces.cpp ├── Queue │ ├── Circlular Queue │ │ └── Insertion_and_Deletion.cpp │ ├── Deletion in a Queue.cpp │ ├── Double ended Queue │ │ └── Insertion_in_a_Doubelended_Queue.cpp │ ├── Insertion_in_Queue.cpp │ ├── Singly Queue │ │ ├── PriorityQueue.cpp │ │ ├── Queue_Implemantiation_Using_Linked_List.cpp │ │ ├── Queue_Implemantiation_Using_Linked_List.exe │ │ ├── Queue_Implementiatio_Using_Array.cpp │ │ └── Queue_Implementiatio_Using_Array.exe │ ├── deletion_in_Queue.cpp │ └── queue_implementation.cpp ├── Stacks │ ├── Array_implementation.cpp │ ├── Questions │ │ ├── .cph │ │ │ └── .ques14.cpp_b3eb7927d1ab7b1ca99c955228a02b59.prob │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── Balanced Paranthesis.cpp │ │ ├── Maximum Element using Stacks.cpp │ │ ├── Postfix_Evaluationstack.cpp │ │ ├── RemoveTheStars.cpp │ │ ├── Stack_Implementation.cpp │ │ ├── StacksusingLinkedlist.cpp │ │ ├── Two_Stacks_in_one_array.cpp │ │ ├── delete stacks.cpp │ │ ├── infix_to_postfix.cpp │ │ ├── infix_to_prefix.cpp │ │ ├── inserting stacks.cpp │ │ ├── next_greater_frequencey_element.cpp │ │ ├── post_fix_to_pre_fix_conversation.cpp │ │ ├── ques1.cpp │ │ ├── ques10.cpp │ │ ├── ques11.cpp │ │ ├── ques12.cpp │ │ ├── ques12.exe │ │ ├── ques13.cpp │ │ ├── ques14.cpp │ │ ├── ques2.cpp │ │ ├── ques3.cpp │ │ ├── ques4.cpp │ │ ├── ques5.cpp │ │ ├── ques6.cpp │ │ ├── ques7.cpp │ │ ├── ques8.cpp │ │ ├── ques9.cpp │ │ ├── stack_using_qqueue.cpp │ │ └── valid_expression.cpp │ ├── dynamic_array_inplementation.cpp │ └── linked_list_implementation.cpp ├── Tree_Algorithms │ ├── BFS.cpp │ └── Minimum_Spanning_Tree.cpp ├── Trees │ ├── BinaryRecursiveSearch.cpp │ ├── Boundary Traversal.cpp │ ├── binary_trees.cpp │ ├── inorder_traversal.cpp │ ├── levelorder_traversal.cpp │ ├── postorder_traversal.cpp │ ├── preorder_traversal.cpp │ ├── questions │ │ ├── ques1.cpp │ │ ├── ques2.cpp │ │ ├── ques3.cpp │ │ ├── ques4.cpp │ │ ├── ques5.cpp │ │ └── ques6.cpp │ └── vertical_order_traversal.cpp ├── Trees_Algorithm │ └── DFS.cpp └── sorting │ ├── bead_sort.cpp │ ├── bubble_sort.cpp │ ├── bucket_sort.cpp │ ├── comb_sort.cpp │ ├── counting_sort_string.cpp │ ├── heap_sort.cpp │ ├── insertion_sort.cpp │ ├── merge_sort.cpp │ ├── non_recursive_merge_sort.cpp │ ├── numeric_string_sort.cpp │ ├── odd_even_sort.cpp │ ├── pigeonhole_sort.cpp │ ├── quick_sort.cpp │ ├── radix_sort.cpp │ ├── random_pivot_quick_sort.cpp │ ├── recursive_bubble_sort.cpp │ ├── selection_sort_iterative.cpp │ ├── selection_sort_recursive.cpp │ ├── shell_sort.cpp │ ├── strand_sort.cpp │ ├── tim_sort.cpp │ └── wave_sort.cpp ├── CONTRIBUTING.md ├── Hashtable.cpp ├── Java_DS └── linkedlist.java ├── Leetcode Medium questions ├── 3Sum Closest │ └── main.cpp ├── 3Sum │ └── main.cpp ├── Add Two Numbers │ └── main.cpp ├── Chef and Division3 │ ├── Question.c │ └── Solution.c ├── Container With Most Water │ └── main.cpp ├── Integer to Roman │ └── main.cpp ├── Letter-combinations-of-a-phone-number │ └── main.cpp ├── Minimum Time to Make Rope Colorful │ └── main.cpp ├── Next Permutation │ └── main.cpp ├── Reverse Integer │ └── main.cpp ├── Rotate Image │ └── main.cpp └── Search in Rotated Sorted Array │ └── main.cpp ├── Python ├── .DS_Store ├── Arrays │ └── Find-missing-number.py └── linkedlist │ ├── .DS_Store │ ├── dsa.py │ └── singularlinkedlist │ ├── 3 Sum.py │ ├── insertingAtbeginning.py │ └── traversingLinkedlist.py ├── README.md ├── Smallest_subarray_with_sum_greater_than_given_value.cpp ├── Socket ├── admin.py ├── client.py ├── cpu_info.py └── user.py ├── Sorting algo ├── bubbleSort.cpp ├── countingSort.cpp ├── heapSort.cpp ├── insertionSort.cpp ├── mergeSort.cpp ├── quickSort.cpp └── selectionSort.cpp ├── Top Interview questions └── Arrays │ ├── CoinChangeProblem.cpp │ ├── MaxProductSubarray.cpp │ ├── MaximumIndex.cpp │ ├── Peak Element.cpp │ ├── Sortthearray.cpp │ ├── SubarraySum.cpp │ ├── TrappingRainwater.cpp │ ├── WaveArray.cpp │ ├── chocolate_distribution_problem.C++ │ ├── missinginteger.cpp │ └── reverseArray.cpp ├── dijkstras.cpp ├── graph_coloring.cpp ├── rotating_triangle.cpp └── sorting_in_java ├── bubble_sort.java ├── bucket_sort.java ├── counting_sort.java ├── insertion_sort.java ├── merge_sort.java ├── quick_sort.java └── selection_sort.java /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/.DS_Store -------------------------------------------------------------------------------- /C#/Sorts/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class BubbleSort 4 | { 5 | // Sample Data 6 | private readonly int[] items = { 4, 100, 2, 23, 18, 1}; 7 | 8 | public static void Main(string[] args) 9 | { 10 | var bubbleSort = new BubbleSort(); 11 | var newItems = bubbleSort.Sort(bubbleSort.items); 12 | 13 | foreach (int item in newItems) 14 | { 15 | Console.WriteLine(item + " "); 16 | } 17 | } 18 | 19 | private int[] Sort(int[] list) 20 | { 21 | int temp; 22 | 23 | for (int i = 0; i <= list.Length - 2; i++) { 24 | for (int j = 0; j <= list.Length - 2; j++) { 25 | if (list[j] > list[j + 1]) { 26 | temp = list[j + 1]; 27 | list[j + 1] = list[j]; 28 | list[j] = temp; 29 | } 30 | } 31 | } 32 | 33 | return list; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /C++/Algorithms/Backtracking/nKnighttour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define N 8 4 | using namespace std; 5 | int sol[N][N]; 6 | bool isValid(int x, int y, int sol[N][N]) 7 | { // check place is in range and not assigned yet 8 | return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); 9 | } 10 | void displaySolution() 11 | { 12 | for (int x = 0; x < N; x++) 13 | { 14 | for (int y = 0; y < N; y++) 15 | cout << setw(3) << sol[x][y] << " "; 16 | cout << endl; 17 | } 18 | } 19 | int knightTour(int x, int y, int move, int sol[N][N], int xMove[N], int yMove[N]) 20 | { 21 | int xNext, yNext; 22 | if (move == N * N) // when the total board is covered 23 | return true; 24 | for (int k = 0; k < 8; k++) 25 | { 26 | xNext = x + xMove[k]; 27 | yNext = y + yMove[k]; 28 | if (isValid(xNext, yNext, sol)) 29 | { // check room is preoccupied or not 30 | sol[xNext][yNext] = move; 31 | if (knightTour(xNext, yNext, move + 1, sol, xMove, yMove) == true) 32 | return true; 33 | else 34 | sol[xNext][yNext] = -1; // backtracking 35 | } 36 | } 37 | return false; 38 | } 39 | bool findKnightTourSol() 40 | { 41 | for (int x = 0; x < N; x++) // initially set all values to -1 of solution matrix 42 | for (int y = 0; y < N; y++) 43 | sol[x][y] = -1; 44 | // all possible moves for knight 45 | int xMove[8] = {2, 1, -1, -2, -2, -1, 1, 2}; 46 | int yMove[8] = {1, 2, 2, 1, -1, -2, -2, -1}; 47 | sol[0][0] = 0; // starting from room (0, 0) 48 | if (knightTour(0, 0, 1, sol, xMove, yMove) == false) 49 | { 50 | cout << "Solution does not exist"; 51 | return false; 52 | } 53 | else 54 | displaySolution(); 55 | return true; 56 | } 57 | int main() 58 | { 59 | findKnightTourSol(); 60 | } 61 | -------------------------------------------------------------------------------- /C++/Algorithms/Backtracking/n_queens_matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | int *x; 8 | int n; 9 | int flag = 0; 10 | bool Place(int k, int i) 11 | { 12 | for (int j = 1; j <= k - 1; j++) 13 | { 14 | if ((x[j] == i) || (abs(x[j] - i) == abs(j - k))) 15 | { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | void write() 22 | { 23 | flag++; 24 | cout << endl<<"Solution " << flag << " "; 25 | cout << endl; 26 | for (int i = 1; i <= n; i++) 27 | { 28 | for (int j = 1; j <= n; j++) 29 | { 30 | if (j == x[i]) 31 | { 32 | cout << "Q" 33 | << " | "; 34 | } 35 | else 36 | { 37 | cout << " " 38 | << " | "; 39 | } 40 | 41 | } 42 | cout<> n; 76 | x = new int[n + 1]; 77 | x[0] = 0; 78 | double time_spent = 0.0; 79 | clock_t begin = clock(); 80 | nqueens(1, n); 81 | clock_t end = clock(); 82 | time_spent += (double)(end - begin) / CLOCKS_PER_SEC; 83 | cout << "No solution found" << endl; 84 | cout << "Execution Time : " << time_spent << " seconds" << endl; 85 | getch(); 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /C++/Algorithms/Kadane_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | long long maxSubarraySum(int arr[], int n){ 2 | 3 | int csum = arr[0]; 4 | int msum = arr[0]; 5 | for(int i=1;i 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | 8 | ios::sync_with_stdio(false); 9 | cin.tie(0); 10 | cout.tie(0); 11 | 12 | int n, q; 13 | cin >> n >> q; 14 | 15 | vector a(n); 16 | for (int i = 0; i < n; i++) 17 | { 18 | cin >> a[i]; 19 | } 20 | 21 | for (int i = 0; i < q; i++) 22 | { 23 | int k; 24 | cin >> k; 25 | 26 | int l = 0, r = n-1 ; 27 | bool found = 0; 28 | 29 | while (l <= r) 30 | { 31 | 32 | int mid = l + (r - l) / 2; 33 | 34 | if (a[mid] == k) 35 | { 36 | found = 1; 37 | break; 38 | } 39 | else if (a[mid] < k) 40 | { 41 | 42 | l = mid + 1; 43 | } 44 | else 45 | { 46 | 47 | r = mid - 1; 48 | } 49 | } 50 | 51 | if (found) 52 | { 53 | cout << "YES\n"; 54 | } 55 | else 56 | { 57 | 58 | cout << "NO\n"; 59 | } 60 | } 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /C++/Algorithms/factorial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | main() 6 | { 7 | int i,f=1,x; 8 | 9 | cin>>x; 10 | 11 | for(i=1;i<=x;i++) 12 | f=f*i; 13 | 14 | cout<<"Factorial:"< 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int n; 7 | cout<<"Enter the no. of elements in the array: "; 8 | cin>>n; 9 | int arr[n]; 10 | for (int i = 0; i < n; i++) 11 | { 12 | cin>> arr[i]; 13 | } 14 | 15 | cout<<"\nAll the sub-arrays of the array are: \n"; 16 | int sum=0, maxSum=INT_MIN, ini=0, fin=0; 17 | cout<maxSum){ 27 | maxSum=sum; 28 | ini=i; 29 | fin=j; 30 | } 31 | sum=0; 32 | } 33 | } 34 | 35 | 36 | cout<<"\nSub-array with maximum sum is: " < 2 | using namespace std; 3 | 4 | int main(){ 5 | int n; 6 | cin>>n; 7 | 8 | char test[n+1]; 9 | cin>>test; 10 | 11 | for (int i = 0; i<=(n)/2; i++) 12 | { 13 | if(test[i]!=test[n-1-i]){ 14 | cout<<"Given testcase is not a palindrome."; 15 | n=0; 16 | break; 17 | } 18 | } 19 | if(n!=0){ 20 | cout<<"Given testcase is a palindrome."; 21 | } 22 | 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /C++/Array/palindromeString.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/C++/Array/palindromeString.exe -------------------------------------------------------------------------------- /C++/Array/printingAllSubArray.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/C++/Array/printingAllSubArray.exe -------------------------------------------------------------------------------- /C++/Array/sortInsertion.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/C++/Array/sortInsertion.exe -------------------------------------------------------------------------------- /C++/Array/sumOfAllSubArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n, sum=0, currSum=0; 6 | cout<< "Enter the no. of values to be entered into array: "; 7 | cin>>n; 8 | int arr[n]; 9 | cout<<"Enter the individual elements of the array: "; 10 | for (int i = 0; i < n; i++) 11 | { 12 | cout<<"\n\t arr[" <> arr[i]; 14 | } 15 | 16 | for (int i = 0; i < n; i++) 17 | { 18 | for (int j = i; j < n; j++) 19 | { 20 | currSum+=arr[j] 21 | } 22 | cout<<"\nCurrent sum of Subarray is: " <>& m) 20 | { 21 | // Base case 22 | if (root == NULL) 23 | return; 24 | 25 | // If node for a particular 26 | // horizontal distance is not 27 | // present, add to the map. 28 | if (m.find(hd) == m.end()) 29 | { 30 | m[hd] = make_pair(root->data, curr); 31 | } 32 | // Compare height for already 33 | // present node at similar horizontal 34 | // distance, if its smaller or same replace it. 35 | else if (m[hd].second <= curr) m[hd] = make_pair(root->data, curr); 36 | 37 | 38 | // Recur for left subtree 39 | printBottomViewUtil(root->left, curr + 1, hd - 1, m); 40 | 41 | // Recur for right subtree 42 | printBottomViewUtil(root->right, curr + 1, hd + 1, m); 43 | } 44 | 45 | void printBottomView(Node* root) 46 | { 47 | 48 | // Map to store Horizontal Distance, 49 | // Height and Data. 50 | map < int, pair < int, int > > m; 51 | 52 | printBottomViewUtil(root, 0, 0, m); 53 | 54 | // Prints the values stored by printBottomViewUtil() 55 | map < int, pair < int, int > > ::iterator it; 56 | for (it = m.begin(); it != m.end(); ++it) 57 | { 58 | pair < int, int > p = it->second; 59 | cout << p.first << " "; 60 | } 61 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Height of tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1 3 | 4 | sol: https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/ 5 | 6 | **note**: maximum depth of tree === height of the tree. 7 | */ 8 | 9 | 10 | 11 | // ----------------------------------------------------------------------------------------------------------------------- // 12 | /* 13 | TC: O(N) 14 | */ 15 | int height(struct Node* node) 16 | { 17 | // if node is null, we return 0. 18 | if (node == NULL) return 0; 19 | 20 | //else we call the recursive function, height for left and right 21 | //subtree and choose their maximum. we also add 1 to the result 22 | //which indicates height of root of the tree. 23 | else { 24 | int lHeight = height(node->left); 25 | int rHeight = height(node->right); 26 | 27 | if (lHeight > rHeight) { 28 | return lHeight + 1; 29 | } 30 | else { 31 | return rHeight + 1; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /C++/Binary Tree/Minimum swaps require to convert binary tree to BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/ 3 | 4 | sorting inorder traversal of tree => Binary Search Tree 5 | or 6 | sort the array and then arrange it in inorder => BST 7 | 8 | 9 | basically here logic is to get inorder of tree, then sort it and compare it with itself to know the swaps 10 | */ 11 | 12 | 13 | 14 | 15 | // ----------------------------------------------------------------------------------------------------------------------- // 16 | // C++ program for Minimum swap required 17 | // to convert binary tree to binary search tree 18 | #include 19 | using namespace std; 20 | 21 | // Inorder Traversal of Binary Tree 22 | void inorder(int a[], std::vector& v, 23 | int n, int index) 24 | { 25 | // if index is greater or equal to vector size 26 | if (index >= n) 27 | return; 28 | inorder(a, v, n, 2 * index + 1); 29 | 30 | // push elements in vector 31 | v.push_back(a[index]); 32 | inorder(a, v, n, 2 * index + 2); 33 | } 34 | 35 | // Function to find minimum swaps to sort an array 36 | int minSwaps(std::vector& v) 37 | { 38 | std::vector > t(v.size()); 39 | int ans = 0; 40 | for (int i = 0; i < v.size(); i++) 41 | t[i].first = v[i], t[i].second = i; 42 | 43 | sort(t.begin(), t.end()); 44 | for (int i = 0; i < t.size(); i++) 45 | { 46 | // second element is equal to i 47 | if (i == t[i].second) 48 | continue; 49 | else 50 | { 51 | // swaping of elements 52 | swap(t[i].first, t[t[i].second].first); 53 | swap(t[i].second, t[t[i].second].second); 54 | } 55 | 56 | // Second is not equal to i 57 | if (i != t[i].second) 58 | --i; 59 | ans++; 60 | } 61 | return ans; 62 | } 63 | 64 | // Driver code 65 | int main() 66 | { 67 | int a[] = { 5, 6, 7, 8, 9, 10, 11 }; 68 | int n = sizeof(a) / sizeof(a[0]); 69 | std::vector v; 70 | inorder(a, v, n, 0); 71 | cout << minSwaps(v) << endl; 72 | } 73 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/Coin change.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/coin-change2448/1 3 | 4 | variation of unbounded_knapsack for more refer to DP_tut/unbounded_knapsack/3_coin.... 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | long long int count(int coins[], int n, int sum) 10 | { 11 | vector> memo(n + 1, vector(sum + 1)); 12 | for (int j = 0;j < sum + 1;j++) memo[0][j] = 0; 13 | for (int i = 1;i < n + 1;i++) memo[i][0] = 1; 14 | 15 | for (int i = 1;i < n + 1;i++) { 16 | for (int j = 1;j < sum + 1;j++) { 17 | if (coins[i - 1] <= j) { 18 | memo[i][j] = memo[i][j - coins[i - 1]] + memo[i - 1][j]; 19 | } 20 | else memo[i][j] = memo[i - 1][j]; 21 | } 22 | } 23 | return memo[n][sum]; 24 | } 25 | 26 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/Equal subset sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/subset-sum-problem2014/1 3 | 4 | for memoization go to DP_tut/1_0-1_knapsack/2_subset... its just variation 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | // tabulation 10 | class Solution { 11 | public: 12 | bool subsetSum(int arr[], int n, int sum) { 13 | vector> tabu(n + 1, vector(sum + 1)); 14 | for (int i = 0;i < n + 1;i++) { 15 | tabu[i][0] = true; 16 | } 17 | for (int j = 1;j < sum + 1;j++) { 18 | tabu[0][j] = false; 19 | } 20 | 21 | for (int i = 1;i < n + 1;i++) { 22 | for (int j = 1;j < sum + 1;j++) { 23 | if (arr[i - 1] <= j) { 24 | tabu[i][j] = tabu[i - 1][j - arr[i - 1]] || tabu[i - 1][j]; 25 | } 26 | else tabu[i][j] = tabu[i - 1][j]; 27 | } 28 | } 29 | return tabu[n][sum]; 30 | } 31 | int equalPartition(int N, int arr[]) 32 | { 33 | int sum = 0; 34 | for (int i = 0;i < N;i++) { 35 | sum += arr[i]; 36 | } 37 | 38 | // this is crux of whole problem 39 | // if sum found is odd then its not possible to divide the array in 2 subset 40 | // and if sum found is even then we can use subset sum problem/implemetation to complete rest of the problem. 41 | if (sum % 2) return 0; 42 | sum /= 2; 43 | 44 | return subsetSum(arr, N, sum); 45 | } 46 | 47 | }; 48 | 49 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/LC subsequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1 3 | 4 | refer DP_tut/LCS/implementation 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | // function to find longest common subsequence 10 | int static memo[1001][1001]; 11 | int lcs(int n, int m, string s1, string s2) { 12 | 13 | // your code here 14 | for (int i = 0;i < n + 1;i++) { 15 | memo[i][0] = 0; 16 | } 17 | for (int j = 0;j < m + 1;j++) { 18 | memo[0][j] = 0; 19 | } 20 | for (int i = 1;i < n + 1;i++) { 21 | for (int j = 1;j < m + 1;j++) { 22 | if (s1[i - 1] == s2[j - 1]) { 23 | memo[i][j] = 1 + memo[i - 1][j - 1]; 24 | } 25 | else { 26 | memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]); 27 | } 28 | } 29 | } 30 | return memo[n][m]; 31 | } 32 | 33 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/LC substring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/longest-common-substring1452/1 3 | 4 | variation of DP_tut/LCS/2_LC_substring... 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | int memo[1001][1001]; 10 | 11 | int longestCommonSubstr(string s1, string s2, int n, int m) 12 | { 13 | // memset(memo, -1, sizeof(memo)); 14 | // your code here 15 | int result = 0; 16 | for (int i = 0;i < n + 1;i++) memo[i][0] = 0; 17 | for (int j = 0;j < m + 1;j++) memo[0][j] = 0; 18 | 19 | for (int i = 1;i < n + 1;i++) { 20 | for (int j = 1;j < m + 1;j++) { 21 | if (s1[i - 1] == s2[j - 1]) { 22 | memo[i][j] = 1 + memo[i - 1][j - 1]; 23 | result = max(result, memo[i][j]); 24 | } 25 | else { 26 | memo[i][j] = 0; 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | 33 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int f(int idx, int prev_idx, int n, int a[], 6 | vector >& dp) 7 | { 8 | if (idx == n) { 9 | return 0; 10 | } 11 | 12 | if (dp[idx][prev_idx + 1] != -1) { 13 | return dp[idx][prev_idx + 1]; 14 | } 15 | 16 | int notTake = 0 + f(idx + 1, prev_idx, n, a, dp); 17 | int take = INT_MIN; 18 | if (prev_idx == -1 || a[idx] > a[prev_idx]) { 19 | take = 1 + f(idx + 1, idx, n, a, dp); 20 | } 21 | 22 | return dp[idx][prev_idx + 1] = max(take, notTake); 23 | } 24 | 25 | int longestSubsequence(int n, int a[]) 26 | { 27 | vector > dp(n + 1, vector(n + 1, -1)); 28 | return f(0, -1, n, a, dp); 29 | } 30 | 31 | 32 | int main() 33 | { 34 | int a[] = { 3, 10, 2, 1, 20 }; 35 | int n = sizeof(a) / sizeof(a[0]); 36 | cout << "Length of lis is " << longestSubsequence(n, a); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/Longest palindromic subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | link: https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/ 4 | 5 | problem: given a string find longest palindromic subsequence 6 | output: length of longest palindromic subsequence 7 | 8 | refer DP_tut\3_LCS\6_Longest_Palindromic... 9 | 10 | crux of the problem: if we want to find the subsequence we use LCS 11 | then if want to find the palindromic then use the same string and reverse it. 12 | 13 | */ 14 | 15 | // ----------------------------------------------------------------------------------------------------------------------- // 16 | 17 | int main() { 18 | // string s2 = reverse of s1. 19 | return LCS(s1, s2, n, n); 20 | } -------------------------------------------------------------------------------- /C++/Dynamic Programming/Longest repeated subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/longest-repeating-subsequence2004/1 3 | 4 | variation of LCS. 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | class Solution { 10 | int memo[1001][1001]; 11 | public: 12 | int LCS(string s1, string s2, int n, int m) 13 | { 14 | for (int i = 0;i < n + 1;i++) memo[i][0] = 0; 15 | for (int j = 0;j < m + 1;j++) memo[0][j] = 0; 16 | 17 | for (int i = 1;i < n + 1;i++) { 18 | for (int j = 1;j < m + 1;j++) { 19 | if (s1[i - 1] == s2[j - 1] && i != j) { // crux: add only if position are not same and char is same. 20 | memo[i][j] = 1 + memo[i - 1][j - 1]; 21 | } 22 | else { 23 | memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]); 24 | } 25 | } 26 | } 27 | return memo[n][m]; 28 | } 29 | int LongestRepeatingSubsequence(string str) { 30 | // Code here 31 | return LCS(str, str, str.length(), str.length()); 32 | } 33 | 34 | }; 35 | 36 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/Minimum number of deletion in a string to make it a palindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome/ 3 | 4 | problem: given string find min. no. of deletion to make it palindrom. 5 | output: min. no. of operation 6 | 7 | crux: find subsequence with palindromic of string itself, and then subtract with the length 8 | refer: longest palindromic subsequnce. 9 | 10 | variation of LCS 11 | */ 12 | 13 | // ----------------------------------------------------------------------------------------------------------------------- // 14 | 15 | int main() { 16 | // string s2 = reverse of s1. 17 | return s1.length() - LCS(s1, s2, n, n); 18 | } 19 | 20 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Dynamic Programming/Permutation coefficient problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://www.geeksforgeeks.org/permutation-coefficient/ 3 | 4 | logic is same as 9_binomial_cofficient but here it is permutation 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | 9 | // recursion 10 | // let's assume if n is the no. of balls and r is to position to fill 11 | int recur(int n, int r) { 12 | // base condition 13 | if (n < r) return 0; 14 | if (n == 0 || r == 0) return 1; 15 | 16 | return recur(n - 1, r) + (r * recur(n - 1, r - 1)); 17 | /* recur(n-1, r-1): it says select fixed ball hence total-1 and ball_left_to_select - 1 and now also there are r pos to permute that fixed ball. 18 | recur(n-1, r): it means reject that fixed ball hence total-1 and ball_left_to_select remains same. 19 | */ 20 | } 21 | 22 | // do memoization and tabulation by self. 23 | 24 | // ----------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- /C++/Hashing/Count_Frequency_of_Element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin>>n; 10 | 11 | vector a(n); 12 | for(int i=0;i>a[i]; 15 | } 16 | 17 | map frquency; 18 | for(int i=0;i :: iterator it; 24 | for(it=frquency.begin();it!=frquency.end();it++) 25 | { 26 | cout<first<<" "<second< maxHeap; 25 | 26 | // push all the elem. of first window 27 | for (int i = 0;i < k;i++) maxHeap.push(arr[i]); 28 | 29 | 30 | for (int i = k;i < n;i++) { 31 | cout << maxHeap.top() << endl; 32 | maxHeap.pop(); 33 | maxHeap.push(arr[i]); 34 | } 35 | } 36 | 37 | // Driver code 38 | int main() 39 | { 40 | int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 41 | int n = sizeof(arr) / sizeof(arr[0]); 42 | int k = 3; 43 | printKMax(arr, n, k); 44 | return 0; 45 | } -------------------------------------------------------------------------------- /C++/Heap/Merge K sorted linklist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1 3 | 4 | also refer: linked_list/31_merge_k_sorted_LL 5 | */ 6 | 7 | // ----------------------------------------------------------------------------------------------------------------------- // 8 | // using heap 9 | typedef pair pin; 10 | 11 | class Solution { 12 | public: 13 | 14 | Node* mergeKLists(Node* arr[], int k) 15 | { 16 | // minHeap to get min. ele of all K sorted LL 17 | priority_queue , greater> pq; 18 | 19 | for (int i = 0;i < k;i++) { 20 | pq.push({ arr[i]->data, arr[i] }); 21 | } 22 | 23 | Node* ans = new Node(0); 24 | Node* finalAns = ans; 25 | 26 | while (!pq.empty()) { 27 | pin curr = pq.top(); 28 | pq.pop(); 29 | 30 | // append the curr's address in ans LL 31 | ans->next = curr.second; 32 | ans = ans->next; 33 | 34 | // if next of curr exist then append it. 35 | if ((curr.second)->next != NULL) pq.push({ (curr.second)->next->data, (curr.second)->next }); 36 | } 37 | 38 | return finalAns->next; 39 | } 40 | }; -------------------------------------------------------------------------------- /C++/Heap/Merge two binary maxheaps.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://practice.geeksforgeeks.org/problems/merge-two-binary-max-heap0144/1 3 | 4 | sol: https://www.geeksforgeeks.org/merge-two-binary-max-heaps/ 5 | */ 6 | 7 | 8 | // ----------------------------------------------------------------------------------------------------------------------- // 9 | /* 10 | TC: O(N * logN) 11 | SC: O(1) 12 | */ 13 | void maxHeapify(vector& arr, int n, int idx) { 14 | // Find largest of node and its children 15 | if (idx >= n) return; 16 | int l = 2 * idx + 1; 17 | int r = 2 * idx + 2; 18 | int max; 19 | if (l < n && arr[l] > arr[idx]) 20 | max = l; 21 | else 22 | max = idx; 23 | if (r < n && arr[r] > arr[max]) max = r; 24 | 25 | // Put maximum value at root and 26 | // recur for the child with the 27 | // maximum value 28 | if (max != idx) { 29 | swap(arr[max], arr[idx]); 30 | maxHeapify(arr, n, max); 31 | } 32 | } 33 | 34 | // Builds a max heap of given arr[0..n-1] 35 | void buildMaxHeap(vector& arr, int n) { 36 | // building the heap from first non-leaf 37 | // node by calling max heapify function 38 | for (int i = n / 2 - 1; i >= 0; i--) maxHeapify(arr, n, i); 39 | } 40 | 41 | class Solution { 42 | public: 43 | vector mergeHeaps(vector& a, vector& b, int n, int m) { 44 | vector merged(n + m, 0); 45 | for (int i = 0; i < n; i++) merged[i] = a[i]; 46 | for (int i = 0; i < m; i++) merged[n + i] = b[i]; 47 | 48 | buildMaxHeap(merged, n + m); 49 | return merged; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /C++/Heap/Reorganize strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://leetcode.com/problems/reorganize-string/ 3 | 4 | video: https://youtu.be/zaM_GLLvysw 5 | */ 6 | 7 | 8 | // ----------------------------------------------------------------------------------------------------------------------- // 9 | #include 10 | using namespace std; 11 | 12 | string reorganizeString(string s) { 13 | // for counting the frequency 14 | map mp; 15 | for (char c : s) mp[c]++; 16 | 17 | 18 | priority_queue> maxHeap; 19 | 20 | // to arrange acc. to the frequency of the char. 21 | for (auto i : mp) { 22 | maxHeap.push({ i.second, i.first }); 23 | } 24 | 25 | string ans = ""; 26 | 27 | // eliminate if only one ele. is present 28 | while (maxHeap.size() > 1) { 29 | // get both top frequent char 30 | pair a = maxHeap.top(); 31 | maxHeap.pop(); 32 | pair b = maxHeap.top(); 33 | maxHeap.pop(); 34 | 35 | // add to string to alternate 36 | ans += a.second; 37 | ans += b.second; 38 | 39 | // reduce the frequence count 40 | a.first--; 41 | b.first--; 42 | 43 | // if the frequency count is still present then push it. 44 | if (a.first > 0) maxHeap.push(a); 45 | if (b.first > 0) maxHeap.push(b); 46 | } 47 | 48 | // if single ele is present than: 49 | // case 1: frequency of the ele. is 2 or more 50 | // case 2: it is the same ele. as the last ele. in ans string 51 | if (maxHeap.size() > 0 && (maxHeap.top().first > 1 || maxHeap.top().second == ans[ans.size() - 1])) return ""; 52 | 53 | // ofc, now ele will be unique 54 | if (maxHeap.size()) ans += maxHeap.top().second; 55 | 56 | return ans; 57 | } 58 | 59 | int main() 60 | { 61 | string s = "abbabbaaab"; 62 | cout << reorganizeString(s); 63 | } -------------------------------------------------------------------------------- /C++/Heap/Sort array using heap HEAPSORT.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | link: https://www.geeksforgeeks.org/heap-sort/ 3 | 4 | build heap means: either build max heap or min heap there is no such thing as only heap 5 | 6 | note: to get ascending sorted array use maxHeap, 7 | to get descending sorted array use minHeap 8 | */ 9 | 10 | 11 | 12 | // ----------------------------------------------------------------------------------------------------------------------- // 13 | // C++ program for implementation of Heap Sort 14 | #include 15 | 16 | using namespace std; 17 | 18 | // To heapify a subtree rooted with node i which is 19 | // an index in arr[]. n is size of heap 20 | void heapify(int arr[], int n, int i) 21 | { 22 | int largest = i; // Initialize largest as root 23 | int l = 2 * i + 1; // left = 2*i + 1 24 | int r = 2 * i + 2; // right = 2*i + 2 25 | 26 | // If left child is larger than root 27 | if (l < n && arr[l] > arr[largest]) 28 | largest = l; 29 | 30 | // If right child is larger than largest so far 31 | if (r < n && arr[r] > arr[largest]) 32 | largest = r; 33 | 34 | // If largest is not root 35 | if (largest != i) { 36 | swap(arr[i], arr[largest]); 37 | 38 | // Recursively heapify the affected sub-tree 39 | heapify(arr, n, largest); 40 | } 41 | } 42 | 43 | // main function to do heap sort 44 | void heapSort(int arr[], int n) 45 | { 46 | // Build heap (rearrange array) 47 | for (int i = n / 2 - 1; i >= 0; i--) 48 | heapify(arr, n, i); 49 | 50 | // One by one extract an element from heap 51 | for (int i = n - 1; i > 0; i--) { 52 | // Move current root to end 53 | swap(arr[0], arr[i]); 54 | 55 | // call max heapify on the reduced heap 56 | heapify(arr, i, 0); 57 | } 58 | } 59 | 60 | /* A utility function to print array of size n */ 61 | void printArray(int arr[], int n) 62 | { 63 | for (int i = 0; i < n; ++i) 64 | cout << arr[i] << " "; 65 | cout << "\n"; 66 | } 67 | 68 | // Driver code 69 | int main() 70 | { 71 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 72 | int n = sizeof(arr) / sizeof(arr[0]); 73 | 74 | heapSort(arr, n); 75 | 76 | cout << "Sorted array is \n"; 77 | printArray(arr, n); 78 | } 79 | -------------------------------------------------------------------------------- /C++/Linked LIst/Circular LinkedList/traver_in_circularLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef struct node 4 | { 5 | int data; 6 | node *next; 7 | } cll; 8 | void traverse(cll *head) 9 | { 10 | cout<<"The list contains : "; 11 | 12 | cll *current = head; 13 | do 14 | { 15 | cout << current->data << " "; 16 | current = current->next; 17 | 18 | } while (current != head); 19 | cout<data = 1; 35 | node2->data = 2; 36 | node3->data = 3; 37 | node4->data = 4; 38 | node5->data = 5; 39 | 40 | head = node1; 41 | node1->next = node2; 42 | node2->next = node3; 43 | node3->next = node4; 44 | node4->next = node5; 45 | node5->next = head; 46 | 47 | traverse(head); 48 | return 0; 49 | 50 | 51 | } -------------------------------------------------------------------------------- /C++/Linked LIst/Question/CheckLinkedListisPalindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | struct Node{ 7 | int data; 8 | struct Node* next; 9 | Node(int x){ 10 | data=x; 11 | next=NULL; 12 | } 13 | }; 14 | 15 | // the helper function is a recursive function. 16 | // it works recursively until the right pointer reaches the end node. 17 | // and at each point checks it with the corresponding node from the beginning -> left pointer 18 | 19 | bool helper(Node* right, Node* &left){ 20 | if(right==NULL) return true; 21 | bool ans = helper(right->next,left) && (right->data==left->data); 22 | left=left->next; 23 | return ans; 24 | } 25 | 26 | 27 | bool isPalindrome(Node *head) 28 | { 29 | Node* left=head; 30 | return helper(head,left); 31 | } 32 | 33 | 34 | 35 | // function to print linked list 36 | void printList(struct Node* head){ 37 | Node* temp=head; 38 | while(temp!=NULL){ 39 | cout<data<<" "; 40 | temp=temp->next; 41 | } 42 | } 43 | 44 | 45 | 46 | int main(){ 47 | 48 | // take the linked ist as input 49 | Node* head=NULL; 50 | Node* tail=NULL; 51 | 52 | int n; 53 | cin>>n; 54 | 55 | int inp; 56 | cin>>inp; 57 | head= new Node(inp); 58 | tail=head; 59 | for(int i=1;i>inp; 61 | tail->next=new Node(inp); 62 | tail=tail->next; 63 | } 64 | 65 | // function to print the linked list. 66 | // printList(head); 67 | // cout<<"\n"; 68 | 69 | if(isPalindrome(head)){ 70 | cout<<"The given linked list is a Palindrome"; 71 | } 72 | else{ 73 | cout<<"The given linked list is not a Palindrome"; 74 | } 75 | 76 | 77 | return 0; 78 | } 79 | 80 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Circularlinkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node { 4 | int data; 5 | struct Node *next; 6 | }; 7 | struct Node* head = NULL; 8 | void insert(int newdata) { 9 | struct Node *newnode = (struct Node *)malloc(sizeof(struct Node)); 10 | struct Node *ptr = head; 11 | newnode->data = newdata; 12 | newnode->next = head; 13 | if (head!= NULL) { 14 | while (ptr->next != head) 15 | ptr = ptr->next; 16 | ptr->next = newnode; 17 | } else 18 | newnode->next = newnode; 19 | head = newnode; 20 | } 21 | void display() { 22 | struct Node* ptr; 23 | ptr = head; 24 | do { 25 | cout<data <<" "; 26 | ptr = ptr->next; 27 | } while(ptr != head); 28 | } 29 | int main() { 30 | insert(3); 31 | insert(1); 32 | insert(7); 33 | insert(2); 34 | insert(9); 35 | cout<<"The circular linked list is: "; 36 | display(); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Detect Loop in LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | void push(Node** head_ref, int new_data) 11 | { 12 | Node* new_node = new Node(); 13 | new_node->data = new_data; 14 | new_node->next = (*head_ref); 15 | (*head_ref) = new_node; 16 | } 17 | 18 | int detectLoop(Node* list) 19 | { 20 | Node *slow_p = list, *fast_p = list; 21 | 22 | while (slow_p && fast_p && fast_p->next) { 23 | slow_p = slow_p->next; 24 | fast_p = fast_p->next->next; 25 | if (slow_p == fast_p) { 26 | return 1; 27 | } 28 | } 29 | return 0; 30 | } 31 | 32 | int main() 33 | { 34 | Node* head = NULL; 35 | 36 | push(&head, 20); 37 | push(&head, 4); 38 | push(&head, 15); 39 | push(&head, 10); 40 | 41 | head->next->next->next->next = head; 42 | if (detectLoop(head)) 43 | cout << "Loop found"; 44 | else 45 | cout << "No Loop"; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Detect loop in a linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | void push(struct Node** head_ref, int new_data) 11 | { 12 | /* allocate node */ 13 | struct Node* new_node = new Node; 14 | 15 | /* put in the data */ 16 | new_node->data = new_data; 17 | 18 | /* link the old list off the new node */ 19 | new_node->next = (*head_ref); 20 | 21 | /* move the head to point to the new node */ 22 | (*head_ref) = new_node; 23 | } 24 | 25 | // Returns true if there is a loop in linked list 26 | // else returns false. 27 | bool detectLoop(struct Node* h) 28 | { 29 | unordered_set s; 30 | while (h != NULL) { 31 | // If this node is already present 32 | // in hashmap it means there is a cycle 33 | // (Because you we encountering the 34 | // node for the second time). 35 | if (s.find(h) != s.end()) 36 | return true; 37 | 38 | // If we are seeing the node for 39 | // the first time, insert it in hash 40 | s.insert(h); 41 | 42 | h = h->next; 43 | } 44 | 45 | return false; 46 | } 47 | 48 | /* Driver program to test above function*/ 49 | int main() 50 | { 51 | /* Start with the empty list */ 52 | struct Node* head = NULL; 53 | 54 | push(&head, 20); 55 | push(&head, 4); 56 | push(&head, 15); 57 | push(&head, 10); 58 | 59 | /* Create a loop for testing */ 60 | head->next->next->next->next = head; 61 | 62 | if (detectLoop(head)) 63 | cout << "Loop found"; 64 | else 65 | cout << "No Loop"; 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Detect_Loop_in_Linked_List_Without_Floyd_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | int data; 7 | Node *next; 8 | int visited; 9 | }; 10 | 11 | void push(Node **head_ref, int val) 12 | { 13 | Node *newNode = new Node(); 14 | newNode->data = val; 15 | newNode->next = *head_ref; 16 | *head_ref = newNode; 17 | } 18 | 19 | bool detectLoop(Node *head) 20 | { 21 | Node *ptr = head; 22 | while(ptr) 23 | { 24 | if(ptr->visited == 1) return true; 25 | ptr->visited = 1; 26 | ptr = ptr->next; 27 | } 28 | return false; 29 | } 30 | 31 | int main() 32 | { 33 | Node *head = NULL; 34 | 35 | push(&head, 10); 36 | push(&head, 9); 37 | push(&head, 8); 38 | push(&head, 7); 39 | push(&head, 6); 40 | push(&head, 5); 41 | push(&head, 4); 42 | push(&head, 3); 43 | 44 | // head->next->next->next->next->next = head; 45 | if(detectLoop(head)) cout << "Loop is present in the List\n"; 46 | else cout << "No Loop is present\n"; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Find middle node.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | typedef struct Node { 6 | int data; 7 | struct Node* next; 8 | } SLL; 9 | 10 | /* Function to get the middle node in the linked list*/ 11 | void findMiddle(SLL *head) 12 | { 13 | /* fast pointer moves two times fast as compared to slow pointer 14 | slow pointer iterates through each node but fast pointer skips every other node 15 | when the fast pointer reaches to the end then the slow pointer will be at the middle node 16 | */ 17 | SLL *slow = head; 18 | SLL *fast = head; 19 | 20 | // iterating slow and fast pointers until fast becomes null or fast->next becomes null 21 | while(fast != NULL && fast->next != NULL) 22 | { 23 | slow = slow->next; 24 | fast = fast->next->next; 25 | } 26 | 27 | printf("Middle node data : %d\n", slow->data); 28 | } 29 | 30 | void push(SLL** head_ref, int new_data) 31 | { 32 | /* allocate node */ 33 | SLL* new_node = new Node(); 34 | 35 | /* put in the data */ 36 | new_node->data = new_data; 37 | 38 | /* link the old list off the new node */ 39 | new_node->next = (*head_ref); 40 | 41 | /* move the head to point to the new node */ 42 | (*head_ref) = new_node; 43 | } 44 | 45 | // Driver Code 46 | int main() 47 | { 48 | /* Start with the empty list */ 49 | SLL* head = NULL; 50 | 51 | // create linked 20->4->15->35->10->44->91->2->31 52 | push(&head, 20); 53 | push(&head, 4); 54 | push(&head, 15); 55 | push(&head, 35); 56 | push(&head, 10); // Middle Node 57 | push(&head, 44); 58 | push(&head, 91); 59 | push(&head, 2); 60 | push(&head, 31); 61 | 62 | findMiddle(head); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/Nth_node_from_the_end.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | /* Function to get the nth node from the last of a linked list*/ 11 | void printNthFromLast(struct Node* head, int n) 12 | { 13 | int len = 0, i; 14 | struct Node* temp = head; 15 | 16 | // count the number of nodes in Linked List 17 | while (temp != NULL) { 18 | temp = temp->next; 19 | len++; 20 | } 21 | 22 | // check if value of n is not 23 | // more than length of the linked list 24 | if (len < n) 25 | return; 26 | 27 | temp = head; 28 | 29 | // get the (len-n+1)th node from the beginning 30 | for (i = 1; i < len - n + 1; i++) 31 | temp = temp->next; 32 | 33 | cout << temp->data; 34 | 35 | return; 36 | } 37 | 38 | void push(struct Node** head_ref, int new_data) 39 | { 40 | /* allocate node */ 41 | struct Node* new_node = new Node(); 42 | 43 | /* put in the data */ 44 | new_node->data = new_data; 45 | 46 | /* link the old list off the new node */ 47 | new_node->next = (*head_ref); 48 | 49 | /* move the head to point to the new node */ 50 | (*head_ref) = new_node; 51 | } 52 | 53 | // Driver Code 54 | int main() 55 | { 56 | /* Start with the empty list */ 57 | struct Node* head = NULL; 58 | 59 | // create linked 35->15->4->20 60 | push(&head, 20); 61 | push(&head, 4); 62 | push(&head, 15); 63 | push(&head, 35); 64 | 65 | printNthFromLast(head, 4); 66 | return 0; 67 | } -------------------------------------------------------------------------------- /C++/Linked LIst/Question/ReverseALinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | //Reverse a linked list 4 | struct Node{ 5 | int data; 6 | Node *next; 7 | }; 8 | class LinkedList{ 9 | Node *head; 10 | public: 11 | LinkedList(); 12 | void append(int value); 13 | void reverse(); 14 | void printList(); 15 | }; 16 | LinkedList::LinkedList(){ 17 | head = nullptr; 18 | } 19 | void LinkedList::append(int value){ 20 | if(head==nullptr){ 21 | head = new Node; 22 | head->next = nullptr; 23 | head->data = value; 24 | } 25 | else{ 26 | Node *n =head; 27 | Node *new_node = new Node; 28 | new_node->data = value; 29 | while(n->next!=nullptr) 30 | n=n->next; 31 | n->next = new_node; 32 | new_node->next = nullptr; 33 | } 34 | } 35 | void LinkedList::reverse(){ 36 | Node *prev, *next , *curr; 37 | prev = nullptr; 38 | curr=head; 39 | while(curr!=nullptr){ 40 | next=curr->next; 41 | curr->next=prev; 42 | prev = curr; 43 | curr=next; 44 | } 45 | head = prev; 46 | } 47 | void LinkedList::printList(){ 48 | Node *n = head; 49 | while(n!=nullptr){ 50 | cout<data<<" "; 51 | n= n->next; 52 | } 53 | cout<>a; 64 | if(a==3){ 65 | break; 66 | } 67 | switch (a) 68 | { 69 | case 1:{ 70 | int new_element; 71 | cout<<"Enter the element to be added: "; 72 | cin>>new_element; 73 | ll.append(new_element); 74 | break; 75 | } 76 | case 2:{ 77 | cout<<"Orignal: "; 78 | ll.printList(); 79 | ll.reverse(); 80 | cout<<"Reversed: "; 81 | ll.printList(); 82 | break; 83 | } 84 | } 85 | } 86 | return 0; 87 | } -------------------------------------------------------------------------------- /C++/Linked LIst/Question/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to reverse a linked list 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct Node { 7 | int data; 8 | struct Node* next; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | struct LinkedList { 17 | Node* head; 18 | LinkedList() { head = NULL; } 19 | 20 | /* Function to reverse the linked list */ 21 | void reverse() 22 | { 23 | // Initialize current, previous and next pointers 24 | Node* current = head; 25 | Node *prev = NULL, *next = NULL; 26 | 27 | while (current != NULL) { 28 | // Store next 29 | next = current->next; 30 | // Reverse current node's pointer 31 | current->next = prev; 32 | // Move pointers one position ahead. 33 | prev = current; 34 | current = next; 35 | } 36 | head = prev; 37 | } 38 | 39 | /* Function to print linked list */ 40 | void print() 41 | { 42 | struct Node* temp = head; 43 | while (temp != NULL) { 44 | cout << temp->data << " "; 45 | temp = temp->next; 46 | } 47 | } 48 | 49 | void push(int data) 50 | { 51 | Node* temp = new Node(data); 52 | temp->next = head; 53 | head = temp; 54 | } 55 | }; 56 | 57 | /* Driver code*/ 58 | int main() 59 | { 60 | /* Start with the empty list */ 61 | LinkedList ll; 62 | ll.push(20); 63 | ll.push(4); 64 | ll.push(15); 65 | ll.push(85); 66 | 67 | cout << "Given linked list\n"; 68 | ll.print(); 69 | 70 | ll.reverse(); 71 | 72 | cout << "\nReversed Linked list \n"; 73 | ll.print(); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/StackFromLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node{ 4 | int data; 5 | Node *next; 6 | }; 7 | class Stack{ 8 | Node *head; 9 | public: 10 | Stack(){ 11 | head = nullptr; 12 | } 13 | void push(int value); 14 | void pop(); 15 | int top(); 16 | bool isEmpty(); 17 | void printStack(); 18 | }; 19 | void Stack::push(int value){ 20 | Node *new_node = new Node; 21 | new_node->data = value; 22 | new_node->next = head; 23 | head = new_node; 24 | } 25 | void Stack::pop(){ 26 | if(!isEmpty()){ 27 | Node *new_top = head->next; 28 | Node *temp = head; 29 | delete temp; 30 | head = new_top; 31 | } 32 | else{ 33 | cout<<"Stack is already empty"<data; 39 | } 40 | else{ 41 | cout<<"Already empty"<data<<" "; 57 | n=n->next; 58 | } 59 | cout<>a; 71 | if(a==4){ 72 | break; 73 | } 74 | switch (a) 75 | { 76 | case 1:{ 77 | int new_element; 78 | cout<<"Enter the element to be added: "; 79 | cin>>new_element; 80 | x.push(new_element); 81 | break; 82 | } 83 | case 2:{ 84 | cout<<"Element popped: "< 2 | #include 3 | using namespace std; 4 | 5 | // A stack based efficient method to calculate 6 | // stock span values 7 | void calculateSpan(int price[], int n, int S[]) 8 | { 9 | // Create a stack and push index of first 10 | // element to it 11 | stack st; 12 | st.push(0); 13 | 14 | // Span value of first element is always 1 15 | S[0] = 1; 16 | 17 | // Calculate span values for rest of the elements 18 | for (int i = 1; i < n; i++) { 19 | // Pop elements from stack while stack is not 20 | // empty and top of stack is smaller than 21 | // price[i] 22 | while (!st.empty() && price[st.top()] <= price[i]) 23 | st.pop(); 24 | 25 | // If stack becomes empty, then price[i] is 26 | // greater than all elements on left of it, 27 | // i.e., price[0], price[1], ..price[i-1]. Else 28 | // price[i] is greater than elements after 29 | // top of stack 30 | S[i] = (st.empty()) ? (i + 1) : (i - st.top()); 31 | 32 | // Push this element to stack 33 | st.push(i); 34 | } 35 | } 36 | 37 | // A utility function to print elements of array 38 | void printArray(int arr[], int n) 39 | { 40 | for (int i = 0; i < n; i++) 41 | cout << arr[i] << " "; 42 | } 43 | 44 | // Driver program to test above function 45 | int main() 46 | { 47 | int n; 48 | cin>>n; 49 | for(int i=0;i>price[i]; 52 | } 53 | int S[n]; 54 | 55 | // Fill the span values in array S[] 56 | calculateSpan(price, n, S); 57 | 58 | // print the calculated span values 59 | printArray(S, n); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/add_two_numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | int sum=0,carry=0; 15 | ListNode* ans=NULL,*res=NULL; 16 | while(l1 or l2 or carry) 17 | { 18 | sum=0; 19 | if(l1) 20 | { 21 | sum+=l1->val; 22 | l1=l1->next; 23 | } 24 | if(l2) 25 | { 26 | sum+=l2->val; 27 | l2=l2->next; 28 | } 29 | sum+=carry; 30 | carry=sum/10; 31 | if(!ans) 32 | { 33 | ans= new ListNode(sum%10); 34 | res=ans; 35 | } 36 | else 37 | { 38 | ans->next= new ListNode(sum%10); 39 | ans=ans->next; 40 | } 41 | } 42 | return res; 43 | 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/Linked LIst/Question/delete_head_without_head_pointer.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct Node { 7 | int data; 8 | struct Node *next; 9 | Node(int x) { 10 | data = x; 11 | next = NULL; 12 | } 13 | }*head; 14 | 15 | Node *findNode(Node* head, int search_for) 16 | { 17 | Node* current = head; 18 | while (current != NULL) 19 | { 20 | if (current->data == search_for) 21 | break; 22 | current = current->next; 23 | } 24 | return current; 25 | } 26 | 27 | 28 | void insert() 29 | { 30 | int n,i,value; 31 | Node *temp; 32 | scanf("%d",&n); 33 | 34 | for(i=0; inext= new Node(value); 46 | temp=temp->next; 47 | temp->next=NULL; 48 | } 49 | } 50 | } 51 | 52 | /* Function to print linked list */ 53 | void printList(Node *node) 54 | { 55 | while (node != NULL) 56 | { 57 | printf("%d ", node->data); 58 | node = node->next; 59 | } 60 | cout << endl; 61 | } 62 | 63 | 64 | void deleteNode(Node *node_ptr); 65 | 66 | /* Drier program to test above function*/ 67 | int main(void) 68 | { 69 | /* Start with the empty list */ 70 | 71 | int t,k,n,value; 72 | 73 | scanf("%d",&t); 74 | while(t--) 75 | { 76 | insert(); 77 | scanf("%d",&k); 78 | Node *del = findNode(head, k); 79 | if (del != NULL && del->next != NULL) 80 | { 81 | deleteNode(del); 82 | } 83 | printList(head); 84 | } 85 | return(0); 86 | } 87 | 88 | 89 | // } Driver Code Ends 90 | /* 91 | struct Node { 92 | int data; 93 | struct Node *next; 94 | Node(int x) { 95 | data = x; 96 | next = NULL; 97 | } 98 | }*head; 99 | */ 100 | 101 | // This function should delete node from linked list. The function 102 | // may assume that node exists in linked list and is not last node 103 | // node: reference to the node which is to be deleted 104 | void deleteNode(Node *node) 105 | { 106 | *node=*(node->next); 107 | } 108 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | typedef struct Node { 6 | int data; 7 | struct Node *pre; 8 | struct Node *next; 9 | }Node; 10 | Node* head = NULL; 11 | 12 | void print() { 13 | Node* ptr; 14 | ptr = head; 15 | while(!(ptr == NULL)) { 16 | cout<< ptr->data <<"\t"; 17 | ptr = ptr->next; 18 | } 19 | } 20 | 21 | 22 | 23 | void insert(int info) { 24 | Node* newnode = (struct Node*) malloc(sizeof(Node)); 25 | newnode->next = head; 26 | newnode->pre = NULL; 27 | newnode->data = info; 28 | if(!(head == NULL)) 29 | head->pre = newnode ; 30 | head = newnode; 31 | } 32 | 33 | int main() { 34 | insert(1); 35 | insert(2); 36 | insert(3); 37 | insert(4); 38 | insert(5); 39 | insert(6); 40 | insert(7); 41 | cout<<"doubly linked list::: "< 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | // constructor 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | void insertAtTail(Node* &tail, int d){ 18 | Node *temp = new Node(d); 19 | tail -> next = temp; 20 | tail = tail ->next; 21 | } 22 | 23 | void print(Node* &head) 24 | { 25 | Node* temp = head; 26 | 27 | while (temp != NULL) 28 | { 29 | cout << temp->data << " "; 30 | temp = temp->next; 31 | } 32 | cout << endl; 33 | } 34 | 35 | int main() 36 | { // created a new node 37 | Node *node1 = new Node(42); 38 | // //tail pointer to node1😃 39 | Node* head = node1; 40 | Node* tail = node1; 41 | insertAtTail(tail, 12); 42 | insertAtTail(tail, 15); 43 | print(head); 44 | 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/insertAthead.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node 4 | { 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | // constructor 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | void insertAtHead(Node *&head, int d) 18 | { 19 | Node *temp = new Node(d); 20 | temp->next = head; 21 | head = temp; 22 | } 23 | 24 | void print(Node* &head) 25 | { 26 | Node* temp = head; 27 | 28 | while (temp != NULL) 29 | { 30 | cout << temp->data << " "; 31 | temp = temp->next; 32 | } 33 | cout << endl; 34 | } 35 | 36 | int main() 37 | { // created a new node 38 | Node *node1 = new Node(42); 39 | // head pointer to node1 😄 40 | Node* head = node1; 41 | insertAtHead(head, 12); 42 | insertAtHead(head, 15); 43 | print(head); 44 | 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/kReverse.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node* next; 9 | }; 10 | 11 | Node* reverse(Node* head, int k) 12 | { 13 | if (!head) 14 | return NULL; 15 | Node* current = head; 16 | Node* next = NULL; 17 | Node* prev = NULL; 18 | int count = 0; 19 | 20 | while (current != NULL && count < k) { 21 | next = current->next; 22 | current->next = prev; 23 | prev = current; 24 | current = next; 25 | count++; 26 | } 27 | 28 | if (next != NULL) 29 | head->next = reverse(next, k); 30 | 31 | return prev; 32 | } 33 | 34 | void push(Node** head_ref, int new_data) 35 | { 36 | 37 | Node* new_node = new Node(); 38 | 39 | new_node->data = new_data; 40 | 41 | new_node->next = (*head_ref); 42 | 43 | (*head_ref) = new_node; 44 | } 45 | 46 | void printList(Node* node) 47 | { 48 | while (node != NULL) { 49 | cout << node->data << " "; 50 | node = node->next; 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | Node* head = NULL; 57 | 58 | push(&head, 45); 59 | push(&head, 78); 60 | push(&head, 12); 61 | push(&head, 23); 62 | push(&head, 56); 63 | push(&head, 89); 64 | push(&head, 85); 65 | push(&head, 52); 66 | push(&head, 10); 67 | 68 | cout << "Given linked list \n"; 69 | printList(head); 70 | head = reverse(head, 4); 71 | 72 | cout << "\nReversed Linked list \n"; 73 | printList(head); 74 | 75 | return (0); 76 | } 77 | 78 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/lenghOfLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | //Linked List Node class 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | this->next = NULL; 13 | } 14 | }; 15 | 16 | Node *takeinput() 17 | { 18 | int data; 19 | cin >> data; 20 | Node *head = NULL, *tail = NULL; 21 | while (data != -1) 22 | { 23 | Node *newNode = new Node(data); 24 | if (head == NULL) 25 | { 26 | head = newNode; 27 | tail = newNode; 28 | } 29 | else 30 | { 31 | tail->next = newNode; 32 | tail = newNode; 33 | } 34 | cin >> data; 35 | } 36 | return head; 37 | } 38 | //function to calculate the no. of nodes in a Linked List 39 | int length(Node *head) 40 | { 41 | int count=0; 42 | while(head!=NULL) 43 | { 44 | count++; 45 | head=head->next; 46 | } 47 | return count; 48 | } 49 | 50 | int main() 51 | { 52 | Node *head = takeinput(); 53 | cout << length(head) << endl; 54 | return 0; 55 | } 56 | 57 | /* 58 | Sample Input: 59 | 4 4 7 8 3 36 8 17 26 7 7 -1 60 | Sample Output 61 | 11 62 | */ 63 | -------------------------------------------------------------------------------- /C++/Linked LIst/Question/linked list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Creating a node 5 | class Node 6 | { 7 | public: 8 | int value; 9 | Node *next; 10 | }; 11 | 12 | int main() 13 | { 14 | Node *head; 15 | Node *one = NULL; 16 | Node *two = NULL; 17 | Node *three = NULL; 18 | 19 | // allocate 3 nodes in the heap 20 | one = new Node(); 21 | two = new Node(); 22 | three = new Node(); 23 | 24 | // Assign value values 25 | one->value = 1; 26 | two->value = 2; 27 | three->value = 3; 28 | 29 | // Connect nodes 30 | one->next = two; 31 | two->next = three; 32 | three->next = NULL; 33 | 34 | // print the linked list value 35 | head = one; 36 | while (head != NULL) 37 | { 38 | printf("%d ", head->value); 39 | head = head->next; 40 | } 41 | } -------------------------------------------------------------------------------- /C++/Linked LIst/Singly Linked List/Reverse_K_nodes_in_a_Linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | int data; 7 | node* next; 8 | 9 | node(int val) 10 | { 11 | data=val; 12 | next=NULL; 13 | } 14 | }; 15 | 16 | void insertAtHead(node* &head, int val) 17 | { 18 | node* n = new node(val); 19 | n->next=head; 20 | head=n; 21 | } 22 | 23 | void insertAtTail(node* &head, int val) //Putting the value using call by refence (head) value because here we are modifying our link list 24 | { 25 | node* n = new node(val); 26 | if(head==NULL) 27 | { 28 | head=n; 29 | return; 30 | } 31 | 32 | node* temp=head; 33 | while(temp->next!=NULL) 34 | { 35 | temp=temp->next; 36 | } 37 | temp->next=n; 38 | } 39 | 40 | void display(node* head) //Calling the function by value 41 | { 42 | node* temp=head; 43 | while(temp!=NULL) 44 | { 45 | cout<data<<"->"; 46 | temp=temp->next; 47 | } 48 | cout<<"NULL"<next; 61 | currptr->next=prevptr; 62 | prevptr=currptr; 63 | currptr=nextptr; 64 | count++; 65 | } 66 | if(nextptr!=NULL){ 67 | head->next= reversek(nextptr,k); 68 | } 69 | } 70 | 71 | int main() 72 | { 73 | node* head=NULL; 74 | insertAtTail(head,1); 75 | insertAtTail(head,2); 76 | insertAtTail(head,3); 77 | insertAtTail(head,4); 78 | insertAtTail(head,5); 79 | insertAtTail(head,6); 80 | 81 | display(head); 82 | int k=2; 83 | node* newhead=reversek(head,k); 84 | display(newhead); 85 | return 0; 86 | } 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /C++/Linked LIst/Singly Linked List/Reverse_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef struct node { 5 | int val; 6 | struct node* next; 7 | } node; 8 | 9 | node* head = NULL; 10 | 11 | 12 | int count(node* head) 13 | { 14 | node* p = head; 15 | int k = 1; 16 | while (p != NULL) { 17 | p = p->next; 18 | k++; 19 | } 20 | return k; 21 | } 22 | 23 | node* ll_reverse(node* head) 24 | { 25 | node* p = head; 26 | long int i = count(head), j = 1; 27 | long int arr[i]; 28 | while (i && p != NULL) { 29 | arr[j++] = p->val; 30 | p = p->next; 31 | i--; 32 | } 33 | j--; 34 | while (j) 35 | cout << arr[j--] << " "; 36 | return head; 37 | } 38 | 39 | 40 | node* insert_end(node* head, int data) 41 | { 42 | node *q = head, *p = (node*)malloc(sizeof(node)); 43 | p->val = data; 44 | while (q->next != NULL) 45 | q = q->next; 46 | q->next = p; 47 | p->next = NULL; 48 | return head; 49 | } 50 | 51 | node* create_ll(node* head, int data) 52 | { 53 | node* p = (node*)malloc(sizeof(node)); 54 | p->val = data; 55 | if (head == NULL) { 56 | head = p; 57 | p->next = NULL; 58 | return head; 59 | } 60 | else { 61 | head = insert_end(head, data); 62 | return head; 63 | } 64 | } 65 | 66 | 67 | int main() 68 | { 69 | int i = 5, j = 1; 70 | while (i--) 71 | head = create_ll(head, j++); 72 | head = ll_reverse(head); 73 | return 0; 74 | } 75 | 76 | 77 | -------------------------------------------------------------------------------- /C++/Linked LIst/Singly Linked List/deletion_of_linkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef struct LinkedList 5 | { 6 | int data; 7 | LinkedList *next; 8 | 9 | } List; 10 | 11 | int Traverse(LinkedList *head) 12 | { 13 | 14 | cout << "The data is : "; 15 | 16 | int count = 0; 17 | LinkedList *current = head; 18 | while (current != NULL) 19 | { 20 | cout << current->data << " "; 21 | current = current->next; 22 | count++; 23 | } 24 | return count; 25 | } 26 | void delete_list(List ** head){ 27 | 28 | List * iterator ,* auxNode ; 29 | 30 | iterator = *head; 31 | while (iterator) 32 | { 33 | auxNode = iterator->next; 34 | delete iterator; 35 | iterator = auxNode; 36 | 37 | } 38 | 39 | *head = NULL; 40 | 41 | } 42 | 43 | // Time Complexity: O(n), for scanning the complete list of size n. 44 | // Space Complexity: O(1), for creating one temporary variable. 45 | 46 | int main(){ 47 | 48 | List *head; 49 | 50 | List *node1 = new List; 51 | List *node2 = new List; 52 | List *node3 = new List; 53 | List *node4 = new List; 54 | List *node5 = new List; 55 | 56 | head = node1; 57 | 58 | node1->data = 1; 59 | node1->next = node2; 60 | 61 | node2->data = 2; 62 | node2->next = node3; 63 | 64 | node3->data = 3; 65 | node3->next = node4; 66 | 67 | node4->data = 4; 68 | node4->next = node5; 69 | 70 | node5->data = 5; 71 | node5->next = NULL; 72 | 73 | Traverse(head); 74 | cout< 2 | using namespace std; 3 | struct node{ 4 | 5 | int data; 6 | node * next; 7 | 8 | }; 9 | 10 | void create(node * ptr){ 11 | int num; 12 | cout<<"Total nodes = ";cin>>num; 13 | int n = 0; 14 | while (n < num){ 15 | 16 | cout<<"Enter data "<>ptr->data; 17 | ptr->next = new node; 18 | ptr = ptr->next; 19 | n++; 20 | } 21 | ptr->next = NULL; 22 | 23 | } 24 | void traverse(node * ptr){ 25 | 26 | while (ptr->next != NULL) 27 | { 28 | cout<data<<"->"; 29 | ptr = ptr->next; 30 | } 31 | cout< 2 | using namespace std; 3 | struct node{ 4 | 5 | int data; 6 | node * next; 7 | 8 | }; 9 | node * start; 10 | 11 | node * create(){ 12 | int num; 13 | cout<<"Total nodes = ";cin>>num; 14 | start = new node; 15 | node * ptr = start; 16 | int n = 0; 17 | while (n < num){ 18 | 19 | cout<<"Enter data "<>ptr->data; 20 | ptr->next = new node; 21 | ptr = ptr->next; 22 | n++; 23 | } 24 | ptr->next = NULL; 25 | 26 | return start; 27 | 28 | } 29 | void traverse(node * ptr){ 30 | 31 | while (ptr->next != NULL) 32 | { 33 | cout<data<<"->"; 34 | ptr = ptr->next; 35 | } 36 | cout< 2 | #include 3 | struct List 4 | { 5 | char data; 6 | struct List *next; 7 | }; 8 | typedef struct List Linked; 9 | int main() 10 | { 11 | Linked *start; 12 | Linked node1, node2, node3, node4; 13 | int i; 14 | start = (struct List *)malloc(sizeof(Linked)); 15 | start = &node1; 16 | node1.data = 'A'; 17 | node1.next = &node2; 18 | node2.data = 'B'; 19 | node2.next = &node3; 20 | node3.data = 'C'; 21 | node3.next = &node4; 22 | node4.data = 'D'; 23 | for (i = 0; i < 4; i++) 24 | { 25 | printf("%c", start->data); 26 | start = start->next; 27 | } 28 | printf("\n Press a key"); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/Linked LIst/Singly Linked List/traversal_of_LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef struct Admission 5 | { 6 | int clas ; 7 | int rollno; 8 | string name; 9 | Admission * next; 10 | } LinkedList ; 11 | 12 | 13 | int Traverse( LinkedList * head){ 14 | 15 | int count = 0; 16 | LinkedList * current = head; 17 | while (current != NULL) 18 | { 19 | cout<<" Name - "<name<clas<rollno<next; 24 | 25 | cout<<"--------------------------------------------------------\n"; 26 | count++; 27 | } 28 | return count; 29 | 30 | // Time Complexity: O(n), for scanning the list of size n. 31 | // Space Complexity: O(1), for creating a temporary variable. 32 | 33 | } 34 | int main(){ 35 | 36 | 37 | // Majorly this is impelemtation in c in c++ it will be uite smooth 38 | 39 | LinkedList * ad_data; 40 | 41 | LinkedList node1, node2 , node3 , node4; 42 | 43 | ad_data = &node1; 44 | 45 | node1.clas = 9; 46 | node1.rollno = 9; 47 | node1.name = "Ankita"; 48 | node1.next = &node2; 49 | 50 | node2.clas = 9; 51 | node2.rollno = 32; 52 | node2.name = "Manraj"; 53 | node2.next = &node3; 54 | 55 | node3.clas = 9; 56 | node3.rollno = 9; 57 | node3.name = "Ankita"; 58 | node3.next = &node4; 59 | 60 | node4.clas = 9; 61 | node4.rollno = 32; 62 | node4.name = "Manraj"; 63 | node4.next = NULL; 64 | 65 | int Traverse_ = Traverse(ad_data); 66 | 67 | cout<<" Total nodes are "< 2 | using namespace std; 3 | int main() 4 | { 5 | int b = 0; 6 | int *a = &b; 7 | 8 | cout << " + - " << uintptr_t(a) << ' ' << a; 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /C++/Linked LIst/XOR Memory Efficient LinkedList/traverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef struct LL 4 | { 5 | int data; 6 | LL *ptrdiff; 7 | }ll; 8 | 9 | ll * xor_opr (ll *a, ll *b) 10 | { 11 | return (ll*) ((uintptr_t) a ^ (uintptr_t) b); // unsigned integer type capable of holding a pointer 12 | } 13 | 14 | void traverse(ll * head ){ 15 | 16 | ll * current = head; 17 | ll * prev = NULL , * next; 18 | 19 | cout<<"Items are : "; 20 | 21 | while (current != NULL) 22 | { 23 | cout<data<<" "; 24 | next = xor_opr(prev , current->ptrdiff); 25 | prev = current; 26 | current = next; 27 | } 28 | 29 | } 30 | 31 | int main() 32 | { 33 | 34 | LL *head; 35 | 36 | LL *node1, *node2, *node3, *node4; 37 | 38 | node1 = new LL; 39 | node2 = new LL; 40 | node3 = new LL; 41 | node4 = new LL; 42 | 43 | node1->data = 1; 44 | node2->data = 2; 45 | node3->data = 3; 46 | node4->data = 4; 47 | 48 | head = node1; 49 | 50 | node1->ptrdiff = xor_opr(NULL , node2); 51 | node2->ptrdiff = xor_opr(node1 , node3); 52 | node3->ptrdiff = xor_opr(node2 , node4); 53 | node4->ptrdiff = xor_opr(node3 , NULL); 54 | 55 | traverse(head); 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /C++/Questions/ABit++Codeforces.cpp: -------------------------------------------------------------------------------- 1 | /*Author : Manraj Singh */ 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | 8 | ios::sync_with_stdio(false); 9 | cin.tie(0); 10 | cout.tie(0); 11 | 12 | int n; 13 | 14 | cin >> n; 15 | int x = 0; 16 | while (n--) 17 | { 18 | 19 | string s; 20 | cin >> s; 21 | if (s == "--X" || s == "X--") 22 | { 23 | 24 | x--; 25 | } 26 | else 27 | { 28 | 29 | x++; 30 | } 31 | } 32 | 33 | cout << x << "\n"; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/Queue/Deletion in a Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to remove an element from the queue 5 | 6 | void remove(int t, queue& q) 7 | { 8 | queue ref; 9 | int s = q.size(); 10 | int cnt = 0; 11 | 12 | // Finding the value to be removed 13 | while (q.front() != t and !q.empty()) { 14 | ref.push(q.front()); 15 | q.pop(); 16 | cnt++; 17 | } 18 | 19 | // If element is not found 20 | if (q.empty()) { 21 | cout << "element not found!!" << endl; 22 | while (!ref.empty()) { 23 | 24 | // Pushing all the elements back into q 25 | q.push(ref.front()); 26 | ref.pop(); 27 | } 28 | } 29 | 30 | // If element is found 31 | else { 32 | q.pop(); 33 | while (!ref.empty()) { 34 | 35 | // Pushing all the elements back into q 36 | q.push(ref.front()); 37 | ref.pop(); 38 | } 39 | int k = s - cnt - 1; 40 | while (k--) { 41 | 42 | // Pushing elements from front of q to its back 43 | int p = q.front(); 44 | q.pop(); 45 | q.push(p); 46 | } 47 | } 48 | } 49 | 50 | // Function to print all the elements of the queue. 51 | void print(queue qr) 52 | { 53 | while (!qr.empty()) { 54 | cout << qr.front() << " "; 55 | qr.pop(); 56 | } 57 | cout << endl; 58 | } 59 | 60 | int main() 61 | { 62 | queue q; 63 | 64 | // Pushing into the queue 65 | q.push(10); 66 | q.push(20); 67 | q.push(30); 68 | q.push(40); 69 | q.push(50); 70 | q.push(60); 71 | print(q); 72 | 73 | // Removing 39 from the queue 74 | remove(39, q); 75 | print(q); 76 | 77 | // Removing 30 from the queue 78 | remove(30, q); 79 | print(q); 80 | return 0; 81 | } -------------------------------------------------------------------------------- /C++/Queue/Insertion_in_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int insert_in_queue(int [], int); 6 | void display(int [], int, int); 7 | 8 | const int SIZE = 50; 9 | 10 | int queue[SIZE]; 11 | 12 | //We have two ends i.e. “front” and “rear” of the queue. When the queue is empty, then both the pointers are set to -1. 13 | //The “rear” end pointer is the place from where the elements are inserted in the queue. The operation of adding /inserting elements in the queue is called “enqueue”. 14 | //The “front” end pointer is the place from where the elements are removed from the queue. The operation to remove/delete elements from the queue is called “dequeue”. 15 | 16 | int front=-1; 17 | int rear=-1; 18 | 19 | void main() 20 | { 21 | int item, check; 22 | char ch='y'; 23 | // Asking the user to input Y or y incase he wants to add one more element in the queue i.e. enque operation 24 | while(ch=='y' || ch=='Y') 25 | { 26 | cout<<"Enter item for insertion: "; 27 | cin>>item; 28 | check = insert_in_queue(queue, item); 29 | if(check == -1) 30 | { 31 | cout<<"\nOverflow..!!..Aborting..!!..Press a key to exit..\n"; 32 | getch(); 33 | exit(1); 34 | } 35 | cout<<"Item inserted successfully..!!\n"; 36 | cout<<"\nNow the Queue (Front...to...Rear) is:\n"; 37 | display(queue, front, rear); 38 | cout<<"\nWant to insert more ? (y/n).. "; 39 | cin>>ch; 40 | } 41 | getch(); 42 | } 43 | 44 | int insert_in_queue(int queue[], int elem) 45 | { 46 | 47 | //When the rear pointer value is size-1, then we say that the queue is full. When the front is null, then the queue is empty. 48 | 49 | if(rear == SIZE-1) 50 | { 51 | return -1; 52 | } 53 | else if(rear == -1) 54 | { 55 | front = rear = 0; 56 | queue[rear] = elem; 57 | } 58 | else 59 | { 60 | rear++; 61 | queue[rear] = elem; 62 | } 63 | return 0; 64 | } 65 | 66 | // Display the cuurent queue formed as a result of enqueue operation 67 | 68 | void display(int queue[], int front, int rear) 69 | { 70 | if(front == -1) 71 | { 72 | return; 73 | } 74 | for(int i=front; i 2 | using namespace std; 3 | 4 | struct QNode 5 | { 6 | int data; 7 | QNode *next; 8 | QNode(int d) 9 | { 10 | data = d; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | struct Queue 16 | { 17 | QNode *front, *rear; 18 | Queue() { front = rear = NULL; } 19 | 20 | void enQueue(int x) 21 | { 22 | 23 | // Create a new LL node 24 | QNode *temp = new QNode(x); 25 | 26 | // If queue is empty, then 27 | // new node is front and rear both 28 | if (rear == NULL) 29 | { 30 | front = rear = temp; 31 | return; 32 | } 33 | 34 | // Add the new node at 35 | // the end of queue and change rear 36 | rear->next = temp; 37 | rear = temp; 38 | } 39 | 40 | // Function to remove 41 | // a key from given queue q 42 | void deQueue() 43 | { 44 | // If queue is empty, return NULL. 45 | if (front == NULL) 46 | return; 47 | 48 | // Store previous front and 49 | // move front one node ahead 50 | QNode *temp = front; 51 | front = front->next; 52 | 53 | // If front becomes NULL, then 54 | // change rear also as NULL 55 | if (front == NULL) 56 | rear = NULL; 57 | 58 | delete (temp); 59 | } 60 | }; 61 | 62 | // Driven Program 63 | int main() 64 | { 65 | 66 | Queue q; 67 | q.enQueue(10); 68 | q.enQueue(20); 69 | q.deQueue(); 70 | q.deQueue(); 71 | q.enQueue(30); 72 | q.enQueue(40); 73 | q.enQueue(50); 74 | q.deQueue(); 75 | cout << "Queue Front : " << (q.front)->data << endl; 76 | cout << "Queue Rear : " << (q.rear)->data; 77 | } 78 | // This code is contributed by rathbhupendra 79 | -------------------------------------------------------------------------------- /C++/Queue/Singly Queue/Queue_Implemantiation_Using_Linked_List.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/C++/Queue/Singly Queue/Queue_Implemantiation_Using_Linked_List.exe -------------------------------------------------------------------------------- /C++/Queue/Singly Queue/Queue_Implementiatio_Using_Array.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/C++/Queue/Singly Queue/Queue_Implementiatio_Using_Array.exe -------------------------------------------------------------------------------- /C++/Queue/deletion_in_Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // creating a queue using list 4 | class Queue 5 | { 6 | public: 7 | list L; 8 | void Push(int i) //adding elements 9 | { 10 | cout<<“Pushing the element : “<<(i)< 2 | using namespace std; 3 | 4 | unordered_mapsymbol={ {'[',-1},{'(',-2},{'{',-3},{']',1},{')',2},{'}',3}}; 5 | void solve() 6 | { 7 | string s; 8 | cin >> s; 9 | stackst; 10 | for(auto bracket : s) 11 | { 12 | if(symbol[bracket]<0) 13 | { 14 | st.push(bracket); 15 | } 16 | else 17 | { 18 | if(st.empty()) 19 | { 20 | cout << "NO\n"; 21 | return; 22 | } 23 | char top=st.top(); 24 | st.pop(); 25 | if(symbol[top]+symbol[bracket]!=0) 26 | { 27 | cout << "NO\n"; 28 | return; 29 | } 30 | } 31 | } 32 | if(st.empty()) 33 | { 34 | cout << "YES\n"; 35 | return; 36 | } 37 | cout << "NO\n"; 38 | return; 39 | 40 | } 41 | 42 | int main() 43 | { 44 | int t; 45 | cin >> t; 46 | while(t--) 47 | { 48 | solve(); 49 | } 50 | } 51 | 52 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/Maximum Element using Stacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main() 6 | { 7 | stack s1,s2; 8 | int n,t,val; 9 | 10 | cin>>n; 11 | if(n==1) 12 | { 13 | cin>>val; 14 | s1.push(val); 15 | if(s2.empty()) 16 | s2.push(val); 17 | else 18 | { 19 | if(val>s2.top()) 20 | s2.push(val); 21 | else 22 | s2.push(s2.top()); 23 | } 24 | } 25 | else if(n==2) 26 | { 27 | s1.pop(); 28 | s2.pop(); 29 | } 30 | else if(n==3) 31 | { 32 | cout< 2 | #include 3 | 4 | typedef long long int ll; 5 | 6 | using namespace std; 7 | 8 | #define SIZE 1000 9 | int top=-1; 10 | int stackk[SIZE]; 11 | 12 | int pop() 13 | { 14 | if(top==-1) 15 | {printf("Stack UnderFlow\n"); 16 | return -12345678;} 17 | else 18 | return stackk[top--]; 19 | } 20 | void push(int data) 21 | { 22 | if(top==SIZE-1) 23 | printf("Stack OverFlow!\n"); 24 | else 25 | stackk[++top]=data; 26 | } 27 | int peek() 28 | { 29 | if(top==-1) 30 | {printf("Stack UnderFlow!\n"); 31 | return -1;} 32 | else 33 | return stackk[top]; 34 | } 35 | int main() 36 | { 37 | string exp; 38 | printf("Enter the Postfix expression--\n"); 39 | cin>>exp; 40 | int l=exp.length(),k,op1,op2; 41 | for(int i=0;i=48&&k<=57) 45 | push(k-48); 46 | else 47 | { 48 | op1=pop(); 49 | op2=pop(); 50 | if(op1==-12345678||op2==-12345678) 51 | { 52 | printf("Not Enough Operands...Sorry!\n"); 53 | break; 54 | } 55 | char ch=exp[i]; 56 | switch(ch) 57 | { 58 | case '*': push(op2*op1); 59 | break; 60 | case '/': push(op2/op1); 61 | break; 62 | case '-': push(op2-op1); 63 | break; 64 | case '+': push(op2+op1); 65 | break; 66 | case '^': push(pow(op2,op1)); 67 | break; 68 | } 69 | } 70 | } 71 | if(op1!=-12345678&&op2!=-12345678) 72 | {if(top==0){ 73 | printf("Output of %s is: %d\n\n",exp,peek()); 74 | } 75 | else 76 | printf("Too many Operands...Oops!\n");} 77 | cout<<"Thank you!"< 2 | #include 3 | 4 | using namespace std; 5 | 6 | string reverse(string str){ 7 | int s = 0; 8 | int e = str.size() - 1; 9 | char temp; 10 | while(s < e){ 11 | temp = str[s]; 12 | str[s] = str[e]; 13 | str[e] = temp; 14 | s++;e--; 15 | } 16 | return str; 17 | } 18 | string removeTheStars(string s) { 19 | stack st; 20 | int n = s.size(); 21 | 22 | for(int i = 0; i 2 | 3 | using namespace std; 4 | 5 | template 6 | class Stack{ 7 | 8 | public: 9 | Stack(int size); 10 | ~Stack(){ 11 | delete[] arr; 12 | }; 13 | 14 | bool empty(); 15 | void push(T x); 16 | void pop(); 17 | int size(); 18 | T top(); 19 | bool full(); 20 | 21 | private: 22 | int capacity; 23 | int cnt; 24 | T* arr; 25 | }; 26 | 27 | template 28 | Stack::Stack(int size){ 29 | arr = new T[size]; 30 | capacity = size; 31 | cnt = 0; 32 | } 33 | 34 | template 35 | bool Stack::empty(){ 36 | if(cnt == 0) { 37 | return true; 38 | } 39 | else { 40 | return false; 41 | } 42 | } 43 | 44 | template 45 | void Stack::push(T x){ 46 | if(!full()) { 47 | arr[cnt] = x; 48 | cnt++; 49 | } 50 | else { 51 | cout << "The stack is full \n"; 52 | } 53 | } 54 | 55 | template 56 | void Stack::pop(){ 57 | if(!empty()){ 58 | cnt--; 59 | } 60 | else { 61 | cout << "The stack is empty \n"; 62 | } 63 | } 64 | 65 | template 66 | int Stack::size(){ 67 | return cnt; 68 | } 69 | 70 | template 71 | T Stack::top(){ 72 | return arr[cnt - 1]; 73 | } 74 | 75 | template 76 | bool Stack::full(){ 77 | return capacity == cnt; 78 | } 79 | 80 | int main(){ 81 | Stack S(1); 82 | S.push('x'); 83 | cout << S.top() << endl; 84 | S.pop(); 85 | cout << S.empty() << endl; 86 | S.push('c'); 87 | cout << S.full() << endl; 88 | cout << S.top() << endl; 89 | cout << S.full() << endl; 90 | S.push(2); 91 | S.pop(); 92 | S.pop(); 93 | } 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/StacksusingLinkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef struct Node 5 | { 6 | int data; 7 | node* next; 8 | } node; 9 | 10 | node* top; 11 | 12 | void push(int num) 13 | { 14 | node* temp; 15 | temp=new Node(); 16 | temp->data=num; 17 | temp->next=top; 18 | top=temp; 19 | } 20 | 21 | void pop() 22 | { 23 | node* temp; 24 | if (top==NULL){ 25 | cout<<"No element in stack\n"; 26 | return; 27 | } 28 | else{ 29 | temp=top; 30 | top=top->next; 31 | temp->next=NULL; 32 | free(temp); 33 | } 34 | } 35 | 36 | void display() 37 | { 38 | node* temp; 39 | if (top==NULL){ 40 | cout<<"No element in Stack\n"; 41 | return; 42 | } 43 | else{ 44 | temp=top; 45 | while (temp!=NULL){ 46 | if(temp->next!=NULL){ 47 | cout<data<<"-> "; 48 | temp=temp->next; 49 | } 50 | else{ 51 | cout<data; 52 | temp=temp->next; 53 | } 54 | } 55 | } 56 | } 57 | 58 | int main() 59 | { 60 | push(10); 61 | push(20); 62 | push(30); 63 | push(40); 64 | display(); 65 | cout<<"\n"; 66 | pop(); 67 | pop(); 68 | push(50); 69 | push(60); 70 | push(70); 71 | pop(); 72 | push(80); 73 | display(); 74 | cout<<"\n"; 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/Two_Stacks_in_one_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Two_Stacks 5 | { 6 | int *arr; 7 | int t, m, n;; 8 | 9 | public: 10 | Two_Stacks(int num) 11 | { 12 | t=num; 13 | arr=new int[num]; 14 | m=-1; 15 | n=t; 16 | } 17 | 18 | 19 | void push1(int x) 20 | { 21 | 22 | if(m<(n - 1)) 23 | { 24 | m++; 25 | arr[m]=x; 26 | } 27 | else 28 | { 29 | cout<<"Stack Overflow"<=0) 51 | { 52 | int temp=arr[m]; 53 | m--; 54 | return temp; 55 | } 56 | else 57 | { 58 | cout<<"Stack UnderFlow"< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | stack stack1; //empty stack of integer type 9 | stack1.push(100); 10 | stack1.push(200); 11 | stack1.push(300); 12 | stack1.push(400); 13 | stack1.push(500); 14 | 15 | stack1.pop(); 16 | stack1.pop(); 17 | 18 | while (!stack1.empty()) 19 | { 20 | cout << "Element =" << stack1.top() << endl; 21 | stack1.pop(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/inserting stacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | stack stack1; //empty stack of integer type 9 | stack1.push(100); 10 | stack1.push(200); 11 | stack1.push(300); 12 | stack1.push(400); 13 | stack1.push(500); 14 | 15 | cout << "The topmost element of the stack is:" << stack1.top() << endl; 16 | cout << "The size of the stack is=" << stack1.size() << endl; 17 | 18 | if (stack1.empty()) 19 | { 20 | cout << "Stack is empty" << endl; 21 | } 22 | else 23 | { 24 | cout << "Stack is not empty" << endl; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/next_greater_frequencey_element.cpp: -------------------------------------------------------------------------------- 1 | // C++ program of Next Greater Frequency Element 2 | #include 3 | using namespace std; 4 | 5 | stack> mystack; 6 | map mymap; 7 | 8 | /*NFG function to find the next greater frequency 9 | element for each element and for placing it in the 10 | resultant array */ 11 | void NGF(int arr[], int res[], int n) { 12 | 13 | // Initially store the frequencies of all elements 14 | // in a hashmap 15 | for(int i = 0; i < n; i++) { 16 | mymap[arr[i]] += 1; 17 | } 18 | 19 | // Get the frequency of the last element 20 | int curr_freq = mymap[arr[n-1]]; 21 | 22 | // push it to the stack 23 | mystack.push({arr[n-1], curr_freq}); 24 | 25 | // place -1 as next greater freq for the last 26 | // element as it does not have next greater. 27 | res[n-1] = -1; 28 | 29 | // iterate through array in reverse order 30 | for(int i = n-2;i>=0;i--) { 31 | curr_freq = mymap[arr[i]]; 32 | 33 | /* If the frequency of the element which is 34 | pointed by the top of stack is greater 35 | than frequency of the current element 36 | then push the current position i in stack*/ 37 | while(mystack.size() > 0 && curr_freq >= mystack.top().second) 38 | mystack.pop(); 39 | 40 | // If the stack is empty, place -1. If it is not empty 41 | // then we will have next higher freq element at the top of the stack. 42 | res[i] = (mystack.size() == 0) ? -1 : mystack.top().first; 43 | 44 | // push the element at current position 45 | mystack.push({arr[i], mymap[arr[i]]}); 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | int arr[] = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; 52 | int n = sizeof(arr) / sizeof(arr[0]); 53 | 54 | int res[n]; 55 | NGF(arr, res, n); 56 | cout << "["; 57 | for(int i = 0; i < n - 1; i++) 58 | { 59 | cout << res[i] << ", "; 60 | } 61 | cout << res[n - 1] << "]"; 62 | 63 | return 0; 64 | } 65 | 66 | // This code is contributed by divyeshrabadiya07. 67 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/post_fix_to_pre_fix_conversation.cpp: -------------------------------------------------------------------------------- 1 | // CPP Program to convert postfix to prefix 2 | #include 3 | using namespace std; 4 | 5 | // function to check if character is operator or not 6 | bool isOperator(char x) 7 | { 8 | switch (x) { 9 | case '+': 10 | case '-': 11 | case '/': 12 | case '*': 13 | return true; 14 | } 15 | return false; 16 | } 17 | 18 | // Convert postfix to Prefix expression 19 | string postToPre(string post_exp) 20 | { 21 | stack s; 22 | 23 | // length of expression 24 | int length = post_exp.size(); 25 | 26 | // reading from right to left 27 | for (int i = 0; i < length; i++) { 28 | 29 | // check if symbol is operator 30 | if (isOperator(post_exp[i])) { 31 | 32 | // pop two operands from stack 33 | string op1 = s.top(); 34 | s.pop(); 35 | string op2 = s.top(); 36 | s.pop(); 37 | 38 | // concat the operands and operator 39 | string temp = post_exp[i] + op2 + op1; 40 | 41 | // Push string temp back to stack 42 | s.push(temp); 43 | } 44 | 45 | // if symbol is an operand 46 | else { 47 | 48 | // push the operand to the stack 49 | s.push(string(1, post_exp[i])); 50 | } 51 | } 52 | 53 | string ans = ""; 54 | while (!s.empty()) { 55 | ans += s.top(); 56 | s.pop(); 57 | } 58 | return ans; 59 | } 60 | 61 | // Driver Code 62 | int main() 63 | { 64 | string post_exp = "ABC/-AK/L-*"; 65 | 66 | // Function call 67 | cout << "Prefix : " << postToPre(post_exp); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/ques10.cpp: -------------------------------------------------------------------------------- 1 | // Consider an empty stack of integers. Let the numbers 1,2,3,4,5,6 be pushed on to 2 | // this stack in the order they appear from left to right. Let 5 indicate a push and X indicate a 3 | // pop operation. Can they be permuted in to the order 325641(output) and order 154623? 4 | 5 | #include 6 | #include 7 | #include 8 | // used stl stack 9 | 10 | using namespace std; 11 | 12 | string permutations(vector &given, vector &required) 13 | { 14 | 15 | char s = 'S', x = 'X'; 16 | 17 | stack output; 18 | 19 | string result = ""; 20 | int k = 0; 21 | 22 | for (int i = 0; i < given.size(); i++) 23 | { 24 | 25 | output.push(given[i]); 26 | result += s; 27 | // cout << "pushed = " << given[i] << endl; 28 | // cout << "result = " << result << endl; 29 | 30 | while ( output.empty() != 1 && output.top() == required[k]) 31 | { 32 | result += x; 33 | // cout << "poped = " << output.top() << endl; 34 | output.pop(); 35 | k++; 36 | // cout << "result = " << result << endl; 37 | } 38 | } 39 | 40 | // cout<<"out of loop\n"; 41 | if (output.empty() == 1) 42 | { 43 | return result; 44 | } 45 | 46 | return "Not possible"; 47 | } 48 | 49 | int main() 50 | { 51 | 52 | vector given; 53 | 54 | for (int i = 0; i < 6; i++) 55 | { 56 | given.push_back(i + 1); 57 | } 58 | 59 | vector req = {3, 2, 5, 6, 4, 1}; 60 | 61 | cout << permutations(given, req) << endl; 62 | 63 | vector req2 = {1, 5, 4, 6, 2, 3}; 64 | 65 | cout << permutations(given, req2) << endl; 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /C++/Stacks/Questions/ques11.cpp: -------------------------------------------------------------------------------- 1 | // Finding Spans: Given an array A, the span S[i] of A[i] is the maximum number 2 | // of consecutive elements A[j] immediately preceding A[i] and such that A[j] < A[i]? 3 | // Other way of asking: Given an array A of integers, find the maximum of j – i subjected to 4 | // the constraint of A[i] < A[j]. 5 | 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | void print(vector &vec) 12 | { 13 | 14 | for (int i = 0; i < vec.size(); i++) 15 | { 16 | cout << vec[i] << " "; 17 | } 18 | cout << endl; 19 | } 20 | vector naive_soln(vector &vec) 21 | { 22 | 23 | vector result; 24 | 25 | for (int i = 0; i < vec.size(); i++) 26 | { 27 | int j = 1; 28 | 29 | while (j <= i && vec[i] > vec[i - j]) 30 | { 31 | j++; 32 | } 33 | 34 | result.push_back(j); 35 | } 36 | 37 | return result; 38 | } 39 | vector stack_impt(vector &vec) 40 | { 41 | 42 | vector result; 43 | stack d; 44 | 45 | int p; 46 | 47 | for (int i = 0; i < vec.size(); i++) 48 | { 49 | while ((!d.empty()) && vec[i] > vec[d.top()]) 50 | { 51 | d.pop(); 52 | } 53 | 54 | if (d.empty()) 55 | { 56 | p = -1; 57 | } 58 | else 59 | { 60 | p = d.top(); 61 | } 62 | 63 | result.push_back(i - p); 64 | 65 | d.push(i); 66 | } 67 | 68 | return result; 69 | } 70 | 71 | int main() 72 | { 73 | 74 | vector values = {6, 3, 4, 5, 2}; 75 | 76 | vector r = naive_soln(values); 77 | print(r); 78 | 79 | // Time Complexity: O(n2). Space Complexity: O(1). 80 | 81 | vector r2 = stack_impt(values); 82 | print(r2); 83 | 84 | // Time Complexity: O(n). Space Complexity: O(n). 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /C++/Stacks/Questions/ques12.cpp: -------------------------------------------------------------------------------- 1 | // Largest rectangle under histogram: A histogram is a polygon composed of a 2 | // sequence of rectangles aligned at a common base line. For simplicity, assume that the 3 | // rectangles have equal widths but may have different heights. For example, the figure on the 4 | // left shows a histogram that consists of rectangles with the heights 3,2,5,6,1,4,4, measured 5 | // in units where 1 is the width of the rectangles. Here our problem is: given an array with 6 | // heights of rectangles (assuming width is 1), we need to find the largest rectangle possible. 7 | // For the given example, the largest rectangle is the shared part. 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | int maxar(vector &vec){ 17 | 18 | int max , maxar = INT_MIN , left , top; 19 | 20 | stack stk; 21 | 22 | for (int i = 0; i < vec.size(); i++) 23 | { 24 | cout<<" i = "< n = {3,1,5,6,2,3}; 71 | vector n2 = {3,1,5,6,4 , 4}; 72 | 73 | cout< 13 | #include 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | string removeduplicates(string str) 19 | { 20 | 21 | int i = 0; 22 | int len = str.size(); 23 | std::string final_str = ""; 24 | 25 | stack stk; 26 | 27 | while (i < len) 28 | { 29 | stk.push(str[i]); 30 | //cout<<"pushed : "< 9 | using namespace std; 10 | 11 | bool isplain(string str) 12 | { 13 | 14 | int i = 0; 15 | int j = str.size() - 1; 16 | 17 | while (str[i] == str[j] && i < j) 18 | { 19 | i++; 20 | j--; 21 | } 22 | if (i < j) 23 | { 24 | return 0; 25 | } 26 | return 1; 27 | } 28 | 29 | int main() 30 | { 31 | 32 | string a = "abababababababXbabababababa"; 33 | 34 | std::cout << isplain(a) << endl; 35 | 36 | string b = "baXab"; 37 | 38 | std::cout << isplain(b) << endl; 39 | 40 | 41 | // for list if make a stack of half the size if linkedlist 42 | // the push the elements till mid 43 | // after that start poping as the elements keeps matching break if not 44 | // if the statck is empty at last means it palindrome 45 | // else not 46 | 47 | 48 | 49 | 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /C++/Stacks/Questions/ques9.cpp: -------------------------------------------------------------------------------- 1 | // 3 stacks in one array: How to implement 3 stacks in one array? 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | int main(){ 8 | 9 | 10 | return 0; 11 | } -------------------------------------------------------------------------------- /C++/Stacks/Questions/stack_using_qqueue.cpp: -------------------------------------------------------------------------------- 1 | /* Program to implement a stack using 2 | two queue */ 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Stack { 8 | // Two inbuilt queues 9 | queue q1, q2; 10 | 11 | // To maintain current number of 12 | // elements 13 | int curr_size; 14 | 15 | public: 16 | Stack() 17 | { 18 | curr_size = 0; 19 | } 20 | 21 | void push(int x) 22 | { 23 | curr_size++; 24 | 25 | // Push x first in empty q2 26 | q2.push(x); 27 | 28 | // Push all the remaining 29 | // elements in q1 to q2. 30 | while (!q1.empty()) { 31 | q2.push(q1.front()); 32 | q1.pop(); 33 | } 34 | 35 | // swap the names of two queues 36 | queue q = q1; 37 | q1 = q2; 38 | q2 = q; 39 | } 40 | 41 | void pop() 42 | { 43 | 44 | // if no elements are there in q1 45 | if (q1.empty()) 46 | return; 47 | q1.pop(); 48 | curr_size--; 49 | } 50 | 51 | int top() 52 | { 53 | if (q1.empty()) 54 | return -1; 55 | return q1.front(); 56 | } 57 | 58 | int size() 59 | { 60 | return curr_size; 61 | } 62 | }; 63 | 64 | // Driver code 65 | int main() 66 | { 67 | Stack s; 68 | s.push(1); 69 | s.push(2); 70 | s.push(3); 71 | 72 | cout << "current size: " << s.size() 73 | << endl; 74 | cout << s.top() << endl; 75 | s.pop(); 76 | cout << s.top() << endl; 77 | s.pop(); 78 | cout << s.top() << endl; 79 | 80 | cout << "current size: " << s.size() 81 | << endl; 82 | return 0; 83 | } -------------------------------------------------------------------------------- /C++/Stacks/Questions/valid_expression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool valid(string str); 4 | int main() 5 | { 6 | int t; 7 | cin>>t; 8 | cin.ignore(); 9 | while(t--) 10 | { 11 | string str; 12 | getline(cin,str); 13 | cout<st; 23 | unordered_mapm={{'{',-1},{'[',-2},{'(',-3},{'}',1},{']',2},{')',3}}; 24 | for(int i=0;i1) 40 | { 41 | return false; 42 | } 43 | } 44 | 45 | } 46 | } 47 | if(st.empty()) 48 | { 49 | return true; 50 | } 51 | return false; 52 | } -------------------------------------------------------------------------------- /C++/Tree_Algorithms/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // add the edge in graph 8 | void edge(vector adj[], int u, int v) 9 | { 10 | adj[u].push_back(v); 11 | } 12 | // function for bfs traversal 13 | void bfs(int s, vector adj[], bool visit[]) 14 | { 15 | queue q; // queue in STL 16 | q.push(s); 17 | visit[s] = true; 18 | while (!q.empty()) 19 | { 20 | int u = q.front(); 21 | cout << u << " "; 22 | q.pop(); 23 | // loop for traverse 24 | for (int i = 0; i < adj[u].size(); i++) 25 | { 26 | if (!visit[adj[u][i]]) 27 | { 28 | q.push(adj[u][i]); 29 | visit[adj[u][i]] = true; 30 | } 31 | } 32 | } 33 | } 34 | // main function 35 | int main() 36 | { 37 | int nv; 38 | cout << "Enter Number of Vertices: "; 39 | cin >> nv; 40 | vector adj[nv]; // vector of array to store the graph 41 | bool visit[nv]; // array to check visit or not of a node 42 | // initially all node are unvisited 43 | for (int i = 0; i < nv; i++) 44 | { 45 | visit[i] = false; 46 | } 47 | int ne; 48 | cout << "Enter Number of Edges: "; 49 | cin >> ne; 50 | int so; 51 | cout << "Enter Starting Node : "; 52 | cin >> so; 53 | 54 | cout << endl 55 | << endl; 56 | // input for edges 57 | for (int i = 0; i < ne; i++) 58 | { 59 | int a, b; 60 | cout << "Enter Edge Starting Node and Ending Node: "; 61 | cin >> a >> b; 62 | edge(adj, a, b); 63 | } 64 | cout << "BFS traversal is" 65 | << " "; 66 | // call bfs funtion 67 | bfs(so, adj, visit); 68 | cout << endl; 69 | } 70 | -------------------------------------------------------------------------------- /C++/Trees/Boundary Traversal.cpp: -------------------------------------------------------------------------------- 1 | //Problem: https://practice.geeksforgeeks.org/problems/boundary-traversal-of-binary-tree/1 2 | 3 | class Solution { 4 | 5 | bool isLeaf(Node *node) 6 | { 7 | if(!node->left and !node->right) return true; 8 | else return false; 9 | } 10 | 11 | void addRight(Node*root, vector&ans) 12 | { 13 | if(!root->right) return; 14 | vectortem; 15 | Node*curr=root->right; 16 | 17 | while(curr) 18 | { 19 | if(!isLeaf(curr))tem.push_back(curr->data); 20 | if(curr->right) 21 | curr=curr->right; 22 | else 23 | curr=curr->left; 24 | } 25 | for(int i=tem.size()-1; i>=0; i--) 26 | { 27 | ans.push_back(tem[i]); 28 | } 29 | 30 | } 31 | 32 | void addLeft(Node *root,vector&ans) 33 | { 34 | Node* curr = root->left; 35 | while(curr) 36 | { 37 | if(!isLeaf(curr))ans.push_back(curr->data); 38 | if(curr->left) curr=curr->left; 39 | else 40 | curr=curr->right; 41 | } 42 | } 43 | void addLeaves(Node *root, vector&ans) 44 | { 45 | if(!root) return; 46 | if(isLeaf(root)){ 47 | ans.push_back(root->data) ; 48 | return; 49 | } 50 | addLeaves(root->left,ans); 51 | addLeaves(root->right,ans); 52 | } 53 | 54 | public: 55 | vector boundary(Node *root) 56 | { 57 | //Your code here 58 | vectorans; 59 | if(!root)return ans; 60 | 61 | if(!isLeaf(root)) ans.push_back(root->data); 62 | 63 | addLeft(root,ans); 64 | addLeaves(root,ans); 65 | addRight(root,ans); 66 | 67 | return ans; 68 | } 69 | }; 70 | -------------------------------------------------------------------------------- /C++/Trees/binary_trees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // This program introduces just to the basic structure of the tree 5 | 6 | struct node 7 | { 8 | int data; 9 | node *left; 10 | node *right; 11 | }; 12 | 13 | node * init(int data) 14 | { 15 | node *n = new node; 16 | n->data = data; 17 | n->left = NULL; 18 | n->left = NULL; 19 | return n; 20 | } 21 | void insert_left(node *root , int data) 22 | { 23 | root->left = init(data); 24 | 25 | } 26 | void insert_right(node *root , int data) 27 | { 28 | root->right = init(data); 29 | } 30 | 31 | void delete_left(node * root ){ 32 | 33 | node * todel = root->left; 34 | root->left = NULL; 35 | delete todel; 36 | } 37 | void delete_right(node * root ){ 38 | 39 | node * todel = root->right; 40 | root->right = NULL; 41 | delete todel; 42 | } 43 | 44 | 45 | int main() 46 | { 47 | node * root = init(1); // root node 48 | 49 | // 1 50 | 51 | insert_left(root , 2); 52 | insert_right(root , 3); 53 | 54 | // 1 55 | // / \' 56 | // 2 3 57 | 58 | insert_left(root->left , 4); 59 | insert_right(root->left , 5); 60 | 61 | // 1 62 | // / \' 63 | // 2 3 64 | // / \' 65 | // 4 5 66 | 67 | cout<data<<"\n"; 68 | 69 | cout<left->data<<"\n"; 70 | cout<right->data<<"\n"; 71 | 72 | cout<left->left->data<<"\n"; 73 | cout<left->right->data<<"\n"; 74 | 75 | cout<right->left->data<<"\n"; 76 | cout<right->right->data<<"\n"; 77 | 78 | 79 | return 0; 80 | } -------------------------------------------------------------------------------- /C++/Trees/levelorder_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct node 7 | { 8 | int data; 9 | node *left; 10 | node *right; 11 | }; 12 | 13 | node *init(int data) 14 | { 15 | node *n = new node; 16 | n->data = data; 17 | n->left = NULL; 18 | n->right = NULL; 19 | return n; 20 | } 21 | void insert_left(node *root, int data) 22 | { 23 | root->left = init(data); 24 | } 25 | void insert_right(node *root, int data) 26 | { 27 | root->right = init(data); 28 | } 29 | 30 | void delete_left(node *root) 31 | { 32 | node *todel = root->left; 33 | root->left = NULL; 34 | delete todel; 35 | } 36 | void delete_right(node *root) 37 | { 38 | node *todel = root->right; 39 | root->right = NULL; 40 | delete todel; 41 | } 42 | 43 | void levelorder(node *root) 44 | { 45 | node * temp; 46 | queue q; 47 | 48 | if (root == NULL) 49 | { 50 | return; 51 | } 52 | 53 | q.push(root); 54 | 55 | while (!q.empty()) 56 | { 57 | temp = q.front(); 58 | q.pop(); 59 | 60 | cout<data<<" "; 61 | 62 | if (temp->left != NULL) 63 | { 64 | q.push(temp->left); 65 | } 66 | if (temp->right != NULL) 67 | { 68 | q.push(temp->right); 69 | } 70 | 71 | } 72 | 73 | } 74 | 75 | int main() 76 | { 77 | node *root = NULL; 78 | 79 | root = init(1); // root node 80 | 81 | // 1 82 | 83 | insert_left(root, 2); 84 | insert_right(root, 3); 85 | 86 | // 1 87 | // / \' 88 | // 2 3 89 | 90 | insert_left(root->left, 4); 91 | insert_right(root->left, 5); 92 | 93 | // 1 94 | // / \' 95 | // 2 3 96 | // / \' 97 | // 4 5 98 | 99 | insert_left(root->right, 6); 100 | insert_right(root->right, 7); 101 | 102 | // 1 103 | // / \' 104 | // 2 3 105 | // / \' / \' 106 | // 4 5 6 7 107 | 108 | levelorder(root); 109 | 110 | return 0; 111 | } -------------------------------------------------------------------------------- /C++/Trees/questions/ques2.cpp: -------------------------------------------------------------------------------- 1 | // Give an algorithm for finding the maximum element in binary tree without recursion. 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct node 10 | { 11 | int data; 12 | node *left; 13 | node *right; 14 | }; 15 | 16 | node *init(int data) 17 | { 18 | node *n = new node; 19 | n->data = data; 20 | n->left = NULL; 21 | n->right = NULL; 22 | return n; 23 | } 24 | void insert_left(node *root, int data) 25 | { 26 | root->left = init(data); 27 | } 28 | void insert_right(node *root, int data) 29 | { 30 | root->right = init(data); 31 | } 32 | 33 | void delete_left(node *root) 34 | { 35 | 36 | node *todel = root->left; 37 | root->left = NULL; 38 | delete todel; 39 | } 40 | void delete_right(node *root) 41 | { 42 | 43 | node *todel = root->right; 44 | root->right = NULL; 45 | delete todel; 46 | } 47 | 48 | int findmax(node *root) 49 | { 50 | 51 | node *temp; 52 | int max = INT_MIN; 53 | queue q; 54 | q.push(root); 55 | 56 | while (!q.empty()) 57 | { 58 | temp = q.front(); 59 | q.pop(); 60 | 61 | if (max < temp->data) 62 | { 63 | max = temp->data; 64 | } 65 | 66 | if (temp->left != NULL) 67 | { 68 | q.push(temp->left); 69 | } 70 | if (temp->right != NULL) 71 | { 72 | q.push(temp->right); 73 | } 74 | } 75 | 76 | return max; 77 | } 78 | int main() 79 | { 80 | node *root = NULL; 81 | 82 | root = init(1); // root node 83 | 84 | // 1 85 | 86 | insert_left(root, 2); 87 | insert_right(root, 3); 88 | 89 | // 1 90 | // / \' 91 | // 2 3 92 | 93 | insert_left(root->left, 4); 94 | insert_right(root->left, 5); 95 | 96 | // 1 97 | // / \' 98 | // 2 3 99 | // / \' 100 | // 4 5 101 | 102 | insert_left(root->right, 6); 103 | insert_right(root->right, 7); 104 | 105 | // 1 106 | // / \' 107 | // 2 3 108 | // / \' / \' 109 | // 4 5 6 7 110 | 111 | cout << "Max - " << findmax(root); 112 | 113 | return 0; 114 | } -------------------------------------------------------------------------------- /C++/Trees/questions/ques3.cpp: -------------------------------------------------------------------------------- 1 | // Give an algorithm for searching an element in binary tree. 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct node 10 | { 11 | int data; 12 | node *left; 13 | node *right; 14 | }; 15 | 16 | node *init(int data) 17 | { 18 | node *n = new node; 19 | n->data = data; 20 | n->left = NULL; 21 | n->right = NULL; 22 | return n; 23 | } 24 | void insert_left(node *root, int data) 25 | { 26 | root->left = init(data); 27 | } 28 | void insert_right(node *root, int data) 29 | { 30 | root->right = init(data); 31 | } 32 | 33 | void delete_left(node *root) 34 | { 35 | 36 | node *todel = root->left; 37 | root->left = NULL; 38 | delete todel; 39 | } 40 | void delete_right(node *root) 41 | { 42 | 43 | node *todel = root->right; 44 | root->right = NULL; 45 | delete todel; 46 | } 47 | 48 | 49 | bool find(node * root , int data) 50 | { 51 | bool temp; 52 | 53 | if (root == NULL ) 54 | { 55 | return 0; 56 | } 57 | else{ 58 | 59 | 60 | if (root->data == data) 61 | { 62 | return 1; 63 | } 64 | else{ 65 | 66 | temp = find(root->left , data); 67 | if (temp != 0) 68 | { 69 | return temp; 70 | } 71 | else{ 72 | 73 | return find(root->right , data); 74 | } 75 | 76 | } 77 | 78 | } 79 | 80 | return 0; 81 | 82 | } 83 | int main() 84 | { 85 | node *root = NULL; 86 | 87 | root = init(1); // root node 88 | 89 | // 1 90 | 91 | insert_left(root, 2); 92 | insert_right(root, 3); 93 | 94 | // 1 95 | // / \' 96 | // 2 3 97 | 98 | insert_left(root->left, 4); 99 | insert_right(root->left, 5); 100 | 101 | // 1 102 | // / \' 103 | // 2 3 104 | // / \' 105 | // 4 5 106 | 107 | insert_left(root->right, 6); 108 | insert_right(root->right, 7); 109 | 110 | // 1 111 | // / \' 112 | // 2 3 113 | // / \' / \' 114 | // 4 5 6 7 115 | 116 | cout << "Found - " << find(root , 6); 117 | 118 | return 0; 119 | } -------------------------------------------------------------------------------- /C++/Trees/questions/ques4.cpp: -------------------------------------------------------------------------------- 1 | // Give an algorithm for searching an element in binary tree without recursion. 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct node 10 | { 11 | int data; 12 | node *left; 13 | node *right; 14 | }; 15 | 16 | node *init(int data) 17 | { 18 | node *n = new node; 19 | n->data = data; 20 | n->left = NULL; 21 | n->right = NULL; 22 | return n; 23 | } 24 | void insert_left(node *root, int data) 25 | { 26 | root->left = init(data); 27 | } 28 | void insert_right(node *root, int data) 29 | { 30 | root->right = init(data); 31 | } 32 | 33 | void delete_left(node *root) 34 | { 35 | 36 | node *todel = root->left; 37 | root->left = NULL; 38 | delete todel; 39 | } 40 | void delete_right(node *root) 41 | { 42 | 43 | node *todel = root->right; 44 | root->right = NULL; 45 | delete todel; 46 | } 47 | 48 | 49 | bool find(node * root , int data) 50 | { 51 | node *temp; 52 | queue q; 53 | q.push(root); 54 | 55 | while (!q.empty()) 56 | { 57 | temp = q.front(); 58 | q.pop(); 59 | 60 | if (data == temp->data) 61 | { 62 | return 1; 63 | } 64 | 65 | if (temp->left != NULL) 66 | { 67 | q.push(temp->left); 68 | } 69 | if (temp->right != NULL) 70 | { 71 | q.push(temp->right); 72 | } 73 | } 74 | 75 | return 0; 76 | 77 | } 78 | int main() 79 | { 80 | node *root = NULL; 81 | 82 | root = init(1); // root node 83 | 84 | // 1 85 | 86 | insert_left(root, 2); 87 | insert_right(root, 3); 88 | 89 | // 1 90 | // / \' 91 | // 2 3 92 | 93 | insert_left(root->left, 4); 94 | insert_right(root->left, 5); 95 | 96 | // 1 97 | // / \' 98 | // 2 3 99 | // / \' 100 | // 4 5 101 | 102 | insert_left(root->right, 6); 103 | insert_right(root->right, 7); 104 | 105 | // 1 106 | // / \' 107 | // 2 3 108 | // / \' / \' 109 | // 4 5 6 7 110 | 111 | cout << "Found - " << find(root , 6); 112 | 113 | return 0; 114 | } -------------------------------------------------------------------------------- /C++/Trees/vertical_order_traversal.cpp: -------------------------------------------------------------------------------- 1 | // Vertical order traversal of a binary tree 2 | 3 | // Time: O(n) 4 | // Space: O(n) 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | vector> verticalOrder(TreeNode* root) { 18 | unordered_map> cols; 19 | vector> queue{{root, 0}}; 20 | for (int i = 0; i < queue.size(); ++i) { 21 | TreeNode *node; 22 | int j; 23 | tie(node, j) = queue[i]; 24 | if (node) { 25 | cols[j].emplace_back(node->val); 26 | queue.push_back({node->left, j - 1}); 27 | queue.push_back({node->right, j + 1}); 28 | } 29 | } 30 | int min_idx = numeric_limits::max(), 31 | max_idx = numeric_limits::min(); 32 | for (const auto& kvp : cols) { 33 | min_idx = min(min_idx, kvp.first); 34 | max_idx = max(max_idx, kvp.first); 35 | } 36 | vector> res; 37 | for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) { 38 | res.emplace_back(move(cols[i])); 39 | } 40 | return res; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /C++/Trees_Algorithm/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // add the edge in graph 8 | void edge(vector adj[], int u, int v) 9 | { 10 | adj[u].push_back(v); 11 | } 12 | // function for dfs traversal 13 | void dfs(int s, vector adj[], bool visit[]) 14 | { 15 | stack stk; // stack in STL 16 | stk.push(s); 17 | visit[s] = true; 18 | while (!stk.empty()) 19 | { 20 | int u = stk.top(); 21 | cout << u << " "; 22 | stk.pop(); 23 | // loop for traverse 24 | for (int i = 0; i < adj[u].size(); i++) 25 | { 26 | if (!visit[adj[u][i]]) 27 | { 28 | stk.push(adj[u][i]); 29 | visit[adj[u][i]] = true; 30 | } 31 | } 32 | } 33 | } 34 | // main function 35 | int main() 36 | { 37 | int nv; 38 | cout << "Enter Number of Vertices: "; 39 | cin >> nv; 40 | vector adj[nv]; // vector of array to store the graph 41 | bool visit[nv]; // array to check visit or not of a node 42 | // initially all node are unvisited 43 | for (int i = 0; i < nv; i++) 44 | { 45 | visit[i] = false; 46 | } 47 | int ne; 48 | cout << "Enter Number of Edges: "; 49 | cin >> ne; 50 | int so; 51 | cout << "Enter Starting Node : "; 52 | cin>>so; 53 | 54 | cout<> a >> b; 61 | edge(adj, a, b); 62 | } 63 | cout << "DFS traversal is" 64 | << " "; 65 | // call dfs function 66 | dfs(so, adj, visit); 67 | cout << endl; 68 | } 69 | -------------------------------------------------------------------------------- /C++/sorting/bead_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement gravity/bead sort 2 | #include 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 | -------------------------------------------------------------------------------- /C++/sorting/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int n; 6 | bool swap_check = true; 7 | std::cout << "Enter the amount of numbers to sort: "; 8 | std::cin >> n; 9 | std::vector numbers; 10 | std::cout << "Enter " << n << " numbers: "; 11 | int num; 12 | 13 | // Input 14 | for (int i = 0; i < n; i++) { 15 | std::cin >> num; 16 | numbers.push_back(num); 17 | } 18 | 19 | // Bubble Sorting 20 | for (int i = 0; (i < n) && (swap_check); i++) { 21 | swap_check = false; 22 | for (int j = 0; j < n - 1 - i; j++) { 23 | if (numbers[j] > numbers[j + 1]) { 24 | swap_check = true; 25 | std::swap(numbers[j], 26 | numbers[j + 1]); // by changing swap location. 27 | // I mean, j. If the number is 28 | // greater than j + 1, then it 29 | // means the location. 30 | } 31 | } 32 | } 33 | 34 | // Output 35 | std::cout << "\nSorted Array : "; 36 | for (int i = 0; i < numbers.size(); i++) { 37 | if (i != numbers.size() - 1) { 38 | std::cout << numbers[i] << ", "; 39 | } else { 40 | std::cout << numbers[i] << std::endl; 41 | } 42 | } 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /C++/sorting/bucket_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array using bucket sort 2 | #include 3 | #include 4 | #include 5 | 6 | // Function to sort arr[] of size n using bucket sort 7 | void bucketSort(float arr[], int n) { 8 | // 1) Create n empty buckets 9 | std::vector *b = new std::vector[n]; 10 | 11 | // 2) Put array elements in different buckets 12 | for (int i = 0; i < n; i++) { 13 | int bi = n * arr[i]; // Index in bucket 14 | b[bi].push_back(arr[i]); 15 | } 16 | 17 | // 3) Sort individual buckets 18 | for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end()); 19 | 20 | // 4) Concatenate all buckets into arr[] 21 | int index = 0; 22 | for (int i = 0; i < n; i++) 23 | for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j]; 24 | delete[] b; 25 | } 26 | 27 | /* Driver program to test above funtion */ 28 | int main() { 29 | float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | bucketSort(arr, n); 32 | 33 | std::cout << "Sorted array is \n"; 34 | for (int i = 0; i < n; i++) std::cout << arr[i] << " "; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /C++/sorting/counting_sort_string.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | void countSort(string arr) { 7 | string output; 8 | 9 | int count[256], i; 10 | for (int i = 0; i < 256; i++) count[i] = 0; 11 | 12 | for (i = 0; arr[i]; ++i) ++count[arr[i]]; 13 | 14 | for (i = 1; i < 256; ++i) count[i] += count[i - 1]; 15 | 16 | for (i = 0; arr[i]; ++i) { 17 | output[count[arr[i]] - 1] = arr[i]; 18 | --count[arr[i]]; 19 | } 20 | 21 | for (i = 0; arr[i]; ++i) arr[i] = output[i]; 22 | 23 | cout << "Sorted character array is " << arr; 24 | } 25 | 26 | int main() { 27 | string arr; 28 | cin >> arr; 29 | 30 | countSort(arr); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /C++/sorting/heap_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | template 6 | void printArray(T *arr, int sz) { 7 | for (int i = 0; i < sz; i++) std::cout << arr[i] << " "; 8 | std::cout << "\n"; 9 | } 10 | 11 | template 12 | void heapify(T *arr, int n, int i) { 13 | int largest = i; 14 | int l = 2 * i + 1; 15 | int r = 2 * i + 2; 16 | 17 | if (l < n && arr[l] > arr[largest]) 18 | largest = l; 19 | 20 | if (r < n && arr[r] > arr[largest]) 21 | largest = r; 22 | 23 | if (largest != i) { 24 | std::swap(arr[i], arr[largest]); 25 | heapify(arr, n, largest); 26 | } 27 | } 28 | 29 | 30 | template 31 | void heapSort(T *arr, int n) { 32 | for (int i = n - 1; i >= 0; i--) heapify(arr, n, i); 33 | 34 | for (int i = n - 1; i >= 0; i--) { 35 | std::swap(arr[0], arr[i]); 36 | heapify(arr, i, 0); 37 | } 38 | } 39 | 40 | 41 | void test() { 42 | std::cout << "Test 1\n"; 43 | int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0}; 44 | int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array 45 | printArray(arr, sz); // displaying the array before sorting 46 | heapSort(arr, sz); // calling heapsort to sort the array 47 | printArray(arr, sz); // display array after sorting 48 | assert(std::is_sorted(arr, arr + sz)); 49 | std::cout << "Test 1 Passed\n========================\n"; 50 | 51 | std::cout << "Test 2\n"; 52 | double arr2[] = {4.5, -3.6, 7.6, 0, 12.9}; 53 | sz = sizeof(arr2) / sizeof(arr2[0]); 54 | printArray(arr2, sz); 55 | heapSort(arr2, sz); 56 | printArray(arr2, sz); 57 | assert(std::is_sorted(arr2, arr2 + sz)); 58 | std::cout << "Test 2 passed\n"; 59 | } 60 | 61 | /** Main function */ 62 | int main() { 63 | test(); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /C++/sorting/merge_sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | 5 | void merge(int *arr, int l, int m, int r) { 6 | int i, j, k; 7 | int n1 = m - l + 1; 8 | int n2 = r - m; 9 | 10 | int *L = new int[n1], *R = new int[n2]; 11 | 12 | for (i = 0; i < n1; i++) L[i] = arr[l + i]; 13 | for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; 14 | 15 | i = 0; 16 | j = 0; 17 | k = l; 18 | while (i < n1 || j < n2) { 19 | if (j >= n2 || (i < n1 && L[i] <= R[j])) { 20 | arr[k] = L[i]; 21 | i++; 22 | } else { 23 | arr[k] = R[j]; 24 | j++; 25 | } 26 | k++; 27 | } 28 | 29 | delete[] L; 30 | delete[] R; 31 | } 32 | 33 | void mergeSort(int *arr, int l, int r) { 34 | if (l < r) { 35 | int m = l + (r - l) / 2; 36 | mergeSort(arr, l, m); 37 | mergeSort(arr, m + 1, r); 38 | merge(arr, l, m, r); 39 | } 40 | } 41 | 42 | 43 | void show(int *arr, int size) { 44 | for (int i = 0; i < size; i++) std::cout << arr[i] << " "; 45 | std::cout << "\n"; 46 | } 47 | 48 | /** Main function */ 49 | int main() { 50 | int size; 51 | std::cout << "Enter the number of elements : "; 52 | std::cin >> size; 53 | int *arr = new int[size]; 54 | std::cout << "Enter the unsorted elements : "; 55 | for (int i = 0; i < size; ++i) { 56 | std::cin >> arr[i]; 57 | } 58 | mergeSort(arr, 0, size - 1); 59 | std::cout << "Sorted array : "; 60 | show(arr, size); 61 | delete[] arr; 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /C++/sorting/numeric_string_sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | bool NumericSort(std::string a, std::string b) { 9 | while (a[0] == '0') { 10 | a.erase(a.begin()); 11 | } 12 | while (b[0] == '0') { 13 | b.erase(b.begin()); 14 | } 15 | int n = a.length(); 16 | int m = b.length(); 17 | if (n == m) 18 | return a < b; 19 | return n < m; 20 | } 21 | 22 | int main() { 23 | int n; 24 | std::cout << "Enter number of elements to be sorted Numerically\n"; 25 | std::cin >> n; 26 | 27 | std::vector v(n); 28 | std::cout << "Enter the string of Numbers\n"; 29 | for (int i = 0; i < n; i++) { 30 | std::cin >> v[i]; 31 | } 32 | 33 | sort(v.begin(), v.end()); 34 | std::cout << "Elements sorted normally \n"; 35 | for (int i = 0; i < n; i++) { 36 | std::cout << v[i] << " "; 37 | } 38 | std::cout << "\n"; 39 | 40 | std::sort(v.begin(), v.end(), NumericSort); 41 | std::cout << "Elements sorted Numerically \n"; 42 | for (int i = 0; i < n; i++) { 43 | std::cout << v[i] << " "; 44 | } 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/sorting/odd_even_sort.cpp: -------------------------------------------------------------------------------- 1 | /* C++ implementation Odd Even Sort */ 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void oddEven(vector &arr, int size) { 8 | bool sorted = false; 9 | while (!sorted) { 10 | sorted = true; 11 | for (int i = 1; i < size - 1; i += 2) // Odd 12 | { 13 | if (arr[i] > arr[i + 1]) { 14 | swap(arr[i], arr[i + 1]); 15 | sorted = false; 16 | } 17 | } 18 | 19 | for (int i = 0; i < size - 1; i += 2) // Even 20 | { 21 | if (arr[i] > arr[i + 1]) { 22 | swap(arr[i], arr[i + 1]); 23 | sorted = false; 24 | } 25 | } 26 | } 27 | } 28 | 29 | void show(vector A, int size) { 30 | int i; 31 | for (i = 0; i < size; i++) cout << A[i] << "\n"; 32 | } 33 | 34 | int main() { 35 | int size, temp; 36 | cout << "\nEnter the number of elements : "; 37 | cin >> size; 38 | 39 | vector arr; 40 | 41 | cout << "\nEnter the unsorted elements : \n"; 42 | 43 | for (int i = 0; i < size; ++i) { 44 | cin >> temp; 45 | arr.push_back(temp); 46 | } 47 | 48 | oddEven(arr, size); 49 | 50 | cout << "Sorted array\n"; 51 | show(arr, size); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C++/sorting/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace sorting { 5 | 6 | 7 | int partition(int arr[], int low, int high) { 8 | int pivot = arr[high]; // taking the last element as pivot 9 | int i = (low - 1); // Index of smaller element 10 | 11 | for (int j = low; j < high; j++) { 12 | // If current element is smaller than or 13 | // equal to pivot 14 | if (arr[j] <= pivot) { 15 | i++; // increment index of smaller element 16 | int temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | } 21 | int temp = arr[i + 1]; 22 | arr[i + 1] = arr[high]; 23 | arr[high] = temp; 24 | return (i + 1); 25 | } 26 | 27 | 28 | void quickSort(int arr[], int low, int high) { 29 | if (low < high) { 30 | int p = partition(arr, low, high); 31 | quickSort(arr, low, p - 1); 32 | quickSort(arr, p + 1, high); 33 | } 34 | } 35 | 36 | } // namespace sorting 37 | 38 | using sorting::quickSort; 39 | 40 | // prints the array after sorting 41 | void show(int arr[], int size) { 42 | for (int i = 0; i < size; i++) std::cout << arr[i] << " "; 43 | std::cout << "\n"; 44 | } 45 | 46 | /** Driver program to test above functions */ 47 | int main() { 48 | int size; 49 | std::cout << "\nEnter the number of elements : "; 50 | 51 | std::cin >> size; 52 | 53 | int *arr = new int[size]; 54 | 55 | std::cout << "\nEnter the unsorted elements : "; 56 | 57 | for (int i = 0; i < size; ++i) { 58 | std::cout << "\n"; 59 | std::cin >> arr[i]; 60 | } 61 | quickSort(arr, 0, size); 62 | std::cout << "Sorted array\n"; 63 | show(arr, size); 64 | delete[] arr; 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /C++/sorting/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void radixsort(int a[], int n) { 7 | int count[10]; 8 | int* output = new int[n]; 9 | memset(output, 0, n * sizeof(*output)); 10 | memset(count, 0, sizeof(count)); 11 | int max = 0; 12 | for (int i = 0; i < n; ++i) { 13 | if (a[i] > max) { 14 | max = a[i]; 15 | } 16 | } 17 | int maxdigits = 0; 18 | while (max) { 19 | maxdigits++; 20 | max /= 10; 21 | } 22 | for (int j = 0; j < maxdigits; j++) { 23 | for (int i = 0; i < n; i++) { 24 | int t = std::pow(10, j); 25 | count[(a[i] % (10 * t)) / t]++; 26 | } 27 | int k = 0; 28 | for (int p = 0; p < 10; p++) { 29 | for (int i = 0; i < n; i++) { 30 | int t = std::pow(10, j); 31 | if ((a[i] % (10 * t)) / t == p) { 32 | output[k] = a[i]; 33 | k++; 34 | } 35 | } 36 | } 37 | memset(count, 0, sizeof(count)); 38 | for (int i = 0; i < n; ++i) { 39 | a[i] = output[i]; 40 | } 41 | } 42 | delete[] output; 43 | } 44 | 45 | void print(int a[], int n) { 46 | for (int i = 0; i < n; ++i) { 47 | std::cout << a[i] << " "; 48 | } 49 | std::cout << std::endl; 50 | } 51 | 52 | int main(int argc, char const* argv[]) { 53 | int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; 54 | int n = sizeof(a) / sizeof(a[0]); 55 | radixsort(a, n); 56 | print(a, n); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /C++/sorting/shell_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int size = 10; 5 | int* array = new int[size]; 6 | // Input 7 | std::cout << "\nHow many numbers do want to enter in unsorted array : "; 8 | std::cin >> size; 9 | std::cout << "\nEnter the numbers for unsorted array : "; 10 | for (int i = 0; i < size; i++) { 11 | std::cin >> array[i]; 12 | } 13 | 14 | // Sorting 15 | for (int i = size / 2; i > 0; i = i / 2) { 16 | for (int j = i; j < size; j++) { 17 | for (int k = j - i; k >= 0; k = k - i) { 18 | if (array[k] < array[k + i]) { 19 | break; 20 | } else { 21 | int temp = array[k + i]; 22 | array[k + i] = array[k]; 23 | array[k] = temp; 24 | } 25 | } 26 | } 27 | } 28 | 29 | // Output 30 | std::cout << "\nSorted array : "; 31 | for (int i = 0; i < size; ++i) { 32 | std::cout << array[i] << "\t"; 33 | } 34 | 35 | delete[] array; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /C++/sorting/strand_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | namespace sorting { 6 | 7 | namespace strand { 8 | 9 | template 10 | std::list strand_sort(std::list lst) { 11 | if (lst.size() < 2) { // Returns list if empty or contains only one element 12 | return lst; // Returns list 13 | } 14 | std::list result; // Define new "result" named list instance. 15 | std::list sorted; // Define new "sorted" named list instance. 16 | while(!lst.empty()) /* if lst is not empty */ { 17 | sorted.push_back(lst.front()); // Adds the first element of "lst" list to the bottom of the "sorted" list. 18 | lst.pop_front(); // Remove first element of "lst" list. 19 | for (auto it = lst.begin(); it != lst.end(); ) { // Return the loop as long as the current iterator is not equal to the last literator of the "lst" list. 20 | if (sorted.back() <= *it) { // If the last reference of the "sorted" list is less than or equal to the current iterator reference. 21 | sorted.push_back(*it); // Adds the iterator retrieved in the loop under the "sorted" list. 22 | it = lst.erase(it); // Deletes the element with the current iterator and assigns the deleted element to the iterator. 23 | } else { 24 | it++; // Next iterator. 25 | } 26 | } 27 | result.merge(sorted); // Merge "result" list with "sorted" list. 28 | } 29 | return result; // Returns sorted list 30 | } 31 | } // namespace strand 32 | } // namespace sorting 33 | 34 | 35 | static void test() { 36 | std::list lst = { -333, 525, 1, 0, 94, 52, 33 }; 37 | 38 | std::cout << "Before: "; 39 | for(auto item: lst) { 40 | std::cout << item << " "; 41 | } 42 | 43 | lst = sorting::strand::strand_sort(lst); // Sort list. 44 | 45 | std::cout << "\nAfter: "; 46 | for(auto item: lst) { 47 | std::cout << item << " "; 48 | } 49 | } 50 | 51 | 52 | int main() { 53 | test(); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /C++/sorting/wave_sort.cpp: -------------------------------------------------------------------------------- 1 | #include /// for std::is_sorted, std::swap 2 | #include /// for assert 3 | #include /// for IO operations 4 | #include /// for std::vector 5 | 6 | 7 | namespace sorting { 8 | 9 | namespace wave_sort { 10 | 11 | template 12 | std::vector waveSort(const std::vector &in_arr, int64_t n) { 13 | std::vector arr(in_arr); 14 | 15 | for (int64_t i = 0; i < n; i++) { 16 | arr[i] = in_arr[i]; 17 | } 18 | std::sort(arr.begin(), arr.end()); 19 | for (int64_t i = 0; i < n - 1; i += 2) { // swap all the adjacent elements 20 | std::swap(arr[i], arr[i + 1]); 21 | } 22 | return arr; 23 | } 24 | } // namespace wave_sort 25 | } // namespace sorting 26 | 27 | static void test() { 28 | // [10, 90, 49, 2, 1, 5, 23] return [2, 1, 10, 5, 49, 23, 90] 29 | std::vector array1 = {10, 90, 49, 2, 1, 5, 23}; 30 | std::cout << "Test 1... "; 31 | std::vector arr1 = sorting::wave_sort::waveSort(array1, 7); 32 | const std::vector o1 = {2, 1, 10, 5, 49, 23, 90}; 33 | assert(arr1 == o1); 34 | std::cout << "passed" << std::endl; 35 | 36 | // [1, 3, 4, 2, 7, 8] return [2, 1, 4, 3, 8, 7] 37 | std::vector array2 = {1, 3, 4, 2, 7, 8}; 38 | std::cout << "Test 2... "; 39 | std::vector arr2 = sorting::wave_sort::waveSort(array2, 6); 40 | const std::vector o2 = {2, 1, 4, 3, 8, 7}; 41 | assert(arr2 == o2); 42 | std::cout << "passed" << std::endl; 43 | 44 | // [3, 3, 3, 3] return [3, 3, 3, 3] 45 | std::vector array3 = {3, 3, 3, 3}; 46 | std::cout << "Test 3... "; 47 | std::vector arr3 = sorting::wave_sort::waveSort(array3, 4); 48 | const std::vector o3 = {3, 3, 3, 3}; 49 | assert(arr3 == o3); 50 | std::cout << "passed" << std::endl; 51 | 52 | // [9, 4, 6, 8, 14, 3] return [4, 3, 8, 6, 14, 9] 53 | std::vector array4 = {9, 4, 6, 8, 14, 3}; 54 | std::cout << "Test 4... "; 55 | std::vector arr4 = sorting::wave_sort::waveSort(array4, 6); 56 | const std::vector o4 = {4, 3, 8, 6, 14, 9}; 57 | assert(arr4 == o4); 58 | std::cout << "passed" << std::endl; 59 | } 60 | 61 | 62 | int main() { 63 | test(); // run self-test implementations 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTRIBUTING.md 2 | 3 | The following are needed to be added in the repository: 4 | ## Data Structures (I) 5 | - Stack 6 | - Queue 7 | - Types of Queue 8 | - Circular Queue 9 | - Priority Queue 10 | - Deque 11 | 12 | ## Data Structures (II) 13 | - Linked List 14 | - Linked List Operations 15 | - Types of Linked List 16 | - Hash Table 17 | - Heap Data Structure 18 | - Fibonacci Heap 19 | - Decrease Key and Delete node from Fibonacci Heap 20 | 21 | ## Tree based DSA (I) 22 | - Tree Data Structure 23 | - Tree Traversal 24 | - Binary Tree 25 | - Full Binary Tree 26 | - Perfect Binary Tree 27 | - Complete Binary Tree 28 | - Balanced Binary Tree 29 | - Binary Search Tree 30 | - AVL Tree 31 | 32 | ## Tree based DSA (II) 33 | - B Tree 34 | - Insertion into B-tree 35 | - Deletion from B-tree 36 | - B+ Tree 37 | - Insertion on a B+ Tree 38 | - Deletion from a B+ Tree 39 | - Red Black Tree 40 | - Insertion in Red Black Tree 41 | - Deletion from Red Black Tree 42 | 43 | ## Graph based DSA 44 | - Graph Data Structure 45 | - Spanning Tree 46 | - Strongly Connected Components 47 | - Adjacency Matrix 48 | - Adjacency List 49 | - DFS Algorithm 50 | - Breadth-first Search 51 | - Bellman Ford's Algorithm 52 | 53 | ## Sorting and Searching Algorithms 54 | - Bubble Sort 55 | - Selection Sort 56 | - Insertion Sort 57 | - Merge Sort 58 | - Quick Sort 59 | - Counting Sort 60 | - Radix Sort 61 | - Bucket Sort 62 | - Heap Sort 63 | - Shell Sort 64 | - Linear Search 65 | - Binary Search 66 | 67 | ## Greedy Algorithms 68 | - Greedy Algorithm 69 | - Ford-Fulkerson Algorithm 70 | - Dijkstra's Algorithm 71 | - Kruskal's Algorithm 72 | - Prim's Algorithm 73 | - Huffman Code 74 | 75 | ## Dynamic Programming 76 | - Dynamic Programming 77 | - Floyd Warshall Algorithm 78 | - Longest Common Subsequence 79 | 80 | ## Other Algorithms 81 | - Backtracking Algorithm 82 | - Rabin-Karp Algorithm 83 | -------------------------------------------------------------------------------- /Java_DS/linkedlist.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LinkedList2{ 3 | public static void main(String args[]){ 4 | LinkedList ll=new LinkedList(); 5 | System.out.println("Initial list of elements: "+ll); 6 | ll.add("Ravi"); 7 | ll.add("Vijay"); 8 | ll.add("Ajay"); 9 | System.out.println("After invoking add(E e) method: "+ll); 10 | //Adding an element at the specific position 11 | ll.add(1, "Gaurav"); 12 | System.out.println("After invoking add(int index, E element) method: "+ll); 13 | LinkedList ll2=new LinkedList(); 14 | ll2.add("Sonoo"); 15 | ll2.add("Hanumat"); 16 | //Adding second list elements to the first list 17 | ll.addAll(ll2); 18 | System.out.println("After invoking addAll(Collection c) method: "+ll); 19 | LinkedList ll3=new LinkedList(); 20 | ll3.add("John"); 21 | ll3.add("Rahul"); 22 | //Adding second list elements to the first list at specific position 23 | ll.addAll(1, ll3); 24 | System.out.println("After invoking addAll(int index, Collection c) method: "+ll); 25 | //Adding an element at the first position 26 | ll.addFirst("Lokesh"); 27 | System.out.println("After invoking addFirst(E e) method: "+ll); 28 | //Adding an element at the last position 29 | ll.addLast("Harsh"); 30 | System.out.println("After invoking addLast(E e) method: "+ll); 31 | //Removing first element from the list 32 | ll.removeFirst(); 33 | System.out.println("After invoking removeFirst() method: "+ll); 34 | LinkedList ll=new LinkedList(); 35 | ll.add("Ravi"); 36 | ll.add("Vijay"); 37 | ll.add("Ajay"); 38 | //Traversing the list of elements in reverse order 39 | Iterator i=ll.descendingIterator(); 40 | while(i.hasNext()) 41 | { 42 | System.out.println(i.next()); 43 | } 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Leetcode Medium questions/3Sum Closest/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | 5 | sort(nums.begin(),nums.end()); 6 | int n = nums.size(); 7 | int diff = INT_MAX; 8 | int ans =0; 9 | for(int i = 0; i target){ 26 | k--; 27 | } 28 | else{ 29 | j++; 30 | } 31 | } 32 | 33 | } 34 | 35 | return ans; 36 | 37 | } 38 | 39 | }; -------------------------------------------------------------------------------- /Leetcode Medium questions/3Sum/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | 5 | sort(nums.begin(),nums.end()); 6 | int n = nums.size(); 7 | vector> ans; 8 | 9 | for(int i = 0; i -nums[i]){ 25 | k--; 26 | } 27 | else if(sum < -nums[i]){ 28 | j++; 29 | } 30 | } 31 | while(inext = temp; 13 | tail = temp; 14 | 15 | } 16 | public: 17 | ListNode* add(ListNode* &l1, ListNode* &l2){ 18 | 19 | if(l1 == NULL && l2 == NULL){ 20 | return NULL; 21 | } 22 | int carry = 0; 23 | ListNode*anshead = NULL; 24 | ListNode*anstail = NULL; 25 | 26 | while(l1 != NULL && l2 != NULL){ 27 | int sum = l1->val + l2->val + carry; 28 | int digit = sum % 10; 29 | insertAttail(anshead,anstail,digit); 30 | carry = sum/10; 31 | l1 =l1->next; 32 | l2 = l2->next; 33 | } 34 | 35 | while(l1 != NULL){ 36 | 37 | int sum = l1->val + carry; 38 | int digit = sum % 10; 39 | insertAttail(anshead,anstail,digit); 40 | carry = sum/10; 41 | l1 =l1->next; 42 | } 43 | while(l2 != NULL){ 44 | 45 | int sum = l2->val + carry; 46 | int digit = sum % 10; 47 | insertAttail(anshead,anstail,digit); 48 | carry = sum/10; 49 | l2 = l2->next; 50 | } 51 | while(carry != NULL){ 52 | 53 | int sum = carry; 54 | int digit = sum % 10; 55 | insertAttail(anshead,anstail,digit); 56 | carry = sum/10; 57 | } 58 | 59 | return anshead; 60 | 61 | } 62 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 63 | 64 | ListNode*ans = add(l1,l2); 65 | 66 | return ans; 67 | } 68 | }; -------------------------------------------------------------------------------- /Leetcode Medium questions/Chef and Division3/Question.c: -------------------------------------------------------------------------------- 1 | // Problem : 2 | /* 3 | Chef wants to host some Division-3 contests. Chef has N setters who are busy creating new problems for him. The ith setter has made Ai problems where 1≤i≤N. 4 | A Division-3 contest should have exactly K problems. Chef wants to plan for the next D days using the problems that they have currently. 5 | But Chef cannot host more than one Division-3 contest in a day. 6 | Given these constraints, can you help Chef find the maximum number of Division-3 contests that can be hosted in these D days? 7 | */ 8 | // Input : 9 | /* 10 | The first line of input contains a single integer T denoting the number of test cases. The description of T test cases follows. 11 | The first line of each test case contains three space-separated integers - N, K and D respectively. 12 | The second line of each test case contains N space-separated integers A1,A2,…,AN respectively. 13 | */ 14 | // Output : 15 | /* 16 | For each test case, print a single line containing one integer ― the maximum number of Division - 3 contests Chef can host in these D days. 17 | */ 18 | // Constraints : 19 | /* 20 | 1≤T≤103 21 | 1≤N≤102 22 | 1≤K≤109 23 | 1≤D≤109 24 | 1≤Ai≤107 for each valid i 25 | */ 26 | // Subtasks : 27 | /* 28 | Subtask #1 (40 points): 29 | N=1 30 | 1≤A1≤105 31 | Subtask #2 (60 points): 32 | Original constraints 33 | */ 34 | // Sample Input : 35 | /* 36 | 5 37 | 1 5 31 38 | 4 39 | 1 10 3 40 | 23 41 | 2 5 7 42 | 20 36 43 | 2 5 10 44 | 19 2 45 | 3 3 300 46 | 1 1 1 47 | */ 48 | // Sample Output : 49 | /* 50 | 0 51 | 2 52 | 7 53 | 4 54 | 1 55 | */ 56 | // Explanation : 57 | /* 58 | Example case 1: Chef only has A1=4 problems and he needs K=5 problems for a Division-3 contest. 59 | So Chef won't be able to host any Division-3 contest in these 31 days. Hence the first output is 0. 60 | Example case 2: Chef has A1=23 problems and he needs K=10 problems for a Division-3 contest. 61 | Chef can choose any 10+10=20 problems and host 2 Division-3 contests in these 3 days. Hence the second output is 2. 62 | Example case 3: Chef has A1=20 problems from setter-1 and A2=36 problems from setter-2, and so has a total of 56 problems. 63 | Chef needs K=5 problems for each Division-3 contest. Hence Chef can prepare 11 Division-3 contests. 64 | But since we are planning only for the next D=7 days and Chef cannot host more than 1 contest in a day, Chef cannot host more than 7 contests. 65 | Hence the third output is 7. 66 | */ -------------------------------------------------------------------------------- /Leetcode Medium questions/Chef and Division3/Solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | void main() 3 | { 4 | int T, N, K, D, A; 5 | scanf("%d", &T); 6 | while (T > 0) 7 | { 8 | int S = 0; 9 | scanf("%d%d%d", &N, &K, &D); 10 | for (int a = 1; a <= N; a += 1) 11 | { 12 | scanf("%d", &A); 13 | S = S + A; 14 | } 15 | if (S / K >= D) 16 | { 17 | printf("%d\n", D); 18 | } 19 | else 20 | { 21 | printf("%d\n", S / K); 22 | } 23 | T--; 24 | } 25 | } -------------------------------------------------------------------------------- /Leetcode Medium questions/Container With Most Water/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | 5 | int start = 0; 6 | int end = height.size()-1; 7 | int area = 0; 8 | while(start s_in = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 5 | vector s = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 6 | vector str; 7 | for(int i = 0; i= s_in[i]){ 9 | str.push_back(s[i]); 10 | num = num - s_in[i]; 11 | } 12 | } 13 | 14 | string ans = ""; 15 | for(auto x: str){ 16 | ans = ans + x; 17 | } 18 | 19 | 20 | return ans; 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /Leetcode Medium questions/Letter-combinations-of-a-phone-number/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const vector pad = { 4 | "", "", "abc", "def", "ghi", "jkl", 5 | "mno", "pqrs", "tuv", "wxyz" 6 | }; 7 | 8 | vector letterCombinations(string digits) { 9 | if (digits.empty()) return {}; 10 | vector result; 11 | result.push_back(""); 12 | 13 | for(auto digit: digits) { 14 | vector tmp; 15 | for(auto candidate: pad[digit - '0']) { 16 | for(auto s: result) { 17 | tmp.push_back(s + candidate); 18 | } 19 | } 20 | result.swap(tmp); 21 | } 22 | return result; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Medium questions/Minimum Time to Make Rope Colorful/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int minCost(string colors, vector& neededTime) { 5 | 6 | int ans = 0; 7 | int n = colors.size(); 8 | int j = 0; 9 | for(int i = 1; i < n; i++){ 10 | if(colors[i] == colors[i-1]){ 11 | ans += min(neededTime[i],neededTime[i-1]); 12 | neededTime[i] = max(neededTime[i], neededTime[i - 1]); 13 | } 14 | } 15 | 16 | return ans; 17 | 18 | } 19 | }; -------------------------------------------------------------------------------- /Leetcode Medium questions/Next Permutation/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void permute(vector nums,vector> &ans,int idx){ 5 | 6 | if(idx == nums.size()){ 7 | ans.push_back(nums); 8 | return; 9 | } 10 | 11 | for(int i = idx; i> permute(vector& nums) { 20 | 21 | vector> ans; 22 | 23 | permute(nums,ans,0); 24 | 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Leetcode Medium questions/Reverse Integer/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | 5 | int reverse = 0; 6 | 7 | while(x != 0){ 8 | if((reverse>INT_MAX/10)||(reverse>& matrix) { 4 | 5 | int n = matrix.size(); 6 | 7 | for(int i = 0; i& nums, int target) { 4 | 5 | int low = 0; 6 | int high = nums.size() - 1; 7 | 8 | while(low <= high){ 9 | 10 | int mid = (low+high)/2; 11 | 12 | if(nums[mid] == target){ 13 | return true; 14 | } 15 | if((nums[low] == nums[mid]) && (nums[high] == nums[mid])){ 16 | ++low; 17 | --high; 18 | } 19 | else if(nums[mid] >= nums[low]){ 20 | 21 | if(target >= nums[low] && target < nums[mid]){ 22 | high = mid - 1; 23 | } 24 | else{ 25 | low = mid + 1; 26 | } 27 | } 28 | 29 | else{ 30 | 31 | if(target > nums[mid] && target <= nums[high]){ 32 | low = mid + 1; 33 | } 34 | 35 | else{ 36 | high = mid -1; 37 | } 38 | } 39 | } 40 | 41 | return false; 42 | 43 | } 44 | 45 | }; -------------------------------------------------------------------------------- /Python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/Python/.DS_Store -------------------------------------------------------------------------------- /Python/Arrays/Find-missing-number.py: -------------------------------------------------------------------------------- 1 | #Approch of getting missing numbers in an array by using N natural numbers Summation Method.... 2 | 3 | def getting_missing_summation(a): 4 | n = a[-1] 5 | sum1=0 6 | total=n*(n+1)//2 7 | sum1=sum(a) 8 | print(total - sum1) 9 | 10 | a = [1,2,3,5,6,7,8,9] 11 | getting_missing_summation(a) 12 | 13 | 14 | -------------------------------------------------------------------------------- /Python/linkedlist/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Manraj-Mann/Hacktoberfest-DSA-Codes/bbcd3aabc820f21b10af9a5caa0ca1c374119f5a/Python/linkedlist/.DS_Store -------------------------------------------------------------------------------- /Python/linkedlist/dsa.py: -------------------------------------------------------------------------------- 1 | # Creating a List with 2 | # the use of multiple values 3 | List = ["Geeks", "For", "Geeks"] 4 | print("\nList containing multiple values: ") 5 | print(List) 6 | 7 | # Creating a Multi-Dimensional List 8 | # (By Nesting a list inside a List) 9 | List2 = [['Geeks', 'For'], ['Geeks']] 10 | print("\nMulti-Dimensional List: ") 11 | print(List2) 12 | 13 | # accessing a element from the 14 | # list using index number 15 | print("Accessing element from the list") 16 | print(List[0]) 17 | print(List[2]) 18 | 19 | # accessing a element using 20 | # negative indexing 21 | print("Accessing element using negative indexing") 22 | 23 | # print the last element of list 24 | print(List[-1]) 25 | 26 | # print the third last element of list 27 | print(List[-3]) 28 | -------------------------------------------------------------------------------- /Python/linkedlist/singularlinkedlist/3 Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | ans=[] 4 | nums.sort() 5 | n=len(nums) 6 | for i in range(n-2): 7 | if i==0 or nums[i]!=nums[i-1]: 8 | j=i+1 9 | k=n-1 10 | while jj and nums[k]==nums[k-1]: 17 | k-=1 18 | j+=1 19 | k-=1 20 | elif sum>0: 21 | k-=1 22 | elif sum<0: 23 | j+=1 24 | return ans -------------------------------------------------------------------------------- /Python/linkedlist/singularlinkedlist/insertingAtbeginning.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, dataval=None): 3 | self.dataval = dataval 4 | self.nextval = None 5 | 6 | class SLinkedList: 7 | def __init__(self): 8 | self.headval = None 9 | # Print the linked list 10 | def listprint(self): 11 | printval = self.headval 12 | while printval is not None: 13 | print (printval.dataval) 14 | printval = printval.nextval 15 | def AtBegining(self,newdata):#adding the node in the beginning 16 | NewNode = Node(newdata) 17 | 18 | # Update the new nodes next val to existing node 19 | NewNode.nextval = self.headval 20 | self.headval = NewNode 21 | 22 | list = SLinkedList() 23 | list.headval = Node("A") 24 | e2 = Node("B") 25 | e3 = Node("C") 26 | 27 | list.headval.nextval = e2 28 | e2.nextval = e3 29 | 30 | list.AtBegining("Z") 31 | list.listprint() -------------------------------------------------------------------------------- /Python/linkedlist/singularlinkedlist/traversingLinkedlist.py: -------------------------------------------------------------------------------- 1 | #declaring the node 2 | class Node: 3 | def __init__(self, dataval=None): 4 | self.dataval = dataval 5 | self.nextval = None 6 | 7 | class SLinkedList: 8 | def __init__(self):#if there doesnt exist head/linkedlist 9 | self.headval = None 10 | 11 | def listprint(self):#traversing the linkedlist n printing it 12 | printval = self.headval 13 | while printval is not None: 14 | print (printval.dataval) 15 | printval = printval.nextval 16 | 17 | list = SLinkedList() 18 | list.headval = Node("A") 19 | e2 = Node("B") 20 | e3 = Node("C") 21 | 22 | # Link first Node to second node 23 | list.headval.nextval = e2 24 | 25 | # Link second Node to third node 26 | e2.nextval = e3 27 | 28 | list.listprint() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest-DSA-Codes 2 | 3 | ### Want to contribute ? Refer [Contributing.md](https://github.com/Manraj-Mann/Hacktoberfest-DSA-Codes/blob/main/CONTRIBUTING.md) 4 | 5 |

image

6 | 7 |

Hello Welcome Developers!

8 | 9 |

What is Hacktoberfest?

10 | 11 |

Every year in October, an open source event called Hacktoberfest inspires individuals all over the world to actively engage in and contribute to open source projects that are hosted on GitHub and GitLab. By taking part in this event, you may receive a free GitHub swag pack. You must submit 4 pull requests in order to receive that awesome swag pack.

12 | 13 |

You can pick an issue and complete it, but there is twist. You have to select a language from the list below to complete the issue.

14 | 15 |

Language list

16 |
  • C
  • 17 |
  • C++
  • 18 |
  • C#
  • 19 |
  • Java
  • 20 |
  • JS
  • 21 |
  • Python
  • 22 |
    23 |

    24 | 25 | ## Let's begin 26 | 27 | 1. Complete the registartion over https://hacktoberfest.com/ 28 | 2. Fork this repository. 29 | 3. Clone on your local machine. 30 | 31 | HTTPS 32 | ```bash 33 | git clone https://github.com//Hacktoberfest-DSA-Codes.git 34 | ``` 35 | SSH 36 | ```bash 37 | git@github.com:/Hacktoberfest-DSA-Codes.git 38 | ``` 39 | 4. Navigate to the project directory. 40 | ```bash 41 | cd Hacktoberfest-DSA-Codes 42 | ``` 43 | 5. Create a new branch. 44 | ```bash 45 | git checkout -b my-new-branch 46 | ``` 47 | 6. Add your contribution. 48 | ```bash 49 | git add . 50 | ``` 51 | 7. Commit your changes. 52 | ```bash 53 | git commit -m "Relevant message" 54 | ``` 55 | 8. Push your changes. 56 | ```bash 57 | git push origin my-new-branch 58 | ``` 59 | 9. Create a new pull request from your forked repository. 60 | 61 | 10. Congratulations 🎉 you just made a pull request! 62 | 63 | Please be advise: After you completed your task don't close the issue 64 | -------------------------------------------------------------------------------- /Smallest_subarray_with_sum_greater_than_given_value.cpp: -------------------------------------------------------------------------------- 1 | int smallestSubWithSum(int arr[], int n, int x) 2 | 3 | { 4 | 5 | int currn_sum = 0; 6 | 7 | int j = 0; 8 | 9 | int length = n; 10 | 11 | for(int i = 0 ; i < n ; i++){ 12 | 13 | currn_sum +=arr[i]; 14 | 15 | if(currn_sum > x){ 16 | 17 | while(currn_sum - arr[j] > x){ 18 | 19 | currn_sum = currn_sum - arr[j]; 20 | 21 | j++; 22 | 23 | } 24 | 25 | if(length > i - j){ 26 | 27 | length = i - j; 28 | 29 | } 30 | 31 | } 32 | 33 | } 34 | 35 | return length + 1; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Socket/client.py: -------------------------------------------------------------------------------- 1 | import socket #Module for making the connection 2 | import os 3 | soc = socket.socket() 4 | soc.connect(("192.168.56.1",5800)) #Build connection with admin machines. 5 | filehandler = open ("/home/testing/Desktop/sentfile.txt", "rb") #Reading file that needs to be sent 6 | sendLine = filehandler.read(1024) #Port number 7 | print("Sending file.") 8 | while (sendLine): 9 | soc.send(sendLine) #sending the file's lines one by one 10 | sendLine = filehandler.read(1024) 11 | print("Task Completed!") 12 | soc.close() #closing connection after completing tasks 13 | print("Connection closed!") -------------------------------------------------------------------------------- /Socket/user.py: -------------------------------------------------------------------------------- 1 | import os 2 | import socket 3 | from datetime import datetime 4 | import psutil 5 | from operator import itemgetter 6 | 7 | filePath = "/home/testing/Desktop/sentfile.txt" 8 | fileMode = "w" 9 | systemUsername = os.getlogin() 10 | systemName = socket.gethostname() 11 | date=datetime.now().strftime("%H:%M:%S %m/%d/%Y ") 12 | allProcess = [] 13 | processList = [] 14 | listSorted = [] 15 | file = open(filePath,fileMode ) 16 | file.write("\n%-30s%-30s"%("Username: " , systemUsername)) 17 | file.write("\n%-30s%-30s"%("Computer Name: " + systemName)) 18 | file.write("\n%-30s%-30s"%("Date and Time: "+date)) 19 | 20 | for aProcess in psutil.process_iter(): 21 | processList = aProcess.as_dict(attrs=['pid', 'name']) 22 | processList['vms'] = aProcess.memory_info().vms / (1024 * 1024) 23 | allProcess.append(processList) 24 | 25 | for item in allProcess: 26 | processList.append([item['name'],item['pid'],item['vms']]) 27 | 28 | listSorted = sorted(processList,key=itemgetter(2), reverse=True) 29 | 30 | 31 | def writeData(): 32 | file.write("\n%-15s%-15s"%("\nTotal number of process:",len(listSorted))) 33 | file.write("\n%-15s%-15s%-15s"%("\nName","Process ID","Process Memory")) 34 | 35 | for i in range(0,10,1): 36 | file.write("\n%-15s%-15s%-15s"%(listSorted[i][0],listSorted[i][1],round(listSorted[i][2],2))) 37 | 38 | 39 | writeData() -------------------------------------------------------------------------------- /Sorting algo/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation 2 | // of Bubble sort 3 | #include 4 | using namespace std; 5 | 6 | // A function to implement bubble sort 7 | void bubbleSort(int arr[], int n) 8 | { 9 | int i, j; 10 | for (i = 0; i < n - 1; i++) 11 | 12 | // Last i elements are already 13 | // in place 14 | for (j = 0; j < n - i - 1; j++) 15 | if (arr[j] > arr[j + 1]) 16 | swap(arr[j], arr[j + 1]); 17 | } 18 | 19 | // Function to print an array 20 | void printArray(int arr[], int size) 21 | { 22 | int i; 23 | for (i = 0; i < size; i++) 24 | cout << arr[i] << " "; 25 | cout << endl; 26 | } 27 | 28 | // Driver code 29 | int main() 30 | { 31 | int arr[] = { 5, 1, 4, 2, 8}; 32 | int N = sizeof(arr) / sizeof(arr[0]); 33 | bubbleSort(arr, N); 34 | cout << "Sorted array: \n"; 35 | printArray(arr, N); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Sorting algo/countingSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | #include 4 | using namespace std; 5 | #define RANGE 255 6 | 7 | // The main function that sort 8 | // the given string arr[] in 9 | // alphabetical order 10 | void countSort(char arr[]) 11 | { 12 | // The output character array 13 | // that will have sorted arr 14 | char output[strlen(arr)]; 15 | 16 | // Create a count array to store count of individual 17 | // characters and initialize count array as 0 18 | int count[RANGE + 1], i; 19 | memset(count, 0, sizeof(count)); 20 | 21 | // Store count of each character 22 | for (i = 0; arr[i]; ++i) 23 | ++count[arr[i]]; 24 | 25 | // Change count[i] so that count[i] now contains actual 26 | // position of this character in output array 27 | for (i = 1; i <= RANGE; ++i) 28 | count[i] += count[i - 1]; 29 | 30 | // Build the output character array 31 | for (i = 0; arr[i]; ++i) { 32 | output[count[arr[i]] - 1] = arr[i]; 33 | --count[arr[i]]; 34 | } 35 | 36 | /* 37 | For Stable algorithm 38 | for (i = sizeof(arr)-1; i>=0; --i) 39 | { 40 | output[count[arr[i]]-1] = arr[i]; 41 | --count[arr[i]]; 42 | } 43 | 44 | For Logic : See implementation 45 | */ 46 | 47 | // Copy the output array to arr, so that arr now 48 | // contains sorted characters 49 | for (i = 0; arr[i]; ++i) 50 | arr[i] = output[i]; 51 | } 52 | 53 | // Driver code 54 | int main() 55 | { 56 | char arr[] = "geeksforgeeks"; 57 | 58 | countSort(arr); 59 | 60 | cout << "Sorted character array is " << arr; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Sorting algo/heapSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | // To heapify a subtree rooted with node i 7 | // which is an index in arr[]. 8 | // n is size of heap 9 | void heapify(int arr[], int N, int i) 10 | { 11 | 12 | // Initialize largest as root 13 | int largest = i; 14 | 15 | // left = 2*i + 1 16 | int l = 2 * i + 1; 17 | 18 | // right = 2*i + 2 19 | int r = 2 * i + 2; 20 | 21 | // If left child is larger than root 22 | if (l < N && arr[l] > arr[largest]) 23 | largest = l; 24 | 25 | // If right child is larger than largest 26 | // so far 27 | if (r < N && arr[r] > arr[largest]) 28 | largest = r; 29 | 30 | // If largest is not root 31 | if (largest != i) { 32 | swap(arr[i], arr[largest]); 33 | 34 | // Recursively heapify the affected 35 | // sub-tree 36 | heapify(arr, N, largest); 37 | } 38 | } 39 | 40 | // Main function to do heap sort 41 | void heapSort(int arr[], int N) 42 | { 43 | 44 | // Build heap (rearrange array) 45 | for (int i = N / 2 - 1; i >= 0; i--) 46 | heapify(arr, N, i); 47 | 48 | // One by one extract an element 49 | // from heap 50 | for (int i = N - 1; i > 0; i--) { 51 | 52 | // Move current root to end 53 | swap(arr[0], arr[i]); 54 | 55 | // call max heapify on the reduced heap 56 | heapify(arr, i, 0); 57 | } 58 | } 59 | 60 | // A utility function to print array of size n 61 | void printArray(int arr[], int N) 62 | { 63 | for (int i = 0; i < N; ++i) 64 | cout << arr[i] << " "; 65 | cout << "\n"; 66 | } 67 | 68 | // Driver's code 69 | int main() 70 | { 71 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 72 | int N = sizeof(arr) / sizeof(arr[0]); 73 | 74 | // Function call 75 | heapSort(arr, N); 76 | 77 | cout << "Sorted array is \n"; 78 | printArray(arr, N); 79 | } 80 | -------------------------------------------------------------------------------- /Sorting algo/insertionSort.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 | { 13 | key = arr[i]; 14 | j = i - 1; 15 | 16 | // Move elements of arr[0..i-1], 17 | // that are greater than key, to one 18 | // position ahead of their 19 | // current position 20 | while (j >= 0 && arr[j] > key) 21 | { 22 | arr[j + 1] = arr[j]; 23 | j = j - 1; 24 | } 25 | arr[j + 1] = key; 26 | } 27 | } 28 | 29 | // A utility function to print an array 30 | // of size n 31 | void printArray(int arr[], int n) 32 | { 33 | int i; 34 | for (i = 0; i < n; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | int arr[] = { 12, 11, 13, 5, 6 }; 43 | int N = sizeof(arr) / sizeof(arr[0]); 44 | 45 | insertionSort(arr, N); 46 | printArray(arr, N); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Sorting algo/quickSort.cpp: -------------------------------------------------------------------------------- 1 | /* C++ implementation of QuickSort */ 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to swap two elements 6 | void swap(int* a, int* b) 7 | { 8 | int t = *a; 9 | *a = *b; 10 | *b = t; 11 | } 12 | 13 | /* This function takes last element as pivot, places 14 | the pivot element at its correct position in sorted 15 | array, and places all smaller (smaller than pivot) 16 | to left of pivot and all greater elements to right 17 | of pivot */ 18 | int partition(int arr[], int low, int high) 19 | { 20 | int pivot = arr[high]; // pivot 21 | int i 22 | = (low 23 | - 1); // Index of smaller element and indicates 24 | // the right position of pivot found so far 25 | 26 | for (int j = low; j <= high - 1; j++) { 27 | // If current element is smaller than the pivot 28 | if (arr[j] < pivot) { 29 | i++; // increment index of smaller element 30 | swap(&arr[i], &arr[j]); 31 | } 32 | } 33 | swap(&arr[i + 1], &arr[high]); 34 | return (i + 1); 35 | } 36 | 37 | /* The main function that implements QuickSort 38 | arr[] --> Array to be sorted, 39 | low --> Starting index, 40 | high --> Ending index */ 41 | void quickSort(int arr[], int low, int high) 42 | { 43 | if (low < high) { 44 | /* pi is partitioning index, arr[p] is now 45 | at right place */ 46 | int pi = partition(arr, low, high); 47 | 48 | // Separately sort elements before 49 | // partition and after partition 50 | quickSort(arr, low, pi - 1); 51 | quickSort(arr, pi + 1, high); 52 | } 53 | } 54 | 55 | /* Function to print an array */ 56 | void printArray(int arr[], int size) 57 | { 58 | int i; 59 | for (i = 0; i < size; i++) 60 | cout << arr[i] << " "; 61 | cout << endl; 62 | } 63 | 64 | // Driver Code 65 | int main() 66 | { 67 | int arr[] = { 10, 7, 8, 9, 1, 5 }; 68 | int n = sizeof(arr) / sizeof(arr[0]); 69 | quickSort(arr, 0, n - 1); 70 | cout << "Sorted array: \n"; 71 | printArray(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /Sorting algo/selectionSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of 2 | // selection sort 3 | #include 4 | using namespace std; 5 | 6 | //Swap function 7 | void swap(int *xp, int *yp) 8 | { 9 | int temp = *xp; 10 | *xp = *yp; 11 | *yp = temp; 12 | } 13 | 14 | void selectionSort(int arr[], int n) 15 | { 16 | int i, j, min_idx; 17 | 18 | // One by one move boundary of 19 | // unsorted subarray 20 | for (i = 0; i < n-1; i++) 21 | { 22 | 23 | // Find the minimum element in 24 | // unsorted array 25 | min_idx = i; 26 | for (j = i+1; j < n; j++) 27 | if (arr[j] < arr[min_idx]) 28 | min_idx = j; 29 | 30 | // Swap the found minimum element 31 | // with the first element 32 | if(min_idx!=i) 33 | swap(&arr[min_idx], &arr[i]); 34 | } 35 | } 36 | 37 | //Function to print an array 38 | void printArray(int arr[], int size) 39 | { 40 | int i; 41 | for (i=0; i < size; i++) 42 | cout << arr[i] << " "; 43 | cout << endl; 44 | } 45 | 46 | // Driver program to test above functions 47 | int main() 48 | { 49 | int arr[] = {64, 25, 12, 22, 11}; 50 | int n = sizeof(arr)/sizeof(arr[0]); 51 | selectionSort(arr, n); 52 | cout << "Sorted array: \n"; 53 | printArray(arr, n); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/CoinChangeProblem.cpp: -------------------------------------------------------------------------------- 1 | // Recursive C++ program for 2 | // coin change problem. 3 | #include 4 | using namespace std; 5 | 6 | // Returns the count of ways we can 7 | // sum coins[0...n-1] coins to get sum "sum" 8 | int count(int coins[], int n, int sum) 9 | { 10 | 11 | // If sum is 0 then there is 1 solution 12 | // (do not include any coin) 13 | if (sum == 0) 14 | return 1; 15 | 16 | // If sum is less than 0 then no 17 | // solution exists 18 | if (sum < 0) 19 | return 0; 20 | 21 | // If there are no coins and sum 22 | // is greater than 0, then no 23 | // solution exist 24 | if (n <= 0) 25 | return 0; 26 | 27 | // count is sum of solutions (i) 28 | // including coins[n-1] (ii) excluding coins[n-1] 29 | return count(coins, n - 1, sum) 30 | + count(coins, n, sum - coins[n - 1]); 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int i, j; 37 | int coins[] = { 1, 2, 3 }; 38 | int n = sizeof(coins) / sizeof(coins[0]); 39 | int sum = 4; 40 | 41 | cout << " " << count(coins, n, sum); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/MaxProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find Maximum Product Subarray 2 | #include 3 | using namespace std; 4 | 5 | /* Returns the product of max product subarray.*/ 6 | int maxSubarrayProduct(int arr[], int n) 7 | { 8 | // Initializing result 9 | int result = arr[0]; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | int mul = arr[i]; 14 | // traversing in current subarray 15 | for (int j = i + 1; j < n; j++) 16 | { 17 | // updating result every time 18 | // to keep an eye over the maximum product 19 | result = max(result, mul); 20 | mul *= arr[j]; 21 | } 22 | // updating the result for (n-1)th index. 23 | result = max(result, mul); 24 | } 25 | return result; 26 | } 27 | 28 | // Driver code 29 | int main() 30 | { 31 | int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | cout << "Maximum Sub array product is " 34 | << maxSubarrayProduct(arr, n); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Top Interview questions/Arrays/MaximumIndex.cpp: -------------------------------------------------------------------------------- 1 | // CPP program for the above approach 2 | #include 3 | using namespace std; 4 | 5 | /* For a given array arr[], 6 | returns the maximum j – i such 7 | that arr[j] > arr[i] */ 8 | int maxIndexDiff(int arr[], int n) 9 | { 10 | int maxDiff = -1; 11 | int i, j; 12 | 13 | for (i = 0; i < n; ++i) { 14 | for (j = n - 1; j > i; --j) { 15 | if (arr[j] > arr[i] && maxDiff < (j - i)) 16 | maxDiff = j - i; 17 | } 18 | } 19 | 20 | return maxDiff; 21 | } 22 | 23 | int main() 24 | { 25 | int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 }; 26 | int n = sizeof(arr) / sizeof(arr[0]); 27 | int maxDiff = maxIndexDiff(arr, n); 28 | cout << "\n" << maxDiff; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/Peak Element.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 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/Sortthearray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array 2 | // with 0, 1 and 2 in a single pass 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort the input array, 7 | // the array is assumed 8 | // to have values in {0, 1, 2} 9 | void sort012(int a[], int arr_size) 10 | { 11 | int lo = 0; 12 | int hi = arr_size - 1; 13 | int mid = 0; 14 | 15 | // Iterate till all the elements 16 | // are sorted 17 | while (mid <= hi) { 18 | switch (a[mid]) { 19 | 20 | // If the element is 0 21 | case 0: 22 | swap(a[lo++], a[mid++]); 23 | break; 24 | 25 | // If the element is 1 . 26 | case 1: 27 | mid++; 28 | break; 29 | 30 | // If the element is 2 31 | case 2: 32 | swap(a[mid], a[hi--]); 33 | break; 34 | } 35 | } 36 | } 37 | 38 | // Function to print array arr[] 39 | void printArray(int arr[], int arr_size) 40 | { 41 | // Iterate and print every element 42 | for (int i = 0; i < arr_size; i++) 43 | cout << arr[i] << " "; 44 | } 45 | 46 | // Driver Code 47 | int main() 48 | { 49 | int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | 52 | sort012(arr, n); 53 | 54 | printArray(arr, n); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/SubarraySum.cpp: -------------------------------------------------------------------------------- 1 | /* A simple program to print subarray 2 | with sum as given sum */ 3 | #include 4 | using namespace std; 5 | 6 | /* Returns true if the there is a subarray 7 | of arr[] with sum equal to 'sum' otherwise 8 | returns false. Also, prints the result */ 9 | void subArraySum(int arr[], int n, int sum) 10 | { 11 | 12 | // Pick a starting point 13 | for (int i = 0; i < n; i++) { 14 | int currentSum = arr[i]; 15 | 16 | if (currentSum == sum) { 17 | cout << "Sum found at indexes " << i << endl; 18 | return; 19 | } 20 | else { 21 | // Try all subarrays starting with 'i' 22 | for (int j = i + 1; j < n; j++) { 23 | currentSum += arr[j]; 24 | 25 | if (currentSum == sum) { 26 | cout << "Sum found between indexes " 27 | << i << " and " << j << endl; 28 | return; 29 | } 30 | } 31 | } 32 | } 33 | cout << "No subarray found"; 34 | return; 35 | } 36 | 37 | // Driver Code 38 | int main() 39 | { 40 | int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; 41 | int n = sizeof(arr) / sizeof(arr[0]); 42 | int sum = 23; 43 | subArraySum(arr, n, sum); 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/TrappingRainwater.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find maximum amount of water that can 2 | // be trapped within given set of bars. 3 | #include 4 | using namespace std; 5 | 6 | int findWater(int arr[], int n) 7 | { 8 | // left[i] contains height of tallest bar to the 9 | // left of i'th bar including itself 10 | int left[n]; 11 | 12 | // Right [i] contains height of tallest bar to 13 | // the right of ith bar including itself 14 | int right[n]; 15 | 16 | // Initialize result 17 | int water = 0; 18 | 19 | // Fill left array 20 | left[0] = arr[0]; 21 | for (int i = 1; i < n; i++) 22 | left[i] = max(left[i - 1], arr[i]); 23 | 24 | // Fill right array 25 | right[n - 1] = arr[n - 1]; 26 | for (int i = n - 2; i >= 0; i--) 27 | right[i] = max(right[i + 1], arr[i]); 28 | 29 | // Calculate the accumulated water element by element 30 | // consider the amount of water on i'th bar, the 31 | // amount of water accumulated on this particular 32 | // bar will be equal to min(left[i], right[i]) - arr[i] 33 | // . 34 | for (int i = 1; i < n - 1; i++) { 35 | int var = min(left[i - 1], right[i + 1]); 36 | if (var > arr[i]) { 37 | water += var - arr[i]; 38 | } 39 | } 40 | 41 | return water; 42 | } 43 | 44 | // Driver program 45 | int main() 46 | { 47 | int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; 48 | int n = sizeof(arr) / sizeof(arr[0]); 49 | cout << findWater(arr, n); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/WaveArray.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to sort an array in wave form using 2 | // a sorting function 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // A utility method to swap two numbers. 8 | void swap(int *x, int *y) 9 | { 10 | int temp = *x; 11 | *x = *y; 12 | *y = temp; 13 | } 14 | 15 | // This function sorts arr[0..n-1] in wave form, i.e., 16 | // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5].. 17 | void sortInWave(int arr[], int n) 18 | { 19 | // Sort the input array 20 | sort(arr, arr+n); 21 | 22 | // Swap adjacent elements 23 | for (int i=0; i 4 | using namespace std; 5 | 6 | // arr[0..n-1] represents sizes of packets 7 | // m is number of students. 8 | // Returns minimum difference between maximum 9 | // and minimum values of distribution. 10 | int findMinDiff(int arr[], int n, int m) 11 | { 12 | // if there are no chocolates or number 13 | // of students is 0 14 | if (m == 0 || n == 0) 15 | return 0; 16 | 17 | // Sort the given packets 18 | sort(arr, arr + n); 19 | 20 | // Number of students cannot be more than 21 | // number of packets 22 | if (n < m) 23 | return -1; 24 | 25 | // Largest number of chocolates 26 | int min_diff = INT_MAX; 27 | 28 | // Find the subarray of size m such that 29 | // difference between last (maximum in case 30 | // of sorted) and first (minimum in case of 31 | // sorted) elements of subarray is minimum. 32 | 33 | for (int i = 0; i + m - 1 < n; i++) { 34 | int diff = arr[i + m - 1] - arr[i]; 35 | if (diff < min_diff) 36 | min_diff = diff; 37 | } 38 | return min_diff; 39 | } 40 | 41 | int main() 42 | { 43 | int arr[] = { 12, 4, 7, 9, 2, 23, 25, 41, 30, 44 | 40, 28, 42, 30, 44, 48, 43, 50 }; 45 | int m = 7; // Number of students 46 | int n = sizeof(arr) / sizeof(arr[0]); 47 | cout << "Minimum difference is " 48 | << findMinDiff(arr, n, m); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/missinginteger.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Find the missing element 2 | 3 | #include 4 | using namespace std; 5 | 6 | void findMissing(int arr[], int N) 7 | { 8 | int i; 9 | int temp[N + 1]; 10 | for(int i = 0; i <= N; i++){ 11 | temp[i] = 0; 12 | } 13 | 14 | for(i = 0; i < N; i++){ 15 | temp[arr[i] - 1] = 1; 16 | } 17 | 18 | 19 | int ans; 20 | for (i = 0; i <= N ; i++) { 21 | if (temp[i] == 0) 22 | ans = i + 1; 23 | } 24 | cout << ans; 25 | } 26 | 27 | /* Driver code */ 28 | int main() 29 | { 30 | int arr[] = { 1, 3, 7, 5, 6, 2 }; 31 | int n = sizeof(arr) / sizeof(arr[0]); 32 | findMissing(arr, n); 33 | } 34 | -------------------------------------------------------------------------------- /Top Interview questions/Arrays/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 | -------------------------------------------------------------------------------- /dijkstras.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int miniDist(int distance[], bool Tset[]) // finding minimum distance 5 | { 6 | int minimum = INT_MAX, ind; 7 | 8 | for (int k = 0; k < 6; k++) 9 | { 10 | if (Tset[k] == false && distance[k] <= minimum) 11 | { 12 | minimum = distance[k]; 13 | ind = k; 14 | } 15 | } 16 | return ind; 17 | } 18 | 19 | void DijkstraAlgo(int graph[6][6], int src) // adjacency matrix 20 | { 21 | int distance[6]; // // array to calculate the minimum distance for each node 22 | bool Tset[6]; // boolean array to mark visited and unvisited for each node 23 | 24 | for (int k = 0; k < 6; k++) 25 | { 26 | distance[k] = INT_MAX; 27 | Tset[k] = false; 28 | } 29 | 30 | distance[src] = 0; // Source vertex distance is set 0 31 | 32 | for (int k = 0; k < 6; k++) 33 | { 34 | int m = miniDist(distance, Tset); 35 | Tset[m] = true; 36 | for (int k = 0; k < 6; k++) 37 | { 38 | // updating the distance of neighbouring vertex 39 | if (!Tset[k] && graph[m][k] && distance[m] != INT_MAX && distance[m] + graph[m][k] < distance[k]) 40 | distance[k] = distance[m] + graph[m][k]; 41 | } 42 | } 43 | cout << "Vertex\t\tDistance from source vertex" << endl; 44 | for (int k = 0; k < 6; k++) 45 | { 46 | char str = 65 + k; 47 | cout << str << "\t\t\t" << distance[k] << endl; 48 | } 49 | } 50 | 51 | int main() 52 | { 53 | int graph[6][6] = { 54 | {0, 1, 2, 0, 0, 0}, 55 | {1, 0, 0, 5, 1, 0}, 56 | {2, 0, 0, 2, 3, 0}, 57 | {0, 5, 2, 0, 2, 2}, 58 | {0, 1, 3, 2, 0, 1}, 59 | {0, 0, 0, 2, 1, 0}}; 60 | DijkstraAlgo(graph, 0); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /graph_coloring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int m, n; 4 | vector x; 5 | vector> adj; 6 | int counter = 0; 7 | 8 | void print(vector &v) 9 | { 10 | 11 | // cout << "\n---------------------------------\n"; 12 | 13 | for (int i = 1; i < v.size(); i++) 14 | { 15 | cout << v[i] << " "; 16 | } 17 | cout << endl; 18 | // cout << "\n----------------------------------\n"; 19 | } 20 | void nextvalue(int k) 21 | { 22 | 23 | while (1) 24 | { 25 | x[k] = (x[k] + 1) % (m + 1); 26 | if (x[k] == 0) 27 | { 28 | 29 | return; 30 | } 31 | int i = 0; 32 | for (i = 0; i < adj[k].size(); i++) 33 | { 34 | if (x[k] == x[adj[k][i]]) 35 | { 36 | 37 | break; 38 | } 39 | } 40 | 41 | if (i == adj[k].size()) 42 | { 43 | 44 | return; 45 | } 46 | } 47 | } 48 | 49 | void mcoloring(int k) 50 | { 51 | while (k <= n) 52 | { 53 | // cout<<"k = "< 2 | #include 3 | #include 4 | #include 5 | 6 | void TriAngle(int x1, int y1, int x2, int y2, int x3, int y3) 7 | { 8 | line(x1, y1, x2, y2); 9 | line(x2, y2, x3, y3); 10 | line(x3, y3, x1, y1); 11 | } 12 | 13 | void Rotate(int x1, int y1, int x2, int y2, int x3, int y3) 14 | { 15 | int x, y, a1, b1, a2, b2, a3, b3; 16 | float Angle; 17 | printf("Enter the angle for rotation: "); 18 | scanf("%f", &Angle); 19 | cleardevice(); 20 | Angle = (Angle * 3.14) / 180; 21 | a1 = x2 + (x1 - x2) * cos(Angle) - (y1 - y2) * sin(Angle); 22 | b1 = y2 + (x1 - x2) * sin(Angle) + (y1 - y2) * cos(Angle); 23 | a2 = x2 + (x2 - x2) * cos(Angle) - (y2 - y2) * sin(Angle); 24 | b2 = y2 + (x2 - x2) * sin(Angle) + (y2 - y2) * cos(Angle); 25 | a3 = x2 + (x3 - x2) * cos(Angle) - (y3 - y2) * sin(Angle); 26 | b3 = y2 + (x3 - x2) * sin(Angle) + (y3 - y2) * cos(Angle); 27 | printf("Rotated: "); 28 | TriAngle(a1, b1, a2, b2, a3, b3); 29 | } 30 | 31 | int main() 32 | { 33 | int gd = DETECT, gm; 34 | int x1, y1, x2, y2, x3, y3; 35 | initgraph(&gd, &gm, (char *)" "); 36 | printf("Enter the 1st point for the triangle: "); 37 | scanf("%d%d", &x1, &y1); 38 | printf("Enter the 2nd point for the triangle: "); 39 | scanf("%d%d", &x2, &y2); 40 | printf("Enter the 3rd point for the triangle: "); 41 | scanf("%d%d", &x3, &y3); 42 | TriAngle(x1, y1, x2, y2, x3, y3); 43 | getch(); 44 | cleardevice(); 45 | Rotate(x1, y1, x2, y2, x3, y3); 46 | setcolor(5); 47 | TriAngle(x1, y1, x2, y2, x3, y3); 48 | getch(); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /sorting_in_java/bubble_sort.java: -------------------------------------------------------------------------------- 1 | // Java program to sort an array 2 | // using bubble sort 3 | import java.util.*; 4 | import java.util.Collections; 5 | //BUBBLE SORT 6 | public static void bubbleSort(int[] a) { 7 | boolean sorted = false; 8 | int temp; 9 | while(!sorted) { 10 | sorted = true; 11 | for (int i = 0; i < array.length - 1; i++) { 12 | if (a[i] > a[i+1]) { 13 | temp = a[i]; 14 | a[i] = a[i+1]; 15 | a[i+1] = temp; 16 | sorted = false; 17 | } 18 | } 19 | } 20 | } 21 | 22 | // Driver code 23 | public static void main(String args[]) 24 | { 25 | float array[] = { 8, 13,1, 9,21, 2}; 26 | 27 | int n = array.length; 28 | bubbleSort(array, n); 29 | 30 | System.out.println("Sorted array is "); 31 | for (float el : array) { 32 | System.out.print(el + " "); 33 | } 34 | } -------------------------------------------------------------------------------- /sorting_in_java/bucket_sort.java: -------------------------------------------------------------------------------- 1 | // Java program to sort an array 2 | // using bucket sort 3 | import java.util.*; 4 | import java.util.Collections; 5 | 6 | class bucket { 7 | 8 | // Function to sort array[] of size n 9 | // using bucket sort 10 | static void bucketSort(float array[], int n) 11 | { 12 | if (n <= 0) 13 | return; 14 | 15 | // Create n empty buckets 16 | Vector[] buckets = new Vector[n]; 17 | 18 | for (int i = 0; i < n; i++) { 19 | buckets[i] = new Vector(); 20 | } 21 | 22 | //Put the array elements in different buckets 23 | for (int i = 0; i < n; i++) { 24 | float ind = array[i] * n; 25 | buckets[(int)ind].add(array[i]); 26 | } 27 | 28 | //Sorting individual buckets 29 | for (int i = 0; i < n; i++) { 30 | Collections.sort(buckets[i]); 31 | } 32 | 33 | //Concatenate all buckets into array[] 34 | int index = 0; 35 | for (int i = 0; i < n; i++) { 36 | for (int j = 0; j < buckets[i].size(); j++) { 37 | array[index++] = buckets[i].get(j); 38 | } 39 | } 40 | } 41 | 42 | // Driver code 43 | public static void main(String args[]) 44 | { 45 | float array[] = { (float)0.897, (float)0.565, 46 | (float)0.656, (float)0.1234, 47 | (float)0.665, (float)0.3434 }; 48 | 49 | int n = array.length; 50 | bucketSort(array, n); 51 | 52 | System.out.println("Sorted array is "); 53 | for (float el : array) { 54 | System.out.print(el + " "); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /sorting_in_java/counting_sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | 4 | // Java program to sort an array 5 | // using counting sort 6 | import java.util.*; 7 | import java.util.Collections; 8 | //COUNTING SORT 9 | class CountingSort { 10 | 11 | int getMax(int[] a, int n) { 12 | int max = a[0]; 13 | for(int i = 1; i max) 15 | max = a[i]; 16 | } 17 | return max; //maximum element from the array 18 | } 19 | 20 | void countSort(int[] a, int n) // function to perform counting sort 21 | { 22 | int[] output = new int [n+1]; 23 | int max = getMax(a, n); 24 | //int max = 42; 25 | int[] count = new int [max+1]; //create count array with size [max+1] 26 | 27 | for (int i = 0; i <= max; ++i) 28 | { 29 | count[i] = 0; // Initialize count array with all zeros 30 | } 31 | 32 | for (int i = 0; i < n; i++) // Store the count of each element 33 | { 34 | count[a[i]]++; 35 | } 36 | 37 | for(int i = 1; i<=max; i++) 38 | count[i] += count[i-1]; //find cumulative frequency 39 | 40 | /* This loop will find the index of each element of the original array in 41 | count array, and 42 | place the elements in output array*/ 43 | for (int i = n - 1; i >= 0; i--) { 44 | output[count[a[i]] - 1] = a[i]; 45 | count[a[i]]--; // decrease count for same numbers 46 | } 47 | 48 | for(int i = 0; i= 0 && current < array[j]) { 11 | array[j+1] = array[j]; 12 | j--; 13 | } 14 | // at this point we've exited, so j is either -1 15 | // or it's at the first element where current >= a[j] 16 | array[j+1] = current; 17 | } 18 | } 19 | 20 | // Driver code 21 | public static void main(String args[]) 22 | { 23 | float array[] = { 8, 13,1, 9,21, 2}; 24 | 25 | int n = array.length; 26 | insertionSort(array, n); 27 | 28 | System.out.println("Sorted array is "); 29 | for (float el : array) { 30 | System.out.print(el + " "); 31 | } 32 | } -------------------------------------------------------------------------------- /sorting_in_java/quick_sort.java: -------------------------------------------------------------------------------- 1 | // Java program to sort an array 2 | // using quick sort 3 | import java.util.*; 4 | import java.util.Collections; 5 | 6 | //QUICK SORT 7 | static int partition(int[] array, int begin, int end) { 8 | int pivot = end; 9 | 10 | int counter = begin; 11 | for (int i = begin; i < end; i++) { 12 | if (array[i] < array[pivot]) { 13 | int temp = array[counter]; 14 | array[counter] = array[i]; 15 | array[i] = temp; 16 | counter++; 17 | } 18 | } 19 | int temp = array[pivot]; 20 | array[pivot] = array[counter]; 21 | array[counter] = temp; 22 | 23 | return counter; 24 | } 25 | 26 | public static void quickSort(int[] array, int begin, int end) { 27 | if (end <= begin) return; 28 | int pivot = partition(array, begin, end); 29 | quickSort(array, begin, pivot-1); 30 | quickSort(array, pivot+1, end); 31 | } 32 | 33 | // Driver code 34 | public static void main(String args[]) 35 | { 36 | float array[] = { 8, 13,1, 9,21, 2}; 37 | 38 | int n = array.length; 39 | quickSort(array, n); 40 | 41 | System.out.println("Sorted array is "); 42 | for (float el : array) { 43 | System.out.print(el + " "); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /sorting_in_java/selection_sort.java: -------------------------------------------------------------------------------- 1 | // Java program to sort an array 2 | // using selection sort 3 | import java.util.*; 4 | import java.util.Collections; 5 | //SELECTION SORT 6 | public static void selectionSort(int[] array) { 7 | for (int i = 0; i < array.length; i++) { 8 | int min = array[i]; 9 | int minId = i; 10 | for (int j = i+1; j < array.length; j++) { 11 | if (array[j] < min) { 12 | min = array[j]; 13 | minId = j; 14 | } 15 | } 16 | // swapping 17 | int temp = array[i]; 18 | array[i] = min; 19 | array[minId] = temp; 20 | } 21 | } 22 | 23 | // Driver code 24 | public static void main(String args[]) 25 | { 26 | float array[] = { 8, 13,1, 9,21, 2}; 27 | 28 | int n = array.length; 29 | selectionSort(array, n); 30 | 31 | System.out.println("Sorted array is "); 32 | for (float el : array) { 33 | System.out.print(el + " "); 34 | } 35 | } --------------------------------------------------------------------------------