From d4e4a6dc1be14cb6d63475540a513852e4f80e22 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 6 Nov 2021 13:54:29 +0530 Subject: [PATCH 01/25] Create Binary Search Applications Added Documentation regarding the Simple Applications of Binary Search --- .../Binary Search/Binary Search Applications | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications new file mode 100644 index 0000000000..037040aece --- /dev/null +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications @@ -0,0 +1,179 @@ +# Binary Search Application + +## Linear Search +The most simple way to search is linear search , as +```c++ +//c++ +int arr[10]={6,5,2,7,1,8,4,9,10,11}; +int search_element=7; +int indx,f=0; +for(int i=0;i<10;i++) +{ + if(arr[i]==search_element) + { + f=1; + indx=i; + } + if(f) + { + cout<<"element found"< +using namespace std; +int first_occurence(int arr[],int n, int search_element){ +int start=0; +int end=n-1; +int indx; +while(start<=end) +{ + int mid= start+(end-start)/2; + if(arr[mid]==search_element){ + indx=mid; // found element and move in the left side to search if any occurence of same element is in the left side + end=mid-1; + } + else if(arr[mid]Output : +> +>First occurence 2 +> +>Last occurence 4 + +In this we can find the occurence of element in array in O(log(n)) time where n is the size of array. we can find the total number of time the element comes in the array if we know the first and last occurence . + +>count= first_occurence - last_occurence + +## Find Floor and Ceil of a element from a given array + + +Floor *is the gretest element in the array smaller than the element we want to find floor.* + +Ceil *is the smallest element in the array greater than the element we want to find ceil.* + + +```c++ +#include +using namespace std; +int find_floor(int arr[],int n, int element){ +int start=0; +int end=n-1; +int indx; +while(start<=end) +{ + int mid= start+(end-start)/2; + if(arr[mid]==element){ + return arr[mid]; + } + else if(arr[mid]Output: +> +>Floor of the element 3 +> +>Ceil of the element 5 + + +These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in O(log (n)) time . From 3580307b38df5a9e29544d3aaf11bded469ba2e6 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 6 Nov 2021 13:55:10 +0530 Subject: [PATCH 02/25] Rename Binary Search Applications to Binary Search Application.mds --- .../{Binary Search Applications => Binary Search Application.mds} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Competitive_Programming/C++/Searching & Sorting/Binary Search/{Binary Search Applications => Binary Search Application.mds} (100%) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.mds similarity index 100% rename from Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Applications rename to Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.mds From c722bba26dd60ebaf215472f9b95bb4ba836bcbb Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 6 Nov 2021 13:55:35 +0530 Subject: [PATCH 03/25] Rename Binary Search Application.mds to Binary Search Application.md --- ...Binary Search Application.mds => Binary Search Application.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Competitive_Programming/C++/Searching & Sorting/Binary Search/{Binary Search Application.mds => Binary Search Application.md} (100%) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.mds b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md similarity index 100% rename from Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.mds rename to Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md From fa668b48f169a3b945df03aa33ec944521200229 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Mon, 8 Nov 2021 23:44:18 +0530 Subject: [PATCH 04/25] Update Binary Search Application.md All the suggested changes are done . --- .../Binary Search Application.md | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md index 037040aece..cacb0ac9f6 100644 --- a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md @@ -47,7 +47,7 @@ return -1; // not found ``` In Binary Search we divide the array in *two halves* and then one half is decided and the searching is done on that half only similarily this divide take place till the element is not found. -so the the time complexity in Worst Case is O(log n) where n is the size of array. +so the the time complexity in Worst Case is *O(log n)* where n is the size of array. Binary Search can solve various other problem in Competitive Programming where we have to print result in specific time otherwise TLE comes. @@ -107,6 +107,8 @@ return 0; > >Last occurence 4 +>Time Complexity O(log n) + In this we can find the occurence of element in array in O(log(n)) time where n is the size of array. we can find the total number of time the element comes in the array if we know the first and last occurence . >count= first_occurence - last_occurence @@ -175,5 +177,21 @@ return 0; > >Ceil of the element 5 +>Time Complexity O(log n) , where n is the size of array + +Explanation: +- In floor of an element in the array we need to find the greatest element samaller than the element we wish to find the floor. +- example: + array =[1,2,3,5,6,7,8] element = 4 for which we have to find the floor , + 1. why Binary Search ? because the array is sorted and we know that the element floor will be present in the array (ie. from start=0 to end=n-1 where n is the size of array) +2. so we find the mid element using start and end of the array index till the time start <= end. +3. then we compare array[mid] with the element for which we have to find floor. +4. and whenever we find any smaller element than 4 ,then we save it in a variable indx(as that can be a possible answer) and move the start to mid+1 , to find if other greater element that is smaller than the element (in this case 4). +5. After Binary Search, we will return the indx as it will have the floor of the element. +- Similarily we can approach ceil, as we know ceil is the smallest greater element than the element for which we want to find ceil. -These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in O(log (n)) time . +These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in O(log (n)) time . + +>The flow of document +> +>Title -> explanation -> code -> Time Complexity From ebbdf3002c9a2be67d0e13eb6bd6bc95069f1a42 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Mon, 8 Nov 2021 23:52:04 +0530 Subject: [PATCH 05/25] Rename Binary Search Application.md to BinarySearchApplication.md renamed --- .../{Binary Search Application.md => BinarySearchApplication.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Competitive_Programming/C++/Searching & Sorting/Binary Search/{Binary Search Application.md => BinarySearchApplication.md} (100%) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md similarity index 100% rename from Competitive_Programming/C++/Searching & Sorting/Binary Search/Binary Search Application.md rename to Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md From d6a5cccd510876639905e749bf453124ef8539b7 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Tue, 9 Nov 2021 14:09:25 +0530 Subject: [PATCH 06/25] Update Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md Co-authored-by: Ravi Kanth Gojur --- .../Binary Search/BinarySearchApplication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md index cacb0ac9f6..c913752ff3 100644 --- a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md @@ -179,7 +179,7 @@ return 0; >Time Complexity O(log n) , where n is the size of array -Explanation: +## Approach: - In floor of an element in the array we need to find the greatest element samaller than the element we wish to find the floor. - example: array =[1,2,3,5,6,7,8] element = 4 for which we have to find the floor , From 27eb296492d57554d6ba7c8f9e3c5f96f95b6efd Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Tue, 9 Nov 2021 14:09:54 +0530 Subject: [PATCH 07/25] Update Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md Co-authored-by: Ravi Kanth Gojur --- .../Binary Search/BinarySearchApplication.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md index c913752ff3..1ad54f92d3 100644 --- a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md @@ -190,7 +190,8 @@ return 0; 5. After Binary Search, we will return the indx as it will have the floor of the element. - Similarily we can approach ceil, as we know ceil is the smallest greater element than the element for which we want to find ceil. -These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in O(log (n)) time . +## Complexity +These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in ```O(log (n))``` time . >The flow of document > From 0a25003da65554709b1a5bbeee2b03685a3d0168 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Tue, 9 Nov 2021 17:43:11 +0530 Subject: [PATCH 08/25] Create BinarySearchApplication.md Done all the required changes suggested. --- .../Binary Search/BinarySearchApplication.md | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md index 1ad54f92d3..863757eef4 100644 --- a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md @@ -113,7 +113,7 @@ In this we can find the occurence of element in array in O(log(n)) time where n >count= first_occurence - last_occurence -## Find Floor and Ceil of a element from a given array +## Find Floor and Ceil of a element from a given array in O(log n) time complexity Floor *is the gretest element in the array smaller than the element we want to find floor.* @@ -121,6 +121,18 @@ Floor *is the gretest element in the array smaller than the element we want to f Ceil *is the smallest element in the array greater than the element we want to find ceil.* +## Explanation: +- In floor of an element in the array we need to find the greatest element samaller than the element we wish to find the floor. +- example: + array =[1,2,3,5,6,7,8] element = 4 for which we have to find the floor , + 1. why Binary Search ? because the array is sorted and we know that the element floor will be present in the array (ie. from start=0 to end=n-1 where n is the size of array) +2. so we find the mid element using start and end of the array index till the time start <= end. +3. then we compare array[mid] with the element for which we have to find floor. +4. and whenever we find any smaller element than 4 ,then we save it in a variable indx(as that can be a possible answer) and move the start to mid+1 , to find if other greater element that is smaller than the element (in this case 4). +5. After Binary Search, we will return the indx as it will have the floor of the element. +- Similarily we can approach ceil, as we know ceil is the smallest greater element than the element for which we want to find ceil. + + ```c++ #include using namespace std; @@ -179,17 +191,6 @@ return 0; >Time Complexity O(log n) , where n is the size of array -## Approach: -- In floor of an element in the array we need to find the greatest element samaller than the element we wish to find the floor. -- example: - array =[1,2,3,5,6,7,8] element = 4 for which we have to find the floor , - 1. why Binary Search ? because the array is sorted and we know that the element floor will be present in the array (ie. from start=0 to end=n-1 where n is the size of array) -2. so we find the mid element using start and end of the array index till the time start <= end. -3. then we compare array[mid] with the element for which we have to find floor. -4. and whenever we find any smaller element than 4 ,then we save it in a variable indx(as that can be a possible answer) and move the start to mid+1 , to find if other greater element that is smaller than the element (in this case 4). -5. After Binary Search, we will return the indx as it will have the floor of the element. -- Similarily we can approach ceil, as we know ceil is the smallest greater element than the element for which we want to find ceil. - ## Complexity These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in ```O(log (n))``` time . From 44c4d2507ccaebe322dcb212f7390638dc976af6 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Wed, 10 Nov 2021 12:25:14 +0530 Subject: [PATCH 09/25] Update BinarySearchApplication.md done changes --- .../Binary Search/BinarySearchApplication.md | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md index 863757eef4..0d0fcb8d8a 100644 --- a/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md +++ b/Competitive_Programming/C++/Searching & Sorting/Binary Search/BinarySearchApplication.md @@ -1,6 +1,9 @@ # Binary Search Application ## Linear Search + +### Explanation +In this the iterator visit one by one to each element of the array to search the element to be seached , so the complexity in Worst case is O(n) where n is the size of array The most simple way to search is linear search , as ```c++ //c++ @@ -22,11 +25,17 @@ for(int i=0;i<10;i++) cout<<"element not present"; } ``` -In this the iterator visit one by one to each element of the array to search the element to be seached , so the complexity in Worst case is O(n) where n is the size of array +>Time Complexity O(n) , where n is the size of array We should use linear search incases where the array is not sorted neither monotonic nor bitonic way. ## Binary Search +### Explanation + +In Binary Search we divide the array in *two halves* and then one half is decided and the searching is done on that half only similarily this divide take place till the element is not found. +so the the time complexity in Worst Case is *O(log n)* where n is the size of array. + + ```c++ //c++ int arr[10]={1,2,3,4,5,6,7,8,9,10}; @@ -45,14 +54,23 @@ while(start<=end) } return -1; // not found ``` - -In Binary Search we divide the array in *two halves* and then one half is decided and the searching is done on that half only similarily this divide take place till the element is not found. -so the the time complexity in Worst Case is *O(log n)* where n is the size of array. +>Time Complexity O(log n) , where n is the size of array Binary Search can solve various other problem in Competitive Programming where we have to print result in specific time otherwise TLE comes. ## Find the first and last occurence +### Explanation + +- In the case of first occurence we search the element and when we find that the mid calculated is the index that has the same element so this can be a answer , that is why we save the index in a varible and move the end pointer to mid-1 , to serach if the element is present before the index stored. +- This way after the binary search the result will have the index of first occurence of that element. +- Similarily in Last occurence we search the element and when we find that the mid calculated is the index that has the same element so this can be a answer , that is why we save the index in a varible and move the start pointer to mid+1 , to serach if the element is present after the index stored. +- This way after the binary search the result will have the index of last occurence of that element. + +In this we can find the occurence of element in array in O(log(n)) time where n is the size of array. we can find the total number of time the element comes in the array if we know the first and last occurence . + +>count= first_occurence - last_occurence + ```c++ #include using namespace std; @@ -107,11 +125,8 @@ return 0; > >Last occurence 4 ->Time Complexity O(log n) +>Time Complexity O(log n) , where n is the size of array -In this we can find the occurence of element in array in O(log(n)) time where n is the size of array. we can find the total number of time the element comes in the array if we know the first and last occurence . - ->count= first_occurence - last_occurence ## Find Floor and Ceil of a element from a given array in O(log n) time complexity @@ -194,6 +209,3 @@ return 0; ## Complexity These are some of the programs that can be solve by Binary Search , Binary search is really important in competitve programming as it do the searching in ```O(log (n))``` time . ->The flow of document -> ->Title -> explanation -> code -> Time Complexity From 46b5ca0c8cfefe74d488182b56f3ed9126c5b76b Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Tue, 16 Nov 2021 01:10:08 +0530 Subject: [PATCH 10/25] Create EuclidAlgorithm.md This include the brute force and Euclid way to find GCD --- .../Maths & Number Theory/EuclidAlgorithm.md | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md diff --git a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md new file mode 100644 index 0000000000..31351d84dd --- /dev/null +++ b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md @@ -0,0 +1,79 @@ +# Euclid Algorithm + +## GCD +Greatest common divisor (GCD) of two nonzero integers a and b is the greatest positive integer d such that d is a divisor of both a and b. + +### Explaination: +1. Initially gcd is equal to 1, as in all nonzero numbers the common divisor is 1. +2. Check among the both the numbers (a and b) which is minimum, as the gcd will be less than or equal to the minimum number. +3. Iterate in reverse order, and the number that divides both the numbers completely will be the gcd. +```C++ +#include +using namespace std; +int main () +{ + int gcd=1; + int a,b; + int n; + cin>>a; // number 1 + cin>>b; // number 2 + if(a>b) // finding minimum among number 1 and number 2 + n=b; + else + n=a; + for(int i=n;i>0;i--) + { + if(a%i==0 && b%i==0) + { + gcd=i; + break; + } + } + cout<<" The GCD of "<Time Complexity: O(n) +> +>where n is the minimum of two numbers. + +
+The disadvantage in this way of finding is that in competitive programming, this can result in TLE (Time Limit Exceeded). and GCD is a common sub question, which can be used in a problem and if this will add O(n) times then the code efficiency decrease. +

