├── README.md ├── UglyNumber.cpp ├── SameTrees.cpp ├── ClimbingStairs.cpp ├── Max69number.cpp ├── HouseRobber.cpp ├── GCDString.cpp ├── JumpGame.cpp ├── Toeplitz.cpp ├── MyCalenderIII.cpp ├── TwoStringEqual.cpp ├── CountOddNumberInterval.cpp ├── DetectCapital.cpp ├── OrderlyQueue.cpp ├── OnlineStockSpan.cpp ├── RemoveStones.cpp ├── ContainsDuplicate2.cpp ├── GuessNumber.cpp ├── JumpII.cpp ├── largestPerimeter.cpp ├── AddArrayForm.cpp ├── RemoveDuplicate.cpp ├── 540.SingleElementInArray.cpp ├── MaxBagWithFullCapacity.cpp ├── maxilengthunique.cpp ├── FlipString.cpp ├── PerfectSquare.cpp ├── DailyTemperature.cpp ├── ReactangleArea.cpp ├── FindTownJudge.cpp ├── SubarraySumDivisibleByk.cpp ├── 35.SearchInsertPostion.cpp ├── ImplementQueueStack.cpp ├── increasingTriplet.cpp ├── EvalutateReversePolishNotation.cpp ├── BreakPalindrome.cpp ├── Decode.cpp ├── UniqueNumberOfOccurance.cpp ├── deleteNodeLinkedList.cpp ├── MaxDepthBinaryTree.cpp ├── PanagramCheck.cpp ├── MinTimeRopeColorful.cpp ├── AddBinary.cpp ├── DetermineifStringHalves.cpp ├── ReverseWordsInAString.cpp ├── MiddleOfLinkedList.cpp ├── LeafSimilarTrees.cpp ├── MaxDiffBetAncAndNode.cpp ├── MakeTheStringGreat.cpp ├── DeleteColn.cpp ├── RemoveAllAdjacentDuplicate.cpp ├── LongestSubsequenceWithLimitedSum.cpp ├── SetMismatch.cpp ├── DetermineIfTwoStringAreClose.cpp ├── KeysAndRooms.cpp ├── MinArrowsThrown.cpp ├── LCS.cpp ├── KClosest.cpp ├── EarliestPossibleFullBloom.cpp ├── GasStation.cpp ├── NonDecreasingSubsequence.cpp ├── ValidSudoko.cpp ├── MinimumRoundToComplete.cpp ├── SortCharactersByFrequency.cpp ├── TimeBasedkeyvalue.cpp ├── InvertBinaryTree.cpp ├── Graph ├── DFS │ ├── Number of Islands.cpp │ ├── Count Sub Islands.cpp │ ├── Minimum Number of Days to Disconnect Island.cpp │ └── Regions Cut By Slashes.cpp └── DSU │ ├── Disjoint set(Union-Find-Rank) Path Compression.cpp Latest │ ├── Disjoint set(Union-Find-Size).cpp │ ├── Minimum Weighted Subgraph With the Required Paths.cpp │ └── Making A Large Island.cpp ├── GroupAnagrams.cpp ├── PathSum.cpp ├── 3SumClosest.cpp ├── VerifyAlienDic.cpp ├── ImageOverlap.cpp ├── ReverseVowelsOfString.cpp ├── AllPathSourceToDes.cpp ├── FindPathExists.cpp ├── CountCompleteTreeNodes.cpp ├── TopKFrequentWords.cpp ├── MinFallingSum.cpp ├── MinAverageDiffer.cpp ├── WhereWillBallFall.cpp ├── LexSmallestEqString.cpp ├── RangeSumOfBst.cpp ├── CountAndSay.cpp ├── OddEvenLinkedList.cpp ├── ContinousSubarray.cpp ├── PreOrderTraversal.cpp ├── MInDistanceBetBSTNode.cpp ├── LongestPalindromeTwoLetterWords.cpp ├── PalindromePartitiong.cpp ├── deleteMiddleLinkedList.cpp ├── ArithmeticSlices.cpp ├── MaximumProductSpilt.cpp ├── WordSearch.cpp ├── BinaryTreeMaximumPathSum.cpp ├── MaxPoints.cpp ├── Important ├── Meeting Room 2.cpp ├── Car Fleets.cpp └── Get the Maximum Score.cpp ├── TwoSumBST.cpp ├── LongestPathDiffrentAdjChar.cpp ├── FindPlayersWithZeroOROne.cpp ├── MedianFromDataStream.cpp ├── SingleThreadedCPU.cpp ├── InsertIntervals.cpp ├── MinimumDifficultyDP.cpp ├── MintoCollectApple.cpp ├── FindClosestNodetoGivenTwoNodes.cpp ├── SameLabelSubtree.cpp ├── 103.ZigzaglevelOrder.cpp ├── MostStoneRemovedWithSameRowAndColumn.cpp ├── UniquePathsIII.cpp ├── StringCompression2.cpp ├── AddOneRowTree.cpp ├── MinGeneticMutation.cpp ├── WordPattern.cpp ├── MaxIceCream.cpp ├── SumOfSubarray.cpp ├── InsertDeleteGetRandom.cpp ├── CircularMaxSumSubarray.cpp ├── IntegerToroman.cpp ├── Skyline.cpp ├── MaxProfitJob.cpp ├── NumberOFDiceRoll.cpp ├── BasicCalculator.cpp ├── MinWindoSubstring.cpp ├── ShortestPathInGrid.cpp ├── NearestExistMaze.cpp ├── wordSeachr2.cpp ├── TwoPointers └── Get the Maximum Score.cpp └── EcretFenching.cpp /README.md: -------------------------------------------------------------------------------- 1 | # C++ -Codes 2 | C++ Codes Leetcode. 3 | ## This repository contain all codes 4 | -------------------------------------------------------------------------------- /UglyNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | if( n <= 0) return 0; 5 | while(n%2 == 0) n = n/2; 6 | while(n%3 == 0) n = n/3; 7 | while(n%5 == 0) n = n/5; 8 | 9 | return n == 1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /SameTrees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSameTree(TreeNode* p, TreeNode* q) { 4 | // Base case 5 | if( p == NULL || q == NULL) return p == q; 6 | if(p->val != q->val) return false; 7 | 8 | return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | 5 | vectordp(n+1); 6 | 7 | dp[0] = 1; // no jump. 8 | dp[1] = 1; 9 | 10 | for(int i=2;i<=n;i++){ 11 | dp[i] = dp[i-1] + dp[i-2]; 12 | } 13 | 14 | return dp[n]; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Max69number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximum69Number (int num) { 4 | // convert int to string.. 5 | string temp = to_string(num); 6 | 7 | for(auto &ch:temp){ 8 | if(ch == '6'){ch = '9'; break;} 9 | } 10 | 11 | return stoi(temp); 12 | 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /HouseRobber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n = nums.size(); 5 | int dp[n+1]; 6 | 7 | dp[0] = 0; 8 | dp[1] = nums[0]; 9 | 10 | for(int i=2;i<=nums.size();i++){ 11 | dp[i] = max(dp[i-1],dp[i-2]+nums[i-1]); 12 | } 13 | return dp[n]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /GCDString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string gcdOfStrings(string str1, string str2) { 4 | 5 | // if they are not same means there is no common substring 6 | // which can form str1 ,str2 completly. 7 | // GCD = "" 8 | if(str1+str2 != str2+str1) return ""; 9 | return str1.substr(0,gcd(str1.length(),str2.length())); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /JumpGame.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int reachable = 0; 5 | int n = nums.size(); 6 | 7 | for(int i=0;ireachable)return false; 9 | else { 10 | reachable = max(reachable,i+nums[i]); 11 | } 12 | } 13 | 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Toeplitz.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isToeplitzMatrix(vector>& matrix) { 4 | for(int i=0;imp; 4 | MyCalendarThree() { 5 | 6 | } 7 | 8 | int book(int start, int end) { 9 | 10 | mp[start]++; 11 | mp[end]--; 12 | 13 | int curr = 0; 14 | int ans = INT_MIN; 15 | for(auto x:mp){ 16 | curr+=x.second; 17 | ans = max(curr,ans); 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /TwoStringEqual.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool arrayStringsAreEqual(vector& word1, vector& word2) { 4 | 5 | string s1 = ""; 6 | string s2=""; 7 | 8 | for(auto x:word1){ 9 | s1+=x; 10 | } 11 | 12 | for(auto x:word2){ 13 | s2+=x; 14 | } 15 | 16 | return s1.compare(s2) == 0; 17 | 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /CountOddNumberInterval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOdds(int low, int high) { 4 | // if both are even. 5 | if(low%2 == 0 && high%2 == 0) 6 | return (high-low)/2; 7 | 8 | // if low = even , high = odd. 9 | else if((low%2 == 0 && high%2!=0) || (low%2 != 0 && high%2 == 0)) 10 | return ((high-low-1)/2)+1; 11 | 12 | // if low = odd , high = odd. 13 | else return ((high-low-2)/2) + 2; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /DetectCapital.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool detectCapitalUse(string word) { 4 | // count the capital letters present in words. 5 | int count =0; 6 | for(int i=0;i 1) { 7 | sort(s.begin(), s.end()); 8 | return s; 9 | } 10 | //when smallest alphabhet comes on index 0. 11 | string res = s; 12 | for (int i = 1; i < s.length(); i++) 13 | res = min(res, s.substr(i) + s.substr(0, i)); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /OnlineStockSpan.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack>st; 4 | StockSpanner() { 5 | 6 | } 7 | 8 | int next(int price) { 9 | int ans =1; 10 | while(!st.empty() && st.top().first <= price){ 11 | // pop out the values and update the ans (consicutive smaller values.) 12 | ans += st.top().second; 13 | st.pop(); 14 | 15 | } 16 | st.push({price,ans}); 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /RemoveStones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minStoneSum(vector& piles, int k) { 4 | priority_queuepq(piles.begin(),piles.end()); 5 | 6 | for(int i=0;i& nums, int k) { 4 | unordered_mapmp; 5 | 6 | for(int i=0;i& nums) { 4 | int maxSofar =0; 5 | int currentMax = 0; 6 | int jump=0; 7 | 8 | for(int i=0;i& nums) { 4 | 5 | int n = nums.size(); 6 | 7 | if(n<3) return 0; 8 | 9 | // sorting in reverse. 10 | 11 | sort(nums.begin(),nums.end(),greater()); 12 | 13 | for(int i=0;i<=n-3;i++){ 14 | if(nums[i+1]+nums[i+2] > nums[i]) return nums[i+1]+nums[i+2]+nums[i]; 15 | } 16 | 17 | return 0; 18 | 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /AddArrayForm.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector addToArrayForm(vector& num, int k) { 4 | 5 | for(int i=num.size()-1;i>=0;i--){ 6 | int temp = num[i]+k; 7 | // value to store . 8 | num[i] = temp%10; 9 | k=temp/10; // carry. 10 | } 11 | 12 | // if k>0 that means we need to insert in front. 13 | while(k>0){ 14 | num.insert(num.begin(),k%10); 15 | k=k/10; 16 | } 17 | 18 | return num; 19 | 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /RemoveDuplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | 5 | int insertIndex = 1; 6 | 7 | for(int i = 1; i < nums.size(); i++){ 8 | // We skip to next index if we see a duplicate element 9 | if(nums[i - 1] != nums[i]) { 10 | // Storing the unique element at insertIndex index and incrementing the insertIndex by 1 11 | nums[insertIndex] = nums[i]; 12 | insertIndex++; 13 | } 14 | } 15 | return insertIndex; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /540.SingleElementInArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int singleNonDuplicate(vector& nums) { 5 | // implementation of binary search 6 | int start = 0; 7 | int end = nums.size()-1; 8 | 9 | while(start& capacity, vector& rocks, int additionalRocks) { 4 | int ans =0; 5 | 6 | for(int i=0;i= x){ 13 | additionalRocks -= x; 14 | ans++; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /maxilengthunique.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxLength(vector& arr, string str = "", int index = 0) { 4 | 5 | //Use set to check if the string contains all unique characters 6 | unordered_sets(str.begin(), str.end()); 7 | if (s.size() != ((int)str.length())) 8 | return 0; 9 | 10 | int result = str.length(); 11 | for (int i = index; i < arr.size(); i++) 12 | result = max(result, maxLength(arr, str+arr[i], i+1)); 13 | 14 | return result; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /FlipString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFlipsMonoIncr(string s) { 4 | int countflip = 0; // 0->1 or 1->0 5 | int countOne = 0; 6 | 7 | for(auto x:s){ 8 | if(x == '1'){countOne++;} 9 | else{ 10 | // at any x == 0 calcualte whether we need it to flip it or 11 | // can flip all the 1 upto that point to 0. One with min val is our required flip count. 12 | countflip = min(++countflip,countOne); 13 | } 14 | } 15 | return countflip; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /PerfectSquare.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | vectordp(n+1); 5 | 6 | dp[0] = 0; 7 | dp[1] = 1; 8 | 9 | for(int i=2;i<=n;i++){ 10 | int min = INT_MAX; 11 | for(int j=1;j*j<=i;j++){ 12 | 13 | int rem = i-j*j; 14 | if(dp[rem] dailyTemperatures(vector& temperatures) { 4 | stackst; 5 | int n = temperatures.size(); 6 | vectorans(n,0); 7 | 8 | 9 | for(int i=n-1;i>=0;i--){ 10 | while(!st.empty()&& temperatures[st.top()]<= temperatures[i]) 11 | st.pop(); 12 | 13 | if(!st.empty()){ 14 | ans[i] = st.top()-i; 15 | } 16 | 17 | st.push(i); 18 | } 19 | 20 | return ans; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /ReactangleArea.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { 4 | 5 | int AreaOfA = (ax2-ax1)*(ay2-ay1); 6 | int AreaOfB= (bx2-bx1)*(by2-by1); 7 | 8 | int overlapR =0; 9 | 10 | // x overlap. 11 | int xoverlap = min(ax2,bx2) - max(ax1,bx1); 12 | int yoverlap = min(ay2,by2) - max(ay1,by1); 13 | 14 | if(xoverlap>0 && yoverlap>0) 15 | overlapR = xoverlap*yoverlap; 16 | 17 | return AreaOfA+AreaOfB-overlapR; 18 | 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /FindTownJudge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | // trust and trustedby. 5 | vector>mp(n+1,{0,0}); 6 | 7 | for(int i=0;i& nums, int k) { 4 | unordered_mapmp; 5 | 6 | int currentSum=0; 7 | int ans =0; 8 | mp[0]++; 9 | 10 | for(auto x:nums){ 11 | currentSum+=x; 12 | int mod = (currentSum %k +k)%k; 13 | 14 | // check if mod already present 15 | if(mp.find(mod)!=mp.end()){ 16 | ans+=mp[mod]; 17 | } 18 | mp[mod]++; 19 | } 20 | return ans; 21 | 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /35.SearchInsertPostion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int binarySearch(vector&nums,int start,int end,int target){ 5 | while(start<=end){ 6 | int mid = start + (end-start)/2; 7 | 8 | if(nums[mid]=target){ 12 | end = mid-1; 13 | } 14 | } 15 | return start; 16 | } 17 | 18 | 19 | int searchInsert(vector& nums, int target) { 20 | 21 | return binarySearch(nums,0,nums.size()-1,target); 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /ImplementQueueStack.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | stack st; 4 | MyQueue() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | if (st.size() == 0) { 10 | st.push(x); 11 | return; 12 | } 13 | int temp = st.top(); 14 | st.pop(); 15 | push(x); 16 | st.push(temp); 17 | } 18 | 19 | int pop() { 20 | int temp = st.top(); 21 | st.pop(); 22 | return temp; 23 | } 24 | 25 | int peek() { 26 | return st.top(); 27 | } 28 | 29 | bool empty() { 30 | return st.empty(); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /increasingTriplet.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool increasingTriplet(vector& nums) { 4 | int n = nums.size(); 5 | 6 | if(n<3) return false; 7 | 8 | int a = INT_MAX; 9 | int b = INT_MAX; 10 | 11 | 12 | for(int i=0;ib) return true; 15 | 16 | // update b or set b; 17 | else if(nums[i]>a) b= nums[i]; 18 | else if(nums[i]& tokens) { 4 | stack st; 5 | for(auto s : tokens) 6 | if(s == "+" || s == "-" || s == "*" || s == "/") { 7 | long a = st.top(); st.pop(); 8 | long b = st.top(); st.pop(); 9 | if(s == "+") a = b + a; 10 | if(s == "-") a = b - a; 11 | if(s == "/") a = b / a; 12 | if(s == "*") a = (b * a); 13 | st.push(a); 14 | } 15 | // stoi - converts from string to int 16 | else st.push(stoi(s)); 17 | return st.top(); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /BreakPalindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string breakPalindrome(string palindrome) { 4 | 5 | int n = palindrome.size(); 6 | 7 | if(n<=1) return ""; 8 | 9 | 10 | //case2 11 | 12 | for(int i=0;idp(n+1); 7 | 8 | dp[0] =1; // for 2nd digit. 9 | 10 | dp[1] = s[0] == '0' ?0:1; 11 | 12 | for(int i=2;i<=n;i++) 13 | { 14 | int onedigit = s[i-1]-'0'; 15 | int twodigit = 10*(s[i-2]-'0')+onedigit; 16 | 17 | if(onedigit>=1) dp[i] += dp[i-1]; 18 | if(twodigit>=10 && twodigit<=26) dp[i]+=dp[i-2]; 19 | } 20 | 21 | 22 | return dp[n]; 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /UniqueNumberOfOccurance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool uniqueOccurrences(vector& arr) { 4 | unordered_mapmp; 5 | 6 | // Store the frequecny. 7 | for(auto num:arr){ 8 | mp[num]++; 9 | } 10 | 11 | // check the count and insert in unordered set. 12 | unordered_setset; 13 | 14 | for(auto it:mp){ 15 | int freq = it.second; 16 | set.insert(freq); 17 | } 18 | 19 | // if size of mp is same as set that means all have unique freq. 20 | return set.size() == mp.size(); 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /deleteNodeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | 13 | ListNode* nextNode = node->next; 14 | 15 | // step 1. 16 | node->val = nextNode->val; 17 | 18 | // step2; 19 | node->next = nextNode->next; 20 | 21 | //step3 22 | nextNode->next = NULL; 23 | 24 | //step4 25 | delete(nextNode); 26 | 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /MaxDepthBinaryTree.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 maxDepth(TreeNode* root) { 15 | if(root == NULL) return 0; 16 | 17 | int left = maxDepth(root->left); 18 | int right = maxDepth(root->right); 19 | 20 | return max(left,right)+1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /PanagramCheck.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfPangram(string sentence) { 4 | 5 | //a-z 6 | 7 | // for(int i=0;i<26;i++){ 8 | // // a,b,c 9 | // char currChar = 'a'+i; 10 | 11 | // if(sentence.find(currChar) == string::npos){ 12 | // return false; 13 | // } 14 | 15 | // } 16 | // return true; 17 | 18 | // unorder_set.size() == 26.. 19 | 20 | unordered_setseen(sentence.begin(),sentence.end()); 21 | 22 | return seen.size() == 26; 23 | 24 | 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /MinTimeRopeColorful.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(string colors, vector& neededTime) { 4 | 5 | int totaltime =0; 6 | int currmax = neededTime[0]; 7 | 8 | for(int i=1;iblen){ b = s.append(alen-blen,'0')+b;} 10 | else if(blen>alen){ a = s.append(blen-alen,'0')+a;} 11 | 12 | // now string are of equal length. 13 | int carry = 0; 14 | string ans; 15 | 16 | for(int i=a.size()-1;i>=0;i--){ 17 | int sum = (a[i]-'0')+(b[i]-'0')+carry; 18 | ans = to_string(sum%2)+ ans; 19 | carry = sum/2; 20 | } 21 | if(carry != 0) ans = "1"+ans; 22 | 23 | return ans; 24 | } 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /DetermineifStringHalves.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isvowel(char ch){ 4 | if(ch =='a'|| ch =='e'||ch == 'i'||ch == 'o'|| ch == 'u'|| ch =='A'|| ch =='E'|| ch =='I'||ch == 'O'|| ch =='U') 5 | return true; 6 | return false; 7 | } 8 | 9 | 10 | bool halvesAreAlike(string s) { 11 | int left = 0; 12 | int right = s.size()-1; 13 | 14 | int leftCount = 0; 15 | int rightCount= 0; 16 | 17 | while(lefttemp; 9 | // to store the ans. 10 | string ans=""; 11 | 12 | while(s>>word){ 13 | temp.push_back(word); 14 | } 15 | //now store the words in reverse order and add the extra space at the end of eaach word. except the first one. 16 | 17 | for(int i=temp.size()-1;i>=0;i--){ 18 | if(i!=0) 19 | ans+=temp[i]+" "; 20 | else 21 | ans+=temp[i]; 22 | 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /MiddleOfLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | 15 | ListNode*fast = head; 16 | ListNode*slow = head; 17 | 18 | while(fast!=NULL && fast->next !=NULL){ 19 | slow=slow->next; 20 | fast = fast->next->next; 21 | } 22 | 23 | return slow; 24 | 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeafSimilarTrees.cpp: -------------------------------------------------------------------------------- 1 | // Time Complexity : O(n) 2 | // Space Complexity : O(n+n) 3 | 4 | 5 | class Solution { 6 | public: 7 | 8 | void dfs(TreeNode* root,vector&v){ 9 | // base condition 10 | if(root == NULL) return; 11 | //condition. 12 | if(root->left == NULL && root->right == NULL) { 13 | v.push_back(root->val); 14 | return; 15 | } 16 | dfs(root->left,v); 17 | dfs(root->right,v); 18 | } 19 | 20 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 21 | 22 | vectortree1; 23 | vectortree2; 24 | 25 | dfs(root1,tree1); 26 | dfs(root2,tree2); 27 | 28 | return tree1 == tree2; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /MaxDiffBetAncAndNode.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxDiff(TreeNode* root,int MaxVal,int MinVal){ 4 | // Base condtion. leaf node end of path. 5 | if(root == NULL) { 6 | return abs(MaxVal - MinVal); 7 | } 8 | // Update the max and min 9 | MaxVal = max(root->val,MaxVal); 10 | MinVal = min(root->val,MinVal); 11 | 12 | // Traversal. 13 | int left = findMaxDiff(root->left,MaxVal,MinVal); 14 | int right = findMaxDiff(root->right,MaxVal,MinVal); 15 | 16 | return max(right,left); 17 | } 18 | 19 | 20 | int maxAncestorDiff(TreeNode* root) { 21 | if(root == NULL) return 0; 22 | return findMaxDiff(root,root->val,root->val); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /MakeTheStringGreat.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeGood(string s) { 4 | // declare the stack st. 5 | vectorst; 6 | 7 | st.push_back(s[0]); 8 | 9 | for(int i=1;i& strs) { 4 | // count no. of rows and coln. 5 | int rows = strs.size(); 6 | int colns = strs[0].size(); 7 | 8 | // store the ans 9 | int ans =0; 10 | 11 | // Traverse column wise and for each row. 12 | for(int i=0;istrs[j][i]){ 16 | ans++; 17 | break; 18 | } 19 | } 20 | } 21 | 22 | return ans; 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /RemoveAllAdjacentDuplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) { 4 | 5 | // declare the stack 6 | vectorst; 7 | 8 | // push index 0. 9 | st.push_back(s[0]); 10 | 11 | // start the loop from index 1. 12 | for(int i=1;i answerQueries(vector& nums, vector& queries) 4 | { 5 | int n = nums.size(); 6 | int m = queries.size(); 7 | 8 | sort(nums.begin(),nums.end()); 9 | 10 | vectorprefixsum(n); 11 | 12 | int temp=0; 13 | for(int i =0;ians; 19 | for(int i=0;i findErrorNums(vector& nums) { 4 | int dup=-1,missing=1; 5 | vectorresult; 6 | 7 | // find the duplicate. 8 | for(auto x:nums){ 9 | // duplicate. 10 | if(nums[abs(x)-1]<0){ 11 | dup =abs(x); 12 | }else{ 13 | nums[abs(x)-1] *=-1; 14 | } 15 | 16 | } 17 | result.push_back(dup); 18 | 19 | // find the missing.. 20 | for(int i=1;i0){ 23 | // missing. 24 | missing = i+1; 25 | } 26 | 27 | } 28 | result.push_back(missing); 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /DetermineIfTwoStringAreClose.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool closeStrings(string word1, string word2) { 4 | 5 | //for storing frequency and presence of character. 6 | vectorfreqW1(26,0),freqW2(26,0); 7 |   vectorIspresentW1(26,0),IspresentW2(26,0); 8 | 9 | for(char c:word1){ 10 | freqW1[c-'a']++; 11 | IspresentW1[c-'a'] = 1; 12 | } 13 | 14 | 15 | for(char c:word2) 16 | { 17 | freqW2[c-'a']++; 18 | IspresentW2[c-'a'] = 1; 19 | } 20 | 21 | 22 | sort(freqW1.begin(),freqW1.end()); 23 | sort(freqW2.begin(),freqW2.end()); 24 | 25 | // if both condition statify return true. 26 | return freqW1==freqW2 && IspresentW1==IspresentW2; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /KeysAndRooms.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(vector>& rooms,vector&visited,int current){ 4 | // make visited. 5 | visited[current] = 1; 6 | 7 | // traversal. 8 | for(int i =0;i>& rooms) { 17 | int n = rooms.size(); 18 | vectorvisited(n,0); 19 | 20 | dfs(rooms,visited,0); 21 | 22 | for(int i=0;i>& points) { 4 | // ans counter and endpoint. 5 | int ans =1; 6 | int endpoint = INT_MAX; 7 | // sorting of points in increasing order of points. 8 | sort(points.begin(),points.end()); 9 | 10 | // now traverse and find the non overlaping interval, bascially ans. 11 | for(auto x:points){ 12 | int start = x[0]; 13 | int end = x[1]; 14 | 15 | if(endpoint < start){ 16 | ans++; // new interval with no overlapping. 17 | endpoint = end; 18 | } 19 | else{ 20 | endpoint = min(endpoint,end); 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LCS.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestCommonSubsequence(string s, string t) { 4 | 5 | int n = s.size(); 6 | int m = t.size(); 7 | 8 | int dp[n+1][m+1]; 9 | 10 | 11 | for(int i=0;i<=n;i++){ 12 | for(int j=0;j<=m;j++){ 13 | if(i==0 || j==0){ 14 | dp[i][j] = 0; 15 | } 16 | } 17 | } 18 | 19 | 20 | for(int i=1;i<=n;i++){ 21 | for(int j=1;j<=m;j++){ 22 | 23 | //if sequence as same 24 | if(s[i-1] == t[j-1]){ 25 | dp[i][j] = 1+dp[i-1][j-1]; 26 | } 27 | else{ 28 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]); 29 | } 30 | } 31 | } 32 | 33 | return dp[n][m]; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /KClosest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findClosestElements(vector& arr, int k, int x) { 4 | 5 | // result vector 6 | 7 | vectorresult; 8 | 9 | // priority max heap. 10 | priority_queue> pq; 11 | 12 | for(auto i:arr){ 13 | 14 | // push pair into heap 15 | pq.push({abs(i-x),i}); 16 | 17 | if(pq.size()>k){ 18 | pq.pop(); 19 | } 20 | 21 | } 22 | 23 | while(!pq.empty()){ 24 | result.push_back(pq.top().second); 25 | pq.pop(); 26 | } 27 | 28 | sort(result.begin(),result.end()); 29 | 30 | return result; 31 | 32 | 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /EarliestPossibleFullBloom.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int earliestFullBloom(vector& plantTime, vector& growTime) { 4 | 5 | int n = plantTime.size(); 6 | vector>store(n); 7 | 8 | // for storing the values. 9 | for(int i=0;i& gas, vector& cost) { 4 | 5 | //greedy problem O(n) 6 | 7 | int totalgas = 0; 8 | int currgas=0; 9 | int startIndex =0; 10 | 11 | 12 | for(int i=0;i=0 ? startIndex:-1; 28 | 29 | 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /NonDecreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector>ans; 4 | 5 | void dfs(vector&nums,vector& temp,int index){ 6 | // base condition 7 | if(temp.size()>1) ans.push_back(temp); 8 | 9 | // for each dfs declare unordered_set 10 | unordered_setset; 11 | for(int i=index;i> findSubsequences(vector& nums) { 23 | vectortemp; 24 | dfs(nums,temp,0); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /ValidSudoko.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSudoku(vector>& board) { 4 | 5 | // Three Cases so 3 condtions. 6 | int rowcase[9][9] ={0}; 7 | int colcase[9][9] = {0}; 8 | int gridcase[9][9] = {0}; 9 | 10 | for(int i=0;i& tasks) { 4 | // store the frequency in map. 5 | unordered_mapmp; 6 | 7 | for(int i=0;imp; 6 | // Declare priority queue to get value sorted according to freq. 7 | priority_queue>pq; 8 | 9 | // string to send the ans. 10 | string ans =""; 11 | 12 | 13 | for(char ch:s){ 14 | mp[ch]++; 15 | } 16 | // push in priority queue. 17 | for(auto it:mp){ 18 | pq.push({it.second,it.first}); 19 | } 20 | 21 | // traverse in heap and append char to the string. 22 | while(!pq.empty()){ 23 | auto temp = pq.top(); 24 | int freq = temp.first; 25 | char ch = temp.second; 26 | 27 | ans+=string(freq,ch); 28 | pq.pop(); 29 | } 30 | 31 | return ans; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /TimeBasedkeyvalue.cpp: -------------------------------------------------------------------------------- 1 | class TimeMap { 2 | public: 3 | map>mp; 4 | TimeMap() { 5 | 6 | } 7 | 8 | void set(string key, string value, int timestamp) { 9 | mp[key][timestamp] = value; 10 | } 11 | 12 | string get(string key, int timestamp) { 13 | if(mp.find(key)!=mp.end()){ 14 | auto it = mp[key].lower_bound(timestamp); 15 | 16 | if(it->first == timestamp) 17 | return it->second; 18 | 19 | it--; 20 | if(it->firstsecond; 22 | } 23 | } 24 | 25 | return ""; 26 | } 27 | }; 28 | 29 | /** 30 | * Your TimeMap object will be instantiated and called as such: 31 | * TimeMap* obj = new TimeMap(); 32 | * obj->set(key,value,timestamp); 33 | * string param_2 = obj->get(key,timestamp); 34 | */ 35 | -------------------------------------------------------------------------------- /InvertBinaryTree.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 | void swap(TreeNode* root){ 15 | TreeNode* temp = root->right; 16 | root->right = root->left; 17 | root->left = temp; 18 | } 19 | 20 | TreeNode* invertTree(TreeNode* root) { 21 | 22 | // base case 23 | if(root == NULL) return root; 24 | 25 | // swap 26 | swap(root); 27 | 28 | // traversal 29 | invertTree(root->left); 30 | invertTree(root->right); 31 | 32 | return root; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Graph/DFS/Number of Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector>directions = {{1,0},{0,1},{-1,0},{0,-1}}; 4 | void dfs(int i,int j,auto&grid){ 5 | // base case 6 | if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j] == '0'){ return; } 7 | 8 | // visited 9 | grid[i][j] = '0'; 10 | 11 | // traversal 12 | for(auto dir:directions){ 13 | int x = i+dir[0]; 14 | int y = j+dir[1]; 15 | dfs(x,y,grid); 16 | } 17 | } 18 | int numIslands(vector>& grid) { 19 | 20 | int count = 0; 21 | for(int i=0;i> groupAnagrams(vector& str) 4 | { 5 | 6 | //1. Store the values in the map.. 7 | map>mp; 8 | 9 | for(int i=0;i> ans(mp.size()); 21 | int index =0; 22 | for(auto x:mp) 23 | { 24 | //to store the anagrams or same items together. 25 | auto temp = x.second; 26 | 27 | for(auto x:temp) 28 | { 29 | ans[index].push_back(x); 30 | } 31 | 32 | index++; 33 | 34 | } 35 | 36 | return ans; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /PathSum.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 | bool hasPathSum(TreeNode* root, int targetSum) { 15 | 16 | if(root == NULL) return false; 17 | 18 | if(root->val == targetSum && root->left == NULL && root->right == NULL) 19 | return true; 20 | 21 | 22 | bool leftside = hasPathSum(root->left,targetSum-root->val); 23 | bool rightside = hasPathSum(root->right,targetSum-root->val); 24 | 25 | return (leftside || rightside); 26 | 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /3SumClosest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | 5 | int n = nums.size(); 6 | if(n<3) return 0; 7 | 8 | sort(nums.begin(),nums.end()); 9 | 10 | int ans =0; 11 | int closest = INT_MAX; 12 | 13 | // traverse i =0 to n-3; 14 | for(int i=0;i<=n-3;i++){ 15 | int j =i+1; 16 | int l = n-1; 17 | 18 | while(jmp; 5 | bool correctOrder(string a,string b){ 6 | int n=min(a.size(),b.size()); 7 | 8 | for(int i=0;imp[b[i]]) { 11 | return false; 12 | } 13 | } 14 | // if they are lexicographically.check if b is substring of a 15 | if(a.size()>b.size() &&(a.find(b)!= string::npos)){ 16 | return false; 17 | } 18 | return true; 19 | } 20 | 21 | bool isAlienSorted(vector& words, string order) { 22 | 23 | for(int i=0;i>& A, vector>& B) { 4 | 5 |    vector> va, vb; 6 | int rows = A.size(), cols = A[0].size(); 7 | 8 |   // Store the indeces of the matrix. 9 | for (int i = 0; i < rows; i++) { 10 | for (int j = 0; j < cols; j++) { 11 | if (A[i][j]) va.push_back({i, j}); 12 | if (B[i][j]) vb.push_back({i, j}); 13 | } 14 | } 15 | 16 | // to store the frequency. of translation vector.. 17 | unordered_map mp; 18 | for (auto &pa : va) { 19 | for (auto &pb : vb) { 20 | string s = to_string(pa[0] - pb[0]) + " " + to_string(pa[1] - pb[1]); 21 | mp[s]++; 22 | } 23 | } 24 | 25 | 26 |   // find the max val of frequency. 27 | int res = 0; 28 | for (auto &it : mp) res = max(res, it.second); 29 | return res; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /ReverseVowelsOfString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isvowel(char ch){ 4 | if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A'|| ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') 5 | return true; 6 | else return false; 7 | } 8 | 9 | string reverseVowels(string s) { 10 | int start =0; 11 | int end = s.size()-1; 12 | 13 | while(start=0 && !isvowel(s[end]) ){ 21 | end--; 22 | } 23 | // if start>&graph,vector>& paths,vectorpath,int start,int destination){ 4 | 5 | path.push_back(start); 6 | // Base condtion if start == destination. 7 | if(start == destination){ 8 | paths.push_back(path); 9 | return; 10 | } 11 | // traversal in dfs (adjacency list is already given) 12 | for(auto x:graph[start]){ 13 | dfs(graph,paths,path,x,destination); 14 | } 15 | } 16 | vector> allPathsSourceTarget(vector>& graph) { 17 | 18 | // 2D vector to store the paths. 19 | vector> paths; 20 | // to store the path 21 | vectorpath; 22 | 23 | int nodes = graph.size(); 24 | 25 | if(nodes == 0) return paths; 26 | 27 | // track paths using dfs traversal 28 | dfs(graph,paths,path,0,nodes-1); 29 | 30 | return paths; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /FindPathExists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool dfs(vector>& graph, vector& visited, int current, int end) { 5 | // Base cases 6 | if(current == end) 7 | return true; 8 | if(visited[current]) 9 | return false; 10 | 11 | // make visited. 12 | visited[current] = 1; 13 | 14 | // Traversal. 15 | for(int i=0; i>& edges, int source, int destination) { 24 | vector> graph(n); 25 | for(int i=0; i visited(n, 0); 30 | return dfs(graph, visited, source, destination); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /CountCompleteTreeNodes.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int countNodes(TreeNode* root) { 5 | 6 | if(root == NULL) return 0; 7 | 8 | int lh = countLeftHeight(root); 9 | int rh = countRightHeight(root); 10 | 11 | 12 | //this means we got a perfect tree hence it will have 2^h -1 nodes. 13 | if(lh == rh) return pow(2, lh) - 1; 14 | 15 | // 1 added for the parent one node while left and right parts are needed to calculate the values for the heights. 16 | return 1+countNodes(root->left)+countNodes(root->right); 17 | 18 | 19 | } 20 | 21 | // calculate left height. 22 | int countLeftHeight(TreeNode* root) 23 | { 24 | int count=0; 25 | while(root) 26 | { 27 | count++; 28 | root = root->left; 29 | } 30 | return count; 31 | } 32 | 33 | // calcualte right height. 34 | int countRightHeight(TreeNode* root) 35 | { 36 | int count=0; 37 | while(root) 38 | { 39 | count++; 40 | root = root->right; 41 | } 42 | return count; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /TopKFrequentWords.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | static bool cmp(pair& a,pair& b) 5 | { 6 | if(a.second == b.second){ 7 | 8 | int val = a.first.compare(b.first); 9 | 10 | if(val<0) return a.second; 11 | else b.second; 12 | } 13 | return a.second > b.second; 14 | 15 | } 16 | 17 | vector topKFrequent(vector& words, int k) { 18 | 19 | vectorresult; 20 | unordered_mapmp; 21 | 22 | for(auto word:words){ 23 | mp[word]++; 24 | } 25 | 26 | // sort it according to value i.e frequency. 27 | vector>temp; 28 | 29 | 30 | 31 | for (auto& it : mp) 32 | { 33 | temp.push_back(it); 34 | } 35 | 36 | 37 | sort(temp.begin(),temp.end(),cmp); 38 | 39 | for(int i=0;i>& matrix) { 4 | int n = matrix.size(); 5 | int m = matrix[0].size(); 6 | // If only one row. return minimum .. 7 | if(n == 1) return *min_element(matrix[0].begin(),matrix[0].end()); 8 | 9 | // Otherwise traverse the entire matrix and update it. 10 | for(int i=1;i& nums) { 4 | 5 | long long totalsum = 0; 6 | int n = nums.size(); 7 | vectorprefix(n); 8 | 9 | for(int i=0;i findBall(vector>& grid) { 4 |   // declare for storing ans. 5 | vector result(grid[0].size(), 0); 6 | 7 |   // loop: for each ball , (col) , traverse the rows. 8 | 9 | for (int col = 0; col < grid[0].size(); col++) { 10 |   // initialize the val of a ball. 11 | int currentCol = col; 12 | 13 |    for (int row = 0; row < grid.size(); row++) { 14 | //next move of the ball. (which will be next col.) 15 |     int nextColumn = currentCol + grid[row][currentCol]; 16 |   // base condition (Blocking condition) 17 | if (nextColumn < 0 || nextColumn > grid[0].size() - 1 ||grid[row][currentCol] != grid[row][nextColumn]) 18 |    { 19 | result[col] = -1; 20 | break; 21 | } 22 |   // Update the values in result and currentCol. 23 | result[col] = nextColumn; 24 | currentCol = nextColumn; 25 | } 26 | } 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /LexSmallestEqString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vectorheadChar; 4 | 5 | // find the parent or headChar. 6 | int find(int x){ 7 | if(headChar[x] == -1){return x;} 8 | 9 | return headChar[x] = find(headChar[x]); 10 | } 11 | 12 | void Union(int x,int y){ 13 | int parentx = find(x); 14 | int parenty = find(y); 15 | 16 | 17 | if(parentx == parenty){return;} 18 | 19 | 20 | // make smaller one represent of other. if parent are diffrent. 21 | headChar[max(parentx,parenty)] = min(parentx,parenty); 22 | } 23 | 24 | 25 | string smallestEquivalentString(string s1, string s2, string baseStr) { 26 | 27 | headChar.resize(26,-1); 28 | // make group (Union) 29 | for(int i=0;ival >= low && root->val<=high){sum += root->val;} 24 | 25 | // traversal. 26 | if(root->val>low){dfs(root->left,low,high);} 27 | if(root->valright,low,high);} 28 | } 29 | int rangeSumBST(TreeNode* root, int low, int high) { 30 | if(root == NULL) return 0; 31 | dfs(root,low,high); 32 | return sum; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /CountAndSay.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string countAndSay(int n) { 4 | // base case. 5 | if(n == 1) return "1"; 6 | if(n == 2) return "11"; 7 | 8 | string s = "11"; 9 | 10 | for(int i=3;i<=n;i++){ 11 | 12 | string temp=""; 13 | s+="$"; // adding the extra radom string "s" to append count of last value. 14 | int count=1; 15 | 16 | for(int j=1;jnext == NULL || head->next->next == NULL) 16 | return head; 17 | 18 | ListNode* oddpointer = head; 19 | ListNode* evenpointer = head->next; 20 | ListNode* startofeven = head->next; 21 | 22 | while(oddpointer->next && evenpointer->next){ 23 | oddpointer->next = evenpointer->next; 24 | evenpointer->next = oddpointer->next->next; 25 | 26 | oddpointer = oddpointer->next; 27 | evenpointer = evenpointer->next; 28 | 29 | } 30 | 31 | // connect the even pointer to the odd pointer. 32 | oddpointer->next = startofeven; 33 | 34 | return head; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /ContinousSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector& nums, int k) { 4 | 5 | // if nums size is less than 2. 6 | if(nums.size()<2) 7 | return false; 8 | 9 | // declare map. 10 | unordered_mapmp; 11 | 12 | // initial index as -ve. case when first number is multiple of k. 13 | mp[0]=-1; 14 | 15 | int running_sum=0; 16 | 17 | for(int i=0;i1) return true; 28 | } 29 | else{ 30 | // if not present store the (mod, index). 31 | mp[running_sum]=i; 32 | } 33 | 34 | } 35 | 36 | return false; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /PreOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Method 1. 3 | class Solution { 4 | public: 5 | vector preorderTraversal(TreeNode* root) { 6 | vectorpreorder; 7 | stackst; 8 | 9 | if(root == NULL){return preorder; } 10 | 11 | st.push(root); 12 | 13 | 14 | while(!st.empty()){ 15 | TreeNode* top = st.top(); 16 | st.pop(); 17 | preorder.push_back(top->val); 18 | 19 | if(top->right!= NULL){ 20 | st.push(top->right); 21 | } 22 | if(top->left!= NULL){ 23 | st.push(top->left); 24 | } 25 | } 26 | 27 | return preorder; 28 | } 29 | }; 30 | 31 | 32 | // Method 2. 33 | void preorderfun(vector& preorder,TreeNode* root){ 34 | if(root == NULL){return;} 35 | preorder.push_back(root->val); 36 | preorderfun(preorder,root->left); 37 | preorderfun(preorder,root->right); 38 | } 39 | 40 | vector preorderTraversal(TreeNode* root) { 41 | vectorpreorder; 42 | preorderfun(preorder,root); 43 | return preorder; 44 | } 45 | -------------------------------------------------------------------------------- /MInDistanceBetBSTNode.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 | vectorinorder; 15 | 16 | void inOrderTraversal(TreeNode* root){ 17 | 18 | // base case 19 | if(root == NULL) return; 20 | 21 | // traversal 22 | inOrderTraversal(root->left); 23 | inorder.push_back(root->val); 24 | inOrderTraversal(root->right); 25 | 26 | } 27 | 28 | int minDiffInBST(TreeNode* root) { 29 | 30 | inOrderTraversal(root); 31 | int ans = INT_MAX; 32 | // values are arrange in ascending order. 33 | // calcualte the diffrence of consicutive. 34 | for(int i=1;i& words) { 4 | 5 | // store the count values for each string. 6 | vector>counter(26,vector(26,0)); 7 | 8 | int ans =0; 9 | // add 4 to ans if reverse is present in words. 10 | // i.e counter values are present. 11 | for(auto x:words){ 12 | int first = x[0]-'a'; 13 | int second = x[1]-'a'; 14 | 15 | // if reverse is present "la" and "al" is present in words vector. 16 | // check through 17 | if(counter[second][first]){ 18 | ans+=4; 19 | counter[second][first]--; 20 | } 21 | // first time occuring in the words string. 22 | else{ 23 | counter[first][second]++; 24 | } 25 | } 26 | 27 | 28 | // add 2 if both letter are same 29 | for(int i=0;i<26;i++){ 30 | if(counter[i][i]){ 31 | ans+=2; 32 | break; 33 | } 34 | } 35 | 36 | return ans; 37 | 38 | 39 | 40 | 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /PalindromePartitiong.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // to store the ans. 4 | vector> ans; 5 | 6 | bool palindrome(string s,int start,int end ){ 7 | while(start&temp,int index ){ 14 | 15 | // base case 16 | if(index == s.size()){ 17 | ans.push_back(temp); 18 | return; 19 | } 20 | 21 | // loop and do partition based on if palindrome string from 0 to index. 22 | for(int i=index;i> partition(string s) { 36 | vector temp; 37 | 38 | recursion(s,temp,0); 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /deleteMiddleLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteMiddle(ListNode* head) { 14 | 15 | if(head == NULL) return NULL; 16 | 17 | // if one element is there in linkedlist. 18 | if(head->next == NULL) return NULL; 19 | 20 | ListNode* fast = head->next->next; 21 | ListNode* slow = head; 22 | 23 | while(fast != NULL && fast->next!=NULL ){ 24 | fast = fast->next->next; 25 | slow = slow->next; 26 | } 27 | 28 | //slow will point to mid-1 index. 29 | 30 | ListNode* mid = slow->next; 31 | 32 | slow->next = mid->next; 33 | mid->next = NULL; 34 | 35 | delete(mid); 36 | 37 | 38 | return head; 39 | 40 | 41 | 42 | 43 | 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /ArithmeticSlices.cpp: -------------------------------------------------------------------------------- 1 | # define ll long long 2 | 3 | class Solution { 4 | public: 5 | int numberOfArithmeticSlices(vector& nums) { 6 | 7 | int n = nums.size(); 8 | 9 | long long ans = 0; 10 | 11 | vector>dp(n); // 12 | 13 | for(int i=1;i=INT_MAX){ 20 | continue; 21 | } 22 | 23 | int seqUptoNow = 0; 24 | 25 | if(dp[j].find(differ) != dp[j].end()){ 26 | seqUptoNow = dp[j][differ]; 27 | } 28 | dp[i][differ] += seqUptoNow + 1; 29 | ans += seqUptoNow; 30 | 31 | } 32 | } 33 | 34 | return (int)ans; 35 | 36 | 37 | 38 | 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /MaximumProductSpilt.cpp: -------------------------------------------------------------------------------- 1 | static int MOD=1e9+7; 2 | class Solution { 3 | public: 4 | long long TotalSum=0,result=0; 5 | //Find total sum of the tree. 6 | void TotalTreeSum(TreeNode* root) 7 | { 8 | if(!root) 9 | return; 10 | TotalSum+=root->val; 11 | TotalTreeSum(root->left); 12 | TotalTreeSum(root->right); 13 | } 14 | 15 | int SubTreeSum(TreeNode* root) 16 | //Find the totalSum under the root, including root. 17 | { 18 | if(root == NULL) 19 | return 0; 20 | 21 | //Find the sum of left and right subtree under root. 22 | int SumUnderLeft=SubTreeSum(root->left); 23 | int SumUnderRight=SubTreeSum(root->right); 24 | 25 | //Find the max product after making left or right subtrees as seprarate tree. 26 | result=max({result,(TotalSum-SumUnderLeft)*SumUnderLeft,(TotalSum-SumUnderRight)*SumUnderRight}); 27 | 28 | //Return the sum of the subtree which include current node (root node). 29 | return SumUnderLeft+SumUnderRight+root->val; 30 | } 31 | 32 | int maxProduct(TreeNode* root) 33 | { 34 | TotalTreeSum(root); 35 | SubTreeSum(root); 36 | return result%MOD; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /WordSearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool dfs(vector>& board, string word,int i,int j,int count){ 4 | // Base case 5 | 6 | // Complete traversal of word. 7 | if(count == word.size()){return true;} 8 | // Return cases. 9 | if(i<0 || i>=board.size() ||j<0 || j>=board[0].size() || word[count] != board[i][j]){return false;} 10 | 11 | // Make it visited. 12 | char temp = board[i][j]; 13 | board[i][j] = '*'; 14 | // Make traversal 15 | 16 | bool isfound = dfs(board,word,i+1,j,count+1) || dfs(board,word,i-1,j,count+1) ||dfs(board,word,i,j+1,count+1)||dfs(board,word,i,j-1,count+1); 17 | 18 | // Backtrack. 19 | board[i][j] = temp; 20 | 21 | return isfound; 22 | 23 | 24 | } 25 | 26 | 27 | 28 | bool exist(vector>& board, string word) { 29 | 30 | for(int i=0;ileft)); 28 | int rhsum = max(0,calcualteMaxPathSum(root->right)); 29 | 30 | 31 | //updating the value in the sum.. // maximum sum upto now.(can be subtree sum) 32 | sum = max(sum,root->val+lhsum+rhsum); 33 | 34 | 35 | //returning the maxximum sum possible.. using which path. 36 | return max(lhsum,rhsum) + root->val; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /MaxPoints.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPoints(vector>& points) { 4 | int ans = 1; 5 | 6 | for(int i=0;i for each point we want new map to declare. 8 | unordered_mapmp; 9 | for(int j=i+1;jstart = start; 8 | * this->end = end; 9 | * } 10 | * } 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int minMeetingRooms(vector& intervals) { 16 | // min number of room required . 17 | 18 | // sort based on start time. 19 | sort(intervals.begin(),intervals.end(),[&](auto& a, auto& b) { 20 | return a.start < b.start; // Sorting by start time 21 | }); 22 | 23 | if(intervals.size() == 0) return 0; 24 | 25 | auto myLambda = [&](auto& a,auto& b){ 26 | return a.end>b.end; 27 | }; 28 | 29 | 30 | // sorting according to the minimum end time. 31 | priority_queue,decltype(myLambda)>pq(myLambda); 32 | 33 | pq.push(intervals[0]); 34 | 35 | for(int i=1;i&store){ 16 | 17 | if(root == NULL) return ; 18 | 19 | // left ,root,right 20 | inorder(root->left,store); 21 | store.push_back(root->val); 22 | inorder(root->right,store); 23 | 24 | } 25 | 26 | 27 | bool findTarget(TreeNode* root, int k) { 28 | 29 | vectorstore; 30 | inorder(root,store); 31 | 32 | // two pointers. 33 | 34 | int start = 0; 35 | int end = store.size()-1; 36 | 37 | while(start>adjlist; 5 | 6 | int dfs(int node,int parent,string& s){ 7 | // to store the max length upto that node including it , so initialize with 1. 8 | int maxpath=1; 9 | 10 | //only take children 11 | for(auto x : adjlist[node]){ 12 | // check only for children 13 | if(x != parent){ 14 | int temp=dfs(x,node,s); 15 | 16 | //if node character and its child character is not equal 17 | if(s[node]!=s[x]){ 18 | // update the ans with maximum value. 19 | // update the maxpath length to return to its parent. 20 | ans=max(ans,maxpath+temp); 21 | maxpath=max(maxpath,1+temp); 22 | } 23 | } 24 | 25 | } 26 | // return the maxpath for current node. 27 | return maxpath; 28 | } 29 | public: 30 | int longestPath(vector& parent, string s) { 31 | int n=parent.size(); 32 | adjlist.resize(n); 33 | 34 | //create adjacency list 35 | for(int i=1;i> findWinners(vector>& matches) { 4 | 5 | // Set initial values as -1. 6 | vectorlossCounter(100001,-1); 7 | 8 | // -1 = not played match. 9 | // 0 = not lost a single match. 10 | // 1 = lost excatly 1 match. 11 | 12 | for(auto& match:matches){ 13 | 14 | int winner = match[0]; 15 | int loser = match[1]; 16 | 17 | // if it is winner make it 0 means , identify he won the match. 18 | if(lossCounter[winner] == -1){lossCounter[winner] = 0;} 19 | 20 | // check for players 1. loser. 21 | // played his first game. 22 | if(lossCounter[loser] == -1){lossCounter[loser] = 1;} 23 | // i.e player has already lost once. 24 | else{lossCounter[loser]++;} 25 | 26 | } 27 | 28 | // return ans. 29 | vector>ans(2,vector()); 30 | 31 | for(int i=1;i<100001;i++){ 32 | if(lossCounter[i] == 1){ 33 | ans[1].push_back(i); 34 | }else if(lossCounter[i] == 0){ 35 | ans[0].push_back(i); 36 | } 37 | } 38 | 39 | return ans; 40 | 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Graph/DFS/Count Sub Islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector>direction = {{0,1},{0,-1},{1,0},{-1,0}}; 5 | 6 | void dfs(auto& grid1,auto& grid2,int i,int j,bool& res){ 7 | if(i<0 || i>=grid2.size() || j<0 || j>=grid2[0].size() || grid2[i][j] == 0) return; 8 | 9 | // change res. 10 | if(grid1[i][j] == 0) res = false; 11 | 12 | // make visited 13 | grid2[i][j] = 0; 14 | 15 | // traversal 16 | dfs(grid1,grid2,i+1,j,res); 17 | dfs(grid1,grid2,i-1,j,res); 18 | dfs(grid1,grid2,i,j+1,res); 19 | dfs(grid1,grid2,i,j-1,res); 20 | 21 | } 22 | 23 | 24 | int countSubIslands(vector>& grid1, vector>& grid2) { 25 | int count = 0; 26 | 27 | for(int i=0;i>first_part; //maxheap; 5 | priority_queue,greater>second_part; // minheap; 6 | 7 | 8 | public: 9 | // Adds a number into the data structure. 10 | void addNum(int num) { 11 | if(first_part.size() == 0 || first_part.top() >= num ) 12 | { 13 | first_part.push(num); 14 | } 15 | else{ 16 | second_part.push(num); 17 | } 18 | 19 | balance(); 20 | 21 | } 22 | 23 | 24 | void balance() 25 | { 26 | if(first_part.size() > (second_part.size()+1)) 27 | { 28 | second_part.push(first_part.top()); 29 | first_part.pop(); 30 | } 31 | else if(second_part.size() > (first_part.size()+1)) 32 | { 33 | first_part.push(second_part.top()); 34 | second_part.pop(); 35 | } 36 | 37 | } 38 | 39 | // Returns the median of current data stream 40 | double findMedian() { 41 | if(first_part.size() == second_part.size()) return ((first_part.top() + second_part.top()) / 2.0); 42 | else if(first_part.size() > second_part.size()) return first_part.top(); 43 | else return second_part.top(); 44 | 45 | } 46 | 47 | 48 | 49 | }; 50 | -------------------------------------------------------------------------------- /SingleThreadedCPU.cpp: -------------------------------------------------------------------------------- 1 | typedef pair P; 2 | typedef long long ll; 3 | class Solution { 4 | public: 5 | vector getOrder(vector>& tasks) { 6 | // to store the ans. 7 | vectorans; 8 | 9 | // min heap 10 | priority_queue,greater<>> pq; 11 | 12 | // insert index in tasks. 13 | int n = tasks.size(); 14 | for(int i=0;i> insert(vector>& intervals, vector& newInterval) { 4 | 5 | vector>ans; 6 | 7 | // 2 cases. 8 | for(auto currentInterval:intervals){ 9 | //case 1 :non overlapping 10 | // new interval is after current interval. add current interval to the ans. 11 | if(currentInterval[1] 2 | using namespace std; 3 | 4 | class DSU 5 | { 6 | private: 7 | vector parent; 8 | vector rank; 9 | 10 | public: 11 | DSU(int n) { 12 | parent.resize(n); 13 | rank.resize(n, 0); // Resizes and initializes rank to 0 14 | 15 | for (int i = 0; i < n; i++) { 16 | parent[i] = i; // Each element is its own parent initially 17 | } 18 | } 19 | 20 | int find(int a) { 21 | if (a == parent[a]) return a; 22 | return parent[a] = find(parent[a]); // Path compression 23 | } 24 | 25 | void Union(int a, int b) { 26 | int a_parent = find(a); 27 | int b_parent = find(b); 28 | 29 | if (a_parent == b_parent) return; // They are already in the same set 30 | 31 | // Union by rank 32 | if (rank[a_parent] < rank[b_parent]) { 33 | parent[a_parent] = b_parent; 34 | } else if (rank[b_parent] < rank[a_parent]) { 35 | parent[b_parent] = a_parent; 36 | } else { 37 | parent[b_parent] = a_parent; 38 | rank[a_parent]++; 39 | } 40 | } 41 | }; 42 | 43 | int main() { 44 | int n; 45 | cout << "Enter the number of elements: "; 46 | cin >> n; 47 | 48 | DSU dsu(n); 49 | 50 | dsu.Union(1, 2); 51 | dsu.Union(4, 1); 52 | 53 | cout << dsu.find(1) << endl; 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Graph/DSU/Disjoint set(Union-Find-Size).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class DSU 5 | { 6 | private: 7 | vector parent; 8 | vector size; 9 | 10 | public: 11 | DSU(int n){ 12 | parent.resize(n); 13 | size.resize(n); // Corrected: resize size vector here 14 | 15 | for(int i = 0; i < n; i++){ 16 | parent[i] = i; 17 | size[i] = 1; 18 | } 19 | } 20 | 21 | int find(int u){ 22 | if(u == parent[u]) return u; 23 | 24 | return parent[u] = find(parent[u]); // Path compression 25 | } 26 | 27 | void Union(int x, int y){ 28 | int x_parent = find(x); 29 | int y_parent = find(y); 30 | 31 | if(x_parent == y_parent) return; 32 | 33 | if(size[x_parent] > size[y_parent]){ 34 | parent[y_parent] = x_parent; 35 | size[x_parent] += size[y_parent]; 36 | }else if(size[x_parent] < size[y_parent]){ // Corrected: Added if here 37 | parent[x_parent] = y_parent; 38 | size[y_parent] += size[x_parent]; 39 | }else{ 40 | parent[x_parent] = y_parent; 41 | size[y_parent] += size[x_parent]; 42 | } 43 | } 44 | }; 45 | 46 | int main(){ 47 | DSU dsu(8); 48 | dsu.Union(0, 2); 49 | dsu.Union(2, 1); 50 | 51 | cout << dsu.find(2) << endl; // Should output the representative of the set that includes 2 52 | 53 | return 54 | } 55 | -------------------------------------------------------------------------------- /MinimumDifficultyDP.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int dp[12][302]; 4 | 5 | public: 6 | 7 | int maxValue(int i,int j, vector&arr){ 8 | int maxi = -1; 9 | 10 | for(int k=i;k<=j;k++){ 11 | maxi = max(maxi,arr[k]); 12 | } 13 | 14 | return maxi; 15 | } 16 | 17 | int minDifficulty(vector& arr, int day) { 18 | // 19 | int n = arr.size(); 20 | 21 | //illegal 22 | if(n>adjlist; 4 | 5 | int dfs(vector& hasApple,int currentNode,int parent,int dis){ 6 | 7 | int disFromChildren = 0; 8 | int disFromRoot = 0; 9 | 10 | for(auto x:adjlist[currentNode]){ 11 | // check only for children if they have apple present or not. 12 | if(x != parent){ 13 | disFromRoot = dfs(hasApple,x,currentNode,dis+1); 14 | // if disfromroot != 0 means children have apple . 15 | // so calculate the dis from the "x" i.e current node to the children. 16 | if(disFromRoot != 0) 17 | disFromChildren += disFromRoot-dis; 18 | } 19 | } 20 | // if no children left or not have any children return the total distance for that subtree. 21 | // (i.e disfromChildren + it own distance from root node (dis)) 22 | return disFromChildren || hasApple[currentNode] ? disFromChildren + dis:0; 23 | 24 | } 25 | int minTime(int n, vector>& edges, vector& hasApple) { 26 | 27 | adjlist.resize(n); 28 | 29 | for(auto x:edges){ 30 | adjlist[x[0]].push_back(x[1]); 31 | adjlist[x[1]].push_back(x[0]); 32 | } 33 | // current node =0 , parent node =-1,distance or level from root. 34 | return dfs(hasApple,0,-1,0)*2; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /FindClosestNodetoGivenTwoNodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void dfs(vector& edges,int node,vector& dist,vector& visited,int distance){ 5 | 6 | // base condition. (already visited or cannot move forward.) 7 | if(node == -1 || visited[node] == 1 ){return ;} 8 | 9 | // make current node visited. 10 | visited[node] = 1; 11 | dist[node] = distance; 12 | // call dfs for other node. 13 | dfs(edges,edges[node],dist,visited,distance+1); 14 | 15 | } 16 | 17 | 18 | int closestMeetingNode(vector& edges, int node1, int node2) { 19 | int n = edges.size(); 20 | 21 | vectordist1(n,-1); 22 | vectordist2(n,-1); 23 | 24 | vectorvisited(n,0); 25 | // dfs for 1 node. 26 | dfs(edges,node1,dist1,visited,0); 27 | 28 | // dfs for 2 node. 29 | vectorvisited2(n,0); 30 | dfs(edges,node2,dist2,visited2,0); 31 | 32 | // we have both distance vector filled. 33 | 34 | int ans = -1; 35 | int value = n; 36 | 37 | for(int i=0;i>adjlist; 4 | vectorans; 5 | 6 | vector dfs(string &labels,int currentNode,int parent){ 7 | 8 | // to store the count vector at each node 9 | vectorcount(26,0); 10 | 11 | for(auto x:adjlist[currentNode]){ 12 | // check only for children. 13 | if(x != parent){ 14 | // it will return count vector for childern. 15 | auto temp = dfs(labels,x,currentNode); 16 | // add temp freq to count freq . 17 | for(int i=0;i<26;i++){ 18 | count[i]+=temp[i]; 19 | } 20 | } 21 | } 22 | 23 | // cal for current node also and add it to the count vector 24 | int ch = labels[currentNode]-'a'; // for b i.e index ch = 1; 25 | count[ch]++; 26 | 27 | // store for the currentNode in ans. 28 | ans[currentNode] = count[ch]; 29 | 30 | return count; 31 | 32 | } 33 | 34 | 35 | vector countSubTrees(int n, vector>& edges, string labels) { 36 | adjlist.resize(n); 37 | ans.resize(n,1); 38 | 39 | for(auto x:edges){ 40 | adjlist[x[0]].push_back(x[1]); 41 | adjlist[x[1]].push_back(x[0]); 42 | } 43 | // current node =0 , parent node =-1,distance or level from root. 44 | dfs(labels,0,-1); 45 | 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /103.ZigzaglevelOrder.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 | vector> zigzagLevelOrder(TreeNode* root) { 15 | 16 | vector> ans; 17 | 18 | queueq; 19 | 20 | if(root == NULL) return ans; 21 | 22 | q.push(root); 23 | 24 | bool flag = false; 25 | 26 | while(!q.empty()){ 27 | // calculate the size. 28 | int size = q.size(); 29 | vectorlevel; 30 | 31 | for(int i=0;ival); 35 | q.pop(); 36 | 37 | if(temp->left != NULL) q.push(temp->left); 38 | 39 | if(temp->right != NULL) q.push(temp->right); 40 | } 41 | ans.push_back(level); 42 | } 43 | 44 | 45 | for(int i=0;i& position, vector& speed) { 4 | // pair 5 | vector>store; 6 | 7 | for(int i=0;i= presentCarTime) // means it will reach faster than fleet , so it will be in the currFleet itself hence no of fleet remain same. else there will be separate fleet for presentCar. 29 | continue; 30 | else{ 31 | count++; 32 | currFleetTime = presentCarTime; // as this car will be in new fleet and other cars will check , if they can join or not. 33 | } 34 | } 35 | return count; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /MostStoneRemovedWithSameRowAndColumn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSameGroup(vector&stone1 ,vector&stone2){ 4 | if(stone1[0] == stone2[0] || stone1[1] == stone2[1]) return true; 5 | return false; 6 | } 7 | 8 | void dfs(vector&visited,vector>& stones,int index){ 9 | 10 | // make it visited. 11 | visited[index] =1; 12 | 13 | // traversal. 14 | for(int i=0;i>& stones) { 24 | //if two stones shares the same row or the same column, they are in same group and we want just one stone to remove all other stone in a group . 25 | // hence question is count the connected component in a graph. 26 | // use dfs. 27 | // Hence our answer will be total count - the number of the connected components 28 | 29 | int n = stones.size(); 30 | vectorvisited(n,0); 31 | int components =0; 32 | for(int i=0;i>&grid,int count){ 8 | // base condtion. 9 | if(i<0 || i>=grid.size() || j<0 || j>=grid[0].size() ||grid[i][j] == -1){ 10 | return ; 11 | } 12 | if(grid[i][j] == 2){ 13 | // if we got all the nonobstacle cover. 14 | if(count == nonObstacle){ 15 | ans++; 16 | } 17 | return; 18 | } 19 | 20 | // make current node visited. 21 | grid[i][j] = -1; 22 | 23 | // Traversal. 24 | dfs(i+1,j,grid,count+1); 25 | dfs(i-1,j,grid,count+1); 26 | dfs(i,j+1,grid,count+1); 27 | dfs(i,j-1,grid,count+1); 28 | 29 | 30 | // backtracking make it non-visited. 31 | grid[i][j] = 0; 32 | 33 | } 34 | 35 | 36 | int uniquePathsIII(vector>& grid) { 37 | 38 | // store the starting position. 39 | int startX = 0; 40 | int startY = 0; 41 | 42 | // find the starting location and number of non-obstacle square. 43 | for(int i=0;i=0;i--){ 16 | for(int j=0;j<=k;j++){ 17 | 18 | // declare 19 | 20 | if(i == n) { dp[n][j] = 0; continue;} 21 | 22 | // case 1 - delete the ith character if possible (j>0) 23 | dp[i][j] = j>0 ? dp[i+1][j-1]:INT_MAX; 24 | 25 | // case 2- keep the ith index. 26 | 27 | // find the index end point 28 | 29 | int possible_del = j,count=0; 30 | for(int end =i;end=0 ;end++){ 31 | if(s[end] == s[i]){ 32 | count++; 33 | 34 | // assumeing the block end here "aaaa" 35 | dp[i][j] = min(dp[i][j] , getLength(count)+dp[end+1][possible_del]); 36 | } 37 | else { 38 | // this character should be deleted. to make length min. 39 | possible_del--; 40 | } 41 | } 42 | 43 | 44 | } 45 | } 46 | 47 | return dp[0][k]; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /AddOneRowTree.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 | 15 | void dfs(TreeNode* root,int val,int currDepth,int depth){ 16 | 17 | if(root == NULL) return; 18 | 19 | // base 20 | if(currDepth == depth-1){ 21 | // left side.new node 22 | TreeNode* leftside = root->left; 23 | root->left = new TreeNode(val); 24 | root->left->left = leftside; 25 | 26 | //rightside 27 | TreeNode*rightside = root->right; 28 | root->right = new TreeNode(val); 29 | root->right->right = rightside; 30 | } 31 | 32 | // traversal 33 | dfs(root->left,val,currDepth+1,depth); 34 | dfs(root->right,val,currDepth+1,depth); 35 | 36 | } 37 | 38 | 39 | TreeNode* addOneRow(TreeNode* root, int val, int depth) { 40 | 41 | // case d==1 42 | if(depth == 1){ 43 | TreeNode* temp = new TreeNode(val); 44 | temp->left = root; 45 | 46 | return temp; 47 | } 48 | 49 | // case 2; d!=1 50 | dfs(root,val,1,depth); 51 | 52 | return root; 53 | 54 | 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /MinGeneticMutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMutation(string start, string end, vector& bank) { 4 | 5 | // queue and set defined. 6 | queue queue; 7 | unordered_set visited; 8 | 9 | // insert start node . 10 | queue.push(start); 11 | visited.insert(start); 12 | 13 | // declare to step to store ans. 14 | int steps = 0; 15 | 16 | // BFS.. 17 | while (!queue.empty()) { 18 | int nodesInQueue = queue.size(); 19 | 20 | for (int j = 0; j < nodesInQueue; j++) { 21 | string node = queue.front(); 22 | queue.pop(); 23 | 24 | // if we reached the end. 25 | if (node == end) { 26 | return steps; 27 | } 28 | 29 | // else do mutation and check for non visited neighbour. 30 | for (char c: "ACGT") { 31 | for (int i = 0; i < node.size(); i++) { 32 | 33 | // do mutation 34 | string mutant = node; 35 | mutant[i] = c; 36 | // check if it is neighbour 37 | if (!visited.count(mutant) && find(bank.begin(), bank.end(), mutant) != bank.end()) { 38 | queue.push(mutant); 39 | visited.insert(mutant); 40 | } 41 | } 42 | } 43 | } 44 | // increase the step value. 45 | steps++; 46 | } 47 | // not found. 48 | return -1; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /WordPattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string s) { 4 | unordered_mapmp; 5 | unordered_mapvisited; 6 | 7 | vectorwordList; 8 | 9 | // stringstream s 10 | stringstream st(s); 11 | 12 | string word; 13 | int count = 0; 14 | 15 | while(st>>word){ 16 | count++; 17 | wordList.push_back(word); 18 | } 19 | 20 | 21 | if(pattern.size() != count){ 22 | return false; 23 | }else{ 24 | for(int i=0;i& costs, int coins) { 5 | 6 | // to get the size of freq array. 7 | int m = *max_element(costs.begin(),costs.end()); 8 | // to store frequency use extra vector 9 | vectorfreq(m+1,0); 10 | 11 | // store the freq. 12 | for(auto x:costs){ 13 | freq[x]++; 14 | } 15 | 16 | // to store the ans 17 | int ans =0; 18 | // traverse on cost vector and see how many coins of that cost can be used . 19 | 20 | for(int cost=1;cost<=m;cost++){ 21 | 22 | // if freq of that cost == 0 then no coin is avaibable move on.. 23 | if(freq[cost] == 0){continue;} 24 | 25 | // if i > coins left so we need to break out as enough coins are not left. 26 | if(cost>coins){break;} 27 | 28 | // else reduce the coins. 29 | 30 | else{ 31 | int usedcoins = min(freq[cost],coins/cost); 32 | coins -= cost*usedcoins; 33 | ans += usedcoins; 34 | } 35 | } 36 | 37 | return ans; 38 | } 39 | }; 40 | 41 | 42 | // Method 1. 43 | class Solution { 44 | public: 45 | int maxIceCream(vector& costs, int coins) { 46 | // sort the costs vector 47 | sort(costs.begin(),costs.end()); 48 | // to store ans; 49 | int ans = 0; 50 | 51 | // traverse and deducte the coins values. 52 | for(auto x:costs) 53 | { 54 | if(x<=coins){ 55 | ans++; 56 | coins-=x; 57 | } 58 | } 59 | return ans; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /SumOfSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int sumSubarrayMins(vector& A) { 5 | 6 | int n = A.size(); 7 | int MOD = 1e9 + 7; 8 | vector left(n), right(n); 9 | 10 | // Left Stack 11 | stackLeft_st; 12 | Left_st.push(0); 13 | 14 | left[0] = 1; // distance = 1 15 | 16 | for(int i=1; iRight_st; 34 | Right_st.push(n-1); 35 | 36 | right[n-1] = 1; 37 | 38 | for(int i=n-2; i>=0; i--) 39 | { 40 | while(!Right_st.empty() && A[i] <= A[Right_st.top()]) 41 | Right_st.pop(); 42 | 43 | if(Right_st.empty()) 44 | right[i] = n-i; // distance 45 | else 46 | right[i] = Right_st.top()-i; 47 | 48 | Right_st.push(i); 49 | } 50 | 51 | // for each value we have left and right contribution will be (Left * Right) * Element 52 | 53 | long long int res = 0; 54 | for(int i=0; i v; 4 | unordered_map mp; 5 | public: 6 | /** Initialize your data structure here. */ 7 | RandomizedSet() { 8 | } 9 | 10 | bool search(int val){ 11 | // is present. 12 | if(mp.find(val)!=mp.end()) 13 | return true; 14 | return false; 15 | 16 | } 17 | 18 | /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ 19 | bool insert(int val) { 20 | // if already there , no need to add. 21 | if(search(val)) 22 | return false; 23 | 24 | v.push_back(val); 25 | mp[val] = v.size()-1; 26 | return true; 27 | } 28 | 29 | /** Removes a value from the set. Returns true if the set contained the specified element. */ 30 | bool remove(int val) { 31 | // if not present.we can remove. 32 | if(!search(val)) 33 | return false; 34 | 35 | // pointer to the value. 36 | auto it = mp.find(val); 37 | v[it->second] = v.back(); 38 | v.pop_back(); 39 | mp[v[it->second]] = it->second; 40 | mp.erase(val); 41 | return true; 42 | } 43 | 44 | /** Get a random element from the set. */ 45 | int getRandom() { 46 | // rand()%v.size() : give us index between 1 to v.size()-1 47 | return v[rand()%v.size()]; 48 | } 49 | }; 50 | 51 | /** 52 | * Your RandomizedSet object will be instantiated and called as such: 53 | * RandomizedSet* obj = new RandomizedSet(); 54 | * bool param_1 = obj->insert(val); 55 | * bool param_2 = obj->remove(val); 56 | * int param_3 = obj->getRandom(); 57 | */ 58 | -------------------------------------------------------------------------------- /CircularMaxSumSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int kadane(vector& nums) { 5 | 6 | //if(nums.size() == 1) return nums[0]; 7 | 8 | int Maxsofar = INT_MIN; 9 | int currmax = 0; 10 | 11 | for(auto i:nums){ 12 | currmax += i; 13 | 14 | //will run for atleast one case 15 | if(currmax >Maxsofar){ 16 | Maxsofar = max(Maxsofar,currmax); 17 | } 18 | 19 | if(currmax<0){ 20 | currmax =0; 21 | } 22 | } 23 | 24 | return Maxsofar; 25 | 26 | } 27 | 28 | int maxSubarraySumCircular(vector& nums) { 29 | 30 | 31 | // for positive nums. 32 | int maxsubarraySum = kadane(nums); 33 | 34 | // reverse the nums vector and then calculate the maxsum_array. == minsum_array of orignal. 35 | int countpositive =0; 36 | int total_sum_reverse =0; 37 | int minvalue_reverse =INT_MAX; 38 | 39 | 40 | for(int i=0;i0){countpositive++;} 45 | total_sum_reverse +=nums[i]; 46 | minvalue_reverse = min(minvalue_reverse,nums[i]); 47 | } 48 | 49 | // all negative return min -ve value == maxpositive value. 50 | if(countpositive == nums.size()){ 51 | return -1*(minvalue_reverse); 52 | } 53 | 54 | 55 | int maxsubarraySum_reverse = kadane(nums); 56 | 57 | int reverse_ans = -1 * (total_sum_reverse - maxsubarraySum_reverse); 58 | 59 | 60 | return max(maxsubarraySum,reverse_ans); 61 | 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Graph/DFS/Minimum Number of Days to Disconnect Island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int i,int j,auto& grid){ 4 | if(i<0 || i>= grid.size() || j<0 || j>=grid[0].size() || grid[i][j] == 0){ 5 | return; 6 | } 7 | 8 | // make visited. 9 | grid[i][j] =0; 10 | 11 | dfs(i+1,j,grid); 12 | dfs(i-1,j,grid); 13 | dfs(i,j+1,grid); 14 | dfs(i,j-1,grid); 15 | 16 | } 17 | int countOfIsland(vector>&grid){ 18 | int count =0; 19 | auto temp = grid; // make copy here itself not in the main func to avoid confution. 20 | 21 | for(int i=0;i>& grid) { 34 | auto temp = grid; 35 | int numOfIslands = countOfIsland(temp); 36 | 37 | // already seperated. 38 | if(numOfIslands == 0 || numOfIslands >=2) return 0; 39 | 40 | // test for each cell. 41 | else{ 42 | temp = grid; 43 | for(int i=0;i=2 || minday == 0) return 1; 50 | temp[i][j] = 1; 51 | } 52 | } 53 | } 54 | } 55 | 56 | return 2; 57 | 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Graph/DFS/Regions Cut By Slashes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(auto& store,int i,int j){ 4 | if(i<0 || j<0|| i>=store.size()||j>=store.size() || store[i][j] == 1){ 5 | return; 6 | } 7 | 8 | // make visited. 9 | store[i][j] = 1; 10 | 11 | // Visit all 4 directions (up, down, left, right) 12 | dfs(store,i+1,j); 13 | dfs(store,i-1,j); 14 | dfs(store,i,j+1); 15 | dfs(store,i,j-1); 16 | } 17 | int regionsBySlashes(vector& grid) { 18 | // n*n so, rows == coln = n. 19 | int n = grid.size(); 20 | 21 | // Create a 3*n x 3*n grid where each cell is divided into 9 smaller parts 22 | vector>store(3*n,vector(3*n,0)); 23 | 24 | for(int i=0;i 0) 6 | { 7 | if(num >= 1000) 8 | { 9 | res += "M"; 10 | num -=1000; 11 | } 12 | else if(num >= 900) 13 | { 14 | res += "CM"; 15 | num -= 900; 16 | } 17 | else if(num >= 500) 18 | { 19 | res += "D"; 20 | num -= 500; 21 | } 22 | else if(num >= 400) 23 | { 24 | res += "CD"; 25 | num -= 400; 26 | } 27 | else if(num >= 100) 28 | { 29 | res += "C"; 30 | num -= 100; 31 | } 32 | else if(num >= 90) 33 | { 34 | res += "XC"; 35 | num -= 90; 36 | } 37 | else if(num >= 50) 38 | { 39 | res += "L"; 40 | num -= 50; 41 | } 42 | else if(num >= 40) 43 | { 44 | res += "XL"; 45 | num -= 40; 46 | } 47 | else if(num >= 10) 48 | { 49 | res += "X"; 50 | num -= 10; 51 | } 52 | else if(num >= 9) 53 | { 54 | res += "IX"; 55 | num -= 9; 56 | } 57 | else if(num >= 5) 58 | { 59 | res += "V"; 60 | num -= 5; 61 | } 62 | else if(num >= 4) 63 | { 64 | res += "IV"; 65 | num -= 4; 66 | } 67 | else if(num >= 1) 68 | { 69 | res += "I"; 70 | num -= 1; 71 | } 72 | } 73 | return res; 74 | 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /Skyline.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | static bool sorting(paira,pairb){ 5 | if(a.first == b.first){ 6 | return a.second> getSkyline(vector>& buildings) { 12 | 13 | vector> result; 14 | 15 | vector> store; 16 | 17 | for(int i=0;ist; 31 | 32 | st.insert(0); 33 | 34 | for(auto x:store){ 35 | if(x.second<0){ 36 | st.insert(-1*x.second); 37 | 38 | if(currentHeight != *st.rbegin()){ 39 | currentHeight = *st.rbegin(); 40 | 41 | vectortemp = {x.first,currentHeight}; 42 | result.push_back(temp); 43 | } 44 | 45 | } 46 | else if(x.second>=0){ 47 | auto it = st.find(x.second); 48 | st.erase(it); 49 | 50 | if(*st.rbegin() != currentHeight){ 51 | currentHeight = *st.rbegin(); 52 | 53 | vectortemp = {x.first,currentHeight}; 54 | result.push_back(temp); 55 | } 56 | } 57 | 58 | 59 | } 60 | 61 | return result; 62 | 63 | 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /MaxProfitJob.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //binary search to find latest non overlapping interval 4 | int latest_non_overlap_opt(vector> &job,int i) 5 | { 6 | int low = 0, high = i - 1; 7 | while (low <= high) 8 | { 9 | int mid = (low + high) / 2; 10 | if (job[mid][0] <= job[i][1]) // end time is less then start time of current job. 11 | { 12 | if (job[mid + 1][0] <= job[i][1]) // increment the low. normal binary search. 13 | low = mid + 1; 14 | else // return lower bound. 15 | return mid; 16 | } 17 | else 18 | high = mid - 1; 19 | } 20 | return -1; 21 | } 22 | 23 | 24 | 25 | int jobScheduling(vector& startTime, vector& endTime, vector& profit) { 26 | int n = startTime.size(); 27 | 28 | vector>job(n,vector(3)); 29 | 30 | for(int i=0;i dp(n,0); 40 | dp[0] = job[0][2]; 41 | 42 | 43 | for(int i=1;i>&dp){ 20 | 21 | //base case 22 | if(dices==0) return target == 0; 23 | 24 | // already visited or calcualted values. 25 | if( dp[dices][target] != -1 ) return dp[dices][target]; 26 | 27 | int ans=0; 28 | for(int i=1;i<=faces;i++){ 29 | if(target-i>=0) 30 | ans = (ans+ HelperforMemo(dices-1,faces,target-i,dp))%mod; 31 | } 32 | dp[dices][target] = ans; 33 | 34 | return ans; 35 | } 36 | 37 | 38 | 39 | int HelperForTabular(int dices,int faces,int target){ 40 | vector>dp(dices+1,vector(target+1,0)); 41 | 42 | 43 | 44 | dp[0][0] = 1; 45 | 46 | for(int i=1;i<=dices;i++){ 47 | for(int j = 1;j<=target;j++){ 48 | for(int f=1;f<=faces;f++){ 49 | if(j-f>=0) 50 | dp[i][j] = (dp[i][j]+ dp[i-1][j-f])%mod; 51 | } 52 | } 53 | } 54 | return dp[dices][target]; 55 | 56 | } 57 | 58 | 59 | 60 | int numRollsToTarget(int n, int k, int target) { 61 | // return HelperforRecursion(n,k,target); 62 | 63 | // memoization. // top down 64 | // vector>dp(n+1,vector(target+1,-1)); 65 | // return HelperforMemo(n,k,target,dp); 66 | 67 | // tabular , bottom up 68 | return HelperForTabular(n,k,target); 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /BasicCalculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculate(string s) { 4 | 5 | long long int sum = 0; 6 | int sign = 1; 7 | 8 | // declare stack. {prev_expression_value , sign before next bracket ()} 9 | stack>st; 10 | 11 | for(int i=0;iphash(256,0); 15 | vectorshash(256,0); 16 | 17 | // to store the min possible substring == ans. 18 |    string ans = ""; 19 | 20 | 21 | //declare the window size i.e(pattern size) && length of string s; 22 | int window = p.size(); 23 | int length = s.size(); 24 | 25 | 26 | // store frequency of pattern 27 | for(int i=0;i,vector>,greater>>pq; 9 | 10 | pq.push({0,src}); 11 | 12 | while(!pq.empty()){ 13 | auto curr = pq.top(); pq.pop(); 14 | ll u = curr.second; 15 | ll d = curr.first; 16 | 17 | if (d > res[u]) continue; // Skip outdated paths 18 | 19 | for(auto&v:adj[u]){ 20 | ll dis = v.second; 21 | ll node = v.first; 22 | 23 | if(d+dis>& edges, int src1, int src2, int dest) { 33 | 34 | unordered_map>>adj; 35 | unordered_map>>revadj; 36 | 37 | for(auto &x:edges){ 38 | ll u = x[0]; 39 | ll v = x[1]; 40 | ll wt = x[2]; 41 | 42 | adj[u].push_back({v,wt}); 43 | revadj[v].push_back({u,wt}); 44 | } 45 | 46 | // make traversal. 47 | vectordes1(n,INF); des1[src1]= 0; 48 | vectordes2(n,INF); des2[src2]= 0; 49 | vectordes3(n,INF); des3[dest]= 0; 50 | 51 | 52 | // Source 1, Source 2, aur destination ke liye shortest path find karo 53 | dykstra(adj,des1,src1); 54 | dykstra(adj,des2,src2); 55 | dykstra(revadj,des3,dest); // dest se sab tak (reverse graph) 56 | 57 | // Answer initialize karo INF se 58 | ll ans = INF; 59 | for(int i=0;i>& grid, int k) { 4 | 5 |   int m = grid.size(); 6 | int n = grid[0].size(); 7 | 8 | // This vector stores the number of obstacles that we can still remove after walking through that cell 9 | vector> visited(m, vector(n, -1)); 10 | 11 | queue> q; 12 | 13 | // x, y, currentLength, remaining k 14 | 15 | q.push({0,0,0,k}); 16 | while(!q.empty()){ 17 | 18 | auto t = q.front(); 19 | q.pop(); 20 | 21 | int x = t[0], y = t[1]; 22 | 23 |    // part 1- base cases. 24 | 25 |     // Invalid cases being dealt here since it's easier to write one condition instead of 4 while pushing. 26 |     if(x<0 || x>=m || y<0 || y>=n) 27 | continue; 28 | 29 | // If you've reached the end, great, return the currentLength! 30 | 31 |      if(x == m-1 && y == n-1) 32 | return t[2]; //currentLength of the path 33 | 34 | // If we hit an obstacle & we don't have any Ks remaining, continue 35 | // If we still have Ks to spend, we spend 1. 36 | 37 |    if(grid[x][y] == 1){ 38 | if(t[3] > 0) 39 | t[3]--; 40 | else 41 | continue; 42 | } 43 | 44 | // If this cell is already visited with a K value lesser than this one, we would want to save Ks for future use, so we continue 45 | if(visited[x][y]!=-1 && visited[x][y] >= t[3]){ 46 | continue; 47 | } 48 | 49 | 50 |    // Part 2 - make visited. 51 | // We store the currentRemaining K after spending K (if required) into the visited matrix. 52 | 53 | visited[x][y] = t[3]; 54 | 55 | 56 |    // Part 3 - Make Traversal. 57 | // Push the adjacent nodes in the queue. 58 | 59 | q.push({x+1, y, t[2]+1, t[3]}); 60 | q.push({x-1, y, t[2]+1, t[3]}); 61 | q.push({x, y+1, t[2]+1, t[3]}); 62 | q.push({x, y-1, t[2]+1, t[3]}); 63 | } 64 | 65 | return -1; 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /NearestExistMaze.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nearestExit(vector>& maze, vector& entrance) { 4 | // declare rows and column variable. 5 | int rows = maze.size(); 6 | int columns = maze[0].size(); 7 | 8 | // we will perfom bfs as shorter distance node will be traverse first at one level. 9 | // define queue. 10 | queue>q; 11 | int steps = 1; 12 | 13 | // all the valid traversal direction. 14 | vector>direction = {{0,1},{0,-1},{1,0},{-1,0}}; 15 | 16 | // push the entry to the queue & make it visited. and apply bfs . 17 | q.push({entrance[0],entrance[1]}); // q.push((x , y)) 18 | // make it visited. 19 | maze[entrance[0]][entrance[1]] = '+'; 20 | 21 | while(!q.empty()){ 22 | 23 | // check the node in that level. 24 | int l=q.size(); 25 | // for every node in the queue visit all of it's adjacent nodes which are not visited yet 26 | for(int i=0;i=rows || y>=columns || maze[x][y]=='+') 40 | continue; 41 | // if we have reached the exit then current steps are the min steps to reach the exit 42 | if(x==0 || y==0 || x==rows-1 || y==columns-1) 43 | return steps; 44 | // block the cell as we have visited and push in queue. 45 | maze[x][y]='+'; 46 | q.push({x,y}); 47 | } 48 | } 49 | //increment the steps. i.e for one circle we did not find exit. 50 | steps++; 51 | 52 | 53 | 54 | } 55 | // if steps are not found. 56 | return -1; 57 | 58 | 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /wordSeachr2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | struct TrieNode { 3 | TrieNode *children[26]; 4 | string word; 5 | 6 | TrieNode() : word("") { 7 | for (int i = 0; i < 26; i++) { 8 | children[i] = nullptr; 9 | } 10 | } 11 | }; 12 | 13 | public: 14 | vector findWords(vector> &board, vector &words) { 15 | TrieNode *root = buildTrie(words); 16 | 17 | vector result; 18 | 19 | for (int i = 0; i < board.size(); i++) { 20 | for (int j = 0; j < board[0].size(); j++) { 21 | dfs(board, i, j, root, result); 22 | } 23 | } 24 | return result; 25 | } 26 | 27 | // Inserts a word into the trie. 28 | TrieNode *buildTrie(vector &words) { 29 | //create trie. 30 | TrieNode *root = new TrieNode(); 31 | 32 | for (int j = 0; j < words.size(); j++) { 33 | string word = words[j]; 34 | TrieNode *curr = root; 35 | 36 | for (int i = 0; i < word.length(); i++) { 37 | char c = word[i] - 'a'; 38 | if (curr->children[c] == nullptr) { 39 | curr->children[c] = new TrieNode(); 40 | } 41 | curr = curr->children[c]; 42 | } 43 | curr->word = word; 44 | } 45 | return root; 46 | } 47 | 48 | void dfs(vector> &board, int i, int j, TrieNode *p, vector &result) { 49 | char c = board[i][j]; 50 | 51 | // base case. 52 | if (c == '#' || !p->children[c - 'a']) return; 53 | 54 | 55 | 56 | // append the child. 57 | p = p->children[c - 'a']; 58 | 59 | // if valid word. add to result. (we got our word.) 60 | if (p->word.size() > 0) { 61 | result.push_back(p->word); 62 | p->word = ""; 63 | } 64 | 65 | // make it visited. 66 | board[i][j] = '#'; 67 | 68 | // travel in valid direction only. 69 | if (i > 0) dfs(board, i - 1, j, p, result); 70 | if (j > 0) dfs(board, i, j - 1, p, result); 71 | if (i < board.size() - 1) dfs(board, i + 1, j, p, result); 72 | if (j < board[0].size() - 1) dfs(board, i, j + 1, p, result); 73 | 74 | // backtrack the value. 75 | board[i][j] = c; 76 | 77 | } 78 | }; 79 | -------------------------------------------------------------------------------- /Important/Get the Maximum Score.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int MOD = 1e9 + 7; // Define MOD to handle large sums and avoid overflow. 4 | 5 | int maxSum(vector& nums1, vector& nums2) { 6 | int i = 0, j = 0; // Pointers for iterating through nums1 and nums2. 7 | long long sum1 = 0, 8 | sum2 = 0; // Sums to accumulate path values from each array. 9 | int n = nums1.size(); // Size of the first array. 10 | int m = nums2.size(); // Size of the second array. 11 | long long int ans = 0; // Variable to store the final result. 12 | 13 | // Traverse both arrays simultaneously until we reach the end of one of 14 | // them. 15 | while (i < n && j < m) { 16 | // If nums1[i] is smaller, accumulate sum1 and move to the next 17 | // element in nums1. 18 | if (nums1[i] < nums2[j]) { 19 | sum1 = (sum1 + nums1[i]) % MOD; 20 | i++; 21 | } 22 | // If nums2[j] is smaller, accumulate sum2 and move to the next 23 | // element in nums2. 24 | else if (nums2[j] < nums1[i]) { 25 | sum2 = (sum2 + nums2[j]) % MOD; 26 | j++; 27 | } 28 | // If both elements are equal (common point), take the maximum of 29 | // sum1 and sum2, add the common element, and move both pointers 30 | // forward. 31 | else { 32 | ans = (ans + max(sum1, sum2) + nums2[j]) % MOD; 33 | i++; 34 | j++; 35 | // Reset sum1 and sum2 after handling the common point. 36 | sum1 = 0; 37 | sum2 = 0; 38 | } 39 | } 40 | 41 | // If there are remaining elements in nums1, add them to sum1. 42 | while (i < n) { 43 | sum1 = (sum1 + nums1[i]) % MOD; 44 | i++; 45 | } 46 | 47 | // Example 3 nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] , if nothing is equal then sum2 and sum1 max of both will be ans. In this case no common point is there so we have ans = 0 uptill end of nums1 traversal. 48 | 49 | // If there are remaining elements in nums2, add them to sum2. 50 | while (j < m) { 51 | sum2 = (sum2 + nums2[j]) % MOD; 52 | j++; 53 | } 54 | 55 | // After finishing both arrays, add the maximum of the remaining sum1 or 56 | // sum2 to the result. 57 | ans = (ans + max(sum1, sum2)) % MOD; 58 | 59 | return ans; // Return the final maximum sum mod 10^9 + 7. 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /TwoPointers/Get the Maximum Score.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int MOD = 1e9 + 7; // Define MOD to handle large sums and avoid overflow. 4 | 5 | int maxSum(vector& nums1, vector& nums2) { 6 | int i = 0, j = 0; // Pointers for iterating through nums1 and nums2. 7 | long long sum1 = 0, 8 | sum2 = 0; // Sums to accumulate path values from each array. 9 | int n = nums1.size(); // Size of the first array. 10 | int m = nums2.size(); // Size of the second array. 11 | long long int ans = 0; // Variable to store the final result. 12 | 13 | // Traverse both arrays simultaneously until we reach the end of one of 14 | // them. 15 | while (i < n && j < m) { 16 | // If nums1[i] is smaller, accumulate sum1 and move to the next 17 | // element in nums1. 18 | if (nums1[i] < nums2[j]) { 19 | sum1 = (sum1 + nums1[i]) % MOD; 20 | i++; 21 | } 22 | // If nums2[j] is smaller, accumulate sum2 and move to the next 23 | // element in nums2. 24 | else if (nums2[j] < nums1[i]) { 25 | sum2 = (sum2 + nums2[j]) % MOD; 26 | j++; 27 | } 28 | // If both elements are equal (common point), take the maximum of 29 | // sum1 and sum2, add the common element, and move both pointers 30 | // forward. 31 | else { 32 | ans = (ans + max(sum1, sum2) + nums2[j]) % MOD; 33 | i++; 34 | j++; 35 | // Reset sum1 and sum2 after handling the common point. 36 | sum1 = 0; 37 | sum2 = 0; 38 | } 39 | } 40 | 41 | // If there are remaining elements in nums1, add them to sum1. 42 | while (i < n) { 43 | sum1 = (sum1 + nums1[i]) % MOD; 44 | i++; 45 | } 46 | 47 | // Example 3 nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] , if nothing is equal then sum2 and sum1 max of both will be ans. In this case no common point is there so we have ans = 0 uptill end of nums1 traversal. 48 | 49 | // If there are remaining elements in nums2, add them to sum2. 50 | while (j < m) { 51 | sum2 = (sum2 + nums2[j]) % MOD; 52 | j++; 53 | } 54 | 55 | // After finishing both arrays, add the maximum of the remaining sum1 or 56 | // sum2 to the result. 57 | ans = (ans + max(sum1, sum2)) % MOD; 58 | 59 | return ans; // Return the final maximum sum mod 10^9 + 7. 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /EcretFenching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // To calculate the crossProduct 4 | // Cross product of two vectors AB and AC 5 | // returns positive for counter clockwise 6 | // turn and negative for clockwise turn 7 | int getRotationAngle(vector A, vector B, vector C) { 8 | // (x2-x1)(y3-y1) - (y2-y1)(x3-x1) -> 3D Cross-product of AB and AC vectors 9 | return ((B[0] - A[0]) * (C[1] - A[1])) - ((B[1] - A[1]) * (C[0] - A[0])); 10 | } 11 | 12 | 13 | vector> outerTrees(vector>& trees) { 14 | // If less then or equal to 3 return Trees. They all need to included . 15 | if (trees.size() <= 3) return trees; 16 | 17 | // sort them according to increasing order of x cordinates. 18 | sort(trees.begin(), trees.end()); 19 | 20 | // Upper HULL construction 21 | vector> UpperHullTrees; 22 | 23 | // Push first 2 points in UpperHullTrees. 24 | UpperHullTrees.push_back(trees[0]); 25 | UpperHullTrees.push_back(trees[1]); 26 | 27 | // Travese throw all the points of sorted Trees. 28 | for (int i = 2; i < trees.size(); i++) { 29 | int Us = UpperHullTrees.size(); 30 | 31 | // Cross Product > 0 bigger counterclockwise angle . So,we need to remove B and insert C. 32 | while (UpperHullTrees.size() >= 2 && getRotationAngle(UpperHullTrees[Us-2], UpperHullTrees[Us-1], trees[i]) > 0) { 33 | UpperHullTrees.pop_back(); 34 | Us--; 35 | } 36 | UpperHullTrees.push_back(trees[i]); 37 | } 38 | 39 | // Lower HULL construction 40 | vector> LowerHullTrees; 41 | 42 | LowerHullTrees.push_back(trees[trees.size() - 1]); 43 | LowerHullTrees.push_back(trees[trees.size() - 2]); 44 | 45 | for (int i = trees.size() - 3; i >= 0; --i) { 46 | int Ls = LowerHullTrees.size(); 47 | while (LowerHullTrees.size() >= 2 && getRotationAngle(LowerHullTrees[Ls-2], LowerHullTrees[Ls-1], trees[i]) > 0) { 48 | LowerHullTrees.pop_back(); 49 | Ls--; 50 | } 51 | LowerHullTrees.push_back(trees[i]); 52 | } 53 | 54 | // Add the top hull to down hull 55 | UpperHullTrees.insert( UpperHullTrees.end(), LowerHullTrees.begin(), LowerHullTrees.end() ); 56 | 57 | // Remove the duplicates present in the lTrees. 58 | sort( UpperHullTrees.begin(), UpperHullTrees.end() ); 59 | UpperHullTrees.erase( unique( UpperHullTrees.begin(), UpperHullTrees.end() ), UpperHullTrees.end() ); 60 | 61 | return UpperHullTrees; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Graph/DSU/Making A Large Island.cpp: -------------------------------------------------------------------------------- 1 | class DSU { 2 | public: 3 | vector parent; 4 | vector size; 5 | 6 | // Constructor that initializes DSU with `n` elements 7 | DSU(int n) { 8 | parent.resize(n); // Resize the parent vector 9 | size.resize(n); // Resize the size vector 10 | for (int i = 0; i < n; i++) { 11 | parent[i] = i; 12 | size[i] = 1; 13 | } 14 | } 15 | 16 | // Path compression for finding the parent 17 | int find(int a) { 18 | if (parent[a] == a) return a; 19 | return parent[a] = find(parent[a]); 20 | } 21 | 22 | // Union by size 23 | void Union(int a, int b) { 24 | int parent_a = find(a); 25 | int parent_b = find(b); 26 | 27 | if (parent_a == parent_b) return; 28 | 29 | if (size[parent_a] < size[parent_b]) { 30 | size[parent_b] += size[parent_a]; 31 | parent[parent_a] = parent_b; 32 | } else if (size[parent_a] > size[parent_b]) { 33 | size[parent_a] += size[parent_b]; 34 | parent[parent_b] = parent_a; 35 | } else { 36 | size[parent_a] += size[parent_b]; 37 | parent[parent_b] = parent_a; 38 | } 39 | } 40 | }; 41 | 42 | class Solution { 43 | public: 44 | vector> directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; 45 | 46 | int largestIsland(vector>& grid) { 47 | int m = grid.size(); 48 | int n = grid[0].size(); 49 | 50 | int totalSize = m * n; // Convert 2D index to 1D index 51 | DSU dsu(totalSize); 52 | 53 | // Lambda to check if a position is valid 54 | auto isValid = [&](int x, int y) { 55 | return x >= 0 && x < m && y >= 0 && y < n; 56 | }; 57 | 58 | // Step 1: Union connected components by size for all '1's in the grid 59 | for (int i = 0; i < m; i++) { 60 | for (int j = 0; j < n; j++) { 61 | if (grid[i][j] == 1) { 62 | for (auto& dir : directions) { 63 | int x_ = i + dir[0]; 64 | int y_ = j + dir[1]; 65 | 66 | if (isValid(x_, y_) && grid[x_][y_] == 1) { 67 | // Union 2D indices after converting to 1D index 68 | int newIndex = x_ * n + y_; 69 | int oldIndex = i * n + j; 70 | 71 | dsu.Union(oldIndex, newIndex); 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | int ans = 0; 79 | // Step 2: Check for each 0 and calculate the max island size after flipping it 80 | for (int i = 0; i < m; i++) { 81 | for (int j = 0; j < n; j++) { 82 | if (grid[i][j] == 0) { // We are considering flipping this 0 83 | unordered_set visitedComp; 84 | int totalSumForThisZero = 1; // Start with 1 for this zero itself 85 | for (auto& dir : directions) { 86 | int x_ = i + dir[0]; 87 | int y_ = j + dir[1]; 88 | 89 | if (isValid(x_, y_) && grid[x_][y_] == 1) { 90 | int index = x_ * n + y_; 91 | int root = dsu.find(index); // Use dsu.find() to get the representative 92 | 93 | if (!visitedComp.count(root)) { 94 | visitedComp.insert(root); 95 | totalSumForThisZero += dsu.size[root]; // Add the size of the component 96 | } 97 | } 98 | } 99 | ans = max(ans, totalSumForThisZero); 100 | } 101 | } 102 | } 103 | 104 | // If no zero was flipped, the largest island is the entire grid or the existing islands 105 | for (int i = 0; i < totalSize; i++) { 106 | ans = max(ans, dsu.size[dsu.find(i)]); 107 | } 108 | 109 | return ans; 110 | } 111 | }; 112 | --------------------------------------------------------------------------------