├── .gitignore ├── Arrays-In-Js ├── Dutch-National-Flag.js ├── Max-Min-In-Array.js └── Reverse-An-Array.js ├── Arrays ├── 10_MinimumNumberOfJumpsToReachEndOfAnArray.cpp ├── 11_FindDuplicateInAnArrayOfN+1Integers.cpp ├── 12_MergeTwoSortedArraysWithoutExtraSpace.cpp ├── 13_Kadane'sAlgo.cpp ├── 14_MergeIntervals.cpp ├── 15_NextPermutation.cpp ├── 16_Count-Inversions.cpp ├── 16_CountInversion.cpp ├── 17_BestTimeToBuyAndSellStock.cpp ├── 18_FindAllPairsOnIntegerArrayWhoseSumIsEqualToAGivenNumber.cpp ├── 19_FindCommonElementsIn3SortedArrays.cpp ├── 1_ReverseAnArray.cpp ├── 20_RearrangeTheArrayInAlternatingPositiveAndNegativeItemsWithO1ExtraSpace.cpp ├── 21_FindIfThereIsAnySubarrayWithSumEqualTo0.cpp ├── 22_FactorialOfALargeNumber.cpp ├── 23_FindMaximumProductSubarray.cpp ├── 24_LongestConsecutiveSubsequence.cpp ├── 25_ArrayElementsAppearingMoreThanNKTimes.cpp ├── 26_MaximumProfitByBuyingAndSellingAShareAtmostTwice.cpp ├── 27_FindWhetherAnArrayIsSubsetOfAnotherArray.cpp ├── 28_FindTheTripletThatSumToAGivenValue.cpp ├── 29_TrappingRainWater.cpp ├── 2_FindTheMinimumAndMaximumElementInAnArray.cpp ├── 30_ChocolateDistributionProblem.cpp ├── 31_SmallestSubarrayWithSumGreaterThanAGivenValue.cpp ├── 32_ThreeWayPartitioningOfAnArrayAroundAGivenValue.cpp ├── 33_MinimumSwapsRequiredToBringElementsLessThanKTogether.cpp ├── 34_MinimumNumberOfOperationsRequiredToMakeAnArrayPalindrome.cpp ├── 35_MedianOfTwoSortedArrayOfSameSize.cpp ├── 36_MedianOf2SortedArraysOfDifferentSizes.cpp ├── 37_Maximum Product Subarray.cpp ├── 3_KthSmallestElement.cpp ├── 4_SortAnArrayOf0s1s2s.cpp ├── 5_MoveAllNegativeNumbersToBeginning.cpp ├── 6_FindUnionAndIntersectionOfTwoarrays.cpp ├── 7_CyclicallyRotateAnArrayByOne.cpp ├── 8_LargestSumContiguousSubarray.cpp └── 9_MinimizeTheMaximumDifferenceBetweenHeights.cpp ├── Backtracking ├── 1_RatInAMazeBacktracking.cpp ├── 2_NQueenProblem.cpp ├── 3_ColoringProblem.cpp └── 5_SudokuSolver ├── Binary Tree ├── 10_RightViewofbinaryTree ├── 12_BottomViewOfBinaryTree.cpp ├── 14_CheckForBalancedTree.cpp ├── 3_HeightOfBinaryTree.cpp ├── 4_DiameterOfBinaryTree.cpp └── Leetcode_145_PostOrderTraversalRecursiveAndIterative.cpp ├── Graphs ├── 13_ImplementTopologicalSort.cpp ├── 22_ImplementFloydWarshallAlgorithm.cpp ├── 25_SnakeandLadderProblem.cpp ├── 27_StronglyConnectedComponents(Kosaraju'sAlgo).cpp ├── 32_CheapestFlightsWithinKStops.cpp ├── 358_DFS_SearchElement.cpp ├── 6_Floodfillalgorithm.cpp ├── 7_MinimumStepByKnight.cpp ├── 9_CloneAGraph.cpp └── DFS_SearchElement.cpp ├── Linked List ├── 2_IsPalindrome.cpp ├── 6_RemoveDuplicatesfromSortedList.cpp └── Floyds_Cycle_Detection_Algorithm.cpp ├── Matrix ├── 1_SpiralTraversalOfAMatrix.cpp ├── 2_SearchAnElementInAMatrix.cpp ├── 3_FindMedianInRowWiseSortedMatrix.cpp ├── 4_FindRowWithMaximumNumberOf1s.cpp └── 5_PrintElementsInSortedOrderUsingRowColumnWiseSortedMatrix.cpp ├── README.md └── Stacks&Queues ├── 10_TheCelebrityProblem.cpp ├── 11_ArithmeticExpressionEvaluation.txt ├── 12_EvaluatePostfixExpression.cpp ├── 13_ImplementAMethodToInsertAnElementAtItsBottomWithoutUsingAnyOtherDataStructure.cpp ├── 14_ReverseAStackUsingRecursion.cpp ├── 15_SortAStackUsingRecursion.cpp ├── 16_MergeOverlappingIntervals.cpp ├── 17_LargestRectangularAreaInHistogram.cpp ├── 18_LengthOfTheLongestValidSubstring.cpp ├── 19_ExpressionContainsRedundantBracketOrNot.cpp ├── 1_ImplementStackFromScratch.cpp ├── 20_ImplementStackUsingQueue.cpp ├── 2_ImplementQueueFromScratch.cpp ├── 3_Implement2StacksInAnArrays.cpp ├── 4_FindTheMiddleElementOfStack.cpp ├── 5_ImplementNStacksInAnArray.cpp ├── 6_CheckTheExpressionHasValidOrBalancedParenthesisOrNot.cpp ├── 7_ReverseAStringUsingStack.cpp ├── 8_DesignAStackThatSupportsgetMinInO1TimeAndO1ExtraSpace.cpp └── 9_FindTheNextGreaterElement.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe -------------------------------------------------------------------------------- /Arrays-In-Js/Dutch-National-Flag.js: -------------------------------------------------------------------------------- 1 | // Given an array A[] consisting of only 0s, 1s, and 2s. The task is to write a function that sorts 2 | // the given array. The functions should put all 0s first, then all 1s and all 2s in last. 3 | // This Problem is also known as Dutch National Flag. 4 | 5 | // First Sol --> Using Sort 6 | // Second Sol ---> Count Sort 7 | 8 | //Efficient Solution 9 | 10 | function DutchNationalFlagSort(array){ 11 | 12 | let low =0; 13 | let mid = 0; 14 | let high = array.length -1; 15 | let temp =0; 16 | 17 | while(mid <=high){ 18 | 19 | if(array[mid] == 0){ 20 | temp = array[low] 21 | array[low] = array[mid] 22 | array[mid] = temp 23 | 24 | low++; 25 | mid++; 26 | }else if(array[mid] == 1){ 27 | mid++; 28 | }else{ 29 | temp = array[mid] 30 | array[mid] = array[high] 31 | array[high] = temp 32 | 33 | high-- 34 | } 35 | } 36 | 37 | return array; 38 | } 39 | 40 | 41 | console.log(DutchNationalFlagSort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ])); -------------------------------------------------------------------------------- /Arrays-In-Js/Max-Min-In-Array.js: -------------------------------------------------------------------------------- 1 | // Find Minimum and Maximum Element from Array 2 | 3 | // Time Complexity = O(n) 4 | function minMax(array){ 5 | let min = Number.POSITIVE_INFINITY 6 | let max = Number.NEGATIVE_INFINITY 7 | 8 | for( let i=0; i< array.length ;i++){ 9 | if(array[i] < min){ 10 | min = array[i] 11 | } 12 | if( array[i] > max){ 13 | max = array[i] 14 | } 15 | } 16 | 17 | console.log("Min" , min); 18 | console.log("Max", max); 19 | } 20 | 21 | minMax([1000, 11, 445, 1, 330, 3000]) -------------------------------------------------------------------------------- /Arrays-In-Js/Reverse-An-Array.js: -------------------------------------------------------------------------------- 1 | // Example : [1,2,3,4] O/P : [4,3,2,1] 2 | 3 | 4 | // Method 1 : TC : O(n) 5 | function reverse(array){ 6 | 7 | for(let i=array.length-1;i>=0 ;i--){ 8 | console.log(array[i]) 9 | } 10 | } 11 | 12 | reverse([1,2,3,4,5]) -------------------------------------------------------------------------------- /Arrays/10_MinimumNumberOfJumpsToReachEndOfAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Refer : https://www.youtube.com/watch?v=5Du2iSRrbEw 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | vector a(n); 11 | for(auto &it : a) cin>>it; 12 | int maxReach = a[0]; 13 | int step = a[0]; 14 | int jump = 1; 15 | if(a[0] == 0){ 16 | cout<<-1<= maxReach){ 29 | cout<<-1<& nums) { 9 | 10 | int tortoise = nums[0]; 11 | int hare = nums[0]; 12 | do{ 13 | tortoise = nums[tortoise]; 14 | hare = nums[nums[hare]]; 15 | }while(tortoise != hare); 16 | 17 | tortoise = nums[0]; 18 | while(tortoise != hare){ 19 | tortoise = nums[tortoise]; 20 | hare = nums[hare]; 21 | } 22 | return hare; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Arrays/12_MergeTwoSortedArraysWithoutExtraSpace.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int arr1[], int arr2[], int n, int m) { 5 | // code here 6 | int gap = n + m; 7 | int i, j; 8 | // cout<<"here"< 0 ; gap = nextGap(gap) ){ 11 | //Comparing elements in first array arr1[] 12 | // cout<<"Mygap"< arr1[i+gap]) 15 | swap(arr1[i], arr1[i+gap]); 16 | } 17 | //Comparing elements in both array arr1[] and arr2[] 18 | 19 | for(j = (gap > n) ? (gap - n) : 0; i < n && j < m; i++, j++ ){ 20 | // cout<<"gap = "< arr2[j]) 24 | swap(arr1[i], arr2[j]); 25 | } 26 | 27 | //Comparing elements in second array arr2[] 28 | if(j < m){ 29 | for(j = 0; j + gap < m; j++){ 30 | if(arr2[j] > arr2[j + gap]) 31 | swap(arr2[j], arr2[j+gap]); 32 | } 33 | } 34 | } 35 | } 36 | 37 | int main(){ 38 | 39 | -------------------------------------------------------------------------------- /Arrays/13_Kadane'sAlgo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //kadane's Algorithm 5 | int largest_sum_subarray (int arr[], int n) { 6 | int sum = 0; 7 | int best = INT_MIN; 8 | 9 | for (int i = 0; i < n; i++) { 10 | sum = max (arr[i], sum + arr[i]); 11 | best = max (best, sum); 12 | } 13 | 14 | return best; 15 | } 16 | 17 | int main() { 18 | 19 | ios_base::sync_with_stdio(false); 20 | cin.tie(NULL); 21 | cout.tie(NULL); 22 | 23 | int test_cases; 24 | cin >> test_cases; 25 | 26 | while (test_cases--) { 27 | int n; 28 | cin >> n; 29 | 30 | int arr[n]; 31 | for (int i = 0; i < n; i++) { 32 | cin >> arr[i]; 33 | } 34 | 35 | int max_sum = largest_sum_subarray (arr, n); 36 | 37 | cout << max_sum << "\n"; 38 | } 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Arrays/14_MergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | if(intervals.empty()) return intervals; 5 | sort(intervals.begin(), intervals.end(), [](vector &a, vector &b){ 6 | return a[0] < b[0]; 7 | }); 8 | int index = 0; 9 | vector> ans; 10 | ans.push_back(intervals[index]); 11 | for(int i = 1; i < intervals.size(); i++){ 12 | if(ans[index][1] >= intervals[i][0]) 13 | ans[index][1] = max(ans[index][1], intervals[i][1]); 14 | else{ 15 | ans.push_back(intervals[i]); 16 | index++; 17 | } 18 | 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Arrays/15_NextPermutation.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity : O(n) 2 | //Space Complexity : O(1) 3 | 4 | class Solution { 5 | public: 6 | void nextPermutation(vector& nums) { 7 | // next_permutation(nums.begin(),nums.end()); 8 | int i = nums.size() - 2; 9 | while (i >= 0 && nums[i + 1] <= nums[i]) { 10 | i--; 11 | } 12 | if (i >= 0) { 13 | int j = nums.size() - 1; 14 | while (j >= 0 && nums[j] <= nums[i]) { 15 | j--; 16 | } 17 | swap(nums[i],nums[j]); 18 | } 19 | reverse(nums.begin() + i +1,nums.end()); 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Arrays/16_Count-Inversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | // arr[]: Input Array 9 | // N : Size of the Array arr[] 10 | // Function to count inversions in the array. 11 | long long merge(long long arr[], long long temp[], long long left, long long mid, long long right){ 12 | long long i, j, k; 13 | long long inv_count = 0; 14 | 15 | i = left; 16 | j = mid; 17 | k = left; 18 | 19 | while(( i <= mid - 1)&&( j <= right )){ 20 | if(arr[i] <= arr[j]){ 21 | temp[k++] = arr[i++]; 22 | } 23 | else{ 24 | temp[k++] = arr[j++]; 25 | 26 | inv_count = inv_count + (mid - i); 27 | } 28 | } 29 | 30 | while( i <= mid - 1) 31 | temp[k++] = arr[i++]; 32 | while( j <= right ) 33 | temp[k++] = arr[j++]; 34 | 35 | for(i = left; i <= right; i++ ){ 36 | arr[i] = temp[i]; 37 | } 38 | 39 | return inv_count; 40 | } 41 | 42 | long long mergesort( long long arr[], long long temp[], long long left, long long right){ 43 | long long mid, inv_count = 0; 44 | 45 | if(right > left){ 46 | 47 | mid = (left + right)/2; 48 | 49 | inv_count += mergesort(arr, temp, left, mid); 50 | inv_count += mergesort(arr, temp, mid + 1, right); 51 | 52 | inv_count += merge(arr, temp, left, mid + 1, right); 53 | } 54 | 55 | return inv_count; 56 | } 57 | 58 | long long inversionCount(long long arr[], long long N) 59 | { 60 | long long temp[N]; 61 | long long ct = mergesort(arr, temp, 0, N - 1); 62 | return ct; 63 | } 64 | 65 | }; 66 | 67 | // { Driver Code Starts. 68 | 69 | int main() { 70 | 71 | long long T; 72 | cin >> T; 73 | 74 | while(T--){ 75 | long long N; 76 | cin >> N; 77 | 78 | long long A[N]; 79 | for(long long i = 0;i> A[i]; 81 | } 82 | Solution obj; 83 | cout << obj.inversionCount(A,N) << endl; 84 | } 85 | 86 | return 0; 87 | } 88 | // } Driver Code Ends -------------------------------------------------------------------------------- /Arrays/16_CountInversion.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity : O(n^2) 2 | //Space Complexity : O(1) 3 | 4 | #include 5 | using namespace std; 6 | 7 | int getInvCount(int arr[], int n) 8 | { 9 | int inv_count = 0; 10 | for (int i = 0; i < n - 1; i++) 11 | for (int j = i + 1; j < n; j++) 12 | if (arr[i] > arr[j]) 13 | inv_count++; 14 | 15 | return inv_count; 16 | } 17 | 18 | // Driver Code 19 | int main() 20 | { 21 | int arr[] = { 1, 20, 6, 4, 5 }; 22 | int n = sizeof(arr) / sizeof(arr[0]); 23 | cout << " Number of inversions are " 24 | << getInvCount(arr, n); 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Arrays/17_BestTimeToBuyAndSellStock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | if(prices.empty()) return 0; 5 | int max_profit = 0; 6 | int min_ele = prices[0]; 7 | for(int i = 0; i < prices.size(); i++){ 8 | min_ele = min(min_ele, prices[i]); 9 | max_profit = max(max_profit, prices[i] - min_ele); 10 | } 11 | return max_profit; 12 | 13 | } 14 | 15 | }; 16 | -------------------------------------------------------------------------------- /Arrays/18_FindAllPairsOnIntegerArrayWhoseSumIsEqualToAGivenNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int getPairsCount(int arr[], int n, int k) { 4 | // code here 5 | unordered_mapmp; 6 | for(int i = 0; i < n; i++){ 7 | mp[arr[i]]++; 8 | } 9 | int cnt = 0; 10 | for(int i = 0; i < n; i++){ 11 | int x = (k-arr[i]); 12 | if(mp[x] > 0){ 13 | cnt += mp[k-arr[i]]; 14 | 15 | if(k-arr[i] == arr[i]) //Making sure that the counter counts when two different pairs are found not with itself 16 | cnt--; //i.e , consider pairs other than itself 17 | 18 | } 19 | } 20 | return cnt/2; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Arrays/19_FindCommonElementsIn3SortedArrays.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity : O(n1 + n2+ n3) 2 | //Space Complexity : O(n1 +n2+ n3) 3 | 4 | class Solution 5 | { 6 | public: 7 | vector commonElements (int A[], int B[], int C[], int n1, int n2, int n3) 8 | { 9 | vector res; 10 | int i = 0, j = 0, p; 11 | while(i ans; 31 | i = 0, j = 0; 32 | int q; 33 | while(i 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | string s; 9 | cin>>s; 10 | int n = s.length(); 11 | for(int i = 0; i < n/2; i++){ 12 | swap(s[i],s[n-1-i]); 13 | } 14 | cout< 2 | using namespace std; 3 | 4 | /* Approach 1 : If ordering was not important we can simply separte the positive values to one side and negative value to the other and then rearrange them alternatively 5 | int main(){ 6 | int n; 7 | cin>>n; 8 | vectorv(n); 9 | for(auto &it : v) cin>>it; 10 | int k = n-1, j = 0; 11 | while(j < k){ //Arranging all the negative values to the end of the array 12 | while(j < n && v[j] > 0 ) 13 | j++; 14 | while(k >j && v[j] < 0) 15 | k--; 16 | if(j < k) 17 | swap(v[j], v[k]); 18 | } 19 | if(j == n-1){ 20 | for(auto i : v) 21 | cout< &v, int n){ //This forces all the negative elements of the array to the beginning 42 | int pivot = 0; 43 | int pIndex = 0; 44 | for(int i = 0; i>n; 56 | vectorv(n); 57 | for(auto &it : v) cin>>it; 58 | int p = partition(v, n); 59 | int i = 0; 60 | while(p < n && v[i]<0){ 61 | swap(v[i], v[p]); 62 | i+=2; 63 | p+=1; 64 | } 65 | for(auto i : v) 66 | cout< v,int index){ 84 | if(index%2 == 0){ 85 | if(v[index] > 0) 86 | return true; 87 | else 88 | return false; 89 | } 90 | else{ 91 | if(v[index] < 0) 92 | return true; 93 | else 94 | return false; 95 | } 96 | } 97 | 98 | int getNextOpposite(vector v, int index){ 99 | for(int i = index+1; i < (int)v.size(); i++){ 100 | if(v[index]*v[i] < 0) 101 | return i; 102 | } 103 | return -1; 104 | } 105 | 106 | void rotateSubarrayRightbyone(vector&v, int start, int end){ 107 | int last = v[end]; 108 | for(int i = end; i>start; i--) 109 | v[i]=v[i-1]; 110 | v[start] = last; 111 | } 112 | 113 | int main(){ 114 | int n; 115 | cin>>n; 116 | vectorv(n); 117 | for(auto &it : v) cin>>it; 118 | for(int i = 0; i < n; i++){ 119 | if(isAtRightPosition(v, i) == false){ 120 | int nextOppositeIndex = getNextOpposite(v, i); 121 | if(nextOppositeIndex != -1){ 122 | rotateSubarrayRightbyone(v, i, nextOppositeIndex); 123 | } 124 | else 125 | break; 126 | } 127 | } 128 | for(auto i : v) 129 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | vector v(n); 11 | for(auto &it : v) cin>>it; 12 | unordered_set st; 13 | int sum = 0, flag = 0; 14 | for(int i = 0; i < n ; i++){ 15 | sum += v[i]; 16 | if(sum == 0 || st.count(sum)){ 17 | cout<<"Yes"< 2 | using namespace std; 3 | #define ll long long 4 | 5 | int main() { 6 | int t; 7 | cin>>t; 8 | while(t--){ 9 | ll n; 10 | cin>>n; 11 | //Approach 1 : But fails for larger number 12 | 13 | // ll res = 1; 14 | // for(ll i = n; i > 0; i--){ 15 | // res *= i; 16 | // } 17 | 18 | //Approach 2 : Basic mathematics 19 | // long double sum = 0; 20 | // string res; 21 | // for(ll i = 1; i<=n; i++){ 22 | // sum += log(i); 23 | // } 24 | // res = to_string(round(exp(sum))); 25 | // string ans; 26 | // for(char ch : res){ 27 | // if(ch!= '.') 28 | // ans += ch; 29 | // else 30 | // break; 31 | // } 32 | // cout<=0; i--) 51 | cout< 2 | using namespace std; 3 | 4 | //Time Complexity : O(n*logn) 5 | //Space Complexity : O(1) 6 | 7 | /*Approach 1 8 | int main() { 9 | int t; 10 | cin>>t; 11 | while(t--){ 12 | int n; 13 | cin>>n; 14 | vector v(n); 15 | for(auto &it : v) cin>>it; 16 | int length = 1, ans = 1; 17 | sort(v.begin(), v.end()); 18 | for(int i = 0; i < n-1; i++){ 19 | if(v[i] != v[i+1]){ 20 | if(v[i+1] == v[i]+1){ 21 | length++; 22 | ans = max(ans, length); 23 | } 24 | else 25 | length = 1; 26 | } 27 | 28 | } 29 | cout<>t; 41 | while(t--){ 42 | int n; 43 | cin>>n; 44 | vector v(n); 45 | for(auto &it : v) cin>>it; 46 | unordered_set st; 47 | for(int i : v) 48 | st.insert(i); 49 | int longestStreak = 1; 50 | for(int nums : st){ 51 | if(!st.count(nums-1)){ 52 | int currNum = nums; 53 | int currenStreak = 1; 54 | while(st.count(currNum + 1)){ 55 | currNum++; 56 | currenStreak++; 57 | } 58 | longestStreak = max(longestStreak, currenStreak); 59 | } 60 | } 61 | cout< 5 | using namespace std; 6 | 7 | // A structure to store an element and its current count 8 | struct eleCount { 9 | int e; // Element 10 | int c; // Count 11 | }; 12 | 13 | // Prints elements with more 14 | // than n/k occurrences in arr[] 15 | // of size n. If there are no 16 | // such elements, then it prints 17 | // nothing. 18 | void moreThanNdK(int arr[], int n, int k) 19 | { 20 | // k must be greater than 21 | // 1 to get some output 22 | if (k < 2) 23 | return; 24 | 25 | /* Step 1: Create a temporary 26 | array (contains element 27 | and count) of size k-1. 28 | Initialize count of all 29 | elements as 0 */ 30 | struct eleCount temp[k - 1]; 31 | for (int i = 0; i < k - 1; i++) 32 | temp[i].c = 0; 33 | 34 | /* Step 2: Process all 35 | elements of input array */ 36 | for (int i = 0; i < n; i++) 37 | { 38 | int j; 39 | 40 | /* If arr[i] is already present in 41 | the element count array, 42 | then increment its count 43 | */ 44 | for (j = 0; j < k - 1; j++) 45 | { 46 | if (temp[j].e == arr[i]) 47 | { 48 | temp[j].c += 1; 49 | break; 50 | } 51 | } 52 | 53 | /* If arr[i] is not present in temp[] */ 54 | if (j == k - 1) { 55 | int l; 56 | 57 | /* If there is position available 58 | in temp[], then place arr[i] in 59 | the first available position and 60 | set count as 1*/ 61 | for (l = 0; l < k - 1; l++) 62 | { 63 | if (temp[l].c == 0) 64 | { 65 | temp[l].e = arr[i]; 66 | temp[l].c = 1; 67 | break; 68 | } 69 | } 70 | 71 | /* If all the position in the 72 | temp[] are filled, then decrease 73 | count of every element by 1 */ 74 | if (l == k - 1) 75 | for (l = 0; l < k-1; l++) 76 | temp[l].c -= 1; 77 | } 78 | } 79 | 80 | /*Step 3: Check actual counts of 81 | * potential candidates in temp[]*/ 82 | for (int i = 0; i < k - 1; i++) 83 | { 84 | // Calculate actual count of elements 85 | int ac = 0; // actual count 86 | for (int j = 0; j < n; j++) 87 | if (arr[j] == temp[i].e) 88 | ac++; 89 | 90 | // If actual count is more than n/k, 91 | // then print it 92 | if (ac > n / k) 93 | cout << "Number:" << temp[i].e 94 | << " Count:" << ac << endl; 95 | } 96 | } 97 | 98 | /* Driver code */ 99 | int main() 100 | { 101 | cout << "First Test\n"; 102 | int arr1[] = { 4, 5, 6, 7, 8, 4, 4 }; 103 | int size = sizeof(arr1) / sizeof(arr1[0]); 104 | int k = 3; 105 | moreThanNdK(arr1, size, k); 106 | 107 | cout << "\nSecond Test\n"; 108 | int arr2[] = { 4, 2, 2, 7 }; 109 | size = sizeof(arr2) / sizeof(arr2[0]); 110 | k = 3; 111 | moreThanNdK(arr2, size, k); 112 | 113 | cout << "\nThird Test\n"; 114 | int arr3[] = { 2, 7, 2 }; 115 | size = sizeof(arr3) / sizeof(arr3[0]); 116 | k = 2; 117 | moreThanNdK(arr3, size, k); 118 | 119 | cout << "\nFourth Test\n"; 120 | int arr4[] = { 2, 3, 3, 2 }; 121 | size = sizeof(arr4) / sizeof(arr4[0]); 122 | k = 3; 123 | moreThanNdK(arr4, size, k); 124 | 125 | return 0; 126 | } -------------------------------------------------------------------------------- /Arrays/26_MaximumProfitByBuyingAndSellingAShareAtmostTwice.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity : O(n) 2 | //Space Complexity : O(n) 3 | 4 | //Leetcode Problem : Buy and sell stock II 5 | 6 | class Solution { 7 | public: 8 | int maxProfit(vector& prices) { 9 | int n = prices.size(); 10 | if(n < 2) 11 | return 0; 12 | vector profit1(n, 0), profit2(n, 0); 13 | int p1 = prices[0]; 14 | int p2 = prices[n-1]; 15 | for(int i = 1; i < n; i++){ 16 | p1 = min(p1, prices[i]); 17 | profit1[i] = max(profit1[i-1], prices[i]-p1); 18 | int j = n-1-i; 19 | p2 = max(p2, prices[j]); 20 | profit2[j] = max(profit2[j+1], p2-prices[j]); 21 | } 22 | int profit = 0; 23 | for(int i = 0; i < n; i++){ 24 | profit = max(profit, profit1[i]+profit2[i]); 25 | } 26 | return profit; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Arrays/27_FindWhetherAnArrayIsSubsetOfAnotherArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Time Complexity : O(mlogm + nlogn) 5 | //Space Complexity : O(1) 6 | 7 | int main() { 8 | int t; 9 | cin>>t; 10 | while(t--){ 11 | int m, n; 12 | cin>>m>>n; 13 | int flag = 0; 14 | vector a1(m), a2(n); 15 | for(auto &it : a1) cin>>it; 16 | for(auto &it : a2) cin>>it; 17 | if(a2.size() > a1.size()){ 18 | cout<<"No"< 2 | using namespace std; 3 | 4 | //Time Complexity : O(n*n) 5 | //Space Complexity : O(1) 6 | 7 | int main() { 8 | int t; 9 | cin>>t; 10 | while(t--){ 11 | int n, x; 12 | cin>>n>>x; 13 | vector a(n); 14 | for(auto &it : a) cin>>it; 15 | int flag = 0, sum = 0; 16 | sort(a.begin(), a.end()); 17 | for(int i = 0; i < n-2; i++){ 18 | int j = i+1, k = n-1; 19 | while(j < k){ 20 | sum = a[i] + a[j] + a[k]; 21 | if(sum > x){ 22 | k--; 23 | } 24 | else if(sum < x) 25 | j++; 26 | else{ 27 | cout<<1<& height) { 4 | //Two Pointer Approach 5 | int left = 0; 6 | int right = height.size() -1; 7 | int left_max = 0, right_max =0, ans =0; 8 | while(left < right){ 9 | if(height[left] < height[right]){ 10 | height[left] >= left_max ? left_max = height[left] 11 | : ans += (left_max - height[left]); 12 | left++; 13 | } 14 | else{ 15 | height[right] >= right_max ? right_max = height[right] 16 | : ans += (right_max - height[right]); 17 | right--; 18 | } 19 | 20 | } 21 | return ans; 22 | } 23 | 24 | }; 25 | -------------------------------------------------------------------------------- /Arrays/2_FindTheMinimumAndMaximumElementInAnArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n; 6 | cout<<"Enter array size"<>n; 8 | int arr[n]; 9 | cout<<"Enter array"<>arr[i]; 12 | int mn = INT_MAX, mx = INT_MIN; 13 | for(int i = 0; i < n; i++){ 14 | if(arr[i] < mn) 15 | mn = arr[i]; 16 | if(arr[i] > mx) 17 | mx = arr[i]; 18 | } 19 | cout<<"Minimum element found :"< 2 | using namespace std; 3 | #define ll long long 4 | 5 | //Time Complexity : O(nlogn) 6 | //Space Complexity : O(1) 7 | 8 | int main() { 9 | int t; 10 | cin>>t; 11 | while(t--){ 12 | ll n, m; 13 | cin>>n; 14 | vector v(n); 15 | for(auto &it : v) cin>>it; 16 | cin>>m; 17 | sort(v.begin(), v.end()); 18 | ll mn = LONG_MAX; 19 | for(int i = 0; i ::max(); 8 | for (int i = 0; i < n && minLen > 1; i++){ 9 | int sum = 0; 10 | for (int j = i; j < n; j++) { 11 | sum += arr[j]; 12 | if (sum > x){ 13 | minLen = min(minLen, j - i + 1); 14 | break; 15 | } 16 | } 17 | } 18 | 19 | return minLen == numeric_limits::max() ? 0 : minLen; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Arrays/32_ThreeWayPartitioningOfAnArrayAroundAGivenValue.cpp: -------------------------------------------------------------------------------- 1 | /*The function should return the modified array 2 | as specified in the problem statement */ 3 | 4 | //Time Complexity : O(n) 5 | //Space Complexity : O(1) 6 | 7 | //Approach : Dutch National Flag Algorithm similar to paritition logic in Quicksort 8 | 9 | vector threeWayPartition(vector A, int a, int b) 10 | { 11 | int low = 0, mid = 0, high = A.size()-1; 12 | while(mid <= high){ 13 | if(A[mid] < a) 14 | swap(A[low++], A[mid++]); 15 | else if(A[mid] > b) 16 | swap(A[mid], A[high--]); 17 | else 18 | mid++; 19 | } 20 | return A; 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Arrays/33_MinimumSwapsRequiredToBringElementsLessThanKTogether.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Time Complexity : O(n) 5 | //Space Complexity : O(1) 6 | 7 | int main() { 8 | int t; 9 | cin>>t; 10 | while(t--){ 11 | int n; 12 | cin>>n; 13 | vector v(n); 14 | for(auto &it : v) cin>>it; 15 | int K; 16 | cin>>K; //Careful : Don't confuse with 'K' and 'k' 17 | int cnt = 0; 18 | 19 | for(int i : v) //Counts the smallest elements less or equal to K 20 | if(i <= K) 21 | cnt++; 22 | 23 | int ans = INT_MAX; 24 | for(int k = 0; k < n-cnt+1; k++){ //Counts for every window the elements that are greater in it 25 | and that'll be ultimately equal to the no. of swaps required. 26 | int bad = 0; 27 | for(int i = k; i <= cnt+k-1; i++ ){ 28 | if(v[i] > K) 29 | bad++; 30 | } 31 | ans = min(ans, bad); 32 | } 33 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | vector v(n); 11 | for(auto &it : v) cin>>it; 12 | int i = 0, j = n-1, cnt = 0; 13 | while(i < j){ 14 | if(v[i] < v[j]){ 15 | i++; 16 | v[i] += v[i-1]; 17 | cnt++; 18 | } 19 | else if(v[i] > v[j]){ 20 | j--; 21 | v[j] += v[j+1]; 22 | cnt++; 23 | } 24 | else{ 25 | i++; 26 | j--; 27 | } 28 | } 29 | cout< 2 | using namespace std; 3 | 4 | //Approach 1 : Merge method of merge sort. We observe that since the size of the two arrays are same hence the merged array will always be of even length and 5 | // our median will be the average of elements at indexes n-1 and n. 6 | 7 | //Time Complexity : O(n) 8 | //Space Complexity : O(1) 9 | /* 10 | int main(){ 11 | int n; 12 | cin>>n; 13 | vector a1(n); 14 | for(auto &it : a1) cin>>it; 15 | vector a2(n); 16 | for(auto &it : a2) cin>>it; 17 | int cnt = 0, i = 0, j = 0, m1= -1, m2 = -1; 18 | while(cnt <= n){ 19 | if(i == n){ 20 | m1 = m2; 21 | m2= a2[0]; 22 | break; 23 | } 24 | if(j == n){ 25 | m1 = m2; 26 | m2 = a1[0]; 27 | break; 28 | } 29 | if(a1[i] <= a2[j]){ 30 | m1 = m2; //Stores the possible previous median 31 | m2 = a1[i]; 32 | i++; 33 | } 34 | else{ 35 | m1 = m2; //Stores the possible previous median 36 | m2 = a2[j]; 37 | j++; 38 | } 39 | cnt++; 40 | } 41 | cout<<(m1+m2)/2< array, int startIndex, int endIndex){ 51 | int indexDiff = (endIndex - startIndex); 52 | if (indexDiff % 2 == 0) 53 | { 54 | return array[startIndex + (indexDiff/2)]; 55 | } 56 | else 57 | { 58 | return (array[startIndex + (indexDiff/2)] + array[startIndex + (indexDiff/2) + 1])/2; 59 | } 60 | } 61 | 62 | int findMedianSortedArrays(vector a, vector b, int startIndexA, int endIndexA, int startIndexB, int endIndexB){ 63 | if(endIndexA- startIndexA == 0 || endIndexB-startIndexB == 0) 64 | return (a[0] + b[0]) /2; 65 | 66 | if(endIndexA-startIndexA == 1 && endIndexB-startIndexB == 1) 67 | return (max(a[startIndexA],b[startIndexB]) + min(a[endIndexA],b[endIndexB]))/2; 68 | 69 | int m1 = findMedian(a, startIndexA, endIndexA); 70 | int m2 = findMedian(b, startIndexB, endIndexB); 71 | 72 | if(m1 == m2) 73 | return m2; 74 | 75 | //since m1<=median<=m2 narrow down search by eliminating elements 76 | if(m1>n; 105 | vector a1(n); 106 | for(auto &it : a1) cin>>it; 107 | vector a2(n); 108 | for(auto &it : a2) cin>>it; 109 | int ans = findMedianSortedArrays(a1, a2, 0, n-1, 0, n-1); 110 | cout< 7 | using namespace std; 8 | 9 | /* This function returns median of ar1[] and ar2[]. 10 | Assumption in this function: 11 | Both ar1[] and ar2[] are sorted arrays */ 12 | int getMedian(int ar1[], int ar2[], int n, int m) 13 | { 14 | int i = 0; /* Current index of input array ar1[] */ 15 | int j = 0; /* Current index of input array ar2[] */ 16 | int count; 17 | int m1 = -1, m2 = -1; 18 | 19 | // Since there are (n+m) elements, 20 | // There are following two cases 21 | // if n+m is odd then the middle 22 | //index is median i.e. (m+n)/2 23 | if((m + n) % 2 == 1) 24 | { 25 | for (count = 0; count <= (n + m)/2; count++) 26 | { 27 | if(i != n && j != m) 28 | { 29 | m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; 30 | } 31 | else if(i < n) 32 | { 33 | m1 = ar1[i++]; 34 | } 35 | // for case when j ar2[j]) ? ar2[j++] : ar1[i++]; 55 | } 56 | else if(i < n) 57 | { 58 | m1 = ar1[i++]; 59 | } 60 | // for case when j 86 | using namespace std; 87 | 88 | // A utility function to find median of two integers 89 | float MO2(int a, int b) 90 | { return ( a + b ) / 2.0; } 91 | 92 | // A utility function to find median of three integers 93 | float MO3(int a, int b, int c) 94 | { 95 | return a + b + c - max(a, max(b, c)) 96 | - min(a, min(b, c)); 97 | } 98 | 99 | // A utility function to find a median of four integers 100 | float MO4(int a, int b, int c, int d) 101 | { 102 | int Max = max( a, max( b, max( c, d ) ) ); 103 | int Min = min( a, min( b, min( c, d ) ) ); 104 | return ( a + b + c + d - Max - Min ) / 2.0; 105 | } 106 | 107 | // Utility function to find median of single array 108 | float medianSingle(int arr[], int n) 109 | { 110 | if (n == 0) 111 | return -1; 112 | if (n%2 == 0) 113 | return (double)(arr[n/2] + arr[n/2-1])/2; 114 | return arr[n/2]; 115 | } 116 | 117 | // This function assumes that N is smaller than or equal to M 118 | // This function returns -1 if both arrays are empty 119 | float findMedianUtil( int A[], int N, int B[], int M ) 120 | { 121 | // If smaller array is empty, return median from second array 122 | if (N == 0) 123 | return medianSingle(B, M); 124 | 125 | // If the smaller array has only one element 126 | if (N == 1) 127 | { 128 | // Case 1: If the larger array also has one element, 129 | // simply call MO2() 130 | if (M == 1) 131 | return MO2(A[0], B[0]); 132 | 133 | // Case 2: If the larger array has odd number of elements, 134 | // then consider the middle 3 elements of larger array and 135 | // the only element of smaller array. Take few examples 136 | // like following 137 | // A = {9}, B[] = {5, 8, 10, 20, 30} and 138 | // A[] = {1}, B[] = {5, 8, 10, 20, 30} 139 | if (M & 1) 140 | return MO2( B[M/2], MO3(A[0], B[M/2 - 1], B[M/2 + 1]) ); 141 | 142 | // Case 3: If the larger array has even number of element, 143 | // then median will be one of the following 3 elements 144 | // ... The middle two elements of larger array 145 | // ... The only element of smaller array 146 | return MO3( B[M/2], B[M/2 - 1], A[0] ); 147 | } 148 | 149 | // If the smaller array has two elements 150 | else if (N == 2) 151 | { 152 | // Case 4: If the larger array also has two elements, 153 | // simply call MO4() 154 | if (M == 2) 155 | return MO4(A[0], A[1], B[0], B[1]); 156 | 157 | // Case 5: If the larger array has odd number of elements, 158 | // then median will be one of the following 3 elements 159 | // 1. Middle element of larger array 160 | // 2. Max of first element of smaller array and element 161 | // just before the middle in bigger array 162 | // 3. Min of second element of smaller array and element 163 | // just after the middle in bigger array 164 | if (M & 1) 165 | return MO3 ( B[M/2], 166 | max(A[0], B[M/2 - 1]), 167 | min(A[1], B[M/2 + 1]) 168 | ); 169 | 170 | // Case 6: If the larger array has even number of elements, 171 | // then median will be one of the following 4 elements 172 | // 1) & 2) The middle two elements of larger array 173 | // 3) Max of first element of smaller array and element 174 | // just before the first middle element in bigger array 175 | // 4. Min of second element of smaller array and element 176 | // just after the second middle in bigger array 177 | return MO4 ( B[M/2], 178 | B[M/2 - 1], 179 | max( A[0], B[M/2 - 2] ), 180 | min( A[1], B[M/2 + 1] ) 181 | ); 182 | } 183 | 184 | int idxA = ( N - 1 ) / 2; 185 | int idxB = ( M - 1 ) / 2; 186 | 187 | /* if A[idxA] <= B[idxB], then median must exist in 188 | A[idxA....] and B[....idxB] */ 189 | if (A[idxA] <= B[idxB] ) 190 | return findMedianUtil(A + idxA, N/2 + 1, B, M - idxA ); 191 | 192 | /* if A[idxA] > B[idxB], then median must exist in 193 | A[...idxA] and B[idxB....] */ 194 | return findMedianUtil(A, N/2 + 1, B + idxA, M - idxA ); 195 | } 196 | 197 | // A wrapper function around findMedianUtil(). This function 198 | // makes sure that smaller array is passed as first argument 199 | // to findMedianUtil 200 | float findMedian( int A[], int N, int B[], int M ) 201 | { 202 | if (N > M) 203 | return findMedianUtil( B, M, A, N ); 204 | 205 | return findMedianUtil( A, N, B, M ); 206 | } 207 | 208 | // Driver program to test above functions 209 | int main() 210 | { 211 | int A[] = {900}; 212 | int B[] = {5, 8, 10, 20}; 213 | 214 | int N = sizeof(A) / sizeof(A[0]); 215 | int M = sizeof(B) / sizeof(B[0]); 216 | 217 | printf("%f", findMedian( A, N, B, M ) ); 218 | return 0; 219 | } 220 | 221 | // Time Complexity: O(min(log m, log n)). 222 | // In each step one half of each array is discarded. So the algorithm takes O(min(log m, log n)) time to reach the median value. 223 | // Space Complexity: O(1). 224 | // No extra space is required. -------------------------------------------------------------------------------- /Arrays/37_Maximum Product Subarray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find Maximum Product Subarray 2 | #include 3 | using namespace std; 4 | 5 | /* Returns the product of max product subarray.*/ 6 | int maxSubarrayProduct(int arr[], int n) 7 | { 8 | // Initializing result 9 | int result = arr[0]; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | int mul = arr[i]; 14 | // traversing in current subarray 15 | for (int j = i + 1; j < n; j++) 16 | { 17 | // updating result every time 18 | // to keep an eye over the maximum product 19 | result = max(result, mul); 20 | mul *= arr[j]; 21 | } 22 | // updating the result for (n-1)th index. 23 | result = max(result, mul); 24 | } 25 | return result; 26 | } 27 | 28 | // Driver code 29 | int main() 30 | { 31 | int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | cout << "Maximum Sub array product is " 34 | << maxSubarrayProduct(arr, n); 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Arrays/3_KthSmallestElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //This code uses concept of quicksort. In this, rather than performing quicksort to the whole array we stop when our pivot becomes the kth smallest element. 5 | 6 | int partition(int arr[], int start,int end){ 7 | 8 | int n = end-start+1; //This 3 line code of generates a random pivot using rand() function 9 | int pivot = rand()%n; 10 | swap(arr[start+pivot], arr[end]); 11 | 12 | pivot = arr[end]; 13 | int pIndex = start; 14 | for(int i = start; i < end; i++){ 15 | if(arr[i] <= pivot){ 16 | swap(arr[i], arr[pIndex]); 17 | pIndex++; 18 | } 19 | } 20 | swap(arr[pIndex], arr[end]); 21 | return pIndex; 22 | } 23 | 24 | int kthsmallest(int arr[], int start, int end, int k){ 25 | int pIndex = partition(arr, start, end); 26 | if(pIndex - start == k-1) 27 | return arr[pIndex]; 28 | 29 | if(pIndex - start > k-1) 30 | return kthsmallest(arr, start, pIndex-1, k); 31 | 32 | return kthsmallest(arr, pIndex+1, end, k-pIndex+start-1); 33 | //while searching the kthsmallest in right half, the kthsmallest element becomes k-((pIndex+1)-start) 34 | } 35 | 36 | 37 | int main(){ 38 | int t; 39 | cin>>t; 40 | while(t--){ 41 | int n, k; 42 | cin>>n; 43 | int arr[n]; 44 | for(int i = 0; i < n; i++) 45 | cin>>arr[i]; 46 | cin>>k; 47 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | int arr[n]; 11 | for(int i = 0; i < n ; i++) 12 | cin>>arr[i]; 13 | //Dutch National Flag algorithm 14 | int low = 0, mid = 0, high = n-1; 15 | while(mid <= high){ 16 | switch(arr[mid]){ 17 | case 0 : swap(arr[low++], arr[mid++]); 18 | break; 19 | case 1 : mid++; 20 | break; 21 | case 2 : swap(arr[mid], arr[high--]); 22 | break; 23 | } 24 | } 25 | for(int i =0; i < n; i++) 26 | cout< 2 | using namespace std; 3 | 4 | int main(){ 5 | int n; 6 | cin>>n; 7 | int arr[n]; 8 | for(int i = 0; i< n; i++) 9 | cin>>arr[i]; 10 | int j = 0; 11 | for(int i = 0; i < n; i++){ //Similar to partition logic in quicksort where pivot is 0. 12 | if(arr[i] < 0){ 13 | swap(arr[j], arr[i]); 14 | j++; 15 | } 16 | } 17 | for(int i = 0; i < n; i++) 18 | cout< 2 | using namespace std; 3 | 4 | //Time Complexity : O(m + n) 5 | //Space Complexity : O(m + n) 6 | 7 | //Union of two array 8 | 9 | int main() { 10 | int t; 11 | cin>>t; 12 | while(t--){ 13 | int n, m; 14 | cin>>n>>m; 15 | int a[n], b[m]; 16 | for(int i = 0; i < n; i++) 17 | cin>>a[i]; 18 | for(int i = 0; i < m; i++) 19 | cin>>b[i]; 20 | int i = 0, j = 0; 21 | while(i>t; 48 | while(t--){ 49 | int n, m; 50 | cin>>n>>m; 51 | int a[n], b[m]; 52 | for(int i = 0; i < n; i++) 53 | cin>>a[i]; 54 | for(int i = 0; i < m; i++) 55 | cin>>b[i]; 56 | int i = 0, j = 0; 57 | while(i 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n; 9 | cin>>n; 10 | vector arr(n); 11 | for(auto &it : arr) cin>>it; 12 | int temp = arr[n-1]; 13 | for(int i = n-1; i > 0; i--){ 14 | arr[i] = arr[i-1]; 15 | } 16 | arr[0] = temp; 17 | for(int i : arr) 18 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--){ 8 | int n ; 9 | cin>>n; 10 | vectora(n); 11 | for(auto &it : a) cin>>it; 12 | int pref = 0; 13 | int max_sum = INT_MIN; 14 | for(int i = 0; i < n ; i++){ 15 | pref += a[i]; 16 | max_sum = max(max_sum, pref); 17 | if(pref<0) 18 | pref = 0; 19 | } 20 | cout< big) 14 | swap(small, big); 15 | 16 | for(int i = 1; i < n-1; i+){ 17 | int subtract = arr[i]-k; 18 | int add= arr[i]+k; 19 | if(subtract >= small or add <= big) 20 | continue; 21 | if(big - subtract <= add-small) 22 | small = subtract; 23 | else 24 | big = add; 25 | } 26 | return min(ans, big-small); 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Backtracking/1_RatInAMazeBacktracking.cpp: -------------------------------------------------------------------------------- 1 | /* refer : https://www.youtube.com/watch?v=4BBB0mvvbGA&list=PLfqMhTWNBTe0b2nM6JHVCnAkhQRGiZMSJ&index=43 2 | 3 | Approach : Backtracking 4 | 5 | We pass x and y which is the position of the rat to the ratinMaze() function. The function then 6 | check for every path as in recursion but it "backtracks" as soon as it fails to find a path. 7 | 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | bool isSafe(vector> &mat, int x, int y, int n){ 14 | if(x < n && y < n && mat[x][y] == 1) 15 | return true; 16 | return false; 17 | } 18 | 19 | bool ratinMaze(vector>& mat, int x, int y, vector> &solMat, int n){ 20 | if(x == n-1 && y == n-1){ 21 | solMat[x][y] = 1; 22 | return true; 23 | } 24 | if(isSafe(mat, x, y, n)){ 25 | solMat[x][y] = 1; 26 | if(ratinMaze(mat, x+1, y, solMat, n)){ 27 | return true; 28 | } 29 | if(ratinMaze(mat, x, y+1, solMat, n)){ 30 | return true; 31 | } 32 | solMat[x][y] = 0; // backtracking 33 | return false; 34 | } 35 | return false; 36 | 37 | } 38 | 39 | int main(){ 40 | int n; 41 | cin>>n; 42 | vector> mat(n, vector(n,0)); 43 | vector> solMat(n, vector(n,0)); 44 | 45 | for(int i = 0; i < n; i++){ 46 | for(int j = 0; j < n; j++){ 47 | cin>>mat[i][j]; 48 | } 49 | } 50 | 51 | if(ratinMaze(mat, 0, 0, solMat, n)){ 52 | cout<<"Path available"<= n. We print the solution grid and return. 7 | 8 | Time Complexity : O(2^n) 9 | Space Complexity : O(2^n) 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | void printSol(vector> &mat, int n){ 16 | for(int i = 0; i < n; i++){ 17 | for(int j = 0; j < n; j++){ 18 | cout<> &mat, int x, int y, int n){ 26 | for(int i = 0; i < x; i++){ //check if the column above has a Queen already placed. 27 | if(mat[i][y] == 1) 28 | return false; 29 | } 30 | 31 | int row = x; 32 | int col = y; 33 | while(row >= 0 && col >= 0){ 34 | if(mat[row][col] == 1){ //check if their exists any Queen in the left diagonal 35 | return false; 36 | } 37 | row--; 38 | col--; 39 | } 40 | row = x; 41 | col = y; 42 | while(row >=0 && col < n){ //check if their exists any Queen in the right diagonal 43 | if(mat[row][col] == 1){ 44 | return false; 45 | } 46 | row--; 47 | col++; 48 | } 49 | return true; 50 | } 51 | 52 | bool nQueen(vector> &mat, int x, int n){ 53 | if(x >= n){ //placed all the n queens 54 | printSol(mat, n); 55 | return true; 56 | } 57 | for(int col = 0; col < n; col++){ 58 | if(isSafe(mat, x, col, n)){ 59 | mat[x][col] = 1; 60 | nQueen(mat, x+1, n); //printing all possible solutions 61 | mat[x][col] = 0; // backtracking 62 | } 63 | } 64 | return false; 65 | } 66 | 67 | int main(){ 68 | int n; 69 | cout<<"Enter size"<>n; 71 | vector> mat(n,vector(n,0)); 72 | nQueen(mat, 0, n); 73 | return 0; 74 | } 75 | 76 | 77 | -------------------------------------------------------------------------------- /Backtracking/3_ColoringProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | bool isSafe(int node, int color[], bool graph[101][101], int n, int col) { 5 | for (int k = 0; k < n; k++) { 6 | if (k != node && graph[k][node] == 1 && color[k] == col) { 7 | return false; 8 | } 9 | } 10 | return true; 11 | } 12 | bool solve(int node, int color[], int m, int N, bool graph[101][101]) { 13 | if (node == N) { 14 | return true; 15 | } 16 | 17 | for (int i = 1; i <= m; i++) { 18 | if (isSafe(node, color, graph, N, i)) { 19 | color[node] = i; 20 | if (solve(node + 1, color, m, N, graph)) return true; 21 | color[node] = 0; 22 | } 23 | 24 | } 25 | return false; 26 | } 27 | 28 | //Function to determine if graph can be coloured with at most M colours such 29 | //that no two adjacent vertices of graph are coloured with same colour. 30 | bool graphColoring(bool graph[101][101], int m, int N) { 31 | int color[N] = { 32 | 0 33 | }; 34 | if (solve(0, color, m, N, graph)) return true; 35 | return false; 36 | } 37 | 38 | int main() { 39 | int N = 4; 40 | int m = 3; 41 | 42 | bool graph[101][101]; 43 | memset(graph, false, sizeof graph); 44 | 45 | // Edges are (0, 1), (1, 2), (2, 3), (3, 0), (0, 2) 46 | graph[0][1] = 1; graph[1][0] = 1; 47 | graph[1][2] = 1; graph[2][1] = 1; 48 | graph[2][3] = 1; graph[3][2] = 1; 49 | graph[3][0] = 1; graph[0][3] = 1; 50 | graph[0][2] = 1; graph[2][0] = 1; 51 | 52 | cout << graphColoring(graph, m, N); 53 | 54 | } 55 | -------------------------------------------------------------------------------- /Backtracking/5_SudokuSolver: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool check(vector> &board, int i, int j, char val) { 3 | int row = i - i % 3, column = j - j % 3; 4 | for (int x = 0; x < 9; x++) if (board[x][j] == val) return false; 5 | for (int y = 0; y < 9; y++) if (board[i][y] == val) return false; 6 | for (int x = 0; x < 3; x++) 7 | for (int y = 0; y < 3; y++) 8 | if (board[row + x][column + y] == val) return false; 9 | return true; 10 | } 11 | 12 | bool solveSudoku(vector> &board, int i, int j) { 13 | if (i == 9) return true; 14 | if (j == 9) return solveSudoku(board, i + 1, 0); 15 | if (board[i][j] != '.') return solveSudoku(board, i, j + 1); 16 | 17 | for (char c = '1'; c <= '9'; c++) { 18 | if (check(board, i, j, c)) { 19 | board[i][j] = c; 20 | if (solveSudoku(board, i, j + 1)) return true; 21 | board[i][j] = '.'; 22 | } 23 | } 24 | return false; 25 | } 26 | 27 | public: 28 | void solveSudoku(vector>& board) { 29 | solveSudoku(board, 0, 0); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Binary Tree/10_RightViewofbinaryTree: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | class Node{ 7 | public: 8 | int data; 9 | Node * left; 10 | Node * right; 11 | }; 12 | 13 | 14 | 15 | // create Node 16 | Node* createNode(int val){ 17 | Node * temp = new Node; 18 | if(!temp){ 19 | cout<<"Error\n"; 20 | return NULL; 21 | } 22 | temp->data = val; 23 | temp->left = NULL; 24 | temp->right = NULL; 25 | return temp; 26 | } 27 | 28 | // build the tree from array 29 | Node * buildtree(vector&arr){ 30 | if(arr.empty()){ 31 | return NULL; 32 | } 33 | Node * root = createNode(arr[0]); 34 | queueq; 35 | q.push(root); 36 | int i = 1; 37 | while(!q.empty() && i < arr.size()){ 38 | Node * temp = q.front(); 39 | q.pop(); 40 | int val = arr[i]; 41 | if(val != 0){ 42 | temp->left = createNode(val); 43 | q.push(temp->left); 44 | } 45 | i++; 46 | if(i>=arr.size()){ 47 | break; 48 | } 49 | val = arr[i]; 50 | if(val != 0){ 51 | temp->right = createNode(val); 52 | q.push(temp->right); 53 | } 54 | i++; 55 | } 56 | return root; 57 | } 58 | 59 | 60 | 61 | vectorans; 62 | void helper(Node * root,int & prev ,int curr){ 63 | if(root == NULL){ 64 | return; 65 | } 66 | if(prev < curr){ 67 | prev = curr; 68 | ans.push_back(root->data); 69 | } 70 | helper(root->right,prev,curr+1); 71 | helper(root->left,prev,curr+1); 72 | return ; 73 | 74 | } 75 | 76 | 77 | void rightSideView(Node* root) { 78 | int prev = 0; 79 | int curr = 1; 80 | helper(root,prev,curr); 81 | for(auto x : ans){ 82 | cout<>testcase; 91 | while(testcase--){ 92 | int size ; 93 | cin>>size; 94 | vectorarr; 95 | for(int i = 0;i>val; 98 | arr.push_back(val); 99 | } 100 | Node * root = buildtree(arr); 101 | rightSideView(root); 102 | } 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Binary Tree/12_BottomViewOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | #define MAX_HEIGHT 100000 5 | 6 | // Tree Node 7 | struct Node 8 | { 9 | int data; 10 | Node* left; 11 | Node* right; 12 | }; 13 | 14 | // Utility function to create a new Tree Node 15 | Node* newNode(int val) 16 | { 17 | Node* temp = new Node; 18 | temp->data = val; 19 | temp->left = NULL; 20 | temp->right = NULL; 21 | 22 | return temp; 23 | } 24 | 25 | 26 | vector bottomView(Node *root); 27 | 28 | // Function to Build Tree 29 | Node* buildTree(string str) 30 | { 31 | // Corner Case 32 | if(str.length() == 0 || str[0] == 'N') 33 | return NULL; 34 | 35 | // Creating vector of strings from input 36 | // string after spliting by space 37 | vector ip; 38 | 39 | istringstream iss(str); 40 | for(string str; iss >> str; ) 41 | ip.push_back(str); 42 | 43 | // Create the root of the tree 44 | Node* root = newNode(stoi(ip[0])); 45 | 46 | // Push the root to the queue 47 | queue queue; 48 | queue.push(root); 49 | 50 | // Starting from the second element 51 | int i = 1; 52 | while(!queue.empty() && i < ip.size()) { 53 | 54 | // Get and remove the front of the queue 55 | Node* currNode = queue.front(); 56 | queue.pop(); 57 | 58 | // Get the current node's value from the string 59 | string currVal = ip[i]; 60 | 61 | // If the left child is not null 62 | if(currVal != "N") { 63 | 64 | // Create the left child for the current node 65 | currNode->left = newNode(stoi(currVal)); 66 | 67 | // Push it to the queue 68 | queue.push(currNode->left); 69 | } 70 | 71 | // For the right child 72 | i++; 73 | if(i >= ip.size()) 74 | break; 75 | currVal = ip[i]; 76 | 77 | // If the right child is not null 78 | if(currVal != "N") { 79 | 80 | // Create the right child for the current node 81 | currNode->right = newNode(stoi(currVal)); 82 | 83 | // Push it to the queue 84 | queue.push(currNode->right); 85 | } 86 | i++; 87 | } 88 | 89 | return root; 90 | } 91 | 92 | 93 | 94 | //Function to return a list containing the bottom view of the given tree. 95 | 96 | class Solution { 97 | public: 98 | vector bottomView(Node *root) { 99 | // Your Code Here 100 | map topNodes; 101 | queue > q; 102 | vector ans; 103 | 104 | if(root == NULL) 105 | return ans; 106 | 107 | q.push(make_pair(root, 0)); 108 | 109 | while(!q.empty()){ 110 | pair temp = q.front(); 111 | q.pop(); 112 | 113 | Node* frontNode = temp.first; 114 | int hd = temp.second; 115 | 116 | topNodes[hd] = frontNode->data; 117 | 118 | if(frontNode->left) 119 | q.push(make_pair(frontNode->left, hd-1)); 120 | 121 | if(frontNode->right) 122 | q.push(make_pair(frontNode->right, hd+1)); 123 | 124 | } 125 | for(auto i : topNodes){ 126 | ans.push_back(i.second); 127 | } 128 | return ans; 129 | } 130 | }; 131 | 132 | int main() { 133 | int t; 134 | string tc; 135 | getline(cin, tc); 136 | t=stoi(tc); 137 | while(t--) 138 | { 139 | string s ,ch; 140 | getline(cin, s); 141 | Node* root = buildTree(s); 142 | Solution ob; 143 | vector res = ob.bottomView(root); 144 | for (int i : res) cout << i << " "; 145 | cout << endl; 146 | } 147 | return 0; 148 | } 149 | -------------------------------------------------------------------------------- /Binary Tree/14_CheckForBalancedTree.cpp: -------------------------------------------------------------------------------- 1 | // Solution to check for balanced tree on GFG 2 | // Solution Author : Vishvesh Trivedi (@NerdyVisky) 3 | // Problem link : https://practice.geeksforgeeks.org/problems/check-for-balanced-tree/1 4 | 5 | // { Driver Code Starts 6 | // Initial Template for C++ 7 | #include 8 | using namespace std; 9 | // Tree Node 10 | struct Node 11 | { 12 | int data; 13 | Node *left; 14 | Node *right; 15 | }; 16 | 17 | // Utility function to create a new Tree Node 18 | Node *newNode(int val) 19 | { 20 | Node *temp = new Node; 21 | temp->data = val; 22 | temp->left = NULL; 23 | temp->right = NULL; 24 | 25 | return temp; 26 | } 27 | 28 | // Function to Build Tree 29 | Node *buildTree(string str) 30 | { 31 | // Corner Case 32 | if (str.length() == 0 || str[0] == 'N') 33 | return NULL; 34 | 35 | // Creating vector of strings from input 36 | // string after spliting by space 37 | vector ip; 38 | 39 | istringstream iss(str); 40 | for (string str; iss >> str;) 41 | ip.push_back(str); 42 | 43 | // Create the root of the tree 44 | Node *root = newNode(stoi(ip[0])); 45 | 46 | // Push the root to the queue 47 | queue queue; 48 | queue.push(root); 49 | 50 | // Starting from the second element 51 | int i = 1; 52 | while (!queue.empty() && i < ip.size()) 53 | { 54 | 55 | // Get and remove the front of the queue 56 | Node *currNode = queue.front(); 57 | queue.pop(); 58 | 59 | // Get the current node's value from the string 60 | string currVal = ip[i]; 61 | 62 | // If the left child is not null 63 | if (currVal != "N") 64 | { 65 | 66 | // Create the left child for the current node 67 | currNode->left = newNode(stoi(currVal)); 68 | 69 | // Push it to the queue 70 | queue.push(currNode->left); 71 | } 72 | 73 | // For the right child 74 | i++; 75 | if (i >= ip.size()) 76 | break; 77 | currVal = ip[i]; 78 | 79 | // If the right child is not null 80 | if (currVal != "N") 81 | { 82 | 83 | // Create the right child for the current node 84 | currNode->right = newNode(stoi(currVal)); 85 | 86 | // Push it to the queue 87 | queue.push(currNode->right); 88 | } 89 | i++; 90 | } 91 | 92 | return root; 93 | } 94 | // } Driver Code Ends 95 | /* A binary tree node structure 96 | 97 | struct Node 98 | { 99 | int data; 100 | struct Node* left; 101 | struct Node* right; 102 | 103 | Node(int x){ 104 | data = x; 105 | left = right = NULL; 106 | } 107 | }; 108 | */ 109 | 110 | class Solution 111 | { 112 | public: 113 | int checkBalance(Node *root) 114 | { 115 | if (root == NULL) 116 | { 117 | return 0; 118 | } 119 | int lh = checkBalance(root->left); 120 | if (lh == -1) 121 | { 122 | return -1; 123 | } 124 | int rh = checkBalance(root->right); 125 | if (rh == -1) 126 | { 127 | return -1; 128 | } 129 | if (lh - rh > 1 || lh - rh < -1) 130 | { 131 | return -1; 132 | } 133 | return (max(lh, rh) + 1); 134 | } 135 | // Function to check whether a binary tree is balanced or not. 136 | bool isBalanced(Node *root) 137 | { 138 | return checkBalance(root) == -1 ? 0 : 1; 139 | } 140 | }; 141 | 142 | // { Driver Code Starts. 143 | 144 | /* Driver program to test size function*/ 145 | 146 | int main() 147 | { 148 | 149 | int t; 150 | scanf("%d ", &t); 151 | while (t--) 152 | { 153 | string s, ch; 154 | getline(cin, s); 155 | 156 | Node *root = buildTree(s); 157 | Solution ob; 158 | cout << ob.isBalanced(root) << endl; 159 | } 160 | return 0; 161 | } 162 | // } Driver Code Ends -------------------------------------------------------------------------------- /Binary Tree/3_HeightOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Solution to the Height of Binary Tree on GFG 2 | // Solution Author : Vishvesh Trivedi (@NerdyVisky) 3 | // Problem Link : https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1 4 | 5 | // { Driver Code Starts 6 | // Initial template for C++ 7 | 8 | #include 9 | using namespace std; 10 | 11 | struct Node 12 | { 13 | int data; 14 | struct Node *left; 15 | struct Node *right; 16 | 17 | Node(int val) 18 | { 19 | data = val; 20 | left = right = NULL; 21 | } 22 | }; 23 | 24 | // Function to Build Tree 25 | Node *buildTree(string str) 26 | { 27 | // Corner Case 28 | if (str.length() == 0 || str[0] == 'N') 29 | return NULL; 30 | 31 | // Creating vector of strings from input 32 | // string after spliting by space 33 | vector ip; 34 | 35 | istringstream iss(str); 36 | for (string str; iss >> str;) 37 | ip.push_back(str); 38 | 39 | // Create the root of the tree 40 | Node *root = new Node(stoi(ip[0])); 41 | 42 | // Push the root to the queue 43 | queue queue; 44 | queue.push(root); 45 | 46 | // Starting from the second element 47 | int i = 1; 48 | while (!queue.empty() && i < ip.size()) 49 | { 50 | 51 | // Get and remove the front of the queue 52 | Node *currNode = queue.front(); 53 | queue.pop(); 54 | 55 | // Get the current node's value from the string 56 | string currVal = ip[i]; 57 | 58 | // If the left child is not null 59 | if (currVal != "N") 60 | { 61 | 62 | // Create the left child for the current Node 63 | currNode->left = new Node(stoi(currVal)); 64 | 65 | // Push it to the queue 66 | queue.push(currNode->left); 67 | } 68 | 69 | // For the right child 70 | i++; 71 | if (i >= ip.size()) 72 | break; 73 | currVal = ip[i]; 74 | 75 | // If the right child is not null 76 | if (currVal != "N") 77 | { 78 | 79 | // Create the right child for the current node 80 | currNode->right = new Node(stoi(currVal)); 81 | 82 | // Push it to the queue 83 | queue.push(currNode->right); 84 | } 85 | i++; 86 | } 87 | 88 | return root; 89 | } 90 | 91 | // } Driver Code Ends 92 | // User function template for C++ 93 | 94 | /* 95 | struct Node 96 | { 97 | int data; 98 | struct Node* left; 99 | struct Node* right; 100 | 101 | Node(int x){ 102 | data = x; 103 | left = right = NULL; 104 | } 105 | }; 106 | */ 107 | class Solution 108 | { 109 | public: 110 | // Function to find the height of a binary tree. 111 | int height(struct Node *root) 112 | { 113 | if (root == NULL) 114 | { 115 | return 0; 116 | } 117 | return (max(height(root->left), height(root->right))) + 1; 118 | } 119 | }; 120 | 121 | // { Driver Code Starts. 122 | int main() 123 | { 124 | int t; 125 | scanf("%d ", &t); 126 | while (t--) 127 | { 128 | string treeString; 129 | getline(cin, treeString); 130 | Node *root = buildTree(treeString); 131 | Solution ob; 132 | cout << ob.height(root) << endl; 133 | } 134 | return 0; 135 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Binary Tree/4_DiameterOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | // Solution for finding the diameter of a binary tree on GFG 2 | // Solution Author : Vishvesh Trivedi (@NerdyVisky) 3 | // Problem link : https://practice.geeksforgeeks.org/problems/diameter-of-binary-tree/1 4 | 5 | #include 6 | using namespace std; 7 | 8 | struct Node 9 | { 10 | int data; 11 | struct Node *left; 12 | struct Node *right; 13 | }; 14 | Node *newNode(int val) 15 | { 16 | Node *temp = new Node; 17 | temp->data = val; 18 | temp->left = NULL; 19 | temp->right = NULL; 20 | return temp; 21 | } 22 | 23 | Node *buildTree(string str) 24 | { 25 | if (str.length() == 0 || str[0] == 'N') 26 | return NULL; 27 | vector ip; 28 | 29 | istringstream iss(str); 30 | for (string str; iss >> str;) 31 | ip.push_back(str); 32 | Node *root = newNode(stoi(ip[0])); 33 | queue queue; 34 | queue.push(root); 35 | 36 | int i = 1; 37 | while (!queue.empty() && i < ip.size()) 38 | { 39 | 40 | Node *currNode = queue.front(); 41 | queue.pop(); 42 | string currVal = ip[i]; 43 | if (currVal != "N") 44 | { 45 | currNode->left = newNode(stoi(currVal)); 46 | queue.push(currNode->left); 47 | } 48 | 49 | i++; 50 | if (i >= ip.size()) 51 | break; 52 | currVal = ip[i]; 53 | 54 | // If the right child is not null 55 | if (currVal != "N") 56 | { 57 | 58 | // Create the right child for the current node 59 | currNode->right = newNode(stoi(currVal)); 60 | 61 | // Push it to the queue 62 | queue.push(currNode->right); 63 | } 64 | i++; 65 | } 66 | 67 | return root; 68 | } 69 | 70 | class Solution 71 | { 72 | public: 73 | // Function to return the diameter of a Binary Tree. 74 | int height(Node *root) 75 | { 76 | if (root == NULL) 77 | { 78 | return 0; 79 | } 80 | else 81 | { 82 | return (max(height(root->left), height(root->right))) + 1; 83 | } 84 | } 85 | int diameter(Node *root) 86 | { 87 | if (root == NULL) 88 | { 89 | return 0; 90 | } 91 | int dia_root = 1 + height(root->left) + height(root->right); 92 | int dia_left = diameter(root->left); 93 | int dia_right = diameter(root->right); 94 | return (max(dia_root, max(dia_left, dia_right))); 95 | } 96 | }; 97 | 98 | int main() 99 | { 100 | int t; 101 | scanf("%d\n", &t); 102 | while (t--) 103 | { 104 | string s; 105 | getline(cin, s); 106 | Node *root = buildTree(s); 107 | Solution ob; 108 | cout << ob.diameter(root) << endl; 109 | } 110 | return 0; 111 | } -------------------------------------------------------------------------------- /Binary Tree/Leetcode_145_PostOrderTraversalRecursiveAndIterative.cpp: -------------------------------------------------------------------------------- 1 | Approach #1: Recursive Method 2 | 3 | The recursive Approach is the straight forward and classical approach. 4 | 5 | If the current node is not empty : 6 | 1. Traverse the left subtree 7 | 2. Traverse the right subtree 8 | 3. Print the node 9 | 10 | class Solution { 11 | public: 12 | vector postorderTraversal(TreeNode* root) { 13 | vector nodes; 14 | postorder(root, nodes); 15 | return nodes; 16 | } 17 | private: 18 | void postorder(TreeNode* root, vector& nodes) { 19 | if (!root) { 20 | return; 21 | } 22 | postorder(root -> left, nodes); 23 | postorder(root -> right, nodes); 24 | nodes.push_back(root -> val); 25 | } 26 | }; 27 | 28 | 29 | Approach #2: Iterative Method. 30 | 31 | The key to the solution lies in: 32 | 33 | Use root to denote the current node under process; 34 | Use stack to save nodes; 35 | A node is added to the result list before pushing into the stack(DRL). 36 | 37 | class Solution { 38 | public: 39 | vector postorderTraversal(TreeNode* root) { 40 | vector ans; 41 | stack stk; 42 | //Postorder(LRD) --> Reverse(DRL) --> DRL is similar to Preorder(DLR) 43 | while(root or !stk.empty()){ 44 | while(root){ 45 | ans.push_back(root->val); 46 | stk.push(root); 47 | root=root->right; 48 | } 49 | root= stk.top(); 50 | stk.pop(); 51 | root=root->left; 52 | } 53 | //Reverse(DRL) 54 | reverse(ans.begin(),ans.end()); 55 | return ans; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Graphs/13_ImplementTopologicalSort.cpp: -------------------------------------------------------------------------------- 1 | /* Approach : DFS 2 | refer : https://cp-algorithms.com/graph/topological-sort.html 3 | 4 | Time Complexity : O(V + E) 5 | Space Complexity : O(V) 6 | 7 | */ 8 | 9 | vector res; 10 | vector visited; 11 | 12 | void dfs(vector adj[], int i){ 13 | if(visited[i]) return; 14 | visited[i] = true; 15 | for(int u : adj[i]){ 16 | if(!visited[u]) 17 | dfs(adj,u); 18 | } 19 | res.push_back(i); 20 | } 21 | 22 | vector topoSort(int V, vector adj[]) { 23 | // Your code here 24 | visited.assign(V,false); 25 | res.clear(); 26 | for(int i=0;i < V; i++){ 27 | if(!visited[i]) 28 | dfs(adj,i); 29 | } 30 | reverse(res.begin(),res.end()); 31 | return res; 32 | } 33 | 34 | /* Approach : Kahn's Algorithm : There is atleast a vertex with indegree 0 in the graph. Push the vertex 35 | with indegree 0 to the queue and remove the outgoing edges from that 36 | vertex. In doing so subtract the indegree of the child vertex and if 37 | its indegree becomes zero push it into the queue. Store all the 38 | vertex with indegree 0 to your res vector which will be your answer. 39 | 40 | refer : https://www.youtube.com/watch?v=bS62tit40m8&list=PL2q4fbVm1Ik6DCzm9XZJbNwyHtHGclcEh&index=30 41 | 42 | Time Complexity: O(V + E) 43 | Space Complexity : O(V) 44 | 45 | */ 46 | 47 | int in[10001]; 48 | vector res; 49 | 50 | void kahn(int n, vector adj[]){ 51 | queue q; 52 | 53 | for(int i = 0; i < n; i++){ 54 | if(in[i] == 0) 55 | q.push(i); 56 | } 57 | 58 | while(!q.empty()){ 59 | int v = q.front(); 60 | q.pop(); 61 | res.push_back(v); 62 | for(int u: adj[v]){ 63 | in[u]--; 64 | if(in[u] == 0) 65 | q.push(u); 66 | } 67 | } 68 | } 69 | 70 | vector topoSort(int V, vector adj[]) { 71 | // code here 72 | 73 | 74 | for(int i = 0; i < V; i++){ 75 | for(int j = 0; j < adj[i].size(); j++){ 76 | in[adj[i][j]]++; 77 | } 78 | } 79 | 80 | kahn(V, adj); 81 | 82 | return res; 83 | } 84 | -------------------------------------------------------------------------------- /Graphs/22_ImplementFloydWarshallAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | // ------Problem statement------ 2 | // The problem is to find the shortest distances between every pair of vertices in a given edge-weighted directed Graph. 3 | // The Graph is represented as an adjacency matrix, and the matrix denotes the weight of the edges (if it exists) else -1. 4 | // Do it in-place. 5 | 6 | // Constraints: 7 | // 1 <= n <= 100 8 | 9 | // Time Complexity: O(n3) 10 | // Space Complexity: O(1) 11 | 12 | 13 | 14 | 15 | 16 | // -------Solution------- 17 | // C++ Program for Floyd Warshall Algorithm 18 | #include 19 | using namespace std; 20 | 21 | // Number of vertices in the graph 22 | #define V 4 23 | 24 | /* Define Infinite as a large enough value.This value will be used for vertices not connected to each other */ 25 | #define INF 99999 26 | 27 | // A function to print the solution matrix 28 | void printSolution(int dist[][V]); 29 | 30 | // Solves the all-pairs shortest path 31 | // problem using Floyd Warshall algorithm 32 | void floydWarshall(int graph[][V]) 33 | { 34 | /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ 35 | 36 | int dist[V][V], i, j, k; 37 | 38 | /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances 39 | are based on shortest paths considering no intermediate vertex. */ 40 | 41 | for (i = 0; i < V; i++) 42 | for (j = 0; j < V; j++) 43 | dist[i][j] = graph[i][j]; 44 | 45 | /* Add all vertices one by one to the set of intermediate vertices. 46 | ---> Before start of an iteration, 47 | we have shortest distances between all pairs of vertices such that the shortest distances consider only the 48 | vertices in set {0, 1, 2, .. k-1} as intermediate vertices. 49 | ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set 50 | becomes {0, 1, 2, .. k} */ 51 | 52 | for (k = 0; k < V; k++) { 53 | // Pick all vertices as source one by one 54 | for (i = 0; i < V; i++) { 55 | // Pick all vertices as destination for the 56 | // above picked source 57 | for (j = 0; j < V; j++) { 58 | // If vertex k is on the shortest path from 59 | // i to j, then update the value of 60 | // dist[i][j] 61 | if (dist[i][j] > (dist[i][k] + dist[k][j]) 62 | && (dist[k][j] != INF 63 | && dist[i][k] != INF)) 64 | dist[i][j] = dist[i][k] + dist[k][j]; 65 | } 66 | } 67 | } 68 | 69 | // Print the shortest distance matrix 70 | printSolution(dist); 71 | } 72 | 73 | /* A utility function to print solution */ 74 | void printSolution(int dist[][V]) 75 | { 76 | cout << "The following matrix shows the shortest " 77 | "distances" 78 | " between every pair of vertices \n"; 79 | for (int i = 0; i < V; i++) { 80 | for (int j = 0; j < V; j++) { 81 | if (dist[i][j] == INF) 82 | cout << "INF" 83 | << " "; 84 | else 85 | cout << dist[i][j] << " "; 86 | } 87 | cout << endl; 88 | } 89 | } 90 | 91 | int main() 92 | { 93 | int graph[V][V] = { { 0, 5, INF, 10 }, 94 | { INF, 0, 3, INF }, 95 | { INF, INF, 0, 1 }, 96 | { INF, INF, INF, 0 } }; 97 | floydWarshall(graph); 98 | return 0; 99 | } -------------------------------------------------------------------------------- /Graphs/25_SnakeandLadderProblem.cpp: -------------------------------------------------------------------------------- 1 | // ------Problem statement------ 2 | // Given a 5x6 snakes and ladders board, find the minimum number of dice throws required to reach the destination or last cell 3 | // (30th cell) from the source (1st cell). 4 | // You are given an integer N denoting the total number of snakes and ladders and an array arr[] of 2*N size where 2*i and 5 | // (2*i + 1)th values denote the starting and ending point respectively of ith snake or ladder. The board looks like the following. 6 | // Note: Assume that you have complete control over the 6 sided dice. 7 | 8 | // Constraints: 9 | // 1 ≤ N ≤ 10 10 | // 1 ≤ arr[i] ≤ 30 11 | 12 | // Time Compelxity: O(n) 13 | // Space Complexity: O(n) 14 | 15 | 16 | 17 | 18 | 19 | // -------Solution------- 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | // An entry in queue used in BFS 25 | struct queueEntry { 26 | int v; // Vertex number 27 | int dist; // Distance of this vertex from source 28 | }; 29 | 30 | // This function returns minimum number of dice throws 31 | // required to Reach last cell from 0'th cell in a snake and 32 | // ladder game. move[] is an array of size N where N is no. 33 | // of cells on board If there is no snake or ladder from 34 | // cell i, then move[i] is -1 Otherwise move[i] contains 35 | // cell to which snake or ladder at i takes to. 36 | int getMinDiceThrows(int move[], int N) 37 | { 38 | // The graph has N vertices. Mark all the vertices as 39 | // not visited 40 | bool* visited = new bool[N]; 41 | for (int i = 0; i < N; i++) 42 | visited[i] = false; 43 | 44 | // Create a queue for BFS 45 | queue q; 46 | 47 | // Mark the node 0 as visited and enqueue it. 48 | visited[0] = true; 49 | queueEntry s 50 | = { 0, 0 }; // distance of 0't vertex is also 0 51 | q.push(s); // Enqueue 0'th vertex 52 | 53 | // Do a BFS starting from vertex at index 0 54 | queueEntry qe; // A queue entry (qe) 55 | while (!q.empty()) { 56 | qe = q.front(); 57 | int v = qe.v; // vertex no. of queue entry 58 | 59 | // If front vertex is the destination vertex, 60 | // we are done 61 | if (v == N - 1) 62 | break; 63 | 64 | // Otherwise dequeue the front vertex and enqueue 65 | // its adjacent vertices (or cell numbers reachable 66 | // through a dice throw) 67 | q.pop(); 68 | for (int j = v + 1; j <= (v + 6) && j < N; ++j) { 69 | // If this cell is already visited, then ignore 70 | if (!visited[j]) { 71 | // Otherwise calculate its distance and mark 72 | // it as visited 73 | queueEntry a; 74 | a.dist = (qe.dist + 1); 75 | visited[j] = true; 76 | 77 | // Check if there a snake or ladder at 'j' 78 | // then tail of snake or top of ladder 79 | // become the adjacent of 'i' 80 | if (move[j] != -1) 81 | a.v = move[j]; 82 | else 83 | a.v = j; 84 | q.push(a); 85 | } 86 | } 87 | } 88 | 89 | // We reach here when 'qe' has last vertex 90 | // return the distance of vertex in 'qe' 91 | return qe.dist; 92 | } 93 | 94 | // Driver program to test methods of graph class 95 | int main() 96 | { 97 | // Let us construct the board given in above diagram 98 | int N = 30; 99 | int moves[N]; 100 | for (int i = 0; i < N; i++) 101 | moves[i] = -1; 102 | 103 | // Ladders 104 | moves[2] = 21; 105 | moves[4] = 7; 106 | moves[10] = 25; 107 | moves[19] = 28; 108 | 109 | // Snakes 110 | moves[26] = 0; 111 | moves[20] = 8; 112 | moves[16] = 3; 113 | moves[18] = 6; 114 | 115 | cout << "Min Dice throws required is " 116 | << getMinDiceThrows(moves, N); 117 | return 0; 118 | } -------------------------------------------------------------------------------- /Graphs/27_StronglyConnectedComponents(Kosaraju'sAlgo).cpp: -------------------------------------------------------------------------------- 1 | // ------Problem statement------ 2 | // Given a Directed Graph with V vertices (Numbered from 0 to V-1) and E edges, Find the number of strongly connected 3 | // components in the graph. 4 | 5 | // Constraints: 6 | // 1 ≤ V ≤ 5000 7 | // 0 ≤ E ≤ (V*(V-1)) 8 | // 0 ≤ u, v ≤ N-1 9 | // Sum of E over all testcases will not exceed 25*106 10 | 11 | // Time Complexity: O(V+E). 12 | // Auxiliary Space: O(V). 13 | 14 | 15 | 16 | 17 | 18 | // -------Solution------- 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | class Graph 25 | { 26 | int V; // No. of vertices 27 | list *adj; // An array of adjacency lists 28 | 29 | // Fills Stack with vertices (in increasing order of finishing 30 | // times). The top element of stack has the maximum finishing 31 | // time 32 | void fillOrder(int v, bool visited[], stack &Stack); 33 | 34 | // A recursive function to print DFS starting from v 35 | void DFSUtil(int v, bool visited[]); 36 | public: 37 | Graph(int V); 38 | void addEdge(int v, int w); 39 | 40 | // The main function that finds and prints strongly connected 41 | // components 42 | void printSCCs(); 43 | 44 | // Function that returns reverse (or transpose) of this graph 45 | Graph getTranspose(); 46 | }; 47 | 48 | Graph::Graph(int V) 49 | { 50 | this->V = V; 51 | adj = new list[V]; 52 | } 53 | 54 | // A recursive function to print DFS starting from v 55 | void Graph::DFSUtil(int v, bool visited[]) 56 | { 57 | // Mark the current node as visited and print it 58 | visited[v] = true; 59 | cout << v << " "; 60 | 61 | // Recur for all the vertices adjacent to this vertex 62 | list::iterator i; 63 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 64 | if (!visited[*i]) 65 | DFSUtil(*i, visited); 66 | } 67 | 68 | Graph Graph::getTranspose() 69 | { 70 | Graph g(V); 71 | for (int v = 0; v < V; v++) 72 | { 73 | // Recur for all the vertices adjacent to this vertex 74 | list::iterator i; 75 | for(i = adj[v].begin(); i != adj[v].end(); ++i) 76 | { 77 | g.adj[*i].push_back(v); 78 | } 79 | } 80 | return g; 81 | } 82 | 83 | void Graph::addEdge(int v, int w) 84 | { 85 | adj[v].push_back(w); // Add w to v’s list. 86 | } 87 | 88 | void Graph::fillOrder(int v, bool visited[], stack &Stack) 89 | { 90 | // Mark the current node as visited and print it 91 | visited[v] = true; 92 | 93 | // Recur for all the vertices adjacent to this vertex 94 | list::iterator i; 95 | for(i = adj[v].begin(); i != adj[v].end(); ++i) 96 | if(!visited[*i]) 97 | fillOrder(*i, visited, Stack); 98 | 99 | // All vertices reachable from v are processed by now, push v 100 | Stack.push(v); 101 | } 102 | 103 | // The main function that finds and prints all strongly connected 104 | // components 105 | void Graph::printSCCs() 106 | { 107 | stack Stack; 108 | 109 | // Mark all the vertices as not visited (For first DFS) 110 | bool *visited = new bool[V]; 111 | for(int i = 0; i < V; i++) 112 | visited[i] = false; 113 | 114 | // Fill vertices in stack according to their finishing times 115 | for(int i = 0; i < V; i++) 116 | if(visited[i] == false) 117 | fillOrder(i, visited, Stack); 118 | 119 | // Create a reversed graph 120 | Graph gr = getTranspose(); 121 | 122 | // Mark all the vertices as not visited (For second DFS) 123 | for(int i = 0; i < V; i++) 124 | visited[i] = false; 125 | 126 | // Now process all vertices in order defined by Stack 127 | while (Stack.empty() == false) 128 | { 129 | // Pop a vertex from stack 130 | int v = Stack.top(); 131 | Stack.pop(); 132 | 133 | // Print Strongly connected component of the popped vertex 134 | if (visited[v] == false) 135 | { 136 | gr.DFSUtil(v, visited); 137 | cout << endl; 138 | } 139 | } 140 | } 141 | 142 | int main() 143 | { 144 | // Create a graph given in the above diagram 145 | Graph g(5); 146 | g.addEdge(1, 0); 147 | g.addEdge(0, 2); 148 | g.addEdge(2, 1); 149 | g.addEdge(0, 3); 150 | g.addEdge(3, 4); 151 | 152 | cout << "Following are strongly connected components in " 153 | "given graph \n"; 154 | g.printSCCs(); 155 | 156 | return 0; 157 | } 158 | -------------------------------------------------------------------------------- /Graphs/32_CheapestFlightsWithinKStops.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei. 3 | 4 | You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 11 | Output: 200 12 | Explanation: The graph is shown. 13 | The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture. 14 | 15 | 16 | Example 2: 17 | 18 | Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 19 | Output: 500 20 | Explanation: The graph is shown. 21 | The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture. 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= n <= 100 27 | 0 <= flights.length <= (n * (n - 1) / 2) 28 | flights[i].length == 3 29 | 0 <= fromi, toi < n 30 | fromi != toi 31 | 1 <= pricei <= 104 32 | There will not be any multiple flights between two cities. 33 | 0 <= src, dst, k < n 34 | src != dst 35 | */ 36 | 37 | int INF = 1e9; 38 | class Solution { 39 | public: 40 | int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { 41 | vector> v(k+2,vector(n,INF)); 42 | 43 | v[0][src] = 0; 44 | 45 | for(int i=1;i<=k+1;i++) { 46 | v[i][src] = 0; 47 | 48 | for(auto u:flights) { 49 | v[i][u[1]] = min(v[i][u[1]],v[i-1][u[0]]+u[2]); 50 | } 51 | } 52 | 53 | return (v[k+1][dst]==INF)?-1:v[k+1][dst]; 54 | 55 | } 56 | }; -------------------------------------------------------------------------------- /Graphs/358_DFS_SearchElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int v[100],dis[100]; 6 | vector arr[100]; 7 | void dfs(int n,int d){ 8 | v[n]=1; 9 | dis[n]=d; 10 | for(int a:arr[n]){ 11 | if(v[a]==0){ 12 | v[a]=1; 13 | dis[a]=dis[a]+1; 14 | dfs(a,dis[a]+1); 15 | } 16 | } 17 | 18 | } 19 | int main() 20 | { 21 | int s; 22 | 23 | arr[0].push_back(1); 24 | arr[0].push_back(9); 25 | arr[1].push_back(2); 26 | arr[2].push_back(0); 27 | arr[2].push_back(3); 28 | arr[9].push_back(3); 29 | 30 | 31 | 32 | dfs(0,0);//1st parameter is starting node and 2nd parameter is distance of starting node i.e. 0 33 | 34 | s=9; //element to be searched i.e.9 35 | if(v[s]==1) 36 | cout<<"\nElements "< 24 | using namespace std; 25 | 26 | // Dimensions of paint screen 27 | #define M 8 28 | #define N 8 29 | 30 | // A recursive function to replace previous color 'prevC' at '(x, y)' 31 | // and all surrounding pixels of (x, y) with new color 'newC' and 32 | void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC) 33 | { 34 | // Base cases 35 | if (x < 0 || x >= M || y < 0 || y >= N) 36 | return; 37 | if (screen[x][y] != prevC) 38 | return; 39 | if (screen[x][y] == newC) 40 | return; 41 | 42 | // Replace the color at (x, y) 43 | screen[x][y] = newC; 44 | 45 | // Recur for north, east, south and west 46 | floodFillUtil(screen, x+1, y, prevC, newC); 47 | floodFillUtil(screen, x-1, y, prevC, newC); 48 | floodFillUtil(screen, x, y+1, prevC, newC); 49 | floodFillUtil(screen, x, y-1, prevC, newC); 50 | } 51 | 52 | // It mainly finds the previous color on (x, y) and 53 | // calls floodFillUtil() 54 | void floodFill(int screen[][N], int x, int y, int newC) 55 | { 56 | int prevC = screen[x][y]; 57 | if(prevC==newC) return; 58 | floodFillUtil(screen, x, y, prevC, newC); 59 | } 60 | 61 | int main() 62 | { 63 | int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, 64 | {1, 1, 1, 1, 1, 1, 0, 0}, 65 | {1, 0, 0, 1, 1, 0, 1, 1}, 66 | {1, 2, 2, 2, 2, 0, 1, 0}, 67 | {1, 1, 1, 2, 2, 0, 1, 0}, 68 | {1, 1, 1, 2, 2, 2, 2, 0}, 69 | {1, 1, 1, 1, 1, 2, 1, 1}, 70 | {1, 1, 1, 1, 1, 2, 2, 1}, 71 | }; 72 | int x = 4, y = 4, newC = 3; 73 | floodFill(screen, x, y, newC); 74 | 75 | cout << "Updated screen after call to floodFill: \n"; 76 | for (int i=0; i 2 | using namespace std; 3 | class Solution 4 | { 5 | public: 6 | int minStepToReachTarget(vector &KnightPos, vector &TargetPos, int N) 7 | { 8 | int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2}; 9 | int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1}; 10 | 11 | queue, int>> q; 12 | 13 | q.push({{KnightPos[0], KnightPos[1]}, 0}); 14 | pair, int> t; 15 | int x, y; 16 | bool visit[N + 1][N + 1]; 17 | 18 | for (int i = 1; i <= N; i++) 19 | for (int j = 1; j <= N; j++) 20 | visit[i][j] = false; 21 | 22 | visit[KnightPos[0]][KnightPos[1]] = true; 23 | 24 | while (!q.empty()) 25 | { 26 | t = q.front(); 27 | q.pop(); 28 | 29 | if (t.first.first == TargetPos[0] && t.first.second == TargetPos[1]) 30 | return t.second; 31 | 32 | for (int i = 0; i < 8; i++) 33 | { 34 | x = t.first.first + dx[i]; 35 | y = t.first.second + dy[i]; 36 | 37 | if ((x >= 1 && x <= N && y >= 1 && y <= N) && !visit[x][y]) 38 | { 39 | visit[x][y] = true; 40 | q.push({{x, y}, t.second + 1}); 41 | } 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Graphs/9_CloneAGraph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Question : https://leetcode.com/problems/clone-graph/ 4 | 5 | Approach : Traverse each non-visited vertices/nodes of a graph and clone the nodes one by one. Also clone the neighbors from the original graph. 6 | 7 | // Definition for a Node. 8 | class Node { 9 | public: 10 | int val; 11 | vector neighbors; 12 | Node() { 13 | val = 0; 14 | neighbors = vector(); 15 | } 16 | Node(int _val) { 17 | val = _val; 18 | neighbors = vector(); 19 | } 20 | Node(int _val, vector _neighbors) { 21 | val = _val; 22 | neighbors = _neighbors; 23 | } 24 | }; 25 | */ 26 | 27 | class Solution { 28 | public: 29 | Node* bfs(Node* src){ 30 | queue q; 31 | q.push(src); 32 | Node* n = new Node(src->val); 33 | 34 | map mp; //used for tracking the visited nodes 35 | mp[src] = n; 36 | 37 | while(!q.empty()){ 38 | Node *u = q.front(); 39 | q.pop(); 40 | vector v = u->neighbors; 41 | int n = v.size(); 42 | for(int i = 0; i < n; i++){ 43 | if(mp[v[i]] == NULL){ 44 | Node* node = new Node(v[i]->val); 45 | q.push(v[i]); 46 | mp[v[i]] = node; 47 | } 48 | mp[u]->neighbors.push_back(mp[v[i]]); 49 | } 50 | } 51 | return mp[src]; 52 | } 53 | 54 | Node* cloneGraph(Node* node) { 55 | if(node == NULL) 56 | return NULL; 57 | return bfs(node); 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Graphs/DFS_SearchElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int v[100],dis[100]; 6 | vector arr[100]; 7 | void dfs(int n,int d){ 8 | v[n]=1; 9 | dis[n]=d; 10 | for(int a:arr[n]){ 11 | if(v[a]==0){ 12 | v[a]=1; 13 | dis[a]=dis[a]+1; 14 | dfs(a,dis[a]+1); 15 | } 16 | } 17 | 18 | } 19 | int main() 20 | { 21 | int s; 22 | 23 | arr[0].push_back(1); 24 | arr[0].push_back(9); 25 | arr[1].push_back(2); 26 | arr[2].push_back(0); 27 | arr[2].push_back(3); 28 | arr[9].push_back(3); 29 | 30 | 31 | 32 | dfs(0,0);//1st parameter is starting node and 2nd parameter is distance of starting node i.e. 0 33 | 34 | s=9; //element to be searched i.e.9 35 | if(v[s]==1) 36 | cout<<"\nElements "< 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | Node(int x) 9 | { 10 | data = x; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | bool isPalindrome(Node *head) 19 | { 20 | Node* slow = head; 21 | stack s; 22 | 23 | while (slow != NULL) { 24 | s.push(slow->data); 25 | slow = slow->next; 26 | } 27 | 28 | while (head != NULL) { 29 | 30 | int i = s.top(); 31 | s.pop(); 32 | 33 | if (head->data != i) 34 | return false; 35 | 36 | head = head->next; 37 | } 38 | 39 | return true; 40 | } 41 | }; -------------------------------------------------------------------------------- /Linked List/6_RemoveDuplicatesfromSortedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | struct Node { 3 | int data; 4 | struct Node *next; 5 | Node(int x) { 6 | data = x; 7 | next = NULL; 8 | } 9 | };*/ 10 | 11 | //Function to remove duplicates from sorted linked list. 12 | Node *removeDuplicates(Node *head) 13 | { 14 | Node* p, *q; 15 | p = head; 16 | if(p == NULL) return head; 17 | p = p->next; 18 | q = head; 19 | int prev = head->data; 20 | while(p != NULL){ 21 | if(p->data == prev){ 22 | q->next = p->next; 23 | delete p; 24 | p = q->next; 25 | continue; 26 | } 27 | prev = p->data; 28 | q = p; 29 | p = p->next; 30 | } 31 | return head; 32 | } 33 | -------------------------------------------------------------------------------- /Linked List/Floyds_Cycle_Detection_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | Node(int x) 10 | { 11 | data = x; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | class Solution 17 | { 18 | public: 19 | // Function to check if the linked list has a loop. 20 | bool detectLoop(Node *head) 21 | { 22 | if (head == NULL) 23 | return false; 24 | else if (head->next == head) 25 | return true; 26 | 27 | Node *slow = head; 28 | Node *fast = head->next; 29 | 30 | while (fast != slow) 31 | { 32 | if (fast == NULL || fast->next == NULL) 33 | return false; 34 | 35 | slow = slow->next; 36 | fast = fast->next->next; 37 | } 38 | 39 | return true; 40 | } 41 | }; -------------------------------------------------------------------------------- /Matrix/1_SpiralTraversalOfAMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Run this code on your local system. This code is 100% correct. GFG have some issue in this question with the test cases. 5 | 6 | //Time Complexity : O(m*n) 7 | //Space Complexity : O(n) 8 | 9 | int main() { 10 | int t; 11 | cin>>t; 12 | while(t--){ 13 | int m, n; 14 | cin>>m>>n; 15 | int mat[m][n] ={0}; 16 | 17 | for(int i = 0; i < m; i++){ 18 | for(int j = 0; j < n; j++){ 19 | cin>>mat[i][j]; 20 | } 21 | } 22 | int top = 0, bottom = m-1, right = n-1, left = 0; 23 | while(1){ 24 | if(left > right) 25 | break; 26 | 27 | for(int i = left; i <= right; i++) //Top row 28 | cout< bottom) 32 | break; 33 | 34 | for(int i = top; i <= bottom; i++) //Right column 35 | cout< right) 39 | break; 40 | 41 | for(int i = right; i >= left; i--) //Bottom row 42 | cout< bottom) 46 | break; 47 | 48 | for(int i = bottom; i >= top; i--) //Left column 49 | cout<>& matrix, int target) { 10 | if(matrix.size() == 0 || matrix[0].size() == 0) return false; 11 | int n = matrix.size(); 12 | int m = matrix[0].size(); 13 | for(int i = 0; i < n; i++){ 14 | if(matrix[i][m-1] < target) 15 | continue; 16 | for(int k = 0; k < m; k++) 17 | if(matrix[i][k] == target) 18 | return true; 19 | 20 | } 21 | return false; 22 | } 23 | }; 24 | 25 | //Time Complexity : log(n*m) 26 | //Space Complexity : O(1) 27 | 28 | //Approach 2 : Taking advantage of the sorted rows we apply binary search on the whole matrix. 29 | 30 | class Solution { 31 | public: 32 | bool searchMatrix(vector>& matrix, int target) { 33 | if(!matrix.size()) return false; 34 | int n = matrix.size(); 35 | int m = matrix[0].size(); 36 | int low = 0, high = n*m - 1, mid; 37 | while(low <= high){ 38 | mid = low + (high - low)/2; 39 | if(matrix[mid/m][mid%m] == target) 40 | return true; 41 | if(matrix[mid/m][mid%m] < target) 42 | low = mid+1; 43 | if(matrix[mid/m][mid%m] > target) 44 | high = mid-1; 45 | } 46 | return false; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Matrix/3_FindMedianInRowWiseSortedMatrix.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Time Complexity : O(32 * r * log(c)) 3 | //Space Complexity : O(1) 4 | 5 | class Solution{ 6 | public: 7 | int median(vector> &matrix, int r, int c){ 8 | //Finding the minimum and maximum element in the matrix 9 | int mn = INT_MAX, mx = INT_MIN; 10 | for(int i = 0; i arr, int i, int j){ 11 | while(i <= j){ 12 | int mid = i + (j-i)/2; 13 | if(arr[mid] == 1 && (arr[mid-1] == 0 || mid == 0)) 14 | return mid; 15 | else if(arr[mid] == 0) 16 | i=mid+1; 17 | else 18 | j=mid-1; //As there is more ones to the left of j. 19 | } 20 | return -1; 21 | } 22 | 23 | int rowWithMax1s(vector > arr, int n, int m) { 24 | int max_row_index = -1; 25 | int j = first(arr[0], 0 , m-1); 26 | if(j == -1) 27 | j = m-1; 28 | 29 | if(j == 0 and arr[0][0] == 1) //Corner Case : for the case when first row itself is all 1. 30 | return 0; 31 | 32 | for(int i = 1; i < n ; i++){ 33 | 34 | while(j>=0 && arr[i][j] == 1){ 35 | j--; 36 | max_row_index = i; 37 | } 38 | 39 | } 40 | return max_row_index; 41 | } 42 | -------------------------------------------------------------------------------- /Matrix/5_PrintElementsInSortedOrderUsingRowColumnWiseSortedMatrix.cpp: -------------------------------------------------------------------------------- 1 | // Time Complexity: O(n^2logn). 2 | // Auxiliary Space: O(n^2) 3 | 4 | // Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. 5 | // Now one by one copy the elements of temp[] back to the given matrix. 6 | vector> sortedMatrix(int N, vector> Mat) 7 | { 8 | vector ans; 9 | // stored element in 1D array 10 | for (int i = 0; i < N; i++) 11 | { 12 | for (int j = 0; j < N; j++) 13 | { 14 | ans.push_back(Mat[i][j]); 15 | } 16 | } 17 | // sort the element in 1D array 18 | sort(ans.begin(), ans.end()); 19 | // stored element in 2D array 20 | for (int i = 0; i < N * N; i++) 21 | { 22 | Mat[i / N][i % N] = ans[i]; 23 | } 24 | 25 | return Mat; 26 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSA-CRACKER 2 | 3 | LOC Stars Badge 4 | Forks Badge 5 | GitHub contributors 6 | 7 | **_If you appreciate my work, please 🌟 this repository. It motivates me. :rocket: :rocket:_** 8 | 9 | **DSA CRACKER sheet : [link](https://drive.google.com/file/d/1FMdN_OCfOI0iAeDlqswCiC2DZzD4nPsb/view)** 10 | 11 | #### :red_circle: :red_circle: IMPORTANT : If you forked this repo and want to be updated with the changes made to this repo refer [How do I update a GitHub forked repository?](https://stackoverflow.com/questions/7244321/how-do-i-update-a-github-forked-repository) 12 | 13 | ### :arrow_forward: Update Corner 14 | 15 | - Added **Clone A Graph** problem in the [Graphs](#graphs) topic. 16 | 17 | # :gift: You Can Contribute. 18 | 19 | #### Make a pull request : 20 | 21 | - If you think you have the better optimal solution. 22 | - If you have the solution to the unsolved problem marked with "red-cross". 23 | 24 | ### Hello, folks! 25 | 26 | This is an attempt to solve 450 questions carefully curated by our very own **[Love Babbar](https://www.youtube.com/watch?v=4iFALQ1ACdA)**. 27 | 28 | ## Topics 29 | 30 | - [Array](#array) 31 | - [Matrix](#matrix) 32 | - [Stack & Queue](#stackqueue) 33 | - [Backtracking](#backtracking) 34 | - [Graphs](#graphs) 35 | - [Linked List](#linkedlist) 36 | 37 | ## Array 38 | 39 | | # | Title | Solution | Time | Space | Difficulty | Note | 40 | | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ---- | ----- | ---------- | ------------------ | 41 | | 1 | [Reverse an Array](https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/) | :heavy_check_mark: | _-_ | _-_ | - | - | 42 | | 2 | [Find the maximum and minimum element in an array](https://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/) | :heavy_check_mark: | _-_ | _-_ | - | - | 43 | | 3 | [Find the "Kth" max and min element of an array](https://practice.geeksforgeeks.org/problems/kth-smallest-element/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 44 | | 4 | [Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo](https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 45 | | 5 | [Move all the negative elements to one side of the array ](https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space//) | :heavy_check_mark: | _-_ | - | - | 46 | | 6 | [Find the Union and Intersection of the two sorted arrays.](https://practice.geeksforgeeks.org/problems/union-of-two-arrays/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 47 | | 7 | [Write a program to cyclically rotate an array by one.](https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 48 | | 8 | [find Largest sum contiguous Subarray V. IMP](https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 49 | | 9 | [Minimise the maximum difference between heights V.IMP](https://practice.geeksforgeeks.org/problems/minimize-the-heights3351/1) | :heavy_check_mark: | _-_ | _-_ | - | Revisit | 50 | | 10 | [Minimum no. of Jumps to reach end of an array](https://practice.geeksforgeeks.org/problems/minimum-number-of-jumps/0) | :heavy_check_mark: | _-_ | _-_ | - | Revisit | 51 | | 11 | [find duplicate in an array of N+1 Integers](https://leetcode.com/problems/find-the-duplicate-number/) | :heavy_check_mark: | _-_ | _-_ | - | - | 52 | | 12 | [Merge 2 sorted arrays without using Extra space.](https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1) | :heavy_check_mark: | _-_ | _-_ | - | Revisit | 53 | | 13 | [Kadane's Algo [V.V.V.V.V IMP]](https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 54 | | 14 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | :heavy_check_mark: | _-_ | _-_ | - | - | 55 | | 15 | [Next Permutation ](https://leetcode.com/problems/next-permutation/) | :heavy_check_mark: | _-_ | _-_ | - | - | 56 | | 16 | [Count Inversion](https://practice.geeksforgeeks.org/problems/inversion-of-array/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 57 | | 17 | [Best time to buy and Sell stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | :heavy_check_mark: | _-_ | _-_ | - | Pending variations | 58 | | 18 | [find all pairs on integer array whose sum is equal to given number](https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 59 | | 19 | [find common elements In 3 sorted arrays](https://practice.geeksforgeeks.org/problems/common-elements1132/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 60 | | 20 | [Rearrange the array in alternating positive and negative items with O(1) extra space](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/) | :heavy_check_mark: | _-_ | _-_ | - | - | 61 | | 21 | [Find if there is any subarray with sum equal to 0](https://practice.geeksforgeeks.org/problems/subarray-with-0-sum/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 62 | | 22 | [Find factorial of a large number](https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers/0) | :heavy_check_mark: | _-_ | _-_ | - | | 63 | | 23 | [find maximum product subarray ](https://practice.geeksforgeeks.org/problems/maximum-product-subarray3604/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 64 | | 24 | [Find longest coinsecutive subsequence](https://practice.geeksforgeeks.org/problems/longest-consecutive-subsequence/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 65 | | 25 | [Given an array of size n and a number k, fin all elements that appear more than " n/k " times.](https://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/) | :heavy_check_mark: | _-_ | _-_ | - | - | 66 | | 26 | [Maximum profit by buying and selling a share atmost twice](https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/) | :heavy_check_mark: | _-_ | _-_ | - | - | 67 | | 27 | [Find whether an array is a subset of another array](https://practice.geeksforgeeks.org/problems/array-subset-of-another-array/0) | :heavy_check_mark: | _-_ | _-_ | - | 68 | | 28 | [Find the triplet that sum to a given value](https://practice.geeksforgeeks.org/problems/triplet-sum-in-array/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 69 | | 29 | [Trapping Rain water problem](https://practice.geeksforgeeks.org/problems/trapping-rain-water/0) | :heavy_check_mark: | _-_ | _-_ | - | Revisit | 70 | | 30 | [Chocolate Distribution problem](https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 71 | | 31 | [Smallest Subarray with sum greater than a given value](https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 72 | | 32 | [Three way partitioning of an array around a given value](https://practice.geeksforgeeks.org/problems/three-way-partitioning/1) | :heavy_check_mark: | _-_ | _-_ | - | | 73 | | 33 | [Minimum swaps required bring elements less equal K together ](https://practice.geeksforgeeks.org/problems/minimum-swaps-required-to-bring-all-elements-less-than-or-equal-to-k-together/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 74 | | 34 | [Minimum no. of operations required to make an array palindrome](https://practice.geeksforgeeks.org/problems/palindromic-array/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 75 | | 35 | [Median of 2 sorted arrays of equal size](https://www.geeksforgeeks.org/median-of-two-sorted-arrays/) | :heavy_check_mark: | _-_ | _-_ | - | Revisit | 76 | | 36 | [Median of 2 sorted arrays of different size](https://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/) | :heavy_check_mark: | _-_ | _-_ | - | - | 77 | 78 |
79 |
80 | ⬆️ Back to Top 81 |
82 |
83 | 84 | ## Matrix 85 | 86 | | # | Title | Solution | Time | Space | Difficulty | Note | 87 | | --- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ---- | ----- | ---------- | ---- | 88 | | 1 | [Spiral traversal on a Matrix](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix/0) | :heavy_check_mark: | 89 | | 2 | [Search an element in a matriix](https://leetcode.com/problems/search-a-2d-matrix/) | :heavy_check_mark: | 90 | | 3 | [Find median in a row wise sorted matrix](https://practice.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1) | :heavy_check_mark: | 91 | | 4 | [Find row with maximum no. of 1's](https://practice.geeksforgeeks.org/problems/row-with-max-1s0023/1) | :heavy_check_mark: | 92 | | 5 | [Print elements in sorted order using row-column wise sorted matrix](https://practice.geeksforgeeks.org/problems/sorted-matrix2333/1) | :heavy_check_mark: | 93 | 94 |
95 |
96 | ⬆️ Back to Top 97 |
98 |
99 | 100 | ## StackQueue 101 | 102 | | # | Title | Solution | Time | Space | Difficulty | Note | 103 | | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ------------ | ------ | ---------- | ---- | 104 | | 1 | [ Implement Stack from Scratch](https://www.tutorialspoint.com/javaexamples/data_stack.htm) | :heavy_check_mark: | _-_ | _-_ | - | 105 | | 2 | [https://www.tutorialspoint.com/javaexamples/data_stack.htm](https://www.geeksforgeeks.org/queue-set-1introduction-and-array-implementation/) | :heavy_check_mark: | _-_ | _-_ | - | - | 106 | | 3 | [Implement 2 stack in an array](https://practice.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 107 | | 4 | [Find the middle element of a stack](https://www.geeksforgeeks.org/design-a-stack-with-find-middle-operation/) | :heavy_check_mark: | _O(n)_ | _O(n)_ | - | - | 108 | | 5 | [Implement "N" stacks in an Array](https://www.geeksforgeeks.org/efficiently-implement-k-stacks-single-array/) | :heavy_check_mark: | _-_ | _-_ | - | 109 | | 6 | [Check the expression has valid or Balanced parenthesis or not.](https://practice.geeksforgeeks.org/problems/parenthesis-checker/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 110 | | 7 | [Reverse a String using Stack](https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 111 | | 8 | [Design a Stack that supports getMin() in O(1) time and O(1) extra space.](https://practice.geeksforgeeks.org/problems/special-stack/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 112 | | 9 | [Find the next Greater element](https://practice.geeksforgeeks.org/problems/next-larger-element/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 113 | | 10 | [The celebrity Problem](https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 114 | | 11 | [Arithmetic Expression evaluation](https://www.geeksforgeeks.org/arithmetic-expression-evalution/#:~:text=The%20stack%20organization%20is%20very,i.e.%2C%20A%20%2B%20B) | :heavy_check_mark: | _-_ | _-_ | - | - | 115 | | 12 | [Evaluation of Postfix expression](https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression/0) | :heavy_check_mark: | _-_ | _-_ | - | - | 116 | | 13 | [Implement a method to insert an element at its bottom without using any other data structure.](https://stackoverflow.com/questions/45130465/inserting-at-the-end-of-stack) | :heavy_check_mark: | _-_ | _-_ | - | - | 117 | | 14 | [Reverse a stack using recursion](https://www.geeksforgeeks.org/reverse-a-stack-using-recursion/) | :heavy_check_mark: | _-_ | _-_ | - | - | 118 | | 15 | [Sort a Stack using recursion](https://practice.geeksforgeeks.org/problems/sort-a-stack/1) | :heavy_check_mark: | _-_ | _-_ | - | - | 119 | | 16 | [Merge Overlapping Intervals](https://practice.geeksforgeeks.org/problems/overlapping-intervals/0) | :heavy_check_mark: | _O(n\*logn)_ | _O(1)_ | - | - | 120 | | 17 | [Largest rectangular Area in Histogram](https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram/0) | :heavy_check_mark: | _O(n)_ | _O(n)_ | - | - | 121 | | 18 | [Length of the Longest Valid Substring](https://practice.geeksforgeeks.org/problems/valid-substring0624/1) | :heavy_check_mark: | _O(n)_ | _O(1)_ | - | - | 122 | | 19 | [Expression contains redundant bracket or not](https://www.geeksforgeeks.org/expression-contains-redundant-bracket-not/) | :heavy_check_mark: | _O(n)_ | _O(n)_ | - | - | 123 | | 20 | [Implement Stack using Queue](https://practice.geeksforgeeks.org/problems/stack-using-two-queues/1) | :heavy_check_mark: | _O(n)_ | _O(n)_ | - | - | 124 | 125 |
126 |
127 | ⬆️ Back to Top 128 |
129 |
130 | 131 | ## Backtracking 132 | 133 | | # | Title | Solution | Time | Space | Difficulty | Note | 134 | | --- | ------------------------------------------------------------------------------------------------------------------ | ------------------ | ------ | ----- | ---------- | ---- | 135 | | 1 | [ Rat In A Maze](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Backtracking/1_RatInAMazeBacktracking.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 136 | | 2 | [ N Queens Problem](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Backtracking/2_NQueenProblem.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 137 | | 3 | [ M coloring Problem](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Backtracking/3_ColoringProblem.cpp) | :heavy_check_mark: | O(n^m) | O(n) | - | 138 | | 5 | [ Sudoku Solver](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Backtracking/5_SudokuSolver.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 139 | 140 |
141 |
142 | ⬆️ Back to Top 143 |
144 |
145 | 146 | ## Graphs 147 | 148 | | # | Title | Solution | Time | Space | Difficulty | Note | 149 | | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | --------- | --------- | ---------- | ---- | 150 | | 6 | [Flood fill Algorithm](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/6_Floodfillalgorithm.cpp) | :heavy_check_mark: | _O(n\*m)_ | _O(n\*m)_ | - | 151 | | 7 | [Minimum Step By Knight](https://practice.geeksforgeeks.org/problems/steps-by-knight5927/1) | :heavy_check_mark: | _-_ | _-_ | - | 152 | | 9 | [Clone A Graph](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/9_CloneAGraph.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 153 | | 13 | [Implement Topological Sorting](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/13_ImplementTopologicalSort.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 154 | | 22 | [Implement Floyd Warshall Algorithm](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/22_ImplementFloydWarshallAlgorithm.cpp) | :heavy_check_mark: | _-_ | _-_ | - | 155 | | 25 | [Snake and Ladder Problem](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/25_SnakeandLadderProblem.cpp) | :heavy_check_mark: | _O(n)_ | _O(n)_ | - | 156 | | 27 | [Strongly Connected Components (Kosaraju's Algo)]() | :heavy_check_mark: | _-_ | _-_ | - | 157 | | 32 | [Cheapest Flights within k stops](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/32_CheapestFlightsWithinKStops.cpp) | :heavy_check_mark: | Quadratic | Quadratic | Medium | 158 | | 37 | [Maximum Product Subarray](https://www.geeksforgeeks.org/maximum-product-subarray/) | :heavy_check_mark: | _-_ | _-_ | - | - | 159 | | 358 | [searching element in Graph using DFS](https://github.com/tarunsinghdev/DSA-CRACKER/blob/main/Graphs/358_DFS_SearchElement.cpp) | :heavy_check_mark: | _O(V+E)_ | _O(V)_ | Medium | 160 |
161 |
162 | ⬆️ Back to Top 163 |
164 |
165 | 166 | ## Binary Tree 167 | 168 | | # | Title | Solution | Time | Space | Difficulty | Note | 169 | | --- | --------------------------------------------------------------------------------------------------- | ------------------ | ---- | --------- | ---------- | ---- | 170 | | 1 | [Right View of Binary Tree](https://leetcode.com/problems/binary-tree-right-side-view/description/) | :heavy_check_mark: | o(n) | O(n) | Medium | 171 | | 2 | [Height of Binary Tree](https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1) | :heavy_check_mark: | O(N) | O(N) | Medium | 172 | | 3 | [Diameter of Binary Tree](https://practice.geeksforgeeks.org/problems/diameter-of-binary-tree/1) | :heavy_check_mark: | O(N) | O(log(N)) | Easy | 173 | | 4 | [Check for Balanced Tree](https://practice.geeksforgeeks.org/problems/check-for-balanced-tree/1) | :heavy_check_mark: | O(N) | O(log(N)) | Easy | 174 | | 5 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | :heavy_check_mark: | O(n) | O(n) | Easy 175 | | 6 | [Bottom View of Binary Tree](https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1) | :heavy_check_mark: | O(n) | O(n) | Medium | 176 |
177 |
178 | ⬆️ Back to Top 179 |
180 |
181 | 182 | ## Arrays In Javascript Implementation 183 | 184 | | # | Title | Solution | Time | Space | Difficulty | Note | 185 | | --- | --------------------------------------------------------------------------------------------------- | ------------------ | ---- | --------- | ---------- | ---- | 186 | | 1 | [Reverse an Array](https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/) | :heavy_check_mark: | O(N) | O(1) | Easy | 187 | | 2 | [Find MAximum and Minimum in Array](https://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/) | :heavy_check_mark: | O(N) | O(1)) | Easy | 188 | | 3 | [Dutch National Flag [ Sort 0's , 1's and 2's without sorting]](https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1) | :heavy_check_mark: | O(N) | O(N)) | Easy | 189 | 190 | ## LinkedList 191 | 192 | | # | Title | Solution | Time | Space | Difficulty | Note | 193 | | --- | --------------------------------------------------------------------------------------------------- | ------------------ | ---- | --------- | ---------- | ---- | 194 | | 1 | [Write a program to Detect loop in a linked list.](https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1) | :heavy_check_mark: | _-_ | _-_ | Easy | - | 195 | | 2 | [Write a Program to check whether the Singly Linked list is a palindrome or not.](https://practice.geeksforgeeks.org/problems/check-if-linked-list-is-pallindrome/1) | :heavy_check_mark: | O(n) | O(n) | Easy | - | 196 | | 3 | [Write a Program to Remove duplicate element from sorted Linked List.](https://practice.geeksforgeeks.org/problems/remove-duplicate-element-from-sorted-linked-list/1) | :heavy_check_mark: | O(n) | O(1) | Easy | - | 197 | 198 | 199 | 200 |
201 |
202 | ⬆️ Back to Top 203 |
204 |
205 | 206 | 207 | 208 | > You can find me on [![LinkedIn][2.2]][2] to stay updated and follow along with my journey. 209 | 210 | 211 | 212 | [2.2]: https://raw.githubusercontent.com/MartinHeinz/MartinHeinz/master/linkedin-3-16.png 213 | 214 | 215 | 216 | [2]: https://www.linkedin.com/in/tarun-singh-981547191/ 217 | -------------------------------------------------------------------------------- /Stacks&Queues/10_TheCelebrityProblem.cpp: -------------------------------------------------------------------------------- 1 | //Approach : Stack 2 | 3 | //Time Complexity : O(n) 4 | //Space Complexity : O(n) 5 | 6 | class Solution { 7 | public: 8 | int celebrity(vector >& M, int n) { 9 | stackst; 10 | for(int i = 0; i < n; i++) 11 | st.push(i); 12 | while(st.size() >= 2){ 13 | int i = st.top(); 14 | st.pop(); 15 | int j = st.top(); 16 | st.pop(); 17 | if(M[i][j] == 1) //i knows j => i is not a celebrity 18 | st.push(j); 19 | else 20 | st.push(i); //i doesn't knows j => j is not a celebrity 21 | } 22 | int potential_candidate = st.top(); 23 | st.pop(); 24 | for(int i = 0; i < n; i++){ 25 | if(i != potential_candidate){ 26 | if(M[i][potential_candidate] == 0 || M[potential_candidate][i] == 1) //Verifying the potential_candidate's row and column 27 | return -1; 28 | } 29 | } 30 | return potential_candidate; 31 | } 32 | }; 33 | 34 | //Approach : Two Pointer Approach 35 | 36 | //Time Complexity : O(n) 37 | //Space Complexity : O(1) 38 | 39 | class Solution { 40 | public: 41 | 42 | int celebrity(vector >& M, int n) { 43 | int a = 0; 44 | int b = n - 1; 45 | 46 | while (a < b) 47 | { 48 | if (M[a][b]) 49 | a++; 50 | else 51 | b--; 52 | } 53 | 54 | for (int i = 0; i < n; i++) //Verifying if 'a' is celebrity 55 | { 56 | if ( (i != a) && ( M[a][i] || M[i][a] == 0 ) ) 57 | return -1; 58 | } 59 | 60 | return a; 61 | } 62 | }; 63 | 64 | -------------------------------------------------------------------------------- /Stacks&Queues/11_ArithmeticExpressionEvaluation.txt: -------------------------------------------------------------------------------- 1 | 2 | Most frequently used expressions are written in infix notation i.e operator lies between the two operand. 3 | For eg : (A + B) * C is an infix expression. 4 | We need to put parenthesis in the order in which we want to perform the operations and also make use of 5 | operator precedence rule. 6 | Though infix expressions gives readability to humans but for the machines it adds extra burden of handling 7 | the parenthesis and operator precedence rules. 8 | 9 | Postfix expressions are usually used by our machinese. In this, operator comes after the operands. 10 | For eg : AB+C* .There is no need of maitaining parenthesis or remembering the operator precedence. 11 | 12 | Prefix expressions as the name suggests are expressions in which operators occur before the operand. 13 | For eg : *+ABC 14 | 15 | NOTE : One main thing to note is that while converting from infix to postfix or from any conversion 16 | to other conversion the order of operands in the final expression is always the same. 17 | -------------------------------------------------------------------------------- /Stacks&Queues/12_EvaluatePostfixExpression.cpp: -------------------------------------------------------------------------------- 1 | /* Approch : Stack. Just push the operands encountered into the stack. When we encounter an operator 2 | pop last two elements from the stack and perform operation onto them and store their result 3 | back into the stack. 4 | 5 | Time Complexity : O(n) 6 | Space Complexity : O(n) 7 | 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | bool isOperand(char c){ 14 | return (c >= '0' && c <='9') ? true : false; 15 | } 16 | 17 | bool isOperator(char c){ 18 | if(c == '+' || c == '-' || c == '*' || c == '/') 19 | return true; 20 | return false; 21 | } 22 | 23 | int performOperation(char c, int op1, int op2){ 24 | if(c == '+') return op1 + op2; 25 | if(c == '-') return op1 - op2; 26 | if(c == '*') return op1 * op2; 27 | if(c == '/') return op1 / op2; 28 | } 29 | 30 | int main() { 31 | int t; 32 | cin>>t; 33 | while(t--){ 34 | string ex; 35 | cin>>ex; 36 | stack st; 37 | for(int i = 0; i < ex.length(); i++){ 38 | if(isOperand(ex[i]) ){ 39 | st.push(ex[i]-'0'); 40 | } 41 | else if(isOperator(ex[i])){ 42 | int op2 = st.top(); st.pop(); 43 | int op1 = st.top(); st.pop(); 44 | int result = performOperation(ex[i], op1, op2); 45 | st.push(result); 46 | } 47 | } 48 | cout< 8 | using namespace std; 9 | 10 | stack st; 11 | 12 | void insertBottom(int x){ 13 | if(st.empty()) 14 | st.push(x); 15 | else{ 16 | int a = st.top(); 17 | st.pop(); 18 | insertBottom(x); //due to recursion, 'a' value gets on hold in the call stack and 19 | //we use this opportunity to insert back all the elements. 20 | 21 | st.push(a); 22 | } 23 | } 24 | 25 | void display(){ 26 | while(!st.empty()){ 27 | cout<>x; 40 | insertBottom(x); 41 | display(); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Stacks&Queues/14_ReverseAStackUsingRecursion.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* Approach : In this stack is reversed using insertBottom function. When at first reverse function 3 | is called it empties the stack and hold value in the call stack. Now when we push elements 4 | back into the stack we call insertBottom function so that elements gets pushed at the 5 | bottom and we have our reversed stack. 6 | 7 | Time Complexity : O(n*n) 8 | Space Complexity : O(n) 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | stack st; 15 | 16 | void insertBottom(int x){ 17 | if(st.empty()) 18 | st.push(x); 19 | else{ 20 | int a = st.top(); 21 | st.pop(); 22 | insertBottom(x); //due to recursion, 'a' value gets on hold in the call stack and 23 | //we use this opportunity to insert back all the elements. 24 | 25 | st.push(a); 26 | } 27 | } 28 | 29 | void reverse_st(){ 30 | if(!st.empty()){ 31 | int b = st.top(); 32 | st.pop(); 33 | reverse_st(); 34 | insertBottom(b); 35 | } 36 | } 37 | 38 | 39 | 40 | void display(){ 41 | while(!st.empty()){ 42 | cout< &s, int elt){ 14 | if(s.empty() || elt > s.top()){ 15 | s.push(elt); 16 | 17 | return; 18 | } 19 | int temp = s.top(); 20 | s.pop(); 21 | sortedInsert(s, elt); 22 | s.push(temp); 23 | 24 | 25 | } 26 | 27 | void sortStack(stack &s){ 28 | if(!s.empty()){ 29 | int temp = s.top(); 30 | s.pop(); 31 | sortStack(s); 32 | sortedInsert(s, temp); 33 | } 34 | } 35 | 36 | void SortedStack :: sort() 37 | { 38 | sortStack(s); 39 | 40 | } 41 | 42 | //Approach 2: Easy and Intutive using temporary stack. 43 | // Time Complexity : O(n*n) 44 | // Space Complexity : O(n) 45 | 46 | stack st, tmp; 47 | 48 | void sortStack(){ 49 | while(!st.empty()){ 50 | int x = st.top(); 51 | st.pop(); 52 | while(!tmp.empty() && tmp.top() > x){ 53 | st.push(tmp.top()); 54 | tmp.pop(); 55 | } 56 | tmp.push(x); 57 | } 58 | } 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /Stacks&Queues/16_MergeOverlappingIntervals.cpp: -------------------------------------------------------------------------------- 1 | /* Approach 1 : Brute Force 2 | In this approach, we simply compare one interval with all the other intervals if overlap 3 | exists. An overlap is said to exist if the interval to be compared with is not 4 | non - overlapping i.e apart from these cases p1.end < p2.start or p2.end < p1.start. 5 | Thus, if overlap case exists, we can update our reference interval to the calcuted merge 6 | interval and somehow erase the interval to which the reference interval was compared with. 7 | 8 | Time Complexity : O(n*n) 9 | Space Complexity : O(1) 10 | 11 | */ 12 | 13 | /*Approach : 2 Using Stack 14 | We first sort the intervals in ascending order of their start time. By sorting we are sure 15 | that no interval after a particular non - overlapping interval exists in the sorted array 16 | that can be overlapping. Thus, as soon as we encounter a non-overlapping interval simply 17 | push into the stack without caring about the remaining intervals as we are sure that as 18 | we have sorted the array those intervals are not overlapping. 19 | 20 | Time Complexity : O(n*logn) 21 | Space Complexity : O(n) 22 | */ 23 | 24 | #include 25 | using namespace std; 26 | 27 | struct Interval{ 28 | int start; 29 | int end; 30 | }; 31 | 32 | bool compare(Interval i1, Interval i2){ 33 | return i1.start < i2.start; 34 | } 35 | 36 | int main() { 37 | int t; 38 | cin>>t; 39 | while(t--){ 40 | int n; 41 | cin>>n; 42 | Interval arr[n]; 43 | for(int i = 0; i < n ; i++){ 44 | cin>>arr[i].start; 45 | cin>>arr[i].end; 46 | } 47 | 48 | sort(arr, arr+n, compare); 49 | 50 | stackst; 51 | st.push(arr[0]); 52 | 53 | for(int i = 1; i < n; i++){ //If an interval overlaps, we merge the interval and push 54 | //newly updated interval to the stack, if not we simply 55 | //push in into the stack. 56 | Interval x = st.top(); 57 | if(arr[i].start <= x.end){ 58 | st.pop(); 59 | x.end = max(arr[i].end, x.end); 60 | st.push(x); 61 | } 62 | else 63 | st.push(arr[i]); 64 | } 65 | stack ans; //Since we need to print the intervals in ascending order 66 | //we make use of another stack. 67 | while(!st.empty()){ 68 | ans.push(st.top()); 69 | st.pop(); 70 | } 71 | while(!ans.empty()){ 72 | Interval y = ans.top(); 73 | cout< 88 | using namespace std; 89 | 90 | int main() { 91 | int t; 92 | cin>>t; 93 | while(t--){ 94 | int n; 95 | cin>>n; 96 | vector> intervals(n , vector(2)); //tackling the same logic but this time 97 | //instead of creating a structure we use 98 | //vector of vectors(just for some fun and 99 | //knowledge). 100 | for(int i = 0; i < n; i++){ 101 | for(int j = 0; j < 2; j++){ 102 | cin>>intervals[i][j]; 103 | } 104 | } 105 | 106 | sort(intervals.begin(), intervals.end(),[](vector &a, vector &b ){ 107 | return a[0] < b[0]; 108 | }); 109 | 110 | int k = 0; 111 | 112 | //To optimize space we modify the intervals vector itself and print only k elements of it. 113 | 114 | for(int i = 1; i < n; i++){ 115 | if(intervals[k][1] >= intervals[i][0]){ 116 | intervals[k][1] = max(intervals[k][1], intervals[i][1]); 117 | 118 | } 119 | else{ 120 | k++; 121 | intervals[k] = intervals[i]; 122 | } 123 | } 124 | 125 | for(int i = 0; i <= k; i++){ 126 | for(int j = 0; j < 2; j++){ 127 | cout< 9 | using namespace std; 10 | 11 | vector nearestSmallerLeftIndex(vector a, int n){ 12 | stack> st; 13 | vector nslIndex; 14 | int pseudoIndex = -1; 15 | for(int i = 0; i < n; i++){ 16 | if(st.size() == 0) 17 | nslIndex.push_back(pseudoIndex); 18 | else if(st.size() > 0 && st.top().first < a[i]) 19 | nslIndex.push_back(st.top().second); 20 | else if(st.size() > 0 && st.top().first >= a[i]){ 21 | while(!st.empty() && st.top().first >= a[i]) 22 | st.pop(); 23 | if(st.empty()) 24 | nslIndex.push_back(-1); 25 | else 26 | nslIndex.push_back(st.top().second); 27 | } 28 | st.push({a[i], i}); 29 | } 30 | return nslIndex; 31 | } 32 | 33 | vector nearestSmallerRightIndex(vector a, int n){ 34 | stack> st; 35 | vector nsrIndex; 36 | int pseudoIndex = n; 37 | for(int i = n-1; i >= 0; i--){ 38 | if(st.size() == 0) 39 | nsrIndex.push_back(pseudoIndex); 40 | else if(st.size() > 0 && st.top().first < a[i]) 41 | nsrIndex.push_back(st.top().second); 42 | else if(st.size() > 0 && st.top().first >= a[i]){ 43 | while(!st.empty() && st.top().first >= a[i]) 44 | st.pop(); 45 | if(st.empty()) 46 | nsrIndex.push_back(pseudoIndex); 47 | else 48 | nsrIndex.push_back(st.top().second); 49 | } 50 | st.push({a[i], i}); 51 | } 52 | reverse(nsrIndex.begin(), nsrIndex.end()); 53 | return nsrIndex; 54 | } 55 | 56 | int main() { 57 | int t; 58 | cin>>t; 59 | while(t--){ 60 | int n; 61 | cin>>n; 62 | vector a(n), left, right, area(n); 63 | for(auto &it : a) cin>>it; 64 | 65 | left = nearestSmallerLeftIndex(a, n); 66 | right = nearestSmallerRightIndex(a, n); 67 | 68 | vector width(n); 69 | for(int i = 0; i < n; i++) 70 | width[i] = right[i] - left[i] - 1; 71 | 72 | for(int i = 0; i < n; i++) 73 | area[i] = a[i] * width[i]; 74 | 75 | int maxArea = *max_element(area.begin(), area.end()); 76 | cout< max) { 27 | max = j - i + 1; 28 | } 29 | } 30 | } 31 | } 32 | return max; 33 | } 34 | }; 35 | 36 | /*Approach 2 : Using Stack 37 | In this approach we initialize stack by pushing -1. -1 acts as a base for the next valid 38 | substring and then we store indexes of the opening braces encountered in the stack. As 39 | soon as we encounter a closing bracket we pop the index stored at the top and if while 40 | popping, the stack is not empty that means there exists a boundary or base index then we can 41 | calculate the length by subtracting current index with the stack's top. 42 | Time Complexity : O(n) 43 | Space Complexity : O(n) 44 | 45 | */ 46 | 47 | class Solution { 48 | public: 49 | int findMaxLen(string s) { 50 | stack st; 51 | int res = 0; 52 | st.push(-1); 53 | for(int i = 0; i < s.length(); i++){ 54 | if(s[i] == '(') 55 | st.push(i); 56 | else{ 57 | st.pop(); 58 | if(st.empty()) 59 | st.push(i); 60 | else 61 | res = max(res, i-st.top()); 62 | } 63 | } 64 | return res; 65 | } 66 | }; 67 | 68 | /* Approach 3 : Without extra space. 69 | 70 | Time Complexity : O(n) 71 | Space Complexity : O(1) 72 | 73 | */ 74 | class Solution { 75 | public: 76 | int findMaxLen(string s) { 77 | int left = 0, right = 0, maxlength = 0; 78 | for (int i = 0; i < s.length(); i++) { 79 | if (s[i] == '(') 80 | left++; 81 | else 82 | right++; 83 | 84 | if (left == right) 85 | maxlength = max(maxlength, 2 * right); 86 | else if (right >= left) 87 | left = right = 0; 88 | 89 | } 90 | left = right = 0; 91 | for (int i = s.length() - 1; i >= 0; i--) { 92 | if (s[i] == '(') 93 | left++; 94 | else 95 | right++; 96 | 97 | if (left == right) 98 | maxlength = max(maxlength, 2 * left); 99 | else if (left >= right) 100 | left = right = 0; 101 | } 102 | return maxlength; 103 | } 104 | }; 105 | -------------------------------------------------------------------------------- /Stacks&Queues/19_ExpressionContainsRedundantBracketOrNot.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tarunsinghdev/DSA-CRACKER/6816916b2f4041180699f3208940d36ecee7ae15/Stacks&Queues/19_ExpressionContainsRedundantBracketOrNot.cpp -------------------------------------------------------------------------------- /Stacks&Queues/1_ImplementStackFromScratch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int mystack[101]; 5 | int top = -1; 6 | 7 | void push(){ 8 | if(top == 102) 9 | cout<<"Can't push, Overflow!"<>elt; 14 | mystack[++top] = elt; 15 | } 16 | } 17 | 18 | void pop(){ 19 | if(top == -1) 20 | cout<<"No element, Can't pop"<>x; 43 | switch(x){ 44 | case 1 : push(); 45 | break; 46 | case 2 : pop(); 47 | break; 48 | case 3 : display(); 49 | break; 50 | case 4 : exit(0); 51 | default : cout<<"Enter correct choice"< 4 | #define size 5 5 | using namespace std; 6 | 7 | int myqueue[size]; 8 | int front = -1, rear = -1; 9 | 10 | void enqueue(int elt){ 11 | if((rear+1)%size == front){ 12 | cout<<"Queue full, Can't push"<>x; 57 | switch(x){ 58 | case 1 : int elt; 59 | cout<<"Enter element to be enqueued"<>elt; 61 | enqueue(elt); 62 | break; 63 | case 2 : dequeue(); 64 | break; 65 | case 3 : display(); 66 | break; 67 | case 4 : exit(0); 68 | default : cout<<"Enter correct choice"< 2 | using namespace std; 3 | 4 | // Function that finds the middle of the stack of size n. Current is current position we’re on 5 | int middle; 6 | void findMiddle(stack &s, int n,int current){ 7 | // If stack becomes empty or all items already are traversed 8 | if (s.empty() || current == n){ 9 | return; 10 | } 11 | 12 | // Remove current item 13 | int x = s.top(); 14 | s.pop(); 15 | 16 | // Call for removing the other items 17 | findMiddle(s, n, current+1); 18 | 19 | // Find the middle 20 | if (current == n/2){ 21 | middle = x; 22 | } 23 | 24 | } 25 | 26 | int main(){ 27 | stack s; 28 | 29 | //push elements into the stack 30 | s.push(5); 31 | s.push(6); 32 | s.push(7); 33 | s.push(8); 34 | s.push(9); 35 | s.push(10); 36 | s.push(11); 37 | int current = 0; 38 | findMiddle(s, s.size(),current); 39 | 40 | // Printing the middle element. 41 | cout< 2 | using namespace std; 3 | #define k 3 4 | #define n 10 5 | //Approach : In this we take two extra arrays, one for the top indexes of k stacks in top[k] array and 6 | // other in the next[n] array which stores the next item index for the k stacks 7 | 8 | /*Solve it in your notebook and you'll get it.*/ 9 | 10 | int top[k]; //Global variables automatically gets initialized to zero. 11 | int next_pos[n]; 12 | int arr[n]; 13 | int free_pos; 14 | 15 | void push(int data, int sn){ 16 | if(free_pos == -1){ 17 | cout<<"Stack Overflow"< 5 | using namespace std; 6 | 7 | int main() { 8 | int t; cin>>t; 9 | while(t--){ 10 | string s; 11 | cin>>s; 12 | stack st; 13 | int n = s.length(); 14 | int flag = 0; 15 | for(int i = 0; i < n; i++){ 16 | if(s[i] == '(' or s[i] == '{' or s[i] == '[') 17 | st.push(s[i]); 18 | else{ 19 | if(!st.empty() && ((s[i] == ')' && st.top() == '(') or (s[i] == '}' && st.top() == '{') or (s[i] == ']' && st.top() == '['))) 20 | st.pop(); 21 | else{ 22 | flag = 1; 23 | break; //Breaks if a pair of opening bracket is not found at top of the stack and also it breaks when first element 24 | //is itself a closing bracket 25 | } 26 | } 27 | } 28 | if(flag){ //Case when first element in the string is itself a closing bracket in that case stack will be empty and only in 29 | // this case the empty stack will print "not balanced" 30 | cout<<"not balanced"< st; 7 | for(int i = 0; i < len; i++){ 8 | st.push(str[i]); 9 | } 10 | 11 | for(int i = 0; i < len; i++){ 12 | str[i] = st.top(); 13 | st.pop(); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Stacks&Queues/8_DesignAStackThatSupportsgetMinInO1TimeAndO1ExtraSpace.cpp: -------------------------------------------------------------------------------- 1 | /*Approach 1 : This solution uses an auxiliary stack named mindata. 2 | Now we have two stacks with us, one stack 's'(already given in the template) which will 3 | be our main stack and other 'mindata' which will hold the current minimum value while we 4 | push elements to the main stack. 5 | First, both the stacks will be empty so we push the first element into both the stacks. 6 | Then, we keep pushing the data on our main stack and push elements in the mindata stack only 7 | if the element is less or equal to the top of the minstack. 8 | While popping we pop from the main stack as usual but we pop from the mindata stack only 9 | when element at the top of mindata stack is equal to the top of the main stack which we are 10 | currently popping. 11 | Thus, we can obtain getMin() in O(1) by accessing the top of our mindata stack. 12 | 13 | 14 | Time Complexity : push : O(1) 15 | pop : O(1) 16 | getMin : O(1) 17 | Space Complexity : O(n) 18 | 19 | */ 20 | stack mindata; 21 | 22 | /*Complete the function(s) below*/ 23 | void push(int a) 24 | { 25 | s.push(a); 26 | if(mindata.size() == 0 || a <= mindata.top()) 27 | mindata.push(a); 28 | } 29 | 30 | bool isFull(int n) 31 | { 32 | return s.size() == n ? true : false; 33 | 34 | } 35 | 36 | bool isEmpty() 37 | { 38 | return s.empty(); 39 | } 40 | 41 | int pop() 42 | { int val = s.top(); 43 | s.pop(); 44 | if(val == mindata.top()) 45 | mindata.pop(); 46 | } 47 | 48 | int getMin() 49 | { 50 | return mindata.top(); 51 | } 52 | 53 | /* Approach 2 : In this, to be able to achieve O(1) getMin() functionality we do some smart work here. 54 | So every time we call our getMin() function it should return us the "current" minimum value 55 | in the stack. 56 | Every time we push an element into our stack we update our "mn" minimum value variable. 57 | Now the problem lies in the fact that while popping how can we know the current minimum 58 | value in the stack as it may be possible that we have popped out the minimum value we 59 | calculated from the stack. Now the value our "mn" minimum variable holds is not our 60 | minimum value as it has been pop out from the stack. How can we find the previous minimum 61 | value or retrieve the previous minimum value from the "mn variable". We apply a simple 62 | trick. 63 | Let's rewind, when we are pushing our elements normally into the stack we at the same time 64 | are maintaining our "mn" variable with the minimum value i.e as soon as we encounter an 65 | element which is lesser than current minimum we update our "mn" variable. Here also we 66 | update our minimum variable but instead of pushing the minimum value encountered into the 67 | stack we push a fake value which is even lesser than the minimum value we have got with the 68 | equation val + (val - min). This equation will make sure that fake value is smaller than 69 | the minimum value. 70 | Why is it so? As explained earlier we need to know current minimum value of the stack. 71 | It may be possible the calculated value has been popped out and to retrieve the 72 | previous value we find it by the equation 2 * min - val. 73 | Proof for the equations : 74 | Suppose you have your current minimum value as v which earlier was mn but now has been 75 | changed as we encounter new minimum. Now we this v as v + (v-mn) in the stack as minimum 76 | value. 77 | Now if we pop out this fake value we know that since this fake value will we lesser 78 | than our minimum value our minimum value must have been updated at this time. 79 | Now we retrieve our previous minimum value by subtracting 2*current minimum(which is v 80 | here) - fake value i.e 81 | 2* v - (v + (v-mn)) = mn which is our previous minimum value and we have retrieved 82 | it back successfully by the simple trick. 83 | If you have come this far make sure to star this repo. and text me on linkedin that 84 | you have understood. 85 | 86 | Time Complexity : push : O(1) 87 | pop : O(1) 88 | getMin : O(1) 89 | 90 | Space Complexity : O(1) 91 | 92 | */ 93 | 94 | int mn; 95 | 96 | void push(int a) 97 | { if(s.size() == 0){ 98 | s.push(a); 99 | mn = a; 100 | } 101 | else if(a >= mn) 102 | s.push(a); 103 | else{ 104 | s.push(a + (a - mn)); //We store fake value in the stack which will be later 105 | //required in the pop function to retrieve our previous min value 106 | mn = a; //Here we store the original minimum value in 'mn' variable and stores a fake value in the stack making it act as flag. 107 | // Note that fake value is even smaller than our original minimum value currently. 108 | } 109 | 110 | } 111 | 112 | bool isFull(int n) 113 | { 114 | return s.size() == n ? true : false; 115 | 116 | } 117 | 118 | bool isEmpty() 119 | { 120 | return s.empty(); 121 | } 122 | 123 | int pop() 124 | { int x = s.top(); 125 | if(x >= mn){ 126 | s.pop(); 127 | return x; 128 | } 129 | else{ 130 | s.pop(); 131 | mn = 2*mn - x; 132 | return mn; 133 | } 134 | } 135 | 136 | int getMin() 137 | { 138 | return mn; 139 | } 140 | -------------------------------------------------------------------------------- /Stacks&Queues/9_FindTheNextGreaterElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define ll long long 3 | using namespace std; 4 | 5 | int main() { 6 | //code 7 | int t; 8 | cin>>t; 9 | while(t--){ 10 | int n; 11 | cin>>n; 12 | vector A(n), ans; 13 | for(auto &it : A) cin>>it; 14 | stack st; 15 | for(int i = n-1; i >= 0; i--){ 16 | if(st.size() == 0) 17 | ans.push_back(-1); 18 | else if(st.size() > 0 && st.top() > A[i]) 19 | ans.push_back(st.top()); 20 | else if(st.size() > 0 && st.top() <= A[i]){ 21 | while(!st.empty() && st.top() <= A[i]){ 22 | st.pop(); 23 | } 24 | if(st.empty()) 25 | ans.push_back(-1); 26 | else 27 | ans.push_back(st.top()); 28 | } 29 | st.push(A[i]); 30 | } 31 | reverse(ans.begin(), ans.end()); 32 | for(auto x : ans) 33 | cout<