├── .github └── config.yml ├── .gitignore ├── Arrays ├── ClosestDistancePoint.cpp ├── Delete_element.cpp ├── Delete_element.exe ├── Equilibrium_point.cpp ├── Four_Sum.cpp ├── Kadane's algorithm.cpp ├── Kadane's algorithm.exe ├── Leaders_in_array.cpp ├── Leaders_in_array.exe ├── Leftrotate_by1.cpp ├── Leftrotate_by1.exe ├── Maximum_consecutive_1s.cpp ├── Maximum_difference.cpp ├── Maximum_length even odd subarray.exe ├── Maximum_length_even_odd_subarray.cpp ├── Maximum_length_even_odd_subarray.exe ├── Maximum_sum_subarray_sizek.cpp ├── Minimum_group_flips.cpp ├── Moore's_voting_algorithm.cpp ├── Remove_dupicates_from_array.cpp ├── Remove_dupicates_from_array.exe ├── Reverse_an_array.cpp ├── Reverse_an_array.exe ├── Rotate and delete.cpp ├── Stock_buy_and_sell.cpp ├── Stock_buy_and_sell.exe ├── Trapping_rainwater.cpp ├── Trapping_rainwater.exe ├── Two Sum ├── check_sorted.cpp ├── check_sorted.exe ├── find_majority_element.cpp ├── frequencies-of-elements.cpp ├── insert_an_element.cpp ├── left_rotate_by_d.cpp ├── maximum circular subarray sum.cpp ├── prefix_sum.cpp ├── ssort.c ├── ssort.exe ├── stackasarray.cpp ├── sumOfElementsOfArray.cpp └── zerosum_triplets.cpp ├── Bit Magic ├── Bit difference.cpp ├── Bitwise_XOR.cpp ├── Bitwise_XOR.exe ├── Check_sparse.cpp ├── Rightmost_different_bit.cpp ├── check_kthbit_set.cpp ├── check_kthbit_set.exe ├── first_set_bit.cpp ├── first_set_bit.exe ├── longest_consecutive_1s.cpp ├── number_of_set_bits.cpp └── rotate_bits.cpp ├── Hashing ├── Implementation_of_open_addressing.cpp ├── Linear_probing.cpp ├── Maximum_points_on_a_line.cpp ├── Number_of_Pairs_With_Absolute_Difference_K.cpp ├── Professor_and_parties.cpp ├── Search_in_unordered_map.cpp ├── Search_in_unordered_map.exe ├── chaining.cpp ├── count_frequency.cpp ├── count_frequency.exe ├── first_unique_character_string.cpp ├── intersection_of_two_arrays.cpp ├── longest_subarray_with_given_sum.cpp ├── pair_sum_in_unsorted_array.cpp ├── sorting_elements_of_array_by_frequency.cpp ├── subarray_with_zreo_sum.cpp ├── subbarays_with_sumK.cpp ├── unordered_map.cpp ├── unordered_map.exe ├── unordered_set.cpp └── unordered_set.exe ├── Linked List ├── Add_Number.cpp ├── Copy_List_with_Random_Pointer.cpp ├── Detect_Loop_Using_Floyd’s Cycle-Finding Algorithm.cpp ├── MinStack.cpp ├── delete_a_Node_linked_list.cpp └── linked_list_merge_sort.cpp ├── Mathematics ├── Absolute_value.cpp ├── Absolute_value.exe ├── Celsius_to_fahrenheit.cpp ├── Celsius_to_fahrenheit.exe ├── Digits_in_factorial.cpp ├── Digits_in_factorial.exe ├── Factorial_of_a_number.cpp ├── Factorial_of_a_number.exe ├── PerimeterOfRectangle.cpp ├── Print_table_of_any_number.cpp ├── Quadratic_equationroots.cpp └── gcd_naive_and_fast.cpp ├── Matrix ├── ReverseSpiral_MATRIX.cpp ├── addition_of_two_matrix.cpp ├── boundary_elements.cpp ├── matrix function.cpp ├── matrix multiplication.cpp ├── multidimension array using vector.exe ├── multidimension_array_using_vector.cpp ├── multidimension_array_using_vector.exe ├── multidimensional_array_double_pointer.cpp ├── print_boundary_Elements.cpp ├── print_spiral_pattern.cpp ├── sum_of_upper_and_lower_triangles.cpp ├── vector_of_vectors.cpp └── vector_of_vectors.exe ├── Queue └── priorityQueue.cpp ├── README.md ├── Recursion ├── 2048_problem.cpp ├── 2048_problem.exe ├── Count_steps_towerofhanoi.cpp ├── Fast_power.cpp ├── Fibonacci.cpp ├── Fibonacci.exe ├── Min Squares.cpp ├── Palindrome.cpp ├── Rod_cutting.cpp ├── Subset_sum.cpp ├── Towerofhanoi.cpp ├── coin_permutation.cpp.txt ├── infinite_recursion.cpp ├── infinite_recursion.exe ├── keypad.cpp.txt ├── print_1_to_n.cpp ├── print_1_to_n.exe ├── print_n_to_1.cpp ├── print_n_to_1.exe ├── printing table of any number.cpp ├── sum_n_natural_numbers.cpp ├── sum_n_natural_numbers.exe ├── sum_of_digits.cpp └── sum_of_digits.exe ├── Searching ├── BInary_search recursive.cpp ├── Binary_search iterative.cpp ├── Index_of_first_occurence_recursive.cpp ├── Minimum size subarray sum ├── Peak_element.cpp ├── Search_in_infinte_size_array.cpp ├── count_more_than_k_occurences.cpp ├── find_square_root.cpp ├── index_of_last_occurence.cpp ├── index_of_last_occurence.exe ├── search_in_sorted_rotated.cpp └── two_pointer.cpp ├── Sorting ├── Bubble Sort.cpp ├── Heap.cpp ├── Hoares partition.cpp ├── Lometo_partition.cpp ├── Merge three sorted arrays.cpp ├── Merge_two_sorted_arrays.cpp ├── Sorting_vector.cpp ├── bucketsort.cpp ├── chocolate distribution.cpp ├── closer to sort.cpp ├── count_inversions.cpp ├── counting sort for string.cpp ├── counting sort.cpp ├── cycle sort.cpp ├── intersection_of_two_sorted_arrays.cpp ├── kth smallest element.cpp ├── merge overlapping intervals.cpp ├── merge_function.cpp ├── quick_sort.cpp ├── sort by absolute difference.cpp └── union_of_two_sorted_arrays.cpp ├── Stack ├── CheckBalancedParentheses.cpp ├── ReverseStringUsingStack.cpp ├── STACK_USING_2_QUEUES.cpp ├── buildStack.cpp └── buildStack.exe ├── Strings ├── Meta Strings Solution C++.txt ├── Meta Strings.txt ├── anagram.cpp ├── iterating_through_a_string.cpp ├── iterating_through_a_string.exe ├── largest_repeating_subsequence.cpp ├── longest_common_subsequence.cpp ├── rabin_karp.cpp ├── read_a_string.cpp ├── read_a_string.exe └── reverse_a_string.cpp ├── first_unique_character_string.cpp ├── graph ├── dijkstra_algorithm.cpp.txt ├── floyd_warshall.cpp ├── lagrange_interpolation.cpp └── newton-raphson-method.cpp └── min_operations_tp_make_all_element_equal.cpp /.github/config.yml: -------------------------------------------------------------------------------- 1 | # Comment to be posted to on first time issues 2 | newIssueWelcomeComment: | 3 | Thanks for opening this issue! 🤗 4 | Wishing you a great [Hacktoberfest 2020](https://hacktoberfest.digitalocean.com) 🙌 🎉 ⚡️ 5 | **Are you looking for beginner-friendly issues? Check out [this](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/) repo.** 6 | 7 | 📢 Spread the word about [@SakshamAgrwl/GFG-DSA-Problem-Solution](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/) repo across your social media channels to help get others involved! 8 | 9 | [![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.png?v=103)](https://github.com/SakshamAgrwl) 10 | 11 | **Show some ❤️** 12 | - Consider leaving a ⭐ [here](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/). 13 | - Follow @SakshamAgrwl for more updates. 14 | 15 | #### Say Hi on [Linkedin](https://www.linkedin.com/in/saksham-agarwal-1286a09m/)! 👋 16 | 17 | 18 | # Comment to be posted to on PRs from first time contributors in your repository 19 | newPRWelcomeComment: | 20 | Thanks for opening this pull request! 🤗 21 | Wishing you a great [Hacktoberfest 2020](https://hacktoberfest.digitalocean.com) 🙌 🎉 ⚡️ 22 | **Are you looking for more beginner-friendly issues? Check out [this](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/) repo.** 23 | 24 | 📢 Spread the word about [@SakshamAgrwl/GFG-DSA-Problem-Solution](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/) repo across your social media channels to help get others involved! 25 | 26 | [![Open Source Love](https://badges.frapsoft.com/os/v2/open-source.svg?v=103)](https://github.com/SakshamAgrwl) 27 | 28 | 29 | **Show some ❤️** 30 | - Consider leaving a ⭐ [here](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/). 31 | - Follow @SakshamAgrwl for more updates. 32 | 33 | #### Say Hi on [Linkedin](https://www.linkedin.com/in/saksham-agarwal-1286a09m/)! 👋 34 | 35 | PS: Please add @SakshamAgrwl as a reviewer if you haven't added. 36 | 37 | 38 | # Comment to be posted to on pull requests merged by a first time user 39 | firstPRMergeComment: | 40 | Congrats on merging your first pull request! 🙌🎉⚡️ 41 | 42 | **Show some ❤️** 43 | - Consider leaving a ⭐ [here](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/). 44 | - Follow @SakshamAgrwl for more updates. 45 | 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.out 2 | a.out 3 | 4 | Stack/a.out -------------------------------------------------------------------------------- /Arrays/ClosestDistancePoint.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int res=9999999;//A global variable to store the minimum distance. 5 | int final_pt[2]; //A global arr\ay to store the two points whose distance is minimum. 6 | void swapping(int &a, int &b) 7 | { //swap the content of a and b 8 | int temp; 9 | temp = a; 10 | a = b; 11 | b = temp; 12 | } 13 | 14 | void merge(int *array, int l, int m, int r) { 15 | int i, j, k, nl, nr; 16 | //size of left and right sub-arrays 17 | nl = m-l+1; nr = r-m; 18 | int larr[nl], rarr[nr]; 19 | //fill left and right sub-arrays 20 | for(i = 0; i>t; 122 | while(t--) 123 | { 124 | int n; 125 | cin>>n; 126 | int a[n]; 127 | for(int i=0;i>a[i]; 129 | mergeSort(a,0,n-1); //Here we are sorting the array. 130 | int mindis=mindist(a,n,0,n-1); 131 | cout <<"\nMinimum Distance: "<< mindis <<"\nPoint 1 = "< 6 | using namespace std; 7 | 8 | int equilibriumPoint(int arr[], int n){ 9 | int sum = 0; 10 | //first we will calcualte the sum 11 | //of all array elements 12 | for(int i=0;i>t; 37 | 38 | while(t--){ 39 | int n; 40 | cin>>n; 41 | int arr[n]; 42 | 43 | for(int i=0;i>arr[i]; 45 | } 46 | 47 | cout< 2 | using namespace std; 3 | 4 | // function to check if there exist four 5 | // elements whose sum is equal to k 6 | bool findfour(int arr[], int n, int k) 7 | { 8 | // map to store sum and indexes for 9 | // a pair sum 10 | unordered_map > > hash; 11 | 12 | for (int i = 0; i < n; i++) { 13 | for (int j = i + 1; j < n; j++) { 14 | 15 | // calculate the sum of each pair 16 | int sum = arr[i] + arr[j]; 17 | 18 | // if k-sum exist in map 19 | if (hash.find(k - sum) != hash.end()) { 20 | auto num = hash.find(k - sum); 21 | vector > v = num->second; 22 | 23 | // check for index coincidence as if 24 | // there is a common that means all 25 | // the four numbers are not from 26 | // different indexes and one of the 27 | // index is repeated 28 | for (int k = 0; k < num->second.size(); k++) { 29 | 30 | pair it = v[k]; 31 | 32 | // if all indexes are different then 33 | // it means four number exist 34 | // set the flag and break the loop 35 | if (it.first != i && it.first != j && 36 | it.second != i && it.second != j) 37 | return true; 38 | } 39 | } 40 | 41 | // store the sum and index pair in hashmap 42 | hash[sum].push_back(make_pair(i, j)); 43 | } 44 | } 45 | hash.clear(); 46 | return false; 47 | } 48 | 49 | // Driver code 50 | int main() 51 | { 52 | int k = 7; 53 | int arr[] = { 1, 5, 1, 0, 6, 0 }; 54 | int n = 6; 55 | if (findfour(arr, n, k)) 56 | cout 57 | << "YES" << endl; 58 | else 59 | cout << "NO" << endl; 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Arrays/Kadane's algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxSum(int arr[], int n){ 5 | int res = arr[0]; 6 | int maxending = arr[0]; 7 | 8 | for(int i=1;i 2 | using namespace std; 3 | 4 | void leaders(int arr[], int n){ 5 | //last element is always a leader as there is no element after it so it is the greatest 6 | int curr_leader = arr[n-1]; 7 | cout<=0;i--){ 9 | if(curr_leader =< arr[i]){ 10 | curr_leader = arr[i]; 11 | cout< 5 | using namespace std; 6 | 7 | void leftRotateby1(int arr[], int n){ 8 | //create a new variable temp that stores the first element of array 9 | int temp = arr[0]; 10 | for(int i=1;i 2 | using namespace std; 3 | 4 | int maxConsecutiveOnes(bool arr[], int n){ 5 | int res = 0; 6 | for(int i=0;i 5 | using namespace std; 6 | 7 | int maxDiff(int arr[], int n){ 8 | int res= arr[1]-arr[0]; 9 | min_val = arr[0]; 10 | for(int j=1;j 2 | using namespace std; 3 | 4 | int maxEvenOdd(int arr[], int n){ 5 | int curr = 1; 6 | int result = 1; 7 | 8 | for(int i=1;i 2 | using namespace std; 3 | 4 | int maxSum(int arr[], int n, int k){ 5 | 6 | //k must be greater 7 | if(n 2 | using namespace std; 3 | 4 | void printGroups(int arr[], int n){ 5 | for(int i=1;i 15 | using namespace std; 16 | 17 | /* Function to find the candidate for Majority */ 18 | int findCandidate(int a[], int size) 19 | { 20 | int maj_index = 0, count = 1; 21 | for (int i = 1; i < size; i++) 22 | { 23 | if (a[maj_index] == a[i]) 24 | count++; 25 | else 26 | count--; 27 | if (count == 0) 28 | { 29 | maj_index = i; 30 | count = 1; 31 | } 32 | } 33 | return a[maj_index]; 34 | } 35 | 36 | /* Function to check if the candidate 37 | occurs more than n/2 times */ 38 | bool isMajority(int a[], int size, int cand) 39 | { 40 | int count = 0; 41 | for (int i = 0; i < size; i++) 42 | 43 | if (a[i] == cand) 44 | count++; 45 | 46 | if (count > size/2) 47 | return 1; 48 | 49 | else 50 | return 0; 51 | } 52 | 53 | /* Function to print Majority Element */ 54 | 55 | void printMajority(int a[], int size) 56 | { 57 | 58 | /* Find the candidate for Majority*/ 59 | int cand = findCandidate(a, size); 60 | 61 | /* Print the candidate if it is Majority*/ 62 | if (isMajority(a, size, cand)) 63 | 64 | cout << " " << cand << " "; 65 | 66 | else 67 | cout << "No Majority Element"; 68 | } 69 | 70 | 71 | /* Driver function to test above functions */ 72 | int main() 73 | { 74 | int a[] = {1, 3, 3, 1, 2}; 75 | int size = (sizeof(a))/sizeof(a[0]); 76 | 77 | // Function calling 78 | printMajority(a, size); 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /Arrays/Remove_dupicates_from_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int remDups(int a[], int n){ 5 | int res = 1; 6 | for(int i=1;i>n; 19 | int a[n]; 20 | 21 | for(int i=0;i>a[i]; 23 | } 24 | 25 | cout< 2 | using namespace std; 3 | 4 | void reverse(int a[], int n){ 5 | int low = 0, high = n-1; 6 | 7 | while(low>n; 19 | int a[n]; 20 | for(int i=0;i>a[i]; 22 | } 23 | 24 | reverse(a,n); 25 | 26 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #define pb push_back 6 | #define ll long long 7 | #define fr(a,b) for(ll i=a;i vi; 11 | typedef pair ii; 12 | typedef vector vii; 13 | typedef set si; 14 | typedef map msi; 15 | void solve() { 16 | int n; 17 | cin >> n; 18 | int a[n]; 19 | fr(0, n) { 20 | cin >> a[i]; 21 | } 22 | if (n == 1) { 23 | cout << a[0] << "\n"; 24 | return; 25 | } 26 | if (n % 2 == 0) { 27 | cout << a[((n - 2) / 4) + 1]; 28 | } 29 | else { 30 | cout << a[((n - 3) / 4) + 2]; 31 | } 32 | cout << "\n"; 33 | } 34 | int main() 35 | { 36 | 37 | ios_base::sync_with_stdio(0); 38 | cin.tie(0); 39 | cout.tie(0); 40 | int t; 41 | cin >> t; 42 | while (t--) { 43 | solve(); 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Arrays/Stock_buy_and_sell.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxProfit(int price[], int n){ 5 | int profit = 0; 6 | for(int i=1;i price[i-1]){ 8 | profit+= (price[i] - price[i-1]); 9 | } 10 | } 11 | 12 | return profit; 13 | } 14 | 15 | int main(){ 16 | int price[] = {1,5,3,8,12}; 17 | int n = sizeof(price)/sizeof(price[0]); 18 | cout< 5 | using namespace std; 6 | 7 | int getWater(int height[],int n){ 8 | int res = 0; 9 | int lmax[n], rmax[n]; 10 | 11 | //finding the maximum height from left so that water can be preserved 12 | lmax[0] = height[0]; 13 | for(int i=1;i=0;i--){ 21 | rmax[i] = max(rmax[i+1],height[i+1]); 22 | } 23 | 24 | //now we will start traversing the middle elements of array 25 | for(int i=1;i twoSum(vector& nums, int &target) { 4 | unordered_map map; 5 | for (int i{0}; i 2 | using namespace std; 3 | 4 | bool isSorted(int a[], int n){ 5 | for(int i=1;i>n; 18 | 19 | int a[n]; 20 | for(int i=0;i>a[i]; 22 | } 23 | 24 | if(isSorted(a,n)){ 25 | cout<<"True"; 26 | } 27 | else{ 28 | cout<<"False"; 29 | } 30 | 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Arrays/check_sorted.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Arrays/check_sorted.exe -------------------------------------------------------------------------------- /Arrays/find_majority_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findMajority(int arr[], int n){ 5 | int res= 0, count = 1; 6 | 7 | for(int i=0;i n/2) 32 | return 1; 33 | 34 | else 35 | return 0; 36 | } 37 | 38 | void printMajority(int a[], int size) 39 | { 40 | /* Find the candidate for Majority*/ 41 | int cand = findCandidate(a, size); 42 | 43 | /* Print the candidate if it is Majority*/ 44 | if (isMajority(a, size, cand)) 45 | cout << " " << cand << " "; 46 | 47 | else 48 | cout << "No Majority Element"; 49 | } 50 | 51 | 52 | /* Driver function to test above functions */ 53 | int main() 54 | { 55 | int a[] = {1, 3, 3, 1, 2}; 56 | int size = (sizeof(a))/sizeof(a[0]); 57 | 58 | // Function calling 59 | printMajority(a, size); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Arrays/frequencies-of-elements.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void countFreq(int arr[], int n) 6 | { 7 | unordered_map mp; 8 | 9 | // Traverse through array elements and 10 | // count frequencies 11 | for (int i = 0; i < n; i++) 12 | mp[arr[i]]++; 13 | 14 | // To print elements according to first 15 | // occurrence, traverse array one more time 16 | // print frequencies of elements and mark 17 | // frequencies as -1 so that same element 18 | // is not printed multiple times. 19 | for (int i = 0; i < n; i++) { 20 | if (mp[arr[i]] != -1) 21 | { 22 | cout << arr[i] << " " << mp[arr[i]] << endl; 23 | mp[arr[i]] = -1; 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | int n; 31 | cout<<"enter the size of array\n"; 32 | cin>>n; 33 | int arr[n]; 34 | for(int i=0;i>arr[i]; 37 | } 38 | countFreq(arr, n); 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Arrays/insert_an_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int insert(int arr[], int x, int n, int cap, int pos){ 5 | if(n==cap){ 6 | return n; 7 | } 8 | 9 | int index = pos-1; 10 | 11 | for(int i= n-1; i>=index; i--){ 12 | arr[i+1] = arr[i]; 13 | } 14 | arr[index] = x; 15 | 16 | return n+1; 17 | } -------------------------------------------------------------------------------- /Arrays/left_rotate_by_d.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void leftRotate(int a[], int n){ 5 | reverse(a, 0, d-1); 6 | reverse(a, d, n-1); 7 | reverse(a,0,n-1); 8 | } 9 | 10 | void reverse(int a[], int low,int high){ 11 | while(low 2 | using namespace std; 3 | 4 | int normalMaxSum(int arr[], int n){ 5 | int res = arr[0]; maxEnding = arr[0]; 6 | for(int i = 1 ; i 4 | using namespace std; 5 | 6 | // Fills prefix sum array 7 | void fillPrefixSum(int arr[], int n, int prefixSum[]) 8 | { 9 | prefixSum[0] = arr[0]; 10 | 11 | // Adding present element 12 | // with previous element 13 | for (int i = 1; i < n; i++) 14 | prefixSum[i] = prefixSum[i-1] + arr[i]; 15 | } 16 | 17 | // Driver Code 18 | int main() 19 | { 20 | int arr[] = { 10, 4, 16, 20 }; 21 | int n = sizeof(arr) / sizeof(arr[0]); 22 | int prefixSum[n]; 23 | 24 | fillPrefixSum(arr, n, prefixSum); 25 | for (int i = 0; i < n; i++) 26 | cout << prefixSum[i] << " "; 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/ssort.c: -------------------------------------------------------------------------------- 1 | 2 | 3 | /****************************************************************************** 4 | 5 | selection sort 6 | 7 | *******************************************************************************/ 8 | #include 9 | int min(int [], int); 10 | void main() 11 | { 12 | int a[]={1,23,24,65,90,13,55},i,loc,temp; 13 | for(i=0;i<6;i++) 14 | { 15 | loc=min(a,i); 16 | temp=a[i]; 17 | a[i]=a[loc]; 18 | a[loc]=temp; 19 | } 20 | for(i=0;i<7;i++) 21 | { 22 | printf("%d\n",a[i]); 23 | } 24 | } 25 | int min(int a[],int i) 26 | { 27 | int j,loc=i; 28 | int key=a[i]; 29 | for(j=i+1;j<7;j++) 30 | { 31 | if(key>a[j]) 32 | { 33 | loc=j ; 34 | key=a[j]; 35 | } 36 | } 37 | return loc; 38 | } 39 | -------------------------------------------------------------------------------- /Arrays/ssort.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Arrays/ssort.exe -------------------------------------------------------------------------------- /Arrays/stackasarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define MAX 100 6 | 7 | class StackAsArray { 8 | private: 9 | int top; 10 | 11 | public: 12 | int myStack[MAX]; 13 | 14 | StackAsArray() { top = -1; } 15 | bool isEmpty(); 16 | bool push(int nNum); 17 | int pop(); 18 | int peek(); 19 | }; 20 | 21 | bool StackAsArray::isEmpty() { 22 | return (top < 0); 23 | } 24 | 25 | bool StackAsArray::push(int nNum) { 26 | if (top == MAX-1) { 27 | cout << "Stack Overflow!" << endl; 28 | return false; 29 | } else { 30 | myStack[++top] = nNum; 31 | cout << nNum << " pushed to stack." << endl; 32 | return true; 33 | } 34 | } 35 | 36 | int StackAsArray::pop() { 37 | if (top < 0) { 38 | cout << "Stack Underflow!" << endl; 39 | return -1; 40 | } else { 41 | return myStack[top--]; 42 | } 43 | } 44 | 45 | int StackAsArray::peek() { 46 | if (top < 0) { 47 | cout << "Stack empty!!" << endl; 48 | return -1; 49 | } else { 50 | int x = myStack[top]; 51 | return x; 52 | } 53 | } 54 | 55 | int main() { 56 | StackAsArray myStack = StackAsArray(); 57 | myStack.push(10); 58 | myStack.push(12); 59 | myStack.push(7); 60 | cout << myStack.pop() << " popped from stack" << endl; 61 | cout << myStack.pop() << " popped from stack" << endl; 62 | cout << myStack.peek() << " is the top element." << endl; 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Arrays/sumOfElementsOfArray.cpp: -------------------------------------------------------------------------------- 1 | // Program to output sum of elements(int) of array 2 | #include 3 | using namespace std; 4 | 5 | //function to return the sum of elements of array 6 | int sumOfElements( int arr[], int n ) { 7 | int sum=0; 8 | for(int i=0; i>n; 18 | int a[n]; //integer array of size n 19 | for(int i=0; i>a[i]; 21 | int ans= sumOfElements( a, n); 22 | cout<<"Sum of elements of array is"< 5 | using namespace std; 6 | 7 | // Prints all triplets in arr[] with 0 sum 8 | void findZeroSumTriplets(int arr[], int n) 9 | { 10 | bool found = true; 11 | for (int i=0; i 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | // Function to find number of bits to be flip 14 | // to convert A to B 15 | int countSetBits(int n){ 16 | int count = 0; 17 | while (n > 0) 18 | { 19 | count++; 20 | n &= (n-1); 21 | } 22 | return count; 23 | } 24 | 25 | int countBitsFlip(int a, int b){ 26 | return countSetBits(a^b); 27 | 28 | // Your logic here 29 | 30 | } 31 | 32 | // { Driver Code Starts. 33 | 34 | // Driver Code 35 | int main() 36 | { 37 | int t; 38 | cin>>t;// input the testcases 39 | while(t--) //while testcases exist 40 | { 41 | int a,b; 42 | cin>>a>>b; //input a and b 43 | 44 | cout< 2 | using namespace std; 3 | 4 | int fun(int a[], int n){ 5 | int x = a[0]; //assigning variable x the first value of array a which is 9 6 | for(int i=0;i>n; 16 | int a[n]; 17 | 18 | for(int i=0;i>a[i]; 20 | } 21 | 22 | cout< 2 | using namespace std; 3 | 4 | bool checkSparse(int n){ 5 | if(n & (n >> 1)){ 6 | return false; 7 | } 8 | 9 | return true; 10 | } 11 | 12 | int main(){ 13 | int T; 14 | cin>>T; 15 | while(T--){ 16 | int n; 17 | cin>>n; 18 | if(checkSparse(n)){ 19 | cout<<"It is sparse"; 20 | } 21 | else{ 22 | cout<<"Not Sparse"; 23 | } 24 | } 25 | 26 | return 0; 27 | 28 | } -------------------------------------------------------------------------------- /Bit Magic/Rightmost_different_bit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int posOfRightMostDiffBit(int m, int n){ 5 | return ffs(m^n); //ffs function is used to return the most significant bit or least significant bit 6 | } //we perform XOR operation on m and n we will get 0 and 1 the position where we will get 1 we return it using ffs fucntion 7 | 8 | 9 | int main(){ 10 | 11 | int t; 12 | cin>>t; //input number of testcases 13 | while(t--) 14 | { 15 | int m,n; 16 | cin>>m>>n; //input m and n 17 | cout << posOfRightMostDiffBit(m, n)< 2 | using namespace std; 3 | 4 | bool checkKthBit(int n, int k){ 5 | if(n & (1 << k)){ 6 | return true; 7 | } 8 | else{ 9 | return false; 10 | } 11 | } 12 | 13 | int main(){ 14 | int t; 15 | cin>>t; 16 | while(t--){ 17 | long long n; 18 | cin>>n; 19 | int k; 20 | cin>>key; 21 | 22 | if(checkKthBit(n,k)){ 23 | cout<<"It is set "; 24 | } 25 | else{ 26 | cout<<"Not set"; 27 | } 28 | } 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Bit Magic/check_kthbit_set.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Bit Magic/check_kthbit_set.exe -------------------------------------------------------------------------------- /Bit Magic/first_set_bit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | unsigned int getFirstSetBit(int n){ 5 | return log2(n & -n) + 1; //this is the formula to find the position of first set bit 6 | } 7 | 8 | int main(){ 9 | int t; 10 | cin>>t; 11 | while(t--){ 12 | int n; 13 | cin>>n; 14 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | 10 | 11 | //User function Template for C++ 12 | 13 | /* Function to calculate the largest consecutive ones 14 | * x: given input to calculate the largest consecutive ones 15 | */ 16 | int maxConsecutiveOnes(int x) 17 | { 18 | int count = 0; 19 | 20 | while(x!=0){ 21 | x = (x & (x<<1)); 22 | count++; 23 | } 24 | 25 | return count; 26 | // Your code here 27 | 28 | 29 | } 30 | 31 | 32 | 33 | // { Driver Code Starts. 34 | 35 | // Driver Code 36 | int main() { 37 | int t; 38 | cin>>t; 39 | while(t--) 40 | { 41 | int n; 42 | cin>>n; 43 | cout< 2 | using namespace std; 3 | 4 | //Count Set Bits 5 | unsigned int countSetBits(unsigned int n) { 6 | // c is the number of count of set bits 7 | unsigned int c = 0; 8 | while (n) { 9 | n = n & (n-1); 10 | c++; 11 | } 12 | return c; 13 | } 14 | 15 | int main() { 16 | //n is the desired input 17 | int n = 17; 18 | 19 | //Print the number of set bits 20 | cout <<"Number of set bits are " << countSetBits(n); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Bit Magic/rotate_bits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int INT_BITS = 32; 5 | 6 | //Function to left rotate n by d bits 7 | int leftRotate(int n, unsigned int d) { 8 | return (n << d)|(n >> (INT_BITS - d)); 9 | } 10 | 11 | //Function to right rotate n by d bits 12 | int rightRotate(int n, unsigned int d) { 13 | return (n >> d)|(n << (INT_BITS - d)); 14 | } 15 | 16 | int main() { 17 | // n is the desired nuber to rotate 18 | int n = 4; 19 | 20 | // d is the number of digits by which we want to rotate 21 | int d = 2; 22 | 23 | // left rotation of n by d digits 24 | cout << "Left Rotation of " << n << " by " << d << " is " << leftRotate(n, d)<<"\n"; 25 | 26 | //right rotation of n by d digits 27 | cout << "Right Rotation of " << n <<" by " << d << " is "<< rightRotate(n, d); 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Hashing/Implementation_of_open_addressing.cpp: -------------------------------------------------------------------------------- 1 | //create a structure 2 | struct myHash{ 3 | int *arr; 4 | int cap,size; 5 | 6 | myHash(int c){ //pass capacity of hash as c 7 | cap = c; 8 | size = 0; 9 | 10 | for(int i=0;i 3 | using namespace std; 4 | 5 | 6 | vector linearProbing(int hashSize,int arr[],int sizeOfArray); 7 | int main() { 8 | int t; 9 | cin>>t; 10 | while(t--) 11 | { 12 | int hashSize; 13 | cin>>hashSize; 14 | 15 | int sizeOfArray; 16 | cin>>sizeOfArray; 17 | int arr[sizeOfArray]; 18 | 19 | for(int i=0;i>arr[i]; 21 | 22 | vector hash; 23 | 24 | hash = linearProbing( hashSize, arr, sizeOfArray); 25 | 26 | for(int i=0;i linearProbing(int hashSize, int arr[], int N){ 44 | 45 | int hash_key; 46 | vector v(hashSize, -1); 47 | 48 | for(int i=0; i>& points) { 4 | 5 | int n = points.size(); 6 | int result = 0; 7 | if(points.size() <= 2){ 8 | return points.size(); 9 | 10 | } 11 | 12 | for(int i=0;i mp; 15 | int duplicates = 0; 16 | double slope = 0.0; 17 | 18 | for(int j=0;j& nums, int k) { 4 | 5 | unordered_map mp; 6 | int count= 0; 7 | 8 | for(auto x: nums){ 9 | 10 | count+= mp[x-k] + mp[x+k]; 11 | 12 | mp[x]++; 13 | } 14 | 15 | 16 | return count; 17 | } 18 | }; -------------------------------------------------------------------------------- /Hashing/Professor_and_parties.cpp: -------------------------------------------------------------------------------- 1 | //probelm link: https://practice.geeksforgeeks.org/problems/professor-and-parties2000/1 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | class Solution{ 11 | public: 12 | 13 | string PartyType(long long int a[], int n) 14 | { 15 | unordered_map mp; 16 | 17 | for(long long i=0;i 1){ 24 | return "BOYS"; 25 | } 26 | 27 | } 28 | return "GIRLS"; 29 | } 30 | }; 31 | 32 | //{ Driver Code Starts. 33 | int main() { 34 | int t; 35 | cin >> t; 36 | while(t--){ 37 | 38 | int n; 39 | cin >> n; 40 | long long int a[n+5]; 41 | for(int i =0;i> a[i]; 43 | Solution ob; 44 | cout<< ob.PartyType(a, n) < 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | unordered_map m; 7 | m["gfg"] = 20; 8 | m["ide"] = 15; 9 | m["courses"] = 10; 10 | //search for an element in map 11 | // if(m.find("ide") != m.end()){ //if the pointer reaches to last element then return false else found then return true 12 | // cout<<"Found"<first)<<" "<<(it->second)<second)< 2 | using namespace std; 3 | 4 | //create a structure 5 | struct myHash{ 6 | int BUCKET; 7 | //define a pointer to the list 8 | list *table; 9 | //define a constructor 10 | myHash(int b){ 11 | BUCKET = b; 12 | table = new list[BUCKET]; 13 | } 14 | void insert(int key){ 15 | int i = key % BUCKET; 16 | table[i].push_back(key); 17 | } 18 | 19 | bool search(int key){ 20 | int i = key % BUCKET; 21 | for(auto x:table[i]){ 22 | if(x==key){ 23 | return true; 24 | } 25 | } 26 | return false; 27 | } 28 | 29 | void remove(int key){ 30 | int i = key % BUCKET; 31 | table[i].remove[key]; 32 | } 33 | }; 34 | 35 | int main(){ 36 | myHash mh(7); 37 | mh.insert(10); 38 | mh.insert(20); 39 | mh.insert(15); 40 | mh.insert(7); 41 | cout< 2 | using namespace std; 3 | 4 | void countFreq(int arr[], int n){ 5 | unordered_map mp; 6 | 7 | for(int i=0;i>n; 20 | int arr[n]; 21 | for(int i=0;i>arr[i]; 23 | } 24 | 25 | countFreq(arr,n); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Hashing/count_frequency.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Hashing/count_frequency.exe -------------------------------------------------------------------------------- /Hashing/first_unique_character_string.cpp: -------------------------------------------------------------------------------- 1 | //Probelm link: https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | 3 | class Solution { 4 | public: 5 | int firstUniqChar(string s) { 6 | 7 | unordered_map mp; 8 | 9 | for(auto it: s){ 10 | mp[it]++; 11 | } 12 | 13 | for(int i=0;i 2 | using namespace std; 3 | 4 | int intersection(int a[], int b[], int m, int n){ 5 | //we will use unordered set 6 | unordered_set s; 7 | //traverse in the first array 8 | for(int i=0;i 2 | using namespace std; 3 | 4 | int maxlen(int arr[], int n, int sum){ 5 | /* we will use map in this question 6 | as it will store the value of prefix sum array 7 | as key and their value as index of prefix sum*/ 8 | unordered_map map; 9 | int prefix_sum = 0, res = 0; 10 | 11 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | int pairWithSumX(int arr[],int n, int X) 6 | { 7 | unordered_set us; 8 | for(int i = 0; i < n; i++) 9 | { 10 | if(us.find(X - arr[i]) != us.end()) 11 | return 1; 12 | 13 | us.insert(arr[i]); 14 | } 15 | return 0; 16 | 17 | } 18 | 19 | int main() 20 | { 21 | int arr[] = {3, 8, 4, 7, 6, 1}; 22 | int n = sizeof(arr)/sizeof(arr[0]); 23 | int X = 14; 24 | 25 | cout << pairWithSumX(arr, n, X); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Hashing/sorting_elements_of_array_by_frequency.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | vector sortByFreq(int arr[],int n); 7 | 8 | int main() { 9 | 10 | 11 | int t; 12 | cin >> t; 13 | 14 | 15 | while(t--){ 16 | 17 | 18 | int n; 19 | cin >> n; 20 | 21 | int a[n+1]; 22 | 23 | for(int i = 0;i> a[i]; 25 | } 26 | vector v; 27 | v = sortByFreq(a,n); 28 | for(int i:v) 29 | cout< &a, pair &b){ 43 | if(a.second > b.second){ 44 | return true; 45 | } 46 | else if(a.second == b.second){ 47 | return a.first < b.first; 48 | } 49 | else{ 50 | return false; 51 | } 52 | } 53 | vector sortByFreq(int arr[],int n) 54 | { 55 | unordered_map mp; 56 | for(int i=0;i(arr[i],1)); 59 | } 60 | else{ 61 | mp[arr[i]]++; 62 | } 63 | 64 | } 65 | 66 | vector> v; 67 | for(auto& it:mp){ 68 | v.push_back(it); 69 | } 70 | 71 | sort(v.begin(),v.end(),compare); 72 | vector ans; 73 | 74 | for(int i=0;i 2 | using namespace std; 3 | 4 | bool isZero(int arr[], int n){ 5 | unordered_set s; 6 | int prefix_sum = 0; 7 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | unordered_map m; 7 | //assigning a string key and an integer value to that key 8 | m["GFG"] = 20; 9 | m["ide"] = 30; 10 | //insert a key and value using insert function 11 | m.insert({"courses",15}); 12 | for(auto x:m){ 13 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | //define an unordered set 7 | unordered_set s; 8 | //now we will insert values in the unordered set or hash 9 | s.insert(15); 10 | s.insert(5); 11 | s.insert(10); 12 | s.insert(20); 13 | 14 | //now we will iterate in the unordered set 15 | for(auto it=s.begin();it!=s.end();it++){ 16 | cout<<(*it)<<" "; 17 | } 18 | cout<next!=NULL){ 10 | temp=temp->next; 11 | } 12 | temp->next=new ListNode(n); 13 | return; 14 | } 15 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 16 | ListNode *res=NULL; 17 | int carry=0; 18 | while(l1!=NULL and l2!=NULL){ 19 | int temp=l1->val+l2->val+carry; 20 | insert_node(res,temp%10); 21 | carry=temp/10; 22 | l1=l1->next; 23 | l2=l2->next; 24 | } 25 | while(l1!=NULL){ 26 | int temp=l1->val+carry; 27 | insert_node(res,temp%10); 28 | carry=temp/10; 29 | l1=l1->next; 30 | } 31 | while(l2!=NULL){ 32 | int temp=l2->val+carry; 33 | insert_node(res,temp%10); 34 | carry=temp/10; 35 | l2=l2->next; 36 | } 37 | if(carry!=0){ 38 | insert_node(res,carry); 39 | } 40 | return res; 41 | } 42 | }; -------------------------------------------------------------------------------- /Linked List/Copy_List_with_Random_Pointer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* copyRandomList(Node* head) { 4 | if(!head){ 5 | return head; 6 | } 7 | Node* tempHead=head; 8 | while(tempHead){ 9 | Node* temp=tempHead->next; 10 | Node* newNode=new Node(tempHead->val); 11 | tempHead->next=newNode; 12 | newNode->next=temp; 13 | tempHead=temp; 14 | } 15 | tempHead=head; 16 | while(tempHead){ 17 | if(tempHead->next){ 18 | tempHead->next->random= (tempHead->random) ? tempHead->random->next : tempHead->random; 19 | } 20 | tempHead=(tempHead->next) ? tempHead->next->next : tempHead->next; 21 | } 22 | Node* copy=head->next; 23 | Node* curr=head; 24 | Node* ans=copy; 25 | while(curr && copy){ 26 | curr->next= (curr->next) ? curr->next->next : curr->next; 27 | copy->next=(copy->next) ? copy->next->next : copy->next; 28 | 29 | curr=curr->next; 30 | copy=copy->next; 31 | 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Linked List/Detect_Loop_Using_Floyd’s Cycle-Finding Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | //Pushing a Node to Linked List 11 | void push(Node** head_ref, int data) { 12 | Node* node = new Node(); 13 | node->data = data; 14 | node->next = (*head_ref); 15 | (*head_ref) = node; 16 | } 17 | 18 | //Detection of Loop using Floyd’s Cycle-Finding Algorithm 19 | bool detectLoop(Node* head){ 20 | Node* s=head;Node* f=head; 21 | while(s!=NULL && f!=NULL && f->next!=NULL) { 22 | s=s->next; 23 | f=f->next->next; 24 | if(f==s) return true; 25 | } 26 | return false; 27 | } 28 | 29 | int main() { 30 | 31 | Node* head = NULL; 32 | // push the desired nodes 33 | push(&head, 2); 34 | push(&head, 20); 35 | push(&head, 40); 36 | push(&head, 50); 37 | push(&head, 75); 38 | 39 | // Sample Loop 40 | head->next->next->next = head; 41 | if (detectLoop(head)) 42 | cout << "Loop is Found"; 43 | else 44 | cout << "No Loop is Found"; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Linked List/MinStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class MinStack { 6 | public: 7 | MinStack() { 8 | st = stack>(); 9 | } 10 | 11 | void push(int val) { 12 | if (st.empty()) { 13 | st.push({ val,val }); 14 | } 15 | else { 16 | st.push({ val,min(val,st.top().second) }); 17 | } 18 | } 19 | 20 | void pop() { 21 | if (st.size()) { st.pop(); } 22 | } 23 | 24 | int top() { 25 | if (st.size()) { 26 | return st.top().first; 27 | } 28 | return -1; 29 | } 30 | 31 | int getMin() { 32 | if (st.size()) { 33 | return st.top().second; 34 | } 35 | return -1; 36 | } 37 | private: 38 | stack> st; 39 | 40 | }; -------------------------------------------------------------------------------- /Linked List/delete_a_Node_linked_list.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to delete a given node in linked list under given constraints 2 | #include 3 | using namespace std; 4 | 5 | /* structure of a linked list node */ 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *next; 11 | }; 12 | 13 | void deleteNode(Node *head, Node *n) 14 | { 15 | // When node to be deleted is head node 16 | if(head == n) 17 | { 18 | if(head->next == NULL) 19 | { 20 | cout << "There is only one node." << 21 | " The list can't be made empty "; 22 | return; 23 | } 24 | 25 | /* Copy the data of next node to head */ 26 | head->data = head->next->data; 27 | 28 | // store address of next node 29 | n = head->next; 30 | 31 | // Remove the link of next node 32 | head->next = head->next->next; 33 | 34 | // free memory 35 | free(n); 36 | 37 | return; 38 | } 39 | 40 | 41 | // When not first node, follow 42 | // the normal deletion process 43 | 44 | // find the previous node 45 | Node *prev = head; 46 | while(prev->next != NULL && prev->next != n) 47 | prev = prev->next; 48 | 49 | // Check if node really exists in Linked List 50 | if(prev->next == NULL) 51 | { 52 | cout << "\nGiven node is not present in Linked List"; 53 | return; 54 | } 55 | 56 | // Remove node from Linked List 57 | prev->next = prev->next->next; 58 | 59 | // Free memory 60 | free(n); 61 | 62 | return; 63 | } 64 | 65 | /* Utility function to insert a node at the beginning */ 66 | void push(Node **head_ref, int new_data) 67 | { 68 | Node *new_node = new Node(); 69 | new_node->data = new_data; 70 | new_node->next = *head_ref; 71 | *head_ref = new_node; 72 | } 73 | 74 | /* Utility function to print a linked list */ 75 | void printList(Node *head) 76 | { 77 | while(head!=NULL) 78 | { 79 | cout<data<<" "; 80 | head=head->next; 81 | } 82 | cout<15->10->11->5->6->2->3 */ 92 | push(&head,3); 93 | push(&head,2); 94 | push(&head,6); 95 | push(&head,5); 96 | push(&head,11); 97 | push(&head,10); 98 | push(&head,15); 99 | push(&head,12); 100 | 101 | cout<<"Given Linked List: "; 102 | printList(head); 103 | 104 | /* Let us delete the node with value 10 */ 105 | cout<<"\nDeleting node "<< head->next->next->data<<" "; 106 | deleteNode(head, head->next->next); 107 | 108 | cout<<"\nModified Linked List: "; 109 | printList(head); 110 | 111 | /* Let us delete the first node */ 112 | cout<<"\nDeleting first node "; 113 | deleteNode(head, head); 114 | 115 | cout<<"\nModified Linked List: "; 116 | printList(head); 117 | return 0; 118 | } 119 | 120 | // This code is contributed by vickyjsr 121 | -------------------------------------------------------------------------------- /Linked List/linked_list_merge_sort.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for linked list merged sort 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | class Node { 7 | public: 8 | int data; 9 | Node* next; 10 | }; 11 | 12 | /* function prototypes */ 13 | Node* SortedMerge(Node* a, Node* b); 14 | void FrontBackSplit(Node* source, 15 | Node** frontRef, Node** backRef); 16 | 17 | /* sorts the linked list by changing next pointers (not data) */ 18 | void MergeSort(Node** headRef) 19 | { 20 | Node* head = *headRef; 21 | Node* a; 22 | Node* b; 23 | 24 | /* Base case -- length 0 or 1 */ 25 | if ((head == NULL) || (head->next == NULL)) { 26 | return; 27 | } 28 | 29 | /* Split head into 'a' and 'b' sublists */ 30 | FrontBackSplit(head, &a, &b); 31 | 32 | /* Recursively sort the sublists */ 33 | MergeSort(&a); 34 | MergeSort(&b); 35 | 36 | /* answer = merge the two sorted lists together */ 37 | *headRef = SortedMerge(a, b); 38 | } 39 | 40 | /* See https:// www.geeksforgeeks.org/?p=3622 for details of this 41 | function */ 42 | Node* SortedMerge(Node* a, Node* b) 43 | { 44 | Node* result = NULL; 45 | 46 | /* Base cases */ 47 | if (a == NULL) 48 | return (b); 49 | else if (b == NULL) 50 | return (a); 51 | 52 | /* Pick either a or b, and recur */ 53 | if (a->data <= b->data) { 54 | result = a; 55 | result->next = SortedMerge(a->next, b); 56 | } 57 | else { 58 | result = b; 59 | result->next = SortedMerge(a, b->next); 60 | } 61 | return (result); 62 | } 63 | 64 | /* UTILITY FUNCTIONS */ 65 | /* Split the nodes of the given list into front and back halves, 66 | and return the two lists using the reference parameters. 67 | If the length is odd, the extra node should go in the front list. 68 | Uses the fast/slow pointer strategy. */ 69 | void FrontBackSplit(Node* source, 70 | Node** frontRef, Node** backRef) 71 | { 72 | Node* fast; 73 | Node* slow; 74 | slow = source; 75 | fast = source->next; 76 | 77 | /* Advance 'fast' two nodes, and advance 'slow' one node */ 78 | while (fast != NULL) { 79 | fast = fast->next; 80 | if (fast != NULL) { 81 | slow = slow->next; 82 | fast = fast->next; 83 | } 84 | } 85 | 86 | /* 'slow' is before the midpoint in the list, so split it in two 87 | at that point. */ 88 | *frontRef = source; 89 | *backRef = slow->next; 90 | slow->next = NULL; 91 | } 92 | 93 | /* Function to print nodes in a given linked list */ 94 | void printList(Node* node) 95 | { 96 | while (node != NULL) { 97 | cout << node->data << " "; 98 | node = node->next; 99 | } 100 | } 101 | 102 | /* Function to insert a node at the beginging of the linked list */ 103 | void push(Node** head_ref, int new_data) 104 | { 105 | /* allocate node */ 106 | Node* new_node = new Node(); 107 | 108 | /* put in the data */ 109 | new_node->data = new_data; 110 | 111 | /* link the old list off the new node */ 112 | new_node->next = (*head_ref); 113 | 114 | /* move the head to point to the new node */ 115 | (*head_ref) = new_node; 116 | } 117 | 118 | /* Driver program to test above functions*/ 119 | int main() 120 | { 121 | /* Start with the empty list */ 122 | Node* res = NULL; 123 | Node* a = NULL; 124 | 125 | /* Let us create a unsorted linked lists to test the functions 126 | Created lists shall be a: 2->3->20->5->10->15 */ 127 | push(&a, 15); 128 | push(&a, 10); 129 | push(&a, 5); 130 | push(&a, 20); 131 | push(&a, 3); 132 | push(&a, 2); 133 | 134 | /* Sort the above created Linked List */ 135 | MergeSort(&a); 136 | 137 | cout << "Sorted Linked List is: \n"; 138 | printList(a); 139 | 140 | return 0; 141 | } 142 | 143 | // This is code is contributed by vickyjsr 144 | -------------------------------------------------------------------------------- /Mathematics/Absolute_value.cpp: -------------------------------------------------------------------------------- 1 | //In this program we need to return the absolute value of n 2 | //suppose n=-45 then absolute value of n will be -45 3 | 4 | #include 5 | using namespace std; 6 | 7 | int absolute(int n){ 8 | int i = abs(n); 9 | return i; 10 | } 11 | 12 | int main(){ 13 | int T; 14 | cin>>T; 15 | 16 | while(T--){ 17 | int n; 18 | cin>>n; 19 | cout< 5 | using namespace std; 6 | 7 | double cToF(int C){ 8 | double F = (9*C)/5 + 32; //The point here is that we first seprately multiply celsius with 9 9 | return F; //and then divide it by 5 so that it returns a double value 10 | } 11 | 12 | int main(){ 13 | int T; 14 | cin>>T; 15 | while(T--){ 16 | int C; 17 | cin>>C; 18 | cout< 6 | using namespace std; 7 | 8 | int digitsInFactorial(int N){ 9 | if(N==0){ 10 | return 0; 11 | } 12 | 13 | if(N<=1){ 14 | return 1; 15 | } 16 | 17 | double digits = 0; 18 | for(int i=2;i<=N;i++){ 19 | digits+=log10(i); 20 | } 21 | 22 | return floor(digits) + 1; 23 | } 24 | 25 | int main(){ 26 | int t; 27 | cin>>t; 28 | while(t--){ 29 | int N; 30 | cin>>N; 31 | cout< 2 | using namespace std; 3 | 4 | long long factorial(int N){ 5 | if(N==0){ 6 | return 1; 7 | } 8 | 9 | return N * factorial(N-1); 10 | } 11 | 12 | 13 | int main(){ 14 | int T; 15 | cin>>T; 16 | while(T--){ 17 | int N; 18 | cin>>N; 19 | cout< 5 | using namespace std; 6 | 7 | int findPerimeter(int l, int b) 8 | { 9 | return (2 * (l + b)); 10 | }; 11 | 12 | int main() 13 | { 14 | int l, b, perimeter; 15 | cout << "Enter the value of length and breadth" << endl; 16 | cin >> l >> b; 17 | perimeter = findPerimeter(l, b); 18 | cout << "The perimeter of rectangle is : " << perimeter << endl; 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /Mathematics/Print_table_of_any_number.cpp: -------------------------------------------------------------------------------- 1 | // To print table of any number 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int i,number, ans ; 9 | cout<<"Enter the number"<>number; 11 | // for(i=1;i<=10;i++) 12 | // { 13 | // ans=number*i; 14 | // cout<<""< 2 | using namespace std; 3 | 4 | 5 | void quadraticRoots(int a,int b, int c) 6 | { 7 | int root1 = 0, root2 = 0; 8 | int temp = (pow(b, 2) - 4*a*c); //value of b^2-4ac 9 | 10 | if(temp < 0)//if b^2-4ac is less then zero then roots are imaginary 11 | cout<<"Imaginary"; 12 | else 13 | { 14 | root1 = floor((-b + sqrt(temp))/(2 *a)); //root1 15 | root2 = floor((-b - sqrt(temp))/(2 *a));//root2 16 | cout<< max(root1,root2) << " " << min(root1,root2); //print the answer 17 | } 18 | } 19 | 20 | int main(){ 21 | int t; 22 | cin>>t; 23 | while(t--){ 24 | int a,b,c; 25 | cin>>a>>b>>c; 26 | 27 | quadraticRoots(a,b,c); 28 | cout< 2 | 3 | using namespace std; 4 | 5 | int gcd_naive(int a, int b) { 6 | int current_gcd = 1; 7 | for (int d = 2; d <= a && d <= b; d++) { 8 | if (a % d == 0 && b % d == 0) { 9 | if (d > current_gcd) { 10 | current_gcd = d; 11 | } 12 | } 13 | } 14 | return current_gcd; 15 | } 16 | 17 | int gcd_fast(int a, int b) { 18 | int m, n, rem; 19 | m = a; 20 | n = b; 21 | 22 | while (n != 0) { 23 | rem = m % n; 24 | m = n; 25 | n = rem; 26 | } 27 | return m; 28 | } 29 | 30 | int main() { 31 | int a, b; 32 | std::cin >> a >> b; 33 | //std::cout << gcd_naive(a, b) << std::endl; 34 | std::cout << gcd_fast(a, b) << std::endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Matrix/ReverseSpiral_MATRIX.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int MAX=100; 4 | int m,n,num; 5 | int a[MAX][MAX]={0}; 6 | void printsparsematrix(int arr[][MAX],int m, int n) 7 | { 8 | for(int i=0;i=0 &&q>=0)) 24 | { 25 | for(int i=0;i=0 && q>=0) 28 | { 29 | p+=1; 30 | if(p=0 && q>=0) 41 | { 42 | q+=1; 43 | if(q=0 && q>=0) 54 | { 55 | p-=1; 56 | if(p>=0) 57 | { 58 | if(a[p][q]!=0) 59 | cout<=0 && q>=0) 67 | { 68 | q-=1; 69 | if(q>=0) 70 | { 71 | if(a[p][q]!=0) 72 | cout<>m>>n>>num; 90 | int A[num]; 91 | int rowno[num],colno[num]; 92 | 93 | for(int i=0;i>rowno[i]>>colno[i]>>A[i]; 97 | } 98 | 99 | int k1=0; 100 | for(int i=0;i>I>>J; 117 | 118 | reverse_spiral_traversal(I, J); 119 | 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /Matrix/addition_of_two_matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | 6 | 7 | 8 | 9 | 10 | class Solution 11 | { 12 | public: 13 | vector > sumMatrix( const vector >& A, const vector >& B) 14 | { 15 | int row = A.size(); 16 | if(!(row>0 && row == B.size())){ 17 | return vector>(); 18 | } 19 | 20 | int col = A[0].size(); 21 | if(!(col>0 && col == B[0].size())){ 22 | return vector>(); 23 | } 24 | 25 | vector> ans(row,vector (col)); 26 | for(int i=0;i>t; 40 | while(t--) 41 | { 42 | int row, col; 43 | cin>> row>> col; 44 | vector > A(row); 45 | for(int i=0; i>A[i][j]; 51 | } 52 | } 53 | cin>> row>> col; 54 | vector > B(row); 55 | for(int i=0; i>B[i][j]; 61 | } 62 | } 63 | Solution ob; 64 | vector > result = ob.sumMatrix(A,B); 65 | if(result.size() == 0) 66 | cout<<"-1"; 67 | else 68 | { 69 | for (int i = 0; i < result.size(); ++i) 70 | { 71 | for (int j = 0; j < result[0].size(); ++j) 72 | { 73 | cout< 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | class Solution 16 | { 17 | public: 18 | vector boundaryTraversal(vector > matrix, int n, int m) 19 | { 20 | vector v; 21 | if(n==1){ 22 | for(int i=0;i=0;i--){ 39 | v.push_back(matrix[n-1][i]); 40 | } 41 | for(int i = n-2;i>=1;i--){ 42 | v.push_back(matrix[i][0]); 43 | } 44 | } 45 | return v; 46 | } 47 | }; 48 | 49 | 50 | 51 | // { Driver Code Starts. 52 | int main() { 53 | int t; 54 | cin>>t; 55 | 56 | while(t--) 57 | { 58 | int n,m; 59 | cin>>n>>m; 60 | vector > matrix(n); 61 | 62 | for(int i=0; i>matrix[i][j]; 68 | } 69 | } 70 | 71 | Solution ob; 72 | vector result = ob.boundaryTraversal(matrix, n, m); 73 | for (int i = 0; i < result.size(); ++i) 74 | cout< 4 | using namespace std; 5 | 6 | void print(vector arr[], int m){ 7 | for(int i=0;i arr[m]; 17 | 18 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k; 7 | 8 | cout << "Enter rows and columns for first matrix: "; 9 | cin >> r1 >> c1; 10 | cout << "Enter rows and columns for second matrix: "; 11 | cin >> r2 >> c2; 12 | 13 | 14 | while (c1!=r2) 15 | { 16 | cout << "Error! column of first matrix not equal to row of second."; 17 | 18 | cout << "Enter rows and columns for first matrix: "; 19 | cin >> r1 >> c1; 20 | 21 | cout << "Enter rows and columns for second matrix: "; 22 | cin >> r2 >> c2; 23 | } 24 | 25 | 26 | cout << endl << "Enter elements of matrix 1:" << endl; 27 | for(i = 0; i < r1; ++i) 28 | for(j = 0; j < c1; ++j) 29 | { 30 | cout << "Enter element a" << i + 1 << j + 1 << " : "; 31 | cin >> a[i][j]; 32 | } 33 | 34 | 35 | cout << endl << "Enter elements of matrix 2:" << endl; 36 | for(i = 0; i < r2; ++i) 37 | for(j = 0; j < c2; ++j) 38 | { 39 | cout << "Enter element b" << i + 1 << j + 1 << " : "; 40 | cin >> b[i][j]; 41 | } 42 | 43 | 44 | for(i = 0; i < r1; ++i) 45 | for(j = 0; j < c2; ++j) 46 | { 47 | mult[i][j]=0; 48 | } 49 | 50 | 51 | for(i = 0; i < r1; ++i) 52 | for(j = 0; j < c2; ++j) 53 | for(k = 0; k < c1; ++k) 54 | { 55 | mult[i][j] += a[i][k] * b[k][j]; 56 | } 57 | 58 | 59 | cout << endl << "Output Matrix: " << endl; 60 | for(i = 0; i < r1; ++i) 61 | for(j = 0; j < c2; ++j) 62 | { 63 | cout << " " << mult[i][j]; 64 | if(j == c2-1) 65 | cout << endl; 66 | } 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Matrix/multidimension array using vector.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Matrix/multidimension array using vector.exe -------------------------------------------------------------------------------- /Matrix/multidimension_array_using_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int m=3,n=2; 7 | vector arr[m]; 8 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | int m = 3, n=2; 6 | 7 | //declare the array 8 | int *arr[m]; 9 | 10 | //alocating the size of array 11 | for(int i=0;i 5 | using namespace std; 6 | 7 | void spiralTraversal(int M[R][C]){ 8 | if(R==1){ 9 | for(int i=0;i0;i--){ 26 | cout<=1;i--){ 29 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | 11 | 12 | class Solution 13 | { 14 | public: 15 | vector spirallyTraverse(vector > matrix, int r, int c) 16 | { 17 | vector v; 18 | int top = 0, right = c-1, bottom = r-1, left = 0; 19 | while(top<=bottom && left<=right){ 20 | //print top row 21 | for(int i=left;i<=right;i++){ 22 | v.push_back(matrix[top][i]); 23 | } 24 | top++; 25 | 26 | //right column 27 | for(int i=top;i<=bottom;i++){ 28 | v.push_back(matrix[i][right]); 29 | } 30 | right--; 31 | 32 | //bottom row 33 | if(top<=bottom){ 34 | for(int i = right;i>=left;i--){ 35 | v.push_back(matrix[bottom][i]); 36 | } 37 | bottom--; 38 | } 39 | 40 | //left column 41 | if(left <=right){ 42 | for(int i=bottom;i>=top;i--){ 43 | v.push_back(matrix[i][left]); 44 | } 45 | 46 | left++; 47 | } 48 | } 49 | 50 | return v; 51 | } 52 | }; 53 | 54 | // { Driver Code Starts. 55 | int main() { 56 | int t; 57 | cin>>t; 58 | 59 | while(t--) 60 | { 61 | int r,c; 62 | cin>>r>>c; 63 | vector > matrix(r); 64 | 65 | for(int i=0; i>matrix[i][j]; 71 | } 72 | } 73 | 74 | Solution ob; 75 | vector result = ob.spirallyTraverse(matrix, r, c); 76 | for (int i = 0; i < result.size(); ++i) 77 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | 11 | 12 | class Solution 13 | { 14 | public: 15 | vector sumTriangles(const vector >& matrix, int n) 16 | { 17 | int uppersum =0, lowersum = 0; 18 | for(int i=0;i=j) 24 | lowersum += matrix[i][j]; 25 | } 26 | } 27 | vector v = {uppersum,lowersum}; 28 | return v; 29 | } 30 | }; 31 | 32 | 33 | // { Driver Code Starts. 34 | 35 | int main() { 36 | int t; 37 | cin>>t; 38 | while(t--) 39 | { 40 | int n; 41 | cin>>n; 42 | vector > matrix(n); 43 | for(int i=0; i>matrix[i][j]; 49 | } 50 | } 51 | Solution ob; 52 | vector result = ob.sumTriangles(matrix,n); 53 | for (int i = 0; i < result.size(); ++i) 54 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int m=3,n=2; 7 | 8 | //declare a vector of vector for rows 9 | //the below whole method creates a 2d array 10 | vector> arr; 11 | 12 | for(int i=0;i v; 14 | for(int j=0;j 9 | 10 | struct node //queue structue 11 | { 12 | int data; 13 | int prn; 14 | node* next; 15 | }; 16 | 17 | class queue //queue class for implementing priority queue 18 | { 19 | private: 20 | node* frontPtr; // front pointer to track first element to poppped 21 | 22 | public: 23 | queue() : frontPtr(NULL) {} // no-arg ctor 24 | 25 | void push(int element, int priority) // insertion function 26 | { 27 | 28 | node* newNode; // creating new Node 29 | newNode = new node; 30 | 31 | newNode->data = element; 32 | newNode->prn = priority; 33 | 34 | 35 | 36 | if(frontPtr == NULL || frontPtr->prn > priority) // if it is first element or has higher priority 37 | { // than all the elements present 38 | newNode->next = frontPtr; 39 | frontPtr = newNode; 40 | 41 | return; 42 | } 43 | 44 | node* itr = frontPtr; 45 | node* old = itr; 46 | 47 | while(itr != NULL) 48 | { 49 | if(itr->prn > priority) 50 | { 51 | break; 52 | } 53 | 54 | old = itr; 55 | itr = itr->next; 56 | } 57 | 58 | 59 | newNode->next = old->next; 60 | old->next = newNode; 61 | 62 | } 63 | 64 | void pop() // deletion function 65 | { 66 | 67 | if(frontPtr == NULL) 68 | { 69 | std::cout << "\n Queue already empty\n"; 70 | return; 71 | } 72 | 73 | node* temp = frontPtr; 74 | frontPtr = frontPtr->next; // simply delete the elemnt at front 75 | 76 | delete temp; 77 | } 78 | 79 | void display() // to display the queue (not a necessary function) 80 | { 81 | if(frontPtr == NULL) 82 | { 83 | std::cout << "\nQueue is empty\n"; 84 | return; 85 | } 86 | node* itr = frontPtr; 87 | 88 | std::cout << "\n\tData" << "\t\t" << "Priority" << std::endl; 89 | 90 | while(itr != NULL) 91 | { 92 | std::cout << "\t" << itr->data << "\t\t" << itr->prn << std::endl; 93 | itr = itr->next; 94 | } 95 | } 96 | 97 | int front() // returns data of first element not its priority 98 | { 99 | if(frontPtr == NULL) 100 | { 101 | std::cout << "\nQueue is empty\n"; 102 | return -1; 103 | } 104 | return frontPtr->data; 105 | } 106 | 107 | }; 108 | 109 | 110 | int main() 111 | { 112 | queue q; 113 | int ch; 114 | 115 | do 116 | { 117 | std::cout << "\n1- Insert element in queue"; 118 | std::cout << "\n2- Delete element from queue"; 119 | std::cout << "\n3- Display queue"; 120 | std::cout << "\n4- Return front element"; 121 | std::cout << "\n0- Exit Programming"; 122 | std::cout << "\n\tEnter your choice: "; 123 | 124 | std::cin >> ch; 125 | 126 | switch(ch) 127 | { 128 | case 1: 129 | int element, priority; 130 | std::cout << "\nEnter element and its priority: "; 131 | std::cin >> element >> priority; 132 | q.push(element, priority); 133 | break; 134 | case 2: 135 | q.pop(); 136 | break; 137 | case 3: 138 | q.display(); 139 | break; 140 | case 4: 141 | if(q.front() != -1) 142 | std::cout << "\nFront element --> " << q.front() << std::endl; 143 | break; 144 | case 0: 145 | std::cout << "\n Exiting Program"; 146 | break; 147 | default: 148 | std::cout << "Invalid choice :("; 149 | break; 150 | 151 | } 152 | 153 | }while(ch != 0); 154 | 155 | 156 | return 0; 157 | 158 | } 159 | 160 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Hacktoberfest 2020](https://hacktoberfest.digitalocean.com/assets/HF-full-logo-b05d5eb32b3f3ecc9b2240526104cf4da3187b8b61963dd9042fdc2536e4a76c.svg) 2 | 3 | [![Say Thanks!](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/saksham1298agarwal%40gmail.com)[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/issues) 4 | 5 | # DSA-Problem-Solutions [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Algorithms%20written%20in%20different%20programing%20languages&url=https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions&via=algorithms&hashtags=algorithms,datastructures,python,java,c,cpp,php,javascript) 6 | 7 | Use this project to make your first contribution to an open source project on GitHub. Practice making your first pull request to a public repository before doing the real thing! 8 | 9 | Celebrate [Hacktoberfest](https://hacktoberfest.digitalocean.com/) by getting involved in the open source community by completing some simple tasks in this project. 10 | 11 | This repository is open to all members of the GitHub community. Any member may contribute to this project without being a collaborator [here](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/) 12 | 13 | ## How to contribute to this project 14 | Here are some ways to contribute to this repository: 15 | 16 | * Build your favourite data structure and push our program in that data structure folder 17 | * If your data structure is found in repo then create a new folder and add your code in it 18 | * Feel free to open any issue in this repo and make sure your add hacktoberfest label to that issue 19 | 20 | ## Getting started 21 | * Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 22 | * Clone your fork down to your local machine 23 | 24 | ```markdown 25 | git clone https://github.com/your-username/GFG-DSA-Problem-Solutions.git 26 | ``` 27 | 28 | * Create a branch 29 | 30 | ```markdown 31 | git checkout -b branch-name 32 | ``` 33 | 34 | * Make your changes (choose from any task below) 35 | * Commit and push 36 | 37 | ```markdown 38 | git add . 39 | git commit -m 'Commit message' 40 | git push origin branch-name 41 | ``` 42 | 43 | * Create a new pull request from your forked repository (Click the `New Pull Request` button located at the top of your repo) 44 | * Wait for your PR review and merge approval! 45 | 46 | **Show some ❤️** 47 | - Consider leaving a ⭐ [here](https://github.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/). 48 | - Follow @SakshamAgrwl for more updates. 49 | 50 | #### Say Hi on [Linkedin](https://www.linkedin.com/in/saksham-agarwal-1286a09m/)! 👋 51 | 52 | 53 | ## Reference links 54 | Here is a great tutorial for creating your first pull request by [Roshan Jossey](https://github.com/Roshanjossey): 55 | [https://github.com/Roshanjossey/first-contributions](https://github.com/Roshanjossey/first-contributions) 56 | 57 | Managing your Forked Repo: [https://help.github.com/articles/fork-a-repo/](https://help.github.com/articles/fork-a-repo/) 58 | 59 | Syncing a Fork: [https://help.github.com/articles/syncing-a-fork/](https://help.github.com/articles/syncing-a-fork/) 60 | 61 | Keep Your Fork Synced: [https://gist.github.com/CristinaSolana/1885435](https://gist.github.com/CristinaSolana/1885435) 62 | 63 | Checkout this list for README examples - Awesome README [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 64 | 65 | Github-Flavored Markdown [https://guides.github.com/features/mastering-markdown/](https://guides.github.com/features/mastering-markdown/) 66 | GitHub license explained [https://choosealicense.com](https://choosealicense.com) 67 | 68 | -------------------------------------------------------------------------------- /Recursion/2048_problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | char words[][10] = {"zero","one","two","three","four","five","six","seven","eight","nine"}; 5 | 6 | void printSpellings(int n){ 7 | if(n==0){ 8 | return; 9 | } 10 | 11 | //separate each digit first 12 | printSpellings(n/10); 13 | int digit = n%10; 14 | cout<>n; 23 | printSpellings(n); 24 | } -------------------------------------------------------------------------------- /Recursion/2048_problem.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Recursion/2048_problem.exe -------------------------------------------------------------------------------- /Recursion/Count_steps_towerofhanoi.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | long long toh(int n, int from, int to, int aux); 7 | 8 | int main() { 9 | 10 | int T; 11 | cin >> T; 12 | while (T--) { 13 | long long moves = 0; 14 | int N; 15 | cin >> N; 16 | moves = toh(N, 1, 3, 2); 17 | cout << moves << endl; 18 | } 19 | return 0; 20 | } 21 | 22 | 23 | 24 | // } Driver Code Ends 25 | 26 | 27 | // You need to complete this function 28 | 29 | // avoid space at the starting of the string in "move disk....." 30 | long long toh(int N, int from, int to, int aux) { 31 | int count = 0; 32 | if (N == 1) 33 | { 34 | cout << "move disk 1 from rod " << from << 35 | " to rod " << to<0){ 41 | count = toh(N - 1, from, aux, to); 42 | cout << "move disk " << N << " from rod " << from<< 43 | " to rod " << to<< endl; 44 | count++; 45 | count += toh(N - 1, aux, to, from); 46 | 47 | } 48 | 49 | 50 | return count; 51 | 52 | // Your code here 53 | } -------------------------------------------------------------------------------- /Recursion/Fast_power.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int power(int a, int n){ 5 | if(n==0){ 6 | return 1; 7 | } 8 | return a*power(a,n-1); 9 | } 10 | 11 | int fastPower(int a, int n){ 12 | if(n==0){ 13 | return 1; 14 | } 15 | 16 | int smaller_ans = fastPower(a,n/2); 17 | smaller_ans *= smaller_ans; 18 | 19 | //if n is odd 20 | if(n&1){ 21 | return smaller_ans*a; 22 | } 23 | return smaller_ans; 24 | } -------------------------------------------------------------------------------- /Recursion/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fib(int n){ 5 | if(n==0){ 6 | return 0; 7 | } 8 | 9 | if(n==1){ 10 | return 1; 11 | } 12 | 13 | return fib(n-1) + fib(n-2); 14 | } 15 | 16 | int main(){ 17 | int t; 18 | cin>>t; 19 | while(t--){ 20 | int n; 21 | cin>>n; 22 | cout< 2 | using namespace std; 3 | 4 | int solve(int n) 5 | { 6 | if(n<=0){return 0;} 7 | if(n==1){return 1;} 8 | if(n==2){ 9 | return 2; 10 | } 11 | int ans=INT_MAX; 12 | for(int i=1;i*i<=n;i++) 13 | { 14 | int temp=1+solve(n-(i*i)); 15 | ans=min(ans,temp); 16 | } 17 | return ans; 18 | } 19 | 20 | int main() 21 | { 22 | int n; 23 | cin>>n; 24 | cout< 2 | using namespace std; 3 | 4 | // A recursive function that 5 | // check a str[s..e] is 6 | // palindrome or not. 7 | bool isPalRec(char str[], 8 | int s, int e) 9 | { 10 | 11 | // If there is only one character 12 | if (s == e) 13 | return true; 14 | 15 | // If first and last 16 | // characters do not match 17 | if (str[s] != str[e]) 18 | return false; 19 | 20 | // If there are more than 21 | // two characters, check if 22 | // middle substring is also 23 | // palindrome or not. 24 | if (s < e + 1) 25 | return isPalRec(str, s + 1, e - 1); 26 | 27 | return true; 28 | } 29 | 30 | bool isPalindrome(char str[]) 31 | { 32 | int n = strlen(str); 33 | 34 | // An empty string is 35 | // considered as palindrome 36 | if (n == 0) 37 | return true; 38 | 39 | return isPalRec(str, 0, n - 1); 40 | } 41 | 42 | // Driver Code 43 | int main() 44 | { 45 | char str[] = "geeg"; 46 | 47 | if (isPalindrome(str)) 48 | cout << "Yes"; 49 | else 50 | cout << "No"; 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Recursion/Rod_cutting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int rodCutting(int n, int a, int b, int c) 5 | { 6 | if(n == 0) 7 | return 0; 8 | if(n < 0) 9 | return -1; 10 | int res = max(max(rodCutting(n-a, a, b, c), rodCutting(n-b, a, b, c)), 11 | rodCutting(n-c, a, b, c)); 12 | 13 | if(res== -1) 14 | return -1; 15 | return 1+res; 16 | } 17 | 18 | int main() 19 | { 20 | int n = 25; 21 | int a = 11, b = 12, c = 13; 22 | cout << rodCutting(n, a, b, c); 23 | } -------------------------------------------------------------------------------- /Recursion/Subset_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countSubsets(int arr[], int sum, int n){ 5 | if(n==0){ 6 | return (sum==0) ? 1:0; 7 | } 8 | 9 | return countSubsets(arr, n-1,sum) + countSubsets(arr, n-1, sum-arr[n-1]); 10 | } 11 | 12 | int main(){ 13 | int n; 14 | cin>>n; 15 | int arr[n]; 16 | for(int i=0;i>a[i]; 18 | } 19 | 20 | cout< 4 | using namespace std; 5 | 6 | void towerOfHanoi(int n, char from_rod, 7 | char to_rod, char aux_rod) 8 | { 9 | if (n == 1) 10 | { 11 | cout << "Move disk 1 from rod " << from_rod << 12 | " to rod " << to_rod< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void coin(vector v,int n,int mc,string asf) 8 | { 9 | if(mc==n) 10 | { 11 | cout<n) 15 | { 16 | return; 17 | } 18 | 19 | for(int i=0;i v{2,3,5,6}; 33 | 34 | coin(v,n,0,""); 35 | } -------------------------------------------------------------------------------- /Recursion/infinite_recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void fun1(){ 5 | cout<<"Great, have some fun"< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | string codes[10]={ 8 | ".", 9 | "abc", 10 | "def", 11 | "ghi", 12 | "jklm", 13 | "no", 14 | "pqrs", 15 | "tu", 16 | "vwxy", 17 | "z"}; 18 | 19 | vector kp(string s) 20 | { 21 | 22 | if(s.size()==0) 23 | { 24 | vector p; 25 | p.push_back(""); 26 | return p; 27 | } 28 | 29 | char ch=s[0]; 30 | int n=ch-'0'; 31 | string ros=s.substr(1,s.size()); 32 | 33 | vector l=kp(ros); 34 | vector ml; 35 | for(int i=0;i>s; 54 | 55 | vector ans=kp(s); 56 | int c=0; 57 | 58 | for(int i=0;i 2 | using namespace std; 3 | 4 | void print1ToN(int N){ 5 | if (N==0){ 6 | return; 7 | } 8 | 9 | print1ToN(N-1); 10 | cout<>N; 16 | 17 | print1ToN(N); 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /Recursion/print_1_to_n.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Recursion/print_1_to_n.exe -------------------------------------------------------------------------------- /Recursion/print_n_to_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printNTo1(int n){ 5 | if(n==0){ 6 | return; 7 | } 8 | cout<>n; 17 | 18 | printNTo1(n); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /Recursion/print_n_to_1.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SakshamAgrwl/GFG-DSA-Problem-Solutions/531ca58a6b2f9293ef5fe87c6c32f0d0cd9d6542/Recursion/print_n_to_1.exe -------------------------------------------------------------------------------- /Recursion/printing table of any number.cpp: -------------------------------------------------------------------------------- 1 | // To print table of any number 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int i, number, ans; 9 | cout << "Enter the number" << endl; 10 | cin >> number; 11 | 12 | i = 1; 13 | do 14 | { 15 | ans = number * i; 16 | cout << "the value is : " << ans << endl; 17 | i++; 18 | 19 | } while (i <= 10); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Recursion/sum_n_natural_numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int sum1ToN(int n){ 5 | if(n==0){ 6 | return 0; 7 | } 8 | 9 | return n + sum1ToN(n-1); 10 | } 11 | 12 | 13 | int main(){ 14 | int T; 15 | cin>>T; 16 | while(T--){ 17 | int n; 18 | cin>>n; 19 | cout< 2 | using namespace std; 3 | 4 | int sumOfDigits(int n){ 5 | if(n<10){ 6 | return n; 7 | } 8 | 9 | return sumOfDigits(n/10) + n%10; 10 | } 11 | 12 | int main(){ 13 | int n; 14 | cin>>n; 15 | cout< 2 | using namespace std; 3 | 4 | int binarySearch(int arr[], int x, int low, int high){ 5 | 6 | if(low > high){ 7 | return -1; 8 | } 9 | 10 | int mid = (low+high)/2; 11 | if( arr[mid] == x){ 12 | return mid; 13 | } 14 | 15 | else if(arr[mid] > x){ 16 | return binarySearch(arr, low,mid-1,x); 17 | } 18 | 19 | else{ 20 | return binarySearch(arr,mid+1,high,x); 21 | } 22 | } -------------------------------------------------------------------------------- /Searching/Binary_search iterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int arr[], int n, int key){ 5 | int low = 0; 6 | int high = n-1; 7 | 8 | while(low>n; 30 | 31 | int arr[n]; 32 | for(int i=0;i>arr[i]; 34 | } 35 | 36 | cout<<"Enter the element you want to search:"; 37 | cin>>key; 38 | 39 | cout< 2 | using namespace std; 3 | 4 | int firstOcc(int arr[],int low, int high, int x){ 5 | if(low>high){ 6 | return -1; 7 | } 8 | 9 | int mid = (high+low)/2; 10 | 11 | if(x>arr[mid]){ 12 | return firstOcc(arr,mid+1,high,x); 13 | } 14 | 15 | else if(arr[mid] > x){ 16 | return firstOcc(arr,mid,high-1,x); 17 | } 18 | 19 | else{ 20 | if(mid==0 || arr[mid-1] != arr[mid]){ 21 | return mid; 22 | } 23 | else{ 24 | return firstOcc(arr,low,mid-1,x); 25 | } 26 | } 27 | return -1; 28 | } -------------------------------------------------------------------------------- /Searching/Minimum size subarray sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int s, vector& nums) { 4 | if (nums.size() == 0) return 0; 5 | int i = 0, j = 0, length = INT_MAX, sum = 0; 6 | nums.push_back (0); 7 | while (j < nums.size()) { 8 | if (sum < s) sum += nums[j++]; 9 | else length = min (length, j - i), sum -= nums[i++]; 10 | } 11 | return (length == INT_MAX ? 0 : length); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Searching/Peak_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findPeak(int arr[], int n){ 5 | int low = 0, high = n-1; 6 | while(low<=high){ 7 | int mid = (low+high)/2; 8 | if(mid == 0 || arr[mid-1] <= arr[mid]) && (mid == n-1 || arr[mid] >= arr[mid+1]){ 9 | return mid; 10 | } 11 | if(mid>0 && arr[mid-1] >= arr[mid]){ 12 | high = mid-1; 13 | } 14 | else{ 15 | low = mid+1; 16 | } 17 | } 18 | return -1; 19 | } -------------------------------------------------------------------------------- /Searching/Search_in_infinte_size_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int arr[],int low, int high,int x){ 5 | while(low<=high){ 6 | int mid = (low + high); 7 | if(arr[mid] == x){ 8 | return mid; 9 | } 10 | else if(arr[mid] > x){ 11 | return binarySearch(arr[],low, high-1,x); 12 | } 13 | 14 | return binarySearch(arr[], low + 1, high, x); 15 | } 16 | 17 | return -1; 18 | } 19 | 20 | 21 | int findPos(int arr[], int x){ 22 | if(arr[0] == x){ 23 | return 0; 24 | } 25 | int i; 26 | while(arr[i] < x){ 27 | i=i*2; 28 | if(arr[i] == x){ 29 | return i; 30 | } 31 | } 32 | return binarySearch(arr[], i/2+1,i,x); 33 | } -------------------------------------------------------------------------------- /Searching/count_more_than_k_occurences.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // A C++ program to print elements with count more than n/k 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | int countOccurence(int arr[], int n, int k); 8 | // Position this line where user code will be pasted. 9 | 10 | /* Driver program to test above function */ 11 | int main() { 12 | int t, k; 13 | cin >> t; 14 | while (t--) { 15 | int n, i; 16 | cin >> n; 17 | 18 | int arr[n]; 19 | 20 | for (i = 0; i < n; i++) cin >> arr[i]; 21 | cin >> k; 22 | cout << countOccurence(arr, n, k) << endl; 23 | } 24 | return 0; 25 | } 26 | // } Driver Code Ends 27 | 28 | 29 | // Function to find element with count more than n/k times 30 | // arr: input array 31 | int countOccurence(int arr[], int n, int k) { 32 | int max = INT_MIN; 33 | for(int i=0;i n/k){ 48 | count++; 49 | } 50 | } 51 | return count; 52 | } -------------------------------------------------------------------------------- /Searching/find_square_root.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findSquareFloor(int x){ 5 | int low = 1, high = x, ans = -1; 6 | while(low<=high){ 7 | int mid = (low+high)/2; 8 | int msq = mid*mid; 9 | if(msq == x){ 10 | return mid; 11 | } 12 | else if(msq > x){ 13 | high = mid-1; 14 | } 15 | else{ 16 | low = mid+1; 17 | ans = mid; 18 | } 19 | } 20 | 21 | return ans; 22 | } -------------------------------------------------------------------------------- /Searching/index_of_last_occurence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int lastOccur(int arr[], int n, int x){ 5 | int low = 0; 6 | int high = n-1; 7 | 8 | if(low>high){ 9 | return -1; 10 | } 11 | 12 | int mid = (low+high)/2; 13 | 14 | if(arr[mid] > x){ 15 | high = mid-1; 16 | } 17 | 18 | else if(arr[mid] < x){ 19 | low = mid+1; 20 | } 21 | 22 | else{ 23 | if(arr[mid] == n-1 || arr[mid] != mid+1){ 24 | return mid; 25 | } 26 | else{ 27 | low = mid+1; 28 | } 29 | } 30 | } 31 | 32 | int main(){ 33 | int n,x; 34 | cin>>n; 35 | 36 | int arr[n]; 37 | for(int i=0;i>arr[i]; 39 | } 40 | 41 | cout<<"Enter the element you want to search:"; 42 | cin>>x; 43 | 44 | cout< 2 | using namespace std; 3 | 4 | int search(int arr[], int n, int x){ 5 | int low = 0, high = n-1; 6 | while(low<=high){ 7 | int mid = (low+high)/2; 8 | if(arr[mid] == x){ 9 | return mid; 10 | } 11 | if(arr[low] < arr[mid]){ 12 | //left half sorted 13 | if(x >= arr[low] && x arr[mid] && x<=arr[high]){ 23 | low = mid+1; 24 | } 25 | else{ 26 | high = mid-1; 27 | } 28 | } 29 | } 30 | 31 | return -1; 32 | } -------------------------------------------------------------------------------- /Searching/two_pointer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPair(int arr[], int n, int x){ 5 | int left = 0, right= n-1; 6 | 7 | while(left x){ 12 | right--; 13 | } 14 | else{ 15 | left++; 16 | } 17 | } 18 | 19 | return false; 20 | } 21 | 22 | int main() 23 | { 24 | int arr[] = {2, 3, 7, 8, 11}; 25 | int n = sizeof(arr)/sizeof(arr[0]); 26 | int x = 14; 27 | 28 | cout << isPresent(arr, n, sum); 29 | } -------------------------------------------------------------------------------- /Sorting/Bubble Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i array[j+1]) { //when the current item is bigger than next 19 | swapping(array[j], array[j+1]); 20 | swaps = 1; //set swap flag 21 | } 22 | } 23 | if(!swaps) 24 | break; // No swap in this pass, so array is sorted 25 | } 26 | } 27 | int main() { 28 | int n; 29 | cout << "Enter the number of elements: "; 30 | cin >> n; 31 | int arr[n]; //create an array with given number of elements 32 | cout << "Enter elements:" << endl; 33 | for(int i = 0; i> arr[i]; 35 | } 36 | cout << "Array before Sorting: "; 37 | display(arr, n); 38 | bubbleSort(arr, n); 39 | cout << "Array after Sorting: "; 40 | display(arr, n); 41 | } -------------------------------------------------------------------------------- /Sorting/Heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void heapify(int arr[], int n, int i) { 5 | // Find largest among root, left child and right child 6 | int largest = i; 7 | int left = 2 * i + 1; 8 | int right = 2 * i + 2; 9 | 10 | if (left < n && arr[left] > arr[largest]) 11 | largest = left; 12 | 13 | if (right < n && arr[right] > arr[largest]) 14 | largest = right; 15 | 16 | // Swap and continue heapifying if root is not largest 17 | if (largest != i) { 18 | swap(arr[i], arr[largest]); 19 | heapify(arr, n, largest); 20 | } 21 | } 22 | 23 | // main function to do heap sort 24 | void heapSort(int arr[], int n) { 25 | // Build max heap 26 | for (int i = n / 2 - 1; i >= 0; i--) 27 | heapify(arr, n, i); 28 | 29 | // Heap sort 30 | for (int i = n - 1; i >= 0; i--) { 31 | swap(arr[0], arr[i]); 32 | 33 | // Heapify root element to get highest element at root again 34 | heapify(arr, i, 0); 35 | } 36 | } 37 | 38 | // Print an array 39 | void printArray(int arr[], int n) { 40 | for (int i = 0; i < n; ++i) 41 | cout << arr[i] << " "; 42 | cout << "\n"; 43 | } 44 | 45 | // Driver code 46 | int main() { 47 | int arr[] = {1, 12, 9, 5, 6, 10}; 48 | int n = sizeof(arr) / sizeof(arr[0]); 49 | heapSort(arr, n); 50 | 51 | cout << "Sorted array is \n"; 52 | printArray(arr, n); 53 | } 54 | -------------------------------------------------------------------------------- /Sorting/Hoares partition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void hoarePartition(int arr[], int l, int h){ 5 | int pivot = arr[l]; 6 | int i = l-1, j = h+1; 7 | while(true){ 8 | do{ 9 | i++; 10 | } 11 | while(arr[i] pivot); 17 | if(arr[i]>=arr[j]){ 18 | return j; 19 | } 20 | swap(arr[i],arr[j]); 21 | } 22 | } -------------------------------------------------------------------------------- /Sorting/Lometo_partition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void lometoPartition(int arr[],int l, int h){ 5 | int pivot = arr[h]; //always last element 6 | int i = l-1; 7 | for(int j=l;j<=h-1;j++){ 8 | if(arr[j] <= pivot){ 9 | i++; 10 | swap(arr[i],arr[j]); 11 | } 12 | } 13 | swap(arr[i+1],arr[h]); 14 | return (i+1); 15 | } -------------------------------------------------------------------------------- /Sorting/Merge three sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | void printVector(const vector& a) 7 | { 8 | for (auto e : a) { 9 | cout << e << " "; 10 | } 11 | cout< merge(vector &A,vector &B) 23 | { 24 | vector v; 25 | int i=0,j=0; 26 | while(i mergeThree(vector& A, vector& B, vector& C) 52 | { 53 | vector v = merge(A,B); 54 | vector c = merge(v,C); 55 | return c; 56 | } 57 | 58 | 59 | 60 | // { Driver Code Starts. 61 | 62 | int main() 63 | { 64 | 65 | 66 | int t; 67 | cin>>t; 68 | while(t--){ 69 | int n,m,o; 70 | cin>>n>>m>>o; 71 | vector A,B,C; 72 | for(int i=0;i>x; 75 | A.push_back(x); 76 | } 77 | 78 | for(int i=0;i>x; 81 | B.push_back(x); 82 | } 83 | 84 | for(int i=0;i>x; 87 | C.push_back(x); 88 | } 89 | 90 | 91 | printVector(mergeThree(A, B, C)); 92 | 93 | } 94 | 95 | return 0; 96 | } 97 | // } Driver Code Ends -------------------------------------------------------------------------------- /Sorting/Merge_two_sorted_arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | void merge(int a[], int b[], int m, int n){ 7 | int i=0,j=0; 8 | while(i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(){ 8 | vector v = {5,7,20,10}; 9 | sort(v.begin(),v.end()); 10 | 11 | for(int x:v){ 12 | cout<); 17 | 18 | for(int x : v){ 19 | cout< 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Function to sort arr[] of size n using bucket sort 8 | void bucketSort(float arr[], int n) 9 | { 10 | // 1) Create n empty buckets 11 | vector b[n]; 12 | 13 | // 2) Put array elements in different buckets 14 | for (int i = 0; i < n; i++) { 15 | int bi = n * arr[i]; // Index in bucket 16 | b[bi].push_back(arr[i]); 17 | } 18 | 19 | // 3) Sort individual buckets 20 | for (int i = 0; i < n; i++) 21 | sort(b[i].begin(), b[i].end()); 22 | 23 | // 4) Concatenate all buckets into arr[] 24 | int index = 0; 25 | for (int i = 0; i < n; i++) 26 | for (int j = 0; j < b[i].size(); j++) 27 | arr[index++] = b[i][j]; 28 | } 29 | 30 | /* Driver program to test above function */ 31 | int main() 32 | { 33 | float arr[] = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 34 | int n = sizeof(arr) / sizeof(arr[0]); 35 | bucketSort(arr, n); 36 | 37 | cout << "Sorted array is \n"; 38 | for (int i = 0; i < n; i++) 39 | cout << arr[i] << " "; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Sorting/chocolate distribution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minDiff(int arr[], int n, int m){ //here m is the no of students 5 | if(m>n){ 6 | return -1; 7 | } 8 | 9 | sort(arr, arr+n); 10 | 11 | int res = arr[m-1]-arr[0]; 12 | for(int i=1;i<(i+m-1);i++){ 13 | res = min(res,arr[i+m-1]-arr[0]); 14 | } 15 | return res; 16 | } -------------------------------------------------------------------------------- /Sorting/closer to sort.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to find the index of x 10 | // arr[]: input array 11 | // n: size of array 12 | // x: element to find index 13 | int binarySearch(int arr[], int low, int high, int x){ 14 | 15 | while(low<=high){ 16 | int mid = low + (high-low) / 2; 17 | 18 | if(arr[mid] == x){ 19 | return mid; 20 | } 21 | if(mid>low && arr[mid-1] == x){ 22 | return (mid-1); 23 | } 24 | if(mid < high && arr[mid+1] == x){ 25 | return (mid+1); 26 | } 27 | 28 | if (arr[mid] > x) { 29 | return binarySearch(arr, low, mid - 2, x); 30 | } 31 | 32 | else{ 33 | return binarySearch(arr, mid + 2, high, x); 34 | } 35 | } 36 | 37 | return -1; 38 | } 39 | 40 | int closer(int arr[],int n, int x) 41 | { 42 | return binarySearch(arr, 0, n-1, x); 43 | 44 | } 45 | 46 | // { Driver Code Starts. 47 | 48 | int main() { 49 | 50 | cin.tie(NULL); 51 | 52 | int t; 53 | cin >> t; 54 | 55 | while(t--){ 56 | 57 | int n; 58 | cin >> n; 59 | int arr[n]; 60 | for(int i = 0;i> arr[i]; 62 | } 63 | int x; 64 | cin >> x; 65 | 66 | int res = closer(arr,n,x); 67 | 68 | cout << res << endl; 69 | } 70 | 71 | return 0; 72 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Sorting/count_inversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int countAndMerge(int arr[], int l, int m, int r){ 5 | int n1 = m-l+1, n2 = r-m; 6 | int left[n1], right[n2]; 7 | //copying the elements of n1 8 | for(int i=0;i 4 | #include 5 | #define RANGE 255 6 | 7 | // The main function that sort the given string arr[] in 8 | // alphabatical order 9 | char* countSort(char arr[]); 10 | 11 | // Driver program to test above function 12 | int main() 13 | { 14 | long int t; 15 | scanf("%ld",&t); 16 | while(t--) 17 | { 18 | long int n; 19 | scanf("%ld",&n); 20 | char arr[n+1]; 21 | scanf("%s",arr); 22 | printf("%s\n", countSort(arr)); 23 | } 24 | return 0; 25 | } 26 | 27 | // } Driver Code Ends 28 | 29 | char* countSort(char arr[]) 30 | { 31 | int k = 26; 32 | int n = strlen(arr); 33 | int count[k]; 34 | for(int i=0;i=0;i--){ 48 | output[count[(int)arr[i]%97]-1] = arr[i]; 49 | count[(int)arr[i]%97]--; 50 | } 51 | for(int i=0;i=0;i--){ 28 | output[count[arr[i]]-1] = arr[i]; 29 | count[arr[i]]--; 30 | } 31 | 32 | //then we will copy the elements from output array to 33 | //original array arr 34 | for(int i=0;i 5 | using namespace std; 6 | 7 | vector printIntersection(int arr1[], int arr2[], int N, int M); 8 | 9 | /* Driver program to test above function */ 10 | int main() 11 | { 12 | int T; 13 | cin >> T; 14 | 15 | while(T--){ 16 | 17 | int N, M; 18 | cin >> N >> M; 19 | int arr1[N]; 20 | int arr2[M]; 21 | for(int i = 0;i> arr1[i]; 23 | } 24 | 25 | for(int i = 0;i> arr2[i]; 27 | } 28 | 29 | // Function calling 30 | vector v; 31 | v = printIntersection(arr1, arr2, N, M); 32 | 33 | for(int i=0;i printIntersection(int arr1[], int arr2[], int N, int M) 50 | { 51 | int i = 0, j = 0; 52 | bool flag=false; 53 | std::vector v; 54 | while (i < N && j < M) 55 | { 56 | if (i > 0 && arr1[i-1] == arr1[i]) 57 | { 58 | i++; 59 | continue; 60 | } 61 | if (arr1[i] < arr2[j]) 62 | i++; 63 | else if (arr2[j] < arr1[i]) 64 | j++; 65 | else 66 | { 67 | v.push_back(arr2[j]); 68 | flag=true; 69 | i++; 70 | j++; 71 | } 72 | } 73 | 74 | if(flag==false) 75 | v.push_back(-1); 76 | return v; 77 | } -------------------------------------------------------------------------------- /Sorting/kth smallest element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void lomitoPartition(int arr[],int l, int h){ 5 | int pivot = arr[h]; 6 | int i = l-1; 7 | for(int j = l;j<=h-1;j++){ 8 | if(arr[j] <= pivot){ 9 | i++; 10 | swap(arr[i],arr[j]); 11 | } 12 | } 13 | swap(arr[i+1],arr[h]); 14 | return (i+1); 15 | } 16 | 17 | int kthSmallest(int arr[], int n, int k){ 18 | int l = 0, h = n-1; 19 | int mid = (l+h)/2; 20 | while(l<=h){ 21 | int p = lomitoPartition(arr,l,h); 22 | if(p==k-1){ 23 | return p; 24 | } 25 | else if(p>k-1){ 26 | l = mid+1; 27 | } 28 | else{ 29 | h = mid-1; 30 | } 31 | } 32 | return -1; 33 | 34 | } -------------------------------------------------------------------------------- /Sorting/merge overlapping intervals.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to merge overlapping Intervals in 2 | // O(n Log n) time and O(1) extra space. 3 | #include 4 | using namespace std; 5 | 6 | // An Interval 7 | struct Interval 8 | { 9 | int s, e; 10 | }; 11 | 12 | // Function used in sort 13 | bool mycomp(Interval a, Interval b) 14 | { return a.s < b.s; } 15 | 16 | void mergeIntervals(Interval arr[], int n) 17 | { 18 | // Sort Intervals in increasing order of 19 | // start time 20 | sort(arr, arr+n, mycomp); 21 | 22 | int index = 0; // Stores index of last element 23 | // in output array (modified arr[]) 24 | 25 | // Traverse all input Intervals 26 | for (int i=1; i= arr[i].s) 31 | { 32 | // Merge previous and current Intervals 33 | arr[index].e = max(arr[index].e, arr[i].e); 34 | arr[index].s = min(arr[index].s, arr[i].s); 35 | } 36 | else { 37 | index++; 38 | arr[index] = arr[i]; 39 | } 40 | } 41 | 42 | // Now arr[0..index-1] stores the merged Intervals 43 | cout << "\n The Merged Intervals are: "; 44 | for (int i = 0; i <= index; i++) 45 | cout << "[" << arr[i].s << ", " << arr[i].e << "] "; 46 | } 47 | 48 | // Driver program 49 | int main() 50 | { 51 | Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} }; 52 | int n = sizeof(arr)/sizeof(arr[0]); 53 | mergeIntervals(arr, n); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Sorting/merge_function.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int arr[], int l, int m, int h){ 5 | int n1 = m-l+1, n2 = h-m; 6 | int left[n1], right[n2]; 7 | 8 | for(int i=0;i 3 | #include 4 | using namespace std; 5 | int partition (int arr[], int low, int high); 6 | /* The main function that implements QuickSort 7 | arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ 8 | void quickSort(int arr[], int low, int high) 9 | { 10 | if (low < high) 11 | { 12 | /* pi is partitioning index, arr[p] is now at right place */ 13 | int pi = partition(arr, low, high); 14 | // Separately sort elements before partition and after partition 15 | quickSort(arr, low, pi - 1); 16 | quickSort(arr, pi + 1, high); 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 | printf("%d ", arr[i]); 25 | printf("\n"); 26 | } 27 | // Driver program to test above functions 28 | int main() 29 | { 30 | int arr[1000],n,T,i; 31 | scanf("%d",&T); 32 | while(T--){ 33 | scanf("%d",&n); 34 | for(i=0;i Array to be sorted, low --> Starting index, high --> Ending index 45 | void quickSort(int arr[], int low, int high) { 46 | if (low < high) { 47 | // pi is partitioning index, arr[p] is now at right place 48 | int pi = partition(arr, low, high); 49 | // Separately sort elements before / partition and after partition 50 | quickSort(arr, low, pi - 1); 51 | quickSort(arr, pi + 1, high); 52 | } 53 | }*/ 54 | /* This function takes last element as pivot, places the pivot element 55 | at its correct position in sorted array, and places all smaller (smaller 56 | than pivot) to left of pivot and all greater elements to right of pivot */ 57 | int partition (int arr[], int low, int high) 58 | { 59 | int pivot = arr[high]; 60 | int i = (low-1); 61 | for(int j=low;j<=high-1;j++){ 62 | if(arr[j]<=pivot){ 63 | i++; 64 | swap(arr[i],arr[j]); 65 | } 66 | } 67 | swap(arr[i+1], arr[high]); 68 | return (i+1); 69 | } -------------------------------------------------------------------------------- /Sorting/sort by absolute difference.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | // Function to sort the given array according to 10 | // the difference with K 11 | // A[]: input array 12 | // N: size of array 13 | int aa; 14 | bool comparator(int a, int b){ 15 | if(abs(a-aa) < abs(b-aa)){ 16 | return true; 17 | } 18 | return false; 19 | } 20 | void sortABS(int A[],int N, int k) 21 | { 22 | aa = k; 23 | stable_sort(A,A+N,comparator); 24 | 25 | } 26 | 27 | 28 | // { Driver Code Starts. 29 | 30 | int main() 31 | { 32 | int T; 33 | cin>> T; 34 | 35 | while (T--) 36 | { 37 | 38 | int N, diff; 39 | cin>>N>>diff; 40 | int A[N]; 41 | 42 | for(int i = 0; i>A[i]; 44 | 45 | sortABS(A, N, diff); 46 | 47 | for(int & val : A) 48 | cout< 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | 9 | //arr1,arr2 : the arrays 10 | // n, m: size of arrays 11 | void merge(vector& v, int arr1[], int arr2[], int n, int m){ 12 | int i=0,j=0; 13 | while(i&arr){ 24 | // for(int i:arr) 25 | // cout< findUnion(int arr1[], int arr2[], int n, int m) 44 | { 45 | vectorv; 46 | merge(v,arr1,arr2,n,m); 47 | circumsize(v); 48 | return v; 49 | } 50 | 51 | // { Driver Code Starts. 52 | 53 | int main() { 54 | 55 | int T; 56 | cin >> T; 57 | 58 | while(T--){ 59 | 60 | 61 | 62 | int N, M; 63 | cin >>N >> M; 64 | 65 | int arr1[N]; 66 | int arr2[M]; 67 | 68 | for(int i = 0;i> arr1[i]; 70 | } 71 | 72 | for(int i = 0;i> arr2[i]; 74 | } 75 | 76 | vector ans = findUnion(arr1,arr2, N, M); 77 | for(int i: ans)cout< 2 | using namespace std; 3 | 4 | // function to check if paranthesis are balanced 5 | bool areParanthesisBalanced(string expr) 6 | { 7 | stack s; 8 | char x; 9 | 10 | // Traversing the Expression 11 | for (int i = 0; i < expr.length(); i++) 12 | { 13 | if (expr[i] == '(' || expr[i] == '[' 14 | || expr[i] == '{') 15 | { 16 | // Push the element in the stack 17 | s.push(expr[i]); 18 | continue; 19 | } 20 | 21 | // IF current current character is not opening 22 | // bracket, then it must be closing. So stack 23 | // cannot be empty at this point. 24 | if (s.empty()) 25 | return false; 26 | 27 | switch (expr[i]) { 28 | case ')': 29 | 30 | // Store the top element in a 31 | x = s.top(); 32 | s.pop(); 33 | if (x == '{' || x == '[') 34 | return false; 35 | break; 36 | 37 | case '}': 38 | 39 | // Store the top element in b 40 | x = s.top(); 41 | s.pop(); 42 | if (x == '(' || x == '[') 43 | return false; 44 | break; 45 | 46 | case ']': 47 | 48 | // Store the top element in c 49 | x = s.top(); 50 | s.pop(); 51 | if (x == '(' || x == '{') 52 | return false; 53 | break; 54 | } 55 | } 56 | 57 | // Check Empty Stack 58 | return (s.empty()); 59 | } 60 | 61 | // Driver code 62 | int main() 63 | { 64 | string expr = "{()}[]"; 65 | 66 | // Function call 67 | if (areParanthesisBalanced(expr)) 68 | cout << "Balanced"; 69 | else 70 | cout << "Not Balanced"; 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Stack/ReverseStringUsingStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A structure to represent a stack 5 | class Stack 6 | { 7 | public: 8 | int top; 9 | unsigned capacity; 10 | char* array; 11 | }; 12 | 13 | // function to create a stack of given 14 | // capacity. It initializes size of stack as 0 15 | Stack* createStack(unsigned capacity) 16 | { 17 | Stack* stack = new Stack(); 18 | stack->capacity = capacity; 19 | stack->top = -1; 20 | stack->array = new char[(stack->capacity * sizeof(char))]; 21 | return stack; 22 | } 23 | 24 | // Stack is full when top is equal to the last index 25 | int isFull(Stack* stack) 26 | { return stack->top == stack->capacity - 1; } 27 | 28 | // Stack is empty when top is equal to -1 29 | int isEmpty(Stack* stack) 30 | { return stack->top == -1; } 31 | 32 | // Function to add an item to stack. 33 | // It increases top by 1 34 | void push(Stack* stack, char item) 35 | { 36 | if (isFull(stack)) 37 | return; 38 | stack->array[++stack->top] = item; 39 | } 40 | 41 | // Function to remove an item from stack. 42 | // It decreases top by 1 43 | char pop(Stack* stack) 44 | { 45 | if (isEmpty(stack)) 46 | return -1; 47 | return stack->array[stack->top--]; 48 | } 49 | 50 | // A stack based function to reverse a string 51 | void reverse(char str[]) 52 | { 53 | // Create a stack of capacity 54 | //equal to length of string 55 | int n = strlen(str); 56 | Stack* stack = createStack(n); 57 | 58 | // Push all characters of string to stack 59 | int i; 60 | for (i = 0; i < n; i++) 61 | push(stack, str[i]); 62 | 63 | // Pop all characters of string and 64 | // put them back to str 65 | for (i = 0; i < n; i++) 66 | str[i] = pop(stack); 67 | } 68 | 69 | // Driver code 70 | int main() 71 | { 72 | char str[] = "GeeksQuiz"; 73 | 74 | reverse(str); 75 | cout << "Reversed string is " << str; 76 | 77 | return 0; 78 | } 79 | 80 | // This code is contributed by rathbhupendra 81 | -------------------------------------------------------------------------------- /Stack/STACK_USING_2_QUEUES.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class QueueStack{ 5 | private: 6 | queue q1; 7 | queue q2; 8 | public: 9 | void push(int); 10 | int pop(); 11 | }; 12 | 13 | 14 | int main() 15 | { 16 | int T; 17 | cin>>T; 18 | while(T--) 19 | { 20 | QueueStack *qs = new QueueStack(); 21 | 22 | int Q; 23 | cin>>Q; 24 | while(Q--){ 25 | int QueryType=0; 26 | cin>>QueryType; 27 | if(QueryType==1) 28 | { 29 | int a; 30 | cin>>a; 31 | qs->push(a); 32 | }else if(QueryType==2){ 33 | cout<pop()<<" "; 34 | 35 | } 36 | } 37 | cout< q1; 47 | queue q2; 48 | public: 49 | void push(int); 50 | int pop(); 51 | }; 52 | */ 53 | 54 | /* The method push to push element into the stack */ 55 | void QueueStack :: push(int x) 56 | { 57 | // Your Code 58 | q2.push(x); 59 | 60 | while(!q1.empty()){ 61 | 62 | q2.push(q1.front()); 63 | q1.pop(); 64 | 65 | 66 | } 67 | while(!q2.empty()){ 68 | q1.push(q2.front()); 69 | q2.pop(); 70 | 71 | 72 | } 73 | 74 | 75 | } 76 | 77 | /*The method pop which return the element poped out of the stack*/ 78 | int QueueStack :: pop() 79 | { if(q1.empty()) 80 | return -1; 81 | 82 | int t1=q1.front(); 83 | q1.pop(); 84 | return(t1); 85 | } 86 | -------------------------------------------------------------------------------- /Stack/buildStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define max 100 4 | int stack[max], top=-1; 5 | void push(int val) 6 | { 7 | cout<<"Enter value to be pushed:"<>val; 9 | if(top>=max-1) 10 | cout<<"Stack Overflow"<=0) 30 | { 31 | cout<<"Stack elements are:"; 32 | for(int i=top; i>=0; i--) 33 | cout<>ch; 59 | switch(ch) { 60 | case 1: { 61 | 62 | push(val); 63 | break; 64 | } 65 | case 2: { 66 | pop(); 67 | break; 68 | } 69 | case 3: { 70 | display(); 71 | break; 72 | } 73 | case 4: { 74 | cout<<"Exit"<>t; 11 | 12 | while(t--) 13 | 14 | { 15 | 16 | int count=0; 17 | 18 | string s,p; 19 | 20 | cin>>s; 21 | cin>>p; 22 | 23 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main(){ 5 | string str = "geeksforgeeks"; 6 | // for(int i=0;i 2 | using namespace std; 3 | 4 | int longRepSubseq(string a){ 5 | int n = a.length(); 6 | 7 | //initialize DP table 8 | int dp[n+1][n+1]; 9 | memset(dp,0,sizeof(dp)); 10 | 11 | for (int i=1; i<=n; i++){ 12 | for (int j=1; j<=n; j++){ 13 | // Characters match but indexes are not same 14 | if (a[i-1] == a[j-1] && i != j) 15 | dp[i][j] = 1 + dp[i-1][j-1]; 16 | //characters do not match 17 | else 18 | dp[i][j] = max(dp[i][j-1], dp[i-1][j]); 19 | } 20 | } 21 | return dp[n][n]; 22 | } 23 | 24 | int main(){ 25 | string a = "aabbcdee"; 26 | cout << "Length of Largest Repeating Subsequence is "<< longRepSubseq(a); 27 | return 0; 28 | } -------------------------------------------------------------------------------- /Strings/longest_common_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //find length of longest common subsequence 5 | int lcs(string a,string b,int m,int n) { 6 | 7 | int dp[m + 1][n + 1]; 8 | for (int i = 0; i <= m; i++) { 9 | for (int j = 0; j <= n; j++) { 10 | //dp[i][j] contains lcs of string a(0..i) and b(0..j) 11 | if (i == 0 || j == 0) 12 | dp[i][j] = 0; 13 | else if (a[i - 1] == b[j - 1]) 14 | dp[i][j] = dp[i - 1][j - 1] + 1; 15 | else 16 | dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); 17 | } 18 | } 19 | return dp[m][n]; 20 | } 21 | 22 | 23 | int main() { 24 | //desired strings are taken 25 | string a = "longest"; 26 | string b = "longsequence"; 27 | 28 | int m = a.size(); 29 | int n = b.size(); 30 | 31 | //Print the length of longest common subsequence 32 | cout << "The length of Longest Common Subsequence is " << lcs(a,b,m,n); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Strings/rabin_karp.cpp: -------------------------------------------------------------------------------- 1 | /* Program is a C++ implementation of Rabin Karp */ 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | // d is the number of characters in the input alphabet 8 | #define d 256 9 | 10 | /* pat -> pattern 11 | txt -> text 12 | q -> A prime number 13 | */ 14 | void search(char pat[], char txt[], int q) 15 | { 16 | int M = strlen(pat); 17 | int N = strlen(txt); 18 | int i, j; 19 | int p = 0; // hash value for pattern 20 | int t = 0; // hash value for txt 21 | int h = 1; 22 | 23 | // The value of h would be "pow(d, M-1)%q" 24 | for (i = 0; i < M - 1; i++) 25 | h = (h * d) % q; 26 | 27 | // Calculate the hash value of pattern and first 28 | // window of text 29 | for (i = 0; i < M; i++) 30 | { 31 | p = (d * p + pat[i]) % q; 32 | t = (d * t + txt[i]) % q; 33 | } 34 | 35 | // Slide the pattern over text one by one 36 | for (i = 0; i <= N - M; i++) 37 | { 38 | 39 | /* Check the hash values of current window of text 40 | and pattern. If the hash values match then only 41 | check for characters on by one */ 42 | if ( p == t ) 43 | { 44 | /* Check for characters one by one */ 45 | for (j = 0; j < M; j++) 46 | { 47 | if (txt[i+j] != pat[j]) 48 | break; 49 | } 50 | 51 | // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] 52 | if (j == M) 53 | cout<<"Pattern found at index "<< i< 2 | using namespace std; 3 | 4 | int main(){ 5 | string str; 6 | cout<<"Enter your name "; 7 | getline(cin,str); 8 | cout<<"Enter your name is "< 2 | using namespace std; 3 | 4 | void reverseWords(string s){ 5 | int start = 0; 6 | for(int end= 0;end mp; 8 | 9 | for(auto it: s){ 10 | mp[it]++; 11 | } 12 | 13 | for(int i=0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class edge 8 | { 9 | public: 10 | int nbr; 11 | int wt; 12 | }; 13 | 14 | vector> graph; 15 | 16 | void addedge(int v1, int v2, int wt) 17 | { 18 | 19 | edge e1; 20 | e1.nbr = v2; 21 | e1.wt = wt; 22 | graph[v1].push_back(e1); 23 | 24 | edge e2; 25 | e2.nbr = v1; 26 | e2.wt = wt; 27 | graph[v2].push_back(e2); 28 | } 29 | 30 | class dpair 31 | { 32 | public: 33 | int v; 34 | int cost; 35 | string psf; 36 | 37 | dpair(int a,int b,string s) 38 | { 39 | v=a; 40 | cost=b; 41 | psf=s; 42 | } 43 | dpair() 44 | { 45 | 46 | } 47 | 48 | bool operator>(const dpair &other)const 49 | { 50 | return cost > other.cost; 51 | } 52 | 53 | }; 54 | 55 | 56 | void djikstra(int n) 57 | { 58 | priority_queue,greater> pq; 59 | vector check(graph.size(),false); 60 | dpair dp(n,0,to_string(n)); 61 | 62 | pq.push(dp); 63 | 64 | while(pq.size()>0) 65 | { 66 | dpair temp=pq.top(); 67 | pq.pop(); 68 | 69 | if(check[temp.v]==true){ 70 | continue; 71 | } 72 | 73 | check[temp.v]=true; 74 | 75 | 76 | cout<()); 100 | graph.push_back(vector()); 101 | graph.push_back(vector()); 102 | graph.push_back(vector()); 103 | graph.push_back(vector()); 104 | graph.push_back(vector()); 105 | graph.push_back(vector()); 106 | 107 | addedge(0, 1, 10); 108 | addedge(1, 2, 10); 109 | addedge(2, 3, 10); 110 | addedge(0, 3, 40); 111 | addedge(3, 4, 2); 112 | addedge(4, 5, 3); 113 | addedge(5, 6, 3); 114 | addedge(4, 6, 8); 115 | 116 | djikstra(0); 117 | 118 | 119 | } -------------------------------------------------------------------------------- /graph/floyd_warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | constexpr int kGraphSize = 5; 6 | constexpr int kInf = 10000; 7 | 8 | void floydWarshall(int graph[kGraphSize][kGraphSize], int out[kGraphSize][kGraphSize]) 9 | { 10 | for (int i = 0; i < kGraphSize; i++) 11 | for (int j = 0; j < kGraphSize; j++) 12 | out[i][j] = graph[i][j]; 13 | 14 | for (int k = 0; k < kGraphSize; k++) 15 | { 16 | for (int i = 0; i < kGraphSize; i++) 17 | { 18 | for (int j = 0; j < kGraphSize; j++) 19 | { 20 | out[i][j] = min(out[i][j], out[i][k] + out[k][j]); 21 | } 22 | } 23 | } 24 | } 25 | 26 | int main() 27 | { 28 | int graph[kGraphSize][kGraphSize] = 29 | {{0, 3, kInf, kInf, 2}, 30 | {kInf, 0, 3, kInf, 4}, 31 | {1, kInf, 0, 1, 3}, 32 | {kInf, 2, kInf, 0, kInf}, 33 | {4, 5, kInf, kInf, 0}}; 34 | int result[kGraphSize][kGraphSize]; 35 | floydWarshall(graph, result); 36 | return 0; 37 | } -------------------------------------------------------------------------------- /graph/lagrange_interpolation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | float x[100], y[100], xp, yp=0, p; 8 | int i,j,n; 9 | 10 | cout<<"Enter number of data: "; 11 | cin>>n; 12 | cout<<"Enter data:"<< endl; 13 | for(i=1;i<=n;i++) 14 | { 15 | cout<<"x["<< i<<"] = "; 16 | cin>>x[i]; 17 | cout<<"y["<< i<<"] = "; 18 | cin>>y[i]; 19 | } 20 | cout<<"Enter interpolation point: "; 21 | cin>>xp; 22 | 23 | /* Implementing Lagrange Interpolation */ 24 | for(i=1;i<=n;i++) 25 | { 26 | p=1; 27 | for(j=1;j<=n;j++) 28 | { 29 | if(i!=j) 30 | { 31 | p = p* (xp - x[j])/(x[i] - x[j]); 32 | } 33 | } 34 | yp = yp + p * y[i]; 35 | } 36 | cout<< endl<<"Interpolated value at "<< xp<< " is "<< yp; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /graph/newton-raphson-method.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | float fn(float x) 5 | { 6 | return pow(x,2)+(3*x)+1 ; 7 | } 8 | float de(float x) 9 | { 10 | return 2*x + 3 ; 11 | } 12 | int main() 13 | { float a,e=0,z; 14 | cout<<"Enter Number "; 15 | cin>>a; 16 | do 17 | { e++; 18 | z=a-(fn(a)/de(a)); 19 | cout<<"The iterative "<0.001); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /min_operations_tp_make_all_element_equal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int operation(int arr[], int N){ 5 | 6 | unordered_map mp; 7 | int max_count = 0; 8 | 9 | for(int i=0;i