From 3726e715622455b768e4dc7618bd8f2bad84533b Mon Sep 17 00:00:00 2001 From: komaljoshi252 <55447267+komaljoshi252@users.noreply.github.com> Date: Sat, 2 Oct 2021 19:31:50 +0530 Subject: [PATCH 001/142] Add files via upload --- Algorithms/job_sequencing.cpp | 224 ++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 Algorithms/job_sequencing.cpp diff --git a/Algorithms/job_sequencing.cpp b/Algorithms/job_sequencing.cpp new file mode 100644 index 0000000..9a88c29 --- /dev/null +++ b/Algorithms/job_sequencing.cpp @@ -0,0 +1,224 @@ +#include + +#include + +#define MAX 100 + +#include + +#include + +using namespace std; + +class Job + +{ + +public : +char id[5]; + int deadline; + int Profit; + +}; + +void jobSequencing(Job jobs[],int n); + +int minvalue(int x,int y) + +{ + +if(x>n; + +for(i=0;i>jobs[i].id; + +cout<< "\nEnter the Profit:"; + +cin>>jobs[i].Profit; + +cout<<"\nEnter deadline:"; + +cin>>jobs[i].deadline; + + + +} + +Job temp; + +cout<<"\nJob(i)\t\t Profit\t\t Deadline\t \n\n"; + +cout<<"--------------------------------------------------"; + +for(i=0;ijobs[j].Profit) + +{ + +temp=jobs[j+1]; + +jobs[j+1]=jobs[j];// descending order + +jobs[j]=temp; + +} + +} + +} + +cout<<"\n\nTotal nuber of jobs:"<dmax) + +{ + +dmax =jobs[i].deadline; + +} + + + + + +} + + + +cout<<"\nTotal time slot: "<=1) + +{ + +if(timeslot[k]==-1) + +{ + +timeslot[k]=i-1; + +filledTimeSlot++; + +break; + +} + +k--; + +} + +if(filledTimeSlot==dmax) + +{ + + break; + +} + +} + +// cout<<"\nJobs done \:n"; + +for(i=1;i<=dmax;i++) + +{ + +cout<<"\tJob"< Date: Sat, 2 Oct 2021 20:29:42 +0530 Subject: [PATCH 002/142] Fix: Unstructured code Making this code readable, Before it looks ugly and has some spacing in it. --- Algorithms/job_sequencing.cpp | 197 ++++++++++++++++------------------ 1 file changed, 94 insertions(+), 103 deletions(-) diff --git a/Algorithms/job_sequencing.cpp b/Algorithms/job_sequencing.cpp index 9a88c29..7c5dd6c 100644 --- a/Algorithms/job_sequencing.cpp +++ b/Algorithms/job_sequencing.cpp @@ -14,211 +14,202 @@ class Job { -public : -char id[5]; - int deadline; - int Profit; + public: + char id[5]; + int deadline; + int Profit; }; -void jobSequencing(Job jobs[],int n); +void jobSequencing(Job jobs[], int n); -int minvalue(int x,int y) +int minvalue(int x, int y) { -if(x> n; -cout<<"\Enter the number of jobs:"; + for (i = 0; i < n; i++) -cin>>n; + { -for(i=0;i> jobs[i].id; -cin>>jobs[i].id; + cout << "\nEnter the Profit:"; -cout<< "\nEnter the Profit:"; + cin >> jobs[i].Profit; -cin>>jobs[i].Profit; + cout << "\nEnter deadline:"; -cout<<"\nEnter deadline:"; + cin >> jobs[i].deadline; -cin>>jobs[i].deadline; + } + Job temp; + cout << "\nJob(i)\t\t Profit\t\t Deadline\t \n\n"; -} + cout << "--------------------------------------------------"; -Job temp; + for (i = 0; i < n; i++) -cout<<"\nJob(i)\t\t Profit\t\t Deadline\t \n\n"; + { -cout<<"--------------------------------------------------"; + cout << "\n\n"; -for(i=0;ijobs[j].Profit) + if (jobs[j + 1].Profit > jobs[j].Profit) -{ + { -temp=jobs[j+1]; + temp = jobs[j + 1]; -jobs[j+1]=jobs[j];// descending order + jobs[j + 1] = jobs[j]; // descending order -jobs[j]=temp; + jobs[j] = temp; -} + } -} + } -} + } -cout<<"\n\nTotal nuber of jobs:"<dmax) + int filledTimeSlot = 0; -{ + int dmax = 0; -dmax =jobs[i].deadline; + for (i = 0; i < n; i++) -} + { + if (jobs[i].deadline > dmax) + { + dmax = jobs[i].deadline; + } + } -} + cout << "\nTotal time slot: " << dmax << endl; -cout<<"\nTotal time slot: "<=1) + while (k >= 1) -{ + { -if(timeslot[k]==-1) + if (timeslot[k] == -1) -{ + { -timeslot[k]=i-1; + timeslot[k] = i - 1; -filledTimeSlot++; + filledTimeSlot++; -break; + break; -} + } -k--; + k--; -} + } -if(filledTimeSlot==dmax) + if (filledTimeSlot == dmax) -{ + { - break; + break; -} + } -} + } -// cout<<"\nJobs done \:n"; + // cout<<"\nJobs done \:n"; -for(i=1;i<=dmax;i++) + for (i = 1; i <= dmax; i++) -{ + { -cout<<"\tJob"< Date: Sat, 2 Oct 2021 21:19:00 +0530 Subject: [PATCH 003/142] Create maxprofit.py --- Competitive programming/PYTHON/maxprofit.py | 35 +++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Competitive programming/PYTHON/maxprofit.py diff --git a/Competitive programming/PYTHON/maxprofit.py b/Competitive programming/PYTHON/maxprofit.py new file mode 100644 index 0000000..d85c6e0 --- /dev/null +++ b/Competitive programming/PYTHON/maxprofit.py @@ -0,0 +1,35 @@ +liStocks = [100, 180, 260, 310, 40, 535, 695] + +#find local minima +def findMin(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val < liStocks[i+1]: + return i, val + return -1, -1 + +#find local maxima +def findMax(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val > liStocks[i+1]: + return i, val + return i+1, liStocks[-1] + + + +def buySellStock(): + index=0 + while index < len(liStocks): + i, val = findMin(liStocks[index:]) + if i > -1: + index=i+index + print("bye stock on day ", index+1, val) + else: + break + + i, val = findMax(liStocks[index:]) + index=i+index + print("sell stock on day ", index+1, val) + + +if __name__ == "__main__": + buySellStock() From 81e5acb74f9e6997eaaf9bd91bc8d9557129c96f Mon Sep 17 00:00:00 2001 From: Yush Chaudhary <47343850+YushChaudhary@users.noreply.github.com> Date: Sat, 2 Oct 2021 21:26:21 +0530 Subject: [PATCH 004/142] Create Find an Element in an array.py Finding the element in the array. --- .../PYTHON/Find an Element in an array.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Competitive programming/PYTHON/Find an Element in an array.py diff --git a/Competitive programming/PYTHON/Find an Element in an array.py b/Competitive programming/PYTHON/Find an Element in an array.py new file mode 100644 index 0000000..5d2a2d1 --- /dev/null +++ b/Competitive programming/PYTHON/Find an Element in an array.py @@ -0,0 +1,5 @@ +# Question is how to find a element in an array + +from array import* +my_array = array('i',[10001,1001,1122,15423]) +print(my_array.index(1122) From cad7d6053e6579822aaddf74e289a12d79dfeb8b Mon Sep 17 00:00:00 2001 From: Lokender10 <71983411+Lokender10@users.noreply.github.com> Date: Sat, 2 Oct 2021 22:32:23 +0530 Subject: [PATCH 005/142] Create Mergesort.cpp --- Algorithms/Mergesort.cpp | 94 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Algorithms/Mergesort.cpp diff --git a/Algorithms/Mergesort.cpp b/Algorithms/Mergesort.cpp new file mode 100644 index 0000000..d68570b --- /dev/null +++ b/Algorithms/Mergesort.cpp @@ -0,0 +1,94 @@ +// C++ program for Merge Sort +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(int array[], int const left, int const mid, int const right) +{ + auto const subArrayOne = mid - left + 1; + auto const subArrayTwo = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArrayOne], + *rightArray = new int[subArrayTwo]; + + // Copy data to temp arrays leftArray[] and rightArray[] + for (auto i = 0; i < subArrayOne; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArrayTwo; j++) + rightArray[j] = array[mid + 1 + j]; + + auto indexOfSubArrayOne = 0, // Initial index of first sub-array + indexOfSubArrayTwo = 0; // Initial index of second sub-array + int indexOfMergedArray = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) { + if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) { + array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + } + else { + array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + } + indexOfMergedArray++; + } + // Copy the remaining elements of + // left[], if there are any + while (indexOfSubArrayOne < subArrayOne) { + array[indexOfMergedArray] = leftArray[indexOfSubArrayOne]; + indexOfSubArrayOne++; + indexOfMergedArray++; + } + // Copy the remaining elements of + // right[], if there are any + while (indexOfSubArrayTwo < subArrayTwo) { + array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo]; + indexOfSubArrayTwo++; + indexOfMergedArray++; + } +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(int array[], int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// UTILITY FUNCTIONS +// Function to print an array +void printArray(int A[], int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int arr[] = { 12, 11, 13, 5, 6, 7 }; + auto arr_size = sizeof(arr) / sizeof(arr[0]); + + cout << "Given array is \n"; + printArray(arr, arr_size); + + mergeSort(arr, 0, arr_size - 1); + + cout << "\nSorted array is \n"; + printArray(arr, arr_size); + return 0; +} + +// This code is contributed by Mayank Tyagi +// This code was revised by Joshua Estes From 2ed4fe7ebd0ae7847a472464fa8cd39562c65d15 Mon Sep 17 00:00:00 2001 From: Lokender10 <71983411+Lokender10@users.noreply.github.com> Date: Sat, 2 Oct 2021 23:13:34 +0530 Subject: [PATCH 006/142] Create Quicksort.cpp --- Algorithms/Quicksort.cpp | 73 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Algorithms/Quicksort.cpp diff --git a/Algorithms/Quicksort.cpp b/Algorithms/Quicksort.cpp new file mode 100644 index 0000000..c077bd4 --- /dev/null +++ b/Algorithms/Quicksort.cpp @@ -0,0 +1,73 @@ +/* C implementation QuickSort */ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = sizeof(arr)/sizeof(arr[0]); + quickSort(arr, 0, n-1); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} From 444b6dd81c34562769c046a3f7831e20decf2edb Mon Sep 17 00:00:00 2001 From: 04018002718 <91694473+04018002718@users.noreply.github.com> Date: Sat, 2 Oct 2021 23:32:19 +0530 Subject: [PATCH 007/142] Create Union of Two Sorted Arrays.cpp --- .../C++/Union of Two Sorted Arrays.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Competitive programming/C++/Union of Two Sorted Arrays.cpp diff --git a/Competitive programming/C++/Union of Two Sorted Arrays.cpp b/Competitive programming/C++/Union of Two Sorted Arrays.cpp new file mode 100644 index 0000000..20786a7 --- /dev/null +++ b/Competitive programming/C++/Union of Two Sorted Arrays.cpp @@ -0,0 +1,63 @@ +#include +using namespace std; + + + // } Driver Code Ends +class Solution{ + public: + //arr1,arr2 : the arrays + // n, m: size of arrays + //Function to return a list containing the union of the two arrays. + vector findUnion(int arr1[], int arr2[], int n, int m) + { + //Your code here - rahul + //return vector with correct order of elements + vector vec; + int arr3[n+m]; + for(int i=0 ; i> T; + + while(T--){ + + + + int N, M; + cin >>N >> M; + + int arr1[N]; + int arr2[M]; + + for(int i = 0;i> arr1[i]; + } + + for(int i = 0;i> arr2[i]; + } + Solution ob; + vector ans = ob.findUnion(arr1,arr2, N, M); + for(int i: ans)cout< Date: Sat, 2 Oct 2021 23:35:07 +0530 Subject: [PATCH 008/142] Create SHUFFLIN.cpp https://www.codechef.com/SEPT21C/problems/SHUFFLIN --- .../C++/Shuffling Parities/SHUFFLIN.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp diff --git a/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp b/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp new file mode 100644 index 0000000..dfca2c6 --- /dev/null +++ b/Competitive programming/C++/Shuffling Parities/SHUFFLIN.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +int main() { + int t,i,j,k;; + cin>>t; + while(t--) + { + int n,c=0; + cin>>n; + int A[n]; + for(i=1;i<=n;i++) + { + cin>>A[i]; + } + for(i=1;i<=n;i++) + { + if(i%2==1) + { + for(j=1;j<=n;j++) + { + if(A[j]>0) + { + if(A[j]%2==0) + { + c++; + A[j]=0; + break; + } + } + } + } + else if(i%2==0) + { + for(j=1;j<=n;j++) + { + if(A[j]>0) + { + if(A[j]%2==1) + { + c++; + A[j]=0; + break; + } + } + } + } + + } + cout< Date: Sat, 2 Oct 2021 23:41:56 +0530 Subject: [PATCH 009/142] Create Tower Of Hanoi.cpp --- Algorithms/Tower Of Hanoi.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Algorithms/Tower Of Hanoi.cpp diff --git a/Algorithms/Tower Of Hanoi.cpp b/Algorithms/Tower Of Hanoi.cpp new file mode 100644 index 0000000..947a465 --- /dev/null +++ b/Algorithms/Tower Of Hanoi.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +void TOH(int n,char a,char b,char c) +{ + if(n==1) + { + cout<<"Move Disk "< Date: Sun, 3 Oct 2021 00:17:10 +0600 Subject: [PATCH 010/142] Create mergesort.py Python program for implementation of MergeSort. --- Algorithms/mergesort.py | 78 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Algorithms/mergesort.py diff --git a/Algorithms/mergesort.py b/Algorithms/mergesort.py new file mode 100644 index 0000000..40d32d1 --- /dev/null +++ b/Algorithms/mergesort.py @@ -0,0 +1,78 @@ + +# Merges two subarrays of arr[]. +# First subarray is arr[l..m] +# Second subarray is arr[m+1..r] + + +def merge(arr, l, m, r): + n1 = m - l + 1 + n2 = r - m + + # create temp arrays + L = [0] * (n1) + R = [0] * (n2) + + # Copy data to temp arrays L[] and R[] + for i in range(0, n1): + L[i] = arr[l + i] + + for j in range(0, n2): + R[j] = arr[m + 1 + j] + + # Merge the temp arrays back into arr[l..r] + i = 0 # Initial index of first subarray + j = 0 # Initial index of second subarray + k = l # Initial index of merged subarray + + while i < n1 and j < n2: + if L[i] <= R[j]: + arr[k] = L[i] + i += 1 + else: + arr[k] = R[j] + j += 1 + k += 1 + + # Copy the remaining elements of L[], if there + # are any + while i < n1: + arr[k] = L[i] + i += 1 + k += 1 + + # Copy the remaining elements of R[], if there + # are any + while j < n2: + arr[k] = R[j] + j += 1 + k += 1 + +# l is for left index and r is right index of the +# sub-array of arr to be sorted + + +def mergeSort(arr, l, r): + if l < r: + + # Same as (l+r)//2, but avoids overflow for + # large l and h + m = l+(r-l)//2 + + # Sort first and second halves + mergeSort(arr, l, m) + mergeSort(arr, m+1, r) + merge(arr, l, m, r) + + +# Driver code to test above +arr = [12, 11, 13, 5, 6, 7] +n = len(arr) +print("Given array is") +for i in range(n): + print("%d" % arr[i]), + +mergeSort(arr, 0, n-1) +print("\n\nSorted array is") +for i in range(n): + print("%d" % arr[i]), + From 17b877490ec2e1d9684fd6bcf93caf75d94f6f47 Mon Sep 17 00:00:00 2001 From: Dhruv Garg Date: Sat, 2 Oct 2021 23:48:04 +0530 Subject: [PATCH 011/142] Median of 2 Sorted Arrays --- .../C++/median_of_2_sorted_arrays.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Competitive programming/C++/median_of_2_sorted_arrays.cpp diff --git a/Competitive programming/C++/median_of_2_sorted_arrays.cpp b/Competitive programming/C++/median_of_2_sorted_arrays.cpp new file mode 100644 index 0000000..fd69fa0 --- /dev/null +++ b/Competitive programming/C++/median_of_2_sorted_arrays.cpp @@ -0,0 +1,53 @@ +#include +typedef long long int ll; +using namespace std; + +double findMedianSortedArrays(vector& nums1, vector& nums2) { + int n1 = nums1.size(); + int n2 = nums2.size(); + + if (n2 < n1) return findMedianSortedArrays(nums2, nums1); + + int lo = 0; + int hi = n1; + + while (lo<=hi) { + int partitionX = (lo+hi)/2; + int partitionY = (n1+n2+1)/2 - partitionX; + + int maxLeftX = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1]; + int minRightX = (partitionX == n1) ? INT_MAX : nums1[partitionX]; + + int maxLeftY = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1]; + int minRightY = (partitionY == n2) ? INT_MAX : nums2[partitionY]; + + if (maxLeftX <= minRightY and maxLeftY <= minRightX) { // Correct Partition + if ((n1 + n2) % 2 == 0) // Even + return double(max(maxLeftX, maxLeftY) + min(minRightX, minRightY))/2; + else + return double(max(maxLeftX, maxLeftY)); + } + else if (maxLeftX > minRightY) hi = partitionX - 1; + else lo = partitionX + 1; + } + return -1; +} + +int main() { + + int n1, n2; + cin >> n1 >> n2; + + vector nums1(n1), nums2(n2); + + for (int i = 0; i < n1; i++) { + cin >> nums1[i]; + } + for (int i = 0; i < n2; i++) { + cin >> nums2[i]; + } + + cout << "Median = " << findMedianSortedArrays(nums1, nums2); + + return 0; +} From cd4061f511b14d17b4b2d33be91ede74e0f8110d Mon Sep 17 00:00:00 2001 From: Pritam Rane Date: Sat, 2 Oct 2021 23:48:15 +0530 Subject: [PATCH 012/142] Radix Sort --- Algorithms/Radixsort.cpp | 75 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Algorithms/Radixsort.cpp diff --git a/Algorithms/Radixsort.cpp b/Algorithms/Radixsort.cpp new file mode 100644 index 0000000..6db9d2d --- /dev/null +++ b/Algorithms/Radixsort.cpp @@ -0,0 +1,75 @@ +// C++ implementation of Radix Sort +#include +using namespace std; + +// A utility function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = {0}; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) + { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} From 6385619a952842fd3a19f0c9ba634b18e2125d62 Mon Sep 17 00:00:00 2001 From: jayesh_user Date: Sat, 2 Oct 2021 23:58:25 +0530 Subject: [PATCH 013/142] CPP selection sort --- Algorithms/selectionSort.cpp | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Algorithms/selectionSort.cpp diff --git a/Algorithms/selectionSort.cpp b/Algorithms/selectionSort.cpp new file mode 100644 index 0000000..3681b3c --- /dev/null +++ b/Algorithms/selectionSort.cpp @@ -0,0 +1,49 @@ +#include +#define MAX 50 + +using namespace std; + +void swap1(int &x, int &y){ + int temp = x; + x = y; + y = temp; +} + +void selectionSort(int arr[], int n){ + int minindex; + for (int i = 0; i < n-1; i++){ + minindex = i; + for(int j = i+1; j < n; j++){ + if(arr[j] < arr[minindex]){ + minindex = j; + } + } + if(minindex != i){ + swap1(arr[i], arr[minindex]); + } + } +} + +void print1(int arr[], int n){ + cout<<"After Sorting:"<> n; + for(int i=0; i>arr[i]; + } + cout<<"Before Sorting: "< Date: Sat, 2 Oct 2021 23:58:30 +0530 Subject: [PATCH 014/142] Create FakeGCD.cpp --- Competitive programming/C++/FakeGCD.cpp | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Competitive programming/C++/FakeGCD.cpp diff --git a/Competitive programming/C++/FakeGCD.cpp b/Competitive programming/C++/FakeGCD.cpp new file mode 100644 index 0000000..f87ec4a --- /dev/null +++ b/Competitive programming/C++/FakeGCD.cpp @@ -0,0 +1,26 @@ +// This is the link to the problem : https://www.codechef.com/COOK133C/problems/FAKEGCD +// Below is my solution +#include +using namespace std; + +int main() { + int t; + cin >> t; + + while(t--) + { + int n; + cin >> n; + + int k=1; + + for(int i=0; i Date: Sun, 3 Oct 2021 00:00:44 +0530 Subject: [PATCH 015/142] Create FAKESWAP.py --- Competitive programming/PYTHON/FAKESWAP.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Competitive programming/PYTHON/FAKESWAP.py diff --git a/Competitive programming/PYTHON/FAKESWAP.py b/Competitive programming/PYTHON/FAKESWAP.py new file mode 100644 index 0000000..7ef2527 --- /dev/null +++ b/Competitive programming/PYTHON/FAKESWAP.py @@ -0,0 +1,19 @@ +# The link to the problem is : https://www.codechef.com/COOK133C/problems/FAKESWAP +# Below is my solution +for i in range(int(input())): + a=int(input()) + b=input() + c=input() + d=e=0 + if b==c: + print("YES") + else: + for i in range(a): + if c[i]=='1': + d+=1 + else: + e+=1 + if d>0 and e>0: + print("YES") + else: + print("NO") From 218d01a983cf5b713787512676d1c2b547a1669f Mon Sep 17 00:00:00 2001 From: drishyadamodaran <56961626+drishyadamodaran@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:04:03 +0530 Subject: [PATCH 016/142] Create README.md --- CompanywiseSolution/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 CompanywiseSolution/README.md diff --git a/CompanywiseSolution/README.md b/CompanywiseSolution/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/CompanywiseSolution/README.md @@ -0,0 +1 @@ + From 87e1a70705c6146ac4a44fff42f9977abb04b6a3 Mon Sep 17 00:00:00 2001 From: imsushant12 Date: Sun, 3 Oct 2021 00:06:07 +0530 Subject: [PATCH 017/142] added merge-sort in C language - iterative and recuursive --- Algorithms/Merge_Sort-Iterative.c | 72 +++++++++++++++++++++++++++++++ Algorithms/Merge_Sort-Recursive.c | 66 ++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 Algorithms/Merge_Sort-Iterative.c create mode 100644 Algorithms/Merge_Sort-Recursive.c diff --git a/Algorithms/Merge_Sort-Iterative.c b/Algorithms/Merge_Sort-Iterative.c new file mode 100644 index 0000000..028dec3 --- /dev/null +++ b/Algorithms/Merge_Sort-Iterative.c @@ -0,0 +1,72 @@ +#include +#include + + +//merging of sub-sorted array +void merging(int a[] , int low , int mid , int high) +{ + int i,j,k; + i = low; + j = mid+1; + k = low; + int b[100]; + while(i <= mid && j <= high) + { + if(a[i] < a[j]) + b[k++] = a[i++]; + else + b[k++] = a[j++]; + } + + for( ; i <=mid ; i++) + b[k++]=a[i]; + + for( ; j <= high ; j++) + b[k++]=a[j]; + + for(i=0 ; i <= high ; i++) + a[i] = b[i]; +} + +void merge_sort(int a[] , int n) +{ + int p,l,h,m,i; + + //this for loop will take account of number of passes + //in each pass number of elements is increasing by previous*2; + for(p=2 ; p <= n ; p=p*2) + { + for(i=0 ; i+p-1 < n ; i=i+p) //for choosing number of elements in each pass + { + l = i; + h = i+p-1; + m = (l+h)/2; + merging(a , l , m , h); + } + } + if(p/2 < n) //when number of elements is odd + merging(a , 0 , p/2 , n-1); +} + + +int main() +{ + int i,n; + + printf("\nEnter total number of elements of array : "); + scanf("%d",&n); + + int a[n]; + + printf("\nEnter elements of array :\n"); + for(i=0 ; i < n ; i++) + scanf("%d" , &a[i]); + + merge_sort(a , n); + + printf("\n\nMerged array is : \n"); + for(i=0 ; i < n ; i++) + printf("%d " , a[i]); + + return 0; +} diff --git a/Algorithms/Merge_Sort-Recursive.c b/Algorithms/Merge_Sort-Recursive.c new file mode 100644 index 0000000..01f0227 --- /dev/null +++ b/Algorithms/Merge_Sort-Recursive.c @@ -0,0 +1,66 @@ +#include +#include + +void merging(int a[] , int low , int mid , int high) +{ + int i,j,k; + i = low; + j = mid+1; + k = low; + int b[100]; + while(i <= mid && j <= high) + { + if(a[i] < a[j]) + b[k++] = a[i++]; + else + b[k++] = a[j++]; + } + + for( ; i <= mid ; i++) + b[k++]=a[i]; + + for( ; j <= high ; j++) + b[k++]=a[j]; + + for(i=0 ; i <= high ; i++) + a[i] = b[i]; +} + +void merge_sort(int a[] , int l , int h) +{ + int mid; + if(l < h) //will check if at least 2 elements are there + { + mid = (l+h)/2; + merge_sort(a , l , mid); + merge_sort(a , mid+1 , h); + merging(a , l , mid , h); + } +} + + +int main() +{ + int i,n,low,high; + + printf("\nEnter total number of elements of array : "); + scanf("%d",&n); + + int a[n]; + + low=0; + high=n-1; + + printf("\nEnter elements of array :\n"); + for(i=0 ; i < n ; i++) + scanf("%d" , &a[i]); + + merge_sort(a , low , high); + + printf("\n\nMerged array is : \n"); + for(i=0 ; i < n ; i++) + printf("%d " , a[i]); + + return 0; +} + From 022806504c59b08aa6f93285ecca5157b1c18401 Mon Sep 17 00:00:00 2001 From: R Nithish <64672533+nithishrcta@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:07:47 +0530 Subject: [PATCH 018/142] Added Matrix-Addition C Program - Added Matrix_Addition C Program to your Repository --- Competitive programming/C/matrix-addition.c | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Competitive programming/C/matrix-addition.c diff --git a/Competitive programming/C/matrix-addition.c b/Competitive programming/C/matrix-addition.c new file mode 100644 index 0000000..6d3b748 --- /dev/null +++ b/Competitive programming/C/matrix-addition.c @@ -0,0 +1,40 @@ +#include +int main() { + int r, c, a[100][100], b[100][100], sum[100][100], i, j; + printf("Enter the number of rows (between 1 and 100): "); + scanf("%d", &r); + printf("Enter the number of columns (between 1 and 100): "); + scanf("%d", &c); + + printf("\nEnter elements of 1st matrix:\n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("Enter element a%d%d: ", i + 1, j + 1); + scanf("%d", &a[i][j]); + } + + printf("Enter elements of 2nd matrix:\n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("Enter element b%d%d: ", i + 1, j + 1); + scanf("%d", &b[i][j]); + } + + + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + sum[i][j] = a[i][j] + b[i][j]; + } + + + printf("\nSum of two matrices: \n"); + for (i = 0; i < r; ++i) + for (j = 0; j < c; ++j) { + printf("%d ", sum[i][j]); + if (j == c - 1) { + printf("\n\n"); + } + } + + return 0; +} From e25d87f0bbbd0ae734b7e2ae00372208c6b5e04b Mon Sep 17 00:00:00 2001 From: abhishekprasad2384 <49679013+abhishekprasad2384@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:09:03 +0530 Subject: [PATCH 019/142] Create Split_Array_Largest_Sum.java --- .../JAVA/Split_Array_Largest_Sum.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Competitive programming/JAVA/Split_Array_Largest_Sum.java diff --git a/Competitive programming/JAVA/Split_Array_Largest_Sum.java b/Competitive programming/JAVA/Split_Array_Largest_Sum.java new file mode 100644 index 0000000..ce95148 --- /dev/null +++ b/Competitive programming/JAVA/Split_Array_Largest_Sum.java @@ -0,0 +1,38 @@ +//Leetcode-410 :Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. +//Write an algorithm to minimize the largest sum among these m subarrays. + + +//Solution :- +class Solution { + public int splitArray(int[] nums, int m) { + // Max ans = split 1 + //Min ans = split to the length + int start =0; + int end =0; + for(int i =0;imid){ + sum= num; + pices++; + } + else{ + sum+=num; + } + } + if(pices>m){ + start=mid+1; + }else + end= mid; + } + return end; + } +} From 674ef0b94981f0ec7c1ebe63711dc6c6cff3648f Mon Sep 17 00:00:00 2001 From: imsushant12 Date: Sun, 3 Oct 2021 00:10:42 +0530 Subject: [PATCH 020/142] added Binary Tree to DLL problem (GFG) in JAVA --- .../JAVA/Binary_Tree_to_DLL.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Competitive programming/JAVA/Binary_Tree_to_DLL.java diff --git a/Competitive programming/JAVA/Binary_Tree_to_DLL.java b/Competitive programming/JAVA/Binary_Tree_to_DLL.java new file mode 100644 index 0000000..8af339c --- /dev/null +++ b/Competitive programming/JAVA/Binary_Tree_to_DLL.java @@ -0,0 +1,58 @@ +/* +Problem Statement: +----------------- +Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as +previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. +The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. +Example 1: +-------- +Input: + 1 + / \ + 3 2 +Output: +3 1 2 +2 1 3 +Explanation: DLL would be 3<=>1<=>2 +Example 2: +--------- +Input: + 10 + / \ + 20 30 + / \ + 40 60 +Output: +40 20 60 10 30 +30 10 60 20 40 +Explanation: DLL would be 40<=>20<=>60<=>10<=>30. +Your Task: You don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter +and returns the head of DLL . The driver code prints the DLL both ways. +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(H). +Note: H is the height of the tree and this space is used implicitly for recursion stack. +*/ + +// Link --> https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1 + +// Code: +class Solution +{ + Node head; + Node bToDLL(Node root) + { + if(root == null) + return null; + + bToDLL(root.right); + root.right = head; + + if(head != null) + head.left = root; + + head = root; + bToDLL(root.left); + + return head; + } +} \ No newline at end of file From 54ac39191947916e6776ff054dd62db1077223fb Mon Sep 17 00:00:00 2001 From: jayesh_user Date: Sun, 3 Oct 2021 00:22:12 +0530 Subject: [PATCH 021/142] Binary Search --- Algorithms/binary search.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Algorithms/binary search.cpp diff --git a/Algorithms/binary search.cpp b/Algorithms/binary search.cpp new file mode 100644 index 0000000..45a4ee7 --- /dev/null +++ b/Algorithms/binary search.cpp @@ -0,0 +1,35 @@ + +// Binary Search in C++ + +#include +using namespace std; + +int binarySearch(int array[], int x, int low, int high) { + + // Repeat until the pointers low and high meet each other + while (low <= high) { + int mid = low + (high - low) / 2; + + if (array[mid] == x) + return mid; + + if (array[mid] < x) + low = mid + 1; + + else + high = mid - 1; + } + + return -1; +} + +int main(void) { + int array[] = {3, 4, 5, 6, 7, 8, 9}; + int x = 4; + int n = sizeof(array) / sizeof(array[0]); + int result = binarySearch(array, x, 0, n - 1); + if (result == -1) + printf("Not found"); + else + printf("Element is found at index %d", result); +} \ No newline at end of file From 635492e03b076d11f70647ab230b94f37746a8b3 Mon Sep 17 00:00:00 2001 From: drishyadamodaran <56961626+drishyadamodaran@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:25:39 +0530 Subject: [PATCH 022/142] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index ebc9e1b..11a9f86 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ + # hacktoberfest2021_CP +![image](https://user-images.githubusercontent.com/56961626/135728682-586fe6e3-7fe0-4ae7-b4df-6d5278f53688.png) + You can contribute here! ## Basics of Git and GitHub From d6d2cbba3d3e8f5c6f1dee12d212360c8278e08c Mon Sep 17 00:00:00 2001 From: shweta-kansal <72966734+shweta-kansal@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:26:14 +0530 Subject: [PATCH 023/142] Create kth largest element in array.cpp --- Algorithms/kth largest element in array.cpp | 35 +++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Algorithms/kth largest element in array.cpp diff --git a/Algorithms/kth largest element in array.cpp b/Algorithms/kth largest element in array.cpp new file mode 100644 index 0000000..5f7fb09 --- /dev/null +++ b/Algorithms/kth largest element in array.cpp @@ -0,0 +1,35 @@ +// Approach --- using min heap + +#include +using namespace std; + +int kthlargest(vectorv ,int k){ + + priority_queue,greater> minh; + for(int i=0;ik) + { + minh.pop(); + } + } + return minh.top(); +} + +int main(){ + + vectorv; + int k= 2 , ans; + + v.push_back(6); + v.push_back(5); + v.push_back(3); + v.push_back(2); + v.push_back(8); + v.push_back(10); + +ans= kthlargest(v,k); + cout< Date: Sun, 3 Oct 2021 00:40:04 +0530 Subject: [PATCH 024/142] Merge Sort in JavaScript --- Algorithms/Merge_Sort.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Algorithms/Merge_Sort.js diff --git a/Algorithms/Merge_Sort.js b/Algorithms/Merge_Sort.js new file mode 100644 index 0000000..8e31e44 --- /dev/null +++ b/Algorithms/Merge_Sort.js @@ -0,0 +1,24 @@ +function merge_sort(left_part,right_part) +{ + var i = 0; + var j = 0; + var results = []; + + while (i < left_part.length || j < right_part.length) { + if (i === left_part.length) { + // j is the only index left_part + results.push(right_part[j]); + j++; + } + else if (j === right_part.length || left_part[i] <= right_part[j]) { + results.push(left_part[i]); + i++; + } else { + results.push(right_part[j]); + j++; + } + } + return results; +} + +console.log(merge_sort([1,4,6], [8,2,9])); \ No newline at end of file From f9b3f0ed655451fbdbcff9abed33f9f0f71fb912 Mon Sep 17 00:00:00 2001 From: Arunim singhal <75484060+arunim-iiitlCS@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:45:49 +0530 Subject: [PATCH 025/142] Create Merge_Sort_Algo.java --- Algorithms/Merge_Sort_Algo.java | 70 +++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Algorithms/Merge_Sort_Algo.java diff --git a/Algorithms/Merge_Sort_Algo.java b/Algorithms/Merge_Sort_Algo.java new file mode 100644 index 0000000..65fd73c --- /dev/null +++ b/Algorithms/Merge_Sort_Algo.java @@ -0,0 +1,70 @@ +//contributed by arunim singhal +import java.util.Scanner; + +public class mergeSort { + void merge(int arr[], int beg, int mid, int end) { + + int l = mid - beg + 1; + int r = end - mid; + + int LeftArray[] = new int[l]; + int RightArray[] = new int[r]; + + for (int i = 0; i < l; ++i) + LeftArray[i] = arr[beg + i]; + + for (int j = 0; j < r; ++j) + RightArray[j] = arr[mid + 1 + j]; + + int i = 0, j = 0; + int k = beg; + while (i < l && j < r) { + if (LeftArray[i] <= RightArray[j]) { + arr[k] = LeftArray[i]; + i++; + } else { + arr[k] = RightArray[j]; + j++; + } + k++; + } + while (i < l) { + arr[k] = LeftArray[i]; + i++; + k++; + } + + while (j < r) { + arr[k] = RightArray[j]; + j++; + k++; + } + } + + void sort(int arr[], int beg, int end) { + if (beg < end) { + int mid = (beg + end) / 2; + sort(arr, beg, mid); + sort(arr, mid + 1, end); + merge(arr, beg, mid, end); + } + } + + public static void main(String args[]) { + int n; + Scanner sc = new Scanner(System.in); + n = sc.nextInt(); + int[] a = new int[10]; + for (int i = 0; i < n; i++) { + + a[i] = sc.nextInt(); + } + mergeSort ob = new mergeSort(); + ob.sort(a, 0, a.length - 1); + + System.out.println("\nSorted array"); + for (int i = 0; i < a.length; i++) { + System.out.print(a[i] + " "); + } + } +} From 4a03153909f44a8810385dc57d76686c3d368c2e Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 00:49:53 +0530 Subject: [PATCH 026/142] Added Maximum Subarray Sum problem Solution in C++ --- Maximum Subarray Sum | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Maximum Subarray Sum diff --git a/Maximum Subarray Sum b/Maximum Subarray Sum new file mode 100644 index 0000000..2212980 --- /dev/null +++ b/Maximum Subarray Sum @@ -0,0 +1,35 @@ +//Maximum Subarray Sum +//Using Kadane's Algorithm +//Time Complexity O(n) +#include + +using namespace std; + +int maxSubArraySum(int arr[],int n) +{ + int maxSum =0 ; + int currSum=0; + for(int i=0;imaxSum) + { + maxSum=currSum; + } + if(currSum<0) + { + currSum=0; + } + + } + return maxSum; +} +int main() +{ + int arr[] = {5,-4,-2,6,-1}; + int n = sizeof(arr)/sizeof(arr[0]); + int maxsum = maxSubArraySum(arr, n); + cout << "Maximum subarray sum is " << maxsum; + + return 0; +} From ef2d9f546fe46c5cca6dbb879ff139a60c8bb090 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 01:30:24 +0530 Subject: [PATCH 027/142] Create Stock Buy And Sell to Maximize Profit in C++ --- Stock Buy And Sell to Maximize Profit in C++ | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Stock Buy And Sell to Maximize Profit in C++ diff --git a/Stock Buy And Sell to Maximize Profit in C++ b/Stock Buy And Sell to Maximize Profit in C++ new file mode 100644 index 0000000..94c660b --- /dev/null +++ b/Stock Buy And Sell to Maximize Profit in C++ @@ -0,0 +1,30 @@ +//Time Complexity O(n) + +#include + +using namespace std; + +int stockBuySell(int arr[],int n) +{ + int max_profit =0; + int minSofar=arr[0]; + for(int i=0;i Date: Sun, 3 Oct 2021 01:30:39 +0530 Subject: [PATCH 028/142] Create Stock Buy Sell to Maximize Profit in C++ --- Stock Buy Sell to Maximize Profit in C++ | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Stock Buy Sell to Maximize Profit in C++ diff --git a/Stock Buy Sell to Maximize Profit in C++ b/Stock Buy Sell to Maximize Profit in C++ new file mode 100644 index 0000000..94c660b --- /dev/null +++ b/Stock Buy Sell to Maximize Profit in C++ @@ -0,0 +1,30 @@ +//Time Complexity O(n) + +#include + +using namespace std; + +int stockBuySell(int arr[],int n) +{ + int max_profit =0; + int minSofar=arr[0]; + for(int i=0;i Date: Sun, 3 Oct 2021 01:36:37 +0530 Subject: [PATCH 029/142] Added a question and solution in Company wise --- .../Find Duplicates in array/question.txt | 21 ++++++++++ .../Find Duplicates in array/solution.java | 38 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Find Duplicates in array/question.txt create mode 100644 CompanywiseSolution/Amazon/Find Duplicates in array/solution.java diff --git a/CompanywiseSolution/Amazon/Find Duplicates in array/question.txt b/CompanywiseSolution/Amazon/Find Duplicates in array/question.txt new file mode 100644 index 0000000..0f7f0a6 --- /dev/null +++ b/CompanywiseSolution/Amazon/Find Duplicates in array/question.txt @@ -0,0 +1,21 @@ +Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array. + +Example 1: + +Input: +N = 4 +a[] = {0,3,1,2} +Output: -1 +Explanation: N=4 and all elements from 0 +to (N-1 = 3) are present in the given +array. Therefore output is -1. + + +Example 2: + +Input: +N = 5 +a[] = {2,3,1,2,3} +Output: 2 3 +Explanation: 2 and 3 occur more than once +in the given array. \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Find Duplicates in array/solution.java b/CompanywiseSolution/Amazon/Find Duplicates in array/solution.java new file mode 100644 index 0000000..5b60182 --- /dev/null +++ b/CompanywiseSolution/Amazon/Find Duplicates in array/solution.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.Scanner; +import java.io.*; +class solution { + public static ArrayList duplicates(int arr[], int n) { + // code here + ArrayList ar=new ArrayList<>(); + for (int i = 0; i = arr.length * 2) { + ar.add(i); + } + } + if(ar.isEmpty()) + ar.add(-1); + return ar; + } + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.println("Enter length of array arr"); + int n=sc.nextInt(); + System.out.println("Enter an array"); + int arr[]=new int[n]; + for(int i=0;i ans=duplicates(arr,n); + for(Integer val:ans) + System.out.print(val+" "); + System.out.println(); + } +} \ No newline at end of file From cbdfa25537b143bbbf3d16c65b6156d8f267a13c Mon Sep 17 00:00:00 2001 From: debachaks <88777152+debachaks@users.noreply.github.com> Date: Sun, 3 Oct 2021 11:55:34 +0530 Subject: [PATCH 030/142] Create Bubble_sort.cpp --- Algorithms/Bubble_sort.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Algorithms/Bubble_sort.cpp diff --git a/Algorithms/Bubble_sort.cpp b/Algorithms/Bubble_sort.cpp new file mode 100644 index 0000000..e7f09f4 --- /dev/null +++ b/Algorithms/Bubble_sort.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +//Bubble sort : swap two elements walaa technique + +int main(){ + int n; + cin>>n; + int arr[n]; + for(int i=0;i>arr[i]; + } + + int counter = 1; + while(counterarr[i+1]){ + if(arr[i]>arr[i+1]){ + int temp=arr[i]; + arr[i]=arr[i+1]; + arr[i+1]=temp; + } + + } + } + counter++; + } + for(int i=0;i Date: Sun, 3 Oct 2021 12:30:03 +0530 Subject: [PATCH 031/142] BinarySearch Binary Search implementation in C --- Algorithms/BinarySearch | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Algorithms/BinarySearch diff --git a/Algorithms/BinarySearch b/Algorithms/BinarySearch new file mode 100644 index 0000000..503e167 --- /dev/null +++ b/Algorithms/BinarySearch @@ -0,0 +1,45 @@ +//srishti1302 +#include +#define COMPARE(x,y) ( (x)<(y)?-1:(x)==(y)? 0 :1 ) +int binsearch(int a[20],int k,int left,int right) +{ + + if(left Date: Sun, 3 Oct 2021 13:41:46 +0530 Subject: [PATCH 032/142] Update kth largest element in array.cpp --- Algorithms/kth largest element in array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Algorithms/kth largest element in array.cpp b/Algorithms/kth largest element in array.cpp index 5f7fb09..bc6e610 100644 --- a/Algorithms/kth largest element in array.cpp +++ b/Algorithms/kth largest element in array.cpp @@ -29,7 +29,7 @@ int main(){ v.push_back(10); ans= kthlargest(v,k); - cout< Date: Sun, 3 Oct 2021 16:09:09 +0530 Subject: [PATCH 033/142] New code kadane_algo.cpp C++ program to print largest contiguous array sum using KADANE ALGORITHM --- Algorithms/kadane_algo.cpp | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Algorithms/kadane_algo.cpp diff --git a/Algorithms/kadane_algo.cpp b/Algorithms/kadane_algo.cpp new file mode 100644 index 0000000..ec22554 --- /dev/null +++ b/Algorithms/kadane_algo.cpp @@ -0,0 +1,41 @@ +// C++ program to print largest contiguous array sum using KADANE ALGORITHM +#include +#include +using namespace std; + +int maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0, + start =0, end = 0, s=0; + + for (int i=0; i< size; i++ ) + { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) + { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) + { + max_ending_here = 0; + s = i + 1; + } + } + cout << "Maximum contiguous sum is " + << max_so_far << endl; + cout << "Starting index "<< start + << endl << "Ending index "<< end << endl; +} + +/*Driver program to test maxSubArraySum*/ +int main() +{ + int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; + int n = sizeof(a)/sizeof(a[0]); + int max_sum = maxSubArraySum(a, n); + return 0; +} From ababbe30595977107867dd66b40fd85ed0198d4f Mon Sep 17 00:00:00 2001 From: Mohit <71942407+mohit0204@users.noreply.github.com> Date: Sun, 3 Oct 2021 16:22:10 +0530 Subject: [PATCH 034/142] Create Search an element in sorted and rotated array.cpp --- ...an element in sorted and rotated array.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Competitive programming/C++/Search an element in sorted and rotated array.cpp diff --git a/Competitive programming/C++/Search an element in sorted and rotated array.cpp b/Competitive programming/C++/Search an element in sorted and rotated array.cpp new file mode 100644 index 0000000..03308a6 --- /dev/null +++ b/Competitive programming/C++/Search an element in sorted and rotated array.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +int Search(vector ,int ); + +int main(){ + + int t; + cin >> t; + + while(t--){ + int n; + cin >> n; + + vector vec(n); + + for(int i =0;i> vec[i]; + + int target; + cin >> target; + + cout << Search(vec,target) << "\n"; + + } +} + + +// vec : given vector of elements +// K : given value whose index we need to find +int Search(vector vec, int k) { + //code here - rahul + int low=0, mid; + int high=vec.size()-1; + while(low<=high) + { + mid=(low+high)/2; + if(vec[mid]==k) + return mid; + if(vec[low]<=vec[mid]) + { + if(k=vec[low]) + { high=mid-1; } + else + { low=mid+1; } + + } + else + { + if(k>vec[mid]&& k<=vec[high]) + { low=mid+1; } + else + { high=mid-1; } + } + + } + return -1; +} From 053fb6b4eb7625cbb6d06a18b6b8b296d1c0b324 Mon Sep 17 00:00:00 2001 From: atharvaka1996 <91828503+atharvaka1996@users.noreply.github.com> Date: Sun, 3 Oct 2021 16:35:20 +0530 Subject: [PATCH 035/142] Added Floyd Warshall Algorithm --- Algorithms/Floyd_Warshall.cpp | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Algorithms/Floyd_Warshall.cpp diff --git a/Algorithms/Floyd_Warshall.cpp b/Algorithms/Floyd_Warshall.cpp new file mode 100644 index 0000000..2001fef --- /dev/null +++ b/Algorithms/Floyd_Warshall.cpp @@ -0,0 +1,63 @@ +//Problem Statement +//The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. +//The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. +//Time Complexity: O(V^3) + +#include +using namespace std; + +vector> floyd_warshall(vector> graph) { + vector> dist(graph); + + int V = graph.size(); + + // Iterate over all phases 1,2,....,V + for(int k=0;k dist[i][k] + dist[k][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } + } + + //Check for negative edge cycle + for(int i=0;i> graph = { + {0,INT_MAX,-2,INT_MAX}, + {4,0,3,INT_MAX}, + {INT_MAX,INT_MAX,0,2}, + {INT_MAX,-1,INT_MAX,0} + }; + + auto it = floyd_warshall(graph); + + //The shortest path from ith node to jth node + for(int i=0;i Date: Sun, 3 Oct 2021 07:23:50 -0400 Subject: [PATCH 036/142] Factorial_calculator.cpp --- .../C++/Factorial_calculator.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Competitive programming/C++/Factorial_calculator.cpp diff --git a/Competitive programming/C++/Factorial_calculator.cpp b/Competitive programming/C++/Factorial_calculator.cpp new file mode 100644 index 0000000..60f1e3b --- /dev/null +++ b/Competitive programming/C++/Factorial_calculator.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() { + int n; + long double factorial = 1.0; + + cout << "Enter a positive integer: "; + cin >> n; + + if (n < 0) + cout << "Error! Factorial of a negative number doesn't exist."; + else { + for(int i = 1; i <= n; ++i) { + factorial *= i; + } + cout << "Factorial of " << n << " = " << factorial; + } + + return 0; +} From 3d224d2c75822edf9add258aab635878dcd2eb66 Mon Sep 17 00:00:00 2001 From: Saiyam7404 <91586337+Saiyam7404@users.noreply.github.com> Date: Sun, 3 Oct 2021 07:24:42 -0400 Subject: [PATCH 037/142] Reverse_a_number.cpp --- .../C++/Reverse_a_number.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Competitive programming/C++/Reverse_a_number.cpp diff --git a/Competitive programming/C++/Reverse_a_number.cpp b/Competitive programming/C++/Reverse_a_number.cpp new file mode 100644 index 0000000..33c5628 --- /dev/null +++ b/Competitive programming/C++/Reverse_a_number.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() { + int n, reversedNumber = 0, remainder; + + cout << "Enter an integer: "; + cin >> n; + + while(n != 0) { + remainder = n%10; + reversedNumber = reversedNumber*10 + remainder; + n /= 10; + } + + cout << "Reversed Number = " << reversedNumber; + + return 0; +} From 5cb3a453ade034873a73223ebc3482356203bad7 Mon Sep 17 00:00:00 2001 From: Harsh Kumar <72307191+harsh2k2@users.noreply.github.com> Date: Sun, 3 Oct 2021 16:59:59 +0530 Subject: [PATCH 038/142] Create generate_pattern.cpp --- .../C++/generate_pattern.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Competitive programming/C++/generate_pattern.cpp diff --git a/Competitive programming/C++/generate_pattern.cpp b/Competitive programming/C++/generate_pattern.cpp new file mode 100644 index 0000000..0d6c9f7 --- /dev/null +++ b/Competitive programming/C++/generate_pattern.cpp @@ -0,0 +1,23 @@ +// C++ code to demonstrate star pattern +#include +using namespace std; + +void pypart(int n) +{ + for (int i = n; i > 0; i--) { + + for (int j = 0; j < i; j++) { + + cout << "* "; + } + + cout << endl; + } +} + +int main() +{ + int n = 5; + pypart(n); + return 0; +} From 40f4c5675eba413a6c8bf64151b3e8d9330eec20 Mon Sep 17 00:00:00 2001 From: Richa-15 <91817502+Richa-15@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:17:41 +0530 Subject: [PATCH 039/142] merge sort implementation in c++ merge sort implementation in c++ using vectors --- merge_sort.cpp | 100 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 merge_sort.cpp diff --git a/merge_sort.cpp b/merge_sort.cpp new file mode 100644 index 0000000..527c4e7 --- /dev/null +++ b/merge_sort.cpp @@ -0,0 +1,100 @@ +// C++ program for Merge Sort +#include +#include +using namespace std; + +// Merges two subarrays of array[]. +// First subarray is arr[begin..mid] +// Second subarray is arr[mid+1..end] +void merge(vector& array, int const left, int const mid, int const right) +{ + auto const subArr1 = mid - left + 1; + auto const subArr2 = right - mid; + + // Create temp arrays + auto *leftArray = new int[subArr1], + *rightArray = new int[subArr2]; + + // Copying data to temp arrays + for (auto i = 0; i < subArr1; i++) + leftArray[i] = array[left + i]; + for (auto j = 0; j < subArr2; j++) + rightArray[j] = array[mid + 1 + j]; + + auto idxSubArr1 = 0, // Initial index of first sub-array + idxSubArr2 = 0; // Initial index of second sub-array + int idxMrgArr = left; // Initial index of merged array + + // Merge the temp arrays back into array[left..right] + while (idxSubArr1 < subArr1 && idxSubArr2 < subArr2) { + if (leftArray[idxSubArr1] <= rightArray[idxSubArr2]) { + array[idxMrgArr] = leftArray[idxSubArr1]; + idxSubArr1++; + } + else { + array[idxMrgArr] = rightArray[idxSubArr2]; + idxSubArr2++; + } + idxMrgArr++; + } + // Copy the remaining elements of + // left[], if there are any + while (idxSubArr1 < subArr1) { + array[idxMrgArr] = leftArray[idxSubArr1]; + idxSubArr1++; + idxMrgArr++; + } + // Copy the remaining elements of + // right[], if there are any + while (idxSubArr2 < subArr2) { + array[idxMrgArr] = rightArray[idxSubArr2]; + idxSubArr2++; + idxMrgArr++; + } +} + +// begin is for left index and end is +// right index of the sub-array +// of arr to be sorted */ +void mergeSort(vector& array, int const begin, int const end) +{ + if (begin >= end) + return; // Returns recursively + + auto mid = begin + (end - begin) / 2; + mergeSort(array, begin, mid); + mergeSort(array, mid + 1, end); + merge(array, begin, mid, end); +} + +// Function to print an array +void printArray(vector& A, int size) +{ + for (auto i = 0; i < size; i++) + cout << A[i] << " "; +} + +// Driver code +int main() +{ + int n, input; + cout<<"enter no. of array elements:"; + cin>> n; + + vector arr; + for (int i = 0; i < n; i++) + { + cin>> input; + arr.push_back(input); + } + + + cout << "Input array is: "; + printArray(arr, n); + + mergeSort(arr, 0, n - 1); + + cout << "\nSorted array is: "; + printArray(arr, n); + return 0; +} \ No newline at end of file From ad1fdc1da27136e789ad332ea730368c1f1baf2d Mon Sep 17 00:00:00 2001 From: avk29 <66971874+avk29@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:30:57 +0530 Subject: [PATCH 040/142] Create binary_search_Recursive.cpp --- Algorithms/binary_search_Recursive.cpp | 37 ++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Algorithms/binary_search_Recursive.cpp diff --git a/Algorithms/binary_search_Recursive.cpp b/Algorithms/binary_search_Recursive.cpp new file mode 100644 index 0000000..d9f9b31 --- /dev/null +++ b/Algorithms/binary_search_Recursive.cpp @@ -0,0 +1,37 @@ +int binsearch(int A[], int low, int high, int key){ + + if (low<=high){ + int mid = low + (high-low)/2; + + if(key== A[mid]){ + return mid; + } + + else if (key>m; + int A[m]; + + for(int i=0; i>A[i]; + } + //Example code to call the binary function + //cout< Date: Sun, 3 Oct 2021 17:34:27 +0530 Subject: [PATCH 041/142] Create heap_sort.cpp --- Algorithms/heap_sort.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Algorithms/heap_sort.cpp diff --git a/Algorithms/heap_sort.cpp b/Algorithms/heap_sort.cpp new file mode 100644 index 0000000..fc00de0 --- /dev/null +++ b/Algorithms/heap_sort.cpp @@ -0,0 +1,39 @@ +void heapify(int arr[], int n, int i) + { + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if(l arr[largest]) + largest = l; + + if(r arr[largest]) + largest = r; + + if(largest != i) + { + swap(arr[i], arr[largest]); + heapify(arr, n, largest); + } + + } + + +void buildHeap(int arr[], int n) + { + for(int i= (n/2)-1; i>=0; i--) + heapify(arr, n, i); + } + + +void heapSort(int arr[], int n) + { + buildHeap(arr, n); + for(int i= n-1; i>0; i--) + { + swap(arr[0], arr[i]); + heapify(arr, i, 0); + } + } + + From 6fcfc4e5609c7d3497fe0aec608ca0b8ed47f5fb Mon Sep 17 00:00:00 2001 From: avk29 <66971874+avk29@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:38:51 +0530 Subject: [PATCH 042/142] Create Deletion_in_Array.cpp --- Algorithms/Deletion_in_Array.cpp | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Algorithms/Deletion_in_Array.cpp diff --git a/Algorithms/Deletion_in_Array.cpp b/Algorithms/Deletion_in_Array.cpp new file mode 100644 index 0000000..2397b83 --- /dev/null +++ b/Algorithms/Deletion_in_Array.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + cout<<"Enter length of the array: "; + cin>>m; + int A[n]; + + for(int i=0; i>A[i]; + } + + //Example function call to delete 2nd element + arr_delete(A,2,m); + + display(A,m-1); + + return 0; + +} From c070f8c0fee61d6eaabe40de5b2214ebbe07f20a Mon Sep 17 00:00:00 2001 From: avk29 <66971874+avk29@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:40:45 +0530 Subject: [PATCH 043/142] Create Linear_Search.cpp --- Algorithms/Linear_Search.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Algorithms/Linear_Search.cpp diff --git a/Algorithms/Linear_Search.cpp b/Algorithms/Linear_Search.cpp new file mode 100644 index 0000000..c3aa58f --- /dev/null +++ b/Algorithms/Linear_Search.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + cout<<"Enter length of the array: "; + cin>>m; + int A[n]; + + for(int i=0; i>A[i]; + } + //Example function call for linear search + cout< Date: Sun, 3 Oct 2021 17:42:20 +0530 Subject: [PATCH 044/142] Create Merge_Two_Arrays.cpp --- Algorithms/Merge_Two_Arrays.cpp | 61 +++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Algorithms/Merge_Two_Arrays.cpp diff --git a/Algorithms/Merge_Two_Arrays.cpp b/Algorithms/Merge_Two_Arrays.cpp new file mode 100644 index 0000000..f998b88 --- /dev/null +++ b/Algorithms/Merge_Two_Arrays.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; + +int* merge(int A[], int m, int B[], int n) { + + int* C = new int[m+n]; + + int i=0, j=0, k=0; + + while (i>n; + + cout<<"Enter length of the array2: "; + cin>>m; + int A[n]; + int B[m]; + + for(int i=0; i>A[i]; + } + + for(int i=0; i>B[i]; + } + + int* C = merge(A,n,B,m); + display(C,m+n); + + return 0; +} From 4346227edb68152f9fb7836b30147875e69ed35f Mon Sep 17 00:00:00 2001 From: avk29 <66971874+avk29@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:43:41 +0530 Subject: [PATCH 045/142] Create Reverse_Array.cpp --- Algorithms/Reverse_Array.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Algorithms/Reverse_Array.cpp diff --git a/Algorithms/Reverse_Array.cpp b/Algorithms/Reverse_Array.cpp new file mode 100644 index 0000000..4b29f6d --- /dev/null +++ b/Algorithms/Reverse_Array.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +void display(int A[],int n){ + for(int i=0; i>n; + int A[n]; + + for(int i=0; i>A[i]; + } + + reverse(A,n); + display(A,n); + + return 0; +} From f0d3c8362f02f72f1183cc22a38d571a323c6d1b Mon Sep 17 00:00:00 2001 From: Varsha Gupta <89845598+varsha080@users.noreply.github.com> Date: Sun, 3 Oct 2021 17:58:15 +0530 Subject: [PATCH 046/142] Create insertion-sort.cpp --- Algorithms/insertion-sort.cpp | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/insertion-sort.cpp diff --git a/Algorithms/insertion-sort.cpp b/Algorithms/insertion-sort.cpp new file mode 100644 index 0000000..9e411ec --- /dev/null +++ b/Algorithms/insertion-sort.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} From 59d656ee08529de1a00e89f46f7b61a1f5c20964 Mon Sep 17 00:00:00 2001 From: Jay Patel <64847529+mr-jay-250@users.noreply.github.com> Date: Sun, 3 Oct 2021 18:54:09 +0530 Subject: [PATCH 047/142] Create RemoveDuplicatesFromaSortedLinkedList.cpp --- .../RemoveDuplicatesFromaSortedLinkedList.cpp | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp diff --git a/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp b/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp new file mode 100644 index 0000000..1f53a76 --- /dev/null +++ b/Algorithms/RemoveDuplicatesFromaSortedLinkedList.cpp @@ -0,0 +1,98 @@ +/* C++ Program to remove duplicates from a sorted linked list */ +#include +using namespace std; + +/* Link list node */ +class Node +{ + public: + int data; + Node* next; +}; + +/* The function removes duplicates from a sorted list */ +void removeDuplicates(Node* head) +{ + /* Pointer to traverse the linked list */ + Node* current = head; + + /* Pointer to store the next pointer of a node to be deleted*/ + Node* next_next; + + /* do nothing if the list is empty */ + if (current == NULL) + return; + + /* Traverse the list till last node */ + while (current->next != NULL) + { + /* Compare current node with next node */ + if (current->data == current->next->data) + { + /* The sequence of steps is important*/ + next_next = current->next->next; + free(current->next); + current->next = next_next; + } + else /* This is tricky: only advance if no deletion */ + { + current = current->next; + } + } +} + +/* UTILITY FUNCTIONS */ +/* Function to insert a node at the beginning of the linked list */ +void push(Node** head_ref, int new_data) +{ + /* allocate node */ + Node* new_node = new Node(); + + /* put in the data */ + new_node->data = new_data; + + /* link the old list off the new node */ + new_node->next = (*head_ref); + + /* move the head to point to the new node */ + (*head_ref) = new_node; +} + +/* Function to print nodes in a given linked list */ +void printList(Node *node) +{ + while (node!=NULL) + { + cout<<" "<data; + node = node->next; + } +} + +/* Driver program to test above functions*/ +int main() +{ + /* Start with the empty list */ + Node* head = NULL; + + /* Let us create a sorted linked list to test the functions + Created linked list will be 11->11->11->13->13->20 */ + push(&head, 20); + push(&head, 13); + push(&head, 13); + push(&head, 11); + push(&head, 11); + push(&head, 11); + + cout<<"Linked list before duplicate removal "; + printList(head); + + /* Remove duplicates from linked list */ + removeDuplicates(head); + + cout<<"\nLinked list after duplicate removal "; + printList(head); + + return 0; +} + +// This code is contributed by rathbhupendra From 066bf6f01004f69a2fe597289d9c13ab819c7fa9 Mon Sep 17 00:00:00 2001 From: pallavieee <76172609+pallavieee@users.noreply.github.com> Date: Sun, 3 Oct 2021 18:57:30 +0530 Subject: [PATCH 048/142] Create Matrix Multiplication.c Its a program for matrix multiplication for unknown numbers through c --- Matrix Multiplication.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Matrix Multiplication.c diff --git a/Matrix Multiplication.c b/Matrix Multiplication.c new file mode 100644 index 0000000..383b5fa --- /dev/null +++ b/Matrix Multiplication.c @@ -0,0 +1,38 @@ +//matrix multiplication // +#include +main() +{ + int a1,a2,a3; + printf ("enter a,b,c(m[a][b]&m[b][c]):\n"); + scanf("%d%d%d",&a1,&a2,&a3); + + int m1[a1][a2],m2[a2][a3],c[a1][a3]; + printf ("enter values of m[%d][%d]\n",a1,a2); + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a2;j++) + scanf("%d",&m1[i][j]); + } + printf ("\n enter values of m[%d][%d]\n",a2,a3); + for(int i=1;i<=a2;i++) + { + for(int j=1;j<=a3;j++) + scanf("%d",&m2[i][j]); + } + printf("MULTIPLICATION OF MATRIX :\n"); + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a3;j++) + { int x=0; + for(int k=1;k<=a2;k++) + x=x+(m1[i][k]*m2[k][j]); + c[i][j]=x; + } + } + for(int i=1;i<=a1;i++) + { + for(int j=1;j<=a3;j++) + printf("%d\t",c[i][j]); + printf("\n"); + } +} From c08d4038acb2b3bbf218cf9e04a355baf1b6afc2 Mon Sep 17 00:00:00 2001 From: morpheus521 <44001225+morpheus521@users.noreply.github.com> Date: Sun, 3 Oct 2021 18:59:36 +0530 Subject: [PATCH 049/142] Create Trie.cpp Trie implementation for insertion and checking for existing words --- Competitive programming/C++/Trie.cpp | 67 ++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Competitive programming/C++/Trie.cpp diff --git a/Competitive programming/C++/Trie.cpp b/Competitive programming/C++/Trie.cpp new file mode 100644 index 0000000..23ea24e --- /dev/null +++ b/Competitive programming/C++/Trie.cpp @@ -0,0 +1,67 @@ +#include +using namespace std; + +struct trie{ + struct trie* child[26]; + bool is_end; + trie(){ + memset(child,0,sizeof(child)); + is_end=false; + } +}; + +struct trie* root; +//inserts a word to the trie +void insert(string s){ + struct trie* temp=root; + //traverses over each character + //if the character already exists then it simply iterates over + //otherwise creates a new node and inserts the character + for(char c: s){ + if(!temp->child[c-'a']) + temp->child[c-'a']=new trie; + temp=temp->child[c-'a']; + } + //sets the last letter's boolean value to true + temp->is_end=true; +} +//returns true if the word exists, false otherwise +bool check(string s){ + struct trie* temp=root; + //iterates over the character of the word + for(char c: s){ + //if at any point the char of the word being check is not found it return false + if(!temp->child[c-'a']) + return false; + temp=temp->child[c-'a']; + } + //returns the last letters boolean value + return temp->is_end; +} + +int main(){ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + root=new trie; + int n; + cout << "Input the number of words in the List" << endl; + cin >> n; + string word; + cout<<"Enter the words"<> word ; + insert(word); + } + cout << "Enter the number of words you want to check exist in the List" << endl; + int m; + cin >> m; + //the words to be checked + for(int i=0; i> word ; + if(check(word)) + cout<< "This word exist in the list" < Date: Sun, 3 Oct 2021 19:00:22 +0530 Subject: [PATCH 050/142] Added z function algorithm It is used to find the number of occurrences of one string in another string. --- Algorithms/Z-Function.cpp | 53 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Algorithms/Z-Function.cpp diff --git a/Algorithms/Z-Function.cpp b/Algorithms/Z-Function.cpp new file mode 100644 index 0000000..4d96919 --- /dev/null +++ b/Algorithms/Z-Function.cpp @@ -0,0 +1,53 @@ +/* +Problem Statement:- + You are given two string a pattern(p) and a text(t) you want to find out + the number of occurrances of the pattern in text +*/ + +#include +#include + +using namespace std; + +vector z_function(string &p,string &t) +{ + string s=p+'#'+t; + int n=s.size(),l=0,r=0; //[l,r] is the current segment matching with the prefix + vector z(n,0); + for(int i=1;i length upto upper index bound + //z[i-l]--> previously matching segement length for prefix + + while(i+z[i]r) //i+z[i]-1 last index of the matching prefix pattern + l=i,r=i+z[i]-1; + } + return z; +} + +int main() +{ + string p,t; + cout<<"\nEnter a pattern : "; + cin>>p; + cout<<"\nEnter a text to be searched for the pattern : "; + cin>>t; + vector z=z_function(p,t); + vector ans; + for(int i=0;i Date: Sun, 3 Oct 2021 22:35:03 +0900 Subject: [PATCH 051/142] feat:add nqueen problem --- Competitive programming/PYTHON/N_Queen.py | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Competitive programming/PYTHON/N_Queen.py diff --git a/Competitive programming/PYTHON/N_Queen.py b/Competitive programming/PYTHON/N_Queen.py new file mode 100644 index 0000000..9f8381d --- /dev/null +++ b/Competitive programming/PYTHON/N_Queen.py @@ -0,0 +1,34 @@ +count = 0 + + +def solution(n): + board = [0] + visited = [False] * (n + 1) + queen(n, board, visited) + print(count) + + +def check(board, x): + for i in range(1, len(board)): + if abs(i - len(board)) == abs(board[i] - x): + return False + return True + + +def queen(n, board, visited): + global count + if len(board) == n + 1: + count += 1 + else: + for i in range(1, n + 1): + if not visited[i]: + if not check(board, i): + continue + board.append(i) + visited[i] = True + queen(n, board, visited) + visited[i] = False + board.pop() + +printf("how many?") +solution(int(input())) From fad1a889ebeede3849fffc22022186a9d77b20fb Mon Sep 17 00:00:00 2001 From: Abhishek <76660005+abhishek213-alb@users.noreply.github.com> Date: Sun, 3 Oct 2021 19:05:30 +0530 Subject: [PATCH 052/142] Create databse.cpp Stores data of students --- Competitive programming/C++/databse.cpp | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Competitive programming/C++/databse.cpp diff --git a/Competitive programming/C++/databse.cpp b/Competitive programming/C++/databse.cpp new file mode 100644 index 0000000..494e24d --- /dev/null +++ b/Competitive programming/C++/databse.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +struct student +{ + char name[50]; + int roll; + float marks; +}; + +int main() +{ + student s; + cout << "Enter information," << endl; + cout << "Enter name: "; + cin >> s.name; + cout << "Enter roll number: "; + cin >> s.roll; + cout << "Enter marks: "; + cin >> s.marks; + + cout << "\nDisplaying Information," << endl; + cout << "Name: " << s.name << endl; + cout << "Roll: " << s.roll << endl; + cout << "Marks: " << s.marks << endl; + return 0; +} From 8bb0a4384f838e2f0da7fde986f3550bc14ff2b0 Mon Sep 17 00:00:00 2001 From: VishalSehgal525 <81109477+VishalSehgal525@users.noreply.github.com> Date: Sun, 3 Oct 2021 19:12:21 +0530 Subject: [PATCH 053/142] Adding remove_duplicates_in_sorted_array.cpp --- .../remove_duplicates_in_sorted_array.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Algorithms/remove_duplicates_in_sorted_array.cpp diff --git a/Algorithms/remove_duplicates_in_sorted_array.cpp b/Algorithms/remove_duplicates_in_sorted_array.cpp new file mode 100644 index 0000000..7ffbecd --- /dev/null +++ b/Algorithms/remove_duplicates_in_sorted_array.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +int removeDuplicates(int arr[], int n) +{ + if (n==0 || n==1) + return n; + int temp[n]; + int j = 0; + for (int i=0; i>n; + int arr[n]; + for(int i = 0;i>arr[i]; + + n = removeDuplicates(arr, n); + + //Displaying updated array + for (int i=0; i Date: Sun, 3 Oct 2021 22:40:13 +0900 Subject: [PATCH 054/142] feat:add knight moves problem --- .../PYTHON/knight_moves.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Competitive programming/PYTHON/knight_moves.py diff --git a/Competitive programming/PYTHON/knight_moves.py b/Competitive programming/PYTHON/knight_moves.py new file mode 100644 index 0000000..e8cb8a1 --- /dev/null +++ b/Competitive programming/PYTHON/knight_moves.py @@ -0,0 +1,38 @@ + + +# input +#The input begins with the number n of scenarios on a single line by itself. +# Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 ≤ l ≤ 300). The entire board has size l × l. The second and third line contain pair of integers {0, ..., l−1}× {0, ..., l−1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario +# output +# For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal, distance is zero. The distance must be written on a single line. +import sys +from collections import deque + + +def solution(): + move = [[2, 1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1]] + IC = int(sys.stdin.readline()) + for _ in range(IC): + row = int(sys.stdin.readline()) + arr = [[0 for _ in range(row)] for _ in range(row)] + sy, sx = list(map(int, sys.stdin.readline().split())) + dy, dx = list(map(int, sys.stdin.readline().split())) + queue = deque() + queue.append((sy, sx)) + while queue: + cy, cx = queue.popleft() + if dx == cx and dy == cy: + print(arr[dy][dx]) + break + for i in range(8): + my = cy + move[i][0] + mx = cx + move[i][1] + if not (0 <= my and 0 <= mx and my < row and mx < row): + continue + if arr[my][mx]: + continue + arr[my][mx] = arr[cy][cx] + 1 + queue.append((my, mx)) + + +solution() From 2a62f79a8f5b4668542494704b48b066e92918c9 Mon Sep 17 00:00:00 2001 From: sooohka Date: Sun, 3 Oct 2021 22:45:19 +0900 Subject: [PATCH 055/142] feat:add knight moves problem --- Competitive programming/PYTHON/sdf | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Competitive programming/PYTHON/sdf diff --git a/Competitive programming/PYTHON/sdf b/Competitive programming/PYTHON/sdf new file mode 100644 index 0000000..e69de29 From fba6c47cc2b5f0a766534095ee0d3a02b695ec1d Mon Sep 17 00:00:00 2001 From: sooohka Date: Sun, 3 Oct 2021 22:45:36 +0900 Subject: [PATCH 056/142] feat:add knight moves problem --- Competitive programming/PYTHON/sdf | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Competitive programming/PYTHON/sdf diff --git a/Competitive programming/PYTHON/sdf b/Competitive programming/PYTHON/sdf deleted file mode 100644 index e69de29..0000000 From 9e9118f67a70407688fc44fb7d0fea844e995cbd Mon Sep 17 00:00:00 2001 From: YOUR NAME Date: Sun, 3 Oct 2021 19:37:25 +0530 Subject: [PATCH 057/142] Added autobiographical number --- .vscode/c_cpp_properties.json | 20 +++++++ .../PYTHON/Special Numbers/Auto_Bio.py | 60 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 Competitive programming/PYTHON/Special Numbers/Auto_Bio.py diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..9e3848d --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,20 @@ +{ + "configurations": [ + { + "name": "Win32", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [ + "_DEBUG", + "UNICODE", + "_UNICODE" + ], + "compilerPath": "C:\\MinGW\\bin\\gcc.exe", + "cStandard": "gnu17", + "cppStandard": "gnu++14", + "intelliSenseMode": "windows-gcc-x86" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py b/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py new file mode 100644 index 0000000..d4601f2 --- /dev/null +++ b/Competitive programming/PYTHON/Special Numbers/Auto_Bio.py @@ -0,0 +1,60 @@ +# Autobiographical numbers within range 0 to N +#An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. +#For example, 1210 has 1 zero, 2 ones, 1 two and 0 threes. + +from math import pow + +def isAutoBio(N): + +#Converting number to string for simpler execution + Str = str(N) + + for i in range(0, len(Str)): + +#Extracting character at each index and converting back to integer + index = int(Str[i]) + + c = 0 #counter variable for counting 0's,1's, and so on + + for j in range(0, len(Str)): + + num = int(Str[j]) + + # Check if equal to the index, if true then increment count + if num == i: + + #An Autobiographical number + c += 1 + + # Return false if counter and index not equal + if c != index: + + return False + + return True + +# Function to print autobiographical number + +def findAutoBios(n): + + + flag= 0 + + #print("********AUTOBIOGRAPHICAL NUMBERS IN THIS RANGE 0 TO ",n) + + for i in range(0,n+1): + + #Passing every number from 0 to n+1 to check for Autobiographical number + + if isAutoBio(i): + flag = 1 + print i,"is an autobiographical number\n" + + +# Driver Code + +if __name__ == "__main__": + + N = input("Please enter the max range\n") + + findAutoBios(N) \ No newline at end of file From a842405c644a2c80330334100697fb45abc119fb Mon Sep 17 00:00:00 2001 From: Srishti Agrawal Date: Sun, 3 Oct 2021 19:38:29 +0530 Subject: [PATCH 058/142] Mergesort Mergesort in java along with execution time --- Algorithms/Mergesort.java | 93 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Algorithms/Mergesort.java diff --git a/Algorithms/Mergesort.java b/Algorithms/Mergesort.java new file mode 100644 index 0000000..71458e6 --- /dev/null +++ b/Algorithms/Mergesort.java @@ -0,0 +1,93 @@ +//srishti1302 +import java.util.*; +public class MergeSort +{ + void merge(int arr[], int l, int m, int r) + { + int n1 = m - l + 1; + int n2 = r - m; + int L[] = new int [n1]; + int R[] = new int [n2]; + for (int i=0; i Date: Sun, 3 Oct 2021 19:40:47 +0530 Subject: [PATCH 059/142] moved merge sort program to Algorithms folder moved merge sort program to Algorithms folder. renamed file --- merge_sort.cpp => Algorithms/merge_sort_C++.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename merge_sort.cpp => Algorithms/merge_sort_C++.cpp (96%) diff --git a/merge_sort.cpp b/Algorithms/merge_sort_C++.cpp similarity index 96% rename from merge_sort.cpp rename to Algorithms/merge_sort_C++.cpp index 527c4e7..0cd202e 100644 --- a/merge_sort.cpp +++ b/Algorithms/merge_sort_C++.cpp @@ -97,4 +97,4 @@ int main() cout << "\nSorted array is: "; printArray(arr, n); return 0; -} \ No newline at end of file +} From 47ac6d1dd80b44a9edcd514ad8cbf4ed26cdf934 Mon Sep 17 00:00:00 2001 From: Vivekpusti Date: Sun, 3 Oct 2021 19:44:09 +0530 Subject: [PATCH 060/142] Create Longest_Harmonious_Subsequence.java --- .../JAVA/Longest_Harmonious_Subsequence.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Competitive programming/JAVA/Longest_Harmonious_Subsequence.java diff --git a/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java b/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java new file mode 100644 index 0000000..776c3b4 --- /dev/null +++ b/Competitive programming/JAVA/Longest_Harmonious_Subsequence.java @@ -0,0 +1,45 @@ + +/* +leetcode-Longest Harmonious Subsequence +Problem Statement: +----------------- +We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. +A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. + +Example 1: +Input: nums = [1,3,2,2,5,2,3,7] +Output: 5 +Explanation: The longest harmonious subsequence is [3,2,2,2,3]. + +Example 2: +Input: nums = [1,2,3,4] +Output: 2 +*/ +// Link -->https://leetcode.com/problems/longest-harmonious-subsequence/ + + + + + +// Code: + +class Solution { + public int findLHS(int[] nums) { + int rst = 0; + Map map = new HashMap<>(); + + // put the number and its occurence in the map + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + + // Traverse the map to get the longest harmonious subsequence + for (int key : map.keySet()) { + if (map.containsKey(key + 1)) { + rst = Math.max(rst, map.get(key) + map.get(key + 1)); + } + } + return rst; + } +} + From 0745cd2037d33cef466ff5a351ed7ae2793faf5b Mon Sep 17 00:00:00 2001 From: pallavieee <76172609+pallavieee@users.noreply.github.com> Date: Sun, 3 Oct 2021 20:02:02 +0530 Subject: [PATCH 061/142] Create Matrix multiplication.c --- .../C/Matrix multiplication.c | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Competitive programming/C/Matrix multiplication.c diff --git a/Competitive programming/C/Matrix multiplication.c b/Competitive programming/C/Matrix multiplication.c new file mode 100644 index 0000000..239b28a --- /dev/null +++ b/Competitive programming/C/Matrix multiplication.c @@ -0,0 +1,60 @@ +#include + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] Date: Sun, 3 Oct 2021 20:04:20 +0530 Subject: [PATCH 062/142] Create Matrixmultiplication.c --- .../C/Matrixmultiplication.c | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Competitive programming/C/Matrixmultiplication.c diff --git a/Competitive programming/C/Matrixmultiplication.c b/Competitive programming/C/Matrixmultiplication.c new file mode 100644 index 0000000..239b28a --- /dev/null +++ b/Competitive programming/C/Matrixmultiplication.c @@ -0,0 +1,60 @@ +#include + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] Date: Sun, 3 Oct 2021 20:04:26 +0530 Subject: [PATCH 063/142] added shellsort.cpp --- Algorithms/shellsort.cpp | 60 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Algorithms/shellsort.cpp diff --git a/Algorithms/shellsort.cpp b/Algorithms/shellsort.cpp new file mode 100644 index 0000000..79ecd22 --- /dev/null +++ b/Algorithms/shellsort.cpp @@ -0,0 +1,60 @@ +using namespace std; +#include + +void ShellSort(int sortedArray[], int size) +{ + for (int t = size / 2; t > 0; t /= 2) + { + for (int i = t; i < size; i++) + { + int temp = sortedArray[i]; + int j; + for (j = i; j >= t && sortedArray[j - t] > temp; j -= t) + { + sortedArray[j] = sortedArray[j - t]; + } + sortedArray[j] = temp; + } + } +} + +int main() +{ + int n; + cout << "Enter the size of the array "; + cin >> n; + int arr[n]; + cout << "Enter the elements in the array \n"; + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + cout << "\n"; + + cout << "Original Array "; + cout << "["; + for (int i = 0; i < n; i++) + { + cout << arr[i] << ", "; + } + cout << "\b\b"; + cout << "]"; + + cout << "\n"; + ShellSort(arr, n); + + cout << "Array after Shell Sort is "; + cout << "["; + for (int i = 0; i < n; i++) + { + cout << arr[i] << ", "; + } + cout << "\b\b"; + cout << "]"; + cout << endl; + + cout << "\n"; + + return 0; +} \ No newline at end of file From b67630b2351a35027875f3ccf24684ba682c8040 Mon Sep 17 00:00:00 2001 From: pallavieee <76172609+pallavieee@users.noreply.github.com> Date: Sun, 3 Oct 2021 20:05:54 +0530 Subject: [PATCH 064/142] Delete Matrix Multiplication.c --- Matrix Multiplication.c | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 Matrix Multiplication.c diff --git a/Matrix Multiplication.c b/Matrix Multiplication.c deleted file mode 100644 index 383b5fa..0000000 --- a/Matrix Multiplication.c +++ /dev/null @@ -1,38 +0,0 @@ -//matrix multiplication // -#include -main() -{ - int a1,a2,a3; - printf ("enter a,b,c(m[a][b]&m[b][c]):\n"); - scanf("%d%d%d",&a1,&a2,&a3); - - int m1[a1][a2],m2[a2][a3],c[a1][a3]; - printf ("enter values of m[%d][%d]\n",a1,a2); - for(int i=1;i<=a1;i++) - { - for(int j=1;j<=a2;j++) - scanf("%d",&m1[i][j]); - } - printf ("\n enter values of m[%d][%d]\n",a2,a3); - for(int i=1;i<=a2;i++) - { - for(int j=1;j<=a3;j++) - scanf("%d",&m2[i][j]); - } - printf("MULTIPLICATION OF MATRIX :\n"); - for(int i=1;i<=a1;i++) - { - for(int j=1;j<=a3;j++) - { int x=0; - for(int k=1;k<=a2;k++) - x=x+(m1[i][k]*m2[k][j]); - c[i][j]=x; - } - } - for(int i=1;i<=a1;i++) - { - for(int j=1;j<=a3;j++) - printf("%d\t",c[i][j]); - printf("\n"); - } -} From 2b0c2b8a7abe8a59bcb191846c98d644ec6fdc56 Mon Sep 17 00:00:00 2001 From: pallavieee <76172609+pallavieee@users.noreply.github.com> Date: Sun, 3 Oct 2021 20:06:16 +0530 Subject: [PATCH 065/142] Delete Matrixmultiplication.c --- .../C/Matrixmultiplication.c | 60 ------------------- 1 file changed, 60 deletions(-) delete mode 100644 Competitive programming/C/Matrixmultiplication.c diff --git a/Competitive programming/C/Matrixmultiplication.c b/Competitive programming/C/Matrixmultiplication.c deleted file mode 100644 index 239b28a..0000000 --- a/Competitive programming/C/Matrixmultiplication.c +++ /dev/null @@ -1,60 +0,0 @@ -#include - -void merge(int Array[],int iterator1,int j1,int iterator2,int j2) -{ - int TemporaryArray[50]; //array used for merging - int i,j,k; - i=iterator1; //beginning of the first list - j=iterator2; //beginning of the second list - k=0; - - while(i<=j1 && j<=j2) //while elements in both lists - { - if(Array[i] Date: Sun, 3 Oct 2021 16:49:03 +0200 Subject: [PATCH 066/142] Added FindElementInArray.cs to C# --- .../C#/FindElementInArray.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Competitive programming/C#/FindElementInArray.cs diff --git a/Competitive programming/C#/FindElementInArray.cs b/Competitive programming/C#/FindElementInArray.cs new file mode 100644 index 0000000..22c874e --- /dev/null +++ b/Competitive programming/C#/FindElementInArray.cs @@ -0,0 +1,31 @@ +# Question is how to find a element in an array + +using System; +using System.Linq; + + +public static class Extensions +{ + public static bool find(this T[] array, T target) { + return array.Contains(target); + } +} + +public class FindElement +{ + public static bool Find(int target, int[] array) + { + bool exists = array.find(target); + return exists; + } + + public static void Test() + { + int[] array = { 1, 2, 3, 4, 5 }; + + if(Find(4, array)) + { + Console.WriteLine("Found Element"); + } + } +} From 403ddc78719c01f87d64af0ae54e75092bad8d15 Mon Sep 17 00:00:00 2001 From: swapnil-092 <78612493+swapnil-092@users.noreply.github.com> Date: Sun, 3 Oct 2021 20:38:53 +0530 Subject: [PATCH 067/142] Competitive Code --- Algorithms/CreateHeap.cpp | 71 ++++++ Algorithms/Diagnolmatrix.cpp | 74 ++++++ Algorithms/HeapSort.c | 55 +++++ Algorithms/Heapify.cpp | 88 +++++++ Algorithms/InsertHeap.cpp | 61 +++++ Algorithms/Kruskal'sMinSpanningTree.cpp | 89 +++++++ Algorithms/LowerTriangularMatrix.cpp | 93 ++++++++ Algorithms/PrimsMinSpanningTree.cpp | 112 +++++++++ Algorithms/duplicate_elements_1.cpp | 38 +++ Algorithms/duplicate_elements_using_hash.cpp | 38 +++ Algorithms/missingelement.cpp | 31 +++ Algorithms/missingusinghash.cpp | 47 ++++ .../C++/InfixToPostfixUsingSTLStack.cpp | 121 ++++++++++ .../C++/PostfixEvaluation.cpp | 219 ++++++++++++++++++ Competitive programming/C++/Tree.cpp | 130 +++++++++++ ...xtended_balanced_parenthesis_using_STL.cpp | 68 ++++++ .../C++/parenthesismatching.cpp | 164 +++++++++++++ .../C++/stackLinkedList.cpp | 167 +++++++++++++ 18 files changed, 1666 insertions(+) create mode 100644 Algorithms/CreateHeap.cpp create mode 100644 Algorithms/Diagnolmatrix.cpp create mode 100644 Algorithms/HeapSort.c create mode 100644 Algorithms/Heapify.cpp create mode 100644 Algorithms/InsertHeap.cpp create mode 100644 Algorithms/Kruskal'sMinSpanningTree.cpp create mode 100644 Algorithms/LowerTriangularMatrix.cpp create mode 100644 Algorithms/PrimsMinSpanningTree.cpp create mode 100644 Algorithms/duplicate_elements_1.cpp create mode 100644 Algorithms/duplicate_elements_using_hash.cpp create mode 100644 Algorithms/missingelement.cpp create mode 100644 Algorithms/missingusinghash.cpp create mode 100644 Competitive programming/C++/InfixToPostfixUsingSTLStack.cpp create mode 100644 Competitive programming/C++/PostfixEvaluation.cpp create mode 100644 Competitive programming/C++/Tree.cpp create mode 100644 Competitive programming/C++/extended_balanced_parenthesis_using_STL.cpp create mode 100644 Competitive programming/C++/parenthesismatching.cpp create mode 100644 Competitive programming/C++/stackLinkedList.cpp diff --git a/Algorithms/CreateHeap.cpp b/Algorithms/CreateHeap.cpp new file mode 100644 index 0000000..0d7c763 --- /dev/null +++ b/Algorithms/CreateHeap.cpp @@ -0,0 +1,71 @@ +#include +#include + +using namespace std; + +void Insert(vector& vec, int key){ + // Insert key at the end + auto i = vec.size(); + vec.emplace_back(key); + + // Rearrange elements: O(log n) + while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ + vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + vec[i] = key; +} + +void InsertInplace(int A[], int n){ + int i = n; + int temp = A[n]; + while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ + A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + A[i] = temp; +} + +void CreateHeap(vector& vec, int A[], int n){ + // O(n log n) + for (int i=0; i +void Print(T& vec, int n, char c){ + cout << c << ": [" << flush; + for (int i=0; i v; + CreateHeap(v, b, sizeof(b)/sizeof(b[0])); + Print(v, v.size(), 'v'); + + cout << "Inplace Insert" << endl; + createHeap(b, sizeof(b)/sizeof(b[0])); + Print(b, sizeof(b)/sizeof(b[0]), 'b'); + + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Diagnolmatrix.cpp b/Algorithms/Diagnolmatrix.cpp new file mode 100644 index 0000000..58d6db7 --- /dev/null +++ b/Algorithms/Diagnolmatrix.cpp @@ -0,0 +1,74 @@ +#include +using namespace std; + +class Diagnol +{ +private: + int *A; + int n; +public: + Diagnol() + { + n=2; + A=new int[2]; + } + Diagnol(int n) + { + this->n=n; + A=new int[n]; + } + ~Diagnol() + { + delete []A; + } + void Set(int i, int j,int x); + int Get(int i, int j); + void Display(); +}; + +void Diagnol::Set(int i, int j,int x) +{ + if(i==j) + A[i-1]=x; +} + +int Diagnol::Get(int i, int j) +{ + if(i==j) + return A[i-1]; + else + return 0; +} + +void Diagnol::Display() +{ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + if(i==j) + cout< +void Insert(int A[], int n) +{ + int i = n, temp; + temp = A[i]; + while (i > 1 && temp > A[i / 2]) + { + A[i] = A[i / 2]; + i = i / 2; + } + A[i] = temp; +} +int Delete(int A[], int n) +{ + int i, j, x, temp, val; + val = A[1]; + x = A[n]; + A[1] = A[n]; + A[n] = val; + i = 1; + j = i * 2; + while (j <= n - 1) + { + if (j < n - 1 && A[j + 1] > A[j]) + j = j + 1; + if (A[i] < A[j]) + { + temp = A[i]; + A[i] = A[j]; + A[j] = temp; + i = j; + j = 2 * j; + } + else + break; + } + return val; +} +int main() +{ + int H[] = {0, 14, 15, 5, 20, 30, 8, 40}; + int i; + for (i = 2; i <= 7; i++) + Insert(H, i); + + for (i = 7; i > 1; i--) + { + Delete(H, i); + } + for (i = 1; i <= 7; i++) + printf("%d ", H[i]); + printf("\n"); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Heapify.cpp b/Algorithms/Heapify.cpp new file mode 100644 index 0000000..d2b8d1e --- /dev/null +++ b/Algorithms/Heapify.cpp @@ -0,0 +1,88 @@ +#include + +using namespace std; + +void swap(int A[], int i, int j){ + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; +} + +int Delete(int A[], int n){ + int x = A[0]; // Max element + A[0] = A[n-1]; + + int i = 0; + int j = 2 * i + 1; + + while (j < n-1){ + // Compare left and right children + if (A[j] < A[j+1]){ + j = j+1; + } + + // Compare parent and largest child + if (A[i] < A[j]){ + swap(A, i, j); + i = j; + j = 2 * i + 1; + } else { + break; + } + } + return x; +} + +void Heapify(int A[], int n){ + // # of leaf elements: (n+1)/2, index of last leaf element's parent = (n/2)-1 + for (int i=(n/2)-1; i>=0; i--){ + + int j = 2 * i + 1; // Left child for current i + + while(j < n-1){ + // Compare left and right children of current i + if (A[j] < A[j+1]){ + j = j+1; + } + + // Compare parent and largest child + if (A[i] < A[j]){ + swap(A, i, j); + i = j; + j = 2 * i + 1; + } else { + break; + } + } + } +} + +template +void Print(T& vec, int n, string s){ + cout << s << ": [" << flush; + for (int i=0; i +#include + +using namespace std; + +// Lecture based +void InsertA(int A[], int n){ + int i = n; + int temp = A[n]; + while (i > 0 && temp > A[i % 2 == 0 ? (i/2)-1 : i/2]){ + A[i] = A[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + A[i] = temp; +} + + +// STL vector based +void Insert(vector& vec, int key){ + // Insert key at the end + auto i = vec.size(); + vec.emplace_back(key); + + // Rearrange elements: Indices are not DRY :-( + while (i > 0 && key > vec[i % 2 == 0 ? (i/2)-1 : i/2]){ + vec[i] = vec[i % 2 == 0 ? (i/2)-1 : i/2]; + i = i % 2 == 0 ? (i/2)-1 : i/2; + } + vec[i] = key; +} + +template +void Print(T& vec, int n){ + cout << "Max Heap: [" << flush; + for (int i=0; i v = {45, 35, 15, 30, 10, 12, 6, 5, 20}; + Print(v, v.size()); + v.reserve(15); // Reserve space for 15 elements + + Insert(v, 50); + Print(v, v.size()); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/Kruskal'sMinSpanningTree.cpp b/Algorithms/Kruskal'sMinSpanningTree.cpp new file mode 100644 index 0000000..e7fc3c1 --- /dev/null +++ b/Algorithms/Kruskal'sMinSpanningTree.cpp @@ -0,0 +1,89 @@ +#include + +#define I 32767 // Infinity +#define V 7 // # of vertices in Graph +#define E 9 // # of edges in Graph + +using namespace std; + +void PrintMCST(int T[][V-1], int A[][E]){ + cout << "\nMinimum Cost Spanning Tree Edges\n" << endl; + for (int i {0}; i 0){ + x = s[x]; + } + + while (u != x){ + v = s[u]; + s[u] = x; + u = v; + } + return x; +} + +void KruskalsMCST(int A[3][9]){ + int T[2][V-1]; // Solution array + int track[E] {0}; // Track edges that are included in solution + int set[V+1] = {-1, -1, -1, -1, -1, -1, -1, -1}; // Array for finding cycle + + int i {0}; + while (i < V-1){ + int min = I; + int u {0}; + int v {0}; + int k {0}; + + // Find a minimum cost edge + for (int j {0}; j + +using namespace std; + +class LowerTri +{ +private: + int *A; + int n; +public: + LowerTri() + { + n=2; + A=new int[2*(2+1)/2]; + } + LowerTri(int n) + { + this->n=n; + A=new int[n*(n+1)/2]; + } + ~LowerTri() + { + delete []A; + } + void Set(int i, int j,int x); + int Get(int i, int j); + void Display(); + int GetDimension(){return n;} +}; + +void LowerTri::Set(int i, int j,int x) +{ + if(i>=j) + // A[i*(i-1)/2+j-1]=x; + A[n*(j-1)-(j-2)*(j-1)/2+i-j]=x; +} + +int LowerTri::Get(int i, int j) +{ + if(i>=j) + // return A[i*(i-1)/2+j-1]; + return A[n*(j-1)-(j-2)*(j-1)/2+i-j]; + return 0; +} + +void LowerTri::Display() +{ + for (int i = 1; i <= n; i++) + { + for (int j = 1; j <= n; j++) + { + if(i>=j) + // cout<>d; + + LowerTri lm(d); + + int x; + cout<<"Enter all elements"<>x; + lm.Set(i,j,x); + + } + + + } + + lm.Display(); + + + return 0; +} \ No newline at end of file diff --git a/Algorithms/PrimsMinSpanningTree.cpp b/Algorithms/PrimsMinSpanningTree.cpp new file mode 100644 index 0000000..d266a45 --- /dev/null +++ b/Algorithms/PrimsMinSpanningTree.cpp @@ -0,0 +1,112 @@ +#include +#define V 8 +#define I 32767 + +using namespace std; + +void PrintMST(int T[][V - 2], int G[V][V]) +{ + cout << "\nMinimum Spanning Tree Edges (w/ cost)\n" + << endl; + int sum{0}; + for (int i{0}; i < V - 2; i++) + { + int c = G[T[0][i]][T[1][i]]; + cout << "[" << T[0][i] << "]---[" << T[1][i] << "] cost: " << c << endl; + sum += c; + } + cout << endl; + cout << "Total cost of MST: " << sum << endl; +} + +void PrimsMST(int G[V][V], int n) +{ + int u; + int v; + int min{I}; + int track[V]; + int T[2][V - 2]{0}; + + // Initial: Find min cost edge + for (int i{1}; i < V; i++) + { + track[i] = I; // Initialize track array with INFINITY + for (int j{i}; j < V; j++) + { + if (G[i][j] < min) + { + min = G[i][j]; + u = i; + v = j; + } + } + } + T[0][0] = u; + T[1][0] = v; + track[u] = track[v] = 0; + + // Initialize track array to track min cost edges + for (int i{1}; i < V; i++) + { + if (track[i] != 0) + { + if (G[i][u] < G[i][v]) + { + track[i] = u; + } + else + { + track[i] = v; + } + } + } + + // Repeat + for (int i{1}; i < n - 1; i++) + { + int k; + min = I; + for (int j{1}; j < V; j++) + { + if (track[j] != 0 && G[j][track[j]] < min) + { + k = j; + min = G[j][track[j]]; + } + } + T[0][i] = k; + T[1][i] = track[k]; + track[k] = 0; + + // Update track array to track min cost edges + for (int j{1}; j < V; j++) + { + if (track[j] != 0 && G[j][k] < G[j][track[j]]) + { + track[j] = k; + } + } + } + PrintMST(T, G); +} + +int main() +{ + + int cost[V][V]{ + {I, I, I, I, I, I, I, I}, + {I, I, 25, I, I, I, 5, I}, + {I, 25, I, 12, I, I, I, 10}, + {I, I, 12, I, 8, I, I, I}, + {I, I, I, 8, I, 16, I, 14}, + {I, I, I, I, 16, I, 20, 18}, + {I, 5, I, I, I, 20, I, I}, + {I, I, 10, I, 14, 18, I, I}, + }; + + int n = sizeof(cost[0]) / sizeof(cost[0][0]) - 1; + + PrimsMST(cost, n); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/duplicate_elements_1.cpp b/Algorithms/duplicate_elements_1.cpp new file mode 100644 index 0000000..bdd0745 --- /dev/null +++ b/Algorithms/duplicate_elements_1.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() +{ + int n, i,j ,Ld=0; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + + for (int i = 0; i < n; i++) + { + if (A[i]==A[i+1] && A[i]!=Ld) + { + cout<<"Duplicates element are "< +using namespace std; + +int max(int A[], int n) +{ + int m = A[0]; + for (int i = 0; i < n; i++) + { + if (A[i] > m) + m = A[i]; + } + return m; +} + +int main() +{ + int n, i; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + + int h = max(A, n) + 1; + int *H = new int[h]; + for (i = 0; i < h; i++) + H[i] = 0; + for (i = 0; i < n; i++) + H[A[i]]++; + for (i = 0; i <= h; i++) + { + if (H[i] > 1) + cout << i << " occurs " << H[i] << " times" << endl; + } + + return 0; +} \ No newline at end of file diff --git a/Algorithms/missingelement.cpp b/Algorithms/missingelement.cpp new file mode 100644 index 0000000..26f9bc7 --- /dev/null +++ b/Algorithms/missingelement.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +int Missing_Elements_1(int A[]) +{ + int diff,l=A[0],i; + diff=l-0; + for (int i = 0; i < 10; i++) + { + if (A[i]-i!=diff) + { + while (diff +using namespace std; + +int max(int A[], int n) +{ + int m = A[0]; + for (int i = 0; i < n; i++) + { + if (A[i] > m) + m = A[i]; + } + return m; +} +int main() +{ + int n, i; + cout << "How many numbers? "; + cin >> n; + int A[n]; + cout << "Enter the numbers : "; + for (i = 0; i < n; i++) + cin >> A[i]; + cout << "The numbers are : "; + for (i = 0; i < n; i++) + cout << A[i] << " "; + cout << endl; + int l = A[0]; + int h = max(A, n) ; + int *H = new int[h]; + for (i = 0; i < h; i++) + H[i] = 0; + + cout << "The hash table is : "; + for (i = 0; i < h; i++) + cout << H[i] << " "; + + for (i = 0; i < n; i++) + H[A[i]]++; + cout << endl + << "Missing Elements" << endl; + for (i = 1; i <= h; i++) + { + if (H[i] == 0) + cout << i << " "; + } + cout << endl; +} diff --git a/Competitive programming/C++/InfixToPostfixUsingSTLStack.cpp b/Competitive programming/C++/InfixToPostfixUsingSTLStack.cpp new file mode 100644 index 0000000..052adb8 --- /dev/null +++ b/Competitive programming/C++/InfixToPostfixUsingSTLStack.cpp @@ -0,0 +1,121 @@ +/* Symbol OutstackPre InstackPre + +,- 1 2 + *,/ 3 4 + ^ 6 5 + ( 7 0 + ) 0 ? +*/ +#include +#include +#include + +using namespace std; + +int isOperand(char x) +{ + if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x == '(' || x == ')') + { + return 0; + } + return 1; +} + +int outPrecedence(char x) +{ + if (x == '+' || x == '-') + { + return 1; + } + else if (x == '*' || x == '/') + { + return 3; + } + else if (x == '^') + { + return 6; + } + else if (x == '(') + { + return 7; + } + else if (x == ')') + { + return 0; + } + return -1; +} + +int inPrecedence(char x) +{ + if (x == '+' || x == '-') + { + return 2; + } + else if (x == '*' || x == '/') + { + return 4; + } + else if (x == '^') + { + return 5; + } + else if (x == '(') + { + return 0; + } + return -1; +} + +char *convert(char *infix) +{ + char *postfix = new char[strlen(infix) + 1]; + + stack stk; + + int i = 0; + int j = 0; + + while (infix[i] != '\0') + { + if (isOperand(infix[i])) + { + postfix[j++] = infix[i++]; + } + else + { + if (stk.empty() || outPrecedence(infix[i]) > inPrecedence(stk.top())) + { + stk.push(infix[i++]); + } + else if (outPrecedence(infix[i]) == inPrecedence(stk.top())) + { + stk.pop(); + } + else + { + postfix[j++] = stk.top(); + stk.pop(); + } + } + } + + while (!stk.empty() && stk.top() != ')') + { + postfix[j++] = stk.top(); + stk.pop(); + } + + postfix[j] = '\0'; + + return postfix; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char infix[] = "((a+b)*c)-d^e^f"; + + cout << convert(infix) << endl; +} \ No newline at end of file diff --git a/Competitive programming/C++/PostfixEvaluation.cpp b/Competitive programming/C++/PostfixEvaluation.cpp new file mode 100644 index 0000000..44d3a9e --- /dev/null +++ b/Competitive programming/C++/PostfixEvaluation.cpp @@ -0,0 +1,219 @@ +#include +#include +#include + +using namespace std; + +class Node +{ +public: + int data; + Node *next; +}; + +class Stack +{ +private: + Node *top; + +public: + Stack(); + ~Stack(); + void push(int x); + int pop(); + int peek(int index); + int isEmpty(); + int isFull(); + int stackTop(); +}; + +Stack::Stack() +{ + top = nullptr; +} + +Stack::~Stack() +{ + Node *p = top; + while (top) + { + top = top->next; + delete p; + p = top; + } +} + +void Stack::push(int x) +{ + Node *t = new Node; + if (t == nullptr) + { + cout << "Stack Overflow!" << endl; + } + else + { + t->data = x; + t->next = top; + top = t; + } +} + +int Stack::pop() +{ + Node *p; + int x = -1; + if (top == nullptr) + { + cout << "Stack Underflow!" << endl; + } + else + { + p = top; + x = p->data; + top = top->next; + delete p; + } + return x; +} + +int Stack::isFull() +{ + Node *t = new Node; + int r = t ? 1 : 0; + delete t; + return r; +} + +int Stack::isEmpty() +{ + return top ? 0 : 1; +} + +int Stack::stackTop() +{ + if (top) + { + return top->data; + } + return -1; +} + +int Stack::peek(int index) +{ + if (isEmpty()) + { + return -1; + } + else + { + Node *p = top; + + for (int i = 0; p != nullptr && i < index - 1; i++) + { + p = p->next; + } + + if (p != nullptr) + { + return p->data; + } + else + { + return -1; + } + } +} + +int isOperand(char x) +{ + if (x == '+' || x == '-' || x == '*' || x == '/') + { + return 0; + } + return 1; +} + +int operation(char op, int x, int y) +{ + if (op == '+') + { + return x + y; + } + else if (op == '-') + { + return x - y; + } + else if (op == '*') + { + return x * y; + } + else if (op == '/') + { + return x / y; + } +} + +int postfixEvaluate(char *postfix) +{ + stack stk; + int x; + int y; + int result; + for (int i = 0; postfix[i] != '\0'; i++) + { + if (isOperand(postfix[i])) + { + // int typecast would not work because of char so subtract '0' + stk.push(postfix[i] - '0'); + } + else + { + y = stk.top(); + stk.pop(); + x = stk.top(); + stk.pop(); + result = operation(postfix[i], x, y); + stk.push(result); + } + } + result = stk.top(); + stk.pop(); + return result; +} + +int Evaluate(char *postfix) +{ + Stack stk; + int x; + int y; + int result; + for (int i = 0; postfix[i] != '\0'; i++) + { + if (isOperand(postfix[i])) + { + // int typecast would not work because of char so subtract '0' + stk.push(postfix[i] - '0'); + } + else + { + y = stk.pop(); + x = stk.pop(); + result = operation(postfix[i], x, y); + stk.push(result); + } + } + result = stk.pop(); + return result; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char postfix[] = "234*+82/-"; + cout << Evaluate(postfix) << endl; + cout << postfixEvaluate(postfix) << endl; + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/Tree.cpp b/Competitive programming/C++/Tree.cpp new file mode 100644 index 0000000..cc35fe9 --- /dev/null +++ b/Competitive programming/C++/Tree.cpp @@ -0,0 +1,130 @@ +#include +#include +#include "QueueCpp.h" + using namespace std; +class Tree +{ + Node *root; + +public: + Tree() { root = NULL; } + void CreateTree(); + void Preorder() { Preorder(root); } + void Preorder(Node *p); + void Postorder() { Postorder(root); } + void Postorder(Node *p); + void Inorder() { Inorder(root); } + void Inorder(Node *p); + void Levelorder() { Levelorder(root); } + void Levelorder(Node *p); + int Height() { return Height(root); } + int Height(Node *root); +}; +void Tree::CreateTree() +{ + Node *p, *t; + int x; + Queue q(100); + printf("Enter root value "); + scanf("%d", &x); + root = new Node; + root->data = x; + root->lchild = root->rchild = NULL; + q.enqueue(root); + while (!q.isEmpty()) + { + p = q.dequeue(); + printf("Enter left child of %d ", p->data); + scanf("%d", &x); + if (x != -1) + { + t = new Node; + t->data = x; + t->lchild = t->rchild = NULL; + p->lchild = t; + q.enqueue(t); + } + printf("eneter right child of %d ", p->data); + scanf("%d", &x); + if (x != -1) + { + t = new Node; + t->data = x; + t->lchild = t->rchild = NULL; + p->rchild = t; + q.enqueue(t); + } + } +} +void Tree::Preorder(struct Node *p) +{ + if (p) + { + printf("%d ", p->data); + Preorder(p->lchild); + Preorder(p->rchild); + } +} +void Tree::Inorder(struct Node *p) +{ + if (p) + { + Inorder(p->lchild); + printf("%d ", p->data); + Inorder(p->rchild); + } +} +void Tree::Postorder(struct Node *p) +{ + if (p) + { + Postorder(p->lchild); + Postorder(p->rchild); + printf("%d ", p->data); + } +} +void Tree::Levelorder(struct Node *root) +{ + Queue q(100); + printf("%d ", root->data); + q.enqueue(root); + while (!q.isEmpty(q)) + { + root = q.dequeue(); + if (root->lchild) + { + printf("%d ", root->lchild->data); + q.enqueue(root->lchild); + } + if (root->rchild) + { + printf("%d ", root->rchild->data); + q.enqueue(root->rchild); + } + } +} +int Tree::Height(struct Node *root) +{ + int x = 0, y = 0; + if (root == 0) + return 0; + x = Height(root->lchild); + y = Height(root->rchild); + if (x > y) + return x + 1; + else + return y + 1; +} +int main() +{ + Tree t; + t.CreateTree(); + cout << "Preorder "; + t.Preorder(); + cout << endl; + cout << "Inorder "; + t.Inorder(); + cout << endl + << endl; + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/extended_balanced_parenthesis_using_STL.cpp b/Competitive programming/C++/extended_balanced_parenthesis_using_STL.cpp new file mode 100644 index 0000000..c1d8246 --- /dev/null +++ b/Competitive programming/C++/extended_balanced_parenthesis_using_STL.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include + +using namespace std; + +int isBalanced(char *exp) +{ + + // Create map + map mapping; + mapping['}'] = '{'; + mapping[')'] = '('; + mapping[']'] = '['; + + // Create map iterator + map::iterator itr; + + // Create stack + stack stk; + + for (int i = 0; i < strlen(exp); i++) + { + if (exp[i] == '{' || exp[i] == '[' || exp[i] == '(') + { + stk.push(exp[i]); + } + else if (exp[i] == '}' || exp[i] == ']' || exp[i] == ')') + { + if (stk.empty()) + { + return false; + } + else + { + char temp = stk.top(); + itr = mapping.find(exp[i]); + if (temp == itr->second) + { // itr->first is key, itr->second is value + stk.pop(); + } + else + { + return false; + } + } + } + } + return stk.empty() ? true : false; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + + char A[] = "{([a+b]*[c-d*g])/e}"; + cout << isBalanced(A) << endl; + + char B[] = "{([a+b]}*[c-d])/e}"; + cout << isBalanced(B) << endl; + + char C[] = "{([{a+b]*[c-d])/e}"; + cout << isBalanced(C) << endl; + + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/parenthesismatching.cpp b/Competitive programming/C++/parenthesismatching.cpp new file mode 100644 index 0000000..86cff9f --- /dev/null +++ b/Competitive programming/C++/parenthesismatching.cpp @@ -0,0 +1,164 @@ +#include +#include +using namespace std; + +class Stack +{ +private: + int size; + int top; + char *S; + +public: + Stack(int size); + ~Stack(); + void push(char x); + char pop(); + char peek(int index); + int isFull(); + int isEmpty(); + void display(); + char stackTop(); +}; + +Stack::Stack(int size) +{ + this->size = size; + top = -1; + S = new char[size]; +} + +Stack::~Stack() +{ + delete[] S; +} + +void Stack::push(char x) +{ + if (isFull()) + { + cout << "Stack Overflow!" << endl; + } + else + { + top++; + S[top] = x; + } +} + +char Stack::pop() +{ + char x = 1; + if (isEmpty()) + { + cout << "Stack Underflow!" << endl; + } + else + { + x = S[top]; + top--; + } + return x; +} + +char Stack::peek(int index) +{ + char x = -1; + if (top - index + 1 < 0 || top - index + 1 == size) + { + cout << "Invalid position!" << endl; + } + else + { + x = S[top - index + 1]; + } + return x; +} + +int Stack::isFull() +{ + if (top == size - 1) + { + return 1; + } + return 0; +} + +int Stack::isEmpty() +{ + if (top == -1) + { + return 1; + } + return 0; +} + +void Stack::display() +{ + for (int i = top; i >= 0; i--) + { + cout << S[i] << " | " << flush; + } + cout << endl; +} + +char Stack::stackTop() +{ + if (isEmpty()) + { + return -1; + } + return S[top]; +} + +bool isBalanced(char *exp) +{ + + // Create a stack + Stack stk((int)strlen(exp)); + + // Process expression + for (int i = 0; i < strlen(exp); i++) + { + + // ( found: Push to stack + if (exp[i] == '(') + { + stk.push(exp[i]); + + // ( found + } + else if (exp[i] == ')') + { + + // ) and stack is empty: Unbalanced expression + if (stk.isEmpty()) + { + return false; + + // ) and stack is not empty + } + else + { + stk.pop(); + } + } + } + + // If stack is empty then balanced else unbalanced + return stk.isEmpty() ? true : false; +} + +int main() +{ + + char E[] = "((a+b)*(c-d))"; + cout << isBalanced(E) << endl; + + char F[] = "((a+b)*(c-d)))"; + cout << isBalanced(F) << endl; + + char G[] = "(((a+b)*(c-d))"; + cout << isBalanced(G) << endl; + return 0; +} \ No newline at end of file diff --git a/Competitive programming/C++/stackLinkedList.cpp b/Competitive programming/C++/stackLinkedList.cpp new file mode 100644 index 0000000..f5a054a --- /dev/null +++ b/Competitive programming/C++/stackLinkedList.cpp @@ -0,0 +1,167 @@ +#include +using namespace std; + +class Node +{ +public: + int data; + Node *next; +}; + +class Stack +{ +private: + Node *top; + +public: + Stack(); + ~Stack(); + void push(int x); + void Display(); + int pop(); + int peek(int index); + int isEmpty(); + int isFull(); + int stackTop(); +}; + +Stack::Stack() +{ + top = nullptr; +} + +Stack::~Stack() +{ + Node *p = top; + while (top) + { + top = top->next; + delete p; + p = top; + } +} + +void Stack::push(int x) +{ + Node *t = new Node; + if (t == nullptr) + { + cout << "Stack Overflow!" << endl; + } + else + { + t->data = x; + t->next = top; + top = t; + } +} + +int Stack::pop() +{ + Node *p; + int x = -1; + if (top == NULL) + { + cout << "Stack Underflow!" << endl; + } + else + { + p = top; + x = p->data; + top = top->next; + delete p; + } + return x; +} + +void Stack::Display() +{ + Node *p = top; + while(p!=NULL) + { + cout<data<<" "; + p=p->next; + } + cout<<"\n"; +} + +int Stack::isFull() +{ + Node *t = new Node; + int r = t ? 1 : 0; + delete t; + return r; +} + +int Stack::isEmpty() +{ + return top ? 0 : 1; +} + +int Stack::stackTop() +{ + if (top) + { + return top->data; + } + return -1; +} + +int Stack::peek(int index) +{ + if (isEmpty()) + { + return -1; + } + else + { + Node *p = top; + + for (int i = 0; p != nullptr && i < index - 1; i++) + { + p = p->next; + } + + if (p != nullptr) + { + return p->data; + } + else + { + return -1; + } + } +} + +int main() +{ + + int A[] = {1, 3, 5, 7, 9}; + + Stack stk; + + // Populate stack + for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) + { + stk.push(A[i]); + } + + cout << "Stack peek at 3rd: " << stk.peek(3) << endl; + cout << "Stack peek at 10th: " << stk.peek(10) << endl; + cout << "Stack top: " << stk.stackTop() << endl; + cout << "Stack full: " << stk.isFull() << endl; + cout << "Stack empty: " << stk.isEmpty() << endl; + + // Pop out elements from stack + cout << "Popped: " << flush; + for (int i = 0; i < sizeof(A) / sizeof(A[0]); i++) + { + cout << stk.pop() << ", " << flush; + } + cout << endl; + + // Underflow + cout << stk.pop() << endl; + + return 0; +} \ No newline at end of file From b2fa67d161b96e5cf0721f2bc95474e958ca232b Mon Sep 17 00:00:00 2001 From: Atharv Patil <71587540+Atharvp18@users.noreply.github.com> Date: Sun, 3 Oct 2021 19:25:29 +0400 Subject: [PATCH 068/142] Add files via upload --- Competitive programming/C++/ADACRA.cpp | 33 ++++++++++++++++++++++++ Competitive programming/C++/FLOW017.cpp | 21 +++++++++++++++ Competitive programming/C++/HS08TEST.cpp | 22 ++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 Competitive programming/C++/ADACRA.cpp create mode 100644 Competitive programming/C++/FLOW017.cpp create mode 100644 Competitive programming/C++/HS08TEST.cpp diff --git a/Competitive programming/C++/ADACRA.cpp b/Competitive programming/C++/ADACRA.cpp new file mode 100644 index 0000000..f3d1915 --- /dev/null +++ b/Competitive programming/C++/ADACRA.cpp @@ -0,0 +1,33 @@ +// The problem link is https://www.codechef.com/problems/ADACRA +#include +#include +using namespace std; + +int main() { + int t; + cin >> t; + while(t--){ + int count_u = 0, count_d = 0; + string S; + cin >> S; + for(int i = 1; i < S.length(); i++){ + if(S[i]!=S[i+1]){ + if(S[i]=='U'){ + count_u += 1; + } + else{ + count_d += 1; + } + } + } + if(S[0] == 'U'){ + count_u += 1; + } + else{ + count_d += 1; + } + int ans = min(count_d, count_u); + cout << ans << "\n"; + } + return 0; +} diff --git a/Competitive programming/C++/FLOW017.cpp b/Competitive programming/C++/FLOW017.cpp new file mode 100644 index 0000000..07cf667 --- /dev/null +++ b/Competitive programming/C++/FLOW017.cpp @@ -0,0 +1,21 @@ +// The problem link is https://www.codechef.com/problems/FLOW017 +#include +using namespace std; + +int main() { + long long int t, a, b, c; + cin >> t; + for(int i = 0; i < t; i++){ + cin >> a >> b >> c; + if(a < max(b,c) && a > min(b,c)){ + cout< min(a,c) && b < max(a,c)){ + cout< +#include +using namespace std; + +int main() { + int x; + float y,d; + cin>>x; + cin>>y; + d=x+0.50; + if(d>y||x%5!=0) + { + cout< Date: Sun, 3 Oct 2021 22:23:23 +0530 Subject: [PATCH 069/142] added --- .../C++/decimal_to_binary.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Competitive programming/C++/decimal_to_binary.cpp diff --git a/Competitive programming/C++/decimal_to_binary.cpp b/Competitive programming/C++/decimal_to_binary.cpp new file mode 100644 index 0000000..53e7f9d --- /dev/null +++ b/Competitive programming/C++/decimal_to_binary.cpp @@ -0,0 +1,23 @@ +#include +#include + +using namespace std; + +int main() +{ + int n; + cin>>n; + vector v; + int rem; + while(n>0){ + rem=n%2; + v.push_back(rem); + n=n/2; + } + reverse(v.begin(), v.end()); + for(int i=0;i Date: Sun, 3 Oct 2021 22:43:48 +0530 Subject: [PATCH 070/142] KMP_Algo.c Implementation of KMP Algorithm for strings in c --- KMP_Algo.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 KMP_Algo.c diff --git a/KMP_Algo.c b/KMP_Algo.c new file mode 100644 index 0000000..c8fe930 --- /dev/null +++ b/KMP_Algo.c @@ -0,0 +1,57 @@ +//srishti1302 +#include +#include +int failure[20]; +void fail(char *pat) +{ + int i,j; + int n=strlen(pat); + failure[0]=-1; + for(j=1;j0)) + i=failure[i]; + if(pat[j]==pat[i+1]) + failure[j]=i+1; + else + failure[j]=-1; + } + for(int k=0;k<=n;k++) + printf("%d\t",failure[k]); +} +int match(char *string, char *pat) +{ + int i=0,j=0; + int lens=strlen(string); + int lenp=strlen(pat); + while(i Date: Mon, 4 Oct 2021 03:36:31 +0530 Subject: [PATCH 071/142] Added MaxAndSecondMax.java --- .../Max and Second Max/MaxSecondMax.java | 40 +++++++++++++++++++ .../Amazon/Max and Second Max/question.md | 1 + 2 files changed, 41 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java create mode 100644 CompanywiseSolution/Amazon/Max and Second Max/question.md diff --git a/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java b/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java new file mode 100644 index 0000000..fa7000f --- /dev/null +++ b/CompanywiseSolution/Amazon/Max and Second Max/MaxSecondMax.java @@ -0,0 +1,40 @@ +import java.util.*; +public class MaxSecondMax { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + System.out.println("Enter the size: "); + int N = sc.nextInt(); + int [] TempArr = new int [N]; + for(int j =0 ; j< N ; j++){ + System.out.println("Enter the Number: "); + TempArr[j] = sc.nextInt(); + } + + System.out.println(Max(TempArr , N)); + sc.close(); + } + + public static ArrayList Max( int arr[] , int size) + { + int counter = 0; + int temp =-1; + for(int i = 0 ; icounter){ + counter = arr[i]; + } + } + + for(int i =0 ; i al = new ArrayList(); + al.add(counter); + al.add(temp); + + return al;//code here. + } +} \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Max and Second Max/question.md b/CompanywiseSolution/Amazon/Max and Second Max/question.md new file mode 100644 index 0000000..e72b414 --- /dev/null +++ b/CompanywiseSolution/Amazon/Max and Second Max/question.md @@ -0,0 +1 @@ +Given an array arr[] of size N of positive integers which may have duplicates. The task is to find the maximum and second maximum from the array, and both of them should be distinct, so If no second max exists, then the second max will be -1. \ No newline at end of file From 936733f7888e0fb1c0f027c3efe2d1678bcf8b35 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 23:08:06 +0530 Subject: [PATCH 072/142] Maximum Subarray Sum Added to folder --- .../C++/Maximum Subarray Sum | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Competitive programming/C++/Maximum Subarray Sum diff --git a/Competitive programming/C++/Maximum Subarray Sum b/Competitive programming/C++/Maximum Subarray Sum new file mode 100644 index 0000000..2212980 --- /dev/null +++ b/Competitive programming/C++/Maximum Subarray Sum @@ -0,0 +1,35 @@ +//Maximum Subarray Sum +//Using Kadane's Algorithm +//Time Complexity O(n) +#include + +using namespace std; + +int maxSubArraySum(int arr[],int n) +{ + int maxSum =0 ; + int currSum=0; + for(int i=0;imaxSum) + { + maxSum=currSum; + } + if(currSum<0) + { + currSum=0; + } + + } + return maxSum; +} +int main() +{ + int arr[] = {5,-4,-2,6,-1}; + int n = sizeof(arr)/sizeof(arr[0]); + int maxsum = maxSubArraySum(arr, n); + cout << "Maximum subarray sum is " << maxsum; + + return 0; +} From 36cc745e83dcf18e5fcc084949a31c2bc614f6fc Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 23:10:59 +0530 Subject: [PATCH 073/142] BuyStockAndSell Added to folder --- Competitive programming/C++/BuyStockAndSell | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Competitive programming/C++/BuyStockAndSell diff --git a/Competitive programming/C++/BuyStockAndSell b/Competitive programming/C++/BuyStockAndSell new file mode 100644 index 0000000..94c660b --- /dev/null +++ b/Competitive programming/C++/BuyStockAndSell @@ -0,0 +1,30 @@ +//Time Complexity O(n) + +#include + +using namespace std; + +int stockBuySell(int arr[],int n) +{ + int max_profit =0; + int minSofar=arr[0]; + for(int i=0;i Date: Sun, 3 Oct 2021 23:14:19 +0530 Subject: [PATCH 074/142] Delete Maximum Subarray Sum Deleted --- Maximum Subarray Sum | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100644 Maximum Subarray Sum diff --git a/Maximum Subarray Sum b/Maximum Subarray Sum deleted file mode 100644 index 2212980..0000000 --- a/Maximum Subarray Sum +++ /dev/null @@ -1,35 +0,0 @@ -//Maximum Subarray Sum -//Using Kadane's Algorithm -//Time Complexity O(n) -#include - -using namespace std; - -int maxSubArraySum(int arr[],int n) -{ - int maxSum =0 ; - int currSum=0; - for(int i=0;imaxSum) - { - maxSum=currSum; - } - if(currSum<0) - { - currSum=0; - } - - } - return maxSum; -} -int main() -{ - int arr[] = {5,-4,-2,6,-1}; - int n = sizeof(arr)/sizeof(arr[0]); - int maxsum = maxSubArraySum(arr, n); - cout << "Maximum subarray sum is " << maxsum; - - return 0; -} From 3de0bd5f7cd47c7cafe73436e9769a93ff0b0561 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 23:14:34 +0530 Subject: [PATCH 075/142] Delete Stock Buy And Sell to Maximize Profit in C++ --- Stock Buy And Sell to Maximize Profit in C++ | 30 -------------------- 1 file changed, 30 deletions(-) delete mode 100644 Stock Buy And Sell to Maximize Profit in C++ diff --git a/Stock Buy And Sell to Maximize Profit in C++ b/Stock Buy And Sell to Maximize Profit in C++ deleted file mode 100644 index 94c660b..0000000 --- a/Stock Buy And Sell to Maximize Profit in C++ +++ /dev/null @@ -1,30 +0,0 @@ -//Time Complexity O(n) - -#include - -using namespace std; - -int stockBuySell(int arr[],int n) -{ - int max_profit =0; - int minSofar=arr[0]; - for(int i=0;i Date: Sun, 3 Oct 2021 23:15:00 +0530 Subject: [PATCH 076/142] Delete Stock Buy Sell to Maximize Profit in C++ --- Stock Buy Sell to Maximize Profit in C++ | 30 ------------------------ 1 file changed, 30 deletions(-) delete mode 100644 Stock Buy Sell to Maximize Profit in C++ diff --git a/Stock Buy Sell to Maximize Profit in C++ b/Stock Buy Sell to Maximize Profit in C++ deleted file mode 100644 index 94c660b..0000000 --- a/Stock Buy Sell to Maximize Profit in C++ +++ /dev/null @@ -1,30 +0,0 @@ -//Time Complexity O(n) - -#include - -using namespace std; - -int stockBuySell(int arr[],int n) -{ - int max_profit =0; - int minSofar=arr[0]; - for(int i=0;i Date: Sun, 3 Oct 2021 23:31:13 +0530 Subject: [PATCH 077/142] Programs Added --- .DS_Store | Bin 0 -> 8196 bytes Algorithms/linkedList.cpp | 123 ++++++++++++++++ Algorithms/queue_implementation.cpp | 137 +++++++++++++++++ Algorithms/stack_implementation.cpp | 78 ++++++++++ Competitive programming/.DS_Store | Bin 0 -> 6148 bytes Competitive programming/PYTHON/.DS_Store | Bin 0 -> 6148 bytes Competitive programming/PYTHON/Fibonacci.py | 30 ++++ .../PYTHON/Frequent_WORD.py | 40 +++++ Competitive programming/PYTHON/SUDOKU.py | 52 +++++++ Competitive programming/PYTHON/Tic-Tac-Toe.py | 138 ++++++++++++++++++ 10 files changed, 598 insertions(+) create mode 100644 .DS_Store create mode 100644 Algorithms/linkedList.cpp create mode 100644 Algorithms/queue_implementation.cpp create mode 100644 Algorithms/stack_implementation.cpp create mode 100644 Competitive programming/.DS_Store create mode 100644 Competitive programming/PYTHON/.DS_Store create mode 100644 Competitive programming/PYTHON/Fibonacci.py create mode 100644 Competitive programming/PYTHON/Frequent_WORD.py create mode 100644 Competitive programming/PYTHON/SUDOKU.py create mode 100644 Competitive programming/PYTHON/Tic-Tac-Toe.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..87c7f6833a18bac21d83afe9ff58df1926413153 GIT binary patch literal 8196 zcmeHMPfrs;6n_IKUH`HC6EvD^Y)nifgnuz|Fs=on#2AnggeaD6JCv2}OtZVCLdEp% z$(x$^0X+Eu`~rIL?8*2M^y*39%xp_-t%)&F2{Xyedwny%H#5K8x4Ul&03=b&jsgq< zKn$yp=22{ZQbfO~O{Fce7$^zi0eo;Fgbm0;&@@^bGy|Fe&46Y=GoTsx9~i)QwkWX{ z?|s#)Tg`xG;6O4Uo(~pQA?-+3l$4JSY-9?6vIEVsppJQf#8{EEBUw>WLeZzn9!LZw zQHntn9Q!RX9Hkw}ijoQrM8SbXGm|JoA#!%aS#mfKTS?t&1~dcB42azQ2wVdXa=`2J z_gRl;(jHG^zX+*oSckvKf?5kqx)c;5%)4~KbAxbXKb0GiDeuB(n~HarOdu5&O*m!)R$m4OL54(J1)!eQi2y*HjsXj zszXkcG6&1$u}dRE*7(@y?vPcU97BEL(!}nr5gRx^dS!Mkzr9m_wEOtE+zycFxdL74 zcddQVYO`);E7~l1U)}5{)2wax$kAiRPjs2xJ-yw1-TnP12L}63oj!dgW%j0>%x2CP z3!ma1_Y+=`-p%=LHd$~oF3T;4^kJBEcWBD&X&Aadv-kH*i`xYp)3;}k?ymckGU;z_ zeLbMza-F`CGP{C|&pmIR2X5$cwsJ4POE4SK{487NIO7&lK35Q3!4mZYluelB7034- zmZOR7RnJLNZ;mB+81lRrDZFJkoA;^kwCtiT_7cDPMNt~JZ&sBHN--g>6o9zBV@o~O zS2abFEHcihVZ`nE$P$B#cvs$nCD?==cnUA!6}*AB@DV=4SJFvNk#poCnIKolRdR#e zCJQ7(Hi%0eD12M>f}j0yCL&I*ei{*5NuPO~<*;91dtnMACJzO0fWbDD@a!u93Q4qj zP{eaE7d6%pN3RiCA4dZMi`Q z;&q^09=|*}WKB-~GF+eGjrZfwde+5) zbkPj#HwN0(f(J$ZKhygBf4^-@uU9jm8TbtbNXK+?I)Q-dCs89-s9QKxVC+a%ltc@bzkU$V^i8GT|MEiU=0Gv<9o+wU1poj5 literal 0 HcmV?d00001 diff --git a/Algorithms/linkedList.cpp b/Algorithms/linkedList.cpp new file mode 100644 index 0000000..db14923 --- /dev/null +++ b/Algorithms/linkedList.cpp @@ -0,0 +1,123 @@ +/*------------------------------------------------------------------------------------------------ + PROGRAM TO SHOW THE OPERATIONS IN A LINKED LIST +--------------------------------------------------------------------------------------------------*/ + +#include +using namespace std; + +// A linked list node +struct Node +{ + int data; + struct Node *next; +}; + +/*----------------Function to insert a new node in front of the list-------------------*/ +void push(struct Node **head, int node_data) +{ + /* 1. create and allocate node */ + struct Node *newNode = new Node; + + /* 2. assign data to node */ + newNode->data = node_data; + + /* 3. set next of new node as head */ + newNode->next = (*head); + + /* 4. move the head to point to the new node */ + (*head) = newNode; +} + +/*----------------Function to insert new node after a given node--------------------*/ +void insertAfter(struct Node *prev_node, int node_data) +{ + /*1. check if the given prev_node is NULL */ + if (prev_node == NULL) + { + cout << "the given previous node is required,cannot be NULL"; + return; + } + + /* 2. create and allocate new node */ + struct Node *newNode = new Node; + + /* 3. assign data to the node */ + newNode->data = node_data; + + /* 4. Make next of new node as next of prev_node */ + newNode->next = prev_node->next; + + /* 5. move the next of prev_node as new_node */ + prev_node->next = newNode; +} + +/*----------------Function to insert new node at the end of the linked list------------------ */ +void append(struct Node **head, int node_data) +{ + /* 1. create and allocate node */ + struct Node *newNode = new Node; + + struct Node *last = *head; /* used in step 5*/ + + /* 2. assign data to the node */ + newNode->data = node_data; + + /* 3. set next pointer of new node to null as its the last node*/ + newNode->next = NULL; + + /* 4. if list is empty, new node becomes first node */ + if (*head == NULL) + { + *head = newNode; + return; + } + + /* 5. Else traverse till the last node */ + while (last->next != NULL) + last = last->next; + + /* 6. Change the next of last node */ + last->next = newNode; + return; +} + +/*-------------------Function to display linked list contents ------------------------*/ +void displayList(struct Node *node) +{ + //traverse the list to display each node + while (node != NULL) + { + cout << node->data << "-->"; + node = node->next; + } + + if (node == NULL) + cout << "null"; +} + +/*-----------------------------------MAIN FUNCTION-------------------------------------*/ +int main() +{ + /* empty list */ + struct Node *head = NULL; + + // Insert 10. + append(&head, 10); + + // Insert 20 at the beginning. + push(&head, 20); + + // Insert 30 at the beginning. + push(&head, 30); + + // Insert 40 at the end. + append(&head, 40); // + + // Insert 50, after 20. + insertAfter(head->next, 50); + + cout << "Final linked list: " << endl; + displayList(head); + + return 0; +} \ No newline at end of file diff --git a/Algorithms/queue_implementation.cpp b/Algorithms/queue_implementation.cpp new file mode 100644 index 0000000..92463fc --- /dev/null +++ b/Algorithms/queue_implementation.cpp @@ -0,0 +1,137 @@ +#include +#include +using namespace std; + +// Define the default capacity of a queue +#define SIZE 10 + +// A class to store a queue +class queue +{ + int *arr; // array to store queue elements + int capacity; // maximum capacity of the queue + int front; // front points to the front element in the queue (if any) + int rear; // rear points to the last element in the queue + int count; // current size of the queue + +public: + queue(int size = SIZE); // constructor + ~queue(); // destructor + + void dequeue(); + void enqueue(int x); + int peek(); + int size(); + bool isEmpty(); + bool isFull(); +}; + +// Constructor to initialize a queue +queue::queue(int size) +{ + arr = new int[size]; + capacity = size; + front = 0; + rear = -1; + count = 0; +} + +// Destructor to free memory allocated to the queue +queue::~queue() +{ + delete[] arr; +} + +// Utility function to dequeue the front element +void queue::dequeue() +{ + // check for queue underflow + if (isEmpty()) + { + cout << "Underflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + + cout << "Removing " << arr[front] << endl; + + front = (front + 1) % capacity; + count--; +} + +// Utility function to add an item to the queue +void queue::enqueue(int item) +{ + // check for queue overflow + if (isFull()) + { + cout << "Overflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + + cout << "Inserting " << item << endl; + + rear = (rear + 1) % capacity; + arr[rear] = item; + count++; +} + +// Utility function to return the front element of the queue +int queue::peek() +{ + if (isEmpty()) + { + cout << "Underflow\nProgram Terminated\n"; + exit(EXIT_FAILURE); + } + return arr[front]; +} + +// Utility function to return the size of the queue +int queue::size() +{ + return count; +} + +// Utility function to check if the queue is empty or not +bool queue::isEmpty() +{ + return (size() == 0); +} + +// Utility function to check if the queue is full or not +bool queue::isFull() +{ + return (size() == capacity); +} + +int main() +{ + // create a queue of capacity 5 + queue q(5); + + q.enqueue(1); + q.enqueue(2); + q.enqueue(3); + + cout << "The front element is " << q.peek() << endl; + q.dequeue(); + + q.enqueue(4); + + cout << "The queue size is " << q.size() << endl; + + q.dequeue(); + q.dequeue(); + q.dequeue(); + + if (q.isEmpty()) + { + cout << "The queue is empty\n"; + } + else + { + cout << "The queue is not empty\n"; + } + + return 0; +} \ No newline at end of file diff --git a/Algorithms/stack_implementation.cpp b/Algorithms/stack_implementation.cpp new file mode 100644 index 0000000..e4a99e5 --- /dev/null +++ b/Algorithms/stack_implementation.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; +int stack[100], n = 100, top = -1; +void push(int val) +{ + if (top >= n - 1) + cout << "Stack Overflow" << endl; + else + { + top++; + stack[top] = val; + } +} +void pop() +{ + if (top <= -1) + cout << "Stack Underflow" << endl; + else + { + cout << "The popped element is " << stack[top] << endl; + top--; + } +} +void display() +{ + if (top >= 0) + { + cout << "Stack elements are:"; + for (int i = top; i >= 0; i--) + cout << stack[i] << " "; + cout << endl; + } + else + cout << "Stack is empty"; +} +int main() +{ + int ch, val; + cout << "1) Push in stack" << endl; + cout << "2) Pop from stack" << endl; + cout << "3) Display stack" << endl; + cout << "4) Exit" << endl; + do + { + cout << "Enter choice: " << endl; + cin >> ch; + switch (ch) + { + case 1: + { + cout << "Enter value to be pushed:" << endl; + cin >> val; + push(val); + break; + } + case 2: + { + pop(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + cout << "Exit" << endl; + break; + } + default: + { + cout << "Invalid Choice" << endl; + } + } + } while (ch != 4); + return 0; +} \ No newline at end of file diff --git a/Competitive programming/.DS_Store b/Competitive programming/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..66d2ac5f591d4afa54634550b523ccd3dab349e7 GIT binary patch literal 6148 zcmeHKQEL-H5T3o9?VTd#K~Nur1@Wn|B(+rfP`D;3SV1jbsfbE@=LLIky)DVbpfPgq z{sRU7g8#!m;BWCsXLhI3yQ(jONZ5hhZ*J$C-OQKVZWaJUcbs$pngHNoBXrMW_Y0#q zwKL}Mh>s{}4i%$EQ*Cm@f>ppO@INbH-re4Ire4HZ<^5g$u1$Y<2YPU$#`%nq)0_r! zmSCyM64z@i7w+Nium_tp-uoKQL0(wne5-L5UhEM5fCn^qO_IH)ae)>_omkuWT&C5NN z7g3rIhB`S-21t4KIL#9^>8f#_jPyLA3Fw9Po7bk(+v{sBd8@N>XV#L_^_6x@uCA@l zX1;gjW@lsj;OO<6>D$@64_FbJz@1jxCB_r@h)zY3SK%(@Gr@`FrVews;mN5fxl3I_6LcLFkmbV>a7DieFZ>taabGr zbOE3o$rvz}1~GyrOe&&D6@0}ICLPBm^8&`wph*Y8mk+@!3%;QUy*kb>H627?(DqgV zt3XwOhIwq#`M>r1`+qgbK3N5<0&}H+aQk7uizV^ddZsu!YbCY=Y-GeM4eAu^_&C-M f9mQ9%X~UQ#2QgqQ4dMuz{Ue}du$@)lpDOSJBgvag literal 0 HcmV?d00001 diff --git a/Competitive programming/PYTHON/.DS_Store b/Competitive programming/PYTHON/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..02188fd39abd249aebbf1fc794b23ad6aa75b843 GIT binary patch literal 6148 zcmeHK%}xR_7@Q&p1fm?hX!Zpp@eLNTYhsL|BJqd|C=!uX1S7Y-`wqT>&*w?!YkOFh z^-758w`r$;(|(<%?G}J)&Id<84M2%Ouvli4V^S|+#R|4WcuM!t#tj;{KpoF3tzCgr zz$vh43dr8A;F!Di6d}_4cX2X~`@M18V+%PR8VvOxZA<}GvPS43#sm@i{6>1;=kY#M zyaUafU;vN23F8oB+~J8~f*JE8U25tgO!-Avb*vL|74I=< aW1S}nqHi%V$P$|S5zsQY$SJT^1%3hb)S{^X literal 0 HcmV?d00001 diff --git a/Competitive programming/PYTHON/Fibonacci.py b/Competitive programming/PYTHON/Fibonacci.py new file mode 100644 index 0000000..3827c59 --- /dev/null +++ b/Competitive programming/PYTHON/Fibonacci.py @@ -0,0 +1,30 @@ +# -- Case-1 -->> Using Function +# This is a program to find fibonacci series using simple function +def fib(n): + if n < 1: # Fibonacci is not defined for negative numbers + return None + if n < 3: # The first two elements of fibonacci are 1 + return 1 + elem1 = elem2 = 1 + sum = 0 + for i in range(3, n+1): + sum = elem1+elem2 + elem1, elem2 = elem2, sum + # First element becomes becomes second element + # Second element becomes the sum of previous two elements + + return sum + + +#--Main--# +for i in range(1, 10): + print(i, " -->> ", fib(i)) + + +# -- Case-2 -->> Using Recursive Function +def fib_rec(n): + if n < 0: + return None + if n < 3: + return 1 + return fib(n-1)+fib(n-2) diff --git a/Competitive programming/PYTHON/Frequent_WORD.py b/Competitive programming/PYTHON/Frequent_WORD.py new file mode 100644 index 0000000..3393bd0 --- /dev/null +++ b/Competitive programming/PYTHON/Frequent_WORD.py @@ -0,0 +1,40 @@ +# # Here we will find the maximum frequent word in the dataset +# # We will use the concept of dictionary. +# inp = list(input("Enter").split()) +# d = {} +# for x in inp: +# d[x] = 0 +# for x in inp: +# d[x] = d[x]+1 + +# max = 0 +# ans = '' +# for x in inp: +# if(d[x] > max): +# max = d[x] +# ans = x +# print(d) +# print(max) +# print("Max Repeating word = ", ans.upper()) +def f(str): + new = {} + freq = {} + str = list(str.lower().split(' ')) + for i in str: + if i not in new: + new[i] = 0 + new[i] += 1 + else: + new[i] += 1 + for i in sorted(list(new.values())): + freq[i] = [] + for x in freq: + for word in new: + if new[word] == x: + freq[x] += [word] + print(str, end='\n\n\n') + print(new) + print(freq) + + +f('My name is Lalit Kumar. My house is in #### %4^ 8') diff --git a/Competitive programming/PYTHON/SUDOKU.py b/Competitive programming/PYTHON/SUDOKU.py new file mode 100644 index 0000000..e578423 --- /dev/null +++ b/Competitive programming/PYTHON/SUDOKU.py @@ -0,0 +1,52 @@ +# A function that checks whether a list passed as an argument contains +# nine digits from '1' to '9'. +def checkset(digs): + return sorted(list(digs)) == [chr(x + ord('0')) for x in range(1, 10)] + + +# A list of rows representing the sudoku. +rows = [ ] +for r in range(9): + ok = False + while not ok: + row = input("Enter row #" + str(r + 1) + ": ") + ok = len(row) == 9 or row.isdigit() + if not ok: + print("Incorrect row data - 9 digits required") + rows.append(row) + +ok = True + +# Check if all rows are good. +for r in range(9): + if not checkset(rows[r]): + ok = False + break + +# Check if all columns are good. +if ok: + for c in range(9): + col = [] + for r in range(9): + col.append(rows[r][c]) + if not checkset(col): + ok = False + break + +# Check if all sub-squares (3x3) are good. +if ok: + for r in range(0, 9, 3): + for c in range(0, 9, 3): + sqr = '' + # Make a string containing all digits from a sub-square. + for i in range(3): + sqr += rows[r+i][c:c+3] + if not checkset(list(sqr)): + ok = False + break + +# Print the final verdict. +if ok: + print("Yes") +else: + print("No") diff --git a/Competitive programming/PYTHON/Tic-Tac-Toe.py b/Competitive programming/PYTHON/Tic-Tac-Toe.py new file mode 100644 index 0000000..37f46f4 --- /dev/null +++ b/Competitive programming/PYTHON/Tic-Tac-Toe.py @@ -0,0 +1,138 @@ +''' +Your task is to write a simple program which pretends to play tic-tac-toe with the user. +To make it all easier for you, we've decided to simplify the game. Here are our assumptions: +-->>The computer (i.e., your program) should play the game using 'X's; +-->>The user (e.g., you) should play the game using 'O's; +-->>The first move belongs to the computer - it always puts its first 'X' in the middle of the board; +-->>All the squares are numbered row by row starting with 1 (see the example session below for reference) +-->>The user inputs their move by entering the number of the square they choose - the number must be valid, + i.e., it must be an integer, it must be greater than 0 and less than 10, and it cannot point to a field which is already occupied; +-->>The program checks if the game is over - there are four possible verdicts: + the game should continue, or the game ends with a tie, your win, or the computer's win; +-->>The computer responds with its move and the check is repeated; +-->>Don't implement any form of artificial intelligence - a random field choice made by the computer is good enough for the game. +''' +# def display_board(board): +# # The function accepts one parameter containing the board's current status +# # and prints it out to the console. + + +# def enter_move(board): +# # The function accepts the board current status, asks the user about their move, +# # checks the input and updates the board according to the user's decision. + + +# def make_list_of_free_fields(board): +# # The function browses the board and builds a list of all the free squares; +# # the list consists of tuples, while each tuple is a pair of row and column numbers. + + +# def victory_for(board, sign): +# # The function analyzes the board status in order to check if +# # the player using 'O's or 'X's has won the game + + +# def draw_move(board): +# The function draws the computer's move and updates the board. + +from random import randrange + + +def display_board(board): + print("+-------" * 3, "+", sep="") + for row in range(3): + print("| " * 3, "|", sep="") + for col in range(3): + print("| " + str(board[row][col]) + " ", end="") + print("|") + print("| " * 3, "|", sep="") + print("+-------" * 3, "+", sep="") + + +def enter_move(board): + ok = False # fake assumption - we need it to enter the loop + while not ok: + move = input("Enter your move: ") + # is user's input valid? + ok = len(move) == 1 and move >= '1' and move <= '9' + if not ok: + # no, it isn't - do the input again + print("Bad move - repeat your input!") + continue + move = int(move) - 1 # cell's number from 0 to 8 + row = move // 3 # cell's row + col = move % 3 # cell's column + sign = board[row][col] # check the selected square + ok = sign not in ['O', 'X'] + if not ok: # it's occupied - to the input again + print("Field already occupied - repeat your input!") + continue + board[row][col] = 'O' # set '0' at the selected square + + +def make_list_of_free_fields(board): + free = [] # the list is empty initially + for row in range(3): # iterate through rows + for col in range(3): # iterate through columns + if board[row][col] not in ['O', 'X']: # is the cell free? + # yes, it is - append new tuple to the list + free.append((row, col)) + return free + + +def victory_for(board, sgn): + if sgn == "X": # are we looking for X? + who = 'me' # yes - it's computer's side + elif sgn == "O": # ... or for O? + who = 'you' # yes - it's our side + else: + who = None # we should not fall here! + cross1 = cross2 = True # for diagonals + for rc in range(3): + if board[rc][0] == sgn and board[rc][1] == sgn and board[rc][2] == sgn: # check row rc + return who + if board[0][rc] == sgn and board[1][rc] == sgn and board[2][rc] == sgn: # check column rc + return who + if board[rc][rc] != sgn: # check 1st diagonal + cross1 = False + if board[2 - rc][2 - rc] != sgn: # check 2nd diagonal + cross2 = False + if cross1 or cross2: + return who + return None + + +def draw_move(board): + free = make_list_of_free_fields(board) # make a list of free fields + cnt = len(free) + if cnt > 0: # if the list is not empty, choose a place for 'X' and set it + this = randrange(cnt) + row, col = free[this] + board[row][col] = 'X' + + +board = [[3 * j + i + 1 for i in range(3)] + for j in range(3)] # make an empty board +board[1][1] = 'X' # set first 'X' in the middle +free = make_list_of_free_fields(board) +human_turn = True # which turn is it now? +while len(free): + display_board(board) + if human_turn: + enter_move(board) + victor = victory_for(board, 'O') + else: + draw_move(board) + victor = victory_for(board, 'X') + if victor != None: + break + human_turn = not human_turn + free = make_list_of_free_fields(board) + +display_board(board) +if victor == 'you': + print("You won!") +elif victor == 'me': + print("I won") +else: + print("Tie!") From 8b2914ffbc7b69846c0b84acd3f376a1c75f8641 Mon Sep 17 00:00:00 2001 From: Harsh Kumar Date: Sun, 3 Oct 2021 23:32:22 +0530 Subject: [PATCH 078/142] Create inverted_pattern.cpp --- .../C++/inverted_pattern.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Competitive programming/C++/inverted_pattern.cpp diff --git a/Competitive programming/C++/inverted_pattern.cpp b/Competitive programming/C++/inverted_pattern.cpp new file mode 100644 index 0000000..4accca4 --- /dev/null +++ b/Competitive programming/C++/inverted_pattern.cpp @@ -0,0 +1,23 @@ +// C++ code to demonstrate star pattern +#include +using namespace std; + +void pypart(int n) +{ + for (int i = n; i > 0; i--) { + + for (int j = 0; j < i; j++) { + + cout << "* "; + } + + cout << endl; + } +} + +int main() +{ + int n = 5; + pypart(n); + return 0; +} \ No newline at end of file From 2d306cda017ed8f1afd0ed05b7f6c0acd054b875 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Sun, 3 Oct 2021 23:41:04 +0530 Subject: [PATCH 079/142] Create Move all zeroes to end --- .../C++/Move all zeroes to end | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Competitive programming/C++/Move all zeroes to end diff --git a/Competitive programming/C++/Move all zeroes to end b/Competitive programming/C++/Move all zeroes to end new file mode 100644 index 0000000..a73bda9 --- /dev/null +++ b/Competitive programming/C++/Move all zeroes to end @@ -0,0 +1,31 @@ + +#include +using namespace std; + + +void pushZerosToEnd(int arr[], int n) +{ + int count = 0; // Count of non-zero elements + + + for (int i = 0; i < n; i++) + if (arr[i] != 0) + arr[count++] = arr[i]; // here count is + // incremented + + + while (count < n) + arr[count++] = 0; +} + + +int main() +{ + int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; + int n = sizeof(arr) / sizeof(arr[0]); + pushZerosToEnd(arr, n); + cout << "Array after pushing all zeros to end of array :\n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} From 5d0c74fa01f1bdce858b154531c0f5e0de987163 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Mon, 4 Oct 2021 00:05:33 +0530 Subject: [PATCH 080/142] Create MajorityElementInarray --- .../C++/MajorityElementInarray | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Competitive programming/C++/MajorityElementInarray diff --git a/Competitive programming/C++/MajorityElementInarray b/Competitive programming/C++/MajorityElementInarray new file mode 100644 index 0000000..5465337 --- /dev/null +++ b/Competitive programming/C++/MajorityElementInarray @@ -0,0 +1,33 @@ +#include +using namespace std; + +void findMajority(int arr[], int size) +{ + unordered_map m; + for(int i = 0; i < size; i++) + m[arr[i]]++; + int count = 0; + for(auto i : m) + { + if(i.second > size / 2) + { + count =1; + cout << "Majority found :" << i.first< Date: Mon, 4 Oct 2021 03:12:44 +0530 Subject: [PATCH 081/142] Print subsets of given array Solution in CPP using Recursion. --- .../C++/Print Subsets of Array.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Competitive programming/C++/Print Subsets of Array.cpp diff --git a/Competitive programming/C++/Print Subsets of Array.cpp b/Competitive programming/C++/Print Subsets of Array.cpp new file mode 100644 index 0000000..7634c97 --- /dev/null +++ b/Competitive programming/C++/Print Subsets of Array.cpp @@ -0,0 +1,30 @@ +// + +#include +using namespace std; + +void printSubsetsOfArray(int input[], int size,int output[],int len) { + if(size==0){ + for(int i=0;i> length; + for(int i=0; i < length; i++) + cin >> input[i]; + printSubsetsOfArray(input, length); +} \ No newline at end of file From b0483f65c0a68bb89a5ce5149c29db92a097e30a Mon Sep 17 00:00:00 2001 From: Aniket Kumar <70529369+ALCHEMAX42@users.noreply.github.com> Date: Mon, 4 Oct 2021 03:14:01 +0530 Subject: [PATCH 082/142] Update-2 Removed whitespaces --- Competitive programming/C++/Print Subsets of Array.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Competitive programming/C++/Print Subsets of Array.cpp b/Competitive programming/C++/Print Subsets of Array.cpp index 7634c97..09981d0 100644 --- a/Competitive programming/C++/Print Subsets of Array.cpp +++ b/Competitive programming/C++/Print Subsets of Array.cpp @@ -1,8 +1,6 @@ // - #include using namespace std; - void printSubsetsOfArray(int input[], int size,int output[],int len) { if(size==0){ for(int i=0;i> input[i]; printSubsetsOfArray(input, length); -} \ No newline at end of file +} From 5ab08827ac5da1dcfa6e5fa6aa5c1e10a1091e92 Mon Sep 17 00:00:00 2001 From: sktagrwl <65661745+sktagrwl@users.noreply.github.com> Date: Mon, 4 Oct 2021 03:33:01 +0530 Subject: [PATCH 083/142] Create GCDalgo.java --- Algorithms/GCDalgo.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Algorithms/GCDalgo.java diff --git a/Algorithms/GCDalgo.java b/Algorithms/GCDalgo.java new file mode 100644 index 0000000..7eb052c --- /dev/null +++ b/Algorithms/GCDalgo.java @@ -0,0 +1,37 @@ +import java.util.Scanner; + +public class GCD { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + Scanner sc = new Scanner(System.in); + int a = sc.nextInt(); + int b = sc.nextInt(); + int gcd = 0; + + + if (a>b) + { + gcd = b; + } + else if (b>a) + { + gcd = a; + } + + while(true) + { + if(a% gcd ==0 && b% gcd==0) + { + System.out.println(gcd); + break; + } + --gcd; + } + + + + } + +} From 39c64a276a1dd8601365f3d0ec590e4738191853 Mon Sep 17 00:00:00 2001 From: ravi4713 <4713rkr@gmail.com> Date: Mon, 4 Oct 2021 07:50:25 +0530 Subject: [PATCH 084/142] added question for check bst in amazon section --- .../Amazon/check_for_BST/questions.txt | 48 +++++++++++++++++++ .../Amazon/check_for_BST/solution.cpp | 26 ++++++++++ 2 files changed, 74 insertions(+) create mode 100644 CompanywiseSolution/Amazon/check_for_BST/questions.txt create mode 100644 CompanywiseSolution/Amazon/check_for_BST/solution.cpp diff --git a/CompanywiseSolution/Amazon/check_for_BST/questions.txt b/CompanywiseSolution/Amazon/check_for_BST/questions.txt new file mode 100644 index 0000000..76ab97d --- /dev/null +++ b/CompanywiseSolution/Amazon/check_for_BST/questions.txt @@ -0,0 +1,48 @@ +Given the root of a binary tree. Check whether it is a BST or not. +Note: We are considering that BSTs can not contain duplicate Nodes. +A BST is defined as follows: + The left subtree of a node contains only nodes with keys less than the node's key. + The right subtree of a node contains only nodes with keys greater than the node's key. + Both the left and right subtrees must also be binary search trees. + +Example 1: + +Input: + 2 + / \ +1 3 +Output: 1 +Explanation: +The left subtree of root node contains node +with key lesser than the root node’s key and +the right subtree of root node contains node +with key greater than the root node’s key. +Hence, the tree is a BST. + +Example 2: + +Input: + 2 + \ + 7 + \ + 6 + \ + 5 + \ + 9 + \ + 2 + \ + 6 +Output: 0 +Explanation: +Since the node with value 7 has right subtree +nodes with keys less than 7, this is not a BST. +Your Task: +You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree as a parameter and returns true if the given binary tree is BST, else returns false. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(Height of the BST). + + diff --git a/CompanywiseSolution/Amazon/check_for_BST/solution.cpp b/CompanywiseSolution/Amazon/check_for_BST/solution.cpp new file mode 100644 index 0000000..c077ff2 --- /dev/null +++ b/CompanywiseSolution/Amazon/check_for_BST/solution.cpp @@ -0,0 +1,26 @@ +class Solution +{ + public: + //Function to check whether a Binary Tree is BST or not. + bool helper(Node* root, int min, int max){ + if (root == NULL){ + return true; + } + if (root->data < min ){ + return false; + } + if (root->data >= max){ + return false; + } + return helper(root->left, min, root->data) && helper(root->right, root->data, max); + + } + bool isBST(Node* root) + { + // Your code here + int min = -1000001; + int max = 1000001; + + return helper(root, min, max); + } +}; From 1a57c6288df905e070afb23a4c8ca318144dd10b Mon Sep 17 00:00:00 2001 From: pallavieee <76172609+pallavieee@users.noreply.github.com> Date: Mon, 4 Oct 2021 09:02:52 +0530 Subject: [PATCH 085/142] Create Merge sort.c --- Competitive programming/C/Merge sort.c | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Competitive programming/C/Merge sort.c diff --git a/Competitive programming/C/Merge sort.c b/Competitive programming/C/Merge sort.c new file mode 100644 index 0000000..239b28a --- /dev/null +++ b/Competitive programming/C/Merge sort.c @@ -0,0 +1,60 @@ +#include + +void merge(int Array[],int iterator1,int j1,int iterator2,int j2) +{ + int TemporaryArray[50]; //array used for merging + int i,j,k; + i=iterator1; //beginning of the first list + j=iterator2; //beginning of the second list + k=0; + + while(i<=j1 && j<=j2) //while elements in both lists + { + if(Array[i] Date: Mon, 4 Oct 2021 09:06:57 +0530 Subject: [PATCH 086/142] Create circular queue.c --- Algorithms/circular queue.c | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Algorithms/circular queue.c diff --git a/Algorithms/circular queue.c b/Algorithms/circular queue.c new file mode 100644 index 0000000..19b3748 --- /dev/null +++ b/Algorithms/circular queue.c @@ -0,0 +1,50 @@ +#include +#include +#define size 3 +void insert(); +void delete(); +void display(); +int front=-1; +int rear =-1; +int a[size]; +int main() +{ + int d; + printf("\n\n\n LIST OF CHOICES AND MENU"); + printf("=========================>>"); + printf("\n 1. insert"); + printf("\n 2. delete"); + printf("\n 3. DISPLAY"); + printf("\n 4. BYE BYE"); + while(1) + { + printf("\n\n enter your choice="); + scanf("%d",&d); + switch(d) + { + case 1: + { + insert(); + break; + } + case 2: + { + delete(); + break; + } + case 3: + { + display(); + break; + } + case 4: + { + exit(0); + } + default: + { + printf("\n INVALID INPUT !!!!!!"); + } + } + } + } From d7306384ca2db66a01de245f49d21d2084e7ae75 Mon Sep 17 00:00:00 2001 From: Lokender10 <71983411+Lokender10@users.noreply.github.com> Date: Mon, 4 Oct 2021 10:22:24 +0530 Subject: [PATCH 087/142] Create Insertion_sort.cpp --- Algorithms/Insertion_sort.cpp | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Algorithms/Insertion_sort.cpp diff --git a/Algorithms/Insertion_sort.cpp b/Algorithms/Insertion_sort.cpp new file mode 100644 index 0000000..b65d2a1 --- /dev/null +++ b/Algorithms/Insertion_sort.cpp @@ -0,0 +1,47 @@ +// C++ program for insertion sort +#include +using namespace std; + +/* Function to sort an array using insertion sort*/ +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + /* Move elements of arr[0..i-1], that are + greater than key, to one position ahead + of their current position */ + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + +// A utility function to print an array of size n +void printArray(int arr[], int n) +{ + int i; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + cout << endl; +} + +/* Driver code */ +int main() +{ + int arr[] = { 12, 11, 13, 5, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + + insertionSort(arr, n); + printArray(arr, n); + + return 0; +} + +// This is code is contributed by rathbhupendra From 59154bdee05064ec2c6b40fa967add484fbfcb89 Mon Sep 17 00:00:00 2001 From: Srishti Agrawal Date: Mon, 4 Oct 2021 10:53:37 +0530 Subject: [PATCH 088/142] lexicographically minimum rotation of a string C++ program to find lexicographically minimum rotation of a given string --- .../C++/LexicographicallyMinimumString | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Competitive programming/C++/LexicographicallyMinimumString diff --git a/Competitive programming/C++/LexicographicallyMinimumString b/Competitive programming/C++/LexicographicallyMinimumString new file mode 100644 index 0000000..9729293 --- /dev/null +++ b/Competitive programming/C++/LexicographicallyMinimumString @@ -0,0 +1,24 @@ +//srishti1302 + +#include +#include +using namespace std; + +string minLexRotation(string str) +{ + + int n = str.length(); + string arr[n]; + string concat = str + str; + for (int i = 0; i < n; i++) + arr[i] = concat.substr(i, n); + sort(arr, arr+n); + return arr[0]; +} + +int main() +{ string str; + cout<<"Enter string:"; + cin>>str; + cout << minLexRotation(str) << endl; +} From 1c36543eb9df7d45fcaa2226e6d3cef614916d0d Mon Sep 17 00:00:00 2001 From: Akarshan Kumar Date: Mon, 4 Oct 2021 12:09:54 +0530 Subject: [PATCH 089/142] Delete c_cpp_properties.json --- .vscode/c_cpp_properties.json | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index 9e3848d..0000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "configurations": [ - { - "name": "Win32", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [ - "_DEBUG", - "UNICODE", - "_UNICODE" - ], - "compilerPath": "C:\\MinGW\\bin\\gcc.exe", - "cStandard": "gnu17", - "cppStandard": "gnu++14", - "intelliSenseMode": "windows-gcc-x86" - } - ], - "version": 4 -} \ No newline at end of file From bfc397dfc6f242c2cc9c43d7d420e442197ffc88 Mon Sep 17 00:00:00 2001 From: pandapritish25 Date: Mon, 4 Oct 2021 12:12:28 +0530 Subject: [PATCH 090/142] deshaw_company_question --- .../Amazon/deshaw/question.txt | 28 ++++ .../Amazon/deshaw/search_in_a_sortedarray.cpp | 127 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 CompanywiseSolution/Amazon/deshaw/question.txt create mode 100644 CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp diff --git a/CompanywiseSolution/Amazon/deshaw/question.txt b/CompanywiseSolution/Amazon/deshaw/question.txt new file mode 100644 index 0000000..332de55 --- /dev/null +++ b/CompanywiseSolution/Amazon/deshaw/question.txt @@ -0,0 +1,28 @@ +Search a number in a sorted rotated array. Basically an array is given +and its is rotated or pivoted from a certain index . Basically we have ro +tell that an element is present or not in that array + +sample input +input line 1- enter the number of elements +input line 2-enter the key needed to find +input line 3- enter all the elements to this + + +output line 1-basically print the index of the element if present +else print a -1 if not present + +example1- +input +9 +10 +5 6 7 8 9 10 1 2 3 + +output-5 + +example-2 +9 +15 +5 6 7 8 9 10 1 2 3 + +output- (-1) + diff --git a/CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp b/CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp new file mode 100644 index 0000000..85ff7c0 --- /dev/null +++ b/CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp @@ -0,0 +1,127 @@ +#include +#include +#include +#include +#include +using namespace std; +#define pb push_back +#define fz(i,a,b) for(ll i=a; i=b; i--) +#define debug(x) cout << #x << " " << x << endl; +typedef long long int ll; +typedef long double lld; + +/*#define debug(x); +printf(x);*/ + +void init() +{ + #ifndef ONLINE_JUDGE + freopen("input.txt" , "r" ,stdin); + freopen("output.txt" , "w" ,stdout); + #endif + +} + +void debugger() +{ + #ifndef ONLINE_JUDGE + freopen("input.txt" , "r" ,stdin); + freopen("output.txt" , "w" ,stdout); + #endif + #ifdef debugger + #define debug(x) cerr << #x<<" "; _print(x); cerr << endl; + #else + #define debugger(x); + #endif +} + + +const int MAXN = (int)((1e5) + 100); +int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);} +int max(int a, int b) {if (a > b) return a; else return b;} +int min(int a, int b) {if (a < b) return a; else return b;} + + +void precision(int a) +{ + cout << setprecision(a) << fixed; +} + + +//** pritishcf307 **// +//**------------------------------------------------------------------------------------------------------**// + + + +int main() +{ + init(); + +ll n; +cin >> n; +ll x; +cin >> x; +bool found=false; +vector v; +for(int i=0;i> a; + v.push_back(a); +} + +ll lo=0; +ll hi=n-1; +ll mid,ans; + +while(hi-lo >= 0) +{ + mid=(lo+hi)/2; + if(v[mid]==x) + { + found=true; + ans=mid; + break; + } + //left part is sorted + else if(v[lo] <= v[mid]) + { + if(x>=v[lo] && x<=v[mid]) + { + hi=mid-1; + } + else + { + lo=mid+1; + } + } + else + { + if(x>=v[mid] && x<=v[hi]) + { + lo=mid+1; + } + else + { + hi=mid-1; + } + } +} + if(found==true) + { + cout << ans << endl; + } + else + { + cout << -1 << endl; + } + return 0; +} + + + + + + + From 8bda511c3d1c97c52db7a9007f93e2e600c8861b Mon Sep 17 00:00:00 2001 From: pandapritish25 Date: Mon, 4 Oct 2021 12:16:15 +0530 Subject: [PATCH 091/142] move to company wise solution --- CompanywiseSolution/{Amazon => }/deshaw/question.txt | 0 .../{Amazon => }/deshaw/search_in_a_sortedarray.cpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/{Amazon => }/deshaw/question.txt (100%) rename CompanywiseSolution/{Amazon => }/deshaw/search_in_a_sortedarray.cpp (100%) diff --git a/CompanywiseSolution/Amazon/deshaw/question.txt b/CompanywiseSolution/deshaw/question.txt similarity index 100% rename from CompanywiseSolution/Amazon/deshaw/question.txt rename to CompanywiseSolution/deshaw/question.txt diff --git a/CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp b/CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp similarity index 100% rename from CompanywiseSolution/Amazon/deshaw/search_in_a_sortedarray.cpp rename to CompanywiseSolution/deshaw/search_in_a_sortedarray.cpp From af3d235177eb69e9caff6eb775c12f57e949da06 Mon Sep 17 00:00:00 2001 From: Avirat Gupta <55698467+AviratGupta@users.noreply.github.com> Date: Mon, 4 Oct 2021 14:44:55 +0530 Subject: [PATCH 092/142] =?UTF-8?q?Create=20Brian=20Kernighan=E2=80=99s=20?= =?UTF-8?q?Algorithm.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brian Kernighan’s Algorithm in python. counting set bits code. --- .../Brian Kernighan\342\200\231s Algorithm.py" | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 "Algorithms/Brian Kernighan\342\200\231s Algorithm.py" diff --git "a/Algorithms/Brian Kernighan\342\200\231s Algorithm.py" "b/Algorithms/Brian Kernighan\342\200\231s Algorithm.py" new file mode 100644 index 0000000..e9ad979 --- /dev/null +++ "b/Algorithms/Brian Kernighan\342\200\231s Algorithm.py" @@ -0,0 +1,12 @@ +def countSetBits(n): + + count = 0 + while (n): + n &= (n-1) + count+= 1 + return count + + +# Program to test function countSetBits +i = 9 +print(countSetBits(i) From a457063d011228fc64267141e8d6e21ebbc8269a Mon Sep 17 00:00:00 2001 From: Shivam Jaiswal Date: Mon, 4 Oct 2021 15:15:14 +0530 Subject: [PATCH 093/142] Kindergarten_Adventures Hackerrank Solutionin C++ --- .../C++/Kindergarten_Adventures.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Competitive programming/C++/Kindergarten_Adventures.cpp diff --git a/Competitive programming/C++/Kindergarten_Adventures.cpp b/Competitive programming/C++/Kindergarten_Adventures.cpp new file mode 100644 index 0000000..835bd42 --- /dev/null +++ b/Competitive programming/C++/Kindergarten_Adventures.cpp @@ -0,0 +1,38 @@ +#include +using namespace std; + +int main() { + int N; + cin >> N; + vector A(N); + for(int i = 0; i < N; i++) { + cin >> A[i]; + } + + int start = 0; + + vector D(N+1, 0); + for(int i = 0; i < N; i++) { + if(A[i] <= i) { + start++; + D[i-A[i]]--; + D[i]++; + } else { + D[i-A[i]+N]--; + D[i]++; + } + } + + int best = start; + int bi = 0; + int cur = start; + for(int i = 0; i < N; i++) { + if(cur > best) { + best = cur; + bi = i; + } + cur += D[i]; + } + + cout << (bi+1) << endl; +} \ No newline at end of file From 48e51e513f9f47e9b83d9bad17c4c74886059bb9 Mon Sep 17 00:00:00 2001 From: Anisha100 <87559560+Anisha100@users.noreply.github.com> Date: Mon, 4 Oct 2021 18:04:53 +0530 Subject: [PATCH 094/142] Create longest_rep_sub_sequence.java --- .../JAVA/longest_rep_sub_sequence.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Competitive programming/JAVA/longest_rep_sub_sequence.java diff --git a/Competitive programming/JAVA/longest_rep_sub_sequence.java b/Competitive programming/JAVA/longest_rep_sub_sequence.java new file mode 100644 index 0000000..83b5b71 --- /dev/null +++ b/Competitive programming/JAVA/longest_rep_sub_sequence.java @@ -0,0 +1,23 @@ +import java.io.*; +import java.util.*; + +class Main { + static int LongestRepSubSeq(String str) { + int n = str.length(); + int[][] dp = new int[n + 1][n + 1]; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); + } + } + return dp[n][n]; + } + + public static void main(String[] args) { + String str = "HHHHHHaaaacccckTTToberFFFeest"; + System.out.println("The length of the largest subsequence that repeats itself is : " + LongestRepSubSeq(str)); + } +} From 3909913c00de765dc4ffea425a293ad291ce8abd Mon Sep 17 00:00:00 2001 From: Anisha100 <87559560+Anisha100@users.noreply.github.com> Date: Mon, 4 Oct 2021 18:11:07 +0530 Subject: [PATCH 095/142] Create 0001spiral_traversal_2d.java --- .../JAVA/0001spiral_traversal_2d.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Competitive programming/JAVA/0001spiral_traversal_2d.java diff --git a/Competitive programming/JAVA/0001spiral_traversal_2d.java b/Competitive programming/JAVA/0001spiral_traversal_2d.java new file mode 100644 index 0000000..2c20bb7 --- /dev/null +++ b/Competitive programming/JAVA/0001spiral_traversal_2d.java @@ -0,0 +1,55 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class SpiralTraversalOf2DArray { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Enter number of rows"); + int row = scanner.nextInt(); + System.out.println("Enter number of column"); + int column = scanner.nextInt(); + int[][] matrix = new int[row][column]; + System.out.println("Enter the elements of 2X2 matrix"); + for (int i = 0; i < row; i++) { + System.out.println("Enter "+ column +" elements for " + i +" row"); + for (int j = 0; j < column; j++) { + matrix[i][j] = scanner.nextInt(); + } + } + List traversalList = spiralTraversal(matrix); + printTraversal(traversalList); + } + public static List spiralTraversal(int matrix[][]){ + List ans = new ArrayList(); + if(matrix.length == 0){ + return ans; + } + int row = matrix.length, column = matrix[0].length; + boolean[][] seen = new boolean[row][column]; + int[] dr = {0, 1, 0, -1}; + int[] dc = {1, 0, -1, 0}; + int r=0, c=0, di=0, cr=0, cc=0; + for (int i = 0; i < row * column; i++) { + ans.add(matrix[r][c]); + seen[r][c] = true; + cr = r + dr[di]; + cc = c + dc[di]; + if(0<=cr && cr list){ + for (int i = 0; i < list.size(); i++) { + System.out.print(list.get(i)+ ((i Date: Mon, 4 Oct 2021 19:09:28 +0530 Subject: [PATCH 096/142] Add files via upload --- Competitive programming/C/Find Remainder.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Competitive programming/C/Find Remainder.c diff --git a/Competitive programming/C/Find Remainder.c b/Competitive programming/C/Find Remainder.c new file mode 100644 index 0000000..204009b --- /dev/null +++ b/Competitive programming/C/Find Remainder.c @@ -0,0 +1,18 @@ +#include + +int main() +{ + int T; + scanf("%d", &T); + while (T--) + { + + int a, b; + scanf("%d %d", &a, &b); + + int ans =a%b ; + printf("%d\n", ans); + } + + return 0; +} \ No newline at end of file From 398fde883f7acb70d76decd119af057145b9a65d Mon Sep 17 00:00:00 2001 From: Prajnakalpa Mishra <56736266+prajnakalpa@users.noreply.github.com> Date: Mon, 4 Oct 2021 19:10:24 +0530 Subject: [PATCH 097/142] Add files via upload --- Competitive programming/C++/Ceiling Sum.cpp | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Competitive programming/C++/Ceiling Sum.cpp diff --git a/Competitive programming/C++/Ceiling Sum.cpp b/Competitive programming/C++/Ceiling Sum.cpp new file mode 100644 index 0000000..8154e78 --- /dev/null +++ b/Competitive programming/C++/Ceiling Sum.cpp @@ -0,0 +1,36 @@ +#include +using namespace std ; + +#define ff first +#define ss second +#define ull unsigned long long +#define mod 1000000007 +#define inf 1e18 +#define w(x) int x;cin>>x;while(x--) +#define f(x,y) for( x=0;x>a>>b; + s1=ceil((b-(a-1))/2)+ceil(((a-1)-a)/2); + s2=ceil((b-(a+1))/2)+ceil(((a+1)-a)/2); + // cout<<"i is "<b){ + x=s1; + } + else{ + x=s2; + } cout< Date: Mon, 4 Oct 2021 20:01:24 +0530 Subject: [PATCH 098/142] Added Solution to Arrays Left Rotation --- .../C++/Arrays_Left_Rotation.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Competitive programming/C++/Arrays_Left_Rotation.cpp diff --git a/Competitive programming/C++/Arrays_Left_Rotation.cpp b/Competitive programming/C++/Arrays_Left_Rotation.cpp new file mode 100644 index 0000000..2bc0010 --- /dev/null +++ b/Competitive programming/C++/Arrays_Left_Rotation.cpp @@ -0,0 +1,33 @@ +#include +#include + +using namespace std; + +int main() +{ + int n,d,x; + cin>>n>>d; + vector a; + for(int i=0;i>x; + a.push_back(x); + } + + vector b; + // //int n = a.size(); + int k = d%n; + //b[0] = a[k]; + b.push_back(a[k]); + for(int i=k+1;i Date: Mon, 4 Oct 2021 20:33:44 +0530 Subject: [PATCH 099/142] Added Priority Queue in Java --- .../JAVA/PriorityQueue.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Competitive programming/JAVA/PriorityQueue.java diff --git a/Competitive programming/JAVA/PriorityQueue.java b/Competitive programming/JAVA/PriorityQueue.java new file mode 100644 index 0000000..c8d45c3 --- /dev/null +++ b/Competitive programming/JAVA/PriorityQueue.java @@ -0,0 +1,87 @@ +public class Priorityqueue { + + public static void main(String[] args) { + + } + +} + +// Implement a priority queue using one of the above implemented linked lists +class PriorityQ { + + static Node head, rear; + + // Linked List Node + static class Node { + + int data; + int priority; + Node prev, next; + } + + // Function to insert a new Node + static void push(Node fItem, Node rItem, int n, int p) { + Node newNode = new Node(); + newNode.data = n; + newNode.priority = p; + + // If linked list is empty + if (fItem == null) { + fItem = newNode; + rItem = newNode; + newNode.next = null; + } else { + + if (p <= (fItem).priority) { + newNode.next = fItem; + (fItem).prev = newNode.next; + fItem = newNode; + } + else if (p > (rItem).priority) { + newNode.next = null; + (rItem).next = newNode; + newNode.prev = (rItem).next; + rItem = newNode; + } // Handle other cases + else { + + // Find position where we need to + // insert. + Node start = (fItem).next; + while (start.priority > p) { + start = start.next; + } + (start.prev).next = newNode; + newNode.next = start.prev; + newNode.prev = (start.prev).next; + start.prev = newNode.next; + } + } + head = fItem; + rear = rItem; + } + + // Return the value at rear + static int peek(Node fItem) { + return fItem.data; + } + + static boolean isEmpty(Node fItem) { + return (fItem == null); + } + + // Removes the element with the + // least priority value form the list + static int pop(Node fItem, Node rItem) { + Node temp = fItem; + int res = temp.data; + (fItem) = (fItem).next; + if (fItem == null) { + fItem = null; + } + + head = fItem; + rear = rItem; + return res; + } +} From e75fba9356f3a378989bba7fb56813031e4debcf Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 21:38:50 +0530 Subject: [PATCH 100/142] Create Count set bits in a integer.cpp --- .../Count set bits in a integer.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp new file mode 100644 index 0000000..dbe1e91 --- /dev/null +++ b/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int numberofones(int n) { + int count = 0; + while (n) { + n = n & (n - 1); + count++; + } + return count; +} + +int main() { + int n; + cin>>n; + + cout< Date: Mon, 4 Oct 2021 21:40:38 +0530 Subject: [PATCH 101/142] Delete KMP_Algo.c --- KMP_Algo.c | 57 ------------------------------------------------------ 1 file changed, 57 deletions(-) delete mode 100644 KMP_Algo.c diff --git a/KMP_Algo.c b/KMP_Algo.c deleted file mode 100644 index c8fe930..0000000 --- a/KMP_Algo.c +++ /dev/null @@ -1,57 +0,0 @@ -//srishti1302 -#include -#include -int failure[20]; -void fail(char *pat) -{ - int i,j; - int n=strlen(pat); - failure[0]=-1; - for(j=1;j0)) - i=failure[i]; - if(pat[j]==pat[i+1]) - failure[j]=i+1; - else - failure[j]=-1; - } - for(int k=0;k<=n;k++) - printf("%d\t",failure[k]); -} -int match(char *string, char *pat) -{ - int i=0,j=0; - int lens=strlen(string); - int lenp=strlen(pat); - while(i Date: Mon, 4 Oct 2021 21:41:05 +0530 Subject: [PATCH 102/142] Revert "Mergesort" --- Algorithms/Mergesort.java | 93 ------------------- .../C++/LexicographicallyMinimumString | 24 ----- 2 files changed, 117 deletions(-) delete mode 100644 Algorithms/Mergesort.java delete mode 100644 Competitive programming/C++/LexicographicallyMinimumString diff --git a/Algorithms/Mergesort.java b/Algorithms/Mergesort.java deleted file mode 100644 index 71458e6..0000000 --- a/Algorithms/Mergesort.java +++ /dev/null @@ -1,93 +0,0 @@ -//srishti1302 -import java.util.*; -public class MergeSort -{ - void merge(int arr[], int l, int m, int r) - { - int n1 = m - l + 1; - int n2 = r - m; - int L[] = new int [n1]; - int R[] = new int [n2]; - for (int i=0; i -#include -using namespace std; - -string minLexRotation(string str) -{ - - int n = str.length(); - string arr[n]; - string concat = str + str; - for (int i = 0; i < n; i++) - arr[i] = concat.substr(i, n); - sort(arr, arr+n); - return arr[0]; -} - -int main() -{ string str; - cout<<"Enter string:"; - cin>>str; - cout << minLexRotation(str) << endl; -} From b4b67c1e0c6a301ae6c66076d7b12c2576af78cd Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 21:47:10 +0530 Subject: [PATCH 103/142] Added some Bit Manipulation problems --- .../Bit Manipulation/2unique_numbers.cpp | 35 +++++++++++++++++++ .../Bit Manipulation/3unique_numbers.cpp | 32 +++++++++++++++++ .../copy_set_bits_in_range.cpp | 24 +++++++++++++ .../count_setbits_from_1_to_n.cpp | 25 +++++++++++++ .../Bit Manipulation/divide_integer_by_2.cpp | 18 ++++++++++ .../numbers_bits_to_be_flipped.cpp | 19 ++++++++++ 6 files changed, 153 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/3unique_numbers.cpp create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/copy_set_bits_in_range.cpp create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/count_setbits_from_1_to_n.cpp create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/divide_integer_by_2.cpp create mode 100644 CompanywiseSolution/Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp new file mode 100644 index 0000000..c8b563d --- /dev/null +++ b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +int setBit(int n, int pos) { + return ((n & (1 << pos)) != 0); +} +void uniquenumber(int arr[], int n) { + int xorsum = 0; + for (int i = 0; i < n; i++) { + xorsum = xorsum ^ arr[i]; + } + int tempxor = xorsum; + int setbit = 0; + int pos = 0; + while (setbit != 1) { + setbit = xorsum & 1; + pos++; + xorsum = xorsum >> 1; + } + int newxor = 0; + for (int i = 0; i < n; i++) { + if (setBit(arr[i], pos - 1)) { + newxor = newxor ^ arr[i]; + } + } + cout< +using namespace std; + +int getBit(int n, int pos) { + return ((n & (1 << pos)) != 0); +} + +int setBit(int n, int pos) { + return (n | (1 << pos)); +} +int uniquenumber(int arr[], int n) { + int result = 0; + for (int i = 0; i < 64; i++) { + int sum = 0; + for (int j = 0; j < n; j++) { + if (getBit(arr[j], i)) { + sum++; + } + } + if (sum % 3 != 0) { + result = setBit(result, i); + } + } + return result; +} + +int main() { + int arr[] = {1,2,3,4,1,2,3,1,2,3}; + + cout< +using namespace std; + +int copysetbits(int x, int y, int l, int r) { + if (1 < l || r > 32) { + return false; + } + + for (int i = l; i <= r; i++) { + int mask = 1 << (i - 1); + + if (y & mask) { + x = x | mask; + } + } + return x; +} + +int main () { + int x, y, l, r; + cin>>x>>y>>l>>r; + cout< +using namespace std; + +int countsetbitsutil(int x) { + if ( x <= 0) { + return 0; + } + return (x % 2 == 0 ? 0 : 1) + countsetbitsutil(x / 2); +} + +int numberofones(int n) { + int count = 0; + for (int i = 0; i <= n; i++) { + count += countsetbitsutil(i); + } + return count; +} + +int main() { + int n; + cin>>n; + + cout< +using namespace std; + +int divide2int(int n) { + if (n == 0) { + return 0; + } + + int x = n >> 1; + return x; +} + +int main() { + int n; + cin>>n; + cout< +using namespace std; + +int flipped(int a, int b) { + int ans = a ^ b; + int count = 0; + while (ans) { + ans = ans & (ans - 1); + count++; + } + return count; +} + +int main () { + int a,b; + cin>>a>>b; + + cout< Date: Mon, 4 Oct 2021 21:49:29 +0530 Subject: [PATCH 104/142] Permutation Minimization by Deque --- .../C++/Permutation Minimization by Deque.c | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Competitive programming/C++/Permutation Minimization by Deque.c diff --git a/Competitive programming/C++/Permutation Minimization by Deque.c b/Competitive programming/C++/Permutation Minimization by Deque.c new file mode 100644 index 0000000..40e6166 --- /dev/null +++ b/Competitive programming/C++/Permutation Minimization by Deque.c @@ -0,0 +1,50 @@ +//https://codeforces.com/contest/1579/problem/E1 + +#include +using namespace std; +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + deque v; + for(int i=0;i>x; + if(i==0) + v.push_back(x); + + int x1=v[0]; + int x2=v[v.size()-1]; + if(i!=0) + { + if(x==x1) + v.push_front(x); + else if (x==x2) + v.push_back(x); + if(xx2 && x>x1) + v.push_back(x); + else if(x>x1 && xx2 && x Date: Mon, 4 Oct 2021 21:52:46 +0530 Subject: [PATCH 105/142] Committing KadanesAlgo.java --- Algorithms/KadanesAlgo.java | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Algorithms/KadanesAlgo.java diff --git a/Algorithms/KadanesAlgo.java b/Algorithms/KadanesAlgo.java new file mode 100644 index 0000000..510c426 --- /dev/null +++ b/Algorithms/KadanesAlgo.java @@ -0,0 +1,38 @@ +class KadanesAlgo +{ + // Function to find the maximum sum of a contiguous subarray + // in a given integer array + public static int kadane(int[] A) + { + // stores the maximum sum subarray found so far + int maxSoFar = 0; + + // stores the maximum sum of subarray ending at the current position + int maxEndingHere = 0; + + // traverse the given array + for (int i: A) + { + // update the maximum sum of subarray "ending" at index `i` (by adding the + // current element to maximum sum ending at previous index `i-1`) + maxEndingHere = maxEndingHere + i; + + // if the maximum sum is negative, set it to 0 (which represents + // an empty subarray) + maxEndingHere = Integer.max(maxEndingHere, 0); + + // update the result if the current subarray sum is found to be greater + maxSoFar = Integer.max(maxSoFar, maxEndingHere); + } + + return maxSoFar; + } + + public static void main(String[] args) + { + int[] A = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; + + System.out.println("The sum of contiguous subarray with the " + + "largest sum is " + kadane(A)); + } +} From cc18238edadf0d9ce13c73c7b7e0483b3f8b2bfa Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 21:56:54 +0530 Subject: [PATCH 106/142] Update 2unique_numbers.cpp --- .../Bit Manipulation/2unique_numbers.cpp | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp index c8b563d..16461a4 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/2unique_numbers.cpp @@ -1,3 +1,23 @@ +// Problem Statement - Given an array in which all numbers except two are repeated once. +// (i.e. we have 2n+2 numbers and n numbers are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way. + +/* Examples - +Input: = 2 +arr[] = {1, 2, 3, 2, 1, 4} +Output: +3 4 +Explanation: +3 and 4 occur exactly once. + +Input: +N = 1 +arr[] = {2, 1, 3, 2} +Output: +1 3 +Explanation: +1 3 occur exactly once. +*/ + #include using namespace std; @@ -32,4 +52,4 @@ int main() { uniquenumber(arr,8); return 0; -} \ No newline at end of file +} From c57adb0cc189d1c3f1886d61764c0591b8e35b14 Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 21:59:35 +0530 Subject: [PATCH 107/142] Update 3unique_numbers.cpp --- .../Amazon/Bit Manipulation/3unique_numbers.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/3unique_numbers.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/3unique_numbers.cpp index 9bec885..dd43535 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/3unique_numbers.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/3unique_numbers.cpp @@ -1,3 +1,18 @@ +/* Given an array of integers, every element appears thrice except for one which occurs once. + +Find that element which does not appear thrice. + + +Example Input 1: A = [1, 2, 4, 3, 3, 2, 2, 3, 1, 1] +Example Output 1: 4 +Explanation: + 4 occur exactly once +Example Input 2: A = [0, 0, 0, 1] +Example Output 2: 1 +*/ + + + #include using namespace std; @@ -29,4 +44,4 @@ int main() { cout< Date: Mon, 4 Oct 2021 22:03:02 +0530 Subject: [PATCH 108/142] Update Count set bits in a integer.cpp --- .../Count set bits in a integer.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp index dbe1e91..47e42ce 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/Count set bits in a integer.cpp @@ -1,3 +1,19 @@ +/* Problem-Statement - Given a positive integer N, print count of set bits in it. + +Examples - Input: N = 6 +Output: 2 +Explanation: +Binary representation is '110' +So the count of the set bit is 2. + +Input: 8 +Output: 1 +Explanation: +Binary representation is '1000' +So the count of the set bit is 1. +*/ + + #include using namespace std; From f247e614b743bad1bfe2dfb3259aa3d6d2978e72 Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 22:06:43 +0530 Subject: [PATCH 109/142] Update copy_set_bits_in_range.cpp --- .../Bit Manipulation/copy_set_bits_in_range.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/copy_set_bits_in_range.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/copy_set_bits_in_range.cpp index e548e6d..b0d016a 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/copy_set_bits_in_range.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/copy_set_bits_in_range.cpp @@ -1,3 +1,18 @@ +/* Problem-Statement - Given two numbers x and y, and a range [l, r] where 1 <= l, r <= 32. The task is consider set bits of y in range [l, r] and set these bits in x also. + +Examples - +Input : x = 10, y = 13, l = 2, r = 3 +Output : x = 14 +Binary representation of 10 is 1010 and +that of y is 1101. There is one set bit +in y at 3'rd position (in given range). +After we copy this bit to x, x becomes 1110 +which is binary representation of 14. + +Input : x = 8, y = 7, l = 1, r = 2 +Output : x = 11 +*/ + #include using namespace std; @@ -21,4 +36,4 @@ int main () { cin>>x>>y>>l>>r; cout< Date: Mon, 4 Oct 2021 22:07:01 +0530 Subject: [PATCH 110/142] Add Symmetric Tree Question --- .../C++/Symmetric_Tree.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Competitive programming/C++/Symmetric_Tree.cpp diff --git a/Competitive programming/C++/Symmetric_Tree.cpp b/Competitive programming/C++/Symmetric_Tree.cpp new file mode 100644 index 0000000..6f0484a --- /dev/null +++ b/Competitive programming/C++/Symmetric_Tree.cpp @@ -0,0 +1,22 @@ +// Link for Question-->https://leetcode.com/problems/symmetric-tree/ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + return check(root->left,root->right); + } + bool check(TreeNode* r1,TreeNode* r2){ + if(r1==NULL && r2==NULL)// if left and root null + { + return true; + } + else if(r1==NULL || r2==NULL || r1->val!=r2->val) //one is not null + { + return false; + } + else{ + //comparing left subtree's left child with right subtree's + //right child AND comparing left subtree's right child with right subtree's left child + return check(r1->left,r2->right) && check(r1->right,r2->left); + } + } +}; \ No newline at end of file From db5774f3051532c53ca067bc37371bc8c4667c20 Mon Sep 17 00:00:00 2001 From: Pranav Chaturvedi <61840685+pchat99@users.noreply.github.com> Date: Mon, 4 Oct 2021 22:08:10 +0530 Subject: [PATCH 111/142] Update count_setbits_from_1_to_n.cpp --- .../count_setbits_from_1_to_n.cpp | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/count_setbits_from_1_to_n.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/count_setbits_from_1_to_n.cpp index 6aa90d3..02a9eb2 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/count_setbits_from_1_to_n.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/count_setbits_from_1_to_n.cpp @@ -1,3 +1,23 @@ +/* Problem Statement - You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive). + +Examples - Input: N = 4 +Output: 5 +Explanation: +For numbers from 1 to 4. +For 1: 0 0 1 = 1 set bits +For 2: 0 1 0 = 1 set bits +For 3: 0 1 1 = 2 set bits +For 4: 1 0 0 = 1 set bits +Therefore, the total set bits is 5. + + +Input: N = 17 +Output: 35 +Explanation: From numbers 1 to 17(both inclusive), +the total number of set bits is 35. +*/ + + #include using namespace std; @@ -22,4 +42,4 @@ int main() { cout< Date: Mon, 4 Oct 2021 22:09:08 +0530 Subject: [PATCH 112/142] Update divide_integer_by_2.cpp --- .../Amazon/Bit Manipulation/divide_integer_by_2.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/divide_integer_by_2.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/divide_integer_by_2.cpp index f15e52b..420d346 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/divide_integer_by_2.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/divide_integer_by_2.cpp @@ -1,3 +1,12 @@ +/* Problem Statement - Given a two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator. + +Examples - Input : a = 10, b = 3 +Output : 3 + +Input : a = 43, b = -8 +Output : -5 +*/ + #include using namespace std; @@ -15,4 +24,4 @@ int main() { cin>>n; cout< Date: Mon, 4 Oct 2021 22:10:00 +0530 Subject: [PATCH 113/142] Update numbers_bits_to_be_flipped.cpp --- .../Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CompanywiseSolution/Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp b/CompanywiseSolution/Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp index 9110e5a..997131f 100644 --- a/CompanywiseSolution/Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp +++ b/CompanywiseSolution/Amazon/Bit Manipulation/numbers_bits_to_be_flipped.cpp @@ -1,3 +1,5 @@ +/* Problem Statement - Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’. */ + #include using namespace std; @@ -16,4 +18,4 @@ int main () { cin>>a>>b; cout< Date: Tue, 5 Oct 2021 04:00:17 +0530 Subject: [PATCH 114/142] added equilibrium.java --- .../Amazon/Equilibrium Point/Equilibrium.java | 40 +++++++++++++++++++ .../Amazon/Equilibrium Point/question.md | 2 + 2 files changed, 42 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java create mode 100644 CompanywiseSolution/Amazon/Equilibrium Point/question.md diff --git a/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java b/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java new file mode 100644 index 0000000..4784527 --- /dev/null +++ b/CompanywiseSolution/Amazon/Equilibrium Point/Equilibrium.java @@ -0,0 +1,40 @@ +import java.util.Scanner; +public class Equilibrium { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + System.out.println("Enter the size of an array :"); + int N = sc.nextInt(); + long [] temp = new long[N]; + System.out.println("Enter the number: "); + for(int i =0 ; i Date: Mon, 4 Oct 2021 22:47:33 +0530 Subject: [PATCH 115/142] Create Print all Codes - String(C++)) --- .../C++/Print all Codes - String(C++)) | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Competitive programming/C++/Print all Codes - String(C++)) diff --git a/Competitive programming/C++/Print all Codes - String(C++)) b/Competitive programming/C++/Print all Codes - String(C++)) new file mode 100644 index 0000000..1478264 --- /dev/null +++ b/Competitive programming/C++/Print all Codes - String(C++)) @@ -0,0 +1,57 @@ +Question: Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. +You are given a numeric string S. Write a program to print the list of all possible codes that can be generated from the given string. + +Solution: + +#include +#include + +using namespace std; + +char itoc(int i){ //int to char + char c = 'a'+i-1; + return c; +} +int ctoi(char a){ //char to int + int i = a - '0'; + return i; +} + +void helper(string input,string output){ + if(input.length()==0){ + cout<1){ + + if(ctoi(input[0])*10+ctoi(input[1])>=10 &&ctoi(input[0])*10+ctoi(input[1])<=26){ + char c2 = itoc(ctoi(input[0])*10+ctoi(input[1])); + //output = output+c2; + helper(input.substr(2),output+c2); + //print(output); + } + } + +} +void printAllPossibleCodes(string input) { + /* + Given the input as a string, print all its possible combinations. You do not need to return anything. + */ + string output; + helper(input,output); +} + +int main(){ + string input; + cin >> input; + + printAllPossibleCodes(input); + return 0; +} From 28a7e2c42f890ab5ea9a52f72f8e581f2f04da34 Mon Sep 17 00:00:00 2001 From: MrLakshay <63330679+MrLakshay@users.noreply.github.com> Date: Mon, 4 Oct 2021 22:47:36 +0530 Subject: [PATCH 116/142] Created program for coin change problem Created program for coin change problem which uses greedy algorithm. --- Algorithms/Greedyalgo_coinchange.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Algorithms/Greedyalgo_coinchange.cpp diff --git a/Algorithms/Greedyalgo_coinchange.cpp b/Algorithms/Greedyalgo_coinchange.cpp new file mode 100644 index 0000000..f0d780e --- /dev/null +++ b/Algorithms/Greedyalgo_coinchange.cpp @@ -0,0 +1,18 @@ +/* + Author Lakshay Goel + Github profile: https://github.com/MrLakshay + Problem statement : Given coins worth 1 ,5 and 10 in unlimited quantity need to find + minimum number of coins 'x' to make 'n' sum of money input by user. + Input: n + Output : x + Exampple: + 17 + 4 +*/ +#include +using namespace std; +int main(){ + int t; + cin>>t; + cout< Date: Mon, 4 Oct 2021 23:15:00 +0530 Subject: [PATCH 117/142] Move the elements.cpp Program of Move the elements in c++. --- .../C++/Move the elements.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Competitive programming/C++/Move the elements.cpp diff --git a/Competitive programming/C++/Move the elements.cpp b/Competitive programming/C++/Move the elements.cpp new file mode 100644 index 0000000..800cec0 --- /dev/null +++ b/Competitive programming/C++/Move the elements.cpp @@ -0,0 +1,33 @@ +/* +Sample Input + +10 +-6 7 13 10 -8 15 5 -9 2 -1 +Sample Output + +7 +13 +10 +15 +5 +2 +-6 +-8 +-9 +-1 +*/ + +void moveElements(int arr[], int n){ + int key,j; + for (int i = 0; i < n; i++) + { + key = arr[i]; + j = i-1; + while (j>=0 && arr[j]<0 && key>=0) + { + arr[j+1] = arr[j]; + j--; + } + arr[j+1] = key; + } +} From 0b11dab8e47631deb505a1d9de817a8704d61980 Mon Sep 17 00:00:00 2001 From: Abhishek Gupta <90904360+ABHIGPT401@users.noreply.github.com> Date: Mon, 4 Oct 2021 23:24:39 +0530 Subject: [PATCH 118/142] BRESENHAM LINE DRAWING ALGORITHM --- Algorithms/bresenham.py | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/bresenham.py diff --git a/Algorithms/bresenham.py b/Algorithms/bresenham.py new file mode 100644 index 0000000..5826297 --- /dev/null +++ b/Algorithms/bresenham.py @@ -0,0 +1,44 @@ +# + + + + + + +import matplotlib.pyplot as plt +def bresenham(x1,y1,x2, y2): + + m = 2 * (y2 - y1) + slope_error = m - (x2 - x1) + + y=y1 + for x in range(x1,x2+1): + + print("(",x ,",",y ,")\n") + + slope_error =slope_error + m + + + if (slope_error >= 0): + y=y+1 + slope_error =slope_error - 2 * (x2 - x1) + + + +x1= int(input()) +x2= int(input()) +y1= int(input()) +y2= int(input()) + +point1 = [x1,y1] +point2 = [x2, y2] + +x_values = [point1[0], point2[0]] + + +y_values = [point1[1], point2[1]] + + +plt.plot(x_values,y_values) +plt.show() + From adffaed754b870cb883daf925084e1a61b7a3263 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Mon, 4 Oct 2021 23:25:01 +0530 Subject: [PATCH 119/142] Create Subarray With 0 sum --- .../C++/Subarray With 0 sum | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Competitive programming/C++/Subarray With 0 sum diff --git a/Competitive programming/C++/Subarray With 0 sum b/Competitive programming/C++/Subarray With 0 sum new file mode 100644 index 0000000..6e84b05 --- /dev/null +++ b/Competitive programming/C++/Subarray With 0 sum @@ -0,0 +1,35 @@ + +#include +using namespace std; + +bool subArrayExists(int arr[], int n) +{ + unordered_set sumSet; + + + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += arr[i]; + + + if (sum == 0 + || sumSet.find(sum) + != sumSet.end()) + return true; + + sumSet.insert(sum); + } + return false; +} + +int main() +{ + int arr[] = { -3, 2, -1, -1, 6 }; + int n = sizeof(arr) / sizeof(arr[0]); + if (subArrayExists(arr, n)) + cout << "Found a subarray"; + else + cout << "No Such Sub Array "; + return 0; +} From 58529280ed1fa91f62b4ae298dc5680d8a719d7f Mon Sep 17 00:00:00 2001 From: Arjun Rai <85013470+arjun-rai912@users.noreply.github.com> Date: Mon, 4 Oct 2021 23:47:05 +0530 Subject: [PATCH 120/142] Create Find_middle_of_a_linkedlist.cpp this is a code of finding the middle of a linked list in c++ with some explanation hope this helps. --- Algorithms/Find_middle_of_a_linkedlist.cpp | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Algorithms/Find_middle_of_a_linkedlist.cpp diff --git a/Algorithms/Find_middle_of_a_linkedlist.cpp b/Algorithms/Find_middle_of_a_linkedlist.cpp new file mode 100644 index 0000000..e4e7988 --- /dev/null +++ b/Algorithms/Find_middle_of_a_linkedlist.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; +class node{ + public: +int data; +node *next;//yaha address store karvana tha toh aysy likha +node(int data){ + this->data=data; + next=NULL; +} +}; +node *middlenode(node *head){ + node *slow=head; + node *fast=head->next; + while(fast && fast->next){ + slow=slow->next; + fast=fast->next->next; + } + if(fast!=NULL){ + return slow->next; + } + return slow; +} + +int main(){ + node n1(81); + node n2(27); + node n3(56); + node *head=&n1;// this head is storing the address of first link list component so that we can access the whole link list through this + n1.next=&n2; + n2.next=&n3;// this is storing address jaha pehle null stored tha + + cout<<"the middle element is "<data; + + + return 0; + + +} + + + + + +//The running time of finding the middle element this way with two pointers is O(n) because once we pass through the entire linked list of n elements, the slower pointer is at the middle node already. From ff3e62fa7d62d2eb4a133624fc167dc4b2826e32 Mon Sep 17 00:00:00 2001 From: ANKIT KUMAR Date: Tue, 5 Oct 2021 00:04:21 +0530 Subject: [PATCH 121/142] Add files via upload --- .../ADOBE/Linked_List/question.md | 26 +++ .../ADOBE/Linked_List/solution.cpp | 191 ++++++++++++++++++ 2 files changed, 217 insertions(+) create mode 100644 CompanywiseSolution/ADOBE/Linked_List/question.md create mode 100644 CompanywiseSolution/ADOBE/Linked_List/solution.cpp diff --git a/CompanywiseSolution/ADOBE/Linked_List/question.md b/CompanywiseSolution/ADOBE/Linked_List/question.md new file mode 100644 index 0000000..8989f64 --- /dev/null +++ b/CompanywiseSolution/ADOBE/Linked_List/question.md @@ -0,0 +1,26 @@ +Clone a linked list with next and random pointer. + +You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b i.e. a->arb = b. + +Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. + +For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. + +Return the head of the copied linked list. + +Example 1: + +N = 4, M = 2 +value = {1,2,3,4} +pairs = {{1,2},{2,4}} +Output: 1 +Explanation: In this test case, there +are 4 nodes in linked list. Among these +4 nodes, 2 nodes have arbitrary pointer +set, rest two nodes have arbitrary pointer +as NULL. Second line tells us the value +of four nodes. The third line gives the +information about arbitrary pointers. +The first node arbitrary pointer is set to +node 2. The second node arbitrary pointer +is set to node 4. \ No newline at end of file diff --git a/CompanywiseSolution/ADOBE/Linked_List/solution.cpp b/CompanywiseSolution/ADOBE/Linked_List/solution.cpp new file mode 100644 index 0000000..b866ed7 --- /dev/null +++ b/CompanywiseSolution/ADOBE/Linked_List/solution.cpp @@ -0,0 +1,191 @@ +#include + +using namespace std; +/* Link list Node */ +struct Node { + int data; + Node *next; + Node *arb; + + Node(int x) { + data = x; + next = NULL; + arb = NULL; + } +}; + + + + // } Driver Code Ends +class Solution +{ + public: + Node *copyList(Node *head) + { + Node *curr=head; + + while(curr!=NULL) + { + Node *nex=curr->next; + curr->next= new Node(curr->data); + curr->next->next=nex; + curr=nex; + } + for(curr=head;curr!=NULL;curr=curr->next->next) + { + curr->next->arb=(curr->arb !=NULL)?curr->arb->next : NULL; + } + Node *res=head->next; + for(curr=head;curr->next!=NULL;) + { + Node *temp=curr->next; + curr->next=curr->next->next; + curr=temp; + } + return res; + } + +}; + +// { Driver Code Starts. + + +void print(Node *root) { + Node *temp = root; + while (temp != NULL) { + int k; + if (temp->arb == NULL) + k = -1; + else + k = temp->arb->data; + cout << temp->data << " " << k << " "; + temp = temp->next; + } +} + + +void append(Node **head_ref, Node **tail_ref, int new_data) { + + Node *new_node = new Node(new_data); + if (*head_ref == NULL) { + *head_ref = new_node; + } else + (*tail_ref)->next = new_node; + *tail_ref = new_node; +} + +bool validation(Node *head, Node *res) { + + + Node *temp1 = head; + Node *temp2 = res; + + int len1 = 0, len2 = 0; + while (temp1 != NULL) { + len1++; + temp1 = temp1->next; + } + while (temp2 != NULL) { + len2++; + temp2 = temp2->next; + } + + /*if lengths not equal */ + + if (len1 != len2) return false; + + temp1 = head; + temp2 = res; + map a; + while (temp1 != NULL) { + + if(temp1==temp2) + return false; + + if (temp1->data != temp2->data) return false; + if (temp1->arb != NULL and temp2->arb != NULL) { + if (temp1->arb->data != temp2->arb->data) + return false; + } else if (temp1->arb != NULL and temp2->arb == NULL) + return false; + else if (temp1->arb == NULL and temp2->arb != NULL) + return false; + a[temp1]=temp2; + temp1 = temp1->next; + temp2 = temp2->next; + } + + + temp1 = head; + temp2 = res; + while (temp1 != NULL) { + + if (temp1->arb != NULL and temp2->arb != NULL) { + if (a[temp1->arb] != temp2->arb) return false; + } + temp1 = temp1->next; + temp2 = temp2->next; + } + return true; +} + + + +int main() { + + int T, i, n, l, k; + Node *generated_addr = NULL; + /*reading input stuff*/ + cin >> T; + while (T--) { + generated_addr = NULL; + struct Node *head = NULL, *tail = NULL; + struct Node *head2 = NULL, *tail2 = NULL; + cin >> n >> k; + for (i = 1; i <= n; i++) { + cin >> l; + append(&head, &tail, l); + append(&head2, &tail2, l); + } + for (int i = 0; i < k; i++) { + int a, b; + cin >> a >> b; + + Node *tempA = head; + Node *temp2A = head2; + int count = -1; + + while (tempA != NULL) { + count++; + if (count == a - 1) break; + tempA = tempA->next; + temp2A = temp2A->next; + } + Node *tempB = head; + Node *temp2B = head2; + count = -1; + + while (tempB != NULL) { + count++; + if (count == b - 1) break; + tempB = tempB->next; + temp2B = temp2B->next; + } + + // when both a is greater than N + if (a <= n){ + tempA->arb = tempB; + temp2A->arb = temp2B; + } + } + /*read finished*/ + + generated_addr = head; + Solution ob; + struct Node *res = ob.copyList(head); + if(validation(head2,res)&&validation(head,res)) + cout << validation(head2, res) << endl; + else + cout << 0 << endl; + } + return 0; \ No newline at end of file From 11f930aa07e48cb195a9fdee53ba22701f89de79 Mon Sep 17 00:00:00 2001 From: rutuja206 <63012051+rutuja206@users.noreply.github.com> Date: Tue, 5 Oct 2021 00:07:45 +0530 Subject: [PATCH 122/142] Create triplet sum to a given value --- .../C++/triplet sum to a given value | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Competitive programming/C++/triplet sum to a given value diff --git a/Competitive programming/C++/triplet sum to a given value b/Competitive programming/C++/triplet sum to a given value new file mode 100644 index 0000000..82fee8f --- /dev/null +++ b/Competitive programming/C++/triplet sum to a given value @@ -0,0 +1,41 @@ + +#include +using namespace std; + + +bool find3Numbers(int A[], int arr_size, int sum) +{ + + for (int i = 0; i < arr_size - 2; i++) + { + + + unordered_set s; + int curr_sum = sum - A[i]; + for (int j = i + 1; j < arr_size; j++) + { + if (s.find(curr_sum - A[j]) != s.end()) + { + printf("Triplet is %d, %d, %d", A[i], + A[j], curr_sum - A[j]); + return true; + } + s.insert(A[j]); + } + } + + + return false; +} + + +int main() +{ + int A[] = { 1, 4, 45, 6, 10, 8 }; + int sum = 22; + int arr_size = sizeof(A) / sizeof(A[0]); + + find3Numbers(A, arr_size, sum); + + return 0; +} From 27be2a19a323373c8a97a75d28652452ab4dd63b Mon Sep 17 00:00:00 2001 From: Hitesh Sharma Date: Tue, 5 Oct 2021 00:18:01 +0530 Subject: [PATCH 123/142] Adding java program to find maximum contiguous sum --- .../Maximum Contiguous sum.java | 29 ++++++++++ .../Morgan Stanley/Question.txt | 57 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java create mode 100644 CompanywiseSolution/Morgan Stanley/Question.txt diff --git a/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java b/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java new file mode 100644 index 0000000..364f8a4 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java @@ -0,0 +1,29 @@ +import java.io.*; +// Java program to print largest contiguous array sum +import java.util.*; + +class Kadane +{ + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} diff --git a/CompanywiseSolution/Morgan Stanley/Question.txt b/CompanywiseSolution/Morgan Stanley/Question.txt new file mode 100644 index 0000000..e2aae7f --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/Question.txt @@ -0,0 +1,57 @@ +Kadane’s Algorithm: + +Initialize: + max_so_far = INT_MIN + max_ending_here = 0 + +Loop for each element of the array + (a) max_ending_here = max_ending_here + a[i] + (b) if(max_so_far < max_ending_here) + max_so_far = max_ending_here + (c) if(max_ending_here < 0) + max_ending_here = 0 +return max_so_far + +Explanation: +The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far + +Lets take the example: + {-2, -3, 4, -1, -2, 1, 5, -3} + + max_so_far = max_ending_here = 0 + + for i=0, a[0] = -2 + max_ending_here = max_ending_here + (-2) + Set max_ending_here = 0 because max_ending_here < 0 + + for i=1, a[1] = -3 + max_ending_here = max_ending_here + (-3) + Set max_ending_here = 0 because max_ending_here < 0 + + for i=2, a[2] = 4 + max_ending_here = max_ending_here + (4) + max_ending_here = 4 + max_so_far is updated to 4 because max_ending_here greater + than max_so_far which was 0 till now + + for i=3, a[3] = -1 + max_ending_here = max_ending_here + (-1) + max_ending_here = 3 + + for i=4, a[4] = -2 + max_ending_here = max_ending_here + (-2) + max_ending_here = 1 + + for i=5, a[5] = 1 + max_ending_here = max_ending_here + (1) + max_ending_here = 2 + + for i=6, a[6] = 5 + max_ending_here = max_ending_here + (5) + max_ending_here = 7 + max_so_far is updated to 7 because max_ending_here is + greater than max_so_far + + for i=7, a[7] = -3 + max_ending_here = max_ending_here + (-3) + max_ending_here = 4 \ No newline at end of file From a5153188f43145a66517114bf0352e569c082040 Mon Sep 17 00:00:00 2001 From: danushan99 Date: Tue, 5 Oct 2021 11:10:06 +0530 Subject: [PATCH 124/142] add some programs --- Competitive programming/C/ArmstrongNumber.c | 19 ++++ Competitive programming/C/Queus.c | 70 ++++++++++++ Competitive programming/C/Reflection.c | 93 ++++++++++++++++ ...earching for specific number in 1D array.c | 52 +++++++++ Competitive programming/C/Stacks.c | 87 +++++++++++++++ .../JAVA/Counting Sort.java | 43 ++++++++ Competitive programming/JAVA/MergeSort.java | 104 ++++++++++++++++++ .../JAVA/Recursive_Bubble_Sort.java | 35 ++++++ 8 files changed, 503 insertions(+) create mode 100644 Competitive programming/C/ArmstrongNumber.c create mode 100644 Competitive programming/C/Queus.c create mode 100644 Competitive programming/C/Reflection.c create mode 100644 Competitive programming/C/Searching for specific number in 1D array.c create mode 100644 Competitive programming/C/Stacks.c create mode 100644 Competitive programming/JAVA/Counting Sort.java create mode 100644 Competitive programming/JAVA/MergeSort.java create mode 100644 Competitive programming/JAVA/Recursive_Bubble_Sort.java diff --git a/Competitive programming/C/ArmstrongNumber.c b/Competitive programming/C/ArmstrongNumber.c new file mode 100644 index 0000000..a3c2d76 --- /dev/null +++ b/Competitive programming/C/ArmstrongNumber.c @@ -0,0 +1,19 @@ +#include + int main() +{ +int n,r,sum=0,temp; +printf("enter the number="); +scanf("%d",&n); +temp=n; +while(n>0) +{ +r=n%10; +sum=sum+(r*r*r); +n=n/10; +} +if(temp==sum) +printf("armstrong number "); +else +printf("not armstrong number"); +return 0; +} diff --git a/Competitive programming/C/Queus.c b/Competitive programming/C/Queus.c new file mode 100644 index 0000000..e853b0d --- /dev/null +++ b/Competitive programming/C/Queus.c @@ -0,0 +1,70 @@ +#include +#define SIZE 6 + +void enQueue(int); +void deQueue(); +void display(); + +int items[SIZE], front = -1, rear = -1; + +int main() { + //deQueue is not possible on empty queue + deQueue(); + + //enQueue 5 elements + enQueue(1); + enQueue(2); + enQueue(3); + enQueue(4); + enQueue(5); + enQueue(6); + + // 7th element can't be added to because the queue is full + enQueue(7); + enQueue(8); + + display(); + + //deQueue removes element entered first i.e. 1 + deQueue(); + + //Now we have just 5 elements + display(); + + return 0; +} + +void enQueue(int value) { + if (rear == SIZE - 1) + printf("\nQueue is Full!!"); + else { + if (front == -1) + front = 0; + rear++; + items[rear] = value; + printf("\nInserted -> %d", value); + } +} + +void deQueue() { + if (front == -1) + printf("\nQueue is Empty!!"); + else { + printf("\nDeleted : %d", items[front]); + front++; + if (front > rear) + front = rear = -1; + } +} + +void display() { + if (rear == -1) + printf("\nQueue is Empty!!!"); + else { + int i; + printf("\nQueue elements are:\n"); + for (i = front; i <= rear; i++) + printf("%d ", items[i]); + } + printf("\n"); +} \ No newline at end of file diff --git a/Competitive programming/C/Reflection.c b/Competitive programming/C/Reflection.c new file mode 100644 index 0000000..d511b06 --- /dev/null +++ b/Competitive programming/C/Reflection.c @@ -0,0 +1,93 @@ +#include +#include +#include +#include +void main() +{ +int poly[30],a[9][3],b[3][3],c[9][3],poly2[30]; +int x,y,p,i,j,k,xc,yc; +int gd=DETECT,gm; +clrscr(); +initgraph(&gd,&gm,"c:\\turboc3\\bgi"); +xc=getmaxx()/2; +yc=getmaxy()/2; +printf("\n Enter number of points : "); +scanf("%d",&p); +j=0; +for(i=0;i=max) + { + printf("Not Possible"); + return 0; + } + for(i=0; i=a) + { + printf("yes, its possible"); + return 0; + } + printf("%d",n[loc]); +} + +----------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +/* + +Output :- + +Enter how many numbers:- +5 +Enter integers:- +4 +Enter integers:- +9 +Enter integers:- +7 +Enter integers:- +15 +Enter integers:- +22 +Enter the location:- +2 +7 + +*/ diff --git a/Competitive programming/C/Stacks.c b/Competitive programming/C/Stacks.c new file mode 100644 index 0000000..eb95685 --- /dev/null +++ b/Competitive programming/C/Stacks.c @@ -0,0 +1,87 @@ +#include +#include + +#define MAX 10 + +int count = 0; + +// Creating a stack +struct stack { + int items[MAX]; + int top; +}; +typedef struct stack st; + +void createEmptyStack(st* s) { + s->top = -1; +} + +// Check if the stack is full +int isfull(st* s) { + if (s->top == MAX - 1) + return 1; + else + return 0; +} + +// Check if the stack is empty +int isempty(st* s) { + if (s->top == -1) + return 1; + else + return 0; +} + +// adding elements in the stack +void push(st* s, int newitem) { + if (isfull(s)) { + printf("STACK FULL"); + } + else { + s->top++; + s->items[s->top] = newitem; + } + count++; +} + +// Remove element from stack +void pop(st* s) { + if (isempty(s)) { + printf("\n STACK EMPTY \n"); + } + else { + printf("Item popped= %d", s->items[s->top]); + s->top--; + } + count--; + printf("\n"); +} + +// Print elements of stack +void printStack(st* s) { + printf("Stack: "); + for (int i = 0; i < count; i++) { + printf("%d ", s->items[i]); + } + printf("\n"); +} + +int main() { + int ch; + st* s = (st*)malloc(sizeof(st)); + + createEmptyStack(s); + + push(s, 1); + push(s, 2); + push(s, 3); + push(s, 4); + push(s, 5); + + printStack(s); + + pop(s); + + printf("\nAfter popping out top element\n"); + printStack(s); +} diff --git a/Competitive programming/JAVA/Counting Sort.java b/Competitive programming/JAVA/Counting Sort.java new file mode 100644 index 0000000..8a0f512 --- /dev/null +++ b/Competitive programming/JAVA/Counting Sort.java @@ -0,0 +1,43 @@ + +class CountingSort { + void sort(char arr[]) + { + int n = arr.length; + + + char output[] = new char[n]; + + int count[] = new int[256]; + for (int i = 0; i < 256; ++i) + count[i] = 0; + + + for (int i = 0; i < n; ++i) + ++count[arr[i]]; + + for (int i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + + for (int i = n - 1; i >= 0; i--) { + output[count[arr[i]] - 1] = arr[i]; + --count[arr[i]]; + } + + for (int i = 0; i < n; ++i) + arr[i] = output[i]; + } + + public static void main(String args[]) + { + CountingSort ob = new CountingSort(); + char arr[] = { 'D','E','M','O','I','C','N'}; + + ob.sort(arr); + + System.out.print("Sorted character array is "); + for (int i = 0; i < arr.length; ++i) + System.out.print(arr[i]); + } +} + diff --git a/Competitive programming/JAVA/MergeSort.java b/Competitive programming/JAVA/MergeSort.java new file mode 100644 index 0000000..2586db6 --- /dev/null +++ b/Competitive programming/JAVA/MergeSort.java @@ -0,0 +1,104 @@ +/* Java program for Merge Sort */ +class MergeSort +{ + // Merges two subarrays of arr[]. + // First subarray is arr[l..m] + // Second subarray is arr[m+1..r] + void merge(int arr[], int l, int m, int r) + { + // Find sizes of two subarrays to be merged + int n1 = m - l + 1; + int n2 = r - m; + + /* Create temp arrays */ + int L[] = new int [n1]; + int R[] = new int [n2]; + + /*Copy data to temp arrays*/ + for (int i=0; i arr[i+1]) + { + + int temp = arr[i]; + arr[i] = arr[i+1]; + arr[i+1] = temp; + } + + bubbleSort(arr, n-1); + } + + + public static void main(String[] args) + { + int arr[] = {64, 34, 25, 12, 22, 11, 90}; + + bubbleSort(arr, arr.length); + + System.out.println("Sorted array : "); + System.out.println(Arrays.toString(arr)); + } +} From b0fb026d88a9ea99deffe2398942e5b405b2d809 Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 11:10:07 +0530 Subject: [PATCH 125/142] Moved to Folder --- CompanywiseSolution/Morgan Stanley/{ => Questions}/Question.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename CompanywiseSolution/Morgan Stanley/{ => Questions}/Question.txt (98%) diff --git a/CompanywiseSolution/Morgan Stanley/Question.txt b/CompanywiseSolution/Morgan Stanley/Questions/Question.txt similarity index 98% rename from CompanywiseSolution/Morgan Stanley/Question.txt rename to CompanywiseSolution/Morgan Stanley/Questions/Question.txt index e2aae7f..2421481 100644 --- a/CompanywiseSolution/Morgan Stanley/Question.txt +++ b/CompanywiseSolution/Morgan Stanley/Questions/Question.txt @@ -54,4 +54,4 @@ Lets take the example: for i=7, a[7] = -3 max_ending_here = max_ending_here + (-3) - max_ending_here = 4 \ No newline at end of file + max_ending_here = 4 From 26774520caa038b3bf31a1280758761050c2a501 Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 11:11:02 +0530 Subject: [PATCH 126/142] Moved to Solutions folder --- .../Morgan Stanley/{ => Solutions}/Maximum Contiguous sum.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/{ => Solutions}/Maximum Contiguous sum.java (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java b/CompanywiseSolution/Morgan Stanley/Solutions/Maximum Contiguous sum.java similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java rename to CompanywiseSolution/Morgan Stanley/Solutions/Maximum Contiguous sum.java From a503e420b8df934e17188c7769d0abddb155cd6a Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 11:12:03 +0530 Subject: [PATCH 127/142] Rename Question.txt to Maximum Contiguous sum.txt --- .../Questions/{Question.txt => Maximum Contiguous sum.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/Questions/{Question.txt => Maximum Contiguous sum.txt} (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Questions/Question.txt b/CompanywiseSolution/Morgan Stanley/Questions/Maximum Contiguous sum.txt similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Questions/Question.txt rename to CompanywiseSolution/Morgan Stanley/Questions/Maximum Contiguous sum.txt From e13d9b5036a394c375c8ecdf4b2172b7451b40e2 Mon Sep 17 00:00:00 2001 From: Lokender10 <71983411+Lokender10@users.noreply.github.com> Date: Tue, 5 Oct 2021 12:16:47 +0530 Subject: [PATCH 128/142] Create Quick_sort.cpp --- Algorithms/Quick_sort.cpp | 73 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Algorithms/Quick_sort.cpp diff --git a/Algorithms/Quick_sort.cpp b/Algorithms/Quick_sort.cpp new file mode 100644 index 0000000..c077bd4 --- /dev/null +++ b/Algorithms/Quick_sort.cpp @@ -0,0 +1,73 @@ +/* C implementation QuickSort */ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = sizeof(arr)/sizeof(arr[0]); + quickSort(arr, 0, n-1); + printf("Sorted array: \n"); + printArray(arr, n); + return 0; +} From 8eb9ee2384836774be915f7f13f4fceac45179b4 Mon Sep 17 00:00:00 2001 From: anu106 Date: Tue, 5 Oct 2021 12:37:55 +0530 Subject: [PATCH 129/142] Add Codeforces 1560B --- .../C++/Codeforces_1560B.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Competitive programming/C++/Codeforces_1560B.cpp diff --git a/Competitive programming/C++/Codeforces_1560B.cpp b/Competitive programming/C++/Codeforces_1560B.cpp new file mode 100644 index 0000000..a80423a --- /dev/null +++ b/Competitive programming/C++/Codeforces_1560B.cpp @@ -0,0 +1,24 @@ +//link to problem->https://codeforces.com/contest/1560/problem/B +//Who's opposite +#include +using namespace std; +int main(){ + int t; + cin>>t; + while(t--){ + int a,b,c; + cin>>a>>b>>c; + int s=2*(abs(a-b)); + if(a<=s && b<=s && c<=s){ + if((s/2+c)>s){ + cout< Date: Tue, 5 Oct 2021 15:06:15 +0530 Subject: [PATCH 130/142] added question asked in amazon --- .../Minimum sum partition/question.md | 12 +++ .../Minimum sum partition/solution.cpp | 75 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/question.md create mode 100644 CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/solution.cpp diff --git a/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/question.md b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/question.md new file mode 100644 index 0000000..ba7c7e6 --- /dev/null +++ b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/question.md @@ -0,0 +1,12 @@ +Minimum sum partition + +Given an integer array arr of size N, the task is to divide it into two sets S1 and S2 +such that the absolute difference between their sums is minimum and find the minimum difference + +Example 1: + +Input: N = 4, arr[] = {1, 6, 11, 5} +Output: 1 +Explanation: +Subset1 = {1, 5, 6}, sum of Subset1 = 12 +Subset2 = {11}, sum of Subset2 = 11 \ No newline at end of file diff --git a/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/solution.cpp b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/solution.cpp new file mode 100644 index 0000000..7ea019f --- /dev/null +++ b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/solution.cpp @@ -0,0 +1,75 @@ +// { Driver Code Starts +#include +using namespace std; + + // } Driver Code Ends +class Solution{ + + public: + int minDifference(int arr[], int n) { + + + + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + bool dp[n + 1][sum + 1]; + + for (int i = 0; i <= n; i++) + dp[i][0] = true; + + for (int i = 1; i <= sum; i++) + dp[0][i] = false; + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= sum; j++) { + + + if (arr[i - 1] <= j) + dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i-1][j]; + else + dp[i][j] = dp[i - 1][j]; + } + } + + + + int mn=INT_MAX; + for(int z=0;z<(sum/2)+1;z++) + { + if(dp[n][z]==true) + mn=min(mn,sum-2*z); + } + return mn; + + + + } +}; + + +// { Driver Code Starts. +int main() +{ + + + int t; + cin >> t; + while (t--) + { + int n; + cin >> n; + + int a[n]; + for(int i = 0; i < n; i++) + cin >> a[i]; + + + + Solution ob; + cout << ob.minDifference(a, n) << "\n"; + + } + return 0; +} // } Driver Code Ends \ No newline at end of file From e0b0e68b17abd8244d2d291a582b930825a58fc6 Mon Sep 17 00:00:00 2001 From: Vanshika Singh <50673504+VanshikaSingh10@users.noreply.github.com> Date: Tue, 5 Oct 2021 15:45:53 +0530 Subject: [PATCH 131/142] Create LazySegmentedTree.cpp --- .../C++/LazySegmentedTree.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Competitive programming/C++/LazySegmentedTree.cpp diff --git a/Competitive programming/C++/LazySegmentedTree.cpp b/Competitive programming/C++/LazySegmentedTree.cpp new file mode 100644 index 0000000..ca4fab1 --- /dev/null +++ b/Competitive programming/C++/LazySegmentedTree.cpp @@ -0,0 +1,80 @@ +#include + +using namespace std; + +#define inf 1e18 + + +int lazy[10000] = {0}; +void lazyUpdate(int tree[], int s, int e, int l, int r, int val , int index) { + if (lazy[index] != 0) { + tree[index] += lazy[index]; + if (e != s) { + lazy[2 * index] += lazy[index]; + lazy[2 * index + 1] += lazy[index]; + } + lazy[index] = 0; + } + + if (s > r or e < l) return; + + if (s >= l and e <= r) { + tree[index] += val; + if (e != s) { + lazy[2 * index] += val; + lazy[2 * index + 1] += val; + } + return; + } + + int mid = (s + e) / 2; + lazyUpdate(tree, s, mid, l, r, val, 2 * index); + lazyUpdate(tree, mid + 1, e, l, r, val, 2 * index + 1); + tree[index] = min(tree[2 * index], tree[2 * index + 1]); + return; +} + +int lazyQuery(int tree[], int s, int e, int l, int r, int index) { + if (lazy[index] != 0) { + tree[index] += lazy[index]; + if (e != s) { + lazy[2 * index] = lazy[index]; + lazy[2 * index + 1] = lazy[index]; + } + lazy[index] = 0; + } + + if (s > r or e < l) return inf; + if (s >= l and e <= r) return tree[index]; + + int mid = (s + e) / 2; + int left = lazyQuery(tree, s, mid, l, r, 2 * index); + int right = lazyQuery(tree, mid + 1, e, l, r, 2 * index + 1); + return min(left, right); + + +} + +void build(int a[], int tree[], int s, int e, int index) { + if (s == e) { + tree[index] = a[e]; + return; + } + int mid = (s + e) / 2; + build(a, tree, s, mid, 2 * index); + build(a, tree, mid + 1, e, 2 * index + 1); + tree[index] = min(tree[2 * index], tree[2 * index + 1]); + return; +} + + +int32_t main() +{ + //An example of implementing this code + // int a[] = {1, 3, 2, -5, 6, 4}; + // int n = sizeof(a) / sizeof(int); + // int tree[4 * n + 1]; + // build(a, tree, 0, n - 1, 1); + // lazyUpdate(tree, 0, n - 1, 0, 2, 10, 1); + // return 0; +} From 04ed14fedcdb808b2516624bedbd2d07dc535a99 Mon Sep 17 00:00:00 2001 From: Vanshika Singh <50673504+VanshikaSingh10@users.noreply.github.com> Date: Tue, 5 Oct 2021 15:48:30 +0530 Subject: [PATCH 132/142] Create FractionalKnapsack.cpp --- Algorithms/FractionalKnapsack.cpp | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Algorithms/FractionalKnapsack.cpp diff --git a/Algorithms/FractionalKnapsack.cpp b/Algorithms/FractionalKnapsack.cpp new file mode 100644 index 0000000..2a48ad4 --- /dev/null +++ b/Algorithms/FractionalKnapsack.cpp @@ -0,0 +1,51 @@ +#include + +using namespace std; + +struct Item{ + int val; + int w; +}; + +bool cmp(Item i1,Item i2){ + double r1= (double)i1.val/i1.w; + double r2=(double)i2.val/i2.w; + return r1>r2; +} + +int fractionalKnapsack(Item items[],int n,int W){ + sort(items,items+n,cmp); + + int rem=W; + double ans=0; + for(int i=0;i Date: Tue, 5 Oct 2021 19:21:02 +0530 Subject: [PATCH 133/142] Create Twins.cpp --- Competitive programming/C++/Twins.cpp | 54 +++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Competitive programming/C++/Twins.cpp diff --git a/Competitive programming/C++/Twins.cpp b/Competitive programming/C++/Twins.cpp new file mode 100644 index 0000000..c084d77 --- /dev/null +++ b/Competitive programming/C++/Twins.cpp @@ -0,0 +1,54 @@ +#include + +using namespace std; + + +void insertionSort(int arr[], int n) +{ + int i, key, j; + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + + while (j >= 0 && arr[j] > key) + { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } +} + + + +int main() +{ + int n=0, *a, i,c=0,tsum=0,j,sum=0; + cin>>n; + a=new int[n]; + for(i=0;i>a[i]; + tsum+=a[i]; + } + + insertionSort(a, n); + + for(i=n-1;i>=0;i--) + { + sum=0; + c++; + for(j=n-1;j>=i;j--) + { + sum+=a[j]; + } + if((2*sum)>tsum) + { + cout< Date: Tue, 5 Oct 2021 19:50:10 +0530 Subject: [PATCH 134/142] Create Vanya and Lanterns.cpp --- .../C++/Vanya and Lanterns.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Competitive programming/C++/Vanya and Lanterns.cpp diff --git a/Competitive programming/C++/Vanya and Lanterns.cpp b/Competitive programming/C++/Vanya and Lanterns.cpp new file mode 100644 index 0000000..a839b1a --- /dev/null +++ b/Competitive programming/C++/Vanya and Lanterns.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +using namespace std; + +int main() +{ + long long l, *a, max1=0; + int n,i; + cin>>n>>l; + a=new long long[n]; + for(i=0;i>a[i]; + } + sort(a, a+n); + for(i=0;i Date: Tue, 5 Oct 2021 19:55:57 +0530 Subject: [PATCH 135/142] added min steps to 1 using DP --- .../DYNAMIC PROGRAMMING/Min steps to 1.cpp | 42 +++++++++++++++++++ .../C++/DYNAMIC PROGRAMMING/Readme.md | 30 +++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 Competitive programming/C++/DYNAMIC PROGRAMMING/Min steps to 1.cpp create mode 100644 Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md diff --git a/Competitive programming/C++/DYNAMIC PROGRAMMING/Min steps to 1.cpp b/Competitive programming/C++/DYNAMIC PROGRAMMING/Min steps to 1.cpp new file mode 100644 index 0000000..db9bca0 --- /dev/null +++ b/Competitive programming/C++/DYNAMIC PROGRAMMING/Min steps to 1.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; + +int countStepsToOne(int n) +{ + int arr[n+1]; + for(int i = 0; i> n; + cout << countStepsToOne(n); +} \ No newline at end of file diff --git a/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md b/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md new file mode 100644 index 0000000..3f5a659 --- /dev/null +++ b/Competitive programming/C++/DYNAMIC PROGRAMMING/Readme.md @@ -0,0 +1,30 @@ +Code : Min Steps to 1 using DP + +Given a positive integer 'n', find and return the minimum number of steps that 'n' has to take to get reduced to 1. You can perform any one of the following 3 steps: +1.) Subtract 1 from it. (n = n - ­1) , +2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) , +3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). +Input format : +The first and the only line of input contains an integer value, 'n'. +Output format : +Print the minimum number of steps. +Constraints : +1 <= n <= 10 ^ 6 +Time Limit: 1 sec +Sample Input 1 : +4 +Sample Output 1 : +2 +Explanation of Sample Output 1 : +For n = 4 +Step 1 : n = 4 / 2 = 2 +Step 2 : n = 2 / 2 = 1 +Sample Input 2 : +7 +Sample Output 2 : +3 +Explanation of Sample Output 2 : +For n = 7 +Step 1 : n = 7 ­- 1 = 6 +Step 2 : n = 6 / 3 = 2 +Step 3 : n = 2 / 2 = 1 \ No newline at end of file From 21dccd18302d767d22d56139cefae4f3e78e3ece Mon Sep 17 00:00:00 2001 From: Dhruvil Dave <67459224+Dhruvil-Dave@users.noreply.github.com> Date: Tue, 5 Oct 2021 20:22:44 +0530 Subject: [PATCH 136/142] Added solution --- .../C++/majority_element.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Competitive programming/C++/majority_element.cpp diff --git a/Competitive programming/C++/majority_element.cpp b/Competitive programming/C++/majority_element.cpp new file mode 100644 index 0000000..8d2a3c7 --- /dev/null +++ b/Competitive programming/C++/majority_element.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +using namespace std; + +int main(){ + +int n; +cin>>n; +int arr[n]; +for(int i=0;i>arr[i]; +} +sort(arr,arr+n); +int count; +vector v; +for(int i=0;i Date: Tue, 5 Oct 2021 21:08:13 +0530 Subject: [PATCH 137/142] Solution of Coin change problem using dp --- .../Minimum sum partition/CoinChange-dp.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/CoinChange-dp.cpp diff --git a/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/CoinChange-dp.cpp b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/CoinChange-dp.cpp new file mode 100644 index 0000000..b929e45 --- /dev/null +++ b/CompanywiseSolution/Amazon/Dynamic Programming/Minimum sum partition/CoinChange-dp.cpp @@ -0,0 +1,60 @@ +/*Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. + + +Example 1: + +Input: +n = 4 , m = 3 +S[] = {1,2,3} +Output: 4 +Explanation: Four Possible ways are: +{1,1,1,1},{1,1,2},{2,2},{1,3}.*/ + +#include + +using namespace std; +long long int count(int S[], int m, int n) { + + + + long long t[m+1][n+1]; + + for(int i=0;i>t; + while(t--){ + int n,m; + cin>>n>>m; + int arr[m]; + for(int i=0;i>arr[i]; + + long long ans=count(arr,m,n); + cout< Date: Tue, 5 Oct 2021 23:35:58 +0530 Subject: [PATCH 138/142] Rename CompanywiseSolution/Morgan Stanley/Questions/Maximum Contiguous sum.txt to CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt --- .../Question.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/{Questions/Maximum Contiguous sum.txt => Max contiguous sum/Question.txt} (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Questions/Maximum Contiguous sum.txt b/CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Questions/Maximum Contiguous sum.txt rename to CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt From bd679fb20abad85021a256033c0ea02917f5e063 Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 23:37:03 +0530 Subject: [PATCH 139/142] Rename CompanywiseSolution/Morgan Stanley/Solutions/Maximum Contiguous sum.java to CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Solution.java --- .../Solution.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/{Solutions/Maximum Contiguous sum.java => Maximum Contiguous sum/Solution.java} (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Solutions/Maximum Contiguous sum.java b/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Solution.java similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Solutions/Maximum Contiguous sum.java rename to CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Solution.java From 637e46e7db44a772c55eb2da9f79a5a4aff260da Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 23:37:43 +0530 Subject: [PATCH 140/142] Rename CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt to CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt --- .../{Max contiguous sum => Maximum contiguous sum}/Question.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/{Max contiguous sum => Maximum contiguous sum}/Question.txt (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt b/CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Max contiguous sum/Question.txt rename to CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt From 60206692794cbbf06037e9fea98225b73a379024 Mon Sep 17 00:00:00 2001 From: Hitesh Sharma <68909492+hitesh181@users.noreply.github.com> Date: Tue, 5 Oct 2021 23:38:26 +0530 Subject: [PATCH 141/142] Rename CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt to CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Question.txt --- .../Question.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename CompanywiseSolution/Morgan Stanley/{Maximum contiguous sum => Maximum Contiguous sum}/Question.txt (100%) diff --git a/CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt b/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Question.txt similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Maximum contiguous sum/Question.txt rename to CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum/Question.txt From 633ff0db027256a0acc30c0796055c7e61313ea0 Mon Sep 17 00:00:00 2001 From: Hitesh Sharma Date: Wed, 6 Oct 2021 00:04:43 +0530 Subject: [PATCH 142/142] Moved max contigous sum and added lower case program --- .../{ => Maximum Contigous Sum}/Question.txt | 0 .../Solution.java.java} | 0 .../String to Lower Case/Question.java.txt | 25 +++++++++++++++ .../String to Lower Case/Solution.java.java | 32 +++++++++++++++++++ 4 files changed, 57 insertions(+) rename CompanywiseSolution/Morgan Stanley/{ => Maximum Contigous Sum}/Question.txt (100%) rename CompanywiseSolution/Morgan Stanley/{Maximum Contiguous sum.java => Maximum Contigous Sum/Solution.java.java} (100%) create mode 100644 CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt create mode 100644 CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java diff --git a/CompanywiseSolution/Morgan Stanley/Question.txt b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Question.txt rename to CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Question.txt diff --git a/CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java b/CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java similarity index 100% rename from CompanywiseSolution/Morgan Stanley/Maximum Contiguous sum.java rename to CompanywiseSolution/Morgan Stanley/Maximum Contigous Sum/Solution.java.java diff --git a/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt new file mode 100644 index 0000000..7f7be13 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Question.java.txt @@ -0,0 +1,25 @@ +Given a string S. The task is to convert characters of string to lowercase. + +Example 1: + +Input: S = "ABCddE" +Output: "abcdde" +Explanation: A, B, C and E are converted to +a, b, c and E thus all uppercase characters +of the string converted to lowercase letter. +Example 2: + +Input: S = "LMNOppQQ" +Output: "lmnoppqq" +Explanation: L, M, N, O, and Q are +converted to l, m, n, o and q thus +all uppercase characters of the +string converted to lowercase letter. +Your Task: +You dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string. + +Expected Time Complexity:O(n) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= |S| <= 1000 \ No newline at end of file diff --git a/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java new file mode 100644 index 0000000..07c4828 --- /dev/null +++ b/CompanywiseSolution/Morgan Stanley/String to Lower Case/Solution.java.java @@ -0,0 +1,32 @@ +// Initial template for Java + +import java.util.*; +import java.io.*; + +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader read = + new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter no of words you want to check"); + int t = Integer.parseInt(read.readLine()); + + while (t-- > 0) { + System.out.println("Enter Word to conver to lowercase"); + String S = read.readLine(); + Solution ob = new Solution(); + + System.out.println(ob.toLower(S)); + } + } +}// } Driver Code Ends + + +// User function template for Java + +class Solution { + static String toLower(String S) { + String S1=S.toLowerCase(); + return S1; + } + +} \ No newline at end of file