├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .vscode ├── launch.json └── settings.json ├── Arrays ├── 1-D Arrays │ ├── Basic │ │ ├── LargestElementInArray.txt │ │ ├── LeftRotateArrayByDPlaces.txt │ │ ├── Miscellaneous │ │ │ ├── FlowerBed.txt │ │ │ └── NumberOfArithmeticTriplets.txt │ │ ├── MonotonicArray.txt │ │ ├── NextGreaterELement.txt │ │ ├── ReverseArrayInGroups.cpp │ │ ├── Screenshot 2023-05-28 215449.png │ │ └── Sort01.txt │ ├── Medium │ │ ├── Majority │ │ │ ├── MajorityElement.txt │ │ │ └── MajorityElement2.txt │ │ ├── RearrangePostiveAndNegative.txt │ │ ├── Screenshot 2023-05-29 174008.png │ │ ├── Screenshot 2023-05-29 204102.png │ │ ├── Screenshot 2023-06-01 101608.png │ │ └── SortColors.txt │ └── Patterns │ │ ├── Duplicates │ │ ├── FindAllMissingNumbersFromDuplicates.txt │ │ ├── FindDupicate.txt │ │ ├── FindMissingAndDuplicate.txt │ │ ├── FindUniqueElement.txt │ │ ├── LeadersInArray.txt │ │ ├── MaximumConsecutiveOnes.txt │ │ ├── MissingNumber.txt │ │ └── UniqueOccurences.txt │ │ ├── Prefix │ │ ├── FindPivot.txt │ │ ├── FindRightAndLeftDifferences.txt │ │ └── PrefixSum.txt │ │ ├── Sorting │ │ ├── BubbleSort.txt │ │ ├── InsertionSort.txt │ │ └── SelectionSort.txt │ │ ├── SubArrays │ │ ├── AllSubArraysGivenSum.txt │ │ ├── CountSubArraysWithXorK.txt │ │ ├── MaximumProductSubarray.txt │ │ ├── MaximumSubArrayLengthWithGivenSum.txt │ │ ├── MaximumSubArraySum.txt │ │ ├── SubArrayWithOddLength.txt │ │ └── SubArraysWithEqual0sand1s.txt │ │ ├── Subsequences │ │ ├── LongestConsecutiveSequence.txt │ │ └── LongestIncreasingSubsequence.txt │ │ └── TwoPointers │ │ ├── 3Sum.txt │ │ ├── 4Sum.txt │ │ ├── AdditionOfArrays.txt │ │ ├── CheckIfArraySorted.txt │ │ ├── IntersectionOfArray.txt │ │ ├── IntersectionOfThreeArrays.txt │ │ ├── MaxSizeKSum.txt │ │ ├── MaximumProductOfThreeNumbers.txt │ │ ├── MergeTwoSortedArrays.txt │ │ ├── MoveZeoresToEnd.txt │ │ ├── RemoveDuplicatesFromSortedArray.txt │ │ ├── SecondLargestAndSmallest.txt │ │ ├── TwoSum.txt │ │ └── UnionOfArray.txt ├── 2-D Arrays │ ├── Basic │ │ ├── Shift2DArray.txt │ │ └── WavePrint.txt │ └── Medium │ │ ├── PascalTriangle.cpp │ │ ├── RotateImage.txt │ │ ├── SetMatrixZeros.txt │ │ ├── SpiralPrintMatrix.txt │ │ └── a.out ├── Algorithms │ ├── BubbleSort.txt │ ├── BucketSort.txt │ ├── CountSort.txt │ ├── DNFsort.txt │ ├── Gap(shellsort).txt │ ├── InsertionSort.txt │ ├── Kadane's.txt │ ├── MergeSort.txt │ ├── MooresVoting.txt │ ├── QuickSort.txt │ ├── SelectionSort.txt │ ├── SlidingWindow.txt │ └── TwoPointers.txt └── Binary Search │ ├── 1-D Arrays │ ├── Basic │ │ ├── CheckArrayIsSortedAndRotate.txt │ │ ├── FindMissingTermInAPSeries.txt │ │ ├── FloorAndCeil.txt │ │ ├── GuessNumberLowerOrHigher.txt │ │ ├── KthMissingPositive.txt │ │ ├── LowerBound.txt │ │ ├── SearchInsertPosition.txt │ │ └── UpperBound.txt │ ├── Hard │ │ └── FindMinimumInSorted2.txt │ └── Medium │ │ ├── CountOccurences.txt │ │ ├── FindKClosest.txt │ │ ├── FindOccurences(firstandlast).txt │ │ ├── KDifferentPairs.txt │ │ ├── SearchAnswersSpace │ │ ├── FindPeakElement.txt │ │ ├── KokoEatingBanans.txt │ │ ├── LeastCapacityToShipWeights.txt │ │ ├── NthRootM.txt │ │ ├── ShipWeights.txt │ │ └── Sqrt(x).txt │ │ ├── SearchSorted │ │ ├── FindKthRotation.txt │ │ ├── FindMinimumInSorted.txt │ │ ├── SearchInARotatedSortedArray.txt │ │ ├── SearchInSortedArrayWithDuplicates.txt │ │ └── SearchSortedArray2.txt │ │ └── SumOfSquaresOfNumber.txt │ ├── 2-D Arrays │ └── Medium │ │ ├── FindRowWithMaximum1s.txt │ │ ├── SearchIn2DMatrix1.txt │ │ └── SearchInA2DMatrix2.txt │ └── ExponentialSearch │ ├── ExponentialSearch.cpp │ └── FindElementInAnInfiniteSortedArray.cpp ├── Hashing ├── Concept.txt ├── FirstRepeating.txt └── FrequencyOfElement.txt ├── LICENSE ├── LinkedLists ├── Doubly │ └── main.cpp └── Singly │ ├── Circular │ └── BasicImplementation.cpp │ ├── DeleteNode.txt │ ├── Implement.txt │ ├── InsertNode.txt │ └── ReverseLinkedList.cpp ├── Maths ├── ArmStrongNumber.txt ├── BasicDivisorLCMGCD │ ├── CountDigits.txt │ ├── FindCommonFactors.txt │ ├── GCDHCF.txt │ ├── PrintDivisors.txt │ └── kThFactor.txt ├── CheckPrime.txt ├── CountSetBits.txt ├── DivisibleBy7.txt ├── Factorial │ ├── FactorialOfLargeNumber.txt │ └── FactorialTrailingZeros.txt ├── FindMissingTermInAPSeries.txt ├── Palindrome.txt ├── ReverseInteger.txt └── UglyNumber.txt ├── Miscellaneous ├── AssignCookies.txt ├── CheckIfStraightLine.txt ├── CheckNDoubleExisits.txt ├── HappyNumber.txt └── LargestPositiveNumberExists.txt ├── Patterns └── basic-patterns.cpp ├── Queues ├── CircularQueue │ └── ImplementationUsingArray.cpp ├── DoubleEndedQueues │ └── main.cpp └── Implementation │ ├── ImplemenetUsingArray.cpp │ ├── UsingLinkedList.cpp │ └── usingStack.cpp ├── README.md ├── Stacks ├── Basic │ ├── MiddleElement.cpp │ └── ReverseStringUsingStack.cpp └── Implementation │ ├── ImplementTwoStacksInSingleArray.cpp │ ├── ImplementUsingLL.cpp │ ├── ImplementUsingQueues.cpp │ └── WithArray.cpp ├── Strings ├── Basic │ ├── CommonCharacters.txt │ ├── ConvertAllSmallCaseToUpperCase.txt │ ├── IsomorphicString.txt │ ├── LargestCommonPrefix.txt │ ├── LargestOddNumberInString.txt │ ├── LengthOfLastWord.txt │ ├── Palindrome │ │ ├── CountPalindromicStrings.txt │ │ ├── Palindrome.txt │ │ └── ValidPalindrome2.txt │ ├── Panagram.txt │ ├── RansomNote.txt │ ├── RemoveAdjacentCharacters.txt │ └── ValidAnagram.txt └── Medium │ ├── GroupAmagrams.txt │ ├── LongestOddLengthSubString.txt │ ├── RemoveAllOccurencesOfStringInMainString.txt │ ├── ReorganizeStrings.txt │ ├── RomanToIntegerandViceversa │ ├── IntegerToRoman.txt │ └── RomanToInteger.txt │ ├── SortCharactersAccrodingToFrequency.txt │ └── StringToInteger(atoi).txt ├── Trees ├── BinaryTrees │ ├── Build │ │ └── RecursiveWay.cpp │ └── Traversal │ │ ├── InorderTraversal.cpp │ │ ├── LevelOrderTraversal.cpp │ │ ├── PostOrder.cpp │ │ └── Preorder.cpp └── Questions │ ├── DiameterOfTree.cpp │ └── HeightOfBinaryTree.cpp └── run.sh /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.ejs": "html", 4 | "iostream": "cpp" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/LargestElementInArray.txt: -------------------------------------------------------------------------------- 1 | Find largest element in array: 2 | 3 | Brute: Sort the array, and return the index of last element. 4 | TC: O(nlogn) (merge sort) 5 | SC: O(1) 6 | 7 | Optimal: Traverse the array and keep track of max element. (consider the first element as max and traverse it) 8 | TC: O(n) 9 | SC: O(1) 10 | 11 | Corner Cases: if element is negative, then max will be -infinity, so we can take max as INT_MIN. 12 | 13 | 14 | Solved Link: https://www.codingninjas.com/codestudio/problems/largest-element-in-the-array-largest-element-in-the-array_5026279?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 15 | 16 | -------------------------------------------------------------------------------- /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, 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/Basic/Miscellaneous/NumberOfArithmeticTriplets.txt: -------------------------------------------------------------------------------- 1 | You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: 2 | 3 | i < j < k, 4 | nums[j] - nums[i] == diff, and 5 | nums[k] - nums[j] == diff. 6 | Return the number of unique arithmetic triplets. 7 | 8 | 9 | Input: nums = [0,1,4,6,7,10], diff = 3 10 | Output: 2 11 | Explanation: 12 | (1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. 13 | (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. 14 | 15 | 16 | https://leetcode.com/problems/number-of-arithmetic-triplets/description/ 17 | 18 | 19 | 20 | class Solution { 21 | public: 22 | int arithmeticTriplets(vector& 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& nums) { 6 | bool isIncreasing=false; 7 | bool isDecreasing=false; 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/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 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/Screenshot 2023-05-28 215449.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/1-D Arrays/Basic/Screenshot 2023-05-28 215449.png -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Basic/Sort01.txt: -------------------------------------------------------------------------------- 1 | Sort Array of 0s and 1s 2 | 3 | Approach 1 4 | using a sorting algorithm like merge sort O(Nlogn)+sc(O(N)) 5 | 6 | Approach 2 7 | 8 | vector arr2; 9 | int count1=0, count0=0; 10 | 11 | // O(N) 12 | 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/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/Medium/Screenshot 2023-05-29 174008.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/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/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/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/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/1-D Arrays/Medium/Screenshot 2023-06-01 101608.png -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Medium/SortColors.txt: -------------------------------------------------------------------------------- 1 | void sortColors(vector& 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/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 | }; -------------------------------------------------------------------------------- /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 mpp; 49 | 50 | for(int i=0; i) 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/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/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/ -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Duplicates/MissingNumber.txt: -------------------------------------------------------------------------------- 1 | Find missing number 2 | 3 | Brute: Apply linear search and find the missing number 4 | This below approach will not work if the array contains duplicate elements and if the number present in array is 0 5 | code: 6 | ``` 7 | int findMissing(int arr[], int n) 8 | { 9 | int i, j, found; 10 | for (i = 1; i <= n; i++) { 11 | found = 0; 12 | for (j = 0; j < n; j++) { 13 | if (arr[j] == i) { 14 | found = 1; 15 | break; 16 | } 17 | } 18 | if (found == 0) 19 | return i; 20 | } 21 | return -1; 22 | } 23 | ``` 24 | 25 | TC: O(n^2) 26 | SC: O(1) 27 | 28 | Better: Use hashing 29 | We can use a hash array of size n+1 with all zeroes to mark the presence of all elements in the array. This approach will work even if the array contains duplicate elements. hash_array[arr[i]]=1 if the element exists. 30 | if hash_array[i]==0 then i is the missing number 31 | TC: O(2N) 32 | SC: O(N) for hashing 33 | 34 | Optimal: Use sum or xor 35 | 36 | Sum: Find the sum of all elements in the array and subtract it from the sum of first n natural numbers. The result is the missing number. 37 | Formula: n(n+1)/2 38 | But this approach will not work if the array contains duplicate elements and will exceed the range of int if the array size is large. 39 | TC: O(N) 40 | SC: O(1) 41 | 42 | XOR: XOR all the elements in the array and then XOR it with all the elements from 1 to n. The result is the missing number. 43 | XOR1=xor of all array elements 44 | XOR2=xor of all elements from 1 to n 45 | Missing number = XOR1 ^ XOR2 46 | Reason: 1^1=0, 0^7=7 47 | TC: O(N) 48 | SC: O(1) 49 | 50 | 51 | https://leetcode.com/problems/missing-number/description/ -------------------------------------------------------------------------------- /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 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 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; 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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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; i& 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 mpp; 26 | mpp[0]=1; 27 | int XR=0; 28 | 29 | 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; 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/SubArrays/MaximumSubArraySum.txt: -------------------------------------------------------------------------------- 1 | Given array you need to find maximum sub array sum 2 | 3 | 4 | Brute: O(n^3) 5 | Generate all sub arrays and find sum of each sub array and return maximum sum(in three loops) 6 | SC: O(1) 7 | 8 | Better: O(n^2) 9 | Generate all sub arrays and find sum of each sub array and return maximum sum(in two loops) 10 | 11 | 12 | Optimal: O(n) 13 | Use kadane's algorithm 14 | 15 | 16 | 1. Start iterating in array, intialize sum and maxSum to 0 17 | 2. keep adding array elements to sum variable 18 | 3. if sum is greater than maxSum, update maxSum 19 | 4. if sum is less than 0, update sum to 0 but why? because if sum is less than 0, it will decrease the sum of next sub array 20 | 5. Whenever you are taking sum or adding, first add and then check if any condition is satisfied 21 | 22 | FOLLOW UP QUESTION: 23 | 1. If you need to return the sub array as well, then you need to maintain two variables start and end 24 | 2. Whenever sum==0, you can update start=i, and when sum>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 | -------------------------------------------------------------------------------- /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 mpp; 51 | mpp[0]=1; 52 | long long frequency=0; 53 | int sum=0; 54 | 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 | -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/Subsequences/LongestIncreasingSubsequence.txt: -------------------------------------------------------------------------------- 1 | Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. 2 | 3 | Brute force approach 4 | TC:O(n^2) SC:O(1) 5 | for(int i=0; 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) -------------------------------------------------------------------------------- /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/IntersectionOfArray.txt: -------------------------------------------------------------------------------- 1 | Intersection of two arrays 2 | 3 | Brute: 4 | 1. Iterate both arrays in nested one, and check if any element is common. O(n^2) 5 | 2. Create a visited array with size of second array containing zero elements 6 | 3. Check whether the element of first array is present in second array, if yes, mark it as visited with value of 1 7 | 8 | This result will have occurences:(to remove this occurences, use set) 9 | vector ans; 10 | vector visited(arr2.size(), 0); 11 | for(int i=0; i 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 | } -------------------------------------------------------------------------------- /Arrays/1-D Arrays/Patterns/TwoPointers/MaxSizeKSum.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/max-number-of-k-sum-pairs/description/ 2 | 3 | You are given an integer array nums and an integer k. 4 | 5 | In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. 6 | 7 | Return the maximum number of operations you can perform on the array. 8 | 9 | 10 | class Solution { 11 | public: 12 | int maxOperations(vector& 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]& 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 | }; -------------------------------------------------------------------------------- /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/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(jsecondLargest) 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/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/1-D Arrays/Patterns/TwoPointers/UnionOfArray.txt: -------------------------------------------------------------------------------- 1 | Union of two sorted arrays (contains duplicate) 2 | 3 | Brute: Use set, and insert first array elements and then insert second array elements 4 | Time complexity for set varies, it is not very much particular 5 | TC: O(n1logn) +O(mlogn)+ O(n1+m) 6 | 7 | SC: O(n1+m)+O(n1+m)->for 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 -------------------------------------------------------------------------------- /Arrays/2-D Arrays/Basic/Shift2DArray.txt: -------------------------------------------------------------------------------- 1 | Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. 2 | 3 | In one shift operation: 4 | 5 | Element at grid[i][j] moves to grid[i][j + 1]. 6 | Element at grid[i][n - 1] moves to grid[i + 1][0]. 7 | Element at grid[m - 1][n - 1] moves to grid[0][0]. 8 | Return the 2D grid after applying shift operation k times. 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | vector> 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 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/2-D Arrays/Medium/RotateImage.txt: -------------------------------------------------------------------------------- 1 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 2 | 3 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 4 | 5 | 6 | 7 | 8 | Brute: 9 | int rows=matrix.size(); 10 | int cols=matrix[0].size(); 11 | vector> 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; 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 | }; -------------------------------------------------------------------------------- /Arrays/2-D Arrays/Medium/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/2-D Arrays/Medium/a.out -------------------------------------------------------------------------------- /Arrays/Algorithms/BubbleSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/BubbleSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/BucketSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/BucketSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/CountSort.txt: -------------------------------------------------------------------------------- 1 | Approach to count sort: 2 | 3 | => 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 | -------------------------------------------------------------------------------- /Arrays/Algorithms/DNFsort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/DNFsort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/Gap(shellsort).txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/Gap(shellsort).txt -------------------------------------------------------------------------------- /Arrays/Algorithms/InsertionSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/InsertionSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/Kadane's.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/Kadane's.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/MergeSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/MergeSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/MooresVoting.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/MooresVoting.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/QuickSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/QuickSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/SelectionSort.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/SelectionSort.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/SlidingWindow.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/SlidingWindow.txt -------------------------------------------------------------------------------- /Arrays/Algorithms/TwoPointers.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Arrays/Algorithms/TwoPointers.txt -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/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 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/GuessNumberLowerOrHigher.txt: -------------------------------------------------------------------------------- 1 | We are playing the Guess Game. The game is as follows: 2 | 3 | I pick a number from 1 to n. You have to guess which number I picked. 4 | 5 | Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. 6 | 7 | You call a pre-defined API int guess(int num), which returns three possible results: 8 | 9 | -1: Your guess is higher than the number I picked (i.e. num > 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 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/KthMissingPositive.txt: -------------------------------------------------------------------------------- 1 | 2 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 3 | 4 | Return the kth positive integer that is missing from this array. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: arr = [2,3,4,7,11], k = 5 11 | Output: 9 12 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 13 | 14 | 15 | 16 | class Solution { 17 | public: 18 | // Here is the intuiton, the numbers less than or equal to k will incrase the k value or else the loop will break. 19 | int findKthPositive(vector& arr, int k) { 20 | // for(int i=0; i=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/Binary Search/1-D Arrays/Basic/SearchInsertPosition.txt: -------------------------------------------------------------------------------- 1 | Search insert element 2 | You are given a sorted array and a given number, if number exists in array return its index, if not return the index where it would be if it were inserted in order. 3 | 4 | 5 | It is just implementation of lower bound 6 | 7 | int searchInsert(vector& 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 | } -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Basic/UpperBound.txt: -------------------------------------------------------------------------------- 1 | What is upper bound? 2 | Upper bound of an element is the smallest element greater than the given element. 3 | arr[index]>n 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/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/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/Binary Search/1-D Arrays/Medium/FindKClosest.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector 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/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/SearchAnswersSpace/FindPeakElement.txt: -------------------------------------------------------------------------------- 1 | A peak element is an element that is strictly greater than its neighbors. 2 | 3 | Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. 4 | 5 | You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. 6 | 7 | You must write an algorithm that runs in O(log n) time. 8 | 9 | 10 | 11 | class Solution { 12 | public: 13 | int findPeakElement(vector& 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/Medium/SearchAnswersSpace/KokoEatingBanans.txt: -------------------------------------------------------------------------------- 1 | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. 2 | 3 | Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. 4 | 5 | Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. 6 | 7 | Return the minimum integer k such that she can eat all the bananas within h hours. 8 | 9 | 10 | class Solution { 11 | public: 12 | long long calculateHours(vector 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 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchAnswersSpace/NthRootM.txt: -------------------------------------------------------------------------------- 1 | You are given 2 numbers (n , m); the task is to find n√m (nth root of m). 2 | 3 | 4 | Input: n = 2, m = 9 5 | Output: 3 6 | Explanation: 3^2 = 9 7 | 8 | 9 | Brute force: 10 | int NthRoot(int n, int m) { 11 | // Write your code here. 12 | for(int i=1; i<=m/2; i++){ 13 | long long power=pow(i,n); 14 | if(power>m) 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) -------------------------------------------------------------------------------- /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/Binary Search/1-D Arrays/Medium/SearchAnswersSpace/Sqrt(x).txt: -------------------------------------------------------------------------------- 1 | You are given a number n, you need to find the square root of it. 2 | Only floor value is required. 3 | 4 | if you are required to find double value of square root, you can use inbuilt function sqrt(). 5 | 6 | Example 1: 7 | 8 | Input: 9 | n = 5 10 | Output: 2 11 | Explanation: Square root of 5 is 2.236068. 12 | The floor value of 2.236068 is 2. 13 | 14 | Answer in floor value code: 15 | Code to get floor value of square root of a number: 16 | 17 | Brute force: 18 | int ans=1; 19 | Linear search from 1 to n, if i*i<=n, ans=i, else break; 20 | for(int i=1; i<=n; i++){ 21 | if(i*i<=n){ 22 | ans=i; 23 | } else { 24 | break; 25 | } 26 | } 27 | 28 | Eventually low will be pointing to the right one and high one will be pointing to the maximum one, so at the end high will be the answer. 29 | 30 | int floorSqrt(int n) 31 | { 32 | // Write your code here. 33 | int low=1, high=n; 34 | while(low<=high){ 35 | long long mid=(low+high)/2; 36 | long long square=mid*mid; 37 | if(square<=n){ 38 | low=mid+1; 39 | } else { 40 | high = mid - 1; 41 | } 42 | } 43 | return high; 44 | } 45 | -------------------------------------------------------------------------------- /Arrays/Binary Search/1-D Arrays/Medium/SearchSorted/FindKthRotation.txt: -------------------------------------------------------------------------------- 1 | You are given n size array rotated one time, find the index of minimum element. which means you will also get the number of times the array is rotated. 2 | 3 | 4 | TC: O(logn) 5 | SC: O(1) 6 | 7 | 8 | int findKRotation(vector &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]& 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 | -------------------------------------------------------------------------------- /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/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/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>& 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/2-D Arrays/Medium/SearchInA2DMatrix2.txt: -------------------------------------------------------------------------------- 1 | Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: 2 | 3 | Integers in each row are sorted in ascending from left to right. 4 | Integers in each column are sorted in ascending from top to bottom. 5 | 6 | 7 | 8 | class Solution { 9 | public: 10 | bool searchMatrix(vector>& 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/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/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) -------------------------------------------------------------------------------- /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; 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 | } -------------------------------------------------------------------------------- /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/Implement.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* constructLL(vector& 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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; -------------------------------------------------------------------------------- /Maths/BasicDivisorLCMGCD/FindCommonFactors.txt: -------------------------------------------------------------------------------- 1 | Given two positive integers a and b, return the number of common factors of a and b. 2 | 3 | An integer x is a common factor of a and b if x divides both a and b. 4 | 5 | 6 | Algorithm: 7 | 1. Take minimum of them. 8 | 2. Iterate from 1 to min. 9 | 3. If both are divisible by i, then increment count. 10 | 4. Return count. 11 | 12 | TC: O(min(a,b)) 13 | SC: O(1) 14 | -------------------------------------------------------------------------------- /Maths/BasicDivisorLCMGCD/GCDHCF.txt: -------------------------------------------------------------------------------- 1 | Find GCD or HCF of given two numbers 2 | 3 | 4 | Brute: 5 | 6 | for(int i=min(a,b); 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 -------------------------------------------------------------------------------- /Maths/BasicDivisorLCMGCD/PrintDivisors.txt: -------------------------------------------------------------------------------- 1 | https:www.codingninjas.com/codestudio/problems/print-all-divisors-of-a-number_1164188?utm_source=youtube&utm_medium=affiliate&utm_campaign=striver_Arrayproblems&leftPanelTab=1 2 | 3 | Now instead of just going till n^2, we can go till square root of n sqrt(n), why? 4 | 36: 5 | 1 36 (i, n/i) 6 | 2 18 (i, n/i) 7 | 3 12 (i, n/i) 8 | 4 9 (i, n/i) 9 | 6 6 (i, n/i) 10 | ----------------- 11 | 9 4 (i, n/i) 12 | 12 3 (i, n/i) 13 | 18 2 (i, n/i) 14 | 36 1 (i, n/i) 15 | 16 | but taking directly sqrt(n) will repeatedly call the function many times, so 17 | instead we can take i*i 18 | vector 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< 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()>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/CountSetBits.txt: -------------------------------------------------------------------------------- 1 | https://practice.geeksforgeeks.org/problems/set-bits0143/1 2 | 3 | Count total set bits in a given number -------------------------------------------------------------------------------- /Maths/DivisibleBy7.txt: -------------------------------------------------------------------------------- 1 | Given an n-digit large number in form of string, check whether it is divisible by 7 or not. Print 1 if divisible by 7, otherwise 0. 2 | 3 | 4 | Example 1: 5 | 6 | Input: num = "8955795758" 7 | Output: 1 8 | Explanation: 8955795758 is divisible 9 | by 7. 10 | 11 | 12 | class Solution{ 13 | public: 14 | int isdivisible7(string num){ 15 | //complete the function here 16 | int n=num.size(); 17 | int first = (num[n-1]-'0') * 2; 18 | int sum=0; 19 | for(int i=0; i0){ 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=(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) -------------------------------------------------------------------------------- /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= 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; -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /Miscellaneous/CheckNDoubleExisits.txt: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/check-if-n-and-its-double-exist/description/ -------------------------------------------------------------------------------- /Miscellaneous/HappyNumber.txt: -------------------------------------------------------------------------------- 1 | Write an algorithm to determine if a number n is happy. 2 | 3 | A happy number is a number defined by the following process: 4 | 5 | Starting with any positive integer, replace the number by the sum of the squares of its digits. 6 | Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 7 | Those numbers for which this process ends in 1 are happy. 8 | Return true if n is a happy number, and false if not. 9 | 10 | 11 | 12 | 13 | Code: 14 | class Solution { 15 | long long getSum(int n){ 16 | long long digitSum=0; 17 | while(n>0){ 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 | } -------------------------------------------------------------------------------- /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]) 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"< 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"< 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< 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< 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< 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< 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"< 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< 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 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< 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 | }; -------------------------------------------------------------------------------- /Strings/Basic/ConvertAllSmallCaseToUpperCase.txt: -------------------------------------------------------------------------------- 1 | 2 | Convert the given string to uppercase without using any predefined function. 3 | 4 | 5 | Example 1: 6 | 7 | Input: 8 | S = "geeks" 9 | Output: GEEKS 10 | 11 | Explanation: 12 | 'a' in ASCII = 97 and 'A' = 65, which we get by subtracting 32 from 97. 13 | 14 | 15 | or inputcharacter-'a'+'A' 16 | 17 | 18 | 19 | 20 | string to_upper(string str){ 21 | //code 22 | 23 | 24 | for(int i=0; i=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<& 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=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 | -------------------------------------------------------------------------------- /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/Palindrome/CountPalindromicStrings.txt: -------------------------------------------------------------------------------- 1 | Given a string s, return the number of palindromic substrings in it. 2 | 3 | A string is a palindrome when it reads the same backward as forward. 4 | 5 | A substring is a contiguous sequence of characters within the string. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "abc" 12 | Output: 3 13 | Explanation: Three palindromic strings: "a", "b", "c". 14 | 15 | 16 | 17 | 18 | 19 | class Solution { 20 | // public: 21 | // bool checkPalindrome(string s, int start, int end){ 22 | // while(start<=end){ 23 | // if(s[start]!=s[end]){ 24 | // return false; 25 | // } 26 | // start++; 27 | // end--; 28 | // } 29 | 30 | // return true; 31 | // } 32 | public: 33 | int checkEvenAndOddLength(string s, int start, int end){ 34 | int count=0; 35 | while(start>=0 && end=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; i 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 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 -------------------------------------------------------------------------------- /Strings/Basic/RemoveAdjacentCharacters.txt: -------------------------------------------------------------------------------- 1 | You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. 2 | 3 | We repeatedly make duplicate removals on s until we no longer can. 4 | 5 | Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "abbaca" 12 | Output: "ca" 13 | Explanation: 14 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 15 | 16 | 17 | 18 | 19 | class Solution { 20 | public: 21 | string removeDuplicates(string s) { 22 | string ans=""; 23 | 24 | // if already element that we are adding that exists, so we remove the element and jump on to the next element. 25 | for(int i=0; i0){ 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 | }; -------------------------------------------------------------------------------- /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> 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. -------------------------------------------------------------------------------- /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/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 | }; -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /Strings/Medium/RomanToIntegerandViceversa/RomanToInteger.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 ones 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 a roman numeral, convert it to an integer. 19 | 20 | 21 | 22 | 23 | class Solution { 24 | public: 25 | int romanToInt(string s) { 26 | int ans=0; 27 | unordered_map 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 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 | }; -------------------------------------------------------------------------------- /Strings/Medium/StringToInteger(atoi).txt: -------------------------------------------------------------------------------- 1 | Input: s = "42" 2 | Output: 42 3 | Explanation: The underlined characters are what is read in, the caret is the current reader position. 4 | Step 1: "42" (no characters read because there is no leading whitespace) 5 | ^ 6 | Step 2: "42" (no characters read because there is neither a '-' nor '+') 7 | ^ 8 | Step 3: "42" ("42" is read in) 9 | ^ 10 | The parsed integer is 42. 11 | Since 42 is in the range [-231, 231 - 1], the final result is 42. 12 | Example 2: 13 | 14 | Input: s = " -42" 15 | Output: -42 16 | Explanation: 17 | Step 1: " -42" (leading whitespace is read and ignored) 18 | ^ 19 | Step 2: " -42" ('-' is read, so the result should be negative) 20 | ^ 21 | Step 3: " -42" ("42" is read in) 22 | 23 | 24 | 25 | 26 | class Solution { 27 | public: 28 | int myAtoi(string s) { 29 | int i=0, sign=1, ans=0; 30 | // if there exists empty spaces skip them 31 | while(s[i]==' '){ 32 | i++; 33 | } 34 | // if they contain any operation at start, consider them 35 | if(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) -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /Trees/BinaryTrees/Traversal/LevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 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 | } -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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/Questions/DiameterOfTree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdfaizanahmed786/Data-Structures-Algorithms/e3a6f9ce30e221c2f07bbadc6de7906162652ac0/Trees/Questions/DiameterOfTree.cpp -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | !#/bin/bash 2 | g++ Patterns/basic-patterns.cpp 3 | ./a.out --------------------------------------------------------------------------------