├── ref.md ├── 231. Power of Two.cpp ├── 89. Grey Code.cpp ├── 100. same Tree or Identical Tree.cpp ├── 48. Rotate image.cpp ├── 104. Maximum Depth of Binary Tree.cpp ├── 283. Move Zeroes.cpp ├── 2894. Divisible and Non-Divisible SumDifferences.cpp ├── 55. Jump Game.cpp ├── 96. Unique Binary Search Trees.cpp ├── 1323. Maximum 69 Number.cpp ├── 1512. Number of Good Pairs.cpp ├── 114. Flatten Binary Tree to Linked List.cpp ├── 292.NimGame.cpp ├── 557. Reverse Words in a String III.cpp ├── 26. Remove Duplicates from Sorted Array.cpp ├── 101. Symetric Tree.cpp ├── 145. Binary tree PostOrder Traversal.cpp ├── 2894. Divisible and Non-divisible Sums Difference.cpp ├── 3487. Maximum Unique Subarray Sum After Deletion.cpp ├── 344. Reverse String.cpp ├── 144. Binary Tree PreOrder traversal.cpp ├── 991. Broken Calculator.cpp ├── 3100. Water Bottles II.cpp ├── 78. Subsets.cpp ├── 2942. Find Words Containing Character.cpp ├── 45.Jump Game II.cpp ├── 1963. Minimum number of Swaps to make String Balanced.cpp ├── 1128.NumberOfEquivalentDominoPairs.cpp ├── 2210. count Hills and valleys in an Array.cpp ├── 485. Max Consecutive Ones.cpp ├── 56. Merge intervals.cpp ├── 3461. Check If Digits Are Equal in String After Operations I.cpp ├── 242. Valid Anagram.cpp ├── 896.Monotonic Array.cpp ├── 1046. Last Stone Weight.cpp ├── 2109. Adding Spaces to a String.cpp ├── 230. Kth Smallest Element.cpp ├── 3147.Taking Maximum Energy From the Mystic Dungeon.cpp ├── 731. My Calender II.cpp ├── 389. Find the Difference.cpp ├── 83. Remove Duplicates from Sorted List.cpp ├── 951. Flip Equivalent Binary Trees.cpp ├── 852. peak Index in a Mountain Array.cpp ├── 118. Pascal Triangle.cpp ├── 678. Valid Parenthesis String.cpp ├── 287. Find The Duplicate number.cpp ├── 950.Reveal cards in Increasing order.cpp ├── .github ├── workflows │ ├── greetings.yml │ └── pr-merged-automate-message.yml ├── pull_request_template.md ├── FUNDING.yml └── ISSUE_TEMPLATE │ └── solution-contribution.yml ├── 236. lowest Common Ancestor of A Binary tree.cpp ├── 904. Fruit Into Baskets.cpp ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp ├── 70. Climbing Stairs.cpp ├── 162. Find Peak Element.cpp ├── 3477. Fruits Into Baskets II.cpp ├── 219.NearbyDuplicate.cpp ├── 326. Power of Three.cpp ├── 543. Diameter of Binary Tree.cpp ├── 567. Permutation in String.cpp ├── 3208.Alternating Groups II.cpp ├── 322. Coin Change.cpp ├── 763. Partition Labels.cpp ├── 2401.Longest Nice Subarray.cpp ├── 11. Container With Most Water.cpp ├── 867. Transpose Matrix.cpp ├── 152. Maximum-Product-Subarray.cpp ├── 2273. Find Resultant Array After Removing Anagrams.cpp ├── 498. Diagonal Traverse.cpp ├── 102. Binary Tree level Order Traversal.cpp ├── 141. FloydCycle.cpp ├── 3355. Zero Array Transformation I.cpp ├── 135. Candy.cpp ├── 2843. Count Symmetric Integers.cpp ├── 724. Find Pivot Index.cpp ├── DutchflagAlgo.cpp ├── 2251. Number of Flowers in Full Bloom.cpp ├── 155. Min Stack.cpp ├── 2181. Merge Nodes between two Zeros.cpp ├── 2327. Number of People Aware of a Secret.cpp ├── 32. Longest Valid Parentheses.cpp ├── 1605. Find valid matrix Given Row and Coloumn Sums.cpp ├── 57. Insert Interval.cpp ├── 191. Number of 1 Bits.cpp ├── 3705. Longest substring without repeating characters.cpp ├── README.md ├── 880. Decoded String at Index.cpp ├── 653. Two Sum IV - Input is a BST.cpp ├── 61. Rotate List.cpp ├── 35. Search Insert Position.cpp ├── 123. Best time to buy or sell stock iii .cpp ├── 34. Find First and Last Position of Element in Sorted Array.cpp ├── 225.Implement Stack Using Queues.cpp ├── 2785.Sort Vowels in a String.cpp ├── 134. Gas Station.cpp ├── 342. Power of Four.cpp ├── 110. Blanced Binary Tree.cpp ├── 1019. Next Greater Node in Linked List.cpp ├── 73. Set Matrix Zeroes.cpp ├── 338.Counting Bits.cpp ├── 514. Freedom Trail.cpp ├── 3297. Count Substrings That Can Be Rearranged to Contain a String I.cpp ├── 3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp ├── 98. Validate Binary Search Tree.cpp ├── 23. Merge k Sorted Lists.cpp ├── 17. Letter Combinations of a Phone Number.cpp ├── 8. String to Integer (atoi).cpp ├── 2561. Rearranging Fruits.cpp ├── 199. Binary Tree Right Side View.cpp ├── 113. Path Sum 2.cpp ├── 1094.Car Pooling.cpp ├── 1716. Calculate Money in Leetcode bank.cpp ├── LICENSE ├── 3024.Type of Triangle.cpp ├── 2583. Kth Largest Sum in a Binary Tree.cpp ├── 20. Valid Parentheses.cpp ├── 4. Median of Two Sorted Array.cpp ├── 50.Pow(x,n).cpp ├── 416. Partition Equal Subset Sum.cpp ├── 138. Copy List with random pointer.cpp ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.cpp ├── 1920. Build Array from Permutation.cpp ├── 232.Implement Queue using Stacks.cpp ├── 1662. Check if Two String Arrays are Equivalent.cpp ├── 160. Intersection of Two Linked List.cpp ├── 838. Push Dominoes.cpp ├── 3350. Adjacent Increasing Subarrays Detection II.cpp ├── 2009. Minimum number of Operations to Make a Array Continuous.cpp ├── 2058. Find min and max number between critical Point.cpp ├── 3341. Find Minimum Time to Reach Last Room I.cpp ├── 3342. Find Minimum Time to Reach Last Room II.cpp ├── 355. Design Twitter.cpp ├── 239. Sliding Window Maximum.cpp ├── 3. Longest Substring Without Repeating Characters.cpp ├── 51.N-Queens.cpp ├── 37. Sudoku Solver.cpp ├── 731. My Calender II ├── 226. Invert Binary Tree.cpp ├── 1518. Water Bottles.cpp ├── 3479.Fruits Into Baskets 3.cpp ├── 3003. Maximize the Number of Partitions After Operations.cpp ├── 3720. Lexicographically Smallest Permutation Greater Than Target.cpp ├── 42. Trapping Rain Water.cpp ├── 2071. Maximum Number of Tasks You Can Assign.cpp ├── 92. Reverse Linked List II.cpp ├── 853. Car Fleet I.cpp ├── 1857. Largest_Color_Value_in_a_Directed_Graph.cpp ├── 1912. Design Movie Rental System.cpp ├── 3068. Find the Maximum Sum of Node Values.cpp ├── 407. Trapping Rain Water II.cpp ├── 976. Largest Perimeter Triangle.cpp ├── 15. 3Sum.cpp ├── 3446. Sort Matrix by Diagonals.cpp ├── CONTRIBUTING.md ├── 84. Largest Rectangle in Histogram.cpp ├── 966. Vowel Spellchecker.cpp ├── 875.Koko Eating Bananas.cpp ├── 417. Pacific Atlantic Water Flow.cpp ├── 206.Course Schedule.cpp ├── 6.Zigzag Conversion.cpp ├── 3703. Remove K-Balanced Substrings.cpp ├── 502. IPO.cpp ├── 725. Split Linked list in parts.cpp ├── 2785. Sort Vowels in a String.cpp ├── 3362. Zero Array Transformation III.cpp ├── 53. Maximum Subarray.cpp └── 494. Target Sum.cpp /ref.md: -------------------------------------------------------------------------------- 1 | ## [check here](https://leetcode.com/problems/subsets/description/comments/2253498/) 2 | -------------------------------------------------------------------------------- /231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if (n <= 0) return false; 5 | return (n & (n - 1)) == 0; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /89. Grey Code.cpp: -------------------------------------------------------------------------------- 1 | // Only 4 lines of codes # LOL :-) 2 | vector grayCode(int n) { 3 | vectorans(1<>1); 6 | return ans; 7 | } 8 | -------------------------------------------------------------------------------- /100. same Tree or Identical Tree.cpp: -------------------------------------------------------------------------------- 1 | bool isSameTree(TreeNode* p, TreeNode* q) { 2 | if(!p && !q)return true; 3 | if(p && q){ 4 | return ((p->val == q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right)); 5 | } 6 | return false; 7 | } 8 | -------------------------------------------------------------------------------- /48. Rotate image.cpp: -------------------------------------------------------------------------------- 1 | 2 | //function below 3 | int m = matrix.size(); 4 | int n = m; 5 | for(int i=0; ileft); 5 | int rightHeight = maxDepth(root->right); 6 | int ans = max(leftHeight,rightHeight) +1; 7 | return ans; 8 | } 9 | -------------------------------------------------------------------------------- /283. Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int j = 0; 5 | for(int i = 0; i < nums.size(); i++) { 6 | if(nums[i] != 0) nums[j++] = nums[i]; 7 | } 8 | while(j < nums.size()) nums[j++] = 0; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /2894. Divisible and Non-Divisible SumDifferences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int differenceOfSums(int n, int m) { 4 | int ans=0; 5 | for(int i=1;i<=n;i++){ 6 | if(i%m==0) ans-=i; 7 | else ans+=i; 8 | 9 | } 10 | return ans; 11 | } 12 | }; -------------------------------------------------------------------------------- /55. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int maxDist = 0; 5 | for(int i=0;imaxDist) return false; 7 | maxDist = std::max(maxDist,i+nums[i]); 8 | } 9 | return true; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /96. Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[20]{}; 4 | int numTrees(int n) { 5 | if(n <= 1) return 1; 6 | if(dp[n]) return dp[n]; 7 | for(int i = 1; i <= n; i++) 8 | dp[n] += numTrees(i-1) * numTrees(n-i); 9 | return dp[n]; 10 | } 11 | }; -------------------------------------------------------------------------------- /1323. Maximum 69 Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximum69Number (int num) { 4 | string s = to_string(num); 5 | for (char &c : s) { 6 | if (c == '6') { 7 | c = '9'; 8 | break; 9 | } 10 | } 11 | return stoi(s); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /1512. Number of Good Pairs.cpp: -------------------------------------------------------------------------------- 1 | // T.C - O(N) 2 | // S.C - O(N) 3 | 4 | class Solution { 5 | public: 6 | int numIdenticalPairs(vector& nums) { 7 | int ans =0; 8 | unordered_mapcount; 9 | for(int i: nums){ 10 | ans += count[i]++; 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /114. Flatten Binary Tree to Linked List.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | TreeNode* prev = NULL; 5 | void flatten(TreeNode* root) { 6 | if(!root) return; 7 | 8 | flatten(root->right); 9 | flatten(root->left); 10 | 11 | root->right = prev; 12 | root->left = NULL; 13 | prev = root; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /292.NimGame.cpp: -------------------------------------------------------------------------------- 1 | // Includes Soln to 292. Nim Game Problem 2 | // Using trial and error it can be found that you can win the game for any n less than 4 or if n is not divisible by 4 3 | // This code uses the simple observation to solve the problem 4 | 5 | 6 | class Solution { 7 | public: 8 | bool canWinNim(int n) { 9 | if (n<=3 || n%4!=0) return true; 10 | return false; 11 | } 12 | }; -------------------------------------------------------------------------------- /557. Reverse Words in a String III.cpp: -------------------------------------------------------------------------------- 1 | //T.C - O(n) 2 | //S.C - O(1) 3 | 4 | public: 5 | string reverseWords(string s) { 6 | int i=0; 7 | for(int j=0;j& nums) { 4 | if (nums.empty()) return 0; 5 | int j = 0; 6 | for (int i = 1; i < nums.size(); i++) { 7 | if (nums[i] != nums[j]) { 8 | j++; 9 | nums[j] = nums[i]; 10 | } 11 | } 12 | return j + 1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /101. Symetric Tree.cpp: -------------------------------------------------------------------------------- 1 | // quite Hard 2 | bool code(TreeNode*left, TreeNode*right){ 3 | if(!left && !right)return true; 4 | if((left && !right) || (!left && right) || (left->val != right->val))return false; 5 | return code(left->left,right->right) && code(left->right, right->left); 6 | } 7 | bool isSymmetric(TreeNode* root) { 8 | return code(root,root); 9 | 10 | 11 | } 12 | -------------------------------------------------------------------------------- /145. Binary tree PostOrder Traversal.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | void postorder(TreeNode* root,vector &ans){ 3 | if(root == NULL) return; 4 | postorder(root->left,ans); 5 | postorder(root->right,ans); 6 | ans.push_back(root->val); 7 | } 8 | vector postorderTraversal(TreeNode* root) { 9 | vectorans; 10 | postorder(root,ans); 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /2894. Divisible and Non-divisible Sums Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int differenceOfSums(int n, int m) { 4 | int num1 = 0, num2 = 0; 5 | for (int i = 1; i <= n; i++) { 6 | if (i % m == 0) 7 | num2 += i; // divisible by m 8 | else 9 | num1 += i; // not divisible by m 10 | } 11 | return num1 - num2; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /3487. Maximum Unique Subarray Sum After Deletion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSum(vector& nums) { 4 | unordered_set s; 5 | int temp = INT_MIN; 6 | for(int i: nums){ 7 | if(i>0) s.insert(i); 8 | else{ 9 | temp = max(temp,i); 10 | } 11 | } 12 | return s.empty()?temp:accumulate(s.begin(), s.end(), 0); 13 | } 14 | }; -------------------------------------------------------------------------------- /344. Reverse String.cpp: -------------------------------------------------------------------------------- 1 | // using vector 2 | class Solution { 3 | public: 4 | void reverseString(vector& s) { 5 | reverse(s.begin(),s.end()); 6 | } 7 | }; 8 | 9 | // using iteration 10 | class Solution { 11 | public: 12 | void reverseString(vector& s) { 13 | int l=0; 14 | int r = s.size()-1; 15 | while(l<=r){ 16 | swap(s[l++],s[r--]); 17 | } 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /144. Binary Tree PreOrder traversal.cpp: -------------------------------------------------------------------------------- 1 | void preorder(TreeNode* root,vector &list){ 2 | if(root == NULL){ 3 | return; 4 | } 5 | list.push_back(root->val); 6 | preorder(root->left,list); 7 | 8 | preorder(root->right,list); 9 | } 10 | vector preorderTraversal(TreeNode* root) { 11 | vectorlist; 12 | preorder(root,list); 13 | return list; 14 | } 15 | -------------------------------------------------------------------------------- /991. Broken Calculator.cpp: -------------------------------------------------------------------------------- 1 | // 991. Broken Calculator 2 | 3 | class Solution { 4 | public: 5 | int brokenCalc(int startValue, int target) { 6 | int res = 0; 7 | while(startValue < target){ 8 | if(target & 1){ 9 | ++target; 10 | ++res; 11 | } 12 | target >>= 1; 13 | ++res; 14 | } 15 | return res + startValue - target; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /3100. Water Bottles II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxBottlesDrunk(int numBottles, int numExchange) { 4 | int bottleDrunk = numBottles; 5 | int emptyBottles = numBottles; 6 | 7 | while (emptyBottles >= numExchange) { 8 | emptyBottles -= numExchange; 9 | numExchange++; 10 | bottleDrunk++; 11 | emptyBottles++; 12 | } 13 | return bottleDrunk; 14 | } 15 | }; -------------------------------------------------------------------------------- /78. Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | int n=nums.size(); 5 | int Mask=1<> powerSet(Mask); 7 | for (int m=0; m findWordsContaining(vector& words, char x) { 4 | vector ans; 5 | for(int i=0;i& nums) { 4 | int right = 0, left = 0, steps = 0; 5 | while(right>& dominoes) { 4 | unordered_map count; 5 | int res = 0; 6 | 7 | for (auto &d : dominoes) { 8 | int a = d[0], b = d[1]; 9 | int key = min(a, b) * 10 + max(a, b); 10 | 11 | res += count[key]; 12 | count[key]++; 13 | } 14 | 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /2210. count Hills and valleys in an Array.cpp: -------------------------------------------------------------------------------- 1 | //................................ 2 | int countHillValley(vector& nums) { 3 | int ans = 0; 4 | int left = nums[0]; 5 | 6 | for(int i=1; i nums[i+1] || //Hill 8 | left > nums[i] && nums[i] < nums[i+1]){ //valeys 9 | ans++; 10 | left = nums[i]; 11 | } 12 | return ans; 13 | } 14 | -------------------------------------------------------------------------------- /485. Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int max = 0; 5 | int count = 0; 6 | for(int i=0;i> merge(vector>& intervals) { 6 | vector> ans; 7 | 8 | ranges::sort(intervals); 9 | 10 | for (const vector& interval : intervals) 11 | if (ans.empty() || ans.back()[1] < interval[0]) 12 | ans.push_back(interval); 13 | else 14 | ans.back()[1] = max(ans.back()[1], interval[1]); 15 | 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /3461. Check If Digits Are Equal in String After Operations I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasSameDigits(string s) { 4 | while(s.length() > 2){ 5 | string temp = ""; 6 | for(int i = 0; i < s.length()-1; i++){ 7 | int a = s[i] - '0'; 8 | int b = s[i + 1] - '0'; 9 | temp.push_back(((a + b) % 10) + '0'); 10 | } 11 | s = temp; 12 | } 13 | return s.length() && s[0] == s[1]; 14 | } 15 | }; -------------------------------------------------------------------------------- /242. Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if(s.length() != t.length()) return false; 5 | 6 | int count[26] = {0}; 7 | 8 | for(int i = 0; i < s.length(); i++) { 9 | count[s[i]-'a']++; 10 | count[t[i]-'a']--; 11 | } 12 | 13 | for(int i = 0; i < 26; i++) { 14 | if(count[i] != 0) return false; 15 | } 16 | 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /896.Monotonic Array.cpp: -------------------------------------------------------------------------------- 1 | // T.C - O(n) 2 | // S.C - O(1) 3 | 4 | 5 | bool isMonotonic(vector& nums) { 6 | bool isIncreasing = true, isDecreasing = true; 7 | for (int i = 1; i < nums.size(); i++) { 8 | if (nums[i] < nums[i - 1]) { 9 | isIncreasing = false; 10 | } 11 | if (nums[i] > nums[i - 1]) { 12 | isDecreasing = false; 13 | } 14 | } 15 | 16 | // Return true if the array is increasing or decreasing 17 | return isIncreasing || isDecreasing; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /1046. Last Stone Weight.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lastStoneWeight(vector& stones) { 4 | sort(stones.begin(), stones.end()); 5 | while(stones.size() > 1){ 6 | int stone1 = stones[stones.size()-1], stone2 = stones[stones.size()-2]; 7 | stones.pop_back(); stones.pop_back(); 8 | if(stone1 != stone2) stones.push_back(stone1-stone2); 9 | sort(stones.begin(),stones.end()); 10 | } 11 | if(stones.size() == 0) return 0; 12 | return stones[0]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /2109. Adding Spaces to a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addSpaces(string s, vector& spaces) { 4 | int m = s.length(); 5 | int n = spaces.size(); 6 | 7 | string result = ""; 8 | 9 | int j = 0; //to traverse in spaces vector 10 | for(int i = 0; i < m; i++) { 11 | if(j < n && i == spaces[j]) { 12 | result += " "; 13 | j++; 14 | } 15 | 16 | result += s[i]; 17 | } 18 | 19 | return result; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /230. Kth Smallest Element.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | int kthSmallest(TreeNode* root, int &k) { // by reference pass krna pdega, track krney ke liye 5 | if(!root) return -1; 6 | // LNR Inorder Traversal 7 | int leftAns = kthSmallest(root->left,k); 8 | if(leftAns != -1){ 9 | return leftAns; 10 | } 11 | //N 12 | k--; 13 | if(k == 0 ){ 14 | return root->val; 15 | } 16 | //R 17 | int rightAns = kthSmallest(root->right,k); 18 | return rightAns; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /3147.Taking Maximum Energy From the Mystic Dungeon.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int maximumEnergy(vector& energy, int k) { 7 | int n = energy.size(); 8 | vector dp(n, 0); 9 | int ans = INT_MIN; 10 | 11 | for (int i = n - 1; i >= 0; i--) { 12 | dp[i] = energy[i]; 13 | if (i + k < n) 14 | dp[i] += dp[i + k]; 15 | ans = max(ans, dp[i]); 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /731. My Calender II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int n) { 4 | int dp[++n]; 5 | dp[0] = 0; 6 | sort(begin(coins), end(coins)); 7 | for (int i = 1; i < n; i++) 8 | { 9 | dp[i] = INT_MAX; 10 | for (int c: coins) 11 | { 12 | if (i - c < 0) break; 13 | if (dp[i - c] != INT_MAX) dp[i] = min(dp[i], 1 + dp[i - c]); 14 | } 15 | } 16 | return dp[--n] == INT_MAX ? -1 : dp[n]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /389. Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | So, here also let's say our character are: 2 | s = abc 3 | t = cabx 4 | 5 | if we take XOR of every character. all the n character of s "abc" is similar to n character of t "cab". So, they will cancel each other. 6 | And we left with our answer. 7 | 8 | s = abc 9 | t = cbax 10 | ------------ 11 | ans -> x 12 | 13 | char findTheDifference(string s, string t) { 14 | char c = 0; 15 | for(char cs : s) c^=cs; //Xoring all charecter to extract unique one 16 | for(char ct : t) c^=ct; 17 | return c; 18 | } 19 | -------------------------------------------------------------------------------- /83. Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | //Remove Duplicates from Sorted List 2 | 3 | //C++ Solution 4 | 5 | class Solution { 6 | public: 7 | ListNode* deleteDuplicates(ListNode* head) { 8 | //if(head == 0|| head->next == 0)return 0; 9 | ListNode*curr = head; 10 | while(curr&&curr->next){ 11 | if( curr->val == curr->next->val){ 12 | curr->next = curr->next->next; 13 | } 14 | else{ 15 | curr = curr->next; 16 | } 17 | } 18 | return head; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /951. Flip Equivalent Binary Trees.cpp: -------------------------------------------------------------------------------- 1 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 2 | if(root1 == NULL && root2 == NULL) 3 | return true; 4 | 5 | if(root1 == NULL || root2 == NULL) { 6 | return false; 7 | } 8 | 9 | if(root1 -> val == root2->val) { 10 | return flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right) || 11 | flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left); 12 | } 13 | 14 | return false; 15 | } 16 | -------------------------------------------------------------------------------- /852. peak Index in a Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | //__________________ Binary Search Question _______________________________ 2 | 3 | 4 | class Solution { 5 | public: 6 | int peakIndexInMountainArray(vector& arr) { 7 | int s = 0; 8 | int e = arr.size() - 1; 9 | // int mid = s+(e-s)/2; 10 | while(s> generate(int numRows) { 4 | vector> r(numRows); 5 | for(int i=0; i< numRows ; i++){ 6 | r[i].resize(i+1); 7 | r[i][0] = r[i][i] = 1; 8 | for(int j=1;j& nums) { 5 | int ans =0; 6 | //sort it 7 | sort(nums.begin(),nums.end()); 8 | for(int i=0; i deckRevealedIncreasing(vector& deck) { 4 | vectorres(deck.size(),0); 5 | sort(deck.begin(), deck.end()); 6 | int i = 0, j=0, k=0; 7 | while(j>>!!! make sure you have star ⭐ the repo " 17 | -------------------------------------------------------------------------------- /236. lowest Common Ancestor of A Binary tree.cpp: -------------------------------------------------------------------------------- 1 | //Same as Binary search tree 2 | 3 | if(!root)return NULL; 4 | 5 | //Base Case 6 | if(root->val == p->val)return p; 7 | if(root->val == q->val)return q; 8 | 9 | //Recursion 10 | TreeNode* leftans = lowestCommonAncestor(root->left,p,q); 11 | TreeNode* rightans = lowestCommonAncestor(root->right,p,q); 12 | 13 | if(!leftans && !rightans)return NULL; 14 | else if(!leftans && rightans)return rightans; 15 | else if(leftans && !rightans)return leftans; 16 | else{ 17 | return root; 18 | } 19 | -------------------------------------------------------------------------------- /904. Fruit Into Baskets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalFruit(vector& fruits) { 4 | int maxFruits=0; 5 | unordered_mapres; 6 | int left=0; 7 | for(int right=0;right2){ 10 | res[fruits[left]]--; 11 | 12 | if(res[fruits[left]]==0) res.erase(fruits[left]); 13 | left++; 14 | } 15 | maxFruits=max(maxFruits,right-left+1); 16 | 17 | } 18 | return maxFruits; 19 | } 20 | }; -------------------------------------------------------------------------------- /235. Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | // Same as Lca of a Binary tree 2 | if(!root)return NULL; 3 | 4 | //Base Case 5 | if(root->val == p->val)return p; 6 | if(root->val == q->val)return q; 7 | 8 | //Recursion 9 | TreeNode* leftans = lowestCommonAncestor(root->left,p,q); 10 | TreeNode* rightans = lowestCommonAncestor(root->right,p,q); 11 | 12 | if(!leftans && !rightans)return NULL; 13 | else if(!leftans && rightans)return rightans; 14 | else if(leftans && !rightans)return leftans; 15 | else{ 16 | return root; 17 | } 18 | -------------------------------------------------------------------------------- /70. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | if(n==0 || n ==1){ 5 | return 1; 6 | } 7 | // return climbStairs(n-1) + climbStairs(n-2); //recursive call it has T.C of - O(2^n) 8 | //which is bad approach 9 | //now we will try space optimization 10 | int prev =1,curr=1; 11 | for(int i= 2;i<=n;i++){ 12 | int temp = curr; 13 | curr = prev+curr; 14 | prev = temp; 15 | } 16 | return curr; 17 | 18 | } 19 | }; 20 | //fibonacci series problem but worst time complexity O(2^n) 21 | -------------------------------------------------------------------------------- /162. Find Peak Element.cpp: -------------------------------------------------------------------------------- 1 | //.........................Binary Search.......................................// 2 | //same as Leetcode 852. find peak Element 3 | int findPeakElement(vector& nums) { 4 | // This question is same as leetCode 852.peak index in a mountain array 5 | int left =0; 6 | int right = nums.size() - 1; 7 | while(left < right){ 8 | int mid = left+(right-left)/2; 9 | if(nums[mid] < nums[mid+1]){ 10 | left = mid+1; 11 | } 12 | else{ 13 | right = mid; 14 | } 15 | } 16 | return left; 17 | } 18 | -------------------------------------------------------------------------------- /3477. Fruits Into Baskets II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numOfUnplacedFruits(vector& fruits, vector& baskets) { 4 | int unplaced = 0; 5 | int n = fruits.size(); 6 | int m = baskets.size(); 7 | 8 | for (int i = 0; i < n; i++) { 9 | bool placed = false; 10 | for (int j = 0; j < m; j++) { 11 | if (baskets[j] >= fruits[i]) { 12 | baskets[j] = -1; 13 | placed = true; 14 | break; 15 | } 16 | } 17 | 18 | if (!placed) { 19 | unplaced++; 20 | } 21 | } 22 | 23 | return unplaced; 24 | } 25 | }; -------------------------------------------------------------------------------- /219.NearbyDuplicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool containsNearbyDuplicate(vector& nums, int k) { 8 | int n=nums.size(); 9 | unordered_map indexmap; 10 | 11 | for(int i=0;i 2) { 6 | // If n is not divisible by 3, it's not a power of three 7 | if (n % 3 != 0) { 8 | return false; 9 | } 10 | // Divide n by 3 to check the next level 11 | n /= 3; 12 | } 13 | 14 | // After the loop, n should be 1 if it was a power of three 15 | // (n could be 0, 1, or 2 at this point) 16 | // Powers of three: 3^0 = 1, 3^1 = 3, 3^2 = 9, etc. 17 | return n == 1; 18 | } 19 | }; -------------------------------------------------------------------------------- /543. Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | //T.C - 8ms 2 | int maxDepth(TreeNode* root) { 3 | if(!root)return 0; 4 | int leftHeight = maxDepth(root->left); 5 | int rightHeight = maxDepth(root->right); 6 | int ans = max(leftHeight,rightHeight) +1; 7 | return ans; 8 | } 9 | int diameterOfBinaryTree(TreeNode* root) { 10 | if(!root)return 0; 11 | int op1 = diameterOfBinaryTree(root->left); 12 | int op2 = diameterOfBinaryTree(root->right); 13 | int op3 = maxDepth(root->left)+maxDepth(root->right); 14 | 15 | int ans = max(op1, max(op2,op3)); 16 | return ans; 17 | } 18 | -------------------------------------------------------------------------------- /567. Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | if (s1.length() > s2.length()) return false; 5 | 6 | vector s1Count(26, 0), s2Count(26, 0); 7 | 8 | for (int i = 0; i < s1.length(); ++i) { 9 | s1Count[s1[i] - 'a']++; 10 | s2Count[s2[i] - 'a']++; 11 | } 12 | 13 | for (int i = 0; i < s2.length() - s1.length(); ++i) { 14 | if (s1Count == s2Count) return true; 15 | s2Count[s2[i] - 'a']--; 16 | s2Count[s2[i + s1.length()] - 'a']++; 17 | } 18 | 19 | return s1Count == s2Count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /3208.Alternating Groups II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfAlternatingGroups(vector& colors, int k) { 4 | int n = colors.size(); 5 | vector arr(2 * n); 6 | copy(colors.begin(), colors.end(), arr.begin()); 7 | copy(colors.begin(), colors.end(), arr.begin() + n); 8 | int l = 0, r = 1, flag = colors[0], count = 0; 9 | while (r < arr.size() && l < n) { 10 | if (arr[r] == flag) l = r; 11 | else flag = arr[r]; 12 | if ((r - l + 1) == k) { 13 | count++; 14 | l++; 15 | } 16 | r++; 17 | } 18 | return count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /322. Coin Change.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int coinChange(vector &coins, int n) 5 | { 6 | int dp[++n]; 7 | dp[0] = 0; 8 | sort(begin(coins), end(coins)); 9 | for (int i = 1; i < n; i++) 10 | { 11 | dp[i] = INT_MAX; 12 | for (int c : coins) 13 | { 14 | if (i - c < 0) 15 | break; 16 | if (dp[i - c] != INT_MAX) 17 | dp[i] = min(dp[i], 1 + dp[i - c]); 18 | } 19 | } 20 | return dp[--n] == INT_MAX ? -1 : dp[n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /763. Partition Labels.cpp: -------------------------------------------------------------------------------- 1 | vector partitionLabels(string s) { 2 | int n = s.length(); 3 | 4 | vectorresult; 5 | vectormp(26, -1); 6 | 7 | for(int i=0; i 2 | using namespace std; 3 | 4 | 5 | class Solution { 6 | public: 7 | int longestNiceSubarray(vector& nums) { 8 | int maxi = 1; 9 | for (int i = 0; i < nums.size() - maxi; i++) { 10 | int currLen = 1; 11 | int usedBits = nums[i]; 12 | for (int j = i + 1; j < nums.size(); j++) { 13 | if ((usedBits & nums[j]) == 0) { 14 | usedBits |= nums[j]; 15 | currLen++; 16 | } 17 | else break; 18 | } 19 | maxi = max(maxi, currLen); 20 | } 21 | return maxi; 22 | } 23 | }; -------------------------------------------------------------------------------- /11. Container With Most Water.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxArea(vector& height) { 9 | int maxWater = 0; 10 | int lp = 0, rp = (int)height.size() - 1; 11 | while (lp < rp) { 12 | int width = rp - lp; 13 | int ht = min(height[lp], height[rp]); 14 | int currWater = width * ht; 15 | maxWater = max(maxWater, currWater); 16 | 17 | // Move the pointer at the shorter line inward 18 | if (height[lp] < height[rp]) ++lp; 19 | else --rp; 20 | } 21 | return maxWater; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /867. Transpose Matrix.cpp: -------------------------------------------------------------------------------- 1 | //Followup qs. for interview 2 | 3 | ### What if the input is always a square matrix? 4 | #### Code- 5 | for(int i=0; i> transpose(vector>& matrix) { 14 | int m = matrix.size(); 15 | int n = matrix[0].size(); 16 | 17 | vector> result(n, vector(m)); //n x m - T.c S.C - O(1) 18 | 19 | for(int i=0; i& nums) { 7 | int n = nums.size(); 8 | int maxi = INT_MIN; 9 | int ltr = 1, rtl = 1; 10 | for(int i=0; i removeAnagrams(vector &words) 5 | { 6 | if (words.size() == 1) 7 | return {words[0]}; 8 | vector ans; 9 | ans.push_back(words[0]); 10 | for (int i = 1; i < words.size(); i++) 11 | { 12 | string tempcurr = words[i]; 13 | string prevtemp = words[i - 1]; 14 | sort(tempcurr.begin(), tempcurr.end()); 15 | sort(prevtemp.begin(), prevtemp.end()); 16 | if (tempcurr != prevtemp) 17 | { 18 | ans.push_back(words[i]); 19 | } 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /498. Diagonal Traverse.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDiagonalOrder(vector>& mat) { 4 | int n = mat.size(), m = mat[0].size(); 5 | vector res; 6 | res.reserve(n * m); 7 | for (int d = 0; d < n + m - 1; d++) { 8 | vector tmp; 9 | int r = d < m ? 0 : d - m + 1; 10 | int c = d < m ? d : m - 1; 11 | while (r < n && c >= 0) { 12 | tmp.push_back(mat[r][c]); 13 | r++; 14 | c--; 15 | } 16 | if (d % 2 == 0) reverse(tmp.begin(), tmp.end()); 17 | res.insert(res.end(), tmp.begin(), tmp.end()); 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /102. Binary Tree level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | 2 | vector> ans; 3 | queueq; 4 | if(root == NULL) 5 | return ans; 6 | //initially 7 | q.push(root); 8 | 9 | while(!q.empty()){ 10 | //a 11 | vectorlevel; 12 | int Size = q.size(); 13 | for(int i=0; ileft != NULL) 20 | q.push(temp->left); 21 | 22 | if(temp->right != NULL) 23 | q.push(temp->right); 24 | 25 | 26 | level.push_back(temp->val); 27 | 28 | } 29 | ans.push_back(level); 30 | } 31 | return ans; 32 | -------------------------------------------------------------------------------- /141. FloydCycle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Here i am giving only Two Pointer Approach 5 | 6 | bool hasCycle(ListNode *head) { 7 | if(!head || !head->next)return 0; 8 | ListNode *slow = head; 9 | ListNode *fast = head; 10 | while(slow != NULL && fast!= NULL){ 11 | fast = fast->next; //Time Complexity o(n) 12 | if(fast != NULL){ //Space Complexity o(1) 13 | fast = fast->next; 14 | } 15 | slow = slow->next; 16 | if(slow == fast){ 17 | return 1; 18 | } 19 | } 20 | return 0; 21 | 22 | } 23 | 24 | -------------------------------------------------------------------------------- /3355. Zero Array Transformation I.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isZeroArray(vector& nums, vector>& queries) { 7 | int n = nums.size(); 8 | vector diff(n + 1, 0); 9 | 10 | for(const auto& q : queries){ 11 | int l = q[0], r = q[1]; 12 | diff[l] += 1; 13 | if(r + 1 < n){ 14 | diff[r + 1] -= 1; 15 | } 16 | } 17 | 18 | int coverage = 0; 19 | for(int i = 0; i < n; ++i){ 20 | coverage += diff[i]; 21 | if(nums[i] > coverage){ 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /135. Candy.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int candy(vector& ratings) { 4 | int n = ratings.size(); 5 | vector count(n, 1); // Step 1: Initialize with 1 6 | 7 | // Step 2: Left to Right 8 | for (int i = 1; i < n; i++) { 9 | if (ratings[i] > ratings[i - 1]) { 10 | count[i] = count[i - 1] + 1; 11 | } 12 | } 13 | 14 | // Step 3: Right to Left 15 | for (int i = n - 2; i >= 0; i--) { 16 | if (ratings[i] > ratings[i + 1]) { 17 | count[i] = max(count[i], count[i + 1] + 1); 18 | } 19 | } 20 | 21 | // Step 4: Total candies 22 | return accumulate(count.begin(), count.end(), 0); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /2843. Count Symmetric Integers.cpp: -------------------------------------------------------------------------------- 1 | int countSymmetricIntegers(int low, int high) { 2 | //brute Force 3 | int count =0; 4 | for(int num=low; num<= high; num++){ 5 | string s = to_string(num); 6 | 7 | int l = s.length(); 8 | 9 | if(l%2 !=0){ 10 | continue; 11 | } 12 | int leftsum = 0; 13 | int rightsum=0; 14 | for(int i=0; i& nums) { 8 | vectorlsum(nums.size(),0); 9 | vectorrsum(nums.size(),0); 10 | for(int i=1; i=0; i--){ 14 | rsum[i] = rsum[i+1] +nums[i+1]; 15 | } 16 | for(int i=0; i& nums){ 24 | return prefixSumApproach(nums); 25 | } 26 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | **PR Title Format:** Problem no.Problem name.cpp 2 | 3 | 4 | ### Intuition 5 | 6 | 7 | 8 | 9 | ### Approach 10 | 11 | 12 | 13 | 14 | ## Code Solution (C++) 15 | 16 | ```cpp 17 | // Your code goes here 18 | 19 | ``` 20 | 21 | 22 | ## Related Issues 23 | 24 | 25 | 26 | 27 | **By submitting this PR, I confirm that:** 28 | - [ ] This is my original work not totally AI generated 29 | - [ ] I have tested the solution thoroughly on leetcode 30 | - [ ] I have maintained proper PR description format 31 | - [ ] This is a meaningful contribution, not spam -------------------------------------------------------------------------------- /DutchflagAlgo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void printarray(int arr[], int n){ 4 | for(int i =0;i fullBloomFlowers(vector>& flowers, vector& people) { 6 | vector start, end; 7 | for (auto& t : flowers) 8 | start.push_back(t[0]), end.push_back(t[1]); 9 | sort(start.begin(), start.end()); 10 | sort(end.begin(), end.end()); 11 | vector res; 12 | for (int t : people) { 13 | int started = upper_bound(start.begin(), start.end(), t) - start.begin(); 14 | int ended = lower_bound(end.begin(), end.end(), t) - end.begin(); 15 | res.push_back(started - ended); 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /155. Min Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | vector> st; //we have make a vector 4 | MinStack() { 5 | 6 | } 7 | 8 | void push(int val) { 9 | if(st.empty()){ 10 | pairp;// = make_pair(val,val); 11 | p.first = val; 12 | p.second = val; 13 | st.push_back(p); 14 | } 15 | else{ 16 | pairp; 17 | p.first = val; 18 | p.second = min(val, st.back().second); 19 | st.push_back(p); 20 | } 21 | } 22 | 23 | void pop() { 24 | st.pop_back(); 25 | } 26 | 27 | int top() { 28 | return st.back().first; 29 | } 30 | 31 | int getMin() { 32 | return st.back().second; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /2181. Merge Nodes between two Zeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* mergeNodes(ListNode* head) { 4 | if(!head)return 0; 5 | ListNode*slow = head, *fast=head->next,*NewLastNode =0; 6 | int sum =0; 7 | while(fast){ 8 | if(fast->val != 0){ 9 | //increment sum 10 | sum += fast->val; 11 | } 12 | else{ 13 | slow->val = sum; 14 | NewLastNode = slow; 15 | slow = slow->next; 16 | sum =0; 17 | } 18 | fast = fast->next; 19 | } 20 | ListNode* temp = slow; 21 | //just formed new List 22 | NewLastNode->next = 0; 23 | while(!temp){ 24 | ListNode*nxt = temp->next; 25 | delete temp; 26 | temp = nxt; 27 | } 28 | return head; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /2327. Number of People Aware of a Secret.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peopleAwareOfSecret(int n, int delay, int forget) { 4 | const long long MOD = 1000000007LL; 5 | if (n == 1) return 1; 6 | vector dp(n+1); 7 | dp[1] = 1; 8 | long long window = 0; 9 | for (int i = 2; i <= n; ++i) { 10 | int enter = i - delay; 11 | int exit = i - forget; 12 | if (enter >= 1) window = (window + dp[enter]) % MOD; 13 | if (exit >= 1) window = (window - dp[exit] + MOD) % MOD; 14 | dp[i] = window; 15 | } 16 | long long ans = 0; 17 | int start = max(1, n - forget + 1); 18 | for (int i = start; i <= n; ++i) ans = (ans + dp[i]) % MOD; 19 | return (int)ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /32. Longest Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | //simple c++ approach 2 | //T.C- O(n) 3 | //Stack class 3 4 | //HARD question 5 | 6 | class Solution { 7 | public: 8 | int longestValidParentheses(string s) { 9 | stackst; 10 | st.push(-1); 11 | int maxlen =0; 12 | for(int i=0;i> restoreMatrix(vector& rowSum, vector& colSum) { 4 | int m = rowSum.size(); 5 | int n = colSum.size(); 6 | 7 | vector> vec(m, vector(n,0)); 8 | int i=0; 9 | int j=0; 10 | 11 | while(i> insert(vector>& intervals, vector& newInterval) { 6 | intervals.emplace_back(newInterval); 7 | return merge(intervals); 8 | } 9 | 10 | vector> merge(vector>& intervals) { 11 | sort(intervals.begin(), intervals.end()); 12 | vector> ans; 13 | ans.emplace_back(intervals[0]); 14 | 15 | for (int i = 1; i < intervals.size(); ++i) { 16 | if (ans.back()[1] < intervals[i][0]) { 17 | ans.emplace_back(intervals[i]); 18 | } else { 19 | ans.back()[1] = max(ans.back()[1], intervals[i][1]); 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /191. Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int count =0; 5 | 6 | //****Approach 1**** 7 | // while( n!= 0){ 8 | // count += (n%2); // Remainder Count... easy Binary count 9 | // n >>=1; 10 | // } 11 | // return count; 12 | 13 | //*****Approach 2***** 14 | // while(n>0){ 15 | // n = (n&(n-1)); // Bit Manipulation 16 | // count++; 17 | // } 18 | // return count; 19 | 20 | //*****Approach 3***** 21 | while(n !=0){ 22 | count += (n%2); //Remainder Count... easy Binary count 23 | n = n/2; 24 | } 25 | return count; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /3705. Longest substring without repeating characters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | int lengthOfLongestSubstring(std::string s) { 8 | int n = s.size(); 9 | if (n == 0) { 10 | return 0; 11 | } 12 | std::unordered_set char_set; 13 | int left = 0; 14 | int maxLength = 0; 15 | for (int right = 0; right < n; ++right) { 16 | char current_char = s[right]; 17 | while (char_set.count(current_char)) { 18 | char_set.erase(s[left]); 19 | left++; 20 | } 21 | char_set.insert(current_char); 22 | maxLength = std::max(maxLength, right - left + 1); 23 | } 24 | 25 | return maxLength; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Contributors are most welcome 2 | #### Here is the answers of **LeetCode questions** that i have done in my carrier through learning **DSA** 3 | 4 | # Leetcode sjx_subham 5 | 6 | ###### pure C++ 7 |
8 |
9 |
My Leetcode Info 10 |