+ +## Euclid Algorithm - GCD IN O(log(min(a, b))) Time Complexity +
+1. In this Algorithm, we donot need to check id a>b or b>a , both will produce the correct result . +2. The iteration will be done till a (1st number) doesnot become 0, base case. +3. At every iteration a is stores by b mod a and b stores a. + + +``` C++ +#include +using namespace std; + +int gcd(int a, int b) +{ + if (a == 0) + return b; + return gcd(b % a, a); +} +int main() +{ + int gcd=1; + int a,b; + int n; + cin>>a; //number 1 + cin>>b; //number 2 + cout<<" The GCD of "< Time Complexity : +> +> O(log(min(a, b))) + +The complexity is O(log (min(a,b))) , as at every iteration (b % a) is done till a becomes 0 , this will take logarithmic time and it will depend on the minimum of the two element. + +This method helps us to solve gcd problem efficiently. From 28bddfe0174d957590639ae25b795eab2e4f112f Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sun, 21 Nov 2021 15:27:25 +0530 Subject: [PATCH 11/25] Create heap.md --- heap.md | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 heap.md diff --git a/heap.md b/heap.md new file mode 100644 index 0000000000..5eb9f31cb6 --- /dev/null +++ b/heap.md @@ -0,0 +1,92 @@ +# Heap Application in Competitive Programming + +## Kth Largest Element + +The Brute Force method to find the kth largest element is to first sort and then find the k-1 index element. This will take O(n log n) time. +Optimized way to solve this is to use min-heap, and this will take O(n log K) time. + +The property of the min-heap structure is that the minimum element remains at the top as we have to find only the kth largest element so after maintaining the heap of k size we can just pop the next top element, as it will be smaller than the kth element. + +The answer will be at the top of the min heap. + +```c++ +//c++ +#include +using namespace std; +int findKthLargest(vectornums, int k) { +priority_queue, greater> minh; +for (auto i = nums.begin(); i != nums.end(); i++){ + minh.push(*i); + if(minh.size()>k){ + minh.pop(); + } +} +return minh.top(); +} +int main(){ +vector v={6,5,2,7,1,8,4,9,10,11}; +int k=3; +int ele; +ele=findKthLargest(v,k); +cout<<"Kth largest element "<OUTPUT: +> +>Kth largest element 9 +> + +> +>*Time Complexity* +> +>*O(n log k)* + +## Top K Frequent Elements + +In this the brute force approach, first form a map to keep the record of the frequency of each element. then Iterate to each element to check which element is are coming frequently, return top k element this will take almost O(n^2) time. + +The Optimize approach is to use heap, after forming a map, we can insert the pair of the frequency and the element in the min heap and the element at the bottom will be the answer of the top k elements. by this method it will take O(n log k) complexity. +```c++ +//c++ +#include +using namespace std; +typedef pair pi; +vector topKFrequent(vector nums, int k) { + priority_queue, greater> pr; + unordered_map mp; + for(auto nm : nums){ + mp[nm]++; + } + vector r; + for(auto m: mp){ + pr.push({m.second,m.first}); + if(pr.size()>k) + pr.pop(); + } + while(pr.size()>0){ + r.push_back(pr.top().second); + pr.pop(); + } + return r; +} +int main(){ +vector v={1,1,1,2,2,2,3}; +int k=2; +vector r; +r=topKFrequent(v,k); +for(auto e:r){ + cout<OUTPUT: +> +> 1 2 +> + +> +>*Time Complexity* +> +>*O(n log k)* From 4bbc08ce2c2a242aa581cc7c7c3e8a3e126cda9d Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sun, 21 Nov 2021 15:43:47 +0530 Subject: [PATCH 12/25] Delete heap.md --- heap.md | 92 --------------------------------------------------------- 1 file changed, 92 deletions(-) delete mode 100644 heap.md diff --git a/heap.md b/heap.md deleted file mode 100644 index 5eb9f31cb6..0000000000 --- a/heap.md +++ /dev/null @@ -1,92 +0,0 @@ -# Heap Application in Competitive Programming - -## Kth Largest Element - -The Brute Force method to find the kth largest element is to first sort and then find the k-1 index element. This will take O(n log n) time. -Optimized way to solve this is to use min-heap, and this will take O(n log K) time. - -The property of the min-heap structure is that the minimum element remains at the top as we have to find only the kth largest element so after maintaining the heap of k size we can just pop the next top element, as it will be smaller than the kth element. - -The answer will be at the top of the min heap. - -```c++ -//c++ -#include -using namespace std; -int findKthLargest(vectornums, int k) { -priority_queue, greater> minh; -for (auto i = nums.begin(); i != nums.end(); i++){ - minh.push(*i); - if(minh.size()>k){ - minh.pop(); - } -} -return minh.top(); -} -int main(){ -vector v={6,5,2,7,1,8,4,9,10,11}; -int k=3; -int ele; -ele=findKthLargest(v,k); -cout<<"Kth largest element "<OUTPUT: -> ->Kth largest element 9 -> - -> ->*Time Complexity* -> ->*O(n log k)* - -## Top K Frequent Elements - -In this the brute force approach, first form a map to keep the record of the frequency of each element. then Iterate to each element to check which element is are coming frequently, return top k element this will take almost O(n^2) time. - -The Optimize approach is to use heap, after forming a map, we can insert the pair of the frequency and the element in the min heap and the element at the bottom will be the answer of the top k elements. by this method it will take O(n log k) complexity. -```c++ -//c++ -#include -using namespace std; -typedef pair pi; -vector topKFrequent(vector nums, int k) { - priority_queue, greater> pr; - unordered_map mp; - for(auto nm : nums){ - mp[nm]++; - } - vector r; - for(auto m: mp){ - pr.push({m.second,m.first}); - if(pr.size()>k) - pr.pop(); - } - while(pr.size()>0){ - r.push_back(pr.top().second); - pr.pop(); - } - return r; -} -int main(){ -vector v={1,1,1,2,2,2,3}; -int k=2; -vector r; -r=topKFrequent(v,k); -for(auto e:r){ - cout<OUTPUT: -> -> 1 2 -> - -> ->*Time Complexity* -> ->*O(n log k)* From 2a994e037fd8a9eb4daaa592ad9caaa91243c1af Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Mon, 22 Nov 2021 00:16:26 +0530 Subject: [PATCH 13/25] Create heap.md --- heap.md | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 heap.md diff --git a/heap.md b/heap.md new file mode 100644 index 0000000000..200735c36c --- /dev/null +++ b/heap.md @@ -0,0 +1,89 @@ +# Heap Application in Competitive Programming + +## Kth Largest Element + +The Brute Force method to find the kth largest element is to first sort and then find the k-1 index element. This will take O(n log n) time. +Optimized way to solve this is to use min-heap, and this will take O(n log K) time. + +The property of the min-heap structure is that the minimum element remains at the top as we have to find only the kth largest element so after maintaining the heap of k size we can just pop the next top element, as it will be smaller than the kth element. + +The answer will be at the top of the min heap. + +```c++ +//c++ +#include +using namespace std; +int findKthLargest(vectornums, int k) { +priority_queue, greater> minh; +for (auto i = nums.begin(); i != nums.end(); i++){ + minh.push(*i); + if(minh.size()>k){ + minh.pop(); + } +} +return minh.top(); +} +int main(){ +vector v={6,5,2,7,1,8,4,9,10,11}; +int k=3; +int ele; +ele=findKthLargest(v,k); +cout<<"Kth largest element "<OUTPUT: +> +>Kth largest element 9 +> +> +>*Time Complexity* +> +>*O(n log k)* +## Top K Frequent Elements + +In this the brute force approach, first form a map to keep the record of the frequency of each element. then Iterate to each element to check which element is are coming frequently, return top k element this will take almost O(n^2) time. + +The Optimize approach is to use heap, after forming a map, we can insert the pair of the frequency and the element in the min heap and the element at the bottom will be the answer of the top k elements. by this method it will take O(n log k) complexity. +```c++ +//c++ +#include +using namespace std; +typedef pair pi; +vector topKFrequent(vector nums, int k) { + priority_queue, greater> pr; + unordered_map mp; + for(auto nm : nums){ + mp[nm]++; + } + vector r; + for(auto m: mp){ + pr.push({m.second,m.first}); + if(pr.size()>k) + pr.pop(); + } + while(pr.size()>0){ + r.push_back(pr.top().second); + pr.pop(); + } + return r; +} +int main(){ +vector v={1,1,1,2,2,2,3}; +int k=2; +vector r; +r=topKFrequent(v,k); +for(auto e:r){ + cout<OUTPUT: +> +> 1 2 +> +> +>*Time Complexity* +> +>*O(n log k)* From 37c05692156631aaf8f864e99f1905cf31de126b Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Mon, 22 Nov 2021 00:51:58 +0530 Subject: [PATCH 14/25] Delete heap.md --- heap.md | 89 --------------------------------------------------------- 1 file changed, 89 deletions(-) delete mode 100644 heap.md diff --git a/heap.md b/heap.md deleted file mode 100644 index 200735c36c..0000000000 --- a/heap.md +++ /dev/null @@ -1,89 +0,0 @@ -# Heap Application in Competitive Programming - -## Kth Largest Element - -The Brute Force method to find the kth largest element is to first sort and then find the k-1 index element. This will take O(n log n) time. -Optimized way to solve this is to use min-heap, and this will take O(n log K) time. - -The property of the min-heap structure is that the minimum element remains at the top as we have to find only the kth largest element so after maintaining the heap of k size we can just pop the next top element, as it will be smaller than the kth element. - -The answer will be at the top of the min heap. - -```c++ -//c++ -#include -using namespace std; -int findKthLargest(vectornums, int k) { -priority_queue, greater> minh; -for (auto i = nums.begin(); i != nums.end(); i++){ - minh.push(*i); - if(minh.size()>k){ - minh.pop(); - } -} -return minh.top(); -} -int main(){ -vector v={6,5,2,7,1,8,4,9,10,11}; -int k=3; -int ele; -ele=findKthLargest(v,k); -cout<<"Kth largest element "<OUTPUT: -> ->Kth largest element 9 -> -> ->*Time Complexity* -> ->*O(n log k)* -## Top K Frequent Elements - -In this the brute force approach, first form a map to keep the record of the frequency of each element. then Iterate to each element to check which element is are coming frequently, return top k element this will take almost O(n^2) time. - -The Optimize approach is to use heap, after forming a map, we can insert the pair of the frequency and the element in the min heap and the element at the bottom will be the answer of the top k elements. by this method it will take O(n log k) complexity. -```c++ -//c++ -#include -using namespace std; -typedef pair pi; -vector topKFrequent(vector nums, int k) { - priority_queue, greater> pr; - unordered_map mp; - for(auto nm : nums){ - mp[nm]++; - } - vector r; - for(auto m: mp){ - pr.push({m.second,m.first}); - if(pr.size()>k) - pr.pop(); - } - while(pr.size()>0){ - r.push_back(pr.top().second); - pr.pop(); - } - return r; -} -int main(){ -vector v={1,1,1,2,2,2,3}; -int k=2; -vector r; -r=topKFrequent(v,k); -for(auto e:r){ - cout<OUTPUT: -> -> 1 2 -> -> ->*Time Complexity* -> ->*O(n log k)* From 418530ed296079b0bda84863453342783cb026c2 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Wed, 24 Nov 2021 23:38:59 +0530 Subject: [PATCH 15/25] Create TopKthFrequentElement.md --- .../TopKthFrequentElement.md | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 Heap/TopKthFrequentElement/TopKthFrequentElement.md diff --git a/Heap/TopKthFrequentElement/TopKthFrequentElement.md b/Heap/TopKthFrequentElement/TopKthFrequentElement.md new file mode 100644 index 0000000000..c0034ed997 --- /dev/null +++ b/Heap/TopKthFrequentElement/TopKthFrequentElement.md @@ -0,0 +1,121 @@ +## Top K Frequent Elements + +- In this the brute force approach, first form a map to keep the record of the frequency of each element. +- then store the map values to the vector in the form of pair that is vector< pair > . +- sort the vector in decreasing order of frequency. +-now the first k elements of the sorted array , are the required result. + +```c++ +//c++ + #include + using namespace std; + typedef pair < int, int >pi; + + bool compare (pi p1, pi p2) + { + if (p1.second == p2.second) + return p1.first > p2.first; + return p1.second > p2.second; + } + + vector < int > topKFrequent (vector < int >nums, int k) + { + int n = nums.size (); + vector < int >r; + unordered_map < int, int >m; + for (int i = 0; i < n; i++) + m[arr[i]]++; + vector < pi > tmp (m.begin (), m.end ()); + sort (tmp.begin (), tmp.end (), compare); + for (int i = 0; i < k; i++) + { + r.push_back (tmp[i].first); + + } + } + + int main () + { + vector < int >v = { 1, 1, 1, 2, 2, 2, 3 }; + int k = 2; + vector < int >r; + r = topKFrequent (v, k); + for (auto e:r) + { + cout << e << " "; + } + return 0; + } +``` +>OUTPUT: +> +> 1 2 +> + +> +>*Time Complexity* +> +>*O(d log d)* + + where d is the count of distinct elements in the vector/array. + + +The Optimize approach is to use heap, +- after forming a map, we can insert the pair of the frequency and the element in the min heap. +- the element at the bottom will be the answer of the top k elements. +- by this method it will take O(k log d) complexity. +where d is the count of distinct elements in the vector/array. +```c++ +//c++ + #include + using namespace std; + typedef pair < int, int >pi; + + vector < int > topKFrequent (vector < int >nums, int k) + { + priority_queue < pi, vector < pi >, greater < pi >> pr; + unordered_map < int, int >mp; + for (auto nm:nums) + { + mp[nm]++; + } + vector < int >r; + for (auto m:mp) + { + pr.push ( + { + m.second, m.first} + ); + if (pr.size () > k) + pr.pop (); + } + while (pr.size () > 0) + { + r.push_back (pr.top ().second); + pr.pop (); + } + return r; + } + + int main () + { + vector < int >v = { 1, 1, 1, 2, 2, 2, 3 }; + int k = 2; + vector < int >r; + r = topKFrequent (v, k); + for (auto e:r) + { + cout << e << " "; + } + return 0; + } +``` +>OUTPUT: +> +> 1 2 +> + +> +>*Time Complexity* +> +>*O(k log d)* From d67be13594c1de398f0efb0124264c9babaf1f70 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Thu, 25 Nov 2021 22:47:55 +0530 Subject: [PATCH 16/25] Delete TopKthFrequentElement.md --- .../TopKthFrequentElement.md | 121 ------------------ 1 file changed, 121 deletions(-) delete mode 100644 Heap/TopKthFrequentElement/TopKthFrequentElement.md diff --git a/Heap/TopKthFrequentElement/TopKthFrequentElement.md b/Heap/TopKthFrequentElement/TopKthFrequentElement.md deleted file mode 100644 index c0034ed997..0000000000 --- a/Heap/TopKthFrequentElement/TopKthFrequentElement.md +++ /dev/null @@ -1,121 +0,0 @@ -## Top K Frequent Elements - -- In this the brute force approach, first form a map to keep the record of the frequency of each element. -- then store the map values to the vector in the form of pair that is vector< pair > . -- sort the vector in decreasing order of frequency. --now the first k elements of the sorted array , are the required result. - -```c++ -//c++ - #include - using namespace std; - typedef pair < int, int >pi; - - bool compare (pi p1, pi p2) - { - if (p1.second == p2.second) - return p1.first > p2.first; - return p1.second > p2.second; - } - - vector < int > topKFrequent (vector < int >nums, int k) - { - int n = nums.size (); - vector < int >r; - unordered_map < int, int >m; - for (int i = 0; i < n; i++) - m[arr[i]]++; - vector < pi > tmp (m.begin (), m.end ()); - sort (tmp.begin (), tmp.end (), compare); - for (int i = 0; i < k; i++) - { - r.push_back (tmp[i].first); - - } - } - - int main () - { - vector < int >v = { 1, 1, 1, 2, 2, 2, 3 }; - int k = 2; - vector < int >r; - r = topKFrequent (v, k); - for (auto e:r) - { - cout << e << " "; - } - return 0; - } -``` ->OUTPUT: -> -> 1 2 -> - -> ->*Time Complexity* -> ->*O(d log d)* - - where d is the count of distinct elements in the vector/array. - - -The Optimize approach is to use heap, -- after forming a map, we can insert the pair of the frequency and the element in the min heap. -- the element at the bottom will be the answer of the top k elements. -- by this method it will take O(k log d) complexity. -where d is the count of distinct elements in the vector/array. -```c++ -//c++ - #include - using namespace std; - typedef pair < int, int >pi; - - vector < int > topKFrequent (vector < int >nums, int k) - { - priority_queue < pi, vector < pi >, greater < pi >> pr; - unordered_map < int, int >mp; - for (auto nm:nums) - { - mp[nm]++; - } - vector < int >r; - for (auto m:mp) - { - pr.push ( - { - m.second, m.first} - ); - if (pr.size () > k) - pr.pop (); - } - while (pr.size () > 0) - { - r.push_back (pr.top ().second); - pr.pop (); - } - return r; - } - - int main () - { - vector < int >v = { 1, 1, 1, 2, 2, 2, 3 }; - int k = 2; - vector < int >r; - r = topKFrequent (v, k); - for (auto e:r) - { - cout << e << " "; - } - return 0; - } -``` ->OUTPUT: -> -> 1 2 -> - -> ->*Time Complexity* -> ->*O(k log d)* From 9e2e4ab02724c878e1de27ce67ccea6a13f7b6a4 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 00:00:47 +0530 Subject: [PATCH 17/25] Update EuclidAlgorithm.md --- .../Maths & Number Theory/EuclidAlgorithm.md | 131 ++++++++++++------ 1 file changed, 85 insertions(+), 46 deletions(-) diff --git a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md index 31351d84dd..fc80bd41fe 100644 --- a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md +++ b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md @@ -1,5 +1,14 @@ # Euclid Algorithm +Problem Statement : Find the GCD of two numbers in an optimised way. + +Input : +GCD : 12 18 + +Output : 6 + +Explaination : as 6 is the greatest common divisor. + ## GCD Greatest common divisor (GCD) of two nonzero integers a and b is the greatest positive integer d such that d is a divisor of both a and b. @@ -8,68 +17,98 @@ Greatest common divisor (GCD) of two nonzero integers a and b is the greatest po 2. Check among the both the numbers (a and b) which is minimum, as the gcd will be less than or equal to the minimum number. 3. Iterate in reverse order, and the number that divides both the numbers completely will be the gcd. ```C++ -#include -using namespace std; -int main () -{ - int gcd=1; - int a,b; - int n; - cin>>a; // number 1 - cin>>b; // number 2 - if(a>b) // finding minimum among number 1 and number 2 - n=b; - else - n=a; - for(int i=n;i>0;i--) - { - if(a%i==0 && b%i==0) - { - gcd=i; + #include + using namespace std; + int main () + { + int gcd = 1; + int a, b; + int n; + cin >> a; // number 1 + cin >> b; // number 2 + if (a > b) // finding minimum among number 1 and number 2 + n = b; + else + n = a; + for (int i = n; i > 0; i--) + { + if (a % i == 0 && b % i == 0) + { + gcd = i; break; - } - } - cout<<" The GCD of "<Time Complexity: O(n) > ->where n is the minimum of two numbers. +>where n is the smaller of two numbers.
The disadvantage in this way of finding is that in competitive programming, this can result in TLE (Time Limit Exceeded). and GCD is a common sub question, which can be used in a problem and if this will add O(n) times then the code efficiency decrease.

