├── Array ├── 463. Island Perimeter ├── 523. Continuous Subarray Sum └── Readme ├── BFS & DFS ├── 1219. Path with Maximum Gold ├── 1971. Find if Path Exists in Graph ├── 1992. Find All Groups of Farmland ├── 200. Number of Islands ├── 463. Island Perimeter ├── 752. Open the Lock └── Readme ├── Bit ├── 1863. Sum of All Subset XOR Totals └── Readme ├── Bits ├── 1915. Number of Wonderful Substrings ├── 260. Single Number III ├── 2997. Minimum Number of Operations to Make Array XOR Equal to K └── ReadMe ├── Comparator ├── Custom Sort String.cpp └── README.md ├── Dynamic_Programming ├── 1137. N-th Tribonacci Number ├── Best Time to Buy and Sell Stock II.cpp ├── Best Time to Buy and Sell Stock III.cpp ├── Best Time to Buy and Sell Stock IV.cpp ├── Best Time to Buy and Sell Stock with Cooldown.cpp ├── Best Time to Buy and Sell Stock with Transaction Fee.cpp ├── Best Time to Buy and Sell Stock.cpp ├── Cherry Pickup II.cpp ├── Coin Change.cpp ├── Count Sorted Vowel Strings.cpp ├── Delete and Earn.cpp ├── Distinct Subsequences.cpp ├── House_Robber ├── House_robber2.cpp ├── LCS.cpp ├── Largest Divisible Subset.cpp ├── Longest Increasing Subsequence.cpp ├── LongestCommonSubString.cpp ├── Longest_Palindromic_SubSequence.cpp ├── Maximum Length of Pair Chain.cpp ├── Minimum ASCII Delete Sum for Two Strings.cpp ├── Minimum Falling Path Sum.cpp ├── Minimum Insertion Steps to Make a String Palindrome.cpp ├── Minimum Path Sum.cpp ├── Minimum number of deletions and insertions.cpp ├── Number Of LIS.cpp ├── Number of Submatrices That Sum to Target.cpp ├── PrintLcs.cpp ├── Rod Cutting.cpp ├── Shortest Common Supersequence .cpp ├── Triangle.cpp ├── Unbounded_KnapSack.cpp ├── Unique Paths.cpp ├── Unique Paths2.cpp └── coin_Change.cpp ├── Graph ├── ReadMe.txt ├── TopoSort │ ├── 310. Minimum Height Trees │ └── ReadME └── Topological Sort ├── Linked List ├── 2487. Remove Nodes From Linked List ├── 2816. Double a Number Represented as a Linked List └── Readme ├── Matrix ├── 861. Score After Flipping Matrix └── Readme ├── Priority_Queue ├── 786. K-th Smallest Prime Fraction └── Readme ├── Queue └── Readme ├── README.md ├── Sliding Window ├── 1208. Get Equal Substrings Within Budget └── Readme ├── Sorting ├── 1051. Height Checker ├── 3075. Maximize Happiness of Selected Children ├── 881. Boats to Save People └── ReadMe ├── Stacks └── Readme ├── Strings ├── 165. Compare Version Numbers ├── 2000. Reverse Prefix of Word ├── KMP │ └── ReadMe └── ReadMe └── Trees ├── 129. Sum Root to Leaf Numbers ├── 1325. Delete Leaves With a Given Value ├── 2331. Evaluate Boolean Binary Tree ├── 404. Sum of Left Leaves ├── 623. Add One Row to Tree ├── 979. Distribute Coins in Binary Tree ├── 988. Smallest String Starting From Leaf └── Readme /Array/463. Island Perimeter: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/island-perimeter/description/?envType=daily-question&envId=2024-04-18 2 | 3 | Approach 1 : Nested Traversal 4 | 5 | class Solution { 6 | public: 7 | int islandPerimeter(vector>& grid) { 8 | int ans=0; 9 | for(int i=0;i0 &&grid[i][j-1]==0)val++; 14 | if(j0 && grid[i-1][j]==0)val++; 16 | if(i>& grid,int i,int j){ 41 | if(i<0 ||j<0 || i>=n || j>=m || grid[i][j]==0){ 42 | val++; 43 | return; 44 | } 45 | 46 | if(grid[i][j]==-1)return; 47 | 48 | grid[i][j]=-1; 49 | 50 | dfs(grid,i-1,j); 51 | dfs(grid,i+1,j); 52 | dfs(grid,i,j+1); 53 | dfs(grid,i,j-1); 54 | } 55 | 56 | int islandPerimeter(vector>& grid) { 57 | n=grid.size(),m=grid[0].size(); 58 | for(int i=0;i>dir {{1,0},{-1,0},{0,-1},{0,1}}; 80 | 81 | void bfs(vector>& grid,int i,int j){ 82 | queue>q; 83 | q.push({i,j}); 84 | grid[i][j]=-1; 85 | while(!q.empty()){ 86 | int r=q.front().first; 87 | int c=q.front().second; 88 | q.pop(); 89 | 90 | for(auto& d :dir){ 91 | int newi=r+d[0]; 92 | int newc=c+d[1]; 93 | 94 | if(newi<0 || newc<0 || newi >=n || newc>=m ||grid[newi][newc]==0){ 95 | val++; 96 | } 97 | else if(grid[newi][newc]==-1)continue; 98 | else if(grid[newi][newc]==1){ 99 | q.push({newi,newc}); 100 | grid[newi][newc]=-1; 101 | } 102 | } 103 | } 104 | } 105 | 106 | int islandPerimeter(vector>& grid) { 107 | n=grid.size(),m=grid[0].size(); 108 | for(int i=0;i& nums, int k) { 6 | mapmp; 7 | 8 | int sum=0; 9 | mp[0]=-1; 10 | 11 | for(int i=0;i=2)return true; 17 | } 18 | else mp[rem]=i; 19 | 20 | } 21 | 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Array/Readme: -------------------------------------------------------------------------------- 1 | All Array Questions here 2 | -------------------------------------------------------------------------------- /BFS & DFS /1219. Path with Maximum Gold: -------------------------------------------------------------------------------- 1 | Q-Link ; https://leetcode.com/problems/path-with-maximum-gold/?envType=daily-question&envId=2024-05-14 2 | 3 | Approach DFS : 4 | 5 | class Solution { 6 | public: 7 | int n,m; 8 | 9 | vector>dir {{0,-1},{1,0},{0,1},{-1,0}}; 10 | 11 | int helper(vector>& grid,int i,int j){ 12 | if(i<0 || j<0 || i>=n || j>=m)return 0; 13 | 14 | int val =grid[i][j]; 15 | int sum=0; 16 | grid[i][j]=0; 17 | 18 | for(auto& x:dir){ 19 | int newi=x[0]+i; 20 | int newj=x[1]+j; 21 | 22 | if(newi<0 || newj<0 || newi>=n || newj>=m || grid[newi][newj]==0){ 23 | continue; 24 | } 25 | else{ 26 | sum =max(sum, helper(grid,newi,newj)); 27 | 28 | } 29 | } 30 | 31 | grid[i][j]=val; 32 | 33 | return sum+val; 34 | 35 | } 36 | 37 | int getMaximumGold(vector>& grid) { 38 | n=grid.size(); 39 | m=grid[0].size(); 40 | 41 | int ans=0; 42 | 43 | for(int i=0;i>& edges, int source, int destination) { 7 | unordered_map>mp; 8 | vectorvis(n,false); 9 | 10 | if(source==destination)return true; 11 | 12 | for(auto& x :edges){ 13 | mp[x[0]].push_back(x[1]); 14 | mp[x[1]].push_back(x[0]); 15 | } 16 | 17 | queueq; 18 | q.push(source); 19 | vis[source]=true; 20 | while(!q.empty()){ 21 | int src=q.front(); 22 | q.pop(); 23 | 24 | if(src==destination)return true; 25 | 26 | for(auto& x :mp[src]){ 27 | if(vis[x]==false){ 28 | q.push(x); 29 | vis[x]=true; 30 | } 31 | } 32 | 33 | } 34 | return false; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /BFS & DFS /1992. Find All Groups of Farmland: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/find-all-groups-of-farmland/description/?envType=daily-question&envId=2024-04-20 2 | 3 | 4 | Approach 1 : BFS 5 | 6 | class Solution { 7 | public: 8 | int n; 9 | int m; 10 | 11 | vector>dir{{1,0},{-1,0},{0,-1},{0,1}}; 12 | 13 | void bfs(vector>& land,int i,int j,int& maxi,int& mini, vector>&ans){ 14 | queue>q; 15 | q.push({i,j}); 16 | 17 | while(!q.empty()){ 18 | int r=q.front().first; 19 | int c=q.front().second; 20 | maxi=max(maxi,r); 21 | mini=max(mini,c); 22 | 23 | q.pop(); 24 | 25 | for(auto& x:dir){ 26 | int nr=x[0]+r; 27 | int nc=x[1]+c; 28 | 29 | if(nr>=0 && nr=0 && nc> findFarmland(vector>& land) { 38 | 39 | n=land.size(); 40 | m=land[0].size(); 41 | vector>ans; 42 | for(int i=0;i>& land,int i,int j,int& maxi,int& mini, vector>&ans,int &val1,int& val2){ 64 | if(i<0 || j<0 || i>=n || j>=m || land[i][j]==0){ 65 | return false; 66 | } 67 | 68 | land[i][j]=0; 69 | 70 | maxi=max(i,maxi); 71 | mini=max(j,mini); 72 | val1=min(val1,i); 73 | val2=min(val2,j); 74 | bool l=dfs(land,i,j-1,maxi,mini,ans,val1,val2); 75 | bool r=dfs(land,i,j+1,maxi,mini,ans,val1,val2); 76 | bool u=dfs(land,i-1,j,maxi,mini,ans,val1,val2); 77 | bool d=dfs(land,i+1,j,maxi,mini,ans,val1,val2); 78 | if(!l && !r && !u && !d ){ 79 | ans.push_back({val1,val2,maxi,mini}); 80 | return true; 81 | } 82 | 83 | return true; 84 | } 85 | 86 | vector> findFarmland(vector>& land) { 87 | 88 | n=land.size(); 89 | m=land[0].size(); 90 | vector>ans; 91 | for(int i=0;i>& grid,int i,int j){ 11 | if(i<0 || j<0 || i>=n || j>=m || grid[i][j]=='0' )return ; 12 | if(grid[i][j]=='1') grid[i][j]='0'; 13 | dfs(grid,i+1,j); 14 | dfs(grid,i,j+1); 15 | dfs(grid,i-1,j); 16 | dfs(grid,i,j-1); 17 | 18 | } 19 | 20 | int numIslands(vector>& grid) { 21 | n=grid.size(); 22 | m=grid[0].size(); 23 | 24 | for(int i=0;i>dir {{1,0},{-1,0},{0,-1},{0,1}}; 46 | 47 | void bfs(vector>& grid,int i,int j){ 48 | 49 | queue>q; 50 | q.push({i,j}); 51 | grid[i][j]='0'; 52 | 53 | while(!q.empty()){ 54 | int r=q.front().first; 55 | int c=q.front().second; 56 | 57 | q.pop(); 58 | 59 | 60 | for(auto& d:dir){ 61 | int newr=d[0]+r; 62 | int newc=d[1]+c; 63 | if(newr >=0 && newc>=0 &&newr>& grid) { 73 | n=grid.size(); 74 | m=grid[0].size(); 75 | 76 | for(int i=0;i>dir {{1,0},{-1,0},{0,-1},{0,1}}; 11 | 12 | void bfs(vector>& grid,int i,int j){ 13 | queue>q; 14 | q.push({i,j}); 15 | grid[i][j]=-1; 16 | while(!q.empty()){ 17 | int r=q.front().first; 18 | int c=q.front().second; 19 | q.pop(); 20 | 21 | for(auto& d :dir){ 22 | int newi=r+d[0]; 23 | int newc=c+d[1]; 24 | 25 | if(newi<0 || newc<0 || newi >=n || newc>=m ||grid[newi][newc]==0){ 26 | val++; 27 | } 28 | else if(grid[newi][newc]==-1)continue; 29 | else if(grid[newi][newc]==1){ 30 | q.push({newi,newc}); 31 | grid[newi][newc]=-1; 32 | } 33 | } 34 | } 35 | } 36 | 37 | int islandPerimeter(vector>& grid) { 38 | n=grid.size(),m=grid[0].size(); 39 | for(int i=0;i>& grid,int i,int j){ 62 | if(i<0 ||j<0 || i>=n || j>=m || grid[i][j]==0){ 63 | val++; 64 | return; 65 | } 66 | 67 | if(grid[i][j]==-1)return; 68 | 69 | grid[i][j]=-1; 70 | 71 | dfs(grid,i-1,j); 72 | dfs(grid,i+1,j); 73 | dfs(grid,i,j+1); 74 | dfs(grid,i,j-1); 75 | } 76 | 77 | int islandPerimeter(vector>& grid) { 78 | n=grid.size(),m=grid[0].size(); 79 | for(int i=0;i&st,queue&q){ 7 | for(int i=0;i<4;i++){ 8 | 9 | char ch=curr[i]; 10 | 11 | char inc=(ch=='9')?'0':ch+1; 12 | char dec=(ch=='0')?'9':ch-1; 13 | 14 | curr[i]=inc; 15 | 16 | if(st.find( curr)==st.end()){ 17 | q.push( curr); 18 | st.insert( curr); 19 | } 20 | 21 | curr[i]=dec; 22 | 23 | if(st.find( curr)==st.end()){ 24 | q.push( curr); 25 | st.insert( curr); 26 | } 27 | 28 | curr[i]=ch; 29 | 30 | } 31 | } 32 | 33 | int openLock(vector& deadends, string target) { 34 | string start="0000"; 35 | unordered_setst(begin(deadends),end(deadends)); 36 | if(st.find(start)!=st.end())return -1; 37 | int level=0; 38 | 39 | queueq; 40 | q.push(start); 41 | 42 | while(!q.empty()){ 43 | 44 | int sz=q.size(); 45 | 46 | while(sz--){ 47 | string curr=q.front(); 48 | q.pop(); 49 | if(curr==target)return level; 50 | 51 | generate(curr,st,q); 52 | 53 | } 54 | level++; 55 | } 56 | return -1; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /BFS & DFS /Readme: -------------------------------------------------------------------------------- 1 | All BFS / DFS code goes here 2 | 3 | -------------------------------------------------------------------------------- /Bit/1863. Sum of All Subset XOR Totals: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/sum-of-all-subset-xor-totals/description/?envType=daily-question&envId=2024-05-20 2 | 3 | class Solution { 4 | public: 5 | 6 | int helper(vectornums,int idx,int xorr){ 7 | 8 | if(idx==nums.size())return xorr; 9 | 10 | int inc=helper(nums,idx+1,xorr^nums[idx]); 11 | int exc=helper(nums,idx+1,xorr); 12 | 13 | 14 | return inc+exc; 15 | } 16 | 17 | int subsetXORSum(vector& nums) { 18 | return helper(nums,0,0); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Bit/Readme: -------------------------------------------------------------------------------- 1 | All Bits Questions goes here 2 | -------------------------------------------------------------------------------- /Bits/1915. Number of Wonderful Substrings: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/number-of-wonderful-substrings/description/?envType=daily-question&envId=2024-04-30 2 | 3 | class Solution { 4 | public: 5 | typedef long long ll; 6 | long long wonderfulSubstrings(string word) { 7 | unordered_map mp; 8 | 9 | mp[0] = 1; 10 | int cum_xor = 0; 11 | 12 | ll result = 0; 13 | 14 | 15 | for(char &ch : word) { 16 | 17 | int shift = ch - 'a'; 18 | 19 | cum_xor ^= (1 << shift); 20 | 21 | result += mp[cum_xor]; 22 | 23 | for(char ch1 = 'a' ; ch1 <= 'j'; ch1++) { 24 | shift = ch1 - 'a'; 25 | 26 | ll check_xor = (cum_xor ^ (1 << shift)); 27 | 28 | result += mp[check_xor]; 29 | } 30 | 31 | mp[cum_xor]++; 32 | 33 | } 34 | 35 | return result; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Bits/260. Single Number III: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/single-number-iii/description/?envType=daily-question&envId=2024-05-31 2 | 3 | class Solution { 4 | public: 5 | vector singleNumber(vector& nums) { 6 | long long xor_r = 0; 7 | 8 | for(int &num : nums) { 9 | xor_r ^= num; 10 | } 11 | 12 | //mask -> right most set bit search 13 | int mask = (xor_r) & (-xor_r); 14 | /* 15 | It works because if you take the two's complement negation of a number, first you complement it, 16 | setting all zeroes to the right of the lowest set bit to one and the lowest set bit to zero, 17 | then you add one, setting the bits on the right to zero and the lowest set bit becomes one again, ending the carry chain. 18 | */ 19 | 20 | int groupa = 0; 21 | int groupb = 0; 22 | 23 | for(int &num : nums) { 24 | if(num & mask) { 25 | groupa ^= num; 26 | } else { 27 | groupb ^= num; 28 | } 29 | } 30 | 31 | return {groupa, groupb}; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Bits/2997. Minimum Number of Operations to Make Array XOR Equal to K: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/description/?envType=daily-question&envId=2024-04-29 2 | 3 | class Solution { 4 | public: 5 | int minOperations(vector& nums, int k) { 6 | int xorr=0; 7 | 8 | for(auto& x : nums)xorr^=x; 9 | 10 | int diff=xorr^k; 11 | 12 | return __builtin_popcount(diff); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Bits/ReadMe: -------------------------------------------------------------------------------- 1 | All Bits Qiestions 2 | -------------------------------------------------------------------------------- /Comparator/Custom Sort String.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/custom-sort-string/description/?envType=daily-question&envId=2024-03-11 2 | 3 | class Solution { 4 | public: 5 | 6 | 7 | string customSortString(string order, string s) { 8 | unordered_mapmp; 9 | for(int i=0;idp(n+1,0); 7 | if(n==0)return 0; 8 | if(n==1 || n==2)return 1; 9 | dp[1]=dp[2]=1; 10 | 11 | for(int i=3;i<=n;i++){ 12 | dp[i]= dp[i-1]+dp[i-2]+dp[i-3]; 13 | } 14 | return dp[n]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector&prices,int buy,int idx){ 9 | if(idx==prices.size())return 0; 10 | 11 | int profit=0; 12 | 13 | if(buy){ 14 | profit=max(-prices[idx]+helper(prices,0,idx+1),0+helper(prices,1,idx+1)); 15 | } 16 | else profit=max(prices[idx]+helper(prices,1,idx+1),helper(prices,0,idx+1)); 17 | 18 | return profit; 19 | } 20 | 21 | int maxProfit(vector& prices) { 22 | return helper(prices,1,0); 23 | } 24 | }; 25 | 26 | Approach 2 : Memo 27 | 28 | class Solution { 29 | public: 30 | 31 | int helper(vector&prices,int buy,int idx, vector>&dp){ 32 | if(idx==prices.size())return 0; 33 | 34 | int profit=0; 35 | 36 | if(dp[idx][buy]!=-1)return dp[idx][buy]; 37 | 38 | if(buy){ 39 | profit=max(-prices[idx]+helper(prices,0,idx+1,dp),0+helper(prices,1,idx+1,dp)); 40 | } 41 | else profit=max(prices[idx]+helper(prices,1,idx+1,dp),helper(prices,0,idx+1,dp)); 42 | 43 | return dp[idx][buy]=profit; 44 | } 45 | 46 | int maxProfit(vector& prices) { 47 | vector>dp(prices.size()+1,vector(2,-1)); 48 | return helper(prices,1,0,dp); 49 | } 50 | }; 51 | 52 | Approach 3 : Tabulation 53 | 54 | class Solution { 55 | public: 56 | 57 | 58 | int maxProfit(vector& prices) { 59 | vector>dp(prices.size()+1,vector(2,0)); 60 | 61 | dp[prices.size()][0]=dp[prices.size()][1]=0; 62 | 63 | for(int idx=prices.size()-1;idx>=0;idx--){ 64 | for(int buy=0;buy<=1;buy++){ 65 | int profit=0; 66 | 67 | if(buy){ 68 | profit=max(-prices[idx]+dp[idx+1][0],0+dp[idx+1][1]); 69 | } 70 | else profit=max(prices[idx]+dp[idx+1][1],dp[idx+1][0]); 71 | 72 | dp[idx][buy]=profit; 73 | } 74 | } 75 | 76 | return dp[0][1]; 77 | } 78 | }; 79 | 80 | Approach 4 : Space Optimization 81 | 82 | class Solution { 83 | public: 84 | 85 | 86 | int maxProfit(vector& prices) { 87 | vectorprev(2),curr(2); 88 | 89 | prev[0]=prev[1]=0; 90 | 91 | for(int idx=prices.size()-1;idx>=0;idx--){ 92 | for(int buy=0;buy<=1;buy++){ 93 | int profit=0; 94 | 95 | if(buy){ 96 | profit=max(-prices[idx]+prev[0],0+prev[1]); 97 | } 98 | else profit=max(prices[idx]+prev[1],prev[0]); 99 | 100 | curr[buy]=profit; 101 | } 102 | prev=curr; 103 | } 104 | 105 | return prev[1]; 106 | } 107 | }; 108 | 109 | Approach 5 : Greedy 110 | 111 | class Solution { 112 | public: 113 | 114 | 115 | int maxProfit(vector& prices) { 116 | int n=prices.size(); 117 | int ans=0; 118 | for(int i=1; i<=n-1; ++i){ 119 | int diff=prices[i]-prices[i-1]; 120 | if(diff>0){ans+=diff;} 121 | } 122 | return ans; 123 | } 124 | }; 125 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock III.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/ 2 | 3 | class Solution { 4 | public: 5 | int helper(vector&prices,int idx,int n,int buy,int cap, vector>>&dp){ 6 | if(n==idx||cap==0)return 0; 7 | if(dp[idx][buy][cap]!=-1)return dp[idx][buy][cap]; 8 | int profit=0; 9 | if(buy)profit=max(-1*prices[idx]+helper(prices,idx+1,n,0,cap,dp),helper(prices,idx+1, 10 | n,1,cap,dp)); 11 | else profit=max(prices[idx]+helper(prices,idx+1,n,1,cap-1,dp),helper(prices,idx+1,n,0,cap,dp)); 12 | 13 | return dp[idx][buy][cap]=profit; 14 | 15 | } 16 | 17 | int maxProfit(vector& prices) { 18 | int n=prices.size(); 19 | vector>>dp(n,vector>(2,vector(3,-1))); 20 | return helper(prices,0,n,1,2,dp); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock IV.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/ 2 | 3 | class Solution { 4 | public: 5 | int helper(vector&prices,int idx,int n,int buy,int cap,vector>>&dp){ 6 | if(n==idx||cap==0)return 0; 7 | 8 | if(dp[idx][buy][cap]!=-1)return dp[idx][buy][cap]; 9 | 10 | int profit=0; 11 | 12 | if(buy)profit=max(-1*prices[idx]+helper(prices,idx+1,n,0,cap,dp),helper(prices,idx+1,n,1,cap,dp)); 13 | else profit=max(prices[idx]+helper(prices,idx+1,n,1,cap-1,dp),helper(prices,idx+1,n,0,cap,dp)); 14 | 15 | return dp[idx][buy][cap]=profit; 16 | 17 | } 18 | int maxProfit(int k, vector& prices) { 19 | int n=prices.size(); 20 | 21 | vector>>dp(n,vector>(2,vector(k+1,-1))); 22 | 23 | return helper(prices,0,n,1,k,dp); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock with Cooldown.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ 2 | 3 | class Solution { 4 | public: 5 | int helper(vector&prices,int idx,int n,int buy, vector>&dp){ 6 | if(idx>=n)return 0; 7 | if(dp[idx][buy]!=-1)return dp[idx][buy]; 8 | int profit=0; 9 | if(buy)profit=max(-1*prices[idx]+helper(prices,idx+1,n,0,dp),helper(prices,idx+1, 10 | n,1,dp)); 11 | else profit=max(prices[idx]+helper(prices,idx+2,n,1,dp),helper(prices,idx+1,n,0,dp)); 12 | 13 | return dp[idx][buy]=profit; 14 | 15 | } 16 | int maxProfit(vector& prices) { 17 | int n=prices.size(); 18 | vector>dp(n,vector(2,-1)); 19 | return helper(prices,0,n,1,dp); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock with Transaction Fee.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ 2 | 3 | class Solution { 4 | public: 5 | 6 | int helper(vector&prices,int idx,int n,int buy, vector>&dp,int fee){ 7 | if(n==idx)return 0; 8 | if(dp[idx][buy]!=-1)return dp[idx][buy]; 9 | int profit=0; 10 | if(buy)profit=max(-1*prices[idx]+helper(prices,idx+1,n,0,dp,fee),helper(prices,idx+1, 11 | n,1,dp,fee)); 12 | else profit=max(prices[idx]-fee+helper(prices,idx+1,n,1,dp,fee),helper(prices,idx+1,n,0,dp,fee)); 13 | 14 | return dp[idx][buy]=profit; 15 | 16 | } 17 | int maxProfit(vector& prices, int fee) { 18 | int n=prices.size(); 19 | vector>dp(n,vector(2,-1)); 20 | return helper(prices,0,n,1,dp,fee); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic_Programming/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int profit=0; 7 | int mini=prices[0]; 8 | 9 | for(int i=1;iprices[i]){ 13 | mini=prices[i]; 14 | 15 | } 16 | } 17 | 18 | return profit; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic_Programming/Cherry Pickup II.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/cherry-pickup-ii/description/ 2 | 3 | Approach 1 : Memo 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector>& grid,int row,int c1,int c2,int n,int m, vector>>&dp){ 9 | if(c1<0 || c2<0 || c1>=m || c2>=m )return -1e9; 10 | 11 | if(row==n-1){ 12 | if(c1==c2)return grid[row][c1]; 13 | return grid[row][c1]+grid[row][c2]; 14 | } 15 | 16 | if(dp[row][c1][c2]!=-1)return dp[row][c1][c2]; 17 | 18 | int val=0; 19 | 20 | int maxi=-1e8; 21 | 22 | for(int i=-1;i<=1;i++){ 23 | for(int j=-1;j<=1;j++){ 24 | if(c1!=c2)val=grid[row][c2]+grid[row][c1]; 25 | else val=grid[row][c1]; 26 | 27 | val+=helper(grid,row+1,c1+i,c2+j,n,m,dp); 28 | 29 | maxi=max(maxi,val); 30 | } 31 | } 32 | 33 | return dp[row][c1][c2]=maxi; 34 | 35 | } 36 | 37 | int cherryPickup(vector>& grid) { 38 | int n=grid.size(); 39 | int m=grid[0].size(); 40 | int idx=0; 41 | vector>>dp(n,vector>(m,vector(m,-1))); 42 | return helper(grid,idx,idx,m-1,n,m,dp); 43 | } 44 | }; 45 | 46 | Approach 2 :Tabulation 47 | 48 | class Solution { 49 | public: 50 | 51 | int helper(vector>& grid,int row,int c1,int c2,int n,int m, vector>>&dp){ 52 | if(c1<0 || c2<0 || c1>=m || c2>=m )return -1e9; 53 | 54 | if(row==n-1){ 55 | if(c1==c2)return grid[row][c1]; 56 | return grid[row][c1]+grid[row][c2]; 57 | } 58 | 59 | if(dp[row][c1][c2]!=-1)return dp[row][c1][c2]; 60 | 61 | int val=0; 62 | 63 | int maxi=-1e8; 64 | 65 | for(int i=-1;i<=1;i++){ 66 | for(int j=-1;j<=1;j++){ 67 | if(c1!=c2)val=grid[row][c2]+grid[row][c1]; 68 | else val=grid[row][c1]; 69 | 70 | val+=helper(grid,row+1,c1+i,c2+j,n,m,dp); 71 | 72 | maxi=max(maxi,val); 73 | } 74 | } 75 | 76 | return dp[row][c1][c2]=maxi; 77 | 78 | } 79 | 80 | int cherryPickup(vector>& grid) { 81 | int n=grid.size(); 82 | int m=grid[0].size(); 83 | int idx=0; 84 | vector>>dp(n,vector>(m,vector(m,0))); 85 | 86 | for(int j1=0;j1=0;i--){ 95 | for(int j1=0;j1=0&&j2+dj>=0) val+=dp[i+1][j1+di][j2+dj]; 105 | else val+=-1e9; 106 | maxi=max(maxi,val); 107 | } 108 | } 109 | dp[i][j1][j2]=maxi; 110 | } 111 | } 112 | } 113 | 114 | return dp[0][0][m-1]; 115 | 116 | } 117 | }; 118 | -------------------------------------------------------------------------------- /Dynamic_Programming/Coin Change.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/coin-change/description/ 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector& coins, int amount,int idx){ 9 | if(amount==0)return 0; 10 | if(idx==0){ 11 | 12 | if(amount%coins[0]==0)return amount/coins[0]; 13 | 14 | else return 1e9; 15 | } 16 | int nonTake=helper(coins,amount,idx-1); 17 | int take=1e9; 18 | if(coins[idx]<=amount)take=1+helper(coins,amount-coins[idx],idx); 19 | 20 | return min(nonTake,take); 21 | } 22 | 23 | int coinChange(vector& coins, int amount) { 24 | int n=coins.size(); 25 | sort(begin(coins),end(coins)); 26 | int val= helper(coins,amount,n-1); 27 | 28 | return (val>=1e9)?-1:val; 29 | } 30 | }; 31 | 32 | Approach 2 : Memo 33 | 34 | class Solution { 35 | public: 36 | 37 | int helper(vector& coins, int amount,int idx, vector>&dp){ 38 | if(amount==0)return 0; 39 | if(idx==0){ 40 | 41 | if(amount%coins[0]==0)return amount/coins[0]; 42 | 43 | else return 1e9; 44 | } 45 | if(dp[idx][amount]!=-1)return dp[idx][amount]; 46 | int nonTake=helper(coins,amount,idx-1,dp); 47 | int take=1e9; 48 | if(coins[idx]<=amount)take=1+helper(coins,amount-coins[idx],idx,dp); 49 | 50 | return dp[idx][amount]= min(nonTake,take); 51 | } 52 | 53 | int coinChange(vector& coins, int amount) { 54 | int n=coins.size(); 55 | vector>dp(n,vector(amount+1,-1)); 56 | int val= helper(coins,amount,n-1,dp); 57 | 58 | return (val>=1e9)?-1:val; 59 | } 60 | }; 61 | 62 | Approach 3 : Tabulation 63 | 64 | class Solution { 65 | public: 66 | 67 | int coinChange(vector& coins, int amount) { 68 | int n=coins.size(); 69 | vector>dp(n,vector(amount+1,-1)); 70 | 71 | // for(int i=0;i=1e9)return -1; 89 | return ans; 90 | } 91 | }; 92 | 93 | Approach 4 : Space Optimization 94 | 95 | class Solution { 96 | public: 97 | 98 | int coinChange(vector& coins, int target) { 99 | int n=coins.size(); 100 | 101 | vectorprev(target+1,0),curr(target+1,0); 102 | // for(int i=0;i=1e9)return -1; 121 | return ans; 122 | } 123 | }; 124 | -------------------------------------------------------------------------------- /Dynamic_Programming/Count Sorted Vowel Strings.cpp: -------------------------------------------------------------------------------- 1 | Q-Link ; https://leetcode.com/problems/count-sorted-vowel-strings/description/ 2 | 3 | Approach 1 : Recursion : 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(int idx,int n){ 9 | if(n==0)return 1; 10 | if(idx>=5)return 0; 11 | 12 | int pick=helper(idx,n-1); 13 | int nonpick=helper(idx+1,n); 14 | 15 | return pick+nonpick; 16 | 17 | } 18 | 19 | int countVowelStrings(int n) { 20 | 21 | 22 | return helper(0,n); 23 | } 24 | }; 25 | 26 | Approach 2 : Memo 27 | 28 | class Solution { 29 | public: 30 | 31 | int helper(int idx,int n, vector>&dp){ 32 | if(n==0)return 1; 33 | if(idx>=5)return 0; 34 | if(dp[idx][n]!=-1)return dp[idx][n]; 35 | int pick=helper(idx,n-1,dp); 36 | int nonpick=helper(idx+1,n,dp); 37 | 38 | return dp[idx][n]=pick+nonpick; 39 | 40 | } 41 | 42 | int countVowelStrings(int n) { 43 | 44 | vector>dp(5,vector(n+1,-1)); 45 | 46 | return helper(0,n,dp); 47 | } 48 | }; 49 | 50 | Approach 3 : Tabulation 51 | 52 | class Solution { 53 | public: 54 | 55 | 56 | 57 | int countVowelStrings(int n) { 58 | 59 | vector>dp(5,vector(n+1,0)); 60 | 61 | for(int idx=0;idx<5;idx++)dp[idx][0]=1; 62 | 63 | for(int i=4;i>=0;i--){ 64 | for(int j=1;j<=n;j++){ 65 | int pick=dp[i][j-1]; 66 | int nonpick=0; 67 | if(i<4)nonpick=dp[i+1][j]; 68 | dp[i][j]=pick+nonpick; 69 | } 70 | } 71 | 72 | return dp[0][n]; 73 | } 74 | }; 75 | 76 | Approach 4 : Space Optimization 77 | 78 | class Solution { 79 | public: 80 | int countVowelStrings(int n) { 81 | 82 | vectordp(5,1); 83 | 84 | while(--n){ 85 | for(int i=3;i>=0;i--){ 86 | dp[i]+=dp[i+1]; 87 | } 88 | } 89 | int sum=0; 90 | 91 | for(auto& x : dp)sum+=x; 92 | 93 | return sum; 94 | } 95 | }; 96 | 97 | Approach 5 : O(1) Space 98 | 99 | class Solution { 100 | public: 101 | int countVowelStrings(int n) { 102 | 103 | int a=1,e=1,i=1,o=1,u=1; 104 | 105 | while(--n){ 106 | o+=u; 107 | i+=o; 108 | e+=i; 109 | a+=e; 110 | } 111 | 112 | return a+e+i+o+u; 113 | } 114 | }; 115 | -------------------------------------------------------------------------------- /Dynamic_Programming/Delete and Earn.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/delete-and-earn/description/ 2 | 3 | 4 | PRoblem is similar like house robber and can be solved by that method plus LIS as well 5 | 6 | Approach 1 : House Robber 7 | 8 | class Solution { 9 | public: 10 | int helper(vector&nums,int idx,vector&dp){ 11 | if(idx==0)return nums[idx]; 12 | if(idx<0)return 0; 13 | if(dp[idx]!=-1)return dp[idx]; 14 | int take=INT_MIN; 15 | if(idx>=1)take=nums[idx]+helper(nums,idx-2,dp); 16 | 17 | int non_take=helper(nums,idx-1,dp); 18 | 19 | return dp[idx]=max(take,non_take); 20 | } 21 | 22 | int deleteAndEarn(vector& nums) { 23 | int maxi=0; 24 | for(auto&x : nums)maxi=max(maxi,x); 25 | vectorvec(maxi+1,0); 26 | 27 | for(int i=0;idp(n,-1); 32 | return helper(vec,n-1,dp); 33 | } 34 | }; 35 | 36 | Approach 2 : By Sorting 37 | 38 | class Solution { 39 | public: 40 | 41 | int helper(vector&nums,int idx, vector&dp){ 42 | if(idx>=nums.size())return 0; 43 | 44 | int currval=nums[idx]; 45 | int index=idx+1; 46 | int total=nums[idx]; 47 | 48 | if(dp[idx]!=-1)return dp[idx]; 49 | 50 | while(index& nums) { 65 | if(nums.size()==1)return nums[0]; 66 | sort(nums.begin(),nums.end()); 67 | vectordp(nums.size()+1,-1); 68 | return helper(nums,0,dp); 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /Dynamic_Programming/Distinct Subsequences.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/distinct-subsequences/description/ 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(string& s,string& t,int n,int m ,int i,int j){ 9 | if(j<0)return 1; 10 | if(i<0)return 0; 11 | 12 | if(s[i]==t[j])return helper(s,t,n,m,i-1,j-1)+helper(s,t,n,m,i-1,j); 13 | return helper(s,t,n,m,i-1,j); 14 | } 15 | 16 | int numDistinct(string s, string t) { 17 | int n=s.length(); 18 | int m=t.length(); 19 | 20 | return helper(s,t,n,m,n-1,m-1); 21 | } 22 | }; 23 | 24 | Approach 2 : Memo 25 | 26 | class Solution { 27 | public: 28 | 29 | int helper(string& s,string& t,int n,int m ,int i,int j,vector>&dp){ 30 | if(j<0)return 1; 31 | if(i<0)return 0; 32 | if(dp[i][j]!=-1)return dp[i][j]; 33 | if(s[i]==t[j])return dp[i][j]= helper(s,t,n,m,i-1,j-1,dp)+helper(s,t,n,m,i-1,j,dp); 34 | return dp[i][j]=helper(s,t,n,m,i-1,j,dp); 35 | } 36 | 37 | int numDistinct(string s, string t) { 38 | int n=s.length(); 39 | int m=t.length(); 40 | 41 | vector>dp(n+1,vector(m+1,-1)); 42 | 43 | return helper(s,t,n,m,n-1,m-1,dp); 44 | } 45 | }; 46 | 47 | Approach 3 : Tabu 48 | 49 | class Solution { 50 | public: 51 | 52 | int numDistinct(string s, string t) { 53 | int n=s.length(); 54 | int m=t.length(); 55 | 56 | vector>dp(n+1,vector(m+1,-1)); 57 | 58 | for(int i=0;i<=n;i++)dp[i][0]=1; 59 | for(int i=1;i<=m;i++)dp[0][i]=0; 60 | 61 | for(int i=1;i<=n;i++){ 62 | for(int j=1;j<=m;j++){ 63 | if(s[i-1]==t[j-1]) dp[i][j]= dp[i-1][j-1]+dp[i-1][j]; 64 | else dp[i][j]=dp[i-1][j]; 65 | } 66 | } 67 | 68 | return (int)dp[n][m]; 69 | } 70 | }; 71 | 72 | Approach 4 : Space Optimization 2D ARRAY 73 | 74 | class Solution { 75 | public: 76 | 77 | int numDistinct(string s, string t) { 78 | int n=s.length(); 79 | int m=t.length(); 80 | vectorprev(m+1),curr(m+1); 81 | 82 | prev[0]=curr[0]=1; 83 | 84 | 85 | for(int i=1;i<=n;i++){ 86 | for(int j=1;j<=m;j++){ 87 | if(s[i-1]==t[j-1]) curr[j]= prev[j-1]+prev[j]; 88 | else curr[j]=prev[j]; 89 | } 90 | prev=curr; 91 | } 92 | 93 | return (int)prev[m]; 94 | } 95 | }; 96 | 97 | Approach 5 : Space Optimization 1D ARRAY 98 | 99 | class Solution { 100 | public: 101 | 102 | int numDistinct(string s, string t) { 103 | int n=s.length(); 104 | int m=t.length(); 105 | vectorcurr(m+1); 106 | 107 | curr[0]=1; 108 | 109 | 110 | for(int i=1;i<=n;i++){ 111 | for(int j=m;j>=1;j--){ 112 | if(s[i-1]==t[j-1]) curr[j]= curr[j-1]+curr[j]; 113 | } 114 | } 115 | 116 | return (int)curr[m]; 117 | } 118 | }; 119 | -------------------------------------------------------------------------------- /Dynamic_Programming/House_Robber: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/house-robber/submissions/1152744861/?envType=daily-question&envId=2024-01-21 2 | 3 | 4 | Approach 1 : Recursion 5 | 6 | class Solution { 7 | public: 8 | 9 | int helper(vector&nums,int idx){ 10 | if(idx==0)return nums[idx]; 11 | if(idx<0)return 0; 12 | 13 | int take=INT_MIN; 14 | if(idx>=1)take=nums[idx]+helper(nums,idx-2); 15 | 16 | int non_take=helper(nums,idx-1); 17 | 18 | return max(take,non_take); 19 | } 20 | 21 | int rob(vector& nums) { 22 | int n=nums.size(); 23 | return helper(nums,n-1); 24 | } 25 | }; 26 | 27 | Approach 2 : Memoization 28 | 29 | class Solution { 30 | public: 31 | 32 | int helper(vector&nums,int idx,vector&dp){ 33 | if(idx==0)return nums[idx]; 34 | if(idx<0)return 0; 35 | if(dp[idx]!=-1)return dp[idx]; 36 | int take=INT_MIN; 37 | if(idx>=1)take=nums[idx]+helper(nums,idx-2,dp); 38 | 39 | int non_take=helper(nums,idx-1,dp); 40 | 41 | return dp[idx]=max(take,non_take); 42 | } 43 | 44 | int rob(vector& nums) { 45 | int n=nums.size(); 46 | vectordp(n,-1); 47 | return helper(nums,n-1,dp); 48 | } 49 | }; 50 | 51 | Approach 3: Tabulation 52 | 53 | int n=nums.size(); 54 | vectordp(n,-1); 55 | dp[0]=nums[0]; 56 | for(int i=1;i=2)take+=dp[i-2]; 59 | int nontake=dp[i-1]; 60 | 61 | dp[i]=max(take,nontake); 62 | } 63 | 64 | return dp[n-1]; 65 | 66 | 67 | Approach 4 : Space Optimisation 68 | 69 | class Solution { 70 | public: 71 | 72 | int rob(vector& nums) { 73 | int n=nums.size(); 74 | vectordp(n,-1); 75 | 76 | int prev=nums[0]; 77 | int prev2=0; 78 | for(int i=1;i=2)take+=prev2; 81 | int nontake=prev; 82 | 83 | int curr=max(take,nontake); 84 | prev2=prev; 85 | prev=curr; 86 | } 87 | 88 | return prev; 89 | } 90 | }; 91 | -------------------------------------------------------------------------------- /Dynamic_Programming/House_robber2.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/house-robber-ii/description/ 2 | 3 | Approach 1 : Memo 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector&nums,int st,int end, vector&dp){ 9 | if(st==end)return nums[end]; 10 | if(st& nums) { 19 | int n=nums.size(); 20 | int end=0; 21 | int end2=1; 22 | if(n==1)return nums[0]; 23 | vectordp(n,-1); 24 | vectordp2(n,-1); 25 | return max( helper(nums,n-1,end2,dp), 26 | helper(nums,n-2,end,dp2)); 27 | } 28 | }; 29 | 30 | Approach 2 : Tabulation 31 | 32 | class Solution { 33 | public: 34 | int helper2(vector&arr){ 35 | 36 | vectordp(arr.size(),-1); 37 | 38 | dp[0]=arr[0]; 39 | 40 | for(int i=1;i=2)take+=dp[i-2]; 43 | 44 | int nontake=dp[i-1]; 45 | 46 | dp[i]=max(take,nontake); 47 | } 48 | return dp[arr.size()-1]; 49 | } 50 | 51 | int rob(vector& nums) { 52 | int n=nums.size(); 53 | if(n==1)return nums[0]; 54 | 55 | vectortemp1,temp2; 56 | 57 | for(int i=0;i&arr){ 72 | 73 | 74 | 75 | int prev=arr[0]; 76 | int prev2=0; 77 | 78 | for(int i=1;i=2)take+=prev2; 81 | 82 | int nontake=prev; 83 | 84 | int cur=max(take,nontake); 85 | 86 | prev2=prev; 87 | prev=cur; 88 | } 89 | return prev; 90 | } 91 | 92 | int rob(vector& nums) { 93 | int n=nums.size(); 94 | if(n==1)return nums[0]; 95 | 96 | vectortemp1,temp2; 97 | 98 | for(int i=0;i>&dp){ 10 | if(idx1<0 || idx2<0)return 0; 11 | if(dp[idx1][idx2]!=-1)return dp[idx1][idx2]; 12 | if(text1[idx1]==text2[idx2])return dp[idx1][idx2]=1 +helper(text1,text2,idx1-1,idx2-1,dp); 13 | 14 | return dp[idx1][idx2]=max(helper(text1,text2,idx1,idx2-1,dp),helper(text1,text2,idx1-1,idx2,dp)); 15 | } 16 | 17 | int longestCommonSubsequence(string text1, string text2) { 18 | int n=text1.length(); 19 | int m=text2.length(); 20 | vector>dp(n+1,vector(m,-1)); 21 | return helper(text1,text2,n-1,m-1,dp); 22 | } 23 | }; 24 | 25 | 26 | Approach 2 : Tabu 27 | 28 | class Solution { 29 | public: 30 | 31 | int longestCommonSubsequence(string text1, string text2) { 32 | int n=text1.length(); 33 | int m=text2.length(); 34 | vector>dp(n+1,vector(m+1,-1)); 35 | 36 | for(int i=0;i<=n;i++)dp[i][0]=0; 37 | for(int i=0;i<=m;i++)dp[0][i]=0; 38 | 39 | for(int i=1;i<=n;i++){ 40 | for(int j=1;j<=m;j++){ 41 | if(text1[i-1]==text2[j-1]) dp[i][j]=1 +dp[i-1][j-1]; 42 | 43 | else dp[i][j]=max(dp[i][j-1],dp[i-1][j]); 44 | } 45 | } 46 | 47 | return dp[n][m]; 48 | } 49 | }; 50 | 51 | 52 | Approach 3 : Space Optimization 53 | 54 | class Solution { 55 | public: 56 | 57 | int longestCommonSubsequence(string text1, string text2) { 58 | int n=text1.length(); 59 | int m=text2.length(); 60 | vectorprev(m+1,0),curr(m+1,0); 61 | 62 | 63 | for(int i=0;i<=m;i++)prev[i]=0; 64 | 65 | for(int i=1;i<=n;i++){ 66 | for(int j=1;j<=m;j++){ 67 | if(text1[i-1]==text2[j-1]) curr[j]=1 +prev[j-1]; 68 | 69 | else curr[j]=max(curr[j-1],prev[j]); 70 | } 71 | prev=curr; 72 | } 73 | 74 | return prev[m]; 75 | } 76 | }; 77 | 78 | -------------------------------------------------------------------------------- /Dynamic_Programming/Largest Divisible Subset.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/largest-divisible-subset/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | vector longestIncreasingSubsequence(int n, vector& nums) { 7 | 8 | vectordp(n,1),hash(n); 9 | int maxi=-1; 10 | int last_Idx=0; 11 | 12 | for(int i=0;imaxi){ 22 | maxi=dp[i]; 23 | last_Idx=i; 24 | } 25 | } 26 | 27 | vectorans; 28 | 29 | while(hash[last_Idx]!=last_Idx){ 30 | ans.push_back(nums[last_Idx]); 31 | last_Idx=hash[last_Idx]; 32 | } 33 | ans.push_back(nums[last_Idx]); 34 | reverse(ans.begin(),ans.end()); 35 | 36 | return ans; 37 | 38 | } 39 | vector largestDivisibleSubset(vector& nums) { 40 | sort(nums.begin(),nums.end()); 41 | return longestIncreasingSubsequence(nums.size(),nums); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Dynamic_Programming/Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/longest-increasing-subsequence/description/ 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector&nums,int idx,int prev){ 9 | if(idx==nums.size())return 0; 10 | 11 | int nontake=helper(nums,idx+1,prev); 12 | int take=0; 13 | 14 | if(prev==-1 || nums[idx]>nums[prev]){ 15 | take=1+helper(nums,idx+1,idx); 16 | } 17 | 18 | return max(take,nontake); 19 | } 20 | 21 | int lengthOfLIS(vector& nums) { 22 | return helper(nums,0,-1); 23 | } 24 | }; 25 | 26 | Approach 2 : Memo 27 | 28 | class Solution { 29 | public: 30 | 31 | int helper(vector&nums,int idx,int prev, vector>&dp){ 32 | if(idx==nums.size())return 0; 33 | 34 | if(dp[idx][prev+1]!=-1)return dp[idx][prev+1]; 35 | 36 | int nontake=helper(nums,idx+1,prev,dp); 37 | int take=0; 38 | 39 | if(prev==-1 || nums[idx]>nums[prev]){ 40 | take=1+helper(nums,idx+1,idx,dp); 41 | } 42 | 43 | return dp[idx][prev+1]=max(take,nontake); 44 | } 45 | 46 | int lengthOfLIS(vector& nums) { 47 | vector>dp(nums.size(),vector(nums.size()+1,-1)); 48 | return helper(nums,0,-1,dp); 49 | } 50 | }; 51 | 52 | Approach 3 : Tabulation 53 | 54 | class Solution { 55 | public: 56 | 57 | 58 | int lengthOfLIS(vector& nums) { 59 | int n=nums.size(); 60 | vector>dp(n+1,vector(n+1,0)); 61 | 62 | for(int i=n-1;i>=0;i--){ 63 | for(int j=i-1;j>=-1;j--){ 64 | int nontake=dp[i+1][j+1]; 65 | int take=0; 66 | 67 | if(j==-1 || nums[i]>nums[j]){ 68 | take=1+dp[i+1][i+1]; 69 | } 70 | dp[i][j+1]=max(take,nontake); 71 | } 72 | 73 | } 74 | 75 | return dp[0][0]; 76 | } 77 | }; 78 | 79 | Approach 4 : Space Optimisation 80 | 81 | class Solution { 82 | public: 83 | 84 | 85 | int lengthOfLIS(vector& nums) { 86 | int n=nums.size(); 87 | vectornext(n+1,0),curr(n+1,0); 88 | 89 | for(int i=n-1;i>=0;i--){ 90 | for(int j=i-1;j>=-1;j--){ 91 | int nontake=next[j+1]; 92 | int take=0; 93 | 94 | if(j==-1 || nums[i]>nums[j]){ 95 | take=1+next[i+1]; 96 | } 97 | curr[j+1]=max(take,nontake); 98 | } 99 | next=curr; 100 | 101 | } 102 | 103 | return curr[0]; 104 | } 105 | }; 106 | 107 | Approach 5 : 1D array Space optimization 108 | 109 | class Solution { 110 | public: 111 | 112 | 113 | int lengthOfLIS(vector& nums) { 114 | int n=nums.size(); 115 | vectordp(n,1); 116 | 117 | for(int i=0;inums[j]){ 120 | dp[i]=max(dp[i],1+dp[j]); 121 | } 122 | } 123 | } 124 | 125 | int maxi=-1; 126 | 127 | for(int i=0;i& nums) { 142 | int n=nums.size(); 143 | vectordp(n,1); 144 | int maxi=-1; 145 | 146 | for(int i=0;inums[j]){ 149 | dp[i]=max(dp[i],1+dp[j]); 150 | } 151 | 152 | } 153 | maxi=max(maxi,dp[i]); 154 | } 155 | 156 | return maxi; 157 | } 158 | }; 159 | 160 | Approach 7 : Printing LIS 161 | 162 | vectordp(n,1),hash(n); 163 | int maxi=-1; 164 | int last_Idx=0; 165 | 166 | for(int i=0;inums[j] && dp[i]<1+dp[j]){ 170 | dp[i]=1+dp[j]; 171 | hash[i]=j; 172 | } 173 | 174 | } 175 | if(dp[i]>maxi){ 176 | maxi=dp[i]; 177 | last_Idx=i; 178 | } 179 | } 180 | 181 | vectorans; 182 | 183 | while(hash[last_Idx]!=last_Idx){ 184 | ans.push_back(nums[last_Idx]); 185 | last_Idx=hash[last_Idx]; 186 | } 187 | ans.push_back(nums[last_Idx]); 188 | reverse(ans.begin(),ans.end()); 189 | 190 | return ans; 191 | 192 | -------------------------------------------------------------------------------- /Dynamic_Programming/LongestCommonSubString.cpp: -------------------------------------------------------------------------------- 1 | It is same as that of normal lcs but we dont have to carry our past soo put zero when they dont match 2 | 3 | class Solution{ 4 | public: 5 | 6 | int longestCommonSubstr (string text1, string text2, int n, int m) 7 | { 8 | // your code here 9 | int ans=0; 10 | vector>dp(n+1,vector(m+1,0)); 11 | 12 | for(int i=0;i>&dp){ 5 | if(i<0 || j<0)return 0; 6 | if(dp[i][j]!=-1)return dp[i][j]; 7 | if(s[i]==t[j])return dp[i][j]=1+helper(i-1,j-1,s,t,dp); 8 | 9 | else return dp[i][j]=max(helper(i-1,j,s,t,dp),helper(i,j-1,s,t,dp)); 10 | } 11 | //Function to find the length of longest common subsequence in two strings. 12 | int lcs(int n, int m, string text1, string text2) 13 | { 14 | // your code here 15 | int i=text1.size(); 16 | int j=text2.size(); 17 | vector>dp(i+1,vector(j+1,-1)); 18 | 19 | return helper(i-1,j-1,text1,text2,dp); 20 | } 21 | int longestPalinSubseq(string A) { 22 | //code here 23 | string b=A; 24 | reverse(b.begin(),b.end()); 25 | return lcs(A.size(),A.size(),A,b); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Dynamic_Programming/Maximum Length of Pair Chain.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/maximum-length-of-pair-chain/description/ 2 | 3 | LIS VARIANT 4 | 5 | class Solution { 6 | public: 7 | int helper(vector>& nums,int idx,int prev, vector>&dp){ 8 | if(idx==nums.size())return 0; 9 | 10 | if(dp[idx][prev+1]!=-1)return dp[idx][prev+1]; 11 | 12 | int nontake=helper(nums,idx+1,prev,dp); 13 | int take=0; 14 | 15 | if(prev==-1 || nums[idx][0]>nums[prev][1]){ 16 | take=1+helper(nums,idx+1,idx,dp); 17 | } 18 | 19 | return dp[idx][prev+1]=max(take,nontake); 20 | } 21 | 22 | int lengthOfLIS(vector>& nums) { 23 | vector>dp(nums.size(),vector(nums.size()+1,-1)); 24 | return helper(nums,0,-1,dp); 25 | } 26 | int findLongestChain(vector>& nums) { 27 | sort(nums.begin(),nums.end()); 28 | return lengthOfLIS(nums); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Dynamic_Programming/Minimum ASCII Delete Sum for Two Strings.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/ 2 | 3 | Approach : MEMOIZATION 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(string& s1,string &s2,int n,int m, vector>&dp){ 9 | 10 | if(n>=s1.length()){ 11 | int val=0; 12 | while(m=s2.length()){ 19 | int val=0; 20 | while(n>dp(s1.length()+1,vector(s2.length()+1,-1)); 43 | return helper(s1,s2,0,0,dp); 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Dynamic_Programming/Minimum Falling Path Sum.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/minimum-falling-path-sum/description/ 2 | 3 | Approach 1: Memo 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector>& matrix,int i,int j,int n,int m,vector>&dp){ 9 | if(i<0||j<0 || j>=m || i>=n)return 1e9; 10 | if(i==n-1)return matrix[i][j]; 11 | 12 | 13 | if(dp[i][j]!=-1)return dp[i][j]; 14 | // cout<<"Hey"<<" "; 15 | 16 | int down=matrix[i][j]+helper(matrix,i+1,j,n,m,dp); 17 | int right=matrix[i][j]+helper(matrix,i+1,j+1,n,m,dp); 18 | int left=matrix[i][j]+helper(matrix,i+1,j-1,n,m,dp); 19 | 20 | return dp[i][j]=min(down,min(right,left)); 21 | 22 | } 23 | 24 | int minFallingPathSum(vector>& matrix) { 25 | int n=matrix.size(); 26 | int m=matrix[0].size(); 27 | vector>dp(n,vector(m,-1)); 28 | 29 | int maxi=INT_MAX; 30 | int row=0; 31 | for(int i=0;i>& matrix,int i,int j,int n,int m,vector>&dp){ 45 | if(i<0||j<0 || j>=m || i>=n)return 1e9; 46 | if(i==n-1)return matrix[i][j]; 47 | 48 | 49 | if(dp[i][j]!=-1)return dp[i][j]; 50 | // cout<<"Hey"<<" "; 51 | 52 | int down=matrix[i][j]+helper(matrix,i+1,j,n,m,dp); 53 | int right=matrix[i][j]+helper(matrix,i+1,j+1,n,m,dp); 54 | int left=matrix[i][j]+helper(matrix,i+1,j-1,n,m,dp); 55 | 56 | return dp[i][j]=min(down,min(right,left)); 57 | 58 | } 59 | 60 | int minFallingPathSum(vector>& matrix) { 61 | int n=matrix.size(); 62 | int m=matrix[0].size(); 63 | vector>dp(n,vector(m,-1)); 64 | for(int i=0;i=0;i--){ 69 | for(int j=m-1;j>=0;j--){ 70 | 71 | int left=1e9,right=1e9,down=1e9; 72 | 73 | down=matrix[i][j]+dp[i+1][j]; 74 | if( j0) left=matrix[i][j]+dp[i+1][j-1]; 76 | 77 | dp[i][j]=min(down,min(right,left)); 78 | } 79 | } 80 | int maxi=dp[0][0]; 81 | 82 | for(int i=0;i>& matrix) { 94 | int n=matrix.size(); 95 | int m=matrix[0].size(); 96 | vectorprev(m,-1); 97 | for(int i=0;i=0;i--){ 102 | vectorcurr(m,-1); 103 | for(int j=m-1;j>=0;j--){ 104 | 105 | int left=1e9,right=1e9,down=1e9; 106 | 107 | down=matrix[i][j]+prev[j]; 108 | if( j0) left=matrix[i][j]+prev[j-1]; 110 | 111 | curr[j]=min(down,min(right,left)); 112 | } 113 | prev=curr; 114 | } 115 | int maxi=prev[0]; 116 | 117 | for(int i=0;i>dp(n+1,vector(m+1,0)); 9 | 10 | // return helper(i-1,j-1,text1,text2,dp); 11 | for(int i=0;i>& grid,int row,int col,vector>&dp){ 9 | if(row==0 && col==0)return grid[row][col]; 10 | if(row<0 || col<0) return 1e8; 11 | 12 | if(dp[row][col]!=-1)return dp[row][col]; 13 | 14 | return dp[row][col]= grid[row][col]+min(helper(grid,row,col-1,dp) 15 | ,helper(grid,row-1,col,dp)); 16 | } 17 | 18 | int minPathSum(vector>& grid) { 19 | int n=grid.size(); 20 | int m=grid[0].size(); 21 | vector>dp(n,vector(m,-1)); 22 | return helper(grid,n-1,m-1,dp); 23 | } 24 | }; 25 | 26 | Approach 2 : Tabulation 27 | 28 | class Solution { 29 | public: 30 | 31 | int minPathSum(vector>& grid) { 32 | int n=grid.size(); 33 | int m=grid[0].size(); 34 | vector>dp(n,vector(m,-1)); 35 | 36 | 37 | 38 | for(int i=0;i0)up=grid[i][j]+dp[i-1][j]; 49 | if(j>0)left=grid[i][j]+dp[i][j-1]; 50 | 51 | dp[i][j]=min(up,left); 52 | } 53 | } 54 | } 55 | 56 | return dp[n-1][m-1]; 57 | 58 | } 59 | }; 60 | 61 | Approach 3 : Space Optimization 62 | 63 | class Solution { 64 | public: 65 | 66 | int minPathSum(vector>& grid) { 67 | int n=grid.size(); 68 | int m=grid[0].size(); 69 | 70 | 71 | vectorprev(m,-1); 72 | 73 | for(int i=0;icurr(m,-1); 76 | for(int j=0;j0)up=grid[i][j]+prev[j]; 86 | if(j>0)left=grid[i][j]+curr[j-1]; 87 | 88 | curr[j]=min(up,left); 89 | } 90 | } 91 | prev=curr; 92 | } 93 | 94 | return prev[m-1]; 95 | 96 | } 97 | }; 98 | -------------------------------------------------------------------------------- /Dynamic_Programming/Minimum number of deletions and insertions.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://www.geeksforgeeks.org/problems/minimum-number-of-deletions-and-insertions0209/1 2 | 3 | class Solution{ 4 | 5 | 6 | public: 7 | int helper(int i,int j,string &s,string &t, vector>&dp){ 8 | if(i<0 || j<0)return 0; 9 | if(dp[i][j]!=-1)return dp[i][j]; 10 | if(s[i]==t[j])return dp[i][j]=1+helper(i-1,j-1,s,t,dp); 11 | 12 | else return dp[i][j]=max(helper(i-1,j,s,t,dp),helper(i,j-1,s,t,dp)); 13 | } 14 | //Function to find the length of longest common subsequence in two strings. 15 | int lcs(int n, int m, string text1, string text2) 16 | { 17 | // your code here 18 | int i=text1.size(); 19 | int j=text2.size(); 20 | vector>dp(i+1,vector(j+1,-1)); 21 | 22 | return helper(i-1,j-1,text1,text2,dp); 23 | } 24 | int minOperations(string str1, string str2) 25 | { 26 | // Your code goes here 27 | return str1.size()+str2.size()-2*lcs(str1.size(),str2.size(),str1,str2); 28 | 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Dynamic_Programming/Number Of LIS.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/ 2 | 3 | class Solution { 4 | public: 5 | int findNumberOfLIS(vector& arr) { 6 | int n=arr.size(); 7 | vectordp(n,1),cnt(n,1); 8 | int maxi = -1; 9 | 10 | for(int i=0;iarr[j]&& dp[j]+1>dp[i]){ 13 | dp[i]=1+dp[j]; 14 | cnt[i]=cnt[j]; 15 | } 16 | else if(arr[i]>arr[j]&& dp[j]+1==dp[i]){ 17 | cnt[i]+=cnt[j]; 18 | } 19 | } 20 | maxi=max(maxi,dp[i]); 21 | } 22 | 23 | int ans=0; 24 | 25 | for(int i=0;i>& matrix, int target) { 6 | int rows = matrix.size(); //m 7 | int cols = matrix[0].size(); //n 8 | 9 | //First taje the cumulative sum row-wise 10 | for(int row = 0; row mp; 25 | mp[0] = 1; 26 | int sum = 0; 27 | //Go downwards row wise 28 | for(int row = 0; row 0 ? matrix[row][startCol-1] : 0); 30 | 31 | if(mp.count(sum-target)) { 32 | result += mp[sum-target]; 33 | } 34 | 35 | mp[sum]++; 36 | 37 | } 38 | 39 | } 40 | } 41 | 42 | return result; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Dynamic_Programming/PrintLcs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | string PrintLCS(string text1, string text2) { 5 | int n=text1.length(); 6 | int m=text2.length(); 7 | vector>dp(n+1,vector(m+1,-1)); 8 | 9 | for(int i=0;i<=n;i++)dp[i][0]=0; 10 | for(int i=0;i<=m;i++)dp[0][i]=0; 11 | 12 | for(int i=1;i<=n;i++){ 13 | for(int j=1;j<=m;j++){ 14 | if(text1[i-1]==text2[j-1]) dp[i][j]=1 +dp[i-1][j-1]; 15 | 16 | else dp[i][j]=max(dp[i][j-1],dp[i-1][j]); 17 | } 18 | } 19 | 20 | string LCS=""; 21 | int len=dp[n][m]; 22 | len--; 23 | for(int i=0;i<=len;i++){ 24 | LCS+="$"; 25 | } 26 | int i=text1.length(),j=text2.length(); 27 | while(i>0 &&j>0){ 28 | 29 | if(text1[i-1]==text2[j-1]){ 30 | 31 | LCS[len]=text1[i-1]; 32 | len--; 33 | i--; 34 | j--; 35 | 36 | } 37 | else if(dp[i-1][j]>dp[i][j-1]){ 38 | i--; 39 | } 40 | else j--; 41 | } 42 | 43 | return LCS; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Dynamic_Programming/Rod Cutting.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://www.geeksforgeeks.org/problems/rod-cutting0840/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article 2 | 3 | Approach 1 : Memo 4 | 5 | class Solution{ 6 | public: 7 | 8 | int helper(int price[], int n,int idx, vector>&dp){ 9 | if(idx==0)return price[0]*n; 10 | if(dp[n][idx]!=-1)return dp[n][idx]; 11 | int nontake=helper(price,n,idx-1,dp); 12 | int take=INT_MIN; 13 | if((idx+1)<=n)take=price[idx]+helper(price,n-idx-1,idx,dp); 14 | 15 | return dp[n][idx]=max(take,nontake); 16 | 17 | 18 | } 19 | 20 | int cutRod(int price[], int n) { 21 | //code here 22 | vector>dp(n+1,vector(n,-1)); 23 | return helper(price,n,n-1,dp); 24 | } 25 | }; 26 | 27 | Approach 2 : Tabulation 28 | 29 | class Solution{ 30 | public: 31 | 32 | int helper(int price[], int n,int idx, vector>&dp){ 33 | if(idx==0)return price[0]*n; 34 | if(dp[n][idx]!=-1)return dp[n][idx]; 35 | int nontake=helper(price,n,idx-1,dp); 36 | int take=INT_MIN; 37 | if((idx+1)<=n)take=price[idx]+helper(price,n-idx-1,idx,dp); 38 | 39 | return dp[n][idx]=max(take,nontake); 40 | 41 | 42 | } 43 | 44 | int cutRod(int price[], int n) { 45 | //code here 46 | vector>dp(n+1,vector(n,-1)); 47 | return helper(price,n,n-1,dp); 48 | } 49 | }; 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Dynamic_Programming/Shortest Common Supersequence .cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/shortest-common-supersequence/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | string PrintLCS(string text1, string text2) { 7 | int n=text1.length(); 8 | int m=text2.length(); 9 | vector>dp(n+1,vector(m+1,-1)); 10 | 11 | for(int i=0;i<=n;i++)dp[i][0]=0; 12 | for(int i=0;i<=m;i++)dp[0][i]=0; 13 | 14 | for(int i=1;i<=n;i++){ 15 | for(int j=1;j<=m;j++){ 16 | if(text1[i-1]==text2[j-1]) dp[i][j]=1 +dp[i-1][j-1]; 17 | 18 | else dp[i][j]=max(dp[i][j-1],dp[i-1][j]); 19 | } 20 | } 21 | 22 | string LCS=""; 23 | 24 | int i=text1.length(),j=text2.length(); 25 | while(i>0 &&j>0){ 26 | 27 | if(text1[i-1]==text2[j-1]){ 28 | 29 | LCS.push_back(text1[i-1]); 30 | 31 | i--; 32 | j--; 33 | 34 | } 35 | else if(dp[i-1][j]>dp[i][j-1]){ 36 | LCS.push_back(text1[i-1]); 37 | i--; 38 | } 39 | else { 40 | LCS.push_back(text2[j-1]); 41 | j--; 42 | } 43 | 44 | } 45 | while(i>0){ 46 | LCS.push_back(text1[i-1]); 47 | i--; 48 | 49 | } 50 | while(j>0){ 51 | LCS.push_back(text2[j-1]); 52 | j--; 53 | 54 | } 55 | reverse(LCS.begin(),LCS.end()); 56 | return LCS; 57 | 58 | } 59 | 60 | string shortestCommonSupersequence(string str1, string str2) { 61 | return PrintLCS(str1,str2); 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Dynamic_Programming/Triangle.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/triangle/description/ 2 | 3 | Approach 1 : recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector>&triangle,int row,int col,int n){ 9 | if(row==n-1)return triangle[row][col]; 10 | 11 | int down=triangle[row][col]+helper(triangle,row+1,col,n); 12 | int right=triangle[row][col]+helper(triangle,row+1,col+1,n); 13 | 14 | return min(down,right); 15 | } 16 | 17 | int minimumTotal(vector>& triangle) { 18 | 19 | int n=triangle.size(); 20 | int idx=0; 21 | return helper(triangle,idx,idx,n); 22 | } 23 | }; 24 | 25 | Approach 2 : Memo 26 | 27 | class Solution { 28 | public: 29 | 30 | int helper(vector>&triangle,int row,int col,int n, vector>&dp){ 31 | if(row==n-1)return triangle[row][col]; 32 | 33 | if(dp[row][col]!=-1)return dp[row][col]; 34 | 35 | int down=triangle[row][col]+helper(triangle,row+1,col,n,dp); 36 | int right=triangle[row][col]+helper(triangle,row+1,col+1,n,dp); 37 | 38 | return dp[row][col]=min(down,right); 39 | } 40 | 41 | int minimumTotal(vector>& triangle) { 42 | 43 | int n=triangle.size(); 44 | vector>dp(n,vector(n,-1)); 45 | int idx=0; 46 | return helper(triangle,idx,idx,n,dp); 47 | } 48 | }; 49 | 50 | Approach 3 : Tabulation 51 | 52 | class Solution { 53 | public: 54 | 55 | int minimumTotal(vector>& triangle) { 56 | 57 | int n=triangle.size(); 58 | vector>dp(n,vector(n,-1)); 59 | 60 | for(int i=0;i=0;i--){ 63 | for(int j=i;j>=0;j--){ 64 | int down=triangle[i][j]+dp[i+1][j]; 65 | int right=triangle[i][j]+dp[i+1][j+1]; 66 | 67 | dp[i][j]=min(down,right); 68 | } 69 | } 70 | 71 | return dp[0][0]; 72 | } 73 | }; 74 | 75 | Approach 4 : Space Optimization 76 | 77 | class Solution { 78 | public: 79 | 80 | int minimumTotal(vector>& triangle) { 81 | 82 | int n=triangle.size(); 83 | 84 | vectorfront(n,-1); 85 | 86 | for(int i=0;i=0;i--){ 89 | vectorcurr(n,-1); 90 | for(int j=i;j>=0;j--){ 91 | int down=triangle[i][j]+front[j]; 92 | int right=triangle[i][j]+front[j+1]; 93 | 94 | curr[j]=min(down,right); 95 | } 96 | front=curr; 97 | } 98 | 99 | return front[0]; 100 | } 101 | }; 102 | -------------------------------------------------------------------------------- /Dynamic_Programming/Unbounded_KnapSack.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://www.geeksforgeeks.org/problems/knapsack-with-duplicate-items4201/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution{ 6 | public: 7 | 8 | int helper(int idx, int W, int val[], int wt[]){ 9 | 10 | if(idx==0){ 11 | return (W/wt[0])*val[0]; 12 | } 13 | 14 | int nontake=helper(idx-1,W,val,wt); 15 | int take=INT_MIN; 16 | if(wt[idx]<=W)take=val[idx]+helper(idx,W-wt[idx],val,wt); 17 | 18 | return max(take,nontake); 19 | } 20 | 21 | int knapSack(int N, int W, int val[], int wt[]) 22 | { 23 | // code here 24 | return helper(N-1,W,val,wt); 25 | } 26 | }; 27 | 28 | Approach 2 : Memo 29 | 30 | class Solution{ 31 | public: 32 | 33 | int helper(int idx, int W, int val[], int wt[], vector>&dp){ 34 | 35 | if(idx==0){ 36 | return (W/wt[0])*val[0]; 37 | } 38 | if(dp[idx][W]!=-1)return dp[idx][W]; 39 | int nontake=helper(idx-1,W,val,wt,dp); 40 | int take=INT_MIN; 41 | if(wt[idx]<=W)take=val[idx]+helper(idx,W-wt[idx],val,wt,dp); 42 | 43 | return dp[idx][W]=max(take,nontake); 44 | } 45 | 46 | int knapSack(int N, int W, int val[], int wt[]) 47 | { 48 | // code here 49 | vector>dp(N,vector(W+1,-1)); 50 | return helper(N-1,W,val,wt,dp); 51 | } 52 | }; 53 | 54 | Approach 3 : Tabulation 55 | 56 | class Solution{ 57 | public: 58 | 59 | 60 | 61 | int knapSack(int N, int W, int val[], int wt[]) 62 | { 63 | // code here 64 | vector>dp(N,vector(W+1,-1)); 65 | for(int i=0;i<=W;i++){ 66 | dp[0][i]= (i/wt[0])*val[0]; 67 | } 68 | for(int i=1;iprev(W+1,0),curr(W+1,0); 92 | for(int i=0;i<=W;i++){ 93 | prev[i]= (i/wt[0])*val[0]; 94 | } 95 | for(int i=1;i>&dp){ 9 | if(m==0 && n==0)return 1; 10 | if(m<0 || n<0)return 0; 11 | if(dp[m][n]!=-1)return dp[m][n]; 12 | int up=helper(m-1,n,dp); 13 | int left=helper(m,n-1,dp); 14 | 15 | return dp[m][n]=up+left; 16 | } 17 | 18 | int uniquePaths(int m, int n) { 19 | 20 | vector>dp(m,vector(n,-1)); 21 | 22 | return helper(m-1,n-1,dp); 23 | 24 | } 25 | }; 26 | 27 | Approach 2 : Tabulation 28 | 29 | class Solution { 30 | public: 31 | 32 | int uniquePaths(int m, int n) { 33 | 34 | vector>dp(m,vector(n,-1)); 35 | 36 | for(int i=0;i0)up=dp[i-1][j]; 44 | if(j>0)left=dp[i][j-1]; 45 | 46 | dp[i][j]=up+left; 47 | } 48 | } 49 | } 50 | 51 | return dp[m-1][n-1]; 52 | 53 | } 54 | }; 55 | 56 | Approach 3 : Space Optimisation 57 | 58 | class Solution { 59 | public: 60 | 61 | int uniquePaths(int m, int n) { 62 | 63 | vectorprev(n,0); 64 | 65 | for(int i=0;icurr(n,0); 67 | for(int j=0;j0)up=prev[j]; 74 | if(j>0)left=curr[j-1]; 75 | 76 | curr[j]=up+left; 77 | } 78 | } 79 | prev=curr; 80 | } 81 | 82 | return prev[n-1]; 83 | 84 | } 85 | }; 86 | -------------------------------------------------------------------------------- /Dynamic_Programming/Unique Paths2.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/unique-paths-ii/description/ 2 | 3 | Approach 1 : Memo 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(vector>& grid,int row,int col, vector>&dp){ 9 | if(row==0 && col==0)return 1; 10 | if(row<0 || col<0)return 0; 11 | 12 | if(grid[row][col]==1)return 0; 13 | 14 | if(dp[row][col]!=-1)return dp[row][col]; 15 | 16 | return dp[row][col]=helper(grid,row,col-1,dp)+helper(grid,row-1,col,dp); 17 | } 18 | 19 | int uniquePathsWithObstacles(vector>& grid) { 20 | int n=grid.size(); 21 | int m=grid[0].size(); 22 | if(grid[0][0]==1)return 0; 23 | if(grid[n-1][m-1]==1)return 0; 24 | vector>dp(n,vector(m,-1)); 25 | return helper(grid,n-1,m-1,dp); 26 | 27 | } 28 | }; 29 | 30 | Approach 2 : Tabulation 31 | 32 | class Solution { 33 | public: 34 | int uniquePathsWithObstacles(vector>& grid) { 35 | int n=grid.size(); 36 | int m=grid[0].size(); 37 | if(grid[0][0]==1)return 0; 38 | if(grid[n-1][m-1]==1)return 0; 39 | vector>dp(n,vector(m,-1)); 40 | 41 | vectorprev(m,-1); 42 | 43 | for(int i=0;i0) up=dp[i-1][j]; 58 | if(j>0)left=dp[i][j-1]; 59 | 60 | dp[i][j]=up+left; 61 | } 62 | } 63 | } 64 | 65 | return dp[n-1][m-1]; 66 | 67 | } 68 | }; 69 | 70 | 71 | Approach 3 : Space Optimization 72 | 73 | class Solution { 74 | public: 75 | int uniquePathsWithObstacles(vector>& grid) { 76 | int n=grid.size(); 77 | int m=grid[0].size(); 78 | if(grid[0][0]==1)return 0; 79 | if(grid[n-1][m-1]==1)return 0; 80 | 81 | vectorprev(m,-1); 82 | 83 | for(int i=0;icurr(m,-1); 85 | for(int j=0;j0) up=prev[j]; 99 | if(j>0)left=curr[j-1]; 100 | 101 | curr[j]=up+left; 102 | } 103 | } 104 | prev=curr; 105 | } 106 | 107 | return prev[m-1]; 108 | 109 | } 110 | }; 111 | -------------------------------------------------------------------------------- /Dynamic_Programming/coin_Change.cpp: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/coin-change-ii/description/ 2 | 3 | Approach 1 : Recursion 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(int amount, vector& coins,int idx){ 9 | 10 | if(idx==0)return (amount%coins[0]==0); 11 | 12 | 13 | int nontake=helper(amount,coins,idx-1); 14 | int take=0; 15 | if(coins[idx]<=amount)take=helper(amount-coins[idx],coins,idx); 16 | 17 | return take+nontake; 18 | } 19 | 20 | int change(int amount, vector& coins) { 21 | 22 | return helper(amount,coins,coins.size()-1); 23 | } 24 | }; 25 | 26 | Approach 2 : Memo 27 | 28 | class Solution { 29 | public: 30 | 31 | int helper(int amount, vector& coins,int idx,vector>&dp){ 32 | 33 | if(idx==0)return (amount%coins[0]==0); 34 | 35 | if(dp[idx][amount]!=-1)return dp[idx][amount]; 36 | int nontake=helper(amount,coins,idx-1,dp); 37 | int take=0; 38 | if(coins[idx]<=amount)take=helper(amount-coins[idx],coins,idx,dp); 39 | 40 | return dp[idx][amount]=take+nontake; 41 | } 42 | 43 | int change(int amount, vector& coins) { 44 | vector>dp(coins.size(),vector(amount+1,-1)); 45 | return helper(amount,coins,coins.size()-1,dp); 46 | } 47 | }; 48 | 49 | Approach 3 : Tabulation 50 | class Solution { 51 | public: 52 | 53 | int change(int amount, vector& coins) { 54 | vector>dp(coins.size(),vector(amount+1,-1)); 55 | for(int i=0;i<=amount;i++)dp[0][i]=(i%coins[0]==0); 56 | for(int i=1;i& coins) { 76 | 77 | vectorprev(amount+1,0),curr(amount+1,0); 78 | for(int i=0;i<=amount;i++)prev[i]=(i%coins[0]==0); 79 | for(int i=1;i findMinHeightTrees(int n, vector>& edges) { 6 | if(n == 1) 7 | return {0}; 8 | 9 | vector result; 10 | vector indegree(n); 11 | map> adj; 12 | 13 | for(vector vec:edges) { 14 | int u = vec[0]; 15 | int v = vec[1]; 16 | indegree[u]++; 17 | indegree[v]++; 18 | adj[u].push_back(v); 19 | adj[v].push_back(u); 20 | } 21 | 22 | queue que; 23 | for(int i = 0; i 2) { 29 | int size = que.size(); 30 | n -= size; //removing nodes with indegreee 1 31 | 32 | while(size--) { 33 | int u = que.front(); 34 | que.pop(); 35 | for(int v:adj[u]) { 36 | indegree[v]--; 37 | if(indegree[v] == 1) 38 | que.push(v); 39 | } 40 | } 41 | } 42 | 43 | while(!que.empty()) { 44 | result.push_back(que.front()); 45 | que.pop(); 46 | } 47 | return result; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Graph/TopoSort/ReadME: -------------------------------------------------------------------------------- 1 | All Topo Sort Questions 2 | -------------------------------------------------------------------------------- /Graph/Topological Sort: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Linked List/2487. Remove Nodes From Linked List: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/remove-nodes-from-linked-list/description/?envType=daily-question&envId=2024-05-06 2 | 3 | Approach 1 : Reverse 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * struct ListNode { 8 | * int val; 9 | * ListNode *next; 10 | * ListNode() : val(0), next(nullptr) {} 11 | * ListNode(int x) : val(x), next(nullptr) {} 12 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | 18 | ListNode* ReverseLL(ListNode* node){ 19 | ListNode* p=node,*q=NULL,*r=NULL; 20 | 21 | while(p){ 22 | r=q; 23 | q=p; 24 | p=p->next; 25 | q->next=r; 26 | } 27 | 28 | return q; 29 | } 30 | 31 | ListNode* removeNodes(ListNode* head) { 32 | ListNode* newHead= ReverseLL(head); 33 | 34 | ListNode* p=newHead,*q=newHead->next; 35 | 36 | while(p->next!=NULL){ 37 | if(p->val>q->val){ 38 | p->next=q->next; 39 | q=q->next; 40 | } 41 | else{ 42 | p=q; 43 | q=q->next; 44 | } 45 | } 46 | 47 | ListNode* newHead2=ReverseLL(newHead); 48 | 49 | return newHead2; 50 | } 51 | }; 52 | 53 | 54 | Approch 2 : Stack 55 | 56 | /** 57 | * Definition for singly-linked list. 58 | * struct ListNode { 59 | * int val; 60 | * ListNode *next; 61 | * ListNode() : val(0), next(nullptr) {} 62 | * ListNode(int x) : val(x), next(nullptr) {} 63 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 64 | * }; 65 | */ 66 | class Solution { 67 | public: 68 | ListNode* removeNodes(ListNode* head) { 69 | stackst; 70 | 71 | ListNode* p=head; 72 | 73 | while(p){ 74 | st.push(p); 75 | p=p->next; 76 | } 77 | 78 | ListNode* node=st.top(); 79 | st.pop(); 80 | 81 | int maxi=node->val; 82 | 83 | ListNode* result=new ListNode(node->val); 84 | 85 | while(!st.empty()){ 86 | ListNode* currNode=st.top(); 87 | st.pop(); 88 | 89 | if(currNode->val>=maxi){ 90 | ListNode* newNode=new ListNode(currNode->val); 91 | currNode->next=result; 92 | result=currNode; 93 | maxi=currNode->val; 94 | } 95 | } 96 | 97 | return result; 98 | } 99 | }; 100 | -------------------------------------------------------------------------------- /Linked List/2816. Double a Number Represented as a Linked List: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/double-a-number-represented-as-a-linked-list/description/?envType=daily-question&envId=2024-05-07 2 | 3 | Approach 1 : REVERSE (R to L) 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * struct ListNode { 8 | * int val; 9 | * ListNode *next; 10 | * ListNode() : val(0), next(nullptr) {} 11 | * ListNode(int x) : val(x), next(nullptr) {} 12 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | 18 | ListNode* ReverseLL(ListNode* node){ 19 | ListNode* p=node,*q=NULL,*r=NULL; 20 | 21 | while(p){ 22 | r=q; 23 | q=p; 24 | p=p->next; 25 | q->next=r; 26 | } 27 | 28 | return q; 29 | } 30 | 31 | ListNode* doubleIt(ListNode* head) { 32 | ListNode* newHead=ReverseLL(head); 33 | 34 | ListNode* p=newHead; 35 | ListNode* q=newHead; 36 | 37 | int carry=0; 38 | 39 | while(p){ 40 | int value=p->val*2+carry; 41 | if(value>=10){ 42 | carry=1; 43 | 44 | } 45 | else{ 46 | carry=0; 47 | } 48 | value=value%10; 49 | 50 | p->val=value; 51 | q=p; 52 | p=p->next; 53 | 54 | } 55 | 56 | if(carry==1){ 57 | ListNode* newNode=new ListNode(1); 58 | q->next=newNode; 59 | } 60 | 61 | return ReverseLL(newHead); 62 | } 63 | }; 64 | 65 | 66 | Approach 2 : L to R 67 | 68 | class Solution { 69 | public: 70 | ListNode* doubleIt(ListNode* head) { 71 | ListNode* p=head; 72 | ListNode* q=NULL; 73 | 74 | bool isFirst=true; 75 | 76 | 77 | while(p){ 78 | int value=p->val*2; 79 | int carry=0; 80 | if(value>=10){ 81 | value=value%10; 82 | carry=1; 83 | } 84 | 85 | p->val=value; 86 | if(q==NULL && carry && isFirst){ 87 | ListNode* newHead=new ListNode(1); 88 | newHead->next=p; 89 | head=newHead; 90 | isFirst=false; 91 | } 92 | else if(q!=NULL && carry) q->val+=1; 93 | 94 | q=p; 95 | p=p->next; 96 | 97 | } 98 | 99 | return head; 100 | } 101 | }; 102 | -------------------------------------------------------------------------------- /Linked List/Readme: -------------------------------------------------------------------------------- 1 | ALL LL Questions goes here 2 | -------------------------------------------------------------------------------- /Matrix /861. Score After Flipping Matrix: -------------------------------------------------------------------------------- 1 | Q-lInk : https://leetcode.com/problems/score-after-flipping-matrix/description/?envType=daily-question&envId=2024-05-13 2 | 3 | class Solution { 4 | public: 5 | int matrixScore(vector>& grid) { 6 | 7 | int n=grid.size(); 8 | int m=grid[0].size(); 9 | 10 | int ans=0; 11 | 12 | ans+=(pow(2,m-1)*n); 13 | 14 | for(int j=1;j V; 6 | 7 | vector kthSmallestPrimeFraction(vector& arr, int k) { 8 | int n = arr.size(); 9 | priority_queue, greater> pq; 10 | 11 | for(int i = 0; i < n; i++) 12 | pq.push({1.0*arr[i]/arr.back(), (double)(i), (double)(n-1)}); 13 | 14 | int smallest = 1; 15 | 16 | while(smallest < k) { 17 | V vec = pq.top(); 18 | pq.pop(); 19 | 20 | int i = vec[1]; 21 | int j = vec[2]-1; 22 | 23 | 24 | pq.push({1.0*arr[i]/arr[j], (double)(i), (double)(j)}); 25 | smallest++; 26 | } 27 | 28 | V vec = pq.top(); 29 | int i = vec[1]; 30 | int j = vec[2]; 31 | return {arr[i], arr[j]}; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Priority_Queue/Readme: -------------------------------------------------------------------------------- 1 | All Priority QUestions Goes Here 2 | -------------------------------------------------------------------------------- /Queue/Readme: -------------------------------------------------------------------------------- 1 | All th queue questions here 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures Repository 2 | 3 | ## Overview 4 | 5 | Welcome to the Data Structures Repository! This repository serves as a comprehensive collection of questions and resources related to various data structures. Whether you're a student learning about data structures, a software engineer preparing for technical interviews, or anyone interested in strengthening their understanding, you'll find a wealth of information organized by specific data structure topics. 6 | 7 | ## Table of Contents 8 | 9 | - [Data Structures](#data-structures) 10 | - [Contributing](#contributing) 11 | - [License](#license) 12 | 13 | ## Data Structures 14 | 15 | Explore questions and resources organized by data structure types: 16 | 17 | 1. [Arrays](/data-structures/arrays) 18 | - Basic operations, manipulation, and common algorithms. 19 | 20 | 2. [Linked Lists](/data-structures/linked-lists) 21 | - Singly linked lists, doubly linked lists, circular linked lists, and related algorithms. 22 | 23 | 3. [Stacks](/data-structures/stacks) 24 | - Fundamental stack operations, applications, and problems. 25 | 26 | 4. [Queues](/data-structures/queues) 27 | - Basic queue operations, types of queues, and real-world applications. 28 | 29 | 5. [Trees](/data-structures/trees) 30 | - Binary trees, AVL trees, heap trees, and various tree traversal techniques. 31 | 32 | 6. [Graphs](/data-structures/graphs) 33 | - Graph representations, traversal, and common algorithms. 34 | 35 | 7. [Hashing](/data-structures/hashing) 36 | - Hash functions, collision resolution, and hash table operations. 37 | 38 | Feel free to contribute by adding new questions, solutions, or suggesting improvements to existing content. 39 | 40 | ## Contributing 41 | 42 | We encourage contributions to enhance the repository! If you have questions to add, solutions to existing problems, or want to improve documentation, follow these steps: 43 | 44 | 1. Fork the repository. 45 | 2. Create a new branch (`git checkout -b feature/add-new-topic`). 46 | 3. Add your content or make changes. 47 | 4. Commit your changes (`git commit -m 'Add new questions for Linked Lists'`). 48 | 5. Push to the branch (`git push origin feature/add-new-topic`). 49 | 6. Open a Pull Request. 50 | 51 | ## License 52 | 53 | This repository is licensed under the [MIT License](/LICENSE). See the [LICENSE](/LICENSE) file for details. 54 | -------------------------------------------------------------------------------- /Sliding Window /1208. Get Equal Substrings Within Budget: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/get-equal-substrings-within-budget/?envType=daily-question&envId=2024-05-28 2 | 3 | class Solution { 4 | public: 5 | int equalSubstring(string s, string t, int maxCost) { 6 | vectorvec(s.length()); 7 | 8 | for(int i=0;imaxCost){ 23 | sum-=vec[i]; 24 | i++; 25 | } 26 | 27 | ans=max(ans,j-i+1); 28 | 29 | j++; 30 | 31 | } 32 | 33 | 34 | return ans; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Sliding Window /Readme: -------------------------------------------------------------------------------- 1 | ALl the SW Questions here 2 | -------------------------------------------------------------------------------- /Sorting/1051. Height Checker: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/height-checker/description/ 2 | 3 | class Solution { 4 | public: 5 | int heightChecker(vector& heights) { 6 | vector v=heights; 7 | int ans=0; 8 | sort(v.begin(),v.end()); 9 | for(int i=0;i& happiness, int k) { 6 | long long ans=0; 7 | 8 | sort(happiness.begin(),happiness.end(),greater()); 9 | 10 | for(int i=0;i& people, int limit) { 6 | sort(begin(people),end(people)); 7 | int n=people.size(); 8 | 9 | int ans=0; 10 | 11 | int i=0,j=n-1; 12 | 13 | while(i<=j){ 14 | if(people[i]+people[j]<=limit){ 15 | i++; 16 | j--; 17 | } 18 | else{ 19 | j--; 20 | } 21 | ans++; 22 | } 23 | 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Sorting/ReadMe: -------------------------------------------------------------------------------- 1 | All Sorting Questions goes here 2 | -------------------------------------------------------------------------------- /Stacks/Readme: -------------------------------------------------------------------------------- 1 | ALL the stacks questions here 2 | -------------------------------------------------------------------------------- /Strings/165. Compare Version Numbers: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/compare-version-numbers/description/?envType=daily-question&envId=2024-05-03 2 | 3 | class Solution { 4 | public: 5 | int compareVersion(string version1, string version2) { 6 | vectorv1(501,0),v2(501,0); 7 | 8 | 9 | string s=""; 10 | int j=0; 11 | 12 | for(int i=0;i0) v1[j++]=stoi(s); 16 | else j++; 17 | s=""; 18 | } 19 | else{ 20 | if(s.length()==0 && version1[i]=='0')continue; 21 | else{ 22 | s+=version1[i]; 23 | } 24 | } 25 | } 26 | 27 | if(s.length()>0) v1[j++]=stoi(s); 28 | 29 | s=""; 30 | j=0; 31 | 32 | for(int i=0;i0) v2[j++]=stoi(s); 37 | else j++; 38 | s=""; 39 | } 40 | else{ 41 | if(s.length()==0 && version2[i]=='0')continue; 42 | else{ 43 | s+=version2[i]; 44 | } 45 | } 46 | } 47 | 48 | if(s.length()>0) v2[j++]=stoi(s); 49 | 50 | 51 | for(int i=0;i<=500;i++){ 52 | if(v1[i]>v2[i])return 1; 53 | else if(v1[i]val); 11 | if(!node->left && !node->right){ 12 | int val=stoi(s); 13 | ans+=val; 14 | } 15 | 16 | helper(node->left,s); 17 | helper(node->right,s); 18 | } 19 | 20 | int sumNumbers(TreeNode* root) { 21 | string s; 22 | 23 | helper(root,s); 24 | 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Trees/1325. Delete Leaves With a Given Value: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/delete-leaves-with-a-given-value/description/?envType=daily-question&envId=2024-05-17 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | TreeNode* removeLeafNodes(TreeNode* root, int target) { 17 | if(!root)return NULL; 18 | root->left=removeLeafNodes(root->left,target); 19 | root->right=removeLeafNodes(root->right,target); 20 | return (root->val==target && root->left==NULL && root->right==NULL)? 21 | NULL :root; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Trees/2331. Evaluate Boolean Binary Tree: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/evaluate-boolean-binary-tree/description/?envType=daily-question&envId=2024-05-16 2 | 3 | class Solution { 4 | public: 5 | bool evaluateTree(TreeNode* root) { 6 | if(root->left==NULL && root->right==NULL){ 7 | return root->val; 8 | 9 | } 10 | bool left= evaluateTree(root->left); 11 | bool right= evaluateTree(root->right); 12 | return (root->val==3)?left&&right:left|| right; 13 | 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Trees/404. Sum of Left Leaves: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/sum-of-left-leaves/description/?envType=daily-question&envId=2024-04-14 2 | 3 | class Solution { 4 | public: 5 | 6 | int helper(TreeNode* node,bool dir){ 7 | if(node==NULL)return 0; 8 | if(dir && node->left==NULL && node->right==NULL)return node->val; 9 | 10 | return helper(node->left,true)+helper(node->right,false); 11 | } 12 | 13 | int sumOfLeftLeaves(TreeNode* root) { 14 | return helper(root,false); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Trees/623. Add One Row to Tree: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/add-one-row-to-tree/description/?envType=daily-question&envId=2024-04-16 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | 17 | void helper(TreeNode* node,int val,int depth,int ourDepth){ 18 | if(node==NULL)return ; 19 | if(ourDepth==depth-1){ 20 | TreeNode* created=new TreeNode(val); 21 | created->left=node->left; 22 | node->left=created; 23 | 24 | TreeNode* created2=new TreeNode(val); 25 | created2->right=node->right; 26 | node->right=created2; 27 | 28 | return ; 29 | } 30 | 31 | helper(node->left,val,depth,ourDepth+1); 32 | helper(node->right,val,depth,ourDepth+1); 33 | 34 | 35 | } 36 | 37 | TreeNode* addOneRow(TreeNode* root, int val, int depth) { 38 | if(depth==1){ 39 | TreeNode* node=new TreeNode(val); 40 | node->left=root; 41 | node->right=NULL; 42 | return node; 43 | } 44 | 45 | helper(root,val,depth,1); 46 | 47 | return root; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Trees/979. Distribute Coins in Binary Tree: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/distribute-coins-in-binary-tree/description/?envType=daily-question&envId=2024-05-18 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | 17 | int steps=0; 18 | 19 | int helper(TreeNode* node){ 20 | if(node==NULL)return 0; 21 | int l=helper(node->left); 22 | int r=helper(node->right); 23 | 24 | steps+=abs(l)+abs(r); 25 | 26 | return l+r+node->val-1; 27 | } 28 | 29 | int distributeCoins(TreeNode* root) { 30 | int ans= helper(root); 31 | 32 | return steps; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Trees/988. Smallest String Starting From Leaf: -------------------------------------------------------------------------------- 1 | Q-Link : https://leetcode.com/problems/smallest-string-starting-from-leaf/description/?envType=daily-question&envId=2024-04-17 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | 17 | void helper(TreeNode* node,string & ans,string value){ 18 | if(node==NULL)return ; 19 | 20 | value = char((node->val + 'a'))+value; 21 | 22 | if(node->left==NULL && node->right==NULL){ 23 | if(ans=="" || ans>value){ 24 | ans=value; 25 | } 26 | } 27 | 28 | helper(node->left,ans,value); 29 | helper(node->right,ans,value); 30 | } 31 | 32 | string smallestFromLeaf(TreeNode* root) { 33 | string ans=""; 34 | string value=""; 35 | 36 | helper(root,ans,value); 37 | 38 | return ans; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Trees/Readme: -------------------------------------------------------------------------------- 1 | All Tree Questions here 2 | --------------------------------------------------------------------------------