├── Arrays ├── Algorithms │ ├── BubbleSort.txt │ ├── BucketSort.txt │ ├── DNFsort.txt │ ├── Kadane's.txt │ ├── MergeSort.txt │ ├── QuickSort.txt │ ├── TwoPointers.txt │ ├── Gap(shellsort).txt │ ├── InsertionSort.txt │ ├── MooresVoting.txt │ ├── SelectionSort.txt │ ├── SlidingWindow.txt │ └── CountSort.txt ├── 2-D Arrays │ ├── Basic │ │ ├── WavePrint.txt │ │ └── Shift2DArray.txt │ └── Medium │ │ ├── a.out │ │ ├── RotateImage.txt │ │ ├── SpiralPrintMatrix.txt │ │ └── PascalTriangle.cpp ├── 1-D Arrays │ ├── Basic │ │ ├── Screenshot 2023-05-28 215449.png │ │ ├── LargestElementInArray.txt │ │ ├── MonotonicArray.txt │ │ ├── ReverseArrayInGroups.cpp │ │ ├── Sort01.txt │ │ ├── LeftRotateArrayByDPlaces.txt │ │ ├── Miscellaneous │ │ │ ├── FlowerBed.txt │ │ │ └── NumberOfArithmeticTriplets.txt │ │ └── NextGreaterELement.txt │ ├── Medium │ │ ├── Screenshot 2023-05-29 174008.png │ │ ├── Screenshot 2023-05-29 204102.png │ │ ├── Screenshot 2023-06-01 101608.png │ │ ├── SortColors.txt │ │ ├── Majority │ │ │ ├── MajorityElement.txt │ │ │ └── MajorityElement2.txt │ │ └── RearrangePostiveAndNegative.txt │ └── Patterns │ │ ├── TwoPointers │ │ ├── CheckIfArraySorted.txt │ │ ├── RemoveDuplicatesFromSortedArray.txt │ │ ├── MoveZeoresToEnd.txt │ │ ├── MaximumProductOfThreeNumbers.txt │ │ ├── IntersectionOfArray.txt │ │ ├── UnionOfArray.txt │ │ ├── MaxSizeKSum.txt │ │ ├── SecondLargestAndSmallest.txt │ │ ├── AdditionOfArrays.txt │ │ ├── TwoSum.txt │ │ ├── MergeTwoSortedArrays.txt │ │ └── IntersectionOfThreeArrays.txt │ │ ├── Duplicates │ │ ├── MaximumConsecutiveOnes.txt │ │ ├── UniqueOccurences.txt │ │ ├── LeadersInArray.txt │ │ ├── FindAllMissingNumbersFromDuplicates.txt │ │ ├── FindUniqueElement.txt │ │ ├── MissingNumber.txt │ │ ├── FindDupicate.txt │ │ └── FindMissingAndDuplicate.txt │ │ ├── Prefix │ │ ├── PrefixSum.txt │ │ ├── FindRightAndLeftDifferences.txt │ │ └── FindPivot.txt │ │ ├── Sorting │ │ ├── SelectionSort.txt │ │ ├── BubbleSort.txt │ │ └── InsertionSort.txt │ │ ├── SubArrays │ │ ├── MaximumSubArraySum.txt │ │ ├── AllSubArraysGivenSum.txt │ │ ├── SubArrayWithOddLength.txt │ │ ├── CountSubArraysWithXorK.txt │ │ ├── MaximumSubArrayLengthWithGivenSum.txt │ │ ├── MaximumProductSubarray.txt │ │ └── SubArraysWithEqual0sand1s.txt │ │ └── Subsequences │ │ ├── LongestIncreasingSubsequence.txt │ │ └── LongestConsecutiveSequence.txt └── Binary Search │ ├── 1-D Arrays │ ├── Medium │ │ ├── CountOccurences.txt │ │ ├── SumOfSquaresOfNumber.txt │ │ ├── SearchAnswersSpace │ │ │ ├── NthRootM.txt │ │ │ ├── Sqrt(x).txt │ │ │ ├── FindPeakElement.txt │ │ │ ├── KokoEatingBanans.txt │ │ │ └── ShipWeights.txt │ │ ├── SearchSorted │ │ │ ├── FindKthRotation.txt │ │ │ ├── FindMinimumInSorted.txt │ │ │ ├── SearchInARotatedSortedArray.txt │ │ │ ├── SearchInSortedArrayWithDuplicates.txt │ │ │ └── SearchSortedArray2.txt │ │ ├── FindKClosest.txt │ │ └── KDifferentPairs.txt │ ├── Basic │ │ ├── UpperBound.txt │ │ ├── SearchInsertPosition.txt │ │ ├── FindMissingTermInAPSeries.txt │ │ ├── GuessNumberLowerOrHigher.txt │ │ ├── LowerBound.txt │ │ ├── FloorAndCeil.txt │ │ ├── CheckArrayIsSortedAndRotate.txt │ │ └── KthMissingPositive.txt │ └── Hard │ │ └── FindMinimumInSorted2.txt │ ├── ExponentialSearch │ ├── ExponentialSearch.cpp │ └── FindElementInAnInfiniteSortedArray.cpp │ └── 2-D Arrays │ └── Medium │ ├── SearchIn2DMatrix1.txt │ └── SearchInA2DMatrix2.txt ├── Trees ├── Questions │ ├── DiameterOfTree.cpp │ └── HeightOfBinaryTree.cpp └── BinaryTrees │ ├── Build │ └── RecursiveWay.cpp │ └── Traversal │ ├── Preorder.cpp │ ├── PostOrder.cpp │ ├── InorderTraversal.cpp │ └── LevelOrderTraversal.cpp ├── Maths ├── Factorial │ ├── FactorialOfLargeNumber.txt │ └── FactorialTrailingZeros.txt ├── CountSetBits.txt ├── Palindrome.txt ├── BasicDivisorLCMGCD │ ├── FindCommonFactors.txt │ ├── CountDigits.txt │ ├── PrintDivisors.txt │ ├── GCDHCF.txt │ └── kThFactor.txt ├── ReverseInteger.txt ├── CheckPrime.txt ├── ArmStrongNumber.txt ├── FindMissingTermInAPSeries.txt ├── DivisibleBy7.txt └── UglyNumber.txt ├── Stacks ├── Basic │ ├── MiddleElement.cpp │ └── ReverseStringUsingStack.cpp └── Implementation │ ├── ImplementUsingQueues.cpp │ ├── WithArray.cpp │ ├── ImplementTwoStacksInSingleArray.cpp │ └── ImplementUsingLL.cpp ├── run.sh ├── Hashing ├── FirstRepeating.txt ├── FrequencyOfElement.txt └── Concept.txt ├── Miscellaneous ├── CheckNDoubleExisits.txt ├── AssignCookies.txt ├── LargestPositiveNumberExists.txt ├── CheckIfStraightLine.txt └── HappyNumber.txt ├── .vscode ├── settings.json └── launch.json ├── README.md ├── LinkedLists └── Singly │ ├── InsertNode.txt │ ├── DeleteNode.txt │ ├── ReverseLinkedList.cpp │ ├── Implement.txt │ └── Circular │ └── BasicImplementation.cpp ├── Strings ├── Basic │ ├── Palindrome │ │ ├── Palindrome.txt │ │ ├── ValidPalindrome2.txt │ │ └── CountPalindromicStrings.txt │ ├── LengthOfLastWord.txt │ ├── LargestOddNumberInString.txt │ ├── IsomorphicString.txt │ ├── ConvertAllSmallCaseToUpperCase.txt │ ├── Panagram.txt │ ├── RansomNote.txt │ ├── CommonCharacters.txt │ ├── ValidAnagram.txt │ ├── RemoveAdjacentCharacters.txt │ └── LargestCommonPrefix.txt └── Medium │ ├── RemoveAllOccurencesOfStringInMainString.txt │ ├── LongestOddLengthSubString.txt │ ├── SortCharactersAccrodingToFrequency.txt │ ├── StringToInteger(atoi).txt │ ├── ReorganizeStrings.txt │ ├── GroupAmagrams.txt │ └── RomanToIntegerandViceversa │ ├── IntegerToRoman.txt │ └── RomanToInteger.txt ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── Queues ├── Implementation │ ├── usingStack.cpp │ ├── ImplemenetUsingArray.cpp │ └── UsingLinkedList.cpp ├── CircularQueue │ └── ImplementationUsingArray.cpp └── DoubleEndedQueues │ └── main.cpp └── LICENSE /Arrays/Algorithms/BubbleSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/BucketSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/DNFsort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/Kadane's.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/MergeSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/QuickSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/TwoPointers.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/2-D Arrays/Basic/WavePrint.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/Gap(shellsort).txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/InsertionSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/MooresVoting.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/SelectionSort.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Arrays/Algorithms/SlidingWindow.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Trees/Questions/DiameterOfTree.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Maths/Factorial/FactorialOfLargeNumber.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Stacks/Basic/MiddleElement.cpp: -------------------------------------------------------------------------------- 1 | // Using recursion -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | !#/bin/bash 2 | g++ Patterns/basic-patterns.cpp 3 | ./a.out -------------------------------------------------------------------------------- /Hashing/FirstRepeating.txt: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/first-repeating-element4018/1 -------------------------------------------------------------------------------- /Miscellaneous/CheckNDoubleExisits.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-n-and-its-double-exist/description/ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.ejs": "html", 4 | "iostream": "cpp" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Hashing/FrequencyOfElement.txt: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/frequency-of-array-elements-1587115620/0 2 | 3 | -------------------------------------------------------------------------------- /Maths/CountSetBits.txt: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/set-bits0143/1 2 | 3 | Count total set bits in a given number -------------------------------------------------------------------------------- /Arrays/2-D Arrays/Medium/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/HEAD/Arrays/2-D Arrays/Medium/a.out -------------------------------------------------------------------------------- /Maths/Palindrome.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/palindrome-number/ 2 | 3 | 4 | Approach: 5 | 1. Reverse integer, and check the acutal number with the reversed number 6 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/Screenshot 2023-05-28 215449.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/HEAD/Arrays/1-D Arrays/Basic/Screenshot 2023-05-28 215449.png -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Medium/Screenshot 2023-05-29 174008.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/HEAD/Arrays/1-D Arrays/Medium/Screenshot 2023-05-29 174008.png -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Medium/Screenshot 2023-05-29 204102.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/HEAD/Arrays/1-D Arrays/Medium/Screenshot 2023-05-29 204102.png -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Medium/Screenshot 2023-06-01 101608.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/HEAD/Arrays/1-D Arrays/Medium/Screenshot 2023-06-01 101608.png -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/CountOccurences.txt: -------------------------------------------------------------------------------- 1 | Similar to ./FindOccurences(firstandlast).txt 2 | 3 | 1. Find the first occurence of the number in the array 4 | 2. Find the last occurence of the number in the array 5 | return last-first+1 6 | 7 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/CheckIfArraySorted.txt: -------------------------------------------------------------------------------- 1 | Check sorted array: 2 | 3 | O(N), SC: O(1) 4 | https://www.codingninjas.com/codestudio/problems/ninja-and-the-sorted-check_6581957?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/RemoveDuplicatesFromSortedArray.txt: -------------------------------------------------------------------------------- 1 | Brute: Store in a set 2 | Optimal: Two pointers, one to iterate and one to store the index of the last unique element 3 | 4 | 5 | https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [] 7 | } -------------------------------------------------------------------------------- /Stacks/Basic/ReverseStringUsingStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | string s1="faizan"; 7 | stack rev; 8 | for(auto it: s1) rev.push(it); 9 | while(!rev.empty()){ 10 | cout<=(INT_MAX)/10 or ans<=(INT_MIN)/10){ 8 | return 0; 9 | } 10 | ans=ans*10+last_digit; 11 | x/=10; 12 | } 13 | 14 | return ans; 15 | 16 | TC: O(log10(n)) 17 | SC: O(1) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structures-Algorithms 2 | A repo to help you to get started in Data Structures and Algorithms. 3 | 4 | ![alt text](https://firebasestorage.googleapis.com/v0/b/chat-app-b3099.appspot.com/o/WhatsApp%20Image%202023-06-10%20at%2010.59.59.jpg?alt=media&token=7b927f57-1726-4638-8dad-e62eb3e0e2b9&_gl=1*1qman5t*_ga*MjAzNjgzNTc0OC4xNjg0Mzg2MjAy*_ga_CW55HF8NVT*MTY4NjQ5NzgxMy4zLjEuMTY4NjQ5Nzg5My4wLjAuMA..) 5 | 6 | ### Now you will get hired 7 | -------------------------------------------------------------------------------- /Maths/CheckPrime.txt: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/check-prime_624674?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 2 | 3 | 4 | int n; 5 | cin>>n; 6 | int count=0; 7 | for(int i=1; i*i<=n; i++){ 8 | if(n%i==0){ 9 | count++; 10 | if((n/i)!=i){ 11 | count++; 12 | } 13 | } 14 | } 15 | 16 | if(count==2){ 17 | cout<<"true"; 18 | } 19 | 20 | else{ 21 | cout<<"false"; 22 | } 23 | 24 | 25 | Tc: O(sqrt(n)) 26 | Sc: O(1) -------------------------------------------------------------------------------- /Maths/BasicDivisorLCMGCD/CountDigits.txt: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/number-of-digits_9173?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | int count=0; 8 | while(n>0){ 9 | // int last_digit=n%10; 10 | count+=1; 11 | n/=10; 12 | 13 | } 14 | 15 | TC: O(log10n) 16 | int count=(int)log10(n)+1; 17 | 18 | return count; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/MaximumConsecutiveOnes.txt: -------------------------------------------------------------------------------- 1 | Find maximum consecutive ones in an array 2 | Example: 1 1 0 1 1 1 3 | Output: 3 4 | 5 | 6 | 7 | You can jump directly to optimal solution: 8 | Optimal: O(n) time and O(1) space 9 | 1. Take two variables, maxCount, count 10 | 2. Iterate over the array 11 | 3. If element is 1, increment count 12 | 4. If element is 0, update maxCount if count > maxCount and reset count to 0 13 | 5. Return maxCount 14 | 15 | https://leetcode.com/problems/max-consecutive-ones/description/ -------------------------------------------------------------------------------- /LinkedLists/Singly/InsertNode.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition of linked list 3 | * class Node { 4 | * 5 | * public: 6 | * int data; 7 | * Node* next; 8 | * Node() : data(0), next(nullptr) {} 9 | * Node(int x) : data(x), next(nullptr) {} 10 | * Node(int x, Node* next) : data(x), next(next) {} 11 | * }; 12 | */ 13 | 14 | Node* insertAtFirst(Node* list, int newValue) { 15 | // Write your code here 16 | Node *newNode=new Node(newValue); 17 | newNode->next=list; 18 | list=newNode; 19 | return newNode; 20 | 21 | } -------------------------------------------------------------------------------- /Maths/ArmStrongNumber.txt: -------------------------------------------------------------------------------- 1 | https://www.codingninjas.com/codestudio/problems/check-armstrong_589?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 2 | 3 | Check for armstrong_589 4 | int n; 5 | cin>>n; 6 | 7 | int countDigits=(int)log10(n)+1; 8 | 9 | int actualNumber=n; 10 | int sum=0; 11 | 12 | while(n>0){ 13 | int last_digit=n%10; 14 | sum+=pow(last_digit, countDigits); 15 | n/=10; 16 | } 17 | 18 | if(sum==actualNumber){ 19 | cout<<"true"; 20 | } 21 | else{ 22 | cout<<"false"; 23 | } 24 | 25 | TC: O(logn) 26 | SC: O(1) 27 | -------------------------------------------------------------------------------- /Strings/Basic/Palindrome/Palindrome.txt: -------------------------------------------------------------------------------- 1 | Check whether a string is a palindrome or not 2 | 3 | 4 | 5 | 6 | class Solution{ 7 | public: 8 | 9 | 10 | int isPalindrome(string S) 11 | { 12 | // Your code goes here 13 | // string str; 14 | TC: O(n) SC: O(n) 15 | // for(int i=S.size()-1; i>=0; i--){ 16 | // str=str+S[i]; 17 | // } 18 | 19 | // return S.compare(str)==0 ? 1 : 0; 20 | 21 | 22 | // TC: O(n) SC: O(1) 23 | for(int i=0; in and the index must be smallest 4 | 5 | 6 | Code: 7 | int upperBound(vector &arr, int x, int n){ 8 | // Write your code here. 9 | int low=0, high=n-1; 10 | int idx=n; 11 | while(low<=high){ 12 | int mid=low+(high-low)/2; 13 | if(arr[mid]>x){ 14 | idx=mid; 15 | high=mid-1; 16 | } 17 | else{ 18 | low=mid+1; 19 | } 20 | } 21 | 22 | return idx; 23 | } 24 | 25 | TC:O(logn) 26 | SC:O(1) 27 | 28 | STL:upper_bound(arr.begin(),arr.end(),n)-arr.begin() -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/UniqueOccurences.txt: -------------------------------------------------------------------------------- 1 | check if all numbers have unqiue occurences in array 2 | 3 | 4 | // TC: O(m+nlogn) SC:O(n+m) 5 | unordered_map mpp; 6 | 7 | set st; 8 | 9 | // Storing all the elements in map 10 | for(int i=0; i& arr, int x) 8 | { 9 | // Write your code here. 10 | int idx=arr.size(); 11 | 12 | int low=0, high=arr.size()-1; 13 | while(low<=high){ 14 | int mid=low+(high-low)/2; 15 | if(arr[mid]>=x){ 16 | idx=mid; 17 | high=mid-1; 18 | 19 | } else { 20 | low=mid+1; 21 | 22 | } 23 | 24 | } 25 | 26 | 27 | return idx; 28 | } -------------------------------------------------------------------------------- /LinkedLists/Singly/DeleteNode.txt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class Node { 4 | * public: 5 | * int data; 6 | * Node *next; 7 | * Node() : data(0), next(nullptr) {} 8 | * Node(int x) : data(x), next(nullptr) {} 9 | * Node(int x, Node *next) : data(x), next(next) {} 10 | * }; 11 | */ 12 | 13 | 14 | Node *deleteLast(Node *list){ 15 | // Write your code here 16 | 17 | Node *temp=list; 18 | Node *p=NULL; 19 | while(temp->next){ 20 | p=temp; 21 | temp=temp->next; 22 | 23 | } 24 | p->next=NULL; 25 | delete temp; 26 | 27 | return list; 28 | 29 | 30 | 31 | } -------------------------------------------------------------------------------- /LinkedLists/Singly/ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* prev=nullptr; 15 | ListNode* curr=head; 16 | while(curr!=nullptr){ 17 | ListNode* temp=curr->next; 18 | curr->next=prev; 19 | prev=curr; 20 | curr=temp; 21 | } 22 | return prev; 23 | } 24 | }; -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SumOfSquaresOfNumber.txt: -------------------------------------------------------------------------------- 1 | Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 2 | 3 | class Solution { 4 | public: 5 | bool judgeSquareSum(int c) { 6 | long long a=0, b=sqrt(c); 7 | // we can check the range in between 0 till the square root of a number 8 | while(a<=b){ 9 | if(a*a+b*b==c){ 10 | return true; 11 | } 12 | else if(a*a+b*b& arr) { 15 | // Write your code here 16 | Node *newNode=new Node(arr[0]); 17 | Node *head=newNode; 18 | 19 | for(int i=1; inext=sub; 23 | newNode=sub; 24 | } 25 | return head; 26 | 27 | 28 | } -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Prefix/PrefixSum.txt: -------------------------------------------------------------------------------- 1 | int *prefixSum = new int[n]; 2 | 3 | // Assigning a[0] to prefixSum[0] 4 | prefixSum[0] = a[0]; 5 | 6 | // Iterating from i = 1 To i = n - 1 7 | for (int i = 1; i < n; i++){ 8 | // Finding prefixSum[i-1] 9 | int prev = prefixSum[i-1]; 10 | 11 | // Calculating and assigning the 12 | // value of prefixSum[i]. 13 | prefixSum[i] = prev + a[i]; 14 | } 15 | 16 | // Returning the prefixSum array. 17 | return prefixSum; 18 | 19 | 20 | To calculate sum[l,r] we can use prefixSum[r] - prefixSum[l-1] 21 | 22 | 23 | 1. https://leetcode.com/problems/binary-prefix-divisible-by-5/description/ -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /Maths/Factorial/FactorialTrailingZeros.txt: -------------------------------------------------------------------------------- 1 | You are given a number N. You need to find no of trailing zeroes in N!. 2 | 3 | 4 | Example: 5 | 5! = 120 so the output should be 1 6 | 10! = 3628800 so the output should be 2 7 | 8 | Approach: 9 | 1. If you divide number with 5, it will give you number of 5s in the number. 10 | 2. If you divide number with 25, it will give you number of 25s in the number. 11 | 3. If you divide number with 125, it will give you number of 125s in the number. 12 | 13 | So, you must repeat this process till n becomes 0. 14 | 15 | (n/5)+(n/25)+(n/125)+..... 16 | 17 | Code: 18 | int count=0; 19 | while(n>0){ 20 | count+=n/5; 21 | n=n/5; 22 | } 23 | 24 | return count; 25 | 26 | Time Complexity: O(logn) -------------------------------------------------------------------------------- /Maths/FindMissingTermInAPSeries.txt: -------------------------------------------------------------------------------- 1 | Actually done using binary search: but here is the O(n) solution 2 | 3 | 4 | class Solution{ 5 | public: 6 | int findMissing(int arr[], int n) { 7 | // code here 8 | int d=(arr[n-1]-arr[0])/(n); 9 | int idx=-1; 10 | 11 | int i=0, j=1; 12 | while(j pick). 10 | 1: Your guess is lower than the number I picked (i.e. num < pick). 11 | 0: your guess is equal to the number I picked (i.e. num == pick). 12 | Return the number that I picked. 13 | 14 | 15 | https://leetcode.com/problems/guess-number-higher-or-lower/description/ 16 | TC: O(logn) SC: O(1) 17 | -------------------------------------------------------------------------------- /Trees/BinaryTrees/Build/RecursiveWay.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node { 4 | public: 5 | int data; 6 | Node *left; 7 | Node *right; 8 | Node(int data){ 9 | this->data=data; 10 | this->left=nullptr; 11 | this->right=nullptr; 12 | } 13 | }; 14 | 15 | 16 | Node * buildTree(){ 17 | int data; 18 | cin>>data; 19 | if(data==-1){ 20 | return nullptr; 21 | } 22 | Node *root=new Node(data); 23 | 24 | cout<<"Enter left child of "<left=buildTree(); 26 | cout<<"Enter right child of "<right=buildTree(); 28 | 29 | return root; 30 | 31 | 32 | } 33 | 34 | 35 | 36 | 37 | int main(){ 38 | Node *root=buildTree(); 39 | return 0; 40 | 41 | } -------------------------------------------------------------------------------- /Queues/Implementation/usingStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | 7 | // queue implementation using two stacks 8 | stack st1; 9 | stack st2; 10 | 11 | int i=0; 12 | while(i<5){ 13 | //algo 14 | // 1. Push everything from stack1 to stack2 15 | // 2. insert x or num to stack 1 16 | // 3. Again push every number from stack2 to stack1 17 | // 4. TC: O(N) SC: O(2N) 18 | int x; 19 | cin>>x; 20 | while(!st1.empty()){ 21 | st2.push(st1.top()); 22 | st1.pop(); 23 | } 24 | st1.push(x); 25 | 26 | while(!st2.empty()){ 27 | st1.push(st2.top()); 28 | st2.pop(); 29 | } 30 | i++; 31 | } 32 | 33 | while(!st1.empty()){ 34 | cout<& nums) { 2 | // think of this: for 0 to low-1 all are zeores 3 | // for 1: low to mid-1 all are ones 4 | // for high+1 to n-1 all are twos 5 | // for mid to high all are unsorted 6 | int low=0, mid=0, high=nums.size()-1; 7 | while(mid<=high){ 8 | if(nums[mid]==0){ 9 | swap(nums[mid], nums[low]); 10 | mid++; 11 | low++; 12 | } 13 | 14 | else if(nums[mid]==1){ 15 | mid++; 16 | } 17 | else{ 18 | swap(nums[mid], nums[high] ); 19 | high--; 20 | } 21 | } 22 | 23 | 24 | 25 | } 26 | 27 | 28 | TC: O(N) 29 | SC: O(1) -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Sorting/SelectionSort.txt: -------------------------------------------------------------------------------- 1 | Given an array, sort an array using selection sort. 2 | 3 | 4 | Approach: 5 | 1. Find the minimum element in the array till last and swap it with the element at the beginning. 6 | 2. Repeat the same process for the remaining array. 7 | 8 | https://www.codingninjas.com/codestudio/problems/selection-sort_981162?leftPanelTab=1 9 | 10 | Code in cpp: 11 | 12 | for(int i=0; iarr[j+1]){ 14 | swap(arr[j], arr[j+1]); 15 | isSwap = true; 16 | } 17 | } 18 | if(isSwap == false){ 19 | break; 20 | } 21 | } 22 | 23 | TC: O(n^2) 24 | Best Case: O(n) when array is already sorted 25 | Bubble sort another name is sinking sort 26 | SC: O(1) -------------------------------------------------------------------------------- /Strings/Basic/LengthOfLastWord.txt: -------------------------------------------------------------------------------- 1 | Given a string s consisting of words and spaces, return the length of the last word in the string. 2 | 3 | A word is a maximal 4 | substring 5 | consisting of non-space characters only. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "Hello World" 12 | Output: 5 13 | Explanation: The last word is "World" with length 5. 14 | Example 2: 15 | 16 | Input: s = " fly me to the moon " 17 | Output: 4 18 | Explanation: The last word is "moon" with length 4. 19 | 20 | 21 | class Solution { 22 | public: 23 | int lengthOfLastWord(string s) { 24 | int count=0; 25 | for(int i=s.size()-1; i>=0; i--){ 26 | if(s[i]==' ' && count==0){ 27 | continue; 28 | } 29 | else if(s[i]==' ' && count!=0){ 30 | break; 31 | } 32 | else{ 33 | count++; 34 | } 35 | } 36 | 37 | return count; 38 | } 39 | }; -------------------------------------------------------------------------------- /Strings/Basic/LargestOddNumberInString.txt: -------------------------------------------------------------------------------- 1 | You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. 2 | 3 | A substring is a contiguous sequence of characters within a string. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: num = "52" 10 | Output: "5" 11 | Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. 12 | 13 | // TC: O(N) SC:O(1) 14 | string ans; 15 | 16 | for(int i=num.size()-1; i>=0; i--){ 17 | if((num[i]-'0')%2!=0){ 18 | ans=num.substr(0, i+1); 19 | break; 20 | } 21 | } 22 | 23 | return ans; 24 | Algorithm: 25 | 1. Traverse from the end of the string 26 | 2. If the current character is odd, return the substring from 0 to i+1 27 | 3. If no odd character is found, return empty string 28 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/MonotonicArray.txt: -------------------------------------------------------------------------------- 1 | Check whether the given array is monotonic or not: 2 | 3 | Optimal : (O(n) time and O(1) space) 4 | 5 | bool isMonotonic(vector& nums) { 6 | bool isIncreasing=false; 7 | bool isDecreasing=false; 8 | for(int i=0; im) break; 15 | if(power==m){ 16 | return i; 17 | } 18 | } 19 | return -1; 20 | } 21 | 22 | TC: O(mlog2N) 23 | For pow() function: O(log2N) 24 | SC: O(1) 25 | 26 | 27 | Optimal: Using binary search 28 | int NthRoot(int n, int m) { 29 | // Write your code here. 30 | int low=1,high=m; 31 | while(low<=high){ 32 | long long mid=(low+high)/2; 33 | if(pow(mid, n)==m){ 34 | return mid; 35 | } 36 | else if(pow(mid, n)>m){ 37 | high=mid-1; 38 | } else { 39 | low = mid + 1; 40 | } 41 | } 42 | 43 | return -1; 44 | } 45 | 46 | TC: O(log2m) log2N for pow() function 47 | SC: O(1) -------------------------------------------------------------------------------- /Strings/Basic/IsomorphicString.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Given two strings s and t, determine if they are isomorphic. 5 | 6 | Two strings s and t are isomorphic if the characters in s can be replaced to get t. 7 | 8 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | bool isIsomorphic(string s, string t) { 15 | int hash[256]={0}; 16 | bool isTCharMapped[256]={0}; 17 | 18 | for(int i=0; i &nums){ 9 | // Write your code here. 10 | int low=0, high=nums.size()-1; 11 | int ans=INT_MAX; 12 | int index=-1; 13 | while(low<=high){ 14 | int mid=(low+high)/2; 15 | // first checking for sorted part, if they are sorted, then pick for the minimum number from it and then elimnate that part. 16 | if(nums[mid]<=nums[high]){ 17 | if(nums[mid]=0 and str[i]-'a'<=25){ 41 | ans=ans+(char)(str[i]-32); 42 | } 43 | else{ 44 | ans=ans+(char)(str[i]+32); 45 | } 46 | } 47 | 48 | cout< Count sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. 4 | 5 | 6 | 1. Calcuate maximum element in array 7 | 2. Create a count array of size 1000000 8 | 3. Store the count of each element in the count array 9 | 4. Modify the count array such that each element at each index stores the sum of previous counts (cumulative sum) why? 10 | For instance, 1 appears 3 times in original array, to appear number 2 next to it, we need to add 3 to the index 2 in the count array. 11 | 5. Create an output array of size same as input array 12 | 6. Traverse the input array from last and put the elements in output array using count array by decrementing the count of each element by 1. 13 | 14 | Time Complexity: O(n+k) where n is the number of elements in input array and k is the range of input. 15 | 16 | -------------------------------------------------------------------------------- /Trees/BinaryTrees/Traversal/Preorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Pre order traversal 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data){ 11 | this->data=data; 12 | this->left=nullptr; 13 | this->right=nullptr; 14 | } 15 | }; 16 | 17 | Node * buildTree(){ 18 | int data; 19 | cin>>data; 20 | if(data==-1){ 21 | return nullptr; 22 | } 23 | Node *root=new Node(data); 24 | 25 | cout<<"Enter left child of "<left=buildTree(); 27 | cout<<"Enter right child of "<right=buildTree(); 29 | 30 | return root; 31 | 32 | 33 | } 34 | 35 | 36 | 37 | 38 | // NLR pattern 39 | void preOrder(Node *root){ 40 | if(root==nullptr){ 41 | return; 42 | } 43 | cout<data<<" "; 44 | preOrder(root->left); 45 | preOrder(root->right); 46 | } 47 | 48 | int main() { 49 | Node *root=buildTree(); 50 | 51 | preOrder(root); 52 | 53 | } -------------------------------------------------------------------------------- /Trees/BinaryTrees/Traversal/PostOrder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Post order traversal 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data){ 11 | this->data=data; 12 | this->left=nullptr; 13 | this->right=nullptr; 14 | } 15 | }; 16 | 17 | Node * buildTree(){ 18 | int data; 19 | cin>>data; 20 | if(data==-1){ 21 | return nullptr; 22 | } 23 | Node *root=new Node(data); 24 | 25 | cout<<"Enter left child of "<left=buildTree(); 27 | cout<<"Enter right child of "<right=buildTree(); 29 | 30 | return root; 31 | 32 | 33 | } 34 | 35 | 36 | 37 | 38 | // LRN pattern 39 | void postOrder(Node *root){ 40 | if(root==nullptr){ 41 | return; 42 | } 43 | postOrder(root->left); 44 | postOrder(root->right); 45 | cout<data<<" "; 46 | } 47 | 48 | int main() { 49 | Node *root=buildTree(); 50 | 51 | postOrder(root); 52 | 53 | } -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/LowerBound.txt: -------------------------------------------------------------------------------- 1 | What is lower bound of an element? 2 | It is the smallest element in the set that is greater than or equal to the given element. 3 | If there is no such element, we just return the size of the array. 4 | arr[index]>=n where index is the smallest one. 5 | 6 | Code: 7 | 8 | int low=0, high=n-1; 9 | 10 | int idx=n; 11 | while(low<=high){ 12 | int mid=low+(high-low)/2; 13 | if(arr[mid]>=x){ 14 | may be this is the answer 15 | idx=mid; 16 | but we will check if there is any other element which is smaller than this 17 | high=mid-1; 18 | 19 | } else { 20 | low=mid+1; 21 | 22 | } 23 | 24 | 25 | 26 | } 27 | 28 | return idx; 29 | 30 | TC: O(logn) 31 | SC: O(1) 32 | 33 | STL: lower_bound(arr,arr+n,x)-arr; 34 | 35 | int lowerElement=lower_bound(arr.begin(), arr.end(), x)-arr.begin(); 36 | 37 | for instance if you are need to find lower bound in this array from 2 to 6 : [1,2,3,4,5,6,7,8,9] then you need to write something like this in the array 38 | lower_bound(arr.begin()+2, arr.begin()+7, x)-arr.begin(); -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/ReverseArrayInGroups.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void reverseArray(vector& arr, int start, int end) { 7 | while (start < end) { 8 | swap(arr[start], arr[end]); 9 | start++; 10 | end--; 11 | } 12 | } 13 | 14 | void reverseInGroups(vector& arr, int n, int k) { 15 | int i = 0; 16 | while (i < n) { 17 | if (i + k <= n) { 18 | reverseArray(arr, i, i + k - 1); 19 | i += k; 20 | } else { 21 | reverseArray(arr, i, n - 1); 22 | break; 23 | } 24 | } 25 | } 26 | }; 27 | 28 | 29 | // Code explanation: 30 | // https://www.geeksforgeeks.org/reverse-an-array-in-groups-of-given-size/ 31 | // 1. First we are checking wheter i+k is less than n or not. If it is less than n then we are reversing the array from i to i+k-1. 32 | // 2. If i+k is greater than n then we are reversing the array from i to n-1. 33 | -------------------------------------------------------------------------------- /Trees/BinaryTrees/Traversal/InorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // In order traversal 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data){ 11 | this->data=data; 12 | this->left=nullptr; 13 | this->right=nullptr; 14 | } 15 | }; 16 | 17 | Node * buildTree(){ 18 | int data; 19 | cin>>data; 20 | if(data==-1){ 21 | return nullptr; 22 | } 23 | Node *root=new Node(data); 24 | 25 | cout<<"Enter left child of "<left=buildTree(); 27 | cout<<"Enter right child of "<right=buildTree(); 29 | 30 | return root; 31 | 32 | 33 | } 34 | 35 | 36 | 37 | 38 | // LNR pattern 39 | void inorderTraversal(Node *root){ 40 | if(root==nullptr){ 41 | return; 42 | } 43 | inorderTraversal(root->left); 44 | cout<data<<" "; 45 | inorderTraversal(root->right); 46 | } 47 | 48 | int main() { 49 | Node *root=buildTree(); 50 | 51 | inorderTraversal(root); 52 | 53 | } -------------------------------------------------------------------------------- /Strings/Medium/RemoveAllOccurencesOfStringInMainString.txt: -------------------------------------------------------------------------------- 1 | Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: 2 | 3 | Find the leftmost occurrence of the substring part and remove it from s. 4 | Return s after removing all occurrences of part. 5 | 6 | A substring is a contiguous sequence of characters in a string. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "daabcbaabcbc", part = "abc" 13 | Output: "dab" 14 | Explanation: The following operations are done: 15 | - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". 16 | - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". 17 | - s = "dababc", remove "abc" starting at index 3, so s = "dab". 18 | Now s has no occurrences of "abc". 19 | 20 | 21 | class Solution { 22 | public: 23 | string removeOccurrences(string s, string part) { 24 | string str=s; 25 | while(str.find(part)!=std::string::npos){ 26 | int idx=str.find(part); 27 | str.erase(idx, part.size()); 28 | } 29 | 30 | return str; 31 | } 32 | }; -------------------------------------------------------------------------------- /Trees/Questions/HeightOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->left = nullptr; 14 | this->right = nullptr; 15 | } 16 | }; 17 | 18 | Node *buildTree() 19 | { 20 | int data; 21 | cin >> data; 22 | if (data == -1) 23 | { 24 | return nullptr; 25 | } 26 | Node *root = new Node(data); 27 | 28 | cout << "Enter left child of " << data << endl; 29 | root->left = buildTree(); 30 | cout << "Enter right child of " << data << endl; 31 | root->right = buildTree(); 32 | 33 | return root; 34 | } 35 | 36 | int heightOfTree(Node *root) 37 | { 38 | 39 | if (root == nullptr) 40 | { 41 | return 0; 42 | } 43 | int left = heightOfTree(root->left); 44 | int right = heightOfTree(root->right); 45 | 46 | return max(left, right) + 1; 47 | } 48 | 49 | int main() 50 | { 51 | Node *root = buildTree(); 52 | cout << heightOfTree(root); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Mohammed Faizan Ahmed 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 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/FloorAndCeil.txt: -------------------------------------------------------------------------------- 1 | You are given an sorted array, you need to find ceil and floor of a given number x. See below definitions. 2 | 1. Ceil of a number x is the smallest number in array greater than or equal to x. 3 | 2. Floor of a number x is the largest number in array smaller than or equal to x. 4 | Note: If target is not found in the array, return -1, -1 5 | 6 | 7 | 8 | pair getFloorAndCeil(int arr[], int n, int x) { 9 | // Write your code here. 10 | sort(arr, arr+n); 11 | // Ceil is the smallest number greater than or equal to x 12 | // Floor is the largest number less than or equal to x 13 | pairp; 14 | p.first=-1; 15 | p.second=-1; 16 | int low=0, high=n-1; 17 | while(low<=high){ 18 | int mid=(low+high)/2; 19 | if(arr[mid]>=x){ 20 | p.second=arr[mid]; 21 | high=mid-1; 22 | 23 | } 24 | else{ 25 | low=mid+1; 26 | } 27 | } 28 | 29 | low=0, high=n-1; 30 | while(low<=high){ 31 | int mid=(low+high)/2; 32 | if(arr[mid]<=x){ 33 | p.first=arr[mid]; 34 | low=mid+1; 35 | } 36 | else{ 37 | high=mid-1; 38 | } 39 | 40 | } 41 | 42 | return p; 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/CheckArrayIsSortedAndRotate.txt: -------------------------------------------------------------------------------- 1 | Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. 2 | 3 | There may be duplicates in the original array. 4 | 5 | Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation. 6 | 7 | class Solution { 8 | public: 9 | bool check(vector& nums) { 10 | int count=0; 11 | for(int i=1; inums[i]){ 15 | count++; 16 | } 17 | 18 | 19 | } 20 | // for rotated not proprerly or not sorted one as well. 21 | if(nums[nums.size()-1]>nums[0]){ 22 | count++; 23 | } 24 | 25 | 26 | return count<=1; 27 | 28 | } 29 | }; 30 | 31 | TC: O(N) 32 | SC: O(1) -------------------------------------------------------------------------------- /Strings/Basic/Panagram.txt: -------------------------------------------------------------------------------- 1 | Given a string check if it is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet (either lowercase or uppercase or both). For example, we say the letter A is present in the string if either 'a' is present or 'A' is present. 2 | 3 | Example 1: 4 | 5 | Input: 6 | S = Bawds jog, flick quartz, vex nymph 7 | Output: 1 8 | Explanation: In the given input, there 9 | are all the letters of the English 10 | alphabet. Hence, the output is 1. 11 | 12 | class Solution 13 | { 14 | public: 15 | //Function to check if a string is Pangram or not. 16 | bool checkPangram (string &str) { 17 | set strSet; 18 | string alpha="abcdefghijklmnopqrstuvwxyz"; 19 | 20 | for (char c : str) { 21 | if(isalpha(c)){ 22 | strSet.insert(c); 23 | 24 | } 25 | } 26 | 27 | for(int i=0; i= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. 4 | 5 | 6 | 7 | Input: g = [1,2,3], s = [1,1] 8 | Output: 1 9 | Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 10 | And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. 11 | You need to output 1. 12 | 13 | 14 | 15 | sort(s.begin(), s.end()); 16 | sort(g.begin(), g.end()); 17 | int i=0, j=0; 18 | while(i=g[i]){ 20 | count++; 21 | i++; 22 | j++; 23 | } 24 | else{ 25 | j++; 26 | } 27 | } 28 | 29 | return count; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/MoveZeoresToEnd.txt: -------------------------------------------------------------------------------- 1 | Move zeroes to end 2 | 3 | Brute: Create a temp array, insert all the elements which are not zero, then count these non-zero elements and insert the remaining zeroes at the end. 4 | TC: O(2n-x) x:number of zeroes, O(N) 5 | SC: O(n-x) x:number of zeroes O(N) n-x: number of non-zero elements 6 | 7 | https://leetcode.com/problems/move-zeroes/description/ 8 | 9 | Optimal:Use two pointers: 10 | Case 1: if first pointer element is zero and second pointer element is non-zero, swap them and increment both pointers 11 | Case 2: if first pointer element is non-zero and second pointer element is non-zero, increment both pointers 12 | Case 3: if first pointer element is zero and second pointer element is zero, increment second pointer and skip to next iteration using continue 13 | 14 | int i=0, j=1; 15 | while(j ls; 19 | 20 | O(sqrt(n)) 21 | for(int i=1; i*i<=n; i++){ 22 | if(n%i==0){ 23 | 24 | ls.push_back(i); 25 | if((n/i)!=i) 26 | ls.push_back(n/i); 27 | 28 | 29 | 30 | } 31 | } 32 | m=no of divisors 33 | O(mlogm)+O(m) 34 | 35 | sort(ls.begin(),ls.end()); 36 | for(auto it:ls) cout< 2 | using namespace std; 3 | // Level order traversal 4 | 5 | class Node { 6 | public: 7 | int data; 8 | Node *left; 9 | Node *right; 10 | Node(int data){ 11 | this->data=data; 12 | this->left=nullptr; 13 | this->right=nullptr; 14 | } 15 | }; 16 | 17 | Node * buildTree(){ 18 | int data; 19 | cin>>data; 20 | if(data==-1){ 21 | return nullptr; 22 | } 23 | Node *root=new Node(data); 24 | 25 | cout<<"Enter left child of "<left=buildTree(); 27 | cout<<"Enter right child of "<right=buildTree(); 29 | 30 | return root; 31 | 32 | 33 | } 34 | 35 | 36 | void levelOrderTraversal(Node *root){ 37 | queue q; 38 | q.push(root); 39 | while(!q.empty()){ 40 | Node *temp=q.front(); 41 | cout<data<<" "; 42 | q.pop(); 43 | if(temp->left){ 44 | q.push(temp->left); 45 | } 46 | 47 | if(temp->right){ 48 | q.push(temp->right); 49 | 50 | } 51 | 52 | } 53 | } 54 | 55 | 56 | 57 | 58 | int main() { 59 | Node *root=buildTree(); 60 | levelOrderTraversal(root); 61 | 62 | 63 | } -------------------------------------------------------------------------------- /Miscellaneous/LargestPositiveNumberExists.txt: -------------------------------------------------------------------------------- 1 | Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array. 2 | 3 | Return the positive integer k. If there is no such integer, return -1. 4 | 5 | Brute: TC:O(n^2) SC:O(1) 6 | int maximumNumber=-1; 7 | for(int i=0; i0) break; 25 | if(abs(nums[i])==nums[j]) { 26 | maximumNumber=max(maximumNumber, abs(nums[i])); 27 | i++; 28 | j--; 29 | } 30 | 31 | else if(abs(nums[i])=1; i--){ 7 | if(a%i==0 && b%i==0) return i; 8 | } 9 | return 1; 10 | 11 | TC: O(min(a,b)) 12 | SC: O(1) 13 | 14 | We are starting from reverse because, we want to find the largest number which divides both a and b. So, we are starting from min(a,b) and going till 1. 15 | 16 | Optimal: 17 | Using Euclid's Algorithm 18 | 19 | Algo: gcd(a,b)=gcd(a-b, b) a>b 20 | gcd(a,b)=gcd(a, b-a) b>a 21 | 22 | or 23 | 24 | gcd(a,b)=gcd(a%b, b) a>b 25 | gcd(a,b)=gcd(a, b%a) b>a 26 | 27 | 28 | if one of the number is 0, then return the other number. 29 | 30 | 31 | while(a>0 && b>0){ 32 | if(a>b) a=a%b; 33 | else b=b%a; 34 | 35 | } 36 | 37 | 38 | if(a==0) return b; 39 | else return a; 40 | 41 | 42 | TC: O(log(min(a,b))) 43 | Why log? 44 | Because, in each iteration, we are reducing the value of a or b by atleast half. 45 | and what is log base value? 46 | it is phi, because we don't know whether a or b is greater, so we are taking the worst case, which is phi. 47 | 48 | 49 | 50 | 51 | https://www.codingninjas.com/codestudio/problems/gcd_6557?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 -------------------------------------------------------------------------------- /Strings/Basic/RansomNote.txt: -------------------------------------------------------------------------------- 1 | Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. 2 | 3 | Each letter in magazine can only be used once in ransomNote. 4 | 5 | 6 | 7 | class Solution { 8 | public: 9 | bool canConstruct(string ran, string mag) { 10 | unordered_map mpp; 11 | for(int i=0; i0) mpp[ransomNote[i]]--; 17 | else return false; 18 | } 19 | 20 | 21 | return true; 22 | 23 | sort(ran.begin(), ran.end()); 24 | sort(mag.begin(), mag.end()); 25 | int i = 0; 26 | int j = 0; 27 | int count = 0; 28 | while(j < mag.size()) { 29 | if(ran[i] == mag[j]) { 30 | count++; 31 | i++; 32 | j++; 33 | } 34 | else j++; 35 | } 36 | return count == ran.size(); 37 | 38 | } 39 | }; 40 | 41 | https://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150 -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/MaximumProductOfThreeNumbers.txt: -------------------------------------------------------------------------------- 1 | Given an array you need to find three numbers that give you maximum product. 2 | 3 | 4 | class Solution { 5 | public: 6 | int maximumProduct(vector& nums) { 7 | extreme naive approach 8 | sort(nums.begin(), nums.end()); 9 | int n=nums.size(); 10 | return max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]); 11 | 12 | int max1=INT_MIN; 13 | int max2=INT_MIN; 14 | int max3=INT_MIN; 15 | 16 | int min1=INT_MAX; 17 | int min2=INT_MAX; 18 | 19 | for(int i=0; i=max1){ 22 | max3=max2; 23 | max2=max1; 24 | max1=nums[i]; 25 | } 26 | else if(nums[i]>=max2){ 27 | max3=max2; 28 | max2=nums[i]; 29 | } 30 | else if(nums[i]>=max3){ 31 | max3=nums[i]; 32 | } 33 | 34 | Checking for all mimimum conditions 35 | if(nums[i]<=min1){ 36 | min2=min1; 37 | min1=nums[i]; 38 | } 39 | else if(nums[i]<=min2){ 40 | min2=nums[i]; 41 | } 42 | 43 | 44 | } 45 | 46 | return max(max1*min1*min2, max1*max2*max3); 47 | } 48 | }; -------------------------------------------------------------------------------- /Strings/Basic/CommonCharacters.txt: -------------------------------------------------------------------------------- 1 | Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: words = ["bella","label","roller"] 8 | Output: ["e","l","l"] 9 | 10 | class Solution { 11 | public: 12 | vector commonChars(vector& words) { 13 | vector commonChar(26, INT_MAX); 14 | for(int i=0; i count(26, 0); 16 | for(int j=0; j result; 28 | 29 | for(int i=0; i0){ 32 | result.push_back(string(1, i+'a')); 33 | count--; 34 | } 35 | } 36 | 37 | return result; 38 | } 39 | }; -------------------------------------------------------------------------------- /Maths/BasicDivisorLCMGCD/kThFactor.txt: -------------------------------------------------------------------------------- 1 | You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0. 2 | 3 | Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors. 4 | 5 | 6 | 7 | class Solution { 8 | public: 9 | int kthFactor(int n, int k) { 10 | 11 | // first I would generate list of all factors and store in the list 12 | // vector ans; 13 | // for(int i=1; i*i<=n; i++){ 14 | // if(n%i==0){ 15 | // ans.push_back(i); 16 | // if((n/i)!=i){ 17 | // ans.push_back(n/i); 18 | // } 19 | 20 | // }} 21 | // // sort(ans.begin(), ans.end()); 22 | 23 | // // if(ans.size()maxSum, you can update end=i 25 | 26 | 27 | Bonus: if in question, it says to return empty sub array as well, which means the maxSum>0, then you can just return maxSum as 0 and return empty array 28 | https://leetcode.com/problems/maximum-subarray/description/ 29 | 30 | 31 | TC: O(n) 32 | SC: O(1) 33 | -------------------------------------------------------------------------------- /Miscellaneous/CheckIfStraightLine.txt: -------------------------------------------------------------------------------- 1 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 2 | 3 | https://leetcode.com/problems/check-if-it-is-a-straight-line/description/ 4 | 5 | class Solution { 6 | public: 7 | bool checkStraightLine(vector>& coordinates) { 8 | int x1=coordinates[0][0]; 9 | int x2=coordinates[1][0]; 10 | 11 | int y1=coordinates[0][1]; 12 | int y2=coordinates[1][1]; 13 | 14 | int xDiff=x2-x1; 15 | int yDiff=y2-y1; 16 | 17 | // Starting from third point 18 | for (int i = 2; i < coordinates.size(); i++) { 19 | // x3-x1/x2-x1 == y3-y1/y2-y1 should satisfy the condition 20 | // to avoid any zero exception error, we mulitply with difference on either side. 21 | // In the case of a straight line, all points on that line will have the same slope with respect to any two points on the line. So, we can compare the slopes between the initial two points (x1, y1) and (x2, y2) and each subsequent point (currX, currY). 22 | int currX = coordinates[i][0]; 23 | int currY = coordinates[i][1]; 24 | 25 | if ((currX - x1) * yDiff != (currY - y1) * xDiff) { 26 | return false; 27 | } 28 | } 29 | 30 | 31 | return true; 32 | } 33 | }; -------------------------------------------------------------------------------- /Strings/Basic/ValidAnagram.txt: -------------------------------------------------------------------------------- 1 | Given two strings s and t, return true if t is an anagram of s, and false otherwise. 2 | 3 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: s = "anagram", t = "nagaram" 10 | Output: true 11 | 12 | 13 | class Solution { 14 | public: 15 | bool isAnagram(string s, string t) { 16 | TC:O(NlogN+MlogM) 17 | sort(s.begin(), s.end()); 18 | sort(t.begin(), t.end()); 19 | 20 | return s==t; 21 | 22 | TC: O(2N+M) SC: O(N) 23 | unordered_map mpp; 24 | for(int i=0; i> shiftGrid(vector>& grid, int k) { 15 | vector oneD; 16 | vector> ans; 17 | int n=grid.size(); 18 | int m=grid[0].size(); 19 | 20 | for(int i=0; i row; 34 | for(int j=0; j ans; 10 | vector visited(arr2.size(), 0); 11 | for(int i=0; ifor array to return the answer 8 | 9 | 10 | 11 | Optimal Approach: Use two pointers 12 | 13 | take two pointers, one for each array 14 | 1. if element at first pointer is less than element at second pointer, then insert first element in the answer array and increment first pointer also check whether the element is already present in the answer array or not using v.back() != arr1[i] 15 | 16 | 2. if element at first pointer is greater than element at second pointer, then insert second element in the answer array and increment second pointer also check whether the element is already present in the answer array or not using v.back() != arr2[j] 17 | 18 | If any array is left, then insert all the elements of that array in the answer array and be sure to check v.back() != arr1[i] or v.back() != arr2[j] 19 | 20 | TC: O(n1+n2) 21 | SC: O(n1+n2) only for returning the answer array 22 | 23 | */ 24 | 25 | https://www.codingninjas.com/codestudio/problems/sorted-array_6613259?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 -------------------------------------------------------------------------------- /Stacks/Implementation/ImplementUsingQueues.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | // usign two queues 6 | // of course we can use here queue in class implementation 7 | queue q1; 8 | queue q2; 9 | int i=0; 10 | int num; 11 | while(i<5){ 12 | cout<<"Enter a number to insert into stack"<>num; 14 | // algo: 15 | // 1. Push element to q2 16 | // 2. add element by element to q2 until q1 is not empty 17 | // 3. swap q1 and q2 18 | q2.push(num); 19 | while(!q1.empty()){ 20 | q2.push(q1.front()); 21 | q1.pop(); 22 | } 23 | swap(q1, q2); 24 | i++; 25 | 26 | } 27 | 28 | 29 | while(!q1.empty()){ 30 | cout< q3; 41 | int j=0; 42 | while(j<5){ 43 | cout<<"Enter the number that you want to insert into the stack:"<>x; 46 | q3.push(x); 47 | for(int i=0; i arr2; 9 | int count1=0, count0=0; 10 | 11 | // O(N) 12 | for(int i=0; i 2 | using namespace std; 3 | class Cqueue{ 4 | public: 5 | int data; 6 | int size; 7 | int rear; 8 | int front; 9 | int *arr; 10 | 11 | Cqueue(int size){ 12 | arr=new int[size]; 13 | this->size=size; 14 | this->rear=-1; 15 | this->front=-1; 16 | } 17 | 18 | void push(int data){ 19 | // if we are inserting first element 20 | if((front==0 && rear==size-1) || rear==front-1){ 21 | 22 | cout<<"Queue is full"<0){ 27 | if(ans[ans.size()-1]==s[i]){ 28 | ans.pop_back(); 29 | 30 | } 31 | else{ 32 | 33 | ans.push_back(s[i]); 34 | } 35 | 36 | } 37 | else{ 38 | ans.push_back(s[i]); 39 | } 40 | } 41 | 42 | return ans; 43 | } 44 | }; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/LeadersInArray.txt: -------------------------------------------------------------------------------- 1 | Find leaders in an array 2 | 3 | Explanation: This means the element is greater than all the elements to its right side. The rightmost element is always a leader. 4 | 5 | Brute: 6 | Always compare for an element to the right side of it. If it is greater than all the elements to its right side, then it is a leader. 7 | vector result; 8 | for(int i=0; i=0; i--){ 31 | if(a[i]>=maxi){ 32 | maxi=a[i]; 33 | result.push_back(a[i]); 34 | } 35 | 36 | } 37 | 38 | reverse(result.begin(), result.end()); 39 | 40 | TC: O(n) 41 | SC: O(N) 42 | 43 | https://practice.geeksforgeeks.org/problems/leaders-in-an-array-1587115620/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchSorted/FindMinimumInSorted.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: 4 | 5 | [4,5,6,7,0,1,2] if it was rotated 4 times. 6 | [0,1,2,4,5,6,7] if it was rotated 7 times. 7 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 8 | 9 | Given the sorted rotated array nums of unique elements, return the minimum element of this array. 10 | 11 | You must write an algorithm that runs in O(log n) time. 12 | 13 | 14 | class Solution { 15 | public: 16 | int findMin(vector& nums) { 17 | // int minElement=*min_element(nums.begin(), nums.end()); 18 | // return minElement; 19 | 20 | 21 | int low=0, high=nums.size()-1; 22 | int ans=INT_MAX; 23 | while(low<=high){ 24 | int mid=(low+high)/2; 25 | // first checking for sorted part, if they are sorted, then pick for the minimum number from it and then elimnate that part. 26 | if(nums[mid]<=nums[high]){ 27 | ans=min(ans, nums[mid]); 28 | high=mid-1; 29 | } 30 | else{ 31 | low=mid+1; 32 | } 33 | } 34 | return ans; 35 | } 36 | } 37 | 38 | TC: O(logn) Worst: O(n/2) if it contains duplicates 39 | -------------------------------------------------------------------------------- /Maths/UglyNumber.txt: -------------------------------------------------------------------------------- 1 | An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. 2 | 3 | Given an integer n, return true if n is an ugly number. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: n = 6 10 | Output: true 11 | Explanation: 6 = 2 × 3 12 | Example 2: 13 | 14 | Input: n = 1 15 | Output: true 16 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 17 | 18 | 19 | class Solution { 20 | public: 21 | bool isUgly(int n) { 22 | if(n==1) return 1; 23 | if(n<=0) return 0; 24 | vector primes={2,3,5}; 25 | for(int i=0; i> ans(rows, vector(cols, 0)); 12 | for(int i=0; i[1][0] 31 | [0][2]-->[2][0] 32 | [0][3]-->[3][0] 33 | 34 | [1][2] --> [2][1] 35 | [1][3] --> [3][1] 36 | 37 | [2][3] --> [3][2] 38 | 39 | for(int j=i+1; j0){ 18 | int last_digit=n%10; 19 | digitSum+=last_digit*last_digit; 20 | n/=10; 21 | } 22 | 23 | return digitSum; 24 | } 25 | public: 26 | bool isHappy(int n) { 27 | unordered_set set; 28 | // The main funda here is, if the number appears twice, the cycle will repeat again which you don't want. So if the number appears again, you will return false. 29 | while(true) { 30 | if (n == 1) { 31 | return true; 32 | } 33 | if (set.count(n)) { 34 | return false; 35 | } 36 | set.insert(n); 37 | n = getSum(n); 38 | } 39 | 40 | 41 | 42 | } 43 | TC: O(klogn) where k is the maximum number of iterations in the while loop and n is the value of the input number. 44 | } -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/LeftRotateArrayByDPlaces.txt: -------------------------------------------------------------------------------- 1 | D=D%N 2 | Left rotate an array by one place: 3 | Optimal:(direct): Store first value of array in temp variable, then shift all elements to left by one place, then store temp variable in last place of array. 4 | Time complexity: O(n) 5 | Auxiliary space: O(1) 6 | Space Complexity: O(n)(Modifying the array) 7 | https://www.codingninjas.com/codestudio/problems/left-rotate-an-array-by-one_5026278?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 8 | 9 | 10 | 11 | Left rotate an array by d places: 12 | Brute: Just take one temp variable and store the array items from 0 to d-1 in it, then shift all elements to left by d places, then store temp variable in last d places of array. 13 | https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements-1587115621/1 14 | 15 | 16 | vector temp; 17 | int k=d%n; 18 | for(int i=0; i& nums) { 14 | // brute force approach 15 | // int maxElement=max_element(nums.begin(), nums.end())-nums.begin(); 16 | // return maxElement; 17 | 18 | 19 | 20 | 21 | if(nums.size()==1) return 0; 22 | if(nums[0]>nums[1]) return 0; 23 | if(nums[nums.size()-1]>nums[nums.size()-2]) return nums.size()-1; 24 | 25 | int low=0, high=nums.size()-1; 26 | 27 | while(low<=high){ 28 | long long mid=(low+high)/2; 29 | 30 | 31 | if(nums[mid]>nums[mid+1] and nums[mid]>nums[mid-1]){ 32 | return mid; 33 | } 34 | if(nums[low]>=nums[mid] or nums[mid-1]>nums[mid]){ 35 | high=mid-1; 36 | } 37 | else{ 38 | low=mid+1; 39 | } 40 | 41 | 42 | 43 | 44 | } 45 | 46 | 47 | 48 | 49 | return low+1; 50 | 51 | } 52 | }; -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Hard/FindMinimumInSorted2.txt: -------------------------------------------------------------------------------- 1 | 2 | Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: 3 | 4 | [4,5,6,7,0,1,4] if it was rotated 4 times. 5 | [0,1,4,4,5,6,7] if it was rotated 7 times. 6 | Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. 7 | 8 | Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array. 9 | 10 | You must decrease the overall operation steps as much as possible. 11 | 12 | 13 | 14 | class Solution { 15 | public: 16 | int findMin(vector& nums) { 17 | 18 | int low=0, high=nums.size()-1; 19 | int ans=INT_MAX; 20 | while(low<=high){ 21 | int mid=(low+high)/2; 22 | // first checking for sorted part, if they are sorted, then pick for the minimum number from it and then elimnate that part. 23 | if(nums[mid]==nums[high] && nums[mid]==nums[low]){ 24 | ans=min(ans, nums[mid]); 25 | low++; 26 | high--; 27 | continue; 28 | } 29 | 30 | if(nums[mid]<=nums[high]){ 31 | ans=min(ans, nums[mid]); 32 | high=mid-1; 33 | } 34 | else{ 35 | low=mid+1; 36 | } 37 | } 38 | return ans; 39 | } 40 | }; 41 | 42 | 43 | TC: O(logn) Worst: O(n/2) if it contains duplicates -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/SubArrays/AllSubArraysGivenSum.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | 5 | 6 | Brute force approach 7 | int count=0; 8 | for(int i=0; i mpp; 43 | 44 | mpp[0]=1; 45 | int prefixSum=0; 46 | 47 | for(int i=0;i& nums, int n) { 7 | 8 | int count=0; 9 | bool inserted=false; 10 | int i=0; 11 | // TC: O(n) SC:O(1) 12 | // Checking the flowerbed, if they are inserted, already mark them as false, and check next one whether next one is one or not and whether the previous one is inserted or not, if the condition becomes true, we increase the count and mark inserted as true and if the condition does not satisfy, mark inserted as false and skip to next iteration. 13 | for(; i=n){ 30 | return true; 31 | } 32 | 33 | return false; 34 | } -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Medium/RearrangePostiveAndNegative.txt: -------------------------------------------------------------------------------- 1 | Rearrange postive and negative numbers 2 | 3 | Brute: 4 | Take two arrays of postive and negative arrays, and then merge them together 5 | vector positives; 6 | vector negatives; 7 | 8 | 9 | for(int i=0; i0) positives.push_back(nums[i]); 11 | else negatives.push_back(nums[i]); 12 | } 13 | 14 | int positiveIndex=0, negativeIndex=0; 15 | for(int i=0; i ans(nums.size(),0); //initialise with 0 33 | int positiveIndex=0, negativeIndex=1; 34 | for(int i=0; i0){ 36 | ans[positiveIndex]=nums[i]; 37 | positiveIndex+=2; 38 | } 39 | else{ 40 | ans[negativeIndex]=nums[i]; 41 | negativeIndex+=2; 42 | } 43 | } 44 | 45 | 46 | 47 | return ans; 48 | TC: O(n) 49 | SC: O(n) 50 | 51 | https://leetcode.com/problems/rearrange-array-elements-by-sign/description/ -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Sorting/InsertionSort.txt: -------------------------------------------------------------------------------- 1 | Given an array, sort array using insertion sort 2 | 3 | 4 | Appraoach: 5 | 1. First fetch the element 6 | 2. Compare the element with the previous element 7 | 3. If the previous element is greater than the current element, then move the previous element to the right side and move the current element to the previous position. or shift the element to the right side. 8 | 4. If the previous element is smaller than the current element, then break the loop. 9 | 5. Copy the current element to the previous position. 10 | 11 | for(int i=1; i=0; j--){ 16 | if the previous element is greater than the current element then move that previous element to the right side and move that current element to the previous position. 17 | if(arr[j]>value){ 18 | arr[j+1]=arr[j]; 19 | } 20 | if the element is already in a correct position we get out of the damn loop. 21 | else{ 22 | break; 23 | } 24 | } 25 | Now, here's the tricky part, when comparing j might have moved a postion extra to left side, hence we need to equate that value to current temp value. 26 | 1 7 10 8: while comparing, 8 with 10, j has moved left and again it has moved left at position 7 is present hence we need to move 10 not 7, hence j+1 equal to i. 27 | arr[j+1]=value; 28 | } 29 | 30 | TC: O(n^2) 31 | SC: O(1) 32 | 33 | 34 | Best case: O(n) (if the array is already sorted) 35 | -------------------------------------------------------------------------------- /Strings/Basic/LargestCommonPrefix.txt: -------------------------------------------------------------------------------- 1 | Write a function to find the longest common prefix string amongst an array of strings. 2 | 3 | If there is no common prefix, return an empty string "". 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: strs = ["flower","flow","flight"] 10 | Output: "fl" 11 | 12 | class Solution { 13 | public: 14 | 15 | string longestCommonPrefix(vector& v) { 16 | 17 | TC: O(n*m) where n is the size of the first string and m is the size of vector (m-1) 18 | SC: O(1) (we are just using the space to return the answer) 19 | if(strs.size()==1) return strs[0]; 20 | string ans=""; 21 | int i=1; 22 | string first=strs[0]; 23 | while(i<=strs[0].size()){ 24 | bool yes=false; 25 | for(int j=1; j spiralOrder(vector>& matrix) { 4 | printing spiral matrix 5 | TC:O(n*m) because we are checking for each condition 6 | 7 | 8 | 9 | int n=matrix.size(); 10 | int m=matrix[0].size(); 11 | vector ans; 12 | int top=0, bottom=n-1; 13 | int left=0, right=m-1; 14 | 15 | while(top<=bottom && left<=right){ 16 | moving from left to right 17 | for(int i=left; i<=right; i++){ 18 | ans.push_back(matrix[top][i]); 19 | } 20 | 21 | top++; 22 | 23 | moving from top to bottom 24 | for(int i=top; i<=bottom; i++){ 25 | ans.push_back(matrix[i][right]); 26 | } 27 | right--; 28 | 29 | moving from right to left 30 | imagine there is a single row and and top has already increased, but we are again going from right to left, what you will print?? 31 | if(top<=bottom){ 32 | for(int i=right; i>=left; i--){ 33 | ans.push_back(matrix[bottom][i]); 34 | } 35 | bottom--; 36 | 37 | } 38 | 39 | moving from bottom to top 40 | now when spiral ends, there will be no top, so there must be some elements in between left and right.. 41 | if(left<=right){ 42 | for(int i=bottom; i>=top; i--){ 43 | ans.push_back(matrix[i][left]); 44 | } 45 | left++; 46 | 47 | } 48 | } 49 | 50 | 51 | 52 | 53 | return ans; 54 | 55 | 56 | } 57 | }; -------------------------------------------------------------------------------- /Strings/Medium/LongestOddLengthSubString.txt: -------------------------------------------------------------------------------- 1 | You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. 2 | 3 | A substring is a contiguous sequence of characters within a string. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: num = "52" 10 | Output: "5" 11 | Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. 12 | 13 | 14 | class Solution { 15 | public: 16 | string largestOddNumber(string num) { 17 | // reverse(num.begin(), num.end()); 18 | // long long nums=stoi(num); 19 | // string ans=""; 20 | 21 | // long long result=0; 22 | // int maxOdd=-1; 23 | 24 | // while(nums!=0){ 25 | // int lastDigit=nums%10; 26 | // if(lastDigit%2!=0){ 27 | // maxOdd=max(lastDigit, maxOdd); 28 | 29 | // } 30 | // result=result*10+lastDigit; 31 | // if(result%2!=0){ 32 | 33 | // if(result>maxOdd){ 34 | // result=maxOdd; 35 | // } 36 | 37 | // } 38 | // nums/=10; 39 | // } 40 | 41 | 42 | 43 | // return maxOdd!=-1 ? to_string(maxOdd) : ""; 44 | 45 | 46 | 47 | // TC: O(N) SC:O(1) 48 | string ans; 49 | 50 | for(int i=num.size()-1; i>=0; i--){ 51 | if((num[i]-'0')%2!=0){ 52 | ans=num.substr(0, i+1); 53 | break; 54 | } 55 | } 56 | 57 | return ans; 58 | } 59 | }; -------------------------------------------------------------------------------- /Strings/Medium/SortCharactersAccrodingToFrequency.txt: -------------------------------------------------------------------------------- 1 | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. 2 | 3 | Return the sorted string. If there are multiple answers, return any of them. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: s = "tree" 10 | Output: "eert" 11 | Explanation: 'e' appears twice while 'r' and 't' both appear once. 12 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 13 | 14 | 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | string frequencySort(string s) { 22 | // using bucket sort technique which is also useful for top k elements and top k words 23 | unordered_map mpp; 24 | string ans; 25 | // declaring a bucket size of n+1 26 | vector bucket(s.size()+1, ""); 27 | 28 | // storing the element frequency count in hashmap 29 | for(int i=0; i0; i--){ 45 | if(!bucket[i].empty()){ 46 | ans.append(bucket[i]); 47 | } 48 | } 49 | 50 | return ans; 51 | 52 | } 53 | }; -------------------------------------------------------------------------------- /Arrays/Binary Search/ExponentialSearch/ExponentialSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(vector arr, int st, int end, int key) { 5 | while (st <= end) { 6 | int mid = (st + end) / 2; 7 | if (arr[mid] == key) { 8 | return mid; 9 | } else if (arr[mid] > key) { 10 | end = mid - 1; 11 | } else { 12 | st = mid + 1; 13 | } 14 | } 15 | return -1; 16 | } 17 | 18 | // Exponential search meaning: 19 | // 1. Find the range where the element is present 20 | // 2. Do binary search in that range 21 | 22 | // Just we are doubling the size of the array, and wherever we find element greater than the key, we do binary search in that range. 23 | // Time complexity: O(log(2^m-1)) = O(log(n-i) 24 | // First we are taking logn iterations, for example when we reach index 16, we have done 4 iterations, so we have done logn iterations. 25 | // The length of subarray could be 2^4-2^3 which is 8, so we have to do log(8) iterations, so total time complexity is O(logn+log(2^m-1)) = O(logn) 26 | 27 | int exponentialSearch(vector arr, int k) { 28 | if (arr[0] == k) { 29 | return 0; 30 | } 31 | int size=sizeof(arr)/sizeof(int); 32 | 33 | int i = 1; 34 | while (i < arr.size() && arr[i] <= k) { 35 | i = i * 2; 36 | } 37 | int ans = binarySearch(arr, i / 2, min(i, size-1), k); 38 | return ans; 39 | } 40 | 41 | int main() { 42 | // exponential search 43 | vector arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 44 | int key = 4; 45 | int ans = exponentialSearch(arr, key); 46 | cout << "Your answer is present at index: " << ans << endl; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/SubArrays/SubArrayWithOddLength.txt: -------------------------------------------------------------------------------- 1 | Given an array you need to find sum of all subarrays whose lenght is odd 2 | 3 | class Solution { 4 | public: 5 | int sumOddLengthSubarrays(vector& arr) { 6 | int sum=0; 7 | TC: O(n^3) SC:O(1) 8 | for(int i=0; i v1, int k, int start) { 24 | for (int i = start; i < v1.size(); i++) { 25 | if (v1[i] > k) { 26 | return v1[i]; 27 | } 28 | } 29 | return -1; 30 | } 31 | 32 | vector nextGreaterElement(vector& nums1, vector& nums2) { 33 | vector ans; 34 | for (int i = 0; i < nums1.size(); i++) { 35 | int j = 0; 36 | while (j < nums2.size()) { 37 | if (nums1[i] == nums2[j]) { 38 | int result = linearSearch(nums2, nums2[j], j); 39 | if (result != -1) { 40 | ans.push_back(result); 41 | } else { 42 | ans.push_back(-1); 43 | } 44 | break; 45 | } 46 | j++; 47 | } 48 | } 49 | return ans; 50 | } 51 | }; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/FindAllMissingNumbersFromDuplicates.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | bool checkElement(vector nums, int key){ 4 | for(int i=0; i findDisappearedNumbers(vector& nums) { 11 | 12 | vector ans; 13 | O(n^2) SC:O(1) I am using just extra space to return the answer 14 | for(int i=1; i<=nums.size(); i++){ 15 | if(!checkElement(nums, i)){ 16 | ans.push_back(i); 17 | } 18 | } 19 | 20 | 21 | 22 | 23 | 24 | unordered_set st; 25 | SC: O(n)+O(1) TC: O(2n) 26 | for(int i=0; i 0) 46 | nums[abs(nums[i]) - 1] *= -1; 47 | } 48 | 49 | A positive element means that the element (index + 1) does not appear in the array, so save it 50 | for (int i = 0; i < nums.size(); ++i) 51 | if (nums[i] > 0) 52 | ans.push_back(i + 1); 53 | 54 | return ans; 55 | 56 | } 57 | 58 | 59 | }; -------------------------------------------------------------------------------- /Stacks/Implementation/WithArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Stack Implmentation using array 6 | class Stack{ 7 | public: 8 | int size; 9 | int top; 10 | int *arr; 11 | 12 | Stack(int size){ 13 | this->size=size; 14 | arr=new int[size]; 15 | top=-1; 16 | } 17 | 18 | void push(int data){ 19 | if(size-top>1){ 20 | top++; 21 | arr[top]=data; 22 | } 23 | else{ 24 | cout<<"Stack overflow"< st; 65 | st.push(10); 66 | st.push(30); 67 | st.push(40); 68 | st.push(50); 69 | 70 | cout<) or 24 | use hash array and take maximum number from it.(but will not work for negative numbers) 25 | SC: O(n) 26 | 27 | 28 | TC: O(n) 29 | 30 | here is the catch, for map, storing elements: O(NlogM) M is the size of map, and N is size of array 31 | When checking for count in map, the iteration will go O(N/2+1) +1 is unique number and other are duplicate numbers 32 | So, TC: O(NlogM) + O(N/2+1) = O(NlogM) + O(N) = O(NlogM) 33 | 34 | 35 | 36 | Store the number and its frequency in the hashmap 37 | if frequency is 1, return that number 38 | 39 | IMPORTANT: 40 | UNORDERED MAP CAN GO O(1) IN BEST CASE, BUT IF THE INPUTS ARE CRITICAL AND LARGE, IT CAN GO O(N^2) IN WORST CASE 41 | ORDERED MAP WILL ALWAYS GO O(N) IN WORST CASE 42 | 43 | BUT IN THIS QUESTION, UNORDERED MAP GOES IN O(N) 44 | 45 | 46 | 47 | 48 | Optimal: Use XOR 49 | TC: O(n) 50 | SC: O(1) 51 | XOR of a number with itself is 0 52 | 53 | https://leetcode.com/problems/single-number/description/ 54 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Prefix/FindRightAndLeftDifferences.txt: -------------------------------------------------------------------------------- 1 | 2 | Given a 0-indexed integer array nums, find a 0-indexed integer array answer where: 3 | 4 | answer.length == nums.length. 5 | answer[i] = |leftSum[i] - rightSum[i]|. 6 | Where: 7 | 8 | leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i] = 0. 9 | rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0. 10 | Return the array answer. 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | vector leftRightDifference(vector& nums) { 19 | vector prefixSum(nums.size(), 0); 20 | int n=nums.size(); 21 | vector ans; 22 | vector suffixSum(nums.size(), 0); 23 | prefixSum[0]=0; 24 | suffixSum[nums.size()-1]=0; 25 | for(int i=1; i ans; 36 | int rsum=0; 37 | int lsum=0; 38 | 39 | for(int i=0; i(INT_MAX)/10 || (ans==(INT_MAX)/10 && s[i]>'7')){ 45 | return sign==-1 ? INT_MIN : INT_MAX; 46 | } 47 | 48 | ans=ans*10+(s[i]-'0'); 49 | i++; 50 | } 51 | 52 | // return the answer with sign, if none of the cases satisfy, we can return answer as zero strightforward. 53 | return ans*sign; 54 | } 55 | }; 56 | 57 | TC: O(n) 58 | SC: O(1) -------------------------------------------------------------------------------- /Arrays/2-D Arrays/Medium/PascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int findNCR(int n, int r) 4 | { 5 | // For example: if 5C3 given, then: 5*4*3/1*2*3 or we can also do this way... 6 | // 5/1 * 4/2 * 3/3 7 | 8 | int ans = 1; 9 | for (int i = 1; i <= r; i++) 10 | { 11 | ans = ans * (n - i + 1); 12 | ans = ans / i; 13 | } 14 | 15 | return ans; 16 | } 17 | 18 | int printVariant1(int n, int r) 19 | { 20 | // Formula : r-1Cc-1 21 | // TC: O(r) 22 | int ans = findNCR(n, r); 23 | return ans; 24 | } 25 | 26 | void printVariant2(int row) 27 | { 28 | // Here row is given 29 | int ans = 1; 30 | cout<> i; 61 | 62 | cout << "Enter column" << endl; 63 | cin >> j; 64 | 65 | // TC: O(r) 66 | cout << printVariant1(i - 1, j - 1) << endl; 67 | 68 | printVariant2(5); 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Arrays/Binary Search/2-D Arrays/Medium/SearchIn2DMatrix1.txt: -------------------------------------------------------------------------------- 1 | Each row is sorted in non-decreasing order. 2 | The first integer of each row is greater than the last integer of the previous row. 3 | Given an integer target, return true if target is in matrix or false otherwise. 4 | 5 | You must write a solution in O(log(m * n)) time complexity. 6 | 7 | 8 | 9 | class Solution { 10 | public: 11 | bool searchMatrix(vector>& matrix, int target) { 12 | // first i would perform linear search 13 | // for(int i=0; itarget){ 37 | high=mid-1; 38 | } 39 | else{ 40 | low=mid+1; 41 | } 42 | } 43 | 44 | return false; 45 | } 46 | }; 47 | 48 | 49 | Time Complexity: O(log(m*n)) 50 | Space Complexity: O(1) 51 | 52 | To calcuate last index: rows*cols-1 53 | To get specific rows and cols: divide mid value to no of cols the quotient will give you row and the mod will give you the column -------------------------------------------------------------------------------- /Arrays/Binary Search/ExponentialSearch/FindElementInAnInfiniteSortedArray.cpp: -------------------------------------------------------------------------------- 1 | // You are given an infinite length sorted array and you need to find an element in it, without knowing the length of the array. 2 | 3 | // You can apply exponential searh here 4 | #include 5 | using namespace std; 6 | int findElementInInfiniteSortedArrayBruteForceApproach(vector arr, int key) 7 | { 8 | // using brute force solution 9 | if (arr[0] == key) 10 | return 0; 11 | int i = 1; 12 | while (1) 13 | { 14 | if (arr[i] > key) 15 | { 16 | break; 17 | } 18 | if (arr[i] == key) 19 | { 20 | return i; 21 | } 22 | i++; 23 | } 24 | return -1; 25 | } 26 | 27 | int binarySearch(vector arr, int st, int end, int key) 28 | { 29 | while (st <= end) 30 | { 31 | int mid = (st + end) / 2; 32 | if (arr[mid] == key) 33 | { 34 | return mid; 35 | } 36 | else if (arr[mid] > key) 37 | { 38 | end = mid - 1; 39 | } 40 | else 41 | { 42 | st = mid + 1; 43 | } 44 | } 45 | return -1; 46 | } 47 | 48 | int findElementUsingExponentialSearch(vector arr, int key) 49 | { 50 | int i = 0, j = 1; 51 | 52 | while (arr[j] <= key) 53 | { 54 | i = j; 55 | j = j * 2; 56 | } 57 | // finding the size of array 58 | int size = sizeof(arr) / sizeof(int); 59 | 60 | return binarySearch(arr, i, min(j, size - 1), key); 61 | } 62 | 63 | int main() 64 | { 65 | vector arr = {1, 2, 4, 5, 6, 7, 8, 9, 10}; 66 | int key = 3; 67 | int ans = findElementInInfiniteSortedArrayBruteForceApproach(arr, key); 68 | cout << "Element at this index is: " << ans << endl; 69 | 70 | return 0; 71 | } 72 | 73 | // TC: O(logn) -------------------------------------------------------------------------------- /Strings/Medium/ReorganizeStrings.txt: -------------------------------------------------------------------------------- 1 | Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. 2 | 3 | Return any possible rearrangement of s or return "" if not possible. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: s = "aab" 10 | Output: "aba" 11 | 12 | 13 | string reorganizeString(string s) { 14 | // creating a hash array 15 | int hash[26]={0}; 16 | for(int i=0; imaxFrequency){ 25 | maxFrequency=hash[i]; 26 | char_max_freq=i+'a'; 27 | } 28 | } 29 | 30 | int index=0; 31 | while(maxFrequency>0 && index0){ 44 | index=index>=s.size() ? 1 : index; 45 | s[index]=i+'a'; 46 | hash[i]--; 47 | index+=2; 48 | } 49 | } 50 | 51 | return s; 52 | 53 | } 54 | 55 | 56 | Algorithm: 57 | 1. Create a hash array to store the frequency of each character. 58 | 2. Find the character with the maximum frequency. 59 | 3. Place the character with the maximum frequency at the even indices. 60 | 4. If the maximum frequency is greater than half the size of the string, then return an empty string. 61 | 5. Place the remaining characters at the odd indices. 62 | 6. Return the string. 63 | -------------------------------------------------------------------------------- /Queues/Implementation/ImplemenetUsingArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Queue{ 5 | public: 6 | int size; 7 | int front; 8 | int rear; 9 | int *arr; 10 | // rear is always pointing to empty cell in array 11 | 12 | Queue(int size){ 13 | this->size=size; 14 | this->rear=0; 15 | this->front=0; 16 | arr=new int[size]; 17 | } 18 | 19 | bool isEmpty(){ 20 | if(rear==front){ 21 | return true; 22 | } 23 | return false; 24 | } 25 | 26 | int getSize(){ 27 | return rear-front; 28 | } 29 | 30 | void pop(){ 31 | if(rear==front){ 32 | cout<<"Queue is empty"< q; 72 | // q.push(4); 73 | // q.push(5); 74 | // cout<& nums, int k) { 13 | int count=0; 14 | // O(N^2) SC:O(1) 15 | // for(int i=0; i mpp; 31 | 32 | // for(int i=0; i0){ 35 | // mpp[remaining]--; 36 | // count++; 37 | // } 38 | // else{ 39 | // mpp[nums[i]]++; 40 | // } 41 | // } 42 | 43 | 44 | // Better solution 45 | sort(nums.begin(), nums.end()); 46 | // Two pointer approach 47 | int low=0, high=nums.size()-1; 48 | 49 | while(lowk){ 57 | high--; 58 | } 59 | else if(nums[low]+nums[high] 2 | #include 3 | using namespace std; 4 | 5 | class Stack{ 6 | public: 7 | int size; 8 | int top1; 9 | int top2; 10 | int *arr; 11 | 12 | Stack(int size){ 13 | this->size=size; 14 | arr=new int[size]; 15 | top1=-1; 16 | top2=size; 17 | } 18 | 19 | 20 | void push1(int data){ 21 | if(top2-top1==1){ 22 | cout<<"Stack 1 is overflown"< mpp; 26 | mpp[0]=1; 27 | int XR=0; 28 | 29 | for(int i=0; i=0 && end& arr, int k) { 20 | // for(int i=0; iK && i<=j){ 60 | sum-=a[i]; 61 | i++; 62 | } 63 | 64 | if(sum==K){ 65 | longestLength=max(longestLength, j-i+1); 66 | } 67 | 68 | 69 | 70 | j++; 71 | 72 | 73 | sum +=a[j]; 74 | 75 | 76 | } 77 | 78 | TC: O(2n) SC: O(1) 79 | 80 | https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1 -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/SecondLargestAndSmallest.txt: -------------------------------------------------------------------------------- 1 | Find second largest element in array: 2 | 3 | 4 | Brute:(sort beforehand) find first largest element, now we know second largest will be at arr[n-2] position, start iterating from backward and to return element, take a variable secondLargest, if (arr[i]secondLargest) secondLargest=arr[i] return secondLargest 5 | 6 | For smallest: find first smallest element, now we know second smallest will be at arr[1] position, start iterating from forward and to return element, take a variable secondSmallest, if (arr[i]>smallest && arr[i]secondLargest && arr[i]smallest) secondSmallest=arr[i] return secondSmallest. 21 | 22 | 23 | TC: O(n)(first pass, for largest)+O(n)(for second pass, for second largest) = O(n) 24 | SC: O(1) 25 | 26 | 27 | 28 | 29 | Optimal: Taking two variables, largest=arr[0], secondLargest=-1 30 | 1. Do nothing, if the largest number is equivalent 31 | 2. If number is smaller than largest, then take that as second largest element 32 | 33 | https://practice.geeksforgeeks.org/problems/find-the-smallest-and-second-smallest-element-in-an-array3226/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article 34 | 35 | TC: O(n) 36 | SC: O(1) 37 | 38 | 39 | All the three approaches: 40 | https://www.codingninjas.com/codestudio/problems/ninja-and-the-second-order-elements_6581960?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 41 | 42 | 43 | 44 | WORKS FOR DUPLICATE -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/AdditionOfArrays.txt: -------------------------------------------------------------------------------- 1 | Given two array A[0….N-1] and B[0….M-1] of size N and M respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the numbers. 2 | 3 | Example 1: 4 | 5 | Input : A[] = {1, 2}, B[] = {2, 1} 6 | Output : 33 7 | Explanation: 8 | N=2, and A[]={1,2} 9 | M=2, and B[]={2,1} 10 | Number represented by first array is 12. 11 | Number represented by second array is 21 12 | Sum=12+21=33 13 | 14 | 15 | 16 | 17 | Code: 18 | 19 | class Solution{ 20 | public: 21 | string calc_Sum(int *a,int n,int *b,int m){ 22 | // Complete the function 23 | string ans; 24 | int i=n-1, j=m-1; 25 | int carry=0; 26 | while(i>=0 && j>=0){ 27 | int sum=a[i]+b[j]+carry; 28 | int lastDigit=sum%10; 29 | ans.push_back(lastDigit+'0'); 30 | carry=sum/10; 31 | 32 | i--; 33 | j--; 34 | } 35 | 36 | 37 | 38 | // What if the first number is still left we can still iterate on it 39 | while(i>=0){ 40 | int sum=a[i]+0+carry; 41 | int lastDigit=sum%10; 42 | ans.push_back(lastDigit+'0'); 43 | carry=sum/10; 44 | 45 | i--; 46 | } 47 | 48 | // What if the second number is still left we can still iterate on it. 49 | while(j>=0){ 50 | int sum=0+b[j]+carry; 51 | int lastDigit=sum%10; 52 | ans.push_back(lastDigit+'0'); 53 | carry=sum/10; 54 | j--; 55 | } 56 | if(carry) ans.push_back(carry+'0'); 57 | 58 | while(ans[ans.size()-1]=='0'){ 59 | ans.pop_back(); 60 | } 61 | 62 | reverse(ans.begin(),ans.end()); 63 | 64 | return ans; 65 | 66 | 67 | 68 | } 69 | } 70 | 71 | 72 | Similar question: https://leetcode.com/problems/add-to-array-form-of-integer/description/ 73 | 74 | The above solution is using two pointer approach 75 | Tc:O(n+m) 76 | Sc:O(1) -------------------------------------------------------------------------------- /Strings/Medium/GroupAmagrams.txt: -------------------------------------------------------------------------------- 1 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 2 | 3 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 10 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | vector> groupAnagrams(vector& strs) { 19 | vector> ans; 20 | unordered_map> mpp; 21 | 22 | for (int i = 0; i < strs.size(); i++) { 23 | string sortedStr = strs[i]; 24 | sort(sortedStr.begin(), sortedStr.end()); 25 | 26 | mpp[sortedStr].push_back(strs[i]); 27 | } 28 | 29 | for(auto it: mpp){ 30 | ans.push_back(it.second); 31 | } 32 | 33 | return ans; 34 | } 35 | 36 | }; 37 | 38 | TC: O(NKlogK+ logM) where M is size of map. 39 | SC: O(NK)+O(M) where M is size of map. 40 | what is k? k is the length of the longest string in the array. 41 | 42 | 43 | Little optimized way: 44 | class Solution { 45 | public: 46 | array hash(string s){ 47 | array hashArray={0}; 48 | for(int i=0; i> groupAnagrams(vector& strs) { 56 | vector> ans; 57 | map, vector> mpp; 58 | 59 | for (int i = 0; i < strs.size(); i++) { 60 | string str = strs[i]; 61 | // sort(sortedStr.begin(), sortedStr.end()); 62 | 63 | mpp[hash(str)].push_back(strs[i]); 64 | } 65 | 66 | for(auto it: mpp){ 67 | ans.push_back(it.second); 68 | } 69 | 70 | return ans; 71 | } 72 | 73 | }; 74 | 75 | Just we are using hasharrays to remove complexity of sorting. 76 | 77 | TC: O(NK+logM) 78 | SC: O(NK+M) what is k? k is the length of the longest string in the array. -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/FindDupicate.txt: -------------------------------------------------------------------------------- 1 | Find Duplicate Number: 2 | 3 | 4 approaches: 4 | 5 | 6 | int findDuplicate(vector& nums) { 7 | int duplicateNumber=-1; 8 | 9 | Brute Force Approach 10 | TC: O(N^2) 11 | SC: O(1) 12 | for(int i=0; i mp; 28 | for(int i=0; i=2){ 34 | duplicateNumber=it.first; 35 | } 36 | } 37 | 38 | 39 | 40 | Another approach 41 | TC: O(nlogn)+O(n) 42 | SC: O(1) 43 | sort(nums.begin(), nums.end()); 44 | for(int i=1; i piles, int banana){ 13 | long long total=0; 14 | for(int i=0; i& piles, int h) { 24 | int maxBanana=*max_element(piles.begin(), piles.end()); 25 | 26 | int low=1, high=maxBanana; 27 | int lessTime; 28 | while(low<=high){ 29 | long long mid=low+(high-low)/2; 30 | 31 | if(calculateHours(piles, mid)<=h){ 32 | lessTime=mid; 33 | high=mid-1; 34 | 35 | } 36 | else if(calculateHours(piles, mid)>h){ 37 | low=mid+1; 38 | } 39 | 40 | } 41 | 42 | return lessTime; 43 | 44 | } 45 | }; 46 | 47 | TC: O(n*log(maxElement)) 48 | SC: O(1) 49 | 50 | 51 | Algoritm: 52 | 1. Find the max element in the array. 53 | 2. Apply binary search on the range 1 to max element. 54 | 3. For each mid, calculate the total hours required to eat all the bananas. 55 | 4. If the total hours is less than or equal to h, then store the mid in lessTime and search for the minimum mid. 56 | 5. If the total hours is greater than h, then search for the higher mid. 57 | 6. Return the lessTime. 58 | -------------------------------------------------------------------------------- /Strings/Medium/RomanToIntegerandViceversa/IntegerToRoman.txt: -------------------------------------------------------------------------------- 1 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 2 | 3 | Symbol Value 4 | I 1 5 | V 5 6 | X 10 7 | L 50 8 | C 100 9 | D 500 10 | M 1000 11 | For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. 12 | 13 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 14 | 15 | I can be placed before V (5) and X (10) to make 4 and 9. 16 | X can be placed before L (50) and C (100) to make 40 and 90. 17 | C can be placed before D (500) and M (1000) to make 400 and 900. 18 | Given an integer, convert it to a roman numeral. 19 | 20 | 21 | 22 | class Solution { 23 | public: 24 | string intToRoman(int num) { 25 | string ans; 26 | map> intToRomanMap = { 27 | {1000, "M"}, 28 | {900, "CM"}, 29 | {500, "D"}, 30 | {400, "CD"}, 31 | {100, "C"}, 32 | {90, "XC"}, 33 | {50, "L"}, 34 | {40, "XL"}, 35 | {10, "X"}, 36 | {9, "IX"}, 37 | {5, "V"}, 38 | {4, "IV"}, 39 | {1, "I"} 40 | }; 41 | for(auto it: intToRomanMap){ 42 | while(num>=it.first){ 43 | ans.append(it.second); 44 | num=num-it.first; 45 | } 46 | 47 | } 48 | 49 | return ans; 50 | 51 | 52 | 53 | 54 | } 55 | }; 56 | 57 | 58 | Algorithm: 59 | 1. Create a map of int to roman numerals 60 | 2. Iterate through the map and check if the number is greater than or equal to the key 61 | 3. If yes, append the value to the answer string and subtract the key from the number 62 | 4. If no, continue to the next key 63 | 5. Return the answer string 64 | 65 | 66 | 67 | 68 | TC: O(n) 69 | SC: O(1) -------------------------------------------------------------------------------- /Queues/Implementation/UsingLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Node{ 4 | public: 5 | int data; 6 | Node *next; 7 | Node(){ 8 | this->data=0; 9 | this->next=nullptr; 10 | } 11 | Node (int data){ 12 | this->data=data; 13 | this->next=nullptr; 14 | } 15 | 16 | }; 17 | 18 | class Queue{ 19 | public: 20 | Node *front=nullptr; 21 | Node *rear=nullptr; 22 | int size; 23 | 24 | Queue(int size){ 25 | this->size=size; 26 | 27 | } 28 | int getSize() { 29 | Node *temp = front; // Start from the front of the queue 30 | int i = 0; 31 | while (temp != nullptr) { 32 | temp = temp->next; 33 | i++; 34 | } 35 | return i; 36 | } 37 | 38 | 39 | void push(int data){ 40 | // first I need to check whether the size of Queue is full or not. 41 | if(getSize()==size){ 42 | cout<<"Queue is full"<next=nullptr; 49 | } 50 | else{ 51 | rear->next = newNode; 52 | newNode->next = nullptr; 53 | rear = newNode; // Update the rear pointer 54 | 55 | } 56 | } 57 | 58 | } 59 | 60 | void pop(){ 61 | if(front==nullptr){ 62 | cout<<"Queue is empty"<next){ 66 | Node *temp=front; 67 | front=temp->next; 68 | temp->next=nullptr; 69 | delete temp; 70 | 71 | } 72 | else{ 73 | front=nullptr; 74 | rear=nullptr; 75 | } 76 | } 77 | } 78 | 79 | bool isEmpty(){ 80 | return front==nullptr; 81 | } 82 | 83 | int getTop(){ 84 | if(front==nullptr){ 85 | cout<<"Queue is empty"<data; 89 | } 90 | 91 | }; 92 | int main() { 93 | Queue q(5); 94 | q.push(5); 95 | q.push(4); 96 | q.push(3); 97 | q.push(6); 98 | cout< findClosestElements(vector& arr, int k, int x) { 4 | 5 | 6 | Two pointer approach 7 | 8 | int l=0, h=arr.size()-1; 9 | 10 | vector ans; 11 | 12 | TC: O(n-k comparisions) SC:O(1) 13 | Algorithm 14 | 1. We have all differences below the array 15 | 2. We want the closest element and so we need the closest ones 16 | 3. If low has bigger number than higher, move low pointer else move higher pointer 17 | 4. You wil reach one point where you'll get the subarray of size k 18 | 19 | // while(h-l>=k){ 20 | // if(x-arr[l]>arr[h]-x){ 21 | // l++; 22 | // } 23 | // else{ 24 | // h--; 25 | // } 26 | // } 27 | 28 | 29 | // return {arr.begin()+l, arr.begin()+h+1}; 30 | 31 | 32 | 33 | 34 | 35 | Using binary search + 2 pointer 36 | Algorithm 37 | 1. In first approach our window size was so big 38 | 2. Let us use small window and expand it, earlier it was big we were shrinking, now we will expand 39 | 3. Take lower bound of x, small index at number greater than or equal to x 40 | 4. Lower bound will be our high, and high-1 will be our l 41 | 5. low is second smallest, high is the smallest 42 | 6. Now, to expand if the low is greater than high, move high right side else move left side 43 | 44 | int high=lower_bound(arr.begin(), arr.end(),x)-arr.begin(); 45 | // if lower bound does not exists, it returns the last element position 46 | 47 | int low=high-1; 48 | while(k--){ 49 | // consider high is the first index, now if low reaches at negative -1 index, the closest will be after high. 50 | if(low<0){ 51 | high++; 52 | } 53 | // if high is at last, there is no way to go above high, so move left 54 | else if(high>=arr.size()){ 55 | low--; 56 | } 57 | else if(x-arr[low]>arr[high]-x){ 58 | high++; 59 | } 60 | else{ 61 | low--; 62 | } 63 | 64 | } 65 | 66 | 67 | return vector(arr.begin()+low+1, arr.begin()+high); 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | } 79 | 80 | 81 | https://leetcode.com/problems/find-k-closest-elements/description/ 82 | }; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/SubArrays/MaximumProductSubarray.txt: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find a 2 | subarray 3 | that has the largest product, and return the product. 4 | 5 | The test cases are generated so that the answer will fit in a 32-bit integer. 6 | 7 | 8 | Brute froce: 9 | TC: O(n^3) SC: O(1) 10 | Some better: O(n^2) SC: O(1) 11 | int maxProduct=INT_MIN; 12 | O(N^3) SC:O(1) 13 | for(int i=0; i& nums) { 36 | int n=nums.size(); 37 | int maxProduct=INT_MIN; 38 | int product=1; 39 | for(int i=0; i=0; i--){ 48 | product=product*nums[i]; 49 | maxProduct=max(maxProduct, product); 50 | if(nums[i]==0){ 51 | product=1; 52 | } 53 | } 54 | return maxProduct; 55 | } 56 | 57 | 58 | 59 | Single Pass: 60 | 61 | 62 | int n=nums.size(); 63 | int maxProduct=INT_MIN; 64 | int prefixProduct=1; 65 | int suffixProduct=1; 66 | 67 | for(int i=0; i 2 | using namespace std; 3 | 4 | // Kind of going in circular way 5 | class Deque{ 6 | public: 7 | int size; 8 | int data; 9 | int front; 10 | int rear; 11 | int *arr; 12 | Deque(int size){ 13 | this->size=size; 14 | arr=new int[size]; 15 | this->front=-1; 16 | this->rear=-1; 17 | 18 | } 19 | 20 | void pushRear(int data){ 21 | // checking if size is full already 22 | if((front==0 && rear==size-1 ) || (rear==front-1)){ 23 | cout<<"Queue is full"< mpp; 28 | 29 | mpp['I']=1; 30 | mpp['V']=5; 31 | mpp['X']=10; 32 | mpp['L']=50; 33 | mpp['C']=100; 34 | mpp['D']=500; 35 | mpp['M']=1000; 36 | 37 | 38 | 39 | for(int i=0; i& nums, int diff) { 23 | 24 | O(n^3) SC:O(1) 25 | int count=0; 26 | for(int i=0; i mpp; 56 | 57 | TC:O(2N) SC:O(N) 58 | 59 | for(int i=0; i prefixSum(nums.size(), 0); 12 | prefixSum[0]=nums[0]; 13 | int leftIndex=INT_MAX; 14 | 15 | for(int i=1; i=0; i--){ 21 | backSum+=nums[i]; 22 | if(backSum==prefixSum[i]){ 23 | leftIndex=min(leftIndex, i); 24 | } 25 | 26 | } 27 | 28 | 29 | return leftIndex==INT_MAX ? -1 : leftIndex; 30 | 31 | 32 | Optimized approach: 33 | 34 | Algo: 35 | Step_#1: 36 | 37 | Let 38 | Left hand side be empty, and 39 | Right hand side holds all weights. 40 | 41 | 42 | Step_#2: 43 | 44 | Iterate weight_i from 0 to (n-1) 45 | 46 | During each iteration, take away weight_#i from right hand side, check whether balance is met or not. 47 | 48 | If yes, then the index i is the pivot index. 49 | 50 | If no, put weight_#i on the left hand side, and repeat the process until balance is met or all weights are exchanged. 51 | 52 | 53 | Step_#3: 54 | 55 | Finally, if all weights are exchanged and no balance is met, then pivot index does not exist, return -1. 56 | 57 | 58 | int totalWeightOnRight=accumulate(nums.begin(), nums.end(), 0); 59 | int totalWeightOnLeft=0; 60 | for(int i=0; i 2 | using namespace std; 3 | class Node{ 4 | public: 5 | int data; 6 | Node *next; 7 | 8 | Node(){ 9 | this->data=0; 10 | this->next=nullptr; 11 | } 12 | 13 | Node(int data){ 14 | this->data=data; 15 | this->next=nullptr; 16 | } 17 | }; 18 | 19 | void insertNode(Node *&tail, int element, int data){ 20 | if(tail==nullptr){ 21 | Node *newNode=new Node(data); 22 | tail=newNode; 23 | newNode->next=newNode; 24 | return; 25 | } 26 | Node *temp=tail; 27 | while(temp->data!=element){ 28 | temp=temp->next; 29 | } 30 | 31 | Node *newNode=new Node(data); 32 | newNode->next=temp->next; 33 | temp->next=newNode; 34 | 35 | 36 | 37 | 38 | }; 39 | void printLL(Node *tail){ 40 | if(tail==nullptr){ 41 | cout<<"Linked list is empty..."<data<<" "; 47 | temp=temp->next; 48 | }while(temp!=tail); 49 | 50 | cout<next; 60 | if(curr==nullptr){ 61 | tail=nullptr; 62 | return; 63 | } 64 | 65 | while(curr->data!=value){ 66 | prev=curr; 67 | curr=curr->next; 68 | } 69 | prev->next=curr->next; 70 | // below step is curcial because if we are pointing the tail to the curr element, then tail may get deleted as well, so we are pointing tail to some other element... 71 | if(tail==curr){ 72 | tail=prev; 73 | } 74 | curr->next=nullptr; 75 | delete curr; 76 | 77 | 78 | } 79 | int main() { 80 | 81 | Node *first=new Node(10); 82 | Node *second=new Node(20); 83 | Node *third=new Node(30); 84 | Node *fourth=new Node(40); 85 | 86 | first->next=second; 87 | second->next=third; 88 | third->next=fourth; 89 | fourth->next=first; 90 | 91 | // doesn't matter to give only first one... 92 | insertNode(first, 40, 60); 93 | printLL(first); 94 | insertNode(first, 20, 300); 95 | printLL(first); 96 | insertNode(first, 10, 400); 97 | printLL(first); 98 | 99 | 100 | deleteNode(first, 10); 101 | printLL(first); 102 | 103 | return 0; 104 | } -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/KDifferentPairs.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPairs(vector& nums, int k) { 4 | int count=0; 5 | set> st; 6 | for(int i=0; i ans={nums[i], nums[j]}; 11 | sort(ans.begin(), ans.end()); 12 | st.insert(ans); 13 | 14 | } 15 | } 16 | } 17 | 18 | TC: O(n^2) and SC: O(n) 19 | 20 | 21 | 22 | // using map 23 | unordered_map mpp; 24 | for(int i=0; i=2){ 31 | count++; 32 | } 33 | } 34 | } 35 | 36 | if(k==0) return count; 37 | 38 | 39 | for(int i=0; i> st; 58 | 59 | 60 | int low=0, high=1; 61 | while(highk){ 72 | low++; 73 | } 74 | else{ 75 | high++; 76 | } 77 | if(low==high) high++; 78 | } 79 | 80 | // return st.size(); 81 | 82 | return st.size(); 83 | 84 | } 85 | }; 86 | 87 | 88 | 89 | 90 | TC: O(nlogn) and SC: O(n) 91 | 92 | 93 | 94 | Using binary search 95 | 1. sort the array 96 | 2. for each element in the array, search for the element k+nums[i] in the array 97 | 3. if found, add it to the set pair. 98 | 4. return the size of the set pair. 99 | 100 | TC: O(nlogn) and SC: O(n) 101 | 102 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchSorted/SearchInARotatedSortedArray.txt: -------------------------------------------------------------------------------- 1 | There is an integer array nums sorted in ascending order (with distinct values). 2 | 3 | Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. 4 | 5 | Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. 6 | 7 | You must write an algorithm with O(log n) runtime complexity. 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | int search(vector& nums, int target) { 19 | // brute force(without using binary search, will be using binary search) 20 | // for(int i=0; i=nums[low]){ 46 | // if left part is sorted, then check whether the target lies in the left part, if it lies move high pointer 47 | if(nums[low]<=target && nums[mid]>=target){ 48 | high=mid-1; 49 | } 50 | // if it does not lie, increment low pointer. 51 | else{ 52 | low=mid+1; 53 | } 54 | } 55 | 56 | // if right part is sorted 57 | else{ 58 | // if right part is sorted, then check whether the target lies in the right part, if it lies move low pointer 59 | if(nums[high]>=target && nums[mid]<=target){ 60 | low=mid+1; 61 | } 62 | // if it does not lie, increment high pointer. 63 | 64 | else{ 65 | high=mid-1; 66 | } 67 | } 68 | } 69 | 70 | return -1; 71 | } 72 | }; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/TwoSum.txt: -------------------------------------------------------------------------------- 1 | Two Sum 2 | 3 | 4 | Brute: 5 | 6 | 1. Two for loops 7 | 2. Check if the sum of the two numbers is equal to the target 8 | 3. If so, return the indices of the two numbers 9 | 10 | for(int i=0; i mp; 29 | 30 | 31 | for(int i=0; i> ans; (for this type, hashmap is the best one) 59 | // storing elements and indices in pair 60 | for(int i=0; itarget){ 72 | e--; 73 | } 74 | else{ 75 | s++; 76 | } 77 | } 78 | return {-1,-1}; 79 | 80 | TC: O(N)+O(Nlogn)=O(Nlogn) 81 | SC: O(N) 82 | 83 | */ 84 | 85 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchAnswersSpace/ShipWeights.txt: -------------------------------------------------------------------------------- 1 | A conveyor belt has packages that must be shipped from one port to another within days days. 2 | 3 | The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. 4 | 5 | Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 12 | Output: 15 13 | Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 14 | 1st day: 1, 2, 3, 4, 5 15 | 2nd day: 6, 7 16 | 3rd day: 8 17 | 4th day: 9 18 | 5th day: 10 19 | 20 | Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. 21 | 22 | 23 | 24 | 25 | 26 | Brute foce: Just do a linear search with time complexity of O((max-min)*n) where n is the number of elements in the array. This is not optimal. 27 | 28 | 29 | Optimal: Use binary search. The time complexity is O(nlogn). The space complexity is O(1). 30 | 31 | 32 | Code: 33 | class Solution { 34 | public: 35 | int getMinimumDays(vector w, int capacity){ 36 | int i=0, j=0; 37 | long long sum=0; 38 | int count=0; 39 | 40 | while(i& w, int days) { 59 | int minNo=*max_element(w.begin(), w.end()); 60 | long long sum=0; 61 | for(auto it: w) sum+=it; 62 | int low=minNo, high=sum; 63 | int ans=-1; 64 | while(low<=high){ 65 | long long mid=(low+high)/2; 66 | if(getMinimumDays(w, mid)<=days){ 67 | ans=mid; 68 | high=mid-1; 69 | } 70 | else{ 71 | low=mid+1; 72 | } 73 | } 74 | return ans; 75 | } 76 | }; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/FindMissingAndDuplicate.txt: -------------------------------------------------------------------------------- 1 | Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2,....,N} is missing and one number 'B' occurs twice in array. Find these two numbers. 2 | 3 | Example 1: 4 | 5 | Input: 6 | N = 2 7 | Arr[] = {2, 2} 8 | Output: 2 1 9 | Explanation: Repeating number is 2 and 10 | smallest positive missing number is 1. 11 | 12 | 13 | 14 | Brute force approach: 15 | int repeating=-1, missing=-1; 16 | 17 | TC: O(N^2) SC:O(1) 18 | for(int i=1; i<=n; i++){ 19 | int count=0; 20 | 21 | for(int j=0; j mpp; 49 | 50 | for(int i=0; imaxiLength){ 33 | maxiLength=count; 34 | } 35 | } 36 | return maxiLength; 37 | 38 | TC:O(N^2) SC:O(1) 39 | 40 | 41 | Better: 42 | 1. Sort the array 43 | 2. Take three variables, count, lastSmaller=INT_MIN, longestLength=1 (because atleast one element will be there) 44 | 3. Start traversing the array 45 | 4. if nums[i]-1 is equal to lastSmaller, increment the count, update lastSmaller=nums[i] 46 | 5. if nums[i]-1 is not equal to lastSmaller, then update count=1, lastSmaller=nums[i] (because we are starting a fresh count) 47 | 6. Update longestLength=max(longestLength, count) 48 | 49 | TC:O(NlogN) SC:O(1) 50 | 51 | 52 | Optimal: 53 | 1. Take a set and insert all the elements of the array 54 | 2. Take a variable longestLength=1 55 | 3. Start traversing the set 56 | 4. if the element-1 is not present in the set, then start a fresh count int count=1, and start a while loop to check if element+1 is present in the set, if yes, then increment the count and element, else break the loop 57 | 5. Update longestLength=max(longestLength, count) 58 | 59 | 60 | IMPORTANT: 61 | For Time complexity, unordered set takes O(1) for insertion, deletion and searching, if collisions are less, then it takes O(1), but if collisions are more, then it takes O(N) for insertion, deletion and searching 62 | 63 | You might think, inner while loop takes n iterations again? No, because we are checking only for the next consecutive element, so it will take only O(2N) time: 64 | 65 | Expalanation: outer loop takes N, now for each element, we are checking for the next consecutive element, so it will take N+N=2N time 66 | 67 | For Space complexity, unordered set takes O(N) space 68 | 69 | TC:O(3N) SC:O(N) 70 | 71 | https://leetcode.com/problems/longest-consecutive-sequence/description/ 72 | 73 | -------------------------------------------------------------------------------- /Hashing/Concept.txt: -------------------------------------------------------------------------------- 1 | What is hashing? 2 | 3 | Hashing is a technique used to convert a range of key values into a range of indexes of an array. We’re going to use the modulo operator to get a range of key values. 4 | 5 | 6 | It is just kind of pre-compute and fetch the values from a hashmap 7 | 8 | We can use hasharray to store the values and then we can use the hasharray to fetch the values 9 | 10 | If the maximum element is given, then we can use the hasharray to store the values and then we can use the hasharray to fetch the values 11 | The length of the hasharray will be the maximum element + 1 12 | hash[arr[i]]++; 13 | 14 | 15 | Normally, without hashing, we will use the following code: 16 | findElement(arr, n){ 17 | for(int i=0; imajorityCount){ 21 | ans.push_back(nums[i]); 22 | } 23 | if(ans.size()==2) break; 24 | } 25 | } 26 | 27 | Better: Using hashmap 28 | 29 | TC: O(nlogm) 30 | SC: O(m)+O(1) 31 | unordered_map mpp; 32 | for(int i=0; imajorityCount){ 86 | ans.push_back(el1); 87 | } 88 | if(ct2>majorityCount){ 89 | ans.push_back(el2); 90 | } 91 | 92 | 93 | return ans; -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/SubArrays/SubArraysWithEqual0sand1s.txt: -------------------------------------------------------------------------------- 1 | Count total subarrays with equal number of 0s and 1s 2 | 3 | 4 | Brute force: 5 | 6 | 7 | class Solution{ 8 | public: 9 | //Function to count subarrays with 1s and 0s. 10 | long long int countSubarrWithEqualZeroAndOne(int arr[], int n) 11 | { 12 | //Your code here 13 | long long length=0; 14 | for(int i=0; i mpp; 51 | mpp[0]=1; 52 | long long frequency=0; 53 | int sum=0; 54 | for(int i=0; i 2 | #include 3 | using namespace std; 4 | class Node{ 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | Node(){ 10 | this->data=0; 11 | this->next=nullptr; 12 | } 13 | Node(int data){ 14 | this->data=data; 15 | this->next=nullptr; 16 | } 17 | 18 | }; 19 | 20 | class Stack{ 21 | public: 22 | Node *head=nullptr; 23 | int size; 24 | Stack(int size){ 25 | this->size=size; 26 | } 27 | 28 | int findLengthOfLinkedList(Node *head){ 29 | Node *temp=head; 30 | int length=0; 31 | while(temp){ 32 | temp=temp->next; 33 | length++; 34 | } 35 | return length; 36 | } 37 | 38 | int getSize(){ 39 | return findLengthOfLinkedList(head); 40 | } 41 | 42 | 43 | void push(int data) { 44 | if (head == nullptr) { 45 | Node *newNode = new Node(data); 46 | head = newNode; 47 | return; 48 | } else { 49 | if(findLengthOfLinkedList(head)==size){ 50 | cout<<"Stack is full"<next) { 56 | temp = temp->next; 57 | } 58 | Node *elem = new Node(data); 59 | temp->next = elem; 60 | } 61 | } 62 | 63 | bool isEmpty(){ 64 | if(head==nullptr) return true; 65 | return false; 66 | } 67 | 68 | int getTop() { 69 | if (head == nullptr) { 70 | cout << "No element in stack" << endl; 71 | return -1; 72 | } else { 73 | Node *temp = head; 74 | while (temp->next) { 75 | temp = temp->next; 76 | } 77 | return temp->data; 78 | } 79 | } 80 | 81 | 82 | void pop() { 83 | if (head == nullptr) { 84 | cout << "Stack is empty" << endl; 85 | } else if (head->next == nullptr) { 86 | delete head; 87 | head = nullptr; 88 | } else { 89 | Node *temp = head; 90 | Node *p = nullptr; 91 | while (temp->next) { 92 | p = temp; 93 | temp = temp->next; 94 | } 95 | p->next = nullptr; 96 | delete temp; 97 | } 98 | } 99 | 100 | 101 | 102 | 103 | }; 104 | 105 | int main() { 106 | 107 | Stack s(5); 108 | s.push(5); 109 | s.push(5); 110 | s.push(7); 111 | s.push(10); 112 | s.push(11); 113 | 114 | 115 | 116 | // cout<>& matrix, int target) { 11 | This is naive brute force solution with time complexity of: O(n*m) with constant extra space. 12 | int rows=matrix.size(); 13 | int cols=matrix[0].size(); 14 | for(int i=0; i=0 && rowIndextarget){ 43 | colIndex--; 44 | } 45 | 46 | else{ 47 | rowIndex++; 48 | } 49 | } 50 | 51 | 52 | return false; 53 | 54 | 55 | } 56 | }; 57 | 58 | 59 | 60 | Try searching from backwards 61 | Algorithm: 62 | 1. Intialize the colIndex to last column 63 | 2. If the element at that rowIndex and colIndex is greater than target, do colIndex-- 64 | 3. If the element is smaller than target, then there is high chance that element may exists in that row, so do row++ 65 | 4. If element is equal to the target, return true, else return false. 66 | 67 | Time Complexity: O(n+m) 68 | Space Complexity: O(1) 69 | 70 | 71 | Since the loop continues as long as colIndex is greater than or equal to 0 and rowIndex is less than the number of rows, it will iterate until either colIndex becomes negative or rowIndex exceeds or equals the number of rows. 72 | 73 | In the worst case, the target element is located at the bottom-left corner of the matrix. In this scenario, the loop will run through all the columns (m iterations) and then iterate through all the rows (n iterations) until it reaches the target or exhausts all elements. 74 | 75 | Thus, the total number of iterations in the worst case is n + m. As we analyze time complexity, we focus on the dominant term, and in this case, both n and m are considered. Therefore, the time complexity of the code is O(n + m). -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/MergeTwoSortedArrays.txt: -------------------------------------------------------------------------------- 1 | You are given two sorted arrays, you need to merge them in sorted order. 2 | 3 | Brute force approach(O(n+m), O(n+mlog(n+m))) 4 | vector ans; 5 | for(int i=0; i=0 && jnums2[j]){ 23 | swap(nums1[i], nums2[j]); 24 | i--; 25 | j++; 26 | } 27 | else{ 28 | break; 29 | } 30 | } 31 | 32 | sort(nums1.begin(), nums1.end()); 33 | sort(nums2.begin(), nums2.end()); 34 | 35 | 36 | We can also use two pointer approach to solve this problem. 37 | 38 | 39 | 40 | 41 | 42 | int gap=(n+m)/2 + (n+m)%2; 43 | 44 | void swapIfGreater(long long nums1[], long long nums2[], int idx1, int idx2){ 45 | if(nums1[idx1]>nums2[idx2]){ 46 | swap(nums1[idx1], nums2[idx2]); 47 | } 48 | } 49 | 50 | 51 | while(gap>0){ 52 | int left=0; 53 | int right=gap; 54 | while(right<(n+m)){ 55 | arr1 and arr2 positions 56 | if index on the merged array is 5 and now you want to find out the index of the 57 | second array, you can just subtract (index(of merged array)-lenght of first array) 58 | if(left=n){ 59 | swapIfGreater(nums1, nums2, left, right-n); 60 | } 61 | if both pointers are in right array which is arr2 62 | else if(left>=n){ 63 | swapIfGreater(nums2, nums2, left-n, right-n); 64 | } 65 | if both pointers are in left array which is arr1 66 | 67 | else{ 68 | swapIfGreater(nums1, nums1, left, right); 69 | } 70 | 71 | left++; 72 | right++; 73 | } 74 | if(gap==1) break; 75 | 76 | gap=(gap/2)+(gap%2); 77 | 78 | } 79 | 80 | 81 | Algorithm: 82 | 1. Calculate the gap = (n + m)/2 + (n + m)%2 83 | 2. Run a loop until gap >= 1 84 | 3. Check if the indices are in the first array, swap the elements if the element in the first array is greater than the element in the second array 85 | 4. Check if the indices are in the second array, swap the elements. 86 | 5. Update the gap = gap/2 + gap%2 87 | 88 | TC: O((n+m)(moving pointer one by one, not exactly) *log2(n+m)(gap one)) -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchSorted/SearchInSortedArrayWithDuplicates.txt: -------------------------------------------------------------------------------- 1 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. 2 | 3 | Return the single element that appears only once. 4 | 5 | Your solution must run in O(log n) time and O(1) space. 6 | 7 | 8 | Brute force approach: O(n) time and O(1) space 9 | 10 | class Solution { 11 | public: 12 | int singleNonDuplicate(vector& nums) { 13 | if(nums.size()==1) return nums[0]; 14 | 15 | for(int i=0; i& nums, int target) { 16 | // applying linear search 17 | for(int i=0; i=nums[low]){ 47 | // if left part is sorted, then check whether the target lies in the left part, if it lies move high pointer 48 | if(nums[low]<=target && nums[mid]>=target){ 49 | high=mid-1; 50 | } 51 | // if it does not lie, increment low pointer. 52 | else{ 53 | low=mid+1; 54 | } 55 | } 56 | 57 | // if right part is sorted 58 | else{ 59 | // if right part is sorted, then check whether the target lies in the right part, if it lies move low pointer 60 | if(nums[high]>=target && nums[mid]<=target){ 61 | low=mid+1; 62 | } 63 | // if it does not lie, increment high pointer. 64 | 65 | else{ 66 | high=mid-1; 67 | } 68 | } 69 | } 70 | 71 | return false; 72 | 73 | 74 | 75 | } 76 | }; 77 | 78 | TC: O(logn), average case 79 | Now, if we have duplicates, then we have to check for all the elements, so worst case is O(n/2) we are shrinking the array by half, so TC: O(n/2) = O(n) (if we have lot of duplicates...) 80 | SC: O(1) -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/IntersectionOfThreeArrays.txt: -------------------------------------------------------------------------------- 1 | Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. 2 | Note: can you take care of the duplicates without using any additional Data Structure? 3 | 4 | 5 | 6 | Input: 7 | n1 = 6; A = {1, 5, 10, 20, 40, 80} 8 | n2 = 5; B = {6, 7, 20, 80, 100} 9 | n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120} 10 | Output: 20 80 11 | Explanation: 20 and 80 are the only 12 | common elements in A, B and C. 13 | 14 | vector commonElements (int A[], int B[], int C[], int n1, int n2, int n3) 15 | { 16 | code here. 17 | Solution 1 18 | set st; 19 | for(int i=0; i ans; 37 | for(auto it:st){ 38 | ans.push_back(i t); 39 | } 40 | 41 | unordered_map mpp; 42 | set st1; 43 | set st2; 44 | set st3; 45 | for(int i=0; i st; 82 | 83 | int i=0, j=0, k=0; 84 | while(iB[j]){ 92 | j++; 93 | } 94 | else if(B[j]>C[k]){ 95 | k++; 96 | } 97 | else{ 98 | i++; 99 | } 100 | 101 | } 102 | 103 | for(auto it: st){ 104 | ans.push_back(it); 105 | } 106 | 107 | 108 | return ans; 109 | 110 | } --------------------------------------------------------------------------------