## Euclid Algorithm - GCD IN O(log(min(a, b))) Time Complexity -
-1. In this Algorithm, we donot need to check id a>b or b>a , both will produce the correct result . -2. The iteration will be done till a (1st number) doesnot become 0, base case. -3. At every iteration a is stores by b mod a and b stores a. +- In this we keep dividing the greater number from the two given number and it results into GCD +- The base case is when the remainder becomes 0. +- In this Algorithm, we donot need to check id a>b or b>a , both will produce the correct result +- The iteration will be done till a (1st number) doesnot become 0, base case. +- At every iteration a is stores by b mod a and b stores a. -``` C++ -#include -using namespace std; -int gcd(int a, int b) -{ - if (a == 0) +``` C++ + #include + using namespace std; + + int gcd (int a, int b) + { + if (a == 0) return b; - return gcd(b % a, a); -} -int main() -{ - int gcd=1; - int a,b; - int n; - cin>>a; //number 1 - cin>>b; //number 2 - cout<<" The GCD of "<> a; //number 1 + cin >> b; //number 2 + cout << " The GCD of " << a << " and " << b << " : " << gcd (a, b); + return 0; + } ``` + +Input : +GCD : 12 18 +Output : 6 + +*In this a and b are two numbers , in which at every recursive call a stores the remainder of +a%b and b stores the previous value of a. Base Case : when a becomes 0 that is the remainder +becomes 0 it will return b.* + +In the above example first a=12 a%b =6 , +this a%b is assign to a in other iteration +a=6 a%b=0, this a%b will be new a value, +since a is 0 this is the base case and b is returned as GCD +which is 6. + > Time Complexity : > > O(log(min(a, b))) From 2d9c394a688ccddbab52e022ecc8e526e2ece60f Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 11:04:27 +0530 Subject: [PATCH 18/25] Update EuclidAlgorithm.md --- .../C++/Maths & Number Theory/EuclidAlgorithm.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md index fc80bd41fe..fd2dafd84c 100644 --- a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md +++ b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md @@ -12,6 +12,8 @@ Explaination : as 6 is the greatest common divisor. ## GCD Greatest common divisor (GCD) of two nonzero integers a and b is the greatest positive integer d such that d is a divisor of both a and b. +# Basic Approach + ### Explaination: 1. Initially gcd is equal to 1, as in all nonzero numbers the common divisor is 1. 2. Check among the both the numbers (a and b) which is minimum, as the gcd will be less than or equal to the minimum number. @@ -63,6 +65,7 @@ and since 6 divides both , so it will GCD of 18 and 12.
The disadvantage in this way of finding is that in competitive programming, this can result in TLE (Time Limit Exceeded). and GCD is a common sub question, which can be used in a problem and if this will add O(n) times then the code efficiency decrease.

