├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md └── src ├── cpp ├── 132-pattern.cpp ├── 3sum.cpp ├── 4sum.cpp ├── add-binary.cpp ├── add-two-numbers.cpp ├── asteroid-collision.cpp ├── backspace-string-compare.cpp ├── best-time-to-buy-and-sell-stock-ii.cpp ├── best-time-to-buy-and-sell-stock-iv.cpp ├── best-time-to-buy-and-sell-stock.cpp ├── binary-search-tree-iterator.cpp ├── binary-tree-cameras.cpp ├── binary-tree-level-order-traversal-ii.cpp ├── binary-tree-level-order-traversal.cpp ├── binary-tree-maximum-path-sum.cpp ├── bitwise-and-of-numbers-range.cpp ├── break-a-palindrome.cpp ├── buy-and-sell-stock-with-transaction-fee.cpp ├── chalkboard-xor-game.cpp ├── cherry-pickup.cpp ├── combination-sum.cpp ├── concatenation-of-array.cpp ├── construct-binary-search-tree-from-preorder-traversal.cpp ├── container-with-most-water.cpp ├── contains-duplicate-ii.cpp ├── contains-duplicate.cpp ├── contiguous-array.cpp ├── convert-sorted-array-to-binary-search-tree.cpp ├── copy-list-with-random-pointer.cpp ├── count-good-triplets.cpp ├── count-hills-and-valleys-in-an-array.cpp ├── count-number-of-pairs-with-absolute-difference-K.cpp ├── count-primes.cpp ├── course-schedule-iii.cpp ├── decode-ways.cpp ├── defanging-an-ip-address.cpp ├── diameter-of-binary-tree.cpp ├── divide-two-integers.cpp ├── dungeon-game.cpp ├── edit-distance.cpp ├── factorial-trailing-zeroes.cpp ├── find-all-duplicates-in-an-array.cpp ├── find-duplicate-subtrees.cpp ├── find-k-closest-elements.cpp ├── find-median-from-data-stream.cpp ├── find-minimum-in-rotated-sorted-array.cpp ├── find-pivot-index.cpp ├── find-the-duplicate-number.cpp ├── find-the-index-of-the-first-occurrence-in-a-string.cpp ├── find-three-consecutive-integers-that-sum-to-a-given-number.cpp ├── first-bad-version.cpp ├── first-missing-positive.cpp ├── flatten-a-multilevel-doubly-linked-list.cpp ├── flatten-binary-tree-to-linked-list.cpp ├── gas-station.cpp ├── group-anagrams.cpp ├── integer-to-roman.cpp ├── jump-game-ii.cpp ├── kids-with-the-greatest-number-of-candies.cpp ├── kth-ancestor-of-a-Tree-Node.cpp ├── kth-largest-element-in-a-stream.cpp ├── kth-largest-element.cpp ├── last-stone-weight.cpp ├── length-of-last-word.cpp ├── letter-combination-of-a-phone-number.cpp ├── linked-list-cycle-ii.cpp ├── longest-consecutive-sequence.cpp ├── lowest-common-ancestor-of-a-binary-tree.cpp ├── majority-element-ii.cpp ├── majority-element.cpp ├── maximal-rectangle.cpp ├── maximum-matching-of-players-with-trainers.cpp ├── maximum-points-you-can-obtain-from-cards.cpp ├── maximum-product-difference-between-two-pairs.cpp ├── maximum-product-subarray.cpp ├── maximum-subarray.cpp ├── maximum-sum-of-two-non-overlapping-subarrays.cpp ├── merge-intervals.cpp ├── merge-k-sorted-lists.cpp ├── merge-sorted-array.cpp ├── merge-two-sorted-lists.cpp ├── middle-of-the-linked-list.cpp ├── minimum-absolute-difference-in-bst.cpp ├── minimum-distance-between-bst-nodes.cpp ├── minimum-path-sum.cpp ├── minimum-time-to-make-rope-colorful.cpp ├── minimum-white-tiles-after-covering-with-carpets.cpp ├── move-zeroes.cpp ├── next-permutation.cpp ├── number-complement.cpp ├── number-of-dice-rolls-With-target-sum.cpp ├── number-of-good-pairs.cpp ├── number-of-islands.cpp ├── odd-even-linked-list.cpp ├── pacific-atlantic-water-flow.cpp ├── palindrome-number.cpp ├── palindrome-partitioning.cpp ├── partition-list.cpp ├── path-sum-ii.cpp ├── path-sum.cpp ├── peak-index-in-a-mountain-array.cpp ├── permutation-in-string.cpp ├── power-of-four.cpp ├── power-of-three.cpp ├── power-of-two.cpp ├── powx-n.cpp ├── product-of-array-except-self.cpp ├── range-sum-of-bst.cpp ├── ransom-note.cpp ├── recover-binary-search-tree.cpp ├── reduce-array-size-to-the-half.cpp ├── regular-expression-matching.cpp ├── remove-all-adjacent-duplicates-in-string-ii.cpp ├── remove-all-adjacent-duplicates-in-string.cpp ├── remove-duplicates-from-sorted-array.cpp ├── reordered-power-of-2.cpp ├── reverse-integer.cpp ├── reverse-linked-list.cpp ├── reverse-nodes-in-k-group.cpp ├── richest-customer-wealth.cpp ├── roman-to-integer.cpp ├── rotate-array.cpp ├── rotate-arrays.cpp ├── rotate-image.cpp ├── rotate-list.cpp ├── rotting-oranges.cpp ├── running-sum-of-1d-array.cpp ├── same-tree.cpp ├── satisfiability-of-equality-equations.cpp ├── scramble-string.cpp ├── search-a-2d-matrix-ii.cpp ├── search-a-2d-matrix.cpp ├── search-in-rotated-sorted-array.cpp ├── serialize-and-deserialize-bst.cpp ├── set-matrix-zeroes.cpp ├── shortest-common-supersequence.cpp ├── shuffle-string.cpp ├── simplify-path.cpp ├── single-threaded-cpu.cpp ├── sort-colors.cpp ├── sort-list.cpp ├── spiral-matrix.cpp ├── string-compression.cpp ├── string-to-integer-atoi.cpp ├── subarray-sum-equals-k.cpp ├── subsets.cpp ├── sum-of-distances-in-tree.cpp ├── swap-nodes-in-pairs.cpp ├── symmetric-tree.cpp ├── top-k-frequent-elements.cpp ├── trapping-rain-water.cpp ├── two-sum-iv-input-is-a-bst.cpp ├── two-sum.cpp ├── unique-number-of-occurrences.cpp ├── unique-paths-2.cpp ├── unique-paths.cpp ├── valid-anagram.cpp ├── validate-binary-search-tree.cpp ├── water-and-jug-problem.cpp ├── word-break-ii.cpp ├── word-search.cpp └── zigzag-conversion.cpp ├── java ├── bag-of-tokens.java ├── best-time-to-buy-and-sell-stock-with-transaction-fee.java ├── best-time-to-buy-and-sell-stock.java ├── binary-search.java ├── complex-number-multiplication.java ├── concatenation-of-consecutive-binary-numbers.java ├── decode-ways.java ├── design-circular-queue.java ├── fibonacci-number.java ├── find-first-and-last-position-of-element-in-sorted-array.java ├── find-the-index-of-the-first-occurrence-in-a-string.java ├── first-unique-character-in-a-string.java ├── first_bad_version.java ├── house-robber-ii.java ├── invert-binary-tree.java ├── length-of-last-word.java ├── longest-common-subsequence.java ├── longest-substring-without-repeated-characters.java ├── longest-substring-without-repeating-characters.java ├── lowest-common-ancestor-of-a-binary-search-tree.java ├── maximum-performance-of-a-team.java ├── meeting-rooms-iii.java ├── merge-two-sorted-lists.java ├── minimum-money-required-before-transactions.java ├── minimum-swaps-to-make-sequences-increasing.java ├── minimum-time-to-make-rope-colorful.java ├── multiply-strings.java ├── palindrome-number.java ├── palindrome-partitioning-ii.java ├── palindromic-substrings.java ├── pascal's-triangle-ii.java ├── pascals-triangle.java ├── path-sum-ii.java ├── path-sum-iii.java ├── path-sum.java ├── power-of-two.java ├── pseudo-palindromic-paths-in-a-binary-tree.java ├── push-dominoes.java ├── remove-duplicates-from-sorted-array.java ├── remove-duplicates-from-sorted-list-ii.java ├── remove-duplicates-from-sorted-list.java ├── remove-nth-node-from-end-of-list.java ├── reshape-the-matrix.java ├── reverse-nodes-in-k-groups.java ├── reverse-odd-levels-of-binary-tree.java ├── running-sum.java ├── satisfiability-of-equality-equations.java ├── search-in-rotated-sorted-array.java ├── sort-colours.java ├── two-sum.java ├── utf-8-validation.java ├── valid-sudoku.java └── word-search.java ├── mysql ├── combine-two-tables.sql ├── customers-who-never-order.sql ├── department-highest-salary.sql ├── employee-bonus.sql └── find-customer-referee.sql └── python ├── N-queens.py ├── binary-tree-inorder-traversal.py ├── bitwise-AND-of-numbers-range.py ├── break-a-palindrome.py ├── climbing-stairs.py ├── encrypt-and-decrypt-strings.py ├── find-the-index-of-the-first-occurrence-in-a-string.py ├── find-the-original-array-of-prefix-xor.py ├── group-anagrams.py ├── increasing-triplet-subsequence.py ├── keys-and-rooms.py ├── length-of-last-word.py ├── palindrome-number.py ├── permutation-sequence.py ├── powx-n.py ├── repeated-substring-pattern.py ├── roman-to-integer.py ├── rotate-image.py ├── serialize-and-deserialize-binary-tree.py ├── simplify-path.py ├── sum-of-two-integers.py ├── the-employee-that-worked-on-the-longest-task.py ├── two-sum.py ├── using-a-robot-to-print-the-lexicographically-smallest-string.py └── valid-sudoku.py /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Yashvardhan Baid 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 | -------------------------------------------------------------------------------- /src/cpp/132-pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool find132pattern(vector& nums) { 4 | int ak = numeric_limits::min(); 5 | stack st; 6 | for (int i = nums.size() - 1; i >= 0; --i) { 7 | if (nums[i] < ak) { 8 | return true; 9 | } else { 10 | while (!st.empty() && nums[i] > st.top()) { 11 | ak = st.top(), st.pop(); 12 | } 13 | } 14 | st.emplace(nums[i]); 15 | } 16 | return false; 17 | } 18 | }; -------------------------------------------------------------------------------- /src/cpp/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector> threeSum(vector& nums) { 5 | if(nums.size()<=2) return {}; 6 | sort(nums.begin(),nums.end()); 7 | vector>ans; 8 | if(nums[nums.size()-1]<0) return {}; 9 | for(int i=0;i0)break; 11 | if(i>0 && nums[i]==nums[i-1]) continue; 12 | int j=i+1,k=nums.size()-1; 13 | while(k>j){ 14 | int s=nums[k]+nums[j]; 15 | if(nums[i]+s==0){ 16 | ans.push_back({nums[i],nums[j],nums[k]}); 17 | while(j0) k--; 23 | else j++; 24 | } 25 | } 26 | return ans; 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /src/cpp/4sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | typedef long long ll; 5 | vector> fourSum(vector& nums, int target) { 6 | if(nums.size()<=3) return {}; 7 | sort(nums.begin(),nums.end()); 8 | int n=nums.size(); 9 | vector>ans; 10 | for(int i=0;i0 && nums[i]==nums[i-1]) continue; 12 | for(int j=i+1;j1 && nums[j]==nums[j-1] && i!=j-1) continue; 14 | int k=j+1,l=n-1; 15 | ll sum=nums[i]+nums[j]; 16 | while(l>k){ 17 | if(nums[k]+nums[l]+sum==target){ 18 | cout<k && nums[l]==nums[l-1]) l--; 21 | while(l>k && nums[k]==nums[k+1]) k++; 22 | l--,k++; 23 | } 24 | else if(nums[l]+nums[k]+sum>target) l--; 25 | else k++; 26 | } 27 | 28 | } 29 | } 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /src/cpp/add-binary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | string result; 5 | int carry = 0; 6 | for(int idxA = a.size()-1, idxB = b.size()-1; idxA>=0 || idxB>=0; idxA--, idxB--) { 7 | int aNum = idxA >=0 ? a[idxA]-'0' : 0; 8 | int bNum = idxB >=0 ? b[idxB]-'0' : 0; 9 | int curPosNum = aNum + bNum + carry; 10 | int tempRe = curPosNum%2; 11 | carry = curPosNum/2; 12 | result.insert(result.begin(), tempRe+'0'); 13 | } 14 | if(carry > 0) result.insert(result.begin(), carry+'0'); 15 | return result; 16 | } 17 | }; 18 | 19 | // Submision link- https://leetcode.com/submissions/detail/814770106/ 20 | -------------------------------------------------------------------------------- /src/cpp/add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 11 | { 12 | ListNode sum{0}; 13 | auto curr = ∑ 14 | int carry = 0; 15 | while (l1 || l2 || carry) 16 | { 17 | int a = l1 ? l1->val : 0; 18 | int b = l2 ? l2->val : 0; 19 | curr->next = new ListNode((carry + a + b) % 10); 20 | carry = (carry + a + b) / 10; 21 | l1 = l1 ? l1->next : nullptr; 22 | l2 = l2 ? l2->next : nullptr; 23 | curr = curr->next; 24 | } 25 | return sum.next; 26 | } 27 | }; 28 | /* 29 | |---------------------------------------------------| 30 | ||| https://codeforces.com/profile/codechaser ||| 31 | ||| https://www.codechef.com/users/codechaser ||| 32 | ||| https://github.com/code-chaser ||| 33 | |---------------------------------------------------| 34 | */ -------------------------------------------------------------------------------- /src/cpp/asteroid-collision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& a) { 4 | stacks; 5 | vectorv; 6 | s.push(a[0]); 7 | 8 | for(int i=1;i0) s.push(a[i]); 10 | else{ 11 | int f=0; 12 | while(s.empty()==false && s.top()>0 ){ 13 | if(s.top()==abs(a[i])){ 14 | s.pop(); 15 | f=1; 16 | break; 17 | } 18 | else if(s.top()0) 9 | temp1.pop_back(); 10 | else if(s[i] != '#'){ 11 | temp1.push_back(s[i]); 12 | } 13 | } 14 | 15 | for(int i = 0; i0) 17 | temp2.pop_back(); 18 | else if(t[i] != '#'){ 19 | temp2.push_back(t[i]); 20 | } 21 | } 22 | 23 | return temp1 == temp2; 24 | } 25 | }; -------------------------------------------------------------------------------- /src/cpp/best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : Mitternachtsmond||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | int maxProfit(vector& prices) { 10 | int m=prices[0],ans=0; 11 | for(int i=1;im){ 13 | ans+=(prices[i]-m); 14 | } 15 | m=prices[i]; 16 | } 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /src/cpp/best-time-to-buy-and-sell-stock-iv.cpp: -------------------------------------------------------------------------------- 1 | // Recursive memoized DP 2 | 3 | class Solution { 4 | public: 5 | int solve(vector &A, int B); 6 | int recur(vector& prices, int ind, int buy, int k, vector>>& dp) { 7 | if (ind == prices.size())return 0; 8 | if (k == 0)return 0; 9 | if (dp[ind][buy][k] != -1)return dp[ind][buy][k]; 10 | if (buy) { 11 | return dp[ind][buy][k] = max(-prices[ind] + recur(prices, ind + 1, 0, k, dp), recur(prices, ind + 1, 1, k, dp)); 12 | } 13 | return dp[ind][buy][k] = max(prices[ind] + recur(prices, ind + 1, 1, k - 1, dp), recur(prices, ind + 1, 0, k, dp)); 14 | } 15 | 16 | int maxProfit(int k, vector& prices) { 17 | vector>> dp(prices.size(), vector>(2, vector(k + 1, -1))); 18 | return recur(prices, 0, 1, k, dp); 19 | } 20 | }; 21 | 22 | // Most optimised solution 23 | // Iterative DP + space optimisation 24 | 25 | int Solution::solve(vector &A, int B) { 26 | if (B > A.size() / 2) { 27 | // infinite transactions case 28 | int res = 0; 29 | for (int i = 1; i < A.size(); i++) { 30 | res += max(0, A[i] - A[i - 1]); 31 | } 32 | return res; 33 | } 34 | 35 | vector > curr(2, vector(B + 1, 0)); 36 | vector > after(2, vector(B + 1, 0)); 37 | 38 | for (int i = A.size() - 1; i >= 0; i--) { 39 | for (int buy = 0; buy <= 1; buy++) { 40 | for (int b = 1; b <= B; b++) { 41 | if (buy) { 42 | curr[buy][b] = max(-A[i] + after[0][b], after[1][b]); 43 | } 44 | else curr[buy][b] = max(A[i] + after[1][b - 1], after[0][b]); 45 | } 46 | } 47 | after = curr; 48 | } 49 | return curr[1][B]; 50 | } 51 | -------------------------------------------------------------------------------- /src/cpp/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : Mitternachtsmond||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | int maxProfit(vector& prices) { 10 | int m=prices[0],ans=0; 11 | for(int i=1;im) ans=max(ans,prices[i]-m); 13 | else m=prices[i]; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /src/cpp/binary-search-tree-iterator.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 BSTIterator { 13 | private: 14 | stackst; 15 | 16 | void _push(TreeNode *n) 17 | { 18 | while(n) 19 | { 20 | st.push(n); 21 | n=n->left; 22 | } 23 | } 24 | 25 | public: 26 | BSTIterator(TreeNode* root) { 27 | _push(root); 28 | } 29 | 30 | int next() { 31 | TreeNode *n; 32 | n=st.top(); 33 | st.pop(); 34 | _push(n->right); 35 | return n->val; 36 | } 37 | 38 | bool hasNext() { 39 | return !st.empty(); 40 | } 41 | }; 42 | 43 | /** 44 | * Your BSTIterator object will be instantiated and called as such: 45 | * BSTIterator* obj = new BSTIterator(root); 46 | * int param_1 = obj->next(); 47 | * bool param_2 = obj->hasNext(); 48 | */ -------------------------------------------------------------------------------- /src/cpp/binary-tree-cameras.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-cameras/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | // first:true -> has camera 17 | // second:true -> is being monitored 18 | 19 | pair cal(TreeNode* root,int &ans){ 20 | if(!root){ 21 | return {false,true}; 22 | } 23 | auto l = cal(root->left,ans); 24 | auto r = cal(root->right,ans); 25 | bool cam = false, mon = false; 26 | if(l.first || r.first){ 27 | mon = true; 28 | } 29 | if(l.second==false || r.second==false){ 30 | ans++; 31 | cam = true; 32 | mon = true; 33 | } 34 | return {cam,mon}; 35 | } 36 | int minCameraCover(TreeNode* root) { 37 | int ans = 0; 38 | auto p = cal(root,ans); 39 | if(p.second == false) ans++; 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /src/cpp/binary-tree-level-order-traversal-ii.cpp: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | 17 | vector> levelOrder(TreeNode* root) { 18 | vector> ans; 19 | vector add; 20 | if(!root) 21 | return ans; 22 | 23 | queue mq; 24 | mq.push(root); 25 | 26 | while(mq.size() > 0){ 27 | int count = mq.size(); 28 | for(int i = 0; i < count; i++){ 29 | root = mq.front(); 30 | mq.pop(); 31 | add.push_back(root->val); 32 | 33 | if(root->left != NULL) 34 | mq.push(root->left); 35 | 36 | if(root->right != NULL) 37 | mq.push(root->right); 38 | } 39 | ans.push_back(add); 40 | add.clear(); 41 | } 42 | 43 | return ans; 44 | } 45 | 46 | vector> levelOrderBottom(TreeNode* root) { 47 | vector> ans = levelOrder(root); 48 | reverse(ans.begin(), ans.end()); 49 | return ans; 50 | } 51 | }; 52 | 53 | // Submission - https://leetcode.com/submissions/detail/706141462/ 54 | -------------------------------------------------------------------------------- /src/cpp/binary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/binary-tree-level-order-traversal/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | vector> levelOrder(TreeNode* root) { 17 | if(root==NULL) 18 | return {}; 19 | vector> ans; 20 | queue q; 21 | q.push(root); 22 | TreeNode *temp; 23 | int len; 24 | while(!q.empty()){ 25 | len=q.size(); 26 | vector v; 27 | for(int i=0;ival); 31 | 32 | if(temp->left) q.push(temp->left); 33 | if(temp->right) q.push(temp->right); 34 | } 35 | ans.push_back(v); 36 | } 37 | return ans; 38 | } 39 | }; 40 | 41 | // Submission - https://leetcode.com/submissions/detail/746124529/ -------------------------------------------------------------------------------- /src/cpp/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-maximum-path-sum/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | int ans = 0; 17 | int sum(TreeNode* root){ 18 | if(!root){ 19 | return 0; 20 | } 21 | if(!root->left && !root->right){ 22 | ans = max(ans,root->val); 23 | return root->val; 24 | } 25 | int l = sum(root->left); 26 | int r = sum(root->right); 27 | int ret = max(l+root->val,r+root->val); 28 | ans = max(ans,max(max(ret,root->val),l+r+root->val)); 29 | return max(ret,root->val); 30 | } 31 | int maxPathSum(TreeNode* root) { 32 | if(!root) return 0; 33 | ans = INT_MIN; 34 | sum(root); 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /src/cpp/bitwise-and-of-numbers-range.cpp: -------------------------------------------------------------------------------- 1 | //Question: https://leetcode.com/problems/bitwise-and-of-numbers-range/ 2 | 3 | class Solution { 4 | public: 5 | //using bitmanipulation 6 | int rangeBitwiseAnd(int left, int right) { 7 | int ans = 0; 8 | while(left>= 1; 10 | right >>= 1; 11 | ans++; 12 | } 13 | 14 | return right< &prices, int state, int i,vector> &dp, int fee) 6 | { 7 | int n = prices.size(); 8 | 9 | if(i == n) return 0; 10 | 11 | if(dp[i][state] != -1) return dp[i][state]; 12 | 13 | int profit = 0; 14 | 15 | if(state) 16 | { 17 | profit = max(-prices[i] + f(prices,0,i+1, dp, fee), 0 + f(prices,1 ,i+1,dp, fee)); 18 | } 19 | 20 | else 21 | { 22 | profit = max(prices[i]- fee + f(prices,1,i+1, dp, fee), 0 + f(prices, 0, i + 1, dp, fee)); 23 | } 24 | return dp[i][state] = profit; 25 | } 26 | 27 | int maxProfit(vector& prices, int fee) 28 | { 29 | vector> dp(prices.size(),vector(2,-1)); 30 | return f(prices, 1,0, dp, fee); 31 | } 32 | }; -------------------------------------------------------------------------------- /src/cpp/chalkboard-xor-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool xorGame(vector& nums) { 4 | int x=nums[0]; 5 | for(int i=1;i>& grid,int r1,int c1,int r2){ 7 | int c2 = r1+c1-r2; 8 | if(r1>=grid.size() || r2>=grid.size() || c1 >= grid[0].size() || c2 >= grid[0].size() || grid[r1][c1] == -1 || grid[r2][c2] == -1){ 9 | return INT_MIN; 10 | } 11 | 12 | if(r1 == grid.size()-1 && c1 == grid[0].size()-1){ 13 | return grid[r1][c1]; 14 | } 15 | if(dp[r1][c1][r2] != -1){ 16 | return dp[r1][c1][r2]; 17 | } 18 | 19 | int x1=0,x2=0; 20 | if(r1 == r2 && c1 == c2){ 21 | x1 += grid[r1][c1]; 22 | } 23 | else{ 24 | x1 += grid[r1][c1]; 25 | x2 += grid[r2][c2]; 26 | } 27 | 28 | int a = dfs(grid, r1, c1+1, r2); // right, right 29 | int b = dfs(grid, r1+1, c1, r2+1); // bottom, bottom 30 | int c = dfs(grid, r1+1, c1, r2); // bottom, right 31 | int d = dfs(grid, r1, c1+1, r2+1); // right, bottom 32 | 33 | if(a == b && b == c && c == d && a == INT_MIN){ 34 | return dp[r1][c1][r2] = INT_MIN; 35 | } 36 | return dp[r1][c1][r2] = x1 + x2 + max(max(a,b),max(c,d)); 37 | } 38 | int cherryPickup(vector>& grid) { 39 | memset(dp,-1,sizeof(dp)); 40 | int ans = dfs(grid,0,0,0); 41 | if(ans == INT_MIN){ 42 | return 0; 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /src/cpp/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void helper(vector& candidates, int target, vector> &ans,vector &combination, int start){ 4 | if(target==0){ 5 | ans.push_back(vector (combination.begin(), combination.end())); 6 | return; 7 | } 8 | for(int i=start;itarget){ 10 | break; 11 | } 12 | combination.push_back(candidates[i]); 13 | helper(candidates, target-candidates[i],ans,combination,i); 14 | combination.pop_back(); 15 | } 16 | } 17 | vector> combinationSum(vector& candidates, int target) { 18 | int n=candidates.size(); 19 | vector> ans; 20 | vector combination; 21 | sort(candidates.begin(), candidates.end()); 22 | helper(candidates,target,ans,combination,0); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /src/cpp/concatenation-of-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | vector getConcatenation(vector& nums) { 7 | vector ans; 8 | int n = nums.size(); 9 | 10 | for(int i=0;i<2*n;i++){ 11 | int x; 12 | x = nums[i%n]; 13 | ans.push_back(x); 14 | } 15 | 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /src/cpp/construct-binary-search-tree-from-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | // Question: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | TreeNode* build_tree(vector& preorder, int l, int r){ 17 | if(l>r) 18 | return nullptr; 19 | TreeNode *root = new TreeNode(preorder[l]); 20 | if(l == r) 21 | return root; 22 | 23 | int ind = l+1; 24 | while(ind<=r && preorder[ind]left = build_tree(preorder, l+1, ind-1); 28 | root->right = build_tree(preorder, ind, r); 29 | 30 | return root; 31 | } 32 | 33 | TreeNode* bstFromPreorder(vector& preorder) { 34 | return build_tree(preorder, 0, preorder.size()-1); 35 | } 36 | }; -------------------------------------------------------------------------------- /src/cpp/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& h) { 4 | int start=0; 5 | int end=h.size()-1; 6 | int max_area=0; 7 | while(starth[end]){ 16 | end=end-1; 17 | } 18 | } 19 | return max_area; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /src/cpp/contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyDuplicate(vector& nums, int k) { 4 | mapm; 5 | for(int i=0;i& nums) { 4 | unordered_mapm; 5 | for(int i=0;i& nums) { 4 | if(nums.size()<=1) return 0; 5 | 6 | unordered_map mp; 7 | mp[0] = -1; 8 | 9 | int cnt = (nums[0] == 1 ? 1 : -1); 10 | mp[cnt] = 0; 11 | 12 | int maxi = 0; 13 | 14 | for(int i = 1; i& nums) { 15 | return func(nums, 0, nums.size()-1); 16 | } 17 | TreeNode *func(vectorv, int lo, int hi) 18 | { 19 | int m; 20 | if(lo>hi) 21 | return NULL; 22 | m=(lo+hi)/2; 23 | TreeNode *root=new TreeNode(v[m], func(v, lo, m-1), func(v, m+1, hi)); 24 | return root; 25 | } 26 | }; -------------------------------------------------------------------------------- /src/cpp/copy-list-with-random-pointer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | Node *copyRandomList(Node *head) 10 | { 11 | Node *front = head; 12 | for (Node *i = head; i != NULL;) 13 | { 14 | front = i->next; 15 | Node *copy = new Node(i->val); 16 | i->next = copy; 17 | copy->next = front; 18 | i = front; 19 | } 20 | for (Node *i = head; i != NULL;) 21 | { 22 | if (i->random != NULL) 23 | { 24 | i->next->random = i->random->next; 25 | } 26 | i = i->next->next; 27 | } 28 | Node *pseudo = new Node(0); 29 | Node *copy = pseudo; 30 | for (Node *i = head; i != NULL;) 31 | { 32 | front = i->next->next; 33 | copy->next = i->next; 34 | i->next = front; 35 | copy = copy->next; 36 | i = front; 37 | } 38 | return pseudo->next; 39 | } 40 | }; 41 | /* 42 | |---------------------------------------------------| 43 | ||| https://codeforces.com/profile/codechaser ||| 44 | ||| https://www.codechef.com/users/codechaser ||| 45 | ||| https://github.com/code-chaser ||| 46 | |---------------------------------------------------| 47 | */ -------------------------------------------------------------------------------- /src/cpp/count-good-triplets.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | int countGoodTriplets(vector& arr, int a, int b, int c) { 7 | int count=0; 8 | int n = arr.size(); 9 | for(int i=0;i& nums) { 4 | int n=nums.size(); 5 | int count =0; 6 | int left; 7 | int right; 8 | for(int mid =1; midnums[left] && nums[mid]>nums[right]) 17 | count++; 18 | } 19 | return count; 20 | } 21 | }; -------------------------------------------------------------------------------- /src/cpp/count-number-of-pairs-with-absolute-difference-K.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | int countKDifference(vector& nums, int k) { 7 | int count=0; 8 | for(int i=0;i prime(n+1,true); 8 | 9 | prime[0]=prime[1]=false; 10 | 11 | for(int i=2;i a, vector b) { 6 | return a[1]>& courses) { 10 | 11 | int n = courses.size(); 12 | int time = 0; 13 | priority_queue q; 14 | 15 | sort(courses.begin(), courses.end(), cmp); 16 | 17 | for(int i=0; i courses[i][0]) { 24 | 25 | int x = q.top(); 26 | q.pop(); 27 | time-=x; 28 | time+=courses[i][0]; 29 | q.push(courses[i][0]); 30 | } 31 | } 32 | } 33 | 34 | return q.size(); 35 | } 36 | }; 37 | 38 | // Submission - https://leetcode.com/submissions/detail/729083953/ -------------------------------------------------------------------------------- /src/cpp/decode-ways.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/submissions/detail/812935762/ 2 | class Solution 3 | { 4 | public: 5 | 6 | int helper(string &s,int ind, int n,vector &dp) 7 | { 8 | if(ind= n) return 1; 10 | 11 | if(dp[ind] != -1) return dp[ind]; 12 | 13 | int ways = 0; 14 | 15 | ways+=helper(s,ind+1,n,dp); 16 | 17 | if((ind + 1 < n) and ((s[ind] == '1' and s[ind+1] <= '9') or (s[ind] == '2' and s[ind+1]<'7'))) 18 | ways+=helper(s,ind+2,n,dp); 19 | 20 | return dp[ind] = ways; 21 | } 22 | 23 | int numDecodings(string s) 24 | { 25 | int n = s.length(); 26 | vector dp(n,-1); 27 | return helper(s,0,n,dp); 28 | } 29 | }; -------------------------------------------------------------------------------- /src/cpp/defanging-an-ip-address.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string defangIPaddr(string address) { 4 | string ans=""; 5 | for(int i=0;ileft, h1); 22 | int d2 = diameter(root->right, h2); 23 | 24 | h = max(h1, h2)+1; 25 | 26 | return max({d1, d2, h1+h2}); 27 | } 28 | 29 | 30 | int diameterOfBinaryTree(TreeNode* root) { 31 | int h = 0; 32 | return diameter(root, h); 33 | } 34 | }; -------------------------------------------------------------------------------- /src/cpp/divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | if (dividend == INT_MIN && divisor == -1) { 5 | return INT_MAX; 6 | } 7 | long dvd = labs(dividend), dvs = labs(divisor), ans = 0; 8 | int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; 9 | while (dvd >= dvs) { 10 | long temp = dvs, m = 1; 11 | while (temp << 1 <= dvd) { 12 | temp <<= 1; 13 | m <<= 1; 14 | } 15 | dvd -= temp; 16 | ans += m; 17 | } 18 | return sign * ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /src/cpp/dungeon-game.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/dungeon-game/ 2 | 3 | class Solution { 4 | public: 5 | vector> dp; 6 | int func(vector>& a,int i,int j){ 7 | if(i == a.size() || j == a[0].size()){ 8 | return INT_MAX; 9 | } 10 | if(dp[i][j] != -1){ 11 | return dp[i][j]; 12 | } 13 | int temp = min(func(a,i+1,j),func(a,i,j+1)); 14 | temp = temp == INT_MAX ? 1 : temp; 15 | 16 | return dp[i][j] = temp - a[i][j] > 0 ? temp - a[i][j] : 1; 17 | 18 | } 19 | 20 | int calculateMinimumHP(vector>& a) { 21 | int n = a.size(); 22 | int m = a[0].size(); 23 | dp = vector> (n+1,vector(m+1,-1)); 24 | 25 | return func(a,0,0); 26 | } 27 | }; -------------------------------------------------------------------------------- /src/cpp/edit-distance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : Mitternachtsmond||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | int minDistance(string word1, string word2) { 10 | int n1=word1.size(); 11 | int n2=word2.size(); 12 | vector>dp(n2+1,vector(n1+1,0)); 13 | // dp[0][0]=0; 14 | for(int i=1;i<=n1;i++) dp[0][i]=i; 15 | for(int i=1;i<=n2;i++) dp[i][0]=i; 16 | for(int i=1;i<=n2;i++){ 17 | for(int j=1;j<=n1;j++){ 18 | if(word2[i-1]==word1[j-1]) dp[i][j]=dp[i-1][j-1]; 19 | else dp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1; 20 | } 21 | } 22 | // for(int i=0;i<=n2;i++){ 23 | // for(int j=0;j<=n1;j++){ 24 | // cout<0){ 6 | ans=ans+(N/5); 7 | N=N/5; 8 | } 9 | return ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /src/cpp/find-all-duplicates-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector &nums) 4 | { 5 | unordered_mapmp; 6 | vectorans; 7 | for (size_t i = 0; i < nums.size(); i++) 8 | { 9 | mp[nums[i]]=0; 10 | } 11 | for (size_t i = 0; i < nums.size(); i++) 12 | { 13 | mp[nums[i]]++; 14 | if(mp[nums[i]]==2){ 15 | ans.push_back(nums[i]); 16 | } 17 | } 18 | 19 | return ans;} 20 | }; 21 | -------------------------------------------------------------------------------- /src/cpp/find-duplicate-subtrees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string helper(TreeNode* root,vector &ans, unordered_map&m ){ 4 | if(!root) 5 | return "# "; 6 | string node=to_string(root->val)+" "; 7 | node+=helper(root->left, ans,m); 8 | node+=helper(root->right, ans,m); 9 | if(m.count(node) && m[node]==1){ 10 | ans.push_back(root); 11 | m[node]++; 12 | } 13 | else if(!m.count(node)){ 14 | m[node]=1; 15 | } 16 | return node; 17 | } 18 | vector findDuplicateSubtrees(TreeNode* root) { 19 | vector ans; 20 | unordered_map m; 21 | helper(root, ans, m); 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /src/cpp/find-k-closest-elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 658. Find K Closest Elements 3 | Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. 4 | 5 | An integer a is closer to x than an integer b if: 6 | 7 | |a - x| < |b - x|, or 8 | |a - x| == |b - x| and a < b 9 | 10 | Example1: 11 | Input: arr = [1,2,3,4,5], k = 4, x = 3 12 | Output: [1,2,3,4] 13 | 14 | Example2: 15 | Input: arr = [1,2,3,4,5], k = 4, x = -1 16 | Output: [1,2,3,4] 17 | 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | class Solution { 23 | public: 24 | vector findClosestElements(vector& arr, int k, int x) { 25 | priority_queue,vector>,greater>> pq; 26 | int n=arr.size(); 27 | for(int i=0;i ans; 31 | while(k--){ 32 | ans.push_back(pq.top().second); 33 | pq.pop(); 34 | } 35 | sort(ans.begin(),ans.end()); 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /src/cpp/find-median-from-data-stream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : Mitternachtsmond||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class MedianFinder 7 | { 8 | public: 9 | MedianFinder() { 10 | 11 | } 12 | priority_queuepq1; // max-heap 13 | priority_queue,greater>pq2; // min-heap 14 | void addNum(int num) { 15 | if(pq1.empty()){ 16 | pq1.push(num); 17 | return; 18 | } 19 | if(pq1.size()==pq2.size()){ 20 | if(num>pq2.top()){ 21 | pq1.push(pq2.top()); 22 | pq2.pop(); 23 | pq2.push(num); 24 | } 25 | else pq1.push(num); 26 | } 27 | else{ 28 | if(num>pq1.top()) pq2.push(num); 29 | else{ 30 | pq2.push(pq1.top()); 31 | pq1.pop(); 32 | pq1.push(num); 33 | } 34 | } 35 | } 36 | double findMedian() { 37 | if(pq1.size()==pq2.size()) return (pq1.top()+pq2.top())/2.0; 38 | else return pq1.top(); 39 | } 40 | }; 41 | 42 | /** 43 | * Your MedianFinder object will be instantiated and called as such: 44 | * MedianFinder* obj = new MedianFinder(); 45 | * obj->addNum(num); 46 | * double param_2 = obj->findMedian(); 47 | */ 48 | -------------------------------------------------------------------------------- /src/cpp/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | 3 | class Solution { 4 | public: 5 | int findMin(vector& nums) { 6 | int n = nums.size(); 7 | if(n == 0) return -1; 8 | int low = 0; 9 | int high = n-1; 10 | 11 | if(nums[low] <= nums[high]){ 12 | return nums[0]; 13 | } 14 | 15 | int pos = -1; 16 | while(low <= high){ 17 | int mid = low + (high - low)/2; 18 | if(nums[mid]= nums[0]){ 22 | low = mid + 1; 23 | } 24 | else{ 25 | high = mid - 1; 26 | } 27 | } 28 | return nums[pos]; 29 | } 30 | }; -------------------------------------------------------------------------------- /src/cpp/find-pivot-index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int pivotIndex(vector& nums) { 4 | int ans = -1; 5 | int n = nums.size(); 6 | int sum = 0; 7 | for(int i=0; i& nums) { 4 | //int ans=0; 5 | sort(nums.begin(),nums.end()); 6 | for(int i=0;i0 && needle[i]!=needle[j]) j=lps[j-1]; 13 | if(needle[i]==needle[j]) j++; 14 | lps[i]=j; 15 | } 16 | int cval=0; 17 | for(int i=0;i0 && needle[j]!=haystack[i]) j=lps[j-1]; 20 | if(needle[j]==haystack[i]) j++; 21 | cval=j; 22 | if(cval==n-1) return i-x+1; 23 | } 24 | return -1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /src/cpp/find-three-consecutive-integers-that-sum-to-a-given-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector sumOfThree(long long n) { 5 | if(n%3==0) return {n/3-1,n/3,n/3+1}; 6 | return {}; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /src/cpp/first-bad-version.cpp: -------------------------------------------------------------------------------- 1 | // The API isBadVersion is defined for you. 2 | // bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | int start = 1; 8 | int end = n; 9 | int mid = start+(end-start)/2; 10 | while(start& arr) { 4 | int n=arr.size(); 5 | if(n==0){ 6 | return 1; 7 | } 8 | sort(arr.begin(), arr.end()); 9 | int index=0; 10 | while(index0 && arr[i]==arr[i-1]){ 16 | continue; 17 | } 18 | if(arr[i]!=count){ 19 | break; 20 | } 21 | count++; 22 | } 23 | return count; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /src/cpp/flatten-a-multilevel-doubly-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | Node *flatten(Node *head) 10 | { 11 | if (head == NULL) 12 | return head; 13 | Node *p = head; 14 | while (p != NULL) 15 | { 16 | if (p->child == NULL) 17 | { 18 | p = p->next; 19 | continue; 20 | } 21 | Node *temp = p->child; 22 | while (temp->next != NULL) 23 | { 24 | temp = temp->next; 25 | } 26 | temp->next = p->next; 27 | if (p->next != NULL) 28 | p->next->prev = temp; 29 | p->next = p->child; 30 | p->child->prev = p; 31 | p->child = NULL; 32 | } 33 | return head; 34 | } 35 | }; 36 | /* 37 | |---------------------------------------------------| 38 | ||| https://codeforces.com/profile/codechaser ||| 39 | ||| https://www.codechef.com/users/codechaser ||| 40 | ||| https://github.com/code-chaser ||| 41 | |---------------------------------------------------| 42 | */ -------------------------------------------------------------------------------- /src/cpp/flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | void flatten(TreeNode *root) 10 | { 11 | if (root == NULL || (root->left == NULL && root->right == NULL)) 12 | return; 13 | if (root->left != NULL) 14 | { 15 | flatten(root->left); 16 | TreeNode *temp = root->right; 17 | root->right = root->left; 18 | root->left = NULL; 19 | TreeNode *t = root->right; 20 | while (t->right) 21 | { 22 | t = t->right; 23 | } 24 | t->right = temp; 25 | } 26 | flatten(root->right); 27 | } 28 | }; 29 | /* 30 | |---------------------------------------------------| 31 | ||| https://codeforces.com/profile/codechaser ||| 32 | ||| https://www.codechef.com/users/codechaser ||| 33 | ||| https://github.com/code-chaser ||| 34 | |---------------------------------------------------| 35 | */ -------------------------------------------------------------------------------- /src/cpp/gas-station.cpp: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/gas-station/ 2 | 3 | class Solution { 4 | public: 5 | int canCompleteCircuit(vector& gas, vector& cost) { 6 | int current = 0; 7 | int total = 0; 8 | int diff = 0; 9 | int start = 0; 10 | 11 | for(int i = 0; i < gas.size(); i++){ 12 | diff = gas[i] - cost[i]; 13 | 14 | total += diff; 15 | current += diff; 16 | if(current < 0){ 17 | start = i + 1; 18 | current = 0; 19 | } 20 | } 21 | 22 | if(total >= 0){ 23 | return start; 24 | } 25 | 26 | return -1; 27 | } 28 | }; 29 | 30 | // Submission - https://leetcode.com/submissions/detail/763086968/ -------------------------------------------------------------------------------- /src/cpp/group-anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | vector> ans; 5 | if(strs.size() == 0) 6 | return ans; 7 | 8 | unordered_map> mp; 9 | for(string s : strs){ 10 | string temp = s; 11 | sort(temp.begin(), temp.end()); 12 | mp[temp].push_back(s); 13 | } 14 | 15 | for(auto it: mp){ 16 | ans.push_back(it.second); 17 | } 18 | 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /src/cpp/integer-to-roman.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string intToRoman(int num) { 5 | // string t=to_string(num); 6 | string ans=""; 7 | if(num/1000){ 8 | int d=num/1000; 9 | for(int i=1;i<=d;i++) ans.push_back('M'); 10 | num%=1000; 11 | } 12 | if(num/100){ 13 | int d=num/100; 14 | if(d==5) ans.push_back('D'); 15 | else if(d==4) ans=ans+"CD"; 16 | else if(d==9) ans=ans+"CM"; 17 | else if(d<=3) for(int i=1;i<=d;i++) ans.push_back('C'); 18 | else{ 19 | ans.push_back('D'); 20 | for(int i=1;i<=(d-5);i++) ans.push_back('C'); 21 | } 22 | num%=100; 23 | } 24 | if(num/10){ 25 | int d=num/10; 26 | if(d==5) ans.push_back('L'); 27 | else if(d==4) ans=ans+"XL"; 28 | else if(d==9) ans=ans+"XC"; 29 | else if(d<=3) for(int i=1;i<=d;i++) ans.push_back('X'); 30 | else{ 31 | ans.push_back('L'); 32 | for(int i=1;i<=(d-5);i++) ans.push_back('X'); 33 | } 34 | num%=10; 35 | } 36 | if(num){ 37 | int d=num; 38 | if(d==5) ans.push_back('V'); 39 | else if(d==4) ans=ans+"IV"; 40 | else if(d==9) ans=ans+"IX"; 41 | else if(d<=3) for(int i=1;i<=d;i++) ans.push_back('I'); 42 | else{ 43 | ans.push_back('V'); 44 | for(int i=1;i<=(d-5);i++) ans.push_back('I'); 45 | } 46 | } 47 | return ans; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /src/cpp/jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/jump-game-ii/ 2 | 3 | class Solution { 4 | public: 5 | int jump(vector& nums) { 6 | if(nums.size() == 1) return 0; 7 | int maxReach = nums[0], currReach = nums[0]; 8 | int count = 1; 9 | if(maxReach >= nums.size()-1) return count; 10 | 11 | for(int i=0; i<=maxReach; i++){ 12 | maxReach = max(maxReach,nums[i]+i); 13 | 14 | if(maxReach >= nums.size()-1) return count+1; 15 | if(i == currReach){ 16 | currReach = maxReach; 17 | count++; 18 | } 19 | } 20 | return -1; 21 | } 22 | }; -------------------------------------------------------------------------------- /src/cpp/kids-with-the-greatest-number-of-candies.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | vector kidsWithCandies(vector& candies, int extraCandies) { 7 | vector ans; 8 | int max = *max_element(candies.begin(),candies.end()); 9 | for(int i=0;i=max){ 12 | ans.push_back(true); 13 | }else{ 14 | ans.push_back(false); 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /src/cpp/kth-ancestor-of-a-Tree-Node.cpp: -------------------------------------------------------------------------------- 1 | class TreeAncestor { 2 | public: 3 | vector >up; 4 | vectorheight; 5 | 6 | TreeAncestor(int n, vector& parent) { 7 | // int x=log2(n)+2; 8 | up=vector >(n,vector(20+1,0)); 9 | height=vector(n,-1); 10 | up[0][0]=0; 11 | for(int i=1;igetKthAncestor(node,k); 40 | */ 41 | -------------------------------------------------------------------------------- /src/cpp/kth-largest-element-in-a-stream.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | private: 3 | priority_queue, greater>q; 4 | int k_; 5 | public: 6 | KthLargest(int k, vector& nums) { 7 | int i; 8 | k_=k; 9 | for(i=0;ik_) 12 | { 13 | while(q.size()!=k_) 14 | q.pop(); 15 | } 16 | } 17 | 18 | int add(int val) { 19 | q.push(val); 20 | if(q.size()>k_) 21 | q.pop(); 22 | return q.top(); 23 | } 24 | }; 25 | 26 | /** 27 | * Your KthLargest object will be instantiated and called as such: 28 | * KthLargest* obj = new KthLargest(k, nums); 29 | * int param_1 = obj->add(val); 30 | */ -------------------------------------------------------------------------------- /src/cpp/kth-largest-element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums and an integer k, return the kth largest element in the array. 3 | Note that it is the kth largest element in the sorted order, not the kth distinct element. 4 | Example: 5 | Input: nums = [3,2,1,5,6,4], k = 2 6 | Output: 5 7 | 8 | 9 | Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 10 | Output: 4 11 | 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | int findKthLargest(vector& nums, int k) { 18 | priority_queue pq; 19 | for(int i=0;i& stones) { 5 | make_heap(stones.begin(), stones.end()); 6 | 7 | while(stones.size()>1){ 8 | pop_heap(stones.begin(), stones.end()); 9 | int first = stones.back(); 10 | stones.pop_back(); 11 | 12 | pop_heap(stones.begin(), stones.end()); 13 | int second = stones.back(); 14 | stones.pop_back(); 15 | 16 | int diff = abs(first-second); 17 | if(diff>0){ 18 | stones.push_back(diff); 19 | push_heap(stones.begin(),stones.end()); 20 | } 21 | } 22 | if(stones.size() == 1) 23 | return stones[0]; 24 | else return 0; 25 | } 26 | }; -------------------------------------------------------------------------------- /src/cpp/length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int n=s.size(); 5 | int c=0; 6 | for(int i=n-1;i>=0;i--){ 7 | if(s[i]==' ') n--; 8 | else break; 9 | } 10 | for(int i=n-1;i>=0;i--){ 11 | if(s[i]!=' ') c++; 12 | else break; 13 | } 14 | return c; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /src/cpp/letter-combination-of-a-phone-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(string digit, string output, int index, vector& ans, string mapping[] ) { 4 | 5 | //base case 6 | if(index >= digit.length()) { 7 | ans.push_back(output); 8 | return; 9 | } 10 | 11 | int number = digit[index] - '0'; 12 | string value = mapping[number]; 13 | 14 | for(int i=0; i letterCombinations(string digits) { 23 | vector ans; 24 | if(digits.length()==0) 25 | return ans; 26 | string output; 27 | int index = 0; 28 | string mapping[10] = {"", "", "abc", "def", "ghi", "jkl","mno","pqrs","tuv","wxyz"}; 29 | solve(digits, output, index, ans, mapping); 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /src/cpp/linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | ListNode *detectCycle(ListNode *head) 10 | { 11 | ListNode *slow = head; 12 | ListNode *fast = head; 13 | if (head == NULL || head->next == NULL) 14 | return NULL; 15 | while (fast != NULL && fast->next != NULL) 16 | { 17 | slow = slow->next; 18 | fast = fast->next->next; 19 | if (fast == slow) 20 | { 21 | fast = head; 22 | while (fast != slow) 23 | { 24 | fast = fast->next; 25 | slow = slow->next; 26 | } 27 | return slow; 28 | } 29 | } 30 | return NULL; 31 | } 32 | }; 33 | /* 34 | |---------------------------------------------------| 35 | ||| https://codeforces.com/profile/codechaser ||| 36 | ||| https://www.codechef.com/users/codechaser ||| 37 | ||| https://github.com/code-chaser ||| 38 | |---------------------------------------------------| 39 | */ -------------------------------------------------------------------------------- /src/cpp/longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/longest-consecutive-sequence/ 2 | 3 | class Solution { 4 | public: 5 | int longestConsecutive(vector& nums) { 6 | int max_len = 0; 7 | unordered_set num_set(nums.begin(), nums.end()); 8 | for (int num : nums) { 9 | if (num_set.find(num - 1) == num_set.end()) { 10 | int curr_num = num; 11 | int curr_len = 1; 12 | while (num_set.find(curr_num + 1) != num_set.end()) { 13 | curr_num++; 14 | curr_len++; 15 | } 16 | max_len = max(max_len, curr_len); 17 | } 18 | } 19 | return max_len; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /src/cpp/lowest-common-ancestor-of-a-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode* ans; 13 | bool helper(TreeNode* root, TreeNode* p, TreeNode* q){ 14 | if(!root){ 15 | return false; 16 | } 17 | bool left = helper(root->left,p,q); 18 | bool right = helper(root->right,p,q); 19 | if(left&&right){ 20 | ans = root; 21 | return false; 22 | } 23 | if(root->val==p->val || root->val==q->val){ 24 | if(left || right){ 25 | ans = root; 26 | return false; 27 | } 28 | else { 29 | return true; 30 | } 31 | } 32 | return left || right; 33 | } 34 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 35 | ans = NULL; 36 | helper(root,p,q); 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /src/cpp/majority-element-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector majorityElement(vector& nums) { 4 | unordered_mapm; 5 | int n=nums.size()/3; 6 | for(int i=0;iv; 10 | for(int i=0;in){ 12 | v.push_back(nums[i]); 13 | } 14 | } 15 | unordered_mapm2; 16 | vectorans; 17 | for(int i=0;i& nums) { 4 | unordered_mapm; 5 | for(int i=0;i(nums.size()/2)){ 12 | ans=nums[i]; 13 | } 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /src/cpp/maximal-rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& arr) { 4 | stacks; 5 | int n=arr.size(); 6 | vector rl(n); 7 | rl[n-1]=n; 8 | s.push(n-1); 9 | for(int i=n-2;i>=0;i--){ 10 | while(!s.empty() && arr[s.top()]>=arr[i]){ 11 | s.pop(); 12 | } 13 | if(s.empty()){ 14 | rl[i]=n; 15 | } 16 | else{ 17 | rl[i]=s.top(); 18 | } 19 | s.push(i); 20 | } 21 | stacks1; 22 | vector ll(n); 23 | ll[0]=-1; 24 | s1.push(0); 25 | for(int i=1;i=arr[i]){ 27 | s1.pop(); 28 | } 29 | if(s1.empty()){ 30 | ll[i]=-1; 31 | } 32 | else{ 33 | ll[i]=s1.top(); 34 | } 35 | s1.push(i); 36 | } 37 | int ans=0; 38 | for(int i=0;i>& arr) { 44 | int m=arr.size(); 45 | if(m==0){ 46 | return 0; 47 | } 48 | int n=arr[0].size(); 49 | if(n==0){ 50 | return 0; 51 | } 52 | vector> ans(m,vector(n,0)); 53 | int maximal=0; 54 | for(int i=0;i& p, vector& t) { 6 | sort(p.begin(),p.end()); 7 | int ans = 0; 8 | multiset s; 9 | for(auto x: t){ 10 | s.insert(x); 11 | } 12 | for(auto x: p){ 13 | auto it = s.lower_bound(x); 14 | if(it == s.end()) break; 15 | ans++; 16 | s.erase(it); 17 | } 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /src/cpp/maximum-points-you-can-obtain-from-cards.cpp: -------------------------------------------------------------------------------- 1 | 2 | //https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ 3 | 4 | class Solution { 5 | public: 6 | int maxScore(vector& nums, int k) { 7 | int n = nums.size(); 8 | if(k >= n){ 9 | return accumulate(nums.begin(),nums.end(),0); 10 | } 11 | int sum = accumulate(nums.begin(),nums.end(),0); 12 | int win = n-k; 13 | int minsum = INT_MAX, csum = 0; 14 | int i=0, j=0; 15 | while(j& nums) { 7 | int maxdiff=0; 8 | sort(nums.begin(),nums.end()); 9 | int n = nums.size(); 10 | maxdiff = abs(nums[0]*nums[1] - nums[n-1]*nums[n-2]); 11 | return maxdiff; 12 | } 13 | }; -------------------------------------------------------------------------------- /src/cpp/maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int currSum=0; 5 | int maxSum=INT_MIN; 6 | for(int i=0;imaxSum){ 9 | maxSum=currSum; 10 | } 11 | if(currSum<0) currSum=0; 12 | } 13 | return maxSum; 14 | } 15 | 16 | }; 17 | -------------------------------------------------------------------------------- /src/cpp/maximum-sum-of-two-non-overlapping-subarrays.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/ 2 | 3 | class Solution { 4 | public: 5 | int maxSumTwoNoOverlap(vector& nums, int a, int b) { 6 | int n = nums.size(); 7 | vector pref(n + 1); 8 | pref[0] = nums[0]; 9 | for (int i = 1; i < n; i++) { 10 | // calculating prefix sum 11 | pref[i] = pref[i - 1] + nums[i]; 12 | } 13 | int ans = -1e9; 14 | // considering a always comes before b. 15 | 16 | // simply move the segment b and maximize segment a on the way 17 | int curr = pref[a - 1]; 18 | for (int i = a; i < n; i++) { 19 | //considering second array to its right 20 | if (i + b <= n) { 21 | int second_sublist_pos = i + b - 1; 22 | int discarding_first_sublist_sum = i - 1; 23 | ans = max(ans, pref[second_sublist_pos] - pref[discarding_first_sublist_sum] + curr); 24 | } 25 | // updating curr if its smaller than its next sub array of length a 26 | curr = max(curr, pref[i] - pref[i - a]); 27 | } 28 | // swap a and b 29 | swap(a, b); 30 | curr = pref[a - 1]; 31 | for (int i = a; i < n; i++) { 32 | if (i + b <= n) { 33 | ans = max(ans, pref[i + b - 1] - pref[i - 1] + curr); 34 | } 35 | curr = max(curr, pref[i] - pref[i - a]); 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /src/cpp/merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { //brute force 4 | int n = intervals.size(); 5 | if(n == 1) return intervals; 6 | vector> ans; 7 | 8 | sort(intervals.begin() , intervals.end()); 9 | 10 | vector curr = intervals[0]; 11 | for(int i=1 ; i= intervals[i][0]) curr[1] = max(curr[1] , intervals[i][1]); 13 | else{ 14 | ans.push_back(curr); 15 | curr = intervals[i]; 16 | } 17 | } 18 | ans.push_back(curr); 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /src/cpp/merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void merge(vector& nums1, int m, vector& nums2, int n) { 5 | vectorans(m+n); 6 | int a1,a2; 7 | a1=a2=0; 8 | while(a1!=m&& a2!=n){ 9 | if(nums1[a1]val < l2->val) 21 | { 22 | result = l1; 23 | result->next = mergeTwoLists(l1->next, l2); 24 | } 25 | else 26 | { 27 | result = l2; 28 | result->next = mergeTwoLists(l1, l2->next); 29 | } 30 | return result; 31 | } 32 | }; 33 | /* 34 | |---------------------------------------------------| 35 | ||| https://codeforces.com/profile/codechaser ||| 36 | ||| https://www.codechef.com/users/codechaser ||| 37 | ||| https://github.com/code-chaser ||| 38 | |---------------------------------------------------| 39 | */ -------------------------------------------------------------------------------- /src/cpp/middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* slow = head; 15 | ListNode* fast = head; 16 | 17 | while(true){ 18 | if(fast == nullptr || fast->next == nullptr){ 19 | return slow; 20 | } 21 | slow = slow->next; 22 | fast = fast->next->next; 23 | } 24 | } 25 | }; -------------------------------------------------------------------------------- /src/cpp/minimum-absolute-difference-in-bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int getMinimumDifference(TreeNode* root) { 15 | int m; 16 | TreeNode *p; 17 | m=INT_MAX; 18 | p=NULL; 19 | func(root, p, m); 20 | return m; 21 | } 22 | void func(TreeNode *n, TreeNode *(&p), int &m) 23 | { 24 | if(!n) 25 | return; 26 | func(n->left, p, m); 27 | if(p) 28 | m=min(m, abs(p->val-n->val)); 29 | p=n; 30 | func(n->right, p, m); 31 | } 32 | }; -------------------------------------------------------------------------------- /src/cpp/minimum-distance-between-bst-nodes.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int minDiffInBST(TreeNode* root) { 15 | int m; 16 | TreeNode *p; 17 | m=INT_MAX; 18 | p=NULL; 19 | func(root, p, m); 20 | return m; 21 | } 22 | void func(TreeNode *n, TreeNode *(&p), int &m) 23 | { 24 | if(!n) 25 | return; 26 | func(n->left, p, m); 27 | if(p && m>(n->val-p->val)) 28 | m=n->val-p->val; 29 | p=n; 30 | func(n->right, p, m); 31 | } 32 | }; -------------------------------------------------------------------------------- /src/cpp/minimum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int minPathSum(vector>& grid) { 5 | vector> dp(grid); 6 | int r = grid.size(); 7 | int c = grid[0].size(); 8 | for(int i = 0; i= 0 && j-1 >= 0) 11 | dp[i][j] += min(dp[i-1][j], dp[i][j-1]); 12 | else{ 13 | if(i-1>=0) 14 | dp[i][j] += dp[i-1][j]; 15 | if(j-1>= 0) 16 | dp[i][j] += dp[i][j-1]; 17 | } 18 | } 19 | } 20 | 21 | return dp[r-1][c-1]; 22 | } 23 | }; -------------------------------------------------------------------------------- /src/cpp/minimum-time-to-make-rope-colorful.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minCost(string colors, vector& nt) { 5 | int n=colors.size(); 6 | if(n==1) return 0; 7 | int ans=0,csum=nt[0],cmax=nt[0]; 8 | char prev=colors[0]; 9 | for(int i=1;i& nums) { 4 | int nonzero=1; 5 | int n=nums.size(); 6 | for(int i=0;i& nums) { 4 | if(nums.size()==0 || nums.size()==1) 5 | return; 6 | int i,j,f=1; 7 | for(i=nums.size()-2;i>=0;i--){ 8 | if(nums[i]i;j--){ 18 | if(nums[j]>nums[i]) 19 | break; 20 | } 21 | swap(nums[i],nums[j]); 22 | reverse(nums.begin()+i+1,nums.end()); 23 | } 24 | } 25 | 26 | }; 27 | -------------------------------------------------------------------------------- /src/cpp/number-complement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findComplement(int num) { 4 | int temp=0; 5 | int comp=0; 6 | int place=0; 7 | while (num!=0) 8 | { 9 | temp=!(num&1); 10 | num=num>>1; 11 | comp=comp+(temp*pow(2,place)); 12 | place++; 13 | } 14 | return comp; 15 | } 16 | }; -------------------------------------------------------------------------------- /src/cpp/number-of-dice-rolls-With-target-sum.cpp: -------------------------------------------------------------------------------- 1 | // Solution Link - https://leetcode.com/submissions/detail/813414108/ 2 | class Solution 3 | { 4 | public: 5 | long long int MOD = 1000000007; 6 | 7 | int helper(int i, int n, int k, int target,int curr_sum, vector> &dp) 8 | { 9 | if(i == n+1 and curr_sum == target) return 1; 10 | 11 | if(i>n || curr_sum>target) return 0; 12 | 13 | if(dp[i][curr_sum] != -1) return dp[i][curr_sum]; 14 | 15 | int combinations = 0; 16 | 17 | for(int j=1;j<=k;j++) 18 | { 19 | combinations = (combinations + helper(i+1,n,k,target,curr_sum+j,dp)) % MOD; 20 | } 21 | 22 | return dp[i][curr_sum] = combinations; 23 | } 24 | 25 | int numRollsToTarget(int n, int k, int target) 26 | { 27 | vector> dp(max(n,k)+1,vector (target+1,-1)); 28 | return helper(1,n,k,target,0,dp); 29 | } 30 | }; -------------------------------------------------------------------------------- /src/cpp/number-of-good-pairs.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | int numIdenticalPairs(vector& nums) { 7 | map m; 8 | for(int i=0;i>& grid){ 5 | if(x<0 || y<0 || x>=grid.size() || y>=grid[0].size()) 6 | return; 7 | if(grid[x][y]!='1' || grid[x][y]=='2')return; 8 | grid[x][y]='2'; 9 | mem++; 10 | dfs(x+1,y,grid); 11 | dfs(x,y+1,grid); 12 | dfs(x-1,y,grid); 13 | dfs(x,y-1,grid); 14 | } 15 | int numIslands(vector>& grid) { 16 | int n=grid.size(),m=grid[0].size(); 17 | int ans=0; 18 | for(int i=0;inext; 15 | while (curr && curr->next) 16 | { 17 | ListNode *even = odd->next; 18 | odd->next = curr->next; 19 | odd = odd->next; 20 | curr->next = odd->next; 21 | odd->next = even; 22 | curr = curr->next; 23 | } 24 | return head; 25 | } 26 | }; 27 | /* 28 | |---------------------------------------------------| 29 | ||| https://codeforces.com/profile/codechaser ||| 30 | ||| https://www.codechef.com/users/codechaser ||| 31 | ||| https://github.com/code-chaser ||| 32 | |---------------------------------------------------| 33 | */ -------------------------------------------------------------------------------- /src/cpp/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | string s = to_string(x); 5 | int start = 0; 6 | int end = s.length() - 1; 7 | 8 | while(start < end) 9 | { 10 | if(s[start++] != s[end--]) 11 | return false; 12 | } 13 | 14 | return true; 15 | } 16 | }; 17 | 18 | // Submission- https://leetcode.com/submissions/detail/814241551/ 19 | -------------------------------------------------------------------------------- /src/cpp/palindrome-partitioning.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/palindrome-partitioning/ 2 | 3 | 4 | class Solution { 5 | public: 6 | vector> ans; 7 | bool ispal(string s){ 8 | if(s.size() == 1) return true; 9 | string temp = s; 10 | reverse(temp.begin(),temp.end()); 11 | return temp.compare(s) == 0 ? true : false; 12 | } 13 | void func(string s,int i,int j, vector &temp){ 14 | if(j==s.size() && i==s.size()){ 15 | ans.push_back(temp); 16 | return; 17 | } 18 | if(j==s.size()){ 19 | return; 20 | } 21 | string sub = s.substr(i,j-i+1); 22 | if(ispal(sub)){ 23 | temp.push_back(sub); 24 | func(s,j+1,j+1,temp); 25 | temp.pop_back(); 26 | func(s,i,j+1,temp); 27 | } 28 | else{ 29 | func(s,i,j+1,temp); 30 | } 31 | } 32 | vector> partition(string s) { 33 | vector temp; 34 | ans.clear(); 35 | func(s,0,0,temp); 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /src/cpp/partition-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | ListNode *partition(ListNode *head, int x) 10 | { 11 | if (head != nullptr && head->next != nullptr) 12 | { 13 | ListNode *curr = head; 14 | ListNode *prev = nullptr; 15 | ListNode *flag = nullptr; 16 | ListNode *temp; 17 | while (curr != nullptr) 18 | { 19 | temp = curr->next; 20 | if (curr->val >= x) 21 | prev = curr; 22 | else 23 | { 24 | if (flag == prev) 25 | { 26 | flag = curr; 27 | prev = curr; 28 | } 29 | else 30 | { 31 | prev->next = temp; 32 | if (flag == nullptr) 33 | { 34 | curr->next = head; 35 | head = curr; 36 | flag = head; 37 | } 38 | else 39 | { 40 | curr->next = flag->next; 41 | flag->next = curr; 42 | flag = flag->next; 43 | } 44 | } 45 | } 46 | curr = temp; 47 | } 48 | } 49 | return head; 50 | } 51 | }; 52 | /* 53 | |---------------------------------------------------| 54 | ||| https://codeforces.com/profile/codechaser ||| 55 | ||| https://www.codechef.com/users/codechaser ||| 56 | ||| https://github.com/code-chaser ||| 57 | |---------------------------------------------------| 58 | */ -------------------------------------------------------------------------------- /src/cpp/path-sum-ii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void f(vector>&ans,vectorvec,int targetSum,TreeNode*root){ 15 | if(root==NULL)return; 16 | vec.push_back(root->val); 17 | targetSum-=root->val; 18 | if(root->left==NULL&&root->right==NULL&&targetSum==0){ 19 | 20 | ans.push_back(vec); 21 | 22 | return ; 23 | } 24 | 25 | 26 | 27 | 28 | 29 | f(ans,vec,targetSum,root->left); 30 | 31 | f(ans,vec,targetSum,root->right); 32 | vec.pop_back(); 33 | 34 | 35 | } 36 | 37 | vector> pathSum(TreeNode* root, int targetSum) { 38 | vector>ans; 39 | vectorvec; 40 | f(ans,vec,targetSum,root);return ans; 41 | } 42 | }; 43 | // https://leetcode.com/submissions/detail/807215142/ -------------------------------------------------------------------------------- /src/cpp/path-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool hasPathSum(TreeNode* root, int targetSum) { 15 | if(root==NULL){ 16 | 17 | return false; 18 | } 19 | if(root->left==NULL&&root->right==NULL){ 20 | if(targetSum-root->val==0){ 21 | return true; 22 | } 23 | } 24 | return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val); 25 | 26 | } 27 | }; 28 | // https://leetcode.com/submissions/detail/809847376/ -------------------------------------------------------------------------------- /src/cpp/peak-index-in-a-mountain-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& arr) { 4 | int s=0; 5 | int e=arr.size()-1; 6 | while(s>1; 21 | } 22 | if(base<0) 23 | return 1/ans; 24 | else 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /src/cpp/product-of-array-except-self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | vectorprefix_pro(nums.size()); 5 | prefix_pro[0]=nums[0]; 6 | for(int i=1;isufix_pro(nums.size()); 11 | sufix_pro[nums.size()-1]=nums[nums.size()-1]; 12 | for(int i=nums.size()-2;i>=0;i--){ 13 | sufix_pro[i]=sufix_pro[i+1]*nums[i]; 14 | } 15 | vectorans(nums.size()); 16 | 17 | for(int i=0;ival) 25 | { 26 | func(root->left, low, high, s); 27 | return; 28 | } 29 | if(low>root->val) 30 | { 31 | func(root->right, low, high, s); 32 | return; 33 | } 34 | s+=root->val; 35 | func(root->left, low, high, s); 36 | func(root->right, low, high, s); 37 | } 38 | }; -------------------------------------------------------------------------------- /src/cpp/ransom-note.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) { 4 | int acount[26]={0}; 5 | int bcount[26]={0}; 6 | for(int i=0;ibcount[i]){ 17 | return false; 18 | } 19 | } 20 | } 21 | return true; 22 | } 23 | }; -------------------------------------------------------------------------------- /src/cpp/recover-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void recoverTree(TreeNode* root) { 15 | TreeNode *p, *f, *m, *l; 16 | p=NULL; 17 | f=NULL; 18 | m=NULL; 19 | l=NULL; 20 | func(root, p, f, m, l); 21 | if(l) 22 | swap(f->val, l->val); 23 | else 24 | swap(f->val, m->val); 25 | } 26 | void func(TreeNode *n, TreeNode *(&p), TreeNode *(&f), TreeNode *(&m), TreeNode *(&l)) 27 | { 28 | if(!n) 29 | return; 30 | func(n->left, p, f, m, l); 31 | if(p && n->valval) 32 | { 33 | if(!m) 34 | { 35 | f=p; 36 | m=n; 37 | } 38 | else 39 | l=n; 40 | } 41 | p=n; 42 | func(n->right, p, f, m, l); 43 | } 44 | }; -------------------------------------------------------------------------------- /src/cpp/reduce-array-size-to-the-half.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1338. Reduce Array Size to The Half 3 | You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. 4 | Return the minimum size of the set so that at least half of the integers of the array are removed. 5 | 6 | Example: 7 | Input: arr = [3,3,3,3,5,5,5,2,2,7] 8 | Output: 2 9 | Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array). 10 | Possible sets of size 2 are {3,5},{3,2},{5,2}. 11 | Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array. 12 | 13 | Example2: 14 | Input: arr = [7,7,7,7,7,7] 15 | Output: 1 16 | Explanation: The only possible set you can choose is {7}. This will make the new array empty. 17 | 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | int minSetSize(vector& arr) { 26 | unordered_map map; 27 | int n=arr.size(); 28 | for(int i=0;i frequency; 32 | for(auto it:map){ 33 | frequency.push_back(it.second); 34 | } 35 | sort(frequency.begin(),frequency.end()); 36 | int ans=0; 37 | int check=n/2; 38 | for(int l=frequency.size()-1;l>=0;l--){ 39 | if(n-frequency[l]<=check){ 40 | ans++; 41 | break; 42 | }else{ 43 | n-=frequency[l]; 44 | ans++; 45 | } 46 | } 47 | return ans; 48 | } 49 | }; -------------------------------------------------------------------------------- /src/cpp/regular-expression-matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | int m=s.length(); 5 | int n=p.length(); 6 | bool** ans=new bool*[m+1]; 7 | for(int i=0;i>stk; 5 | for(int i=0;i=1;i--){ 11 | stk.pop(); 12 | } 13 | } 14 | else{ 15 | stk.push({s[i],x}); 16 | } 17 | } 18 | else{ 19 | stk.push({s[i],1}); 20 | } 21 | } 22 | string ans=""; 23 | while(stk.empty()==false){ 24 | ans.push_back(stk.top().first); 25 | stk.pop(); 26 | } 27 | reverse(ans.begin(),ans.end()); 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/cpp/remove-all-adjacent-duplicates-in-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) { 4 | string ans; 5 | for(int i=0;i& nums) { 6 | int n = nums.size(), j = 1; 7 | for(int i = 1; i < n; i++) 8 | { 9 | if(nums[i] != nums[i-1]) 10 | { 11 | nums[j++] = nums[i]; 12 | } 13 | } 14 | return j; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /src/cpp/reordered-power-of-2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector digitcount(int n){ 4 | vectorcnt(10); 5 | while(n){ 6 | cnt[n%10]++; 7 | n/=10; 8 | } 9 | return cnt; 10 | } 11 | bool reorderedPowerOf2(int n) { 12 | if(!(n&(n-1))) return 1; 13 | vectort=digitcount(n); 14 | for(int i=0;i<31;i++){ 15 | vectorx=digitcount((1< INT_MAX/10) return 0; 14 | 15 | num*=10; 16 | num=(num+z);temp/=10; 17 | } 18 | // if(num==INT_MAX && sign==-1) return 0; 19 | return num*sign; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /src/cpp/reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | ListNode *reverseList(ListNode *head) 10 | { 11 | ListNode *last = head, *lastToLast = NULL, *temp; 12 | while (last != NULL) 13 | { 14 | temp = last->next; 15 | last->next = lastToLast; 16 | lastToLast = last; 17 | last = temp; 18 | } 19 | return lastToLast; 20 | } 21 | }; 22 | /* 23 | |---------------------------------------------------| 24 | ||| https://codeforces.com/profile/codechaser ||| 25 | ||| https://www.codechef.com/users/codechaser ||| 26 | ||| https://github.com/code-chaser ||| 27 | |---------------------------------------------------| 28 | */ -------------------------------------------------------------------------------- /src/cpp/reverse-nodes-in-k-group.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | ListNode *reverseKGroup(ListNode *head, int k) 10 | { 11 | ListNode *prev = NULL; 12 | ListNode *curr = head; 13 | ListNode *next; 14 | int count = 0; 15 | ListNode *temp = head; 16 | int c = 0; 17 | while (c < k && temp != NULL) 18 | { 19 | temp = temp->next; 20 | c++; 21 | } 22 | if (c < k) 23 | return curr; 24 | while (curr != NULL && count < k) 25 | { 26 | next = curr->next; 27 | curr->next = prev; 28 | prev = curr; 29 | curr = next; 30 | count++; 31 | } 32 | if (next != NULL) 33 | head->next = reverseKGroup(next, k); 34 | return prev; 35 | } 36 | }; 37 | /* 38 | |---------------------------------------------------| 39 | ||| https://codeforces.com/profile/codechaser ||| 40 | ||| https://www.codechef.com/users/codechaser ||| 41 | ||| https://github.com/code-chaser ||| 42 | |---------------------------------------------------| 43 | */ -------------------------------------------------------------------------------- /src/cpp/richest-customer-wealth.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | int maximumWealth(vector>& accounts) { 7 | int m,n,max=0,sum=0; 8 | m = accounts.size(); 9 | n = accounts[0].size(); 10 | for(int i=0;imax){ 15 | max = sum; 16 | } 17 | sum = 0; 18 | } 19 | 20 | return max; 21 | } 22 | }; -------------------------------------------------------------------------------- /src/cpp/roman-to-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int getTranslateNum(char s) { 3 | switch(s) { 4 | case 'I': return 1; 5 | case 'V': return 5; 6 | case 'X': return 10; 7 | case 'L': return 50; 8 | case 'C': return 100; 9 | case 'D': return 500; 10 | case 'M': return 1000; 11 | default: return 0; 12 | } 13 | return 0; 14 | } 15 | public: 16 | int romanToInt(string s) { 17 | if(s.empty()) return 0; 18 | int returnValue = 0; 19 | for(unsigned int i=0; i& nums, int k) { 4 | int n=nums.size(); 5 | vector temp(n); 6 | for(int i=0;i& nums, int k) { 4 | vector temp(nums.size()); 5 | 6 | for(int i=0;i>& matrix) { 12 | int n=matrix.size(); 13 | for(int i=0;inext == NULL) 12 | return head; 13 | ListNode *node1 = head; 14 | ListNode *node2 = NULL; 15 | int count = 1; 16 | while (node1->next != NULL) 17 | { 18 | node2 = node1; 19 | node1 = node1->next; 20 | count++; 21 | } 22 | k = (k >= count ? k % count : k); 23 | for (int i = 0; i < k; i++) 24 | { 25 | node1->next = head; 26 | head = node1; 27 | node2->next = NULL; 28 | while (node1->next != NULL) 29 | { 30 | node2 = node1; 31 | node1 = node1->next; 32 | } 33 | } 34 | return head; 35 | } 36 | }; 37 | /* 38 | |---------------------------------------------------| 39 | ||| https://codeforces.com/profile/codechaser ||| 40 | ||| https://www.codechef.com/users/codechaser ||| 41 | ||| https://github.com/code-chaser ||| 42 | |---------------------------------------------------| 43 | */ -------------------------------------------------------------------------------- /src/cpp/rotting-oranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; 4 | int orangesRotting(vector>&arr) { 5 | int m=arr.size(); 6 | int n=arr[0].size(); 7 | int time=0; 8 | queue>q; 9 | for(int i=0;icurr=q.front(); 21 | q.pop(); 22 | for(int j=0;j<4;j++){ 23 | int r=curr.first+dir[j][0]; 24 | int c=curr.second+dir[j][1]; 25 | if(r<0||c<0||r>m-1||c>n-1||arr[r][c]!=1) 26 | continue; 27 | q.push({r,c}); 28 | arr[r][c]=-1; 29 | } 30 | } 31 | time++; 32 | } 33 | for(int i=0;i runningSum(vector& nums) { 7 | vector ans; 8 | int n = nums.size(); 9 | int sum=0; 10 | for(int i=0;ileft,q->left)&&isSameTree(p->right,q->right)&&p->val==q->val; 22 | } 23 | }; 24 | //sumittion https://leetcode.com/submissions/detail/803842022/ -------------------------------------------------------------------------------- /src/cpp/satisfiability-of-equality-equations.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/satisfiability-of-equality-equations/ 2 | 3 | class Solution { 4 | public: 5 | int findParent(int g,vector &p){ 6 | if(p[g] == g){ 7 | return g; 8 | } 9 | return p[g] = findParent(p[g],p); 10 | } 11 | void unionn(int a,int b,vector &p,vector &rank){ 12 | if(p[a] == p[b]) return; 13 | 14 | int pa = findParent(a,p); 15 | int pb = findParent(b,p); 16 | 17 | if(pa == pb) return; 18 | if(rank[pa] == rank[pb]){ 19 | p[pb] = pa; 20 | rank[pa]++; 21 | } 22 | else if(rank[pa] < rank[pb]){ 23 | p[pa] = pb; 24 | } 25 | else{ 26 | p[pb] = pa; 27 | } 28 | } 29 | bool equationsPossible(vector& equations) { 30 | vector p(26), rank(26,0); 31 | for(int i=0; i<26; i++) p[i]=i; 32 | 33 | for(auto x: equations){ 34 | if(x[1] == '='){ 35 | unionn(x[0]-'a', x[3]-'a', p, rank); 36 | } 37 | } 38 | for(auto x: equations){ 39 | if(x[1] == '!'){ 40 | int a = findParent(x[0]-'a',p); 41 | int b = findParent(x[3]-'a',p); 42 | if(a == b) return false; 43 | } 44 | } 45 | return true; 46 | } 47 | }; -------------------------------------------------------------------------------- /src/cpp/scramble-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isScramble(string s1, string s2) { 4 | int len=s1.size(); 5 | bool ans[len][len][len+1]; 6 | for(int k=1;k<=len+1;k++){ 7 | for(int i=0;i+k<=len;i++){ 8 | for(int j=0;j+k<=len;j++){ 9 | if(k==1){ 10 | ans[i][j][k]=(s1[i]==s2[j]); 11 | } 12 | else{ 13 | for(int q=1;q>& matrix, int target) { 4 | int rows=matrix.size(); 5 | int col=matrix[0].size(); 6 | int i=0; 7 | int j=col-1; 8 | while(i=0){ 9 | if(matrix[i][j]==target) 10 | return 1; 11 | else if(matrix[i][j]>target) 12 | j--; 13 | else 14 | i++; 15 | } 16 | return 0; 17 | } 18 | }; -------------------------------------------------------------------------------- /src/cpp/search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool bsearch(vector> arr,int line,int n,int target){ 4 | int start,end; 5 | start=0; 6 | end=n-1; 7 | int mid=start+(end-start)/2; 8 | while(start<=end){ 9 | if(arr[line][mid]==target){ 10 | return 1; 11 | } 12 | else if(arr[line][mid]> arr, int rows,int target){ 22 | int ans=-1; 23 | int start=0; 24 | int end=rows-1; 25 | int mid=start+(end-start)/2; 26 | while(start<=end){ 27 | if(arr[mid][0]>target){ 28 | end=mid-1; 29 | } 30 | else{ 31 | ans=mid; 32 | start=mid+1; 33 | } 34 | mid=start+(end-start)/2; 35 | } 36 | return ans; 37 | } 38 | bool searchMatrix(vector>& matrix, int target) { 39 | int rows=matrix.size(); 40 | int col=matrix[0].size(); 41 | if(targetmatrix[rows-1][col-1]) 42 | return 0; 43 | for(int i=0;i& nums, int target, int s, int e){ 6 | while(s<=e){ 7 | int mid = s + (e-s)/2; 8 | if(nums[mid] == target) 9 | return mid; 10 | if(nums[mid]>target) 11 | e = mid - 1; 12 | else 13 | s = mid + 1; 14 | } 15 | return -1; 16 | } 17 | 18 | int search(vector& nums, int target) { 19 | int n = nums.size(); 20 | int l = 0, r = n-1; 21 | 22 | while(lnums[r]) 25 | l = mid+1; 26 | else 27 | r = mid; 28 | } 29 | 30 | if(target<=nums[n-1]) 31 | return bin_search(nums, target, l, n-1); 32 | else 33 | return bin_search(nums, target, 0, l-1); 34 | } 35 | }; -------------------------------------------------------------------------------- /src/cpp/serialize-and-deserialize-bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Codec { 11 | public: 12 | 13 | // Encodes a tree to a single string. 14 | string serialize(TreeNode* root) { 15 | string s; 16 | s=""; 17 | func1(root, s); 18 | return s; 19 | } 20 | void func1(TreeNode *n, string &s) 21 | { 22 | if(!n) 23 | { 24 | s+="$,"; 25 | return; 26 | } 27 | s+=to_string(n->val); 28 | s+=","; 29 | func1(n->left, s); 30 | func1(n->right, s); 31 | } 32 | 33 | // Decodes your encoded data to tree. 34 | TreeNode* deserialize(string data) { 35 | int i; 36 | i=0; 37 | return func2(data, i); 38 | } 39 | TreeNode *func2(string &s, int &i) 40 | { 41 | string n; 42 | n=""; 43 | while(s[i]!=',') 44 | { 45 | n+=s[i]; 46 | i++; 47 | } 48 | i++; 49 | if(n=="$") 50 | return NULL; 51 | TreeNode *root=new TreeNode(stoi(n)); 52 | root->left=func2(s, i); 53 | root->right=func2(s, i); 54 | return root; 55 | } 56 | }; 57 | 58 | // Your Codec object will be instantiated and called as such: 59 | // Codec* ser = new Codec(); 60 | // Codec* deser = new Codec(); 61 | // string tree = ser->serialize(root); 62 | // TreeNode* ans = deser->deserialize(tree); 63 | // return ans; -------------------------------------------------------------------------------- /src/cpp/set-matrix-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | int m = matrix.size(); 5 | int n = matrix[0].size(); 6 | vector d1(m,-1); 7 | vector d2(n,-1); 8 | 9 | for(int i=0 ; i& indices) { 7 | string res=s; 8 | 9 | for(int i=0; i st; 6 | string res; 7 | 8 | for(int i = 0; i getOrder(vector>& tasks) { 6 | priority_queue,vector>,greater>> opq; 7 | priority_queue,vector>,greater>> pq; 8 | int n = tasks.size(); 9 | if(n == 0) return {}; 10 | vector ans; 11 | for(int k=0;k= opq.top()[0]){ 17 | pq.push({opq.top()[1],opq.top()[2]}); 18 | opq.pop(); 19 | } 20 | if(!pq.empty()){ 21 | auto tp = pq.top(); 22 | pq.pop(); 23 | t += tp.first; 24 | ans.push_back(tp.second); 25 | } 26 | else{ 27 | t = int(opq.top()[0]); 28 | } 29 | } 30 | while(!pq.empty()){ 31 | auto tp = pq.top(); 32 | pq.pop(); 33 | t += tp.first; 34 | ans.push_back(tp.second); 35 | } 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /src/cpp/sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int low = 0; 5 | int mid = 0; 6 | int high = nums.size()-1; 7 | 8 | while(mid <= high){ 9 | if(nums[mid] == 0){ 10 | swap(nums[low],nums[mid]); 11 | low++; 12 | mid++; 13 | } 14 | else if(nums[mid] == 1){ 15 | mid++; 16 | } 17 | else{ 18 | swap(nums[mid],nums[high]); 19 | high--; 20 | } 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /src/cpp/sort-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : codechaser||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | class Solution 7 | { 8 | public: 9 | void mergesorting(ListNode **head) 10 | { 11 | ListNode *curr = *head; 12 | ListNode *first; 13 | ListNode *second; 14 | if (!curr || !curr->next) 15 | return; 16 | findmid(curr, &first, &second); 17 | mergesorting(&first); 18 | mergesorting(&second); 19 | *head = mergeboth(first, second); 20 | } 21 | ListNode *sortList(ListNode *head) 22 | { 23 | mergesorting(&head); 24 | return head; 25 | } 26 | ListNode *mergeboth(ListNode *first, ListNode *second) 27 | { 28 | ListNode *answer = NULL; 29 | if (!first) 30 | return second; 31 | if (!second) 32 | return first; 33 | if (first->val <= second->val) 34 | { 35 | answer = first; 36 | answer->next = mergeboth(first->next, second); 37 | } 38 | else 39 | { 40 | answer = second; 41 | answer->next = mergeboth(first, second->next); 42 | } 43 | return answer; 44 | } 45 | void findmid(ListNode *curr, ListNode **first, ListNode **second) 46 | { 47 | ListNode *fast = curr->next; 48 | ListNode *slow = curr; 49 | while (!fast) 50 | { 51 | fast = fast->next; 52 | if (!fast) 53 | { 54 | fast = fast->next; 55 | slow = slow->next; 56 | } 57 | } 58 | *first = curr; 59 | *second = slow->next; 60 | slow->next = NULL; 61 | } 62 | }; 63 | /* 64 | |---------------------------------------------------| 65 | ||| https://codeforces.com/profile/codechaser ||| 66 | ||| https://www.codechef.com/users/codechaser ||| 67 | ||| https://github.com/code-chaser ||| 68 | |---------------------------------------------------| 69 | */ -------------------------------------------------------------------------------- /src/cpp/spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | vector ans; 7 | int startrow=0; 8 | int startcol=0; 9 | int endrow=n-1; 10 | int endcol=m-1; 11 | int count=0; 12 | int total=n*m; 13 | while(count=startcol && count=startrow && count& s, int count){ 4 | string c=to_string(count); 5 | for(int i=0;i& chars) { 10 | int count=1; 11 | vector s; 12 | s.push_back(chars[0]); 13 | for(int i=1;i1){ 19 | put(s,count); 20 | } 21 | s.push_back(chars[i]); 22 | count=1; 23 | } 24 | } 25 | if(count>1) 26 | put(s,count); 27 | chars=s; 28 | return chars.size(); 29 | } 30 | }; -------------------------------------------------------------------------------- /src/cpp/string-to-integer-atoi.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int myAtoi(string s) { 5 | int i=0,n=s.size(),sign=1; 6 | while(s[i]==' ' && i='0' && s[i]<='9'){ 13 | t=t*10+(s[i]-'0'); 14 | if(sign==1 && t>INT_MAX) return INT_MAX; 15 | if(sign==-1 && -t& nums, int k) { 6 | int cnt = 0; 7 | unordered_map mp; 8 | int curr = 0; 9 | 10 | for(int n : nums){ 11 | curr += n; 12 | if(curr == k) 13 | cnt++; 14 | if(mp[curr-k]) 15 | cnt += mp[curr-k]; 16 | if(mp[curr]) 17 | mp[curr] += 1; 18 | else 19 | mp[curr] = 1; 20 | } 21 | 22 | return cnt; 23 | } 24 | }; -------------------------------------------------------------------------------- /src/cpp/subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(vector nums, vector output, int index, vector>& ans){ 4 | if(index>=nums.size()){ 5 | ans.push_back(output); 6 | return; 7 | } 8 | 9 | //exclude 10 | solve(nums,output,index+1,ans); 11 | 12 | //include 13 | int element=nums[index]; 14 | output.push_back(element); 15 | 16 | solve(nums,output,index+1,ans); 17 | } 18 | public: 19 | vector> subsets(vector& nums) { 20 | vector> ans; 21 | 22 | vector output; 23 | 24 | int index=0; 25 | 26 | solve(nums,output,index,ans); 27 | 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /src/cpp/sum-of-distances-in-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector >adj; 4 | vectoreuler; 5 | vectordp; 6 | vectorst; 7 | void dfs(int x,int p){ 8 | dp[x]=0; 9 | euler.push_back(x); 10 | for(auto i:adj[x]){ 11 | if(i==p)continue; 12 | dfs(i,x); 13 | dp[x]+=dp[i]; 14 | dp[x]+=st[i]; 15 | dp[x]++; 16 | st[x]+=st[i]; 17 | st[x]++; 18 | euler.push_back(x); 19 | } 20 | 21 | } 22 | vector sumOfDistancesInTree(int n, vector>& edges) { 23 | adj=vector >(n); 24 | for(auto p : edges){ 25 | adj[p[0]].push_back(p[1]); 26 | adj[p[1]].push_back(p[0]); 27 | } 28 | dp=vector(n,0); 29 | st=vector(n,0); 30 | euler.clear(); 31 | vectorans(n,0); 32 | dfs(0,0); 33 | 34 | ans[0]=dp[0]; 35 | for(int i=1;inext != nullptr) 15 | result = head->next; 16 | while (head != nullptr && head->next != nullptr) 17 | { 18 | auto forward1 = head->next, forward2 = forward1->next; 19 | if (forward2 != nullptr) 20 | { 21 | if (forward2->next != nullptr) 22 | head->next = forward2->next; 23 | else 24 | head->next = forward2; 25 | } 26 | else 27 | { 28 | head->next = forward2; 29 | } 30 | forward1->next = head; 31 | head = forward2; 32 | } 33 | return result; 34 | } 35 | }; 36 | /* 37 | |---------------------------------------------------| 38 | ||| https://codeforces.com/profile/codechaser ||| 39 | ||| https://www.codechef.com/users/codechaser ||| 40 | ||| https://github.com/code-chaser ||| 41 | |---------------------------------------------------| 42 | */ -------------------------------------------------------------------------------- /src/cpp/symmetric-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool f(TreeNode*ptr,TreeNode*p){ 15 | if(ptr==NULL && p==NULL){ 16 | return true; 17 | } 18 | if(ptr==NULL||p==NULL){ 19 | return false; 20 | } 21 | return ptr->val==p->val&&f(ptr->left,p->right)&&f(ptr->right,p->left); 22 | } 23 | bool isSymmetric(TreeNode* root) { 24 | if(root==NULL){ 25 | return true; 26 | } 27 | 28 | return f(root->left,root->right); 29 | } 30 | }; 31 | 32 | // sumission link https://leetcode.com/submissions/detail/803837894/ -------------------------------------------------------------------------------- /src/cpp/trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3 | --||author : Mitternachtsmond||-- 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | */ 6 | 7 | class Solution 8 | { 9 | public: 10 | int trap(vector& height) { 11 | int n=height.size(); 12 | vectorpremax(n),suffmax(n); 13 | premax[0]=height[0]; 14 | for(int i=1;i=0;i--) suffmax[i]=max(suffmax[i+1],height[i]); 17 | int ans=0; 18 | for(int i=1;iv; 17 | func(root, v); 18 | i=0; 19 | j=v.size()-1; 20 | while(i&v) 32 | { 33 | if(!n) 34 | return; 35 | func(n->left, v); 36 | v.push_back(n->val); 37 | func(n->right, v); 38 | } 39 | }; -------------------------------------------------------------------------------- /src/cpp/two-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Author - Shadowpii 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& nums, int target) { 7 | unordered_map mp; 8 | vector ans; 9 | for (int i = 0; i < nums.size(); i++) 10 | if (mp.count(target - nums[i])) 11 | { 12 | ans.push_back(mp[target - nums[i]]); 13 | ans.push_back(i); 14 | return ans; 15 | } 16 | else 17 | mp[nums[i]] = i; 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /src/cpp/unique-number-of-occurrences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool uniqueOccurrences(vector& arr) { 4 | vector count; 5 | sort(arr.begin(),arr.end()); 6 | int n=arr.size(); 7 | int c=0; 8 | for(int i=0;i> &dp, vector>& grid) 6 | { 7 | if(i>=0 and j>=0 and grid[i][j] == 1) return 0; 8 | if(i==0 and j==0) return 1; 9 | if(i<0 or j<0) return 0; 10 | 11 | if(dp[i][j]!=-1) return dp[i][j]; 12 | 13 | int up = f(i-1,j,dp,grid); 14 | int left = f(i,j-1,dp,grid); 15 | 16 | return dp[i][j] = up+left; 17 | } 18 | 19 | int uniquePathsWithObstacles(vector>& obstacleGrid) 20 | { 21 | int m = obstacleGrid.size(); 22 | int n = obstacleGrid[0].size(); 23 | 24 | vector> dp(m,vector(n,-1)); 25 | 26 | return f(m-1,n-1,dp,obstacleGrid); 27 | } 28 | }; -------------------------------------------------------------------------------- /src/cpp/unique-paths.cpp: -------------------------------------------------------------------------------- 1 | // Solution Link - https://leetcode.com/submissions/detail/762177296/ 2 | class Solution 3 | { 4 | public: 5 | int f(int i, int j, vector> &dp) 6 | { 7 | if(i==0 and j==0) return 1; 8 | if(i<0 or j<0) return 0; 9 | 10 | if(dp[i][j]!=-1) return dp[i][j]; 11 | 12 | int up = f(i-1,j,dp); 13 | int left = f(i,j-1,dp); 14 | 15 | return dp[i][j] = up + left; 16 | } 17 | 18 | int uniquePaths(int m, int n) 19 | { 20 | vector> dp(m, vector (n,-1)); 21 | return f(m-1,n-1,dp); 22 | } 23 | }; -------------------------------------------------------------------------------- /src/cpp/valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-anagram/ 2 | 3 | class Solution { 4 | public: 5 | bool isAnagram(string s, string t) { 6 | unordered_mapmp,mpp; 7 | for(auto i:s)mp[i]++; 8 | for(auto i:t)mpp[i]++; 9 | if(mp!=mpp)return false; 10 | return true; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /src/cpp/validate-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vectorv; 15 | void inorder(TreeNode* root){ 16 | if(root==NULL) return; 17 | inorder(root->left); 18 | v.push_back(root->val); 19 | inorder(root->right); 20 | } 21 | bool isValidBST(TreeNode* root) { 22 | inorder(root); 23 | for(int i=0;i=v[i+1]){ 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/cpp/water-and-jug-problem.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMeasureWater(int a, int b, int c) { 4 | if(c>a+b)return false; 5 | if(c% __gcd(a , b) == 0)return true; 6 | return false; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /src/cpp/word-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool help(vector>& board,int cl,int i,int j,int &r,int &c,int &l,string &word){ 4 | if(cl==l){ 5 | return true; 6 | } 7 | // if(i==r || j==c) return false; 8 | char z=board[i][j]; 9 | board[i][j]='*'; 10 | 11 | if(i>0){ 12 | if(word[cl]==board[i-1][j]) { 13 | if(help(board,cl+1,i-1,j,r,c,l,word)) return true; 14 | } 15 | } 16 | if(j>0){ 17 | if(word[cl]==board[i][j-1]) { 18 | if(help(board,cl+1,i,j-1,r,c,l,word)) return true; 19 | } 20 | } 21 | if(i+1>& board, string word) { 36 | int r=board.size(),c=board[0].size(),l=word.size(); 37 | if(r*c < l) return 0; 38 | for(int i=0;i0 && k=tokens[i]) 20 | { 21 | power-=tokens[i]; 22 | ++score; 23 | ++i; 24 | } 25 | else 26 | { 27 | if(score>0&&i!=j) 28 | { 29 | power+=tokens[j]; 30 | --score; 31 | } 32 | --j; 33 | 34 | } 35 | } 36 | return score>0?score:0; 37 | } 38 | } 39 | 40 | //Submission link:-https://leetcode.com/submissions/detail/798096841/ 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/java/best-time-to-buy-and-sell-stock-with-transaction-fee.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices, int fee) { 3 | int n = prices.length; 4 | int [][] dp = new int[n][2]; 5 | for (int[] tempDp : dp) { 6 | Arrays.fill(tempDp, -1); 7 | } 8 | return maxProfit(prices, fee, 0, false, dp); 9 | } 10 | private int maxProfit(final int[] prices, final int fee, int i, boolean isSelling, int[][] dp) { 11 | 12 | int j = 0; 13 | int n = prices.length; 14 | if (isSelling) { 15 | j = 1; 16 | } 17 | 18 | if (i >= n) { 19 | return 0; 20 | } 21 | else if (dp[i][j] != -1) { 22 | return dp[i][j]; 23 | } 24 | else { 25 | // donot do any transaction on current date 26 | int a = maxProfit(prices, fee, i+1, isSelling, dp); 27 | int b = 0; 28 | if (isSelling) { 29 | // sell a stock 30 | b = maxProfit(prices, fee, i+1, false, dp) + prices[i] - fee; 31 | } 32 | else { 33 | b = maxProfit(prices, fee, i+1, true, dp) - prices[i]; 34 | } 35 | int ans = Math.max(a, b); 36 | dp[i][j] = ans; 37 | return ans; 38 | } 39 | } 40 | } 41 | // Submisssion link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/submissions/664871512/ -------------------------------------------------------------------------------- /src/java/best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | /*Question:-You are given an array prices where prices[i] is the price of a given stock on the ith day. 2 | 3 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 4 | 5 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 6 | 7 | */ 8 | 9 | //Solution 10 | 11 | 12 | class Solution { 13 | public int maxProfit(int[] prices) { 14 | int max = 0; 15 | int min = Integer.MAX_VALUE; 16 | for( int i = 0; i< prices.length; i++){ 17 | min = Math.min(min , prices[i]); 18 | max = Math.max(max , prices[i] - min); 19 | } 20 | return max; 21 | } 22 | } 23 | 24 | //Submission link:-https://leetcode.com/submissions/detail/798948024/ 25 | -------------------------------------------------------------------------------- /src/java/binary-search.java: -------------------------------------------------------------------------------- 1 | // Question - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search 2 | // target in nums. If target exists, then return its index. Otherwise, return -1. 3 | // You must write an algorithm with O(log n) runtime complexity. 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [-1,0,3,5,9,12], target = 9 8 | // Output: 4 9 | // Explanation: 9 exists in nums and its index is 4 10 | 11 | class Solution { 12 | public int search(int[] nums, int target) { 13 | int start = 0; 14 | int end = nums.length - 1; 15 | int mid = start + (end - start)/2; 16 | while (start <= end) { 17 | if(target > mid) { 18 | start = mid + 1; 19 | } else (target < mid) { 20 | end = mid - 1; 21 | } 22 | } 23 | return -1; 24 | 25 | } 26 | } 27 | 28 | // Submission - https://leetcode.com/submissions/detail/790314581/ -------------------------------------------------------------------------------- /src/java/complex-number-multiplication.java: -------------------------------------------------------------------------------- 1 | /*Question:-A complex number can be represented as a string on the form "real+imaginaryi" where: 2 | 3 | real is the real part and is an integer in the range [-100, 100]. 4 | imaginary is the imaginary part and is an integer in the range [-100, 100]. 5 | i2 == -1. 6 | Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.*/ 7 | 8 | 9 | //Solution 10 | 11 | 12 | 13 | class Solution { 14 | public String complexNumberMultiply(String num1, String num2) { 15 | 16 | int a = Integer.parseInt(num1.substring(0,num1.indexOf('+'))); 17 | int b = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1)); 18 | int c = Integer.parseInt(num2.substring(0,num2.indexOf('+'))); 19 | int d = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1)); 20 | 21 | return "" + (a*c - b*d) + "+" + (a*d + c*b)+"i"; 22 | 23 | 24 | } 25 | } 26 | 27 | //Submission link:-https://leetcode.com/submissions/detail/618995919/ 28 | -------------------------------------------------------------------------------- /src/java/concatenation-of-consecutive-binary-numbers.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: n = 1 8 | Output: 1 9 | Explanation: "1" in binary corresponds to the decimal value 1.*/ 10 | 11 | //Solution// 12 | 13 | class Solution { 14 | public int concatenatedBinary(int n) { 15 | final long modulo = (long) (1e9 + 7); 16 | long result = 0; 17 | int binaryDigits = 0; 18 | for (int i = 1; i <= n; i++) { 19 | if ((i & (i - 1)) == 0) binaryDigits++; 20 | result = ((result << binaryDigits) + i) % modulo; 21 | } 22 | return (int) result; 23 | } 24 | } 25 | 26 | //Submission link:-https://leetcode.com/submissions/detail/806807209/ 27 | -------------------------------------------------------------------------------- /src/java/decode-ways.java: -------------------------------------------------------------------------------- 1 | /*Question:-A message containing letters from A-Z can be encoded into numbers using the following mapping: 2 | 3 | 'A' -> "1" 4 | 'B' -> "2" 5 | ... 6 | 'Z' -> "26" 7 | To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: 8 | 9 | "AAJF" with the grouping (1 1 10 6) 10 | "KJF" with the grouping (11 10 6) 11 | Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". 12 | 13 | Given a string s containing only digits, return the number of ways to decode it.*/ 14 | 15 | class Solution { 16 | public int numDecodings(String s) { 17 | Map countMap = new HashMap<>(); 18 | return count(s, 0, countMap); 19 | } 20 | public int count(String s, int index, Map countMap) { 21 | if(countMap.containsKey(index)) return countMap.get(index); 22 | int count = 0; 23 | if(index < s.length()) { 24 | int a1 = Integer.parseInt(s.substring(index, index + 1)); 25 | if(a1 < 1 || a1 > 26) count += 0; 26 | else count += count(s, index + 1, countMap); 27 | 28 | if(a1 != 0 && index + 1 < s.length()){ 29 | int a2 = Integer.parseInt(s.substring(index, index + 2)); 30 | if(a2 < 1 || a2 > 26) count += 0; 31 | else count += count(s, index + 2, countMap); 32 | } 33 | countMap.put(index, count); 34 | return count; 35 | } else { 36 | return 1; 37 | } 38 | } 39 | } 40 | 41 | 42 | //submission link:-https://leetcode.com/submissions/detail/812672463/ 43 | -------------------------------------------------------------------------------- /src/java/fibonacci-number.java: -------------------------------------------------------------------------------- 1 | // Question - The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number 2 | // is the sum of the two preceding ones, starting from 0 and 1. That is, 3 | // F(0) = 0, F(1) = 1 4 | // F(n) = F(n - 1) + F(n - 2), for n > 1. 5 | // Given n, calculate F(n). 6 | 7 | // Example 1: 8 | 9 | // Input: n = 2 10 | // Output: 1 11 | // Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 12 | 13 | class Solution { 14 | public int fib(int n) { 15 | 16 | //using recursion 17 | 18 | // if (n<=1) 19 | // return n; 20 | // else 21 | // { 22 | // int[] F = new int[n+1]; 23 | // F[0]=0; 24 | // F[1]=1; 25 | // for(int i=2;i<=n;i++) 26 | // F[i]=F[i-1]+F[i-2]; 27 | // return F[n]; 28 | // } 29 | 30 | // if(n==0 || n==1) 31 | // return n; 32 | 33 | // return fib(n-1)+fib(n-2); 34 | 35 | //using iterative approach 36 | int a = 0; 37 | int b = 1; 38 | if(n < 2){ 39 | return n; 40 | } 41 | else{ 42 | int c = 0; 43 | for(int i=1; i< n; i++){ 44 | c = a + b; 45 | a = b; 46 | b = c; 47 | } 48 | return c; 49 | } 50 | } 51 | } 52 | 53 | // Submission - https://leetcode.com/submissions/detail/787301524/ -------------------------------------------------------------------------------- /src/java/find-first-and-last-position-of-element-in-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int a = findFirst(nums, target); 4 | int b = findLast(nums, target); 5 | 6 | int[] x = new int[2]; 7 | x[0] = a; 8 | x[1] = b; 9 | return x; 10 | } 11 | private int findFirst (int[] nums, int target) { 12 | int n = nums.length; 13 | int i = 0; 14 | int j = n-1; 15 | 16 | int ans = -1; 17 | 18 | while (i <= j) { 19 | int m = i + (j-i)/2; 20 | if (nums[m] == target) { 21 | ans = m; 22 | j = m - 1; 23 | } 24 | else if (nums[m] > target) { 25 | j = m-1; 26 | } 27 | else { 28 | i = m+1; 29 | } 30 | } 31 | 32 | return ans; 33 | } 34 | 35 | private int findLast (int[] nums, int target) { 36 | int n = nums.length; 37 | int i = 0; 38 | int j = n-1; 39 | 40 | int ans = -1; 41 | 42 | while (i <= j) { 43 | int m = i + (j-i)/2; 44 | if (nums[m] == target) { 45 | ans = m; 46 | i = m + 1; 47 | } 48 | else if (nums[m] > target) { 49 | j = m-1; 50 | } 51 | else { 52 | i = m+1; 53 | } 54 | } 55 | 56 | return ans; 57 | } 58 | } 59 | // Submission Link: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/submissions/635553424/ -------------------------------------------------------------------------------- /src/java/find-the-index-of-the-first-occurrence-in-a-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | return haystack.indexOf(needle); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/java/first-unique-character-in-a-string.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: s = "leetcode" 8 | Output: 0*/ 9 | 10 | 11 | //Solution 12 | 13 | 14 | class Solution { 15 | public int firstUniqChar(String s) { 16 | int result = Integer.MAX_VALUE; 17 | for(char c = 'a'; c <= 'z'; c++){ 18 | int index = s.indexOf(c); 19 | if(index != - 1 && index == s.lastIndexOf(c)){ 20 | result = Math.min(result, index); 21 | } 22 | } 23 | return result == Integer.MAX_VALUE ? - 1 : result; 24 | } 25 | } 26 | 27 | 28 | //Subbmission link:-https://leetcode.com/submissions/detail/801402377/ 29 | -------------------------------------------------------------------------------- /src/java/first_bad_version.java: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | boolean isBadVersion(int version); */ 3 | 4 | public class Solution extends VersionControl { 5 | public int firstBadVersion(int n) { 6 | int i = 1; 7 | int j = n; 8 | 9 | int ans = j; 10 | while (i <= j) { 11 | int m = i + (j-i)/2; 12 | if (isBadVersion(m)) { 13 | ans = m; 14 | j=m-1; 15 | } 16 | else { 17 | i=m+1; 18 | } 19 | } 20 | return ans; 21 | } 22 | } 23 | // Submission Link: https://leetcode.com/problems/first-bad-version/submissions/634890233/ -------------------------------------------------------------------------------- /src/java/house-robber-ii.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. 3 | 4 | Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 5 | 6 | Input: nums = [2,3,2] 7 | Output: 3 8 | Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. 9 | 10 | Submission Link: https://leetcode.com/submissions/detail/814642362/ 11 | 12 | */ 13 | 14 | public class HouseRobberII { 15 | public int rob(int[] nums) { 16 | if (nums.length == 0) 17 | return 0; 18 | if (nums.length < 2) 19 | return nums[0]; 20 | 21 | int[] startFromFirstHouse = new int[nums.length + 1]; 22 | int[] startFromSecondHouse = new int[nums.length + 1]; 23 | 24 | startFromFirstHouse[0] = 0; 25 | startFromFirstHouse[1] = nums[0]; 26 | startFromSecondHouse[0] = 0; 27 | startFromSecondHouse[1] = 0; 28 | 29 | for (int i = 2; i <= nums.length; i++) { 30 | startFromFirstHouse[i] = Math.max(startFromFirstHouse[i - 1], startFromFirstHouse[i - 2] + nums[i-1]); 31 | startFromSecondHouse[i] = Math.max(startFromSecondHouse[i - 1], startFromSecondHouse[i - 2] + nums[i-1]); 32 | } 33 | 34 | return Math.max(startFromFirstHouse[nums.length - 1], startFromSecondHouse[nums.length]); 35 | } 36 | } -------------------------------------------------------------------------------- /src/java/invert-binary-tree.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given the root of a binary tree, invert the tree, and return its root. 2 | Example 1:- 3 | image link:-https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg 4 | Input: root = [4,2,7,1,3,6,9] 5 | Output: [4,7,2,9,6,3,1] 6 | 7 | */ 8 | 9 | //Solution 10 | 11 | class Solution { 12 | 13 | public TreeNode invertTree(TreeNode root) { 14 | 15 | helper(root); 16 | return root; 17 | } 18 | 19 | private void helper(TreeNode root) 20 | { 21 | if(root==null)return; 22 | 23 | TreeNode temp=root.left; 24 | root.left=root.right; 25 | root.right=temp; 26 | 27 | helper(root.left); 28 | helper(root.right); 29 | 30 | } 31 | } 32 | 33 | //Submission link:-https://leetcode.com/submissions/detail/806137566/ 34 | -------------------------------------------------------------------------------- /src/java/length-of-last-word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | s=s.trim(); 4 | for(int i=s.length()-1;i>=0;i--){ 5 | if(s.charAt(i)==' ') return s.length()-i-1; 6 | } 7 | return s.length(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/java/longest-substring-without-repeated-characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | if (s.length() == 0) return 0; 4 | int curStartingIdx = 0; 5 | ArrayList substring = new ArrayList(); 6 | int maxValue = 0; 7 | for (int i = 0; i < s.length(); i++) { 8 | if (!substring.contains(s.charAt(i))){ 9 | substring.add(s.charAt(i)); 10 | if (maxValue < substring.size()) { 11 | maxValue = substring.size(); 12 | } 13 | } else { 14 | substring.clear(); 15 | curStartingIdx++; 16 | i = curStartingIdx-1; 17 | } 18 | } 19 | 20 | return maxValue; 21 | } 22 | } -------------------------------------------------------------------------------- /src/java/longest-substring-without-repeating-characters.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: s = "abcabcbb" 8 | Output: 3 9 | Explanation: The answer is "abc", with the length of 3.*/ 10 | 11 | //Solution 12 | 13 | import java.util.*; 14 | class Solution { 15 | public int lengthOfLongestSubstring(String s) { 16 | int left = 0; 17 | int right = 0; 18 | int length = s.length(); 19 | int max_length = 0; 20 | Set check = new HashSet<>(); 21 | 22 | while(right < length){ 23 | if(check.contains( s.charAt(right)) == true){ 24 | 25 | while((left < right) && check.contains(s.charAt(right)) == true){ 26 | check.remove(s.charAt(left)); 27 | left++; 28 | } 29 | } 30 | 31 | check.add(s.charAt(right)); 32 | max_length = Math.max(max_length, right-left+1); 33 | right++; 34 | 35 | } 36 | 37 | return max_length; 38 | } 39 | } 40 | 41 | //Submission link:-https://leetcode.com/submissions/detail/797209410/ 42 | -------------------------------------------------------------------------------- /src/java/lowest-common-ancestor-of-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. 2 | 3 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * public class TreeNode { 9 | * int val; 10 | * TreeNode left; 11 | * TreeNode right; 12 | * TreeNode(int x) { val = x; } 13 | * } 14 | */ 15 | 16 | class Solution { 17 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 18 | if(p==null || q==null) 19 | return root; 20 | if(root==null || root==p || root==q) 21 | return root; 22 | if(p.valroot.val || p.val>root.val && q.val (p2[0] - p1[0])); 22 | 23 | // Priority-Queue to maintain players with highest relative speeds with efficiencies greater than the one under iteration. 24 | PriorityQueue speedQueue = new PriorityQueue<>(k); 25 | long teamPerformance = 0, teamSpeed = 0; 26 | 27 | for (int i=0; i= k) { 30 | teamSpeed -= speedQueue.remove(); 31 | } 32 | speedQueue.add(players[i][1]); 33 | teamSpeed += players[i][1]; 34 | 35 | teamPerformance = Math.max(teamPerformance, teamSpeed * players[i][0]); 36 | } 37 | return (int) (teamPerformance % 1000000007); 38 | } 39 | } 40 | 41 | 42 | //Submission link:-https://leetcode.com/submissions/detail/797195537/ 43 | -------------------------------------------------------------------------------- /src/java/merge-two-sorted-lists.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 | if (l1 == null) { 4 | return l2; 5 | } else if (l2 == null) { 6 | return l1; 7 | } else if (l1.val < l2.val) { 8 | l1.next = mergeTwoLists(l1.next, l2); 9 | return l1; 10 | } else { 11 | l2.next = mergeTwoLists(l1, l2.next); 12 | return l2; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/java/minimum-time-to-make-rope-colorful.java: -------------------------------------------------------------------------------- 1 | /*Question:-Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. 2 | 3 | Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. 4 | 5 | Return the minimum time Bob needs to make the rope colorful.*/ 6 | 7 | 8 | //Solution// 9 | 10 | 11 | 12 | 13 | class Solution { 14 | public int minCost(String colors, int[] neededTime) { 15 | int cost=0; 16 | int pos=0; 17 | for(int i=1;i 1){ 29 | sb.deleteCharAt(0); 30 | } 31 | 32 | return sb.toString(); 33 | } 34 | } -------------------------------------------------------------------------------- /src/java/palindrome-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | String first = Integer.toString(x); 4 | String second = ""; 5 | 6 | for (int i = first.length()-1; i >= 0; i--) { 7 | second = second + first.charAt(i); 8 | } 9 | if (first.equals(second)){ 10 | return true; 11 | } else {return false;} 12 | } 13 | } -------------------------------------------------------------------------------- /src/java/palindrome-partitioning-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCut(String s) { 3 | int n = s.length(); 4 | int[][] dp = new int[n][n]; 5 | for (int [] d : dp) { 6 | Arrays.fill(d, -1); 7 | } 8 | return rec (s, 0, n-1, dp); 9 | } 10 | private int rec (String s, int i, int j, int[][] dp) { 11 | if (i >= j) { 12 | return 0; 13 | } 14 | else if (dp[i][j] != -1) { 15 | return dp[i][j]; 16 | } 17 | else { 18 | int ans = j-i+1; 19 | if (isPal(s, i, j)) { 20 | ans = 0; 21 | } 22 | else { 23 | for (int k = i; k = j) { 17 | return true; 18 | } 19 | else if (dp[i][j] != 0) { 20 | return dp[i][j] == 1; 21 | } 22 | else { 23 | boolean ans = false; 24 | if (s.charAt(i) == s.charAt(j)) { 25 | ans = isPal(s, i+1, j-1, dp); 26 | } 27 | else { 28 | ans = false; 29 | } 30 | 31 | dp[i][j] = ans ? 1 : -1; 32 | 33 | return ans; 34 | } 35 | } 36 | } 37 | // submission link: https://leetcode.com/problems/palindromic-substrings/submissions/620740483/ -------------------------------------------------------------------------------- /src/java/pascal's-triangle-ii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List getRow(int rowIndex) { 3 | List> finallist; 4 | finallist = new ArrayList>(); 5 | List list1 = new ArrayList<>(); 6 | List list2 = new ArrayList<>(); 7 | List alist = new ArrayList<>(); 8 | list1.add(1); 9 | list2.add(1); 10 | alist.add(1); 11 | list2.add(1); 12 | alist.add(1); 13 | finallist.add(list1); 14 | finallist.add(list2); 15 | if (rowIndex == 1){ 16 | return list2; 17 | } 18 | for (int j = 3;j <= rowIndex + 1;j++) { 19 | List list3 = new ArrayList<>(); 20 | list3.add(1); 21 | for (int i = 0; i < alist.size() - 1; i++) { 22 | list3.add(alist.get(i) + alist.get(i + 1)); 23 | } 24 | list3.add(1); 25 | finallist.add(list3); 26 | alist.clear(); 27 | alist.addAll(list3); 28 | if (rowIndex + 1 == j){ 29 | return alist; 30 | } 31 | } 32 | return list1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/java/pascals-triangle.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given an integer numRows, return the first numRows of Pascal's triangle. 2 | 3 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | image address:-https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif 6 | Example 1: 7 | 8 | Input: numRows = 5 9 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]*/ 10 | 11 | //Solution// 12 | 13 | class Solution { 14 | public List> generate(int numRows) { 15 | List> res = new ArrayList>(); 16 | List row, pre = null; 17 | for (int i = 0; i < numRows; ++i) { 18 | row = new ArrayList(); 19 | for (int j = 0; j <= i; ++j) 20 | if (j == 0 || j == i) 21 | row.add(1); 22 | else 23 | row.add(pre.get(j - 1) + pre.get(j)); 24 | pre = row; 25 | res.add(row); 26 | } 27 | return res; 28 | } 29 | } 30 | 31 | //Submission link:-https://leetcode.com/submissions/detail/799641385/ 32 | -------------------------------------------------------------------------------- /src/java/path-sum-ii.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/path-sum-ii/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | class Solution { 19 | 20 | List> list; 21 | 22 | public List> pathSum(TreeNode root, int targetSum) { 23 | 24 | if (root==null) { 25 | return new ArrayList<>(); 26 | } 27 | 28 | list=new ArrayList<>(); 29 | path(root,targetSum,0,new ArrayList<>()); 30 | 31 | return list; 32 | } 33 | 34 | void path(TreeNode root, int target, int sum, List list1) { 35 | 36 | if (root==null) { 37 | return; 38 | } 39 | 40 | list1.add(root.val); 41 | 42 | sum=sum+root.val; 43 | 44 | if (root.left==null && root.right==null && sum==target) { 45 | 46 | List ans=new ArrayList(list1); 47 | list.add(ans); 48 | } 49 | 50 | path(root.left,target,sum,list1); 51 | path(root.right,target,sum,list1); 52 | 53 | list1.remove(list1.size()-1); 54 | } 55 | } 56 | 57 | // Submission - https://leetcode.com/submissions/detail/807289901/ 58 | -------------------------------------------------------------------------------- /src/java/path-sum-iii.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/path-sum-iii/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | class Solution { 19 | public int pathSum(TreeNode root, int targetSum) { 20 | return count(root,targetSum,0,false); 21 | } 22 | 23 | private int count(TreeNode root, int targetSum, int sum, boolean flag) { 24 | 25 | if (root==null) { 26 | return 0; 27 | } 28 | 29 | int cnt=0; 30 | 31 | cnt=cnt+count(root.left,targetSum,sum+root.val,true) + count(root.right,targetSum,sum+root.val,true); 32 | 33 | if (!flag) { 34 | cnt+= count(root.left,targetSum,sum,false) + count(root.right,targetSum,sum,false); 35 | } 36 | 37 | if (root.val+sum==targetSum) { 38 | cnt++; 39 | } 40 | 41 | return cnt; 42 | } 43 | } 44 | 45 | // Submission - https://leetcode.com/submissions/detail/572580737/ -------------------------------------------------------------------------------- /src/java/path-sum.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/path-sum/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode() {} 10 | * TreeNode(int val) { this.val = val; } 11 | * TreeNode(int val, TreeNode left, TreeNode right) { 12 | * this.val = val; 13 | * this.left = left; 14 | * this.right = right; 15 | * } 16 | * } 17 | */ 18 | class Solution { 19 | public boolean hasPathSum(TreeNode root, int sum) { 20 | 21 | if (root==null) { 22 | return false; 23 | } 24 | 25 | if (root.left==null && root.right==null) { 26 | if (sum==root.val) { 27 | return true; 28 | } 29 | } 30 | 31 | if (hasPathSum(root.left,sum-root.val)) { 32 | return true; 33 | } 34 | if (hasPathSum(root.right,sum-root.val)) { 35 | return true; 36 | } 37 | 38 | return false; 39 | 40 | } 41 | } 42 | 43 | // Submission - https://leetcode.com/submissions/detail/434711704/ -------------------------------------------------------------------------------- /src/java/power-of-two.java: -------------------------------------------------------------------------------- 1 | // question - Given an integer n, return true if it is a power of two. Otherwise, return false. 2 | // An integer n is a power of two, if there exists an integer x such that n == 2x. 3 | 4 | // Example 1: 5 | // Input: n = 1 6 | // Output: true 7 | // Explanation: 2^0 = 1 8 | 9 | class Solution { 10 | public boolean isPowerOfTwo(int n) { 11 | 12 | if(n == 1){ 13 | return true; 14 | }else if(n == 0){ 15 | return false; 16 | }else if(n % 2 != 0){ 17 | return false; 18 | } 19 | return isPowerOfTwo(n/2); 20 | 21 | 22 | } 23 | } 24 | 25 | // Submission - https://leetcode.com/submissions/detail/789071171/ -------------------------------------------------------------------------------- /src/java/pseudo-palindromic-paths-in-a-binary-tree.java: -------------------------------------------------------------------------------- 1 | /*Question:-Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. 2 | 3 | Return the number of pseudo-palindromic paths going from the root node to leaf nodes. 4 | Example 1 5 | image link:-https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png 6 | Input: root = [2,3,1,3,1,null,1] 7 | Output: 2 8 | */ 9 | 10 | //Solution 11 | 12 | class Solution { 13 | int ans = 0; 14 | public int pseudoPalindromicPaths (TreeNode root) { 15 | ans = 0; 16 | dfs(root, 0); 17 | return ans; 18 | } 19 | private void dfs(TreeNode root, int count) { 20 | if (root == null) return; 21 | count ^= 1 << (root.val - 1); 22 | dfs(root.left, count); 23 | dfs(root.right, count); 24 | if (root.left == null && root.right == null && (count & (count - 1)) == 0) ans++; 25 | } 26 | } 27 | 28 | //Submission link:-https://leetcode.com/submissions/detail/799637669/ 29 | -------------------------------------------------------------------------------- /src/java/remove-duplicates-from-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int count = 0; 4 | // Loop for all the elements in the array 5 | for (int i = 0; i < nums.length; i++) { 6 | // If the current element is equal to the next element, we skip 7 | if (i < nums.length - 1 && nums[i] == nums[i + 1]) { 8 | continue; 9 | } 10 | // We will update the array in place 11 | nums[count] = nums[i]; 12 | count++; 13 | } 14 | return count; 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /src/java/remove-duplicates-from-sorted-list-ii.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode deleteDuplicates(ListNode head) { 15 | 16 | // sentinel 17 | ListNode sentinel = new ListNode(0, head); 18 | 19 | // predecessor = the last node 20 | // before the sublist of duplicates 21 | ListNode pred = sentinel; 22 | 23 | while (head != null) { 24 | // if it's a beginning of duplicates sublist 25 | // skip all duplicates 26 | if (head.next != null && head.val == head.next.val) { 27 | // move till the end of duplicates sublist 28 | while (head.next != null && head.val == head.next.val) { 29 | head = head.next; 30 | } 31 | // skip all duplicates 32 | pred.next = head.next; 33 | // otherwise, move predecessor 34 | } else { 35 | pred = pred.next; 36 | } 37 | 38 | // move forward 39 | head = head.next; 40 | } 41 | return sentinel.next; 42 | } 43 | } 44 | 45 | // Submission - https://leetcode.com/submissions/detail/656737500/ -------------------------------------------------------------------------------- /src/java/remove-duplicates-from-sorted-list.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode deleteDuplicates(ListNode head) { 15 | 16 | if (head==null || head.next==null) { 17 | return head; 18 | } 19 | 20 | ListNode temp1=head, temp2=head.next; 21 | 22 | while (temp2!=null) { 23 | 24 | if (temp1.val==temp2.val) { 25 | temp2=temp2.next; 26 | temp1.next=temp2; 27 | } else { 28 | temp1=temp1.next; 29 | temp2=temp2.next; 30 | } 31 | } 32 | 33 | return head; 34 | } 35 | 36 | } 37 | 38 | // Submission - https://leetcode.com/submissions/detail/426116279/ -------------------------------------------------------------------------------- /src/java/remove-nth-node-from-end-of-list.java: -------------------------------------------------------------------------------- 1 | // Question - https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode() {} 9 | * ListNode(int val) { this.val = val; } 10 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | * } 12 | */ 13 | class Solution { 14 | public ListNode removeNthFromEnd(ListNode head, int n) { 15 | 16 | int size=size(head); 17 | 18 | if (size==n) { 19 | return head.next; 20 | } 21 | 22 | int i=0; 23 | ListNode temp=head; 24 | 25 | while (i> 3 == 0b11110) { 26 | count = 3; 27 | } else if (value >> 4 == 0b1110) { 28 | count = 2; 29 | } else if (value >> 5 == 0b110) { 30 | count = 1; 31 | } else if (value >> 7 == 0b0) { 32 | count = 0; 33 | } else { 34 | return false; 35 | } 36 | } else { 37 | if (value >> 6 == 0b10) { 38 | count--; 39 | } else { 40 | return false; 41 | } 42 | } 43 | } 44 | return count == 0; 45 | } 46 | } 47 | 48 | //Submission link:-https://leetcode.com/submissions/detail/798949428/ 49 | -------------------------------------------------------------------------------- /src/java/valid-sudoku.java: -------------------------------------------------------------------------------- 1 | /*Question:-Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: 2 | 3 | Each row must contain the digits 1-9 without repetition. 4 | Each column must contain the digits 1-9 without repetition. 5 | Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. 6 | Note: 7 | 8 | A Sudoku board (partially filled) could be valid but is not necessarily solvable. 9 | Only the filled cells need to be validated according to the mentioned rules.*/ 10 | 11 | //Solution// 12 | 13 | class Solution { 14 | public boolean isValidSudoku(char[][] board) { 15 | int[] row = new int[board.length]; 16 | int[] col = new int[board.length]; 17 | int[] cube = new int[board.length]; 18 | for(int k = 0; k < 3; k++) { 19 | for(int i = 0; i < board.length; i++) { 20 | for(int j = k * 3; j < (k + 1) * 3; j++) { 21 | if (!Character.isDigit(board[i][j])) { 22 | continue; 23 | } 24 | int c = 1 << (board[i][j] - '0'); 25 | int cubeIndex = k * 3 + i / 3; 26 | if ((row[i] & c) > 0 || (col[j] & c) > 0 || (cube[cubeIndex] & c) > 0) { 27 | return false; 28 | } 29 | row[i] |= c; 30 | col[j] |= c; 31 | cube[cubeIndex] |= c; 32 | } 33 | } 34 | } 35 | return true; 36 | } 37 | } 38 | 39 | //Submission link:-https://leetcode.com/submissions/detail/800641694/ 40 | -------------------------------------------------------------------------------- /src/mysql/combine-two-tables.sql: -------------------------------------------------------------------------------- 1 | SELECT A.firstName, A.lastName, B.city, B.state FROM Person A LEFT JOIN Address B ON A.personId = B.personId; -------------------------------------------------------------------------------- /src/mysql/customers-who-never-order.sql: -------------------------------------------------------------------------------- 1 | SELECT C.name AS Customers FROM Customers C LEFT JOIN Orders O ON C.id = O.customerId WHERE O.customerId is NULL; -------------------------------------------------------------------------------- /src/mysql/department-highest-salary.sql: -------------------------------------------------------------------------------- 1 | SELECT D.name AS Department, E.name AS Employee, E.Salary FROM Employee AS E INNER JOIN Department AS D ON E.departmentId = D.id WHERE (E.departmentId, E.salary) IN (SELECT departmentId, MAX(salary) FROM Employee GROUP BY departmentId); -------------------------------------------------------------------------------- /src/mysql/employee-bonus.sql: -------------------------------------------------------------------------------- 1 | SELECT E.name, B.bonus FROM Employee AS E LEFT JOIN Bonus AS B ON E.empId = B.empId WHERE B.bonus<1000 OR B.bonus IS NULL; -------------------------------------------------------------------------------- /src/mysql/find-customer-referee.sql: -------------------------------------------------------------------------------- 1 | SELECT name FROM Customer WHERE referee_id !=2 OR referee_id IS NULL; -------------------------------------------------------------------------------- /src/python/N-queens.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveNQueens(self, n: int) -> List[List[str]]: 3 | def isafe(row,col,board,n): 4 | drow,dcol = row,col 5 | 6 | while row >=0 and col >=0: 7 | if board[row][col] == 'Q': return False 8 | row-=1 9 | col-=1 10 | row ,col = drow,dcol 11 | while col >=0: 12 | if board[row][col] == 'Q': return False 13 | col -=1 14 | 15 | row ,col = drow,dcol 16 | while row < n and col >=0: 17 | if board[row][col] == 'Q': return False 18 | row+=1 19 | col-=1 20 | return True 21 | 22 | def solve(col,board,n): 23 | if col == n: 24 | copy = [''.join(row) for row in board] 25 | ans.append(copy) 26 | return 27 | 28 | for row in range(n): 29 | if isafe(row,col,board,n): 30 | board[row][col] = 'Q' 31 | solve(col+1,board,n) 32 | board[row][col] = '.' 33 | 34 | 35 | 36 | board = [['.']*n for _ in range(n)] 37 | ans = [] 38 | solve(0,board,n) 39 | return ans 40 | -------------------------------------------------------------------------------- /src/python/binary-tree-inorder-traversal.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/binary-tree-inorder-traversal/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 11 | ans = [] 12 | if root != None: 13 | ans += self.inorderTraversal(root.left) 14 | ans.append(root.val) 15 | ans += self.inorderTraversal(root.right) 16 | return ans 17 | -------------------------------------------------------------------------------- /src/python/bitwise-AND-of-numbers-range.py: -------------------------------------------------------------------------------- 1 | # 201. Bitwise AND of Numbers Range 2 | # https://leetcode.com/problems/bitwise-and-of-numbers-range/ 3 | 4 | class Solution: 5 | def rangeBitwiseAnd(self, left: int, right: int) -> int: 6 | zero_bits = 0 7 | while left != right: 8 | left >>= 1 9 | right >>= 1 10 | zero_bits += 1 11 | return left << zero_bits 12 | -------------------------------------------------------------------------------- /src/python/break-a-palindrome.py: -------------------------------------------------------------------------------- 1 | # 1328. Break a Palindrome 2 | # https://leetcode.com/problems/break-a-palindrome/ 3 | 4 | class Solution: 5 | def breakPalindrome(self, palindrome: str) -> str: 6 | if len(palindrome) == 1: return "" 7 | letters = list(palindrome) 8 | 9 | for i in range(len(letters) // 2): 10 | if letters[i] != 'a': 11 | letters[i] = 'a' 12 | return "".join(letters) 13 | 14 | letters[-1] = 'b' 15 | return "".join(letters) 16 | -------------------------------------------------------------------------------- /src/python/climbing-stairs.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/climbing-stairs/ 2 | 3 | class Solution: 4 | temp ={ 5 | 1 : 1, 6 | 2 : 2 7 | } 8 | def climbStairs(self, n: int) -> int: 9 | if n in self.temp: 10 | return self.temp[n] 11 | else: 12 | self.temp[n] = self.climbStairs(n-1) + self.climbStairs(n-2) 13 | return self.temp[n] -------------------------------------------------------------------------------- /src/python/encrypt-and-decrypt-strings.py: -------------------------------------------------------------------------------- 1 | # 2227. Encrypt and Decrypt Strings 2 | # https://leetcode.com/problems/encrypt-and-decrypt-strings/ 3 | 4 | class Encrypter: 5 | 6 | def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): 7 | self.back = dict() 8 | self.keys = keys 9 | self.values = values 10 | self.dictionary = dictionary 11 | 12 | for i, key in enumerate(keys): 13 | self.back[key] = i 14 | 15 | self.ddict = Counter(self.encrypt(d) for d in self.dictionary) 16 | 17 | def encrypt(self, word1: str) -> str: 18 | return ''.join(self.values[self.back[i]] for i in word1) 19 | 20 | def decrypt(self, word2: str) -> int: 21 | return self.ddict[word2] 22 | 23 | # Your Encrypter object will be instantiated and called as such: 24 | # obj = Encrypter(keys, values, dictionary) 25 | # param_1 = obj.encrypt(word1) 26 | # param_2 = obj.decrypt(word2) 27 | -------------------------------------------------------------------------------- /src/python/find-the-index-of-the-first-occurrence-in-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | return haystack.find(needle) 4 | -------------------------------------------------------------------------------- /src/python/find-the-original-array-of-prefix-xor.py: -------------------------------------------------------------------------------- 1 | # 2433. Find The Original Array of Prefix Xor 2 | # https://leetcode.com/problems/find-the-original-array-of-prefix-xor/ 3 | 4 | class Solution: 5 | def findArray(self, pref: List[int]) -> List[int]: 6 | result = [pref[0]] 7 | for i in range(1, len(pref)): 8 | result.append(pref[i - 1] ^ pref[i]) 9 | return result 10 | -------------------------------------------------------------------------------- /src/python/group-anagrams.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/group-anagrams/ 2 | class Solution: 3 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 4 | d={} 5 | for words in strs: 6 | key=tuple(sorted(words)) 7 | d[key]=d.get(key,[])+[words] 8 | return d.values() -------------------------------------------------------------------------------- /src/python/increasing-triplet-subsequence.py: -------------------------------------------------------------------------------- 1 | # 334. Increasing Triplet Subsequence 2 | # https://leetcode.com/problems/increasing-triplet-subsequence/ 3 | 4 | class Solution: 5 | def increasingTriplet(self, nums: List[int]) -> bool: 6 | first = second = float('inf') 7 | for num in nums: 8 | if num <= first: 9 | first = num 10 | elif num <= second: 11 | second = num 12 | else: 13 | return True 14 | return False 15 | -------------------------------------------------------------------------------- /src/python/keys-and-rooms.py: -------------------------------------------------------------------------------- 1 | # 841. Keys and Rooms 2 | # https://leetcode.com/problems/keys-and-rooms/ 3 | 4 | class Solution: 5 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 6 | visited = set() 7 | 8 | def dfs(u): 9 | visited.add(u) 10 | for v in rooms[u]: 11 | if v not in visited: 12 | dfs(v) 13 | dfs(0) 14 | return len(visited) == len(rooms) 15 | -------------------------------------------------------------------------------- /src/python/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | return len(s.split()[-1]) 4 | -------------------------------------------------------------------------------- /src/python/palindrome-number.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/palindrome-number/ 2 | 3 | class Solution: 4 | def isPalindrome(self, x: int) -> bool: 5 | y = str(x) 6 | lst = list(y) 7 | lst.reverse() 8 | y = "".join(lst) 9 | try: 10 | y = int(y) 11 | except: 12 | ValueError 13 | if x == y: 14 | return True 15 | else: 16 | return False -------------------------------------------------------------------------------- /src/python/permutation-sequence.py: -------------------------------------------------------------------------------- 1 | # 60. Permutation Sequence 2 | # https://leetcode.com/problems/permutation-sequence/ 3 | 4 | class Solution: 5 | def getPermutation(self, n: int, k: int) -> str: 6 | factorial = 1 7 | nums = [] 8 | for i in range(1, n): 9 | factorial *= i 10 | nums.append(str(i)) 11 | nums.append(str(n)) 12 | 13 | k -= 1 14 | result = [] 15 | while True: 16 | result.append(nums[k // factorial]) 17 | nums.pop(k // factorial) 18 | if len(nums) == 0: break 19 | k %= factorial 20 | factorial //= len(nums) 21 | 22 | return "".join(result) 23 | -------------------------------------------------------------------------------- /src/python/powx-n.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/powx-n/ 2 | 3 | class Solution: 4 | def myPow(self, x: float, n: int) -> float: 5 | # Base case 6 | if n == 0: 7 | return 1 8 | # determine whether to divide by the answer 9 | if n < 0: 10 | div = True 11 | else: 12 | div = False 13 | 14 | n = abs(n) 15 | ans = 1 16 | while n>0: 17 | ans *= x 18 | print(ans) 19 | n -= 1 # decrement n by 1 20 | 21 | return 1/ans if div else ans # divide by the answer if n is negative -------------------------------------------------------------------------------- /src/python/repeated-substring-pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | # find abab in abababab 4 | t=s*2 5 | if t[1:-1].find(s)!=-1: return 1 6 | else: return 0 7 | 8 | -------------------------------------------------------------------------------- /src/python/roman-to-integer.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/roman-to-integer/ 2 | 3 | class Solution: 4 | def romanToInt(self, s: str) -> int: 5 | roman_dic = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} 6 | ans = 0 7 | 8 | for i in range(len(s)): 9 | 10 | if i != 0 and roman_dic[s[i - 1]] < roman_dic[s[i]]: 11 | ans = ans + roman_dic[s[i]] - roman_dic[s[i - 1]] * 2 12 | else: 13 | ans = ans + roman_dic[s[i]] 14 | 15 | return ans -------------------------------------------------------------------------------- /src/python/rotate-image.py: -------------------------------------------------------------------------------- 1 | # 48. Rotate Image 2 | # https://leetcode.com/problems/rotate-image/ 3 | 4 | class Solution: 5 | def rotate(self, matrix: List[List[int]]) -> None: 6 | """ 7 | Do not return anything, modify matrix in-place instead. 8 | """ 9 | self.reflect(matrix) 10 | self.transpose(matrix) 11 | 12 | def transpose(self, matrix: List[List[int]]) -> None: 13 | for i in range(1, len(matrix)): 14 | for j in range(i): 15 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 16 | 17 | def reflect(self, matrix: List[List[int]]) -> None: 18 | i = 0 19 | j = len(matrix) - 1 20 | while i < j: 21 | matrix[i], matrix[j] = matrix[j], matrix[i] 22 | i += 1 23 | j -= 1 24 | -------------------------------------------------------------------------------- /src/python/serialize-and-deserialize-binary-tree.py: -------------------------------------------------------------------------------- 1 | # 297. Serialize and Deserialize Binary Tree 2 | # https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | class Codec: 12 | 13 | def serialize(self, root): 14 | """Encodes a tree to a single string. 15 | 16 | :type root: TreeNode 17 | :rtype: str 18 | """ 19 | def serializeUtil(root): 20 | if not root: 21 | vals.append("None") 22 | return 23 | vals.append(str(root.val)) 24 | serializeUtil(root.left) 25 | serializeUtil(root.right) 26 | 27 | vals = [] 28 | serializeUtil(root) 29 | return " ".join(vals) 30 | 31 | def deserialize(self, data): 32 | """Decodes your encoded data to tree. 33 | 34 | :type data: str 35 | :rtype: TreeNode 36 | """ 37 | def deserializeUtil(): 38 | val = next(vals) 39 | if val == "None": 40 | return None 41 | node = TreeNode(int(val)) 42 | node.left = deserializeUtil() 43 | node.right = deserializeUtil() 44 | return node 45 | 46 | vals = iter(data.split()) 47 | return deserializeUtil() 48 | 49 | # Your Codec object will be instantiated and called as such: 50 | # ser = Codec() 51 | # deser = Codec() 52 | # ans = deser.deserialize(ser.serialize(root)) 53 | -------------------------------------------------------------------------------- /src/python/simplify-path.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/simplify-path/ 2 | 3 | class Solution: 4 | def simplifyPath(self, path): 5 | stack = [] 6 | for elem in path.split("/"): 7 | if stack and elem == "..": 8 | stack.pop() 9 | elif elem not in [".", "", ".."]: 10 | stack.append(elem) 11 | 12 | return "/" + "/".join(stack) -------------------------------------------------------------------------------- /src/python/sum-of-two-integers.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getSum(self, a, b): 3 | mask = 0xffffffff 4 | 5 | while b != 0: 6 | tmp = (a & b) << 1 7 | a = (a ^ b) & mask 8 | b = tmp & mask 9 | 10 | if a > mask // 2: 11 | return ~(a ^ mask) 12 | else: 13 | return a -------------------------------------------------------------------------------- /src/python/the-employee-that-worked-on-the-longest-task.py: -------------------------------------------------------------------------------- 1 | # 2432. The Employee That Worked on the Longest Task 2 | # https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/ 3 | 4 | class Solution: 5 | def hardestWorker(self, n: int, logs: List[List[int]]) -> int: 6 | longest = logs[0][1] 7 | result = logs[0][0] 8 | for i in range(1, len(logs)): 9 | duration = logs[i][1] - logs[i - 1][1] 10 | if duration > longest or (duration == longest and logs[i][0] < result): 11 | longest = logs[i][1] - logs[i - 1][1] 12 | result = logs[i][0] 13 | 14 | return result 15 | -------------------------------------------------------------------------------- /src/python/two-sum.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/two-sum/ 2 | 3 | class Solution: 4 | def twoSum(self, nums, target): 5 | for i in range(len(nums)): 6 | try: 7 | diffindex = nums.index(target - nums[i], i + 1) 8 | except ValueError: 9 | continue 10 | if diffindex > i: 11 | return {i, diffindex} -------------------------------------------------------------------------------- /src/python/using-a-robot-to-print-the-lexicographically-smallest-string.py: -------------------------------------------------------------------------------- 1 | # 2434. Using a Robot to Print the Lexicographically Smallest String 2 | # https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/ 3 | 4 | class Solution: 5 | def robotWithString(self, s: str) -> str: 6 | stack = [] 7 | result = [] 8 | smallest_from_right = [""] * len(s) 9 | smallest_from_right[-1] = s[-1] 10 | 11 | for i in range(len(smallest_from_right) - 2, -1, -1): 12 | smallest_from_right[i] = min(s[i], smallest_from_right[i + 1]) 13 | 14 | for i in range(len(s)): 15 | while stack and stack[-1] <= smallest_from_right[i]: 16 | result.append(stack.pop()) 17 | stack.append(s[i]) 18 | 19 | while stack: 20 | result.append(stack.pop()) 21 | 22 | return "".join(result) 23 | -------------------------------------------------------------------------------- /src/python/valid-sudoku.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/valid-sudoku/ 2 | 3 | class Solution: 4 | def isValidSudoku(self, board): 5 | row = {i:set() for i in range(9)} 6 | col = {i:set() for i in range(9)} 7 | box = {i:set() for i in range(9)} 8 | for i in range(9): 9 | for j in range(9): 10 | # skip '.' 11 | if board[i][j] == '.': 12 | continue 13 | # check row 14 | if board[i][j] in row[i]: 15 | return False 16 | else: 17 | row[i].add(board[i][j]) 18 | # check column 19 | if board[i][j] in col[j]: 20 | return False 21 | else: 22 | col[j].add(board[i][j]) 23 | # check box 24 | if board[i][j] in box[(i//3)*3+(j//3)]: 25 | return False 26 | else: 27 | box[(i//3)*3+(j//3)].add(board[i][j]) 28 | return True --------------------------------------------------------------------------------