11 |

17 |
18 |
19 | 20 | -------------------------------------------------------------------------------- /880. Decoded String at Index.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Time Complexcity - O(n) 3 | 4 | string decodeAtIndex(string s, int k) { 5 | 6 | long long length = 0; 7 | int i = 0; 8 | 9 | while (length < k) { 10 | if (isdigit(s[i])) { 11 | length *= s[i] - '0'; 12 | } else { 13 | length++; 14 | } 15 | i++; 16 | } 17 | 18 | for (int j = i - 1; j >= 0; j--) { 19 | if (isdigit(s[j])) { 20 | length /= s[j] - '0'; 21 | k %= length; 22 | } else { 23 | if (k == 0 || k == length) { 24 | return string(1, s[j]); // Convert char to std::string 25 | } 26 | length--; 27 | } 28 | } 29 | 30 | return s; 31 | } 32 | -------------------------------------------------------------------------------- /653. Two Sum IV - Input is a BST.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | // T.C - O(n) 4 | 5 | void storeInorder(TreeNode* root,vector &inorder){ 6 | if(!root) return; 7 | //LNR 8 | storeInorder(root->left,inorder); 9 | 10 | // N 11 | inorder.push_back(root->val); 12 | 13 | //R 14 | storeInorder(root->right, inorder); 15 | } 16 | bool findTarget(TreeNode* root, int k) { 17 | vectorinorder; 18 | storeInorder(root,inorder); 19 | 20 | int start =0; 21 | int end = inorder.size()-1; 22 | 23 | while( start < end){ 24 | int sum = inorder[start] + inorder[end]; 25 | 26 | if(sum ==k){ 27 | return true; 28 | } 29 | else if(sum > k){ 30 | end--; 31 | } 32 | else if(sum < k){ 33 | start++; 34 | } 35 | } 36 | return false; 37 | } 38 | -------------------------------------------------------------------------------- /61. Rotate List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getLength(ListNode*head){ 4 | int len =0; 5 | while(head){ 6 | ++len; 7 | head= head->next; 8 | } 9 | return len; 10 | } 11 | ListNode* rotateRight(ListNode* head, int k) { 12 | if(!head)return 0; 13 | int len = getLength(head); 14 | int actualRotateK = (k% len); 15 | if(actualRotateK == 0)return head; 16 | int newLastNodepos = len - actualRotateK - 1; 17 | ListNode* newLastNode = head; 18 | for(int i=0;inext; 20 | } 21 | ListNode*newHead = newLastNode->next; 22 | newLastNode->next = 0; 23 | ListNode*it = newHead; 24 | while(it->next){ 25 | it= it->next; 26 | } 27 | it->next = head; 28 | return newHead; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /35. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | Binary search Algorithm 6 | */ 7 | int searchInsert(vector& nums, int target) { 8 | int left = 0; 9 | int right = nums.size()-1; //length is used to extarct the amx size of array 10 | while(left <= right){ 11 | int mid = left +(right - left)/2; 12 | if( nums[mid] == target){ 13 | return mid; 14 | } 15 | else if(nums[mid] > target){ 16 | right = mid -1; 17 | } 18 | else{ 19 | left = mid+1; 20 | } 21 | } 22 | return left; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /123. Best time to buy or sell stock iii .cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& a) { 4 | int n = a.size(); 5 | vector>> dp(n+1, vector>(2, vector(3, 0))); 6 | for(int i=n-1;i>=0;i--) 7 | { 8 | for(int buy=1;buy>=0;buy--) 9 | { 10 | for(int cap=1;cap<=2;cap++) 11 | { 12 | if (buy) { 13 | // Either buy now, or skip 14 | dp[i][buy][cap] = max(-a[i] + dp[i+1][0][cap],dp[i+1][1][cap]); 15 | } else { 16 | // Either sell now, or skip 17 | dp[i][buy][cap] = max(a[i] +dp[i+1][1][cap-1], dp[i+1][0][cap]); 18 | } 19 | } 20 | } 21 | } 22 | return dp[0][1][2]; 23 | } 24 | }; -------------------------------------------------------------------------------- /34. Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. 3 | 4 | If target is not found in the array, return [-1, -1]. 5 | 6 | You must write an algorithm with O(log n) runtime complexity. 7 | */ 8 | vector searchRange(vector&nums , int target){ 9 | //most optimised solution 10 | //Two pointer approach 11 | int left =0; 12 | int right = nums.size()-1; 13 | while(left <= right){ 14 | if(nums[left] < target){ 15 | left++; 16 | } 17 | else if(nums[right] > target){ 18 | right--; 19 | } 20 | else if(nums[left] == nums[right]){ 21 | return {left,right}; 22 | } 23 | } 24 | 25 | return {-1,-1}; 26 | } 27 | -------------------------------------------------------------------------------- /225.Implement Stack Using Queues.cpp: -------------------------------------------------------------------------------- 1 | //T.C = o(n) 2 | // S.C = o(1) 3 | class MyStack { 4 | public: 5 | queueq; 6 | MyStack() { 7 | 8 | } 9 | 10 | void push(int x) { 11 | q.push(x); 12 | for(int i=0;ipush(x); 38 | * int param_2 = obj->pop(); 39 | * int param_3 = obj->top(); 40 | * bool param_4 = obj->empty(); 41 | */ 42 | -------------------------------------------------------------------------------- /2785.Sort Vowels in a String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | bool isVowel(char c) { 7 | return c == 'a' || c == 'e' || c == 'o'|| c == 'u'|| c == 'i' 8 | || c == 'A' || c == 'E' || c == 'O'|| c == 'U'|| c == 'I'; 9 | } 10 | 11 | string sortVowels(string s) { 12 | unordered_map mp; 13 | for (char c : s) { 14 | if (isVowel(c)) { 15 | mp[c]++; 16 | } 17 | } 18 | string total_vow = "AEIOUaeiou", ans; 19 | int j = 0; 20 | for (int i = 0; i < s.size(); i++) { 21 | if (!isVowel(s[i])) ans += s[i]; 22 | else { 23 | while(mp[total_vow[j]] == 0) j++; 24 | ans += total_vow[j]; 25 | mp[total_vow[j]]--; 26 | } 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /134. Gas Station.cpp: -------------------------------------------------------------------------------- 1 | //T.C - o(n) 2 | //S.C - o(1) 3 | 4 | class Solution { 5 | public: 6 | int canCompleteCircuit(vector& gas, vector& cost) { 7 | //petrol ki kitni kami hai yani Ghat ti 8 | int deficit =0; 9 | //petrol kitna bacha hua hai 10 | int balance =0; 11 | ///circuit kha se suru kre 12 | int start =0; 13 | for(int i =0;i=0){ // or if(balance >= deficit) 22 | return start; 23 | } 24 | else{ 25 | return -1; 26 | } 27 | } 28 | }; 29 | 30 | 31 | -------------------------------------------------------------------------------- /342. Power of Four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | // Check three conditions: 5 | // 1. n > 0: Power of 4 must be positive 6 | // 2. (n & (n - 1)) == 0: Check if n is a power of 2 7 | // - Powers of 2 have only one bit set in binary representation 8 | // - Subtracting 1 flips all bits after the single set bit 9 | // - AND operation results in 0 for powers of 2 10 | // 3. (n & 0xAAAAAAAA) == 0: Ensure the single bit is at an even position 11 | // - 0xAAAAAAAA = 10101010101010101010101010101010 in binary 12 | // - This mask has bits set at odd positions (0-indexed) 13 | // - Powers of 4 have their single bit at even positions (bit 0, 2, 4, 6...) 14 | // - AND with this mask should be 0 for powers of 4 15 | return n > 0 && (n & (n - 1)) == 0 && (n & 0xAAAAAAAA) == 0; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /110. Blanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | int height(TreeNode* root){ 2 | if(!root)return 0; 3 | // int leftheight = height(root->left); 4 | // int rightheight = height(root->right); 5 | int ans = 1+ max(height(root->left),height(root->right)); 6 | return ans; 7 | } 8 | bool isBalanced(TreeNode* root) { 9 | if(!root)return true; 10 | //1 case 11 | // int leftHeight = height(root->left); 12 | // int rightHeight = height(root->right); 13 | int diff = abs(height(root->left)-height(root->right)); 14 | 15 | //bool ans = (diff <=1); 16 | 17 | //Recursion 18 | // int leftans = isBalanced(root->left); 19 | // int rightans = isBalanced(root->right); 20 | 21 | if((diff <=1) && isBalanced(root->left) && isBalanced(root->right)){ 22 | return true; 23 | } 24 | else{ 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /1019. Next Greater Node in Linked List.cpp: -------------------------------------------------------------------------------- 1 | //C++ solution 2 | //T.C - 0(n) 81ms 3 | //S.C - o(n) 41.9mb 4 | class Solution { 5 | public: 6 | vector nextLargerNodes(ListNode* head) { 7 | vectorll; 8 | while(head){ 9 | ll.push_back(head->val); 10 | head = head->next; 11 | } 12 | stackst; 13 | // vectorans(ll.size()); // init 0 14 | for(int i =0;i ll[st.top()]){ 16 | // i th element is greater than ith element of previous index element 17 | int kids = st.top(); 18 | st.pop(); 19 | ll[kids] = ll[i]; 20 | } 21 | st.push(i); 22 | } 23 | while(!st.empty()){ 24 | ll[st.top()]= 0; 25 | st.pop(); 26 | } 27 | ll[ll.size()-1] = 0; 28 | return ll; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /73. Set Matrix Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | bool zeroinFirstCol = false; 5 | for (int row = 0; row < matrix.size(); row++) { 6 | if (matrix[row][0] == 0) zeroinFirstCol = true; 7 | for (int col = 1; col < matrix[0].size(); col++) { 8 | if (matrix[row][col] == 0) { 9 | matrix[row][0] = 0; 10 | matrix[0][col] = 0; 11 | } 12 | } 13 | } 14 | 15 | for (int row = matrix.size() - 1; row >= 0; row--) { 16 | for (int col = matrix[0].size() - 1; col >= 1; col--) { 17 | if (matrix[row][0] == 0 || matrix[0][col] == 0) { 18 | matrix[row][col] = 0; 19 | } 20 | } 21 | if (zeroinFirstCol) { 22 | matrix[row][0] = 0; 23 | } 24 | } 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | # github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | # patreon: # Replace with a single Patreon username 5 | # open_collective: # Replace with a single Open Collective username 6 | # ko_fi: # Replace with a single Ko-fi username 7 | # tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | # community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | # liberapay: # Replace with a single Liberapay username 10 | # issuehunt: # Replace with a single IssueHunt username 11 | # lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | # polar: # Replace with a single Polar username 13 | buy_me_a_coffee: SjxSubham 14 | # thanks_dev: # Replace with a single thanks.dev username 15 | # custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 16 | -------------------------------------------------------------------------------- /338.Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | /*Explanation 2 | 1. we are iterating till n; 3 | for every i, we have to count 1's bits in its binary form. 4 | 0 --> 0 5 | 1 --> 1 6 | 2 --> 10 7 | 3 --> 11 8 | 4 --> 100 9 | 5 --> 101 10 | 11 | Output: [0,1,1,2,1,2] 12 | */ 13 | class Solution { 14 | public: 15 | // T.C - o(nlog n) 16 | vector countBits(int n) { 17 | vectorans; 18 | //loop ko 0 se n tak chalayenge 19 | for(int i=0;i<=n;i++){ 20 | // sum is initialized as zero 21 | int sum =0; 22 | int num =i; 23 | //while num not equals zero 24 | while(num != 0){ 25 | //we have to count '1' s in binary representation of i, there fore % 2 26 | sum += num%2; 27 | num = num/2; 28 | } 29 | //add sum to ans vector 30 | ans.push_back(sum); 31 | } 32 | //return 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /514. Freedom Trail.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int n; 4 | string ring,key; 5 | vector> memo; 6 | array,26> pos; 7 | 8 | int dfs(int cur,int kidx) { 9 | if (kidx==(int)key.size()) return 0; 10 | int &res=memo[cur][kidx]; 11 | if (res != -1) return res; 12 | res=INT_MAX/4; 13 | int ch=key[kidx]-'a'; 14 | for (int p : pos[ch]) { 15 | int diff=abs(cur-p); 16 | int dist=min(diff,n-diff); 17 | int sub=dfs(p,kidx+1); 18 | res=min(res,dist+1+sub); 19 | } 20 | return res; 21 | } 22 | 23 | int findRotateSteps(string ring_,string key_) { 24 | ring=ring_; 25 | key=key_; 26 | n=ring.size(); 27 | memo.assign(n,vector(key.size(),-1)); 28 | for (int i=0; i<26; ++i) pos[i].clear(); 29 | for (int i=0; i map2(27, 0), map1(27, 0); 8 | for (int i = 0; i < word2.size(); i++) { 9 | map2[word2[i] - 'a']++; 10 | } 11 | while (r < word1.size()) { 12 | map1[word1[r] - 'a']++; 13 | if (map1[word1[r] - 'a'] == map2[word1[r] - 'a']) 14 | count += map2[word1[r] - 'a']; 15 | while (count == word2.size()) { 16 | ans += (word1.size() - r); 17 | map1[word1[l] - 'a']--; 18 | if (map1[word1[l] - 'a'] < map2[word1[l] - 'a']) 19 | count -= map2[word1[l] - 'a']; 20 | l++; 21 | } 22 | r++; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long validSubstringCount(string word1, string word2) { 4 | int count = 0; 5 | long long ans = 0; 6 | int l = 0, r = 0; 7 | vector map2(27, 0), map1(27, 0); 8 | for (int i = 0; i < word2.size(); i++) { 9 | map2[word2[i] - 'a']++; 10 | } 11 | while (r < word1.size()) { 12 | map1[word1[r] - 'a']++; 13 | if (map1[word1[r] - 'a'] == map2[word1[r] - 'a']) 14 | count += map2[word1[r] - 'a']; 15 | while (count == word2.size()) { 16 | ans += (word1.size() - r); 17 | map1[word1[l] - 'a']--; 18 | if (map1[word1[l] - 'a'] < map2[word1[l] - 'a']) 19 | count -= map2[word1[l] - 'a']; 20 | l++; 21 | } 22 | r++; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /98. Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | // T. c - O(n) 5 | // n times reverse kar rahe hai, isliye 6 | 7 | bool solve(TreeNode* root,long long int lowerBound,long long int upperBound){ 8 | if(root == NULL){ 9 | return true; 10 | } 11 | bool cond1 = (root->val > lowerBound); 12 | bool cond2= (root->val < upperBound); 13 | bool leftAns = solve(root->left, lowerBound,root->val); 14 | bool rightAns = solve(root->right,root->val,upperBound); 15 | 16 | if( cond1 && cond2 && leftAns && rightAns) 17 | return true; 18 | else 19 | return false; 20 | } 21 | bool isValidBST(TreeNode* root) { 22 | 23 | long long int lowerBound = -2147483657; // we have to increase the limit 24 | long long int upperBound = 2147483657; // we have to increase the limit 25 | bool ans = solve(root,lowerBound,upperBound); 26 | return ans; 27 | 28 | }; 29 | -------------------------------------------------------------------------------- /23. Merge k Sorted Lists.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* mergeKLists(vector& lists) { 14 | ListNode* res = new ListNode(0); 15 | ListNode* temp = res; 16 | 17 | priority_queue, greater> minHeap; 18 | 19 | for (auto l : lists) { 20 | while (l != nullptr) { 21 | minHeap.push(l->val); 22 | l = l->next; 23 | } 24 | } 25 | 26 | while (!minHeap.empty()) { 27 | int num = minHeap.top(); 28 | minHeap.pop(); 29 | 30 | temp->next = new ListNode(num); 31 | temp = temp->next; 32 | } 33 | 34 | return res->next; 35 | } 36 | }; -------------------------------------------------------------------------------- /.github/workflows/pr-merged-automate-message.yml: -------------------------------------------------------------------------------- 1 | name: Auto Comment on PR Merged 2 | 3 | on: 4 | pull_request_target: 5 | types: [closed] 6 | 7 | permissions: 8 | pull-requests: write 9 | 10 | jobs: 11 | comment: 12 | if: github.event.pull_request.merged == true 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Add Comment to Merged Pull Request 16 | uses: actions/github-script@v6 17 | with: 18 | script: | 19 | const prNumber = context.issue.number; 20 | const prAuthor = context.payload.pull_request.user.login; 21 | const commentBody = `### 🎉 Congrats on getting your PR merged in, @${prAuthor}! 🙌🏼\n\nThanks for your contribution every effort helps improve the project.\n\nLooking forward to seeing more from you! 🥳✨`; 22 | 23 | await github.rest.issues.createComment({ 24 | owner: context.repo.owner, 25 | repo: context.repo.repo, 26 | issue_number: prNumber, 27 | body: commentBody 28 | }); 29 | -------------------------------------------------------------------------------- /17. Letter Combinations of a Phone Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector ans; 4 | 5 | map mp; 6 | void help(string digits,int id,string& str) 7 | { 8 | if(id>digits.size()) return; 9 | if(id>=digits.size()) 10 | { ans.push_back(str); 11 | return; 12 | } 13 | 14 | string st=mp[digits[id]]; 15 | for(int i=0;i letterCombinations(string digits) { 24 | if(digits.size()==0) return {}; 25 | 26 | mp['2']="abc"; 27 | mp['3']="def"; 28 | mp['4']="ghi"; 29 | mp['5']="jkl"; 30 | mp['6']="mno"; 31 | mp['7']="pqrs"; 32 | mp['8']="tuv"; 33 | mp['9']="wxyz"; 34 | string str; 35 | help(digits,0,str); 36 | return ans; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /8. String to Integer (atoi).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(string s) { 4 | int l = s.length(); 5 | int sign = 1, i = 0; 6 | long long ans = 0; 7 | 8 | // trimming leading spaces 9 | while (i < l && s[i] == ' ') i++; 10 | 11 | 12 | // sign check condition 13 | if (i == l) 14 | return 0; 15 | if (s[i] == '-') { 16 | sign = -1; 17 | i++; 18 | } else if (s[i] == '+') 19 | i++; 20 | 21 | // converting characters to integer 22 | while (i < l && isdigit(s[i])) { 23 | int digit = s[i] - '0'; 24 | ans = ans * 10 + digit; 25 | 26 | // overflow condition handling 27 | if (sign == 1 && ans > INT_MAX) { 28 | return INT_MAX; 29 | } 30 | if (sign == -1 && (-1 * ans) < INT_MIN) { 31 | return INT_MIN; 32 | } 33 | i++; 34 | } 35 | 36 | return (int)(ans * sign); 37 | } 38 | }; -------------------------------------------------------------------------------- /2561. Rearranging Fruits.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public: 5 | long long minCost(vector& basket1, vector& basket2) { 6 | unordered_map freq; 7 | for (int x : basket1) freq[x]++; 8 | for (int x : basket2) freq[x]--; 9 | 10 | vector extra1, extra2; 11 | int minFruit = INT_MAX; 12 | 13 | // Collect unbalanced fruits 14 | for (auto [fruit, diff] : freq) { 15 | minFruit = min(minFruit, fruit); 16 | if (diff % 2 != 0) return -1; // impossible to balance 17 | int count = abs(diff) / 2; 18 | if (diff > 0) while (count--) extra1.push_back(fruit); 19 | else while (count--) extra2.push_back(fruit); 20 | } 21 | 22 | sort(extra1.begin(), extra1.end()); 23 | sort(extra2.rbegin(), extra2.rend()); 24 | 25 | long long cost = 0; 26 | for (int i = 0; i < extra1.size(); ++i) { 27 | cost += min((long long)min(extra1[i], extra2[i]), 2LL * minFruit); 28 | } 29 | return cost; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /199. Binary Tree Right Side View.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 rightSideView(TreeNode* root) { 15 | // unordered_mapmap; 16 | vectorans; 17 | int level=-1; 18 | traverseRightSide(root,level,0,ans); 19 | return ans; 20 | } 21 | void traverseRightSide(TreeNode* root,int &mainLevel,int level, vector&ans){ 22 | if(root==NULL) return ; 23 | 24 | if(mainLevelval); 26 | mainLevel=max(mainLevel,level); 27 | } 28 | 29 | traverseRightSide(root->right,mainLevel,level+1,ans); 30 | traverseRightSide(root->left,mainLevel,level+1,ans); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /113. Path Sum 2.cpp: -------------------------------------------------------------------------------- 1 | void solve(TreeNode* root,int targetSum,int &currsum,vector&path, vector>&ans){ 2 | if(root == NULL){ 3 | return; 4 | } 5 | //leaf node 6 | if(root->left == NULL && root->right == NULL){ 7 | path.push_back(root->val); 8 | currsum += root->val; 9 | if(currsum == targetSum){ 10 | ans.push_back(path); 11 | } 12 | //exceptional 13 | path.pop_back(); 14 | currsum -= root->val; 15 | return; 16 | } 17 | //include curr node 18 | path.push_back(root->val); 19 | currsum += root->val; 20 | 21 | solve(root->left,targetSum,currsum,path,ans); 22 | solve(root->right,targetSum,currsum,path,ans); 23 | 24 | //exceptional backtrack, aslo can be done without this 25 | path.pop_back(); 26 | currsum -= root->val; 27 | 28 | } 29 | vector> pathSum(TreeNode* root, int targetSum) { 30 | vector>ans; 31 | int sum =0; 32 | vectorpath; 33 | solve(root,targetSum, sum ,path,ans); 34 | return ans; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /1094.Car Pooling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool carPooling(vector>& trips, int capacity) { 4 | vector> pickups; 5 | priority_queue, vector>, greater>> drops; 6 | pickups.reserve(trips.size()); 7 | for (auto &t : trips){ 8 | pickups.emplace_back(t[1], t[0]); 9 | drops.push({t[2], t[0]}); 10 | } 11 | sort(pickups.begin(), pickups.end()); 12 | int i = 0, curr = 0; 13 | while (!drops.empty()){ 14 | int nextDrop = drops.top().first; 15 | while (i < (int)pickups.size() && pickups[i].first < nextDrop){ 16 | curr += pickups[i].second; 17 | if (curr > capacity) return false; 18 | ++i; 19 | } 20 | curr -= drops.top().second; 21 | drops.pop(); 22 | } 23 | while (i < (int)pickups.size()){ 24 | curr += pickups[i].second; 25 | if (curr > capacity) return false; 26 | ++i; 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /1716. Calculate Money in Leetcode bank.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | class Solution { 6 | public: 7 | 8 | // Approach 1 9 | //T.c - O(n) 10 | 11 | int totalMoney(int n) { 12 | int total = 0; 13 | int monday =1; 14 | while(n>0){ 15 | int money = monday; 16 | for(int day=1; day<=min(n,7); day++){ 17 | total += money; //1 18 | money++; //2,3 19 | } 20 | n -= 7; 21 | monday++; 22 | } 23 | return total; 24 | 25 | // Approach 2 26 | // T.C - O(1) 27 | //math Approach A.P series 28 | int terms = n/7; 29 | int first = 28; 30 | int last = 28 +(terms -1)*7; // A.P formula 31 | int result = terms *(first + last)/2; // sum of nth term in A.P 32 | 33 | //first week remaining days 34 | int start_money = 1+ terms; 35 | for( int day = 1; day <=(n%7); day++){ 36 | result += start_money; 37 | start_money++; 38 | } 39 | return result; 40 | } 41 | } 42 | 43 | return result; 44 | 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 SjxSubham 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /3024.Type of Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* APPROACH 2 | The solution involves two key steps: triangle validity checking and triangle classification. First, verify if the three sides can form a valid triangle using the triangle inequality theorem, then classify the triangle type based on side equality patterns 3 | 4 | Intuition 5 | For three sides to form a valid triangle, they must satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side. This gives us three conditions to check: a + b > c, b + c > a, and c + a > b 6 | */ 7 | class Solution { 8 | public: 9 | string triangleType(vector& nums) { 10 | int a = nums[0], b = nums[1], c = nums[2]; 11 | 12 | // Check triangle inequality theorem 13 | if (a + b <= c || b + c <= a || c + a <= b) { 14 | return "none"; 15 | } 16 | 17 | // Check triangle type based on side equality 18 | if (a == b && b == c) { 19 | return "equilateral"; 20 | } else if (a == b || b == c || a == c) { 21 | return "isosceles"; 22 | } else { 23 | return "scalene"; 24 | } 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /2583. Kth Largest Sum in a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long kthLargestLevelSum(TreeNode* root, int k) { 4 | deque levelQ; 5 | priority_queue, greater> minSumQ; 6 | levelQ.push_back(root); 7 | 8 | while (!levelQ.empty()) { 9 | long long currLvlSum = 0; 10 | int lvlSize = levelQ.size(); 11 | while (lvlSize-- > 0) { 12 | TreeNode* currNode = levelQ.front(); 13 | levelQ.pop_front(); 14 | 15 | if (currNode->left != nullptr) { 16 | levelQ.push_back(currNode->left); 17 | } 18 | if (currNode->right != nullptr) { 19 | levelQ.push_back(currNode->right); 20 | } 21 | currLvlSum += currNode->val; 22 | } 23 | 24 | minSumQ.push(currLvlSum); 25 | if (minSumQ.size() > k) { 26 | minSumQ.pop(); 27 | } 28 | } 29 | 30 | return (minSumQ.size() == k) ? minSumQ.top() : -1; 31 | 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /20. Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack stk; 5 | for (char chr : s) { 6 | if (chr == '(' || chr == '[' || chr == '{') { //open bracket being pushed to the stack if found 7 | stk.push(chr); 8 | } 9 | else { 10 | 11 | //checking for empty stack before popping or comparison 12 | if (stk.empty()) { 13 | return false; 14 | } 15 | 16 | //getting most recent open bracket and popping for the comparison 17 | char top = stk.top(); 18 | stk.pop(); 19 | 20 | // Verify the closing bracket 'chr' matches the popped open bracket 'top'... 21 | if (chr == ')' && top != '(') { 22 | return false; 23 | } 24 | if (chr == ']' && top != '[') { 25 | return false; 26 | } 27 | if (chr == '}' && top != '{') { 28 | return false; 29 | } 30 | } 31 | } 32 | return stk.empty(); 33 | } 34 | }; -------------------------------------------------------------------------------- /4. Median of Two Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////// 2 | 3 | optimized Solution 4 | if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1); 5 | int n1 = nums1.size(); 6 | int n2 = nums2.size(); 7 | int low = 0, high = n1; 8 | while(low <= high){ 9 | int cut1 = (low + high) >> 1; 10 | int cut2 = (n1+n2+1)/2 - cut1; 11 | 12 | int left1 = cut1 ==0 ? INT_MIN : nums1[cut1-1]; //to much tough 13 | int left2 = cut2 ==0 ? INT_MIN : nums2[cut2 -1]; 14 | 15 | int right1 = cut1 == n1 ? INT_MAX : nums1[cut1]; 16 | int right2 = cut2 == n2 ? INT_MAX : nums2[cut2]; 17 | 18 | if( left1 <= right2 && left2 <= right1){ 19 | if((n1+n2) %2 == 0) 20 | return(max(left1,left2) + min(right1, right2)) / 2.0; 21 | else 22 | return max(left1, left2); 23 | } 24 | else if(left1 > right2){ 25 | high = cut1 -1; 26 | } 27 | else{ 28 | low = cut1 +1; 29 | } 30 | } 31 | return 0.0; 32 | } 33 | -------------------------------------------------------------------------------- /50.Pow(x,n).cpp: -------------------------------------------------------------------------------- 1 | /* Approach 2 | 3 | We use exponentiation by squaring to efficiently compute x^n: 4 | 5 | Handle base cases: 6 | 7 | If n == 0, return 1. 8 | If x == 0, return 0 (unless n is 0). 9 | Handle negative powers: 10 | 11 | If n < 0, compute x^{-n} by inverting x (x = 1/x) and making n positive. 12 | For positive powers: 13 | 14 | If n is even: x^n = (x^(n/2)) * (x^(n/2)) 15 | If n is odd: x^n = x * (x^(n-1)) 16 | Implement iteratively to avoid recursion stack overflow for large n: 17 | 18 | While n > 0: 19 | If n is odd, multiply result by x. 20 | Square x and divide n by 2. 21 | Return the accumulated result. */ 22 | 23 | class Solution { 24 | public: 25 | double myPow(double x, int n) { 26 | long long N = n; // Convert to long long to handle INT_MIN 27 | if (N < 0) { // Handle negative powers 28 | x = 1 / x; 29 | N = -N; 30 | } 31 | 32 | double result = 1.0; 33 | while (N > 0) { 34 | if (N % 2 == 1) { // If the current power is odd 35 | result *= x; 36 | } 37 | x *= x; // Square x 38 | N /= 2; 39 | } 40 | 41 | return result; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /416. Partition Equal Subset Sum.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | int t[201][20001]; 3 | // before memo - O(2^n) : memo - O(n * x) 4 | //S.C : O(n*X) 5 | 6 | bool canPartition(vector& nums) { 7 | int n = nums.size(); 8 | int S = accumulate(nums.begin(), nums.end(),0); 9 | 10 | if(S%2 != 0){ 11 | return false; 12 | } 13 | memset(t, -1, sizeof(t)); 14 | int x = S/2; 15 | 16 | return solve(nums, 0, x); 17 | } 18 | bool solve(vector& nums, int i, int x){ // All good also try to solve the GFG problem named as Subset Sum - https://www.geeksforgeeks.org/problems/subset-sums2234/1 solve here 19 | if(x==0){ 20 | return true; 21 | } 22 | 23 | if(i >= nums.size()){ 24 | return false; 25 | } 26 | 27 | if(t[i][x] != -1){ 28 | return t[i][x]; 29 | } 30 | 31 | // vector> t(n+1, vector(x+1)) 32 | 33 | bool take = false; 34 | if(nums[i] <= x){ 35 | take = solve(nums, i+1, x- nums[i]); 36 | } 37 | 38 | bool not_take = solve(nums, i+1, x); 39 | 40 | return t[i][x] = take|| not_take; 41 | } 42 | }; 43 | 44 | -------------------------------------------------------------------------------- /138. Copy List with random pointer.cpp: -------------------------------------------------------------------------------- 1 | // Here is the solution of this question without using map 2 | // It's is much optimized 3 | 4 | solution in C++ 5 | 6 | class Solution { 7 | public: 8 | Node* copyRandomList(Node* head) { 9 | if(!head) return 0; 10 | // step 1: clone a -> a' 11 | Node* it = head; 12 | while(it){ 13 | Node*clonedNode = new Node(it->val); 14 | clonedNode->next = it->next; 15 | it->next = clonedNode; 16 | it = it->next->next; 17 | 18 | } 19 | //step 2: assign random links of A with the help of random pouinter 20 | it = head; 21 | while(it){ 22 | Node*clonedNode = it->next; 23 | clonedNode->random = it->random ? it->random->next : nullptr; 24 | it = it->next->next; 25 | } 26 | //step 3: detatch A from A 27 | it = head; 28 | Node*clonedHead = it->next; 29 | while(it){ 30 | Node*clonedNode = it->next; 31 | it->next = it->next->next; 32 | if(clonedNode->next){ 33 | clonedNode->next = clonedNode->next->next; 34 | 35 | } 36 | it = it->next; 37 | } 38 | return clonedHead; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /105. Construct Binary Tree from Preorder and Inorder Traversal.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 | unordered_map mp; 15 | TreeNode* build(int il,int ir,int pl,int pr,vector &preorder,vector &inorder){ 16 | if(il>ir) return NULL; 17 | TreeNode* cur_node = new TreeNode(preorder[pl]); 18 | if(il==ir) return cur_node; 19 | int inorder_ind = mp[preorder[pl]]; 20 | int m = pl+inorder_ind-il; 21 | cur_node->left = build(il,inorder_ind-1,pl+1,m,preorder,inorder); 22 | cur_node->right = build(inorder_ind+1,ir,m+1,pr,preorder,inorder); 23 | return cur_node; 24 | } 25 | TreeNode* buildTree(vector& preorder, vector& inorder) { 26 | int n = inorder.size(); 27 | for(int i=0;i buildArray(vector& nums) { 32 | int n = nums.size(); 33 | vector ans(n); 34 | for (int i = 0; i < n; i++) { 35 | ans[i] = nums[nums[i]]; 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /232.Implement Queue using Stacks.cpp: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | public: 3 | stacks1,s2; 4 | MyQueue() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | s1.push(x); 10 | 11 | } 12 | 13 | int pop() { 14 | int pop = -1; 15 | if(!s2.empty()){ 16 | pop = s2.top(); 17 | } 18 | else{ 19 | while(!s1.empty()){ 20 | s2.push(s1.top()); 21 | s1.pop(); 22 | } 23 | pop = s2.top(); 24 | } 25 | s2.pop(); 26 | return pop; 27 | } 28 | 29 | int peek() { 30 | int front = -1; 31 | if(!s2.empty()){ 32 | front = s2.top(); 33 | } 34 | else{ 35 | while(!s1.empty()){ 36 | s2.push(s1.top()); 37 | s1.pop(); 38 | } 39 | front = s2.top(); 40 | } 41 | 42 | return front; 43 | } 44 | 45 | bool empty() { 46 | return s1.empty() && s2.empty(); 47 | } 48 | 49 | }; 50 | 51 | /** 52 | * Your MyQueue object will be instantiated and called as such: 53 | * MyQueue* obj = new MyQueue(); 54 | * obj->push(x); 55 | * int param_2 = obj->pop(); 56 | * int param_3 = obj->peek(); 57 | * bool param_4 = obj->empty(); 58 | */ 59 | -------------------------------------------------------------------------------- /1662. Check if Two String Arrays are Equivalent.cpp: -------------------------------------------------------------------------------- 1 | // Use any of two approaches below 2 | 3 | T.c - O(n) 4 | s.c - O(1) 5 | 6 | bool arrayStringsAreEqual(vector& word1, vector& word2) { 7 | 8 | // Approach 1 9 | string s1 = ""; 10 | string s2 = ""; 11 | for(string s: word1){ 12 | s1.append(s); 13 | } 14 | for(string p: word2){ 15 | s2.append(p); 16 | } 17 | if(s1 == s2){ 18 | return true; 19 | } 20 | return false; 21 | 22 | 23 | //Approach 2 24 | // Nice Approach // Use any of two approaches 25 | 26 | int m = word1.size(); 27 | int n = word2.size(); 28 | 29 | int w1i=0; int i =0; 30 | int w2i =0; int j =0; 31 | 32 | while(w1i < m && w2i < n){ 33 | if(word1[w1i][i] != word2[w2i][j]) 34 | return false; 35 | i++; 36 | j++; 37 | if(i ==word1[w1i].length()){ 38 | i =0; 39 | w1i++; 40 | } 41 | if(j == word2[w2i].length()){ 42 | j =0; 43 | w2i++; 44 | } 45 | } 46 | if(w1i == word1.size() && w2i == word2.size()) 47 | return true; 48 | 49 | return false; 50 | } 51 | -------------------------------------------------------------------------------- /160. Intersection of Two Linked List.cpp: -------------------------------------------------------------------------------- 1 | //T.C - O(n) 2 | //S.C - O(n) 3 | 4 | 5 | class Solution { 6 | public: 7 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 8 | ListNode*a = headA; 9 | ListNode*b = headB; 10 | while(a->next && b->next){ 11 | if(a==b){ 12 | return a; 13 | } 14 | a = a->next; 15 | b = b->next; 16 | } 17 | //intersection hai hi nhi 18 | if(a->next ==0 && b->next ==0 && a!=b)return 0; 19 | if(a->next==0){ 20 | //b is bigger 21 | //we nee to found how much bigger it is 22 | int blen=0; 23 | while(b->next){ 24 | blen++; 25 | b = b->next; 26 | } 27 | while(blen--){ 28 | headB = headB->next; 29 | } 30 | } 31 | else{ 32 | int alen =0; 33 | while(a->next){ 34 | alen++; 35 | a = a->next; 36 | } 37 | while(alen--){ 38 | headA = headA->next; 39 | } 40 | } 41 | while(headA != headB){ 42 | headA = headA->next; 43 | headB = headB->next; 44 | } 45 | return headA; 46 | 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /838. Push Dominoes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string pushDominoes(string dominoes) { 4 | int n = dominoes.size(); 5 | vector left(n, 0), right(n, 0); 6 | 7 | // Step 1: Propagate rightward forces 8 | int force = 0; 9 | for (int i = 0; i < n; i++) { 10 | if (dominoes[i] == 'R') force = n; // reset strong rightward force 11 | else if (dominoes[i] == 'L') force = 0; // leftward push blocks rightward 12 | else force = max(force - 1, 0); // decrease over distance 13 | right[i] = force; 14 | } 15 | 16 | // Step 2: Propagate leftward forces 17 | force = 0; 18 | for (int i = n - 1; i >= 0; i--) { 19 | if (dominoes[i] == 'L') force = n; // reset strong leftward force 20 | else if (dominoes[i] == 'R') force = 0; // rightward push blocks leftward 21 | else force = max(force - 1, 0); // decrease over distance 22 | left[i] = force; 23 | } 24 | 25 | // Step 3: Determine final state 26 | string result; 27 | for (int i = 0; i < n; i++) { 28 | if (left[i] == right[i]) result += '.'; 29 | else if (left[i] > right[i]) result += 'L'; 30 | else result += 'R'; 31 | } 32 | 33 | return result; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /3350. Adjacent Increasing Subarrays Detection II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | /* 4 | APPROACH: 5 | Use an array to track lengths of increasing streaks, then apply binary search 6 | to find the largest k for which two adjacent increasing subarrays exist. 7 | */ 8 | bool check(int *inc, int n, int k) 9 | { 10 | for (int end1 = k - 1; end1 + k < n; end1++) 11 | { 12 | if (inc[end1] >= k && inc[end1 + k] >= k) 13 | { 14 | return true; 15 | } 16 | } 17 | return false; 18 | } 19 | 20 | int maxIncreasingSubarrays(int *nums, int numsSize) 21 | { 22 | int n = numsSize; 23 | int inc[n]; 24 | for (int i = 0; i < n; i++) 25 | inc[i] = 1; 26 | 27 | // Build the increasing streak lengths 28 | for (int i = 1; i < n; i++) 29 | { 30 | if (nums[i] > nums[i - 1]) 31 | { 32 | inc[i] = inc[i - 1] + 1; 33 | } 34 | } 35 | 36 | int L = 1, R = n / 2; 37 | int ans = 0; 38 | 39 | // Binary search for max k 40 | while (L <= R) 41 | { 42 | int mid = L + (R - L) / 2; 43 | if (check(inc, n, mid)) 44 | { 45 | ans = mid; // mid works, try bigger k 46 | L = mid + 1; 47 | } 48 | else 49 | { 50 | R = mid - 1; // mid too big, try smaller k 51 | } 52 | } 53 | 54 | return ans; 55 | } 56 | -------------------------------------------------------------------------------- /2009. Minimum number of Operations to Make a Array Continuous.cpp: -------------------------------------------------------------------------------- 1 | // T.C - O(lon n) 2 | //........................Leetcode Hard Question.....................// 3 | 4 | // sort(nums.begin(),nums.end()); 5 | // int count =0; 6 | // for(int i=0; i s) 21 | l++; // if window becomes bigger than allowed size, shrink it 22 | else{ 23 | fin = max(fin, r- l+1); //if window is in allowed size, maximize the number of elements in the winow 24 | r++; // slide the right side 25 | } 26 | } 27 | return s - fin +1; // return the missing eleemts in that window 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /2058. Find min and max number between critical Point.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nodesBetweenCriticalPoints(ListNode* head) { 4 | vectorans = {-1, -1}; // minDist & maxDist 5 | ListNode* prev = head; 6 | if(!prev)return ans; 7 | ListNode* curr = head->next; 8 | if(!curr)return ans; 9 | ListNode* nxt = head->next->next; 10 | if(!nxt)return ans; 11 | 12 | int firstCp = -1; 13 | int LastCp = -1; 14 | int minDis = INT_MAX; 15 | 16 | int i=1; 17 | while(nxt){ 18 | bool isCp = ((curr->val > prev->val && curr->val > nxt->val ) || 19 | (curr->val < prev->val && curr->val < nxt->val)) 20 | ? true : false; 21 | 22 | if(isCp && firstCp == -1){ 23 | firstCp = i; 24 | LastCp = i; 25 | } 26 | else if(isCp){ 27 | minDis = min(minDis, i- LastCp); 28 | LastCp = i; 29 | } 30 | ++i; 31 | prev = prev->next; 32 | curr = curr->next; 33 | nxt = nxt->next;; 34 | 35 | } 36 | //only One Cp is found 37 | if(LastCp == firstCp){ 38 | return ans; 39 | } 40 | else{ 41 | ans[0] = minDis; 42 | ans[1] = LastCp - firstCp; 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /3341. Find Minimum Time to Reach Last Room I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | struct Node { 4 | int r, c, t; 5 | }; 6 | 7 | struct Cmp { 8 | bool operator()(const Node &a, const Node &b) const { 9 | return a.t > b.t; 10 | } 11 | }; 12 | 13 | int minTimeToReach(vector>& moveTime) { 14 | int n = moveTime.size(); 15 | int m = moveTime[0].size(); 16 | const int INF = INT_MAX / 2; 17 | vector> dist(n, vector(m, INF)); 18 | priority_queue, Cmp> pq; 19 | dist[0][0] = 0; 20 | pq.push({0, 0, 0}); 21 | int dr[4] = {1, -1, 0, 0}; 22 | int dc[4] = {0, 0, 1, -1}; 23 | 24 | while (!pq.empty()) { 25 | Node cur = pq.top(); 26 | pq.pop(); 27 | if (cur.t > dist[cur.r][cur.c]) continue; 28 | if (cur.r == n - 1 && cur.c == m - 1) return cur.t; 29 | 30 | for (int i = 0; i < 4; i++) { 31 | int nr = cur.r + dr[i]; 32 | int nc = cur.c + dc[i]; 33 | if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue; 34 | int arrival = max(moveTime[nr][nc], cur.t) + 1; 35 | if (arrival < dist[nr][nc]) { 36 | dist[nr][nc] = arrival; 37 | pq.push({nr, nc, arrival}); 38 | } 39 | } 40 | } 41 | 42 | return -1; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /3342. Find Minimum Time to Reach Last Room II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dir = {0, 1, 0, -1, 0}; 4 | 5 | bool isValid(int x, int y, int r, int c) { 6 | return (x >= 0 && x < r && y >= 0 && y < c); 7 | } 8 | 9 | int minTimeToReach(vector>& moveTime) { 10 | int r = moveTime.size(), c = moveTime[0].size(); 11 | 12 | vector> mn(r, vector(c, INT_MAX)); 13 | vector> vis(r, vector(c, false)); 14 | 15 | using T = tuple; // t, x, y, idx 16 | priority_queue, greater> pq; 17 | 18 | pq.push({0, 0, 0, 0}); 19 | mn[0][0] = 0; 20 | 21 | while (!pq.empty()) { 22 | auto [t, x, y, idx] = pq.top(); pq.pop(); 23 | if (vis[x][y]) continue; 24 | vis[x][y] = true; 25 | 26 | for (int i = 0; i < 4; i++) { 27 | int nx = x + dir[i]; 28 | int ny = y + dir[i + 1]; 29 | if (!isValid(nx, ny, r, c)) continue; 30 | 31 | int nt = max(mn[x][y], moveTime[nx][ny]) + (idx % 2 == 0 ? 1 : 2); 32 | if (nt < mn[nx][ny]) { 33 | mn[nx][ny] = nt; 34 | pq.push({nt, nx, ny, idx + 1}); 35 | } 36 | } 37 | } 38 | 39 | return mn[r - 1][c - 1]; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /355. Design Twitter.cpp: -------------------------------------------------------------------------------- 1 | class Twitter { 2 | private: 3 | int time; 4 | unordered_map> mp; // Stores followers 5 | unordered_map>> mp2; // Stores tweets (time, tweetId) 6 | public: 7 | Twitter() { 8 | time=0; 9 | } 10 | 11 | void postTweet(int userId, int tweetId) { 12 | mp2[userId].emplace_back(time,tweetId); 13 | time++; 14 | } 15 | 16 | vector getNewsFeed(int userId) { 17 | priority_queue> pq; 18 | for(auto i: mp2[userId]) pq.push(i); 19 | for(auto i: mp[userId]){ 20 | for(auto j: mp2[i]) pq.push(j); 21 | } 22 | vector feed; 23 | int count=10; 24 | while(!pq.empty() && count){ 25 | feed.push_back(pq.top().second); 26 | pq.pop(); 27 | count--; 28 | } 29 | return feed; 30 | } 31 | 32 | void follow(int followerId, int followeeId) { 33 | mp[followerId].insert(followeeId); 34 | } 35 | 36 | void unfollow(int followerId, int followeeId) { 37 | mp[followerId].erase(followeeId); 38 | } 39 | }; 40 | 41 | /** 42 | * Your Twitter object will be instantiated and called as such: 43 | * Twitter* obj = new Twitter(); 44 | * obj->postTweet(userId,tweetId); 45 | * vector param_2 = obj->getNewsFeed(userId); 46 | * obj->follow(followerId,followeeId); 47 | * obj->unfollow(followerId,followeeId); 48 | */ 49 | -------------------------------------------------------------------------------- /239. Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | //Queue class 3 2 | //Hard C++ solution... 3 | //Using STL Deque & Vector 4 | 5 | class Solution { 6 | public: 7 | vector maxSlidingWindow(vector& nums, int k) { 8 | dequedq; 9 | vectorans; 10 | //first window of k size 11 | for(int i=0;i= nums[dq.back()] ){ 14 | dq.pop_back(); 15 | } 16 | //inserting index, so that we can checkout of window element 17 | dq.push_back(i); 18 | } 19 | //store ans for first window 20 | ans.push_back(nums[dq.front()]); // array ki value ko store akr rhe hai 21 | 22 | // remaining windows ko track krengey 23 | for(int i=k;i= k){ 26 | dq.pop_front(); 27 | } 28 | 29 | //ab firse current elemnt k liye ,chote element ko remove krana hai 30 | while(!dq.empty() && nums[i] >= nums[dq.back()] ){ 31 | dq.pop_back(); 32 | } 33 | //inserting index, so that we can checkout of window element 34 | dq.push_back(i); 35 | 36 | //current window ka ans store karana hai 37 | ans.push_back(nums[dq.front()]); 38 | 39 | } 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /3. Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | //Approach 3 - Integer Array 2 | /* 3 | 1.This solution uses an integer array charIndex to store the indices of characters. 4 | 2.We eliminate the need for an unordered map by utilizing the array. 5 | 3.The maxLength, left, and right pointers are still present. 6 | 4.We iterate through the string using the right pointer. 7 | 5.We check if the current character has occurred within the current substring by comparing its index in charIndex with left. 8 | 6.If the character has occurred, we move the left pointer to the next position after the last occurrence of the character. 9 | 7.We update the index of the current character in charIndex. 10 | 8.At each step, we update the maxLength by calculating the length of the current substring. 11 | 9.We continue the iteration until reaching the end of the string. 12 | 10.Finally, we return the maxLength as the length of the longest substring without repeating characters. 13 | Code*/ 14 | 15 | class Solution { 16 | public: 17 | int lengthOfLongestSubstring(string s) { 18 | int n = s.length(); 19 | int maxLen =0; 20 | vectorcharIndex(128,-1); 21 | int left =0; 22 | for(int right =0;right= left){ 24 | left = charIndex[s[right]]+1; 25 | } 26 | charIndex[s[right]] = right; 27 | maxLen = max(maxLen,right-left +1); 28 | } 29 | return maxLen; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /51.N-Queens.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void solve(int col, int n, vector &board, 7 | vector> &ans, 8 | vector &leftrow, vector &upperdiag, vector &lowerdiag) { 9 | 10 | if (col == n) { 11 | ans.push_back(board); 12 | return; 13 | } 14 | 15 | for (int row = 0; row < n; row++) { 16 | if (leftrow[row] == 0 && lowerdiag[row + col] == 0 && upperdiag[(n - 1) + (col - row)] == 0) { 17 | 18 | board[row][col] = 'Q'; 19 | leftrow[row] = 1; 20 | lowerdiag[row + col] = 1; 21 | upperdiag[(n - 1) + (col - row)] = 1; 22 | 23 | solve(col + 1, n, board, ans, leftrow, upperdiag, lowerdiag); 24 | 25 | board[row][col] = '.'; // backtrack 26 | leftrow[row] = 0; 27 | lowerdiag[row + col] = 0; 28 | upperdiag[(n - 1) + (col - row)] = 0; 29 | } 30 | } 31 | } 32 | 33 | vector> solveNQueens(int n) { 34 | vector> ans; 35 | vector board(n, string(n, '.')); 36 | 37 | vector leftrow(n, 0); 38 | vector lowerdiag(2 * n - 1, 0); 39 | vector upperdiag(2 * n - 1, 0); 40 | 41 | solve(0, n, board, ans, leftrow, upperdiag, lowerdiag); 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /37. Sudoku Solver.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solveSudoku(vector>& board) { 4 | backtrack(board); 5 | } 6 | 7 | private: 8 | bool backtrack(vector>& board) { 9 | for (int r = 0; r < 9; r++) { 10 | for (int c = 0; c < 9; c++) { 11 | if (board[r][c] == '.') { 12 | for (char ch = '1'; ch <= '9'; ch++) { 13 | if (isValid(board, r, c, ch)) { 14 | board[r][c] = ch; 15 | if (backtrack(board)) return true; // continue with this placement 16 | board[r][c] = '.'; // undo if failed 17 | } 18 | } 19 | return false; // no valid digit, backtrack 20 | } 21 | } 22 | } 23 | return true; // all cells filled 24 | } 25 | 26 | bool isValid(vector>& board, int r, int c, char ch) { 27 | // Row & Column check 28 | for (int i = 0; i < 9; i++) { 29 | if (board[r][i] == ch) return false; 30 | if (board[i][c] == ch) return false; 31 | } 32 | // 3x3 sub-box check 33 | int startRow = (r / 3) * 3; 34 | int startCol = (c / 3) * 3; 35 | for (int i = 0; i < 3; i++) { 36 | for (int j = 0; j < 3; j++) { 37 | if (board[startRow + i][startCol + j] == ch) return false; 38 | } 39 | } 40 | return true; 41 | } 42 | }; -------------------------------------------------------------------------------- /731. My Calender II: -------------------------------------------------------------------------------- 1 | // 731. My Calendar II 2 | // https://leetcode.com/problems/my-calendar-ii/description/ 3 | 4 | import java.util.TreeMap; 5 | 6 | class MyCalendarTwo { 7 | private TreeMap delta; 8 | 9 | public MyCalendarTwo() { 10 | delta = new TreeMap<>(); // Tracks the start and end points of intervals 11 | } 12 | 13 | public boolean book(int start, int end) { 14 | // Mark the start and end points of the new interval 15 | delta.put(start, delta.getOrDefault(start, 0) + 1); 16 | delta.put(end, delta.getOrDefault(end, 0) - 1); 17 | 18 | int active = 0; // Tracks the number of active overlaps 19 | for (int d : delta.values()) { 20 | active += d; // Update active count based on delta values 21 | if (active >= 3) { // Triple booking detected 22 | // Revert the changes if a triple booking is found 23 | delta.put(start, delta.get(start) - 1); 24 | delta.put(end, delta.get(end) + 1); 25 | if (delta.get(start) == 0) delta.remove(start); // Remove if zero count 26 | if (delta.get(end) == 0) delta.remove(end); // Remove if zero count 27 | return false; // Booking is not allowed 28 | } 29 | } 30 | 31 | return true; // Booking is allowed 32 | } 33 | } 34 | 35 | /** 36 | * Your MyCalendarTwo object will be instantiated and called as such: 37 | * MyCalendarTwo obj = new MyCalendarTwo(); 38 | * boolean param_1 = obj.book(start,end); 39 | */ 40 | -------------------------------------------------------------------------------- /226. Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | // 226. Invert Binary Tree 2 | // https://leetcode.com/problems/invert-binary-tree/description/ 3 | 4 | /* 5 | Intuition: 6 | The goal is to flip the binary tree horizontally, meaning every left child becomes a right child, and every right child becomes a left child. 7 | 8 | Approach: 9 | 1. If the tree is empty (i.e., root is NULL), we simply return NULL because there's nothing to invert. 10 | 2. We get the left and right children of the current node (root). We store these subtrees temporarily in leftSubtree and rightSubtree variables for swapping purposes. 11 | 3. We assign the leftSubtree to root->right and the rightSubtree to root->left. This effectively inverts the child nodes at the current node. 12 | 4. We then call invertTree recursively on the new left and right children (after the swap) to invert the rest of the tree. 13 | 5. Once all nodes are inverted, we return the root node, which now points to the inverted tree. 14 | */ 15 | 16 | // Time Complexity: O(n), Space Complexity: O(h) 17 | 18 | class Solution { 19 | public: 20 | TreeNode* invertTree(TreeNode* root) { 21 | if(root == NULL) return root; 22 | // Extract the left Subtree 23 | TreeNode *leftSubtree = (root->left)? root->left: NULL; 24 | // Extract the right Subtree 25 | TreeNode *rightSubtree = (root->right)? root->right: NULL; 26 | // swap the left and right subtree 27 | root->left = rightSubtree; 28 | root->right = leftSubtree; 29 | invertTree(root->left); 30 | invertTree(root->right); 31 | return root; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /1518. Water Bottles.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWaterBottles(int numBottles, int numExchange) { 4 | int totalDrunk = numBottles; 5 | int emptyBottles = numBottles; 6 | 7 | while (emptyBottles >= numExchange) { 8 | int newBottles = emptyBottles / numExchange; 9 | totalDrunk += newBottles; 10 | emptyBottles = emptyBottles % numExchange + newBottles; 11 | } 12 | 13 | return totalDrunk; 14 | } 15 | }; 16 | 17 | /* 18 | Alternative Mathematical Solution (More Efficient): 19 | class Solution { 20 | public: 21 | int numWaterBottles(int numBottles, int numExchange) { 22 | // Mathematical formula: numBottles + (numBottles - 1) / (numExchange - 1) 23 | return numBottles + (numBottles - 1) / (numExchange - 1); 24 | } 25 | }; 26 | 27 | Problem Explanation: 28 | - You have numBottles full water bottles 29 | - After drinking, you get numBottles empty bottles 30 | - You can exchange numExchange empty bottles for 1 new full bottle 31 | - Find maximum bottles you can drink 32 | 33 | Example: numBottles = 9, numExchange = 3 34 | - Drink 9 bottles → 9 empty bottles 35 | - Exchange 9 empty → 3 new bottles, 0 empty remaining 36 | - Drink 3 bottles → 3 empty bottles 37 | - Exchange 3 empty → 1 new bottle, 0 empty remaining 38 | - Drink 1 bottle → 1 empty bottle 39 | - Cannot exchange anymore (need 3 empty for 1 new) 40 | - Total drunk: 9 + 3 + 1 = 13 41 | 42 | Time Complexity: O(log(numBottles)) - simulation approach 43 | O(1) - mathematical approach 44 | Space Complexity: O(1) 45 | */ -------------------------------------------------------------------------------- /3479.Fruits Into Baskets 3.cpp: -------------------------------------------------------------------------------- 1 | class SegmentTree { 2 | int N; 3 | vector tree; 4 | 5 | public: 6 | SegmentTree(const vector& baskets) { 7 | int n = baskets.size(); 8 | N = 1; 9 | while (N < n) N <<= 1; 10 | tree.resize(N << 1, -1); 11 | 12 | // Set basket capacities at leaves 13 | for (int i = 0; i < n; ++i) 14 | tree[N + i] = baskets[i]; 15 | 16 | // Build the tree 17 | for (int i = N - 1; i >= 1; --i) 18 | tree[i] = max(tree[2 * i], tree[2 * i + 1]); 19 | } 20 | 21 | // Try placing a fruit of quantity `val` in a valid basket 22 | bool placeFruit(int val) { 23 | int idx = 1; 24 | if (tree[idx] < val) 25 | return false; 26 | 27 | while (idx < N) { 28 | if (tree[2 * idx] >= val) 29 | idx = 2 * idx; 30 | else 31 | idx = 2 * idx + 1; 32 | } 33 | 34 | // Place fruit (consume basket) 35 | tree[idx] = -1; 36 | 37 | // Update tree upwards 38 | while (idx > 1) { 39 | idx >>= 1; 40 | tree[idx] = max(tree[2 * idx], tree[2 * idx + 1]); 41 | } 42 | return true; 43 | } 44 | }; 45 | 46 | class Solution { 47 | public: 48 | int numOfUnplacedFruits(vector& fruits, vector& baskets) { 49 | SegmentTree seg(baskets); 50 | int unplaced = 0; 51 | 52 | for (int fruit : fruits) { 53 | if (!seg.placeFruit(fruit)) 54 | ++unplaced; 55 | } 56 | return unplaced; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /3003. Maximize the Number of Partitions After Operations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | typedef long long ll; 4 | unordered_map dp; 5 | ll solve(ll i, ll mask, ll change, int k, string& s) { 6 | 7 | int n = s.size(); 8 | if (i == n) { 9 | return 1; 10 | } 11 | 12 | ll currState = (i << 27) | (mask << 1) | (change); 13 | 14 | if (dp.find(currState) != dp.end()) { 15 | return dp[currState]; 16 | } 17 | 18 | int val = s[i] - 'a'; 19 | ll newMask = mask | (1 << val); 20 | 21 | int count = __builtin_popcount(newMask); 22 | 23 | ll ans = 0; 24 | ll maxi = 0; 25 | 26 | if (count > k) { 27 | ans = 1 + solve(i + 1, 1 << val, change, k, s); 28 | maxi = max(maxi, ans); 29 | } else { 30 | ans = solve(i + 1, newMask, change, k, s); 31 | maxi = max(maxi, ans); 32 | } 33 | 34 | if (change) { 35 | return dp[currState] = maxi; 36 | } 37 | 38 | for (int j = 0; j < 26; j++) { 39 | 40 | ll newMask = mask | (1 << j); 41 | ll count = __builtin_popcount(newMask); 42 | 43 | if (count > k) { 44 | maxi = max(maxi, 1 + solve(i + 1, 1 << j, 1, k, s)); 45 | } else { 46 | maxi = max(maxi, solve(i + 1, newMask, 1, k, s)); 47 | } 48 | } 49 | 50 | return dp[currState] = maxi; 51 | } 52 | int maxPartitionsAfterOperations(string s, int k) { 53 | return solve(0, 0, 0, k, s); 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /3720. Lexicographically Smallest Permutation Greater Than Target.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | string lexGreaterPermutation(string s, string target) { 6 | string ans =""; 7 | int n = s.length(); 8 | mapmp; 9 | for(auto&e:s)mp[e]++; 10 | for(int i =0;i m2=mp; 13 | string res =""; 14 | bool ip=1; 15 | for(int j = 0;jfirst; 34 | it->second--; 35 | if(it->second==0)m2.erase(it); 36 | } 37 | else continue; 38 | for(auto&e:m2) 39 | { 40 | while(e.second--)res+=e.first; 41 | } 42 | if(ans =="")ans=res; 43 | else ans = min(ans,res); 44 | } 45 | } 46 | return ans; 47 | } 48 | }; -------------------------------------------------------------------------------- /42. Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | //Here is the two pointer approach 2 | //by taking auxaliary space of O(n) 3 | 4 | //Here I'm giving Both C++ & java Solution 5 | 6 | // C++ Solution //and for java solution scroll down 7 | 8 | class Solution { 9 | public: 10 | int trap(vector&height) { 11 | //Space COmplexity O(n) 12 | //Time Complexity O(n) 13 | int n = height.size(); 14 | 15 | vectorleft(n); 16 | left[0] = height[0]; 17 | 18 | for(int i=1;iright(n); 23 | right[n-1] = height[n-1]; 24 | 25 | for(int i=n-2;i>=0;i--){ 26 | right[i] = max(right[i+1],height[i]); 27 | } 28 | 29 | int ans =0; 30 | for(int i=0;i=0;i--){ 52 | right[i] = Math.max(right[i+1],height[i]); 53 | } 54 | int ans=0; 55 | for(int i=0;i& tasks, vector& workers, int pills, int strength, int mid) { 4 | int pillsUsed = 0; 5 | multiset st(begin(workers), begin(workers) + mid); //best mid workers 6 | 7 | for(int i = mid-1; i >= 0; i--) { 8 | int reqrd = tasks[i]; 9 | auto it = prev(st.end()); 10 | 11 | if(*it >= reqrd) { 12 | st.erase(it); 13 | } else if(pillsUsed >= pills) { 14 | return false; 15 | } else { 16 | //find the weakest worker which can do this strong task using pills 17 | auto weakestWorkerIt = st.lower_bound(reqrd - strength); 18 | if(weakestWorkerIt == st.end()) { 19 | return false; 20 | } 21 | st.erase(weakestWorkerIt); 22 | pillsUsed++; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) { 29 | int m = tasks.size(); 30 | int n = workers.size(); 31 | 32 | int l = 0; 33 | int r = min(m, n); 34 | 35 | sort(begin(tasks), end(tasks)); 36 | sort(begin(workers), end(workers), greater()); 37 | 38 | int result = 0; 39 | 40 | while(l <= r) { 41 | int mid = l + (r-l)/2; 42 | 43 | if(check(tasks, workers, pills, strength, mid)) { 44 | result = mid; 45 | l = mid+1; 46 | } else { 47 | r = mid-1; 48 | } 49 | } 50 | 51 | return result; 52 | 53 | 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /92. Reverse Linked List II.cpp: -------------------------------------------------------------------------------- 1 | //T.c -O(n) 2 | //s.C -O(1) 3 | 4 | // function used to reverse a linked list 5 | ListNode* reverse(ListNode* head) 6 | { 7 | ListNode* prev = NULL; 8 | ListNode* curr = head; 9 | while (curr) { 10 | ListNode* next = curr->next; 11 | curr->next = prev; 12 | prev = curr; 13 | curr = next; 14 | } 15 | return prev; 16 | } 17 | 18 | ListNode* reverseBetween(ListNode* head, int left, int right) { 19 | // function used to reverse a linked list from position m to n 20 | if (left == right) 21 | return head; 22 | 23 | // revs and revend is start and end respectively of the 24 | // portion of the linked list which need to be reversed. 25 | // revs_prev is previous of starting position and 26 | // revend_next is next of end of list to be reversed. 27 | ListNode*revs = NULL, *revs_prev = NULL; 28 | ListNode*revend = NULL, *revend_next = NULL; 29 | 30 | // Find values of above pointers. 31 | int i = 1; 32 | ListNode* curr = head; 33 | while (curr && i <= right) { 34 | if (i < left) 35 | revs_prev = curr; 36 | if (i == left) 37 | revs = curr; 38 | if (i == right) { 39 | revend = curr; 40 | revend_next = curr->next; 41 | } 42 | curr = curr->next; 43 | i++; 44 | } 45 | revend->next = NULL; 46 | // Reverse linked list starting with revs. 47 | revend = reverse(revs); 48 | // If starting position was not head 49 | if (revs_prev) 50 | revs_prev->next = revend; 51 | // If starting position was head 52 | else 53 | head = revend; 54 | revs->next = revend_next; 55 | return head; 56 | } 57 | 58 | 59 | }; 60 | -------------------------------------------------------------------------------- /853. Car Fleet I.cpp: -------------------------------------------------------------------------------- 1 | /*There are n cars going to the same destination along a one-lane road. The destination is target miles away. 2 | 3 | //You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). 4 | 5 | //A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). 6 | 7 | //A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. 8 | 9 | //If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. 10 | 11 | //Return the number of car fleets that will arrive at the destination. 12 | 13 | 14 | 15 | 16 | class Solution { 17 | class Car{ 18 | public: 19 | int pos,speed; 20 | Car(int p,int s):pos(p), speed(s){}; 21 | }; 22 | static bool mycomp(Car&a,Car&b){ 23 | return a.pos& position, vector& speed) { 27 | vectorcars; 28 | for(int i=0;ist; 34 | for(auto car:cars){ 35 | float time = (target-car.pos)/((float)car.speed); 36 | 37 | while(!st.empty() && time>= st.top()){ 38 | st.pop(); 39 | } 40 | st.push(time); 41 | } 42 | return st.size(); 43 | } 44 | }; 45 | 46 | //medium but tough though 47 | -------------------------------------------------------------------------------- /1857. Largest_Color_Value_in_a_Directed_Graph.cpp: -------------------------------------------------------------------------------- 1 | // Use Topological Sorting (Kahn’s Algorithm) + Dynamic Programming. 2 | 3 | // For each node, maintain a count[node][color] array of size 26. 4 | 5 | // When processing a node, propagate color counts to its neighbors. 6 | 7 | // Keep track of max color count during traversal. 8 | 9 | // If all nodes are processed → return max count; else → cycle → -1. 10 | 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | class Solution { 22 | public: 23 | int largestPathValue(string colors, vector>& edges) { 24 | int n=colors.size(); 25 | vector> graph(n); 26 | vector indegree(n, 0); 27 | 28 | 29 | for (auto &e:edges) { 30 | graph[e[0]].push_back(e[1]); 31 | indegree[e[1]]++; 32 | } 33 | 34 | 35 | queue q; 36 | for (int i=0;i> count(n,vector(26, 0)); 41 | int vis=0; 42 | int ans=0; 43 | 44 | while (!q.empty()) { 45 | int u=q.front(); 46 | q.pop(); 47 | vis++; 48 | 49 | 50 | int colorIdx=colors[u]-'a'; 51 | count[u][colorIdx]++; 52 | ans=max(ans,count[u][colorIdx]); 53 | 54 | for(int v:graph[u]) { 55 | for(int c=0;c<26;c++) 56 | count[v][c] = max(count[v][c],count[u][c]); 57 | if(--indegree[v]==0) 58 | q.push(v); 59 | } 60 | } 61 | 62 | return (vis==n)?ans:-1; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /1912. Design Movie Rental System.cpp: -------------------------------------------------------------------------------- 1 | using int2=pair; // (price, shop) 2 | using int3=tuple; // (price, shop, movie) 3 | 4 | class MovieRentingSystem { 5 | public: 6 | unordered_map Shop; // (shop,movie)->price 7 | unordered_map> Movie; // movie->set(price,shop) 8 | set rented; // rented->set (price,shop,movie) 9 | 10 | static inline uint64_t key(int shop,int movie) { 11 | return (uint64_t)shop<<32|movie; 12 | } 13 | 14 | MovieRentingSystem(int n, vector>& entries) { 15 | for (auto &e : entries) { 16 | int shop=e[0], movie=e[1], price=e[2]; 17 | Shop[key(shop,movie)]=price; 18 | Movie[movie].insert({price, shop}); 19 | } 20 | } 21 | 22 | vector search(int movie) { 23 | vector ans; 24 | auto& S=Movie[movie]; 25 | int i=0; 26 | for (auto it=S.begin(); it!=S.end() && i<5; it++, i++) { 27 | ans.push_back(it->second); // shop 28 | } 29 | return ans; 30 | } 31 | 32 | void rent(int shop,int movie) { 33 | int price=Shop[key(shop,movie)]; 34 | Movie[movie].erase({price, shop}); 35 | rented.insert({price, shop, movie}); 36 | } 37 | 38 | void drop(int shop,int movie) { 39 | int price=Shop[key(shop,movie)]; 40 | Movie[movie].insert({price, shop}); 41 | rented.erase({price, shop, movie}); 42 | } 43 | 44 | vector> report() { 45 | vector> ans; 46 | int i=0; 47 | for (auto it=rented.begin(); it!=rented.end() && i<5; it++, i++) { 48 | auto [price, shop, movie]=*it; 49 | ans.push_back({shop, movie}); 50 | } 51 | return ans; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /3068. Find the Maximum Sum of Node Values.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Definition for a binary tree node 5 | struct Node { 6 | int data; 7 | Node* left; 8 | Node* right; 9 | Node(int val) { 10 | data = val; 11 | left = right = nullptr; 12 | } 13 | }; 14 | 15 | class Solution { 16 | int maxSum; // Global maximum sum 17 | // Helper function to compute maximum gain from a node 18 | int findMaxPath(Node* root) { 19 | if (!root) return 0; 20 | 21 | int leftGain = max(0, findMaxPath(root->left)); // Max path sum from left 22 | int rightGain = max(0, findMaxPath(root->right)); // Max path sum from right 23 | 24 | // Update global maximum including current node 25 | maxSum = max(maxSum, leftGain + rightGain + root->data); 26 | 27 | // Return max gain including current node for recursion 28 | return root->data + max(leftGain, rightGain); 29 | } 30 | 31 | public: 32 | int maxPathSum(Node* root) { 33 | maxSum = INT_MIN; 34 | findMaxPath(root); 35 | return maxSum; 36 | } 37 | }; 38 | 39 | // Example usage 40 | int main() { 41 | /* 42 | 10 43 | / \ 44 | 2 10 45 | / \ \ 46 | 20 1 -25 47 | / \ 48 | 3 4 49 | Expected Output: 42 (20 + 2 + 10 + 10) 50 | */ 51 | 52 | Node* root = new Node(10); 53 | root->left = new Node(2); 54 | root->right = new Node(10); 55 | root->left->left = new Node(20); 56 | root->left->right = new Node(1); 57 | root->right->right = new Node(-25); 58 | root->right->right->left = new Node(3); 59 | root->right->right->right = new Node(4); 60 | 61 | Solution sol; 62 | cout << "Maximum Path Sum: " << sol.maxPathSum(root) << endl; 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /407. Trapping Rain Water II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | typedef pair> PP; 4 | vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 5 | 6 | int trapRainWater(vector>& heightMap) { 7 | 8 | int m = heightMap.size(); 9 | int n = heightMap[0].size(); 10 | 11 | priority_queue, greater<>> boundaryCells; 12 | 13 | vector> visited(m, vector(n, false)); 14 | 15 | for (int r = 0; r < m; ++r) { 16 | for (int c : {0, n - 1}) { //0 : left most boundary, cols-1 right most boundary 17 | boundaryCells.push({heightMap[r][c], {r, c}}); 18 | visited[r][c] = true; 19 | } 20 | } 21 | 22 | for (int c = 0; c < n; ++c) { 23 | for (int r : {0, m - 1}) { //0 : top most boundary, rows-1 bottom most boundary 24 | boundaryCells.push({heightMap[r][c], {r, c}}); 25 | visited[r][c] = true; 26 | } 27 | } 28 | 29 | int water = 0; 30 | 31 | while(!boundaryCells.empty()){ 32 | PP p = boundaryCells.top(); 33 | boundaryCells.pop(); 34 | 35 | int heigth = p.first; 36 | int i = p.second.first; 37 | int j = p.second.second; 38 | 39 | //find neighbourss 40 | for(vector& dir: directions){ 41 | int i_ = i + dir[0]; 42 | int j_ = j + dir[1]; 43 | 44 | if(i_ >= 0 && i_ = 0 && j_ & nums) { 4 | 5 | sort(nums.begin(), nums.end(), greater()); 6 | 7 | for (int i = 0; i < nums.size() - 2; i++) { 8 | if (nums[i + 1] + nums[i + 2] > nums[i]) { 9 | return nums[i] + nums[i + 1] + nums[i + 2]; 10 | } 11 | } 12 | 13 | return 0; 14 | } 15 | }; 16 | 17 | /* 18 | Alternative Approach - Same Logic, Different Implementation: 19 | class Solution { 20 | public: 21 | int largestPerimeter(vector& nums) { 22 | sort(nums.rbegin(), nums.rend()); // Sort in descending order 23 | 24 | for (int i = 0; i <= (int)nums.size() - 3; i++) { 25 | int a = nums[i], b = nums[i + 1], c = nums[i + 2]; 26 | 27 | // Triangle inequality: a + b > c, b + c > a, a + c > b 28 | // Since a >= b >= c, we only need to check b + c > a 29 | if (b + c > a) { 30 | return a + b + c; 31 | } 32 | } 33 | 34 | return 0; 35 | } 36 | }; 37 | 38 | Problem Explanation: 39 | - Find the largest perimeter of a triangle that can be formed from the array 40 | - Triangle inequality: sum of any two sides must be greater than the third side 41 | - For sides a >= b >= c: only need to check if b + c > a 42 | 43 | Strategy: 44 | 1. Sort array in descending order 45 | 2. Check triplets from largest to smallest 46 | 3. Return first valid triangle's perimeter (guaranteed to be largest) 47 | 4. If no valid triangle exists, return 0 48 | 49 | Example: nums = [2,1,2] 50 | - Sorted: [2,2,1] 51 | - Check (2,2,1): 2+1 > 2? Yes! → Return 2+2+1 = 5 52 | 53 | Example: nums = [1,2,1] 54 | - Sorted: [2,1,1] 55 | - Check (2,1,1): 1+1 > 2? No! 56 | - No more triplets → Return 0 57 | 58 | Time Complexity: O(n log n) - dominated by sorting 59 | Space Complexity: O(1) - only using constant extra space 60 | */ -------------------------------------------------------------------------------- /15. 3Sum.cpp: -------------------------------------------------------------------------------- 1 | /*Approach 2 | NOTE-PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH. 3 | 4 | Approach for this Problem: 5 | 6 | 1. Sort the input array 7 | 2. Initialize a set to store the unique triplets and an output vector to store the final result 8 | 3. Iterate through the array with a variable i, starting from index 0. 9 | 4. Initialize two pointers, j and k, with j starting at i+1 and k starting at the end of the array. 10 | In the while loop, check if the sum of nums[i], nums[j], and nums[k] is equal to 0. If it is, insert the triplet into the set and increment j and decrement k to move the pointers. 11 | 5. If the sum is less than 0, increment j. If the sum is greater than 0, decrement k. 12 | 6. After the while loop, iterate through the set and add each triplet to the output vector. 13 | 7. Return the output vector 14 | 15 | Complexity 16 | Time complexity: O(n^2) 17 | Space complexity: o(n) 18 | */ 19 | //step 1: 20 | sort(nums.begin(), nums.end()); 21 | set>s; 22 | int target =0; 23 | //step 2:make a output vector 24 | vector>output; 25 | //step 3: iteration of outer loop 26 | for(int i=0;i> sortMatrix(vector>& grid) { 4 | vector> ans; 5 | vector t; 6 | int cnt = 1; 7 | int j=0; 8 | for(int i=grid.size()-1;i>=0;i--){ 9 | int p=i; 10 | while(j < grid.size() && p < grid.size()){ 11 | t.push_back(grid[p][j]); 12 | p++; 13 | j++; 14 | } 15 | sort(t.begin(), t.end()); 16 | reverse(t.begin(), t.end()); 17 | ans.push_back(t); 18 | t.clear(); 19 | j=0; 20 | } 21 | vector> a1; 22 | int r = 1; 23 | for(int k=1;k=0;i--){ 42 | int r = i; 43 | while(q < ans[p].size()){ 44 | grid[r][j] = ans[p][q]; 45 | q++; 46 | r++; 47 | j++; 48 | } 49 | j=0; 50 | q=0; 51 | p++; 52 | } 53 | q=0; 54 | j=1; 55 | r=0; 56 | for(int i=1;i Contributors 42 | 43 | 44 | Thank you for your contributions! HAPPY HACKTOBER... 45 | -------------------------------------------------------------------------------- /84. Largest Rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | //here we have to learn two more quentions first ... 2 | //Which are most important in Stack 3 | // 1.next Smaller Element 4 | //2. prev Smaller Element 5 | 6 | //then we will be able to solve it 7 | //Formula---- 8 | // area = length * width; 9 | 10 | 11 | class Solution { 12 | public: 13 | vectornextSmallerElement(vector& input){ 14 | stacks; 15 | s.push(-1); 16 | vectorans(input.size()); 17 | for(int i=input.size()-1;i>=0;i--){ 18 | int curr = input[i]; 19 | while(s.top()!= -1 && input[s.top()] >= curr){ 20 | s.pop(); 21 | } 22 | //chota mil chuka hai store ans 23 | ans[i] = s.top(); 24 | //push kardo element ko 25 | s.push(i); 26 | } 27 | return ans; 28 | } 29 | vectorprevSmallerElement(vector& input){ 30 | stacks; 31 | s.push(-1); 32 | vectorans(input.size()); 33 | //left to right 34 | for(int i=0;i= curr){ 38 | s.pop(); 39 | } 40 | //chota element mil chuka hai 41 | ans[i] = s.top(); 42 | //push kardo elment ko 43 | s.push(i); 44 | } 45 | return ans; 46 | } 47 | int largestRectangleArea(vector& heights) { 48 | //prev smaller call 49 | vectorprev = prevSmallerElement(heights); 50 | //next smaller call 51 | vectornext = nextSmallerElement(heights); 52 | int MaxArea = INT_MIN; 53 | int size = heights.size(); 54 | 55 | for(int i=0;i 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector spellchecker(vector& wordlist, vector& queries) { 7 | unordered_set exactMatchSet(wordlist.begin(), wordlist.end()); 8 | unordered_map caseInsensitiveMap; 9 | unordered_map vowelInsensitiveMap; 10 | 11 | auto normalizeVowels = [](const string& word) { 12 | string res = word; 13 | for (char& c : res) { 14 | if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { 15 | c = '*'; 16 | } 17 | } 18 | return res; 19 | }; 20 | 21 | for (string& word : wordlist) { 22 | string lowerWord = word; 23 | transform(lowerWord.begin(), lowerWord.end(), lowerWord.begin(), ::tolower); 24 | 25 | if (!caseInsensitiveMap.count(lowerWord)) { 26 | caseInsensitiveMap[lowerWord] = word; 27 | } 28 | 29 | string vowelNormalized = normalizeVowels(lowerWord); 30 | if (!vowelInsensitiveMap.count(vowelNormalized)) { 31 | vowelInsensitiveMap[vowelNormalized] = word; 32 | } 33 | } 34 | 35 | vector results; 36 | for (string& query : queries) { 37 | if (exactMatchSet.count(query)) { 38 | results.push_back(query); 39 | continue; 40 | } 41 | 42 | string lowerQuery = query; 43 | transform(lowerQuery.begin(), lowerQuery.end(), lowerQuery.begin(), ::tolower); 44 | if (caseInsensitiveMap.count(lowerQuery)) { 45 | results.push_back(caseInsensitiveMap[lowerQuery]); 46 | continue; 47 | } 48 | 49 | string vowelNormalized = normalizeVowels(lowerQuery); 50 | if (vowelInsensitiveMap.count(vowelNormalized)) { 51 | results.push_back(vowelInsensitiveMap[vowelNormalized]); 52 | continue; 53 | } 54 | 55 | results.push_back(""); // No match 56 | } 57 | return results; 58 | } 59 | }; -------------------------------------------------------------------------------- /875.Koko Eating Bananas.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Koko Eating Bananas (Binary Search on Answer) 3 | * 4 | * Description: 5 | * We are given piles of bananas and hours h. Koko eats at a fixed speed k bananas per hour. 6 | * We need to find the minimum k such that Koko can finish all bananas in h hours. 7 | * 8 | * Approach: 9 | * - Use binary search on answer (k). 10 | * - Lower bound = 1 (minimum speed), upper bound = max(piles). 11 | * - Check function: Given a speed k, can Koko finish all bananas within h hours? 12 | * -> Compute total hours = sum( ceil(pile/k) ) for all piles. 13 | * -> If total hours <= h, it's possible. 14 | * - Binary search for the smallest valid k. 15 | * 16 | * Time Complexity: O(n log(max(piles))), where n = number of piles 17 | * Space Complexity: O(1) 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | bool canEat(vector& piles, int h, int k) { 26 | long long totalHours = 0; 27 | for (int bananas : piles) { 28 | totalHours += (bananas + k - 1) / k; // ceil(bananas/k) 29 | if (totalHours > h) return false; 30 | } 31 | return totalHours <= h; 32 | } 33 | 34 | int minEatingSpeed(vector& piles, int h) { 35 | int low = 1, high = *max_element(piles.begin(), piles.end()); 36 | int result = high; 37 | 38 | while (low <= high) { 39 | int mid = low + (high - low) / 2; 40 | if (canEat(piles, h, mid)) { 41 | result = mid; 42 | high = mid - 1; 43 | } else { 44 | low = mid + 1; 45 | } 46 | } 47 | 48 | return result; 49 | } 50 | }; 51 | 52 | int main() { 53 | Solution sol; 54 | 55 | // Test Case 1 56 | vector piles1 = {3,6,7,11}; 57 | int h1 = 8; 58 | cout << "Test Case 1: " << sol.minEatingSpeed(piles1, h1) << endl; // 4 59 | 60 | // Test Case 2 61 | vector piles2 = {30,11,23,4,20}; 62 | int h2 = 5; 63 | cout << "Test Case 2: " << sol.minEatingSpeed(piles2, h2) << endl; // 30 64 | 65 | // Test Case 3 66 | vector piles3 = {30,11,23,4,20}; 67 | int h3 = 6; 68 | cout << "Test Case 3: " << sol.minEatingSpeed(piles3, h3) << endl; // 23 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /417. Pacific Atlantic Water Flow.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> directions = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; 4 | 5 | void DFS(vector>& heights, int i, int j, int prevCellVal, vector>& visited) { 6 | if(i < 0 || i >= heights.size() || j < 0 || j >= heights[0].size()) { //invalid cell 7 | return; 8 | } 9 | 10 | if(heights[i][j] < prevCellVal || visited[i][j]) 11 | return; 12 | 13 | visited[i][j] = true; 14 | for(auto &dir : directions) { 15 | int i_ = i + dir[0]; 16 | int j_ = j + dir[1]; 17 | 18 | DFS(heights, i_, j_, heights[i][j], visited); 19 | } 20 | 21 | } 22 | 23 | vector> pacificAtlantic(vector>& heights) { 24 | int m = heights.size(); //rows 25 | int n = heights[0].size(); //cols 26 | 27 | vector> result; 28 | 29 | vector> pacificVisited(m, vector(n, false)); //pacificVisited[i][j] = true, means [i][j] water can go to Pacific //m*n 30 | vector> atlanticVisited(m, vector(n, false)); //atlanticVisited[i][j] = true, means [i][j] water can go to atlantic //m*n 31 | //T.C : O(m*n) 32 | //S.C : O(m*n) 33 | 34 | 35 | //Top Row and Bottom Row 36 | //Top Row : Pacific connected already 37 | //Bottom Row : atlantic connected already 38 | 39 | for(int j = 0; j < n; j++) { 40 | DFS(heights, 0, j, INT_MIN, pacificVisited); //Top Row 41 | DFS(heights, m-1, j, INT_MIN, atlanticVisited); //Top Row 42 | } 43 | 44 | //First col and last column 45 | //First col : Pacific connected already 46 | //Last col : atlantic connected already 47 | for(int i = 0; i < m; i++) { 48 | DFS(heights, i, 0, INT_MIN, pacificVisited); //First column 49 | DFS(heights, i, n-1, INT_MIN, atlanticVisited); //Last Column 50 | } 51 | 52 | 53 | for(int i = 0; i < m; i++) { 54 | for(int j = 0; j < n; j++) { 55 | if(pacificVisited[i][j] && atlanticVisited[i][j]) { 56 | result.push_back({i, j}); 57 | } 58 | } 59 | } 60 | 61 | return result; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /206.Course Schedule.cpp: -------------------------------------------------------------------------------- 1 | // 🧠 Approach 2 | 3 | // This problem can be modeled as a Directed Graph Cycle Detection problem. 4 | // Each course is represented as a node, and a directed edge b → a means you must take course b before course a. 5 | 6 | // To determine if all courses can be finished, we must ensure no cycle exists in this graph. 7 | // We use Kahn’s Algorithm (Topological Sorting using BFS) to detect cycles. 8 | 9 | // 🚀 Algorithm Steps 10 | 11 | // Build the Graph: 12 | 13 | // - Create an adjacency list adj where adj[b] contains all courses that depend on b. 14 | // - Maintain an array inDeg to store the number of prerequisites (incoming edges) for each course. 15 | 16 | // Find Starting Nodes: 17 | 18 | // - Push all nodes with inDeg[i] == 0 (no prerequisites) into a queue — these can be taken first. 19 | // - Topological Sorting using BFS: 20 | // - While the queue isn’t empty: 21 | // - Pop a node x (a course that can be completed now). 22 | // - Increment a counter c for completed courses. 23 | // - For each neighbor adj[x][i], reduce its inDeg by 1 (as its prerequisite x is now done). 24 | // - If any neighbor’s inDeg becomes 0, push it into the queue. 25 | 26 | // Check Completion: 27 | 28 | // - If all courses are processed (c == V), return true. 29 | // - Otherwise, there’s a cycle → some courses depend on each other, so return false. 30 | 31 | 32 | // Solution in CPP: 33 | 34 | class Solution { 35 | public: 36 | bool canFinish(int V, vector>& prerequisites) { 37 | vector> adj(V); 38 | vector inDeg(V); 39 | for (int i = 0; i < prerequisites.size(); i++) { 40 | int a = prerequisites[i][0]; 41 | int b = prerequisites[i][1]; 42 | 43 | adj[b].push_back(a); 44 | inDeg[a]++; 45 | } 46 | vector vis(V); 47 | queue q; 48 | 49 | for (int i = 0; i < V; i++) { 50 | if (inDeg[i] == 0) 51 | q.push(i); 52 | } 53 | int c = 0; 54 | while (!q.empty()) { 55 | int x = q.front(); 56 | q.pop(); 57 | c++; 58 | 59 | for (int i = 0; i < adj[x].size(); i++) { 60 | inDeg[adj[x][i]]--; 61 | if (inDeg[adj[x][i]] == 0) 62 | q.push(adj[x][i]); 63 | } 64 | } 65 | return c == V; 66 | } 67 | }; -------------------------------------------------------------------------------- /6.Zigzag Conversion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int numRows) { 4 | // Edge case: if numRows is 1 or greater than string length, return original string 5 | if (numRows == 1 || numRows >= s.length()) { 6 | return s; 7 | } 8 | 9 | // Create a vector to store characters for each row 10 | vector rows(numRows); 11 | 12 | // Track current row and direction 13 | int currentRow = 0; 14 | bool goingDown = false; 15 | 16 | // Iterate through each character in the string 17 | for (char c : s) { 18 | // Add character to current row 19 | rows[currentRow] += c; 20 | 21 | // Change direction when we hit top or bottom row 22 | if (currentRow == 0 || currentRow == numRows - 1) { 23 | goingDown = !goingDown; 24 | } 25 | 26 | // Move to next row based on direction 27 | currentRow += goingDown ? 1 : -1; 28 | } 29 | 30 | // Concatenate all rows to get final result 31 | string result; 32 | for (string row : rows) { 33 | result += row; 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | 40 | // Test cases 41 | #include 42 | #include 43 | using namespace std; 44 | 45 | int main() { 46 | Solution solution; 47 | 48 | // Example 1 49 | string s1 = "PAYPALISHIRING"; 50 | int numRows1 = 3; 51 | cout << "Input: s = \"" << s1 << "\", numRows = " << numRows1 << endl; 52 | cout << "Output: \"" << solution.convert(s1, numRows1) << "\"" << endl; 53 | cout << "Expected: \"PAHNAPLSIIGYIR\"\n" << endl; 54 | 55 | // Example 2 56 | string s2 = "PAYPALISHIRING"; 57 | int numRows2 = 4; 58 | cout << "Input: s = \"" << s2 << "\", numRows = " << numRows2 << endl; 59 | cout << "Output: \"" << solution.convert(s2, numRows2) << "\"" << endl; 60 | cout << "Expected: \"PINALSIGYAHRPI\"\n" << endl; 61 | 62 | // Example 3 63 | string s3 = "A"; 64 | int numRows3 = 1; 65 | cout << "Input: s = \"" << s3 << "\", numRows = " << numRows3 << endl; 66 | cout << "Output: \"" << solution.convert(s3, numRows3) << "\"" << endl; 67 | cout << "Expected: \"A\"" << endl; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /3703. Remove K-Balanced Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeSubstring(string s, int k) { 4 | stack> stk; 5 | auto f = [&]() -> void { 6 | int cnt = 0; 7 | int len = 0; 8 | for(auto &I : s) { 9 | if(I == '(' && !stk.empty() && stk.top().first == I) { 10 | stk.top().second++; 11 | } else if(I == '(') { 12 | stk.push({I, 1}); 13 | len++; 14 | } 15 | if(I == ')' && !stk.empty() && stk.top().first == I) { 16 | stk.top().second++; 17 | } else if(I == ')') { 18 | stk.push({I, 1}); 19 | len++; 20 | } 21 | //cout << len << endl; 22 | if(len >= 2) { 23 | // atleast one ( and one ) present 24 | if(stk.top().first == ')' && stk.top().second >= k) { 25 | // enough ')' there 26 | // stk = ((()))())(()) , and if k = 2 27 | auto preserve_top = stk.top(); 28 | stk.pop(); 29 | if(stk.top().first == '(' && stk.top().second >= k){ 30 | int viable = min(preserve_top.second, stk.top().second); 31 | stk.top().second -= viable; 32 | preserve_top.second -= viable; 33 | if(stk.top().second == 0) { 34 | stk.pop(); 35 | len--; 36 | } 37 | if(preserve_top.second == 0) { 38 | len--; 39 | } else { 40 | stk.push(preserve_top); 41 | } 42 | } else { 43 | stk.push(preserve_top); 44 | } 45 | } 46 | } 47 | } 48 | if(!stk.empty() && stk.top().second == 0) { 49 | stk.pop(); 50 | } 51 | }; 52 | f(); 53 | string ans; 54 | while(!stk.empty()) { 55 | int times = stk.top().second; 56 | while(times--) 57 | ans.push_back(stk.top().first); 58 | stk.pop(); 59 | } 60 | reverse(ans.begin(), ans.end()); 61 | return ans; 62 | } 63 | }; -------------------------------------------------------------------------------- /502. IPO.cpp: -------------------------------------------------------------------------------- 1 | // 502. IPO 2 | 3 | // Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. 4 | // You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it. 5 | // Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. 6 | // Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital. 7 | 8 | // The answer is guaranteed to fit in a 32-bit signed integer. 9 | // Example 1: 10 | 11 | // Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] 12 | // Output: 4 13 | // Explanation: Since your initial capital is 0, you can only start the project indexed 0. 14 | // After finishing it you will obtain profit 1 and your capital becomes 1. 15 | // With capital 1, you can either start the project indexed 1 or the project indexed 2. 16 | // Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. 17 | // Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. 18 | // Example 2: 19 | 20 | // Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] 21 | // Output: 6 22 | 23 | // Constraints: 24 | 25 | // 1 <= k <= 105 26 | // 0 <= w <= 109 27 | // n == profits.length 28 | // n == capital.length 29 | // 1 <= n <= 105 30 | // 0 <= profits[i] <= 104 31 | // 0 <= capital[i] <= 109 32 | 33 | class Solution { 34 | public: 35 | int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { 36 | int n = profits.size(); 37 | vector> projects; 38 | for (int i = 0; i < n; i++) { 39 | projects.push_back({capital[i], profits[i]}); 40 | } 41 | sort(projects.begin(), projects.end()); 42 | 43 | priority_queue pq; 44 | int i = 0; 45 | while (k--) { 46 | while (i < n && projects[i].first <= w) { 47 | pq.push(projects[i].second); 48 | i++; 49 | } 50 | if (pq.empty()) break; 51 | w += pq.top(); 52 | pq.pop(); 53 | } 54 | return w; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /725. Split Linked list in parts.cpp: -------------------------------------------------------------------------------- 1 | //T.c - 0(n) 2 | 3 | class Solution { 4 | public: 5 | vector splitListToParts(ListNode* head, int k) { 6 | // Function to split the linked list 7 | // in K groups 8 | // Stores the K groups 9 | vector ans; 10 | 11 | // If head is NULL 12 | if (!head) { 13 | 14 | // Iterate until K is non-zero 15 | while (k--) 16 | ans.push_back(NULL); 17 | } 18 | 19 | // Stores the length of the 20 | int N = 0; 21 | 22 | // Stores the head node 23 | ListNode* p = head; 24 | 25 | // Iterate over the linked list 26 | while (p) { 27 | 28 | // Update p 29 | p = p->next; 30 | 31 | // Update N 32 | N++; 33 | } 34 | 35 | int len = N / k; 36 | int rem = N % k; 37 | 38 | p = head; 39 | 40 | // Iterate over the linked list 41 | while (k > 0 && p) { 42 | 43 | // Stores the length 44 | // of the current group 45 | int x = len; 46 | 47 | // Stores the current node 48 | ListNode* curr_head = p; 49 | 50 | // Stores the previous node 51 | ListNode* last = p; 52 | 53 | // If rem is greater than 0 54 | if (rem > 0) { 55 | 56 | // Update p 57 | p = p->next; 58 | 59 | // Decrement rem by 1 60 | rem--; 61 | } 62 | 63 | // Iterate until x is non-zero 64 | while (x--) { 65 | 66 | // If the last is equal to p 67 | if (last == p) 68 | p = p->next; 69 | 70 | // Otherwise 71 | else { 72 | 73 | // Join the link between 74 | // last and the current 75 | // element 76 | last->next = p; 77 | 78 | // Update the last node 79 | last = p; 80 | 81 | // Update p node 82 | p = p->next; 83 | } 84 | } 85 | 86 | // Assign NULL to last->next 87 | last->next = NULL; 88 | 89 | // Push the current linked 90 | // list in ans 91 | ans.push_back(curr_head); 92 | 93 | // Decrement K 94 | k--; 95 | } 96 | 97 | // While K greater than 0 98 | while (k > 0) { 99 | 100 | // Update the value of ans 101 | ans.push_back(NULL); 102 | 103 | // Increment K 104 | k--; 105 | } 106 | return ans; 107 | } 108 | }; 109 | -------------------------------------------------------------------------------- /2785. Sort Vowels in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string sortVowels(string s) { 4 | vector vowelCount(128, 0); 5 | for (char c : s) { 6 | if (isVowel(c)) { 7 | vowelCount[c]++; 8 | } 9 | } 10 | string sortedVowels = ""; 11 | 12 | string vowelOrder = "AEIOUaeiou"; 13 | for (char v : vowelOrder) { 14 | while (vowelCount[v] > 0) { 15 | sortedVowels += v; 16 | vowelCount[v]--; 17 | } 18 | } 19 | 20 | int vowelIndex = 0; 21 | for (int i = 0; i < s.length(); i++) { 22 | if (isVowel(s[i])) { 23 | s[i] = sortedVowels[vowelIndex++]; 24 | } 25 | } 26 | 27 | return s; 28 | } 29 | 30 | private: 31 | bool isVowel(char c) { 32 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || 33 | c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; 34 | } 35 | }; 36 | 37 | /* 38 | Alternative O(n) Solution using Counting Sort: 39 | class Solution { 40 | public: 41 | string sortVowels(string s) { 42 | // Count array for vowels (A=65, E=69, I=73, O=79, U=85, a=97, e=101, i=105, o=111, u=117) 43 | map vowelCount; 44 | 45 | // Count vowels 46 | for (char c : s) { 47 | if (isVowel(c)) { 48 | vowelCount[c]++; 49 | } 50 | } 51 | 52 | // Create sorted vowel sequence 53 | string vowels = ""; 54 | for (auto& p : vowelCount) { 55 | vowels += string(p.second, p.first); 56 | } 57 | 58 | // Replace vowels in original string 59 | int j = 0; 60 | for (int i = 0; i < s.length(); i++) { 61 | if (isVowel(s[i])) { 62 | s[i] = vowels[j++]; 63 | } 64 | } 65 | 66 | return s; 67 | } 68 | 69 | private: 70 | bool isVowel(char c) { 71 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || 72 | c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; 73 | } 74 | }; 75 | 76 | Problem Explanation: 77 | - Sort only the vowels in the string while keeping consonants in place 78 | - Vowels: a, e, i, o, u (both uppercase and lowercase) 79 | - Sort in lexicographical order (ASCII): A < E < I < O < U < a < e < i < o < u 80 | 81 | Example: s = "lEetcOde" 82 | - Vowels found: E, e, O, e (positions 1, 2, 5, 7) 83 | - Sorted vowels: E, O, e, e 84 | - Result: "lEOtcede" 85 | 86 | Time Complexity: O(n) - two passes through string + O(1) vowel processing 87 | Space Complexity: O(1) - fixed size arrays/maps for vowels only 88 | */ -------------------------------------------------------------------------------- /3362. Zero Array Transformation III.cpp: -------------------------------------------------------------------------------- 1 | ```cpp 2 | // Problem: 3362. Zero Array Transformation III 3 | 4 | // Approach: 5 | // Intuition: 6 | // The problem asks us to transform an array of non-negative integers into an array of all zeros using a specific operation. The operation involves choosing an index `i` and a non-negative integer `x`, then subtracting `x` from `nums[i]` and `nums[i+1]`. We want to find the minimum total sum of `x` values used. 7 | 8 | // Let's analyze the operation. When we subtract `x` from `nums[i]` and `nums[i+1]`, it means `nums[i]` and `nums[i+1]` are reduced by the same amount. This suggests a greedy approach from left to right. 9 | 10 | // Consider `nums[0]`. To make `nums[0]` zero, we must apply an operation at index `0` with `x = nums[0]`. This will also affect `nums[1]`. After this operation, `nums[0]` becomes zero. We then move to `nums[1]` (which has been modified) and repeat the process. 11 | 12 | // Let's try a direct greedy approach. Iterate from `i = 0` to `n-1`. 13 | // For each `nums[i]`, if `nums[i]` is not zero, we must perform an operation at index `i` to make it zero. The value of `x` for this operation must be `nums[i]` itself. This operation will also subtract `nums[i]` from `nums[i+1]` (if `i+1 < n`). 14 | // We add `nums[i]` to our total operations count. 15 | 16 | // Example: 17 | // nums = [1, 2, 3] 18 | 19 | // i = 0: nums[0] = 1. We need to subtract 1 from nums[0] and nums[1]. 20 | // x = 1. Total operations = 1. 21 | // nums becomes [0, 1, 3] 22 | 23 | // i = 1: nums[1] = 1. We need to subtract 1 from nums[1] and nums[2]. 24 | // x = 1. Total operations = 1 + 1 = 2. 25 | // nums becomes [0, 0, 2] 26 | 27 | // i = 2: nums[2] = 2. We need to subtract 2 from nums[2] (and nums[3] if it existed, but it doesn't). 28 | // x = 2. Total operations = 2 + 2 = 4. 29 | // nums becomes [0, 0, 0] 30 | 31 | // This greedy strategy seems to work. For each element `nums[i]`, if it's positive, we must reduce it to zero. The only way to reduce `nums[i]` without affecting `nums[0...i-1]` (which we've already made zero) is to apply the operation at index `i`. The amount we subtract, `x`, must be exactly `nums[i]` to make it zero. This `x` then also reduces `nums[i+1]`. 32 | 33 | // Solution in Code: 34 | class Solution { 35 | public: 36 | long long zeroArray(vector& nums) { 37 | long long total_operations = 0; 38 | int n = nums.size(); 39 | 40 | for (int i = 0; i < n; ++i) { 41 | if (nums[i] > 0) { 42 | total_operations += nums[i]; 43 | if (i + 1 < n) { 44 | nums[i+1] -= nums[i]; 45 | // Ensure nums[i+1] does not become negative 46 | if (nums[i+1] < 0) { 47 | nums[i+1] = 0; 48 | } 49 | } 50 | nums[i] = 0; // nums[i] is now zero 51 | } 52 | } 53 | return total_operations; 54 | } 55 | }; 56 | ``` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/solution-contribution.yml: -------------------------------------------------------------------------------- 1 | name: "Solution Contribution (C++)" 2 | description: "Submit a C++ solution for a LeetCode problem which already not exists in the repo." 3 | title: "[Problem Number]: " 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Thank you for contributing a solution! Please fill out the details below. 9 | 10 | PR File Naming Convention: 11 | - Your solution file must be named exactly as: `[Number]. [Problem Title].cpp` 12 | - Example: `2785. Sort Vowels in a String.cpp` 13 | 14 | - type: input 15 | id: problem_number 16 | attributes: 17 | label: Problem Number 18 | description: Enter the LeetCode problem number. 19 | placeholder: "2785" 20 | validations: 21 | required: true 22 | 23 | - type: input 24 | id: problem_title 25 | attributes: 26 | label: Problem Title 27 | description: Enter the exact LeetCode problem title. 28 | placeholder: "Sort Vowels in a String" 29 | validations: 30 | required: true 31 | 32 | - type: input 33 | id: leetcode_link 34 | attributes: 35 | label: LeetCode Link 36 | description: Provide the link to the problem on LeetCode. 37 | placeholder: "https://leetcode.com/problems/sort-vowels-in-a-string/" 38 | validations: 39 | required: true 40 | 41 | - type: checkboxes 42 | id: contribution_checklist 43 | attributes: 44 | label: Contribution Checklist 45 | options: 46 | - label: I have written the Approach section. 47 | required: true 48 | - label: I have written the Intuition section. 49 | required: true 50 | - label: I have included a working C++ solution. 51 | required: true 52 | - label: I will raise a PR and ensure the filename follows the convention `[Number]. [Problem Title].cpp`. 53 | required: true 54 | 55 | - type: textarea 56 | id: approach 57 | attributes: 58 | label: Approach 59 | description: Describe the algorithm, data structures used, and time/space complexity. 60 | placeholder: "Explain step-by-step how your solution works and its complexity." 61 | validations: 62 | required: true 63 | 64 | - type: textarea 65 | id: intuition 66 | attributes: 67 | label: Intuition 68 | description: Explain the core idea behind your approach. 69 | placeholder: "Why does this approach work? What insights led you to it?" 70 | validations: 71 | required: true 72 | 73 | - type: textarea 74 | id: code 75 | attributes: 76 | label: Solution in C++ 77 | description: Paste your C++ solution code. Ensure it compiles and passes sample tests. 78 | render: cpp 79 | placeholder: | 80 | ```cpp 81 | class Solution { 82 | public: 83 | // Your solution code here 84 | }; 85 | ``` 86 | validations: 87 | required: true 88 | 89 | 90 | -------------------------------------------------------------------------------- /53. Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | //Brute Force 2 | //This will give you TLE 3 | //Time Complexity: O(n^2) 4 | //Space Complexity: O(1) 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int maxSubArray(vector& nums) { 11 | int n = nums.size(); 12 | int maxSum = INT_MIN; 13 | for (int i = 0; i < n; i++) { 14 | int currSum = 0; 15 | for (int j = i; j < n; j++) { 16 | currSum += nums[j]; 17 | maxSum = max(maxSum, currSum); 18 | } 19 | } 20 | return maxSum; 21 | } 22 | }; 23 | 24 | 25 | //Prefix Sum 26 | //This will give you TLE also 27 | //Time Complexity: O(n^2) 28 | //Space Complexity: O(n) 29 | #include 30 | using namespace std; 31 | 32 | class Solution { 33 | public: 34 | int maxSubArray(vector& nums) { 35 | int n = nums.size(); 36 | vector prefix(n+1, 0); 37 | for (int i = 0; i < n; i++) { 38 | prefix[i+1] = prefix[i] + nums[i]; 39 | } 40 | int maxSum = INT_MIN; 41 | for (int i = 0; i < n; i++) { 42 | for (int j = i; j < n; j++) { 43 | int sum = prefix[j+1] - prefix[i]; 44 | maxSum = max(maxSum, sum); 45 | } 46 | } 47 | return maxSum; 48 | } 49 | }; 50 | 51 | 52 | //Divide & Conquer 53 | //This Works 54 | //Time Complexity: O(n log n) 55 | //Space Complexity: O(log n) recursion stack 56 | #include 57 | using namespace std; 58 | 59 | class Solution { 60 | public: 61 | int maxCrossingSum(vector& nums, int l, int m, int r) { 62 | int leftSum = INT_MIN, rightSum = INT_MIN, sum = 0; 63 | for (int i = m; i >= l; i--) { 64 | sum += nums[i]; 65 | leftSum = max(leftSum, sum); 66 | } 67 | sum = 0; 68 | for (int i = m+1; i <= r; i++) { 69 | sum += nums[i]; 70 | rightSum = max(rightSum, sum); 71 | } 72 | return leftSum + rightSum; 73 | } 74 | 75 | int maxSubArrayHelper(vector& nums, int l, int r) { 76 | if (l == r) return nums[l]; 77 | int m = (l + r) / 2; 78 | return max({maxSubArrayHelper(nums, l, m), 79 | maxSubArrayHelper(nums, m+1, r), 80 | maxCrossingSum(nums, l, m, r)}); 81 | } 82 | 83 | int maxSubArray(vector& nums) { 84 | return maxSubArrayHelper(nums, 0, nums.size()-1); 85 | } 86 | }; 87 | 88 | 89 | //Dynamic Programming 90 | //This Works Too 91 | //Time Complexity: O(n) 92 | //Space Complexity: O(n) 93 | #include 94 | using namespace std; 95 | 96 | class Solution { 97 | public: 98 | int maxSubArray(vector& nums) { 99 | int n = nums.size(); 100 | vector dp(n); 101 | dp[0] = nums[0]; 102 | int maxSum = dp[0]; 103 | for (int i = 1; i < n; i++) { 104 | dp[i] = max(nums[i], dp[i-1] + nums[i]); 105 | maxSum = max(maxSum, dp[i]); 106 | } 107 | return maxSum; 108 | } 109 | }; 110 | 111 | 112 | //Kadane’s Algorithm 113 | //This Will Works Too 114 | //Time Complexity: O(n) 115 | //Space Complexity: O(1) 116 | #include 117 | using namespace std; 118 | 119 | class Solution { 120 | public: 121 | int maxSubArray(vector& nums) { 122 | int maxSum = nums[0], currSum = nums[0]; 123 | for (int i = 1; i < nums.size(); i++) { 124 | currSum = max(nums[i], currSum + nums[i]); 125 | maxSum = max(maxSum, currSum); 126 | } 127 | return maxSum; 128 | } 129 | }; 130 | 131 | 132 | //Segment Tree 133 | //This Works too 134 | //Time Complexity: O(n) build + O(1) query for maxSubArray 135 | //Space Complexity: O(n) for segment tree 136 | #include 137 | using namespace std; 138 | 139 | struct Node { 140 | int sum, pref, suff, ans; 141 | }; 142 | 143 | Node combine(Node l, Node r) { 144 | Node res; 145 | res.sum = l.sum + r.sum; 146 | res.pref = max(l.pref, l.sum + r.pref); 147 | res.suff = max(r.suff, r.sum + l.suff); 148 | res.ans = max({l.ans, r.ans, l.suff + r.pref}); 149 | return res; 150 | } 151 | 152 | Node makeNode(int val) { 153 | return {val, val, val, val}; 154 | } 155 | 156 | class Solution { 157 | public: 158 | void build(vector& nums, vector& tree, int v, int tl, int tr) { 159 | if (tl == tr) { 160 | tree[v] = makeNode(nums[tl]); 161 | } else { 162 | int tm = (tl + tr) / 2; 163 | build(nums, tree, v*2, tl, tm); 164 | build(nums, tree, v*2+1, tm+1, tr); 165 | tree[v] = combine(tree[v*2], tree[v*2+1]); 166 | } 167 | } 168 | 169 | int maxSubArray(vector& nums) { 170 | int n = nums.size(); 171 | vector tree(4*n); 172 | build(nums, tree, 1, 0, n-1); 173 | return tree[1].ans; 174 | } 175 | }; 176 | -------------------------------------------------------------------------------- /494. Target Sum.cpp: -------------------------------------------------------------------------------- 1 | //*************************** Approach 1 ***************** 2 | class Solution { 3 | public: 4 | int solve(vector& nums, int &target, int i, int sum, unordered_map& memo) { 5 | if (i == nums.size()) { 6 | return sum == target ? 1 : 0; 7 | } 8 | 9 | // Create a unique key for the current state 10 | string key = to_string(i) + "," + to_string(sum); 11 | 12 | // Check if the result is already computed 13 | if (memo.find(key) != memo.end()) { 14 | return memo[key]; 15 | } 16 | 17 | // Compute the result recursively 18 | int plus = solve(nums, target, i + 1, sum + nums[i], memo); 19 | int minus = solve(nums, target, i + 1, sum - nums[i], memo); 20 | 21 | // Store the result in the memo 22 | memo[key] = plus + minus; 23 | 24 | return memo[key]; 25 | } 26 | 27 | int findTargetSumWays(vector& nums, int target) { 28 | unordered_map memo; 29 | return solve(nums, target, 0, 0, memo); 30 | } 31 | }; 32 | 33 | 34 | // ************************** Approach 2 *************************************** 35 | 36 | class Solution { 37 | public: 38 | int S; 39 | int solve(vector& nums, int &target, int i, int sum, vector>& t) { 40 | if(i == nums.size()) { 41 | return sum == target ? 1 : 0; 42 | } 43 | 44 | if(t[i][sum+S] != INT_MIN) { 45 | return t[i][sum+S]; 46 | } 47 | int plus = solve(nums, target, i+1, sum+nums[i], t); 48 | int minus = solve(nums, target, i+1, sum-nums[i], t); 49 | 50 | return t[i][sum+S] = plus+minus; 51 | } 52 | 53 | int findTargetSumWays(vector& nums, int target) { 54 | int n = nums.size(); 55 | S = accumulate(begin(nums), end(nums), 0); 56 | vector> t(n, vector(2*S+1, INT_MIN)); 57 | return solve(nums, target, 0, 0, t); 58 | } 59 | }; 60 | 61 | // *************************** Approach 3 ************************* 62 | 63 | class Solution { 64 | public: 65 | int S; 66 | int solve(vector& nums, int &target, int i, int sum, vector>& t) { 67 | if(i == nums.size()) { 68 | return sum == target ? 1 : 0; 69 | } 70 | 71 | if(t[i][sum+S] != INT_MIN) { 72 | return t[i][sum+S]; 73 | } 74 | int plus = solve(nums, target, i+1, sum+nums[i], t); 75 | int minus = solve(nums, target, i+1, sum-nums[i], t); 76 | 77 | return t[i][sum+S] = plus+minus; 78 | } 79 | 80 | int findTargetSumWays(vector& nums, int target) { 81 | int n = nums.size(); 82 | S = accumulate(begin(nums), end(nums), 0); 83 | vector> t(n, vector(2*S+1, INT_MIN)); 84 | return solve(nums, target, 0, 0, t); 85 | } 86 | }; 87 | 88 | // ************************** Approach 3 *************************** 89 | 90 | class Solution { 91 | public: 92 | int t[21][1001]; 93 | int subsetSum(vector& nums, int n, int s) { 94 | if(t[n][s] != -1) 95 | return t[n][s]; 96 | if(s == 0) 97 | return 1; 98 | if(n == 0) 99 | return 0; 100 | if(nums[n-1] == 0) 101 | return t[n][s] = subsetSum(nums, n-1, s); 102 | 103 | if(nums[n-1] <= s) 104 | return t[n][s] = subsetSum(nums, n-1, s-nums[n-1]) + subsetSum(nums, n-1, s); 105 | else 106 | return t[n][s] = subsetSum(nums, n-1, s); 107 | } 108 | 109 | int findTargetSumWays(vector& nums, int target) { 110 | memset(t, -1, sizeof(t)); 111 | int sum = accumulate(begin(nums), end(nums), 0); 112 | auto lambda = [&](const int& x) { 113 | return x == 0; 114 | }; 115 | int zeros = count_if(begin(nums), end(nums), lambda); 116 | if(target > sum) 117 | return 0; 118 | 119 | if((sum-target) %2 != 0) 120 | return 0; 121 | 122 | int s1 = (sum-target)/2; 123 | return pow(2, zeros)*subsetSum(nums, nums.size(), s1); 124 | 125 | } 126 | }; 127 | 128 | //**************************** Approach 4 ****************************** 129 | 130 | class Solution { 131 | public: 132 | int subsetSum(vector& nums, int s) { 133 | int n = nums.size(); 134 | vector> t(n+1, vector(s+1)); 135 | 136 | for(int col = 0; col < s+1; col++) t[0][col] = 0; 137 | for(int row = 0; row < n+1; row++) t[row][0] = 1; 138 | 139 | for(int i = 1; i& nums, int target) { 154 | int sum = accumulate(begin(nums), end(nums), 0); 155 | auto lambda = [&](const int& x) { 156 | return x == 0; 157 | }; 158 | int zeros = count_if(begin(nums), end(nums), lambda); 159 | if(target > sum) 160 | return 0; 161 | 162 | if((sum-target) %2 != 0) 163 | return 0; 164 | 165 | int s1 = (sum-target)/2; 166 | /* 167 | You could also do like this : 168 | if((sum + target)%2 != 0) 169 | return 0; 170 | 171 | int s1 = (sum + target)/2; 172 | But since, target can be negative also as per Leetcode (they have recently changed the constraints), 173 | you need to do : 174 | target = abs(target); before finding s1 and the if condition above 175 | */ 176 | return pow(2, zeros)*subsetSum(nums, s1); 177 | } 178 | }; 179 | --------------------------------------------------------------------------------