├── Array ├── Rotate Array.cpp ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves.cpp ├── Find Minimum in Rotated Sorted Array II.cpp ├── 406. Queue Reconstruction by Height.cpp ├── 1358. Number of Substrings Containing All Three Characters ├── 487. Max Consecutive Ones II.cpp ├── 278. First Bad Version.cpp ├── 986. Interval List Intersections.cpp ├── 1248. Count Number of Nice Subarrays.cpp ├── 169. Majority Element.cpp ├── 1540. Can Convert String in K Moves.cpp ├── 1524. Number of Sub-arrays With Odd Sum.cpp ├── Check If Array Pairs Are Divisible by k.cpp ├── 340. Longest Substring with At Most K Distinct Characters.cpp ├── 135. Candy.cpp ├── Contiguous Array.cpp ├── 1537. Get the Maximum Score,cpp ├── 1498. Number of Subsequences That Satisfy the Given Sum Condition.cpp ├── 1423. Maximum Points You Can Obtain from Cards.cpp ├── 1004. Max Consecutive Ones III.cpp ├── 424. Longest Repeating Character Replacement.cpp ├── 1010. Pairs of Songs With Total Durations Divisible by 60.cpp ├── 1267. Count Servers that Communicate.cpp ├── 1552. Magnetic Force Between Two Balls.cpp ├── 1504. Count Submatrices With All Ones.cpp ├── 163. Missing Ranges.cpp ├── 324. Wiggle Sort II.cpp ├── Sort Array By Parity.cpp ├── 5455. Minimum Number of Days to Make m Bouquets.cpp ├── 31. Next Permutation.cpp ├── 259. 3Sum Smaller.cpp ├── 4.MedianOfTwoSortedArrays.cpp ├── 1536. Minimum Swaps to Arrange a Binary Grid.cpp ├── 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum.cpp ├── 1229. Meeting Scheduler.cpp ├── 252. Meeting Rooms.cpp ├── 41. First Missing Positive.cpp ├── 42. Trapping Rain Water.cpp ├── 88. Merge Sorted Array.cpp ├── 93. Restore IP Addresses.cpp ├── 238. Product of Array Except Self.cpp └── 11. Container With Most Water.cpp ├── Bit Manipulation ├── 260. Single Number III.cpp ├── 137. Single Number II.cpp ├── 1310. XOR Queries of a Subarray.cpp ├── 1290. Convert Binary Number in a Linked List to Integer.cpp ├── 201. Bitwise AND of Numbers Range.cpp └── 1342. Number of Steps to Reduce a Number to Zero.cpp ├── Dynamic Programming ├── 647. Palindromic Substrings.cpp ├── 279. Perfect Squares2.cpp ├── 1510. Stone Game IV.cpp ├── 279. Perfect Squares.cpp ├── 256. Paint House.cpp ├── 91. Decode Ways.cpp ├── 1027. Longest Arithmetic Sequence.cpp ├── 368. Largest Divisible Subset.cpp ├── 1035. Uncrossed Lines.cpp ├── 1406. Stone Game III.cpp ├── 72. Edit Distance.cpp ├── 1547. Minimum Cost to Cut a Stick.cpp ├── 53. Maximum Subarray.cpp ├── 778. Swim in Rising Water.cpp ├── 1458. Max Dot Product of Two Subsequences.cpp ├── 1314. Matrix Block Sum.cpp ├── 161. One Edit Distance.cpp ├── 1463. Cherry Pickup II.cpp ├── 121. Best Time to Buy and Sell Stock.cpp ├── 84. Largest Rectangle in Histogram.cpp ├── 10. Regular Expression Matching.cpp ├── 62. Unique Paths.cpp ├── 1092. Shortest Common Supersequence .cpp ├── 44. Wildcard Matching.cpp ├── 1473. Paint House III.cpp ├── 122. Best Time to Buy and Sell Stock II.cpp ├── 718. Maximum Length of Repeated Subarray.cpp ├── 746. Min Cost Climbing Stairs.cpp ├── 935. Knight Dialer.cpp ├── 45. Jump Game II.cpp ├── 85. Maximal Rectangle.cpp ├── 343. Integer Break.cpp ├── 55. Jump Game.cpp └── 1143. Longest Common Subsequence.cpp ├── Strings ├── 686. Repeated String Match.cpp ├── 791. Custom Sort String.cpp ├── 541. Reverse String II.cpp ├── 953. Verifying an Alien Dictionary.cpp ├── 1100. Find K-Length Substrings With No Repeated Characters.cpp ├── Count and Say.cpp ├── 1081. Smallest Subsequence of Distinct Characters.cpp ├── 1071. Greatest Common Divisor of Strings.cpp ├── 1297. Maximum Number of Occurrences of a Substring.cpp ├── 567. Permutation in String.cpp ├── 5. Longest Palindromic Substring,cpp. Longest Palindromic Substring.cpp ├── 819. Most Common Word.cpp ├── 273. Integer to English Words.cpp ├── 966. Vowel Spellchecker.cpp ├── 12. Integer to Roman.cpp ├── 14. Longest Common Prefix.cpp ├── 415. Add Strings.cpp ├── 3. Longest Substring Without Repeating Characters.cpp ├── 22. Generate Parentheses.cpp ├── 468. Validate IP Address.cpp ├── 6. ZigZag Conversion.cpp └── 1249. Minimum Remove to Make Valid Parentheses.cpp ├── 1503. Last Moment Before All Ants Fall Out of a Plank.cpp ├── Hash Table ├── 771. Jewels and Stones.cpp ├── 575. Distribute Candies.cpp ├── 1488. Avoid Flood in The City.cpp ├── 208. Implement Trie (Prefix Tree).cpp ├── 244. Shortest Word Distance II.cpp ├── 13. Roman to Integer.cpp ├── Insert Delete GetRandom O(1).cpp ├── 1128. Number of Equivalent Domino Pairs.cpp ├── 560. Subarray Sum Equals K.cpp ├── 325. Maximum Size Subarray Sum Equals k.cpp ├── 763. Partition Labels.cpp └── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.cpp ├── TREES ├── 1448. Count Good Nodes in Binary Tree.cpp ├── 687. Longest Univalue Path.cpp ├── Inorder Traversal iterative.cpp ├── Print all the ancestors in a binary tree.cpp ├── 1008. Construct Binary Search Tree from Preorder Traversal.cpp ├── 572. Subtree of Another Tree.cpp ├── 979. Distribute Coins in Binary Tree.cpp ├── 1522. Diameter of N-Ary Tree.cpp ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── 108. Convert Sorted Array to Binary Search Tree.cpp ├── 1519. Number of Nodes in the Sub-Tree With the Same Label.cpp ├── 549. Binary Tree Longest Consecutive Sequence II.cpp ├── Binary Tree Upside Down.cpp ├── Vertical Order Traversal of a Binary Tree.cpp ├── Path Sum III.cpp ├── 1273. Delete Tree Nodes.cpp ├── 1022. Sum of Root To Leaf Binary Numbers.cpp ├── 30DayLeetCodeChallenge 30thq.cpp ├── 366. Find Leaves of Binary Tree.cpp ├── 545. Boundary of Binary Tree.cpp ├── 285. Inorder Successor in BST.cpp ├── 993. Cousins in Binary Tree.cpp ├── 1530. Number of Good Leaf Nodes Pairs.cpp └── class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { unordered_map map; map[root]=NULL; queue q1; q1.push(root); while(!map.count(p)||!map.count(q)) { TreeNode* t=q1.front(); q1.pop(); if(t) { map[t->left]=t; map[t->right]=t; q1.push(t->left); q1.push(t->right); } } unordered_set s; while(p!=NULL) { s.insert(p); p=map[p]; } while(s.find(q)==s.end()) q=map[q]; return q; } }; ├── Stacks ├── 503. Next Greater Element II.cpp ├── 32. Longest Valid Parentheses.cpp ├── 1541. Minimum Insertions to Balance a Parentheses String.cpp └── 394. Decode String.cpp ├── HEAP ├── 1499. Max Value of Equation.cpp ├── 378. Kth Smallest Element in a Sorted Matrix.cpp ├── 778. Swim in Rising Water1.cpp ├── 692. Top K Frequent Words.cpp ├── 703. Kth Largest Element in a Stream.cpp └── 253. Meeting Rooms II.cpp ├── Linked Lists ├── 138. Copy List with Random Pointer.cpp ├── 328. Odd Even Linked List.cpp ├── 206. Reverse Linked List.cpp ├── 24. Swap Nodes in Pairs.cpp └── 143. Reorder List.cpp ├── Graph ├── KahnsAlgorithm.cpp ├── 210. Course Schedule II.cpp ├── 1101. The Earliest Moment When Everyone Become Friends.cpp ├── 841. Keys and Rooms.cpp ├── 1462. Course Schedule IV2.cpp ├── 133. Clone Graph.pp.cpp ├── 1494. Parallel Courses II.cpp ├── 1462. Course Schedule IV.cpp ├── 1061. Lexicographically Smallest Equivalent String.cpp ├── 1466. Reorder Routes to Make All Paths Lead to the City Zero.cpp ├── 1102. Path With Maximum Minimum Value.cpp ├── 1129. Shortest Path with Alternating Colors.cpp ├── 1319. Number of Operations to Make Network Connected.cpp ├── 1443. Minimum Time to Collect All Apples in a Tree.cpp └── 329. Longest Increasing Path in a Matrix.cpp ├── DFS ├── All Paths From Source to destination.cpp ├── Possible Bipartition.cpp ├── 51. N-Queens.cpp ├── 1568. Minimum Number of Days to Disconnect Island.cpp ├── 323. Number of Connected Components in an Undirected Graph.cpp └── 339. Nested List Weight Sum.cpp ├── BFS ├── 1553. Minimum Number of Days to Eat N Oranges.cpp ├── 1514. Path with Maximum Probability.cpp ├── 1197. Minimum Knight Moves.cpp ├── Word Ladder II.cpp ├── 773. Sliding Puzzle.cpp ├── 364. Nested List Weight Sum II.cpp ├── 433. Minimum Genetic Mutation.cpp ├── 127. Word Ladder.cpp ├── 1306. Jump Game III.cpp └── 130. Surrounded Regions.cpp ├── Design ├── Shuffle an Array.cpp ├── 146. LRU Cache.cpp ├── 348. Design Tic-Tac-Toe.cpp └── 716. Max Stack.cpp ├── MATH ├── 9. Palindrome Number.cpp ├── 258.AddDigits.cpp ├── 836. Rectangle Overlap.cpp ├── 202.Happy Number.cpp ├── 263.Ugly Number.cpp └── 976. Largest Perimeter Triangle. Largest Perimeter Triangle.cpp └── TRIE └── 1065. Index Pairs of a String.cpp /Array/Rotate Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n=nums.size(); 5 | k=k%n; 6 | reverse(nums.begin(),nums.begin()+n-k); 7 | reverse(nums.begin()+n-k,nums.end()); 8 | reverse(nums.begin(),nums.end()); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Bit Manipulation/260. Single Number III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | int b=0; 5 | for(int i:nums)b^=i; 6 | int diff=b&(-b); 7 | int x=0; 8 | for(int i:nums)if((i&diff)!=0)x^=i; 9 | return {x,b^x}; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Bit Manipulation/137. Single Number II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int seenonce=0,seentwice=0; 5 | for(int &x:nums) 6 | { 7 | seenonce=~(seentwice)&(seenonce^x); 8 | seentwice=~(seenonce)&(seentwice^x); 9 | } 10 | return seenonce; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic Programming/647. Palindromic Substrings.cpp: -------------------------------------------------------------------------------- 1 | int countSubstrings(string s) { 2 | int ans=0; 3 | int n=s.size(); 4 | for(int i=0;i=0 && i+j=0 && i+j& nums) { 4 | if(nums.size()<=4)return 0; 5 | sort(nums.begin(),nums.end()); 6 | int n=nums.size(); 7 | return min({nums[n-4]-nums[0],nums[n-1]-nums[3],nums[n-2]-nums[2],nums[n-3]-nums[1]}); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Dynamic Programming/279. Perfect Squares2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | if(n<0)return 0; 5 | vector dp(n+1,INT_MAX); 6 | dp[0]=0; 7 | for(int i=1;i<=n;i++) 8 | { 9 | for(int j=1;j*j<=i;j++) 10 | dp[i]=min(dp[i],dp[i-j*j]+1); 11 | } 12 | return dp[n]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/Find Minimum in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int l=0,r=nums.size()-1; 5 | while(lnums[r])l=m+1; 10 | else l++; 11 | } 12 | return nums[l]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /1503. Last Moment Before All Ants Fall Out of a Plank.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getLastMoment(int n, vector& left, vector& right) { 4 | int maxL = 0, minR = n; 5 | if (!left.empty()) maxL = *max_element (left.begin(), left.end()); 6 | if (!right.empty()) minR = *min_element (right.begin(), right.end()); 7 | return max (maxL, n - minR); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Bit Manipulation/1310. XOR Queries of a Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector xorQueries(vector& arr, vector>& queries) { 4 | for(int i=1;i ans; 7 | for(auto &x:queries) 8 | ans.push_back(x[0]==0?arr[x[1]]:(arr[x[1]]^arr[x[0]-1])); 9 | return ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Hash Table/771. Jewels and Stones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We use a hashset to solve it 3 | Space complexity = O(n) 4 | Time complexity = O(n) 5 | */ 6 | int numJewelsInStones(string J, string S) { 7 | int ans=0; 8 | unordered_set s(J.begin(),J.end()); 9 | for(int i=0;i> reconstructQueue(vector>& p) { 2 | sort(p.begin(),p.end(),[](vector &a,vector &b) 3 | { 4 | return (a[0]>b[0])||(a[0]==b[0] && a[1]> ans; 7 | for(auto &x:p) 8 | ans.insert(ans.begin()+x[1],x); 9 | return ans; 10 | } 11 | -------------------------------------------------------------------------------- /Array/1358. Number of Substrings Containing All Three Characters: -------------------------------------------------------------------------------- 1 | int numberOfSubstrings(string s) { 2 | int count[3]={0,0,0}, j=0,ans=0; 3 | for(int i=0;ival>=m)ans++; 6 | solve(root->left,max(root->val,m)); 7 | solve(root->right,max(root->val,m)); 8 | } 9 | int goodNodes(TreeNode* root) { 10 | if(!root)return ans; 11 | solve(root,INT_MIN); 12 | return ans; 13 | } 14 | -------------------------------------------------------------------------------- /Strings/791. Custom Sort String.cpp: -------------------------------------------------------------------------------- 1 | We use STL to custom sort the string. 2 | string customSortString(string S, string T) { 3 | unordered_map map; 4 | for(int i=0;i& nums) { 2 | int ans = 0, count = 0, index = -1; 3 | for(int i = 0;i< nums.size(); i++){ 4 | if(nums[i] == 1){ 5 | count++; 6 | }else{ 7 | count = i - index; 8 | index = i; 9 | } 10 | ans = max(ans,count); 11 | } 12 | return ans; 13 | } 14 | -------------------------------------------------------------------------------- /Array/278. First Bad Version.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Just do a binary search fromt 1 to n 3 | */ 4 | int firstBadVersion(int n) { 5 | int l=1,r=n,ans; 6 | while(l<=r) 7 | { 8 | int m=l+(r-l)/2; 9 | if(isBadVersion(m)) 10 | { 11 | ans=m; 12 | r=m-1; 13 | } 14 | else 15 | l=m+1; 16 | } 17 | return ans; 18 | } -------------------------------------------------------------------------------- /Array/986. Interval List Intersections.cpp: -------------------------------------------------------------------------------- 1 | vector> intervalIntersection(vector>& A, vector>& B) { 2 | vector> ans; 3 | for(int i=0,j=0;i dp(n+1,0); 5 | for(int i=1;i<=n;i++) 6 | { 7 | for(int j=1;j*j<=i;j++) 8 | { 9 | if(!dp[i-j*j]) 10 | { 11 | dp[i]=true; 12 | break; 13 | } 14 | } 15 | } 16 | return dp[n]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Dynamic Programming/279. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | there are many approaches to solve this problem. 3 | I will be using dp to solve this. 4 | */ 5 | int numSquares(int n) { 6 | vector dp(n+1,0); 7 | for(int i=1;i<=n;i++) 8 | { 9 | dp[i]=i; 10 | for(int j=1;j<=sqrt(i);j++) 11 | { 12 | dp[i]=min(dp[i],1+dp[i-j*j]); 13 | } 14 | } 15 | return dp[n]; 16 | } 17 | -------------------------------------------------------------------------------- /Hash Table/575. Distribute Candies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The algorithm to solve this pretty simple: 3 | return the minimum of the diffrent types of candies and candies.size()/2 4 | */ 5 | int distributeCandies(vector& candies) { 6 | unordered_set s; 7 | for(int i=0;icandies.size()/2)return candies.size()/2; 10 | else 11 | return s.size(); 12 | } 13 | -------------------------------------------------------------------------------- /Array/1248. Count Number of Nice Subarrays.cpp: -------------------------------------------------------------------------------- 1 | int numberOfSubarrays(vector& nums, int k) { 2 | for(int &x:nums) 3 | x=x%2; 4 | unordered_map map; 5 | map[0]=1; 6 | int sum=0,ans=0; 7 | for(int i=0;i& nums) { 4 | int major=nums[0],count=1; 5 | for(int i=1;i>& costs) { 2 | if(costs.size()==0)return 0; 3 | for(int i=1;i v(27,0); 6 | for(int i=0;i<(int)s.size();i++) 7 | { 8 | if(s[i]==t[i])continue; 9 | int x=t[i]-s[i]; 10 | if(x<0)x+=26; 11 | if(x>k||x+v[x]>k)return false; 12 | v[x]+=26; 13 | } 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/91. Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | vector dp(s.length()+1,0); 5 | dp[0]=1; 6 | dp[1]=(s[0]!='0')?1:0; 7 | for(int i=2;i<=s.length();i++) 8 | { 9 | int one=s[i-1]-'0'; 10 | int two=stoi(s.substr(i-2,2)); 11 | if(one>0)dp[i]=dp[i-1]; 12 | if(two>=10 && two<=26)dp[i]+=dp[i-2]; 13 | } 14 | return dp[s.length()]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /TREES/687. Longest Univalue Path.cpp: -------------------------------------------------------------------------------- 1 | int helper(TreeNode* root,int parent) 2 | { 3 | if(!root||root->val!=parent)return 0; 4 | return max(helper(root->left,parent),helper(root->right,parent))+1; 5 | } 6 | int longestUnivaluePath(TreeNode* root) { 7 | if(!root)return 0; 8 | int childmax=max(longestUnivaluePath(root->left),longestUnivaluePath(root->right)); 9 | return max(childmax,helper(root->left,root->val)+helper(root->right,root->val)); 10 | } -------------------------------------------------------------------------------- /Array/1524. Number of Sub-arrays With Odd Sum.cpp: -------------------------------------------------------------------------------- 1 | int c1 = 0, c2 = 1, n = arr.length; 2 | int currSum = 0; 3 | long ans = 0; 4 | int mod = (int)Math.pow(10, 9) + 7; 5 | for(int i = 0; i < n; i++) { 6 | currSum += arr[i]; 7 | if(currSum % 2 == 0) { 8 | ans = (ans + c1) % mod; 9 | c2++; 10 | } else { 11 | ans = (ans + c2) % mod; 12 | c1++; 13 | } 14 | } 15 | return (int)ans; 16 | -------------------------------------------------------------------------------- /Array/Check If Array Pairs Are Divisible by k.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/contest/weekly-contest-195/problems/check-if-array-pairs-are-divisible-by-k/ 3 | */ 4 | 5 | class Solution { 6 | public: 7 | bool canArrange(vector& arr, int k) { 8 | vector a(k); 9 | for(int num:arr) 10 | { 11 | a[(num%k+k)%k]++; 12 | } 13 | for(int i=1;i map; 4 | for(int i=0;ik) 8 | { 9 | map[s[j]]--; 10 | if(map[s[j]]==0)map.erase(s[j]); 11 | j++; 12 | } 13 | ans=max(ans,i-j+1); 14 | } 15 | return ans; 16 | } 17 | -------------------------------------------------------------------------------- /Dynamic Programming/1027. Longest Arithmetic Sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestArithSeqLength(vector& A) { 4 | unordered_map> dp; 5 | int ans=1; 6 | for(int i=0;i inorderTraversal(TreeNode* root) { 2 | if(!root)return {}; 3 | vector ans; 4 | stack st; 5 | while(!st.empty()||root) 6 | { 7 | while(root) 8 | { 9 | st.push(root); 10 | root=root->left; 11 | } 12 | root=st.top(); 13 | st.pop(); 14 | ans.push_back(root->val); 15 | root=root->right; 16 | } 17 | return ans; 18 | } 19 | -------------------------------------------------------------------------------- /Strings/953. Verifying an Alien Dictionary.cpp: -------------------------------------------------------------------------------- 1 | bool isAlienSorted(vector& words, string order) { 2 | unordered_map map; 3 | for(int i=0;i ans; 6 | for(int i=0;i ch(26,0); 4 | for(int i=0;i=k) 8 | { 9 | ch[s[i-k]-'a']--; 10 | } 11 | int count=0; 12 | for(int j=0;j<26;j++)count+=ch[j]==1?1:0; 13 | if(count==k)ans++; 14 | } 15 | 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /Stacks/503. Next Greater Element II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | int n=nums.size(); 5 | if(n==0)return {}; 6 | vector ans(n,-1); 7 | stack st; 8 | for(int i=0;i<2*n;i++) 9 | { 10 | while(!st.empty() && nums[st.top()]& ratings) { 4 | int n=ratings.size(); 5 | vector t(n,1); 6 | for(int i=1;iratings[i-1]) 9 | t[i]=t[i-1]+1; 10 | } 11 | for(int i=n-1;i>0;i--) 12 | { 13 | if(ratings[i-1]>ratings[i]) 14 | t[i-1]=max(t[i-1],t[i]+1); 15 | } 16 | int ans=0; 17 | for(int i=0;i st; 5 | st.push(-1); 6 | int ans=0; 7 | for(int i=0;i<(int)s.size();i++) 8 | { 9 | if(s[i]=='(')st.push(i); 10 | else 11 | { 12 | st.pop(); 13 | if(st.empty()) 14 | st.push(i); 15 | else 16 | ans=max(ans,i-st.top()); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /HEAP/1499. Max Value of Equation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxValueOfEquation(vector>& points, int k) { 4 | using pii=pair; 5 | priority_queue pq; 6 | int ans=INT_MIN; 7 | for(int i=0;ik))pq.pop(); 10 | if(!pq.empty())ans=max(ans,points[i][1]+points[i][0]+pq.top().first); 11 | pq.push({points[i][1]-points[i][0],points[i][0]}); 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /TREES/Print all the ancestors in a binary tree.cpp: -------------------------------------------------------------------------------- 1 | bool printAncestors(struct node *root, int target) 2 | { 3 | /* base cases */ 4 | if (root == NULL) 5 | return false; 6 | 7 | if (root->data == target) 8 | return true; 9 | 10 | /* If target is present in either left or right subtree of this node, 11 | then print this node */ 12 | if ( printAncestors(root->left, target) || 13 | printAncestors(root->right, target) ) 14 | { 15 | cout << root->data << " "; 16 | return true; 17 | } 18 | 19 | /* Else return false */ 20 | return false; 21 | } 22 | -------------------------------------------------------------------------------- /Array/Contiguous Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector& nums) { 4 | if(nums.size()==0)return 0; 5 | unordered_map map; 6 | int sum=0,ans=0; 7 | for(int i=0;i 0 -> 1 4 | let ans = 0 5 | we right shift ans and add the head->val 6 | 00 + 1 =1 only 7 | 10 + 0 =10 8 | 100 + 1 =101 =ans =5 9 | */ 10 | 11 | int getDecimalValue(ListNode* head) { 12 | int ans=0; 13 | while(head) 14 | { 15 | ans<<=1; 16 | ans|=head->val; 17 | head=head->next; 18 | } 19 | return ans; 20 | } -------------------------------------------------------------------------------- /Dynamic Programming/368. Largest Divisible Subset.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector largestDivisibleSubset(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | vector> t(nums.size()); 6 | vector ans; 7 | for(int i=0;it[i].size()) 12 | t[i]=t[j]; 13 | } 14 | t[i].push_back(nums[i]); 15 | if(ans.size()val>x)root->left=build(root->left,x); 12 | if(root->valright=build(root->right,x); 13 | return root; 14 | } 15 | TreeNode* bstFromPreorder(vector& preorder) { 16 | TreeNode* root=NULL; 17 | for(int &x:preorder) 18 | { 19 | root=build(root,x); 20 | } 21 | return root; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Linked Lists/138. Copy List with Random Pointer.cpp: -------------------------------------------------------------------------------- 1 | Node* copyRandomList(Node* head) { 2 | if(head==NULL)return NULL; 3 | unordered_map map; 4 | Node* result=new Node(head->val); 5 | map[head]=result; 6 | Node* p1=head->next,*p2=result; 7 | while(p1) 8 | { 9 | p2->next=new Node(p1->val); 10 | p2=p2->next; 11 | map[p1]=p2; 12 | p1=p1->next; 13 | } 14 | p1=head,p2=result; 15 | while(p1) 16 | { 17 | p2->random=map[p1->random]; 18 | p1=p1->next; 19 | p2=p2->next; 20 | } 21 | return result; 22 | -------------------------------------------------------------------------------- /Strings/1081. Smallest Subsequence of Distinct Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string smallestSubsequence(string text) { 4 | string ans; 5 | int last[26]={},seen[26]={}; 6 | for(int i=0;itext[i] && i& nums1, vector& nums2) { 4 | long long x=0,y=0,i=0,j=0,prevx=0,prevy=0,mod=1e9+7; 5 | while(inums2[j])y+=nums2[j++]; 9 | else 10 | { 11 | x=y=max(prevx+nums1[i++],prevy+nums2[j++]); 12 | } 13 | prevx=x; 14 | prevy=y; 15 | } 16 | while(i s1,s2; 7 | for(char &ch:str1) 8 | { 9 | if(s1.find(ch)==s1.end()) 10 | s1.insert(ch); 11 | } 12 | for(char &ch:str2) 13 | s2.insert(ch); 14 | if(s1.size()!=s2.size())return ""; 15 | return str1.substr(0, gcd(str1.size(), str2.size())); 16 | } -------------------------------------------------------------------------------- /Graph/KahnsAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | void toposort() 2 | { 3 | vector indegree(n,0); 4 | for(int i=0;i q; 10 | for(int i=0;i top_order; 16 | while(!q.empty()) 17 | { 18 | int t=q.front(); 19 | q.pop(); 20 | top_order.push_back(t); 21 | for(auto &x:adj[t]) 22 | { 23 | if(--indegree[x]==0)q.push(x); 24 | } 25 | } 26 | if(count==n)cout<<"NO SORT POSSIBLE"<& arr, int target) { 4 | vector precomp = {0, 1}; 5 | for (auto i = 0; i < arr.size(); ++i) { 6 | precomp.push_back((precomp.back() << 1) % 1000000007); 7 | } 8 | sort(arr.begin(),arr.end()); 9 | int l=0,r=arr.size()-1; 10 | int ans=0; 11 | while(l<=r) 12 | { 13 | if(arr[l]+arr[r]>target)r--; 14 | else 15 | { 16 | ans = (ans + precomp[r - l + 1]) % 1000000007; 17 | l++; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /DFS/All Paths From Source to destination.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | void helper(vector>& graph,int src,int dst,vector path) 5 | { 6 | path.push_back(src); 7 | if(src==dst) 8 | { 9 | ans.push_back(path); 10 | return; 11 | } 12 | for(auto x:graph[src]) 13 | { 14 | helper(graph,x,dst,path); 15 | } 16 | } 17 | vector> allPathsSourceTarget(vector>& graph) { 18 | int n=graph.size(); 19 | if(n==0)return ans; 20 | vector path; 21 | helper(graph,0,n-1,path); 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Dynamic Programming/1035. Uncrossed Lines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUncrossedLines(vector& A, vector& B) { 4 | int ans=0; 5 | int n=A.size(),m=B.size(); 6 | vector> dp(n+1,vector(m+1,0)); 7 | for(int i=1;i<=n;i++) 8 | { 9 | for(int j=1;j<=m;j++) 10 | { 11 | if(A[i-1]==B[j-1]) 12 | { 13 | dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1); 14 | } 15 | else 16 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 17 | ans=max(ans,dp[i][j]); 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Strings/1297. Maximum Number of Occurrences of a Substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxFreq(string s, int maxLetters, int minSize, int maxSize) { 4 | int ans=0,start=0; 5 | unordered_map map; 6 | unordered_map map1; 7 | for(int i=0;iminSize) 11 | { 12 | if(--map[s[start]]==0)map.erase(s[start]); 13 | start++; 14 | } 15 | if(i-start+1==minSize && map.size()<=maxLetters) 16 | ans=max(ans,++map1[s.substr(start,i-start+1)]); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/1406. Stone Game III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[50001]; 4 | int help(vector& s,int i) 5 | { 6 | if(i>=s.size())return 0; 7 | if(dp[i]!=-1)return dp[i]; 8 | int ans=INT_MIN; 9 | ans=max(ans,s[i]-help(s,i+1)); 10 | if(i+1& s) { 15 | for(int i=0;i0)return "Alice"; 18 | else if(ans==0)return "Tie"; 19 | return "Bob"; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/72. Edit Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | int n=word1.size(),m=word2.size(); 5 | vector> dp(n+1,vector(m+1,0)); 6 | dp[0][0]=0; 7 | for(int i=1;i<=n;i++)dp[i][0]=i; 8 | for(int i=1;i<=m;i++)dp[0][i]=i; 9 | for(int i=1;i<=n;i++) 10 | { 11 | for(int j=1;j<=m;j++) 12 | { 13 | if(word1[i-1]==word2[j-1]) 14 | dp[i][j]=dp[i-1][j-1]; 15 | else 16 | dp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1; 17 | } 18 | } 19 | return dp[n][m]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/1547. Minimum Cost to Cut a Stick.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[102][102]; 4 | int helper(vector& cuts,int l,int r) 5 | { 6 | if(l+1==r)return 0; 7 | if(dp[l][r]!=-1)return dp[l][r]; 8 | dp[l][r]=INT_MAX; 9 | for(int i=l+1;i& cuts) { 16 | cuts.push_back(0); 17 | cuts.push_back(n); 18 | sort(cuts.begin(),cuts.end()); 19 | memset(dp,-1,sizeof(dp)); 20 | return helper(cuts,0,cuts.size()-1); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Array/1423. Maximum Points You Can Obtain from Cards.cpp: -------------------------------------------------------------------------------- 1 | Source:- https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/597883/Javascript-and-C%2B%2B-solutions 2 | int maxScore(vector& cardPoints, int k) { 3 | int n=cardPoints.size(); 4 | int sum=0,ans=0; 5 | deque dq; 6 | for(int i=n-k;i& nums) { 8 | if(nums.size()==0)return 0; 9 | int max_till_now=nums[0],max_ans=nums[0]; 10 | for(int i=1;i> dir={{1,0},{0,1},{0,-1},{-1,0}}; 5 | void dfs(vector>& grid,int i,int j,int curr) 6 | { 7 | if(i<0||j<0||i>=grid.size()||j>=grid.size()||max(curr,grid[i][j])>=dp[i][j])return; 8 | dp[i][j]=max(curr,grid[i][j]); 9 | for(auto &x:dir) 10 | dfs(grid,i+x[0],j+x[1],dp[i][j]); 11 | } 12 | int swimInWater(vector>& grid) { 13 | int n=grid.size(); 14 | for(int i=0;i& A, int k) { 12 | int l=0,r=0,z=0,ans=0; 13 | while(rk) 17 | { 18 | if(A[l++]==0)z--; 19 | } 20 | ans=max(r-l+1,ans); 21 | r++; 22 | } 23 | return ans; 24 | } -------------------------------------------------------------------------------- /Strings/567. Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | I used two vectors of size 26. 3 | The first vector lets say map1 stores the frequency of characters in s1 4 | The second vector lets say map2 stores the frequency of characters in s2 as soon as i>=s1.size() we decrement the frequency fo the character presnt in i-s1.size() location 5 | */ 6 | bool checkInclusion(string s1, string s2) { 7 | if(s2.size() map1(26),map2(26); 10 | for(char &ch:s1)map1[ch-'a']++; 11 | for(int i=0;i=l)map2[s2[i-l]-'a']--; 15 | if(map1==map2)return true; 16 | } 17 | return false; 18 | } -------------------------------------------------------------------------------- /BFS/1553. Minimum Number of Days to Eat N Oranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDays(int n) { 4 | if(n<3)return n; 5 | unordered_set s; 6 | queue q; 7 | q.push(n); 8 | int ans=0; 9 | while(!q.empty()) 10 | { 11 | int size=q.size(); 12 | for(int i=0;i st; 6 | for(int i=0;i& nums1, vector& nums2) { 2 | int n=nums1.size(),m=nums2.size(); 3 | vector> dp(n,vector(m)); 4 | for(int i=0;i0)dp[i][j]=max(dp[i][j],dp[i-1][j]); 14 | if(j>0)dp[i][j]=max(dp[i][j],dp[i][j-1]); 15 | if(i>0&&j>0) 16 | dp[i][j]=max(dp[i][j],dp[i-1][j-1]+max(0,nums1[i]*nums2[j])); 17 | } 18 | } 19 | return dp[n-1][m-1]; 20 | } 21 | -------------------------------------------------------------------------------- /Array/424. Longest Repeating Character Replacement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Here the important thing to note is that the most repeating character not necessarily have to produce the longest substring. 3 | when we are iterating through the loop at present what is the most repeating character will be used in our slidng window 4 | whilst we cache in our maximum. 5 | */ 6 | int characterReplacement(string s, int k) { 7 | unordered_map map; 8 | 9 | int i=0,j=0,ans=0,same=0; 10 | for(i=0;ik) 14 | { 15 | map[s[j]]--; 16 | j++; 17 | } 18 | ans=max(ans,i-j+1); 19 | } 20 | return ans; 21 | } -------------------------------------------------------------------------------- /Strings/5. Longest Palindromic Substring,cpp. Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | string longestPalindrome(string s) { 4 | int maxlen = 0, start=0; 5 | for(int i = 0;i < s.size();++i) { 6 | int left = i, right = i; 7 | while(s[right+1] == s[left]) {//Skip same char in the middle 8 | right++; 9 | i++; 10 | } 11 | while(left -1 >= 0 && right + 1 < s.size() && s[right+1] == s[left-1]) {//Handle expand 12 | left--; 13 | right++; 14 | } 15 | if(right-left+1 > maxlen) {//record max pos 16 | maxlen = right-left+1; 17 | start = left; 18 | } 19 | } 20 | return s.substr(start, maxlen); 21 | } -------------------------------------------------------------------------------- /Array/1010. Pairs of Songs With Total Durations Divisible by 60.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem is like 2 sum with a twist. 3 | We are going to use a map to store the a number so when a number + mapped number gives 60 we can increment our answer. 4 | I will be explaining with the code :- 5 | */ 6 | int numPairsDivisibleBy60(vector& time) { 7 | int ans=0; 8 | unordered_map map; 9 | for (int &t : time) { 10 | ans += map[(60 - t % 60) % 60]; 11 | ++map[t % 60]; 12 | } 13 | return ans; 14 | } 15 | /* 16 | Let Input: [30,20,150,100,40] 17 | 18 | Bsically we are scaling all the inputs in the order of mod 60 So we find wo inputs whose sum is equal to 60. 19 | (60 - t % 60) % 60 this value check if for t 60-t exist or not if so increment ur answer. -------------------------------------------------------------------------------- /Dynamic Programming/1314. Matrix Block Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixBlockSum(vector>& mat, int k) { 4 | int n=mat.size(),m=mat[0].size(); 5 | vector> dp(n+1,vector(m+1)); 6 | for(int i=1;i<=n;i++) 7 | { 8 | for(int j=1;j<=m;j++) 9 | dp[i][j]=mat[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; 10 | } 11 | vector> ans(n,vector(m)); 12 | for(int i=0;i>& matrix, int k) { 8 | priority_queue pq; 9 | for(int i=0;im)return isOneEditDistance(t,s); 18 | for(int i=0;i>& grid) 5 | { 6 | if(j1<0||j2<0||i>=n||j1>=m||j2>=m)return 0; 7 | if(dp[i][j1][j2]!=-1)return dp[i][j1][j2]; 8 | int ans=grid[i][j1]+(j1==j2?0:grid[i][j2]); 9 | int count=0; 10 | for(int x=-1;x<2;x++) 11 | { 12 | for(int y=-1;y<2;y++) 13 | { 14 | count=max(count,help(i+1,j1+x,j2+y,n,m,grid)); 15 | } 16 | } 17 | return dp[i][j1][j2]=ans+count; 18 | } 19 | int cherryPickup(vector>& grid) { 20 | int n=grid.size(); 21 | int m=grid[0].size(); 22 | memset(dp,-1,sizeof dp); 23 | return help(0,0,m-1,n,m,grid); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Graph/210. Course Schedule II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOrder(int n, vector>& prerequisites) { 4 | vector ans,indegree(n); 5 | vector> graph(n); 6 | for(auto &x:prerequisites) 7 | { 8 | graph[x[1]].push_back(x[0]); 9 | indegree[x[0]]++; 10 | } 11 | queue q; 12 | int count=0; 13 | for(int i=0;i>& grid) { 2 | vector row(grid.size()); 3 | vector col(grid[0].size()); 4 | for(int i=0;i1 || row[i]>1)) //If int the same row or colum there is another server increment it 18 | ans++; 19 | } 20 | } 21 | return ans; 22 | } -------------------------------------------------------------------------------- /Design/Shuffle an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector nums; 3 | public: 4 | Solution(vector& nums) { 5 | this->nums=nums; 6 | } 7 | 8 | /** Resets the array to its original configuration and return it. */ 9 | vector reset() { 10 | return nums; 11 | } 12 | 13 | /** Returns a random shuffling of the array. */ 14 | vector shuffle() { 15 | vector result(nums); 16 | for(int i=0;i param_1 = obj->reset(); 29 | * vector param_2 = obj->shuffle(); 30 | */ 31 | -------------------------------------------------------------------------------- /Dynamic Programming/121. Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | What u want to keep doing in this problem is recording the maximum profit and recording the minimum element at the same time. 3 | say the array is [4,3,6,8,9]. 4 | let my smallest element be INT_MAX 5 | so my profit will be max(profit,arr[i]-smallest) 6 | so at the same time we will be recording the minimum 7 | [4,3,6,8,9] 8 | profit smallest 9 | 0 INT_MAX 10 | 0 4 11 | 0 3 12 | 3 3 13 | 5 3 14 | 6 3 15 | Thus 3 is the final answer. 16 | */ 17 | int maxProfit(vector& prices) { 18 | int profit=0,smallest=INT_MAX; 19 | for(int i=0;i &parent) 6 | { 7 | return parent[x]==x?x:find(parent[x],parent); 8 | } 9 | int earliestAcq(vector>& logs, int N) { 10 | sort(logs.begin(),logs.end()); 11 | vector groups(N); 12 | for(int i=0;i rank(N,0); 14 | int count=0,ans=INT_MIN; 15 | for(auto &x:logs) 16 | { 17 | int group1=find(x[1],groups); 18 | int group2=find(x[2],groups); 19 | if(group1!=group2) 20 | { 21 | N--; 22 | if(N==1)return x[0]; 23 | groups[group1]=group2; 24 | } 25 | } 26 | return -1; 27 | } -------------------------------------------------------------------------------- /Graph/841. Keys and Rooms.cpp: -------------------------------------------------------------------------------- 1 | unordered_map> graph; 2 | vector vis; 3 | bool canVisitAllRooms(vector>& rooms) { 4 | int n=rooms.size(); 5 | vis.resize(n,false); 6 | for(int i=0;i q; 12 | q.push(0); 13 | int count=0; 14 | while(!q.empty() && count!=n) 15 | { 16 | int t=q.front(); 17 | q.pop(); 18 | if(vis[t]==false)count++; 19 | vis[t]=true; 20 | if(graph[t].size()) 21 | { 22 | for(auto &x:graph[t]) 23 | { 24 | if(!vis[x])q.push(x); 25 | } 26 | } 27 | } 28 | return count==n; 29 | } 30 | -------------------------------------------------------------------------------- /TREES/572. Subtree of Another Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to solve this problem is find the node of s which equals the root node of t. Once found we can use a function to check if every 3 | node equals every other node. 4 | 3 5 | / \ 6 | --> 4 5 7 | / \ 8 | 1 2 9 | 10 | 4 11 | / \ 12 | 1 2 13 | 14 | Here as soon as we find 4 we just check if every node in s is equal to every other node in t 15 | */ 16 | 17 | bool issame(TreeNode* s,TreeNode* t) 18 | { 19 | if(!s&&!t)return true; 20 | if(!s||!t)return false; 21 | if(s->val!=t->val)return false; 22 | return s->val==t->val&&issame(s->left,t->left)&&issame(s->right,t->right); 23 | } 24 | bool isSubtree(TreeNode* s, TreeNode* t) { 25 | if(!s)return false; 26 | return issame(s,t)||isSubtree(s->left,t)||isSubtree(s->right,t); 27 | } -------------------------------------------------------------------------------- /TREES/979. Distribute Coins in Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Explanation:-https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/221939/C%2B%2B-with-picture-post-order-traversal 3 | 4 | Algorithm:- 5 | 1.We perfom a dfs(post oreder) on the tree. 6 | 2.We we simulatneously cache in our steps count 7 | 3. We update the root value as |dfs(root->left)| + |dfs(root->right)| 8 | 4.We return root->val-1 9 | */ 10 | int dfs(TreeNode* root,int &steps) 11 | { 12 | if(!root)return 0; 13 | int l=dfs(root->left,steps); 14 | steps+=abs(l); 15 | int r=dfs(root->right,steps); 16 | steps+=abs(r); 17 | root->val+=l+r; 18 | return root->val-1; 19 | 20 | } 21 | int distributeCoins(TreeNode* root) { 22 | if(!root)return 0; 23 | int steps=0; 24 | dfs(root,steps); 25 | return steps; 26 | } -------------------------------------------------------------------------------- /Array/1552. Magnetic Force Between Two Balls.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDistance(vector& arr, int k) { 4 | int n=arr.size(); 5 | sort(arr.begin(),arr.end()); 6 | int l=1,r=arr[n-1]-arr[0]; 7 | int ans=0; 8 | while(l<=r) 9 | { 10 | int m=(l+r)/2; 11 | if(check(arr,n,k,m)) 12 | { 13 | ans=m; 14 | l=m+1; 15 | } 16 | else r=m-1; 17 | } 18 | return ans; 19 | } 20 | private: 21 | bool check(vector& arr, int n,int k,int m) 22 | { 23 | int p=arr[0]; 24 | int count=1; 25 | for(int i=1;i=m) 28 | { 29 | p=arr[i]; 30 | count++; 31 | } 32 | } 33 | return count>=k; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Dynamic Programming/84. Largest Rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | int largestRectangleArea(vector& heights) { 2 | if(heights.size()<1)return 0; 3 | stack st; 4 | int i=0,area,max_area=-1; 5 | while(i=heights[st.top()]) 8 | st.push(i++); 9 | else 10 | { 11 | int top=st.top(); 12 | st.pop(); 13 | area=heights[top]*(st.empty()?i:i-st.top()-1); 14 | max_area=max(max_area,area); 15 | } 16 | } 17 | while(!st.empty()) 18 | { 19 | int top=st.top(); 20 | st.pop(); 21 | area=heights[top]*(st.empty()?i:i-st.top()-1); 22 | max_area=max(max_area,area); 23 | } 24 | return max_area; 25 | } 26 | -------------------------------------------------------------------------------- /Dynamic Programming/10. Regular Expression Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | vector> dp(s.size()+1,vector(p.size()+1)); 5 | dp[0][0]=true; 6 | for(int i=1;i>& mat) { 4 | int n=mat.size(),m=mat[0].size(); 5 | vector> prefix(n,vector(m)); 6 | for(int i=0;i=0;j--) 9 | { 10 | if(!mat[i][j])continue; 11 | if(j!=m-1) 12 | prefix[i][j]+=prefix[i][j+1]; 13 | prefix[i][j]+=mat[i][j]; 14 | } 15 | } 16 | int ans=0; 17 | for(int i=0;iINT_MAX then do the following: 7 | Keep a conditional statement before the formula saying if(r>int_max/10 || r==int_max/10 && x%10>7)return false because even if its 8 | palindrome it doesnt satify the fact that the number should be an integer. 9 | */ 10 | bool isPalindrome(int x) { 11 | if(x==0)return true; 12 | int n=x; 13 | int sign=(x>0)?1:-1; 14 | if(sign<0)return false; 15 | x=abs(x); 16 | int r=0; 17 | while(x>0) 18 | { 19 | if(r>INT_MAX/10 || r==INT_MAX/10 && x%10>7)return false; 20 | r=r*10+x%10; 21 | x/=10; 22 | } 23 | return r==n; 24 | } 25 | -------------------------------------------------------------------------------- /Hash Table/1488. Avoid Flood in The City.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector avoidFlood(vector& rains) { 4 | unordered_map map; 5 | set s; 6 | vector ans; 7 | for(int i=0;i ban(banned.begin(), banned.end()); 8 | unordered_map map; 9 | for (auto & c: p) c = isalpha(c) ? tolower(c) : ' '; 10 | istringstream iss(p); 11 | string w; 12 | int m=0;string ans; 13 | while(iss>>w) 14 | { 15 | if(ban.find(w)==ban.end()) 16 | { 17 | map[w]++; 18 | if(map[w]>m) 19 | { 20 | m=map[w]; 21 | ans=w; 22 | } 23 | } 24 | } 25 | return ans; 26 | } -------------------------------------------------------------------------------- /Array/163. Missing Ranges.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 3 | 4 | Example: 5 | 6 | Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99, 7 | Output: ["2", "4->49", "51->74", "76->99"] 8 | 9 | 10 | */ 11 | 12 | class Solution { 13 | public: 14 | string helper(long start,long end) 15 | { 16 | return start==end?to_string(start):to_string(start)+"->"+to_string(end); 17 | } 18 | vector findMissingRanges(vector& nums, int lower, int upper) { 19 | vector ans; 20 | long prev=(long)lower-1; 21 | for(int i=0;i<=nums.size();i++) 22 | { 23 | long curr=(i==nums.size()?(long)upper+1:(long)nums[i]); 24 | if(curr-prev>=(long)2) 25 | ans.push_back(helper(prev+1,curr-1)); 26 | prev=curr; 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Array/324. Wiggle Sort II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 3 | 4 | Example 1: 5 | 6 | Input: nums = [1, 5, 1, 1, 6, 4] 7 | Output: One possible answer is [1, 4, 1, 5, 1, 6]. 8 | 9 | Example 2: 10 | 11 | Input: nums = [1, 3, 2, 2, 3, 1] 12 | Output: One possible answer is [2, 3, 1, 3, 1, 2]. 13 | */ 14 | 15 | class Solution { 16 | public: 17 | void wiggleSort(vector& nums) { 18 | vector sorted(nums.begin(),nums.end()); 19 | sort(sorted.begin(),sorted.end()); 20 | for(int i=nums.size()-1,j=0,k=i/2+1;i>=0;i--) 21 | { 22 | nums[i]=sorted[i&1?k++:j++]; 23 | } 24 | } 25 | }; 26 | 27 | /* 28 | It is actually very smart to reverse the halves. Consider the case SMML, the result is 29 | M S 30 | L M 31 | 32 | MLSM 33 | 34 | If we don't reverse the halves, the result would be 35 | S M 36 | M L 37 | 38 | SMML 39 | which is wrong 40 | */ 41 | -------------------------------------------------------------------------------- /Array/Sort Array By Parity.cpp: -------------------------------------------------------------------------------- 1 | We will be trying to attack this question by using an inplace algorithm. 2 | Although using an auxilliary array will work its not space efficient. 3 | We will place two pointers at the start lets say l and r. 4 | We will try to make l point to an odd value and r to an even value and we swap. 5 | array = 2 5 3 7 6 | ^ 7 | | 8 | l,r 9 | 10 | Since l is pointing to an even value it swaps with the right pointer and increments itself. 11 | 12 | array = 2 5 3 8 13 | ^ ^ 14 | | | 15 | r l 16 | then right poiter increments as usual and we reach 8. 17 | Since 8 is an even number we swap it with left and incement left ponter. 18 | 19 | array = 2 8 5 3 20 | 21 | vector sortArrayByParity(vector &A) { 22 | int l=0,r=0; 23 | while(r> &graph,vector &color,int c) 4 | { 5 | if(color[i]!=0)return color[i]==c; 6 | color[i]=c; 7 | for(auto &x:graph[i]) 8 | if(!dfs(x,graph,color,-c)) 9 | return false; 10 | return true; 11 | } 12 | bool possibleBipartition(int n, vector>& dislikes) { 13 | if(dislikes.size()==0)return true; 14 | if(n==1)return false; 15 | vector> graph(n+1); 16 | int cc=0; 17 | for(auto &x:dislikes) 18 | { 19 | graph[x[0]].push_back(x[1]); 20 | graph[x[1]].push_back(x[0]); 21 | } 22 | vector color(n+1,0); 23 | for(int i=1;i<=n;i++) 24 | { 25 | if(color[i]==0 && !dfs(i,graph,color,1)) 26 | return false; 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Dynamic Programming/62. Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | Whenever attempting a dp problem stating the number of ways try to find out that at my current poistion 2 | how many ways is possible for me to reach this position. 3 | The first row and first column only 1 way will be possible because the only other way to reach this is either 4 | right or down which are the contraints of the problem. 5 | 6 | let m=3,n=4; 7 | 1 2 3 4 8 | 1 1 1 1 1 9 | 2 1 2 3 4 <----- DP Matrix dp[i][j] = dp[i-1][j] + dp[i][j-1] where i!=0 and j!=0 10 | 3 1 3 6 10 11 | 12 | Thus there are 10 ways to go! 13 | 14 | 15 | int uniquePaths(int m, int n) { 16 | vector> dp(m,vector(n)); 17 | for(int i=0;i checkIfPrerequisite(int n, vector>& p, vector>& q) { 4 | vector> graph(n,vector(n,INT_MAX/2)); 5 | for(int i=0;igraph[i][k]+graph[k][j]) 16 | graph[i][j]=graph[i][k]+graph[k][j]; 17 | } 18 | } 19 | } 20 | vector ans; 21 | for(int i=0;i& v, int m, int k,int mid) 4 | { 5 | int c=0,tot=0; 6 | for(int i=0;i=m)return true; 20 | return false; 21 | } 22 | int minDays(vector& v, int m, int k) { 23 | int l=0,r=*max_element(v.begin(),v.end()),ans=-1; 24 | while(l<=r) 25 | { 26 | int mid=l+(r-l)/2; 27 | if(check(v,m,k,mid)) 28 | { 29 | ans=mid; 30 | r=mid-1; 31 | } 32 | else l=mid+1; 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /BFS/1514. Path with Maximum Probability.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { 4 | vector> graph(n); 5 | for(int i=0;i ans(n,0.0); 11 | queue q; 12 | q.push(start); 13 | ans[start]=1.0; 14 | while(!q.empty()) 15 | { 16 | int t=q.front(); 17 | q.pop(); 18 | for(auto &x:graph[t]) 19 | { 20 | if(ans[t]*x.second>ans[x.first]) 21 | { 22 | ans[x.first]=ans[t]*x.second; 23 | q.push(x.first); 24 | } 25 | } 26 | } 27 | return ans[end]; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /TREES/1522. Diameter of N-Ary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int dfs(Node* root,int &ans) 24 | { 25 | if(!root)return 0; 26 | int max1=0,max2=0; 27 | for(Node* a:root->children) 28 | { 29 | int height=dfs(a,ans); 30 | if(height>max1) 31 | { 32 | max2=max1; 33 | max1=height; 34 | } 35 | else if(height>max2)max2=height; 36 | } 37 | ans=max(ans,max1+max2); 38 | return max1+1; 39 | } 40 | int diameter(Node* root) { 41 | int ans=0; 42 | dfs(root,ans); 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Dynamic Programming/1092. Shortest Common Supersequence .cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string lcs(string s1,string s2) 4 | { 5 | vector> dp(s1.size()+1,vector(s2.size()+1)); 6 | for(int i=1;i<=s1.size();i++) 7 | { 8 | for(int j=1;j<=s2.size();j++) 9 | { 10 | if(s1[i-1]==s2[j-1]) 11 | dp[i][j]=dp[i-1][j-1]+s1[i-1]; 12 | else dp[i][j]+=dp[i-1][j].size()>dp[i][j-1].size()?dp[i-1][j]:dp[i][j-1]; 13 | } 14 | } 15 | return dp[s1.size()][s2.size()]; 16 | } 17 | string shortestCommonSupersequence(string str1, string str2) { 18 | int i=0,j=0; 19 | string ans; 20 | for(char ch:lcs(str1,str2)) 21 | { 22 | while(str1[i]!=ch)ans+=str1[i++]; 23 | while(str2[j]!=ch)ans+=str2[j++]; 24 | ans+=ch; 25 | i++;j++; 26 | } 27 | return ans+str1.substr(i)+str2.substr(j); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Array/31. Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | void nextPermutation(vector& nums) { 2 | int k=nums.size()-2; 3 | while(k>=0 && nums[k]>=nums[k+1])k--; //we are trying to find a point were we can start performing a swap that is a swap with a bigger number and a smaller number. 4 | if(k==-1) 5 | { 6 | sort(nums.begin(),nums.end()); //if it is sorted in the reverse order the next permuation will rewind back to the first. 7 | return; 8 | } 9 | for(int i=nums.size()-1;i>k;i--) 10 | { 11 | if(nums[i]>nums[k]) //again we are trying to find a greater element present in the back to swap with a smaller element present in the front to get a greater array than the current one 12 | { 13 | swap(nums[i],nums[k]); 14 | break; 15 | } 16 | } 17 | reverse(nums.begin()+k+1,nums.end()); //we reverse it becuase we have to get the permutation which is just greater than the current one. 18 | } -------------------------------------------------------------------------------- /Hash Table/208. Implement Trie (Prefix Tree).cpp: -------------------------------------------------------------------------------- 1 | class Trie { 2 | public: 3 | unordered_set s; 4 | Trie() { 5 | 6 | } 7 | 8 | /** Inserts a word into the trie. */ 9 | void insert(string word) { 10 | s.insert(word); 11 | } 12 | 13 | /** Returns if the word is in the trie. */ 14 | bool search(string word) { 15 | if(s.find(word)==s.end())return false; 16 | return true; 17 | } 18 | 19 | /** Returns if there is any word in the trie that starts with the given prefix. */ 20 | bool startsWith(string prefix) { 21 | if(s.size()==0)return false; 22 | for(auto it=s.begin();it!=s.end();it++) 23 | { 24 | string str=*it; 25 | bool ans=true; 26 | if(prefix.size()>str.size())continue; 27 | for(int i=0;i>& grid) { 4 | int n=grid.size(); 5 | using pii=pair>; 6 | vector> dir={{1,0},{0,1},{-1,0},{0,-1}}; 7 | int seen[n][n]; 8 | memset(seen,0,sizeof seen); 9 | priority_queue,greater> pq; 10 | pq.push({grid[0][0],{0,0}}); 11 | int ans=0; 12 | seen[0][0]=1; 13 | while(!pq.empty()) 14 | { 15 | auto p=pq.top(); 16 | pq.pop(); 17 | ans=max(ans,p.first); 18 | if(p.second.first==n-1 && p.second.second==n-1)return ans; 19 | for(auto &a:dir) 20 | { 21 | int x=p.second.first+a[0]; 22 | int y=p.second.second+a[1]; 23 | if(x<0||y<0||x>=n||y>=n||seen[x][y])continue; 24 | seen[x][y]=1; 25 | pq.push({grid[x][y],{x,y}}); 26 | } 27 | } 28 | return -1; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Strings/273. Integer to English Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector ones={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; 4 | vector tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; 5 | string toWords(int n) 6 | { 7 | if(n>=1000000000) 8 | return toWords(n/1000000000)+" Billion"+toWords(n%1000000000); 9 | if(n>=1000000) 10 | return toWords(n/1000000)+" Million"+toWords(n%1000000); 11 | if(n>=1000) 12 | return toWords(n/1000)+" Thousand"+toWords(n%1000); 13 | if(n>=100) 14 | return toWords(n/100)+" Hundred"+toWords(n%100); 15 | if(n>=20) 16 | return " "+tens[n/10]+toWords(n%10); 17 | if(n>=1) 18 | return " "+ones[n]; 19 | return ""; 20 | } 21 | string numberToWords(int n) { 22 | return n?toWords(n).substr(1):"Zero"; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Bit Manipulation/201. Bitwise AND of Numbers Range.cpp: -------------------------------------------------------------------------------- 1 | /*The bruteforce solution to this problem would be to initialize x=1 and & x from m to n. 2 | While this is efficient we can do better using some bit logic. 3 | Lets take two nubers 4 | m = 1000010010110 5 | n = 1000101011011 6 | so this is the range givven to us. 7 | We kniw that even one 0 is present it can make the whole result 0. 8 | As this is a range given here in m and n whatever it is the first 4 digits from the left will be the same 9 | whatsoever ans the rest will be 0s as there will be atleast 1 0. 10 | So we can leverage this fact and decrease our original complexity to logarithmic. 11 | we rightshift m and n unti they are equal and right shift if by the sam amount as the above logic mentioned 12 | all the other eements will be 0. 13 | 14 | */ 15 | int rangeBitwiseAnd(int m, int n) { 16 | int i=0; 17 | while(m!=n) 18 | { 19 | m>>=1; //<------right shifting 20 | n>>=1; 21 | i++; 22 | } 23 | return m<> which sores all the positions where an alphabet occurs and use it to find 6 | the shortest distance. 7 | */ 8 | unordered_map> map; 9 | WordDistance(vector& words) { 10 | for(int i=0;i& rec1, vector& rec2) { 12 | int A=rec1[0],B=rec1[1],C=rec1[2],D=rec1[3],E=rec2[0],F=rec2[1],G=rec2[2],H=rec2[3]; 13 | long long x_dist=length(A,E,C,G); 14 | long long y_dist=length(B,F,D,H); 15 | 16 | if(x_dist<=0) //<----a negative x_dist and y_dist can contribute to a positive area which should be avoided. 17 | x_dist=0; 18 | if(y_dist<=0) 19 | y_dist=0; 20 | return x_dist*y_dist>0; 21 | } -------------------------------------------------------------------------------- /TREES/106. Construct Binary Tree from Inorder and Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* helper(vector& inorder, vector& postorder,int is,int ie,int ps,int pe) 13 | { 14 | if(ps>pe)return NULL; 15 | TreeNode* node=new TreeNode(postorder[pe]); 16 | int pos; 17 | for(int i=is;i<=ie;i++) 18 | if(inorder[i]==node->val) 19 | { 20 | pos=i; 21 | break; 22 | } 23 | node->left=helper(inorder,postorder,is,pos-1,ps,ps+pos-is-1); 24 | node->right=helper(inorder,postorder,pos+1,ie,pe-ie+pos,pe-1); 25 | return node; 26 | } 27 | TreeNode* buildTree(vector& inorder, vector& postorder) { 28 | return helper(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /TREES/108. Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Divide and Conquer:- 3 | 4 | As the tree is heightbalanced the root will be present at the n/2 location of the nums array where n is the size of the array. 5 | So we can use this base case to build our tree 6 | [-10,-3,0,5,9] 7 | 8 | 0 will be the root. 9 | Then we pass the left part of the array to root->left and right part of the array to root right and repeat the same procedure. 10 | 11 | 12 | 1. 0 13 | 14 | 15 | root->left = build(nums,l,m-1) 16 | 17 | | | 18 | | -10 | 19 | | -3 | 20 | |______| 21 | 22 | 2. 0 23 | / 24 | -10 25 | \ 26 | -3 27 | 28 | and we repeat this procedure to get the answer 29 | */ 30 | 31 | { 32 | if(l>r)return NULL; 33 | int m=(l+r)/2; 34 | TreeNode* newnode=new TreeNode(nums[m]); 35 | newnode->left=makeBST(nums,l,m-1); 36 | newnode->right=makeBST(nums,m+1,r); 37 | return newnode; 38 | } 39 | TreeNode* sortedArrayToBST(vector& nums) { 40 | return makeBST(nums,0,nums.size()-1); 41 | } -------------------------------------------------------------------------------- /Array/259. 3Sum Smaller.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. 3 | 4 | Example: 5 | 6 | Input: nums = [-2,0,1,3], and target = 2 7 | Output: 2 8 | Explanation: Because there are two triplets which sums are less than 2: 9 | [-2,0,1] 10 | [-2,0,3] 11 | 12 | Follow up: Could you solve it in O(n2) runtime? 13 | 14 | */ 15 | 16 | 17 | class Solution { 18 | public: 19 | int threeSumSmaller(vector& nums, int target) { 20 | int count=0; 21 | sort(nums.begin(),nums.end()); 22 | for(int i=0;i> dp(s.size()+1,vector(p.size()+1,false)); 20 | dp[0][0]=true; 21 | if(p[0]=='*')dp[0][1]=true; 22 | for(int i=1;i s; 25 | while(1) 26 | { 27 | int sum=0; 28 | while(n) 29 | { 30 | sum+=pow(n%10,2); 31 | n/=10; 32 | } 33 | if(s.find(sum)!=s.end())break; 34 | s.insert(sum); 35 | if(sum==1)return true; 36 | n=sum; 37 | } 38 | return false; 39 | } -------------------------------------------------------------------------------- /DFS/51. N-Queens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | bool isValid(vector &rows,int row,int col,int n) 5 | { 6 | for(int i=0;i=0&&j>=0;i--,j--) 9 | { 10 | if(rows[i][j]=='Q')return false; 11 | } 12 | for(int i=row-1,j=col+1;i>=0&&j &rows,int row,int n) 17 | { 18 | if(row==n) 19 | { 20 | ans.push_back(rows); 21 | return; 22 | } 23 | for(int col=0;col> solveNQueens(int n) { 34 | vector row(n,string(n,'.')); 35 | solve(row,0,n); 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Dynamic Programming/1473. Paint House III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[101][21][101]; 4 | int help(int i,int l,int t,vector& houses, vector>& cost, int m, int n, int target) 5 | { 6 | if(dp[i][l][t]!=-1)return dp[i][l][t]; 7 | if(t>target)return INT_MAX/2; 8 | if(i==m) 9 | { 10 | if(target==t)return 0; 11 | else return INT_MAX/2; 12 | } 13 | int ans=INT_MAX/2; 14 | if(houses[i]==0) 15 | { 16 | for(int j=0;j& houses, vector>& cost, int m, int n, int target) { 28 | memset(dp,-1,sizeof dp); 29 | return help(0,0,0,houses,cost,m,n,target)==INT_MAX/2?-1:help(0,0,0,houses,cost,m,n,target); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /TREES/1519. Number of Nodes in the Sub-Tree With the Same Label.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> graph; 4 | vector> count; 5 | vector ans; 6 | void dfs(int i,string &labels,int prev) 7 | { 8 | if(graph[i].size()==0) 9 | { 10 | ans[i]=1; 11 | return; 12 | } 13 | for(auto &x:graph[i]) 14 | { 15 | if(x==prev)continue; 16 | dfs(x,labels,i); 17 | for(int j=0;j<26;j++) 18 | count[i][j]+=count[x][j]; 19 | } 20 | ans[i]=count[i][labels[i]-'a']; 21 | } 22 | vector countSubTrees(int n, vector>& edges, string labels) { 23 | graph.resize(n); 24 | count.resize(n,vector(26)); 25 | ans.resize(n); 26 | for(auto &x:edges) 27 | { 28 | graph[x[0]].push_back(x[1]); 29 | graph[x[1]].push_back(x[0]); 30 | } 31 | for(int i=0;iroot->node. 5 | 2. Decrease from node->root->node 6 | 7 | The way we can do this is by doing a postordere traversal to those nodes that satisfies root->val+1/root->val-1. 8 | */ 9 | int helper(TreeNode* root,int par,int sum) 10 | { 11 | if(!root)return 0; 12 | if(root->val==par+sum) 13 | return max(helper(root->left,root->val,sum),helper(root->right,root->val,sum))+1; 14 | return 0; 15 | } 16 | int longestConsecutive(TreeNode* root) { 17 | if(!root)return NULL; 18 | int l1=0,l2=0,childmax=0; 19 | l1=helper(root->left,root->val,-1)+helper(root->right,root->val,1)+1; 20 | l2=helper(root->left,root->val,1)+helper(root->right,root->val,-1)+1; 21 | childmax=max(longestConsecutive(root->left),longestConsecutive(root->right)); 22 | return max(l1,max(l2,childmax)); 23 | } -------------------------------------------------------------------------------- /Graph/133. Clone Graph.pp.cpp: -------------------------------------------------------------------------------- 1 | We use unordered map to clone the graph 2 | 3 | Node* cloneGraph(Node* node) { 4 | if(!node)return NULL; 5 | unordered_map map; 6 | Node* copy=new Node(node->val); //We create a new node with the nodes value 7 | map[node]=copy; //We store it in the map so it will help get get access to tha element in o(1) time 8 | queue q; 9 | q.push(node); 10 | while(!q.empty()) 11 | { 12 | Node* t=q.front(); 13 | q.pop(); 14 | for(Node* x:t->neighbors) //We explore all of its neighbors to make copies of edges and its adjacent nodes 15 | { 16 | if(!map.count(x)) //This is to make sure we dont visit the node multiple times 17 | { 18 | map[x]=new Node(x->val); //We create the new nodes 19 | q.push(x); 20 | } 21 | map[t]->neighbors.push_back(map[x]); //This the creation of edges 22 | } 23 | 24 | } 25 | return copy; 26 | } -------------------------------------------------------------------------------- /BFS/1197. Minimum Knight Moves.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | #define tr 303 4 | using pii=pair; 5 | int minKnightMoves(int st, int d) { 6 | vector> dir={{-2,-1},{2,-1},{-2,1},{2,1},{-1,-2},{1,-2},{-1,2},{1,2}}; 7 | queue q; 8 | q.push({0,0}); 9 | bool vis[2*tr][2*tr]; 10 | memset(vis,false,sizeof(vis)); 11 | int count=0; 12 | vis[tr][tr]=true; 13 | while(!q.empty()) 14 | { 15 | int n=q.size(); 16 | for(int i=0;inext)return head; 10 | ListNode* odd=head,*even=head->next,*firsteven=even; 11 | while(even&&even->next) 12 | { 13 | odd->next=odd->next->next; 14 | even->next=even->next->next; 15 | odd=odd->next; 16 | even=even->next; 17 | } 18 | odd->next=firsteven; 19 | return head; 20 | } 21 | /* 22 | Let us test this code with an example 23 | 1->2->3->4->5->6->NULL 24 | 25 | odd points to 1 and even points to 2 26 | odd->next=odd->next->next make 1->3 27 | even->next=even->next->next makes 2->4 28 | then we move the odd pointer to 3 and even pointer to 4 29 | 30 | then 1->3->5 31 | 2->4->6 32 | then we move the odd pointer to 5 and even pointer to 6 33 | at this point even->next is NULL so we break 34 | */ -------------------------------------------------------------------------------- /Hash Table/13. Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We will be using hash tables to tackle this problem. 3 | We store the integrs correspong to the roman numerals and cache in whenever we want to. 4 | The only caviat u have to look forward is that when traversing through the string if s[i] map={ 18 | {'I',1}, 19 | {'V',5}, 20 | {'X',10}, 21 | {'L',50}, 22 | {'C',100}, 23 | {'D',500}, 24 | {'M',1000}}; 25 | int ans=map[s[s.size()-1]]; 26 | for(int i=s.size()-2;i>=0;i--) 27 | { 28 | if(map[s[i+1]]>map[s[i]])ans-=map[s[i]]; 29 | else 30 | ans+=map[s[i]]; 31 | } 32 | return ans; 33 | } -------------------------------------------------------------------------------- /Graph/1494. Parallel Courses II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public:using Graph = unordered_map>; 3 | 4 | Graph buildGraph(vector>& dependencies, vector& degree) { 5 | Graph graph; 6 | for (auto& relation : dependencies) { 7 | graph[relation[0]].insert(relation[1]); 8 | degree[relation[1]]++; 9 | } 10 | return graph; 11 | } 12 | int minNumberOfSemesters(int n, vector>& d, int k) { 13 | vector indegree(n+1); 14 | Graph graph=buildGraph(d,indegree); 15 | queue q; 16 | int semesters=0; 17 | for(int i=1;i<=n;i++) 18 | if(indegree[i]==0)q.push(i); 19 | while(!q.empty()) 20 | { 21 | int size=q.size(); 22 | semesters++; 23 | for(int i=0;i spellchecker(vector& wordlist, vector& queries) { 19 | unordered_set set(wordlist.begin(),wordlist.end()); 20 | unordered_map map1,map2; 21 | for(string s:wordlist) 22 | { 23 | string low=lower(s),nvowel=devowel(s); 24 | map1.insert({low,s}); 25 | map2.insert({nvowel,s}); 26 | } 27 | for(string &s:queries) 28 | { 29 | if(set.find(s)!=set.end())continue; 30 | string low=lower(s),nvowel=devowel(s); 31 | if(map1.count(low))s=map1[low]; 32 | else if(map2.count(nvowel))s=map2[nvowel]; 33 | else s=""; 34 | } 35 | return queries; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /TREES/Binary Tree Upside Down.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Input: [1,2,3,4,5] 3 | 1 4 | / \ 5 | 2 3 6 | / \ 7 | 4 5 8 | 9 | 10 | 11 | Output: [4,5,2,#,#,3,1] 12 | 13 | 4 14 | / \ 15 | 5 2 16 | / \ 17 | 3 1 18 | 19 | 20 | 21 | Follow the reversing of linked list code 22 | */ 23 | TreeNode* upsideDownBinaryTree(TreeNode* root) { 24 | TreeNode* curr=root,*next,*prev=NULL,*temp=NULL; 25 | while(curr) 26 | { 27 | next=curr->left; 28 | 29 | curr->left=temp; 30 | temp=curr->right; 31 | curr->right=prev; 32 | 33 | prev=curr; 34 | curr=next; 35 | } 36 | return prev; 37 | } 38 | 39 | 40 | /* 41 | 42 | public ListNode reverseList(ListNode head) { 43 | ListNode pre = null; 44 | ListNode cur = head; 45 | while (cur != null) { <---------Reversing ll 46 | ListNode next = cur.next; 47 | cur.next = pre; 48 | pre = cur; 49 | cur = next; 50 | } 51 | 52 | return pre; 53 | } 54 | */ -------------------------------------------------------------------------------- /TREES/Vertical Order Traversal of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | map>> map; 15 | void inorder(TreeNode* root,int x,int y) 16 | { 17 | if(!root)return; 18 | inorder(root->left,x-1,y+1); 19 | map[x][y].insert(root->val); 20 | inorder(root->right,x+1,y+1); 21 | } 22 | vector> verticalTraversal(TreeNode* root) { 23 | inorder(root,0,0); 24 | vector> ans; 25 | for(auto it:map) 26 | { 27 | vector col; 28 | for(auto p:it.second) 29 | { 30 | col.insert(col.end(),p.second.begin(),p.second.end()); 31 | } 32 | ans.push_back(col); 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Bit Manipulation/1342. Number of Steps to Reduce a Number to Zero.cpp: -------------------------------------------------------------------------------- 1 | We have to use bit mani pulation for this as it is way faster than the brute force method 2 | It is as simple as these steps 3 | 1. Check if the number is even or odd. 4 | 2. If the number is even right shift and increment the answer. 5 | 3 If the number is odd DONOT subtract it, as right shif will get back to half the value 6 | All u have to do is increment the answer by 2. 7 | Let 8 | num = 9 <--- as the number is odd we increment answer twice. count=1 9 | 9/2 = 4 <--- as the number is even we increment the answer by 1 count=2 10 | 4/2 = 2 <--- as the number is even we increment the answer by 1 count=3 11 | 2/2 = 1 <--- as the number is even we increment the answer by 1 count=4 12 | 1/2 = 0 <--- as the number is even we increment the answer by 1 count=5 13 | Thus the answer is 5. 14 | 15 | 16 | int numberOfSteps (int num) { 17 | int ans=0; 18 | while(num>0) 19 | { 20 | if(num%2==1)ans++; 21 | num>>=1; 22 | ans++; <----as 1 is odd it will count twice which we dont want. 23 | } 24 | return ans-1; 25 | } -------------------------------------------------------------------------------- /Graph/1462. Course Schedule IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { 4 | vector> v(n); 5 | vector> graph(n); 6 | vector indegree(n); 7 | for(auto &x:prerequisites) 8 | { 9 | graph[x[1]].push_back(x[0]); 10 | indegree[x[0]]++; 11 | } 12 | queue q; 13 | for(int i=0;i seen; 29 | for(int i=0;i& nums1, vector& nums2) { 4 | int x=nums1.size(),y=nums2.size(); 5 | if(x>y)return findMedianSortedArrays(nums2,nums1); 6 | int l=0,r=x; 7 | while(l<=r) 8 | { 9 | int partitionx=(l+r)/2; 10 | int partitiony=(x+y+1)/2-partitionx; 11 | int maxleftx=(partitionx==0)?INT_MIN:nums1[partitionx-1]; 12 | int minrightx=(partitionx==x)?INT_MAX:nums1[partitionx]; 13 | int maxlefty=(partitiony==0)?INT_MIN:nums2[partitiony-1]; 14 | int minrighty=(partitiony==y)?INT_MAX:nums2[partitiony]; 15 | if(maxleftx<=minrighty && maxlefty<=minrightx) 16 | { 17 | if((x+y)%2==0) 18 | return ((double)max(maxleftx,maxlefty)+min(minrightx,minrighty))/2.0; 19 | else 20 | return (double)max(maxleftx,maxlefty); 21 | } 22 | else if(maxleftx>minrighty) 23 | r=partitionx-1; 24 | else l=partitionx+1; 25 | } 26 | return -1; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Dynamic Programming/122. Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Here the way to tackle this problem is to visualize it. 3 | If I were to buy the data at every small value and sell it at the immediate biggest value i can get the answer. 4 | Let me demonstrate: 5 | 7 6 | \ 5 6 7 | \ /\ /\ 8 | \ / \/ 4 --------->[7,1,5,3,6,4] 9 | \/ 3 10 | 1 11 | So if we were to buy at every valley and sell at evry peak we can acheive the goal given in this q. 12 | buy-1,3,4 13 | sell-5,6 14 | but as 4 doesnt have a pair we discard it 15 | profit = (sum of peaks) - (sum of valleys) 16 | 11 - 4 = 7 17 | */ 18 | int maxProfit(vector& prices) { 19 | int ans=0,profit=0; 20 | int valley,peak; 21 | for(int i=0;i=prices[i+1])i++; 24 | valley = prices[i]; 25 | while(i digit; 5 | stack ans_st; 6 | string ans; 7 | int i=0; 8 | while(i &parent) 9 | { 10 | return parent[x]==x?x:find(parent[x],parent); 11 | } 12 | string smallestEquivalentString(string A, string B, string S) { 13 | string ans; 14 | vector groups(26); 15 | for(int i=0;i<26;i++)groups[i]=i; 16 | for(int i=0;i &v) 4 | { 5 | int ans=0; 6 | for(int i=v.size()-1;i>=0;i--) 7 | { 8 | if(v[i])break; 9 | ans++; 10 | } 11 | return ans; 12 | } 13 | vector grid_to_vec(vector> grid) 14 | { 15 | vector ans; 16 | for(auto &x:grid) 17 | { 18 | ans.push_back(zeroes(x)); 19 | } 20 | return ans; 21 | } 22 | int helper(vector &v) 23 | { 24 | int n=v.size(),ans=0; 25 | for(int i=0;ii) 33 | { 34 | swap(v[j],v[j-1]); 35 | ans++; 36 | j--; 37 | } 38 | } 39 | } 40 | return ans; 41 | } 42 | int minSwaps(vector>& grid) { 43 | vector a=grid_to_vec(grid); 44 | return helper(a); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /TRIE/1065. Index Pairs of a String.cpp: -------------------------------------------------------------------------------- 1 | class Trie { 2 | public: 3 | bool end; 4 | Trie* children[26]; 5 | Trie(){ 6 | end=false; 7 | memset(children,NULL,sizeof(children)); 8 | } 9 | }; 10 | class Solution { 11 | public: 12 | Trie* root=new Trie(); 13 | void insert(string s) 14 | { 15 | Trie* node=root; 16 | for(char ch:s) 17 | { 18 | if(!node->children[ch-'a']) 19 | node->children[ch-'a']=new Trie(); 20 | node=node->children[ch-'a']; 21 | } 22 | node->end=true; 23 | } 24 | vector> indexPairs(string text, vector& words) { 25 | vector> ans; 26 | for(string str:words) 27 | { 28 | insert(str); 29 | } 30 | for(int i=0;ichildren[text[j]-'a']; 36 | if(!node)break; 37 | if(node->end) 38 | { 39 | ans.push_back({i,j}); 40 | } 41 | } 42 | } 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Design/146. LRU Cache.cpp: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | public: 3 | unordered_map::iterator> pos; 4 | unordered_map map; 5 | int size; 6 | list l; 7 | LRUCache(int capacity) { 8 | size=capacity; 9 | } 10 | void use(int key) 11 | { 12 | if(pos.find(key)!=pos.end()) 13 | l.erase(pos[key]); 14 | else 15 | { 16 | if(l.size()>=size) 17 | { 18 | int old=l.back(); 19 | l.pop_back(); 20 | map.erase(old); 21 | pos.erase(old); 22 | } 23 | } 24 | l.push_front(key); 25 | pos[key]=l.begin(); 26 | } 27 | int get(int key) { 28 | if(map.find(key)!=map.end()) 29 | { 30 | use(key); 31 | return map[key]; 32 | } 33 | return -1; 34 | } 35 | 36 | void put(int key, int value) { 37 | use(key); 38 | map[key]=value; 39 | } 40 | }; 41 | 42 | /** 43 | * Your LRUCache object will be instantiated and called as such: 44 | * LRUCache* obj = new LRUCache(capacity); 45 | * int param_1 = obj->get(key); 46 | * obj->put(key,value); 47 | */ 48 | -------------------------------------------------------------------------------- /Design/348. Design Tic-Tac-Toe.cpp: -------------------------------------------------------------------------------- 1 | class TicTacToe { 2 | public: 3 | vector rows; 4 | vector cols; 5 | int diagonal,antidiagonal,n; 6 | TicTacToe(int size) { 7 | n=size; 8 | diagonal=0,antidiagonal=0; 9 | rows.resize(n),cols.resize(n); 10 | } 11 | 12 | /** Player {player} makes a move at ({row}, {col}). 13 | @param row The row of the board. 14 | @param col The column of the board. 15 | @param player The player, can be either 1 or 2. 16 | @return The current winning condition, can be either: 17 | 0: No one wins. 18 | 1: Player 1 wins. 19 | 2: Player 2 wins. */ 20 | int move(int row, int col, int player) { 21 | int toadd=player==1?1:-1; 22 | rows[row]+=toadd; 23 | cols[col]+=toadd; 24 | if(row==col)diagonal+=toadd; 25 | if(col==(n-row-1))antidiagonal+=toadd; 26 | if(abs(rows[row])==n||abs(cols[col])==n||abs(diagonal)==n||abs(antidiagonal)==n)return player; 27 | return 0; 28 | } 29 | }; 30 | 31 | /** 32 | * Your TicTacToe object will be instantiated and called as such: 33 | * TicTacToe* obj = new TicTacToe(n); 34 | * int param_1 = obj->move(row,col,player); 35 | */ 36 | -------------------------------------------------------------------------------- /Strings/12. Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | /*We will be using the array of nubers and sarray of strings to tackle this problem. 2 | Let the number be 74 = LXXIV 3 | let int check[]={1000,900,500,400,100,90,50,40,10,9,5,4,1} 4 | string s[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"} 5 | check the number which is lesser than equal to 74 which is 50 in the array 6 | 50 - L 7 | so we append that into our answer. 8 | ans = L 9 | num=24(74-50) 10 | the number closest to 24 in the array is 10 11 | ans = LX 12 | nums = 14(24-10) 13 | the number closest to 14 is 10 again 14 | ans = LXX 15 | num = 4 16 | ans = LXXIV. 17 | You might be wondering why 4,9 ,40 etc are there in the array. 18 | if 4 wasnt there in the above array it would have been ans = LXXIIII 19 | which is wrong. 20 | */ 21 | string intToRoman(int num) { 22 | int arr[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 23 | string s[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 24 | string ans; 25 | for(int i=0;num!=0;i++) 26 | { 27 | while(num>=arr[i]) 28 | { 29 | num-=arr[i]; 30 | ans+=s[i]; 31 | } 32 | } 33 | return ans; 34 | } 35 | -------------------------------------------------------------------------------- /Strings/14. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We will be using Common sense to solve this. 3 | we take the first string as our answer initially. 4 | we keep shrinking our answer for each iteration from 1 to n-1. 5 | 6 | LET 7 | strs = ["flower","flow","flight"] 8 | We initially put ans="flower" 9 | then we start analyzing str[1] 10 | if(s[i]!=ans[i])break 11 | and update the ans to ans.substr(0,i) where i denotes the index at which either both strings mismatched or reached the end of 1 of the strings. 12 | 13 | So after analyzing strs[1] we we that i stops at 4 cuz we reached end of 1 string so ans = "flow" note that substr(i,j) means 14 | substring from i to i+j and not to i+j+1! 15 | 16 | In the next iteration we analyze strs[2]. 17 | After following the steps mentioned above u see i breaking out at 2 itself due to mismatch. 18 | ans="fl" yielding our answer. 19 | */ 20 | string longestCommonPrefix(vector& strs) { 21 | if(strs.size()==0)return ""; 22 | string ans=strs[0]; 23 | for(string &s:strs) 24 | { 25 | int i; 26 | for(i=0;i> findLadders(string b, string e, vector& wordList) { 4 | vector> ans; 5 | unordered_map map; 6 | for(string w:wordList)map.insert({w,INT_MAX}); 7 | queue>> q; 8 | q.push({b,{b}}); 9 | map[b]=0; 10 | while(!q.empty()) 11 | { 12 | auto n=q.front(); 13 | q.pop(); 14 | string s=n.first; 15 | auto x=n.second; 16 | if(s==e) 17 | { 18 | ans.push_back(x); 19 | continue; 20 | } 21 | for(int i=0;i2->3 6 | 7 | If example u want to reverse 1->2 to 2->1.Instead of swaping the nodes we use the above pointer based approach: 8 | 9 | 1 -> 2 10 | ^ ^ ^ 11 | | | | 12 | prev curr next 13 | 14 | We carry out this method by first making 1 point to NULL. This is done by curr->next=prev and then we without the next node we will not be 15 | able to reach 2 think about it cuz our curr->next has been shifted to prev. Thats the main reason for using the next node. 16 | 17 | So after the above operation we move prev to curr and curr=next and use the above mentioned formula. 18 | 19 | */ 20 | ListNode* reverseList(ListNode* head) { 21 | if(!head)return NULL; 22 | ListNode* prev,*curr,*next; 23 | prev=NULL,curr=head; 24 | while(curr) 25 | { 26 | next=curr->next; 27 | curr->next=prev; 28 | prev=curr; 29 | curr=next; 30 | } 31 | return prev; 32 | } -------------------------------------------------------------------------------- /TREES/Path Sum III.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int ans=0; 15 | int pathSum(TreeNode* root, int sum) { 16 | if(!root)return 0; 17 | queue q; 18 | q.push(root); 19 | while(!q.empty()) 20 | { 21 | int n=q.size(); 22 | for(int i=0;ileft)q.push(t->left); 28 | if(t->right)q.push(t->right); 29 | } 30 | } 31 | return ans; 32 | } 33 | private: 34 | void helper(TreeNode* root,int sum,int curr) 35 | { 36 | if(!root)return; 37 | curr+=root->val; 38 | if(curr==sum)ans++; 39 | helper(root->left,sum,curr); 40 | helper(root->right,sum,curr); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Hash Table/Insert Delete GetRandom O(1).cpp: -------------------------------------------------------------------------------- 1 | class RandomizedSet { 2 | public: 3 | vector nums; 4 | unordered_map map; 5 | RandomizedSet() { 6 | 7 | } 8 | 9 | /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 10 | bool insert(int val) { 11 | if(map.count(val))return false; 12 | nums.push_back(val); 13 | map[val]=nums.size()-1; 14 | return true; 15 | } 16 | 17 | /** Removes a value from the set. Returns true if the set contained the specified element. */ 18 | bool remove(int val) { 19 | if(map.find(val)==map.end())return false; 20 | int last=nums.back(); 21 | map[last]=map[val]; 22 | nums[map[val]]=last; 23 | nums.pop_back(); 24 | map.erase(val); 25 | return true; 26 | } 27 | 28 | /** Get a random element from the set. */ 29 | int getRandom() { 30 | return nums[rand()%nums.size()]; 31 | } 32 | }; 33 | 34 | /** 35 | * Your RandomizedSet object will be instantiated and called as such: 36 | * RandomizedSet* obj = new RandomizedSet(); 37 | * bool param_1 = obj->insert(val); 38 | * bool param_2 = obj->remove(val); 39 | * int param_3 = obj->getRandom(); 40 | */ 41 | -------------------------------------------------------------------------------- /Dynamic Programming/718. Maximum Length of Repeated Subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is similar to the solution of common substring problem. 3 | we create a dp matrix and match the the two arrays together. 4 | 5 | Lets consider the example 6 | A: [1,2,3,2,1] 7 | B: [3,2,1,4,7] 8 | 9 | 3 2 1 4 7 10 | 0 0 0 0 0 0 11 | 1 0 0 0 1 0 0 12 | 2 0 0 1 0 0 0 <--------The logic used here is that if arr[i]==arr2[i] then dp[i][j]=1+dp[i-1][j-1] else dp[i][j]=0 13 | 3 0 1 0 0 0 0 14 | 2 0 0 2 0 0 0 15 | 1 0 0 0 3 0 0 16 | 17 | After this we traverse thru dp to check for the maximum element and that is out answer =3. 18 | */ 19 | 20 | int findLength(vector& A, vector& B) { 21 | if(A.size()==0&&B.size()==0)return true; 22 | if(A.size()==0||B.size()==0)return false; 23 | int ans=0; 24 | vector> dp(A.size()+1,vector(B.size()+1)); 25 | for(int i=1;i<=A.size();i++) 26 | { 27 | for(int j=1;j<=B.size();j++) 28 | { 29 | if(A[i-1]==B[j-1]) 30 | dp[i][j]=1+dp[i-1][j-1]; 31 | else 32 | dp[i][j]=0; 33 | ans=max(ans,dp[i][j]); 34 | } 35 | 36 | } 37 | return ans; 38 | } -------------------------------------------------------------------------------- /TREES/1273. Delete Tree Nodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A tree rooted at node 0 is given as follows: 3 | 4 | The number of nodes is nodes; 5 | The value of the i-th node is value[i]; 6 | The parent of the i-th node is parent[i]. 7 | 8 | Remove every subtree whose sum of values of nodes is zero. 9 | 10 | After doing so, return the number of nodes remaining in the tree. 11 | */ 12 | 13 | 14 | class Solution { 15 | public: 16 | vector dp; 17 | int dfs(int u,vector>& graph,vector& value) 18 | { 19 | int sum=value[u]; 20 | for(auto x:graph[u]) 21 | sum+=dfs(x,graph,value); 22 | if(sum==0)dp[u]=true; 23 | return sum; 24 | } 25 | int dfs(int u,vector>& graph) 26 | { 27 | if(dp[u])return 0; 28 | int ans=1; 29 | for(auto x:graph[u]) 30 | ans+=dfs(x,graph); 31 | return ans; 32 | } 33 | int deleteTreeNodes(int n, vector& parent, vector& value) { 34 | vector> graph(n); 35 | dp.resize(n); 36 | for(int i=0;i& cost) { 22 | for(int i=2;i>& connections) { 4 | vector> indegree(n),outdegree(n); 5 | for(auto &x:connections) 6 | { 7 | outdegree[x[0]].push_back(x[1]); 8 | indegree[x[1]].push_back(x[0]); 9 | } 10 | queue q; 11 | int ans=0; 12 | unordered_set s; 13 | s.insert(0); 14 | for(auto &x:outdegree[0]) 15 | { 16 | ans++; 17 | q.push(x); 18 | s.insert(x); 19 | } 20 | for(auto &x:indegree[0]) 21 | { 22 | q.push(x); 23 | s.insert(x); 24 | } 25 | while(!q.empty()) 26 | { 27 | int t=q.front(); 28 | q.pop(); 29 | s.insert(t); 30 | for(auto &x:outdegree[t]) 31 | { 32 | if(s.find(x)==s.end()) 33 | {ans++; 34 | q.push(x); 35 | } 36 | } 37 | for(auto &x:indegree[t]) 38 | { 39 | if(s.find(x)==s.end()){ 40 | q.push(x); 41 | } 42 | } 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /TREES/1022. Sum of Root To Leaf Binary Numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First for this question u should be able to print all paths from root to leaf 3 | Cuz only after this do we convert it to decimal and proceed 4 | I would suggest u guys to solve this first and then jump into this. 5 | https://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/ 6 | 7 | So instead of printing the solution we call a funcion called convert to decimal. 8 | Note that when u have been pushing elements into ur array the one with 0 index is ur most significant bit. 9 | 10 | So to covert it all we have to do is n=n*2+v[i] where i is from 0 to v.size()-1 11 | 12 | Code:- 13 | */ 14 | int ans=0; 15 | int convert_decimal(vector v) 16 | { 17 | int n=0; 18 | for(int i=0;i t) 23 | { 24 | if(!root)return; 25 | t.push_back(root->val); 26 | if(!root->left && !root->right)ans+=convert_decimal(t); 27 | findpath(root->left,t); 28 | findpath(root->right,t); 29 | } 30 | int sumRootToLeaf(TreeNode* root) { 31 | if(!root)return 0; 32 | vector t; 33 | findpath(root,t); 34 | return ans; 35 | } -------------------------------------------------------------------------------- /DFS/1568. Minimum Number of Days to Disconnect Island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int i,int j,vector> &grid) 4 | { 5 | if(i<0||j<0||i>=grid.size()||j>=grid[0].size()||grid[i][j]==0)return; 6 | grid[i][j]=0; 7 | dfs(i+1,j,grid); 8 | dfs(i-1,j,grid); 9 | dfs(i,j+1,grid); 10 | dfs(i,j-1,grid); 11 | } 12 | bool disconnected(vector> grid) 13 | { 14 | int count=0; 15 | for(int i=0;i1)return true; 24 | } 25 | } 26 | } 27 | return false; 28 | } 29 | int minDays(vector>& grid) { 30 | if(disconnected(grid))return 0; 31 | for(int i=0;i helper(vector arr,int sum) 4 | { 5 | unordered_map map; 6 | map[0]=-1; 7 | int s=0,index1=-1,index2=-1,min=INT_MAX; 8 | for(int i=0;i& arr, int target) { 27 | if(arr[0]==11 && target==11)return -1; 28 | vector v=helper(arr,target); 29 | if(v[0]==-1 && v[1]==-1)return -1; 30 | vector t; 31 | for(int i=0;i=v[0] && i<=v[1])continue; 34 | t.push_back(arr[i]); 35 | } 36 | vector v1=helper(t,target); 37 | if(v1[0]==-1 && v1[1]==-1)return -1; 38 | return (v[1]-v[0]+1)+(v1[1]-v1[0]+1); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /BFS/773. Sliding Puzzle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int slidingPuzzle(vector>& board) { 4 | string target="123450"; 5 | string s; 6 | unordered_set set; 7 | for(int i=0;i> dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}}; 16 | queue q; 17 | q.push(s); 18 | int ans=0; 19 | while(!q.empty()) 20 | { 21 | int n=q.size(); 22 | for(int i=0;i>& A) { 12 | priority_queue> pq; 13 | vector> dir={{1,0},{-1,0},{0,1},{0,-1}}; 14 | pq.push({A[0][0],0,0}); 15 | int n=A.size(),m=A[0].size(),ans=A[0][0]; 16 | int a; 17 | A[0][0]=-1; 18 | while(!pq.empty()) 19 | { 20 | auto [a ,i, j]=pq.top(); 21 | pq.pop(); 22 | ans=min(ans,a); 23 | if(i==n-1 && j==m-1)break; 24 | for(auto &b:dir) 25 | { 26 | int x=b[0]+i; 27 | int y=j+b[1]; 28 | if(x<0||x>=n||y<0||y>=m||A[x][y]==-1)continue; 29 | pq.push({A[x][y],x,y}); 30 | A[x][y]=-1; 31 | } 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Graph/1129. Shortest Path with Alternating Colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | using pii=pair; 4 | vector shortestAlternatingPaths(int n, vector>& red_edges, vector>& blue_edges) { 5 | vector> grr(n),grb(n); 6 | for(auto &x:red_edges) 7 | grr[x[0]].push_back(x[1]); 8 | for(auto &x:blue_edges) 9 | grb[x[0]].push_back(x[1]); 10 | vector> vis(n,vector(2,0)); 11 | queue q; 12 | q.push({0,0}); 13 | q.push({0,1}); 14 | vis[0][0]=1; 15 | vis[0][1]=1; 16 | int d=0; 17 | vector ans(n,-1); 18 | while(!q.empty()) 19 | { 20 | int len=q.size(); 21 | while(len-->0) 22 | { 23 | pii p=q.front(); 24 | q.pop(); 25 | if(ans[p.first]==-1)ans[p.first]=d; 26 | auto graph=p.second?grr:grb; 27 | int color=p.second?0:1; 28 | for(auto &x:graph[p.first]) 29 | { 30 | if(vis[x][color])continue; 31 | vis[x][color]=1; 32 | q.push({x,color}); 33 | } 34 | } 35 | d++; 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Dynamic Programming/935. Knight Dialer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This actually a pretty naive dp solution. 3 | U just implement the definition of dp and u ll get the answer. 4 | Dynamic Programming is mainly an optimization over plain recursion. We will just use it to store values in an array. 5 | By the way i wont be using recursionI found a simpler way to do it :- 6 | */ 7 | int knightDialer(int N) { 8 | if(N==1)return 10; 9 | long mod = 1000000007; 10 | vector prev(10,1),curr(10,0); 11 | while(--N) 12 | { 13 | curr[0]=(prev[4]+prev[6])%mod; //These are the possible locations i can reach from 0 14 | curr[1]=(prev[6]+prev[8])%mod; 15 | curr[2]=(prev[7]+prev[9])%mod; 16 | curr[3]=(prev[4]+prev[8])%mod; 17 | curr[4]=(prev[9]+prev[0]+prev[3])%mod; 18 | curr[6]=(prev[1]+prev[7]+prev[0])%mod; 19 | curr[7]=(prev[6]+prev[2])%mod; 20 | curr[8]=(prev[1]+prev[3])%mod; 21 | curr[9]=(prev[2]+prev[4])%mod; 22 | for(int i=0;i<10;i++)prev[i]=curr[i]; //As N keeps decrementing we update the array to keep track of the steps we take 23 | } 24 | long sum=0; 25 | for(int i=0;i<10;i++) 26 | sum=(sum+curr[i])%mod; 27 | return (int)sum; 28 | } -------------------------------------------------------------------------------- /TREES/30DayLeetCodeChallenge 30thq.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree 3 | 4 | Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 5 | 6 | We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. 7 | 8 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] 9 | Output: true 10 | Explanation: 11 | The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 12 | Other valid sequences are: 13 | 0 -> 1 -> 1 -> 0 14 | 0 -> 0 -> 0 15 | */ 16 | 17 | ANSWER: 18 | 19 | bool dfs(TreeNode* root,vector& arr,int index) 20 | { 21 | if(!root)return false; 22 | if(index==arr.size()-1 && !root->left && !root->right &&root->val==arr[index])return true; 23 | else if(indexval==arr[index]) 24 | return dfs(root->left,arr,index+1)||dfs(root->right,arr,index+1); 25 | else 26 | return false; 27 | } 28 | bool isValidSequence(TreeNode* root, vector& arr) { 29 | if(!root)return arr.size()==0; 30 | return dfs(root,arr,0); 31 | } -------------------------------------------------------------------------------- /Hash Table/1128. Number of Equivalent Domino Pairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We store the pair into hashmap and increment it wheever we encounter this. 3 | How do we store the pair? 4 | Let the pair be {a,b} where a store the minimum of the 2 and b stores the maximum of the two. 5 | 6 | Once we iterate through the map we our count value will not store n or n-1 nut will store this 7 | if n=it->second-1 8 | count+=(n)*(n+1)/2 why? 9 | because dominoes matching occurs for every domino after it so for example 10 | 11 | [1,2][1,2][1,2][1,2][2,1][2,1] 12 | 13 | here map[{1,2}] = 6 14 | but for the first 1,2 5 are matched with it 15 | for second 1,2 4 are matched with it 16 | Thus n,n-1,n-2,,,,1 = n*(n+1)/2 (Sum of natural numbers upto n) 17 | */ 18 | int numEquivDominoPairs(vector>& dominoes) { 19 | map,int> map; 20 | for(int i=0;isecond>1) 29 | { 30 | int n=it->second-1; 31 | count+=(n)*(n+1)/2; 32 | } 33 | } 34 | return count; 35 | } -------------------------------------------------------------------------------- /TREES/366. Find Leaves of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We record the depth of each of the nodes in the tree using an unordered map and according to their depths we push it into our matrix. 3 | 1 4 | / \ 5 | 2 3 6 | / \ 7 | 4 5 8 | 9 | We use a depth function that maps the node to its depth. 10 | 11 | map 12 | 1->2 13 | 2->1 14 | 3->0(because nod child nodes) 15 | 4->0 16 | 5->0 17 | 18 | Then u can use any of ur traversals and push the integer into the mapped location in the matrix. 19 | _ _ 20 | | 4 5 3 | 21 | | | 22 | | 2 | 23 | | | 24 | |_ 1 _| 25 | 26 | */ 27 | unordered_map map; 28 | vector> ans; 29 | int depth(TreeNode* root) 30 | { 31 | if(!root)return -1; 32 | map[root]=max(depth(root->left),depth(root->right))+1; 33 | return map[root]; 34 | } 35 | void build(TreeNode* root) 36 | { 37 | if(!root)return; 38 | build(root->left); 39 | ans[map[root]].push_back(root->val); 40 | build(root->right); 41 | } 42 | vector> findLeaves(TreeNode* root) { 43 | int d=depth(root); 44 | ans=vector>(d+1); 45 | build(root); 46 | return ans; 47 | } 48 | -------------------------------------------------------------------------------- /BFS/364. Nested List Weight Sum II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The solution discussed here will be BFS. 3 | We first push the vector into the queue. 4 | We keep a currsum which calculates the current sum for each level and pushed into the another queue of int. 5 | 6 | Now while calculatint the answer we add the product of the front of the queue and the q size. 7 | 8 | */ 9 | int depthSumInverse(vector& nestedList) { 10 | queue> q; 11 | queue q_final; 12 | q.push(nestedList); 13 | while(!q.empty()) 14 | { 15 | int n=q.size(); 16 | int currsum=0; 17 | for(int i=0;i p=q.front(); 20 | q.pop(); 21 | for(NestedInteger ni:p) 22 | { 23 | if(ni.isInteger()) 24 | currsum+=ni.getInteger(); 25 | else 26 | q.push(ni.getList()); 27 | } 28 | } 29 | q_final.push(currsum); 30 | } 31 | int ans=0; 32 | while(!q_final.empty()) 33 | { 34 | ans+=q_final.front()*q_final.size(); 35 | q_final.pop(); 36 | } 37 | return ans; 38 | } -------------------------------------------------------------------------------- /TREES/545. Boundary of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The algorithm to solve this is 3 | 1. print the root node val. 4 | 2. print left node vals except for leaves. 5 | 3. print the left leaves. 6 | 4. print the right leaves. 7 | 5. print the right nodes. 8 | */ 9 | vector ans; 10 | void printleft(TreeNode* root) 11 | { 12 | if(!root || (!root->left&&!root->right))return; 13 | ans.push_back(root->val); 14 | if(!root->left)printleft(root->right); 15 | else 16 | printleft(root->left); 17 | } 18 | void printleaf(TreeNode* root) 19 | { 20 | if(!root)return; 21 | printleaf(root->left); 22 | if(!root->left && !root->right)ans.push_back(root->val); 23 | printleaf(root->right); 24 | } 25 | void printright(TreeNode* root) 26 | { 27 | if(!root || (!root->left && !root->right))return; 28 | if(!root->right)printright(root->left); 29 | else printright(root->right); 30 | ans.push_back(root->val); 31 | } 32 | vector boundaryOfBinaryTree(TreeNode* root) { 33 | if(!root)return ans; 34 | ans.push_back(root->val); 35 | printleft(root->left); 36 | printleaf(root->left); 37 | printleaf(root->right); 38 | printright(root->right); 39 | return ans; 40 | } -------------------------------------------------------------------------------- /Linked Lists/24. Swap Nodes in Pairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is a pointer intensive problem. 3 | The way to crack this is to use a prev pointer and a next pointer. 4 | 5 | Let head = 1->2->3->4 6 | 1 -> 2 -> 3 -> 4 7 | ^ ^ 8 | | | 9 | p c 10 | 11 | now we want to swap 1 and 2. 12 | so we make p->next to point to 2(making 2 the first member) 13 | then we make c->next = c->next->next 14 | Now the only problem is 2 should connect to 1. 15 | p>next=2 so p->next->next=c and c=c->next 16 | 17 | thus we have swapped 2 and 1 18 | 19 | 2 -> 1 -> 3 -> 4 20 | ^ ^ 21 | | | 22 | p c 23 | We perform the same procedure which swaps 3 and 4. 24 | 25 | 2->1->4->3 26 | 27 | */ 28 | ListNode* swapPairs(ListNode* head) { 29 | if(!head || !head->next)return head; 30 | ListNode* newhead=new ListNode(0); 31 | newhead->next=head; 32 | ListNode* prev=newhead,*curr=head; 33 | while(curr&&curr->next) //<--------------- because if curr->next is NULL and curr->next=curr->next->next will throw an error. 34 | { 35 | prev->next=curr->next; 36 | curr->next=curr->next->next; 37 | prev->next->next=curr; 38 | prev=curr; 39 | curr=curr->next; 40 | } 41 | return newhead->next; 42 | } -------------------------------------------------------------------------------- /Strings/415. Add Strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | I would suggest u to use this method as it will help u int the question (2. Add two numbers) which is a must do interview question. 3 | How we are going to do this is that we will reverse the strings and will propagate carry from left to right as this would be easy to implement. 4 | 5 | num1 = "23" 6 | num2 = "37" 7 | 8 | after reversing 9 | num1 = "32" 10 | num2 = "73" 11 | 12 | we add 3 and 10 and mod it with 10 and propagate (sum/10) to the right so here (7+3)%10 and propaget 1(10/10) to the left 13 | */ 14 | string addStrings(string num1, string num2) { 15 | if(num1.size()==0&&num2.size()==0)return ""; 16 | if(num1.size()==0)return num2; 17 | if(num2.size()==0)return num1; 18 | reverse(num1.begin(),num1.end()); 19 | reverse(num2.begin(),num2.end()); 20 | string ans; 21 | int i=0,carry=0; 22 | while(i& bank) { 2 | vector dir={'A','C','G','T'}; 3 | unordered_set s(bank.begin(),bank.end()); //help us with find and erase for a gene 4 | queue q; 5 | q.push(start); 6 | int count=0; 7 | s.erase(start); //if start is present in the set we erase to avoid looping 8 | while(!q.empty()) 9 | { 10 | int n=q.size(); 11 | for(int i=0;i end2 or start2 > end1. 12 | */ 13 | 14 | 15 | class Solution { 16 | public: 17 | vector minAvailableDuration(vector>& slots1, vector>& slots2, int duration) { 18 | sort(slots1.begin(),slots1.end()); 19 | sort(slots2.begin(),slots2.end()); 20 | vector ans; 21 | int i=0,j=0; 22 | while(i=duration)return {low,low+duration}; 26 | if(high==slots1[i][1])i++; 27 | else j++; 28 | } 29 | return {}; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Dynamic Programming/45. Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The approach we ll be taking is DP. 3 | Remainder: This is an O(n^2) solution. 4 | Like any other tyical DP question we ask ourselves at the currnt index how many minimum jumps did i take to get here. 5 | I will be creating a dp array where the ith location denoted the minimum jumps i took to get there. 6 | lets assum 7 | nums = [2,3,1,1,4] 8 | index = [0,1,2,3,4] 9 | 10 | At the initial position the minimum jumps taken to reach there would be 0. 11 | Thus this will be our base case. 12 | For the next case: 13 | now we check if 2+0>=i(1) which is true then 14 | dp[i] = min(dp[i],dp[j]+1) (Note that dp will be holding mximum values at the beginning) 15 | = 1 16 | thus dp = [0,1] 17 | 18 | dp = [0,1,1] (first index jump) 19 | dp = [0,1,1,2] (second index jump) 20 | dp = [0,1,1,2,2] (second index jump) 21 | 22 | thus 2 is our final answer! 23 | */ 24 | int jump(vector& nums) { 25 | vector dp(nums.size(),INT_MAX); 26 | dp[0]=0; 27 | for(int i=1;i=i) 32 | { 33 | dp[i]=min(dp[i],dp[j]+1); 34 | } 35 | } 36 | } 37 | return dp[nums.size()-1]; 38 | } -------------------------------------------------------------------------------- /Dynamic Programming/85. Maximal Rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int max_area=-1; 4 | void find(vector arr) 5 | { 6 | if(arr.size()<1)return; 7 | stack st; 8 | int area,top,i=0; 9 | while(i=arr[st.top()]) 12 | st.push(i++); 13 | else 14 | { 15 | top=st.top(); 16 | st.pop(); 17 | area=arr[top]*(st.empty()?i:i-st.top()-1); 18 | max_area=max(max_area,area); 19 | } 20 | } 21 | while(!st.empty()) 22 | { 23 | top=st.top(); 24 | st.pop(); 25 | area=arr[top]*(st.empty()?i:i-st.top()-1); 26 | max_area=max(max_area,area); 27 | } 28 | } 29 | int maximalRectangle(vector>& matrix) { 30 | if(matrix.size()<1)return 0; 31 | int n=matrix.size(),m=matrix[0].size(); 32 | vector t(m,0); 33 | for(int i=0;i1+4=1*4=4 8 | 1*2*2=4(4 is split at two 2s) 9 | 2+3 =2*3 =6 10 | 2+2+1=2*2*1=4 11 | 1+1+3=3*1*1=3 12 | Thus the maximum is 6. 13 | Now how do we code this algorithm? 14 | we create a dp matrix that says at ith state the best possible product is dp[i] with an exception of 2! 15 | 16 | 17 | int integerBreak(int n) { 18 | vector dp(n+1); 19 | dp[1]=1; 20 | dp[2]=2; 21 | int maxans=0; 22 | for(int i=3;i<=n;i++) 23 | { 24 | for(int j=1;j map; 21 | int l=0,r=0,ans=0; 22 | while(l<=r&&r &a,const vector&b) //<-----This is how we sort 2d matrices. 20 | { 21 | return a[0]>& interval) { 25 | if(interval.size()<=1)return true; 26 | sort(interval.begin(),interval.end(),compare); 27 | for(int i=1;i 1 15 | 1 1 -> 1 16 | 3 3 -> 2 as(3-3 = 0 is present in the map) count=1 17 | 6 6 -> 3 as(6-3 = 3 is present in the map) count=2 18 | 11 11 -> 1 19 | 17 17 -> 1 20 | 14 14 -> 1 as(14-3=11 is present in the map) count=3 21 | 22 | thus the count is 3. 23 | */ 24 | 25 | int subarraySum(vector& nums, int k) { 26 | unordered_map map{{0,1}}; 27 | int sum=0,count=0; 28 | for(int x:nums) 29 | { 30 | sum+=x; 31 | count+=map[sum-k]; 32 | map[sum]++; 33 | } 34 | return count; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Array/41. First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to be tackling the problem is to make all the elements from 1 to n wich are present in the array to be in their respective locations(ie i-1) 3 | Like if we have the array [0,2,1] 4 | we want nums[i] to be placed at i-1th location: 5 | [1,2,0] 6 | So to do this we will first traverse through the array and check if nums[i]=i+1 then we cana proceed if not swap it with the element 7 | present at its location. 8 | But a problem would arise due to this: 9 | [7,8,9,11] there is no location 6 in this array thus throwing an error. 10 | So lets revise our conditions 11 | if nums[i]==i+1 or if nums[i]>nums.size() i++ 12 | but again what if 0 or a negative number is present in an array there are no negative locations right? 13 | So if nums[i] =i+1 or if nums[i]>nums.size() or if nums[i]<=0 just ignore that element and proceed. 14 | */ 15 | After taking care of all these caviats we can finally try to simply traverse the array and if nums[i]!=i+1 i+1 would be our answer. 16 | 17 | int firstMissingPositive(vector& nums) { 18 | int i=0; 19 | while(inums.size())i++; 22 | else if(nums[i]!=nums[nums[i]-1])swap(nums[i],nums[nums[i]-1]); 23 | else i++; 24 | } 25 | i=0; 26 | while(i ans=maxleft-left[i] and increment left pointer. 9 | 6. if 3. fails that means there is a potential of storing water in the right side. 10 | 7.If the height[right] is greater than maxright update maxright and move the pointer backward. 11 | 8. If its lesser ans=maxright-height[i]. 12 | */ 13 | int trap(vector& height) { 14 | int ans=0,left=0,right=height.size()-1; 15 | int maxleft=0,maxright=0; 16 | while(leftmaxleft)maxleft=height[left]; 21 | else ans+=maxleft-height[left]; 22 | left++; 23 | } 24 | else 25 | { 26 | if(height[right]>maxright)maxright=height[right]; 27 | else 28 | ans+=maxright-height[right]; 29 | right--; 30 | } 31 | } 32 | return ans; 33 | } -------------------------------------------------------------------------------- /DFS/323. Number of Connected Components in an Undirected Graph.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to solve this question is first build a graph:- 3 | vector> graph(n); 4 | int ans=0; //I use an adjacency list u can use whatever u want 5 | for(auto x:edges) 6 | { 7 | graph[x[0]].push_back(x[1]); 8 | graph[x[1]].push_back(x[0]); 9 | } 10 | After building a graph our main focus is to vist all the neighbours of all the nodes in the graph and more importantly to not visit them multiple 11 | times. 12 | We can do this by doing a dfs and a bool matrix which keeps tracks of the visited nodes so that we donot visit them again:- 13 | */ 14 | void dfs(vector> &graph,vector &vis,int i) 15 | { 16 | if(vis[i])return; 17 | vis[i]=true; 18 | for(auto x:graph[i]) 19 | dfs(graph,vis,x); 20 | } 21 | int countComponents(int n, vector>& edges) { 22 | vector> graph(n); 23 | int ans=0; 24 | for(auto x:edges) 25 | { 26 | graph[x[0]].push_back(x[1]); 27 | graph[x[1]].push_back(x[0]); 28 | } 29 | vector vis(n,false); 30 | for(int i=0;i &ans) 12 | { 13 | if(open<0)return; //<-----checks for validity of the sequence 14 | if(i==n) 15 | { 16 | if(open==0)ans.push_back(s); // <-----checks all the boxes so its a valid sequence. 17 | return; 18 | } 19 | backtrack(n,i+1,open+1,s+'(',ans); 20 | backtrack(n,i+1,open-1,s+')',ans); 21 | } 22 | vector generateParenthesis(int n) { 23 | vector ans; 24 | if(n==0)return ans; 25 | backtrack(2*n,0,0,"",ans); //<-------total string size must be 2*n n for opening braces + n for closing braces. 26 | return ans; 27 | } -------------------------------------------------------------------------------- /MATH/263.Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | /*The intuition that first comes to our minds is that if(num%2==0||num%3==0||num%5==0)return true 2 | Well this might pass some test cases but it is absolutely wrong. 3 | let me demonstrate: 4 | Let num=14; 5 | its prime factors are:1,2,7,14 6 | but the questions says apart from 1 and the number itself only 2,3,5 are allowed 7 | So how do we tackle this problem? 8 | We try to keep dividing the by 2 as long as the number is divisble by 2 9 | Then with the current number we keep dividing by 3 as long as its divisble by 3 10 | similarly for 5. 11 | If the final number that we get is 1 then we have got the result. 12 | Let me demonstrate: 13 | Let us take the same number 14 | num=14<-----divisible by 2 so keep dividing 15 | 14/2=7<-----not divisible by 2 so stop 16 | 7<----------not divisble by 3 so stop 17 | 7<----------not divisble by 5 so stop 18 | the final answer we got is 7 which is not equal to 1 so return false. 19 | Lets take another example 20 | num=30<-----divisble by 2 so keep dividing by 2 21 | num=15<-----not divisible by 2 so stop 22 | num=15<-----divisble by 3 so keep dividing by 3 23 | num=5<------not divisible by 3 so stop 24 | num=5<------divisble by 5 so keep dividing by 5 25 | num=1<------not divisible by 5 so stop 26 | as 1==1 return true 27 | */ 28 | bool isUgly(int num) { 29 | if(num==0)return false;//<-----0 is neither divisble by 2,3 nor 5 30 | while(num%2==0)num/=2; 31 | while(num%3==0)num/=3; 32 | while(num%5==0)num/=5; 33 | return num==1; 34 | } 35 | -------------------------------------------------------------------------------- /Strings/468. Validate IP Address.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector split(string s,char ch) 4 | { 5 | vector ans; 6 | string block; 7 | istringstream iss(s); 8 | while(getline(iss,block,ch)) 9 | ans.push_back(block); 10 | return ans; 11 | } 12 | bool isvalidIPv6(string s) 13 | { 14 | if(count(s.begin(),s.end(),':')!=7)return false; 15 | vector parts=split(s,':'); 16 | if(parts.size()!=8)return false; 17 | for(string &str:parts) 18 | { 19 | if(str.size()>4||str.empty())return false; 20 | for(char ch:str) 21 | { 22 | if(!isdigit(ch) && (!isalpha(ch) || toupper(ch)>'F'))return false; 23 | } 24 | 25 | } 26 | return true; 27 | } 28 | bool isvalidIPv4(string s) 29 | { 30 | if(count(s.begin(),s.end(),'.')!=3)return false; 31 | vector parts=split(s,'.'); 32 | if(parts.size()!=4)return false; 33 | for(string &str:parts) 34 | { 35 | if(str.size()>3||(str.size()>1 &&str[0]=='0')||str.empty()) 36 | return false; 37 | for(char ch:str) 38 | if(!isdigit(ch))return false; 39 | if(stoi(str)>255)return false; 40 | } 41 | return true; 42 | } 43 | string validIPAddress(string IP) { 44 | return isvalidIPv4(IP)?"IPv4":(isvalidIPv6(IP)?"IPv6":"Neither"); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Design/716. Max Stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Here the only problem that you will be facing is popmax: 3 | To tackle this we follow this algorithm: 4 | 1. We find the maxstack top in our normal stack, 5 | 2.When we find that element we pop that element from both the stack. 6 | 3.We used a temp stack which pushed elements which were not the maxstack top. 7 | 4 While we use the push the temp stack elements back to the normal stack we push it into macstack if it empty or if the element is greater than top to maxstack. 8 | */ 9 | stack s1,s2; 10 | void add (int x) 11 | { 12 | if(s2.empty()||x>=s2.top())s2.push(x); 13 | } 14 | MaxStack() { 15 | 16 | } 17 | 18 | void push(int x) { 19 | s1.push(x); 20 | add(x); 21 | } 22 | 23 | int pop() { 24 | int x=s1.top(); 25 | s1.pop(); 26 | if(s2.top()==x)s2.pop(); 27 | return x; 28 | } 29 | 30 | int top() { 31 | return s1.top(); 32 | } 33 | 34 | int peekMax() { 35 | return s2.top(); 36 | } 37 | 38 | int popMax() { 39 | int x=s2.top(); 40 | stack t; 41 | while(s1.top()!=s2.top()) 42 | { 43 | t.push(s1.top()); 44 | s1.pop(); 45 | } 46 | s2.pop(); 47 | s1.pop(); 48 | while(!t.empty()) 49 | { 50 | s1.push(t.top()); 51 | add(t.top()); 52 | t.pop(); 53 | } 54 | return x; 55 | } -------------------------------------------------------------------------------- /Dynamic Programming/55. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is can be solved in many ways. The approach i will be taking is greedy. Reason being i can bring down the time complexity 3 | to o(n). 4 | Approach: 5 | 6 | nums = 2 3 1 1 4 7 | indices--> 0 1 2 3 4 8 | 9 | I ll keep picking the best solution i have at my current position.(definition of greedy). 10 | 11 | let me have a variable lets say jump that records my greedy chice i have taken. 12 | At index 0 my greedy choice would be to obviously take the current element 13 | jump=nums[i]+i=2+0 = 2 14 | Now i move on to the index and pick the better one among the 2. 15 | Since jump = nums[i]+i = 4>2 i will greedily pick this element. 16 | Now i have i go to the next index = 2 17 | jump = nums[i]+i = 30 1 2 3 4 26 | 27 | here jump will take value 1+0 =1 initially. 28 | Then it takes 1+1=2 . 29 | At index 2 it sticks with the original value of jump. 30 | Finally when it reaches index 3 the jump value& nums) { 33 | int jump=0; 34 | for(int i=0;i &parent) 14 | { 15 | return parent[x]==x?x:find(parent[x],parent); 16 | } 17 | int makeConnected(int n, vector>& connections) { 18 | vector groups(n); 19 | for(int i=0;i=components-1)?components-1:-1; 35 | } -------------------------------------------------------------------------------- /DFS/339. Nested List Weight Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | If the element is an integer we and th product of that integer and depth. 3 | Else we do do dfs with an incremented depth by calling the List function. 4 | 5 | eg:-[1,[4,[6]]] 6 | Intinially I call a dfs function with vector and depth=1. 7 | As the element is an integer we just add the product of the integer with depth. 8 | sum=1 9 | 10 | As the second element is a List we will call the List function dfs(nestedList[i].getList(),depth+1) 11 | 12 | | | 13 | | | 14 | | | <------recursion Stack 15 | |[4,[6]]| 16 | 17 | We start by checking if the first element is an integer as it is an Integer we add it to our sum 18 | 19 | sum = sum + integer*depth = 1+4*2=9 20 | 21 | As the second element is a list we call dfs 22 | 23 | | | 24 | | | 25 | | [6] | <------recursion Stack 26 | |[4,[6]]| 27 | 28 | We start by checking if the first element is an integer as it is an Integer we add it to our sum 29 | 30 | sum = sum + integer*depth =9 + 6*3=27 31 | 32 | */ 33 | 34 | int dfs(vector& nestedList,int depth) 35 | { 36 | int n=nestedList.size(),sum=0; 37 | for(int i=0;i& nestedList) { 47 | return dfs(nestedList,1); 48 | } -------------------------------------------------------------------------------- /HEAP/692. Top K Frequent Words.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We will be using minheap as it is more space optimized. 3 | The idea is to store the top k frequent words in a minheap that means the most frequent word will be at the end of the minheap(leaf of the tree). 4 | we have to build a heap such a way that it stores the frequency of the string as well as the string itself. 5 | */ 6 | struct comp 7 | { 8 | bool operator()(const pair &a,const pair &b) 9 | { 10 | if(a.first!=b.first) 11 | return a.first>b.first; 12 | else 13 | return a.second topKFrequent(vector& words, int k) { 17 | unordered_map map; 18 | priority_queue,vector>, comp> pq; 19 | vector ans(k); 20 | for(string &w:words) 21 | map[w]++; 22 | for(auto it=map.begin();it!=map.end();it++) 23 | { 24 | if(pq.size()second,it->first}); 26 | else 27 | { 28 | if(pq.top().firstsecond||(pq.top().first==it->second && pq.top().second>it->first)) 29 | { 30 | pq.pop(); 31 | pq.push({it->second,it->first}); 32 | } 33 | } 34 | } 35 | while(!pq.empty()) 36 | { 37 | ans[--k]=pq.top().second; 38 | pq.pop(); 39 | } 40 | return ans; 41 | } -------------------------------------------------------------------------------- /MATH/976. Largest Perimeter Triangle. Largest Perimeter Triangle.cpp: -------------------------------------------------------------------------------- 1 | /*Lets learn the basics of triangle 2 | according to the triangle inequality 3 | for a triangle to exist->sum of lengths of two sides must be greater than the 3rd side. 4 | NOTE:It will be equal to the 3rd side when the area is 0. 5 | /\ 6 | 4 / \ 3 7 | / \ 8 | ------ 9 | 5 10 | in this case sum of any two sides is greater than or equal to the 3rd side. 11 | Thus as we get want the largest area the last 3 sides of the array would give us thee answer 12 | provided it follows the inequality property. 13 | so what we do is sort it in the decreasing order and take 3 elements and check for the inequality. 14 | let me demonstrate 15 | Input: [3,6,2,3] 16 | we sort it first in decreasing order 17 | [6,3,3,2] 18 | we keep taking 3 elements from the start and keep checking 19 | as soon as it satisfies we break from the loop and return the answer. 20 | here the first 3 elements are [6,3,3] 21 | but 3+3=6 which is a triangle with 0 area so it is discarded. 22 | next is [3,3,2] which satisfies the inequality. 23 | thus the perimeter is 3+3+2=9 24 | */ 25 | int largestPerimeter(vector& A) { 26 | if(A.size()<3)return 0; 27 | int per=0; 28 | sort(A.rbegin(),A.rend()); 29 | for(int i=0;i=A[i+1]+A[i+2])continue; 32 | else 33 | { 34 | per=A[i]+A[i+1]+A[i+2]; 35 | break; 36 | } 37 | } 38 | return per; 39 | } 40 | -------------------------------------------------------------------------------- /Strings/6. ZigZag Conversion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | All we have to do in this problem is to go down up down up... 3 | we maintain a bool variable that flips its states once i is at 0 or at numRows-1. 4 | We simulatneously add to vector array conatining string and later tranfer it to a string. 5 | We are mimicing the question as it is. 6 | 7 | s = "PAYPALISHIRING", numRows = 3 8 | Lets maintain a vector of size numRows. 9 | Let my bool variable say goingdown=false initially. 10 | we add 'P' to the first row. 11 | we add 'A' to the second row. 12 | we add 'Y' to the third row. 13 | as we reached the end of the row we flip the state of goingdown. So no we move up. 14 | [P] 15 | [AP] 16 | [Y] 17 | We go to the 1st row 18 | [PA] 19 | [AP] 20 | [Y] 21 | now as we reached 0th row we flip the state of goingdown(ie goingdown = true). 22 | [PA] 23 | [APL] 24 | [Y] 25 | if we continuously do this we reach the final desired state 26 | [PAHN] 27 | [APLSIIG] 28 | [YIR] 29 | Now we use an auxiliary string that adds the string row wise yielding the final answer. 30 | */ 31 | string convert(string s, int numRows) { 32 | if(s.size()==0)return s; 33 | if(numRows==1)return s; 34 | vector ans(min(numRows, int(s.size()))); 35 | int curr=0; 36 | bool goingdown=false; 37 | for(char &ch:s) 38 | { 39 | ans[curr]+=ch; 40 | if(curr==0||curr==numRows-1)goingdown=!goingdown; 41 | curr+=(goingdown)?1:-1; 42 | } 43 | string res=""; 44 | for(string &s1:ans)res+=s1; 45 | return res; 46 | } 47 | -------------------------------------------------------------------------------- /Dynamic Programming/1143. Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Always use a dp table to solve questions related to dp. 3 | Although it might not yield the most optimal solution (usually o(n^2)) it can be used to understand dp well for beginners. 4 | Here in my dp table the ith row signifies what is maximum susbesquence length that i got gained so far. 5 | In order to get such an answer lets try to device our logic as such: 6 | if my string characters match i will take dp[i-1][j-1] + 1 (Since we are trying to match characters by characters) 7 | if not take the maximum of dp[i-1][j] &&dp[i][j-1].Why? 8 | Becasue we are trying to find the longest subsequence and not substring.S we will have to keep propagating the maximum length of the 9 | Commom subsequence throughout the dp array in order to yield out final answer. 10 | Let 11 | text1 = "abcde", text2 = "ace" . 12 | 13 | 0 a c e 14 | 0 0 0 0 0 15 | a 0 1 1 1 16 | b 0 1 1 1 17 | c 0 1 2 2 18 | d 0 1 2 2 19 | e 0 1 2 3 20 | 21 | thus the final answer is dp[text1.length()][text2.length()]. 22 | */ 23 | int longestCommonSubsequence(string text1, string text2) { 24 | vector> dp(text1.size()+1,vector(text2.size()+1)); 25 | for(int i=1;i<=text1.size();i++) 26 | { 27 | for(int j=1;j<=text2.size();j++) 28 | { 29 | if(text1[i-1]==text2[j-1]) 30 | dp[i][j] = 1+dp[i-1][j-1]; 31 | else 32 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 33 | } 34 | } 35 | return dp[text1.size()][text2.size()]; 36 | } -------------------------------------------------------------------------------- /TREES/285. Inorder Successor in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We tackle this problem just by doing a simple traversal by using a while loop. 3 | Binary seach trees are formed in such a way such that left child will hold a value lesser than parent and right child will hold value 4 | greater than parent. 5 | We use a while loop to traverse the BST due to the above property. 6 | If root->val <= p->val move root to its right child as the right child is greater. 7 | Else we store succ as root and keep proceeding to the left hild as we want the minimum element greater than p->val. 8 | 9 | root = [5,3,6,2,4,null,null,1], p = 4 10 | 11 | 5 <----root 12 | /\ 13 | 3 6 14 | / \ 15 | 2 4 16 | / 17 | 1 18 | root->val>root->left thus we store succ as 5 19 | 20 | we move root->left 21 | 22 | 5 <----root 23 | /\ 24 | root--> 3 6 25 | / \ 26 | 2 4 27 | / 28 | 1 29 | As root->valval we move to root->right which is 4 so we again move right which is NULL. 30 | 31 | Thus suc=5 will be the final answer. 32 | 33 | */ 34 | TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { 35 | if(!root||!p)return NULL; 36 | TreeNode* suc=NULL; 37 | while(root) 38 | { 39 | if(root->val<=p->val) 40 | { 41 | root=root->right; 42 | } 43 | else 44 | { 45 | suc=root; 46 | root=root->left; 47 | } 48 | } 49 | return suc; 50 | } -------------------------------------------------------------------------------- /Array/88. Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to think about the solution is that we will have to do a reverse sorting. 3 | We initialize k=m+n-1 as that will be the last location of nums1. 4 | We will keep checking for the greater element of the two arrays(i=m-1,j=n-1) and insert the values. 5 | nums1 = [1,2,3,0,0,0], m = 3 6 | nums2 = [2,5,6], n = 3 7 | 8 | nums1 = [1,2,3,0,0,0] 9 | | | 10 | i k 11 | 12 | nums2 = [2,5,6] 13 | | 14 | j 15 | nums2[j]>nums1[i] thus nums1[k]=6 16 | k and j are decremented. 17 | 18 | nums1 = [1,2,3,0,0,6] 19 | | | 20 | i k 21 | 22 | nums2 = [2,5,6] 23 | | 24 | j 25 | nums2[j]>nums1[i] thus nums1[k]=5 26 | k and j are decremented. 27 | 28 | nums1 = [1,2,3,0,5,6] 29 | | | 30 | i k 31 | 32 | nums2 = [2,5,6] 33 | | 34 | j 35 | We keep following up this procedure and we get the desired reult. 36 | */ 37 | void merge(vector& nums1, int m, vector& nums2, int n) { 38 | int i=m-1,j=n-1,k=m+n-1; 39 | while(i>=0&&j>=0) 40 | { 41 | if(nums1[i]>nums2[j]) 42 | { 43 | nums1[k]=nums1[i]; 44 | i--; 45 | k--; 46 | } 47 | else 48 | { 49 | nums1[k]=nums2[j]; 50 | j--; 51 | k--; 52 | } 53 | } 54 | while(i>=0) 55 | nums1[k--]=nums1[i--]; 56 | while(j>=0) 57 | nums1[k--]=nums2[j--]; 58 | } -------------------------------------------------------------------------------- /BFS/127. Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | I will using bfs and brute force solution. 3 | This solution was suprisingly fast. 4 | We are going to do our standard bfs traversal :- 5 | First I store the wordlist in a set. 6 | We push the begin word into the queue and start traversing. 7 | I start process the string present in a queue and i check if i remove one letter from that string is it present on the set or not. 8 | If so i push the word into the queue and delete the word from the set so that i don visit it again. 9 | I do this until i reach the end word. 10 | If i dont i return 0. 11 | */ 12 | int ladderLength(string b, string e, vector& wordList) { 13 | unordered_set s(wordList.begin(),wordList.end()); 14 | queue q; 15 | q.push(b); 16 | int count=0; 17 | s.erase(b); 18 | while(!q.empty()) 19 | { 20 | int n=q.size(); 21 | count++; 22 | for(int i=0;i restoreIpAddresses(string s) { 4 | vector ans; 5 | string temp; 6 | for(int a=1;a<=3;a++) 7 | for(int b=1;b<=3;b++) 8 | for(int c=1;c<=3;c++) 9 | for(int d=1;d<=3;d++) 10 | { 11 | if(a+b+c+d==s.length()) 12 | { 13 | int A=stoi(s.substr(0,a)); 14 | int B=stoi(s.substr(a,b)); 15 | int C=stoi(s.substr(a+b,c)); 16 | int D=stoi(s.substr(a+b+c,d)); 17 | if(A<=255 && B<=255 && C<=255 && D<=255) 18 | if((temp=to_string(A)+'.'+to_string(B)+'.'+to_string(C)+'.'+to_string(D)).length()==s.length()+3) 19 | ans.push_back(temp); 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | 26 | 27 | class Solution { 28 | public: 29 | vector ans; 30 | void dfs(string s,int index,string path,int count) 31 | { 32 | if(count>4)return; 33 | if(count==4 && index>=s.length()) 34 | { 35 | path.pop_back(); 36 | ans.push_back(path); 37 | return; 38 | } 39 | for(int i=1;i<4 && index+i<=s.length();i++) 40 | { 41 | string t=s.substr(index,i); 42 | if((i!=1 && t[0]=='0')||(stoi(t)>=256))continue; 43 | dfs(s,index+i,path+t+'.',count+1); 44 | 45 | } 46 | } 47 | vector restoreIpAddresses(string s) { 48 | dfs(s,0,"",0); 49 | return ans; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Graph/1443. Minimum Time to Collect All Apples in a Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To visit a node from a parent the cost is 2. Because I visit the node and backtrack which is considered to the cost. 3 | 4 | I have to count only the cost of collecting the apples present in the nodes and not count unnecessary nodes. 5 | How do we do that? 6 | 7 | We use a dfs finction to help us with that. 8 | We have 5 parameters 9 | 1. A build graph adjacncy list 10 | 2. A vector bool array to help us not visit a node multiple times 11 | 3. A node which is passed as 0 initially. 12 | 4. Cost variable which will be 2 more that the previous one because of the fact i told about earlier 13 | 5. hasApple array. 14 | 15 | The dfs will help us with finding the cost by the following method:- 16 | 17 | 1. If I find out that atleast one of my children have nodes i return the cost and the children cost to the call stack. 18 | 2. If I find out that none of the children contains apples we return 0. 19 | */ 20 | vector vis; 21 | int dfs(vector> &graph,vector& hasApple,int node,int cost) 22 | { 23 | if(vis[node])return 0; 24 | vis[node]=true; 25 | int children_cost=0; 26 | for(auto x:graph[node]) 27 | children_cost+=dfs(graph,hasApple,x,2); 28 | if(children_cost==0 && hasApple[node]==false)return 0; 29 | return (children_cost+cost); 30 | } 31 | int minTime(int n, vector>& edges, vector& hasApple) { 32 | vector> graph(n); 33 | vis=vector(n,false); 34 | for(auto &x:edges) 35 | { 36 | graph[x[0]].push_back(x[1]); 37 | graph[x[1]].push_back(x[0]); 38 | } 39 | return dfs(graph,hasApple,0,0); 40 | } -------------------------------------------------------------------------------- /TREES/993. Cousins in Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The question asks for x and y who have different parents and same depth. 3 | My answer would be a bfs. 4 | We use two maps to solve the problem; One for storing the prent of x and y 5 | The pther for stroing the depth of x and y 6 | Finally if the first map values are unequal and the second map values are equal we return true. 7 | */ 8 | 9 | bool isCousins(TreeNode* root, int x, int y) { 10 | unordered_map map; 11 | map[x]=root; 12 | map[y]=root; 13 | queue q; 14 | q.push(root); 15 | while(!q.empty()) 16 | { 17 | TreeNode* t=q.front(); 18 | q.pop(); 19 | if(t->left) 20 | { 21 | if(t->left->val==x)map[x]=t; 22 | else if(t->left->val==y)map[y]=t; 23 | q.push(t->left); 24 | } 25 | if(t->right) 26 | { 27 | if(t->right->val==x)map[x]=t; 28 | else if(t->right->val==y)map[y]=t; 29 | q.push(t->right); 30 | } 31 | } 32 | unordered_map map1; 33 | int level=0; 34 | q.push(root); 35 | while(!q.empty()) 36 | { 37 | int n=q.size(); 38 | level++; 39 | for(int i=0;ival==x)map1[x]=level; 44 | else if(t->val==y)map1[y]=level; 45 | if(t->left)q.push(t->left); 46 | if(t->right)q.push(t->right); 47 | } 48 | } 49 | return map[x]!=map[y]&&map1[x]==map1[y]; 50 | } -------------------------------------------------------------------------------- /Graph/329. Longest Increasing Path in a Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestIncreasingPath(vector>& matrix) { 4 | if(matrix.size()==0)return 0; 5 | vector> dir={{0,1},{0,-1},{1,0},{-1,0}}; 6 | int n=matrix.size(),m=matrix[0].size(); 7 | vector> indegree(n,vector(m,0)); 8 | for(int i=0;i=0 && ny>=0 && nxmatrix[i][j]) 19 | indegree[i][j]++; 20 | } 21 | } 22 | } 23 | } 24 | queue> q; 25 | for(int i=0;i p=q.front(); 35 | q.pop(); 36 | for(auto &x:dir) 37 | { 38 | int nx=p.first+x[0]; 39 | int ny=p.second+x[1]; 40 | if(nx>=0 && ny>=0 && nx productExceptSelf(vector& nums) { 32 | vector ans; 33 | if(nums.size()==0)return ans; 34 | vector left(nums.size()); 35 | vector right(nums.size()); 36 | left[0]=1,right[nums.size()-1]=1; 37 | for(int i=1;i=0;i--) 40 | right[i]=nums[i+1]*right[i+1]; 41 | for(int i=0;i>mp; 3 | vectorleaves; 4 | int ans = 0; 5 | 6 | void storeLeaves(TreeNode* root) { 7 | if (!root) return; 8 | storeLeaves(root->left); 9 | if (!root->left && !root->right) 10 | leaves.push_back(root); 11 | if (root->left) { 12 | mp[root].push_back(root->left); 13 | mp[root->left].push_back(root); 14 | } 15 | if (root->right) { 16 | mp[root].push_back(root->right); 17 | mp[root->right].push_back(root); 18 | } 19 | storeLeaves(root->right); 20 | } 21 | 22 | void bfs(TreeNode* v, int distance) { 23 | queueq; 24 | q.push(v); 25 | int dist = 0; 26 | 27 | unordered_mapvisited; 28 | 29 | while (!q.empty()) { 30 | int size = q.size(); 31 | for (int i = 0; i < size; i++) { 32 | TreeNode* node = q.front(); 33 | q.pop(); 34 | if (visited[node]) continue; 35 | if (node != v && !node->left && !node->right) 36 | ans++; 37 | visited[node] = true; 38 | for (auto j = 0; j < mp[node].size(); j++) 39 | q.push(mp[node][j]); 40 | } 41 | dist++; 42 | if (dist > distance) return; 43 | } 44 | } 45 | 46 | public: 47 | int countPairs(TreeNode* root, int distance) { 48 | if (!root) return 0; 49 | storeLeaves(root); 50 | for (int i = 0; i < leaves.size(); i++) 51 | bfs(leaves[i], distance); 52 | return ans/2; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /HEAP/703. Kth Largest Element in a Stream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is a typicaly heap question.The biggere question is what heap do we use/ 3 | While both heaps would yield the correct answer we want to produce an anwer with the brtter complexity. 4 | The answer would be a minheap 5 | 6 | Let num = [3,4,5,10,2] k=3 7 | 8 | | 3 | 9 | | 4 | <---------This would be the minheap after storing the first 3 element in it with the smallest elemeyt at the top. 10 | |__5__| 11 | Now the what we do is our main goal is to make the kth larget element at the top of the heap so extraction takes o(1)time excluding the heapify time. 12 | 13 | We would build the heap by storing the larget k numbers in the heao with the smallest of them at the top yielding the kth 14 | largest number. 15 | 16 | | 4 | 17 | | 5 | <---------as 10 was greater than the top of the heap (i.e 3) we popped it and stored 10 in it. 18 | |__10_| 19 | Remember Our Goal here is the store the k largest elements into the heap. 20 | 21 | | 4 | 22 | | 5 | <---------as 2 wasnt greater than heap.top() we just dont do anything. 23 | |__10_| 24 | 25 | Thus our final answer is heap.top() -> 4. 26 | */ 27 | priority_queue,greater> minheap; 28 | int m_k; 29 | KthLargest(int k, vector& nums) { 30 | m_k=k; 31 | for(int x:nums)add(x); 32 | } 33 | 34 | int add(int val) { 35 | if(minheap.size()minheap.top()) 39 | { 40 | minheap.pop(); 41 | minheap.push(val); 42 | } 43 | } 44 | return minheap.top(); 45 | } 46 | -------------------------------------------------------------------------------- /TREES/class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { unordered_map map; map[root]=NULL; queue q1; q1.push(root); while(!map.count(p)||!map.count(q)) { TreeNode* t=q1.front(); q1.pop(); if(t) { map[t->left]=t; map[t->right]=t; q1.push(t->left); q1.push(t->right); } } unordered_set s; while(p!=NULL) { s.insert(p); p=map[p]; } while(s.find(q)==s.end()) q=map[q]; return q; } };: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 | unordered_map map; 14 | map[root]=NULL; 15 | queue q1; 16 | q1.push(root); 17 | while(!map.count(p)||!map.count(q)) 18 | { 19 | TreeNode* t=q1.front(); 20 | q1.pop(); 21 | if(t) 22 | { 23 | map[t->left]=t; 24 | map[t->right]=t; 25 | q1.push(t->left); 26 | q1.push(t->right); 27 | } 28 | } 29 | unordered_set s; 30 | while(p!=NULL) 31 | { 32 | s.insert(p); 33 | p=map[p]; 34 | } 35 | while(s.find(q)==s.end()) 36 | q=map[q]; 37 | return q; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Hash Table/325. Maximum Size Subarray Sum Equals k.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The solution this given here is by using a map. 3 | Keep summing up the integers present in the array if sum-k exists check if i-maps[(sum-k)] beats ur answer till then where map[sum] stores the index 4 | of the array 5 | 6 | There can be a case where the sum will be equal to k so we can check if (i+1) beats ans or not. 7 | 8 | [1, -1, 5, -2, 3] k=3; 9 | ^ 10 | | 11 | i 12 | 13 | sum=1 14 | sum!=k 15 | 1-3=-2 doesnt exist in the map 16 | ans=0 17 | map[1]=0<---map[sum]=i 18 | 19 | [1, -1, 5, -2, 3] 20 | ^ 21 | | 22 | i 23 | 24 | sum=0 25 | sum!=k 26 | 0-3=-3 doesnt exist in the map 27 | ans=0 28 | map[0]=1 29 | 30 | [1, -1, 5, -2, 3] 31 | ^ 32 | | 33 | i 34 | 35 | sum=5 36 | sum!=k 37 | 5-3=2 doesnt exist in the map 38 | ans=0 39 | map[5]=2 40 | 41 | [1, -1, 5, -2, 3] 42 | ^ 43 | | 44 | i 45 | 46 | sum=3 47 | sum==k so ans=4(ans=i+1) 48 | //skip doesnt exist in the map 49 | ans=4 50 | map[3]=3 51 | 52 | [1, -1, 5, -2, 3] 53 | ^ 54 | | 55 | i 56 | 57 | sum=6 58 | sum!=k 59 | 6-3 doesnt exist in the map 60 | ans=4 61 | map[6]=4 62 | 63 | Thus the answer is 4 64 | */ 65 | int maxSubArrayLen(vector& nums, int k) { 66 | unordered_map map; 67 | int ans=0,sum=0; 68 | for(int i=0;i8 13 | b->5 14 | c->7 15 | d->14 16 | e->15 17 | f->11 18 | g->13 19 | h->19 20 | i->22 21 | j->23 22 | k->20 23 | l->21 24 | 25 | 26 | so when we start our maxindex=0 and last index=0 27 | maxindex =8 because of a 28 | max index wont change because of b as bs last index is 5 29 | max index wont change because of c 30 | thus when i reaches 8 it has hit the max index thus we have got our first segment (maxindex-lastindex+1) 31 | now we update last index to 9 and we follow the same procedure 32 | now maxindex and i would be same at 15 thus the segment size will be maxindex-lastindex+1=7 33 | and similarly the last segement will be of size 8 34 | 35 | */ 36 | vector partitionLabels(string S) { 37 | unordered_map map; 38 | vector ans; 39 | if(S.size()==0)return ans; 40 | for(int i=0;i2->3->4 9 | 10 | Middle is 2 so we try to reverse 3 and 4 11 | 1->2->4->3 12 | Note that for merging purposes we will be making slow->next=NULL so we can treat this as 2 different lists. 13 | 14 | 1->2 15 | 4->3 16 | 17 | merging 18 | 1->4->2->3 19 | */ 20 | 21 | void mergelist(ListNode*p,ListNode* q) //For merging 22 | { 23 | ListNode* t; 24 | while(q) 25 | { 26 | t=p->next; 27 | p->next=q; 28 | q=q->next; 29 | p=p->next; 30 | p->next=t; 31 | p=p->next; 32 | } 33 | } 34 | ListNode* reverse(ListNode* head) //reversing the second half of the ll 35 | { 36 | ListNode* prev=NULL,*curr=head,*next; 37 | while(curr) 38 | { 39 | next=curr->next; 40 | curr->next=prev; 41 | prev=curr; 42 | curr=next; 43 | } 44 | return prev; 45 | } 46 | ListNode* findmid(ListNode* head) //Finding the middle 47 | { 48 | ListNode* slow=head,*fast=head; 49 | while(fast&&fast->next) 50 | { 51 | slow=slow->next; 52 | fast=fast->next->next; 53 | } 54 | ListNode* mid=slow->next; 55 | slow->next=NULL; 56 | return mid; 57 | } 58 | void reorderList(ListNode* head) { 59 | if(!head)return; 60 | ListNode* p=head; 61 | ListNode* q=findmid(head); 62 | q=reverse(q); 63 | mergelist(p,q); 64 | } -------------------------------------------------------------------------------- /HEAP/253. Meeting Rooms II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: 3 | For those who dont have premium this is the question: 4 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. 5 | 6 | Example 1: 7 | 8 | Input: [[0, 30],[5, 10],[15, 20]] 9 | Output: 2 10 | 11 | Example 2: 12 | 13 | Input: [[7,10],[2,4]] 14 | Output: 1 15 | 16 | Answer: 17 | We start by sorting the matrix according to the first elements because it has to be scheduled with increasing time. 18 | If the start time is greater than the end time of the previous meeting we dont need to allocate an extra room. 19 | However if the start time is lesser than the end time of the previous meeting we hve to allocate a new room. 20 | We have sorted the start time but for the end time we use a minheap. 21 | We store the end times in the min heap because if the start time of a later meeting is greater than the smallest end time of the other we can allocate the same room for it. 22 | time complexity---->o(nlogn) 23 | space complexity---->o(n) 24 | */ 25 | struct Compare 26 | { 27 | bool operator()(const vector &one, const vector &two) 28 | { //<-------this is how we sort 2d matrices 29 | return one[0] < two[0]; 30 | } 31 | }compare; 32 | int minMeetingRooms(vector>& interval) { 33 | if(interval.size()==0)return 0; 34 | priority_queue,greater> pq; 35 | sort(interval.begin(), interval.end(), compare); 36 | pq.push(interval[0][1]); 37 | for(int i=1;i=pq.top())pq.pop(); 40 | pq.push(interval[i][1]); 41 | } 42 | return pq.size(); 43 | } -------------------------------------------------------------------------------- /Array/11. Container With Most Water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The approach to this solution that iw ill be taking is two pointer and a bit of common sense. 3 | I will place my left pointer (l) at 0 and right pointer (r) at height.size()-1. 4 | I will assign breadth eaqual to the size of the array - 1 (Because on account of the distance from the first index u take till the last). 5 | Now i will check the smaller height of the two and set that as the current height. Why> Because the smaller rod only will acount for 6 | the height because anything above that will cause an overflow at the smaller side. 7 | 8 | How do we move the pointers? 9 | We move the pointers based on which index as the bigger height. Why? -> Cuz The bigger height has the potential of yielding me 10 | a bigger area because irrespective of what height I will be taking breadth wiill decrease by 1. 11 | 12 | Input: [1,8,6,8,3,7] 13 | ^ ^ 14 | | | 15 | l r 16 | area = 0 17 | breadth = 5 18 | l=0 -----> height[l]height[r] 20 | 21 | decrement breadth 22 | 23 | Continue this until l==r. 24 | */ 25 | 26 | int maxArea(vector& height) { 27 | int breadth=height.size()-1,l=0,r=height.size()-1; 28 | int ans=0; 29 | while(llimit) 14 | | 15 | last element(NOTE:m.end() is not the last element it is the terminating character). 16 | 8-8<=4 so we continue whilst storing the maximum = 1 17 | 18 | [8,2,4,7] 19 | ^ ^ 20 | | | 21 | i j 22 | m=[8,2] 23 | 24 | if (*m.rbegin()-m.begin()>limit) condition:true 25 | so we search for nums[i] and delete. 26 | m=[2] 27 | 28 | 29 | [8,2,4,7] 30 | ^ ^ 31 | | | 32 | i j 33 | m[2,4] 34 | if (*m.rbegin()-m.begin()>limit) condition:false 35 | maximum=2 36 | 37 | [8,2,4,7] 38 | ^ ^ 39 | | | 40 | i j 41 | m=[2,4,7] 42 | if (*m.rbegin()-m.begin()>limit) condition:true 43 | so we search for nums[i] and delete. 44 | m=[2,4,7] 45 | 46 | [8,2,4,7] 47 | ^ ^ 48 | | | 49 | i j 50 | as j has terminated our answer will become 2 51 | */ 52 | int longestSubarray(vector& nums, int limit) { 53 | multiset m; 54 | int j=0,ans=1; 55 | for(int i=0;ilimit) 59 | m.erase(m.find(nums[j++])); 60 | ans=max(ans,i-j+1); 61 | } 62 | return ans; 63 | } -------------------------------------------------------------------------------- /Strings/1249. Minimum Remove to Make Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to tackle this question is to keep a varial lets say open that increments for every opening braces and decrements for every closing 3 | braces. 4 | We will first be considering mismatches of the closing brackets ')'. 5 | if open is equal to 0 and a closing bracket occurs ignore it. 6 | s = "lee(t(c)o)de)" open=0 7 | ^ 8 | | 9 | i 10 | open = 1 11 | s = "lee(t(c)o)de)" 12 | ^ 13 | | 14 | i 15 | open = 2 16 | 17 | s = "lee(t(c)o)de)" 18 | ^ 19 | | 20 | i 21 | open is not 0 22 | open = 1 23 | 24 | s = "lee(t(c)o)de)" 25 | ^ 26 | | 27 | i 28 | open not 0 29 | open = 0 30 | 31 | s = "lee(t(c)o)de)" 32 | ^ 33 | | 34 | i 35 | open is 0 so ignore 36 | 37 | But what if there are more opening braces than closing to handle this we first make sure the closing braces are taken care of 38 | then with the same open we start from behind and check if open is > 0 if so we skip it and decremnt open. 39 | */ 40 | 41 | string minRemoveToMakeValid(string s) { 42 | int open=0; 43 | string t; 44 | for(int i=0;i=0;i--) 56 | { 57 | if(t[i]=='(' && open>0) 58 | { 59 | open--; 60 | continue; 61 | } 62 | ans+=t[i]; 63 | } 64 | reverse(ans.begin(),ans.end()); 65 | return ans; 66 | } 67 | -------------------------------------------------------------------------------- /BFS/1306. Jump Game III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The way to solve this question is using BFS/DFS. 3 | Here i ahve given a BFS solution. 4 | I ll first push the starting position into the queue and start exploring is neighbors. 5 | I will maintain a boolean array to make sure i dont get caught into a loop 6 | Let me explain how a loop can occur:- 7 | [3,0,2,1,2] 8 | start=2 9 | 10 | i can move either left or right. 11 | Let me for example take this route 12 | 13 | 2->3->1->2 14 | This will go indefinitely. 15 | 16 | Let me explain the algorithm with the same example 17 | 0 1 2 3 4 <---indices 18 | [3,0,2,1,2] 19 | start=2 20 | 21 | q=[2](Remember that the start position they give is the index) 22 | we pop 2 out and store it into i. 23 | We mark 2 as visited 24 | check if if(i+arr[i]>=n)false or if(i-arr[i]<0)false 25 | 26 | Thus we push i+arr[i] and i-arr[i] into the queue. 27 | q=[0,4] 28 | Pop 0 out 29 | check if if(i+arr[i]>=n)false or if(i-arr[i]<0)true 30 | So we push only i+arr[i] into the arry. 31 | 32 | q=[4,3] 33 | Pop 4 out 34 | check if if(i+arr[i]>=n)true or if(i-arr[i]<0)false 35 | So we push only i-arr[i] into the arry. 36 | 37 | q=[3,3] 38 | Note that 3 was already we visited so we popped out 39 | 40 | q[3] 41 | Again it gets popped out. 42 | 43 | As 0 was never encountered in our traversal we return false. 44 | */ 45 | bool canReach(vector& arr, int start) { 46 | int n=arr.size(); 47 | queue q; 48 | q.push(start); 49 | vector visited(n,false); 50 | while(!q.empty()) 51 | { 52 | int i=q.front(); 53 | q.pop(); 54 | if(arr[i]==0)return true; 55 | if(!visited[i]){ 56 | visited[i]=true; 57 | if(i+arr[i]=0)q.push(i-arr[i]); 59 | } 60 | } 61 | return false; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /BFS/130. Surrounded Regions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | We will be using number of islands algorithm to solve this. 3 | the algorithm goes like such 4 | 5 | X X X X 6 | X O O X 7 | X X O X 8 | X O X X 9 | | 10 | | 11 | | 12 | v 13 | 14 | X X X X 15 | X O O X 16 | X X O X <----We tamper with matrix in such a way that the order and any of its for adacent cells are made '*' if the cell contains 'O' 17 | X * X X 18 | 19 | Then we do our flips 20 | 21 | X X X X 22 | X X X X 23 | X X X X 24 | X * X X 25 | 26 | The we change * with O 27 | 28 | X X X X 29 | X X X X 30 | X X X X 31 | X O X X 32 | */ 33 | void helper(vector>& board,int i,int j) 34 | { 35 | if(i<0||i>board.size()-1||j<0||j>board[0].size()-1||board[i][j]=='X'||board[i][j]=='*')return; 36 | board[i][j]='*'; 37 | helper(board,i-1,j); 38 | helper(board,i+1,j); 39 | helper(board,i,j-1); 40 | helper(board,i,j+1); 41 | } 42 | void solve(vector>& board) { 43 | if(board.size()==0)return; 44 | int rows=board.size(),cols=board[0].size(); 45 | if(board.size()==0)return; 46 | for (int i=0;i