├── README.md ├── DAY24 ├── COUNTING BITS.CPP ├── CLIMBING STAIRS.CPP ├── Kth Largest Element in an Array.CPP └── Top K Frequent Elements.CPP ├── DAY4 ├── Middleoflinkedlist.cpp ├── LINKEDLISTCYCLE.CPP ├── REMOVEDUPLICATESFFROMSORTEDLINKEDLIST.CPP ├── removelinkedlistelement.cpp └── mergesortinlinkedlist.cpp ├── DAY7 ├── BINARYNOTODECIMALINLL.CPP ├── REMOVENTHNODEFROMLL.CPP ├── REVERSEALL2.CPP ├── PARTITIONLIST.CPP ├── REMOVEDUPLICATESFROMMLL2.CPP └── ADDTWONUMBERS2.CPP ├── DAY28 ├── UNIQUE BST.CPP ├── LCA OF BST.CPP ├── BST ITERATOR.CPP └── RECOVER A BINARY TREE.CPP ├── DAY18 ├── MAJORITY ELEMENT.CPP ├── MERGE SORTED ARRAY.CPP ├── REVERSE PAIRS.CPP ├── LARGEST RECTANGLE IN HISTOGRAM.CPP ├── GAME OF LIFE.CPP └── Print all possible combinations of r elements in a given array of size n.CPP ├── DAY12 ├── EXCEL SHEET COLOUMN TIOTLE.CPP ├── palindrome number.cpp ├── ADD BINARY.CPP ├── HAPPY NUMBER.CPP ├── maximum product of three number.cpp └── MINIMUM MOOVES TO EQUAL ARRAY ELEMENT.CPP ├── DAY41 ├── PRODUCT SUM SUBARRAY.CPP ├── UNIQUE PATH.CPP ├── KNIGHT DIALER.CPP ├── MIN PATH SUM.CPP ├── MAXIMISE THE CUT SEGMENTS.CPP └── ONES AND ZEROS.CPP ├── DAY10 ├── SUM OF LEFT LEAVES.CPP ├── Lowest Common Ancestor of a Binary Search Tree.CPP ├── PATH SUM.CPP ├── Binary Tree Inorder Traversal.CPP ├── SAME TREE.CPP └── Balanced Binary Tree.CPP ├── DAY21 ├── LCA OF BINARY TREE.CPP ├── VALIDATE BST.CPP ├── BINARY TREE RIGHT SIDE VIEW.CPP ├── combination.cpp ├── COMBINATION SUM2.CPP └── PARTITION EQUAL SUBSSET SUM.CPP ├── DAY3 ├── jumpgame.cpp ├── MAXIMUMPOINTSYOU CAN OBTAINFROMTHECARDS.CPP ├── SUBARRAYSUMEQUALTOK.cpp ├── wordsearch.cpp └── spiralmatrix.cpp ├── DAY5 ├── reverselinkedlist.cpp ├── interssectiionoftwolinkedlist.cpp ├── addteonumbers.cpp ├── palindromelinkedlist.cpp └── givenonlyforpointer.cpp ├── DAY13 ├── MISSING NUMBER.CPP ├── KTH FACTOR OF N.CPP ├── REVERSE INTEGER .CPP ├── POWER OF TWO.CPP └── VALID SQUARE.CPP ├── DAY27 ├── ONLINE STOCK SPAN.CPP ├── DAILY TEMPERTAURE.CPP ├── MINIMUM COST TREE WITH LEAF VALUE.CPP ├── SUM OF SUBARRAY MINIMUMS.CPP ├── DISTANCE OF NEAREST CELL HAVING 1.CPP └── ROTTEN ORANGES.CPP ├── DAY1 ├── BTTOBUYASELL2.CPP ├── removeduplicates.cpp ├── movezeros.cpp ├── SortColors.cpp ├── besttimetobuyandsellstocks.cpp ├── duplicateno.cpp └── twosum.cpp ├── DAY2 ├── allduplicateinanarray.cpp ├── containerwithmostwater.cpp ├── setmatrixzeros.cpp ├── subarraysumdivisiblebyk.cpp ├── 3SUM.cpp └── choclatedistribution.cpp ├── DAY38 ├── Minimum Time to Make Rope Colorful.CPP ├── Minimum Deletions to Make Character Frequencies Unique.CPP ├── RESTORE ARRAY WITH ADJACENT PAIRS.CPP ├── UNIQUE PATH3.CPP ├── Maximum Number of Visible Points.CPP └── Solving Cryptarithmetic Puzzles Backtracking.CPP ├── DAY11 ├── CHECK WETHER BST CONTAINS DEAD END OR NOT.CPP ├── RANGE SUM OF BST.CPP ├── MINIMUM ABSOLUTE DIFFERENCE.CPP ├── BINARY TREE PATH.CPP ├── PREDECESSOR AND SUCCESSOR.CPP └── SUBTREE OF ANOTHER TREE.CPP ├── DAY29 ├── FLATENING A TREE INTO LL.CPP ├── REDUNDANT CONNECTION.CPP ├── SORT COLORS.CPP ├── PATH SUM III.CPP ├── Construct Binary Tree from Preorder and Postorder Traversal.CPP └── UNIQUE BST2.CPP ├── DAY8 ├── BACKSPACESTRINGCOMPARE.CPP ├── IMPLEMENTSTACKUSINGQUEUE.CPP ├── IMPLEMENTQUEUEUSINGSTACK.CPP └── NEXTGREATERELEMENT1.CPP ├── DAY19 ├── reverse words..cpp ├── INTEGER TO ROMAN .CPP ├── GROUP ANAGRAMS.CPP ├── BASIC CALCULATOR.CPP └── GENERATE PARENTHESIS.CPP ├── DAY9 ├── MERGETWOBINARYTREE.CPP ├── CONVERTSORTEDARRAYTOBST.CPP ├── INVERTBINARYTREE.CPP ├── MAXIMUMDEPTHOFBINARYTREE.CPP ├── DIAMETEROFBINARYTREE.CPP └── SYMMTRICTREE.CPP ├── DAY23 ├── ROTATE IMAGE.CPP ├── CIRCULAR TOUR .CPP ├── THE CELEBRITY PROBLEM.CPP ├── SPIRAL MATRIX.CPP └── Maximum size rectangle binary sub-matrix with all 1s.CPP ├── DAY32 ├── TASK SCHEDULAR.CPP ├── Largest subarray with 0 sum .CPP ├── GAS STATION.CPP ├── REMOVE K SIGITS.CPP └── Minimum cost for acquiring all coins with k extra coins allowed with every coin.CPP ├── DAY16 ├── MINIMUM DISTANCE B │ ├── K^TH SMALLEST ELEMENT IN BST.CPP │ ├── Preorder to Postorder.CPP │ ├── Count BST nodes that lie in a given range.CPP │ ├── W TOWO GIVEN NODES IN BINARY TREE.CPP │ └── BINARY TREE ZIGZAG LEVEL ORDER TRAVELSEL.CPP └── MAXIMUMU WIDTH OF BINARY TREE.CPP ├── DAY20 ├── Permute two arrays such that sum of every pair is greater or equal to K.CPP ├── MINIMUM NO OF SWAPS REQUIRED TYO SORT AN ARRAY,.CPP ├── FIND PEAK ELEMENT .CPP └── SEARCH IN ROTATED SORTED ARRAY.CPP ├── DAY43 ├── DFS OF GRAPH.CPP ├── FLOOD FILL.CPP ├── BFS OF GRAPH.CPP ├── RAT IN A MAZE1.CPP ├── DETECT CYCLE IN UNDIRECTED GRAPH.CPP ├── DETECTT CYCLE IN DIRECTED GRAPH.CPP └── NUMBER OF ISLANDS.CPP ├── DAY25 ├── Kth Smallest Element in a Sorted Matrix.CPP ├── FLATTEN A MULTILEVEL DOUBLY LL.CPP ├── AGGRESSIVE COW.CPP ├── MINIMUM NUMBER OF PAGES.CPP └── COUNT OF SMALLER NO AFTER ITSELF.CPP ├── DAY42 ├── MAXIMAL SQUARSES.CPP ├── COIN CHANGE.CPP ├── DECODE WAYS.CPP ├── COUNT SQURE SUBMATRISES WITH ALL ONES.CPP ├── MAXIMUM LENGHT OF REAPETED SUBARRAY.CPP └── longest common substring.cpp ├── DAY37 ├── BINARY TREE MAXIMUM PATH SUM.CPP ├── Populating Next Right Pointers in Each Node.CPP ├── vertical order traversal.cpp ├── non overl;apping intervals.cpp ├── BINARY TREE CAMERAS.CPP └── Serialize and Deserialize Binary Tree.CPP ├── DAY14 ├── IMPLEMENT SSTRSTR().CPP ├── LONGEST COMMON PREFIX.CPP ├── VALID PALINDROME 2.CPP ├── VALID PARENTHESIS.CPP ├── PRINT ALL DUPLICATES IN THE INPUT STRING.CPP └── SIMPLYFY PATH.CPP ├── DAY31 ├── FIND THE MOST COMPETETIVE SUB SEQUENCE.CPP ├── REORGANIZE A STRING.CPP ├── VALID NUMBER.CPP ├── SMALLEST POSITIVE MISSING NO.CPP └── INTEGER TO WORDS.CPP ├── DAY39 ├── SLIDING WINDOW MAXIMU.CPP ├── ugly number 2.cpp ├── k closest points to origin.cpp ├── SWIM IN RISING WATER.CPP ├── MINIMUM COST TO HIRE K WORKER.CPP └── minimum number of refueling stops.cpp ├── DAY26 ├── MAXVALUE OF EQUATION.CPP ├── max value of equation.cpp ├── VALID NUMBER.CPP ├── Insert Delete GetRandom Duplicates allowed.cpp └── Largest Rectangle in Histogram.CPP ├── DAY30 ├── KTH SMALLEST ELEMENT IN SORTED MATRIX.CPP ├── PRINT ANAGRAM TOGETHER.CPP ├── Furthest Building You Can Reach.CPP ├── IMPLEMENT A PHONE DIRECTORY.CPP └── Design Add and Search Words Data Structure.CPP ├── DAY6 ├── REVERSEKNODEINLL.CPP ├── REMOVEDUPLICATEFROMSORTEDLL.CPP ├── MERGEKSORTEDLL.CPP └── SORTLIST.CPP ├── DAY17 ├── FLATTENING A LL.CPP ├── REARRANGE THE LIST IN ZIG ZAG FASHION.CPP └── REORDER LIST.CPP ├── DAY40 ├── EVALUATE REVERSE POLISH NOTATION.CPP ├── TEXT JUSTIFICATION.CPP ├── DISTINT SUBSEEQUENCE.CPP ├── IMPLEMENT STACK USING QUEUE.CPP └── MINIMUM WINDOW SUBSTRING.CPP ├── DAY36 ├── PERMUTATION 2.CPP ├── SUBSETS 2.CPP ├── SUBSETS.CPP ├── BEAUTIFUL ARRANGEMENT.CPP ├── PALINDROME PARTITIONING.CPP └── PRINT ALL PALINDROMIC PARTITION OF A STRING.CPP ├── DAY33 ├── WOWRD SEARCH 2.CPP └── Find Maximum number possible by doing at-most K swaps.CPP ├── DAY45 ├── Most Stones Removed with Same Row or Column.CPP └── Find the City With the Smallest Number of Neighbors at a Threshold Distance.CPP ├── DAY44 ├── DECODED STRINGS.CPP ├── Number of Operations to Make Network Connected.CPP ├── FIND EVENTUALLY SAFE STATES.CPP ├── STEPS BY KNIGHT.CPP └── Strongly Connected Components (Kosaraju's Algo).CPP ├── DAY22 ├── BINARY TREE LEVEL ORDER TRAVERSAL.CPP ├── SUDOKO SOLVER.CPP ├── MAX RECTANGLE.CPP ├── LARGEST RECTANGLE HISTOGRAM.CPP └── NQUEENS.CPP ├── DAY35 ├── M COLOURING PROBLEM.CPP └── Find maximum of minimum for every window size in a given array.CPP ├── DAY34 ├── BINARY TREE TO SLL.CPP └── Minimum sum of two numbers formed from digits of an array.CPP └── DAY15 ├── Permute two arrays such that sum of every pair is greater or equal to K.CPP ├── Find a pair with the given difference.CPP ├── Ceiling in a sorted array.CPP ├── Check if reversing a sub array make the array sorted.CPP ├── Product of Array except itself.CPP └── Make all array elements equal with minimum cost.CPP /README.md: -------------------------------------------------------------------------------- 1 | # DSA-SHEET 2 | Contains all solution of Arsh Goyal DSA sheet 3 | -------------------------------------------------------------------------------- /DAY24/COUNTING BITS.CPP: -------------------------------------------------------------------------------- 1 | vector countBits(int n) { 2 | vector res(n+1, 0); 3 | for (int i = 1; i <= n; ++i) { 4 | res[i] = res[i >> 1] + (i & 1); 5 | } 6 | return res; 7 | } -------------------------------------------------------------------------------- /DAY4/Middleoflinkedlist.cpp: -------------------------------------------------------------------------------- 1 | ListNode* middleNode(ListNode* head) { 2 | ListNode *slow = head, *fast = head; 3 | while (fast && fast->next) 4 | slow = slow->next, fast = fast->next->next; 5 | return slow; 6 | } -------------------------------------------------------------------------------- /DAY7/BINARYNOTODECIMALINLL.CPP: -------------------------------------------------------------------------------- 1 | int getDecimalValue(ListNode* head) { 2 | int ans=0; 3 | ListNode* temp=head; 4 | while(temp!=NULL){ 5 | ans*=2; 6 | ans+=(temp->val); 7 | temp=temp->next; 8 | } 9 | return ans; 10 | } -------------------------------------------------------------------------------- /DAY28/UNIQUE BST.CPP: -------------------------------------------------------------------------------- 1 | int numTrees(int n) { 2 | int dp[n+1]; 3 | dp[0] = dp[1] = 1; 4 | for (int i=2; i<=n; i++) { 5 | dp[i] = 0; 6 | for (int j=1; j<=i; j++) { 7 | dp[i] += dp[j-1] * dp[i-j]; 8 | } 9 | } 10 | return dp[n]; 11 | } -------------------------------------------------------------------------------- /DAY18/MAJORITY ELEMENT.CPP: -------------------------------------------------------------------------------- 1 | int majorityElement(vector& nums) { 2 | 3 | unordered_map m; 4 | 5 | for (int i : nums) { 6 | if (++m[i]>nums.size() / 2) { 7 | return i; 8 | } 9 | } 10 | return 0; 11 | } -------------------------------------------------------------------------------- /DAY24/CLIMBING STAIRS.CPP: -------------------------------------------------------------------------------- 1 | int climbStairs(int n) { 2 | if (n <= 2) return n; 3 | int prev = 2, prev2 = 1, res; 4 | for (int i = 3; i <= n; i++) { 5 | res = prev + prev2; 6 | prev2 = prev; 7 | prev = res; 8 | } 9 | return res; 10 | 11 | } -------------------------------------------------------------------------------- /DAY12/EXCEL SHEET COLOUMN TIOTLE.CPP: -------------------------------------------------------------------------------- 1 | string convertToTitle(int n) { 2 | 3 | string res; 4 | 5 | char tmp; 6 | 7 | while(n){ 8 | 9 | n -= 1; 10 | 11 | tmp = 'A' + n % 26; 12 | 13 | res = tmp + res; 14 | 15 | n /= 26; 16 | 17 | } 18 | 19 | return res; 20 | 21 | } -------------------------------------------------------------------------------- /DAY41/PRODUCT SUM SUBARRAY.CPP: -------------------------------------------------------------------------------- 1 | int maxProduct(vector A) { 2 | int n = A.size(), res = A[0], l = 0, r = 0; 3 | for (int i = 0; i < n; i++) { 4 | l = (l ? l : 1) * A[i]; 5 | r = (r ? r : 1) * A[n - 1 - i]; 6 | res = max(res, max(l, r)); 7 | } 8 | return res; 9 | } -------------------------------------------------------------------------------- /DAY41/UNIQUE PATH.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | vector cur(n, 1); 5 | for (int i = 1; i < m; i++) { 6 | for (int j = 1; j < n; j++) { 7 | cur[j] += cur[j - 1]; 8 | } 9 | } 10 | return cur[n - 1]; 11 | } 12 | }; -------------------------------------------------------------------------------- /DAY10/SUM OF LEFT LEAVES.CPP: -------------------------------------------------------------------------------- 1 | int sumOfLeftLeaves(TreeNode* root) { 2 | return dfs(root, false); 3 | } 4 | int dfs(TreeNode* root, bool isLeft) { 5 | if(!root) return 0; 6 | if(!root -> left && !root -> right) return isLeft ? root -> val : 0; 7 | return dfs(root -> left, true) + dfs(root -> right, false); 8 | } -------------------------------------------------------------------------------- /DAY21/LCA OF BINARY TREE.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 2 | if (!root || root == p || root == q) return root; 3 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 4 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 5 | return !left ? right : !right ? left : root; 6 | } -------------------------------------------------------------------------------- /DAY3/jumpgame.cpp: -------------------------------------------------------------------------------- 1 | bool canJump(vector& nums) { 2 | int i, minjump = 0; 3 | for(i = nums.size()-2; i >= 0; i--){ 4 | minjump++; 5 | if(nums[i] >= minjump) 6 | minjump = 0; 7 | } 8 | if(minjump == 0) 9 | return true; 10 | else 11 | return false; 12 | } -------------------------------------------------------------------------------- /DAY24/Kth Largest Element in an Array.CPP: -------------------------------------------------------------------------------- 1 | int findKthLargest(vector& nums, int k) { 2 | priority_queue, greater> pq; 3 | for (int num : nums) { 4 | pq.push(num); 5 | if (pq.size() > k) { 6 | pq.pop(); 7 | } 8 | } 9 | return pq.top(); 10 | } -------------------------------------------------------------------------------- /DAY5/reverselinkedlist.cpp: -------------------------------------------------------------------------------- 1 | ListNode* reverseList(ListNode* head) { 2 | ListNode* prev=NULL; 3 | ListNode* curr=head; 4 | ListNode* next; 5 | while(curr!=NULL){ 6 | next=curr->next; 7 | curr->next=prev; 8 | prev=curr; 9 | curr=next; 10 | } 11 | return prev; 12 | } -------------------------------------------------------------------------------- /DAY13/MISSING NUMBER.CPP: -------------------------------------------------------------------------------- 1 | int missingNumber(vector& nums) { 2 | int n=nums.size(),i; 3 | sort(nums.begin(),nums.end()); 4 | for( i=0;i factors; 3 | for(int i = 1; i <= n; i++){ 4 | if(n % i == 0) factors.push_back(i); 5 | if(factors.size() == k) break; 6 | } 7 | if(k <= factors.size()) 8 | return factors[k-1]; 9 | else return -1; 10 | 11 | } -------------------------------------------------------------------------------- /DAY27/ONLINE STOCK SPAN.CPP: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack> s; 4 | int next(int price) { 5 | int res = 1; 6 | while (!s.empty() && s.top().first <= price) { 7 | res += s.top().second; 8 | s.pop(); 9 | } 10 | s.push({price, res}); 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /DAY28/LCA OF BST.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | if (!root || root == p || root == q) return root; 5 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 6 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 7 | return !left ? right : !right ? left : root; 8 | } 9 | }; -------------------------------------------------------------------------------- /DAY1/BTTOBUYASELL2.CPP: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int maxProfit(vector& prices) { 4 | int profit = 0; 5 | for(int i = 1; i < prices.size(); i++) 6 | if(prices[i] > prices[i-1]) // yesterday was valley, today is peak 7 | profit += prices[i] - prices[i-1]; // buy yesterday, sell today 8 | return profit; 9 | } -------------------------------------------------------------------------------- /DAY10/Lowest Common Ancestor of a Binary Search Tree.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 2 | while (root) { 3 | if (p->val < root->val && q->val < root->val) root = root->left; 4 | else if (p->val > root->val && q->val > root->val) root = root->right; 5 | else return root; 6 | } 7 | return root; 8 | } -------------------------------------------------------------------------------- /DAY2/allduplicateinanarray.cpp: -------------------------------------------------------------------------------- 1 | //use unordered map and save all the frequency and return the values which have frequency of 2; 2 | vector findDuplicates(vector& nums) { 3 | if(nums.empty())return {}; 4 | vectorans; 5 | unordered_mapmp; 6 | for(int no:nums)mp[no]++; 7 | for(auto it:mp)if(it.second==2)ans.push_back(it.first); 8 | return ans; 9 | } -------------------------------------------------------------------------------- /DAY3/MAXIMUMPOINTSYOU CAN OBTAINFROMTHECARDS.CPP: -------------------------------------------------------------------------------- 1 | int maxScore(vector& cardPoints, int k) { 2 | int res=0, n=cardPoints.size(), s=0; 3 | for(int i=n-k; i 2 | using namespace std; 3 | int removeDuplicates(vector& nums) { 4 | if(nums.size() == 0) return 0; 5 | int left = 0; 6 | for(int right =1; right< nums.size(); right++){ 7 | if(nums[left] != nums[right]) 8 | left++; 9 | nums[left] = nums[right]; 10 | } 11 | return left+1; 12 | }s -------------------------------------------------------------------------------- /DAY38/Minimum Time to Make Rope Colorful.CPP: -------------------------------------------------------------------------------- 1 | int minCost(string s, vector& cost) { 2 | int res = cost[0], max_cost = cost[0]; 3 | for (int i = 1; i < s.size(); ++i) { 4 | if (s[i] != s[i - 1]) { 5 | res -= max_cost; 6 | max_cost = 0; 7 | } 8 | res += cost[i]; 9 | max_cost = max(max_cost, cost[i]); 10 | } 11 | return res - max_cost; 12 | } -------------------------------------------------------------------------------- /DAY11/CHECK WETHER BST CONTAINS DEAD END OR NOT.CPP: -------------------------------------------------------------------------------- 1 | bool solve(Node* root, int mn, int mx){ 2 | 3 | if(root == NULL) return 0; 4 | if(root->data == mn and root->data == mx) return 1; 5 | 6 | return solve(root->left, mn, root->data - 1) or solve(root->right, root->data+1, mx); 7 | 8 | } 9 | bool isDeadEnd(Node *root) 10 | { 11 | int mn = 1, mx = INT_MAX; 12 | return solve(root, mn, mx); 13 | } -------------------------------------------------------------------------------- /DAY29/FLATENING A TREE INTO LL.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void flatten(TreeNode *root) { 4 | while (root) { 5 | if (root->left && root->right) { 6 | TreeNode* t = root->left; 7 | while (t->right) 8 | t = t->right; 9 | t->right = root->right; 10 | } 11 | 12 | if(root->left) 13 | root->right = root->left; 14 | root->left = NULL; 15 | root = root->right; 16 | } 17 | } 18 | }; -------------------------------------------------------------------------------- /DAY7/REMOVENTHNODEFROMLL.CPP: -------------------------------------------------------------------------------- 1 | ListNode* removeNthFromEnd(ListNode* head, int n) { 2 | ListNode** t1 = &head, *t2 = head; 3 | for(int i = 1; i < n; ++i) 4 | { 5 | t2 = t2->next; 6 | } 7 | while(t2->next != NULL) 8 | { 9 | t1 = &((*t1)->next); 10 | t2 = t2->next; 11 | } 12 | *t1 = (*t1)->next; 13 | return head; 14 | } -------------------------------------------------------------------------------- /DAY8/BACKSPACESTRINGCOMPARE.CPP: -------------------------------------------------------------------------------- 1 | bool backspaceCompare(string s, string t) { 2 | stacks1,s2; 3 | int n=s.size(); 4 | int m=t.size(); 5 | for(int i=0;ival; //Body 4 | if(targetSum==0&&!root->left&&!root->right)return true; //body 5 | return hasPathSum(root->left,targetSum)||hasPathSum(root->right,targetSum);//Propagation 6 | } -------------------------------------------------------------------------------- /DAY19/reverse words..cpp: -------------------------------------------------------------------------------- 1 | string reverseWords(string s) { 2 | vector words; 3 | stringstream ss(s); 4 | string tmp; 5 | while (ss >> tmp) 6 | words.push_back(tmp); 7 | 8 | string ans; 9 | for (int i = words.size() - 1; i >= 0; --i) { 10 | if (i != words.size() - 1) ans += " "; 11 | ans += words[i]; 12 | } 13 | return ans; 14 | } -------------------------------------------------------------------------------- /DAY12/palindrome number.cpp: -------------------------------------------------------------------------------- 1 | bool isPalindrome(int x) { 2 | int digit; 3 | long reverse=0; 4 | int temp=x; 5 | while(x>0){ 6 | 7 | digit=x%10; 8 | reverse=(reverse*10)+digit; 9 | x=x/10; 10 | 11 | } 12 | if(reverse==temp){ 13 | return true; 14 | } 15 | else{ 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /DAY9/MERGETWOBINARYTREE.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) { 2 | if ( root1 && root2 ) { 3 | TreeNode * root = new TreeNode(root1->val + root2->val); 4 | root->left = mergeTrees(root1->left, root2->left); 5 | root->right = mergeTrees(root1->right, root2->right); 6 | return root; 7 | } else { 8 | return root1 ? root1 : root2; 9 | } 10 | } -------------------------------------------------------------------------------- /DAY1/movezeros.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | void moveZeroes(vector& nums) { 5 | int j = 0; 6 | // move all the nonzero elements advance 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (nums[i] != 0) { 9 | nums[j++] = nums[i]; 10 | } 11 | } 12 | for (;j < nums.size(); j++) { 13 | nums[j] = 0; 14 | } 15 | } -------------------------------------------------------------------------------- /DAY11/RANGE SUM OF BST.CPP: -------------------------------------------------------------------------------- 1 | int sum=0; 2 | int inorder(TreeNode* root,int L,int R) 3 | { 4 | if(root){ 5 | inorder(root->left,L,R); 6 | if(root->val>=L && root->val<=R) 7 | sum+=root->val; 8 | inorder(root->right,L,R); 9 | } 10 | return sum; 11 | } 12 | int rangeSumBST(TreeNode* root, int L, int R) { 13 | if(!root)return 0; 14 | return inorder(root,L,R); 15 | } -------------------------------------------------------------------------------- /DAY5/interssectiionoftwolinkedlist.cpp: -------------------------------------------------------------------------------- 1 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 2 | ListNode *ptr1 = headA; 3 | ListNode *ptr2 = headB; 4 | while(ptr1 != ptr2){ 5 | if(ptr1 == NULL){ 6 | ptr1 = headB; 7 | } 8 | else{ 9 | ptr1 = ptr1 -> next; 10 | } 11 | if(ptr2 == NULL){ 12 | ptr2 = headA; 13 | } 14 | else{ 15 | ptr2 = ptr2 -> next; 16 | } 17 | } 18 | return ptr1; 19 | } -------------------------------------------------------------------------------- /DAY21/VALIDATE BST.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidBST(TreeNode* root) { 4 | return isValidBST(root, NULL, NULL); 5 | } 6 | 7 | bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) { 8 | if(!root) return true; 9 | if(minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) 10 | return false; 11 | return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode); 12 | } 13 | }; -------------------------------------------------------------------------------- /DAY23/ROTATE IMAGE.CPP: -------------------------------------------------------------------------------- 1 | void rotate(vector>& matrix) { 2 | int n = matrix.size(); 3 | int a = 0; 4 | int b = n-1; 5 | while(a &ans,int level){ 2 | if(root==NULL){ 3 | return ; 4 | } 5 | if(level==ans.size()){ 6 | ans.push_back(root->val); 7 | } 8 | solve(root->right,ans,level+1); 9 | solve(root->left,ans,level+1); 10 | } 11 | vector rightSideView(TreeNode* root) { 12 | vector ans; 13 | solve(root,ans,0); 14 | return ans; 15 | } -------------------------------------------------------------------------------- /DAY32/TASK SCHEDULAR.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int leastInterval(vector& tasks, int n) { 4 | unordered_mapmp; 5 | int count = 0; 6 | for(auto e : tasks) 7 | { 8 | mp[e]++; 9 | count = max(count, mp[e]); 10 | } 11 | 12 | int ans = (count-1)*(n+1); 13 | for(auto e : mp) if(e.second == count) ans++; 14 | return max((int)tasks.size(), ans); 15 | } 16 | }; -------------------------------------------------------------------------------- /DAY16/MINIMUM DISTANCE B/K^TH SMALLEST ELEMENT IN BST.CPP: -------------------------------------------------------------------------------- 1 | void inorder(TreeNode* root,vector& res){ 2 | if(!root) 3 | return; 4 | inorder(root->left, res); 5 | res.push_back(root->val); 6 | inorder(root->right,res); 7 | 8 | } 9 | int kthSmallest(TreeNode* root, int k) { 10 | if(!root) 11 | return -1; 12 | vector arr; 13 | inorder(root, arr); 14 | return arr[k-1]; 15 | 16 | } -------------------------------------------------------------------------------- /DAY13/REVERSE INTEGER .CPP: -------------------------------------------------------------------------------- 1 | int reverse(int x) { 2 | 3 | int ans=0; 4 | 5 | while(x!=0){ 6 | int digit=x%10; 7 | 8 | if( (ans > INT_MAX/10) || (ans < INT_MIN/10) ){ 9 | return 0; 10 | } 11 | ans = (ans*10)+digit; 12 | x = x/10; 13 | 14 | 15 | } 16 | return ans; 17 | } -------------------------------------------------------------------------------- /DAY20/Permute two arrays such that sum of every pair is greater or equal to K.CPP: -------------------------------------------------------------------------------- 1 | bool isPossible(long long a[], long long b[], long long n, long long k) { 2 | //SORT THE ARRAY A IN ACENDING ORDER 3 | sort(a,a+n); 4 | //SORT THE ARRAY B IN DECENDING ORDER 5 | sort(b,b+n,greater()); 6 | 7 | 8 | for(int i=0;i& nums, int k) { 2 | int cum=0; // cumulated sum 3 | map rec; // prefix sum recorder 4 | int cnt = 0; // number of found subarray 5 | rec[0]++; // to take into account those subarrays that begin with index 0 6 | for(int i=0;i& nums1, int m, vector& nums2, int n) { 4 | int i = m - 1, j = n - 1, k = m + n - 1; 5 | while(i >= 0 and j >= 0) { 6 | if(nums1[i] < nums2[j]) { 7 | nums1[k--] = nums2[j--]; 8 | } else { 9 | nums1[k--] = nums1[i--]; 10 | } 11 | } 12 | while(j >= 0) { 13 | nums1[k--] = nums2[j--]; 14 | } 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /DAY43/DFS OF GRAPH.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfsUtility(int i,vector adj[],vector &ans,vector &vis){ 4 | ans.push_back(i); 5 | vis[i] = 1; 6 | for(auto it : adj[i]){ 7 | if(!vis[it]) dfsUtility(it,adj,ans,vis); 8 | } 9 | } 10 | vector dfsOfGraph(int V, vector adj[]) { 11 | vector ans; 12 | vector vis(V,0); 13 | dfsUtility(0,adj,ans,vis); 14 | return ans; 15 | } 16 | }; -------------------------------------------------------------------------------- /DAY16/MINIMUM DISTANCE B/Preorder to Postorder.CPP: -------------------------------------------------------------------------------- 1 | Node* create(int pre[],int &i,int upperBound,int size) 2 | { 3 | if(i>=size || pre[i]>upperBound) return NULL; 4 | Node* root=newNode(pre[i++]); 5 | root->left=create(pre,i,root->data,size); 6 | root->right=create(pre,i,upperBound,size); 7 | 8 | return root; 9 | } 10 | Node* post_order(int pre[], int size) 11 | { 12 | if(!size) return NULL; 13 | int i=0; 14 | Node* root=create(pre,i,INT_MAX,size); 15 | 16 | return root; 17 | } -------------------------------------------------------------------------------- /DAY25/Kth Smallest Element in a Sorted Matrix.CPP: -------------------------------------------------------------------------------- 1 | int kthSmallest(vector>& matrix, int k) { 2 | int m = matrix.size(), n = matrix[0].size(); // For general, the matrix need not be a square 3 | priority_queue maxHeap; 4 | for (int r = 0; r < m; ++r) { 5 | for (int c = 0; c < n; ++c) { 6 | maxHeap.push(matrix[r][c]); 7 | if (maxHeap.size() > k) maxHeap.pop(); 8 | } 9 | } 10 | return maxHeap.top(); 11 | } -------------------------------------------------------------------------------- /DAY42/MAXIMAL SQUARSES.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalSquare(vector>& M) { 4 | int m = size(M), n = size(M[0]), ans = 0; 5 | vector> dp(2, vector(n+1)); 6 | for(int i = m-1; ~i; i--) 7 | for(int j = n-1; ~j; j--) 8 | dp[i&1][j] = (M[i][j] == '1' ? 1 + min({dp[(i+1)&1][j], dp[i&1][j+1], dp[(i+1)&1][j+1]}) : 0), 9 | ans = max(ans, dp[i&1][j]); 10 | 11 | return ans * ans; 12 | } 13 | }; -------------------------------------------------------------------------------- /DAY1/SortColors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // using 3 pointers low,mid,high putting at specific position 4 | void sortcolors(vector& nums,int n){ 5 | int l=nums[0],m=nums[0],h=nums[n-1]; 6 | while(m<=h){ 7 | if(nums[m]==0){ 8 | swap(nums[l],nums[m]); 9 | l++; 10 | m++; 11 | } 12 | if(nums[m]==1) 13 | m++; 14 | if(nums[m]==2){ 15 | swap(nums[m],nums[h]); 16 | h--; 17 | } 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /DAY37/BINARY TREE MAXIMUM PATH SUM.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(TreeNode* root,int &maxi){ 4 | if(root==NULL)return 0; 5 | int left=max(0,solve(root->left,maxi)); 6 | int right=max(0,solve(root->right,maxi)); 7 | 8 | maxi=max(maxi,left+right+root->val); 9 | return max(left,right)+root->val; 10 | } 11 | int maxPathSum(TreeNode* root) { 12 | int maxi=INT_MIN; 13 | solve(root,maxi); 14 | return maxi; 15 | } 16 | }; -------------------------------------------------------------------------------- /DAY10/Binary Tree Inorder Traversal.CPP: -------------------------------------------------------------------------------- 1 | vector inorderTraversal(TreeNode* root) { 2 | vector nodes; 3 | stack todo; 4 | while (root || !todo.empty()) { 5 | while (root) { 6 | todo.push(root); 7 | root = root -> left; 8 | } 9 | root = todo.top(); 10 | todo.pop(); 11 | nodes.push_back(root -> val); 12 | root = root -> right; 13 | } 14 | return nodes; 15 | } -------------------------------------------------------------------------------- /DAY14/IMPLEMENT SSTRSTR().CPP: -------------------------------------------------------------------------------- 1 | int strStr(string haystack, string needle) { 2 | int m = haystack.size(), n = needle.size(); 3 | for (int i = 0; i <= m - n; i++) { 4 | int j = 0; 5 | for (; j < n; j++) { 6 | if (haystack[i + j] != needle[j]) { 7 | break; 8 | } 9 | } 10 | if (j == n) { 11 | return i; 12 | } 13 | } 14 | return -1; 15 | 16 | 17 | } -------------------------------------------------------------------------------- /DAY2/containerwithmostwater.cpp: -------------------------------------------------------------------------------- 1 | int maxArea(vector& height) { 2 | int maxArea = 0; 3 | int i = 0, j = height.size() - 1; 4 | while(i < j) 5 | { 6 | maxArea = max(maxArea, min(height[i], height[j]) * (j - i)); 7 | if(height[i] < height[j]) 8 | i++; 9 | else 10 | j--; 11 | } 12 | 13 | return maxArea; 14 | } -------------------------------------------------------------------------------- /DAY4/LINKEDLISTCYCLE.CPP: -------------------------------------------------------------------------------- 1 | bool hasCycle(ListNode *head) { 2 | if(head==NULL|| head->next==NULL){ 3 | return false; 4 | } 5 | 6 | ListNode* fast=head; 7 | ListNode* slow=head; 8 | while(fast && fast->next){ 9 | fast=fast->next->next; 10 | 11 | 12 | 13 | slow=slow->next; 14 | if(slow==fast){ 15 | return true; 16 | } 17 | } 18 | return false; 19 | } -------------------------------------------------------------------------------- /DAY41/KNIGHT DIALER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ms = { {4, 6}, {6, 8}, {7, 9}, {4, 8}, {3, 9, 0}, {}, {1, 7, 0}, {2, 6}, {1, 3}, {4, 2}}; 4 | int knightDialer(int N) { 5 | vector d1(10, 1), d2(10); 6 | for (; --N > 0; swap(d1, d2)) 7 | for (auto i = 0; i < 10; ++i) 8 | d2[i] = accumulate(begin(ms[i]), end(ms[i]), 0, [&](int s, int i) {return (s + d1[i]) % 1000000007;}); 9 | return accumulate(begin(d1), end(d1), 0, [](int s, int n) {return (s + n) % 1000000007;}); 10 | } 11 | }; -------------------------------------------------------------------------------- /DAY9/CONVERTSORTEDARRAYTOBST.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* sortedArrayToBST(vector& nums) { 2 | return helper(nums, 0, nums.size()-1); 3 | } 4 | TreeNode* helper(vector& nums, int low,int high){ 5 | if(low<=high){ 6 | int mid = low + (high-low)/2; 7 | TreeNode* root = new TreeNode(nums[mid]); 8 | root->left = helper(nums, low, mid-1); 9 | root->right = helper(nums, mid+1, high); 10 | return root; 11 | } 12 | return NULL; 13 | } -------------------------------------------------------------------------------- /DAY19/INTEGER TO ROMAN .CPP: -------------------------------------------------------------------------------- 1 | string intToRoman(int num) { 2 | string res; 3 | string sym[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 4 | int val[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 5 | 6 | for(int i=0; num != 0; i++) 7 | { 8 | while(num >= val[i]) 9 | { 10 | num -= val[i]; 11 | res += sym[i]; 12 | } 13 | } 14 | 15 | return res; 16 | } -------------------------------------------------------------------------------- /DAY20/MINIMUM NO OF SWAPS REQUIRED TYO SORT AN ARRAY,.CPP: -------------------------------------------------------------------------------- 1 | int minswaps(vector&nums){ 2 | int n=nums.size(); 3 | vector> v(n); 4 | for(int i=0;i mostCompetitive(vector& nums, int k) { 2 | vector stack; 3 | int nums_to_delete = nums.size()-k; 4 | for (int i = 0; i < nums.size(); i++) { 5 | while (!stack.empty() && nums[i] < stack.back() && nums_to_delete) { 6 | stack.pop_back(); 7 | nums_to_delete--; 8 | } 9 | stack.push_back(nums[i]); 10 | } 11 | return vector(stack.begin(), stack.begin()+k); 12 | } -------------------------------------------------------------------------------- /DAY41/MIN PATH SUM.CPP: -------------------------------------------------------------------------------- 1 | int minPathSum(vector>& grid) { 2 | int m = grid.size(); 3 | int n = grid[0].size(); 4 | vector> dp(m,vector(n,0)); 5 | dp[0][0] = grid[0][0]; 6 | for(int i=1;i 2 | using namespace std; 3 | int maxProfit(vector& prices) { 4 | int min = INT_MAX; 5 | int op = 0; 6 | int profit = 0; 7 | 8 | for(int i = 0; i < prices.size(); i++){ 9 | if(prices[i] < min){ 10 | min = prices[i]; 11 | } 12 | profit = prices[i] - min; 13 | if(op < profit){ 14 | op = profit; 15 | } 16 | } 17 | return op; 18 | } -------------------------------------------------------------------------------- /DAY39/SLIDING WINDOW MAXIMU.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()]); 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /DAY1/duplicateno.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // using linked list and slow and fast pointer approach 6 | int duplicates(vector nums){ 7 | int slow=nums[0]; 8 | int fast=nums[0]; 9 | do{ 10 | slow=nums[slow]; 11 | fast=nums[nums[fast]]; 12 | }while(slow!=fast); 13 | 14 | fast=nums[0]; 15 | while(slow!=fast){ 16 | slow=nums[slow]; 17 | fast=nums[fast]; 18 | } 19 | return slow; 20 | } 21 | -------------------------------------------------------------------------------- /DAY11/MINIMUM ABSOLUTE DIFFERENCE.CPP: -------------------------------------------------------------------------------- 1 | int inorderTraverse(TreeNode* root, int& val, int& min_dif) { 2 | if (root->left != NULL) 3 | inorderTraverse(root->left, val, min_dif); 4 | if (val >= 0) 5 | min_dif = min(min_dif, root->val - val); 6 | val = root->val; 7 | if (root->right != NULL) 8 | inorderTraverse(root->right, val, min_dif); 9 | return min_dif; 10 | } 11 | int getMinimumDifference(TreeNode* root) { 12 | auto min_dif = INT_MAX, val = -1; 13 | return inorderTraverse(root, val, min_dif); 14 | } -------------------------------------------------------------------------------- /DAY13/POWER OF TWO.CPP: -------------------------------------------------------------------------------- 1 | bool isPowerOfTwo(int n) { 2 | /* THIS SOUTION IS A BASIC ONE 3 | // if(n<=0) return false; 4 | 5 | // return (n&(n-1)==0);\ 6 | */ 7 | 8 | //setbit 9 | if(n<=0) 10 | return false; 11 | 12 | int count=0; 13 | while(n!=0) 14 | { 15 | if(n&1) 16 | count++; 17 | n=n>>1; 18 | } 19 | if(count>1)return false; 20 | 21 | return true; 22 | 23 | } -------------------------------------------------------------------------------- /DAY26/MAXVALUE OF EQUATION.CPP: -------------------------------------------------------------------------------- 1 | int findMaxValueOfEquation(vector>& points, int k) { 2 | priority_queue> p; 3 | int ans=INT_MIN; 4 | for(int i=0;ik)p.pop(); 6 | if(!p.empty()){ 7 | ans=max(ans,points[i][0]+points[i][1]+p.top().first); 8 | 9 | } 10 | p.push({points[i][1]-points[i][0],points[i][0]}); 11 | } 12 | return ans; 13 | } -------------------------------------------------------------------------------- /DAY26/max value of equation.cpp: -------------------------------------------------------------------------------- 1 | int findMaxValueOfEquation(vector>& points, int k) { 2 | priority_queue> p; 3 | int ans=INT_MIN; 4 | for(int i=0;ik)p.pop(); 6 | if(!p.empty()){ 7 | ans=max(ans,points[i][0]+points[i][1]+p.top().first); 8 | 9 | } 10 | p.push({points[i][1]-points[i][0],points[i][0]}); 11 | } 12 | return ans; 13 | } -------------------------------------------------------------------------------- /DAY42/COIN CHANGE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | int Max = amount + 1; 5 | vector dp(amount + 1, Max); 6 | dp[0] = 0; 7 | for (int i = 1; i <= amount; i++) { 8 | for (int j = 0; j < coins.size(); j++) { 9 | if (coins[j] <= i) { 10 | dp[i] = min(dp[i], dp[i - coins[j]] + 1); 11 | } 12 | } 13 | } 14 | return dp[amount] > amount ? -1 : dp[amount]; 15 | } 16 | }; -------------------------------------------------------------------------------- /DAY27/DAILY TEMPERTAURE.CPP: -------------------------------------------------------------------------------- 1 | Vector dailyTemperatures(vector& temperatures) { 2 | vector res(temperatures.size()); 3 | for (int i = temperatures.size() - 1; i >= 0; --i) { 4 | int j = i+1; 5 | while (j < temperatures.size() && temperatures[j] <= temperatures[i]) { 6 | if (res[j] > 0) j = res[j] + j; 7 | else j = temperatures.size(); 8 | } 9 | // either j == size || temperatures[j] > temperatures[i] 10 | if (j < temperatures.size()) res[i] = j - i; 11 | } 12 | return res; 13 | } -------------------------------------------------------------------------------- /DAY30/KTH SMALLEST ELEMENT IN SORTED MATRIX.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthSmallest(vector>& matrix, int k) { 4 | int m = matrix.size(), n = matrix[0].size(); // For general, the matrix need not be a square 5 | priority_queue maxHeap; 6 | for (int r = 0; r < m; ++r) { 7 | for (int c = 0; c < n; ++c) { 8 | maxHeap.push(matrix[r][c]); 9 | if (maxHeap.size() > k) maxHeap.pop(); 10 | } 11 | } 12 | return maxHeap.top(); 13 | } 14 | }; -------------------------------------------------------------------------------- /DAY42/DECODE WAYS.CPP: -------------------------------------------------------------------------------- 1 | class Solution { // 0 ms, faster than 100.00% 2 | public: 3 | int numDecodings(const string& s) { 4 | int n = s.size(), dp = 0, dp1 = 1, dp2 = 0; 5 | for (int i = n - 1; i >= 0; --i) { 6 | if (s[i] != '0') // Single digit 7 | dp += dp1; 8 | if (i+1 < s.size() && (s[i] == '1' || s[i] == '2' && s[i+1] <= '6')) // Two digits 9 | dp += dp2; 10 | dp2 = dp1; 11 | dp1 = dp; 12 | dp = 0; 13 | } 14 | return dp1; 15 | } 16 | }; -------------------------------------------------------------------------------- /DAY30/PRINT ANAGRAM TOGETHER.CPP: -------------------------------------------------------------------------------- 1 | //QUESTION FROM TRIE; 2 | vector > Anagrams(vector& string_list) 3 | { 4 | unordered_map> m; 5 | for(int i=0;i> v; 13 | for(auto x : m) 14 | { 15 | v.push_back(x.second); 16 | } 17 | return v; 18 | } -------------------------------------------------------------------------------- /DAY29/REDUNDANT CONNECTION.CPP: -------------------------------------------------------------------------------- 1 | vector findRedundantConnection(vector>& edges) { 2 | vector p(2000, 0); 3 | for(int i = 0; i < p.size(); i++ ) 4 | p[i] = i; 5 | 6 | vector res; 7 | for(auto v : edges ){ 8 | int n1 = v[0], n2 = v[1]; 9 | while(n1 != p[n1]) n1 = p[n1]; 10 | while(n2 != p[n2]) n2 = p[n2]; 11 | if( n1 == n2 ) 12 | res = v; 13 | else 14 | p[n1] = n2; 15 | } 16 | return res; 17 | } -------------------------------------------------------------------------------- /DAY20/FIND PEAK ELEMENT .CPP: -------------------------------------------------------------------------------- 1 | int findPeakElement(vector& nums) { 2 | int start = 0; 3 | int end = nums.size() - 1; 4 | 5 | while (start < end) 6 | { 7 | int mid = start - (start - end) / 2; 8 | 9 | if (nums[mid] < nums[mid + 1]) 10 | { 11 | start = mid + 1; 12 | } 13 | else 14 | { 15 | end = mid; 16 | } 17 | } 18 | return start; 19 | 20 | 21 | } -------------------------------------------------------------------------------- /DAY14/LONGEST COMMON PREFIX.CPP: -------------------------------------------------------------------------------- 1 | string longestCommonPrefix(vector& str) { 2 | int n = str.size(); 3 | if(n==0) return ""; 4 | 5 | string ans = ""; 6 | sort(begin(str), end(str)); 7 | string a = str[0]; 8 | string b = str[n-1]; 9 | 10 | for(int i=0; i cnt(26); 3 | int mostFreq = 0, i = 0; 4 | 5 | for(char c : S) 6 | if(++cnt[c - 'a'] > cnt[mostFreq]) 7 | mostFreq = (c - 'a'); 8 | 9 | if(2 * cnt[mostFreq] - 1 > S.size()) return ""; 10 | 11 | while(cnt[mostFreq]) { 12 | S[i] = ('a' + mostFreq); 13 | i += 2; 14 | cnt[mostFreq]--; 15 | } 16 | 17 | for(int j = 0; j < 26; j++) { 18 | while(cnt[j]) { 19 | if(i >= S.size()) i = 1; 20 | S[i] = ('a' + j); 21 | cnt[j]--; 22 | i += 2; 23 | } 24 | } 25 | 26 | return S; 27 | } -------------------------------------------------------------------------------- /DAY29/SORT COLORS.CPP: -------------------------------------------------------------------------------- 1 | void sortColors(vector& nums) {//insertion sort is used 2 | int low =0; 3 | int high = nums.size()-1; 4 | int mid =0; 5 | 6 | while(mid <= high){ 7 | if(nums[mid] == 0){ 8 | swap(nums[mid], nums[low]); 9 | low++; 10 | mid++; 11 | } 12 | else if(nums[mid] == 1){ 13 | mid++; 14 | } 15 | else { 16 | swap(nums[mid], nums[high]); 17 | high--; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /DAY32/Largest subarray with 0 sum .CPP: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int maxLen(vector&A, int n) 4 | { unordered_map mp; 5 | int sum = 0; 6 | int ans = 0; 7 | for(int i = 0; i < n; i++){ 8 | sum += A[i]; 9 | if(sum == 0){ 10 | ans = max(ans , i + 1); 11 | } 12 | else if(!mp.count(sum)){ 13 | mp[sum] = i; 14 | } 15 | else{ 16 | ans = max(ans, i - mp[sum]); 17 | } 18 | } 19 | return ans; 20 | } -------------------------------------------------------------------------------- /DAY7/REVERSEALL2.CPP: -------------------------------------------------------------------------------- 1 | ListNode* reverseBetween(ListNode* head, int left, int right) { 2 | ListNode *dummy = new ListNode(0), *pre = dummy, *cur; 3 | dummy -> next = head; 4 | for (int i = 0; i < left - 1; i++) { 5 | pre = pre -> next; 6 | } 7 | cur = pre -> next; 8 | for (int i = 0; i < right - left; i++) { 9 | ListNode* temp = pre -> next; 10 | pre -> next = cur -> next; 11 | cur -> next = cur -> next -> next; 12 | pre -> next -> next = temp; 13 | } 14 | return dummy -> next; 15 | 16 | } -------------------------------------------------------------------------------- /DAY9/INVERTBINARYTREE.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* invertTree(TreeNode* root) { 2 | if (!root) { 3 | return NULL; 4 | } 5 | queue todo; 6 | todo.push(root); 7 | while (!todo.empty()) { 8 | TreeNode* node = todo.front(); 9 | todo.pop(); 10 | swap(node -> left, node -> right); 11 | if (node -> left) { 12 | todo.push(node -> left); 13 | } 14 | if (node -> right) { 15 | todo.push(node -> right); 16 | } 17 | } 18 | return root; 19 | } -------------------------------------------------------------------------------- /DAY30/Furthest Building You Can Reach.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int furthestBuilding(vector& heights, int bricks, int ladders) { 4 | priority_queue pq; 5 | for (int i = 0; i < heights.size() - 1; i++) { 6 | int d = heights[i + 1] - heights[i]; 7 | if (d > 0) 8 | pq.push(-d); 9 | if (pq.size() > ladders) { 10 | bricks += pq.top(); 11 | pq.pop(); 12 | } 13 | if (bricks < 0) 14 | return i; 15 | } 16 | return heights.size() - 1; 17 | } 18 | }; -------------------------------------------------------------------------------- /DAY42/COUNT SQURE SUBMATRISES WITH ALL ONES.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSquares(vector>& matrix) { 4 | int result = 0; 5 | 6 | for(int i = 0; i 0 && j > 0 && matrix[i][j]>0) 11 | matrix[i][j] = min(matrix[i-1][j-1], min(matrix[i-1][j], matrix[i][j-1])) + 1; 12 | 13 | result += matrix[i][j]; 14 | } 15 | } 16 | 17 | return result; 18 | } 19 | }; -------------------------------------------------------------------------------- /DAY11/BINARY TREE PATH.CPP: -------------------------------------------------------------------------------- 1 | void binaryTreePaths(vector& result, TreeNode* root, string t) { 2 | if(!root->left && !root->right) { 3 | result.push_back(t); 4 | return; 5 | } 6 | 7 | if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val)); 8 | if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val)); 9 | } 10 | 11 | vector binaryTreePaths(TreeNode* root) { 12 | vector result; 13 | if(!root) return result; 14 | 15 | binaryTreePaths(result, root, to_string(root->val)); 16 | return result; 17 | } -------------------------------------------------------------------------------- /DAY37/Populating Next Right Pointers in Each Node.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* connect(Node* root) { 4 | if(root == NULL) return NULL; 5 | //connects the left subtree of same level with right subtree of that same level 6 | if(root->left != NULL) root->left->next = root->right; 7 | //connect the rightmost node of a level to the leftmost node of the next level. 8 | if(root->right != NULL && root->next != NULL) root->right->next = root->next->left; 9 | //recursive calls for left and right subtrees. 10 | connect(root->left); 11 | connect(root->right); 12 | return root; 13 | } 14 | }; -------------------------------------------------------------------------------- /DAY9/MAXIMUMDEPTHOFBINARYTREE.CPP: -------------------------------------------------------------------------------- 1 | int maxDepth(TreeNode* root) { 2 | if(root == NULL) 3 | return 0; 4 | 5 | int res = 0; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()) 9 | { 10 | ++ res; 11 | for(int i = 0, n = q.size(); i < n; ++ i) 12 | { 13 | TreeNode *p = q.front(); 14 | q.pop(); 15 | 16 | if(p -> left != NULL) 17 | q.push(p -> left); 18 | if(p -> right != NULL) 19 | q.push(p -> right); 20 | } 21 | } 22 | 23 | return res; 24 | } -------------------------------------------------------------------------------- /DAY16/MINIMUM DISTANCE B/Count BST nodes that lie in a given range.CPP: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int getCount(Node *root, int l, int h) 4 | { 5 | // your code goes here 6 | if(root == NULL){ 7 | return 0; 8 | } 9 | if(root->data >= l && root->data <= h){ 10 | 11 | return getCount(root->left,l,h) + getCount(root->right,l,h) + 1; 12 | 13 | } 14 | if(root->data < l){ 15 | return getCount(root->right,l,h); 16 | } 17 | if(root->data > h){ 18 | return getCount(root->left,l,h); 19 | } 20 | 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /DAY12/ADD BINARY.CPP: -------------------------------------------------------------------------------- 1 | string addBinary(string a, string b) { 2 | int i = a.length()-1; 3 | int j = b.length()-1; 4 | string ans; 5 | int carry = 0; 6 | 7 | while(i>=0 || j>=0 || carry){ 8 | if(i>=0){ 9 | carry += a[i] - '0'; 10 | i--; 11 | } 12 | if(j>=0){ 13 | carry += b[j] - '0'; 14 | j--; 15 | } 16 | 17 | ans += (carry%2 + '0'); 18 | carry = carry/2; 19 | } 20 | reverse(ans.begin(),ans.end()); 21 | return ans; 22 | } -------------------------------------------------------------------------------- /DAY12/HAPPY NUMBER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int digitSquareSum(int n){ 4 | int temp; 5 | int sum=0; 6 | 7 | while(n){ 8 | temp=n%10; 9 | sum+=temp*temp; 10 | n/=10; 11 | } 12 | return sum; 13 | } 14 | public: 15 | bool isHappy(int n) { 16 | int slow, fast; 17 | slow = fast = n; 18 | do { 19 | slow = digitSquareSum(slow); 20 | fast = digitSquareSum(fast); 21 | fast = digitSquareSum(fast); 22 | } while(slow != fast); 23 | if (slow == 1) return 1; 24 | else return 0; 25 | } 26 | }; -------------------------------------------------------------------------------- /DAY10/SAME TREE.CPP: -------------------------------------------------------------------------------- 1 | bool isSameTree(TreeNode* p, TreeNode* q) { 2 | //3 base case; 3 | if(p==NULL && q==NULL){ 4 | return true; 5 | } 6 | if(p!=NULL && q==NULL){ 7 | return false; 8 | } 9 | if(p==NULL && q!=NULL){ 10 | return false; 11 | } 12 | bool isleft=isSameTree(p->left,q->left); 13 | bool isright=isSameTree(p->right,q->right); 14 | 15 | bool value=q->val==p->val; 16 | if(isleft && isright && value){ 17 | return true; 18 | } 19 | else{ 20 | return false; 21 | } 22 | } -------------------------------------------------------------------------------- /DAY6/REVERSEKNODEINLL.CPP: -------------------------------------------------------------------------------- 1 | ListNode* reverseKGroup(ListNode* head, int k) { 2 | ListNode* cursor = head; 3 | for(int i = 0; i < k; i++){ 4 | if(cursor == nullptr) return head; 5 | cursor = cursor->next; 6 | } 7 | 8 | ListNode* curr = head; 9 | ListNode* prev = nullptr; 10 | ListNode* nxt = nullptr; 11 | 12 | for(int i = 0; i < k; i++){ 13 | nxt = curr->next; 14 | curr->next = prev; 15 | prev = curr; 16 | curr = nxt; 17 | } 18 | head->next = reverseKGroup(curr, k); 19 | return prev; 20 | } -------------------------------------------------------------------------------- /DAY38/Minimum Deletions to Make Character Frequencies Unique.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDeletions(string s) { 4 | int ans = 0; 5 | // count each char 6 | unordered_map char_counts; 7 | for (const char& c : s) char_counts[c]++; 8 | // make a set to hold which counts we've seen 9 | unordered_set seen; 10 | // for each count 11 | for (auto[k, v] : char_counts) { 12 | // if we've seen it, decrement it until we haven't 13 | while (seen.find(v) != seen.end()) { 14 | v--; 15 | ans++; 16 | } 17 | // add it 18 | if (v > 0) seen.insert(v); 19 | } 20 | 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /DAY17/FLATTENING A LL.CPP: -------------------------------------------------------------------------------- 1 | Node *merge(Node *a,Node *b){ 2 | Node *c=new Node(0); 3 | Node *dummy=c; 4 | while(a && b){ 5 | if(a->data<=b->data){ 6 | c->bottom=a; 7 | c=c->bottom; 8 | a=a->bottom; 9 | }else{ 10 | c->bottom=b; 11 | c=c->bottom; 12 | b=b->bottom; 13 | } 14 | } 15 | 16 | if(a){ 17 | c->bottom=a; 18 | }else{ 19 | c->bottom=b; 20 | } 21 | return dummy->bottom; 22 | } 23 | 24 | Node *flatten(Node *root){ 25 | if(root==NULL) return NULL; 26 | return merge(root,flatten(root->next)); 27 | } 28 | -------------------------------------------------------------------------------- /DAY40/EVALUATE REVERSE POLISH NOTATION.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector& tokens) { 4 | stack stn; 5 | for(auto s:tokens) { 6 | if(s.size()>1 || isdigit(s[0])) stn.push(stoi(s)); 7 | else { 8 | auto x2=stn.top(); stn.pop(); 9 | auto x1=stn.top(); stn.pop(); 10 | switch(s[0]) { 11 | case '+': x1+=x2; break; 12 | case '-': x1-=x2; break; 13 | case '*': x1*=x2; break; 14 | case '/': x1/=x2; break; 15 | } 16 | stn.push(x1); 17 | } 18 | } 19 | return stn.top(); 20 | } 21 | }; -------------------------------------------------------------------------------- /DAY36/PERMUTATION 2.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void recursion(vector num, int i, int j, vector > &res) { 4 | if (i == j-1) { 5 | res.push_back(num); 6 | return; 7 | } 8 | for (int k = i; k < j; k++) { 9 | if (i != k && num[i] == num[k]) continue; 10 | swap(num[i], num[k]); 11 | recursion(num, i+1, j, res); 12 | } 13 | } 14 | vector > permuteUnique(vector &num) { 15 | sort(num.begin(), num.end()); 16 | vector >res; 17 | recursion(num, 0, num.size(), res); 18 | return res; 19 | } 20 | }; -------------------------------------------------------------------------------- /DAY41/MAXIMISE THE CUT SEGMENTS.CPP: -------------------------------------------------------------------------------- 1 | int solve(int n, int x, int y, int z) 2 | { 3 | // initialise all values of DP as infinite small value 4 | vectordp(n+1,INT_MIN); 5 | dp[0]=0; 6 | for(int i=1;i<=n;i++) 7 | { 8 | if(i-x >=0) 9 | dp[i]=max(dp[i],dp[i-x]+1); 10 | if(i-y>=0) 11 | dp[i]=max(dp[i],dp[i-y]+1); 12 | if(i-z>=0) 13 | dp[i]=max(dp[i],dp[i-z]+1); 14 | } 15 | return dp[n]<0?0:dp[n]; 16 | } 17 | int maximizeTheCuts(int n, int x, int y, int z) 18 | { 19 | //Your code here 20 | return solve(n,x,y,z); 21 | } -------------------------------------------------------------------------------- /DAY4/REMOVEDUPLICATESFFROMSORTEDLINKEDLIST.CPP: -------------------------------------------------------------------------------- 1 | ListNode* deleteDuplicates(ListNode* head) { 2 | if(head==nullptr){ 3 | return head; 4 | } 5 | ListNode* curr=head; 6 | 7 | while(curr!=nullptr){ 8 | if(curr->next!=nullptr && (curr->val==curr->next->val)){ 9 | ListNode* next_next=curr->next->next; 10 | ListNode* nodetodelete=curr->next; 11 | delete(nodetodelete); 12 | curr->next=next_next; 13 | } 14 | else{ 15 | curr=curr->next; 16 | 17 | } 18 | } 19 | return head; 20 | } -------------------------------------------------------------------------------- /DAY39/ugly number 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | vectordp(n); 5 | dp[0]=1; 6 | int p1=0; 7 | int p2=0; 8 | int p3=0; 9 | for(int i=1;i& gas, vector& cost) { 2 | int current=0; 3 | int gas_cost=0,fuel_cost=0; 4 | int start=0; 5 | for(int i=0;i fullJustify(vector &words, int L) { 2 | vector res; 3 | for(int i = 0, k, l; i < words.size(); i += k) { 4 | for(k = l = 0; i + k < words.size() and l + words[i+k].size() <= L - k; k++) { 5 | l += words[i+k].size(); 6 | } 7 | string tmp = words[i]; 8 | for(int j = 0; j < k - 1; j++) { 9 | if(i + k >= words.size()) tmp += " "; 10 | else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), ' '); 11 | tmp += words[i+j+1]; 12 | } 13 | tmp += string(L - tmp.size(), ' '); 14 | res.push_back(tmp); 15 | } 16 | return res; 17 | } -------------------------------------------------------------------------------- /DAY43/FLOOD FILL.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 4 | if (image[sr][sc] != newColor) 5 | dfs(image, sr, sc, image[sr][sc], newColor); 6 | return image; 7 | } 8 | 9 | private: 10 | void dfs(vector>& image, int i, int j, int c0, int c1) { 11 | if (i < 0 || j < 0 || i >= image.size() || j >= image[0].size() || image[i][j] != c0) return; 12 | image[i][j] = c1; 13 | dfs(image, i, j - 1, c0, c1); 14 | dfs(image, i, j + 1, c0, c1); 15 | dfs(image, i - 1, j, c0, c1); 16 | dfs(image, i + 1, j, c0, c1); 17 | } 18 | }; -------------------------------------------------------------------------------- /DAY1/twosum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector twoSum(vector& nums, int target) { 4 | unordered_map hash; 5 | vector result; 6 | for (int i = 0; i < nums.size(); i++) { 7 | int numberToFind = target - nums[i]; 8 | 9 | //if numberToFind is found in map, return them 10 | if (hash.find(numberToFind) != hash.end()) { 11 | //+1 because indices are NOT zero based 12 | result.push_back(hash[numberToFind] ); 13 | result.push_back(i ); 14 | return result; 15 | } 16 | 17 | //number was not found. Put it in the map. 18 | hash[nums[i]] = i; 19 | } 20 | return result; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /DAY28/BST ITERATOR.CPP: -------------------------------------------------------------------------------- 1 | class BSTIterator { 2 | private: stack myStack; 3 | public: 4 | BSTIterator(TreeNode *root) { 5 | pushAll(root); 6 | } 7 | 8 | /** @return whether we have a next smallest number */ 9 | bool hasNext() { 10 | return !myStack.empty(); 11 | } 12 | 13 | /** @return the next smallest number */ 14 | int next() { 15 | TreeNode *tmpNode = myStack.top(); 16 | myStack.pop(); 17 | pushAll(tmpNode->right); 18 | return tmpNode->val; 19 | } 20 | 21 | private: 22 | void pushAll(TreeNode *node) { 23 | for (; node != NULL; myStack.push(node), node = node->left); 24 | } 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /DAY7/PARTITIONLIST.CPP: -------------------------------------------------------------------------------- 1 | ListNode* partition(ListNode* head, int x) { 2 | ListNode *head1 = new ListNode(0); 3 | ListNode *head2 = new ListNode(0); 4 | ListNode *h1 = head1; 5 | ListNode *h2 = head2; 6 | while(head) 7 | { 8 | int v = head->val; 9 | if(v < x) 10 | { 11 | head1->next = head; 12 | head1 = head1->next; 13 | } else { 14 | head2->next = head; 15 | head2 = head2->next; 16 | } 17 | head = head->next; 18 | } 19 | head2->next = NULL; 20 | head1->next = h2->next;; 21 | return h1->next; 22 | } -------------------------------------------------------------------------------- /DAY2/setmatrixzeros.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void setZeroes(vector>& matrix) { 4 | int col0=1,row=matrix.size(),col=matrix[0].size(); 5 | 6 | for(int i=0;i=0;i--){ 15 | for(int j=col-1;j>=1;j--) 16 | if(matrix[i][0]==0 || matrix[0][j]==0) 17 | matrix[i][j]=0; 18 | if(col0==0) matrix[i][0]=0; 19 | 20 | } 21 | } -------------------------------------------------------------------------------- /DAY19/GROUP ANAGRAMS.CPP: -------------------------------------------------------------------------------- 1 | vector> groupAnagrams(vector& strs) { 2 | ios_base::sync_with_stdio(false); 3 | cin.tie(NULL); 4 | 5 | unordered_map > mymap; 6 | int n = strs.size(); 7 | string temp; 8 | 9 | for(int i =0;i > result; 17 | 18 | for(auto itr=mymap.begin();itr!=mymap.end();++itr) 19 | result.push_back(itr->second); 20 | 21 | return result; 22 | } -------------------------------------------------------------------------------- /DAY36/SUBSETS 2.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void helper(vector>& res, vector& temp, vector& nums, int pos){ 3 | res.push_back(temp); 4 | 5 | for(int i=pos; i> subsetsWithDup(vector& nums) { 16 | vector> res; 17 | vector temp; 18 | sort(nums.begin(), nums.end()); 19 | helper(res, temp, nums, 0); 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /DAY37/vertical order traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map>> m; 4 | void dfs(TreeNode* r, int x, int y) { 5 | if (r != nullptr) { 6 | m[x][y].insert(r->val); 7 | dfs(r->left, x - 1, y + 1); 8 | dfs(r->right, x + 1, y + 1); 9 | } 10 | } 11 | vector> verticalTraversal(TreeNode* r, vector> res = {}) { 12 | dfs(r, 0, 0); 13 | for (auto itx = m.begin(); itx != m.end(); ++itx) { 14 | res.push_back(vector()); 15 | for (auto ity = itx->second.begin(); ity != itx->second.end(); ++ity) { 16 | res.back().insert(end(res.back()), begin(ity->second), end(ity->second)); 17 | } 18 | } 19 | return res; 20 | } 21 | 22 | }; -------------------------------------------------------------------------------- /DAY42/MAXIMUM LENGHT OF REAPETED SUBARRAY.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector& A, vector& B) { 4 | int m = A.size(), n = B.size(), ans = 0; 5 | vector cur(n + 1, 0); 6 | for (int i = 1; i <= m; i++) { 7 | int pre = cur[0]; 8 | for (int j = 1; j <= n; j++) { 9 | int temp = cur[j]; 10 | if (A[i - 1] == B[j - 1]) { 11 | cur[j] = pre + 1; 12 | ans = max(ans, cur[j]); 13 | } else { 14 | cur[j] = 0; 15 | } 16 | pre = temp; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /DAY25/FLATTEN A MULTILEVEL DOUBLY LL.CPP: -------------------------------------------------------------------------------- 1 | Node* flatten(Node* head) { 2 | if(!head) return head; 3 | Node *temp = head; 4 | stack st; 5 | while(temp){ 6 | if(temp->child!=NULL){ 7 | if(temp->next!=NULL) st.push(temp->next); 8 | temp->child->prev = temp; 9 | temp->next = temp->child; 10 | temp->child = NULL; 11 | } 12 | if(!temp->next && !st.empty()){ 13 | Node* top = st.top(); 14 | st.pop(); 15 | temp->next = top; 16 | top->prev = temp; 17 | } 18 | temp = temp->next; 19 | } 20 | return head; 21 | } -------------------------------------------------------------------------------- /DAY9/DIAMETEROFBINARYTREE.CPP: -------------------------------------------------------------------------------- 1 | pair diameterfast(TreeNode* root){ 2 | 3 | //base case 4 | if(root==NULL){ 5 | pair p=make_pair(0,0); 6 | return p; 7 | } 8 | pair left=diameterfast(root->left); 9 | pair right=diameterfast(root->right); 10 | 11 | int op1=left.first; 12 | int op2=right.first; 13 | int op3=left.second+right.second; 14 | 15 | pair ans; 16 | ans.first=max(op1,max(op2,op3)); 17 | ans.second=max(right.second,left.second)+1; 18 | return ans; 19 | } 20 | int diameterOfBinaryTree(TreeNode* root) { 21 | return diameterfast(root).first; 22 | } -------------------------------------------------------------------------------- /DAY26/VALID NUMBER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNumber(string S) { 4 | bool num = false, exp = false, sign = false, dec = false; 5 | for (auto c : S) 6 | if (c >= '0' && c <= '9') num = true ; 7 | else if (c == 'e' || c == 'E') 8 | if (exp || !num) return false; 9 | else exp = true, sign = false, num = false, dec = false; 10 | else if (c == '+' || c == '-') 11 | if (sign || num || dec) return false; 12 | else sign = true; 13 | else if (c == '.') 14 | if (dec || exp) return false; 15 | else dec = true; 16 | else return false; 17 | return num; 18 | } 19 | }; -------------------------------------------------------------------------------- /DAY36/SUBSETS.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(vector nums,vector output,int index,vector>& ans){ 4 | //base 5 | if(index>=nums.size()){ 6 | ans.push_back(output); 7 | return; 8 | } 9 | //exclude 10 | solve(nums,output,index+1,ans); 11 | //include 12 | int element=nums[index]; 13 | output.push_back(element); 14 | solve(nums,output,index+1,ans); 15 | } 16 | public: 17 | vector> subsets(vector& nums) { 18 | vector> ans; 19 | vector output; 20 | int index=0; 21 | solve(nums,output,index,ans); 22 | return ans; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /DAY6/REMOVEDUPLICATEFROMSORTEDLL.CPP: -------------------------------------------------------------------------------- 1 | ListNode* deleteDuplicates(ListNode* head) { 2 | ListNode *dummy=new ListNode(0,head); 3 | ListNode *prev=dummy; 4 | 5 | while(head!=NULL){ 6 | 7 | if(head->next!=NULL && head->val==head->next->val){ 8 | 9 | while(head->next!=NULL && head->val==head->next->val)head=head->next; 10 | 11 | 12 | prev->next=head->next; 13 | } 14 | 15 | else prev=prev->next; 16 | 17 | 18 | head=head->next; 19 | } 20 | 21 | return dummy->next; 22 | 23 | } -------------------------------------------------------------------------------- /DAY7/REMOVEDUPLICATESFROMMLL2.CPP: -------------------------------------------------------------------------------- 1 | ListNode* deleteDuplicates(ListNode* head) { 2 | ListNode *dummy=new ListNode(0,head); 3 | ListNode *prev=dummy; 4 | 5 | while(head!=NULL){ 6 | 7 | if(head->next!=NULL && head->val==head->next->val){ 8 | 9 | while(head->next!=NULL && head->val==head->next->val)head=head->next; 10 | 11 | 12 | prev->next=head->next; 13 | } 14 | 15 | else prev=prev->next; 16 | 17 | 18 | head=head->next; 19 | } 20 | 21 | return dummy->next; 22 | 23 | } -------------------------------------------------------------------------------- /DAY27/MINIMUM COST TREE WITH LEAF VALUE.CPP: -------------------------------------------------------------------------------- 1 | int mctFromLeafValues(vector& arr) { 2 | int sum = 0; 3 | while(arr.size() > 1) 4 | { 5 | int min_product = INT_MAX; // min(a[0]*a[1], ... a[N-1]*a[N]) 6 | int me_index = -1; // min(a[i], a[i+1]) 7 | 8 | for(int i = 1; i < arr.size(); ++i) 9 | { 10 | if( min_product > arr[i-1]*arr[i]) 11 | { 12 | me_index = arr[i-1] < arr[i] ? i - 1 : i; 13 | min_product = arr[i-1]*arr[i]; 14 | } 15 | } 16 | sum += min_product; 17 | arr.erase(arr.begin() + me_index); 18 | } 19 | 20 | return sum; 21 | } -------------------------------------------------------------------------------- /DAY33/WOWRD SEARCH 2.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(vector nums,vector output,int index,vector>& ans){ 4 | //base 5 | if(index>=nums.size()){ 6 | ans.push_back(output); 7 | return; 8 | } 9 | //exclude 10 | solve(nums,output,index+1,ans); 11 | //include 12 | int element=nums[index]; 13 | output.push_back(element); 14 | solve(nums,output,index+1,ans); 15 | } 16 | public: 17 | vector> subsets(vector& nums) { 18 | vector> ans; 19 | vector output; 20 | int index=0; 21 | solve(nums,output,index,ans); 22 | return ans; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /DAY12/maximum product of three number.cpp: -------------------------------------------------------------------------------- 1 | int maximumProduct(vector& nums) { 2 | int f[2][4], i, j; 3 | f[0][0] = f[1][0] = 1; 4 | for (j = 3; j > 0; --j) { 5 | f[0][j] = INT_MIN; 6 | f[1][j] = INT_MAX; 7 | } 8 | 9 | for (i = 0; i < nums.size(); ++i) { 10 | for (j = 3; j > 0; --j) { 11 | if (f[0][j - 1] == INT_MIN) { 12 | continue; 13 | } 14 | f[0][j] = max(f[0][j], max(f[0][j - 1] * nums[i], f[1][j - 1] * nums[i])); 15 | f[1][j] = min(f[1][j], min(f[0][j - 1] * nums[i], f[1][j - 1] * nums[i])); 16 | } 17 | } 18 | return f[0][3]; 19 | } -------------------------------------------------------------------------------- /DAY37/non overl;apping intervals.cpp: -------------------------------------------------------------------------------- 1 | bool comp(vector &a,vector &b) { 2 | return a[1]>& intervals) { 7 | int ans=-1; 8 | if(intervals.size()==0) return 0; 9 | sort(intervals.begin(),intervals.end(),comp); //custom comperator is used. 10 | vector prev= intervals[0]; 11 | 12 | for(vector i: intervals) { 13 | if(prev[1]>i[0]) { 14 | ans++; //we dont update previous, because i[1] will be grater then prev[1] 15 | }else prev=i; // we want the end point to be minimum 16 | } 17 | return ans; //ans was initially made -1 because our prev and intervals[0] will always match 18 | } 19 | }; -------------------------------------------------------------------------------- /DAY23/CIRCULAR TOUR .CPP: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | //Function to find starting point where the truck can start to get through 5 | //the complete circle without exhausting its petrol in between. 6 | int tour(petrolPump p[],int n) 7 | { 8 | int balance=0; 9 | int deficiet=0; 10 | int start=0; 11 | for(int i=0;i=0){ 21 | return start; 22 | } 23 | else{ 24 | return -1; 25 | } 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /DAY6/MERGEKSORTEDLL.CPP: -------------------------------------------------------------------------------- 1 | ListNode* mergeKLists(vector& lists) { 2 | if(lists.empty()){ 3 | return nullptr; 4 | } 5 | while(lists.size() > 1){ 6 | lists.push_back(mergeTwoLists(lists[0], lists[1])); 7 | lists.erase(lists.begin()); 8 | lists.erase(lists.begin()); 9 | } 10 | return lists.front(); 11 | } 12 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 13 | if(l1 == nullptr){ 14 | return l2; 15 | } 16 | if(l2 == nullptr){ 17 | return l1; 18 | } 19 | if(l1->val <= l2->val){ 20 | l1->next = mergeTwoLists(l1->next, l2); 21 | return l1; 22 | } 23 | else{ 24 | l2->next = mergeTwoLists(l1, l2->next); 25 | return l2; 26 | } 27 | } -------------------------------------------------------------------------------- /DAY31/VALID NUMBER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNumber(string S) { 4 | bool num = false, exp = false, sign = false, dec = false; 5 | for (auto c : S){ 6 | if (c >= '0' && c <= '9') num = true ; 7 | else if (c == 'e' || c == 'E') 8 | if (exp || !num) return false; 9 | else exp = true, sign = false, num = false, dec = false; 10 | else if (c == '+' || c == '-') 11 | if (sign || num || dec) return false; 12 | else sign = true; 13 | else if (c == '.') 14 | if (dec || exp) return false; 15 | else dec = true; 16 | else return false; 17 | } 18 | return num; 19 | 20 | } 21 | }; -------------------------------------------------------------------------------- /DAY45/Most Stones Removed with Same Row or Column.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dfs(vector>&stones,int index,vector&visited,int&n){ 4 | visited[index]=true; 5 | int result=0; 6 | for(int i=0;i>&stones) { 12 | int n = stones.size(); 13 | vectorvisited(n,0); 14 | int result=0; 15 | for(int i=0;inext) 9 | { 10 | if(flag) 11 | { 12 | if(curr->data > curr->next->data) 13 | { 14 | swap(curr->data,curr->next->data); 15 | } 16 | } 17 | else 18 | { 19 | if(curr->data < curr->next->data) 20 | { 21 | swap(curr->data,curr->next->data); 22 | } 23 | } 24 | 25 | flag = !flag; 26 | curr = curr->next; 27 | } 28 | 29 | return head; 30 | } -------------------------------------------------------------------------------- /DAY43/BFS OF GRAPH.CPP: -------------------------------------------------------------------------------- 1 | vector bfsOfGraph(int V, vector adj[]) { 2 | vector ans; 3 | queue q; 4 | vector visited; 5 | visited.resize(V,false); 6 | //pushing or starting with initial element 7 | q.push(0); 8 | visited[0]; 9 | while(!q.empty()) 10 | { 11 | int s=q.front(); 12 | ans.push_back(s); 13 | q.pop(); 14 | for(auto adjacent:adj[s]) 15 | { 16 | while(!visited[adjacent]) 17 | { 18 | //check if not coming again 19 | visited[adjacent]=true; 20 | q.push(adjacent); 21 | } 22 | } 23 | } 24 | 25 | return ans; 26 | } -------------------------------------------------------------------------------- /DAY36/BEAUTIFUL ARRANGEMENT.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solve(vector ans,int index,int &count){ 4 | if(index==ans.size()){ 5 | count++; 6 | return; 7 | } 8 | for(int j=index;j ans; 20 | int count=0; 21 | for(int i=1;i<=n;i++){ 22 | ans.push_back(i); 23 | } 24 | solve(ans,0,count); 25 | return count; 26 | } 27 | }; -------------------------------------------------------------------------------- /DAY8/IMPLEMENTSTACKUSINGQUEUE.CPP: -------------------------------------------------------------------------------- 1 | queue q1; 2 | queue q2; 3 | MyStack() { 4 | 5 | } 6 | 7 | /** Push element x onto stack. */ 8 | void push(int x) { 9 | q2.push(x); 10 | while(!q1.empty()){ 11 | q2.push(q1.front()); q1.pop(); 12 | } 13 | swap(q1, q2); 14 | } 15 | 16 | /** Removes the element on top of the stack and returns that element. */ 17 | int pop() { 18 | int result = top(); 19 | q1.pop(); 20 | return result; 21 | } 22 | 23 | /** Get the top element. */ 24 | int top() { 25 | return q1.front(); 26 | } 27 | 28 | /** Returns whether the stack is empty. */ 29 | bool empty() { 30 | return q1.empty(); 31 | } -------------------------------------------------------------------------------- /DAY11/PREDECESSOR AND SUCCESSOR.CPP: -------------------------------------------------------------------------------- 1 | void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) 2 | { 3 | // Your code goes here 4 | if(!root) 5 | return; 6 | if(root->key==key){ 7 | Node *tmp; 8 | if(root->left){ 9 | tmp=root->left; 10 | while(tmp->right) 11 | tmp=tmp->right; 12 | pre=tmp; 13 | } 14 | if(root->right){ 15 | tmp=root->right; 16 | while(tmp->left) 17 | tmp=tmp->left; 18 | suc=tmp; 19 | } 20 | return; 21 | } 22 | if(keykey){ 23 | suc=root; 24 | findPreSuc(root->left,pre,suc,key); 25 | return; 26 | } 27 | pre=root; 28 | findPreSuc(root->right,pre,suc,key); 29 | return; 30 | } -------------------------------------------------------------------------------- /DAY32/REMOVE K SIGITS.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeKdigits(string num, int k) { 4 | if(num.length()==k)return "0"; 5 | // get all eligible elements in a stack 6 | stack s; 7 | for(char c:num){ 8 | while(k && !s.empty() && int(s.top())>int(c)){s.pop();k--;} 9 | s.push(c); 10 | } 11 | //if still no change in k then remove k elements 12 | if(k) while(k--){s.pop();} 13 | // remove leading 0s ,if present 14 | stack t; 15 | while(!s.empty()){t.push(s.top());s.pop();} 16 | while(t.top()=='0'&&t.size()!=1)t.pop(); 17 | //return the answer 18 | num=""; 19 | while(!t.empty()){num.push_back(t.top());t.pop();} 20 | return num; 21 | } 22 | }; -------------------------------------------------------------------------------- /DAY4/removelinkedlistelement.cpp: -------------------------------------------------------------------------------- 1 | ListNode* removeElements(ListNode* head, int val) { 2 | if(head==nullptr) return head; 3 | // This is for the case when a linked list is like this: 4 | // 1->1->2->null , val = 1 5 | // 1->1->1->null , val = 1 6 | while(head!=nullptr && head->val==val){ 7 | head = head->next; 8 | } 9 | ListNode* curr = head; 10 | while(curr!=nullptr && curr->next!=nullptr){ 11 | if(curr->next->val==val){ 12 | curr->next = curr->next->next; 13 | // After doing the above step, I am not updating "curr" because of these type of test cases: 14 | // 1->2->3->6->6->6->5->null val = 6 15 | } 16 | else 17 | curr = curr->next; 18 | } 19 | return head; 20 | } -------------------------------------------------------------------------------- /DAY2/subarraysumdivisiblebyk.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int subarraysDivByK(vector& nums, int k) { 4 | unordered_map mp; 5 | int sum = 0; 6 | mp[0] = 1; // for 0 reminder. 7 | int currSum =0; 8 | int ans =0; 9 | int rem = 0; 10 | for(int i =0;i0;num--) word += curStr; 16 | } else if (cur >= '0' && cur <='9') { 17 | num = num*10 + cur - '0'; 18 | } else if (cur == ']') { 19 | return word; 20 | } else { // Normal characters 21 | word += cur; 22 | } 23 | } 24 | return word; 25 | } 26 | }; -------------------------------------------------------------------------------- /DAY20/SEARCH IN ROTATED SORTED ARRAY.CPP: -------------------------------------------------------------------------------- 1 | int search(vector& nums, int target) { 2 | int start=0,end=nums.size()-1,mid; 3 | while(start<=end) 4 | { 5 | mid=(start+end)/2; 6 | if(nums[mid]==target) 7 | return mid; 8 | if(nums[start]<=nums[mid]) 9 | { 10 | if(target<=nums[mid] && target>=nums[start]) 11 | end=mid-1; 12 | else 13 | start=mid+1; 14 | } 15 | 16 | else 17 | { 18 | if(target>=nums[mid] && target<=nums[end]) 19 | start=mid+1; 20 | else 21 | end=mid-1; 22 | } 23 | 24 | } 25 | return -1; 26 | } -------------------------------------------------------------------------------- /DAY21/combination.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | 5 | void helper(int idx, int k,vector¤t,int n, vector>& ans) 6 | { 7 | if(current.size()==k) // base case 8 | { 9 | ans.push_back(current); 10 | return; 11 | } 12 | 13 | for(int i=idx;i> combine(int n, int k) { 22 | vector> ans; 23 | vectorcurrent; 24 | helper(1,k,current,n,ans); 25 | return ans; //return answer 26 | } 27 | }; -------------------------------------------------------------------------------- /DAY40/DISTINT SUBSEEQUENCE.CPP: -------------------------------------------------------------------------------- 1 | int numDistinct(string s, string t) { 2 | //we use unsigned int because there is a case with a quite large data 3 | vector> dp(t.size() + 1, vector(s.size() + 1)); 4 | 5 | //set as default value of the first line as 1 6 | for (int j = 0; j <= s.size(); j++)dp[0][j] = 1; 7 | 8 | //logic of the loop is above 9 | for (int i = 1; i <= t.size(); i++) { 10 | for (int j = 1; j <= s.size(); j++) { 11 | 12 | if (t[i - 1] == s[j - 1]) { 13 | dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]; 14 | } 15 | else { 16 | dp[i][j] = dp[i][j - 1]; 17 | } 18 | } 19 | } 20 | return dp[dp.size() - 1][dp[0].size() - 1]; 21 | } -------------------------------------------------------------------------------- /DAY28/RECOVER A BINARY TREE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | 4 | void markTree(TreeNode* root, TreeNode*& prev, TreeNode*& first, TreeNode*& end) { 5 | if (!root) return; 6 | markTree(root->left, prev, first, end); 7 | if (prev) { 8 | if (root->val < prev->val) { 9 | if (!first) { 10 | first = prev; 11 | } 12 | end = root; 13 | } 14 | } 15 | prev = root; 16 | markTree(root->right, prev, first, end); 17 | } 18 | 19 | 20 | public: 21 | void recoverTree(TreeNode* root) { 22 | TreeNode *prev = nullptr, *first = nullptr, *end = nullptr; 23 | markTree(root, prev, first, end); 24 | swap(first->val, end->val); 25 | return; 26 | } 27 | }; -------------------------------------------------------------------------------- /DAY42/longest common substring.cpp: -------------------------------------------------------------------------------- 1 | int longestCommonSubstr (string s1, string s2, int n, int m) 2 | { 3 | int dp[n+1][m+1]; 4 | for(int i=0; i q1; 4 | queue q2; 5 | MyStack() { 6 | 7 | } 8 | 9 | /** Push element x onto stack. */ 10 | void push(int x) { 11 | q2.push(x); 12 | while(!q1.empty()){ 13 | q2.push(q1.front()); q1.pop(); 14 | } 15 | swap(q1, q2); 16 | } 17 | 18 | /** Removes the element on top of the stack and returns that element. */ 19 | int pop() { 20 | int result = top(); 21 | q1.pop(); 22 | return result; 23 | } 24 | 25 | /** Get the top element. */ 26 | int top() { 27 | return q1.front(); 28 | } 29 | 30 | /** Returns whether the stack is empty. */ 31 | bool empty() { 32 | return q1.empty(); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /DAY5/addteonumbers.cpp: -------------------------------------------------------------------------------- 1 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 2 | ListNode* dummy=new ListNode(0); 3 | ListNode* head=dummy; 4 | int carry=0; 5 | while(l1!=nullptr || l2!=nullptr || carry>0){ 6 | int val1=0; 7 | if(l1!=nullptr){ 8 | val1=l1->val; 9 | } 10 | int val2=0; 11 | if(l2!=nullptr){ 12 | val2=l2->val; 13 | } 14 | int sum=val1+val2+carry; 15 | int rem=sum%10; 16 | int quo=sum/10; 17 | carry=quo; 18 | ListNode* temp=new ListNode(rem); 19 | head->next=temp; 20 | head=head->next; 21 | if(l1!=NULL){ 22 | l1=l1->next; 23 | } 24 | if(l2!=NULL){ 25 | l2=l2->next; 26 | } 27 | } 28 | return dummy->next; 29 | } -------------------------------------------------------------------------------- /DAY22/BINARY TREE LEVEL ORDER TRAVERSAL.CPP: -------------------------------------------------------------------------------- 1 | vector> levelOrder(TreeNode* root) { 2 | vector > result; 3 | if (!root) return result; 4 | queue q; 5 | q.push(root); 6 | q.push(NULL); 7 | vector cur_vec; 8 | while(!q.empty()) { 9 | TreeNode* t = q.front(); 10 | q.pop(); 11 | if (t==NULL) { 12 | result.push_back(cur_vec); 13 | cur_vec.resize(0); 14 | if (q.size() > 0) { 15 | q.push(NULL); 16 | } 17 | } else { 18 | cur_vec.push_back(t->val); 19 | if (t->left) q.push(t->left); 20 | if (t->right) q.push(t->right); 21 | } 22 | } 23 | return result; 24 | } 25 | -------------------------------------------------------------------------------- /DAY32/Minimum cost for acquiring all coins with k extra coins allowed with every coin.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to acquire all n coins 2 | #include 3 | using namespace std; 4 | 5 | // function to calculate min cost 6 | int minCost(int coin[], int n, int k) 7 | { 8 | // sort the coins value 9 | sort(coin, coin + n); 10 | 11 | // calculate no. of 12 | // coins needed 13 | int coins_needed = ceil(1.0 * n / 14 | (k + 1)); 15 | 16 | // calculate sum of 17 | // all selected coins 18 | int ans = 0; 19 | for (int i = 0; i <= coins_needed - 1; 20 | i++) 21 | ans += coin[i]; 22 | 23 | return ans; 24 | } 25 | 26 | // Driver Code 27 | int main() 28 | { 29 | int coin[] = {8, 5, 3, 10, 30 | 2, 1, 15, 25}; 31 | int n = sizeof(coin) / sizeof(coin[0]); 32 | int k = 3; 33 | cout << minCost(coin, n, k); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /DAY9/SYMMTRICTREE.CPP: -------------------------------------------------------------------------------- 1 | bool isSymmetric(TreeNode* root) { 2 | TreeNode *left, *right; 3 | if (!root) 4 | return true; 5 | 6 | queue q1, q2; 7 | q1.push(root->left); 8 | q2.push(root->right); 9 | while (!q1.empty() && !q2.empty()){ 10 | left = q1.front(); 11 | q1.pop(); 12 | right = q2.front(); 13 | q2.pop(); 14 | if (NULL == left && NULL == right) 15 | continue; 16 | if (NULL == left || NULL == right) 17 | return false; 18 | if (left->val != right->val) 19 | return false; 20 | q1.push(left->left); 21 | q1.push(left->right); 22 | q2.push(right->right); 23 | q2.push(right->left); 24 | } 25 | return true; 26 | } -------------------------------------------------------------------------------- /DAY44/Number of Operations to Make Network Connected.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vectorparent; 3 | int find(int x) { 4 | return (parent[x] == x) ? x : find(parent[x]); 5 | } 6 | public: 7 | int makeConnected(int n, vector>& connections) { 8 | 9 | int c = connections.size(); 10 | if (n-1 > c) return -1; 11 | 12 | parent.resize(n); 13 | for (int i = 0; i < n; i++) 14 | parent[i] = i; 15 | 16 | for (int i = 0; i < c; i++) { 17 | int x = find(connections[i][0]); 18 | int y = find(connections[i][1]); 19 | if (x != y) parent[y] = x; 20 | } 21 | 22 | int ans = 0; 23 | for (int i = 0; i < n; i++) 24 | if (parent[i] == i) 25 | ans++; 26 | 27 | return ans-1; 28 | } 29 | }; -------------------------------------------------------------------------------- /DAY21/COMBINATION SUM2.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void findCombination(int ind, int target, vector &arr, vector> &ans, vector&ds) { 4 | if(target==0) { 5 | ans.push_back(ds); 6 | return; 7 | } 8 | for(int i = ind;iind && arr[i]==arr[i-1]) continue; 10 | if(arr[i]>target) break; 11 | ds.push_back(arr[i]); 12 | findCombination(i+1, target - arr[i], arr, ans, ds); 13 | ds.pop_back(); 14 | } 15 | } 16 | public: 17 | vector> combinationSum2(vector& candidates, int target) { 18 | sort(candidates.begin(), candidates.end()); 19 | vector> ans; 20 | vector ds; 21 | findCombination(0, target, candidates, ans, ds); 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /DAY12/MINIMUM MOOVES TO EQUAL ARRAY ELEMENT.CPP: -------------------------------------------------------------------------------- 1 | // function for finding array sum 2 | int arraySum (int *arr, int n) 3 | { 4 | int sum = 0; 5 | for (int i=0; i& nums) { 20 | // find array sum 21 | int sum = arraySum (nums,nums.size()); 22 | 23 | // find the smallest element from array 24 | int small = smallest (nums, nums.size()); 25 | 26 | // calculate min operation required 27 | int minOperation = sum - (nums.size() * small); 28 | 29 | // return result 30 | return minOperation; 31 | } -------------------------------------------------------------------------------- /DAY35/M COLOURING PROBLEM.CPP: -------------------------------------------------------------------------------- 1 | bool is_valid(bool graph[101][101], int n, vector &color, int k, int i){ 2 | for(int j=0; j &color, int i){ 12 | if(i == n){ 13 | return true; 14 | } 15 | 16 | for(int k=0; k color(n, -1); 34 | return solve(graph, m, n, color, 0); 35 | } -------------------------------------------------------------------------------- /DAY44/FIND EVENTUALLY SAFE STATES.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | enum Color {WHITE, GRAY, BLACK}; 4 | bool dfs(int i, vector & color, vector> & graph) 5 | { 6 | if(color[i]) 7 | return color[i] == BLACK; 8 | color[i] = GRAY; 9 | for(int & v : graph[i]) 10 | { 11 | if(color[v] == GRAY) 12 | return false; 13 | if(color[v] == WHITE && !dfs(v, color, graph)) 14 | return false; 15 | } 16 | color[i] = BLACK; 17 | return true; 18 | } 19 | vector eventualSafeNodes(vector>& graph) 20 | { 21 | int n = int(graph.size()); 22 | vector color(n, WHITE); 23 | vector result; 24 | for(int i = 0; i < n; ++i) 25 | if(dfs(i, color, graph)) 26 | result.push_back(i); 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /DAY43/RAT IN A MAZE1.CPP: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | int n; 5 | vector ans; 6 | vector > maze; 7 | void dfs(int i, int j, string a, char ch){ 8 | if(i == n - 1 && j == n - 1){ 9 | ans.push_back(a); 10 | return; 11 | } 12 | maze[i][j] = -1; 13 | if(j + 1 < n && maze[i][j + 1] == 1 && ch != 'L') dfs(i, j + 1, a + 'R', 'R'); 14 | if(i + 1 < n && maze[i + 1][j] == 1 && ch != 'U') dfs(i + 1, j, a + 'D', 'D'); 15 | if(i - 1 >= 0 && maze[i - 1][j] == 1 && ch != 'D') dfs(i - 1, j, a + 'U', 'U'); 16 | if(j - 1 >= 0 && maze[i][j - 1] == 1 && ch != 'R') dfs(i, j - 1, a + 'L', 'L'); 17 | maze[i][j] = 1; 18 | } 19 | vector findPath(vector> &m, int nn) { 20 | if(m[0][0] == 0) return ans; n = nn; maze = m; 21 | dfs(0, 0, "", 'A'); 22 | return ans; 23 | } 24 | 25 | }; -------------------------------------------------------------------------------- /DAY34/BINARY TREE TO SLL.CPP: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to convert binary tree to doubly linked list and return it. 5 | Node * bToDLL(Node *root) 6 | { 7 | Node* newHead = new Node(); 8 | Node* temp = newHead; 9 | 10 | // your code here 11 | Node* curr = root; 12 | stack st; 13 | while(curr != NULL || st.empty() == false) { 14 | while(curr != NULL) { 15 | st.push(curr); 16 | curr = curr->left; 17 | } 18 | curr = st.top(); 19 | temp->right = curr; 20 | curr->left = temp; 21 | temp = temp->right; 22 | st.pop(); 23 | curr = curr->right; 24 | } 25 | 26 | temp->right = NULL; 27 | newHead = newHead->right; 28 | newHead->left = NULL; 29 | 30 | return newHead; 31 | } 32 | }; -------------------------------------------------------------------------------- /DAY10/Balanced Binary Tree.CPP: -------------------------------------------------------------------------------- 1 | pair isBalancedFast(TreeNode* root){ 2 | //basecase 3 | if(root==NULL){ 4 | pair p=make_pair(true,0); 5 | return p; 6 | } 7 | pair isleft=isBalancedFast(root->left); 8 | pair isright=isBalancedFast(root->right); 9 | 10 | bool leftans=isleft.first; 11 | bool rightans=isright.first; 12 | 13 | bool diff=abs(isleft.second-isright.second)<=1; 14 | 15 | pair ans; 16 | ans.second=max(isleft.second,isright.second)+1; 17 | 18 | if(leftans && rightans && diff){ 19 | ans.first=true; 20 | } 21 | else{ 22 | ans.first=false; 23 | } 24 | return ans; 25 | } 26 | bool isBalanced(TreeNode* root) { 27 | return isBalancedFast(root).first; 28 | } -------------------------------------------------------------------------------- /DAY36/PALINDROME PARTITIONING.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool ispalin(string s,int start,int end){ 4 | while(start<=end){ 5 | if(s[start++]!=s[end--]) 6 | return false; 7 | } 8 | return true; 9 | } 10 | void solve(int index,string s,vector& path,vector> &res){ 11 | if(index==s.size()){ 12 | res.push_back(path); 13 | return; 14 | } 15 | for(int i=index;i> partition(string s) { 25 | vector> res; 26 | vector path; 27 | solve(0,s,path,res); 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /DAY39/k closest points to origin.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> kClosest(vector>& points, int k) { 4 | vector> ans; 5 | priority_queue>> pq; 6 | if(points.size()==0)return ans; 7 | 8 | 9 | for(int i=0;i s1; 2 | stack s2; 3 | /** Initialize your data structure here. */ 4 | MyQueue() { 5 | 6 | } 7 | 8 | /** Push element x to the back of queue. */ 9 | void push(int x) { 10 | while(!s1.empty()) { 11 | s2.push(s1.top()); 12 | s1.pop(); 13 | } 14 | s2.push(x); 15 | while(!s2.empty()) { 16 | s1.push(s2.top()); 17 | s2.pop(); 18 | } 19 | } 20 | 21 | /** Removes the element from in front of queue and returns that element. */ 22 | int pop() { 23 | int curr = s1.top(); 24 | s1.pop(); 25 | return curr; 26 | } 27 | 28 | /** Get the front element. */ 29 | int peek() { 30 | return s1.top(); 31 | } 32 | 33 | /** Returns whether the queue is empty. */ 34 | bool empty() { 35 | return s1.empty(); 36 | } -------------------------------------------------------------------------------- /DAY15/Permute two arrays such that sum of every pair is greater or equal to K.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to check whether permutation of two 2 | // arrays satisfy the condition a[i] + b[i] >= k. 3 | #include 4 | using namespace std; 5 | 6 | // Check whether any permutation exists which 7 | // satisfy the condition. 8 | bool isPossible(int a[], int b[], int n, int k) 9 | { 10 | // Sort the array a[] in decreasing order. 11 | sort(a, a + n); 12 | 13 | // Sort the array b[] in increasing order. 14 | sort(b, b + n, greater()); 15 | 16 | // Checking condition on each index. 17 | for (int i = 0; i < n; i++) 18 | if (a[i] + b[i] < k) 19 | return false; 20 | 21 | return true; 22 | } 23 | 24 | // Driven Program 25 | int main() 26 | { 27 | int a[] = { 2, 1, 3 }; 28 | int b[] = { 7, 8, 9 }; 29 | int k = 10; 30 | int n = sizeof(a)/sizeof(a[0]); 31 | 32 | isPossible(a, b, n, k) ? cout << "Yes" : 33 | cout << "No"; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /DAY29/PATH SUM III.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map map; 4 | int count = 0; 5 | 6 | void countPathSum(TreeNode* root, int target, long long sum){ 7 | if(!root) 8 | return; 9 | sum += root->val; //Path sum from root 10 | if(sum == target) 11 | count++; 12 | if(map.find(sum - target) != map.end()) //checking whether any target sum path present in the path from root to the current node 13 | count += map[sum - target]; 14 | map[sum]++; 15 | countPathSum(root->left, target, sum); 16 | countPathSum(root->right, target, sum); 17 | map[sum]--; //After visiting the left and right subtree, we have to reduce this path sum count from map since we are leaving this path 18 | } 19 | 20 | int pathSum(TreeNode* root, int targetSum) { 21 | countPathSum(root, targetSum, 0); 22 | return count; 23 | } 24 | }; -------------------------------------------------------------------------------- /DAY15/Find a pair with the given difference.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to find a pair with the given difference 2 | #include 3 | using namespace std; 4 | 5 | // The function assumes that the array is sorted 6 | bool findPair(int arr[], int size, int n) 7 | { 8 | // Initialize positions of two elements 9 | int i = 0; 10 | int j = 1; 11 | 12 | // Search for a pair 13 | while (i < size && j < size) 14 | { 15 | if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n) ) 16 | { 17 | cout << "Pair Found: (" << arr[i] << 18 | ", " << arr[j] << ")"; 19 | return true; 20 | } 21 | else if (arr[j]-arr[i] < n) 22 | j++; 23 | else 24 | i++; 25 | } 26 | 27 | cout << "No such pair"; 28 | return false; 29 | } 30 | 31 | // Driver program to test above function 32 | int main() 33 | { 34 | int arr[] = {1, 8, 30, 40, 100}; 35 | int size = sizeof(arr)/sizeof(arr[0]); 36 | int n = -60; 37 | findPair(arr, size, n); 38 | return 0; 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /DAY43/DETECT CYCLE IN UNDIRECTED GRAPH.CPP: -------------------------------------------------------------------------------- 1 | bool isCycle(int V, vector adj[]) { 2 | // Code here 3 | int visited[V]; 4 | memset(visited,0,sizeof(visited)); 5 | queue q; 6 | for(int i=0;i myStack; 3 | char sign = '+'; 4 | long long res = 0, tmp = 0; 5 | for (unsigned int i = 0; i < s.size(); i++) { 6 | if (isdigit(s[i])) 7 | tmp = 10*tmp + s[i]-'0'; 8 | if (!isdigit(s[i]) && !isspace(s[i]) || i == s.size()-1) { 9 | if (sign == '-') 10 | myStack.push(-tmp); 11 | else if (sign == '+') 12 | myStack.push(tmp); 13 | else { 14 | int num; 15 | if (sign == '*' ) 16 | num = myStack.top()*tmp; 17 | else 18 | num = myStack.top()/tmp; 19 | myStack.pop(); 20 | myStack.push(num); 21 | } 22 | sign = s[i]; 23 | tmp = 0; 24 | } 25 | } 26 | while (!myStack.empty()) { 27 | res += myStack.top(); 28 | myStack.pop(); 29 | } 30 | return res; 31 | } -------------------------------------------------------------------------------- /DAY25/AGGRESSIVE COW.CPP: -------------------------------------------------------------------------------- 1 | bool ispossible(vector &stalls, int k,int mid){ 2 | int cowcount=1; 3 | int lastpos=stalls[0]; 4 | for(int i=0;i=mid){ 6 | cowcount++; 7 | if(cowcount==k){ 8 | return true; 9 | } 10 | lastpos=stalls[i]; 11 | } 12 | } 13 | return false; 14 | } 15 | int aggressiveCows(vector &stalls, int k) 16 | {sort(stalls.begin(),stalls.end()); 17 | int s=0; 18 | // int maxi=-1; 19 | // for(int i=0;i restoreArray(vector>& adjacentPairs) { 2 | unordered_map > adj; 3 | for(auto &p : adjacentPairs) { 4 | adj[p[0]].push_back(p[1]); 5 | adj[p[1]].push_back(p[0]); 6 | } 7 | vector ans(adjacentPairs.size() + 1, INT_MIN); 8 | unordered_map vis; 9 | for(auto it : adj) { 10 | if(it.second.size() == 1) { 11 | if(ans[0] == INT_MIN) { 12 | ans[0] = it.first; 13 | }else { 14 | ans.back() = it.first; 15 | } 16 | vis[it.first] = 1; 17 | } 18 | } 19 | 20 | for(int i = 1; i < ans.size() - 1; ++i) { 21 | for(int x : adj[ans[i - 1]]) { 22 | if(vis[x]) continue; 23 | ans[i] = x; 24 | vis[x] = 1; 25 | } 26 | } 27 | return ans; 28 | } -------------------------------------------------------------------------------- /DAY16/MINIMUM DISTANCE B/W TOWO GIVEN NODES IN BINARY TREE.CPP: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | /* Should return minimum distance between a and b 4 | in a tree with given root*/ 5 | Node* lca(Node* root,int a,int b){ 6 | if(root==NULL) return NULL; 7 | if(root->data==a||root->data==b) return root; 8 | Node* left=lca(root->left,a,b); 9 | Node* right=lca(root->right,a,b); 10 | if(!left) return right; 11 | if(!right) return left; 12 | return root; 13 | } 14 | int distance(Node* root,int num,int dist){ 15 | if(root==NULL) return -1; 16 | if(root->data==num) return dist; 17 | int left=distance(root->left,num,dist+1); 18 | if(left!=-1) return left; 19 | return distance(root->right,num,dist+1); 20 | } 21 | int findDist(Node* root, int a, int b) { 22 | // Your code here 23 | Node* lowest=lca(root,a,b); 24 | // cout<data< n) 24 | arr[i] = 1; 25 | 26 | // Updating indices according to values 27 | for (int i = 0; i < n; i++) 28 | arr[(arr[i] - 1) % n] += n; 29 | 30 | // Finding which index has value less than n 31 | for (int i = 0; i < n; i++) 32 | if (arr[i] <= n) 33 | return i + 1; 34 | 35 | // If array has values from 1 to n 36 | return n + 1; 37 | } 38 | }; -------------------------------------------------------------------------------- /DAY31/INTEGER TO WORDS.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string hundredStr(int num){ 4 | vector arr1={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten", 5 | "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; 6 | vector arr2={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; 7 | string ret; 8 | ret=num%100<20?arr1[num%100]:arr2[(num%100)/10]+(num%10?" "+arr1[num%10]:""); 9 | if(num>99)ret=arr1[num/100]+" Hundred"+(num%100?" "+ret:""); 10 | return ret; 11 | } 12 | string numberToWords(int num) { 13 | string ret; 14 | vector strarr={"Thousand","Million","Billion"}; 15 | ret=hundredStr(num%1000); 16 | for(int i=0;i<3;i++){ 17 | num/=1000; 18 | ret=num%1000?hundredStr(num%1000)+" "+strarr[i]+" "+ ret:ret; 19 | } 20 | while(ret.back()==' ')ret.pop_back(); 21 | return ret.empty()?"Zero":ret; 22 | } 23 | }; -------------------------------------------------------------------------------- /DAY40/MINIMUM WINDOW SUBSTRING.CPP: -------------------------------------------------------------------------------- 1 | string minWindow(string s, string t) { 2 | if (s.size() == 0 || t.size() == 0) return ""; 3 | vector remaining(128, 0); 4 | int required = t.size(); 5 | for (int i = 0; i < required; i++) remaining[t[i]]++; 6 | // left is the start index of the min-length substring ever found 7 | int min = INT_MAX, start = 0, left = 0, i = 0; 8 | while(i <= s.size() && start < s.size()) { 9 | if(required) { 10 | if (i == s.size()) break; 11 | remaining[s[i]]--; 12 | if (remaining[s[i]] >= 0) required--; 13 | i++; 14 | } else { 15 | if (i - start < min) { 16 | min = i -start; 17 | left = start; 18 | } 19 | remaining[s[start]]++; 20 | if (remaining[s[start]] > 0) required++; 21 | start++; 22 | } 23 | } 24 | return min == INT_MAX? "" : s.substr(left, min); 25 | } -------------------------------------------------------------------------------- /DAY43/DETECTT CYCLE IN DIRECTED GRAPH.CPP: -------------------------------------------------------------------------------- 1 | bool isCyclic(int V, vector adj[]) 2 | { 3 | vectorindegree(V,0); 4 | queueq; 5 | 6 | for(int i=0;i> threeSum(vector& nums) { 3 | int n_size = nums.size(); 4 | sort(nums.begin(), nums.end()); 5 | vector> result; 6 | for (int i = 0; i < n_size; ++i) { 7 | // all numbers from now on will be greater than 0, no point in continuing 8 | if (nums[i] > 0) break; 9 | 10 | // we have seen this number & combo before; skip 11 | if (i > 0 and nums[i] == nums[i-1]) continue; 12 | 13 | int left = i+1, right = n_size - 1; 14 | while (left < right) { 15 | int sum = nums[i] + nums[left] + nums[right]; 16 | if (sum < 0) { 17 | ++left; 18 | } else if (sum > 0) { 19 | --right; 20 | } else { 21 | result.push_back({nums[i], nums[left], nums[right]}); 22 | int last_left = nums[left], last_right = nums[right]; 23 | // we have seen this number & combo before; skip 24 | while (left < right && nums[left] == last_left) ++left; 25 | while (left < right && nums[right] == last_right) --right; 26 | } 27 | } 28 | 29 | } 30 | return result; 31 | } -------------------------------------------------------------------------------- /DAY39/SWIM IN RISING WATER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | struct T { 5 | int t, x, y; 6 | T(int a, int b, int c) : t (a), x (b), y (c){} 7 | bool operator< (const T &d) const {return t > d.t;} 8 | }; 9 | 10 | int swimInWater(vector>& grid) { 11 | int N = grid.size (), res = 0; 12 | priority_queue pq; 13 | pq.push(T(grid[0][0], 0, 0)); 14 | vector> seen(N, vector(N, 0)); 15 | seen[0][0] = 1; 16 | static int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, { -1, 0}}; 17 | 18 | while (true) { 19 | auto p = pq.top (); 20 | pq.pop (); 21 | res = max(res, p.t); 22 | if (p.x == N - 1 && p.y == N - 1) return res; 23 | for (auto& d : dir) { 24 | int i = p.x + d[0], j = p.y + d[1]; 25 | if (i >= 0 && i < N && j >= 0 && j < N && !seen[i][j]) { 26 | seen[i][j] = 1; 27 | pq.push (T(grid[i][j], i, j)); 28 | } 29 | } 30 | } 31 | } 32 | }; -------------------------------------------------------------------------------- /DAY11/SUBTREE OF ANOTHER TREE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector nodes; 3 | 4 | public: 5 | bool isSubtree(TreeNode* s, TreeNode* t) { 6 | if (!s && !t) return true; 7 | if (!s || !t) return false; 8 | 9 | getDepth(s, getDepth(t, -1)); 10 | 11 | for (TreeNode* n: nodes) 12 | if (identical(n, t)) 13 | return true; 14 | 15 | return false; 16 | } 17 | 18 | int getDepth(TreeNode* r, int d) { 19 | if (!r) 20 | return -1; 21 | 22 | int depth = max(getDepth(r->left, d), getDepth(r->right, d)) + 1; 23 | 24 | // Check if depth equals required value 25 | // Require depth is -1 for tree t (only return the depth, no push) 26 | if (depth == d) 27 | nodes.push_back(r); 28 | 29 | return depth; 30 | } 31 | 32 | bool identical(TreeNode* a, TreeNode* b) { 33 | if (!a && !b) return true; 34 | if (!a || !b || a->val != b->val) return false; 35 | 36 | return identical(a->left, b->left) && identical(a->right, b->right); 37 | } 38 | }; -------------------------------------------------------------------------------- /DAY13/VALID SQUARE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // helper function to calculate distance between two points 4 | double dist(vector& p1, vector& p2) { 5 | return sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1])); 6 | } 7 | 8 | bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { 9 | // keep points in an array to be able to get them by index 10 | vector> points = {p1, p2, p3, p4}; 11 | set lengths; 12 | 13 | for (int i=0; i<4; i++) { 14 | for (int j=i+1; j<4; j++) { 15 | double curr = dist(points[i], points[j]); 16 | if (curr != 0) 17 | lengths.insert(curr); 18 | 19 | // if distance is zero - we got a duplicated point 20 | else 21 | return false; 22 | } 23 | } 24 | // We are supposed to end with only two different lengths: the sides and the diagonals 25 | return lengths.size() == 2; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /DAY39/MINIMUM COST TO HIRE K WORKER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double mincostToHireWorkers(vector& quality, vector& wage, int K) { 4 | int N = quality.size(); 5 | vector>vec; // ratio, quality 6 | for(int i = 0; i < N; i++) { 7 | vec.push_back(make_pair(wage[i] * 1.0 / quality[i], quality[i])); 8 | } 9 | // sort in ascending order 10 | sort(vec.begin(), vec.end(), [](auto& a, auto& b){ 11 | return a.first < b.first; 12 | }); 13 | int quality_cnt = 0; 14 | priority_queue q; // max-min heap 15 | for(int i = 0; i < K; i++) { 16 | quality_cnt += vec[i].second; 17 | q.push(vec[i].second); 18 | } 19 | double ans = quality_cnt * vec[K - 1].first; 20 | for(int i = K; i < N; i++) { 21 | q.push(vec[i].second); 22 | quality_cnt += vec[i].second; 23 | quality_cnt -= q.top(); 24 | q.pop(); 25 | ans = min(ans, quality_cnt * vec[i].first); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /DAY37/BINARY TREE CAMERAS.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int camera(TreeNode* root){ 4 | if (root->left==NULL && root->right==NULL){ 5 | root->val=1; 6 | return 0; 7 | } 8 | int res=0,l=2,r=2; 9 | if (root->left){ 10 | res += camera(root->left); 11 | l = root->left->val; 12 | } 13 | if (root->right){ 14 | res += camera(root->right); 15 | r = root->right->val; 16 | } 17 | // children are unwatched so camera needed 18 | if (l==1 || r==1){ 19 | root->val = 3; 20 | return (res+1); 21 | } 22 | // camera present 23 | if (l==3 || r==3){ 24 | root->val = 2; 25 | return res; 26 | } 27 | // current node is unwatched, so it will be watched from its parent node 28 | root->val=1; 29 | return res; 30 | } 31 | 32 | int minCameraCover(TreeNode* root) { 33 | int res = camera(root); 34 | if (root->val == 1){ 35 | res++; 36 | } 37 | return res; 38 | } 39 | }; -------------------------------------------------------------------------------- /DAY38/UNIQUE PATH3.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int res = 0, empty = 1; 4 | void dfs(vector>& grid, int x, int y, int count) { 5 | if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] == -1) return; 6 | 7 | if (grid[x][y] == 2) { 8 | if(empty == count) res++; 9 | return; 10 | } 11 | 12 | grid[x][y] = -1; 13 | 14 | dfs(grid, x+1, y, count+1); 15 | dfs(grid, x-1, y, count+1); 16 | dfs(grid, x, y+1, count+1); 17 | dfs(grid, x, y-1, count+1); 18 | 19 | grid[x][y] = 0; 20 | 21 | } 22 | 23 | int uniquePathsIII(vector>& grid) { 24 | int start_x, start_y; 25 | for (int i = 0; i < grid.size(); i++) { 26 | for (int j = 0; j < grid[0].size(); j++) { 27 | if (grid[i][j] == 1) start_x = i, start_y = j; 28 | else if (grid[i][j] == 0) empty++; 29 | } 30 | } 31 | 32 | dfs(grid, start_x, start_y, 0); 33 | return res; 34 | } 35 | }; -------------------------------------------------------------------------------- /DAY44/STEPS BY KNIGHT.CPP: -------------------------------------------------------------------------------- 1 | bool check(int i, int j, int N, vector> &dis) { 2 | if (i > N || i < 1 || j > N || j < 1 || dis[i][j] != -1) 3 | return false; 4 | return true; 5 | } 6 | int minStepToReachTarget(vector&KnightPos,vector&TargetPos,int N) 7 | { 8 | // Code here 9 | int x[8] = {-1, 1, 2, -2, -1, 1, 2, -2}; 10 | int y[8] = {2, 2, 1, 1, -2, -2, -1, -1}; 11 | queue> q; 12 | vector> dis(N + 1, vector(N + 1, -1)); 13 | q.push(KnightPos); 14 | dis[KnightPos[0]][KnightPos[1]] = 0; 15 | while (!q.empty()) { 16 | vector u = q.front(); 17 | q.pop(); 18 | for (int v = 0; v < 8; v++) { 19 | int i = u[0] + x[v]; 20 | int j = u[1] + y[v]; 21 | if (check(i, j, N, dis)) { 22 | dis[i][j] = dis[u[0]][u[1]] + 1; 23 | q.push({i, j}); 24 | } 25 | if (i == TargetPos[0] && j == TargetPos[1]) 26 | break; 27 | } 28 | } 29 | return dis[TargetPos[0]][TargetPos[1]]; 30 | } -------------------------------------------------------------------------------- /DAY16/MINIMUM DISTANCE B/BINARY TREE ZIGZAG LEVEL ORDER TRAVELSEL.CPP: -------------------------------------------------------------------------------- 1 | vector> zigzagLevelOrder(TreeNode* root) { 2 | if (root == NULL) { 3 | return vector > (); 4 | } 5 | vector > result; 6 | 7 | queue nodesQueue; 8 | nodesQueue.push(root); 9 | bool leftToRight = true; 10 | 11 | while ( !nodesQueue.empty()) { 12 | int size = nodesQueue.size(); 13 | vector row(size); 14 | for (int i = 0; i < size; i++) { 15 | TreeNode* node = nodesQueue.front(); 16 | nodesQueue.pop(); 17 | 18 | // find position to fill node's value 19 | int index = (leftToRight) ? i : (size - 1 - i); 20 | 21 | row[index] = node->val; 22 | if (node->left) { 23 | nodesQueue.push(node->left); 24 | } 25 | if (node->right) { 26 | nodesQueue.push(node->right); 27 | } 28 | } 29 | // after this level 30 | leftToRight = !leftToRight; 31 | result.push_back(row); 32 | } 33 | return result; 34 | } -------------------------------------------------------------------------------- /DAY19/GENERATE PARENTHESIS.CPP: -------------------------------------------------------------------------------- 1 | void solve(int curropen,int currclose,int remopen,int remclose,string &output,vector &result){ 2 | //base case 3 | if(remopen==0 &&remclose==0){ 4 | result.push_back(output); 5 | return; 6 | } 7 | //'(' iske liye kheltai hai 8 | if(remopen>0){ 9 | output.push_back('('); 10 | solve(curropen+1,currclose,remopen-1,remclose,output,result); 11 | output.pop_back(); 12 | } 13 | //')'iske liya kuch kartai hai 14 | if(remclose>0 && curropen>currclose){ 15 | output.push_back(')'); 16 | solve(curropen,currclose+1,remopen,remclose-1,output,result); 17 | output.pop_back(); 18 | } 19 | 20 | } 21 | vector generateParenthesis(int n) { 22 | vector result; 23 | string output="("; 24 | int curropen=1; 25 | int currclose=0; 26 | int remopen=n-1; 27 | int remclose=n; 28 | 29 | solve(curropen,currclose,remopen,remclose,output,result); 30 | return result; 31 | } -------------------------------------------------------------------------------- /DAY14/VALID PALINDROME 2.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validPalindrome(string s) { 4 | int n = s.size(); 5 | if(n<=2) return true; 6 | 7 | // Keep two pointers Left and Right 8 | int L,R; 9 | L = 0; 10 | R = n-1; 11 | 12 | while(L<=R) 13 | { 14 | //Both first and last element match 15 | if(s[L]==s[R]) 16 | { 17 | ++L;--R; 18 | } 19 | 20 | // One of the element is not matching 21 | else 22 | { 23 | //Removing Left 24 | int LL = L+1, LR = R; 25 | while(LL<=LR && s[LL]==s[LR]) {++LL;--LR;} 26 | if(LL>=LR) return true; 27 | 28 | //Removing Right 29 | int RL = L, RR = R-1; 30 | while(RL<=RR && s[RL]==s[RR]) {++RL;--RR;} 31 | if(RL>=RR) return true; 32 | 33 | return false; 34 | 35 | } 36 | 37 | } 38 | 39 | return true; 40 | } 41 | }; -------------------------------------------------------------------------------- /DAY14/VALID PARENTHESIS.CPP: -------------------------------------------------------------------------------- 1 | bool isValid(string s) { 2 | stack st; //taking stack for keep tracking the order of the brackets.. 3 | for(auto i:s) //iterate over each and every elements 4 | { 5 | if(i=='(' or i=='{' or i=='[') st.push(i); //if current element of the string will be opening bracket then we will just simply push it into the stack 6 | else //if control comes to else part, it means that current element is a closing bracket, so check two conditions current element matches with top of the stack and the stack must not be empty... 7 | { 8 | if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}')||(st.top()=='[' and i!=']')) return false; 9 | st.pop(); //if control reaches to that line, it means we have got the right pair of brackets, so just pop it. 10 | } 11 | } 12 | return st.empty(); //at last, it may possible that we left something into the stack unpair so return checking stack is empty or not.. 13 | } -------------------------------------------------------------------------------- /DAY5/palindromelinkedlist.cpp: -------------------------------------------------------------------------------- 1 | ListNode* findMid(ListNode* head){ 2 | ListNode* slow=head,*fast=head; 3 | while(fast!=NULL && fast->next!=NULL){ 4 | slow=slow->next; 5 | fast=fast->next; 6 | if(fast) fast=fast->next; 7 | } 8 | return slow; 9 | } 10 | ListNode* reverseList(ListNode* head){ 11 | ListNode* prev=NULL,*curr=head,*temp=NULL; 12 | while(curr != NULL){ 13 | temp=curr->next; 14 | curr->next=prev; 15 | prev=curr; 16 | curr=temp; 17 | } 18 | return prev; 19 | } 20 | bool compareList(ListNode* head1, ListNode* head2){ 21 | while(head1!=NULL && head2!=NULL){ 22 | if(head1->val != head2->val) return false; 23 | head1=head1->next; 24 | head2=head2->next; 25 | } 26 | return true; 27 | } 28 | bool isPalindrome(ListNode* head) { 29 | if(head==NULL || head->next==NULL) return true; 30 | ListNode* h=head; 31 | ListNode* mid = findMid(h); 32 | ListNode* h2=reverseList(mid); 33 | return compareList(head,h2); 34 | } -------------------------------------------------------------------------------- /DAY18/REVERSE PAIRS.CPP: -------------------------------------------------------------------------------- 1 | int count; 2 | 3 | void checkCount(vector& nums, int start, int mid, int end){ 4 | 5 | // two pointers; 6 | int l = start, r = mid + 1; 7 | while(l <= mid && r <= end){ 8 | if((long)nums[l] > (long) 2 * nums[r]){ 9 | count += (mid - l + 1); 10 | r++; 11 | }else{ 12 | l++; 13 | } 14 | } 15 | // worst case might be nlog(n) 16 | sort(nums.begin() + start, nums.begin() + end + 1); 17 | return; 18 | 19 | 20 | 21 | //every step sort 22 | } 23 | void mergeSort(vector& nums, int start, int end){ 24 | if(start == end) return; 25 | 26 | int mid = (start + end)/2; 27 | mergeSort(nums,start, mid); 28 | mergeSort(nums,mid+1,end); 29 | 30 | checkCount(nums,start,mid,end); 31 | return; 32 | 33 | } 34 | public: 35 | int reversePairs(vector& nums) { 36 | if(!nums.size())return 0; 37 | count = 0; 38 | mergeSort(nums,0,nums.size()-1); 39 | return count; 40 | } -------------------------------------------------------------------------------- /DAY35/Find maximum of minimum for every window size in a given array.CPP: -------------------------------------------------------------------------------- 1 | // A naive method to find maximum of 2 | // minimum of all windows of different 3 | // sizes 4 | #include 5 | using namespace std; 6 | 7 | void printMaxOfMin(int arr[], int n) 8 | { 9 | // Consider all windows of different 10 | // sizes starting from size 1 11 | for (int k = 1; k <= n; k++) { 12 | // Initialize max of min for 13 | // current window size k 14 | int maxOfMin = INT_MIN; 15 | 16 | // Traverse through all windows 17 | // of current size k 18 | for (int i = 0; i <= n - k; i++) { 19 | // Find minimum of current window 20 | int min = arr[i]; 21 | for (int j = 1; j < k; j++) { 22 | if (arr[i + j] < min) 23 | min = arr[i + j]; 24 | } 25 | 26 | // Update maxOfMin if required 27 | if (min > maxOfMin) 28 | maxOfMin = min; 29 | } 30 | 31 | // Print max of min for current 32 | // window size 33 | cout << maxOfMin << " "; 34 | } 35 | } 36 | 37 | // Driver program 38 | int main() 39 | { 40 | int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; 41 | int n = sizeof(arr) / sizeof(arr[0]); 42 | printMaxOfMin(arr, n); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /DAY8/NEXTGREATERELEMENT1.CPP: -------------------------------------------------------------------------------- 1 | vector nextGreaterElement(vector& nums1, vector& nums2) { 2 | //since there are no duplicates, we can store them in a map; 3 | 4 | vector res(nums1.size(), -1); //to be returned, initialize it with -1. 5 | stack st; 6 | unordered_map umap; 7 | 8 | for(int i=0; i st.top()) 13 | { 14 | //NGE of st.top() is element 15 | 16 | umap[st.top()] = element; 17 | st.pop(); 18 | } 19 | 20 | st.push(element); 21 | } 22 | 23 | for(int i=0; i& strs, int m, int n) { 4 | vector> memo(m+1, vector(n+1, 0)); 5 | int numZeroes, numOnes; 6 | 7 | for (auto &s : strs) { 8 | numZeroes = numOnes = 0; 9 | // count number of zeroes and ones in current string 10 | for (auto c : s) { 11 | if (c == '0') 12 | numZeroes++; 13 | else if (c == '1') 14 | numOnes++; 15 | } 16 | 17 | // memo[i][j] = the max number of strings that can be formed with i 0's and j 1's 18 | // from the first few strings up to the current string s 19 | // Catch: have to go from bottom right to top left 20 | // Why? If a cell in the memo is updated(because s is selected), 21 | // we should be adding 1 to memo[i][j] from the previous iteration (when we were not considering s) 22 | // If we go from top left to bottom right, we would be using results from this iteration => overcounting 23 | for (int i = m; i >= numZeroes; i--) { 24 | for (int j = n; j >= numOnes; j--) { 25 | memo[i][j] = max(memo[i][j], memo[i - numZeroes][j - numOnes] + 1); 26 | } 27 | } 28 | } 29 | return memo[m][n]; 30 | } 31 | }; -------------------------------------------------------------------------------- /DAY14/PRINT ALL DUPLICATES IN THE INPUT STRING.CPP: -------------------------------------------------------------------------------- 1 | //SOLUTION BY GFG; 2 | // C++ program to count all duplicates 3 | // from string using hashing 4 | #include 5 | using namespace std; 6 | # define NO_OF_CHARS 256 7 | 8 | class gfg 9 | { 10 | public : 11 | 12 | /* Fills count array with 13 | frequency of characters */ 14 | void fillCharCounts(char *str, int *count) 15 | { 16 | int i; 17 | for (i = 0; *(str + i); i++) 18 | count[*(str + i)]++; 19 | } 20 | 21 | /* Print duplicates present 22 | in the passed string */ 23 | void printDups(char *str) 24 | { 25 | 26 | // Create an array of size 256 and fill 27 | // count of every character in it 28 | int *count = (int *)calloc(NO_OF_CHARS, 29 | sizeof(int)); 30 | fillCharCounts(str, count); 31 | 32 | // Print characters having count more than 0 33 | int i; 34 | for (i = 0; i < NO_OF_CHARS; i++) 35 | if(count[i] > 1) 36 | printf("%c, count = %d \n", i, count[i]); 37 | 38 | free(count); 39 | } 40 | }; 41 | 42 | /* Driver code*/ 43 | int main() 44 | { 45 | gfg g ; 46 | char str[] = "test string"; 47 | g.printDups(str); 48 | //getchar(); 49 | return 0; 50 | } 51 | 52 | 53 | -------------------------------------------------------------------------------- /DAY27/SUM OF SUBARRAY MINIMUMS.CPP: -------------------------------------------------------------------------------- 1 | int sumSubarrayMins(vector& arr) { 2 | stack s1, s2; 3 | int n = arr.size(); 4 | vector next_smaller(n), prev_smaller(n); 5 | 6 | 7 | for(int i = 0;iarr[i]){ 15 | next_smaller[s1.top()] = i - s1.top() - 1; 16 | s1.pop(); 17 | } 18 | s1.push(i); 19 | } 20 | 21 | for(int i = n-1;i>=0;i--){ 22 | while(!s2.empty() && arr[s2.top()]>=arr[i]){ 23 | prev_smaller[s2.top()] = s2.top() - i - 1; 24 | s2.pop(); 25 | } 26 | s2.push(i); 27 | } 28 | 29 | long ans = 0; 30 | int mod = 1e9 + 7; 31 | 32 | for(int i = 0;i>& grid) { 4 | int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0}; 5 | for (int i = 0; i < m; i++) { 6 | for (int j = 0; j < n; j++) { 7 | if (grid[i][j] == '1') { 8 | islands++; 9 | grid[i][j] = '0'; 10 | queue> todo; 11 | todo.push({i, j}); 12 | while (!todo.empty()) { 13 | pair p = todo.front(); 14 | todo.pop(); 15 | for (int k = 0; k < 4; k++) { 16 | int r = p.first + offsets[k], c = p.second + offsets[k + 1]; 17 | if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') { 18 | grid[r][c] = '0'; 19 | todo.push({r, c}); 20 | } 21 | } 22 | } 23 | } 24 | } 25 | } 26 | return islands; 27 | } 28 | }; -------------------------------------------------------------------------------- /DAY29/Construct Binary Tree from Preorder and Postorder Traversal.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* constructFromPrePost(vector& pre, vector& post) { 4 | 5 | //map all the elements of postorder with their index 6 | 7 | unordered_map mp; 8 | for(int i=0;i& pre,unordered_map& mp,int& preorderIndex) 16 | { 17 | int curr=pre[preorderIndex]; 18 | TreeNode* n=new TreeNode(curr); 19 | preorderIndex++; 20 | if(preorderIndexleft=buildTree(pre,mp,preorderIndex); 24 | } 25 | else 26 | return n; 27 | if(preorderIndex < pre.size() && mp[pre[preorderIndex]] < mp[curr]) 28 | { 29 | n->right=buildTree(pre,mp,preorderIndex); 30 | } 31 | return n; 32 | 33 | } 34 | }; -------------------------------------------------------------------------------- /DAY25/MINIMUM NUMBER OF PAGES.CPP: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find minimum number of pages. 5 | bool ispossible(int A[], int N, int M,int mid){ 6 | int pagesum=0; 7 | int studcount=1; 8 | for(int i=0;iM ||A[i]>mid ) 15 | return false; 16 | 17 | pagesum=A[i]; 18 | } 19 | 20 | 21 | } 22 | return true; 23 | 24 | } 25 | int findPages(int A[], int N, int M) 26 | { 27 | int s=0; 28 | int sum=0; 29 | for(int i=0;i 2 | using namespace std; 3 | 4 | /* Function to get index of ceiling of x in arr[low..high] */ 5 | int ceilSearch(int arr[], int low, int high, int x) 6 | { 7 | 8 | int i; 9 | 10 | /* If x is smaller than or equal to first element, 11 | then return the first element */ 12 | if(x <= arr[low]) 13 | return low; 14 | 15 | /* Otherwise, linearly search for ceil value */ 16 | for(i = low; i < high; i++) 17 | { 18 | if(arr[i] == x) 19 | return i; 20 | 21 | /* if x lies between arr[i] and arr[i+1] including 22 | arr[i+1], then return arr[i+1] */ 23 | if(arr[i] < x && arr[i+1] >= x) 24 | return i+1; 25 | } 26 | 27 | /* If we reach here then x is greater than the last element 28 | of the array, return -1 in this case */ 29 | return -1; 30 | } 31 | 32 | 33 | /* Driver code*/ 34 | int main() 35 | { 36 | int arr[] = {1, 2, 8, 10, 10, 12, 19}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | int x = 3; 39 | int index = ceilSearch(arr, 0, n-1, x); 40 | if(index == -1) 41 | cout << "Ceiling of " << x << " doesn't exist in array "; 42 | else 43 | cout << "ceiling of " << x << " is " << arr[index]; 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /DAY27/DISTANCE OF NEAREST CELL HAVING 1.CPP: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to find distance of nearest 1 in the grid for each cell. 5 | vector>nearest(vector>M) { 6 | queue > q; 7 | vector > dir {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 8 | int n = M.size(), m = M[0].size(); 9 | vector > v(n, vector (m, INT_MAX)); 10 | for(int i=0; i p = q.front(); 22 | q.pop(); 23 | for(auto i:dir){ 24 | int x = p.first + i.first; 25 | int y = p.second + i.second; 26 | if(x >= 0 && x < n && y >= 0 && y < m && v[x][y] > 1+v[p.first][p.second]){ 27 | v[x][y] = 1+v[p.first][p.second]; 28 | q.push({x, y}); 29 | } 30 | } 31 | } 32 | } 33 | return v; 34 | } 35 | }; -------------------------------------------------------------------------------- /DAY3/wordsearch.cpp: -------------------------------------------------------------------------------- 1 | bool visited[6][6]; 2 | 3 | bool solve(vector>& board,string word,int m,int n,string s,int r,int c) 4 | { 5 | if(s==word) return true; 6 | if(r<0 || c<0 || r>=m || c>=n || board[r][c]!=word[s.size()] || visited[r][c]==true) 7 | return false; 8 | 9 | s+=board[r][c]; 10 | visited[r][c]=true; 11 | int d = solve(board,word,m,n,s,r+1,c); // Moving downward 12 | int u = solve(board,word,m,n,s,r-1,c); // Moving upward 13 | int f = solve(board,word,m,n,s,r,c+1); // Moving right or forward 14 | int b = solve(board,word,m,n,s,r,c-1); // Moving left or backward 15 | visited[r][c]=false; 16 | s.pop_back(); 17 | return u || d || f || b; 18 | } 19 | 20 | bool exist(vector>& board, string word) { 21 | int m=board.size(),n=board[0].size(); 22 | string s=""; 23 | for(int i=0;i>& grid) { 2 | // Code here 3 | if(grid.size()==0) 4 | return 0; 5 | int tot=0,cnt=0; 6 | queue> q; 7 | for(int i=0;i=n||ny>=m||grid[nx][ny]!=1)continue; 27 | grid[nx][ny]=2; 28 | q.push({nx,ny}); 29 | 30 | } 31 | } 32 | if(!q.empty())day++; 33 | 34 | } 35 | 36 | return (cnt==tot)?day:-1; 37 | 38 | } -------------------------------------------------------------------------------- /DAY34/Minimum sum of two numbers formed from digits of an array.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to find minimum sum of two numbers 2 | // formed from all digits in a given array. 3 | #include 4 | using namespace std; 5 | 6 | // Returns sum of two numbers formed 7 | // from all digits in a[] 8 | int minSum(int arr[], int n) 9 | { 10 | // min Heap 11 | priority_queue , greater > pq; 12 | 13 | // to store the 2 numbers formed by array elements to 14 | // minimize the required sum 15 | string num1, num2; 16 | 17 | // Adding elements in Priority Queue 18 | for(int i=0; i>a; 5 | unordered_map> mp; 6 | 7 | RandomizedCollection() { 8 | 9 | } 10 | 11 | bool insert(int val) { 12 | auto it=mp.find(val); 13 | if(it == mp.end()) 14 | { 15 | mp[val].push_back(a.size()); 16 | a.push_back(make_pair(val, mp[val].size()-1)); 17 | return true; 18 | } 19 | else{ 20 | mp[val].push_back(a.size()); 21 | a.push_back(make_pair(val, mp[val].size()-1)); 22 | return false; 23 | } 24 | } 25 | 26 | bool remove(int val) { 27 | auto it=mp.find(val); 28 | if(it != mp.end()){ 29 | auto last = a.back(); 30 | mp[last.first][last.second] = mp[val].back(); 31 | a[mp[val].back()] = last; 32 | mp[val].pop_back(); 33 | if(mp[val].empty()) 34 | mp.erase(val); 35 | a.pop_back(); 36 | return true; 37 | } 38 | return false; 39 | 40 | } 41 | 42 | int getRandom() { 43 | return a[rand()%a.size()].first; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /DAY16/MAXIMUMU WIDTH OF BINARY TREE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int widthOfBinaryTree(TreeNode* root) { 4 | if(!root) return 0; 5 | 6 | //similar to level order 7 | queue> q; 8 | int maxwidth =0; 9 | q.push(make_pair(root, 0)); 10 | 11 | while(!q.empty()){ 12 | 13 | 14 | unsigned long long int left_index = q.front().second, right_index = 0; 15 | unsigned long long int sz = q.size(); 16 | 17 | 18 | for(unsigned long long int i=0; i p = q.front(); 21 | q.pop(); 22 | TreeNode *temp = p.first; 23 | right_index = p.second; 24 | 25 | if(temp->left) 26 | q.push(make_pair(temp->left, 2*right_index + 1)); 27 | if(temp->right) 28 | q.push(make_pair(temp->right, 2*right_index + 2)); 29 | 30 | } 31 | 32 | maxwidth = max(maxwidth, int(right_index - left_index + 1)); 33 | } 34 | 35 | return maxwidth; 36 | } 37 | }; -------------------------------------------------------------------------------- /DAY38/Maximum Number of Visible Points.CPP: -------------------------------------------------------------------------------- 1 | #define PI 3.14159265 2 | #define MARGIN 1e-9 3 | 4 | class Solution { 5 | public: 6 | double get_angle(int x_diff, int y_diff) { 7 | return atan2(y_diff, x_diff) * 180 / PI; 8 | } 9 | int visiblePoints(vector>& points, int angle, vector& location) { 10 | int i, j, n = points.size(), common = 0; 11 | vector vals; 12 | for(i=0; i a = vals; 27 | a.insert(a.end(), vals.begin(), vals.end()); 28 | for(i=vals.size(); i topKFrequent(vector& nums, int k) { 19 | unordered_map m; //Key->Number...Value->Freq 20 | //STEP-1: Store frequency of all elements in map 21 | for(int ele: nums) 22 | m[ele]+=1; 23 | 24 | //STEP-2: Now build a heap 25 | priority_queue,compare> heap; //Compare defines a max-heap based on frequency 26 | for(auto it: m) 27 | heap.push(node(it.first,it.second)); 28 | 29 | vector ans; //Stores top-K elements 30 | //STEP-3: Pop top-k elemnts and store the numbers in ans vector 31 | while(k--) 32 | { 33 | node temp = heap.top(); 34 | heap.pop(); 35 | ans.push_back(temp.no); 36 | } 37 | return ans; 38 | } 39 | }; -------------------------------------------------------------------------------- /DAY22/SUDOKO SOLVER.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isvalid(vector>& board,int row,int col,char c){ 4 | for(int i=0;i<9;i++){ 5 | if(board[i][col]==c) 6 | return false; 7 | if(board[row][i]==c) 8 | return false; 9 | if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c) 10 | return false; 11 | } 12 | return true; 13 | } 14 | bool solve(vector>& board){ 15 | for(int i=0;i>& board) { 37 | solve(board); 38 | } 39 | }; -------------------------------------------------------------------------------- /DAY15/Check if reversing a sub array make the array sorted.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to check whether reversing a 2 | // sub array make the array sorted or not 3 | #include 4 | using namespace std; 5 | 6 | // Return true, if reversing the subarray will 7 | // sort the array, else return false. 8 | bool checkReverse(int arr[], int n) 9 | { 10 | // Copying the array. 11 | int temp[n]; 12 | for (int i = 0; i < n; i++) 13 | temp[i] = arr[i]; 14 | 15 | // Sort the copied array. 16 | sort(temp, temp + n); 17 | 18 | // Finding the first mismatch. 19 | int front; 20 | for (front = 0; front < n; front++) 21 | if (temp[front] != arr[front]) 22 | break; 23 | 24 | // Finding the last mismatch. 25 | int back; 26 | for (back = n - 1; back >= 0; back--) 27 | if (temp[back] != arr[back]) 28 | break; 29 | 30 | // If whole array is sorted 31 | if (front >= back) 32 | return true; 33 | 34 | // Checking subarray is decreasing or not. 35 | do 36 | { 37 | front++; 38 | if (arr[front - 1] < arr[front]) 39 | return false; 40 | } while (front != back); 41 | 42 | return true; 43 | } 44 | 45 | // Driven Program 46 | int main() 47 | { 48 | int arr[] = { 1, 2, 5, 4, 3 }; 49 | int n = sizeof(arr)/sizeof(arr[0]); 50 | 51 | checkReverse(arr, n)? (cout << "Yes" << endl): 52 | (cout << "No" << endl); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /DAY39/minimum number of refueling stops.cpp: -------------------------------------------------------------------------------- 1 | int minRefuelStops(int target, int startFuel, vector>& stations) { 2 | int n = stations.size(); 3 | 4 | priority_queue pq; //max heap 5 | /* 6 | if we can't reach target, I will first use the largestfuel Station 7 | (which can take me farthest) and move ahead and keep doing this. 8 | */ 9 | int curr = startFuel; //my current position 10 | int i = 0; //station index 11 | int result = 0; 12 | while(curr < target) { //until I reach my target 13 | while(i < n && curr >= stations[i][0]) { 14 | /* 15 | Sice, I am already ahead of or at this station 16 | (i.e. curr >= stations[i][0]) we don't use this 17 | station and try to move ahead but I store this 18 | station in maxheap to use in future 19 | */ 20 | pq.push(stations[i][1]); 21 | //Keep the station at top which can take me farthest (maximum gas) 22 | i++; 23 | } 24 | 25 | if(pq.empty()) //we can't move further now 26 | return -1; 27 | 28 | int dist = pq.top(); 29 | pq.pop(); 30 | 31 | curr += dist; 32 | result++; 33 | } 34 | 35 | return result; 36 | 37 | } -------------------------------------------------------------------------------- /DAY7/ADDTWONUMBERS2.CPP: -------------------------------------------------------------------------------- 1 | /*IT IS DONE WITH THE HELP OF STACK ; 2 | */ 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | stacks1; 5 | stacks2; 6 | stacks; 7 | 8 | while(l1){ 9 | s1.push(l1->val); 10 | l1=l1->next; 11 | } 12 | while(l2){ 13 | s2.push(l2->val); 14 | l2=l2->next; 15 | } 16 | int carry=0; 17 | while( !s1.empty() || !s2.empty() || carry!=0){ 18 | int s1val=!s1.empty() ?s1.top(): 0; 19 | int s2val=!s2.empty() ?s2.top(): 0; 20 | 21 | int current_sum=s1val+s2val+ carry; 22 | 23 | int finaldigit=current_sum%10; 24 | carry= current_sum/10; 25 | 26 | s.push(finaldigit); 27 | if(!s1.empty()){ 28 | s1.pop(); 29 | } 30 | if(!s2.empty()){ 31 | s2.pop(); 32 | } 33 | } 34 | 35 | ListNode* dummy=new ListNode(-1); 36 | ListNode* l3=dummy; 37 | while(!s.empty()){ 38 | ListNode* new_node=new ListNode(s.top()); 39 | l3->next=new_node; 40 | l3=l3->next; 41 | 42 | s.pop(); 43 | } 44 | return dummy->next; 45 | 46 | 47 | } -------------------------------------------------------------------------------- /DAY23/THE CELEBRITY PROBLEM.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to find celebrity 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Max # of persons in the party 7 | #define N 8 8 | 9 | // Person with 2 is celebrity 10 | bool MATRIX[N][N] = {{0, 0, 1, 0}, 11 | {0, 0, 1, 0}, 12 | {0, 0, 0, 0}, 13 | {0, 0, 1, 0}}; 14 | 15 | bool knows(int a, int b) 16 | { 17 | return MATRIX[a][b]; 18 | } 19 | 20 | // Returns -1 if celebrity 21 | // is not present. If present, 22 | // returns id (value from 0 to n-1). 23 | int findCelebrity(int n) 24 | { 25 | //the graph needs not be constructed 26 | //as the edges can be found by 27 | //using knows function 28 | 29 | //degree array; 30 | int indegree[n]={0},outdegree[n]={0}; 31 | 32 | //query for all edges 33 | for(int i=0; inext == nullptr) 3 | { 4 | list1->next = list2; 5 | return list1; 6 | } 7 | ListNode* curr1 = list1; 8 | ListNode* next1 = curr1->next; 9 | ListNode* curr2 = list2; 10 | ListNode* next2 = curr2->next; 11 | while(next1 != nullptr && curr2 != nullptr) 12 | { 13 | if( (curr2->val >= curr1->val) && (curr2->val <= next1->val) ) 14 | { 15 | // add node in between first list 16 | curr1->next = curr2; 17 | next2 = curr2->next; 18 | curr2->next = next1; 19 | // update pointers 20 | curr1 = curr2; 21 | curr2 = next2; 22 | } 23 | else 24 | { 25 | curr1 = next1; 26 | next1 = next1->next; 27 | if(next1 == nullptr) 28 | { 29 | curr1->next = curr2; 30 | return list1; 31 | } 32 | } 33 | } 34 | return list1; 35 | } 36 | 37 | public: 38 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 39 | if(list1==nullptr) 40 | return list2; 41 | if(list2==nullptr) 42 | return list1; 43 | if(list1->val<=list2->val){ 44 | return solve(list1,list2); 45 | } 46 | else{ 47 | return solve(list2,list1); 48 | } 49 | } -------------------------------------------------------------------------------- /DAY2/choclatedistribution.cpp: -------------------------------------------------------------------------------- 1 | //solution by GFG; 2 | // C++ program to solve chocolate distribution 3 | // problem 4 | #include 5 | using namespace std; 6 | 7 | // arr[0..n-1] represents sizes of packets 8 | // m is number of students. 9 | // Returns minimum difference between maximum 10 | // and minimum values of distribution. 11 | int findMinDiff(int arr[], int n, int m) 12 | { 13 | // if there are no chocolates or number 14 | // of students is 0 15 | if (m == 0 || n == 0) 16 | return 0; 17 | 18 | // Sort the given packets 19 | sort(arr, arr + n); 20 | 21 | // Number of students cannot be more than 22 | // number of packets 23 | if (n < m) 24 | return -1; 25 | 26 | // Largest number of chocolates 27 | int min_diff = INT_MAX; 28 | 29 | // Find the subarray of size m such that 30 | // difference between last (maximum in case 31 | // of sorted) and first (minimum in case of 32 | // sorted) elements of subarray is minimum. 33 | 34 | for (int i = 0; i + m - 1 < n; i++) { 35 | int diff = arr[i + m - 1] - arr[i]; 36 | if (diff < min_diff) 37 | min_diff = diff; 38 | } 39 | return min_diff; 40 | } 41 | 42 | int main() 43 | { 44 | int arr[] = { 12, 4, 7, 9, 2, 23, 25, 41, 30, 45 | 40, 28, 42, 30, 44, 48, 43, 50 }; 46 | int m = 7; // Number of students 47 | int n = sizeof(arr) / sizeof(arr[0]); 48 | cout << "Minimum difference is " 49 | << findMinDiff(arr, n, m); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /DAY21/PARTITION EQUAL SUBSSET SUM.CPP: -------------------------------------------------------------------------------- 1 | // Returns true if there exists a subset 2 | // with given sum in arr[] 3 | #include 4 | using namespace std; 5 | 6 | bool isSubsetSum(int arr[], int n, int sum) 7 | { 8 | 9 | // The value of subset[i%2][j] will be true 10 | // if there exists a subset of sum j in 11 | // arr[0, 1, ...., i-1] 12 | bool subset[2][sum + 1]; 13 | 14 | for (int i = 0; i <= n; i++) { 15 | for (int j = 0; j <= sum; j++) { 16 | 17 | // A subset with sum 0 is always possible 18 | if (j == 0) 19 | subset[i % 2][j] = true; 20 | 21 | // If there exists no element no sum 22 | // is possible 23 | else if (i == 0) 24 | subset[i % 2][j] = false; 25 | else if (arr[i - 1] <= j) 26 | subset[i % 2][j] = subset[(i + 1) % 2] 27 | [j - arr[i - 1]] || subset[(i + 1) % 2][j]; 28 | else 29 | subset[i % 2][j] = subset[(i + 1) % 2][j]; 30 | } 31 | } 32 | 33 | return subset[n % 2][sum]; 34 | } 35 | 36 | // Driver code 37 | int main() 38 | { 39 | int arr[] = { 6, 2, 5 }; 40 | int sum = 7; 41 | int n = sizeof(arr) / sizeof(arr[0]); 42 | if (isSubsetSum(arr, n, sum) == true) 43 | cout <<"There exists a subset with given sum"; 44 | else 45 | cout <<"No subset exists with given sum"; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /DAY17/REORDER LIST.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* reverse(ListNode* head) 4 | { 5 | ListNode* prev=NULL; 6 | ListNode* curr=head; 7 | ListNode* nxt=NULL; 8 | 9 | while(curr) 10 | { 11 | nxt=curr->next; 12 | curr->next=prev; 13 | prev=curr; 14 | curr=nxt; 15 | } 16 | return prev; 17 | } 18 | 19 | 20 | void reorderList(ListNode* head) { 21 | 22 | //step 1 - using slow and fast pointer approach to find the mid of the list 23 | ListNode* slow=head; 24 | ListNode* fast=head->next; 25 | 26 | while(fast and fast->next) 27 | { 28 | slow=slow->next; 29 | fast=fast->next->next; 30 | } 31 | 32 | //step 2 - reverse the second half and split the List into two. 33 | ListNode* second=reverse(slow->next); // independent list second 34 | slow->next=NULL; 35 | ListNode* first=head; // independent list first 36 | 37 | //step 3 - merging the two list 38 | // second list can be shorter when LL size is odd 39 | while(second) 40 | { 41 | ListNode* temp1=first->next; 42 | ListNode* temp2=second->next; 43 | first->next=second; 44 | second->next=temp1; 45 | first=temp1; 46 | second=temp2; 47 | } 48 | } 49 | }; -------------------------------------------------------------------------------- /DAY22/MAX RECTANGLE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector nextSmallerElement(vector arr, int n){ 4 | stack s; 5 | s.push(-1); 6 | vector ans(n); 7 | for(int i=n-1;i>=0;i--){ 8 | int curr=arr[i]; 9 | while( s.top()!=-1 && arr[s.top()]>=curr){ 10 | s.pop(); 11 | } 12 | ans[i]=s.top(); 13 | s.push(i); 14 | } 15 | return ans; 16 | } 17 | vector prevSmallerElement(vector arr, int n){ 18 | stack s; 19 | s.push(-1); 20 | vector ans(n); 21 | for(int i=0;i=curr){ 24 | s.pop(); 25 | } 26 | ans[i]=s.top(); 27 | s.push(i); 28 | } 29 | return ans; 30 | } 31 | public: 32 | int largestRectangleArea(vector& heights) { 33 | int n=heights.size(); 34 | vector next(n); 35 | next=nextSmallerElement(heights,n); 36 | 37 | vector prev(n); 38 | prev=prevSmallerElement(heights,n); 39 | int area=INT_MIN; 40 | for(int i=0;i 2 | using namespace std; 3 | 4 | /* Function to print product array 5 | for a given array arr[] of size n */ 6 | void productArray(int arr[], int n) 7 | { 8 | 9 | // Base case 10 | if (n == 1) { 11 | cout << 0; 12 | return; 13 | } 14 | /* Allocate memory for temporary 15 | arrays left[] and right[] */ 16 | int* left = new int[sizeof(int) * n]; 17 | int* right = new int[sizeof(int) * n]; 18 | 19 | /* Allocate memory for the product array */ 20 | int* prod = new int[sizeof(int) * n]; 21 | 22 | int i, j; 23 | 24 | /* Left most element of left 25 | array is always 1 */ 26 | left[0] = 1; 27 | 28 | /* Right most element of right 29 | array is always 1 */ 30 | right[n - 1] = 1; 31 | 32 | /* Construct the left array */ 33 | for (i = 1; i < n; i++) 34 | left[i] = arr[i - 1] * left[i - 1]; 35 | 36 | /* Construct the right array */ 37 | for (j = n - 2; j >= 0; j--) 38 | right[j] = arr[j + 1] * right[j + 1]; 39 | 40 | /* Construct the product array using 41 | left[] and right[] */ 42 | for (i = 0; i < n; i++) 43 | prod[i] = left[i] * right[i]; 44 | 45 | /* print the constructed prod array */ 46 | for (i = 0; i < n; i++) 47 | cout << prod[i] << " "; 48 | 49 | return; 50 | } 51 | 52 | /* Driver code*/ 53 | int main() 54 | { 55 | int arr[] = { 10, 3, 5, 6, 2 }; 56 | int n = sizeof(arr) / sizeof(arr[0]); 57 | cout << "The product array is: \n"; 58 | productArray(arr, n); 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /DAY22/LARGEST RECTANGLE HISTOGRAM.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector nextSmallerElement(vector arr, int n){ 4 | stack s; 5 | s.push(-1); 6 | vector ans(n); 7 | for(int i=n-1;i>=0;i--){ 8 | int curr=arr[i]; 9 | while( s.top()!=-1 && arr[s.top()]>=curr){ 10 | s.pop(); 11 | } 12 | ans[i]=s.top(); 13 | s.push(i); 14 | } 15 | return ans; 16 | } 17 | vector prevSmallerElement(vector arr, int n){ 18 | stack s; 19 | s.push(-1); 20 | vector ans(n); 21 | for(int i=0;i=curr){ 24 | s.pop(); 25 | } 26 | ans[i]=s.top(); 27 | s.push(i); 28 | } 29 | return ans; 30 | } 31 | public: 32 | int largestRectangleArea(vector& heights) { 33 | int n=heights.size(); 34 | vector next(n); 35 | next=nextSmallerElement(heights,n); 36 | 37 | vector prev(n); 38 | prev=prevSmallerElement(heights,n); 39 | int area=INT_MIN; 40 | for(int i=0;i nextSmallerElement(vector arr, int n){ 4 | stack s; 5 | s.push(-1); 6 | vector ans(n); 7 | for(int i=n-1;i>=0;i--){ 8 | int curr=arr[i]; 9 | while( s.top()!=-1 && arr[s.top()]>=curr){ 10 | s.pop(); 11 | } 12 | ans[i]=s.top(); 13 | s.push(i); 14 | } 15 | return ans; 16 | } 17 | vector prevSmallerElement(vector arr, int n){ 18 | stack s; 19 | s.push(-1); 20 | vector ans(n); 21 | for(int i=0;i=curr){ 24 | s.pop(); 25 | } 26 | ans[i]=s.top(); 27 | s.push(i); 28 | } 29 | return ans; 30 | } 31 | public: 32 | int largestRectangleArea(vector& heights) { 33 | int n=heights.size(); 34 | vector next(n); 35 | next=nextSmallerElement(heights,n); 36 | 37 | vector prev(n); 38 | prev=prevSmallerElement(heights,n); 39 | int area=INT_MIN; 40 | for(int i=0;i nextSmallerElement(vector arr, int n){ 4 | stack s; 5 | s.push(-1); 6 | vector ans(n); 7 | for(int i=n-1;i>=0;i--){ 8 | int curr=arr[i]; 9 | while( s.top()!=-1 && arr[s.top()]>=curr){ 10 | s.pop(); 11 | } 12 | ans[i]=s.top(); 13 | s.push(i); 14 | } 15 | return ans; 16 | } 17 | vector prevSmallerElement(vector arr, int n){ 18 | stack s; 19 | s.push(-1); 20 | vector ans(n); 21 | for(int i=0;i=curr){ 24 | s.pop(); 25 | } 26 | ans[i]=s.top(); 27 | s.push(i); 28 | } 29 | return ans; 30 | } 31 | public: 32 | int largestRectangleArea(vector& heights) { 33 | int n=heights.size(); 34 | vector next(n); 35 | next=nextSmallerElement(heights,n); 36 | 37 | vector prev(n); 38 | prev=prevSmallerElement(heights,n); 39 | int area=INT_MIN; 40 | for(int i=0;is; 6 | 7 | if(path[n-1]!='/') // so that initially path always ends with '/' 8 | path+="/", ++n; 9 | 10 | int i=1; // since path always starts from '/' 11 | string ans=""; 12 | string temp=""; 13 | while(i > solveNQueens(int n) { 5 | std::vector > res; 6 | std::vector nQueens(n, std::string(n, '.')); 7 | solveNQueens(res, nQueens, 0, n); 8 | return res; 9 | } 10 | private: 11 | void solveNQueens(std::vector > &res, std::vector &nQueens, int row, int &n) { 12 | if (row == n) { 13 | res.push_back(nQueens); 14 | return; 15 | } 16 | for (int col = 0; col != n; ++col) 17 | if (isValid(nQueens, row, col, n)) { 18 | nQueens[row][col] = 'Q'; 19 | solveNQueens(res, nQueens, row + 1, n); 20 | nQueens[row][col] = '.'; 21 | } 22 | } 23 | bool isValid(std::vector &nQueens, int row, int col, int &n) { 24 | //check if the column had a queen before. 25 | for (int i = 0; i != row; ++i) 26 | if (nQueens[i][col] == 'Q') 27 | return false; 28 | //check if the 45° diagonal had a queen before. 29 | for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) 30 | if (nQueens[i][j] == 'Q') 31 | return false; 32 | //check if the 135° diagonal had a queen before. 33 | for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j) 34 | if (nQueens[i][j] == 'Q') 35 | return false; 36 | return true; 37 | } 38 | }; -------------------------------------------------------------------------------- /DAY30/IMPLEMENT A PHONE DIRECTORY.CPP: -------------------------------------------------------------------------------- 1 | struct node{ 2 | node *next[26]={NULL}; 3 | bool isLeaf=false; 4 | }; 5 | class trie{ 6 | node *root; 7 | public: 8 | trie(){ 9 | root= new node; 10 | } 11 | void insert(string &s){ 12 | node *head=root; 13 | for(int i=0;inext[s[i]-'a']) head->next[s[i]-'a']=new node; 15 | head=head->next[s[i]-'a']; 16 | } 17 | head->isLeaf=true; 18 | } 19 | 20 | void func(node *head,string &t,vector &ans){ 21 | if(head->isLeaf) ans.push_back(t); 22 | for(int i=0;i<26;i++){ 23 | if(head->next[i]){ 24 | t.push_back('a'+i); 25 | func(head->next[i],t,ans); 26 | t.pop_back(); // backtracking 27 | } 28 | } 29 | } 30 | 31 | vector pre(string &p){ 32 | node *head=root; 33 | for(int i=0;inext[p[i]-'a']) head->next[p[i]-'a']=new node; 35 | head=head->next[p[i]-'a']; 36 | } 37 | vector ans; 38 | func(head,p,ans); 39 | if(ans.empty()) ans.push_back("0"); 40 | return ans; 41 | } 42 | }; 43 | class Solution{ 44 | public: 45 | vector> displayContacts(int n, string contact[], string s) 46 | { 47 | trie *t=new trie(); 48 | for(int i=0;iinsert(contact[i]); 49 | string p; 50 | vector> ans; 51 | for(auto i:s){ 52 | p.push_back(i); 53 | ans.push_back(t->pre(p)); 54 | } 55 | return ans; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /DAY18/GAME OF LIFE.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidNeighbor(int x, int y, vector>& board) { 4 | return (x >= 0 && x < board.size() && y >= 0 && y < board[0].size()); 5 | } 6 | 7 | void gameOfLife(vector>& board) { 8 | vector dx = {0, 0, 1, 1, 1, -1, -1, -1}; //8 coordinated for neighbours 9 | vector dy = {1, -1, 1, -1, 0, 0, 1, -1}; 10 | 11 | for (int row = 0; row < board.size(); row++) { 12 | for (int col = 0; col < board[0].size(); col++) { 13 | 14 | int count_live_neighbors = 0; 15 | 16 | for (int i = 0; i < 8; i++) { 17 | int curr_x = row + dx[i], curr_y = col +dy[i]; 18 | if (isValidNeighbor(curr_x, curr_y, board) && abs(board[curr_x][curr_y])==1) 19 | count_live_neighbors++; 20 | } 21 | 22 | if (board[row][col] == 1 && (count_live_neighbors < 2 || count_live_neighbors > 3)) 23 | board[row][col] = -1; 24 | 25 | if (board[row][col] == 0 && count_live_neighbors == 3) 26 | board[row][col] = 2; 27 | } 28 | } 29 | 30 | for (int row = 0; row < board.size(); row++) { 31 | for (int col = 0; col < board[0].size(); col++) { 32 | if (board[row][col] >= 1) 33 | board[row][col] = 1; 34 | else 35 | board[row][col] = 0; 36 | } 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /DAY6/SORTLIST.CPP: -------------------------------------------------------------------------------- 1 | ListNode* sortList(ListNode* head){ 2 | bool done = (!head); 3 | // Keep partitioning our list into bigger sublists length. Starting with a size of 1 and doubling each time 4 | for (int step = 1; !done; step *= 2) { 5 | done = true; 6 | ListNode** next_ptr = &head; 7 | ListNode* remaining = head; 8 | ListNode* list[2]; 9 | do { 10 | // Split off two sublists of size step 11 | for (auto& sub_head : list) { 12 | sub_head = remaining; 13 | ListNode* tail = nullptr; 14 | for (int i = 0; i < step && remaining; ++i, remaining = remaining->next) { 15 | tail = remaining; 16 | } 17 | // Terminate our sublist 18 | if (tail) { 19 | tail->next = nullptr; 20 | } 21 | } 22 | 23 | // We're done if these are the first two sublists in this pass and they 24 | // encompass the entire primary list 25 | done &= !remaining; 26 | 27 | // If we have two sublists, merge them into one 28 | if (list[1]) { 29 | while (list[0] || list[1]) { 30 | int idx = (!list[1] || list[0] && list[0]->val <= list[1]->val) ? 0 : 1; 31 | *next_ptr = list[idx]; 32 | list[idx] = list[idx]->next; 33 | next_ptr = &(**next_ptr).next; 34 | } 35 | 36 | // Terminate our new sublist 37 | *next_ptr = nullptr; 38 | } else { 39 | // Only a single sublist, no need to merge, just attach to the end 40 | *next_ptr = list[0]; 41 | } 42 | } while (remaining); 43 | } 44 | return head; 45 | } -------------------------------------------------------------------------------- /DAY3/spiralmatrix.cpp: -------------------------------------------------------------------------------- 1 | vector spiralOrder(vector>& matrix) { 2 | vector ans; 3 | int row = matrix.size(); 4 | int col = matrix[0].size(); 5 | 6 | int count = 0; 7 | int total = row*col; 8 | 9 | //index initialisation 10 | int startingRow = 0; 11 | int startingCol = 0; 12 | int endingRow = row-1; 13 | int endingCol = col-1; 14 | 15 | 16 | while(count < total) { 17 | 18 | //print starting row 19 | for(int index = startingCol; count < total && index<=endingCol; index++) { 20 | ans.push_back(matrix[startingRow][index]); 21 | count++; 22 | } 23 | startingRow++; 24 | 25 | //print ending column 26 | for(int index = startingRow; count < total && index<=endingRow; index++) { 27 | ans.push_back(matrix[index][endingCol]); 28 | count++; 29 | } 30 | endingCol--; 31 | 32 | //print ending row 33 | for(int index = endingCol; count < total && index>=startingCol; index--) { 34 | ans.push_back(matrix[endingRow][index]); 35 | count++; 36 | } 37 | endingRow--; 38 | 39 | //print starting column 40 | for(int index = endingRow; count < total && index>=startingRow; index--) { 41 | ans.push_back(matrix[index][startingCol]); 42 | count++; 43 | } 44 | startingCol++; 45 | } 46 | return ans; 47 | } 48 | -------------------------------------------------------------------------------- /DAY23/SPIRAL MATRIX.CPP: -------------------------------------------------------------------------------- 1 | vector spiralOrder(vector>& matrix) { 2 | vector ans; 3 | int row = matrix.size(); 4 | int col = matrix[0].size(); 5 | 6 | int count = 0; 7 | int total = row*col; 8 | 9 | //index initialisation 10 | int startingRow = 0; 11 | int startingCol = 0; 12 | int endingRow = row-1; 13 | int endingCol = col-1; 14 | 15 | 16 | while(count < total) { 17 | 18 | //print starting row 19 | for(int index = startingCol; count < total && index<=endingCol; index++) { 20 | ans.push_back(matrix[startingRow][index]); 21 | count++; 22 | } 23 | startingRow++; 24 | 25 | //print ending column 26 | for(int index = startingRow; count < total && index<=endingRow; index++) { 27 | ans.push_back(matrix[index][endingCol]); 28 | count++; 29 | } 30 | endingCol--; 31 | 32 | //print ending row 33 | for(int index = endingCol; count < total && index>=startingCol; index--) { 34 | ans.push_back(matrix[endingRow][index]); 35 | count++; 36 | } 37 | endingRow--; 38 | 39 | //print starting column 40 | for(int index = endingRow; count < total && index>=startingRow; index--) { 41 | ans.push_back(matrix[index][startingCol]); 42 | count++; 43 | } 44 | startingCol++; 45 | } 46 | return ans; 47 | } 48 | 49 | }; -------------------------------------------------------------------------------- /DAY5/givenonlyforpointer.cpp: -------------------------------------------------------------------------------- 1 | //by geeks for geeks 2 | 3 | #include 4 | using namespace std; 5 | 6 | /* Link list node */ 7 | class Node { 8 | public: 9 | int data; 10 | Node* next; 11 | }; 12 | 13 | /* Given a reference (pointer to pointer) to the head 14 | of a list and an int, push a new node on the front 15 | of the list. */ 16 | void push(Node** head_ref, int new_data) 17 | { 18 | /* allocate node */ 19 | Node* new_node = new Node(); 20 | 21 | /* put in the data */ 22 | new_node->data = new_data; 23 | 24 | /* link the old list off the new node */ 25 | new_node->next = (*head_ref); 26 | 27 | /* move the head to point to the new node */ 28 | (*head_ref) = new_node; 29 | } 30 | 31 | void printList(Node* head) 32 | { 33 | Node* temp = head; 34 | while (temp != NULL) { 35 | cout << temp->data << " "; 36 | temp = temp->next; 37 | } 38 | } 39 | 40 | void deleteNode(Node* node) 41 | { 42 | Node* prev; 43 | if (node == NULL) 44 | return; 45 | else { 46 | while (node->next != NULL) { 47 | node->data = node->next->data; 48 | prev = node; 49 | node = node->next; 50 | } 51 | prev->next = NULL; 52 | } 53 | } 54 | 55 | /* Driver code*/ 56 | int main() 57 | { 58 | /* Start with the empty list */ 59 | Node* head = NULL; 60 | 61 | /* Use push() to construct below list 62 | 1->12->1->4->1 */ 63 | push(&head, 1); 64 | push(&head, 4); 65 | push(&head, 1); 66 | push(&head, 12); 67 | push(&head, 1); 68 | 69 | cout << "Before deleting \n"; 70 | printList(head); 71 | 72 | /* I m deleting the head itself. 73 | You can check for more cases */ 74 | deleteNode(head); 75 | 76 | cout << "\nAfter deleting \n"; 77 | printList(head); 78 | return 0; 79 | } 80 | 81 | 82 | -------------------------------------------------------------------------------- /DAY38/Solving Cryptarithmetic Puzzles Backtracking.CPP: -------------------------------------------------------------------------------- 1 | /* ExhaustiveSolve 2 | * --------------- 3 | * This is the "not-very-smart" version of cryptarithmetic solver. It takes 4 | * the puzzle itself (with the 3 strings for the two addends and sum) and a 5 | * string of letters as yet unassigned. If no more letters to assign 6 | * then we've hit a base-case, if the current letter-to-digit mapping solves 7 | * the puzzle, we're done, otherwise we return false to trigger backtracking 8 | * If we have letters to assign, we take the first letter from that list, and 9 | * try assigning it the digits from 0 to 9 and then recursively working 10 | * through solving puzzle from here. If we manage to make a good assignment 11 | * that works, we've succeeded, else we need to unassign that choice and try 12 | * another digit. This version is easy to write, since it uses a simple 13 | * approach (quite similar to permutations if you think about it) but it is 14 | * not so smart because it doesn't take into account the structure of the 15 | * puzzle constraints (for example, once the two digits for the addends have 16 | * been assigned, there is no reason to try anything other than the correct 17 | * digit for the sum) yet it tries a lot of useless combos regardless 18 | */ 19 | bool ExhaustiveSolve(puzzleT puzzle, string lettersToAssign) 20 | { 21 | if (lettersToAssign.empty()) // no more choices to make 22 | return PuzzleSolved(puzzle); // checks arithmetic to see if works 23 | for (int digit = 0; digit <= 9; digit++) // try all digits 24 | { 25 | if (AssignLetterToDigit(lettersToAssign[0], digit)) 26 | { 27 | if (ExhaustiveSolve(puzzle, lettersToAssign.substr(1))) 28 | return true; 29 | UnassignLetterFromDigit(lettersToAssign[0], digit); 30 | } 31 | } 32 | return false; // nothing worked, need to backtrack 33 | } 34 | -------------------------------------------------------------------------------- /DAY36/PRINT ALL PALINDROMIC PARTITION OF A STRING.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to print all palindromic partitions 2 | // of a given string. 3 | #include 4 | using namespace std; 5 | 6 | // Returns true if str is palindrome, else false 7 | bool checkPalindrome(string str) 8 | { 9 | int len = str.length(); 10 | len--; 11 | for (int i=0; i > partitions) 21 | { 22 | for (int i = 0; i < partitions.size(); ++i) 23 | { 24 | for(int j = 0; j < partitions[i].size(); ++j) 25 | cout << partitions[i][j] << " "; 26 | cout << endl; 27 | } 28 | return; 29 | } 30 | 31 | // Goes through all indexes and recursively add remaining 32 | // partitions if current string is palindrome. 33 | void addStrings(vector > &v, string &s, 34 | vector &temp, int index) 35 | { 36 | int len = s.length(); 37 | string str; 38 | vector current = temp; 39 | if (index == 0) 40 | temp.clear(); 41 | for (int i = index; i < len; ++i) 42 | { 43 | str = str + s[i]; 44 | if (checkPalindrome(str)) 45 | { 46 | temp.push_back(str); 47 | if (i+1 < len) 48 | addStrings(v,s,temp,i+1); 49 | else 50 | v.push_back(temp); 51 | temp = current; 52 | } 53 | } 54 | return; 55 | } 56 | 57 | // Generates all palindromic partitions of 's' and 58 | // stores the result in 'v'. 59 | void partition(string s, vector >&v) 60 | { 61 | vector temp; 62 | addStrings(v, s, temp, 0); 63 | printSolution(v); 64 | return; 65 | } 66 | 67 | // Driver code 68 | int main() 69 | { 70 | string s = "geeks"; 71 | vector > partitions; 72 | partition(s, partitions); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /DAY29/UNIQUE BST2.CPP: -------------------------------------------------------------------------------- 1 | TreeNode* clone(TreeNode* root){ 2 | if(root == nullptr) 3 | return nullptr; 4 | TreeNode* newroot = new TreeNode(root->val); 5 | newroot->left = clone(root->left); 6 | newroot->right = clone(root->right); 7 | return newroot; 8 | } 9 | vector generateTrees(int n) { 10 | vector res(1,nullptr); 11 | for(int i = 1; i <= n; i++){ 12 | vector tmp; 13 | for(int j = 0; jleft = target; 18 | tmp.push_back(root); 19 | 20 | if(oldroot!=nullptr){ 21 | TreeNode* tmpold = oldroot; 22 | while(tmpold->right!=nullptr){ 23 | TreeNode* nonroot = new TreeNode(i); 24 | TreeNode *tright = tmpold->right; 25 | tmpold->right = nonroot; 26 | nonroot->left = tright; 27 | TreeNode *target = clone(oldroot); 28 | tmp.push_back(target); 29 | tmpold->right = tright; 30 | tmpold = tmpold->right; 31 | } 32 | tmpold->right = new TreeNode(i); 33 | TreeNode *target = clone(oldroot); 34 | tmp.push_back(target); 35 | tmpold->right = nullptr; 36 | } 37 | } 38 | res=tmp; 39 | } 40 | return res; 41 | } -------------------------------------------------------------------------------- /DAY33/Find Maximum number possible by doing at-most K swaps.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to find maximum 2 | // integer possible by doing 3 | // at-most K swap operations on 4 | // its digits. 5 | #include 6 | using namespace std; 7 | 8 | // Function to find maximum 9 | // integer possible by 10 | // doing at-most K swap operations 11 | // on its digits 12 | void findMaximumNum( 13 | string str, int k, 14 | string& max, int ctr) 15 | { 16 | // return if no swaps left 17 | if (k == 0) 18 | return; 19 | 20 | int n = str.length(); 21 | 22 | // Consider every digit after 23 | // the cur position 24 | char maxm = str[ctr]; 25 | for (int j = ctr + 1; j < n; j++) { 26 | // Find maximum digit greater 27 | // than at ctr among rest 28 | if (maxm < str[j]) 29 | maxm = str[j]; 30 | } 31 | 32 | // If maxm is not equal to str[ctr], 33 | // decrement k 34 | if (maxm != str[ctr]) 35 | --k; 36 | 37 | // search this maximum among the rest from behind 38 | //first swap the last maximum digit if it occurs more then 1 time 39 | //example str= 1293498 and k=1 then max string is 9293418 instead of 9213498 40 | for (int j = n-1; j >=ctr; j--) { 41 | // If digit equals maxm swap 42 | // the digit with current 43 | // digit and recurse for the rest 44 | if (str[j] == maxm) { 45 | // swap str[ctr] with str[j] 46 | swap(str[ctr], str[j]); 47 | 48 | // If current num is more than 49 | // maximum so far 50 | if (str.compare(max) > 0) 51 | max = str; 52 | 53 | // recurse other swaps after cur 54 | findMaximumNum(str, k, max, ctr + 1); 55 | 56 | // Backtrack 57 | swap(str[ctr], str[j]); 58 | } 59 | } 60 | } 61 | 62 | // Driver code 63 | int main() 64 | { 65 | string str = "129814999"; 66 | int k = 4; 67 | 68 | string max = str; 69 | findMaximumNum(str, k, max, 0); 70 | 71 | cout << max << endl; 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /DAY15/Make all array elements equal with minimum cost.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to find minimum cost to 2 | // make all elements equal 3 | #include 4 | using namespace std; 5 | 6 | // Utility method to compute cost, when 7 | // all values of array are made equal to X 8 | int computeCost(int arr[], int N, int X) 9 | { 10 | int cost = 0; 11 | for (int i = 0; i < N; i++) 12 | cost += abs(arr[i] - X); 13 | return cost; 14 | } 15 | 16 | // Method to find minimum cost to make all 17 | // elements equal 18 | int minCostToMakeElementEqual(int arr[], int N) 19 | { 20 | int low, high; 21 | low = high = arr[0]; 22 | 23 | // setting limits for ternary search by 24 | // smallest and largest element 25 | for (int i = 0; i < N; i++) { 26 | if (low > arr[i]) 27 | low = arr[i]; 28 | if (high < arr[i]) 29 | high = arr[i]; 30 | } 31 | 32 | /* loop until difference between low and high 33 | become less than 3, because after that 34 | mid1 and mid2 will start repeating 35 | */ 36 | while ((high - low) > 2) { 37 | 38 | // mid1 and mid2 are representative array 39 | // equal values of search space 40 | int mid1 = low + (high - low) / 3; 41 | int mid2 = high - (high - low) / 3; 42 | 43 | int cost1 = computeCost(arr, N, mid1); 44 | int cost2 = computeCost(arr, N, mid2); 45 | 46 | // if mid2 point gives more total cost, 47 | // skip third part 48 | if (cost1 < cost2) 49 | high = mid2; 50 | 51 | // if mid1 point gives more total cost, 52 | // skip first part 53 | else 54 | low = mid1; 55 | } 56 | 57 | // computeCost gets optimum cost by sending 58 | // average of low and high as X 59 | return computeCost(arr, N, (low + high) / 2); 60 | } 61 | 62 | // Driver code to test above method 63 | int main() 64 | { 65 | int arr[] = { 1, 100, 101 }; 66 | int N = sizeof(arr) / sizeof(int); 67 | cout << minCostToMakeElementEqual(arr, N); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /DAY25/COUNT OF SMALLER NO AFTER ITSELF.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void merge(vector &count, vector> &v, int left, int mid, int right){ 5 | vector> temp(right - left + 1); 6 | int i=left; 7 | int j=mid+1; 8 | int k=0; 9 | 10 | while(i<=mid && j<=right){ 11 | 12 | if(v[i].first <= v[j].first){ 13 | temp[k++] = v[j++]; 14 | } 15 | 16 | else{ 17 | 18 | count[v[i].second] += right-j+1; 19 | temp[k++] = v[i++]; 20 | 21 | } 22 | 23 | } 24 | 25 | 26 | while(i<=mid){ 27 | temp[k++] = v[i++]; 28 | } 29 | 30 | while(j<=right){ 31 | temp[k++] = v[j++]; 32 | } 33 | 34 | for(int i=left;i<=right;i++){ 35 | v[i] = temp[i-left]; 36 | } 37 | 38 | } 39 | 40 | void mergeSort(vector &count, vector> &v, int left, int right){ 41 | 42 | 43 | if(left countSmaller(vector& nums) { 53 | int n = nums.size(); 54 | vector> v(n); 55 | for(int i=0;i p; 57 | p.first = nums[i]; 58 | p.second = i; 59 | v[i] = p; 60 | } 61 | 62 | 63 | vector count(n, 0); 64 | mergeSort(count, v, 0, n-1); 65 | return count; 66 | 67 | } 68 | }; -------------------------------------------------------------------------------- /DAY37/Serialize and Deserialize Binary Tree.CPP: -------------------------------------------------------------------------------- 1 | class Codec{ 2 | public: 3 | // Encodes a tree to a single string. 4 | string serialize(TreeNode* root) { 5 | if(!root) return ""; 6 | 7 | string s =""; 8 | queue q; 9 | q.push(root); 10 | while(!q.empty()) { 11 | TreeNode* curNode = q.front(); 12 | q.pop(); 13 | if(curNode==NULL) s.append("#,"); 14 | else s.append(to_string(curNode->val)+','); 15 | if(curNode != NULL){ 16 | q.push(curNode->left); 17 | q.push(curNode->right); 18 | } 19 | } 20 | return s; 21 | } 22 | 23 | // Decodes your encoded data to tree. 24 | TreeNode* deserialize(string data) { 25 | if(data.size() == 0) return NULL; 26 | stringstream s(data); 27 | string str; 28 | getline(s, str, ','); 29 | TreeNode *root = new TreeNode(stoi(str)); 30 | queue q; 31 | q.push(root); 32 | while(!q.empty()) { 33 | 34 | TreeNode *node = q.front(); 35 | q.pop(); 36 | 37 | getline(s, str, ','); 38 | if(str == "#") { 39 | node->left = NULL; 40 | } 41 | else { 42 | TreeNode* leftNode = new TreeNode(stoi(str)); 43 | node->left = leftNode; 44 | q.push(leftNode); 45 | } 46 | 47 | getline(s, str, ','); 48 | if(str == "#") { 49 | node->right = NULL; 50 | } 51 | else { 52 | TreeNode* rightNode = new TreeNode(stoi(str)); 53 | node->right = rightNode; 54 | q.push(rightNode); 55 | } 56 | } 57 | return root; 58 | } 59 | }; -------------------------------------------------------------------------------- /DAY30/Design Add and Search Words Data Structure.CPP: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public: 3 | bool word; 4 | TrieNode* children[26]; 5 | TrieNode() { 6 | word = false; 7 | memset(children, NULL, sizeof(children)); 8 | } 9 | }; 10 | 11 | class WordDictionary { 12 | public: 13 | /** Initialize your data structure here. */ 14 | WordDictionary() { 15 | 16 | } 17 | 18 | /** Adds a word into the data structure. */ 19 | void addWord(string word) { 20 | TrieNode* node = root; 21 | for (char c : word) { 22 | if (!node -> children[c - 'a']) { 23 | node -> children[c - 'a'] = new TrieNode(); 24 | } 25 | node = node -> children[c - 'a']; 26 | } 27 | node -> word = true; 28 | } 29 | 30 | /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 31 | bool search(string word) { 32 | return search(word.c_str(), root); 33 | } 34 | private: 35 | TrieNode* root = new TrieNode(); 36 | 37 | bool search(const char* word, TrieNode* node) { 38 | for (int i = 0; word[i] && node; i++) { 39 | if (word[i] != '.') { 40 | node = node -> children[word[i] - 'a']; 41 | } else { 42 | TrieNode* tmp = node; 43 | for (int j = 0; j < 26; j++) { 44 | node = tmp -> children[j]; 45 | if (search(word + i + 1, node)) { 46 | return true; 47 | } 48 | } 49 | } 50 | } 51 | return node && node -> word; 52 | } 53 | }; 54 | 55 | /** 56 | * Your WordDictionary object will be instantiated and called as such: 57 | * WordDictionary* obj = new WordDictionary(); 58 | * obj->addWord(word); 59 | * bool param_2 = obj->search(word); 60 | */ -------------------------------------------------------------------------------- /DAY18/Print all possible combinations of r elements in a given array of size n.CPP: -------------------------------------------------------------------------------- 1 | // C++ program to print all combination 2 | // of size r in an array of size n 3 | #include 4 | using namespace std; 5 | 6 | void combinationUtil(int arr[], int data[], 7 | int start, int end, 8 | int index, int r); 9 | 10 | // The main function that prints 11 | // all combinations of size r 12 | // in arr[] of size n. This function 13 | // mainly uses combinationUtil() 14 | void printCombination(int arr[], int n, int r) 15 | { 16 | // A temporary array to store 17 | // all combination one by one 18 | int data[r]; 19 | 20 | // Print all combination using 21 | // temporary array 'data[]' 22 | combinationUtil(arr, data, 0, n-1, 0, r); 23 | } 24 | 25 | /* arr[] ---> Input Array 26 | data[] ---> Temporary array to 27 | store current combination 28 | start & end ---> Starting and 29 | Ending indexes in arr[] 30 | index ---> Current index in data[] 31 | r ---> Size of a combination to be printed */ 32 | void combinationUtil(int arr[], int data[], 33 | int start, int end, 34 | int index, int r) 35 | { 36 | // Current combination is ready 37 | // to be printed, print it 38 | if (index == r) 39 | { 40 | for (int j = 0; j < r; j++) 41 | cout << data[j] << " "; 42 | cout << endl; 43 | return; 44 | } 45 | 46 | // replace index with all possible 47 | // elements. The condition "end-i+1 >= r-index" 48 | // makes sure that including one element 49 | // at index will make a combination with 50 | // remaining elements at remaining positions 51 | for (int i = start; i <= end && 52 | end - i + 1 >= r - index; i++) 53 | { 54 | data[index] = arr[i]; 55 | combinationUtil(arr, data, i+1, 56 | end, index+1, r); 57 | } 58 | } 59 | 60 | // Driver code 61 | int main() 62 | { 63 | int arr[] = {1, 2, 3, 4, 5}; 64 | int r = 3; 65 | int n = sizeof(arr)/sizeof(arr[0]); 66 | printCombination(arr, n, r); 67 | } 68 | 69 | 70 | -------------------------------------------------------------------------------- /DAY45/Find the City With the Smallest Number of Neighbors at a Threshold Distance.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> adj[105]; 4 | vector> ans; 5 | 6 | bool static cmp(const pair p1 ,const pair p2) 7 | { 8 | if(p1.first != p2.first) 9 | return p1.first < p2.first; 10 | 11 | return p1.second > p2.second; 12 | } 13 | 14 | void dijkstra(int src, int n, int distanceThreshold) 15 | { 16 | priority_queue, vector>, greater> > pq; 17 | vector distance(n + 1, INT_MAX); 18 | 19 | distance[src] = 0; 20 | pq.push({0,src}); 21 | 22 | while(! pq.empty()) 23 | { 24 | int prev = pq.top().second; 25 | int prevDist = pq.top().first; 26 | pq.pop(); 27 | 28 | for(auto it : adj[prev]) 29 | { 30 | int next = it.first; 31 | int nextDist = it.second; 32 | if(distance[next] > distance[prev] + nextDist) 33 | { 34 | distance[next] = distance[prev] + nextDist; 35 | pq.push({distance[next], next}); 36 | } 37 | } 38 | } 39 | 40 | int cnt = 0; 41 | for(int i=0;i>& edges, int distanceThreshold) { 53 | 54 | for(int i=0;i nextSmallerElement(int *arr, int n){ 4 | stack s; 5 | s.push(-1); 6 | vector ans(n); 7 | for(int i=n-1;i>=0;i--){ 8 | int curr=arr[i]; 9 | while( s.top()!=-1 && arr[s.top()]>=curr){ 10 | s.pop(); 11 | } 12 | ans[i]=s.top(); 13 | s.push(i); 14 | } 15 | return ans; 16 | } 17 | vector prevSmallerElement(int *arr, int n){ 18 | stack s; 19 | s.push(-1); 20 | vector ans(n); 21 | for(int i=0;i=curr){ 24 | s.pop(); 25 | } 26 | ans[i]=s.top(); 27 | s.push(i); 28 | } 29 | return ans; 30 | } 31 | int largestRectangleArea(int* heights,int n) { 32 | // int n=heights.size(); 33 | vector next(n); 34 | next=nextSmallerElement(heights,n); 35 | 36 | vector prev(n); 37 | prev=prevSmallerElement(heights,n); 38 | int area=INT_MIN; 39 | for(int i=0;i adj[], vector&vis, stack&s ) 10 | { 11 | vis[i]=1; 12 | 13 | for(auto it:adj[i]) 14 | { 15 | if(vis[it]==0) 16 | { 17 | tp(it,adj,vis,s); 18 | } 19 | 20 | 21 | } 22 | s.push(i); 23 | //return; 24 | } 25 | void dfs(int i, vector&visited, vector nadj[]) 26 | { 27 | visited[i]=1; 28 | 29 | for(auto it: nadj[i]) 30 | { 31 | if(visited[it]==0) 32 | { 33 | dfs(it,visited, nadj); 34 | } 35 | } 36 | } 37 | int kosaraju(int V, vector adj[]) 38 | { 39 | stacks; 40 | s.push(0); 41 | //vectortopo; 42 | vectorvis(V,0); 43 | 44 | 45 | for(int i=0;i nadj[V]; 54 | 55 | for(int i=0;ivisited(V,0); 63 | int count=0; 64 | while(!s.empty()) 65 | { 66 | int i=s.top(); 67 | s.pop(); 68 | if(visited[i]==0) 69 | { 70 | dfs(i, visited, nadj); 71 | count++; 72 | } 73 | } 74 | return count; 75 | } 76 | }; --------------------------------------------------------------------------------