├── Arrays ├── 4SumProblem.cpp ├── KadaneAlgo.cpp ├── BestTimetoBuyandSellStock.cpp ├── RotateImage.cpp ├── duplicateNumber.cpp ├── countNumberofSubarrayWithXorasK.cpp ├── TwoSumProblem.cpp ├── longestSubstringWithoutRepeatingChars.cpp ├── largestSubbarayWithZeroSum.cpp ├── NextPermutation.cpp ├── GridUniquePaths.cpp ├── sliding_window.cpp ├── MajorityElement.cpp ├── SingleElementInSortedArray.cpp ├── PascalTriangle.cpp ├── LongestConsecutiveSeq.cpp ├── Powxn.cpp ├── SortanArray0f0s1sand2s.cpp ├── SetMatrixZeroes.cpp ├── MajorityElement2.cpp ├── SearchIn2DMatrix.cpp ├── selection.cpp ├── reversepairs.cpp ├── mergeIntervals.cpp ├── bubble.cpp ├── MergeTwoSortedArraysWithoutExtraSpace.cpp ├── insertion.cpp ├── CountInversions.cpp └── FindTheMissingAndRepeatingNumber.cpp ├── Hashing ├── LFUCache.cpp ├── LRUCache.cpp ├── TwoSum.cpp ├── LargestSubarraywithSumZero.cpp ├── LongestConsecutiveSequence.cpp ├── LongestSubstringWithoutRepeatingCharacters.cpp ├── 4Sum.cpp └── CountSubarraysWithXorasK.cpp ├── 2Pointer ├── ReversePairs.cpp ├── MaxConsecutiveOnes.cpp ├── RemoveDuplicatesFromSortedArray.cpp └── TrappingRainwater.cpp ├── LinkedList ├── MiddleofTheLL.cpp ├── ReverseLL.cpp ├── DetectACycleInLL.cpp ├── RemoveNthNodeFromEndofLL.cpp ├── IntersectionPointofTwoLL.cpp ├── AddAsLL.cpp ├── MergeTwoSortedLL.cpp ├── ReverseNodesinKGroup.cpp ├── FindTheStartingPointofTheCycle.cpp ├── DeletioninLL.cpp ├── PalindromeLL.cpp ├── OddEvenLinkedList.cpp ├── FlattenALL.cpp ├── LLImplementationofQueues.cpp ├── DLL.cpp ├── cloneLL.cpp ├── RotateaLL.cpp └── CLL.cpp ├── Readme.md ├── Trees ├── searchInBst.cpp ├── maxDepth.cpp ├── isSymmetric.cpp ├── ceilBst.cpp ├── floorInBst.cpp ├── preorder.cpp ├── lcaBST.cpp ├── RightViewOfBinaryTree.cpp ├── diameterOfTree.Cpp ├── maximumPathSum.cpp ├── isBTBalanced.Cpp ├── MaximumBinaryTree.cpp ├── terativePreorderTraversal.Cpp ├── lca.cpp ├── iterativeTraversalInorder.cpp ├── insertBST.cpp ├── kThSmallestBst.cpp ├── LevelOrderTraversal.cpp ├── isBSTIterative.cpp ├── iterativePostOrderTraversal2Stack.cpp ├── bottomViewOfBt.cpp ├── topViewOfBt.cpp ├── constructBtFromPreOrderandInorder.cpp ├── BuildBtfromPostOrderandInOrder.cpp ├── verticalOrderTraversal.cpp ├── iterativePostOrder1Stack.cpp ├── KthElementBstMorris.cpp ├── ZigZagLevelOrderTraversal.cpp ├── boundaryTraversal.cpp ├── SeriaLizeAndDeseriaLize.cpp ├── Alltraversals.cpp └── timeToBurnATree.cpp ├── Stacks_Queues ├── reverseaSentenceUsingStack.cpp ├── ReverseaStack.cpp ├── SlidingWindow.cpp ├── NextGreaterElement.cpp ├── StackusingSingleQueue.cpp ├── validParenthesis.cpp ├── LargestRectangeHistogram.cpp ├── stack_using_vector.cpp ├── StackusingQueue.cpp ├── QueueUsingStack.cpp ├── RottenOranges.cpp ├── StacksUsingArrays.cpp ├── StackUsingLinkedList.cpp ├── two_stack_in_array.cpp ├── infixtopostfixusingstacks.cpp ├── LRU.cpp ├── QueueUsingArrays.cpp └── LFU.cpp ├── Strings ├── ReverseWordsInAString.cpp ├── LongestCommonPrefix.cpp ├── KMP.cpp └── RabinKarp.cpp ├── DP ├── MinCostPath.cpp ├── MaxProductSubarray.cpp ├── LIS.cpp ├── coinchange.cpp ├── Editdistance.cpp ├── LCS.cpp ├── 01Knapsack.cpp ├── EggDropping.cpp ├── RodCuttingProblem.cpp ├── MCM.cpp └── WordBreak.cpp ├── BinarySearch ├── SingleElementSortedArray.cpp ├── MatrixMedian.cpp ├── NthRootOfANumber.cpp ├── searchInSortedRotatedArray.cpp ├── KthElementOfTwoSortedArrays.cpp ├── AggressiveCows.cpp ├── BooksAllocation.cpp └── MedianOfTwoSortedArrays.cpp ├── Bit └── PowerSet.cpp ├── Graphs ├── shortestPathUndirectedUnweightedGraph.cpp ├── bipartiteGraphDfs.cpp ├── BellmanFord.cpp ├── DFS.cpp ├── BFS.cpp ├── FlloydWarshall.cpp ├── TopologicalSortBFS-Kahn's_Algo.cpp ├── checkCycleDGBFS.cpp ├── cycleCheckUGDfs.cpp ├── bipartiteGraphBfs.cpp ├── Djikistra's_Algo.cpp ├── Kosarajau.cpp ├── cycleCheckDGDfs.cpp ├── KrusKals.cpp ├── cycleCheckUGBfs.cpp ├── TopologicalSortDFS.cpp ├── Prims.cpp └── NumberOfIslands.cpp ├── Greedy ├── MinimumCoins.cpp ├── MinimumPlatforms.cpp ├── JobSequencingProblem.cpp ├── FractionalKnapsack.cpp └── NMeetingsInOneRoom.cpp └── Recursion_Backtracking ├── subsetSum.cpp ├── subsetsSum2.cpp ├── kthPermutationSequence.cpp ├── MColoring.cpp ├── CombinationSum2.cpp ├── CombinationSum.cpp ├── printSequence.cpp ├── PalindromePartitioning.cpp ├── SudokuSolver.cpp ├── NQueen.cpp └── RatInAMaze.cpp /Arrays/4SumProblem.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Hashing/LFUCache.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Hashing/LRUCache.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /2Pointer/ReversePairs.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /LinkedList/MiddleofTheLL.cpp: -------------------------------------------------------------------------------- 1 | ListNode *middleNode(ListNode *head){ 2 | ListNode *slow = head; 3 | ListNode *fast = head; 4 | while(fast !=NULL && fast->next!=NULL){ 5 | slow=slow->next; 6 | fast=fast->next->next; 7 | } 8 | return slow; 9 | } -------------------------------------------------------------------------------- /Arrays/KadaneAlgo.cpp: -------------------------------------------------------------------------------- 1 | int maxSubarray(vector &nums){ 2 | int sum = 0; 3 | int maxi = INT_MIN; 4 | for(auto it:nums){ 5 | sum+=it; 6 | maxi=max(sum,maxi); 7 | if(sum<0){ 8 | sum=0; 9 | } 10 | } 11 | 12 | return maxi; 13 | 14 | } -------------------------------------------------------------------------------- /LinkedList/ReverseLL.cpp: -------------------------------------------------------------------------------- 1 | node *reverseRecur(node* &head){ 2 | if(head==NULL || head->next==NULL){ 3 | return head; 4 | } 5 | node *newHead = reverseRecur(head->next); 6 | head->next->next=head; 7 | head->next=NULL; 8 | 9 | return newHead; 10 | } -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Striver SDE Sheet 2 | > Programming is today's language of creativity 3 | 4 | ### This repository encapsulates complete solution of the well known 'Striver SDE Sheet ' in C++ 5 | 6 | ### Feel free to contribute with optimize code and documentation(comments). -------------------------------------------------------------------------------- /Arrays/BestTimetoBuyandSellStock.cpp: -------------------------------------------------------------------------------- 1 | int maxProfit(vector &nums){ 2 | int maxPro=0; 3 | int minPrice=INT_MAX; 4 | for(int i=0;i> &m){ 2 | int n = m.size(); 3 | 4 | for(int i=0;ival != val){ 5 | root = valval? root->left:root->right; 6 | } 7 | return root; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Stacks_Queues/reverseaSentenceUsingStack.cpp: -------------------------------------------------------------------------------- 1 | void reverseSentence(string s){ 2 | stacks; 3 | for(int i=0;ileft); 7 | int rh = maxDepth(root->right); 8 | 9 | return 1 + max(lh, rh); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Arrays/duplicateNumber.cpp: -------------------------------------------------------------------------------- 1 | int findDuplicate(vector &nums){ 2 | int slow = nums[0]; 3 | int fast = nums[0]; 4 | 5 | do{ 6 | slow=nums[slow]; 7 | fast = nums[nums[fast]]; 8 | } 9 | while(slow!=fast); 10 | 11 | fast=nums[0]; 12 | 13 | while(slow!=fast){ 14 | slow=nums[slow]; 15 | fast=nums[fast]; 16 | } 17 | 18 | return fast; 19 | } -------------------------------------------------------------------------------- /Arrays/countNumberofSubarrayWithXorasK.cpp: -------------------------------------------------------------------------------- 1 | int solve(vector&a,int b){ 2 | mapfreq; 3 | 4 | int c=0; 5 | int xorr=0; 6 | 7 | for(auto it:a){ 8 | xorr=xorr^it; 9 | 10 | if(xorr==b){ 11 | c++; 12 | } 13 | 14 | if(freq.find(xorr^b)!=freq.end()){ 15 | c+=freq[xorr^b]; 16 | } 17 | 18 | freq[xorr]+=1; 19 | } 20 | 21 | 22 | return c; 23 | } -------------------------------------------------------------------------------- /Arrays/TwoSumProblem.cpp: -------------------------------------------------------------------------------- 1 | vectortwoSum(vector &nums , int target){ 2 | vector ans; 3 | unordered_mapmpp; 4 | for(int i=0;itwoSums(vector&nums,int target){ 3 | vectorans; 4 | unordered_mapm; 5 | for(int i=0;inext==NULL){ 3 | return false; 4 | } 5 | 6 | ListNode *fast=head; 7 | ListNode *slow =head; 8 | 9 | 10 | while(fast->next && fast->next->next){ 11 | fast=fast->next->next; 12 | slow=slow->next; 13 | if(fast==slow){ 14 | return true; 15 | } 16 | 17 | } 18 | return false; 19 | } -------------------------------------------------------------------------------- /2Pointer/MaxConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int findMaxConsOnes(vector &nums){ 7 | int cnt=0; 8 | int maxi=0; 9 | for(int i=0;i mpp(256,-1); 3 | 4 | int left=0,right=0; 5 | 6 | int n=s.size(); 7 | 8 | int len=0; 9 | while(right 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int removeDuplicates(vector &nums){ 7 | if(nums.size()==0){ 8 | return 0; 9 | } 10 | 11 | int i=0; 12 | 13 | for(int j=1;jmpp; 3 | int maxi=0; 4 | int sum=0; 5 | 6 | for(int i=0;inext=head; 4 | ListNode*fast=start; 5 | ListNode *slow = start; 6 | 7 | for(int i=1;i<=n;i++){ 8 | fast=fast->next; 9 | } 10 | 11 | while(fast->next!=NULL){ 12 | fast=fast->next; 13 | slow=slow->next; 14 | } 15 | 16 | slow->next=slow->next->next; 17 | 18 | return start->next; 19 | 20 | } -------------------------------------------------------------------------------- /Strings/ReverseWordsInAString.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | string s[] = {"i", "like", "this", "program", "very", "much"}; 8 | 9 | string ans = ""; 10 | for (int i = 5; i >= 0; i--) 11 | { 12 | ans += s[i] + " "; 13 | } 14 | cout << ("Reversed String:") << endl; 15 | cout << (ans.substr(0, ans.length() - 1)) << endl; 16 | 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/NextPermutation.cpp: -------------------------------------------------------------------------------- 1 | void nextPerm(vector &nums){ 2 | int n = nums.size(),k,l; 3 | for(k=n-2;k>=0;k--){ 4 | if(nums[k]k;l--){ 14 | if(nums[l]>nums[k]){ 15 | break; 16 | } 17 | } 18 | 19 | swap(nums[k],nums[l]); 20 | reverse(nums.begin()+k+1,nums.end()); 21 | } 22 | } -------------------------------------------------------------------------------- /DP/MinCostPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int arr1[]={2,2,5,4,8}; 7 | int arr2[]={2,2,6,8,8}; 8 | 9 | int n=5; 10 | 11 | setans; 12 | 13 | for(int i=0;ival == root2->val) && f(root1->left, root2->right) && f(root1->right, root2->left); 7 | } 8 | bool isSymmetric(TreeNode* root) { 9 | if(!root) return true; 10 | return f(root->left, root->right); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /BinarySearch/SingleElementSortedArray.cpp: -------------------------------------------------------------------------------- 1 | int singleNonDuplicate(vector& nums) { 2 | int low = 0, high = nums.size() - 2; 3 | while(low <= high) { 4 | int mid = (low + high) >> 1; 5 | if(nums[mid] == nums[mid^1]) { 6 | low = mid + 1; 7 | } 8 | else { 9 | high = mid - 1; 10 | } 11 | } 12 | return nums[low]; 13 | } -------------------------------------------------------------------------------- /Stacks_Queues/ReverseaStack.cpp: -------------------------------------------------------------------------------- 1 | 2 | void insertAtBottom(stack &st,int ele){ 3 | 4 | if(st.empty()){ 5 | st.push(ele); 6 | return; 7 | } 8 | 9 | int topele=st.top(); 10 | st.pop(); 11 | insertAtBottom(st,ele); 12 | 13 | st.push(topele); 14 | } 15 | 16 | 17 | void reverse(stack &st){ 18 | 19 | if(st.empty()){ 20 | return; 21 | } 22 | 23 | int ele = st.top(); 24 | st.pop(); 25 | reverse(st); 26 | 27 | insertAtBottom(st,ele); 28 | } -------------------------------------------------------------------------------- /DP/MaxProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | 2 | int maxProduct(int* arr, int n){ 3 | int minVal = arr[0]; 4 | int maxVal = arr[0]; 5 | 6 | int maxProduct = arr[0]; 7 | 8 | for (int i = 1; i < n; i++) { 9 | 10 | 11 | if (arr[i] < 0){ 12 | swap(maxVal, minVal); 13 | } 14 | maxVal = max(arr[i], maxVal * arr[i]); 15 | minVal = min(arr[i], minVal * arr[i]); 16 | 17 | maxProduct = max(maxProduct, maxVal); 18 | } 19 | 20 | return maxProduct; 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /Arrays/GridUniquePaths.cpp: -------------------------------------------------------------------------------- 1 | // Lovebabbar , interview bit , leetcode , gfg , Code Library , CSES , Lead Coding , Kartik Arora 2 | // Fraz sheet , interview questions(sources,codeverse etc) , code n code , code with sunny , Riddhi Dutta DP & Trees Sheet 3 | 4 | 5 | int uniquePaths(int m , int n){ 6 | int N = n+m-2; 7 | int r = m-1; 8 | double res=1; 9 | 10 | for(int i=1;i<=r;i++){ 11 | res=res*(N-r+i)/i; 12 | } 13 | 14 | return int(res); 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /Arrays/sliding_window.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, s; 7 | cout<<"Enter the size of array: "; 8 | cin>>n; 9 | cout<<"Enter the size of window."; 10 | cin>>s; 11 | int A[n]; 12 | for(int i = 0; i < n; i++) 13 | cin>>A[i]; 14 | 15 | for(int j = 0; j <= n-s; j++) 16 | { 17 | for(int k = j; k *root, int key){ 2 | 3 | int ceil = -1; 4 | while (root) { 5 | 6 | if (root->data == key) { 7 | ceil = root->data; 8 | return ceil; 9 | } 10 | 11 | if (key > root->data) { 12 | root = root->right; 13 | } 14 | else { 15 | ceil = root->data; 16 | root = root->left; 17 | } 18 | } 19 | return ceil; 20 | } 21 | -------------------------------------------------------------------------------- /Trees/floorInBst.cpp: -------------------------------------------------------------------------------- 1 | int floorInBST(TreeNode * root, int key) 2 | { 3 | int floor = -1; 4 | while (root) { 5 | 6 | if (root->val == key) { 7 | floor = root->val; 8 | return floor; 9 | } 10 | 11 | if (key > root->val) { 12 | floor = root->val; 13 | root = root->right; 14 | } 15 | else { 16 | root = root->left; 17 | } 18 | } 19 | return floor; 20 | } 21 | -------------------------------------------------------------------------------- /Arrays/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | int majorityElement(vector& nums) { 2 | int count=0; 3 | int candidate=0; 4 | 5 | 6 | for(int num:nums){ 7 | if(count==0){ 8 | candidate=num; 9 | } 10 | if(num==candidate){ 11 | count+=1; 12 | }else{ 13 | count--; 14 | } 15 | 16 | } 17 | 18 | return candidate; 19 | } -------------------------------------------------------------------------------- /Trees/preorder.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | private: 4 | void dfs(TreeNode *node, vector &preorder) { 5 | if(node == NULL) return; 6 | 7 | preorder.push_back(node->val); 8 | dfs(node->left, preorder); 9 | dfs(node->right, preorder); 10 | } 11 | public: 12 | vector preorderTraversal(TreeNode* root) { 13 | vector preorder; 14 | dfs(root, preorder); 15 | return preorder; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Arrays/SingleElementInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int singleNonDuplicate(vector& nums) { 5 | int low = 0, high = nums.size() - 2; 6 | while(low <= high) { 7 | int mid = (low + high) >> 1; 8 | if(nums[mid] == nums[mid^1]) { 9 | low = mid + 1; 10 | } 11 | else { 12 | high = mid - 1; 13 | } 14 | } 15 | return nums[low]; 16 | } 17 | }; -------------------------------------------------------------------------------- /Trees/lcaBST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | if(!root) return NULL; 5 | int curr = root->val; 6 | if(curr < p->val && curr < q->val) { 7 | return lowestCommonAncestor(root->right, p, q); 8 | } 9 | if(curr > p->val && curr > q->val) { 10 | return lowestCommonAncestor(root->left, p, q); 11 | } 12 | return root; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Bit/PowerSet.cpp: -------------------------------------------------------------------------------- 1 | vector AllPossibleStrings(string s){ 2 | int n = s.size(); 3 | vector ans; 4 | for(int num = 0; num < (1 << n); num++) { 5 | string sub = ""; 6 | for(int i = 0;i 0) 12 | ans.push_back(sub); 13 | } 14 | sort(ans.begin(), ans.end()); 15 | return ans; 16 | } -------------------------------------------------------------------------------- /Hashing/LargestSubarraywithSumZero.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxLen(int arr[],int n){ 5 | unordered_mapmpp; 6 | int maxi=0; 7 | int sum=0; 8 | for(int i=0;i &res) 4 | { 5 | if(root==NULL) return ; 6 | if(res.size()==level) res.push_back(root->val); 7 | recursion(root->right, level+1, res); 8 | recursion(root->left, level+1, res); 9 | } 10 | 11 | vector rightSideView(TreeNode *root) { 12 | vector res; 13 | recursion(root, 0, res); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LinkedList/IntersectionPointofTwoLL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 4 | if(headA==NULL || headB == NULL){ 5 | return NULL; 6 | } 7 | 8 | ListNode*a = headA; 9 | ListNode*b = headB; 10 | 11 | while(a!=b){ 12 | a=a==NULL ? headB : a->next; 13 | b=b==NULL ? headA : b->next; 14 | } 15 | 16 | return a; 17 | 18 | 19 | } 20 | }; -------------------------------------------------------------------------------- /Arrays/PascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector> generate(int numRows) { 5 | vector> r(numRows); 6 | for(int i=0;i 2 | using namespace std; 3 | 4 | int lis(int arr[],int n){ 5 | vectorseq; 6 | seq.push_back(arr[0]); 7 | for(int i=1;ileft, diameter); 14 | int rh = height(node->right, diameter); 15 | diameter = max(diameter, lh + rh); 16 | return 1 + max(lh, rh); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Trees/maximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPathSum(TreeNode* root) { 4 | int maxi = INT_MIN; 5 | maxPathDown(root, maxi); 6 | return maxi; 7 | } 8 | 9 | int maxPathDown(TreeNode* node, int &maxi) { 10 | if (node == NULL) return 0; 11 | int left = max(0, maxPathDown(node->left, maxi)); 12 | int right = max(0, maxPathDown(node->right, maxi)); 13 | maxi = max(maxi, left + right + node->val); 14 | return max(left, right) + node->val; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Strings/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | string longestCommonPrefix(vector& strs) { 2 | assert(strs.size() > 0); 3 | 4 | string result = strs[0]; 5 | 6 | for (int i = 1; i < strs.size(); i++) 7 | { 8 | for (int j = 0; j < result.size(); j++) 9 | { 10 | if (result[j] != strs[i][j]) 11 | { 12 | result.erase(j, result.size() - j); 13 | } 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | -------------------------------------------------------------------------------- /Arrays/LongestConsecutiveSeq.cpp: -------------------------------------------------------------------------------- 1 | int longestConsecutive(vector &nums){ 2 | set hashSet; 3 | for(int num:nums){ 4 | hashSet.insert(num); 5 | } 6 | 7 | int longestStreak=0; 8 | 9 | 10 | for(int nums:nums){ 11 | if(!hashSet.count(num-1)){ 12 | int currentNum=num; 13 | int currentStreak=1; 14 | 15 | while(hashSet.count(currentNum+1)){ 16 | currentNum+=1; 17 | currentStreak+=1; 18 | } 19 | 20 | longestStreak=max(longestStreak,currentStreak); 21 | 22 | 23 | } 24 | } 25 | return longestStreak; 26 | } 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Graphs/shortestPathUndirectedUnweightedGraph.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | void BFS(vector adj[], int N, int src) 4 | { 5 | int dist[N]; 6 | for(int i = 0;i q; 8 | 9 | dist[src] = 0; 10 | q.push(src); 11 | 12 | while(q.empty()==false) 13 | { 14 | int node = q.front(); 15 | q.pop(); 16 | 17 | for(auto it:adj[node]){ 18 | if(dist[node] + 1 < dist[it]){ 19 | dist[it]=dist[node]+1; 20 | q.push(it); 21 | } 22 | } 23 | } 24 | for(int i = 0;ival; 10 | l1=l1->next; 11 | } 12 | 13 | if(l2 != NULL){ 14 | sum+=l2->val; 15 | l2=l2->next; 16 | } 17 | 18 | sum+=carry; 19 | carry=sum/10; 20 | ListNode *node = new ListNode(sum % 10); 21 | temp->next = node; 22 | temp= temp->next; 23 | } 24 | 25 | return dummy->next; 26 | } 27 | -------------------------------------------------------------------------------- /Stacks_Queues/SlidingWindow.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | deque dq; 5 | vector ans; 6 | for (int i=0; i=k-1) ans.push_back(nums[dq.front()]); 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Arrays/Powxn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | double anss =1.0; 5 | long long ans = n; 6 | if(ans<0){ 7 | ans=-1*ans; 8 | } 9 | while(ans){ 10 | if(ans%2){ 11 | anss=anss*x; 12 | ans=ans-1; 13 | }else{ 14 | x=x*x; 15 | ans=ans/2; 16 | } 17 | } 18 | 19 | if(n<0){ 20 | anss = double(1.0)/double(anss); 21 | } 22 | return anss; 23 | } 24 | }; -------------------------------------------------------------------------------- /Greedy/MinimumCoins.cpp: -------------------------------------------------------------------------------- 1 | 2 | int deno[] = { 1, 2, 5, 10, 20, 3 | 50, 100, 500, 1000 }; 4 | int n = sizeof(deno) / sizeof(deno[0]); 5 | 6 | void findMin(int V) 7 | { 8 | sort(deno, deno + n); 9 | 10 | // Initialize result 11 | vector ans; 12 | 13 | // Traverse through all denomination 14 | for (int i = n - 1; i >= 0; i--) { 15 | 16 | // Find denominations 17 | while (V >= deno[i]) { 18 | V -= deno[i]; 19 | ans.push_back(deno[i]); 20 | } 21 | } 22 | 23 | // Print result 24 | for (int i = 0; i < ans.size(); i++) 25 | cout << ans[i] << " "; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Stacks_Queues/NextGreaterElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | int n = nums.size(); 5 | vector nge(n, -1); 6 | stack st; 7 | for(int i = 2*n-1;i>=0;i--) { 8 | while(!st.empty() && st.top() <= nums[i%n]) { 9 | st.pop(); 10 | } 11 | 12 | if(i left); 10 | if (leftHeight == -1) return -1; 11 | int rightHeight = dfsHeight (root -> right); 12 | if (rightHeight == -1) return -1; 13 | 14 | if (abs(leftHeight - rightHeight) > 1) return -1; 15 | return max (leftHeight, rightHeight) + 1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Greedy/MinimumPlatforms.cpp: -------------------------------------------------------------------------------- 1 | int findPlatform(int arr[], int dep[], int n) 2 | { 3 | sort(arr, arr+n); 4 | sort(dep, dep+n); 5 | 6 | int plat_needed = 1, result = 1; 7 | int i = 1, j = 0; 8 | 9 | while (i < n && j < n) { 10 | if (arr[i] <= dep[j]) { 11 | plat_needed++; 12 | i++; 13 | } 14 | 15 | else if (arr[i] > dep[j]) { 16 | plat_needed--; 17 | j++; 18 | } 19 | 20 | if (plat_needed > result) 21 | result = plat_needed; 22 | } 23 | 24 | return result; 25 | } -------------------------------------------------------------------------------- /Arrays/SortanArray0f0s1sand2s.cpp: -------------------------------------------------------------------------------- 1 | 2 | void sortColors(vector& nums) { 3 | int lo = 0; 4 | int hi = nums.size() - 1; 5 | int mid = 0; 6 | 7 | while (mid <= hi) { 8 | switch (nums[mid]) { 9 | 10 | case 0: 11 | swap(nums[lo++], nums[mid++]); 12 | break; 13 | 14 | 15 | case 1: 16 | mid++; 17 | break; 18 | 19 | 20 | case 2: 21 | swap(nums[mid], nums[hi--]); 22 | break; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Stacks_Queues/StackusingSingleQueue.cpp: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | public: 3 | 4 | queue que; 5 | 6 | MyStack() { 7 | 8 | } 9 | 10 | 11 | void push(int x) { 12 | que.push(x); 13 | for(int i=0;ist; 5 | for(auto it: s) { 6 | if(it=='(' || it=='{' || it == '[') st.push(it); 7 | else { 8 | if(st.size() == 0) return false; 9 | char ch = st.top(); 10 | st.pop(); 11 | if((it == ')' and ch == '(') or (it == ']' and ch == '[') or (it == '}' and ch == '{')) 12 | continue; 13 | else return false; 14 | } 15 | } 16 | return st.empty(); 17 | } 18 | }; -------------------------------------------------------------------------------- /Arrays/SetMatrixZeroes.cpp: -------------------------------------------------------------------------------- 1 | void setZeroes(vector>& matrix) { 2 | int col0 = 1, rows = matrix.size(), cols = matrix[0].size(); 3 | 4 | for (int i = 0; i < rows; i++) { 5 | if (matrix[i][0] == 0) col0 = 0; 6 | for (int j = 1; j < cols; j++) 7 | if (matrix[i][j] == 0) 8 | matrix[i][0] = matrix[0][j] = 0; 9 | } 10 | 11 | for (int i = rows - 1; i >= 0; i--) { 12 | for (int j = cols - 1; j >= 1; j--) 13 | if (matrix[i][0] == 0 || matrix[0][j] == 0) 14 | matrix[i][j] = 0; 15 | if (col0 == 0) matrix[i][0] = 0; 16 | } 17 | } -------------------------------------------------------------------------------- /Trees/MaximumBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* constructMaximumBinaryTree(vector& nums) { 4 | vector stk; 5 | for (int i = 0; i < nums.size(); ++i) 6 | { 7 | TreeNode* cur = new TreeNode(nums[i]); 8 | while (!stk.empty() && stk.back()->val < nums[i]) 9 | { 10 | cur->left = stk.back(); 11 | stk.pop_back(); 12 | } 13 | if (!stk.empty()) 14 | stk.back()->right = cur; 15 | stk.push_back(cur); 16 | } 17 | return stk.front(); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Hashing/LongestConsecutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int longestConsSum(vector& nums){ 6 | sethashset; 7 | for(int num:nums){ 8 | hashset.insert(num); 9 | } 10 | 11 | int longestStreak=0; 12 | for(int num:nums){ 13 | if(!hashset.count(num-1)){ 14 | int currentnum=num; 15 | int currentStreak=1; 16 | while(hashset.count(currentnum+1)){ 17 | currentnum+=1; 18 | currentStreak+=1; 19 | } 20 | 21 | longestStreak=max(longestStreak,currentStreak); 22 | } 23 | } 24 | 25 | return longestStreak; 26 | } 27 | 28 | int main(){ 29 | 30 | 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /DP/coinchange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int count(int ind , int sum , int s[], int n , vector>&dp){ 6 | if(sum==0){ 7 | return 1; 8 | } 9 | 10 | if(ind>=n || sum < 0){ 11 | return 0; 12 | } 13 | 14 | if(dp[ind][sum]!=-1){ 15 | return dp[ind][sum]; 16 | } 17 | 18 | int left = count(ind,sum-s[ind],s,n); 19 | int right = count(ind+1,sum,s,n); 20 | 21 | 22 | return dp[ind][sum]=left+right; 23 | } 24 | 25 | 26 | int main(){ 27 | 28 | int s[]={1,2}; 29 | int sum=4; 30 | int n=2; 31 | vector>dp(n,vector(sum+1,-1)); 32 | 33 | cout<val > l2->val){ 10 | swap(l1,l2); 11 | } 12 | ListNode* res=l1; 13 | while(l1!=NULL && l2!=NULL){ 14 | ListNode* temp = NULL; 15 | while(l1!=NULL && l1->val <= l2->val){ 16 | temp=l1; 17 | l1=l1->next; 18 | } 19 | temp->next=l2; 20 | swap(l1,l2); 21 | } 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /Trees/terativePreorderTraversal.Cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | vector preorderTraversal(TreeNode* root) { 5 | vector preorder; 6 | if(root == NULL) return preorder; 7 | 8 | stack st; 9 | st.push(root); 10 | while(!st.empty()){ 11 | root = st.top(); 12 | st.pop(); 13 | preorder.push_back(root->val); 14 | if(root->right != NULL){ 15 | st.push(root->right); 16 | } 17 | if(root->left!= NULL){ 18 | st.push(root->left); 19 | } 20 | } 21 | return preorder; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /2Pointer/TrappingRainwater.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int water(vector &height){ 7 | int left=0; 8 | int right=n-1; 9 | int res=0; 10 | int maxLeft=0; 11 | int maxRight=0; 12 | 13 | 14 | while(left<=right){ 15 | if(height[left]<=height[right]){ 16 | if(height[left]<=maxLeft){ 17 | maxLeft=height[left]; 18 | }else{ 19 | res+=maxLeft-height[left]; 20 | } 21 | left++; 22 | }else{ 23 | if(height[right]>=maxRight){ 24 | maxRight=height[right]; 25 | }else{ 26 | res+=maxRight-height[right]; 27 | } 28 | right--; 29 | } 30 | } 31 | 32 | return res; 33 | } 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /Trees/lca.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | //base case 5 | if (root == NULL || root == p || root == q) { 6 | return root; 7 | } 8 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 9 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 10 | 11 | //result 12 | if(left == NULL) { 13 | return right; 14 | } 15 | else if(right == NULL) { 16 | return left; 17 | } 18 | else { //both left and right are not null, we found our result 19 | return root; 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Trees/iterativeTraversalInorder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | vector inorderTraversal(TreeNode* root) { 5 | stack st; 6 | TreeNode* node = root; 7 | vector inorder; 8 | while(true) { 9 | if(node != NULL) { 10 | st.push(node); 11 | node = node->left; 12 | } 13 | else { 14 | 15 | if(st.empty() == true) break; 16 | node = st.top(); 17 | st.pop(); 18 | inorder.push_back(node->val); 19 | node = node->right; 20 | } 21 | } 22 | return inorder; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Arrays/MajorityElement2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector majorityElement(vector& a) 4 | { 5 | int N = a.size(); 6 | vector result; 7 | unordered_map frequency; 8 | for(int &x : a) 9 | frequency[x]++; 10 | for(auto &x : frequency) 11 | if(x.second > N / 3) 12 | result.emplace_back(x.first); 13 | return result; 14 | } 15 | int main() 16 | { 17 | vector a = {1 , 2 , 3 , 3 , 2}; 18 | vector result = majorityElement(a); 19 | if(result.empty()) 20 | cout << "No majority elements\n"; 21 | else 22 | for(int &x : result) 23 | cout << x << " "; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Recursion_Backtracking/subsetSum.cpp: -------------------------------------------------------------------------------- 1 | 2 | public: 3 | void func(int ind, int sum,vector &arr, int N, vector &sumSubset) { 4 | if(ind == N) { 5 | sumSubset.push_back(sum); 6 | return; 7 | } 8 | 9 | // pick the element 10 | func(ind + 1, sum + arr[ind], arr, N, sumSubset); 11 | 12 | // Do-not pick the element 13 | func(ind + 1, sum, arr, N, sumSubset); 14 | } 15 | public: 16 | vector subsetSums(vector arr, int N) 17 | { 18 | vector sumSubset; 19 | func(0, 0, arr, N, sumSubset); 20 | sort(sumSubset.begin(), sumSubset.end()); 21 | return sumSubset; 22 | } -------------------------------------------------------------------------------- /Recursion_Backtracking/subsetsSum2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void findSubsets(int ind, vector &nums, vector &ds, vector> &ans) { 4 | ans.push_back(ds); 5 | for(int i = ind;i> subsetsWithDup(vector& nums) { 14 | vector> ans; 15 | vector ds; 16 | sort(nums.begin(), nums.end()); 17 | findSubsets(0, nums, ds, ans); 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /DP/Editdistance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int editDist(int i , int j ,string s1 , string s2){ 6 | if(i==s1.size()){ 7 | return s2.size()-j; 8 | } 9 | 10 | if(j==s2.size()){ 11 | return s1.size()-i; 12 | } 13 | 14 | if(s1[i]==s2[j]){ 15 | return dp[i][j]=editDist(i+1,j+1,s1,s2); 16 | } 17 | 18 | else{ 19 | int left=1+editDist(i,j+1,s1,s2); 20 | int mid=1+editDist(i+1,j,s1,s2); 21 | int right=1+editDist(i+1,j+1,s1,s2); 22 | 23 | return min({left,mid,right}); 24 | } 25 | } 26 | 27 | 28 | 29 | int main(){ 30 | 31 | string s1,s2; 32 | cin>>s1>>s2; 33 | int n=s1.size(); 34 | int m=s2.size(); 35 | 36 | cout< 2 | using namespace std; 3 | 4 | int lcs(int i, int j , string s1 , string s2,vector> &dp){ 5 | if(i>=s1.size() || j>=s2.size()){ 6 | return 0; 7 | } 8 | 9 | if(dp[i][j]!=-1){ 10 | return dp[i][j]; 11 | } 12 | 13 | if(s1[i]==s2[j]){ 14 | return 1+lcs(i+1,j+1,s1,s2,dp); 15 | } 16 | 17 | else{ 18 | int left = lcs(i+1,j,s1,s2,dp); 19 | int right = lcs(i,j+1,s1,s2,dp); 20 | return dp[i][j]=max(left,right); 21 | } 22 | } 23 | 24 | 25 | int main(){ 26 | 27 | string s1,s2; 28 | cin>>s1>>s2; 29 | int n=s1.size(); 30 | int m=s2.size(); 31 | vector>dp(n,vector(m,-1)); 32 | 33 | cout<>& matrix, int target) { 4 | int lo = 0; 5 | if(!matrix.size()) return false; 6 | int hi = (matrix.size() * matrix[0].size()) - 1; 7 | 8 | while(lo <= hi) { 9 | int mid = (lo + (hi - lo) / 2); 10 | if(matrix[mid/matrix[0].size()][mid % matrix[0].size()] == target) { 11 | return true; 12 | } 13 | if(matrix[mid/matrix[0].size()][mid % matrix[0].size()] < target) { 14 | lo = mid + 1; 15 | } 16 | else { 17 | hi = mid - 1; 18 | } 19 | } 20 | return false; 21 | } 22 | }; -------------------------------------------------------------------------------- /Trees/insertBST.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* insertIntoBST(TreeNode* root, int val) { 4 | if(root == NULL) return new TreeNode(val); 5 | TreeNode *cur = root; 6 | while(true) { 7 | if(cur->val <= val) { 8 | if(cur->right != NULL) cur = cur->right; 9 | else { 10 | cur->right = new TreeNode(val); 11 | break; 12 | } 13 | } else { 14 | if(cur->left != NULL) cur = cur->left; 15 | else { 16 | cur->left = new TreeNode(val); 17 | break; 18 | } 19 | } 20 | } 21 | return root; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Trees/kThSmallestBst.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthSmallest(TreeNode root, int k) { 3 | Stack stack = new Stack(); 4 | TreeNode node = root; 5 | int cnt = 0; 6 | while(true){ 7 | if(node != null){ 8 | stack.push(node); 9 | node = node.left; 10 | } 11 | else{ 12 | if(stack.isEmpty()){ 13 | break; 14 | } 15 | node = stack.pop(); 16 | // inorder.add(node.val); 17 | cnt++; 18 | if(cnt == k) return node.val; 19 | node = node.right; 20 | } 21 | } 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Trees/LevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> levelOrder(TreeNode* root) { 4 | vector> ans; 5 | if(root == NULL) return ans; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()) { 9 | int size = q.size(); 10 | vector level; 11 | for(int i = 0;ileft != NULL) q.push(node->left); 15 | if(node->right != NULL) q.push(node->right); 16 | level.push_back(node->val); 17 | } 18 | ans.push_back(level); 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Recursion_Backtracking/kthPermutationSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getPermutation(int n, int k) { 4 | int fact = 1; 5 | vector numbers; 6 | for(int i = 1;inext; 17 | cnt++; 18 | } 19 | if(cnt < k){ 20 | return head; 21 | } 22 | 23 | while(curr != NULL && count < k){ 24 | next = curr->next; 25 | curr->next = prev; 26 | prev = curr; 27 | curr = next; 28 | count++; 29 | } 30 | 31 | if(next != NULL){ 32 | head->next = reverseKGroup(next, k); 33 | } 34 | 35 | return prev; 36 | } 37 | }; -------------------------------------------------------------------------------- /LinkedList/FindTheStartingPointofTheCycle.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | ListNode *detectCycle(ListNode *head) { 5 | if (head == NULL || head->next == NULL) 6 | return NULL; 7 | 8 | ListNode *slow = head; 9 | ListNode *fast = head; 10 | ListNode *entry = head; 11 | 12 | while (fast->next && fast->next->next) { 13 | slow = slow->next; 14 | fast = fast->next->next; 15 | if (slow == fast) { 16 | while(slow != entry){ 17 | slow = slow->next; 18 | entry = entry->next; 19 | } 20 | return entry; 21 | } 22 | } 23 | return NULL; 24 | } 25 | }; -------------------------------------------------------------------------------- /Trees/isBSTIterative.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidBST(TreeNode* root) { 4 | stack st; 5 | TreeNode* node = root; 6 | TreeNode* prev = NULL; 7 | while(true) { 8 | if(node != NULL) { 9 | st.push(node); 10 | node = node->left; 11 | } 12 | else { 13 | 14 | if(st.empty() == true) break; 15 | node = st.top(); 16 | st.pop(); 17 | // inorder.push_back(node->val); 18 | if(prev != NULL && node->val <= prev->val) return false; 19 | prev = node; 20 | node = node->right; 21 | } 22 | } 23 | return true; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Stacks_Queues/LargestRectangeHistogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& heights) { 4 | stack st; 5 | int maxA = 0; 6 | int n = heights.size(); 7 | for(int i = 0;i<=n;i++) { 8 | while(!st.empty() && (i==n || heights[st.top()] >= heights[i])) { 9 | int height = heights[st.top()]; 10 | st.pop(); 11 | int width; 12 | if(st.empty()) width = i; 13 | else width = i - st.top() - 1; 14 | 15 | // cout << i << " " << width << " " << height << endl; 16 | maxA = max(maxA, width * height); 17 | } 18 | st.push(i); 19 | } 20 | return maxA; 21 | } 22 | }; -------------------------------------------------------------------------------- /Trees/iterativePostOrderTraversal2Stack.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | vector postorderTraversal(TreeNode* root) { 5 | vector postorder; 6 | if(root == NULL) return postorder; 7 | stack st1, st2; 8 | st1.push(root); 9 | while(!st1.empty()) { 10 | root = st1.top(); 11 | st1.pop(); 12 | st2.push(root); 13 | if(root->left != NULL) { 14 | st1.push(root->left); 15 | } 16 | if(root->right != NULL) { 17 | st1.push(root->right); 18 | } 19 | } 20 | while(!st2.empty()) { 21 | postorder.push_back(st2.top()->val); 22 | st2.pop(); 23 | } 24 | return postorder; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /DP/01Knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | int knapsack(int ind , int W , int val[] , int wt[] , int n, vector> &dp){ 7 | if(ind>=n){ 8 | return 0; 9 | } 10 | 11 | if(W==0){ 12 | return 0; 13 | } 14 | 15 | if(wt[ind]<=W){ 16 | int left=val[ind]+knapsack(ind+1,W-wt[ind],val,wt,n,dp); 17 | int right = knapsack(ind+1,W,val,wt,n,dp); 18 | 19 | return dp[ind][W]=max(left,right); 20 | } 21 | 22 | else{ 23 | return dp[ind][W] = knapsack(ind+1,W,val,wt,n,dp); 24 | } 25 | } 26 | 27 | 28 | int main(){ 29 | 30 | int wt[]={25,25,30}; 31 | int val[]={100,100,180}; 32 | int n=3; 33 | int weight=50; 34 | 35 | 36 | vector>dp(n,vector(weight+1,-1)); 37 | 38 | cout<next->data!=val){ 4 | temp=temp->next; 5 | } 6 | node *todelete = temp->next; 7 | temp->next=temp->next->next; 8 | 9 | delete todelete; 10 | } 11 | 12 | 13 | void deleteFirst(node* &head){ 14 | node *todelete=head; 15 | head=head->next; 16 | 17 | delete todelete; 18 | } 19 | 20 | 21 | 22 | 23 | /** 24 | * Definition for singly-linked list. 25 | * struct ListNode { 26 | * int val; 27 | * ListNode *next; 28 | * ListNode(int x) : val(x), next(NULL) {} 29 | * }; 30 | */ 31 | // class Solution { 32 | // public: 33 | // void deleteNode(ListNode* node) { 34 | // ListNode *temp = node; 35 | // node->val = node->next->val; 36 | // node->next=node->next->next; 37 | // } 38 | // }; -------------------------------------------------------------------------------- /LinkedList/PalindromeLL.cpp: -------------------------------------------------------------------------------- 1 | bool isPalindrome(ListNode *head){ 2 | if(head==NULL || head->next==NULL){ 3 | return true; 4 | } 5 | 6 | ListNode *slow = head; 7 | ListNode *fast=head; 8 | 9 | 10 | while(fast->next!=NULL && fast->next->next!=NULL){ 11 | slow=slow->next; 12 | fast=fast->next->next; 13 | } 14 | 15 | 16 | slow->next=reverseList(slow->next); 17 | slow=slow->next; 18 | 19 | 20 | while(slow != NULL){ 21 | if(head->val != slow->val){ 22 | return false; 23 | } 24 | 25 | head=head->next; 26 | slow=slow->next; 27 | } 28 | 29 | return true; 30 | 31 | } 32 | 33 | ListNode *reverseList(ListNode *head){ 34 | ListNode *pre=NULL; 35 | ListNode *next=NULL; 36 | while(head != NULL){ 37 | next=head->next; 38 | head->next=pre; 39 | pre=head; 40 | head=next; 41 | 42 | } 43 | 44 | return pre; 45 | } -------------------------------------------------------------------------------- /BinarySearch/MatrixMedian.cpp: -------------------------------------------------------------------------------- 1 | int countSmallerThanMid(vector &row, int mid) { 2 | int l = 0, h = row.size() - 1; 3 | while(l <= h) { 4 | int md = (l + h) >> 1; 5 | if(row[md] <= mid) { 6 | l = md + 1; 7 | } 8 | else { 9 | h = md - 1; 10 | } 11 | } 12 | return l; 13 | } 14 | int findMedian(vector > &A) { 15 | int low = INT_MIN; 16 | int high = INT_MAX; 17 | int n = A.size(); 18 | int m = A[0].size(); 19 | while(low <= high) { 20 | int mid = (low + high) >> 1; 21 | int cnt = 0; 22 | for(int i = 0;i valueIndexHash; 10 | int iMax = 0, iStartIndexPos = 0; 11 | for(int iCurIndexPos = 0; iCurIndexPos < iLength; iCurIndexPos++) 12 | { 13 | if(valueIndexHash.find(s[iCurIndexPos]) != valueIndexHash.end()) 14 | { 15 | int iIndex = valueIndexHash[s[iCurIndexPos]]; 16 | iStartIndexPos = max(iStartIndexPos, iIndex + 1); 17 | } 18 | 19 | valueIndexHash[s[iCurIndexPos]] = iCurIndexPos; 20 | iMax = max(iMax, iCurIndexPos - iStartIndexPos + 1); 21 | } 22 | 23 | return iMax; 24 | } 25 | }; -------------------------------------------------------------------------------- /BinarySearch/NthRootOfANumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | double multiply(double number, int n) { 4 | double ans = 1.0; 5 | for(int i = 1;i<=n;i++) { 6 | ans = ans * number; 7 | } 8 | return ans; 9 | } 10 | 11 | double getNthRoot(int n, int m) { 12 | double low = 1; 13 | double high = m; 14 | double eps = 1e-6; 15 | 16 | while((high - low) > eps) { 17 | double mid = (low + high) / 2.0; 18 | if(multiply(mid, n) < m) { 19 | low = mid; 20 | } 21 | else { 22 | high = mid; 23 | } 24 | } 25 | 26 | cout << low << " " << high << endl; 27 | 28 | // just to check 29 | cout << pow(m, (double)(1.0/(double)n)); 30 | } 31 | int main() { 32 | int n, m; 33 | cin >> n >> m; 34 | getNthRoot(n, m); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /LinkedList/OddEvenLinkedList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | if (head == NULL) 5 | return NULL; 6 | 7 | 8 | ListNode *odd = head; 9 | ListNode *even = head->next; 10 | 11 | ListNode *evenFirst = even; 12 | 13 | while (1) 14 | { 15 | if (!odd || !even || !(even->next)) 16 | { 17 | odd->next = evenFirst; 18 | break; 19 | } 20 | odd->next = even->next; 21 | odd = even->next; 22 | 23 | if (odd->next == NULL) 24 | { 25 | even->next = NULL; 26 | odd->next = evenFirst; 27 | break; 28 | } 29 | 30 | // Connecting even nodes 31 | even->next = odd->next; 32 | even = odd->next; 33 | } 34 | 35 | return head; 36 | } 37 | }; 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /LinkedList/FlattenALL.cpp: -------------------------------------------------------------------------------- 1 | Node* mergeTwoLists(Node* a, Node* b) { 2 | 3 | Node *temp = new Node(0); 4 | Node *res = temp; 5 | 6 | while(a != NULL && b != NULL) { 7 | if(a->data < b->data) { 8 | temp->bottom = a; 9 | temp = temp->bottom; 10 | a = a->bottom; 11 | } 12 | else { 13 | temp->bottom = b; 14 | temp = temp->bottom; 15 | b = b->bottom; 16 | } 17 | } 18 | 19 | if(a) temp->bottom = a; 20 | else temp->bottom = b; 21 | 22 | return res -> bottom; 23 | 24 | } 25 | Node *flatten(Node *root) 26 | { 27 | 28 | if (root == NULL || root->next == NULL) 29 | return root; 30 | root->next = flatten(root->next); 31 | root = mergeTwoLists(root, root->next); 32 | 33 | return root; 34 | } -------------------------------------------------------------------------------- /Stacks_Queues/stack_using_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct mystack 6 | { 7 | vector v; 8 | 9 | void push(int x) 10 | { 11 | v.push_back(x); 12 | } 13 | 14 | int pop() 15 | { 16 | int res = v.back(); 17 | v.pop_back(); 18 | return res; 19 | } 20 | 21 | int size() 22 | { 23 | return v.size(); 24 | } 25 | 26 | int peek() 27 | { 28 | return v.back(); 29 | } 30 | 31 | bool isempty() 32 | { 33 | return v.empty(); 34 | } 35 | }; 36 | 37 | int main(void) 38 | { 39 | mystack s; 40 | s.push(5); 41 | s.push(10); 42 | s.push(15); 43 | cout << s.pop() << endl; 44 | cout << s.size() << endl; 45 | cout << s.peek() << endl; 46 | cout << s.isempty() << endl; 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Recursion_Backtracking/MColoring.cpp: -------------------------------------------------------------------------------- 1 | bool isSafe(int node, int color[], bool graph[101][101], int n, int col) { 2 | for(int k = 0;k bottomView(Node *root) { 4 | vector ans; 5 | if(root == NULL) return ans; 6 | map mpp; 7 | queue> q; 8 | q.push({root, 0}); 9 | while(!q.empty()) { 10 | auto it = q.front(); 11 | q.pop(); 12 | Node* node = it.first; 13 | int line = it.second; 14 | mpp[line] = node->data; 15 | 16 | if(node->left != NULL) { 17 | q.push({node->left, line-1}); 18 | } 19 | if(node->right != NULL) { 20 | q.push({node->right, line + 1}); 21 | } 22 | 23 | } 24 | 25 | for(auto it : mpp) { 26 | ans.push_back(it.second); 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /LinkedList/LLImplementationofQueues.cpp: -------------------------------------------------------------------------------- 1 | class node { 2 | public: 3 | int data; 4 | node* next; 5 | 6 | 7 | node(int val){ 8 | data=val; 9 | next=NULL; 10 | } 11 | 12 | }; 13 | 14 | class queue{ 15 | node* front; 16 | node* back; 17 | public: 18 | queue(){ 19 | front=NULL; 20 | back=NULL; 21 | } 22 | 23 | void push(int x){ 24 | 25 | node* n = new node(x); 26 | 27 | if(front==NULL){ 28 | back=n; 29 | front=n; 30 | } 31 | 32 | back->next=n; 33 | back=n; 34 | } 35 | 36 | void pop(){ 37 | if(front==NULL){ 38 | cout<<"Queue Underflow"<next; 42 | 43 | delete todelete; 44 | } 45 | 46 | int peek(){ 47 | if(front==NULL){ 48 | cout<<"No element"<data; 53 | } 54 | 55 | bool empty(){ 56 | if(front==NULL){ 57 | return true; 58 | } 59 | 60 | return false; 61 | } 62 | 63 | }; -------------------------------------------------------------------------------- /Recursion_Backtracking/CombinationSum2.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | void findCombination(int ind, int target, vector &arr, vector> &ans, vector&ds) { 5 | if(target==0) { 6 | ans.push_back(ds); 7 | return; 8 | } 9 | for(int i = ind;iind && arr[i]==arr[i-1]) continue; 11 | if(arr[i]>target) break; 12 | ds.push_back(arr[i]); 13 | findCombination(i+1, target - arr[i], arr, ans, ds); 14 | ds.pop_back(); 15 | } 16 | } 17 | public: 18 | vector> combinationSum2(vector& candidates, int target) { 19 | sort(candidates.begin(), candidates.end()); 20 | vector> ans; 21 | vector ds; 22 | findCombination(0, target, candidates, ans, ds); 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /BinarySearch/searchInSortedRotatedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& a, int target) { 4 | int low = 0, high = a.size() - 1; 5 | while(low <= high) { 6 | int mid = (low + high) >> 1; 7 | if(a[mid] == target) return mid; 8 | 9 | // the left side is sorted 10 | if(a[low] <= a[mid]) { 11 | if(target >= a[low] && target <= a[mid]) { 12 | high = mid - 1; 13 | } 14 | else { 15 | low = mid + 1; 16 | } 17 | } 18 | else { 19 | if(target >= a[mid] && target <= a[high]) { 20 | low = mid + 1; 21 | } 22 | else { 23 | high = mid - 1; 24 | } 25 | } 26 | } 27 | return -1; 28 | } 29 | }; -------------------------------------------------------------------------------- /Recursion_Backtracking/CombinationSum.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | void findCombination(int ind, int target, vector &arr, vector> &ans, vector&ds) { 5 | if(ind == arr.size()) { 6 | if(target == 0) { 7 | ans.push_back(ds); 8 | } 9 | return; 10 | } 11 | // pick up the element 12 | if(arr[ind] <= target) { 13 | ds.push_back(arr[ind]); 14 | findCombination(ind, target - arr[ind], arr, ans, ds); 15 | ds.pop_back(); 16 | } 17 | 18 | findCombination(ind+1, target, arr, ans, ds); 19 | 20 | } 21 | public: 22 | vector> combinationSum(vector& candidates, int target) { 23 | vector> ans; 24 | vector ds; 25 | findCombination(0, target, candidates, ans, ds); 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Recursion_Backtracking/printSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private void recurPermute(int index, int[] nums, List> ans) { 3 | if(index == nums.length) { 4 | List ds = new ArrayList<>(); 5 | for(int i = 0;i(ds)); 9 | return; 10 | } 11 | for(int i = index;i> permute(int[] nums) { 23 | List> ans = new ArrayList<>(); 24 | recurPermute(0, nums, ans); 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /BinarySearch/KthElementOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | int kthElement(int arr1[], int arr2[], int n, int m, int k) 2 | { 3 | if(n > m) { 4 | return kthElement(arr2, arr1, m, n, k); 5 | } 6 | 7 | int low = max(0,k-m), high = min(k,n); 8 | 9 | while(low <= high) { 10 | int cut1 = (low + high) >> 1; 11 | int cut2 = k - cut1; 12 | int l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1]; 13 | int l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1]; 14 | int r1 = cut1 == n ? INT_MAX : arr1[cut1]; 15 | int r2 = cut2 == m ? INT_MAX : arr2[cut2]; 16 | 17 | if(l1 <= r2 && l2 <= r1) { 18 | return max(l1, l2); 19 | } 20 | else if (l1 > r2) { 21 | high = cut1 - 1; 22 | } 23 | else { 24 | low = cut1 + 1; 25 | } 26 | } 27 | return 1; 28 | } -------------------------------------------------------------------------------- /Greedy/JobSequencingProblem.cpp: -------------------------------------------------------------------------------- 1 | struct Job{ 2 | int profit; 3 | int dead; 4 | }; 5 | 6 | bool comparison(Job a, Job b) 7 | { 8 | return (a.profit > b.profit); 9 | } 10 | pair JobScheduling(Job arr[], int n) 11 | { 12 | 13 | sort(arr, arr + n, comparison); 14 | int maxi = arr[0].dead; 15 | for(int i = 1;i0; j--) 29 | { 30 | if (slot[j]==-1) 31 | { 32 | slot[j] = i; 33 | countJobs++; 34 | jobProfit+=arr[i].profit; 35 | break; 36 | } 37 | } 38 | } 39 | 40 | return make_pair(countJobs, jobProfit); 41 | } 42 | -------------------------------------------------------------------------------- /Recursion_Backtracking/PalindromePartitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> partition(string s) { 4 | vector > res; 5 | vector path; 6 | func(0, s, path, res); 7 | return res; 8 | } 9 | 10 | void func(int index, string s, vector &path, 11 | vector > &res) { 12 | if(index == s.size()) { 13 | res.push_back(path); 14 | return; 15 | } 16 | for(int i = index; i < s.size(); ++i) { 17 | if(isPalindrome(s, index, i)) { 18 | path.push_back(s.substr(index, i - index + 1)); 19 | func(i+1, s, path, res); 20 | path.pop_back(); 21 | } 22 | } 23 | } 24 | 25 | bool isPalindrome(string s, int start, int end) { 26 | while(start <= end) { 27 | if(s[start++] != s[end--]) 28 | return false; 29 | } 30 | return true; 31 | } 32 | }; -------------------------------------------------------------------------------- /DP/RodCuttingProblem.cpp: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming solution for Rod cutting problem 2 | #include 3 | #include 4 | 5 | // A utility function to get the maximum of two integers 6 | int max(int a, int b) { return (a > b)? a : b;} 7 | 8 | /* Returns the best obtainable price for a rod of length n and 9 | price[] as prices of different pieces */ 10 | int cutRod(int price[], int n) 11 | { 12 | int val[n+1]; 13 | val[0] = 0; 14 | int i, j; 15 | 16 | // Build the table val[] in bottom up manner and return the last entry 17 | // from the table 18 | for (i = 1; i<=n; i++) 19 | { 20 | int max_val = INT_MIN; 21 | for (j = 0; j < i; j++) 22 | max_val = max(max_val, price[j] + val[i-j-1]); 23 | val[i] = max_val; 24 | } 25 | 26 | return val[n]; 27 | } 28 | 29 | /* Driver program to test above functions */ 30 | int main() 31 | { 32 | int arr[] = {1, 5, 8, 9, 10, 17, 17, 20}; 33 | int size = sizeof(arr)/sizeof(arr[0]); 34 | printf("Maximum Obtainable Value is %d", cutRod(arr, size)); 35 | getchar(); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Hashing/4Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> fourSum(vector& nums, int target) { 4 | vector> v; 5 | sort(nums.begin(), nums.end()); 6 | 7 | for(int i = 0; i < nums.size(); i++){ 8 | if(i != 0 && nums[i] == nums[i - 1]) continue; 9 | for(int j = i + 1; j < nums.size(); j++){ 10 | if(j != i + 1 && nums[j] == nums[j - 1]) continue; 11 | 12 | int k = j + 1; 13 | int l = nums.size() - 1; 14 | 15 | while(k < l){ 16 | long long sum = nums[i] + nums[j]; 17 | sum += nums[k] + nums[l]; 18 | if(target == sum ){ 19 | v.push_back({nums[i], nums[j], nums[k], nums[l]}); 20 | k++; 21 | while(k < l && nums[k] == nums[k - 1]) k++; 22 | } 23 | else if( sum < target) k++; 24 | else l--; 25 | } 26 | 27 | } 28 | } 29 | 30 | return v; 31 | } 32 | }; -------------------------------------------------------------------------------- /Trees/topViewOfBt.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to return a list of nodes visible from the top view 5 | //from left to right in Binary Tree. 6 | vector topView(Node *root) 7 | { 8 | vector ans; 9 | if(root == NULL) return ans; 10 | map mpp; 11 | queue> q; 12 | q.push({root, 0}); 13 | while(!q.empty()) { 14 | auto it = q.front(); 15 | q.pop(); 16 | Node* node = it.first; 17 | int line = it.second; 18 | if(mpp.find(line) == mpp.end()) mpp[line] = node->data; 19 | 20 | if(node->left != NULL) { 21 | q.push({node->left, line-1}); 22 | } 23 | if(node->right != NULL) { 24 | q.push({node->right, line + 1}); 25 | } 26 | 27 | } 28 | 29 | for(auto it : mpp) { 30 | ans.push_back(it.second); 31 | } 32 | return ans; 33 | } 34 | 35 | }; 36 | -------------------------------------------------------------------------------- /Arrays/selection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minindex(int A[], int start, int end) 5 | { 6 | int index = start; 7 | for(int i = start; i <= end; i++) 8 | { 9 | if(A[index] > A[i]) 10 | index = i; 11 | } 12 | return index; 13 | } 14 | 15 | 16 | void selection_sort(int A[], int n) 17 | { 18 | for(int i = 0; i <= n-1; i++) 19 | { 20 | int temp; 21 | temp = minindex(A, i, n-1); 22 | swap(A[i], A[temp]); // On each pass, we add one element to it's sorted position. 23 | } 24 | } 25 | 26 | 27 | void display(int A[], int size) // To display the array 28 | { 29 | for(int i = 0; i < size; i++) 30 | cout<& preorder, vector& inorder) { 4 | map inMap; 5 | 6 | for(int i = 0; i < inorder.size(); i++) { 7 | inMap[inorder[i]] = i; 8 | } 9 | 10 | TreeNode* root = buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, inMap); 11 | return root; 12 | } 13 | TreeNode* buildTree(vector& preorder, int preStart, int preEnd, vector& inorder, int inStart, int inEnd, map &inMap) { 14 | if(preStart > preEnd || inStart > inEnd) return NULL; 15 | 16 | TreeNode* root = new TreeNode(preorder[preStart]); 17 | int inRoot = inMap[root->val]; 18 | int numsLeft = inRoot - inStart; 19 | 20 | root->left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap); 21 | root->right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap); 22 | 23 | return root; 24 | } 25 | }; -------------------------------------------------------------------------------- /Arrays/reversepairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vectort; 4 | int merge(vector& nums,int l,int m,int h){ 5 | int c=0,j=m+1; 6 | for(int i=l;i<=m;i++){ 7 | while(j<=h && nums[i]>2*(long)nums[j]) j++; 8 | c+=j-(m+1); 9 | } 10 | int i=l,k=l; 11 | j=m+1; 12 | while(i<=m && j<=h){ 13 | if(nums[i]<=nums[j])t[k++]=nums[i++]; 14 | else t[k++]=nums[j++]; 15 | } 16 | while(i<=m)t[k++]=nums[i++]; 17 | while(j<=h)t[k++]=nums[j++]; 18 | for(int i=l;i<=h;i++)nums[i]=t[i]; 19 | return c; 20 | } 21 | int mergesort(vector& nums,int l,int h){ 22 | int inv=0; 23 | if(h>l){ 24 | int m=l+(h-l)/2; 25 | inv+=mergesort(nums,l,m); 26 | inv+=mergesort(nums,m+1,h); 27 | inv+=merge(nums,l,m,h); 28 | } 29 | return inv; 30 | } 31 | int reversePairs(vector& nums) { 32 | t=vector(nums.size()); 33 | return mergesort(nums,0,nums.size()-1); 34 | } 35 | }; -------------------------------------------------------------------------------- /Trees/BuildBtfromPostOrderandInOrder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* buildTree(vector& inorder, vector& postorder) { 4 | if (inorder.size() != postorder.size()) 5 | return NULL; 6 | map hm; 7 | for (int i=0;i &inorder, int is, int ie, vector &postorder, int ps, int pe, 13 | map &hm){ 14 | if (ps>pe || is>ie) return NULL; 15 | TreeNode* root = new TreeNode(postorder[pe]); 16 | int ri = hm[postorder[pe]]; 17 | TreeNode* leftchild = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm); 18 | TreeNode* rightchild = buildTreePostIn(inorder,ri+1, ie, postorder, ps+ri-is, pe-1, hm); 19 | root->left = leftchild; 20 | root->right = rightchild; 21 | return root; 22 | } 23 | }; -------------------------------------------------------------------------------- /Stacks_Queues/StackusingQueue.cpp: -------------------------------------------------------------------------------- 1 | // if push(x){ 2 | // Add x -> queue 2 3 | // element by element transfer q1 -> q2 in fifo manner 4 | // swap q1 and q2 5 | 6 | // pop(){ 7 | // q1.pop(); 8 | // } 9 | 10 | //top(){ 11 | // return q1.front(); 12 | // } 13 | 14 | // } 15 | 16 | 17 | class MyStack { 18 | public: 19 | 20 | queue que; 21 | /** Initialize your data structure here. */ 22 | MyStack() { 23 | 24 | } 25 | 26 | /** Push element x onto stack. */ 27 | void push(int x) { 28 | que.push(x); 29 | for(int i=0;i> verticalTraversal(TreeNode* root) { 4 | map>> nodes; 5 | queue>> todo; 6 | todo.push({root, {0, 0}}); 7 | while (!todo.empty()) { 8 | auto p = todo.front(); 9 | todo.pop(); 10 | TreeNode* node = p.first; 11 | int x = p.second.first, y = p.second.second; 12 | nodes[x][y].insert(node -> val); 13 | if (node -> left) { 14 | todo.push({node -> left, {x - 1, y + 1}}); 15 | } 16 | if (node -> right) { 17 | todo.push({node -> right, {x + 1, y + 1}}); 18 | } 19 | } 20 | vector> ans; 21 | for (auto p : nodes) { 22 | vector col; 23 | for (auto q : p.second) { 24 | col.insert(col.end(), q.second.begin(), q.second.end()); 25 | } 26 | ans.push_back(col); 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Trees/iterativePostOrder1Stack.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | vector postorderTraversal(TreeNode* root) { 5 | vector postorder; 6 | if(root == NULL) return postorder; 7 | stack st1; 8 | TreeNode* current = root; 9 | while(current != NULL || !st1.empty()) { 10 | if(current != NULL){ 11 | st1.push(current); 12 | current = current->left; 13 | }else{ 14 | TreeNode* temp = st1.top()->right; 15 | if (temp == NULL) { 16 | temp = st1.top(); 17 | st1.pop(); 18 | postorder.push_back(temp->val); 19 | while (!st1.empty() && temp == st1.top()->right) { 20 | temp = st1.top(); 21 | st1.pop(); 22 | postorder.push_back(temp->val); 23 | } 24 | } else { 25 | current = temp; 26 | } 27 | } 28 | } 29 | return postorder; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Arrays/mergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | vector> merge(vector>& intervals) { 2 | vector> mergedIntervals; 3 | if(intervals.size() == 0) { 4 | return mergedIntervals; 5 | } 6 | sort(intervals.begin(), intervals.end()); 7 | vector tempInterval = intervals[0]; 8 | 9 | for(auto it : intervals) { 10 | 11 | //consider the case 12 | // tempInterval->[1,8], 13 | // it-> [6,7] 14 | //here it[0][1,6], 21 | // it-> [7, 9] 22 | 23 | else { 24 | mergedIntervals.push_back(tempInterval); 25 | tempInterval = it; 26 | } 27 | } 28 | mergedIntervals.push_back(tempInterval); 29 | return mergedIntervals; 30 | } -------------------------------------------------------------------------------- /Stacks_Queues/QueueUsingStack.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | stack input, output; 4 | /** Initialize your data structure here. */ 5 | MyQueue() { 6 | 7 | } 8 | 9 | /** Push element x to the back of queue. */ 10 | void push(int x) { 11 | input.push(x); 12 | } 13 | 14 | /** Removes the element from in front of queue and returns that element. */ 15 | int pop() { 16 | // shift input to output 17 | if (output.empty()) 18 | while (input.size()) 19 | output.push(input.top()), input.pop(); 20 | 21 | int x = output.top(); 22 | output.pop(); 23 | return x; 24 | } 25 | 26 | /** Get the front element. */ 27 | int peek() { 28 | // shift input to output 29 | if (output.empty()) 30 | while (input.size()) 31 | output.push(input.top()), input.pop(); 32 | return output.top(); 33 | } 34 | 35 | /** Returns whether the queue is empty. */ 36 | bool empty() { 37 | return input.empty() && output.empty(); 38 | } 39 | 40 | }; -------------------------------------------------------------------------------- /DP/MCM.cpp: -------------------------------------------------------------------------------- 1 | /* A naive recursive implementation that simply 2 | follows the above optimal substructure property */ 3 | #include 4 | using namespace std; 5 | 6 | // Matrix Ai has dimension p[i-1] x p[i] 7 | // for i = 1..n 8 | int MatrixChainOrder(int p[], int i, int j) 9 | { 10 | if (i == j) 11 | return 0; 12 | int k; 13 | int min = INT_MAX; 14 | int count; 15 | 16 | // place parenthesis at different places 17 | // between first and last matrix, recursively 18 | // calculate count of multiplications for 19 | // each parenthesis placement and return the 20 | // minimum count 21 | for (k = i; k < j; k++) 22 | { 23 | count = MatrixChainOrder(p, i, k) 24 | + MatrixChainOrder(p, k + 1, j) 25 | + p[i - 1] * p[k] * p[j]; 26 | 27 | if (count < min) 28 | min = count; 29 | } 30 | 31 | // Return minimum count 32 | return min; 33 | } 34 | 35 | // Driver Code 36 | int main() 37 | { 38 | int arr[] = { 1, 2, 3, 4, 3 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | cout << "Minimum number of multiplications is " 42 | << MatrixChainOrder(arr, 1, n - 1); 43 | } 44 | 45 | // This code is contributed by Shivi_Aggarwal 46 | -------------------------------------------------------------------------------- /Arrays/bubble.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void bubble_sort(int A[], int size) 5 | { 6 | int swapcount = 0; 7 | for(int i = 0; i <= size-1; i++) // Running n times passes (Worst case) 8 | { 9 | for(int j = 0; j <= size-2-i; j++) // Here the inner loop size decreases with each pass. 10 | { 11 | swapcount = 0; 12 | if(A[j] > A[j+1]) // If the next element is smaller, then swap current and next 13 | { 14 | swap(A[j], A[j+1]); // In built function of C++ 15 | swapcount = swapcount + 1; 16 | } 17 | } 18 | if(swapcount == 0) 19 | break; 20 | } 21 | } 22 | 23 | 24 | void display(int A[], int size) // To display the array 25 | { 26 | for(int i = 0; i < size; i++) 27 | cout< r2; 5 | } 6 | // function to return fractionalweights 7 | double fractionalKnapsack(int W, Item arr[], int n) 8 | { 9 | // Your code here 10 | 11 | sort(arr, arr + n, comp); 12 | 13 | int curWeight = 0; 14 | double finalvalue = 0.0; 15 | 16 | 17 | for (int i = 0; i < n; i++) { 18 | // If the weight of current item and weight already in knapsack is less 19 | // than equal to knapsack capacity, push it to the knapsack 20 | if (curWeight + arr[i].weight <= W) { 21 | curWeight += arr[i].weight; 22 | finalvalue += arr[i].value; 23 | } 24 | 25 | //else add the a part of the current wait which can be included in 26 | //knapsack 27 | 28 | else { 29 | int remain = W - curWeight; 30 | finalvalue += (arr[i].value / (double)arr[i].weight) * (double)remain; 31 | break; 32 | } 33 | } 34 | 35 | return finalvalue; 36 | 37 | } -------------------------------------------------------------------------------- /BinarySearch/AggressiveCows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool isPossible(int a[], int n, int cows, int minDist) { 4 | int cntCows = 1; 5 | int lastPlacedCow = a[0]; 6 | for(int i = 1;i= minDist) { 8 | cntCows++; 9 | lastPlacedCow = a[i]; 10 | } 11 | } 12 | if(cntCows >= cows) return true; 13 | return false; 14 | } 15 | int main() { 16 | int t; 17 | cin >> t; 18 | while(t--) { 19 | int n, cows; 20 | cin >> n >> cows; 21 | int a[n]; 22 | for(int i = 0;i> a[i]; 23 | sort(a,a+n); 24 | 25 | int low = 1, high = a[n-1] - a[0]; 26 | 27 | while(low <= high) { 28 | int mid = (low + high) >> 1; 29 | 30 | if(isPossible(a,n,cows,mid)) { 31 | low = mid + 1; 32 | } 33 | else { 34 | high = mid - 1; 35 | } 36 | } 37 | cout << high << endl; 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /BinarySearch/BooksAllocation.cpp: -------------------------------------------------------------------------------- 1 | int isPossible(vector &A, int pages, int students) { 2 | int cnt = 0; 3 | int sumAllocated = 0; 4 | for(int i = 0;i pages) { 6 | cnt++; 7 | sumAllocated = A[i]; 8 | if(sumAllocated > pages) return false; 9 | } 10 | else { 11 | sumAllocated += A[i]; 12 | } 13 | } 14 | if(cnt < students) return true; 15 | return false; 16 | } 17 | int books(vector &A, int B) { 18 | if(B > A.size()) return -1; 19 | int low = A[0]; 20 | int high = 0; 21 | for(int i = 0;i> 1; 28 | //cout << low << " " << high << " " << mid << endl; 29 | if(isPossible(A, mid, B)) { 30 | res = mid; 31 | high = mid - 1; 32 | } 33 | else { 34 | low = mid + 1; 35 | } 36 | } 37 | 38 | return low; // or we can return res too , that will too give correct answer 39 | } -------------------------------------------------------------------------------- /Greedy/NMeetingsInOneRoom.cpp: -------------------------------------------------------------------------------- 1 | struct meeting 2 | { 3 | int start; 4 | int end; 5 | int pos; 6 | }; 7 | bool comparator(struct meeting m1, meeting m2) 8 | { 9 | if (m1.end < m2.end) 10 | return true; 11 | else if (m1.end > m2.end) 12 | return false; 13 | else if (m1.pos < m2.pos) 14 | return true; 15 | return false; 16 | } 17 | void maxMeetings(int s[], int e[], int n) 18 | { 19 | struct meeting meet[n]; 20 | for (int i = 0; i < n; i++) 21 | { 22 | meet[i].start = s[i], meet[i].end = e[i], meet[i].pos = i + 1; 23 | } 24 | 25 | sort(meet, meet + n, comparator); 26 | 27 | vector answer; 28 | 29 | int limit = meet[0].end; 30 | answer.push_back(meet[0].pos); 31 | 32 | for (int i = 1; i < n; i++) 33 | { 34 | 35 | // we will push into the ans vector only if the start time of current 36 | // meeting is greater than ending time of previous meeting 37 | if (meet[i].start > limit) 38 | { 39 | limit = meet[i].end; 40 | answer.push_back(meet[i].pos); 41 | } 42 | } 43 | for (int i = 0; i < answer.size(); i++) 44 | { 45 | cout << answer[i] << " "; 46 | } 47 | } -------------------------------------------------------------------------------- /Trees/KthElementBstMorris.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthSmallest(TreeNode* root, int k) { 4 | // nvector inorder; 5 | int cnt = 0; 6 | int ans = -1; 7 | TreeNode* cur = root; 8 | while(cur != NULL) { 9 | if(cur->left == NULL) { 10 | // inorder.push_back(cur->val); 11 | cnt++; 12 | if(cnt == k) ans = cur->val; 13 | cur = cur->right; 14 | } 15 | else { 16 | TreeNode* prev = cur->left; 17 | while(prev->right != NULL && prev->right != cur) { 18 | prev = prev->right; 19 | } 20 | 21 | if(prev->right == NULL) { 22 | prev->right = cur; 23 | cur = cur->left; 24 | } 25 | else { 26 | prev->right = NULL; 27 | // inorder.push_back(cur->val); 28 | cnt++; 29 | if(cnt == k) ans = cur->val; 30 | cur = cur->right; 31 | } 32 | } 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Arrays/MergeTwoSortedArraysWithoutExtraSpace.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | int nextGap(int gap) 7 | { 8 | if (gap <= 1) 9 | return 0; 10 | return (gap / 2) + (gap % 2); 11 | } 12 | 13 | void merge(int* arr1, int* arr2, int n, int m) 14 | { 15 | int i, j, gap = n + m; 16 | for (gap = nextGap(gap);gap > 0; gap = nextGap(gap)) 17 | { 18 | for (i = 0; i + gap < n; i++) 19 | if (arr1[i] > arr1[i + gap]) 20 | swap(arr1[i], arr1[i + gap]); 21 | 22 | for (j = gap > n ? gap - n : 0;i < n && j < m; 23 | i++, j++) 24 | if (arr1[i] > arr2[j]) 25 | swap(arr1[i], arr2[j]); 26 | 27 | if (j < m) { 28 | for (j = 0; j + gap < m; j++) 29 | if (arr2[j] > arr2[j + gap]) 30 | swap(arr2[j], arr2[j + gap]); 31 | } 32 | } 33 | } 34 | 35 | int main(){ 36 | 37 | int a1[] = { 10, 27, 38, 43, 82 }; 38 | int a2[] = { 3, 9 }; 39 | int n = sizeof(a1) / sizeof(int); 40 | int m = sizeof(a2) / sizeof(int); 41 | 42 | 43 | merge(a1, a2, n, m); 44 | 45 | printf("First Array: "); 46 | for (int i = 0; i < n; i++) 47 | printf("%d ", a1[i]); 48 | 49 | printf("\nSecond Array: "); 50 | for (int i = 0; i < m; i++) 51 | printf("%d ", a2[i]); 52 | printf("\n"); 53 | return 0; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Graphs/bipartiteGraphDfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool bipartiteDfs(int node, vector adj[], int color[]) { 5 | for(auto it : adj[node]) { 6 | if(color[it] == -1) { 7 | color[it] = 1 - color[node]; 8 | if(!bipartiteDfs(it, adj, color)) { 9 | return false; 10 | } 11 | } else if(color[it] == color[node]) return false; 12 | } 13 | return true; 14 | } 15 | bool checkBipartite(vector adj[], int n) { 16 | int color[n]; 17 | memset(color, -1, sizeof color); 18 | for(int i = 0;i> n >> m; 31 | vector adj[n]; 32 | for(int i = 0;i> u >> v; 35 | adj[u].push_back(v); 36 | adj[v].push_back(u); 37 | } 38 | 39 | if(checkBipartite(adj, n)) { 40 | cout << "yes"; 41 | } else { 42 | cout << "No"; 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Trees/ZigZagLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> zigzagLevelOrder(TreeNode* root) { 4 | vector> result; 5 | if (root == NULL) { 6 | return result; 7 | } 8 | 9 | queue nodesQueue; 10 | nodesQueue.push(root); 11 | bool leftToRight = true; 12 | 13 | while ( !nodesQueue.empty()) { 14 | int size = nodesQueue.size(); 15 | vector row(size); 16 | for (int i = 0; i < size; i++) { 17 | TreeNode* node = nodesQueue.front(); 18 | nodesQueue.pop(); 19 | 20 | // find position to fill node's value 21 | int index = (leftToRight) ? i : (size - 1 - i); 22 | 23 | row[index] = node->val; 24 | if (node->left) { 25 | nodesQueue.push(node->left); 26 | } 27 | if (node->right) { 28 | nodesQueue.push(node->right); 29 | } 30 | } 31 | // after this level 32 | leftToRight = !leftToRight; 33 | result.push_back(row); 34 | } 35 | return result; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Graphs/BellmanFord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node { 4 | int u; 5 | int v; 6 | int wt; 7 | node(int first, int second, int weight) { 8 | u = first; 9 | v = second; 10 | wt = weight; 11 | } 12 | }; 13 | 14 | int main(){ 15 | int N,m; 16 | cin >> N >> m; 17 | vector edges; 18 | for(int i = 0;i> u >> v >> wt; 21 | edges.push_back(node(u, v, wt)); 22 | } 23 | 24 | int src; 25 | cin >> src; 26 | 27 | 28 | int inf = 10000000; 29 | vector dist(N, inf); 30 | 31 | dist[src] = 0; 32 | 33 | for(int i = 1;i<=N-1;i++) { 34 | for(auto it: edges) { 35 | if(dist[it.u] + it.wt < dist[it.v]) { 36 | dist[it.v] = dist[it.u] + it.wt; 37 | } 38 | } 39 | } 40 | 41 | int fl = 0; 42 | for(auto it: edges) { 43 | if(dist[it.u] + it.wt < dist[it.v]) { 44 | cout << "Negative Cycle"; 45 | fl = 1; 46 | break; 47 | } 48 | } 49 | 50 | if(!fl) { 51 | for(int i = 0;i 2 | using namespace std; 3 | 4 | 5 | class Solution { 6 | void dfs(int node, vector &vis, vector adj[], vector &storeDfs) { 7 | storeDfs.push_back(node); 8 | vis[node] = 1; 9 | for(auto it : adj[node]) { 10 | if(!vis[it]) { 11 | dfs(it, vis, adj, storeDfs); 12 | } 13 | } 14 | } 15 | public: 16 | vectordfsOfGraph(int V, vector adj[]){ 17 | vector storeDfs; 18 | vector vis(V+1, 0); 19 | for(int i = 1;i<=V;i++) { 20 | if(!vis[i]) dfs(i, vis, adj, storeDfs); 21 | } 22 | return storeDfs; 23 | } 24 | }; 25 | 26 | // { Driver Code Starts. 27 | int main(){ 28 | int tc; 29 | cin >> tc; 30 | while(tc--){ 31 | int V, E; 32 | cin >> V >> E; 33 | 34 | vector adj[V]; 35 | 36 | for(int i = 0; i < E; i++) 37 | { 38 | int u, v; 39 | cin >> u >> v; 40 | adj[u].push_back(v); 41 | adj[v].push_back(u); 42 | } 43 | // string s1; 44 | // cin>>s1; 45 | Solution obj; 46 | vectorans=obj.dfsOfGraph(V, adj); 47 | for(int i=0;ibfsOfGraph(int V, vector adj[]){ 5 | vector bfs; 6 | vector vis(V, 0); 7 | queue q; 8 | q.push(0); 9 | vis[0] = 1; 10 | while(!q.empty()) { 11 | int node = q.front(); 12 | q.pop(); 13 | bfs.push_back(node); 14 | 15 | for(auto it : adj[node]) { 16 | if(!vis[it]) { 17 | q.push(it); 18 | vis[it] = 1; 19 | } 20 | } 21 | } 22 | 23 | return bfs; 24 | } 25 | }; 26 | 27 | // { Driver Code Starts. 28 | int main(){ 29 | int tc; 30 | cin >> tc; 31 | // for multiple graphs 32 | while(tc--){ 33 | int V, E; 34 | cin >> V >> E; 35 | 36 | vector adj[V]; 37 | 38 | for(int i = 0; i < E; i++) 39 | { 40 | int u, v; 41 | cin >> u >> v; 42 | adj[u].push_back(v); 43 | // adj[v].push_back(u); // uncomment this for undirected graoh 44 | } 45 | // string s1; 46 | // cin>>s1; 47 | Solution obj; 48 | vectorans=obj.bfsOfGraph(V, adj); 49 | for(int i=0;i 4 | using namespace std; 5 | 6 | // defining the number of vertices 7 | #define nV 4 8 | 9 | #define INF 999 10 | 11 | void printMatrix(int matrix[][nV]); 12 | 13 | // Implementing floyd warshall algorithm 14 | void floydWarshall(int graph[][nV]) { 15 | int matrix[nV][nV], i, j, k; 16 | 17 | for (i = 0; i < nV; i++) 18 | for (j = 0; j < nV; j++) 19 | matrix[i][j] = graph[i][j]; 20 | 21 | // Adding vertices individually 22 | for (k = 0; k < nV; k++) { 23 | for (i = 0; i < nV; i++) { 24 | for (j = 0; j < nV; j++) { 25 | if (matrix[i][k] + matrix[k][j] < matrix[i][j]) 26 | matrix[i][j] = matrix[i][k] + matrix[k][j]; 27 | } 28 | } 29 | } 30 | printMatrix(matrix); 31 | } 32 | 33 | void printMatrix(int matrix[][nV]) { 34 | for (int i = 0; i < nV; i++) { 35 | for (int j = 0; j < nV; j++) { 36 | if (matrix[i][j] == INF) 37 | printf("%4s", "INF"); 38 | else 39 | printf("%4d", matrix[i][j]); 40 | } 41 | printf("\n"); 42 | } 43 | } 44 | 45 | int main() { 46 | int graph[nV][nV] = {{0, 3, INF, 5}, 47 | {2, 0, INF, 4}, 48 | {INF, 1, 0, INF}, 49 | {INF, INF, 2, 0}}; 50 | floydWarshall(graph); 51 | } -------------------------------------------------------------------------------- /Stacks_Queues/RottenOranges.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int orangesRotting(vector>& grid) { 5 | if(grid.empty()) return 0; 6 | int m = grid.size(), n = grid[0].size(), days = 0, tot = 0, cnt = 0; 7 | queue> rotten; 8 | for(int i = 0; i < m; ++i){ 9 | for(int j = 0; j < n; ++j){ 10 | if(grid[i][j] != 0) tot++; 11 | if(grid[i][j] == 2) rotten.push({i, j}); 12 | } 13 | } 14 | 15 | int dx[4] = {0, 0, 1, -1}; 16 | int dy[4] = {1, -1, 0, 0}; 17 | 18 | while(!rotten.empty()){ 19 | int k = rotten.size(); 20 | cnt += k; 21 | while(k--){ 22 | int x = rotten.front().first, y = rotten.front().second; 23 | rotten.pop(); 24 | for(int i = 0; i < 4; ++i){ 25 | int nx = x + dx[i], ny = y + dy[i]; 26 | if(nx < 0 || ny < 0 || nx >= m || ny >= n || grid[nx][ny] != 1) continue; 27 | grid[nx][ny] = 2; 28 | rotten.push({nx, ny}); 29 | } 30 | } 31 | if(!rotten.empty()) days++; 32 | } 33 | 34 | return tot == cnt ? days : -1; 35 | } 36 | }; -------------------------------------------------------------------------------- /Arrays/insertion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void insertion_sort(int A[], int size) 5 | { 6 | for(int i = 1; i <= size-1; i++) // Outer loop is used to pick elements in the array 7 | { 8 | int temp = A[i]; // temp varriable is used for comparisons 9 | for(int j = i-1; j >= 0; j--) // This inner loop is used to iterate in the sorted array backwards 10 | { 11 | if(A[j] > temp) // If the element is greater than temp, 12 | { // then push it by one index and store the number in the newly empty space 13 | A[j+1] = A[j]; 14 | A[j] = temp; 15 | } 16 | else // If any element is smaller than or equal to the temp element, break it. 17 | break; 18 | } 19 | } 20 | } 21 | 22 | void display(int A[], int size) // To display the array 23 | { 24 | for(int i = 0; i < size; i++) 25 | cout<& nums1, vector& nums2) { 4 | if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1); 5 | int n1 = nums1.size(); 6 | int n2 = nums2.size(); 7 | int low = 0, high = n1; 8 | 9 | while(low <= high) { 10 | int cut1 = (low+high) >> 1; 11 | int cut2 = (n1 + n2 + 1) / 2 - cut1; 12 | 13 | 14 | int left1 = cut1 == 0 ? INT_MIN : nums1[cut1-1]; 15 | int left2 = cut2 == 0 ? INT_MIN : nums2[cut2-1]; 16 | 17 | int right1 = cut1 == n1 ? INT_MAX : nums1[cut1]; 18 | int right2 = cut2 == n2 ? INT_MAX : nums2[cut2]; 19 | 20 | 21 | if(left1 <= right2 && left2 <= right1) { 22 | if( (n1 + n2) % 2 == 0 ) 23 | return (max(left1, left2) + min(right1, right2)) / 2.0; 24 | else 25 | return max(left1, left2); 26 | } 27 | else if(left1 > right2) { 28 | high = cut1 - 1; 29 | } 30 | else { 31 | low = cut1 + 1; 32 | } 33 | } 34 | return 0.0; 35 | } 36 | }; -------------------------------------------------------------------------------- /Stacks_Queues/StacksUsingArrays.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define MAX 1000 7 | 8 | class Stack { 9 | int top; 10 | 11 | public: 12 | int a[MAX]; 13 | 14 | Stack() { top = -1; } 15 | bool push(int x); 16 | int pop(); 17 | int peek(); 18 | bool isEmpty(); 19 | }; 20 | 21 | bool Stack::push(int x) 22 | { 23 | if (top >= (MAX - 1)) { 24 | cout << "Stack Overflow"; 25 | return false; 26 | } 27 | else { 28 | a[++top] = x; 29 | cout << x << " pushed into stack\n"; 30 | return true; 31 | } 32 | } 33 | 34 | int Stack::pop() 35 | { 36 | if (top < 0) { 37 | cout << "Stack Underflow"; 38 | return 0; 39 | } 40 | else { 41 | int x = a[top--]; 42 | return x; 43 | } 44 | } 45 | int Stack::peek() 46 | { 47 | if (top < 0) { 48 | cout << "Stack is Empty"; 49 | return 0; 50 | } 51 | else { 52 | int x = a[top]; 53 | return x; 54 | } 55 | } 56 | 57 | bool Stack::isEmpty() 58 | { 59 | return (top < 0); 60 | } 61 | 62 | // Driver program to test above functions 63 | int main() 64 | { 65 | class Stack s; 66 | s.push(10); 67 | s.push(20); 68 | s.push(30); 69 | cout << s.pop() << " Popped from stack\n"; 70 | cout<<"Elements present in stack : "; 71 | while(!s.isEmpty()) 72 | { 73 | 74 | cout< 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector topo(int N, vector adj[]) { 7 | queue q; 8 | vector indegree(N, 0); 9 | for(int i = 0;i topo 21 | while(!q.empty()) { 22 | int node = q.front(); 23 | q.pop(); 24 | topo.push_back(node) 25 | for(auto it : adj[node]) { 26 | indegree[it]--; 27 | if(indegree[it] == 0) { 28 | q.push(it); 29 | } 30 | } 31 | } 32 | return topo; 33 | } 34 | }; 35 | 36 | 37 | 38 | int main() 39 | { 40 | 41 | int t; 42 | cin >> t; 43 | while(t--) 44 | { 45 | int V, E; 46 | cin >> V >> E; 47 | 48 | vector adj[V]; 49 | 50 | for(int i = 0; i < E; i++) 51 | { 52 | int u, v; 53 | cin >> u >> v; 54 | adj[u].push_back(v); 55 | } 56 | 57 | Solution obj; 58 | cout << obj.isCyclic(V, adj) << "\n"; 59 | } 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Graphs/checkCycleDGBFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isCyclic(int N, vector adj[]) { 7 | queue q; 8 | vector indegree(N, 0); 9 | for(int i = 0;i> t; 44 | while(t--) 45 | { 46 | int V, E; 47 | cin >> V >> E; 48 | 49 | vector adj[V]; 50 | 51 | for(int i = 0; i < E; i++) 52 | { 53 | int u, v; 54 | cin >> u >> v; 55 | adj[u].push_back(v); 56 | } 57 | 58 | Solution obj; 59 | cout << obj.isCyclic(V, adj) << "\n"; 60 | } 61 | 62 | return 0; 63 | } -------------------------------------------------------------------------------- /Graphs/cycleCheckUGDfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // o- based indexing code 5 | 6 | 7 | class Solution { 8 | 9 | public: 10 | bool checkForCycle(int node, int parent, vector &vis, vector adj[]) { 11 | vis[node] = 1; 12 | for(auto it: adj[node]) { 13 | if(!vis[it]) { 14 | if(checkForCycle(it, node, vis, adj)) 15 | return true; 16 | } 17 | else if(it!=parent) 18 | return true; 19 | } 20 | 21 | return false; 22 | } 23 | public: 24 | bool isCycle(int V, vectoradj[]){ 25 | vector vis(V+1, 0); 26 | for(int i = 0;i> tc; 40 | while(tc--){ 41 | int V, E; 42 | cin >> V >> E; 43 | vectoradj[V]; 44 | for(int i = 0; i < E; i++){ 45 | int u, v; 46 | cin >> u >> v; 47 | adj[u].push_back(v); 48 | adj[v].push_back(u); 49 | } 50 | Solution obj; 51 | bool ans = obj.isCycle(V, adj); 52 | if(ans) 53 | cout << "1\n"; 54 | else cout << "0\n"; 55 | } 56 | return 0; 57 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Graphs/bipartiteGraphBfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // Any graph having odd length cycle cannot be bipartite graph 6 | 7 | bool bipartiteBfs(int src, vector adj[], int color[]) { 8 | queueq; 9 | q.push(src); 10 | color[src] = 1; 11 | while(!q.empty()) { 12 | int node = q.front(); 13 | q.pop(); 14 | 15 | for(auto it : adj[node]) { 16 | if(color[it] == -1) { 17 | color[it] = 1 - color[node]; 18 | q.push(it); 19 | } else if(color[it] == color[node]) { 20 | return false; 21 | } 22 | } 23 | } 24 | return true; 25 | } 26 | bool checkBipartite(vector adj[], int n) { 27 | int color[n]; 28 | memset(color, -1, sizeof color); 29 | for(int i = 0;i> n >> m; 41 | vector adj[n]; 42 | for(int i = 0;i> u >> v; 45 | adj[u].push_back(v); 46 | adj[v].push_back(u); 47 | } 48 | 49 | if(checkBipartite(adj, n)) { 50 | cout << "yes"; 51 | } else { 52 | cout << "No"; 53 | } 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Graphs/Djikistra's_Algo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | int n,m,source; 6 | cin >> n >> m; 7 | vector > g[n+1]; // 1-indexed adjacency list for of graph 8 | 9 | int a,b,wt; 10 | for(int i = 0; i> a >> b >> wt; 12 | g[a].push_back(make_pair(b,wt)); 13 | g[b].push_back(make_pair(a,wt)); 14 | } 15 | 16 | cin >> source; 17 | 18 | // Dijkstra's algorithm begins from here 19 | priority_queue,vector >,greater > > pq;// min-heap ; In pair => (dist,from) 20 | vector distTo(n+1,INT_MAX); // 1-indexed array for calculating shortest paths; 21 | 22 | distTo[source] = 0; 23 | pq.push(make_pair(0,source)); // (dist,from) 24 | 25 | while( !pq.empty() ){ 26 | int dist = pq.top().first; 27 | int prev = pq.top().second; 28 | pq.pop(); 29 | 30 | vector >::iterator it; 31 | for( it = g[prev].begin() ; it != g[prev].end() ; it++){ 32 | int next = it->first; 33 | int nextDist = it->second; 34 | if( distTo[next] > distTo[prev] + nextDist){ 35 | distTo[next] = distTo[prev] + nextDist; 36 | pq.push(make_pair(distTo[next], next)); 37 | } 38 | } 39 | 40 | } 41 | 42 | cout << "The distances from source, " << source << ", are : \n"; 43 | for(int i = 1 ; i<=n ; i++) cout << distTo[i] << " "; 44 | cout << "\n"; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Graphs/Kosarajau.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void dfs(int node, stack &st, vector &vis, vector adj[]) { 4 | vis[node] = 1; 5 | for(auto it: adj[node]) { 6 | if(!vis[it]) { 7 | dfs(it, st, vis, adj); 8 | } 9 | } 10 | 11 | st.push(node); 12 | } 13 | void revDfs(int node, vector &vis, vector transpose[]) { 14 | cout << node << " "; 15 | vis[node] = 1; 16 | for(auto it: transpose[node]) { 17 | if(!vis[it]) { 18 | revDfs(it, vis, transpose); 19 | } 20 | } 21 | } 22 | int main() { 23 | int n, m; 24 | cin >> n >> m; 25 | vector adj[n]; 26 | for(int i = 0;i> u >> v; 29 | adj[u].push_back(v); 30 | } 31 | 32 | stack st; 33 | vector vis(n, 0); 34 | for(int i = 0;i transpose[n]; 41 | 42 | for(int i = 0;i>& board) { 4 | solve(board); 5 | } 6 | 7 | bool solve(vector>& board){ 8 | for(int i = 0; i < board.size(); i++){ 9 | for(int j = 0; j < board[0].size(); j++){ 10 | if(board[i][j] == '.'){ 11 | for(char c = '1'; c <= '9'; c++){ 12 | if(isValid(board, i, j, c)){ 13 | board[i][j] = c; 14 | 15 | if(solve(board)) 16 | return true; 17 | else 18 | board[i][j] = '.'; 19 | } 20 | } 21 | 22 | return false; 23 | } 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | bool isValid(vector>& board, int row, int col, char c){ 30 | for(int i = 0; i < 9; i++) { 31 | if(board[i][col] == c) 32 | return false; 33 | 34 | if(board[row][i] == c) 35 | return false; 36 | 37 | if(board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) 38 | return false; 39 | } 40 | return true; 41 | } 42 | }; -------------------------------------------------------------------------------- /Graphs/cycleCheckDGDfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | bool checkCycle(int node, vector adj[], int vis[], int dfsVis[]) { 7 | vis[node] = 1; 8 | dfsVis[node] = 1; 9 | for(auto it : adj[node]) { 10 | if(!vis[it]) { 11 | if(checkCycle(it, adj, vis, dfsVis)) return true; 12 | } else if(dfsVis[it]) { 13 | return true; 14 | } 15 | } 16 | dfsVis[node] = 0; 17 | return false; 18 | } 19 | public: 20 | bool isCyclic(int N, vector adj[]) { 21 | int vis[N], dfsVis[N]; 22 | memset(vis, 0, sizeof vis); 23 | memset(dfsVis, 0, sizeof dfsVis); 24 | 25 | for(int i = 0;i> t; 45 | while(t--) 46 | { 47 | int V, E; 48 | cin >> V >> E; 49 | 50 | vector adj[V]; 51 | 52 | for(int i = 0; i < E; i++) 53 | { 54 | int u, v; 55 | cin >> u >> v; 56 | adj[u].push_back(v); 57 | } 58 | 59 | Solution obj; 60 | cout << obj.isCyclic(V, adj) << "\n"; 61 | } 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Stacks_Queues/StackUsingLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | 7 | int data; 8 | node *next; 9 | 10 | node(int d) 11 | { 12 | data = d; 13 | next = NULL; 14 | } 15 | }; 16 | 17 | struct mystack 18 | { 19 | node *head; 20 | int size; 21 | 22 | mystack() 23 | { 24 | head = NULL; 25 | size = 0; 26 | } 27 | 28 | void push(int x) 29 | { 30 | node *temp = new node(x); 31 | temp->next = head; 32 | head = temp; 33 | size++; 34 | } 35 | 36 | int pop() 37 | { 38 | if (head == NULL) 39 | { 40 | return INT_MAX; 41 | } 42 | 43 | int res = head->data; 44 | node *temp = head; 45 | head = head->next; 46 | size--; 47 | return res; 48 | } 49 | 50 | int sizeo() 51 | { 52 | return size; 53 | } 54 | 55 | int peek() 56 | { 57 | if (head == NULL) 58 | { 59 | return INT_MAX; 60 | } 61 | return head->data; 62 | } 63 | 64 | bool isempty() 65 | { 66 | return (head == NULL); 67 | } 68 | }; 69 | 70 | int main(void) 71 | { 72 | mystack s; 73 | s.push(5); 74 | s.push(10); 75 | s.push(15); 76 | cout << s.pop() << endl; 77 | cout << s.sizeo() << endl; 78 | cout << s.peek() << endl; 79 | cout << s.isempty() << endl; 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /LinkedList/DLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | class node{ 6 | 7 | public: 8 | int data; 9 | node *next; 10 | node *prev; 11 | 12 | node(int val){ 13 | data=val; 14 | next=NULL; 15 | prev=NULL; 16 | } 17 | 18 | }; 19 | 20 | 21 | void insertAtHead(node* &head,int val){ 22 | node* n = new node(val); 23 | n->next=head; 24 | if(head != NULL){ 25 | head->prev=n; 26 | } 27 | 28 | head=n; 29 | } 30 | 31 | void display(node* head){ 32 | node* temp = head; 33 | while(temp!=NULL){ 34 | cout<data<<" "; 35 | temp=temp->data; 36 | }cout<next=NULL){ 50 | temp=temp->next; 51 | } 52 | 53 | temp->next=n; 54 | n->prev=temp; 55 | } 56 | 57 | void deleteAtHead(node* &head){ 58 | node* todelete = head; 59 | head=head->next; 60 | head->prev=NULL; 61 | 62 | delete todelete; 63 | } 64 | 65 | void deletion(node* &head,int pos){ 66 | 67 | if(pos==1){ 68 | deleteAtHead(head); 69 | } 70 | 71 | node* temp=head; 72 | int count=1; 73 | 74 | while(temp!=NULL && count!=pos){ 75 | temp=temp->next; 76 | count++; 77 | } 78 | 79 | temp->prev->next=temp->next; 80 | if(temp->next!=NULL){ 81 | temp->next->prev=temp->prev; 82 | } 83 | delete temp; 84 | 85 | } 86 | 87 | 88 | int main(){ 89 | 90 | 91 | 92 | return 0; 93 | } 94 | 95 | -------------------------------------------------------------------------------- /Recursion_Backtracking/NQueen.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | void solve(int col, vector &board, vector> &ans, 5 | vector &leftRow, 6 | vector &upperDiagonal, vector &lowerDiagonal, int n) { 7 | if(col == n) { 8 | ans.push_back(board); 9 | return; 10 | } 11 | 12 | 13 | for(int row = 0;row> solveNQueens(int n) { 31 | vector> ans; 32 | vector board(n); 33 | string s(n, '.'); 34 | for(int i = 0;i leftRow(n, 0), upperDiagonal(2 * n - 1, 0), lowerDiagonal(2 * n - 1, 0); 38 | solve(0,board, ans, leftRow, upperDiagonal, lowerDiagonal, n); 39 | return ans; 40 | } 41 | 42 | }; -------------------------------------------------------------------------------- /Trees/boundaryTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | bool isLeaf(Node* root) { 3 | return !root->left && !root->right; 4 | } 5 | 6 | void addLeftBoundary(Node* root, vector &res) { 7 | Node* cur = root->left; 8 | while (cur) { 9 | if (!isLeaf(cur)) res.push_back(cur->data); 10 | if (cur->left) cur = cur->left; 11 | else cur = cur->right; 12 | } 13 | } 14 | void addRightBoundary(Node* root, vector &res) { 15 | Node* cur = root->right; 16 | vector tmp; 17 | while (cur) { 18 | if (!isLeaf(cur)) tmp.push_back(cur->data); 19 | if (cur->right) cur = cur->right; 20 | else cur = cur->left; 21 | } 22 | for (int i = tmp.size()-1; i >= 0; --i) { 23 | res.push_back(tmp[i]); 24 | } 25 | } 26 | 27 | void addLeaves(Node* root, vector& res) { 28 | if (isLeaf(root)) { 29 | res.push_back(root->data); 30 | return; 31 | } 32 | if (root->left) addLeaves(root->left, res); 33 | if (root->right) addLeaves(root->right, res); 34 | } 35 | public: 36 | vector printBoundary(Node *root) 37 | { 38 | vector res; 39 | if (!root) return res; 40 | 41 | if (!isLeaf(root)) res.push_back(root->data); 42 | 43 | addLeftBoundary(root, res); 44 | 45 | // add leaf nodes 46 | addLeaves(root, res); 47 | 48 | addRightBoundary(root, res); 49 | return res; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Arrays/CountInversions.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int _mergeSort(int arr[], int temp[], int left, int right); 6 | int merge(int arr[], int temp[], int left, int mid, 7 | int right); 8 | 9 | 10 | int mergeSort(int arr[], int array_size) 11 | { 12 | int temp[array_size]; 13 | return _mergeSort(arr, temp, 0, array_size - 1); 14 | } 15 | 16 | int _mergeSort(int arr[], int temp[], int left, int right) 17 | { 18 | int mid, inv_count = 0; 19 | if (right > left) { 20 | mid = (right + left) / 2; 21 | 22 | inv_count += _mergeSort(arr, temp, left, mid); 23 | inv_count += _mergeSort(arr, temp, mid + 1, right); 24 | 25 | inv_count += merge(arr, temp, left, mid + 1, right); 26 | } 27 | return inv_count; 28 | } 29 | 30 | int merge(int arr[], int temp[], int left, int mid, 31 | int right) 32 | { 33 | int i, j, k; 34 | int inv_count = 0; 35 | 36 | i = left; 37 | j = mid; 38 | k = left; 39 | while ((i <= mid - 1) && (j <= right)) { 40 | if (arr[i] <= arr[j]) { 41 | temp[k++] = arr[i++]; 42 | } 43 | else { 44 | temp[k++] = arr[j++]; 45 | 46 | 47 | inv_count = inv_count + (mid - i); 48 | } 49 | } 50 | 51 | 52 | while (i <= mid - 1) 53 | temp[k++] = arr[i++]; 54 | 55 | 56 | while (j <= right) 57 | temp[k++] = arr[j++]; 58 | 59 | 60 | for (i = left; i <= right; i++) 61 | arr[i] = temp[i]; 62 | 63 | return inv_count; 64 | } 65 | 66 | int main() 67 | { 68 | int arr[] = { 1, 20, 6, 4, 5 }; 69 | int n = 5; 70 | int ans = mergeSort(arr, n); 71 | cout << " Number of inversions are " << ans; 72 | return 0; 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /Graphs/KrusKals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node { 4 | int u; 5 | int v; 6 | int wt; 7 | node(int first, int second, int weight) { 8 | u = first; 9 | v = second; 10 | wt = weight; 11 | } 12 | }; 13 | 14 | bool comp(node a, node b) { 15 | return a.wt < b.wt; 16 | } 17 | 18 | int findPar(int u, vector &parent) { 19 | if(u == parent[u]) return u; 20 | return parent[u] = findPar(parent[u], parent); 21 | } 22 | 23 | void unionn(int u, int v, vector &parent, vector &rank) { 24 | u = findPar(u, parent); 25 | v = findPar(v, parent); 26 | if(rank[u] < rank[v]) { 27 | parent[u] = v; 28 | } 29 | else if(rank[v] < rank[u]) { 30 | parent[v] = u; 31 | } 32 | else { 33 | parent[v] = u; 34 | rank[u]++; 35 | } 36 | } 37 | int main(){ 38 | int N,m; 39 | cin >> N >> m; 40 | vector edges; 41 | for(int i = 0;i> u >> v >> wt; 44 | edges.push_back(node(u, v, wt)); 45 | } 46 | sort(edges.begin(), edges.end(), comp); 47 | 48 | vector parent(N); 49 | for(int i = 0;i rank(N, 0); 52 | 53 | int cost = 0; 54 | vector> mst; 55 | for(auto it : edges) { 56 | if(findPar(it.v, parent) != findPar(it.u, parent)) { 57 | cost += it.wt; 58 | mst.push_back({it.u, it.v}); 59 | unionn(it.u, it.v, parent, rank); 60 | } 61 | } 62 | cout << cost << endl; 63 | for(auto it : mst) cout << it.first << " - " << it.second << endl; 64 | return 0; 65 | } -------------------------------------------------------------------------------- /DP/WordBreak.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | unordered_set dict; 6 | 7 | void printResult(vector A) 8 | { 9 | for (int i = 0; i < A.size(); i++) 10 | cout << A[i] << '\n'; 11 | } 12 | 13 | 14 | vector combine(vector prev, string word){ 15 | 16 | // Loop to find the append string 17 | // which can be broken into 18 | for (int i = 0; i < prev.size(); i++) { 19 | prev[i] += " " + word; 20 | } 21 | return prev; 22 | } 23 | 24 | // Utility function for word Break 25 | vector wordBreakUtil(string s) 26 | { 27 | // Condition to check if the 28 | // subproblem is already computed 29 | if (mp.find(s) != mp.end()) 30 | return mp[s]; 31 | vector res; 32 | 33 | 34 | if (dict.find(s) != dict.end()) 35 | res.push_back(s); 36 | 37 | // Loop to iterate over the substring 38 | for (int i = 1; i < s.length(); i++) { 39 | string word = s.substr(i); 40 | if (dict.find(word) != dict.end()) { 41 | string rem = s.substr(0, i); 42 | vector prev = 43 | combine(wordBreakUtil(rem), word); 44 | res.insert(res.end(), 45 | prev.begin(), prev.end()); 46 | } 47 | } 48 | 49 | mp[s] = res; 50 | return res; 51 | } 52 | 53 | 54 | vector wordBreak(string s,vector& wordDict) 55 | { 56 | // Clear the previous stored data 57 | mp.clear(); 58 | dict.clear(); 59 | dict.insert(wordDict.begin(), wordDict.end()); 60 | return wordBreakUtil(s); 61 | } 62 | 63 | int main() 64 | { 65 | vector wordDict1 = { 66 | "cat", "cats", "and", "sand", "dog" }; 67 | printResult(wordBreak("catsanddog", wordDict1)); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Stacks_Queues/two_stack_in_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct twostacks 5 | { 6 | int *arr; 7 | int top1; 8 | int top2; 9 | int cap; 10 | 11 | twostacks(int n) 12 | { 13 | cap = n; 14 | arr = new int[cap]; 15 | top1 = -1; 16 | top2 = cap; 17 | } 18 | 19 | void push1(int x) 20 | { 21 | if (top1 < top2 - 1) 22 | { 23 | top1++; 24 | arr[top1] = x; 25 | } 26 | } 27 | void push2(int x) 28 | { 29 | if (top2 - 1 > top1) 30 | { 31 | top2--; 32 | arr[top2] = x; 33 | } 34 | } 35 | 36 | int pop1() 37 | { 38 | if (top1 >= 0) 39 | { 40 | int res = arr[top1]; 41 | top1--; 42 | return res; 43 | } 44 | else 45 | { 46 | exit(1); 47 | } 48 | } 49 | int pop2() 50 | { 51 | if (top2 < cap) 52 | { 53 | int res = arr[top2]; 54 | top2++; 55 | return res; 56 | } 57 | else 58 | { 59 | exit(1); 60 | } 61 | } 62 | 63 | int size1() 64 | { 65 | return top1 + 1; 66 | } 67 | 68 | int size2() 69 | { 70 | return (cap - top2); 71 | } 72 | }; 73 | 74 | int main(void) 75 | { 76 | twostacks s(5); 77 | s.push1(5); 78 | s.push1(10); 79 | s.push2(20); 80 | s.push2(30); 81 | s.push2(40); 82 | cout << s.pop1() << endl; 83 | cout << s.size1() << endl; 84 | cout << s.size2() << endl; 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /LinkedList/cloneLL.cpp: -------------------------------------------------------------------------------- 1 | class Node { 2 | public: 3 | int val; 4 | Node* next; 5 | Node* random; 6 | 7 | Node(int _val) { 8 | val = _val; 9 | next = NULL; 10 | random = NULL; 11 | } 12 | }; 13 | 14 | class Solution { 15 | public: 16 | Node* copyRandomList(Node* head) { 17 | Node *iter = head; 18 | Node *front = head; 19 | 20 | // First round: make copy of each node, 21 | // and link them together side-by-side in a single list. 22 | while (iter != NULL) { 23 | front = iter->next; 24 | 25 | Node *copy = new Node(iter->val); 26 | iter->next = copy; 27 | copy->next = front; 28 | 29 | iter = front; 30 | } 31 | 32 | // Second round: assign random pointers for the copy nodes. 33 | iter = head; 34 | while (iter != NULL) { 35 | if (iter->random != NULL) { 36 | iter->next->random = iter->random->next; 37 | } 38 | iter = iter->next->next; 39 | } 40 | 41 | // Third round: restore the original list, and extract the copy list. 42 | iter = head; 43 | Node *pseudoHead = new Node(0); 44 | Node *copy = pseudoHead; 45 | 46 | while (iter != NULL) { 47 | front = iter->next->next; 48 | 49 | // extract the copy 50 | copy->next = iter->next; 51 | 52 | // restore the original list 53 | iter->next = front; 54 | 55 | copy = copy -> next; 56 | iter = front; 57 | } 58 | 59 | return pseudoHead->next; 60 | } 61 | }; -------------------------------------------------------------------------------- /Graphs/cycleCheckUGBfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // } Driver Code Ends 5 | 6 | 7 | class Solution { 8 | 9 | public: 10 | bool checkForCycle(int s, int V, vector adj[], vector& visited) 11 | { 12 | vector parent(V, -1); 13 | 14 | // Create a queue for BFS 15 | queue> q; 16 | 17 | visited[s] = true; 18 | q.push({s, -1}); 19 | 20 | while (!q.empty()) { 21 | 22 | int node = q.front().first; 23 | int par = q.front().second; 24 | q.pop(); 25 | 26 | for (auto it : adj[node]) { 27 | if (!visited[it]) { 28 | visited[it] = true; 29 | q.push({it, node}); 30 | } 31 | else if (par != it) 32 | return true; 33 | } 34 | } 35 | return false; 36 | } 37 | public: 38 | bool isCycle(int V, vectoradj[]){ 39 | vector vis(V, 0); 40 | for(int i = 0;i> tc; 54 | while(tc--){ 55 | int V, E; 56 | cin >> V >> E; 57 | vectoradj[V]; 58 | for(int i = 0; i < E; i++){ 59 | int u, v; 60 | cin >> u >> v; 61 | adj[u].push_back(v); 62 | adj[v].push_back(u); 63 | } 64 | Solution obj; 65 | bool ans = obj.isCycle(V, adj); 66 | if(ans) 67 | cout << "1\n"; 68 | else cout << "0\n"; 69 | } 70 | return 0; 71 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Graphs/TopologicalSortDFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution{ 5 | void findTopoSort(int node, vector &vis, stack &st, vector adj[]) { 6 | vis[node] = 1; 7 | 8 | for(auto it : adj[node]) { 9 | if(!vis[it]) { 10 | findTopoSort(it, vis, st, adj); 11 | } 12 | } 13 | st.push(node); 14 | } 15 | public: 16 | vector topoSort(int N, vector adj[]) { 17 | stack st; 18 | vector vis(N, 0); 19 | for(int i = 0;i topo; 25 | while(!st.empty()) { 26 | topo.push_back(st.top()); 27 | st.pop(); 28 | } 29 | return topo; 30 | 31 | } 32 | }; 33 | 34 | 35 | int check(int V, vector &res, vector adj[]) { 36 | vector map(V, -1); 37 | for (int i = 0; i < V; i++) { 38 | map[res[i]] = i; 39 | } 40 | for (int i = 0; i < V; i++) { 41 | for (int v : adj[i]) { 42 | if (map[i] > map[v]) return 0; 43 | } 44 | } 45 | return 1; 46 | } 47 | 48 | int main() { 49 | int T; 50 | cin >> T; 51 | while (T--) { 52 | int N, E; 53 | cin >> E >> N; 54 | int u, v; 55 | 56 | vector adj[N]; 57 | 58 | for (int i = 0; i < E; i++) { 59 | cin >> u >> v; 60 | adj[u].push_back(v); 61 | } 62 | 63 | Solution obj; 64 | vector res = obj.topoSort(N, adj); 65 | 66 | cout << check(N, res, adj) << endl; 67 | } 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Stacks_Queues/infixtopostfixusingstacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | string postfix(string s); 8 | int check(char c); 9 | 10 | int main(){ 11 | string inputvalue; 12 | cout<<"ENTER THE INFIX EXPRESSION"<>inputvalue; 14 | cout< mystack; 35 | string result; 36 | 37 | for (int i = 0; i < s.length(); i++) 38 | { 39 | if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')) 40 | { 41 | result+=s[i]; 42 | } 43 | else if(s[i]=='('){ 44 | mystack.push(s[i]); 45 | } 46 | else if(s[i]==')'){ 47 | while (!mystack.empty() && mystack.top()!= '(') 48 | { 49 | result+=mystack.top(); 50 | mystack.pop(); 51 | } 52 | if(!mystack.empty()){ 53 | mystack.pop(); 54 | } 55 | 56 | } 57 | else{ 58 | while(!mystack.empty() && check(mystack.top())>check(s[i])){ 59 | result+=mystack.top(); 60 | mystack.pop(); 61 | } 62 | mystack.push(s[i]); 63 | } 64 | } 65 | while(!mystack.empty()){ 66 | result+=mystack.top(); 67 | mystack.pop(); 68 | } 69 | return result; 70 | 71 | } 72 | -------------------------------------------------------------------------------- /LinkedList/RotateaLL.cpp: -------------------------------------------------------------------------------- 1 | ListNode* rotateRight(ListNode* head, int k){ 2 | if(!head || !head->next || k==0){ 3 | return head; 4 | } 5 | 6 | ListNode *cur = head; 7 | int len=1; 8 | while(cur->next && ++len){ 9 | cur=cur->next; 10 | } 11 | 12 | cur->next=head; 13 | k=k % len; 14 | k=len - k; 15 | while(k--){ 16 | cur=cur->next; 17 | } 18 | 19 | head=cur->next; 20 | cur->next=NULL; 21 | 22 | return head; 23 | } 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | #include 38 | using namespace std; 39 | 40 | string generateKey(string str, string key) 41 | { 42 | int x = str.size(); 43 | 44 | for (int i = 0; ; i++) 45 | { 46 | if (x == i) 47 | i = 0; 48 | if (key.size() == str.size()) 49 | break; 50 | key.push_back(key[i]); 51 | } 52 | return key; 53 | } 54 | 55 | string cipherText(string str, string key) 56 | { 57 | string cipher_text; 58 | 59 | for (int i = 0; i < str.size(); i++) 60 | { 61 | char x = (str[i] + key[i]) %26; 62 | x += 'A'; 63 | 64 | cipher_text.push_back(x); 65 | } 66 | return cipher_text; 67 | } 68 | 69 | string originalText(string cipher_text, string key) 70 | { 71 | string orig_text; 72 | 73 | for (int i = 0 ; i < cipher_text.size(); i++) 74 | { 75 | char x = (cipher_text[i] - key[i] + 26) %26; 76 | 77 | x += 'A'; 78 | orig_text.push_back(x); 79 | } 80 | return orig_text; 81 | } 82 | 83 | 84 | int main(){ 85 | 86 | 87 | string str; cin>>str; 88 | string key; cin>>key; 89 | 90 | string key = generateKey(str, keyword); 91 | string cipher_text = cipherText(str, key); 92 | 93 | cout << "Ciphertext : "<< cipher_text < 2 | using namespace std; 3 | 4 | 5 | class node{ 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int val){ 11 | data=val; 12 | next=NULL; 13 | } 14 | }; 15 | 16 | 17 | void deleteAtHead(node* &head){ 18 | node* temp = head; 19 | while(temp->next!=head){ 20 | temp=temp->next; 21 | } 22 | 23 | node* todelete = head; 24 | temp->next=head->next; 25 | head=head->next; 26 | 27 | 28 | delete todelete; 29 | } 30 | 31 | 32 | 33 | void deletion(node* &head,int pos){ 34 | 35 | if(pos==1){ 36 | deleteAtHead(head); 37 | return; 38 | } 39 | 40 | node* temp=head; 41 | int count=1; 42 | 43 | 44 | while(count!=pos-1){ 45 | temp=temp->next; 46 | count++; 47 | } 48 | 49 | node* todelete = temp->next; 50 | temp->next=temp->next->next; 51 | 52 | 53 | delete todelete; 54 | } 55 | 56 | void insertAtHead(node* &head,int val){ 57 | node* n = new node(val); 58 | 59 | if(head==NULL){ 60 | n->next=n; 61 | head=n; 62 | return; 63 | } 64 | 65 | while(temp->next!=head){ 66 | temp=temp->next; 67 | } 68 | 69 | temp->next=n; 70 | n->next=head; 71 | head=n; 72 | } 73 | 74 | 75 | void display(node* head){ 76 | node* temp = head; 77 | do{ 78 | cout<data<<" "; 79 | temp=temp->next; 80 | }while(temp!=head); 81 | } 82 | 83 | void insertAtTail(node* &head,int val){ 84 | 85 | if(head==NULL){ 86 | insertAtHead(head,val); 87 | return; 88 | } 89 | 90 | node* n = new node(val); 91 | node* temp = head; 92 | 93 | 94 | while(temp->next!=head){ 95 | temp=temp->next; 96 | } 97 | 98 | temp->next=n; 99 | n->next=head; 100 | } 101 | 102 | 103 | 104 | int main(){ 105 | 106 | 107 | 108 | return 0; 109 | } -------------------------------------------------------------------------------- /Strings/KMP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void lps_func(string txt, vector&Lps){ 5 | Lps[0] = 0; 6 | int len = 0; 7 | int i=1; 8 | while (iLps(m); 34 | 35 | lps_func(pattern,Lps); // This function constructs the Lps array. 36 | 37 | int i=0,j=0; 38 | while(i 5 | using namespace std; 6 | 7 | // Returns count of subarrays of arr with XOR 8 | // value equals to m 9 | long long subarrayXor(int arr[], int n, int m) 10 | { 11 | long long ans = 0; // Initialize answer to be returned 12 | 13 | // Create a prefix xor-sum array such that 14 | // xorArr[i] has value equal to XOR 15 | // of all elements in arr[0 ..... i] 16 | int* xorArr = new int[n]; 17 | 18 | // Create map that stores number of prefix array 19 | // elements corresponding to a XOR value 20 | unordered_map mp; 21 | 22 | // Initialize first element of prefix array 23 | xorArr[0] = arr[0]; 24 | 25 | // Computing the prefix array. 26 | for (int i = 1; i < n; i++) 27 | xorArr[i] = xorArr[i - 1] ^ arr[i]; 28 | 29 | // Calculate the answer 30 | for (int i = 0; i < n; i++) { 31 | 32 | // Find XOR of current prefix with m. 33 | int tmp = m ^ xorArr[i]; 34 | 35 | // If above XOR exists in map, then there 36 | // is another previous prefix with same 37 | // XOR, i.e., there is a subarray ending 38 | // at i with XOR equal to m. 39 | ans = ans + ((long long)mp[tmp]); 40 | 41 | // If this subarray has XOR equal to m itself. 42 | if (xorArr[i] == m) 43 | ans++; 44 | 45 | // Add the XOR of this subarray to the map 46 | mp[xorArr[i]]++; 47 | } 48 | 49 | // Return total count of subarrays having XOR of 50 | // elements as given value m 51 | return ans; 52 | } 53 | 54 | // Driver program to test above function 55 | int main() 56 | { 57 | int arr[] = { 4, 2, 2, 6, 4 }; 58 | int n = sizeof(arr) / sizeof(arr[0]); 59 | int m = 6; 60 | 61 | cout << "Number of subarrays having given XOR is " 62 | << subarrayXor(arr, n, m); 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Graphs/Prims.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int N,m; 7 | cin >> N >> m; 8 | vector > adj[N]; 9 | 10 | int a,b,wt; 11 | for(int i = 0; i> a >> b >> wt; 13 | adj[a].push_back(make_pair(b,wt)); 14 | adj[b].push_back(make_pair(a,wt)); 15 | } 16 | 17 | int parent[N]; 18 | 19 | int key[N]; 20 | 21 | bool mstSet[N]; 22 | 23 | for (int i = 0; i < N; i++) 24 | key[i] = INT_MAX, mstSet[i] = false; 25 | 26 | priority_queue< pair, vector > , greater> > pq; 27 | 28 | key[0] = 0; 29 | parent[0] = -1; 30 | pq.push({0, 0}); 31 | // Run the loop till all the nodes have been visited 32 | // because in the brute code we checked for mstSet[node] == false while computing the minimum 33 | // but here we simply take the minimal from the priority queue, so a lot of times a node might be taken twice 34 | // hence its better to keep running till all the nodes have been taken. 35 | // try the following case: 36 | // Credits: Srejan Bera 37 | // 6 7 38 | // 0 1 5 39 | // 0 2 10 40 | // 0 3 100 41 | // 1 3 50 42 | // 1 4 200 43 | // 3 4 250 44 | // 4 5 50 45 | while(!pq.empty()) 46 | { 47 | int u = pq.top().second; 48 | pq.pop(); 49 | 50 | mstSet[u] = true; 51 | 52 | for (auto it : adj[u]) { 53 | int v = it.first; 54 | int weight = it.second; 55 | if (mstSet[v] == false && weight < key[v]) { 56 | parent[v] = u; 57 | key[v] = weight; 58 | pq.push({key[v], v}); 59 | } 60 | } 61 | 62 | } 63 | 64 | for (int i = 1; i < N; i++) 65 | cout << parent[i] << " - " << i <<" \n"; 66 | return 0; 67 | } -------------------------------------------------------------------------------- /Trees/SeriaLizeAndDeseriaLize.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Codec { 3 | public: 4 | 5 | // Encodes a tree to a single string. 6 | string serialize(TreeNode* root) { 7 | if(!root) return ""; 8 | 9 | string s =""; 10 | queue q; 11 | q.push(root); 12 | while(!q.empty()) { 13 | TreeNode* curNode = q.front(); 14 | q.pop(); 15 | if(curNode==NULL) s.append("#,"); 16 | else s.append(to_string(curNode->val)+','); 17 | if(curNode != NULL){ 18 | q.push(curNode->left); 19 | q.push(curNode->right); 20 | } 21 | } 22 | return s; 23 | } 24 | 25 | // Decodes your encoded data to tree. 26 | TreeNode* deserialize(string data) { 27 | if(data.size() == 0) return NULL; 28 | stringstream s(data); 29 | string str; 30 | getline(s, str, ','); 31 | TreeNode *root = new TreeNode(stoi(str)); 32 | queue q; 33 | q.push(root); 34 | while(!q.empty()) { 35 | 36 | TreeNode *node = q.front(); 37 | q.pop(); 38 | 39 | getline(s, str, ','); 40 | if(str == "#") { 41 | node->left = NULL; 42 | } 43 | else { 44 | TreeNode* leftNode = new TreeNode(stoi(str)); 45 | node->left = leftNode; 46 | q.push(leftNode); 47 | } 48 | 49 | getline(s, str, ','); 50 | if(str == "#") { 51 | node->right = NULL; 52 | } 53 | else { 54 | TreeNode* rightNode = new TreeNode(stoi(str)); 55 | node->right = rightNode; 56 | q.push(rightNode); 57 | } 58 | } 59 | return root; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /Stacks_Queues/LRU.cpp: -------------------------------------------------------------------------------- 1 | 2 | class LRUCache { 3 | public: 4 | class node { 5 | public: 6 | int key; 7 | int val; 8 | node* next; 9 | node* prev; 10 | node(int _key, int _val) { 11 | key = _key; 12 | val = _val; 13 | } 14 | }; 15 | 16 | node* head = new node(-1,-1); 17 | node* tail = new node(-1,-1); 18 | 19 | int cap; 20 | unordered_mapm; 21 | 22 | LRUCache(int capacity) { 23 | cap = capacity; 24 | head->next = tail; 25 | tail->prev = head; 26 | } 27 | 28 | void addnode(node* newnode) { 29 | node* temp = head->next; 30 | newnode->next = temp; 31 | newnode->prev = head; 32 | head->next = newnode; 33 | temp->prev = newnode; 34 | } 35 | 36 | void deletenode(node* delnode) { 37 | node* delprev = delnode->prev; 38 | node* delnext = delnode->next; 39 | delprev->next = delnext; 40 | delnext->prev = delprev; 41 | } 42 | 43 | int get(int key_) { 44 | if (m.find(key_) != m.end()) { 45 | node* resnode = m[key_]; 46 | int res = resnode->val; 47 | m.erase(key_); 48 | deletenode(resnode); 49 | addnode(resnode); 50 | m[key_] = head->next; 51 | return res; 52 | } 53 | 54 | return -1; 55 | } 56 | 57 | void put(int key_, int value) { 58 | if(m.find(key_) != m.end()) { 59 | node* existingnode = m[key_]; 60 | m.erase(key_); 61 | deletenode(existingnode); 62 | } 63 | if(m.size() == cap) { 64 | m.erase(tail->prev->key); 65 | deletenode(tail->prev); 66 | } 67 | 68 | addnode(new node(key_, value)); 69 | m[key_] = head->next; 70 | } 71 | }; -------------------------------------------------------------------------------- /Trees/Alltraversals.cpp: -------------------------------------------------------------------------------- 1 | // LC link : https://leetcode.com/problems/binary-tree-postorder-traversal 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | 16 | public: 17 | vector postorderTraversal(TreeNode* root) { 18 | stack> st; 19 | st.push({root, 1}); 20 | vector pre, in, post; 21 | if(root == NULL) return post; 22 | 23 | while(!st.empty()) { 24 | auto it = st.top(); 25 | st.pop(); 26 | 27 | // this is part of pre 28 | // increment 1 to 2 29 | // push the left side of the tree 30 | if(it.second == 1) { 31 | pre.push_back(it.first->val); 32 | it.second++; 33 | st.push(it); 34 | 35 | if(it.first->left != NULL) { 36 | st.push({it.first->left, 1}); 37 | } 38 | } 39 | 40 | // this is a part of in 41 | // increment 2 to 3 42 | // push right 43 | else if(it.second == 2) { 44 | in.push_back(it.first->val); 45 | it.second++; 46 | st.push(it); 47 | 48 | if(it.first->right != NULL) { 49 | st.push({it.first->right, 1}); 50 | } 51 | } 52 | // don't push it back again 53 | else { 54 | post.push_back(it.first->val); 55 | } 56 | } 57 | 58 | return post; 59 | } 60 | }; 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /Strings/RabinKarp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define d 256 5 | 6 | 7 | void search(char pat[], char txt[], int q) 8 | { 9 | int M = strlen(pat); 10 | int N = strlen(txt); 11 | int i, j; 12 | int p = 0; // hash value for pattern 13 | int t = 0; // hash value for txt 14 | int h = 1; 15 | 16 | // The value of h would be "pow(d, M-1)%q" 17 | for (i = 0; i < M - 1; i++) 18 | h = (h * d) % q; 19 | 20 | // Calculate the hash value of pattern and first 21 | // window of text 22 | for (i = 0; i < M; i++) 23 | { 24 | p = (d * p + pat[i]) % q; 25 | t = (d * t + txt[i]) % q; 26 | } 27 | 28 | // Slide the pattern over text one by one 29 | for (i = 0; i <= N - M; i++) 30 | { 31 | 32 | // Check the hash values of current window of text 33 | // and pattern. If the hash values match then only 34 | // check for characters one by one 35 | if ( p == t ) 36 | { 37 | bool flag = true; 38 | /* Check for characters one by one */ 39 | for (j = 0; j < M; j++) 40 | { 41 | if (txt[i+j] != pat[j]) 42 | { 43 | flag = false; 44 | break; 45 | } 46 | if(flag) 47 | cout< 5 | using namespace std; 6 | 7 | /* The output of this function is stored at 8 | *x and *y */ 9 | void getTwoElements(int arr[], int n, 10 | int* x, int* y) 11 | { 12 | /* Will hold xor of all elements 13 | and numbers from 1 to n */ 14 | int xor1; 15 | 16 | /* Will have only single set bit of xor1 */ 17 | int set_bit_no; 18 | 19 | int i; 20 | *x = 0; 21 | *y = 0; 22 | 23 | xor1 = arr[0]; 24 | 25 | /* Get the xor of all array elements */ 26 | for (i = 1; i < n; i++) 27 | xor1 = xor1 ^ arr[i]; 28 | 29 | /* XOR the previous result with numbers 30 | from 1 to n*/ 31 | for (i = 1; i <= n; i++) 32 | xor1 = xor1 ^ i; 33 | 34 | /* Get the rightmost set bit in set_bit_no */ 35 | set_bit_no = xor1 & ~(xor1 - 1); 36 | 37 | /* Now divide elements into two 38 | sets by comparing a rightmost set 39 | bit of xor1 with the bit at the same 40 | position in each element. Also, 41 | get XORs of two sets. The two 42 | XORs are the output elements. 43 | The following two for loops 44 | serve the purpose */ 45 | for (i = 0; i < n; i++) { 46 | if (arr[i] & set_bit_no) 47 | /* arr[i] belongs to first set */ 48 | *x = *x ^ arr[i]; 49 | 50 | else 51 | /* arr[i] belongs to second set*/ 52 | *y = *y ^ arr[i]; 53 | } 54 | for (i = 1; i <= n; i++) { 55 | if (i & set_bit_no) 56 | /* i belongs to first set */ 57 | *x = *x ^ i; 58 | 59 | else 60 | /* i belongs to second set*/ 61 | *y = *y ^ i; 62 | } 63 | 64 | /* *x and *y hold the desired 65 | output elements */ 66 | } 67 | 68 | /* Driver code */ 69 | int main() 70 | { 71 | int arr[] = { 1, 3, 4, 5, 5, 6, 2 }; 72 | int* x = (int*)malloc(sizeof(int)); 73 | int* y = (int*)malloc(sizeof(int)); 74 | int n = sizeof(arr) / sizeof(arr[0]); 75 | 76 | getTwoElements(arr, n, x, y); 77 | cout << " The missing element is " << *x << " and the repeating" 78 | << " number is " << *y; 79 | getchar(); 80 | } 81 | 82 | // This code is contributed by Code_Mech 83 | -------------------------------------------------------------------------------- /Trees/timeToBurnATree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int findMaxDistance(map*, BinaryTreeNode*> &mpp, BinaryTreeNode* target) { 4 | queue*> q; 5 | q.push(target); 6 | map*,int> vis; 7 | vis[target] = 1; 8 | int maxi = 0; 9 | while(!q.empty()) { 10 | int sz = q.size(); 11 | int fl = 0; 12 | for(int i = 0;ileft && !vis[node->left]) { 16 | fl = 1; 17 | vis[node->left] = 1; 18 | q.push(node->left); 19 | } 20 | if(node->right && !vis[node->right]) { 21 | fl = 1; 22 | vis[node->right] = 1; 23 | q.push(node->right); 24 | } 25 | 26 | if(mpp[node] && !vis[mpp[node]]) { 27 | fl = 1; 28 | vis[mpp[node]] = 1; 29 | q.push(mpp[node]); 30 | } 31 | } 32 | if(fl) maxi++; 33 | } 34 | return maxi; 35 | } 36 | BinaryTreeNode* bfsToMapParents(BinaryTreeNode* root, 37 | map*, BinaryTreeNode*> &mpp, int start) { 38 | queue*> q; 39 | q.push(root); 40 | BinaryTreeNode* res; 41 | while(!q.empty()) { 42 | BinaryTreeNode* node = q.front(); 43 | if(node->data == start) res = node; 44 | q.pop(); 45 | if(node->left) { 46 | mpp[node->left] = node; 47 | q.push(node->left); 48 | } 49 | if(node->right) { 50 | mpp[node->right] = node; 51 | q.push(node->right); 52 | } 53 | } 54 | return res; 55 | } 56 | int timeToBurnTree(BinaryTreeNode* root, int start) 57 | { 58 | map*, BinaryTreeNode*> mpp; 59 | BinaryTreeNode* target = bfsToMapParents(root, mpp, start); 60 | int maxi = findMaxDistance(mpp, target); 61 | return maxi; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Recursion_Backtracking/RatInAMaze.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | void solve(int i, int j, vector> &a, int n, vector &ans, string move, 3 | vector> &vis, int di[], int dj[]) { 4 | if(i==n-1 && j==n-1) { 5 | ans.push_back(move); 6 | return; 7 | } 8 | string dir = "DLRU"; // states Down Left Right Up 9 | for(int ind = 0; ind<4;ind++) { 10 | int nexti = i + di[ind]; 11 | int nextj = j + dj[ind]; 12 | if(nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && !vis[nexti][nextj] && a[nexti][nextj] == 1) { 13 | vis[i][j] = 1; 14 | solve(nexti, nextj, a, n, ans, move + dir[ind], vis, di, dj); 15 | vis[i][j] = 0; 16 | } 17 | } 18 | // downward 19 | // if(i+1=0 && !vis[i][j-1] && a[i][j-1] == 1) { 27 | // vis[i][j] = 1; 28 | // solve(i, j-1, a, n, ans, move + 'L', vis); 29 | // vis[i][j] = 0; 30 | // } 31 | 32 | // // right 33 | // if(j+1=0 && !vis[i-1][j] && a[i-1][j] == 1) { 41 | // vis[i][j] = 1; 42 | // solve(i-1, j, a, n, ans, move + 'U', vis); 43 | // vis[i][j] = 0; 44 | // } 45 | } 46 | public: 47 | vector findPath(vector> &m, int n) { 48 | vector ans; 49 | vector> vis(n, vector (n, 0)); 50 | int di[] = {+1, 0, 0, -1}; 51 | int dj[] = {0, -1, 1, 0}; 52 | if(m[0][0] == 1) solve(0,0,m,n, ans, "", vis, di, dj); 53 | return ans; 54 | } 55 | }; -------------------------------------------------------------------------------- /Graphs/NumberOfIslands.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void DFS(vector> &M, int i, int j, int ROW, 6 | int COL) 7 | { 8 | //Base condition 9 | //if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return 10 | if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) 11 | { 12 | return; 13 | } 14 | 15 | if (M[i][j] == 1) 16 | { 17 | M[i][j] = 0; 18 | DFS(M, i + 1, j, ROW, COL); //right side traversal 19 | DFS(M, i - 1, j, ROW, COL); //left side traversal 20 | DFS(M, i, j + 1, ROW, COL); //upward side traversal 21 | DFS(M, i, j - 1, ROW, COL); //downward side traversal 22 | DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal 23 | DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal 24 | DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal 25 | DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal 26 | } 27 | } 28 | 29 | int countIslands(vector> &M) 30 | { 31 | int ROW = M.size(); 32 | int COL = M[0].size(); 33 | int count = 0; 34 | for (int i = 0; i < ROW; i++) 35 | { 36 | for (int j = 0; j < COL; j++) 37 | { 38 | if (M[i][j] == 1) 39 | { 40 | M[i][j] = 0; 41 | count++; 42 | DFS(M, i + 1, j, ROW, COL); //right side traversal 43 | DFS(M, i - 1, j, ROW, COL); //left side traversal 44 | DFS(M, i, j + 1, ROW, COL); //upward side traversal 45 | DFS(M, i, j - 1, ROW, COL); //downward side traversal 46 | DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal 47 | DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal 48 | DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal 49 | DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal 50 | } 51 | } 52 | } 53 | return count; 54 | } 55 | 56 | // Driver Code 57 | int main() 58 | { 59 | vector> M = {{1, 1, 0, 0, 0}, 60 | {0, 1, 0, 0, 1}, 61 | {1, 0, 0, 1, 1}, 62 | {0, 0, 0, 0, 0}, 63 | {1, 0, 1, 0, 1}}; 64 | 65 | cout << "Number of islands is: " << countIslands(M); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Stacks_Queues/QueueUsingArrays.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement a queue using an array 2 | #include 3 | using namespace std; 4 | 5 | struct Queue { 6 | int front, rear, capacity; 7 | int* queue; 8 | Queue(int c) 9 | { 10 | front = rear = 0; 11 | capacity = c; 12 | queue = new int; 13 | } 14 | 15 | ~Queue() { delete[] queue; } // desturctor 16 | 17 | 18 | void queueEnqueue(int data) 19 | { 20 | // check queue is full or not 21 | if (capacity == rear) { 22 | printf("\nQueue is full\n"); 23 | return; 24 | } 25 | 26 | else { 27 | queue[rear] = data; 28 | rear++; 29 | } 30 | return; 31 | } 32 | 33 | 34 | void queueDequeue() 35 | { 36 | if (front == rear) { 37 | printf("\nQueue is empty\n"); 38 | return; 39 | } 40 | 41 | else { 42 | for (int i = 0; i < rear - 1; i++) { 43 | queue[i] = queue[i + 1]; 44 | } 45 | 46 | // decrement rear 47 | rear--; 48 | } 49 | return; 50 | } 51 | 52 | // print queue elements 53 | void queueDisplay() 54 | { 55 | int i; 56 | if (front == rear) { 57 | printf("\nQueue is Empty\n"); 58 | return; 59 | } 60 | 61 | // traverse front to rear and print elements 62 | for (i = front; i < rear; i++) { 63 | printf(" %d <-- ", queue[i]); 64 | } 65 | return; 66 | } 67 | 68 | // print front of queue 69 | void queueFront() 70 | { 71 | if (front == rear) { 72 | printf("\nQueue is Empty\n"); 73 | return; 74 | } 75 | printf("\nFront Element is: %d", queue[front]); 76 | return; 77 | } 78 | }; 79 | 80 | // Driver code 81 | int main(void) 82 | { 83 | // Create a queue of capacity 4 84 | Queue q(4); 85 | 86 | // print Queue elements 87 | q.queueDisplay(); 88 | 89 | // inserting elements in the queue 90 | q.queueEnqueue(20); 91 | q.queueEnqueue(30); 92 | q.queueEnqueue(40); 93 | q.queueEnqueue(50); 94 | 95 | // print Queue elements 96 | q.queueDisplay(); 97 | 98 | // insert element in the queue 99 | q.queueEnqueue(60); 100 | 101 | // print Queue elements 102 | q.queueDisplay(); 103 | 104 | q.queueDequeue(); 105 | q.queueDequeue(); 106 | 107 | printf("\n\nafter two node deletion\n\n"); 108 | 109 | // print Queue elements 110 | q.queueDisplay(); 111 | 112 | // print front of the queue 113 | q.queueFront(); 114 | 115 | return 0; 116 | } 117 | -------------------------------------------------------------------------------- /Stacks_Queues/LFU.cpp: -------------------------------------------------------------------------------- 1 | struct Node { 2 | int key, value, cnt; 3 | Node *next; 4 | Node *prev; 5 | Node(int _key, int _value) { 6 | key = _key; 7 | value = _value; 8 | cnt = 1; 9 | } 10 | }; 11 | struct List { 12 | int size; 13 | Node *head; 14 | Node *tail; 15 | List() { 16 | head = new Node(0, 0); 17 | tail = new Node(0,0); 18 | head->next = tail; 19 | tail->prev = head; 20 | size = 0; 21 | } 22 | 23 | void addFront(Node *node) { 24 | Node* temp = head->next; 25 | node->next = temp; 26 | node->prev = head; 27 | head->next = node; 28 | temp->prev = node; 29 | size++; 30 | } 31 | 32 | void removeNode(Node* delnode) { 33 | Node* delprev = delnode->prev; 34 | Node* delnext = delnode->next; 35 | delprev->next = delnext; 36 | delnext->prev = delprev; 37 | size--; 38 | } 39 | 40 | 41 | 42 | }; 43 | class LFUCache { 44 | map keyNode; 45 | map freqListMap; 46 | int maxSizeCache; 47 | int minFreq; 48 | int curSize; 49 | public: 50 | LFUCache(int capacity) { 51 | maxSizeCache = capacity; 52 | minFreq = 0; 53 | curSize = 0; 54 | } 55 | void updateFreqListMap(Node *node) { 56 | keyNode.erase(node->key); 57 | freqListMap[node->cnt]->removeNode(node); 58 | if(node->cnt == minFreq && freqListMap[node->cnt]->size == 0) { 59 | minFreq++; 60 | } 61 | 62 | List* nextHigherFreqList = new List(); 63 | if(freqListMap.find(node->cnt + 1) != freqListMap.end()) { 64 | nextHigherFreqList = freqListMap[node->cnt + 1]; 65 | } 66 | node->cnt += 1; 67 | nextHigherFreqList->addFront(node); 68 | freqListMap[node->cnt] = nextHigherFreqList; 69 | keyNode[node->key] = node; 70 | } 71 | 72 | int get(int key) { 73 | if(keyNode.find(key) != keyNode.end()) { 74 | Node* node = keyNode[key]; 75 | int val = node->value; 76 | updateFreqListMap(node); 77 | return val; 78 | } 79 | return -1; 80 | } 81 | 82 | void put(int key, int value) { 83 | if (maxSizeCache == 0) { 84 | return; 85 | } 86 | if(keyNode.find(key) != keyNode.end()) { 87 | Node* node = keyNode[key]; 88 | node->value = value; 89 | updateFreqListMap(node); 90 | } 91 | else { 92 | if(curSize == maxSizeCache) { 93 | List* list = freqListMap[minFreq]; 94 | keyNode.erase(list->tail->prev->key); 95 | freqListMap[minFreq]->removeNode(list->tail->prev); 96 | curSize--; 97 | } 98 | curSize++; 99 | // new value has to be added who is not there previously 100 | minFreq = 1; 101 | List* listFreq = new List(); 102 | if(freqListMap.find(minFreq) != freqListMap.end()) { 103 | listFreq = freqListMap[minFreq]; 104 | } 105 | Node* node = new Node(key, value); 106 | listFreq->addFront(node); 107 | keyNode[key] = node; 108 | freqListMap[minFreq] = listFreq; 109 | } 110 | } 111 | }; --------------------------------------------------------------------------------