+# Optimised Approach ## Euclid Algorithm - GCD IN O(log(min(a, b))) Time Complexity From 638de2242414097cfd34c5aa7721bf75e5927638 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 13:47:24 +0530 Subject: [PATCH 19/25] Create ReverseWordInAString.md --- .../C++/String/ReverseWordInAString.md | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Competitive_Programming/C++/String/ReverseWordInAString.md diff --git a/Competitive_Programming/C++/String/ReverseWordInAString.md b/Competitive_Programming/C++/String/ReverseWordInAString.md new file mode 100644 index 0000000000..e761a1aee4 --- /dev/null +++ b/Competitive_Programming/C++/String/ReverseWordInAString.md @@ -0,0 +1,85 @@ + Reverse word in a String + +Input: s = "a good example" + +Output: "example good a" + +Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. + +## 1st Approach + +- In this approach , first we will reverse the given string . +- then we have to split the string using istringstream . +- then simply start the for each word we will reverse the word and it to the resultant string. +- to reverse function in c++ takes O(n) time complexity. + +``` c++ + string reverseWords(string s) { + reverse(s.begin(), s.end()); + string word, result; + istringstream iss(s); + + while (iss >> word) { + reverse(word.begin(), word.end()); + result += word + " "; + } + + result.pop_back(); + return result; + } + int main(){ + string st; + cin >> st; + cout << reverseWords ( st ); + return 0; + } +``` +>Input: s = "a good example" +> +>Output: "example good a" + +> Time Complexity O(n*m) n is number of words in the string ; m is the alphabets in each word. +> +>Space Complexity O(n) + +## 2nd Approach + +### Using Stack + +- In this approch , we will store the word in stack and when we have traverse the full string . +- then we will store the top word in resulting string and then pop. +- we will do this till the stack doesnot turn empty. + +**We have used stack as it works on principle of first in last out.** +``` c++ + string reverseWords(string s) { + stack words; + + istringstream iss(s); + string word; + while (iss >> word) { + words.push(word); + } + + string result = ""; + for (; !words.empty(); words.pop()) { + result += words.top() + " "; + } + + result.pop_back(); + return result; + } + int main(){ + string st; + cin >> st; + cout << reverseWords ( st ); + return 0; + } +``` +>Input: s = "a good example" +> +>Output: "example good a" + +>Time Complexity : O(n) , where n is the number of words in the string. +>Space Complexity: O(n) , as we are using stack + From 190919bd152035e4fbb4023c427d1be572a3d98c Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 20:26:07 +0530 Subject: [PATCH 20/25] Delete ReverseWordInAString.md --- .../C++/String/ReverseWordInAString.md | 85 ------------------- 1 file changed, 85 deletions(-) delete mode 100644 Competitive_Programming/C++/String/ReverseWordInAString.md diff --git a/Competitive_Programming/C++/String/ReverseWordInAString.md b/Competitive_Programming/C++/String/ReverseWordInAString.md deleted file mode 100644 index e761a1aee4..0000000000 --- a/Competitive_Programming/C++/String/ReverseWordInAString.md +++ /dev/null @@ -1,85 +0,0 @@ - Reverse word in a String - -Input: s = "a good example" - -Output: "example good a" - -Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. - -## 1st Approach - -- In this approach , first we will reverse the given string . -- then we have to split the string using istringstream . -- then simply start the for each word we will reverse the word and it to the resultant string. -- to reverse function in c++ takes O(n) time complexity. - -``` c++ - string reverseWords(string s) { - reverse(s.begin(), s.end()); - string word, result; - istringstream iss(s); - - while (iss >> word) { - reverse(word.begin(), word.end()); - result += word + " "; - } - - result.pop_back(); - return result; - } - int main(){ - string st; - cin >> st; - cout << reverseWords ( st ); - return 0; - } -``` ->Input: s = "a good example" -> ->Output: "example good a" - -> Time Complexity O(n*m) n is number of words in the string ; m is the alphabets in each word. -> ->Space Complexity O(n) - -## 2nd Approach - -### Using Stack - -- In this approch , we will store the word in stack and when we have traverse the full string . -- then we will store the top word in resulting string and then pop. -- we will do this till the stack doesnot turn empty. - -**We have used stack as it works on principle of first in last out.** -``` c++ - string reverseWords(string s) { - stack words; - - istringstream iss(s); - string word; - while (iss >> word) { - words.push(word); - } - - string result = ""; - for (; !words.empty(); words.pop()) { - result += words.top() + " "; - } - - result.pop_back(); - return result; - } - int main(){ - string st; - cin >> st; - cout << reverseWords ( st ); - return 0; - } -``` ->Input: s = "a good example" -> ->Output: "example good a" - ->Time Complexity : O(n) , where n is the number of words in the string. ->Space Complexity: O(n) , as we are using stack - From b1ce60dbb99672e4f8589ae5f6094e0e00624715 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 20:57:40 +0530 Subject: [PATCH 21/25] Create ReverseWordInAString.md --- .../C++/String/ReverseWordInAString.md | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Competitive_Programming/C++/String/ReverseWordInAString.md diff --git a/Competitive_Programming/C++/String/ReverseWordInAString.md b/Competitive_Programming/C++/String/ReverseWordInAString.md new file mode 100644 index 0000000000..5d6ffb038f --- /dev/null +++ b/Competitive_Programming/C++/String/ReverseWordInAString.md @@ -0,0 +1,85 @@ +# Reverse word in a String + +Input: s = "a good example" + +Output: "example good a" + +Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. + +## 1st Approach + +- In this approach , first we will reverse the given string . +- then we have to split the string using istringstream . +- then simply start the for each word we will reverse the word and it to the resultant string. +- to reverse function in c++ takes O(n) time complexity. + +``` c++ + string reverseWords(string s) { + reverse(s.begin(), s.end()); + string word, result; + istringstream iss(s); + + while (iss >> word) { + reverse(word.begin(), word.end()); + result += word + " "; + } + + result.pop_back(); + return result; + } + int main(){ + string st; + cin >> st; + cout << reverseWords ( st ); + return 0; + } +``` +>Input: s = "a good example" +> +>Output: "example good a" + +> Time Complexity O(n*m) n is number of words in the string ; m is the alphabets in each word. +> +>Space Complexity O(n) + +## 2nd Approach + +### Using Stack + +- In this approch , we will store the word in stack and when we have traverse the full string . +- then we will store the top word in resulting string and then pop. +- we will do this till the stack doesnot turn empty. + +**We have used stack as it works on principle of first in last out.** +``` c++ + string reverseWords(string s) { + stack words; + + istringstream iss(s); + string word; + while (iss >> word) { + words.push(word); + } + + string result = ""; + for (; !words.empty(); words.pop()) { + result += words.top() + " "; + } + + result.pop_back(); + return result; + } + int main(){ + string st; + cin >> st; + cout << reverseWords ( st ); + return 0; + } +``` +>Input: s = "a good example" +> +>Output: "example good a" + +>Time Complexity : O(n) , where n is the number of words in the string. +>Space Complexity: O(n) , as we are using stack + From 9a941089e8ded7ede1d63dc9a8c652a80ce571ee Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Fri, 26 Nov 2021 21:05:15 +0530 Subject: [PATCH 22/25] Delete EuclidAlgorithm.md --- .../Maths & Number Theory/EuclidAlgorithm.md | 121 ------------------ 1 file changed, 121 deletions(-) delete mode 100644 Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md diff --git a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md b/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md deleted file mode 100644 index fd2dafd84c..0000000000 --- a/Competitive_Programming/C++/Maths & Number Theory/EuclidAlgorithm.md +++ /dev/null @@ -1,121 +0,0 @@ -# Euclid Algorithm - -Problem Statement : Find the GCD of two numbers in an optimised way. - -Input : -GCD : 12 18 - -Output : 6 - -Explaination : as 6 is the greatest common divisor. - -## GCD -Greatest common divisor (GCD) of two nonzero integers a and b is the greatest positive integer d such that d is a divisor of both a and b. - -# Basic Approach - -### Explaination: -1. Initially gcd is equal to 1, as in all nonzero numbers the common divisor is 1. -2. Check among the both the numbers (a and b) which is minimum, as the gcd will be less than or equal to the minimum number. -3. Iterate in reverse order, and the number that divides both the numbers completely will be the gcd. -```C++ - #include - using namespace std; - int main () - { - int gcd = 1; - int a, b; - int n; - cin >> a; // number 1 - cin >> b; // number 2 - if (a > b) // finding minimum among number 1 and number 2 - n = b; - else - n = a; - for (int i = n; i > 0; i--) - { - if (a % i == 0 && b % i == 0) - { - gcd = i; - break; - } - } - cout << " The GCD of " << a << " and " << b << " : " << gcd; - return 0; - } -``` - -Input : -GCD : 12 18 -Output : 6 - -*In this we will first find the smaller number from both a and b , then -in the loop from the smaller number to 0 iterate and check which number divides both, -that will be the GCD of the given two numbers.* - -So in the above example since from 18 and 12 , 12 is smaller -so the loop will work will start from 12 to 0 , -and since 6 divides both , so it will GCD of 18 and 12. - - ->Time Complexity: O(n) -> ->where n is the smaller of two numbers. - -
-The disadvantage in this way of finding is that in competitive programming, this can result in TLE (Time Limit Exceeded). and GCD is a common sub question, which can be used in a problem and if this will add O(n) times then the code efficiency decrease. -

