├── E-Extra ├── README.md ├── turtle.cpp ├── Design.cpp └── Projectile.cpp ├── S-STL ├── README.md ├── A-Algorithm │ └── CompareFunctionUsingInBuiltSort.cpp └── C-Containers │ ├── V-Vector │ ├── Vector-Begin.cpp │ ├── README.md │ └── Vector_Iterator.cpp │ ├── S-Set │ └── Sets.cpp │ ├── L-List │ └── Lists.cpp │ └── M-Multiset │ └── MultiSetSTL.cpp ├── contributors.md ├── P-PriorityQueue ├── README.md ├── PriorityQueue.cpp └── PriorityQueueSTLComparator.cpp ├── S-StringAlgorithms ├── README.md └── KMP │ └── kmp.cpp ├── _config.yml ├── P-Problem Statements & Solution ├── README.md ├── 1-Level 1 │ ├── LowercaseToUppercase.cpp │ ├── CountingFrequencies.cpp │ ├── README.md │ └── 24hrTo12hrFormat.cpp └── 2-Level 2 │ └── AggressiveCows.cpp ├── S-Strings ├── StringSorting ├── StringReverse.cpp ├── StringSorting.cpp ├── StringComparison.cpp ├── StringToknizer.cpp ├── CountCharOccurrence.cpp ├── StringPalindrome │ └── StringPalindrome.cpp └── Strings.cpp ├── S-SortingAlgorithms ├── T-TopologicalSorting │ ├── README.md │ └── TopologicalSortBFS.cpp ├── SelectionSort.cpp ├── InsertionSort.cpp ├── BubbleSort.cpp ├── DutchNationalFlagSort.cpp ├── CountingSort.cpp └── QuickSort.cpp ├── Q-Queue ├── QueueSTL.cpp ├── QueueUsingArray.cpp └── QueueUsingStacks.cpp ├── R-Recursion ├── Types of Recursion │ ├── TailRecursion.cpp │ ├── HeadRecursion.cpp │ ├── TreeRecursion.cpp │ ├── DirectRecursion.cpp │ ├── IndirectRecursion.cpp │ └── LinearRecursion.cpp ├── PowerOfTwo.cpp ├── TowerofHanoi.cpp ├── PowerOfThree.cpp ├── TaylorsSerieHornersRule.cpp ├── RecursiveGCDandLCM.cpp ├── FibonacciNumber.cpp ├── Sum of subsets ├── ReplacePi.cpp ├── SubsequenceKSUM.cpp └── InversionCount.cpp ├── S-Stack ├── StacksSTL.cpp ├── RedundantParenthesis │ └── RedudantParenthesis.cpp ├── DecimalToBinary.cpp ├── SortStack.cpp ├── Bracket Balancing Using Stack │ ├── README.md │ └── Bracket_Balancing_using_Stack.cpp ├── TheCelebrityProblem │ └── CelebrityProblem.cpp ├── NextGreaterElement │ ├── README.md │ └── nge.cpp └── ReverseStack.cpp ├── O-OOPS ├── B-Binding │ ├── LateBinding.cpp │ ├── EarlyBinding.cpp │ └── README.md └── I-Inheritance │ └── Hybrid-Inheritance.cpp ├── .github ├── workflows │ ├── Auto_Issue_Closer.yml │ ├── greetings.yml │ └── contributors.yml ├── keylabeler.yml └── ISSUE_TEMPLATE │ └── issue-form.yml ├── A-AdvancedDataStructures └── README.md ├── M-MathematicalAlgorithms ├── EulidGreatestCommonDivisor.cpp ├── ArmstrongNumber.cpp ├── BisectionMethod.cpp ├── primeSum.cpp └── JugglerSequence │ └── JugglerSequence.cpp ├── B-BitManipulation ├── Swapping 2 Numbers │ ├── readme.md │ └── swapping.cpp ├── Count_set_Bits.cpp ├── MaximizeExpression.cpp └── SubsetsGeneration.cpp ├── T-Template ├── ClassTemplate.cpp └── FunctionTemplate.cpp ├── S-SearchingAlgorithms ├── SimpleLinearSearch.cpp ├── BinarySearch.cpp └── SearchElementRotatedSortedArray.cpp ├── A-Array ├── SortingInWaveForm.cpp ├── MissingAndRepeatingNumber.cpp ├── MajorityElement.cpp ├── PrefixSum.cpp ├── WavePrintOfMatrix.cpp ├── CountingDivisibleSubstrings.cpp ├── AntispiralMatrix.cpp ├── SymmetricMatrix.cpp ├── TraceAndNormal.cpp ├── FirstNegativeInEveryWindow.cpp └── Stock Buy And Sell.cpp ├── Miscellaneous ├── F-Friend │ └── FriendFunction.cpp ├── Lambda_Functions.cpp └── Exception_Handling.cpp ├── D-DynamicProgramming ├── Kadane's Algorithm │ └── Kadane's Algorithm.cpp ├── CountOfSubsetsWithGivenSum.cpp ├── MinCostClimbingStairs.cpp ├── ClimbingStairs.cpp ├── EggDroppingPuzzle.cpp ├── LongestCommonSubsequence.cpp ├── TravelingSalesPerson.cpp ├── TrappingRainWater.cpp ├── MinimumInsertionDeletion.cpp ├── RodCutting.cpp ├── UniquePaths.cpp ├── Minimum_insertions_form_palindrome.cpp ├── Equal_Sum_Partition.cpp ├── CoinChange.cpp └── KnapsackwithDuplicateItems.cpp ├── G-GreedyAlgorithms ├── BusyManProblem.cpp ├── BuyMaximumStocksiStocksBoughtIthDay.cpp ├── FractionalKnapsack.cpp ├── OptimalMergePattern.cpp └── JobSequencing_with_Deadlines.cpp ├── L-LinkedList ├── S-SinglyLinkedList │ ├── README_Reverse_Linked_List.md │ ├── ReverseLinkedList.cpp │ ├── middleElementOfLinkedList.cpp │ └── DetectCycleInLinkedList.cpp ├── Clone a List with Random pointers │ └── README.md ├── Merge K Sorted LinkedList │ └── README.md └── D-DoublyLinkedList │ └── DoublyLinkedListOperations.cpp ├── S-Sets ├── FindKthDistinctCharacterGivenString.cpp ├── Cartesian_Product.cpp ├── SetUnion.cpp └── IntersectionSets.cpp ├── G-Graphs ├── I-Implementation │ ├── AdjacencyList.cpp │ ├── AdjListUsingHashmap.cpp │ └── AdjacencyMatrix.cpp ├── N-NetworkFlow │ └── README.md ├── T-TraversalInGraphs │ ├── BreadthFirstSearch.cpp │ └── DepthFirstSearch.cpp ├── README.md ├── ArticulationPoints.cpp ├── GraphColoring.cpp └── M-MinimumSpanningTree │ └── Kruskal.cpp ├── G-GraphAlgorithms ├── S-SingleSourceShortestPath │ └── floyd_warshall.cpp └── MultistageGraphShortestPath.cpp ├── LICENSE.md ├── B-Backtracking ├── SubsetSum.cpp ├── TheKnight’stourproblem.cpp └── RatInMaze.cpp ├── D-DivideAndConquerAlgorithms └── Pow.cpp ├── T-Tree ├── B-BinarySearchTree │ ├── Check Valid BST │ │ ├── checkValidBST.cpp │ │ └── README.md │ ├── Ceil Value in BST │ │ └── readme.md │ └── Floor Value in BST │ │ └── Readme.md ├── G-GenricTree │ ├── LevelOrderTraversalOfaGenricTree.cpp │ └── GenricTree.cpp ├── B-BinaryTree │ └── Height_of_Tree.cpp └── F-FenwickTree │ └── K_Query.cpp ├── H-HashMap ├── Set&Unordered_Set │ ├── set.cpp │ ├── unordered_set.cpp │ └── readme.md ├── Multimap.cpp ├── HashMaps.cpp ├── Map.cpp └── UnorderedMaps-CustomHashmaps-OperatorOverloading.cpp └── H-Heap ├── klargest.cpp ├── MinCostRopes.cpp ├── HeapSort.cpp └── Heapify.cpp /E-Extra/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /S-STL/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /contributors.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /P-PriorityQueue/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /S-StringAlgorithms/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /P-Problem Statements & Solution/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /S-STL/A-Algorithm/CompareFunctionUsingInBuiltSort.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /S-Strings/StringSorting: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lakhankumawat/LearnCPP/HEAD/S-Strings/StringSorting -------------------------------------------------------------------------------- /E-Extra/turtle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main_program{ 4 | turtleSim(); 5 | cout<< "How many times?"; 6 | int i; 7 | int j=1; 8 | cin>> i; 9 | repeat(i){ 10 | forward(2);right(2*j); 11 | j++; 12 | } 13 | wait(10); 14 | } 15 | -------------------------------------------------------------------------------- /E-Extra/Design.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main_program{ 4 | turtleSim(); 5 | left(45); 6 | forward(20); 7 | repeat(8){ 8 | repeat(56){ 9 | forward(0.1); 10 | left(4); 11 | } 12 | forward(20); 13 | 14 | } 15 | forward(50); 16 | wait(5); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /S-SortingAlgorithms/T-TopologicalSorting/README.md: -------------------------------------------------------------------------------- 1 | 2 | ### Guess the output for the topological sorting in the image given below . 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Q-Queue/QueueSTL.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | 8 | queue Q; 9 | 10 | for(int i=1;i<=5;i++) 11 | Q.push(i); 12 | 13 | while(!Q.empty()){ 14 | 15 | cout< 5 | #include 6 | using namespace std; 7 | int main(){ 8 | 9 | vector v; 10 | 11 | for(int i=0;i<5;i++) 12 | v.push_back(i+1); 13 | 14 | for(auto o= v.begin();o!=v.end();o++){ 15 | cout<<*o; 16 | } 17 | 18 | 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /R-Recursion/Types of Recursion/TailRecursion.cpp: -------------------------------------------------------------------------------- 1 | // Code Showing Tail Recursion 2 | #include 3 | using namespace std; 4 | 5 | // Recursion function 6 | void fun(int n) 7 | { 8 | if (n > 0) { 9 | cout << n << " "; 10 | 11 | // Last statement in the function 12 | fun(n - 1); 13 | } 14 | } 15 | 16 | // Driver Code 17 | int main() 18 | { 19 | int x; 20 | cout<<"Enter the value of x"; 21 | cin>>x; 22 | fun(x); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /R-Recursion/Types of Recursion/HeadRecursion.cpp: -------------------------------------------------------------------------------- 1 | // C++ program showing Head Recursion 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Recursive function 7 | void fun(int n) 8 | { 9 | if (n > 0) { 10 | 11 | // First statement in the function 12 | fun(n - 1); 13 | 14 | cout << " "<< n; 15 | } 16 | } 17 | 18 | // Driver code 19 | int main() 20 | { 21 | int x; 22 | cout<<"Enter thevalue of x"; 23 | cin>>x; 24 | fun(x); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /S-Stack/StacksSTL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | stack s; 8 | 9 | // to push an element into the stack 10 | for(int i=0;i<5;i++) 11 | s.push(i+1); 12 | 13 | // to pop an element from the stack till it becomes empty 14 | while(!s.empty()){ 15 | cout< 3 | using namespace std; 4 | 5 | class Base 6 | { 7 | public: 8 | virtual void show() { cout<<" In Base \n"; } 9 | }; 10 | 11 | class Derived: public Base 12 | { 13 | public: 14 | void show() { cout<<"In Derived \n"; } 15 | }; 16 | 17 | int main(void) 18 | { 19 | Base *bp = new Derived; 20 | cout<<"Called the derived class show function using the base class pointer"<show(); // RUN-TIME POLYMORPHISM 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /S-Strings/StringReverse.cpp: -------------------------------------------------------------------------------- 1 | //program to reverse a string using recursion in C++ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //#function to reverse a string 8 | void reverse(char *x, int begin, int end) 9 | { 10 | char c; 11 | if (begin >= end) 12 | return; 13 | c = *(x + begin); 14 | *(x + begin) = *(x + end); 15 | *(x + end) = c; 16 | reverse(x, ++begin, --end); 17 | } 18 | 19 | int main() 20 | { 21 | char a[100]; 22 | cin >> a; 23 | reverse(a, 0, strlen(a) - 1); 24 | cout << a; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /R-Recursion/Types of Recursion/TreeRecursion.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to show Tree Recursion 2 | #include 3 | using namespace std; 4 | 5 | // Recursive function 6 | void fun(int n) 7 | { 8 | if (n > 0) 9 | { 10 | cout << " " << n; 11 | 12 | // Calling once 13 | fun(n - 1); 14 | 15 | // Calling twice 16 | fun(n - 1); 17 | } 18 | } 19 | 20 | // Driver code 21 | int main() 22 | { 23 | int n; 24 | cout<<"Enter the value of n"; 25 | cin>>n; 26 | fun(n); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /.github/workflows/Auto_Issue_Closer.yml: -------------------------------------------------------------------------------- 1 | name: Auto Issue Closer on Merge 2 | 3 | on: 4 | pull_request: 5 | # Will trigger on closed PRs 6 | types: [closed] 7 | 8 | jobs: 9 | Close_Issue: 10 | 11 | runs-on: ubuntu-latest 12 | # Checks if PR is merged (subflag) 13 | if: ${{ github.event.pull_request.merged == true }} 14 | 15 | steps: 16 | - name: Closes issues related to a merged pull request. 17 | uses: ldez/gha-mjolnir@v1.0.3 18 | env: 19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 20 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | greeting: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: Suvraneel/Greeting-action@main 12 | with: 13 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 14 | issue_message: 'Hello @${{github.actor}}, thanks for creating your first issue at LearnCPP, hope you followed the guidelines.' 15 | pr-message: 'Congratulations!! for making your first PR at LearnCPP, our mentors will review it soon.' 16 | 17 | -------------------------------------------------------------------------------- /A-AdvancedDataStructures/README.md: -------------------------------------------------------------------------------- 1 | #Segment Tree 2 | ###Definition :- 3 | Segment Tree is used in cases where there are multiple range queries on array and modifications of elements of the same array. 4 | For example, finding the sum of all the elements in an array from indices L to R, or finding the minimum 5 | (famously known as Range Minumum Query problem) of all the elements in an array from indices L to R. 6 | 7 | **Time Complexity for Update** - O(log N) 8 | **Time Complexity for bulding a Segment Tree** - O(N) 9 | **Time Complexity to query** - O(log N) 10 | -------------------------------------------------------------------------------- /.github/workflows/contributors.yml: -------------------------------------------------------------------------------- 1 | name: Contribute List 2 | on: 3 | push: 4 | branches: 5 | - main 6 | workflow_dispatch: 7 | 8 | jobs: 9 | contrib-readme-job: 10 | runs-on: ubuntu-latest 11 | name: A job to automate contrib in readme 12 | steps: 13 | - name: Contribute List 14 | uses: akhilmhdh/contributors-readme-action@v2.3.3 15 | with: 16 | readme_path: "contributors.md" 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | -------------------------------------------------------------------------------- /M-MathematicalAlgorithms/EulidGreatestCommonDivisor.cpp: -------------------------------------------------------------------------------- 1 | 2 | //link for understanding this algorithm is https://youtu.be/O3WlqAH_naA 3 | //Note please visit this link for understanding Euclids Algorithm for finding Greatest commom Divisor 4 | 5 | #include 6 | using namespace std; 7 | int main(){ 8 | cout<<"Enter two numbers whose GCD you want to find (Greater First NO.):"<>m>>n; 11 | while(m%n!=0){ 12 | int nextm= n; 13 | int nextn = m%n; 14 | m=nextm; 15 | n = nextn; 16 | } 17 | cout<<"GCD is : "< 2 | using namespace std; 3 | 4 | // recursive function to calculate square of a number 5 | int square(int x) 6 | { 7 | // base case 8 | if (x == 0) 9 | { 10 | return x; 11 | } 12 | 13 | // recursive case 14 | else 15 | { 16 | return square(x-1) + (2*x) - 1; 17 | } 18 | } 19 | int main() { 20 | // implementation of square function 21 | 22 | int input; 23 | cout<<"Enter the value of input"; 24 | cin>>input; 25 | cout << input<<"^2 = "< 2 | using namespace std; 3 | 4 | //Find the minimum element in the unsorted array and swap it with element at the begining 5 | 6 | int main(){ 7 | int arr[]={34,67,12,89,32,49,88,17,44}; 8 | int n=sizeof(arr)/sizeof(int); 9 | for(int i=0;i 3 | using namespace std; 4 | 5 | void funB(int n); 6 | 7 | void funA(int n) 8 | { 9 | if (n > 0) { 10 | cout <<" "<< n; 11 | 12 | // Fun(A) is calling fun(B) 13 | funB(n - 1); 14 | } 15 | } 16 | 17 | void funB(int n) 18 | { 19 | if (n > 1) { 20 | cout <<" "<< n; 21 | 22 | // Fun(B) is calling fun(A) 23 | funA(n / 2); 24 | } 25 | } 26 | 27 | // Driver code 28 | int main() 29 | { 30 | int x; 31 | cout<<"Enter the value of x"; 32 | cin>>x; 33 | funA(x); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /S-Strings/StringSorting.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | bool comp(string s1,string s2){ 9 | if (s1.length()==s2.length()){ 10 | return s1s2.length()); 14 | } 15 | 16 | 17 | int main(){ 18 | 19 | int n; 20 | cin>>n; 21 | cin.get(); 22 | string s[n];//vector 23 | 24 | 25 | 26 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | int num, temp, r, result = 0; 6 | cout << "Enter a 3 digit number: "; 7 | cin >> num; 8 | temp = num; 9 | 10 | while (temp != 0) { 11 | // r contains the last digit 12 | r = temp % 10; 13 | 14 | result += r * r * r; 15 | 16 | // removing last digit from the temp 17 | temp /= 10; 18 | } 19 | 20 | if (result == num) 21 | cout << num << " is an Armstrong number."; 22 | else 23 | cout << num << " is not an Armstrong number."; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /S-Strings/StringComparison.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main () 5 | { 6 | // declare string variables 7 | string string1; 8 | string string2; 9 | // Taking the input of two strings 10 | cout << " Enter the String 1: " << endl; 11 | cin >> string1; 12 | cout << " Enter the String 2: " << endl; 13 | cin >> string2; 14 | 15 | //comparing the two strings and returning the value 16 | if ( string1 == string2) 17 | { 18 | cout < 13 | 14 | - A= A^B 15 | - B= A^B = (A^B)^B=A^0=A [From A=A^B] 16 | - A=A^B=(A^B)^A=B [From B=A] 17 | 18 | ### Example : 19 | Let , A=5(101) , B=7(111) 20 | 21 | - A=A^B= 5^7= (101)^(111)=010=2 22 | - B= A^B = 2^7= (010)^(111)=101=5 23 | - A= A^B=2^5=(010)^(101)=7 24 | 25 | **So, Now A=7 , B=5** 26 | 27 | -------------------------------------------------------------------------------- /E-Extra/Projectile.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Important Note : To run this program you need to download simple codeblocks application 3 | //Download link is given in README.md :) 4 | #include 5 | 6 | main_program{ 7 | 8 | initCanvas("projectile",1000,1000);//Create a canvas named projectile of size 1000X1000 9 | int start = getClick(); 10 | Circle p(start/65536,start%65536,5);//To create a circle at click position whose x coordinate is start/65536,y = start%65536,Radius 5 11 | p.penDown(); 12 | double vx=1,vy=-1,gravity=0.01; 13 | repeat(400){ 14 | p.move(vx,vy); 15 | vy+=gravity; 16 | wait(0.01);} 17 | getClick(); //Wait for user to click . After click terminates. 18 | } 19 | -------------------------------------------------------------------------------- /B-BitManipulation/Swapping 2 Numbers/swapping.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int num1 ,num2; 6 | cout<<"Enter 2 number :"<>num1>>num2; 8 | 9 | //Swapping using XOR opeartion 10 | num1=num1^num2; 11 | num2=num1^num2; 12 | // num2= num1^num2=num1^num2^num2= num1 13 | 14 | num1=num1^num2; 15 | //num1 = num1^num2= (num1^num2)^num2= num1 16 | 17 | cout<<"elements after swapping -> "<<"1st number= "< 5 | using namespace std; 6 | 7 | bool poweroftwo (int n) 8 | { 9 | if(n==1 || n==2) return true; // base case 10 | 11 | if(n % 2 == 1 || n==0) return false; // base case 12 | 13 | return poweroftwo(n/2); 14 | } 15 | 16 | int main() 17 | { 18 | int n; 19 | 20 | cout<<"Enter a number : "; 21 | cin >> n; 22 | 23 | if(poweroftwo(n)) 24 | cout<<"This number can be expressed as a power of two \n"; 25 | 26 | else 27 | cout<<"This number can't be expressed as a power of two \n"; 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /S-Strings/StringToknizer.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //char *strtokchar *s,char *delimiters 7 | //returns a token on each subsequent call 8 | //on the first call function pass the string argument for 's' 9 | //on subsequent pass string argument as null 10 | 11 | int main(){ 12 | 13 | char s[100]="Today is a preety day"; 14 | 15 | char *ptr=strtok(s," "); 16 | cout< 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | 8 | /* priority Queue are included in queue header file */ 9 | 10 | /*priority_queue pq; */ //max priority queue - Print in descending order 11 | priority_queue,greater > pq; //min priority queue -ascending order 12 | int n,no; 13 | cin>>n; 14 | 15 | 16 | for(int i=1;i<=n;i++) 17 | pq.push(i); //O(logn) to insert an element in pq 18 | 19 | 20 | //Higher no has high priority over here 21 | while(!pq.empty()){ 22 | cout< 5 | using namespace std; 6 | 7 | 8 | void TOH(int n,char src,char helper,char dest){ 9 | if(n==0){//no disks left 10 | return; 11 | } 12 | 13 | TOH(n-1,src,dest,helper); 14 | cout<<"Disk "<>n;//total disks 29 | TOH(n,'A','B','C'); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /R-Recursion/PowerOfThree.cpp: -------------------------------------------------------------------------------- 1 | /* Time Complexity : O(N) 2 | Space Complexity : O(N) */ 3 | 4 | #include 5 | using namespace std; 6 | 7 | bool powerthree(int n) 8 | { 9 | if(n==1 || n==3) return true; // base case 10 | 11 | if(n % 3 !=0 || n==0) return false; // base case 12 | 13 | return powerthree(n/3); //recursive call n/3 times 14 | } 15 | 16 | int main() 17 | { 18 | int n; 19 | 20 | cout<<"Enter a number : "; 21 | cin>>n; 22 | 23 | if(powerthree(n)) //function call to find the solution 24 | cout<<"Number can be represented as power of 3\n"; 25 | 26 | else 27 | cout<<"Number can't be represented as power of 3\n"; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /P-Problem Statements & Solution/1-Level 1/LowercaseToUppercase.cpp: -------------------------------------------------------------------------------- 1 | // Question:- A string given lowercase and you have to convert it into upperase 2 | // Input String only conatins lowercase alphabetical letters. 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | string lowercase; // Declaring string 11 | cin>>lowercase; // taking input 12 | 13 | for(int i=0;i 3 | using namespace std; 4 | 5 | template 6 | class myclass { 7 | T a, b; 8 | public: 9 | myclass (T first, T second) 10 | {a=first; b=second;} 11 | T getMaxval (); 12 | }; 13 | template 14 | T myclass::getMaxval () 15 | { 16 | return (a>b? a : b); 17 | } 18 | int main () { 19 | myclass myobject (100, 75); //object which takes integer in the constructor 20 | cout<<"Maximum of 100 and 75 = "< mychobject('A','a'); //object which takes integer in the constructor 23 | cout<<"Maximum of 'A' and 'a' = "<Vectors in C++ 3 | 4 | - Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. 5 | - Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. 6 | - In vectors, data is inserted at the end. 7 | - Inserting at the end takes differential time, as sometimes there may be a need of extending the array. 8 | - Removing the last element takes only constant time because no resizing happens. 9 | - Inserting and erasing at the beginning or in the middle is linear in time. 10 | -------------------------------------------------------------------------------- /S-SortingAlgorithms/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // code needs to be improved 2 | // it should be implemented when a user can input the array of any input size n. 3 | 4 | #include 5 | using namespace std; 6 | 7 | //Repeatedly swap two adjacent elements if they are in wrong order. 8 | 9 | int main(){ 10 | int arr[]={9,4,6,2,45,23,90,7}; 11 | int n=sizeof(arr)/sizeof(int); 12 | int counter=1; 13 | while(counterarr[i+1]){ 16 | swap(arr[i],arr[i+1]); 17 | } 18 | } 19 | counter++; 20 | } 21 | //Printing the sorted array. 22 | cout<<"Sorted Array: "; 23 | for(int i=0;i 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | int arr[]={10,20,40,70,100}; 8 | int n=sizeof(arr)/sizeof(int); 9 | 10 | cout<>key; 15 | //It will return address of searched element so auto instead of int 16 | auto it = find(arr,arr+n,key); //Find function is present in algorithm headerfile 17 | 18 | //Final add to it - address[0] i.e arr 19 | int index=it-arr; 20 | 21 | //if element is not in index it will return end element of array index +1 22 | if (index==5) 23 | cout<<"Element not present"; 24 | else 25 | cout<<"Element is at index"< 2 | using namespace std; 3 | 4 | // Taylor Series by horner rule using recursion 5 | double taylorHornerRec(int x, int n) 6 | { 7 | static double s = 1; 8 | if (n == 0) 9 | { 10 | return s; 11 | } 12 | else 13 | { 14 | s = (1 + (x / n)) * s; 15 | return taylorHornerRec(x, n - 1); // Calling the function recursively 16 | } 17 | } 18 | 19 | // Driver Code 20 | int main() 21 | { 22 | // Declaring the int variable 23 | int x; 24 | int n; 25 | // Taking the input from user 26 | cout << "Enter the value of x"; 27 | cin >> x; 28 | 29 | cout << "Enter the value of n"; 30 | cin >> n; 31 | // calling the function and printing the result 32 | cout << taylorHornerRec(x, n) << endl; 33 | } 34 | -------------------------------------------------------------------------------- /A-Array/SortingInWaveForm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Function to swap two numbers. 6 | void swap(int *x, int *y) 7 | { 8 | int temp = *x; 9 | *x = *y; 10 | *y = temp; 11 | } 12 | 13 | // This function sorts arr[0..n-1] in wave form 14 | void sortInWave(int arr[], int n) 15 | { 16 | // Sort the input array 17 | sort(arr, arr+n); 18 | 19 | // Swap adjacent elements 20 | for (int i=0; i>n; 29 | 30 | int arr[n]; 31 | for(int i=0;i>arr[i]; 33 | 34 | sortInWave(arr, n); 35 | 36 | for (int i=0; i 5 | using namespace std; 6 | #include 7 | //method 1 : slow approach 8 | int countSetBit(unsigned int n){ 9 | int ans=0; 10 | while (n>0) 11 | { 12 | ans+=(n&1); 13 | n=n>>1; 14 | } 15 | return ans; 16 | } 17 | //method 2 : fast approach 18 | int countSetBitFast(unsigned int n){ 19 | int ans=0; 20 | while(n>0){ 21 | n=n&(n-1); 22 | ans++; 23 | } 24 | return ans; 25 | } 26 | 27 | int main(){ 28 | 29 | unsigned int n = 15;//1111 30 | cout< 3 | using namespace std; 4 | 5 | // Finding missing and repeating element 6 | void printTwoElements(int arr[], int size) 7 | { 8 | int i; 9 | // Repeating element 10 | printf("\n The repeating element is"); 11 | 12 | for (i = 0; i < size; i++) { 13 | if (arr[abs(arr[i]) - 1] > 0) 14 | arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; 15 | else 16 | printf(" %d ", abs(arr[i])); 17 | } 18 | // Missing element 19 | printf("\nand the missing element is "); 20 | for (i = 0; i < size; i++) { 21 | if (arr[i] > 0) 22 | printf("%d", i + 1); 23 | } 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | int n; 30 | cin>>n; 31 | int arr[n]; 32 | for (int i = 0; i < n; i++) 33 | { 34 | cin>>arr[i]; 35 | } 36 | printTwoElements(arr, n); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /S-SortingAlgorithms/DutchNationalFlagSort.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Read more : https://www.educative.io/edpresso/the-dutch-national-flag-problem-in-cpp 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main(){ 8 | int arr[]={2,1,0,0,2,1,2,0,1,1,0,2,0,2}; 9 | int n=sizeof(arr)/sizeof(int); 10 | 11 | int low=0; 12 | int mid=0; 13 | int high=n-1; 14 | 15 | while(mid<=high){ 16 | if(arr[mid]==0){ 17 | swap(arr[low],arr[mid]); 18 | low++; 19 | mid++; 20 | } 21 | else if(arr[mid]==1){ 22 | mid++; 23 | } 24 | else{ 25 | swap(arr[mid],arr[high]); 26 | high--; 27 | } 28 | } 29 | 30 | //Printing the array 31 | cout<<"Sorted Array: "; 32 | for(int i=0;i 8 | using namespace std; 9 | 10 | class Base 11 | { 12 | public: 13 | void show() { cout<<" In Base \n"; } 14 | }; 15 | 16 | class Derived: public Base 17 | { 18 | public: 19 | void show() { cout<<"In Derived \n"; } 20 | }; 21 | 22 | int main(void) 23 | { 24 | Base *bp = new Derived; 25 | 26 | // The function call decided at 27 | // compile time (compiler sees type 28 | // of pointer and calls base class 29 | // function.) 30 | cout<<"Trying to call the derived class show function using the base class pointer"<show(); 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Miscellaneous/F-Friend/FriendFunction.cpp: -------------------------------------------------------------------------------- 1 | // 2 | #include 3 | using namespace std; 4 | class P 5 | { 6 | private: 7 | int memebervariable; 8 | friend void ChangePrivate(P &); //not a member of class P and can be declared in either p 9 | 10 | public: 11 | P(int n) : memebervariable(n) {} 12 | void PrintPrivate(void) { cout << memebervariable << endl; } 13 | 14 | 15 | }; 16 | 17 | void ChangePrivate(P &i) { i.memebervariable++; } //it has access to 18 | 19 | int main() 20 | { 21 | int n; 22 | cout<<"Enter any integer value to be assigned to private member variable of class P: "; 23 | cin>>n; 24 | P p(n); 25 | cout<<"Initially: "; 26 | p.PrintPrivate(); 27 | cout<<"calling the friend function to increment the private member variable value"< 3 | using namespace std; 4 | 5 | void largestSum (int Arr[], int n) 6 | { 7 | int max_sum = Arr[0]; 8 | int curr_sum = 0; 9 | for (int i=0;i= max_sum) 13 | { 14 | max_sum = curr_sum; 15 | } 16 | if(curr_sum < 0 ) 17 | { 18 | curr_sum = 0; 19 | } 20 | } 21 | cout<>n; 30 | cout<<"\nEnter array elements :\n"; 31 | for (int i=0;i>A[i]; 34 | } 35 | cout<<"\nLargest Sum of subarray of A is :"; 36 | largestSum(A,n); 37 | return 0; 38 | } 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /P-Problem Statements & Solution/1-Level 1/CountingFrequencies.cpp: -------------------------------------------------------------------------------- 1 | // The problem is to count frequencies of all elements in an array in O(n) time complexity 2 | 3 | #include 4 | using namespace std; 5 | 6 | void countFreq(int arr[], int n) 7 | { 8 | unordered_map mp; 9 | 10 | // Traverse through array elements and 11 | // count frequencies 12 | for (int i = 0; i < n; i++) 13 | mp[arr[i]]++; 14 | 15 | // Traverse through map and print frequencies 16 | for (auto x : mp) 17 | cout << x.first << " " << x.second << endl; 18 | } 19 | // driver code 20 | int main() 21 | { 22 | int n; 23 | cout<<"Enter the number of Elements in an array = "; 24 | cin >> n; 25 | int arr[n+1]; 26 | //Inserting an array 1 2 2 4 5 4 27 | for(int i =0;i> arr[i]; 29 | } 30 | countFreq(arr, n); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /S-STL/C-Containers/S-Set/Sets.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | /*------Some Properties of set--------- 8 | 1. duplicate values are not there i.e unique data items 9 | 2. it can be of type order or unordered 10 | 3. Updation of values is not possible ,we can remove a particular value and can insert a new 11 | one on its place but direct updation is not possible. 12 | */ 13 | 14 | int main(){ 15 | set s; 16 | 17 | int arr[]={10,20,11,9,32,10,11}; 18 | int n =sizeof(arr)/sizeof(int); 19 | 20 | for(int i=0;i::iterator it=s.begin();it!=s.end();it++) 31 | cout<<(*it)<<" "; 32 | 33 | 34 | 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /R-Recursion/RecursiveGCDandLCM.cpp: -------------------------------------------------------------------------------- 1 | /*--------------------The program for calculating GCD and LCM by using the recursive method-------------------------*/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | /*-------------Recursive method for the calculation of GCD----------------------------*/ 7 | int calculateGCD(int a, int b){ 8 | if(a == 0) 9 | return b; 10 | if(b == 0) 11 | return a; 12 | return calculateGCD(b, a % b); 13 | } 14 | 15 | int calculateLCM(int a, int b){ 16 | return ((a * b) / calculateGCD(a, b)); 17 | } 18 | 19 | 20 | int main(){ 21 | int a, b; 22 | 23 | /*------------Taking the inputs from the user --------------------*/ 24 | cout << "Enter the two numbers : " << endl; 25 | cin >> a >> b; 26 | 27 | /*------------Calling the methods and printing their results-----------------*/ 28 | cout << "The GCD of two numbers is : " << calculateGCD(a, b) << endl; 29 | cout << "The LCM of two numbers is : " << calculateLCM(a, b) << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /A-Array/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void findMajority(int arr[], int n) 5 | { 6 | int maxCount = 0; 7 | int index = -1; 8 | for (int i = 0; i < n; i++) { 9 | int count = 0; 10 | for (int j = 0; j < n; j++) { 11 | if (arr[i] == arr[j]) 12 | count++; 13 | } 14 | 15 | // update maxCount if count of 16 | // current element is greater 17 | if (count > maxCount) { 18 | maxCount = count; 19 | index = i; 20 | } 21 | } 22 | 23 | // if maxCount is greater than n/2 24 | // return the corresponding element 25 | if (maxCount > n / 2) 26 | cout << arr[index] << endl; 27 | 28 | else 29 | cout << "No Majority Element" << endl; 30 | } 31 | 32 | // Driver code 33 | int main() 34 | { 35 | 36 | int n; 37 | cin>>n; 38 | 39 | int arr[n]; 40 | for(int i=0;i>arr[i]; 42 | 43 | findMajority(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /G-GreedyAlgorithms/BusyManProblem.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | //------------------------------------PROBLEM : 👨‍💼BusyManProblem ---------------------------------- 4 | #include 5 | using namespace std; 6 | #include 7 | #include 8 | 9 | bool compare(pair p1,pair p2){ 10 | return p1.second> p; 16 | cin>>t; 17 | while(t--){ 18 | cin>>no; 19 | for(int i=0;i>s>>e; 21 | p.push_back(make_pair(s,e)); 22 | } 23 | sort(p.begin(),p.end(),compare); //Sorting the jobs on the basis of their end times 24 | 25 | int res=1; 26 | int fin=p[0].second; //take the first job and sort remaining 27 | 28 | for(int i=1;i=fin){ 30 | fin=p[i].second; 31 | res++; 32 | } 33 | } 34 | cout<2->3->4->NULL 6 | Output: Linked list should be changed to, 7 | 4->3->2->1->NULL 8 | ### To reverse a linked list, do the following. 9 | 1. Initialize three pointers prev as NULL, curr as head and next as NULL 10 | 2. Iterate through the linked list. In loop, do following, 11 | 12 | 13 | 14 | next = curr->next 15 | 16 | 17 | 18 | curr->next = prev 19 | 20 | 21 | 22 | prev = curr 23 | 24 | 25 | 26 | curr = next 27 | ## Time Complexity and Space Complexity 28 | 1.Time Complexity: O(n) 29 | 2.Space Complexity: O(1) 30 | 31 | ## Image for Reference 32 | ![image](https://user-images.githubusercontent.com/74498344/158961580-61a95b47-fa77-4547-bfe1-7288fb8aa88b.png) 33 | 34 | -------------------------------------------------------------------------------- /R-Recursion/FibonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | /* FIBONACCI NUMBER PROGRAM 2 | TIME COMPLEXITY : O(N) 3 | SPACE COMPLEXITY : O(N) Here, N is recursion stack space. 4 | 5 | Link to the article for reference : https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ */ 6 | 7 | 8 | #include 9 | using namespace std; 10 | 11 | // Function to calculate nth fibonacci number 12 | int fibonacci(int n) 13 | { if(n==0) // base case 14 | return 0; 15 | 16 | if(n==1) // base case 17 | return 1; 18 | 19 | return ( fibonacci(n-1)+fibonacci(n-2) ); 20 | } 21 | 22 | int main() 23 | { 24 | /* Fibonacci sequence : 0,1,1,2,3,5,8,13 .... 25 | it means that 0 and 1 (first two numbers) remains same and nth number is obtained by addition of previous two numbers. */ 26 | 27 | int n; 28 | cout<<"Enter a number : "; 29 | cin>>n; 30 | 31 | int ans=fibonacci(n); // function call 32 | 33 | cout<<"FIBONACCI NO : "<> n; 23 | int a[n]; 24 | cout << "Enter the values" << endl; 25 | for(i=0;i>a[i]; 27 | cout << "Enter the value of sum" << endl; 28 | cin >> sum; 29 | bool f = false; 30 | S.subsetSum_Recursive(a, n, sum); 31 | if (f) 32 | cout << "subset with the given sum found" << endl; 33 | else 34 | cout << "no required subset found" << endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /A-Array/PrefixSum.cpp: -------------------------------------------------------------------------------- 1 | /* Given an array of N integers. Given Q queries and in each query given L and R print sum of array elements from index L to R (both inclusive) 2 | Constraints 3 | 1<=N<=10^5 4 | 1<=arr[i]<=10^9 5 | 1<=Q<=10^5 6 | 1<=L,R<=N 7 | */ 8 | #include 9 | using namespace std; 10 | 11 | const int N=1e5+10; 12 | int arr[N]; 13 | int prefix[N]; 14 | 15 | int main() 16 | { 17 | int n; 18 | cin>>n; 19 | 20 | for (int i = 1; i <=n; i++) // Using 1-based indexing 21 | { 22 | cin>>arr[i]; 23 | } 24 | 25 | int q; 26 | cin>> q; 27 | 28 | for (int i = 1; i <=n; i++) 29 | { 30 | prefix[i]=prefix[i-1]+arr[i]; // prefix[i] stores the sum of numbers from 1 to i 31 | } 32 | 33 | while(q--){ 34 | int l,r; 35 | cin>>l>>r; 36 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | // https://www.geeksforgeeks.org/find-kth-distinct-character-from-start-of-given-given-string/ 6 | 7 | // Function for printing the Kth distinct character using sets 8 | int printKthDistinct(string& str, int& k) 9 | { 10 | //Declaring a set named uniqueEle 11 | set uniqueEle; 12 | int n = str.length(); 13 | //Traversing the given string and finding the kth unique/ distinct element 14 | for (int i = 0; i < n; i++) { 15 | uniqueEle.insert(str[i]); 16 | if (uniqueEle.size() == k) 17 | return str[i]; 18 | } 19 | return -1; 20 | } 21 | 22 | int main() 23 | { 24 | //taking the input from the user 25 | string str; 26 | cout<<"Enter the string: "; 27 | getline(cin, str); 28 | int k; 29 | cout<>k; 31 | int ans = printKthDistinct(str, k); 32 | if (ans == -1) 33 | cout << -1; 34 | else 35 | cout << (char)ans; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /G-Graphs/I-Implementation/AdjacencyList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | class Graph{ 6 | //Graph of type having total vertex and a list of adj. list 7 | int V; 8 | list *l; 9 | public: 10 | Graph(int V){ 11 | this->V=V; 12 | l=new list[V]; 13 | } 14 | 15 | void add_edge(int x,int y){ 16 | //Push that edge in both nodes places 17 | 18 | l[x].push_back(y); 19 | l[y].push_back(x); 20 | } 21 | 22 | void print_graph(){ 23 | //Iterate over the vertices and print list is a good idea 24 | 25 | for (int i = 0; i < V; i++) 26 | { 27 | /* code */ 28 | cout<<"Vertices : "<"; 29 | for(auto nbr:l[i]){ 30 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int set1[100],set2[100],n,m,i,j; 7 | 8 | //Initialize Set 1 9 | 10 | cout<<"Enter the number of elements in Set 1 : "; 11 | cin>>n; 12 | cout<<"Enter the elements of Set 1 : "; 13 | for(i=0;i>set1[i]; 16 | } 17 | 18 | //Initialize set 2 19 | 20 | cout<<"Enter the number of elements in Set 2 :"; 21 | cin>>m; 22 | cout<<"Enter the elements of Set 2: "; 23 | for(i=0;i>set2[i]; 26 | } 27 | 28 | //Finding the cartesian Product of two set 29 | /* Example of cartesian product : 30 | set 1= {1,2,3} 31 | set 2 ={4,5} 32 | cartesian product = {{1,4},{1,5},{2,4}{2,5},{3,4},{3,5}} */ 33 | 34 | cout<<"The cartesian product of two set is : "< 3 | #include 4 | #define INT_MAX 10000 5 | using namespace std; 6 | 7 | 8 | vector > floyd_warshall(vector> graph){ 9 | 10 | 11 | vector> dist(graph); 12 | 13 | int v=graph.size();//vertices in the graph 14 | for(int k=0;k dist[i][k]+dist[k][j]){ 18 | dist[i][j]=dist[i][k]+dist[k][j]; 19 | } 20 | } 21 | } 22 | } 23 | return dist; 24 | } 25 | 26 | 27 | int main(){ 28 | 29 | //4 vertices (4x4 matrix basically) 30 | vector > graph={ 31 | {0,3,INT_MAX,7}, 32 | {8,0,3,INT_MAX}, 33 | {5,INT_MAX,0,1}, 34 | {2,INT_MAX,INT_MAX,0} 35 | }; 36 | 37 | 38 | auto result = floyd_warshall(graph); 39 | for(int i=0;i 2 | using namespace std; 3 | int count_of_subsets(int arr[], int n, int sum){ 4 | //declaring the matrix 5 | int t[n+1][sum+1]; 6 | //Initializing the first row and column of the matrix 7 | for(int i = 0; i<=n; i++){ 8 | for(int j = 0; j<=sum; j++){ 9 | if(i==0){ 10 | t[i][j] = 0; 11 | } 12 | if(j==0){ 13 | t[i][j] = 1; 14 | } 15 | } 16 | } 17 | // Filling other rows and columns 18 | for(int i = 1; i<=n; i++){ 19 | for(int j = 1; j<=sum; j++){ 20 | //if value is less than the sum 21 | if(arr[i-1]<=j){ 22 | t[i][j] = t[i-1][j] + t[i-1][j-arr[i-1]]; 23 | } 24 | else{ 25 | t[i][j] = t[i-1][j]; 26 | } 27 | } 28 | } 29 | return t[n][sum]; //returning the result 30 | 31 | } 32 | 33 | int main(){ 34 | int n = 6; 35 | int a[] = {2,3,5,6,8,10}; 36 | int sum = 10; 37 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | int arr[]={10,20,40,40,40,70,100,130,560}; 8 | int n=sizeof(arr)/sizeof(int); 9 | 10 | cout<>key; 15 | 16 | bool present = binary_search(arr,arr+n,key); 17 | if(present) 18 | cout<<"Present"<=key i.e >=40 index 2 28 | auto l =lower_bound(arr,arr+n,40); 29 | cout<<"Lower Bound of 40 is : "<40 index 5 33 | auto it =upper_bound(arr,arr+n,40); 34 | cout<<"Upper Bound of 40 is : "< 2 | using namespace std; 3 | //https://www.geeksforgeeks.org/maximize-the-expression-bit-manipulation/ 4 | #define MAX 32 5 | 6 | // Function to return the value of the maximized expression 7 | int maximizingTheExpression(int x, int y) 8 | { 9 | int ans = x; 10 | 11 | // int can have 32 bits 12 | for (int bit = MAX - 1; bit >= 0; bit--) { 13 | 14 | // Considering the ith bit of W to be 1 15 | int bitOfW = 1 << bit; 16 | 17 | // Calculating the value of (y AND bitOfW) 18 | int a = y & bitOfW; 19 | 20 | // Checking if bitOfD satisfies (y AND W = W) 21 | if (a == bitOfW) { 22 | 23 | // Checking if bitOfD can maximize (x ^ W) 24 | int b = ans & bitOfW; 25 | if (b == 0) { 26 | ans = ans ^ bitOfW; 27 | } 28 | } 29 | } 30 | 31 | return ans; 32 | } 33 | 34 | 35 | int main() 36 | { 37 | int x, y; 38 | cout<<"Enter the value of x and y "; 39 | cin>>x>>y; 40 | 41 | cout << maximizingTheExpression(x,y); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /Miscellaneous/Lambda_Functions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define ll long long int 6 | 7 | int main() 8 | { 9 | ios_base::sync_with_stdio(false); 10 | cout.tie(0); 11 | cin.tie(0); 12 | 13 | // Empty lambda function 14 | []() 15 | { 16 | cout << "This is the first Lambda function \n"; 17 | }(); 18 | 19 | // Capturing the variables and passing it at the end of function only 20 | [](int a, int b) 21 | { 22 | cout << abs(a - b) << endl; 23 | }(10, 30); 24 | 25 | // Defining the return type by -> return type 26 | int a = [](int a, int b) -> int 27 | { 28 | return a + b; 29 | }(20, 34); 30 | cout << a << "\n"; 31 | 32 | int x = 10; 33 | int y = 40; 34 | float z = 4.5; 35 | 36 | // Capturing the variables as capture by reference. 37 | [&x, &y, &z]() 38 | { 39 | cout << y - x + z; 40 | }(); 41 | 42 | // Shortcut to capture all variables as capture by reference 43 | [&]() 44 | { 45 | cout << "\n" 46 | << y - x + z; 47 | }(); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 LakhanKumawat ᵖ⁺ 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /G-Graphs/I-Implementation/AdjListUsingHashmap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Graph{ 8 | //Graph of type having total vertex and a list of adj. list 9 | unordered_map>> m; 10 | 11 | public: 12 | void addEdge(string x,string y,bool bidir,int wt){ 13 | 14 | m[x].push_back(make_pair(y,wt)); 15 | if(bidir==true){ 16 | m[y].push_back(make_pair(x,wt)); 17 | } 18 | } 19 | 20 | void printGraph(){ 21 | for(auto c:m){ 22 | string src=c.first; 23 | cout<<"from "<> nbr=c.second; 25 | for(auto s:nbr){ 26 | cout< 2 | using namespace std; 3 | class vehicle //vehicle class (base class) created 4 | { 5 | public: 6 | vehicle() //constructor of vehicle class 7 | { 8 | cout<< "This is a vehicle\n"; 9 | } 10 | }; 11 | class Car: public vehicle //class Car(derived from vehicle/base class via Single Inheritance) created 12 | { 13 | public: 14 | Car() //constructor of car class 15 | { 16 | cout<< "This is a car\n"; 17 | } 18 | }; 19 | class Racing //Racing class created 20 | { 21 | public: 22 | Racing() //constructor of racing class 23 | { 24 | cout<< "This is for Racing\n"; 25 | } 26 | }; 27 | class Ferrari: public Car, public Racing //Ferrari class (derived from both Car and Racing class via Multiple Inheritance) created 28 | { 29 | public: 30 | Ferrari() //constructor of ferrari class 31 | { 32 | cout<< "Ferrari is a Racing Car\n"; 33 | } 34 | 35 | }; 36 | int main() { 37 | Ferrari f; //Object of class Ferrari class will call the constructors of all parent classes and their parent classes as well. 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /G-Graphs/N-NetworkFlow/README.md: -------------------------------------------------------------------------------- 1 | # Network Flow 2 | 3 | ## Ford Fulkerson 4 | 5 | ![PsuedoCode](https://user-images.githubusercontent.com/55774240/134647454-23023cac-841a-485f-8e64-e8fd4117e6eb.jpg) 6 | 7 | ### Some more examples 8 | 9 | ![Flow1](https://user-images.githubusercontent.com/55774240/134647325-c7b6d61d-4430-445a-aab6-95ea98af6ae5.png)
10 | ![Flow2](https://user-images.githubusercontent.com/55774240/134647321-3d1628e2-d728-44a3-bdd5-a928a511e05c.png)
11 | ![Flow3](https://user-images.githubusercontent.com/55774240/134647335-2e8c3c0d-8856-4523-8c71-8645a76bbb38.png)
12 | ![Flow4](https://user-images.githubusercontent.com/55774240/134647330-d867271d-af90-4fa5-b54f-1d74600482ff.png) 13 | 14 | 15 | ## Edmonds-Karp algorithm 16 | 17 | Edmonds-Karp algorithm is just an implementation of the Ford-Fulkerson method that uses BFS for finding augmenting paths. 18 | 19 | ## Graph example 20 | 21 | ![graph](https://user-images.githubusercontent.com/55774240/134647528-843ea5af-86de-4ea9-8c05-d2dd60204bbf.png) 22 | 23 | Max Flow for the above graph is 150 `Source is 0 , Sink is 1` : calculate on your own **If you have doubt how feel free to post in discussion of this repo** 24 | -------------------------------------------------------------------------------- /T-Template/FunctionTemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template //T is the template argument that accepts different data types 5 | void func_swap(T &arg1, T &arg2) 6 | { 7 | T temp; 8 | temp = arg1; 9 | arg1 = arg2; 10 | arg2 = temp; 11 | } 12 | 13 | int main() 14 | { 15 | int num1 = 10, num2 = 20; 16 | double d1 = 100.53, d2 = 435.54; 17 | char ch1 = 'A', ch2 = 'Z'; 18 | 19 | cout << "Original data\n"; 20 | cout << "num1 = " << num1 << "\tnum2 = " << num2<> n; 31 | vector arr(n); 32 | for (int i = 0; i < n; i++) { 33 | cin >> arr[i]; 34 | } 35 | cin >> tar; 36 | printTargetSumSubsets(arr, 0, "", 0, tar); 37 | } 38 | -------------------------------------------------------------------------------- /G-Graphs/T-TraversalInGraphs/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | template 10 | class Graph{ 11 | 12 | map > l; 13 | 14 | public: 15 | void addEdge(int x,int y){ 16 | l[x].push_back(y); 17 | l[y].push_back(x); 18 | } 19 | 20 | void bfs(T src){ 21 | map visited; 22 | queue q; 23 | 24 | 25 | q.push(src); 26 | visited[src]=true; 27 | 28 | //While Queue us not empty 29 | while(!q.empty()){ 30 | 31 | //Remove start node from q get nbrs keep rollin 32 | T node = q.front(); 33 | q.pop(); 34 | // l[node] will give me the list of nodes which are nbr of nodes see map above 35 | cout< g; 53 | g.addEdge(0,1); 54 | g.addEdge(1,2); 55 | g.addEdge(2,3); 56 | 57 | g.bfs(0); 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /D-DivideAndConquerAlgorithms/Pow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | double myPow_h(double x, int n){ 8 | if (n==0){ 9 | //if value of n=0 then return 1 10 | return 1; 11 | } 12 | double m=myPow_h(x,n/2); // call the function recurrsivly 13 | if(n%2==0){ 14 | // 15 | return m*m; // if n is factor of 2 then return m square 16 | } 17 | else{ 18 | return m*m*x; // if not factor of 2 then return m square into x 19 | } 20 | } 21 | 22 | double myPow(double x, int n){ 23 | if (n<0){ // if n is less then 1 it means -ve power on a number or reciprocal of the x^n 24 | return 1/myPow_h(x,n); 25 | } 26 | else{ //otherwise 27 | return myPow_h(x,n); // otherwise return result 28 | } 29 | } 30 | 31 | 32 | 33 | 34 | int main(){ 35 | cout<<"enter the base number"<>x; 38 | cout<<"enter the power"<>n; 41 | double val=myPow(x,n); 42 | cout<<"answer : "< 4 | using namespace std; 5 | struct Node{//Structure of Tree Node 6 | int data; 7 | Node*left, *right; 8 | Node(int val){ 9 | data=val; 10 | left=right=NULL; 11 | } 12 | }; 13 | 14 | //function to be called 15 | bool valid(Node*root, long minVal,long maxVal){ 16 | if(root==NULL)return true; //empty Tree is valid 17 | if(root->data>=maxVal or root->data<=minVal)return false; 18 | 19 | return valid(root->left,minVal,root->data)and valid(root->right,root->data,maxVal);//1st Left recursion Then right 20 | } 21 | 22 | //main function which will return thr result in boolean format 23 | bool isValidBST(Node*root){ 24 | return valid(root,INT_MIN,INT_MAX); 25 | } 26 | 27 | 28 | 29 | int main(){ 30 | Node*root=new Node(5); 31 | root->left=new Node(1); 32 | root->right=new Node(6); 33 | root->right->left=new Node(4); 34 | root->right->right=new Node(8); 35 | 36 | /* 37 | Given Tree: 38 | 5 39 | / \ 40 | 1 6 41 | /\ 42 | 4 8 43 | 44 | */ 45 | 46 | 47 | if(isValidBST(root))cout<<"It's a Valid BST"< 2 | 3 | #include 4 | using namespace std; 5 | int main(){ 6 | 7 | sets; 8 | cout<<"enter set size->"; 9 | int n; 10 | cin>>n; 11 | for(int i=0;i"; 14 | cin>>val; 15 | s.insert(val); 16 | } 17 | cout<"<"<"<"; 29 | int key; 30 | cin>>key; 31 | if(s.find(key)!=s.end()) 32 | { 33 | cout<5 44 | enter Value->1 45 | enter Value->2 46 | enter Value->3 47 | enter Value->4 48 | enter Value->5 49 | 50 | Size of Set ->5 51 | display Set elements-> 52 | 1 2 3 4 5 53 | Searching in Set-> 54 | Find the element You are in Search for->4 55 | 4 is present 56 | 57 | */ 58 | -------------------------------------------------------------------------------- /A-Array/WavePrintOfMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int m,n; 6 | cout<<"Enter number of rows of the matrix: "; 7 | cin>>m; 8 | cout<<"Enter number of columns of the matrix: "; 9 | cin>>n; 10 | int matrix[m][n]; 11 | 12 | //Taking a matrix as an input 13 | cout<<"Enter the elements of matrix: "<>matrix[i][j]; 17 | } 18 | } 19 | 20 | //To print in wave form 21 | cout<<"Printing elements of matrix in wave form: "<=0;row_no--){ 35 | cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int helper(string & s, int tar){ 8 | 9 | int cont=0; 10 | for(int i=0;i>s; 34 | int cont; 35 | cont = counting_divisible_substring(s); // get results 36 | cout<<"Output: "<<(cont%((int)(pow(10.0,9.0))+7))< 6 | #include 7 | using namespace std; 8 | 9 | int totalWays(int currentIndex,int target,unordered_map&m) 10 | { 11 | //base conditions 12 | if(currentIndex==target) return 1; 13 | if(currentIndex>target) return 0; 14 | 15 | //making currentKey from the changing parameter of the recursive call 16 | int currentKey=currentIndex; 17 | 18 | //if currentKey already exists then returning it value 19 | if(m.count(currentKey)) return m[currentKey]; 20 | 21 | //exploring the two possibilities-oneJump & twoJump 22 | int oneJump=totalWays(currentIndex+1,target,m); 23 | int twoJump=totalWays(currentIndex+2,target,m); 24 | 25 | //storing the answer for currentKey in the unordered_map,so that we can use it in future 26 | m[currentKey]=oneJump+twoJump; 27 | 28 | return m[currentKey]; 29 | } 30 | 31 | int main() 32 | { 33 | int n; 34 | cin>>n; 35 | unordered_mapm; 36 | cout<< totalWays(0,n,m); 37 | return 0; 38 | } 39 | 40 | //Time Complexity = O(n) 41 | //Space Complexity = O(n) -------------------------------------------------------------------------------- /S-Strings/CountCharOccurrence.cpp: -------------------------------------------------------------------------------- 1 | //----------Counts the Occurence of particular Chararacter in String ------// 2 | #include 3 | #include 4 | using namespace std ; 5 | 6 | // to count occurrence of character in a string 7 | void countEachChar(string str){ // taking sentence as input 8 | int *counter = new int[256]; // array for all character 9 | int len = str.size(); 10 | for (int i = 0; i 2 | using namespace std; 3 | // } Driver Code Ends 4 | //User function template for C++ 5 | class Solution{ 6 | public: 7 | vector kLargest(int arr[], int n, int k) { 8 | priority_queue , greater > minHeap ; 9 | for(int i=0 ; i k) 13 | { 14 | minHeap.pop() ; 15 | } 16 | } 17 | 18 | int size = minHeap.size() ; 19 | vector v(size) ; 20 | int index= size-1; 21 | while(!minHeap.empty()) 22 | { 23 | v[index--] = minHeap.top() ; 24 | minHeap.pop() ; 25 | } 26 | 27 | return v; 28 | } 29 | 30 | }; 31 | 32 | // { Driver Code Starts. 33 | 34 | int main() { 35 | int t; 36 | cin >> t; 37 | while (t--) { 38 | int n, k; 39 | cin >> n >> k; 40 | int arr[n]; 41 | for (int i = 0; i < n; i++) { 42 | cin >> arr[i]; 43 | } 44 | Solution ob; 45 | auto ans = ob.kLargest(arr, n, k); 46 | for (auto x : ans) { 47 | cout << x << " "; 48 | } 49 | cout << "\n"; 50 | } 51 | return 0; 52 | } 53 | // } Driver Code Ends -------------------------------------------------------------------------------- /G-Graphs/I-Implementation/AdjacencyMatrix.cpp: -------------------------------------------------------------------------------- 1 | //---- create and display an adjacency matrix ----// 2 | 3 | #include 4 | 5 | using namespace std; 6 | #define Max 100 7 | int adj[Max][Max]; 8 | int n; 9 | 10 | int main() 11 | { 12 | int max_edges,i,j,origin,destin; 13 | int graph_type; 14 | cout<<"Enter 1 for undirected graph or 2 for dirtected graph : "; 15 | cin>>graph_type; 16 | cout<<"Enter number of vertices : "; 17 | cin>>n; 18 | if(graph_type==1) 19 | max_edges=n*(n-1)/2; 20 | else 21 | max_edges=n*(n-1); 22 | for(i=1;1<=max_edges;i++){ 23 | cout<<"Enter -1 -1 to exit or edge "<>origin>>destin; 25 | if((origin==-1) && (destin==-1)) 26 | break; 27 | if(origin>=n||destin>=n||destin<0||origin<0) 28 | { 29 | cout<<"invalid vertex"< 2 | using namespace std; 3 | int main(){ 4 | unordered_setun; 5 | cout<<"enter unordered_set size->"; 6 | int m; 7 | cin>>m; 8 | for(int i=0;i"; 11 | cin>>val; 12 | un.insert(val); 13 | } 14 | cout<"<"<"<"; 26 | int k; 27 | cin>>k; 28 | if(un.find(k)!=un.end()) 29 | { 30 | cout<6 42 | enter Value->10 43 | enter Value->8 44 | enter Value->12 45 | enter Value->1 46 | enter Value->10 47 | enter Value->7 48 | 49 | Size of unordered_Set ->5 50 | display unordered_Set elements-> 51 | 7 10 8 12 1 52 | Searching in unordered_Set-> 53 | Find the element You are in Search for->15 54 | 15 is not present 55 | */ -------------------------------------------------------------------------------- /D-DynamicProgramming/EggDroppingPuzzle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | int dp[201][201] ; 7 | public: 8 | int solve(int e , int f) 9 | { 10 | if(f==0 || f==1) 11 | { 12 | return dp[e][f]=f ; 13 | } 14 | if(e==1) 15 | { 16 | return dp[e][f]=f ; 17 | } 18 | if(dp[e][f]!=-1) 19 | { 20 | return dp[e][f] ; 21 | } 22 | 23 | int finalAns = INT_MAX ; 24 | for(int k=1; k<=f ; k++) 25 | { 26 | int tempAns= 1+ max(solve(e-1, k-1), solve(e, f-k)) ; 27 | finalAns = min(finalAns , tempAns) ; 28 | } 29 | return dp[e][f] = finalAns ; 30 | } 31 | int eggDrop(int n, int k) 32 | { 33 | memset(dp, -1, sizeof(dp)) ; 34 | solve(n , k) ; 35 | } 36 | }; 37 | 38 | // { Driver Code Starts. 39 | int main() 40 | { 41 | //taking total testcases 42 | int t; 43 | cin>>t; 44 | while(t--) 45 | { 46 | //taking eggs and floors count 47 | int n, k; 48 | cin>>n>>k; 49 | Solution ob; 50 | //calling function eggDrop() 51 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | //https://www.geeksforgeeks.org/buy-maximum-stocks-stocks-can-bought-th-day/ 6 | 7 | // Returning the maximum stocks 8 | int buyMaxStocks(int n, int k, int prices[]) 9 | { 10 | vector > vec; 11 | 12 | // Now, Making pair of product cost and number of the day.. 13 | for (int i = 0; i < n; ++i) 14 | vec.push_back(make_pair(prices[i], i + 1)); 15 | 16 | // Sort the vector pair. 17 | sort(vec.begin(), vec.end()); 18 | 19 | // Calculating the maximum number of stock count. 20 | int result = 0; 21 | for (int i = 0; i < n; ++i) { 22 | result += min(vec[i].second, k / vec[i].first); 23 | k -= vec[i].first * min(vec[i].second, (k / vec[i].first)); 24 | } 25 | 26 | return result; 27 | } 28 | 29 | int main() 30 | { 31 | int prices[100]; 32 | int days; 33 | cout<<"Enter the number of days: "; 34 | cin>>days; 35 | for(int i=0; i>prices[i]; 38 | } 39 | int money; 40 | cout<<"Enter the initial amount of money the customer has: "; 41 | cin>>money; 42 | 43 | cout << buyMaxStocks(days, money, prices) << endl; 44 | return 0; 45 | } -------------------------------------------------------------------------------- /O-OOPS/B-Binding/README.md: -------------------------------------------------------------------------------- 1 | # Table of Content 2 | - [Binding In C++](#binding) 3 | - [Early Binding](#early) 4 | - [Late Binding](#late) 5 | 6 | 7 | 8 | # Binding In C++ 9 | ``` 10 | The binding means the process of converting identifiers into addresses. 11 | For each variables and functions this binding is done. 12 | For functions it is matching the call with the right function definition by the compiler. 13 | The binding is done either at compile time or at runtime. 14 | ``` 15 | ![cpp-binding](https://user-images.githubusercontent.com/84399701/164407761-e1b2a480-3715-4346-9f25-40ac8cc6a77b.png) 16 | 17 | 18 | 19 | 20 | ## Early Binding 21 | 22 | ``` 23 | Early Binding (compile-time time polymorphism) 24 | As the name indicates, compiler (or linker) directly associate an address to the function call. 25 | It replaces the call with a machine language instruction that tells the mainframe to leap to the address of the function. 26 | By default early binding happens in C++. 27 | ``` 28 | 29 | 30 | 31 | 32 | ## Late Binding 33 | 34 | ``` 35 | Late Binding : (Run time polymorphism) 36 | In this, the compiler adds code that identifies the kind of object at runtime then matches the call with the right function definition. 37 | This can be achieved by declaring a virtual function. 38 | ``` 39 | -------------------------------------------------------------------------------- /R-Recursion/ReplacePi.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | //------------------------------------PROBLEM :String Replace PI using Recursion ---------------------------------- 4 | #include 5 | using namespace std; 6 | #define ll long long int 7 | #define pb push_back 8 | #define mp make_pair 9 | typedef pair pii; 10 | typedef pair pl; 11 | typedef vector vi; 12 | typedef vector vl; 13 | typedef vector vpii; 14 | typedef vector vpl; 15 | typedef vector vvi; 16 | typedef vector vvl; 17 | #define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--)) 18 | 19 | 20 | //character array and index 21 | void addPi(char s[],int i){ 22 | if(s[i]=='\0' and s[i+1]=='\0'){ 23 | return; 24 | } 25 | if(s[i]=='p' and s[i+1]=='i'){ 26 | int j=i+2; 27 | while(s[j]!='\0')j++; 28 | 29 | while(j>=i+2){ 30 | s[j+2]=s[j]; 31 | j--; 32 | } 33 | s[i]='3'; 34 | s[i+1]='.'; 35 | s[i+2]='1'; 36 | s[i+3]='4'; 37 | 38 | addPi(s,i+4); 39 | }else{ 40 | //no p and corresponding 'i' 41 | addPi(s,i+1); 42 | } 43 | 44 | } 45 | 46 | 47 | int main() 48 | { 49 | ios_base :: sync_with_stdio(false); 50 | cin.tie(nullptr); 51 | cout.tie(nullptr); 52 | 53 | char arr[10000]; 54 | cin>>arr; 55 | addPi(arr,0); 56 | 57 | cout< 3 | using namespace std; 4 | 5 | /* Function to test whether a string is palindrome or not */ 6 | bool isPalindrome(string S) 7 | { 8 | if (S.length() <= 1) 9 | { 10 | return true; // if length of string is 1 or 0 it will be palindrome for sure 11 | } 12 | 13 | // if length of string is more than one we will iterate over a loop 14 | for (int i = 0; i < S.length() / 2; i++) 15 | { 16 | if (S[i] != S[S.length() - i - 1]) // checking characters from first and last of string 17 | { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | int main() 25 | { 26 | cout << "Enter the string:" << endl; // Input string 27 | string s; 28 | cin >> s; 29 | 30 | bool ans = isPalindrome(s); // function call to check a string is palindrome or not 31 | if(ans){ 32 | cout << "True" << endl; // true if palindrome 33 | }else{ 34 | cout << "False" << endl; // false if not palindrome 35 | } 36 | } 37 | 38 | /* 39 | Input: 40 | 1. "abba" 41 | 2. "abc" 42 | 3. "abccad" 43 | Output: 44 | True 45 | False 46 | False 47 | 48 | Explanation: 49 | 1. abba is a palindrome 50 | 2. abc is not a palindrome 51 | 3. abccad is not a palindrome 52 | */ -------------------------------------------------------------------------------- /D-DynamicProgramming/LongestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // The longest common subsequence in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | void lcsAlgo(char *S1, char *S2, int m, int n) { 7 | int LCS_table[m + 1][n + 1]; 8 | 9 | 10 | // Building the matrix in bottom-up way 11 | for (int i = 0; i <= m; i++) { 12 | for (int j = 0; j <= n; j++) { 13 | if (i == 0 || j == 0) 14 | LCS_table[i][j] = 0; 15 | else if (S1[i - 1] == S2[j - 1]) 16 | LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1; 17 | else 18 | LCS_table[i][j] = max(LCS_table[i - 1][j], LCS_table[i][j - 1]); 19 | } 20 | } 21 | 22 | int index = LCS_table[m][n]; 23 | char lcsAlgo[index + 1]; 24 | lcsAlgo[index] = '\0'; 25 | 26 | int i = m, j = n; 27 | while (i > 0 && j > 0) { 28 | if (S1[i - 1] == S2[j - 1]) { 29 | lcsAlgo[index - 1] = S1[i - 1]; 30 | i--; 31 | j--; 32 | index--; 33 | } 34 | 35 | else if (LCS_table[i - 1][j] > LCS_table[i][j - 1]) 36 | i--; 37 | else 38 | j--; 39 | } 40 | 41 | // Printing the sub sequences 42 | cout << "S1 : " << S1 << "\nS2 : " << S2 << "\nLCS: " << lcsAlgo << "\n"; 43 | } 44 | 45 | int main() { 46 | char S1[] = "ACADE"; 47 | char S2[] = "CBGSA"; 48 | int m = strlen(S1); 49 | int n = strlen(S2); 50 | 51 | lcsAlgo(S1, S2, m, n); 52 | } -------------------------------------------------------------------------------- /S-Sets/SetUnion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a[10],b[10],c[10],i,j,k=0,num1,num2; 8 | 9 | //Initialize set A 10 | cout<<"Enter number of element of set A\n"; 11 | cin>>num1; 12 | cout<<"Enter the element of set A \n"; 13 | for(i=0;i>a[i]; 15 | 16 | //Initialize set B 17 | cout<<("Enter number of element of set B\n"); 18 | cin>>num2; 19 | cout<<"Enter the element of set B \n"; 20 | for(i=0;i>b[i]; 22 | 23 | //Finding if there is any repeated element in set A 24 | for(i=0;i 4 | using namespace std; 5 | #define V 4 6 | 7 | // implementation of traveling Salesman Problem 8 | int travllingSalesmanProblem(int graph[][V], int s) 9 | { 10 | // store all vertex apart from source vertex 11 | vector vertex; 12 | for (int i = 0; i < V; i++) 13 | if (i != s) 14 | vertex.push_back(i); 15 | 16 | // store minimum weight Hamiltonian Cycle. 17 | int min_path = INT_MAX; 18 | do { 19 | 20 | // store current Path weight(cost) 21 | int current_pathweight = 0; 22 | 23 | // compute current path weight 24 | int k = s; 25 | for (int i = 0; i < vertex.size(); i++) { 26 | current_pathweight += graph[k][vertex[i]]; 27 | k = vertex[i]; 28 | } 29 | current_pathweight += graph[k][s]; 30 | 31 | // update minimum 32 | min_path = min(min_path, current_pathweight); 33 | 34 | } while ( 35 | next_permutation(vertex.begin(), vertex.end())); 36 | 37 | return min_path; 38 | } 39 | 40 | // Driver Code 41 | int main() 42 | { 43 | // matrix representation of graph 44 | int graph[][V] = { { 0, 10, 15, 20 }, 45 | { 10, 0, 35, 25 }, 46 | { 15, 35, 0, 30 }, 47 | { 20, 25, 30, 0 } }; 48 | int s = 0; 49 | cout << travllingSalesmanProblem(graph, s) << endl; 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /H-HashMap/Multimap.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(){ 7 | int n; 8 | char c; 9 | string s; 10 | 11 | multimap m; 12 | /*Multimap can be used to store multiple values 13 | for the same key */ 14 | 15 | cin>>n; 16 | 17 | for(int i=0;i>c>>s; 19 | m.insert(make_pair(c,s)); 20 | 21 | } 22 | 23 | 24 | for (auto p:m) 25 | cout< "<second<<" , "; 39 | cout<second=="Cat") 43 | m.erase(f); 44 | 45 | for (auto p:m) 46 | cout< "< Apple 60 | B -> Banana 61 | C -> Cat 62 | D -> Dog 63 | E -> Eyes 64 | Dog , 65 | Cat Removed 66 | B -> Banana 67 | D -> Dog 68 | E -> Eyes 69 | */ 70 | 71 | -------------------------------------------------------------------------------- /T-Tree/G-GenricTree/LevelOrderTraversalOfaGenricTree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | // https://leetcode.com/problems/n-ary-tree-level-order-traversal/ 6 | 7 | struct Node { 8 | int data; 9 | vectorchildren; 10 | }; 11 | 12 | Node* newNode(int key) { 13 | Node* temp = new Node; 14 | temp->data = key; 15 | return temp; 16 | 17 | } 18 | 19 | Node* construct(int arr[], int n ) { 20 | Node* root = NULL; 21 | stackst; 22 | for (int i = 0; i < n; i++) { 23 | if (arr[i] == -1) { 24 | st.pop(); 25 | } else { 26 | Node* t = newNode(arr[i]); 27 | if (st.size() > 0) { 28 | st.top()->children.push_back(t); 29 | } else { 30 | root = t; 31 | } 32 | st.push(t); 33 | } 34 | } 35 | return root; 36 | } 37 | 38 | void levelorder(Node* node) 39 | { 40 | if (node == NULL) return; 41 | queue q; 42 | q.push(node); 43 | while (q.size() > 0) 44 | { 45 | Node* temp = q.front(); 46 | q.pop(); 47 | cout << temp->data << " " ; 48 | for (Node* child : temp->children) 49 | { 50 | q.push(child); 51 | } 52 | } 53 | cout << "." << endl; 54 | } 55 | 56 | int main() { 57 | int n; 58 | cin >> n; 59 | int arr[n]; 60 | for (int i = 0; i < n; i++) { 61 | cin >> arr[i]; 62 | } 63 | Node* root = construct(arr, n); 64 | levelorder(root); 65 | } -------------------------------------------------------------------------------- /D-DynamicProgramming/TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | // Problem Statement: https://leetcode.com/problems/trapping-rain-water/ 2 | 3 | // C++ program to find maximum amount of water that can 4 | // be trapped within given set of bars. 5 | // Space Complexity : O(1) 6 | 7 | #include 8 | using namespace std; 9 | 10 | int findWater(int arr[], int n) 11 | { 12 | // initialize output 13 | int result = 0; 14 | 15 | // maximum element on left and right 16 | int left_max = 0, right_max = 0; 17 | 18 | // indices to traverse the array 19 | int lo = 0, hi = n - 1; 20 | 21 | while (lo <= hi) { 22 | if (arr[lo] < arr[hi]) { 23 | if (arr[lo] > left_max) 24 | // update max in left 25 | left_max = arr[lo]; 26 | else 27 | // water on curr element = max - curr 28 | result += left_max - arr[lo]; 29 | lo++; 30 | } 31 | else { 32 | if (arr[hi] > right_max) 33 | // update right maximum 34 | right_max = arr[hi]; 35 | else 36 | result += right_max - arr[hi]; 37 | hi--; 38 | } 39 | } 40 | 41 | return result; 42 | } 43 | 44 | int main() 45 | { 46 | int arr[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; 47 | int n = sizeof(arr) / sizeof(arr[0]); 48 | cout << "Maximum water that can be accumulated is " 49 | << findWater(arr, n); 50 | } 51 | 52 | // Output : Maximum water that can be accumulated is 6. 53 | 54 | // Time Complexity : O(n) 55 | 56 | // Space Complexity : O(1) 57 | -------------------------------------------------------------------------------- /S-SearchingAlgorithms/SearchElementRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Search element in rotated sorted array 2 | 3 | // Problem Statement: https://leetcode.com/problems/search-in-rotated-sorted-array/ 4 | 5 | #include 6 | using namespace std; 7 | 8 | int SearchElement(int arr[],int n,int element){ 9 | int low=0,high=n-1; 10 | while(low<=high){ 11 | int mid=(low+high)/2; 12 | if(arr[mid]==element){ // Element found 13 | return mid; 14 | } 15 | if(arr[low]<=arr[mid]){ // left half sorted 16 | if(element>=arr[low] && elementarr[mid] && element<=arr[high]){ 25 | low=mid+1; // go in right sorted half 26 | } 27 | else{ 28 | high=mid-1; // go in left unsorted half 29 | } 30 | } 31 | } 32 | return -1; 33 | } 34 | int main() 35 | { 36 | int n; 37 | cin>>n; 38 | int arr[n]; 39 | for (int i = 0; i < n; i++) 40 | { 41 | cin>>arr[i]; 42 | } 43 | int element; 44 | cin>>element; 45 | cout< 5 | #include 6 | using namespace std; 7 | 8 | void showlist(list mylist){ 9 | list ::iterator itr;//Making a iterator of my list as i cannot access index just like arrays 10 | 11 | for(itr=mylist.begin();itr!=mylist.end();itr++){ 12 | cout<<" "<<*itr<<" "; //simple for loop to print the value of the element s in the list 13 | } 14 | cout< mylist;//convention basically to make a list of type int 21 | //Now to push the data and perform the series of operations in the list 22 | for(int i=1;i<=10;i++) 23 | mylist.push_back(i*2); //vector::push_back() is a library function of "vector" header, it is used to insert/add an element at the end of the vector 24 | 25 | cout<<"List is : ";showlist(mylist);//to show the list function is defined above 26 | 27 | cout<<"Front : "< 2 | using namespace std; 3 | 4 | //https://www.geeksforgeeks.org/generic-treesn-array-trees/ 5 | 6 | // defining node 7 | class node{ 8 | public: 9 | int data; 10 | vector children; 11 | 12 | node(int val){ 13 | this->data=val; 14 | } 15 | 16 | }; 17 | 18 | //function to create genric tree (n) 19 | void creatingtree(node* &root,int arr[],int n){ 20 | 21 | stack st; 22 | for(int i=0;i0){ 34 | 35 | st.top()->children.push_back(newnode); 36 | } 37 | else{ 38 | root=newnode; 39 | } 40 | st.push(newnode); 41 | } 42 | } 43 | } 44 | 45 | // function to display the genric tree (n) 46 | void display(node* root){ 47 | string str=to_string(root->data)+"->"; 48 | for(node*child:root->children){ 49 | str +=to_string(child->data)+", "; 50 | } 51 | str+="."; 52 | cout<children){ 55 | display(child); 56 | } 57 | 58 | } 59 | 60 | int main(){ 61 | node* root=NULL; 62 | 63 | int arr[]={10,20,50,-1,60,-1,-1,30,70,-1,80,110,-1,120,-1,-1,90,-1,-1,40,100,-1,-1,-1}; 64 | int n=sizeof(arr)/sizeof(arr[0]); 65 | creatingtree(root,arr,n); 66 | display(root); 67 | } 68 | -------------------------------------------------------------------------------- /.github/keylabeler.yml: -------------------------------------------------------------------------------- 1 | # Determines if we search the title (optional). Defaults to true. 2 | matchTitle: true 3 | 4 | # Determines if we search the body (optional). Defaults to true. 5 | matchBody: true 6 | 7 | # Determines if label matching is case sensitive (optional). Defaults to true. 8 | caseSensitive: false 9 | 10 | # Explicit keyword mappings to labels. Form of match:label. Required. 11 | labelMappings: 12 | Audio : Audio 13 | Video : Video 14 | Documentation : Documentation 15 | Android Dev (Flutter): Android-Dev-Flutter 16 | Android Dev (Kotlin): Android-Dev-Kotlin 17 | Android Dev (Java): Android-Dev-Java 18 | Backend Dev (Java): Backend-Dev-Java 19 | Backend Dev (.NET): .NET 20 | Backend Dev (PHP): Backend-Dev-PHP 21 | Backend Dev (Python): Backend-Dev-Python 22 | C/CPP : C/CPP 23 | Competitive Programming : Competitive Programming 24 | Cyber Security : Cyber Security 25 | DSA : DSA 26 | Database : Database 27 | Datascience with Python : DSWP 28 | Datascience with R : Datascience with R 29 | Frontend Dev HTML/CSS/JS : Frontend Dev HTML/CSS/JS 30 | Frontend Dev React/Angular/Vue : Frontend Dev React/Angular/Vue 31 | Golang : Golang 32 | Interview Prep : Interview Prep 33 | Java_Domain : Java 34 | JavaScript : JavaScript 35 | MERN : MERN 36 | Machine Learning : Machine Learning 37 | Open Source : Open Source 38 | Python_Domain : Python 39 | Rust : Rust 40 | Statistics : Statistics 41 | UI/UX : UI/UX 42 | -------------------------------------------------------------------------------- /A-Array/AntispiralMatrix.cpp: -------------------------------------------------------------------------------- 1 | // Header file 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Driver Code 7 | int main() 8 | { 9 | //Inputs 10 | int R, C; 11 | cin >> R >> C; 12 | 13 | int mat[R][C]; 14 | for (int i = 0; i < R; i++) 15 | { 16 | for (int j = 0; j < C; j++) 17 | { 18 | cin >> mat[i][j]; 19 | } 20 | } 21 | 22 | int i, k = 0, l = 0; 23 | int m = R - 1, n = C - 1; 24 | 25 | stack stk; 26 | 27 | // k - starting row index 28 | // m - ending row index 29 | // l - starting column index 30 | // n - ending column index 31 | // i - iterator 32 | 33 | while (k <= m && l <= n) 34 | { 35 | 36 | for (i = l; i <= n; ++i) 37 | stk.push(mat[k][i]); // First Row 38 | k++; 39 | 40 | for (i = k; i <= m; ++i) 41 | stk.push(mat[i][n]); //Last column 42 | n--; 43 | 44 | if (k <= m) //Last Row 45 | { 46 | for (i = n; i >= l; --i) 47 | stk.push(mat[m][i]); 48 | m--; 49 | } 50 | 51 | if (l <= n) //First column 52 | { 53 | for (i = m; i >= k; --i) 54 | stk.push(mat[i][l]); 55 | l++; 56 | } 57 | } 58 | 59 | while (!stk.empty()) 60 | { 61 | cout << stk.top() << " "; 62 | stk.pop(); 63 | } 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /D-DynamicProgramming/MinimumInsertionDeletion.cpp: -------------------------------------------------------------------------------- 1 | // Header File 2 | #include 3 | 4 | using namespace std; 5 | 6 | // LCS function to find the length of longest common subsequence in two strings 7 | // str1 and str2 8 | int lcs(string str1, string str2, int m, int n) 9 | { 10 | int L[m + 1][n + 1]; 11 | int i, j; 12 | 13 | for (i = 0; i <= m; i++) { 14 | for (j = 0; j <= n; j++) { 15 | if (i == 0 || j == 0) 16 | L[i][j] = 0; 17 | 18 | else if (str1.at(i - 1) == str2.at(j - 1)) 19 | L[i][j] = L[i - 1][j - 1] + 1; 20 | 21 | else 22 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 23 | } 24 | } 25 | // L[m][n] contains the length 26 | // of the LCS of the tw strings 27 | return L[m][n]; 28 | } 29 | 30 | // Function to print the output 31 | // and find the Total number of insertions and total number of deletions 32 | void printMinDelAndInsert(string str1, string str2) 33 | { 34 | int m = str1.size(); 35 | int n = str2.size(); 36 | 37 | int len = lcs(str1, str2, m, n); 38 | 39 | cout << "Minimum number of deletions = " << (m - len) 40 | << endl; 41 | 42 | cout << "Minimum number of insertions = " << (n - len) 43 | << endl; 44 | } 45 | 46 | //Driver Code 47 | int main() 48 | { 49 | string str1 ; 50 | string str2; 51 | // Inputs 52 | cout<<"Enter string 1: "; 53 | cin>>str1; 54 | cout<<"Enter string 2: "; 55 | cin>>str2; 56 | //Calling Function 57 | printMinDelAndInsert(str1, str2); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /G-Graphs/T-TraversalInGraphs/DepthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | template 10 | class Graph{ 11 | 12 | map > l; 13 | 14 | public: 15 | void addEdge(int x,int y){ 16 | l[x].push_back(y); 17 | l[y].push_back(x); 18 | } 19 | /* Here is below function we don't want to create a copy of visited map 20 | in fact we want it to remain same so we have passed argument by value 21 | rather than by reference */ 22 | void dfs_helper(T src,map &visited){ 23 | //recursive function that will traverse the graph 24 | 25 | cout< visited; 38 | //Mark all the nodes a not visited in the beginning 39 | for(auto p:l){ 40 | T node =p.first; 41 | visited[node]=false; 42 | } 43 | 44 | //Call the helper function 45 | dfs_helper(src,visited); 46 | 47 | 48 | } 49 | }; 50 | 51 | int main(){ 52 | 53 | Graph g; 54 | g.addEdge(0,1); 55 | g.addEdge(1,2); 56 | g.addEdge(2,3); 57 | g.addEdge(3,4); 58 | g.addEdge(4,5); 59 | g.addEdge(3,0); 60 | 61 | g.dfs(0); 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /H-HashMap/HashMaps.cpp: -------------------------------------------------------------------------------- 1 | 2 | //PLease read the text file Hashmaps.txt in this directory before precedding further 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | int main(){ 8 | //basic vector int key and int mapping 9 | map l; 10 | //insert values in hashmap 11 | l.insert(pair(1,10)); 12 | l.insert(pair(2,20)); 13 | l.insert(pair(3,30)); 14 | l.insert(pair(4,40)); 15 | l.insert(pair(5,50)); 16 | //make a map iterator 17 | map::iterator itr; 18 | cout<<"1.Using itr basic begin to end : \n"; 19 | //to print the map in various fashion 20 | for(itr=l.begin();itr!=l.end();itr++) 21 | cout<first<<"\t"<second<<"\n"; 22 | 23 | cout<<"\n2.Another one : \n"; 24 | //Assigninng to another map 25 | map l2(l.begin(),l.end()); 26 | 27 | for(itr=l2.begin();itr!=l2.end();itr++) 28 | cout<first<<"\t"<second<<"\n"; 29 | 30 | cout<<"\n3.Remove : \n"; 31 | //removing values from map from begin to key value 2 32 | l.erase(l.begin(),l.find(3)); 33 | 34 | for(itr=l.begin();itr!=l.end();itr++) 35 | cout<first<<"\t"<second<<"\n"; 36 | 37 | cout<<"\n4.Remove one: \n"; 38 | //removing values from map with key value 5 39 | l.erase(5); 40 | 41 | for(itr=l.begin();itr!=l.end();itr++) 42 | cout<first<<"\t"<second<<"\n"; 43 | 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /S-Stack/RedundantParenthesis/RedudantParenthesis.cpp: -------------------------------------------------------------------------------- 1 | /* Redundant Parenthesis code */ 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | cout<< "Enter the string:"<> s; 9 | stack st; // stack created 10 | bool ans = false; 11 | 12 | for(int i=0;i 2-> 3-> 4-> 5 -> NULL 24 | - where 1->rand = 5 25 | 2->rand = 4 26 | 3->rand = 2 27 | 4->rand = 1 28 | 5->rand = 3 29 | 30 | ## Output Example: 31 | - cloned list = 1 -> 2-> 3-> 4-> 5 -> NULL 32 | - where 1->rand = 5 33 | 2->rand = 4 34 | 3->rand = 2 35 | 4->rand = 1 36 | 5->rand = 3 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /G-GreedyAlgorithms/FractionalKnapsack.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //1.Take profit/weight ratio and sort in decreasing order. 7 | //2.Take the sum weight till sum is not exceed capacity. 8 | //3.Output the maximum profit or all the included weights. 9 | 10 | struct Object{ 11 | float weight; 12 | float profit; 13 | float PWratio; 14 | }; 15 | bool cmp(struct Object a, struct Object b) 16 | { 17 | return a.PWratio > b.PWratio; 18 | } 19 | 20 | void KnapSackFractional(Object a[],int n,int capacity){ 21 | sort(a,a + n,cmp); 22 | float p=0; 23 | for(int i=0;i>capacity; 45 | cout<<"Enter Total Objects: "; 46 | cin>>no; 47 | Object Arr[no]; 48 | for(int i=0;i>Arr[i].profit; 51 | cout<<" Weight "<>Arr[i].weight; 52 | Arr[i].PWratio = Arr[i].profit/Arr[i].weight; 53 | //cout<<" Ratio "< 3 | 4 | using namespace std; 5 | 6 | // Calculating minimum computations to merge file optimally 7 | int min_computation(int size, int files[]){ 8 | int i,total_computation=0; 9 | 10 | // creating minheap (insertin files size) 11 | priority_queue, greater > pq; 12 | for(i=0;i1) //merge untill priority queue is not empty 17 | { 18 | int lweight=pq.top(); 19 | pq.pop(); 20 | int rweight=pq.top(); 21 | pq.pop(); 22 | int rootweight= lweight + rweight; 23 | total_computation+= rootweight; 24 | pq.push(rootweight); 25 | } 26 | return total_computation; 27 | } 28 | 29 | //-----main-------// 30 | /* 31 | files[5]={2,4,7,9,12} 32 | [2,4 merge ->6] 33 | [6,7 merge ->13] 34 | [9,12 merge -> 21] 35 | [13,21 merge -> 34] therefore minimum computation are (6+13+21+34) 74 */ 36 | int main() 37 | { 38 | int nfile; 39 | cout<<"Enter the number of files : "; 40 | cin>>nfile; //total files 41 | int *files = new int(nfile); 42 | for(int i=0;i>files[i]; 45 | } 46 | 47 | cout<<"Minimum computation required to merge all files in one file are "< 16 | Given a time in 24 hour format, convert it to 12 hour time format. 17 | 18 | 19 | ## Examples 20 |
21 | Enter time in 24 hr format(hh:mm:ss)= 16:23:20
22 | Time in 12hr format is = 4:23:20 PM
23 | 
24 |
25 | Enter time in 24 hr format(hh:mm:ss)= 00:12:45
26 | Time in 12hr format is = 24:12:45 AM
27 | 
28 | 29 | ## Approach 30 | 31 | The approach to solving this problem requires some observations. 32 | * First that the minutes and seconds will be same in both the cases. 33 | * The only change will be in the hours and according to that
Meridien(i.e. AM/PM)
will be appended to the string. 34 | * For hours, first convert it from string to int datatype, then take its modulo with 12 and that will be our hours in 12-hour format. Still, there will be a case when hour becomes 00 i.e (12 or 00 in 24-hour format) which we need to handle separately. 35 | 36 | ## Complexity 37 |
38 | Time Complexity  : O(1)
39 | Space Complexity : O(1)
40 | 
41 | -------------------------------------------------------------------------------- /S-SortingAlgorithms/CountingSort.cpp: -------------------------------------------------------------------------------- 1 | //Program 2 | #include 3 | using namespace std; 4 | 5 | //counting sort function 6 | void countsort(int a[], int n){ 7 | 8 | //Declaring an array of range 256 - max number of bits of all characters in ascii codes. 9 | int count[256]; //for counting the number of occurences of a particular character 10 | 11 | for(int i=0;i<256;i++){ 12 | count[i]=0; 13 | } 14 | 15 | //storing count of each character 16 | for(int i=0;i=0;i--){ 28 | output[count[a[i]]-1] = a[i]; 29 | count[a[i]]--; 30 | } 31 | 32 | //copying the values of output array to the original array 33 | for(int i=0;i>n; 50 | int a[n]; 51 | for(int i=0;i>a[i]; 53 | } 54 | //calling the countsort function 55 | countsort(a,n); 56 | 57 | //print the sorted array 58 | print(a,n); 59 | return 0; 60 | 61 | } -------------------------------------------------------------------------------- /S-SortingAlgorithms/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | 2 | /*------------------------QUICK SORT------------------------*/ 3 | /*Inventor: Tony Hoare 4 | Worst complexity: n^2 5 | Average complexity: n*log(n) 6 | Best complexity: n*log(n) 7 | Method: Partitioning 8 | Stable: No 9 | InPlace : YES 10 | -----------------------------*/ 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | using namespace std; 18 | 19 | void swap(int *a,int *b){ 20 | int temp=*a; 21 | *a=*b; 22 | *b=temp; 23 | } 24 | 25 | 26 | int partition(int *A,int low,int high){ 27 | int pivot=A[low]; 28 | int left=low,right=high; 29 | while(leftlow && A[right]>pivot){ 34 | right--; 35 | } 36 | if(left>n; 65 | int A[n]; 66 | for(int i=0;i>A[i]; 68 | } 69 | 70 | Quick_sort(A,0,n-1); 71 | 72 | Print(A,n); 73 | 74 | return 0; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /D-DynamicProgramming/RodCutting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Function to find the maximum revenue from cutting a rod of length (len) 8 | // where the rod of length (i) has cost (prices[i - 1]) 9 | int RodCutting(vector & prices, int len) { 10 | // (dp) stores the maximum revenue achieved from cutting a rod of length (from 1 to len) 11 | vector dp (len + 1, 0); 12 | // If the rod length is negative (invalid) or zero there's no revenue from it 13 | if (len <= 0) { 14 | return 0; 15 | } 16 | // Cut a rod of length (i) 17 | for (int i = 1; i <= len; i++) { 18 | // divide the rod of length (i) into two rods of lengths (j) and (i - j) 19 | // and store the maximum revenue 20 | for (int j = 0; j < i; j++) { 21 | // (dp[i]) stores the maximum revenue achieved from cutting a rod of length (i) 22 | dp[i] = max(dp[i], prices[j] + dp[i - j - 1]); 23 | } 24 | } 25 | // (dp[len]) contains the maximum revenue from cutting a rod of length (len) 26 | return dp[len]; 27 | } 28 | 29 | int main(){ 30 | int len; 31 | cout << "Enter the rod length :"; 32 | cin >> len; 33 | 34 | vector prices(len); 35 | for(int i = 1; i <= len; i++){ 36 | cout << "Enter the price of the rod of length " << i << " :"; 37 | cin >> prices[i - 1]; 38 | } 39 | 40 | cout <<"Maximum revenue = "< 5 | #include 6 | using namespace std; 7 | 8 | int totalPaths(int currentRow,int currentCol,int targetRow,int targetCol,vector>&v) 9 | { 10 | //base conditions 11 | if(currentRow==targetRow && currentCol==targetCol) return 1;//valid path 12 | if(currentRow<0 || currentCol<0 ||currentRow>targetRow ||currentCol>targetCol) return 0;//invalid path 13 | 14 | //if value is already present in the vector v ,then extract from it, no need to make recursive calls for it 15 | if(v[currentRow][currentCol]!=-1) return v[currentRow][currentCol]; 16 | 17 | //exploring the two possibilities :-1.right movement 2.downward movement 18 | int right = totalPaths(currentRow,currentCol+1,targetRow,targetCol,v); //when the robot moves right 19 | int down = totalPaths(currentRow+1,currentCol,targetRow,targetCol,v); //when the robot moves down 20 | 21 | //storing the answer for the current coordinate in v,so that we can use it in future 22 | v[currentRow][currentCol] = (right+down); 23 | return v[currentRow][currentCol]; 24 | 25 | } 26 | int uniquePaths(int m, int n) 27 | { 28 | vector>v(m,vector(n,-1)); 29 | return totalPaths(0,0,m-1,n-1,v); 30 | } 31 | 32 | int main() 33 | { 34 | int m,n; 35 | cin>>m; 36 | cin>>n; 37 | cout<< uniquePaths(m,n) ; 38 | return 0; 39 | } -------------------------------------------------------------------------------- /S-Stack/DecimalToBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define true 1 5 | #define false 0 6 | //Implementing stack using array 7 | struct stack 8 | { 9 | int top;//variable 10 | int items[20];//array 11 | }; 12 | struct stack s; 13 | 14 | //Initializing the Stack 15 | void initialization() 16 | { 17 | s.top=-1; 18 | } 19 | 20 | //Checking if the stack is empty 21 | int empty() 22 | { 23 | if(s.top==-1) 24 | return true; 25 | else 26 | return false; 27 | } 28 | 29 | //Printing the element from top of the stack 30 | int pop() 31 | { 32 | int temp; 33 | if(s.top==-1) 34 | cout<<"underflow condition "; 35 | temp=s.items[s.top]; 36 | s.top--; 37 | return temp; 38 | } 39 | 40 | //Pusing the elements into the stack 41 | void push(int num) 42 | { 43 | 44 | if(s.top==9) 45 | cout<<"stack overflow"; 46 | s.top++; 47 | s.items[s.top]=num; 48 | } 49 | 50 | int main() 51 | { 52 | int num,temp,bin; 53 | initialization(); 54 | 55 | //Taking the input of the number from the user 56 | cout<<"Enter the number : "; 57 | cin>>num; 58 | 59 | //finding the remainder and pushing it into the stack 60 | while(num!=0) 61 | { 62 | temp=num%2; 63 | push(temp); 64 | num=num/2; 65 | } 66 | 67 | //Printing the binary equivalent 68 | cout<<"The Binary Equivalent is : "; 69 | while(empty()!=1) 70 | { 71 | bin=pop(); 72 | cout< 6 | using namespace std; 7 | 8 | // Convert Function which takes in 24hour time and convert it to 12 hour format 9 | void convert12(string str) 10 | { 11 | // Get Hours 12 | int h1 = (int)str[0] - '0'; 13 | int h2 = (int)str[1] - '0'; 14 | 15 | int hh = h1 * 10 + h2; 16 | 17 | // Finding out the Meridien of time ie. AM or PM 18 | string Meridien; 19 | if (hh < 12) { 20 | Meridien = "AM"; 21 | } 22 | else 23 | Meridien = "PM"; 24 | 25 | hh %= 12; 26 | 27 | // Handle 00 and 12 case separately 28 | if (hh == 0) { 29 | cout << "12"; 30 | 31 | // Printing minutes and seconds 32 | for (int i = 2; i < 8; ++i) { 33 | cout << str[i]; 34 | } 35 | } 36 | else { 37 | cout << hh; 38 | // Printing minutes and seconds 39 | for (int i = 2; i < 8; ++i) { 40 | cout << str[i]; 41 | } 42 | } 43 | 44 | // After time is printed cout Meridien 45 | cout << " " << Meridien << '\n'; 46 | } 47 | 48 | // Driver code 49 | int main() 50 | { 51 | 52 | string str; 53 | cout << "Enter time in 24 hr format(hh:mm:ss)= "; 54 | cin >> str; 55 | cout << "Time in 12hr format is = "; 56 | convert12(str); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /A-Array/SymmetricMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int i,j,r,c,flag=0; 7 | 8 | //taking input for number of rows and columns 9 | cout<<"Enter order of matrix :"<>r>>c; 11 | int arr[r][c]; 12 | 13 | //checking if the matrix is square 14 | if(r!=c) 15 | cout<<"\nNot a symmetric matrix"; 16 | else 17 | { 18 | //taking input for values of the matrix 19 | cout<<"\nEnter the values in the matrix :"<>arr[i][j]; 25 | } 26 | } 27 | 28 | //printing the user entered matrix 29 | cout<<"The entered matrix is :"; 30 | for(i=0 ; ii. 12 | - Send the pairs to the merge function. 13 | - If k-i<=i, loop again but only till k/2. 14 | 2) Merge Step:- 15 | - Create pointer to return the combined list. 16 | - Add the smaller value from either list. 17 | - Increment pointer from which value has been taken. 18 | - Return merged and sorted linked list from two lists. 19 | 20 | ![List1](https://user-images.githubusercontent.com/67220225/158016476-3fad6f1b-6038-4118-a8da-80c27e2fedfd.png) 21 | 22 | 23 | ## Time Complexity: O(n\*k\*log k) 24 | - Outer while loop in function merge_k_ll() runs log k times and everytime it processes n*k elements. 25 | 26 | ## Space Complexity: O(n*k) 27 | - Because recursion is used in merge() and to merge the final 2 linked lists of size (n\*k)/2, n\*k recursive calls will be made. 28 | 29 | You can also see different approches [here](https://www.geeksforgeeks.org/merge-k-sorted-linked-lists/). -------------------------------------------------------------------------------- /Q-Queue/QueueUsingArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int queue[50], n=50, front=0, rear=-1; 4 | void Insert(){ 5 | int item; 6 | if(rear== n-1) //Condition of Queue Overflow 7 | {cout<<"Queue Overflow"<>item; 11 | rear++; 12 | queue[rear]=item; 13 | }} 14 | void Delete(){ 15 | if((front==0 && rear==-1) || front==rear+1){ //Condition of Queue underflow 16 | cout<<"Queue Underflow "; 17 | } 18 | else{ cout<<"Item deleted from queue is : "<< queue[front]<>choice; 42 | switch(choice){ 43 | case 1: Insert(); 44 | break; 45 | case 2: Delete(); 46 | break; 47 | case 3: Display(); 48 | break; 49 | case 4: cout<<"Exit"< 2 | using namespace std; 3 | 4 | //https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/ 5 | 6 | //function to display the 2-d array 7 | void display(vector>& chess) { 8 | for (int i = 0; i < chess.size(); i++) { 9 | for (int j = 0; j < chess.size(); j++) { 10 | cout << chess[i][j] << " "; 11 | } 12 | cout << endl; 13 | } 14 | cout << endl; 15 | } 16 | 17 | void printKnightsTour(vector>& chess, int n, int r, int c, int upcomingMove) { 18 | //base case 19 | if (r < 0 || c < 0 || r >= n || c >= n || chess[r][c] != 0) { 20 | return; 21 | } 22 | if (upcomingMove == n * n) { 23 | chess[r][c] = upcomingMove; 24 | display(chess); 25 | chess[r][c] = 0; 26 | return; 27 | } 28 | chess[r][c] = upcomingMove; 29 | printKnightsTour(chess, n, r - 2, c + 1, upcomingMove + 1); 30 | printKnightsTour(chess, n, r - 1, c + 2, upcomingMove + 1); 31 | printKnightsTour(chess, n, r + 1, c + 2, upcomingMove + 1); 32 | printKnightsTour(chess, n, r + 2, c + 1, upcomingMove + 1); 33 | printKnightsTour(chess, n, r + 2, c - 1, upcomingMove + 1); 34 | printKnightsTour(chess, n, r + 1, c - 2, upcomingMove + 1); 35 | printKnightsTour(chess, n, r - 1, c - 2, upcomingMove + 1); 36 | printKnightsTour(chess, n, r - 2, c - 1, upcomingMove + 1); 37 | chess[r][c] = 0; 38 | } 39 | 40 | int main() { 41 | int n, r, c; 42 | cin >> n >> r >> c; 43 | vector> chess(n, vector (n, 0)); 44 | printKnightsTour(chess, n, r, c, 1); 45 | } -------------------------------------------------------------------------------- /G-Graphs/README.md: -------------------------------------------------------------------------------- 1 | # Table of content 2 | - [Connected components in undirected graph](#connected-components-in-undirected-graph) 3 | - [Code](ConnectedComponentUndirectedGraph.cpp) 4 | - [Algorithm](#algorithm) 5 | - [Properties](#properties) 6 | - [Advantages](#advantages) 7 | 8 | 9 | ## Connected components in undirected graph 10 | - connected components in a undirected graph ia a subgraph in which each pair of node in the subgraph have path between them . 11 | 12 | 13 | 14 | ![Connected components in undirected graph](https://media.geeksforgeeks.org/wp-content/uploads/20190401132549/Diagram.jpg) 15 | 16 | ### Algorithm 17 | ``` 18 | ConnectedComponent(){ 19 | 1. initialized all vertices as unchecked 20 | 2. for all vertices 21 | - if not checked than apply dfs by calling dfs(v,checked[]) function . 22 | } 23 | 24 | dfs(v,checked[]){ 25 | 1. mark v as checked and diaplay it 26 | 2. for neighbouring vertex 27 | - if not checked apply dfs to unchecked neighbouring vertex 28 | } 29 | 30 | ``` 31 | 32 | ### Properties 33 | 34 | - Time Complexity: O(V+E), where V is the number of vertices and E is total number edges in a graph. 35 | 36 | - Space Complexity: O(n) , where n is total number of vertices in graph . 37 | 38 | ### Advantages 39 | - use in the social networking sites, connected components are used to depict the group of people who are friends of each other or who have any common interest 40 | - It can also be used to convert a graph into a Direct Acyclic graph of strongly connected components . 41 | -------------------------------------------------------------------------------- /H-HashMap/Set&Unordered_Set/readme.md: -------------------------------------------------------------------------------- 1 | # Set & Unordered_set: 2 | - ## Set in C++ : 3 | Each element is unique in set and elements are stored in sorted order. Value of elements cann't be modified once it's inserted but removal and adding new value is possible 4 | 5 | - ### Functions in Set--> 6 | 1. begin() = return iterator to 1st element to the set. 7 | 2. end() = return iterator to last element to the set. 8 | 3. size() = return number of elements stored in set. 9 | 4. insert(X)= insert new element 'X' in sorted position 10 | 5. find(key)= return iterator pointing to the element 'key' 11 | 6. empty() = bool function return true if set is empty 12 | either return false. 13 | --- 14 | 15 | - ## Unordered Set : 16 | Unique keys are only allowed . unordered_set is implemented using hash table where keys are hashed into indices of hash table, so it's not possible to maintain sorted order. 17 | 18 | - ### Functions in Set--> 19 | 1. begin() = return iterator to 1st element to the set. 20 | 2. end() = return iterator to last element to the set. 21 | 3. size() = return number of elements stored in set. 22 | 4. insert(X)= insert new element 'X' in unordered_set 23 | 5. find(key)= return iterator pointing to the element 'key' 24 | 6. empty() = bool function return true if set is empty 25 | either return false. 26 | 27 | --- 28 | ### Difference between Set & unordered_set : 29 | 30 | 1. Set is ordered sequence of unique keys , but unordered_set is not sorted sequence . 31 | 2. Time complexity in set functions are almost O(log n) but in unordered_set is O(1). 32 | -------------------------------------------------------------------------------- /M-MathematicalAlgorithms/BisectionMethod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define epsilon 0.01 4 | // epsilon be the error in determing roots of a function 5 | // take an example of a function whose solution we have to find 6 | // Let function be: x^3 - x^2 + 2 7 | double value_of_function(double x) 8 | { 9 | return x*x*x - x*x + 2; 10 | } 11 | 12 | // Prints root of func(x) with error of epilon 13 | void bisection_method(double a, double b) 14 | { 15 | if (value_of_function(a) * value_of_function(b) >= 0) 16 | { 17 | cout << "Values of a and b are not correctly assumed."<<"\n"; 18 | return; 19 | } 20 | // let c be the other value between a and b. 21 | double c = a; 22 | 23 | while ((b-a) >= epsilon) 24 | { 25 | // let c be the mid point 26 | c = (a+b)/2; 27 | 28 | // Checking if middle point is root 29 | if (value_of_function(c) == 0.0) 30 | { 31 | break; 32 | } 33 | // Deciding the side to repeat the steps 34 | else if (value_of_function(c)*value_of_function(a) < 0) 35 | { 36 | b = c; 37 | } 38 | else 39 | { 40 | a = c; 41 | } 42 | } 43 | 44 | cout << "The value of roots of the function is : " << c; 45 | } 46 | // Code to solve above function. 47 | int main() 48 | { 49 | double a =-100; 50 | double b = 200; // a and b are boundary values. 51 | bisection_method(a, b); // calling above function 52 | return 0; 53 | } -------------------------------------------------------------------------------- /H-Heap/MinCostRopes.cpp: -------------------------------------------------------------------------------- 1 | /* Minimum Cost Of Ropes 2 | Time Complexity : O(n log n) 3 | Space Complexity : O(n) , since we are using priority queue for storing data. */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | //Function to return the minimum cost of connecting the ropes. 9 | long long cost(long long arr[], long long n) 10 | { 11 | priority_queue,greater>pq(arr,arr+n); 12 | //declared min heap so that elements should be stored in ascending order 13 | long long cost = 0; 14 | 15 | while(pq.size()>1) //till heap is not empty, run this loop 16 | { 17 | long long first = pq.top(); 18 | pq.pop(); 19 | long long second = pq.top(); 20 | pq.pop(); 21 | // take out first two minimum elements from priority queue and add them 22 | cost = cost+first+second; 23 | 24 | pq.push(first+second); // push the final result in priority queue 25 | } 26 | return cost; 27 | } 28 | 29 | 30 | int main() 31 | { 32 | long long n,i,a[100001]; 33 | cout<<"Enter the no. of elements in array : "; 34 | cin >> n; 35 | cout<<"Enter the elements.....\n"; 36 | 37 | for (i = 0; i < n; i++) 38 | { 39 | cin >> a[i]; 40 | } 41 | cout<<"\n"; 42 | 43 | cout<<"Minimum cost for connecting ropes : "< 2 | using namespace std; 3 | //function to check if cows can be allocated for the given minimum distance betwen two cows 4 | bool isAllocationPossible(vector& stall, int cows, int minDist) { 5 | int cntCows = 1;//we placed one cow at the very start of the stall 6 | int recentlyPlacedPosition = stall[0]; // get the value of the start of the array as onw cow is placed 7 | 8 | //for every other stalls check 9 | for (int i = 1; i < stall.size(); i++) { 10 | //when distance between the lastly placed cow and current stall is geater than or equal to minimum distance then allocate the cow in that stall 11 | if (stall[i] - recentlyPlacedPosition >= minDist) { 12 | cntCows++; 13 | recentlyPlacedPosition = stall[i]; 14 | } 15 | } 16 | //if all cows are placed then move current allocation is possible 17 | if (cntCows == cows) return true; 18 | return false; 19 | } 20 | int main() { 21 | vector stall = {1,2,4,8,9}; 22 | int cows=3; 23 | int ans; 24 | sort(stall.begin(),stall.end()); 25 | int low = 1, high = stall[stall.size() - 1] - stall[0]; 26 | //binary search starts 27 | while (low <= high) { 28 | int mid = (low + high) >> 1; 29 | if (isAllocationPossible(stall, cows, mid)) { 30 | res = mid; 31 | low = mid + 1; 32 | } else { 33 | high = mid - 1; 34 | } 35 | } 36 | // printing the answer 37 | cout << "The largest minimum distance is " << high << endl; 38 | return 0; 39 | } -------------------------------------------------------------------------------- /G-GreedyAlgorithms/JobSequencing_with_Deadlines.cpp: -------------------------------------------------------------------------------- 1 | //GDB CODE LINK Compile and Execute : https://onlinegdb.com/rknD8SBeO 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | //1.Sort the profit in decreasing order 8 | //2.set the job just before of before deadline Time. 9 | 10 | struct Job{ 11 | int JobNo; 12 | int deadL; 13 | int profit; 14 | }; 15 | 16 | bool comparison(Job a, Job b) 17 | { 18 | return (a.profit > b.profit); 19 | } 20 | 21 | void JobSchedulingUsingDeadline(Job a[],int n, int finaldead){ 22 | sort(a,a+n,comparison); 23 | 24 | int result[n],totalprofit=0; 25 | bool slot[n]; 26 | 27 | for(int j=0;j=0;j--){ 33 | if(slot[j]==false){ 34 | totalprofit+=a[i].profit; 35 | result[j] = i; // Add this job to result 36 | slot[j] = true; // Make this slot occupied 37 | break; 38 | } 39 | } 40 | } 41 | cout<<"Jobs Sequencing Order : "; 42 | for(int o=0;o>no; 54 | cout<<"Enter Your Final Deadline: "; 55 | cin>>finaldead; 56 | Job Arr[no]; 57 | cout<<" Profit Deadline"<<"\n"; 58 | for(int i=0;i>Arr[i].profit>>Arr[i].deadL; 62 | Arr[i].JobNo = i; 63 | } 64 | 65 | JobSchedulingUsingDeadline(Arr,no,finaldead); 66 | } 67 | 68 | 69 | -------------------------------------------------------------------------------- /L-LinkedList/S-SinglyLinkedList/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /*Program to reverse a linked list.*/ 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Node { 7 | public: 8 | int data; 9 | Node * next; 10 | Node(int data) { 11 | this -> data = data; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | class LinkedList { 17 | public: 18 | Node * head; 19 | LinkedList() { 20 | head = NULL; 21 | } 22 | //Function to reverse the linked list 23 | void reverse() { 24 | Node * current = head; 25 | Node * prev = NULL, * next = NULL; 26 | 27 | while (current != NULL) { 28 | next = current -> next; 29 | 30 | current -> next = prev; 31 | 32 | prev = current; 33 | current = next; 34 | } 35 | head = prev; 36 | } 37 | //Function to print the linked list 38 | void print() { 39 | Node * temp = head; 40 | while (temp != NULL) { 41 | cout << temp -> data << " "; 42 | temp = temp -> next; 43 | } 44 | } 45 | //Function to Insert values to Linked List 46 | void push(int data) { 47 | Node * temp = new Node(data); 48 | temp -> next = head; 49 | head = temp; 50 | } 51 | }; 52 | //Driver Function 53 | int main() { 54 | LinkedList listl; 55 | int n,k; 56 | cout << "Enter the number of nodes in linked list: "; 57 | cin >> n; 58 | cout << "Enter the nodes: "; 59 | for(int i=1;i<=n;i++){ 60 | cin >> k; 61 | listl.push(k); 62 | } 63 | 64 | cout << "Given linked list\n"; 65 | listl.print(); 66 | 67 | listl.reverse(); 68 | 69 | cout << "\nReversed Linked list \n"; 70 | listl.print(); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /H-Heap/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // To heapify a subtree rooted with node i which is 5 | // an index in arr[]. n is size of heap 6 | void heapify(int arr[], int n, int i) 7 | { 8 | int largest = i; // Initialize largest as root 9 | int l = 2 * i + 1; // left = 2*i + 1 10 | int r = 2 * i + 2; // right = 2*i + 2 11 | 12 | // If left child is larger than root 13 | if (l < n && arr[l] > arr[largest]) 14 | largest = l; 15 | 16 | // If right child is larger than largest so far 17 | if (r < n && arr[r] > arr[largest]) 18 | largest = r; 19 | 20 | // If largest is not root 21 | if (largest != i) { 22 | swap(arr[i], arr[largest]); 23 | 24 | // Recursively heapify the affected sub-tree 25 | heapify(arr, n, largest); 26 | } 27 | } 28 | 29 | // performing heap Sort 30 | void heapSort(int arr[], int n) 31 | { 32 | // Build heap (rearrange array) 33 | for (int i = n / 2 - 1; i >= 0; i--) 34 | heapify(arr, n, i); 35 | 36 | // One by one extract an element from heap 37 | for (int i = n - 1; i > 0; i--) { 38 | // Move current root to end 39 | swap(arr[0], arr[i]); 40 | 41 | // call max heapify on the reduced heap 42 | heapify(arr, i, 0); 43 | } 44 | } 45 | 46 | 47 | int main() 48 | { 49 | cout << "Enter the size of the array:" ; 50 | int n; 51 | cin >> n; 52 | cout << "Enter the elements of the array: "; 53 | int arr[n]; 54 | for(int i=0;i> arr[i]; 57 | } 58 | heapSort(arr, n); 59 | 60 | cout << "Sorted array:\n" ; 61 | for(int i=0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | int main() 7 | { 8 | //Declaration 9 | int mat[50][50],trace=0,i,j,a,b; 10 | float normal; 11 | cout<<"Enter the order of the matrix : \n"; 12 | cin>>a>>b; 13 | 14 | // Condition for trace of a matrix 15 | if(a!=b) 16 | { 17 | cout<<"invalid matrix!\n"; 18 | exit(0); 19 | } 20 | 21 | // Taking the input of elements of a matrix 22 | cout<<"Enter the elements of the matrix : \n"; 23 | for(i=0; i>mat[i][j]; 28 | } 29 | } 30 | 31 | // print matrix elements 32 | cout<<"The matrix is :"< 7 | using namespace std; 8 | 9 | // Declared a class 10 | class SortStack 11 | { 12 | public: stack st; 13 | void sort(); 14 | }; 15 | 16 | void show(stack st) 17 | { 18 | cout<<"Sorted order of Stack : "; 19 | while (!st.empty()) 20 | { 21 | cout<<" "<>t; 32 | 33 | while(t--) 34 | { 35 | SortStack *x = new SortStack(); 36 | int n; 37 | cout<<"Enter the no. of elements in stack : "; 38 | cin>>n; 39 | cout<<"Enter the elements......\n"; 40 | for(int i=0;i>k; 44 | x->st.push(k); //push elements into stack 45 | } 46 | x->sort(); //call sort function 47 | show(x->st); 48 | } 49 | } 50 | 51 | 52 | 53 | void SortStack :: sort() 54 | { 55 | priority_queue,greater>pq; // declaring min heap 56 | 57 | while(!st.empty()) // run the loop till the stack is not empty 58 | { 59 | pq.push(st.top()); 60 | st.pop(); 61 | } 62 | 63 | while(!pq.empty()) // run the loop till the min heap is not empty 64 | { 65 | st.push(pq.top()); 66 | pq.pop(); 67 | } 68 | } -------------------------------------------------------------------------------- /Q-Queue/QueueUsingStacks.cpp: -------------------------------------------------------------------------------- 1 | // IMPLEMENTATION OF QUEUE USING TWO STACKS 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | class queue{ 9 | stack s1; 10 | stack s2; 11 | public: 12 | //SIMPLY PUSH THE ELEMENT IN STACK1 13 | void enqueue(int x){ 14 | s1.push(x); 15 | } 16 | 17 | int dequeue(){ 18 | if(s1.empty() && s2.empty()){ 19 | cout << "Error" << endl; 20 | exit(0); 21 | } 22 | //REVERESE STACK1 BY USING STACK2 23 | if(s2.empty()){ 24 | while(!s1.empty()){ 25 | s2.push(s1.top()); 26 | s1.pop(); 27 | } 28 | } 29 | //THEN SIMPLY POPPING THE FIRST ELEMENT OF STACK2, i.e. THE LAST ELEMENT OF STACK1 30 | int topval = s2.top(); 31 | s2.pop(); 32 | 33 | return topval; 34 | } 35 | 36 | // RETURNS TRUE IF BOTH STACKS ARE EMPTY 37 | bool empty(){ 38 | if(s1.empty() && s2.empty()){ 39 | return true; 40 | } 41 | else 42 | return false; 43 | } 44 | }; 45 | 46 | /* 47 | DRIVER PROGRAM 48 | 49 | Queue q : 50 | 1 | 2 | 3 | 4 51 | 52 | */ 53 | int main(){ 54 | queue q; 55 | q.enqueue(1); 56 | q.enqueue(2); 57 | q.enqueue(3); 58 | q.enqueue(4); 59 | cout << q.dequeue() << endl; 60 | cout << q.dequeue() << endl; 61 | cout << q.dequeue() << endl; 62 | cout << q.dequeue() << endl; 63 | if(q.empty()) 64 | cout << "Queue is empty" << endl; 65 | else 66 | cout << "Queue not empty" << endl; 67 | return 0; 68 | } -------------------------------------------------------------------------------- /D-DynamicProgramming/Minimum_insertions_form_palindrome.cpp: -------------------------------------------------------------------------------- 1 | // An LCS based program to find minimum number 2 | // insertions needed to make a string palindrome 3 | #include 4 | using namespace std; 5 | 6 | 7 | // Returns length of LCS for X[0..m-1], Y[0..n-1]. 8 | int lcs( string X, string Y, int m, int n ) 9 | { 10 | int L[m+1][n+1]; 11 | int i, j; 12 | 13 | /* Following steps build L[m+1][n+1] in bottom 14 | up fashion. */ 15 | for (i = 0; i <= m; i++) 16 | { 17 | for (j = 0; j <= n; j++) 18 | { 19 | if (i == 0 || j == 0) 20 | L[i][j] = 0; 21 | 22 | else if (X[i - 1] == Y[j - 1]) 23 | L[i][j] = L[i - 1][j - 1] + 1; 24 | 25 | else 26 | L[i][j] = max(L[i - 1][j], L[i][j - 1]); 27 | } 28 | } 29 | 30 | /* L[m][n] contains length of LCS for X[0..n-1] 31 | and Y[0..m-1] */ 32 | return L[m][n]; 33 | } 34 | 35 | void reverseStr(string& str) 36 | { 37 | int n = str.length(); 38 | 39 | // Swap character starting from two 40 | // corners 41 | for (int i = 0; i < n / 2; i++) 42 | swap(str[i], str[n - i - 1]); 43 | } 44 | 45 | // LCS based function to find minimum number of 46 | // insertions 47 | int findMinInsertionsLCS(string str, int n) 48 | { 49 | // Create another string to store reverse of 'str' 50 | string rev = ""; 51 | rev = str; 52 | reverseStr(rev); 53 | 54 | // The output is length of string minus length of lcs of 55 | // str and it reverse 56 | return (n - lcs(str, rev, n, n)); 57 | } 58 | 59 | // Driver code 60 | int main() 61 | { 62 | string str; 63 | cout<<"Enter string"<>str; 65 | cout << findMinInsertionsLCS(str, str.length()); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /R-Recursion/Types of Recursion/LinearRecursion.cpp: -------------------------------------------------------------------------------- 1 | #include //including libraries 2 | using namespace std; 3 | int Max_num(int n,int m); //declaring function earlier so that it will not give error. 4 | int rec_num( int *arr, int n) // declaring function rec_num() with two arguments i.e. arr and n 5 | { 6 | // declaring base condition 7 | if (n == 1) 8 | { 9 | return arr[0]; 10 | } 11 | // calling recursively the rec_num function with decreasing the size of array by 1 and also returning the result after backtracking the function. 12 | return Max_num (rec_num (arr, n-1), arr[n-1]); 13 | } 14 | // function which is declare above for getting the maximum number 15 | int Max_num (int n, int m) 16 | { 17 | if (n > m) 18 | return n; 19 | return m; 20 | } 21 | int main () 22 | { //printing for taking input from the user 23 | cout<<"Enter the size of array"; 24 | //declaring the size of array 25 | int n; 26 | //taking the size of array from the user in form of input 27 | cin>>n; 28 | //declaring the array 29 | int arr[n]; 30 | //printing the result for getting elements of array from the user 31 | cout<<"Enter the elements of array"; 32 | //taking elements of array from the user in form of for loop 33 | for(int i=0;i>arr[i]; 36 | } 37 | //declaring the integer type variable max and calling the rec_num function with array and their size 38 | int max = rec_num(arr, NUM); // call function 39 | 40 | cout<<"The maximum number is: "< 2 | 3 | using namespace std; 4 | 5 | #define ll long long int 6 | 7 | void Intersection_array(int a[], int b[], int n, int m) 8 | { 9 | int i = 0, j = 0; // Initialize the pointers with zero 10 | 11 | while (i < n && j < m) 12 | { 13 | if (a[i] == b[j]) // if equal we found one element to be added in our intersection set 14 | { 15 | cout << a[i] << " "; 16 | i++; 17 | j++; 18 | } 19 | else if (a[i] < b[j]) // If element in array a is less than array b element then we increase i pointer. 20 | { 21 | i++; 22 | } 23 | else // If element in array b is less than array a element then we increase j pointer. 24 | { 25 | 26 | j++; 27 | } 28 | } 29 | } 30 | 31 | int main() 32 | 33 | { 34 | ios_base::sync_with_stdio(false); 35 | cout.tie(0); 36 | cin.tie(0); 37 | int n, m; 38 | printf("\n\nEnter the size of array A : "); 39 | cin >> n; 40 | printf("\nEnter the size of array B : "); 41 | cin >> m; 42 | int a[n], b[m]; 43 | printf("\n\nEnter array A : "); 44 | for (int i = 0; i < n; i++) 45 | { 46 | cin >> a[i]; 47 | } 48 | printf("\nEnter array B : "); 49 | for (int i = 0; i < m; i++) 50 | { 51 | cin >> b[i]; 52 | } 53 | 54 | // Sorting the both array in ascending order. 55 | sort(a, a + n); 56 | sort(b, b + m); 57 | 58 | cout << "\n\nThe intersection of array is : "; 59 | Intersection_array(a, b, n, m); 60 | cout << "\n\n"; 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /B-Backtracking/RatInMaze.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | //------------------------------------PROBLEM :Rat In Maze (Maze Runner LOL :) ---------------------------------- 4 | #include 5 | using namespace std; 6 | 7 | bool ratInMaze(char maze[10][10],int soln[][10],int i,int j,int m,int n){ 8 | 9 | //Hits the base case path found , prints path 10 | if(i==m && j==n){ 11 | soln[m][n]=1; 12 | for(int i=0;i<=m;i++){ 13 | for (int j = 0; j <=n; j++) 14 | { 15 | cout<m || j>n){ 25 | return false; 26 | } 27 | 28 | //IF rat encounters a block 29 | if(maze[i][j]=='X'){ 30 | return false; 31 | } 32 | 33 | //assuming solution exits throush current cell and going further 34 | soln[i][j]=1; 35 | 36 | 37 | bool rightSuccess = ratInMaze(maze,soln,i,j+1,m,n); 38 | bool downSuccess = ratInMaze(maze,soln,i+1,j,m,n); 39 | 40 | //Backtracking 41 | soln[i][j]=0; 42 | 43 | if(rightSuccess|| downSuccess){ 44 | return true; 45 | } 46 | return false; 47 | 48 | } 49 | 50 | 51 | int main() 52 | { 53 | ios_base :: sync_with_stdio(false); 54 | cin.tie(nullptr); 55 | cout.tie(nullptr); 56 | 57 | char maze[10][10]={ 58 | "0000", 59 | "000X", 60 | "000X", 61 | "0X00", 62 | }; 63 | 64 | int soln[10][10]={0}; 65 | int m=4,n=4; //number of rows and column 66 | 67 | bool isPathfound= ratInMaze(maze,soln,0,0,m-1,n-1); 68 | 69 | if(isPathfound) 70 | cout<<"Path Found"< 2 | using namespace std; 3 | // node class for linked list 4 | class node{ 5 | public: 6 | int data; 7 | node* next; 8 | //constructor which will assign the given value to node and set next pointer to null 9 | node(int key){ 10 | data = key; 11 | next = nullptr; 12 | } 13 | }; 14 | // Function will create a linked list, new nodes will be added at the end of the list 15 | void create(node** head, int val){ 16 | node* newnode = new node(val); 17 | node* ptr = *head; 18 | if(ptr == nullptr){ 19 | *head = newnode; 20 | } 21 | else{ 22 | while(ptr->next != nullptr){ 23 | ptr = ptr->next; 24 | } 25 | ptr->next = newnode; 26 | } 27 | } 28 | // Function will find the middle element of the linked list 29 | int middle(node* temp_head){ 30 | node* slow = temp_head, *fast = temp_head; 31 | while(fast && fast->next){ 32 | slow = slow->next; 33 | fast = fast->next->next; 34 | } 35 | return slow->data; 36 | } 37 | int main() 38 | { 39 | int no_of_nodes; 40 | cout<<"Enter the number of nodes in the linked list\n"; 41 | cin>>no_of_nodes; 42 | node* ll = nullptr; //creating head node and setting to null 43 | //creating the linked list 44 | cout<<"Enter the values in the linked list\n"; 45 | while(no_of_nodes--){ 46 | int val; 47 | cin>>val; 48 | create(&ll, val); 49 | } 50 | cout<<"The middle element of the linked list is: "< ## What is Ceil Value in BST ? 5 | ``` 6 | Let suppose we are given a key , and we have to find Ceil value with respect of the key value , present int our BST. 7 | ``` 8 | **The Smallest value present in BST which is just greater or equal to the the key given is called Ceil value** 9 | ___ 10 | ## EXAMPLE => 11 | ![image](https://user-images.githubusercontent.com/77873383/159840232-4f926f98-2c2e-4051-a01c-4cea440ff06c.png) 12 | 13 | 14 | For the given BST , as shown above , if
15 | 16 | **1. key= 7 >> Ceil value=7**
17 | **2. key= 12 >> Ceil value=13**
18 | **1. key= 5 >> Ceil value=6** 19 | 20 |
21 | 22 | ****By default if Ceil value not present in BST for the given Key, then Code will return -1 and if the node's value and key value is same then return node's value as Ceilvalue .** 23 | 24 | --- 25 | 26 | ## Approach to find Ceil Value in BST: 27 | > A easy approach is to traverse the BST using any traversale method(Inorder or Preorder or Postorder) and keep updating the closest Greater or same element. 28 | 29 | ```txt 30 | 1. Start from root 31 | 2. if root->data ==key return node's data as Ceil value 32 | 3. else if root->data>key then Ceil value must be at left subtree, Go to root->left 33 | 4. Else ceil value must be at root's right subtree , Go to root->right 34 | 5. If after traversal Ceil value is not found then return -1. 35 | ``` 36 | --- 37 | 38 | ## Time & Space Complexity : 39 | > **Time Complexity :** O(h) for the traversal , [h is height of BST]
40 | **Space Complexity :** No extra/auxillary space required. 41 | -------------------------------------------------------------------------------- /S-Stack/Bracket Balancing Using Stack/README.md: -------------------------------------------------------------------------------- 1 | # Bracket Balancing Using Stack 2 | 3 | Here we will discuss how to check the balanced brackets using stacks. We not only check the opening and closing brackets but also check the ordering of brackets. For an example we can say that the expression **"[{} () {()}]"** it is correct, but **"{[}]"** it is not correct. 4 | ``` 5 | Input: Some expression with brackets "{()}[]" 6 | Output: They are balanced 7 | ``` 8 | 9 | ## Algorithim 10 | ``` 11 | Step 1: Define a stack to hold brackets 12 | Step 2: Traverse the expression from left to right 13 | Step 2.1: If the character is opening bracket (, or { or [, then push it into stack 14 | Step 2.2: If the character is closing bracket ), } or ] Then pop from stack, and if the popped character is matched with the starting bracket then it is ok. otherwise they are not balanced. 15 | Step 3: After traversal if the starting bracket is present in the stack then it is not balanced. 16 | ``` 17 | #### Below is representation of above approach 18 | 19 | ![ForBalancedParanthesisInanExoression1](https://user-images.githubusercontent.com/85986613/157252818-fc5e6215-255d-4cc2-bf1e-c93ea46d9269.png) 20 | 21 | 22 | **Time Complexity:** O(n) 23 | **Auxiliary Space:** O(n) for stack. 24 | 25 | ### Test Case 26 | 27 | ![image](https://user-images.githubusercontent.com/85986613/158027991-5b591672-c5cc-42a5-af19-82eb57ab11d7.png) 28 | 29 | ![image](https://user-images.githubusercontent.com/85986613/158028015-ac57daa1-3753-4e10-8aba-2cedf5bf6452.png) 30 | 31 | ![image](https://user-images.githubusercontent.com/85986613/158028121-a6cafb9c-d15f-4cb5-8d03-71be620be167.png) 32 | -------------------------------------------------------------------------------- /A-Array/FirstNegativeInEveryWindow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vectorprintFirstNegativeInteger(vectorA, int n ,int k) { 4 | //---------Finding the first negative in k size size window in the vector USING SLIDING WINDOW APPROACH------ 5 | 6 | //deque to make a movable window 7 | deque q; 8 | 9 | //vector of every first negative integer in k size window 10 | vector ans; 11 | 12 | //the first loop is made to store something in queue 13 | //else everytime 0 will be stored as queue would be empty 14 | for (int i = 0; i < k; i++) { 15 | //Index of every -ve integer pushed in deque 16 | if (A[i] < 0) { 17 | q.push_back(i); 18 | } 19 | } 20 | //first -ve integer in vector ans by getting front element of deque 21 | if (q.size()> 0) { 22 | ans.push_back(A[q.front()]); 23 | } 24 | //0 is pushed that is there is no -ve int in k size window 25 | else { 26 | ans.push_back(0); 27 | } 28 | for (int i = k; i < A.size(); i++) { 29 | //the last index of window is reached or passed if i - index in queue >=k 30 | if (!q.empty() && i - q.front() >= k) { 31 | //making space for next window 32 | q.pop_front(); 33 | } 34 | if (A[i] < 0) { 35 | q.push_back(i); 36 | } 37 | if (q.size() > 0) { 38 | ans.push_back(A[q.front()]); 39 | } 40 | else { 41 | ans.push_back(0); 42 | } 43 | } 44 | return ans; 45 | } 46 | int main() 47 | { 48 | int n = 8; 49 | vectorA = { 12,-1,-7,8,-15,30,16,28 }; 50 | int k = 3; 51 | vectorans = printFirstNegativeInteger(A, n, k); 52 | for (auto x : ans) { 53 | cout << x << " "; 54 | } 55 | /*OUTPUT 56 | -1 -1 -7 -15 -15 0 57 | */ 58 | 59 | } 60 | -------------------------------------------------------------------------------- /S-Stack/TheCelebrityProblem/CelebrityProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int CelebrityProblem(vector>& v1) 5 | { 6 | stack s1; 7 | 8 | for (int i = 0; i1) 12 | { 13 | int temp1 = s1.top(); 14 | s1.pop(); 15 | 16 | int temp2 = s1.top(); 17 | s1.pop(); 18 | 19 | if (v1[temp1][temp2]) 20 | s1.push(temp2); 21 | 22 | else 23 | s1.push(temp1); 24 | } 25 | 26 | int potential_celeb=s1.top(); 27 | 28 | for(int i=0; i>n>>m; 49 | vector> v; 50 | 51 | for (int i = 0; i < n; i++) 52 | { 53 | int x; 54 | vectortemp; 55 | for(int j=0;j>x; 58 | temp.push_back(x); 59 | } 60 | v.push_back(temp); 61 | 62 | } 63 | 64 | int celebrity = CelebrityProblem(v); 65 | 66 | if(celebrity == -1) 67 | cout<<"No Celebrity Exists!"<
7 | 8 | ![](https://media.geeksforgeeks.org/wp-content/uploads/BSTSearch.png) 9 | 10 | ### Approach: 11 | For Every Node We have to check that all values present in Left-Subtree will be less than parent and all node values present at right of parent are greater than parent. 12 | 13 | ### Algorithm: 14 | - For every Node We take a certain valid range and between that range node value will be lie to fullfill to be Valid BST 15 | Initial Range of Parent/Root Node is taken as 16 | ```[INT_MIN, INT_MAX]``` 17 | 18 | - For every **Left Child** the range will be ```[INT_MIN, parent->data]``` 19 | - For every **Right Child** the range will be 20 | ```[parent->data, INT_MAX]``` 21 | - During Recursion if any Node disagreed these Condition retuen false . 22 | 23 | ![validBST](https://user-images.githubusercontent.com/77873383/164070536-557900b0-8054-4c5a-a0f8-6a534f9ff141.png) 24 | 25 | 26 | ### Pseudo Code : 27 | ```cpp 28 | bool validBST(Node*root, long minVal,long maxVal){ 29 | if(root==NULL)return true; //empty Tree is valid 30 | if(root->data>=maxVal or root->data<=minVal)return false; 31 | 32 | return valid(root->left,minVal,root->data)and valid(root->right,root->data,maxVal);//1st Left recursion Then right 33 | } 34 | ``` 35 | ### Time & Space Complexity: 36 | - Time Complexity : O(N) 37 | - Space Complexity : O(1) 38 | -------------------------------------------------------------------------------- /T-Tree/B-BinarySearchTree/Floor Value in BST/Readme.md: -------------------------------------------------------------------------------- 1 | # Floor Value in Binary Seacrh Tree(BST) 2 | ___ 3 | 4 | > ## What is Floor Value in BST ? 5 | ``` 6 | Let suppose we are given a key , and we have to find floor value with respect of the key value , present int our BST. 7 | ``` 8 | **The greatest value present in BST which is just smaller than the key given is called Floor value** 9 | ___ 10 | 11 | # EXAMPLE => 12 | ![image](https://user-images.githubusercontent.com/77873383/159840232-4f926f98-2c2e-4051-a01c-4cea440ff06c.png) 13 | 14 | 15 | For the given BST , as shown above , if
16 | 17 | **1. key= 7 >> Floor value=6**
18 | **2. key= 12 >> Floor value=10**
19 | **1. key= 3 >> Floor value=2** 20 | 21 |
22 | 23 | ****By default if floor value not present in BST for the given Key, then Code will return -1 and if the node's value and key value is same then return node's value as Floor value .** 24 | 25 | --- 26 | 27 | # Approach to find Floor Value in BST: 28 | > A easy approach is to traverse the BST using any traversale method(Inorder or Preorder or Postorder) and keep updating the closest smaller or same element. 29 | 30 | 31 | ```txt 32 | 1. Start from root 33 | 2. if root->data ==key return node's data as floor value 34 | 3. else if root->data>key then floor value must be at left subtree, Go to root->left 35 | 4. Else floor value must be at root's right subtree , Go to root->right 36 | 5. If after traversal floor value is not found then return -1. 37 | ``` 38 | --- 39 | 40 | # Time & Space Complexity : 41 | > **Time Complexity :** O(h) for the traversal , [h is height of BST]
42 | **Space Complexity :** No extra/auxillary space required. 43 | -------------------------------------------------------------------------------- /S-Strings/Strings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | string s0("Hello world"); 8 | string s1="Hello world"; 9 | 10 | string s2(s1); 11 | 12 | string s3=s2; 13 | 14 | char a[]={'a','b','c','\0'}; 15 | string s4=a; 16 | 17 | cout<0 or <0 checks strings lexi 35 | 36 | if (s1>s0) 37 | cout<<"Mango is lexi greater than Apple"< 2 | using namespace std; 3 | 4 | 5 | struct Node 6 | { 7 | int value; 8 | struct Node *left, *right; 9 | struct Node *root; 10 | 11 | }; 12 | 13 | struct Node *create ( int val ) 14 | { 15 | 16 | struct Node *p = new Node; 17 | p->value = val; 18 | p->left = p->right = NULL; 19 | p->root = NULL; 20 | return p; 21 | } 22 | 23 | struct Node* tree(Node* t, int v){ 24 | if (t == NULL) 25 | return create(v); 26 | 27 | if (v < t->value) 28 | t->left = tree(t->left, v); 29 | else 30 | t->right = tree(t->right, v); 31 | 32 | return t; 33 | } 34 | 35 | ///------------Height of the binary tree------------/// 36 | int height( struct Node* p ) 37 | { 38 | if ( p == NULL ) 39 | return 0; 40 | if ( p->left == NULL && p->right == NULL ) 41 | return 1; 42 | else{ 43 | int l = height( p->left ); 44 | int r = height( p->right ); 45 | return 1 + (l > r ? l : r ); 46 | } 47 | } 48 | 49 | 50 | 51 | // Driver functions 52 | int main() 53 | { 54 | int size; 55 | Node *root = new Node; 56 | root = NULL; 57 | 58 | cout<<"Enter the size of array : "; 59 | cin>>size; 60 | 61 | int a[size]; 62 | 63 | cout<<"Enter the elements in array : "; 64 | for(int i=0;i>a[i]; 67 | } 68 | 69 | for(int i = 0; i < size; i++) 70 | { 71 | root = tree(root, a[i]); 72 | } 73 | 74 | cout << "\n Height of tree: "< 3 | #include 4 | using namespace std; 5 | 6 | //Make a class to store type of data in queue 7 | 8 | class Person{ 9 | public: 10 | string name; 11 | int age; 12 | 13 | //Person constructor ---Empty one / Default one 14 | Person(){ 15 | 16 | } 17 | //Person constructor ---Parameters provided 18 | Person(string n,int a){ 19 | 20 | name=n; 21 | age=a; 22 | } 23 | 24 | }; 25 | 26 | //Person comparator to compare two persons on the basis of their age 27 | class PersonCompare{ 28 | public: 29 | bool operator()(Person A, Person B){ 30 | return A.age < B.age; 31 | } 32 | }; 33 | 34 | 35 | int main(){ 36 | 37 | //---Pq of type Person--------- 38 | //--------Vector to store data in pq------ 39 | //--Use person compare to arrange data in heap------- 40 | 41 | priority_queue, PersonCompare> pq; 42 | 43 | int n,age; 44 | string name; 45 | 46 | cin>>n; 47 | cout<<"Name Age"<>name>>age; 50 | 51 | Person p(name,age); 52 | pq.push(p); 53 | } 54 | 55 | //Extract the top 3 elements from the PQ with greater age 56 | 57 | int k=3; 58 | 59 | for(int i=0;i 21 | using namespace std; 22 | 23 | vectorprimeSumDivision(int n) 24 | { 25 | vectorsieve(n, true); // create a sieve 26 | 27 | sieve[0] = false; // mark 0 and 1 as false as 0 and 1 are non prime 28 | sieve[1] = true; 29 | 30 | for (int i=2; i*i>num; 53 | 54 | vectorans=primeSumDivision(num); 55 | cout< 4 | using namespace std; 5 | 6 | //Function Declaration 7 | bool subsetSum(int arr[], int sum, int n); 8 | 9 | // Driver Code 10 | int main() 11 | { 12 | int arr[] = {1,5,11,5}; 13 | int n = sizeof(arr) / sizeof(arr[0]); 14 | 15 | int sum = 0; 16 | for (int i = 0; i < n; i++) 17 | sum += arr[i]; 18 | 19 | if (sum % 2 != 0) // Checking if the sum of array is odd 20 | cout << "false"; 21 | 22 | else if (sum % 2 == 0) // Checking if the sum of the array is even 23 | subsetSum(arr, sum / 2, n)?cout<<"True":cout<<"False"; 24 | 25 | return 0; 26 | } 27 | 28 | // subsetSum function 29 | bool subsetSum(int arr[], int sum, int n) 30 | { 31 | int t[n + 1][sum + 1]; //Initializing the table 32 | for (int i = 0; i < n + 1; i++) 33 | { 34 | for (int j = 0; j < sum + 1; j++) 35 | { 36 | if (i == 0) 37 | t[i][j] = false; //Initializing the first row as false 38 | 39 | if (j == 0) 40 | t[i][j] = true; //Initializing the first column as true 41 | } 42 | } 43 | 44 | for (int i = 1; i <= n; i++) 45 | { 46 | for (int j = 1; j <= sum; j++) 47 | { 48 | if (arr[i - 1] <= j) 49 | t[i][j] = t[i][j - arr[i - 1]] || t[i - 1][j]; 50 | else 51 | t[i][j] = t[i - 1][j]; 52 | } 53 | } 54 | 55 | return t[n][sum]; //returning the result 56 | } 57 | 58 | /* 59 | Complexity: 60 | 61 | Time Complexity: O(sum*n) 62 | 63 | Auxiliary Space: O(sum*n) 64 | 65 | */ -------------------------------------------------------------------------------- /G-Graphs/ArticulationPoints.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | #define V 5 5 | #define pb push_back 6 | 7 | unordered_map> adj; 8 | 9 | void DFS(int u,vector& disc,vector& low,vector& parent,vector& articulation_Point) 10 | { 11 | static int time = 0; 12 | disc[u] = low[u] = time; 13 | time+=1; 14 | int children = 0; 15 | 16 | for(int v: adj[u]) 17 | { 18 | if(disc[v]==-1) //If v is not visited 19 | { 20 | children += 1; 21 | parent[v] = u; 22 | DFS(v,disc,low,parent,articulation_Point); 23 | low[u] = min(low[u],low[v]); 24 | 25 | if(parent[u]==-1 and children>1) //Case-1: U is root 26 | articulation_Point[u] = true; 27 | 28 | if(parent[u]!=-1 and low[v]>=disc[u]) //Case-2: Atleast 1 component will get separated 29 | articulation_Point[u] = true; 30 | } 31 | else if(v!=parent[u]) //Ignore child to parent edge 32 | low[u] = min(low[u],disc[v]); 33 | } 34 | } 35 | 36 | void findAPs_Tarjan() 37 | { 38 | vector disc(V,-1),low(V,-1),parent(V,-1); 39 | vector articulation_Point(V,false); //Avoids cross-edge 40 | 41 | for(int i=0;i 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int maxProfit(vector& v){ 9 | 10 | int maxd=0; //maximum profit initially 0 as if we can not earn profit we have to return 0 11 | int itr=INT_MAX; //buying process should be minimum so if initialize it as max int 12 | 13 | for(int i=0;iv[i]){ // check whether the it's cost price is greater then previous cost price 15 | itr=v[i];//set minimum local buying cost 16 | } 17 | else if(v[i]-itr>maxd){ //check whether difference between current minimum cost price and current selling price is maximum or not 18 | maxd=v[i]-itr;//set local maximum profit (difference of selling price and buying price is profit) 19 | //Note: from here we can also find buying and selling cost as V[i] selling and itr is buying costs here 20 | } 21 | } 22 | return maxd;//returning global maximum profit 23 | 24 | } 25 | //Time complexity: O(n) 26 | //Space complexity: O(1) 27 | 28 | int main(){ 29 | vector v={}; 30 | cout<<"Enter number of Elements:"<>n; 33 | cout<<"Enter Elements:"<>ele; 37 | v.push_back(ele); 38 | } 39 | cout<<"input array: {"; 40 | for(int i: v){ 41 | cout< 3 | #include 4 | using namespace std; 5 | #define pb push_back 6 | void solve(){ 7 | int v,e,no; 8 | cout<<"Enter the vertices and number of edges in graph"<>v>>e; 10 | vector> g(v); 11 | cout<<"Enter Edges A-B"<>x>>y; 15 | g[x].pb(y); 16 | g[y].pb(x); 17 | } 18 | 19 | int res[v]; //Resultant Array to check which of the nodes are colored 20 | bool available[v]; //Available array to check availability of color 21 | res[0]=0; // Initial node is colored 0 22 | 23 | for(int i=1;i 3 | #include 4 | 5 | using namespace std; 6 | int main(){ 7 | 8 | 9 | //Assign 5 vectors value 10 10 | vector a(5,10); 11 | vector b(a.begin(),a.end()); 12 | vector d{1,2,3,4,5}; 13 | 14 | //using simple for loop 15 | for(int i=0;i::iterator; 20 | for(auto it=b.begin();it!=b.end();it++) 21 | cout<<*it+10<<" "; 22 | cout< v; 31 | int s,no; //s size 32 | cin>>s; 33 | 34 | for(int i=0;i>no; 37 | v.push_back(no); 38 | } 39 | 40 | for(int c:v) 41 | cout< 3 | 4 | using namespace std; 5 | 6 | 7 | void heapify(int arr[], int n, int i) 8 | { 9 | int largest = i; // Initialize largest as root 10 | int l = 2 * i + 1; // left = 2*i + 1 11 | int r = 2 * i + 2; // right = 2*i + 2 12 | 13 | // If left child is larger than root 14 | if (l < n && arr[l] > arr[largest]) 15 | largest = l; 16 | 17 | // If right child is larger than largest so far 18 | if (r < n && arr[r] > arr[largest]) 19 | largest = r; 20 | 21 | // If largest is not root 22 | if (largest != i) { 23 | swap(arr[i], arr[largest]); 24 | 25 | // Recursively heapify the affected sub-tree 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | 30 | // Function to build a Max-Heap from the given array 31 | void buildHeap(int arr[], int n) 32 | { 33 | // Index of last non-leaf node 34 | int startIdx = (n / 2) - 1; 35 | 36 | // Perform reverse level order traversal 37 | // from last non-leaf node and heapify 38 | // each node 39 | for (int i = startIdx; i >= 0; i--) { 40 | heapify(arr, n, i); 41 | } 42 | } 43 | 44 | // A utility function to print the array 45 | // representation of Heap 46 | void printHeap(int arr[], int n) 47 | { 48 | cout << "Array representation of Heap is:\n"; 49 | 50 | for (int i = 0; i < n; ++i) 51 | cout << arr[i] << " "; 52 | cout << "\n"; 53 | } 54 | 55 | int main() 56 | { 57 | cout << "Enter the size of the array:" ; 58 | int n; 59 | cin >> n; 60 | cout << "Enter the elements of the array: "; 61 | int arr[n]; 62 | for(int i=0;i> arr[i]; 65 | } 66 | 67 | buildHeap(arr, n); 68 | 69 | printHeap(arr, n); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /T-Tree/F-FenwickTree/K_Query.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define lli long long int 4 | #include 5 | using namespace std; 6 | struct P{ 7 | lli v,idx; 8 | }; 9 | struct event{ 10 | lli value; 11 | lli l,r,ind; 12 | }; 13 | bool com(P a,P b){ 14 | return a.v>b.v; 15 | } 16 | bool compare(event a,event b){ 17 | return a.value>b.value; 18 | } 19 | 20 | lli BIT[300005]; 21 | lli ans[200005]; 22 | //the update function 23 | void update(lli p,lli val){ 24 | while(p<300005){ 25 | BIT[p]+=val; 26 | p+=p&(-p); 27 | } 28 | } 29 | //the query function 30 | lli queri(lli p){ 31 | lli sum=0; 32 | while(p){ 33 | sum+=BIT[p]; 34 | p-=p&(-p); 35 | } 36 | return sum; 37 | } 38 | int main() 39 | { 40 | lli n; 41 | scanf("%lld",&n); 42 | P a[n+1]; 43 | for(int i=1;i<=n;i++){ 44 | scanf("%lld",&a[i].v); 45 | a[i].idx=i; 46 | } 47 | //sorting needed so that the bits where they are stored can be maintained according to the index 48 | sort(a+1,a+n+1,com); 49 | lli q; 50 | scanf("%lli",&q); 51 | event t[q]; 52 | for(int i=0;i>t[i].l>>t[i].r>>t[i].value; 55 | t[i].ind=i; 56 | } 57 | //the qeueries are sorted so that there are no overlaps 58 | sort(t,t+q,compare); 59 | lli g=1; 60 | for(int i=0;it[i].value) 63 | //the update query 64 | {update(a[g].idx,1);g++;} 65 | //the sum query 66 | ans[t[i].ind]=queri(t[i].r)-queri(t[i].l-1); 67 | } 68 | for(int i=0;i 8 | using namespace std; 9 | 10 | // Subsets function with template to take any data type. 11 | template 12 | vector> subsets(vector arr) { 13 | 14 | int s = arr.size(); 15 | vector>res((1 << s)); // create result vector with size = (1< 2^(array.size()) 16 | for (int mask = 0; mask < (1 << s); mask++) // Loop on 2^(array.size()) 17 | { 18 | // Loop on array size to check if each i of the current mask is 1 or not. 19 | for (int i = 0; i < s; i++) { 20 | if ((mask >> i) & 1) // is the i-th bit of this mask 1? 21 | res[mask].push_back(arr[i]); // if ith bit of this mask is 1 then push array element in index i in result vector. 22 | } 23 | } 24 | return res; 25 | } 26 | 27 | // Function to print 2D vector (result vector for subsets) 28 | template 29 | void printVec(vector> vec) { 30 | for (int i = 0; i < vec.size(); i++) { 31 | cout << '{'; 32 | for (int j = 0; j < vec[i].size(); j++) { 33 | cout << vec[i][j]; 34 | if (j != vec[i].size() - 1) 35 | cout << ", "; 36 | } 37 | cout << "}\n"; 38 | } 39 | } 40 | 41 | int main() { 42 | 43 | ios::sync_with_stdio(false), cin.tie(), cout.tie(); 44 | 45 | // Test 1 46 | vector>res1; 47 | res1 = subsets({ 1, 2, 3 }); 48 | printVec(res1); 49 | 50 | cout << "\n-----------------------------------------\n"; 51 | 52 | // Test 2 53 | vector>res2; 54 | res2 = subsets({ 'a', 'b', 'c' }); 55 | printVec(res2); 56 | 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /D-DynamicProgramming/CoinChange.cpp: -------------------------------------------------------------------------------- 1 | //COIN CHANGE 2 | 3 | #include 4 | using namespace std; 5 | 6 | int minCoins(int currentCoin,int amount,vector&coins,int n,vector>&v) 7 | { 8 | //base conditions 9 | if(amount == 0) return 0; 10 | 11 | if(currentCoin >= n) return 100001; 12 | 13 | //if value is already present in the vector v ,then extract from it, no need to make recursive calls for it 14 | if(v[currentCoin][amount] != -1) 15 | return v[currentCoin][amount]; 16 | 17 | //Explore the two possibilities :- 1)take the coin ,2)don't take the coin 18 | int consider = 100001; 19 | 20 | //we'll consider a coin only when its denomination is either less than or equal to the amount 21 | if(coins[currentCoin] <= amount) 22 | consider = 1 + minCoins(currentCoin,amount-coins[currentCoin],coins,n,v); 23 | 24 | int notConsider = minCoins(currentCoin+1,amount,coins,n,v); 25 | 26 | //storing the answer for the current coordinate in v,so that we can use it in future 27 | v[currentCoin][amount] = min(consider,notConsider); 28 | return v[currentCoin][amount]; 29 | } 30 | int coinChange(vector& coins, int amount) 31 | { 32 | int n = coins.size(); 33 | 34 | vector>v(n,vector(amount+1,-1)); 35 | 36 | int ans = minCoins(0,amount,coins,n,v); 37 | 38 | if(ans >= 100001) return -1; 39 | 40 | return ans; 41 | } 42 | 43 | int main() 44 | { 45 | int n; 46 | cin>>n; 47 | vectorcoins(n,0); 48 | for(int i=0;i>coins[i]; 50 | 51 | int amount; 52 | cin>>amount; 53 | 54 | cout< 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | void TopologicalBfs(vector adj[], int N) 10 | { 11 | 12 | vector inDegree(N, 0); 13 | 14 | for (int i = 0; i < N; i++) 15 | { 16 | for (int j = 0; j < adj[i].size(); j++) 17 | { 18 | inDegree[adj[i][j]]++; 19 | } 20 | } 21 | 22 | queue q; 23 | 24 | for (int i = 0; i < N; i++) 25 | { 26 | if (inDegree[i] == 0) 27 | { 28 | q.push(i); 29 | } 30 | } 31 | 32 | while (!q.empty()) 33 | { 34 | int cur = q.front(); 35 | q.pop(); 36 | cout << cur << " "; 37 | for (int i = 0; i < adj[cur].size(); i++) 38 | { 39 | inDegree[adj[cur][i]]--; 40 | if (inDegree[adj[cur][i]] == 0) 41 | { 42 | q.push(adj[cur][i]); 43 | } 44 | } 45 | } 46 | } 47 | }; 48 | // Driver program to test above function 49 | int main() 50 | { 51 | 52 | int T; 53 | cin >> T; 54 | while (T--) 55 | { 56 | int N, E; 57 | cin >> E >> N; 58 | int u, v; 59 | 60 | vector adj[N]; 61 | 62 | for (int i = 0; i < E; i++) 63 | { 64 | cin >> u >> v; 65 | adj[u].push_back(v); 66 | } 67 | 68 | Solution obj; 69 | obj.TopologicalBfs(adj, N); 70 | cout << endl; 71 | } 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /H-HashMap/Map.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Please read the README.md before going through the code for better understanding for maps 3 | 4 | 5 | #include 6 | #include 7 | #include // The header file specifically made for STL-Maps 8 | 9 | #include // A High utility header file generally used in Competitive Programming contains 100's header file 10 | 11 | using namespace std; 12 | 13 | void print(map &m) 14 | { 15 | cout< TIME COMPLEXITY 19 | } 20 | 21 | } 22 | 23 | int main() 24 | { 25 | 26 | map m; // Declaration syntax of STL-Map 27 | 28 | m[1]="abc"; 29 | m[5]="cdc"; 30 | m[3]="acd"; 31 | 32 | //Insertion takes O(logn) : It depends on the key also ( Refer to RED BLACK TREES ) -> TIME COMPLEXITY 33 | 34 | auto it1=m.find(3); // returns iterator of the value '3' and stores it in it1 35 | 36 | if(it1==m.end()){ // if '3' is not present then it1 will be assigned with m.end() which has NO VALUE 37 | cout<<"NO VALUE"< TIME COMPLEXITY 46 | 47 | print(m); 48 | 49 | m.clear(); // clears the whole map 50 | 51 | 52 | // Another way of insert 53 | 54 | m.insert({4,"afg"}); 55 | 56 | // priniting using iterator method 57 | 58 | map :: iterator it; 59 | 60 | for(it=m.begin();it!=m.end();it++) 61 | { 62 | 63 | cout<<(*it).first<<" "<<(*it).second< 2 | #include 3 | using namespace std; 4 | 5 | class edge{ 6 | public: 7 | int src; 8 | int dest; 9 | int weight; 10 | }; 11 | 12 | bool compare(edge e1, edge e2){ 13 | return e1.weight>n>>E; 67 | edge *Arr = new edge[E]; 68 | for(int i=0;i>Arr[i].src>>Arr[i].dest>>Arr[i].weight; 70 | } 71 | 72 | Kruskal(Arr,n,E); 73 | } -------------------------------------------------------------------------------- /R-Recursion/SubsequenceKSUM.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | //------------------------------------PROBLEM : Subsequence with K sum ---------------------------------- 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | void generate(vector arr, vector output, int index, int sum, int tempSum) 10 | { 11 | if (index >= arr.size()) 12 | { 13 | if (tempSum == sum) 14 | { 15 | //printing all subsequences 16 | for (int i = 0; i < output.size(); i++) 17 | { 18 | cout << output[i] << " "; 19 | } 20 | cout << endl; 21 | } 22 | return; 23 | } 24 | 25 | output.push_back(arr[index]); 26 | tempSum += arr[index]; 27 | generate(arr, output, index + 1, sum, tempSum); 28 | output.pop_back(); 29 | tempSum -= arr[index]; 30 | generate(arr, output, index + 1, sum, tempSum); 31 | } 32 | 33 | int main() 34 | { 35 | 36 | vector arr; 37 | int n, sum; 38 | 39 | cout << "Enter the total number of elements in the array/vector : " << endl; 40 | cin >> n; 41 | 42 | cout << "Enter the elements : " << endl; 43 | for (int i = 0; i < n; i++) 44 | { 45 | int temp; 46 | cin >> temp; 47 | arr.push_back(temp); 48 | } 49 | 50 | cout << "Enter the subsequence sum : " << endl; 51 | cin >> sum; 52 | cout << "The subsequences are as follows : " << endl; 53 | 54 | int tempSum = 0; 55 | vector output; 56 | int index = 0; 57 | 58 | //this prints all the subsequences 59 | generate(arr, output, index, sum, tempSum); 60 | //It is also possible to store all the subsequences in a 2D vector by passing it as a reference in the 'generate' function 61 | return 0; 62 | 63 | } 64 | 65 | -------------------------------------------------------------------------------- /S-Stack/Bracket Balancing Using Stack/Bracket_Balancing_using_Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | bool isBalanced(string expr) { 5 | stack s; 6 | char ch; 7 | for (int i=0; i>expr; 40 | if (isBalanced(expr)) 41 | cout << "Balanced"; 42 | else 43 | cout << "Not Balanced"; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /L-LinkedList/S-SinglyLinkedList/DetectCycleInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node { 5 | public: 6 | int num; 7 | node* next; 8 | node(int val) { 9 | num = val; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | //utility function to insert node in the list 15 | void insertNode(node* &head,int val) { 16 | node* newNode = new node(val); 17 | 18 | if(head == NULL) { 19 | head = newNode; 20 | return; 21 | } 22 | 23 | node* temp = head; 24 | while(temp->next != NULL) temp = temp->next; 25 | 26 | temp->next = newNode; 27 | return; 28 | } 29 | 30 | //utility function to create cycle 31 | void createCycle(node* &head,int a,int b) { 32 | int cnta = 0,cntb = 0; 33 | node* p1 = head; 34 | node* p2 = head; 35 | while(cnta != a || cntb != b) { 36 | if(cnta != a) p1 = p1->next, ++cnta; 37 | if(cntb != b) p2 = p2->next, ++cntb; 38 | } 39 | p2->next = p1; 40 | } 41 | 42 | //utility function to detect cycle 43 | bool cycleDetect(node* head) { 44 | if(head == NULL) return false; 45 | node* fast = head; 46 | node* slow = head; 47 | 48 | while(fast->next != NULL && fast->next->next != NULL) { 49 | fast = fast->next->next; 50 | slow = slow->next; 51 | if(fast == slow) return true; 52 | } 53 | return false; 54 | } 55 | 56 | 57 | int main() { 58 | node* head = NULL; 59 | insertNode(head,1); 60 | insertNode(head,2); 61 | insertNode(head,3); 62 | insertNode(head,4); 63 | createCycle(head,1,3);//creating cycle in the list 64 | if(cycleDetect(head) == true) 65 | cout<<"Cycle detected\n"; 66 | else 67 | cout<<"Cycle not detected\n"; 68 | return 0; 69 | } -------------------------------------------------------------------------------- /S-StringAlgorithms/KMP/kmp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to implement the KMP algorithm 5 | void KMP(string text, string pattern) 6 | { 7 | int m = text.length(); 8 | int n = pattern.length(); 9 | 10 | // if pattern is an empty string 11 | if (n == 0) 12 | { 13 | cout << "The pattern occurs with shift 0"; 14 | return; 15 | } 16 | 17 | // if text's length is less than that of pattern's 18 | if (m < n) 19 | { 20 | cout << "Pattern not found"; 21 | return; 22 | } 23 | 24 | // next[i] stores the index of the next best partial match 25 | int next[n + 1]; 26 | 27 | for (int i = 0; i < n + 1; i++) { 28 | next[i] = 0; 29 | } 30 | 31 | for (int i = 1; i < n; i++) 32 | { 33 | int j = next[i + 1]; 34 | 35 | while (j > 0 && pattern[j] != pattern[i]) { 36 | j = next[j]; 37 | } 38 | 39 | if (j > 0 || pattern[j] == pattern[i]) { 40 | next[i + 1] = j + 1; 41 | } 42 | } 43 | 44 | for (int i = 0, j = 0; i < m; i++) 45 | { 46 | if (text[i] == pattern[j]) 47 | { 48 | if (++j == n) { 49 | cout << "The pattern occurs with shift " << i - j + 1 << endl; 50 | } 51 | } 52 | else if (j > 0) 53 | { 54 | j = next[j]; 55 | i--; // since `i` will be incremented in the next iteration 56 | } 57 | } 58 | } 59 | 60 | // Program to implement the KMP algorithm in C++ 61 | int main() 62 | { 63 | string text ; 64 | string pattern; 65 | cout<<"Enter the text "; 66 | cin>>text; 67 | cout<<"Enter the pattern "; 68 | cin>>pattern; 69 | 70 | KMP(text, pattern); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue-form.yml: -------------------------------------------------------------------------------- 1 | name: New Issue 2 | description: Description 3 | title: "Title " 4 | labels: [""] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | Thanks for taking the time to make an issue! 10 | - type: textarea 11 | id: description 12 | attributes: 13 | label: Description 14 | description: Enter a brief description 15 | placeholder: Please include a summary. Please also include relevant motivation and context. 16 | value: "Description" 17 | validations: 18 | required: true 19 | - type: dropdown 20 | id: version 21 | attributes: 22 | label: Domain 23 | description: Select domain of Contribution 24 | options: 25 | - CPP 26 | - Competitive Programming 27 | - Algorithm 28 | - Data Structure 29 | - Standard Template Library 30 | - README 31 | - UI/UX 32 | - Other 33 | validations: 34 | required: true 35 | - type: dropdown 36 | id: contribtype 37 | attributes: 38 | label: Type of Contribution 39 | multiple: true 40 | options: 41 | - Addition 42 | - Refactoring 43 | - Enhancement 44 | - Documentation 45 | - Others 46 | - type: checkboxes 47 | id: terms 48 | attributes: 49 | label: Code of Conduct 50 | description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/Lakhankumawat/LearnCPP/blob/main/.github/CODE_OF_CONDUCT.md) 51 | options: 52 | - label: I follow [Contributing Guidelines](https://github.com/Lakhankumawat/LearnCPP/blob/main/Contributing.md) & [Code of conduct](https://github.com/Lakhankumawat/LearnCPP/blob/main/.github/CODE_OF_CONDUCT.md) of LearnCPP. 53 | required: true 54 | -------------------------------------------------------------------------------- /R-Recursion/InversionCount.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | 3 | Welcome to GDB Online. 4 | GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, 5 | C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. 6 | Code, Compile, Run and Debug online from anywhere in world. 7 | 8 | *******************************************************************************/ 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | int Merge(int a[],int low,int mid,int high){ 14 | 15 | int i=low,j=mid+1,k=low,temp[10000]; 16 | int inv_count=0; 17 | while(i<=mid && j<=high){ 18 | if(a[i]<=a[j]){ 19 | temp[k++]=a[i++]; 20 | }else{ 21 | temp[k++]=a[j++]; 22 | inv_count+=mid-i+1; 23 | } 24 | } 25 | while(i<=mid){temp[k++]=a[i++];} 26 | while(j<=high){temp[k++]=a[j++];} 27 | 28 | for (int i = low; i <= high; i++) 29 | { 30 | /* code */ 31 | a[i]=temp[i]; 32 | } 33 | 34 | } 35 | 36 | 37 | 38 | int inversion_count(int a[],int low,int high){ 39 | 40 | if(low>=high){ 41 | return 0;} 42 | int mid = (low+high)/2; 43 | int x=inversion_count(a,low,mid); 44 | int y=inversion_count(a,mid+1,high); 45 | int z=Merge(a,low,mid,high); //Cross inversion counts 46 | return x+y+z; 47 | } 48 | 49 | 50 | int main(){ 51 | int arr[]={5,4,3,6,1,2,7}; 52 | int s = sizeof(arr)/sizeof(arr[0]); 53 | cout< 2 | 3 | using namespace std; 4 | // This function prints the juggler Sequence using loop 5 | void printJugglerWithLoop(long long a) 6 | { 7 | // print the first term 8 | cout<>a; 60 | cout << "Juggler sequence using Loop: "; 61 | printJugglerWithLoop(a); 62 | cout< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | 7 | { 8 | ios_base::sync_with_stdio(false); 9 | cout.tie(0); 10 | cin.tie(0); 11 | int div, a, b, ch = 0; 12 | printf("\nEnter Two number for Division \n"); 13 | cin >> a >> b; 14 | 15 | // By Inputting the value it will enter try block and check condition if b=0 then throw the exception. 16 | try 17 | { 18 | if (b == 0) 19 | { 20 | throw 101; 21 | } 22 | div = a / b; 23 | cout << "The division is : " << div; 24 | } 25 | 26 | // Catch block will catch the error. 27 | catch (int e) 28 | { 29 | cout << "\nThese lines are executed because we given a undefined thing which is an exception for program and we also specified the error for better understanding for error done by user\n\n"; 30 | cout << "------------------Error------------------------"; 31 | cout << "\n\nDivision by zero is Undefined " 32 | << "Error Code --> " << e; 33 | cout << "\n\n------------------------------------------\n"; 34 | } 35 | 36 | // This will catch the error when double type exception is thrown 37 | catch (double e) 38 | { 39 | cout << "Double Val thrown"; 40 | } 41 | 42 | // This will catch the error when char type exception is thrown 43 | catch (char e) 44 | { 45 | cout << "Char Val thrown"; 46 | } 47 | 48 | // This will catch the error when string type exception is thrown 49 | catch (string e) 50 | { 51 | cout << "string Val thrown"; 52 | } 53 | 54 | // This will catch the error when above block not catch the exception thrown. 55 | catch (...) 56 | { 57 | cout << "All catches handeled"; 58 | } 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /S-Stack/NextGreaterElement/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Table of content 3 | - [Problem Statement: Next Greater Element.](#nge) 4 | - [Algorithm.](#algo) 5 | - [Visualization of Algorithm.](#approach) 6 | - [Time Complexity](#time) 7 | - [Auxiliary Space](#space) 8 | 9 |
10 | # Next Greater Element Using Stack 11 | 12 | Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. 13 | ``` 14 | Input: elements of array 11 13 21 3 15 | Output: 16 | 11-->13 17 | 13-->21 18 | 21-->-1 19 | 3-->-1 20 | ``` 21 | 22 | ## Algorithm 23 | ``` 24 | * Push the first element to stack. 25 | * Pick rest of the elements one by one and follow the following steps in loop. 26 | 1. Mark the current element as next. 27 | 2. If stack is not empty, compare top element of stack with next. 28 | 3. If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element. 29 | 4. Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements. 30 | * Finally, push the next in the stack. 31 | * After the loop in step 2 is over, pop all the elements from the stack and print -1 as the next element for them 32 | ``` 33 | 34 | ## Visualization of Algorithm below: 35 | ![NextGreaterElement](https://user-images.githubusercontent.com/84399701/163118470-25118e13-5087-4b2a-94c3-d3f7e5b760e3.png) 36 | 37 | 38 | **Time Complexity:** O(n) 39 | 40 | 41 | 42 | 43 | 44 | 45 | **Auxiliary Space:** O(n) for stack. 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /D-DynamicProgramming/KnapsackwithDuplicateItems.cpp: -------------------------------------------------------------------------------- 1 | //Knapsack with Duplicate Items 2 | //link of the Problem Statement :- https://practice.geeksforgeeks.org/problems/knapsack-with-duplicate-items4201/1/# 3 | 4 | #include 5 | using namespace std; 6 | 7 | //function to calculate max profit 8 | int maxProfit(int currentItem,int n,int capacity,int profit[],int weight[],vector>&v) 9 | { 10 | //base conditions 11 | if(capacity == 0) return 0; //we can't add anymore items if the capacity of the knapsack becomes 0 12 | 13 | if(currentItem >= n) return 0; //we can't get any profit form items that dosen't exists 14 | 15 | if(v[currentItem][capacity] != -1) //if answer for that co-ordinade already exists, then returning it value 16 | return v[currentItem][capacity]; 17 | 18 | //exploring the 2 possibilities :- 1)Considering the item, 2)not considering the item 19 | int consider=0; 20 | if(weight[currentItem] <= capacity) 21 | consider= profit[currentItem] + maxProfit(currentItem,n,capacity-weight[currentItem],profit,weight,v); 22 | 23 | int notConsider = maxProfit(currentItem+1,n,capacity,profit,weight,v); 24 | 25 | //storing the answer for currentKey in the unordered_map,so that we can use it in future 26 | v[currentItem][capacity] = max(consider,notConsider); 27 | return v[currentItem][capacity]; 28 | } 29 | int knapSack(int N, int W, int val[], int wt[]) 30 | { 31 | vector>v(N,vector(W+1,-1)); 32 | return maxProfit(0,N,W,val,wt,v); 33 | } 34 | 35 | int main() 36 | { 37 | int N,W; 38 | cin>>N>>W; 39 | int wt[N],val[W]; 40 | 41 | for(int i=0;i>wt[i]; 43 | 44 | for(int i=0;i>val[i]; 46 | 47 | cout< 2 | using namespace std; 3 | struct node{ 4 | int data; 5 | struct node *next; 6 | struct node *prev; 7 | }; 8 | struct node *head=NULL; 9 | 10 | void Insert(){int item; 11 | struct node *newNode; 12 | newNode= (struct node *)malloc(sizeof(struct node)); 13 | cout<<"Insert item in the beginning"<>item; 15 | newNode ->data=item; 16 | newNode ->next=NULL; 17 | newNode ->prev=NULL; 18 | if((head==NULL) 19 | { 20 | head = newNode; 21 | return; 22 | } 23 | newNode->next=head; 24 | head=newNode; 25 | 26 | }} 27 | 28 | 29 | void Delete(){ 30 | struct node *temp=head; 31 | if(head==NULL) 32 | {cout<<"List is empty"<data<next; 36 | temp->next ->prev= NULL; 37 | } 38 | free(temp); 39 | 40 | } 41 | 42 | void Display(){ 43 | struct node *temp=head; 44 | if (head==NULL) { 45 | cout<<"List is empty"<data<<" "; 52 | temp=temp->next; 53 | } 54 | cout<>choice; 66 | switch(choice){ 67 | case 1: Insert(); 68 | break; 69 | case 2: Delete(); 70 | break; 71 | case 3: Display(); 72 | break; 73 | case 4: cout<<"Exit"< 6 | using namespace std; 7 | 8 | // GLOBAL DECLARATION 9 | stack st; 10 | string ans; 11 | 12 | //function that inserts an element into stack. 13 | void insert(char x) 14 | { 15 | 16 | if(st.size() == 0) st.push(x); 17 | 18 | else 19 | { //take out the topmost element, pop it and recursively call the function 20 | char a = st.top(); 21 | st.pop(); 22 | insert(x); 23 | 24 | 25 | // when inserted at the bottom then push items in stack 26 | st.push(a); 27 | } 28 | } 29 | 30 | // function that reverses the given stack 31 | void reverse() 32 | { 33 | if(st.size()>0) 34 | { 35 | 36 | // Hold all items in stack until we reach its end 37 | char x = st.top(); 38 | st.pop(); 39 | reverse(); 40 | 41 | // call the function for inserting 42 | insert(x); 43 | } 44 | } 45 | 46 | 47 | int main() 48 | { 49 | 50 | // push elements into the stack 51 | st.push('3'); 52 | st.push('2'); 53 | st.push('1'); 54 | st.push('7'); 55 | 56 | cout<<"Previous Stack\n"; 57 | 58 | // print the old elements 59 | cout<<"3"<<" "<<"2"<<" "<<"1"<<" "<<"7"< 3 | #include 4 | using namespace std; 5 | 6 | //Custom key for a map of a Student class 7 | class Student{ 8 | public: 9 | string firstname; 10 | string lastname; 11 | string rollno; 12 | 13 | //Constructor to make Students 14 | Student(string f,string l,string no){ 15 | firstname=f; 16 | lastname=l; 17 | rollno=no; 18 | } 19 | 20 | //Operator overloading in C++ defining our own custom == operator function 21 | //Since already a definition of == was present in c++ we defined one more so its called operator overloading 22 | 23 | bool operator ==(const Student &s) const{ 24 | return rollno==s.rollno?true:false; 25 | } 26 | 27 | 28 | }; 29 | 30 | //Define our hashfn 31 | class Hashfn{ 32 | 33 | public: 34 | // size_t is unsigned int type of data type 35 | /*----This Hashfn Sorts on the basis of the length() fname+ lname greater will be at top--*/ 36 | size_t operator()(const Student &s) const{ 37 | 38 | return s.firstname.length()+s.lastname.length(); 39 | 40 | } 41 | }; 42 | 43 | int main(){ 44 | 45 | /* to map the key student by marks(int) using HashFn */ 46 | unordered_map student_map; 47 | 48 | Student s1("lakhan","kumawat","055"); 49 | Student s2("Fauna","Mittal","010"); 50 | Student s3("Lakhan","paarek","211"); 51 | Student s4("Fauna","Mittal","032"); 52 | Student s5("Abcdefgh","hacker","-0-"); 53 | 54 | //Add Student marks to hashmap 55 | student_map[s1]=100; 56 | student_map[s2]=40; 57 | student_map[s3]=30; 58 | student_map[s4]=10; 59 | student_map[s5]=10000; 60 | //Iterate over all students 61 | 62 | for(auto s:student_map){ 63 | cout< 5 | using namespace std; 6 | 7 | /* prints element and NGE pair for all elements of arr[] of size n */ 8 | void printNGE(int arr[], int n) 9 | { 10 | stack s; 11 | 12 | /* push the first element to stack */ 13 | s.push(arr[0]); 14 | 15 | // iterate for rest of the elements 16 | for (int i = 1; i < n; i++) 17 | { 18 | 19 | if (s.empty()) { 20 | s.push(arr[i]); 21 | continue; 22 | } 23 | 24 | /* if stack is not empty, then pop an element from stack. 25 | If the popped element is smaller than next, then 26 | a) print the pair 27 | b) keep popping while elements are 28 | smaller and stack is not empty */ 29 | while (s.empty() == false 30 | && s.top() < arr[i]) 31 | { 32 | cout << s.top() 33 | << " --> " << arr[i] << endl; 34 | s.pop(); 35 | } 36 | 37 | /* push next to stack so that we can find next greater for it */ 38 | s.push(arr[i]); 39 | } 40 | 41 | /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ 42 | while (s.empty() == false) { 43 | cout << s.top() << " --> " << -1 << endl; 44 | s.pop(); 45 | } 46 | delete []arr; 47 | } 48 | 49 | /* Driver code */ 50 | int main() 51 | { 52 | int n; 53 | cout<<"Enter size of the array: "<>n; 55 | int* arr=new int[n]; 56 | cout<<"Enter elements of the array: "<>arr[i]; 60 | } 61 | cout<<"Next Greater Element Output"< 3 | #include //maximum value of an object of int type 4 | #include 5 | 6 | using namespace std; 7 | 8 | #define inf INT_MAX 9 | #define n 12 10 | 11 | int shortestPath(int graph[n][n]); 12 | 13 | int main(){ 14 | int graph[n][n] ={ 15 | inf , 9 , 7 , 3 , 12 , inf , inf , inf , inf , inf , inf , inf 16 | , inf , inf , inf , inf , inf , 4 , 2 , 7 , inf , inf , inf , inf 17 | , inf , inf , inf , inf , inf , 2 , 7 , inf , inf , inf , inf , inf 18 | , inf , inf , inf , inf , inf , inf , inf , 11 , inf , inf , inf , inf 19 | , inf , inf , inf , inf , inf , inf , 11 , 8 , inf , inf , inf , inf 20 | , inf , inf , inf , inf , inf , inf , inf , inf , 6 , 5 , inf , inf 21 | , inf , inf , inf , inf , inf , inf , inf , inf , 4 , 3 , inf , inf 22 | , inf , inf , inf , inf , inf , inf , inf , inf , inf , 5 , 6 , inf 23 | , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , 4 24 | , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , 2 25 | , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , 5 26 | , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf , inf 27 | }; 28 | 29 | cout<<"The Shortest Path cost : "<=0;i--){ 38 | cost[i]=inf; 39 | for(j=1;j 4 | #include 5 | using namespace std; 6 | 7 | typedef multiset::iterator It; 8 | 9 | int main(){ 10 | /* ------KEYPOINTS-------- 11 | Multiset - that can store multiple elements that have same elements 12 | stored in a specific -> sorted according to the internal comparison 13 | values once inserted can't be modified 14 | associative container -> elements are referred by their value and not by index 15 | underlying data structure - BST 16 | 17 | */ 18 | int arr[]={10,20,11,9,32,10,11,20,20,30}; 19 | int n =sizeof(arr)/sizeof(int); 20 | 21 | multiset s(arr,arr+n); 22 | 23 | for(auto x:s) 24 | cout< range=s.equal_range(20); 51 | 52 | for(auto i=range.first;i!=range.second;i++) 53 | cout<<*i<<" | "; 54 | 55 | cout<