-# Optimised Approach - -## Euclid Algorithm - GCD IN O(log(min(a, b))) Time Complexity - -- In this we keep dividing the greater number from the two given number and it results into GCD -- The base case is when the remainder becomes 0. -- In this Algorithm, we donot need to check id a>b or b>a , both will produce the correct result -- The iteration will be done till a (1st number) doesnot become 0, base case. -- At every iteration a is stores by b mod a and b stores a. - - -``` C++ - #include - using namespace std; - - int gcd (int a, int b) - { - if (a == 0) - return b; - return gcd (b % a, a); - } - - int main () - { - int a, b; - int n; - cin >> a; //number 1 - cin >> b; //number 2 - cout << " The GCD of " << a << " and " << b << " : " << gcd (a, b); - return 0; - } -``` - -Input : -GCD : 12 18 -Output : 6 - -*In this a and b are two numbers , in which at every recursive call a stores the remainder of -a%b and b stores the previous value of a. Base Case : when a becomes 0 that is the remainder -becomes 0 it will return b.* - -In the above example first a=12 a%b =6 , -this a%b is assign to a in other iteration -a=6 a%b=0, this a%b will be new a value, -since a is 0 this is the base case and b is returned as GCD -which is 6. - -> Time Complexity : -> -> O(log(min(a, b))) - -The complexity is O(log (min(a,b))) , as at every iteration (b % a) is done till a becomes 0 , this will take logarithmic time and it will depend on the minimum of the two element. - -This method helps us to solve gcd problem efficiently. From c872926e34caa8b275632164dc2e19f36a05cbfc Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 27 Nov 2021 13:45:00 +0530 Subject: [PATCH 23/25] Competitive programming (#9) * Create ReverseWordInAString.md (#6) * Competitive programming (#8) * Merge two arrays according to constraints added. * Create MagicNumber.md * Rename MagicNumber.md to NthMagicNumber.md * header file and heading added. * Rename Competitive_Programming/Python/Maths & Number Theory/MagicNumber/NthMagicNumber.md to Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md Co-authored-by: BootLook <73538645+priyankapiba@users.noreply.github.com> Co-authored-by: Jinal4502 <65852362+Jinal4502@users.noreply.github.com> Co-authored-by: Ahana Pal <59911272+ErzaTitania-2001@users.noreply.github.com> Co-authored-by: BootLook <73538645+priyankapiba@users.noreply.github.com> Co-authored-by: Jinal4502 <65852362+Jinal4502@users.noreply.github.com> Co-authored-by: Ahana Pal <59911272+ErzaTitania-2001@users.noreply.github.com> --- .../C++/Array/Merge-two-arrays.md | 106 ++++++++++++++++++ .../NthMagicNumber/NthMagicNumber.md | 66 +++++++++++ 2 files changed, 172 insertions(+) create mode 100644 Competitive_Programming/C++/Array/Merge-two-arrays.md create mode 100644 Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md diff --git a/Competitive_Programming/C++/Array/Merge-two-arrays.md b/Competitive_Programming/C++/Array/Merge-two-arrays.md new file mode 100644 index 0000000000..80d0fc3846 --- /dev/null +++ b/Competitive_Programming/C++/Array/Merge-two-arrays.md @@ -0,0 +1,106 @@ +# Merge two arrays by satisfying given constraints +Given two sorted arrays X[] and Y[] of size m and n each where m >= n and X[] has exactly n vacant cells, merge elements of Y[] in their correct position in array X[], i.e., merge (X, Y) by keeping the sorted order. + +For example, + +## Input: + +X[] = { 0, 2, 0, 3, 0, 5, 6, 0, 0 } +Y[] = { 1, 8, 9, 10, 15 } + +The vacant cells in X[] is represented by 0 + +## Output: + +X[] = { 1, 2, 3, 5, 6, 8, 9, 10, 15 } + +## Approach: +The idea is simple – move non-empty elements of X[] at the beginning of X[] and then merge X[] with Y[] starting from the end. The merge process is similar to the merge routine of the merge sort algorithm. + +## Code: +``` Cpp +#include= 0 && n >= 0) + { + // put the next greater element in the next free position in `X[]` from the end + if (X[m] > Y[n]) { + X[k--] = X[m--]; + } + else { + X[k--] = Y[n--]; + } + } + + // copy the remaining elements of `Y[]` (if any) to `X[]` + while (n >= 0) { + X[k--] = Y[n--]; + } + + // fill `Y[]` with all zeroes + for (int i = 0; i < n; i++) { + Y[i] = 0; + } +} + +// The function moves non-empty elements in `X[]` in the +// beginning and then merge them with `Y[]` +void rearrange(int X[], int Y[], int m, int n) +{ + // return if `X` is empty + if (m == 0) { + return; + } + + // moves non-empty elements of `X[]` at the beginning + int k = 0; + for (int i = 0; i < m; i++) + { + if (X[i] != 0) { + X[k++] = X[i]; + } + } + + // merge `X[0 … k-1]` and `Y[0 … n-1]` into `X[0 … m-1]` + merge(X, Y, k - 1, n - 1); +} + +int main() +{ + // vacant cells in `X[]` is represented by 0 + int X[] = { 0, 2, 0, 3, 0, 5, 6, 0, 0 }; + int Y[] = { 1, 8, 9, 10, 15 }; + + int m = sizeof(X) / sizeof(X[0]); + int n = sizeof(Y) / sizeof(Y[0]); + + /* Validate input before calling `rearrange()` + 1. Both arrays `X[]` and `Y[]` should be sorted (ignore 0's in `X[]`) + 2. Size of array `X[]` >= size of array `Y[]` (i.e., `m >= n`) + 3. Total number of vacant cells in array `X[]` = size of array `Y[]` */ + + // merge `Y[]` into `X[]` + rearrange(X, Y, m, n); + + // print merged array + for (int i = 0; i < m; i++) { + printf("%d ", X[i]); + } + + return 0; +} +``` + +## Output: + +1 2 3 5 6 8 9 10 15 + +## Time Complexity +Time complexity of the above solution is O(m + n) and runs in constant space. Here, m and n are the size of the first and second array, respectively. diff --git a/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md b/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md new file mode 100644 index 0000000000..055d512092 --- /dev/null +++ b/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md @@ -0,0 +1,66 @@ +# Nth Magic Number + +A number that can be represented as a power of 5 or sum of unique powers of 5 is called a magic number. + +Initial magic numbers are: + +5, 25, 30(5+25), 125, 130(5+125), 150(25 + 125), 155(5+25+125), 625, 630(5+625), 650(25+625), 655(5+25+625), 750(125+625), 755(5+125+625), 775(25+125+625), 780(5+25+125+625), 3125, .... + +| value of n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +|------------------|---|----|----|-----|-----|-----|-----|-----|-----|-----| +| nth magic number | 5 | 25 | 30 | 125 | 130 | 150 | 155 | 625 | 630 | 650 | + + +Also, for n-values can be represented in binary as 0001(1), 0010(2), 0011(3), 0100(4), 0101(5), ... + +| value of n | 0001 | 0010 | 0011 | 0100 | 0101 | 0110 | 0111 | 1000 | 1001 | 1010 | +|------------------|------|------|------|------|------|------|------|------|------|------| +| nth magic number | 5 | 25 | 30 | 125 | 130 | 150 | 155 | 625 | 630 | 650 | + +For example, take n = 0011 i.e. n = 3, so we can get the nth magic number in this way, + +``` +0*pow(5,4) + 0*pow(5,3) + 1*pow(5,2) + 1*pow(5,1) += 0 + 0 + 25 + 5 += 30 +``` + +## Implementation in Python: + +```Python3 +def magic_number(n): + + temp = 1 + nth_magic_num = 0 + + # Continue till all the bits of n are not zero + while (n): + + temp = temp*5 + + # if the rightmost bit of n is 1 + if (n & 1): + nth_magic_num += temp + + # right-shift by one bit i.e. it will return half of a given number + # example: + # 5 -> 0101 + # 5 >>=1 -> 0010 -> 2 + # or 5 // 2 = 2 + n >>= 1 # or n = n//2 + + return nth_magic_num + + +# Input function +n = 7 +print(f"{n}th magic number is {magic_number(n)}.") +``` + +### Output: + +7th magic number is 155. + +## Time Complexity: + +The time complexity of this algorithm will be O(logn) as everytime we reduce the number by a factor of 2. From c870f05c4490ff90e35201076ad672c5ba7ba206 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 27 Nov 2021 13:51:39 +0530 Subject: [PATCH 24/25] Delete NthMagicNumber.md --- .../NthMagicNumber/NthMagicNumber.md | 66 ------------------- 1 file changed, 66 deletions(-) delete mode 100644 Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md diff --git a/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md b/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md deleted file mode 100644 index 055d512092..0000000000 --- a/Competitive_Programming/Python/Maths & Number Theory/NthMagicNumber/NthMagicNumber.md +++ /dev/null @@ -1,66 +0,0 @@ -# Nth Magic Number - -A number that can be represented as a power of 5 or sum of unique powers of 5 is called a magic number. - -Initial magic numbers are: - -5, 25, 30(5+25), 125, 130(5+125), 150(25 + 125), 155(5+25+125), 625, 630(5+625), 650(25+625), 655(5+25+625), 750(125+625), 755(5+125+625), 775(25+125+625), 780(5+25+125+625), 3125, .... - -| value of n | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -|------------------|---|----|----|-----|-----|-----|-----|-----|-----|-----| -| nth magic number | 5 | 25 | 30 | 125 | 130 | 150 | 155 | 625 | 630 | 650 | - - -Also, for n-values can be represented in binary as 0001(1), 0010(2), 0011(3), 0100(4), 0101(5), ... - -| value of n | 0001 | 0010 | 0011 | 0100 | 0101 | 0110 | 0111 | 1000 | 1001 | 1010 | -|------------------|------|------|------|------|------|------|------|------|------|------| -| nth magic number | 5 | 25 | 30 | 125 | 130 | 150 | 155 | 625 | 630 | 650 | - -For example, take n = 0011 i.e. n = 3, so we can get the nth magic number in this way, - -``` -0*pow(5,4) + 0*pow(5,3) + 1*pow(5,2) + 1*pow(5,1) -= 0 + 0 + 25 + 5 -= 30 -``` - -## Implementation in Python: - -```Python3 -def magic_number(n): - - temp = 1 - nth_magic_num = 0 - - # Continue till all the bits of n are not zero - while (n): - - temp = temp*5 - - # if the rightmost bit of n is 1 - if (n & 1): - nth_magic_num += temp - - # right-shift by one bit i.e. it will return half of a given number - # example: - # 5 -> 0101 - # 5 >>=1 -> 0010 -> 2 - # or 5 // 2 = 2 - n >>= 1 # or n = n//2 - - return nth_magic_num - - -# Input function -n = 7 -print(f"{n}th magic number is {magic_number(n)}.") -``` - -### Output: - -7th magic number is 155. - -## Time Complexity: - -The time complexity of this algorithm will be O(logn) as everytime we reduce the number by a factor of 2. From 3ea0050bae64450ce23255439218a07db356c306 Mon Sep 17 00:00:00 2001 From: Sakshi Arora <59931342+iam-sakshi@users.noreply.github.com> Date: Sat, 27 Nov 2021 13:52:10 +0530 Subject: [PATCH 25/25] Delete Merge-two-arrays.md --- .../C++/Array/Merge-two-arrays.md | 106 ------------------ 1 file changed, 106 deletions(-) delete mode 100644 Competitive_Programming/C++/Array/Merge-two-arrays.md diff --git a/Competitive_Programming/C++/Array/Merge-two-arrays.md b/Competitive_Programming/C++/Array/Merge-two-arrays.md deleted file mode 100644 index 80d0fc3846..0000000000 --- a/Competitive_Programming/C++/Array/Merge-two-arrays.md +++ /dev/null @@ -1,106 +0,0 @@ -# Merge two arrays by satisfying given constraints -Given two sorted arrays X[] and Y[] of size m and n each where m >= n and X[] has exactly n vacant cells, merge elements of Y[] in their correct position in array X[], i.e., merge (X, Y) by keeping the sorted order. - -For example, - -## Input: - -X[] = { 0, 2, 0, 3, 0, 5, 6, 0, 0 } -Y[] = { 1, 8, 9, 10, 15 } - -The vacant cells in X[] is represented by 0 - -## Output: - -X[] = { 1, 2, 3, 5, 6, 8, 9, 10, 15 } - -## Approach: -The idea is simple – move non-empty elements of X[] at the beginning of X[] and then merge X[] with Y[] starting from the end. The merge process is similar to the merge routine of the merge sort algorithm. - -## Code: -``` Cpp -#include= 0 && n >= 0) - { - // put the next greater element in the next free position in `X[]` from the end - if (X[m] > Y[n]) { - X[k--] = X[m--]; - } - else { - X[k--] = Y[n--]; - } - } - - // copy the remaining elements of `Y[]` (if any) to `X[]` - while (n >= 0) { - X[k--] = Y[n--]; - } - - // fill `Y[]` with all zeroes - for (int i = 0; i < n; i++) { - Y[i] = 0; - } -} - -// The function moves non-empty elements in `X[]` in the -// beginning and then merge them with `Y[]` -void rearrange(int X[], int Y[], int m, int n) -{ - // return if `X` is empty - if (m == 0) { - return; - } - - // moves non-empty elements of `X[]` at the beginning - int k = 0; - for (int i = 0; i < m; i++) - { - if (X[i] != 0) { - X[k++] = X[i]; - } - } - - // merge `X[0 … k-1]` and `Y[0 … n-1]` into `X[0 … m-1]` - merge(X, Y, k - 1, n - 1); -} - -int main() -{ - // vacant cells in `X[]` is represented by 0 - int X[] = { 0, 2, 0, 3, 0, 5, 6, 0, 0 }; - int Y[] = { 1, 8, 9, 10, 15 }; - - int m = sizeof(X) / sizeof(X[0]); - int n = sizeof(Y) / sizeof(Y[0]); - - /* Validate input before calling `rearrange()` - 1. Both arrays `X[]` and `Y[]` should be sorted (ignore 0's in `X[]`) - 2. Size of array `X[]` >= size of array `Y[]` (i.e., `m >= n`) - 3. Total number of vacant cells in array `X[]` = size of array `Y[]` */ - - // merge `Y[]` into `X[]` - rearrange(X, Y, m, n); - - // print merged array - for (int i = 0; i < m; i++) { - printf("%d ", X[i]); - } - - return 0; -} -``` - -## Output: - -1 2 3 5 6 8 9 10 15 - -## Time Complexity -Time complexity of the above solution is O(m + n) and runs in constant space. Here, m and n are the size of the first and second array, respectively.