├── .github ├── FUNDING.yml └── config.yml ├── C++ ├── 100_Same_Tree.cpp ├── 143.Reorder_List.cpp ├── 189.Rotate-array.cpp ├── 238.Product_of_array_except_self ├── 3sum.cpp ├── Baseball-Game.cpp ├── Best-Time-to-Buy-and-Sell-Stock-II.cpp ├── Binary-Tree-Cameras.cpp ├── Binary-Tree-Level-Order-Traversal.cpp ├── Binary-Tree-Maximum-Path-Sum.cpp ├── Binary-Tree-Zigzag-Level-Order-Traversal.cpp ├── BinarySearch.cpp ├── Cherry-Pickup-II.cpp ├── Count-Different-Palindromic-Subsequences.cpp ├── Count-Primes.cpp ├── Course-Schedule-II.cpp ├── Course-Schedule.cpp ├── Crawler-Log-Folder.cpp ├── Critical-Connections-in-a-Network.cpp ├── Daily_Temperatures.cpp ├── Defanging an IP Address.cpp ├── Degree-of-an-Array.cpp ├── Detect-Capital.cpp ├── Excel-Sheet-Column-Number.cpp ├── Excel-Sheet-Column-Title.cpp ├── Find-The-Difference.cpp ├── Integer-Break.cpp ├── Is-Graph-Bipartite.cpp ├── LRU-Cache.cpp ├── Largest-Rectangle-in-Histogram.cpp ├── Linked-List-Cycle-II.cpp ├── Longest-Mountain-in-Array.cpp ├── Merge-Two-Sorted-Lists.cpp ├── Minimum-Number-of-Flips-to-Convert-Binary-Matrix-to-Zero-Matrix.cpp ├── Most-Stones-Removed-with-Same-Row-or-Column.cpp ├── Move-Zeroes.cpp ├── Network-delay-time.cpp ├── Number-Complement.cpp ├── Number-of-Recent-Calls.cpp ├── Partition-Equal-Subset-Sum.cpp ├── Path-Sum-II.cpp ├── Recover-a-Tree-From-Preorder-Traversal.cpp ├── RedundantConnection.cpp ├── Remove-Covered-Intervals.cpp ├── Reshape-the-Matrix.cpp ├── Reverse-Integer.cpp ├── Roman_to_Integer.cpp ├── Shortest-Bridge.cpp ├── Shortest-Common-Supersequence.cpp ├── Single-Number-II.cpp ├── Single-Number-III.cpp ├── Single-Number.cpp ├── Spiral-matrix.cpp ├── Sudoku-Solver.cpp ├── Swap-nodes-in-pairs.cpp ├── Time-Needed-To-Inform-All-Employees.cpp ├── Unique-Paths-III.cpp ├── Valid_Parentheses.cpp ├── asteroid-collision.cpp ├── brick-wall.cpp ├── combination-sum.cpp ├── container-with-most-water.cpp ├── decode-string.cpp ├── dungeon-game.cpp ├── k-closest-points-to-origin.cpp ├── k-diff-pairs-in-an-array.cpp ├── letter-combinations-of-a-phone-number.cpp ├── maximum-subarray.cpp ├── merge-k-sorted-lists.cpp ├── minimum-add-to-make-parentheses-valid.cpp ├── minimum-remove-to-make-valid-parentheses.cpp ├── number-of-islands.cpp ├── remove-all-adjacent-duplicates-in-string.cpp ├── remove-element.cpp ├── teemo-attacking.cpp ├── two-sum.cpp └── xor-operation-in-an-array.cpp ├── CONTRIBUTING.md ├── Java ├── 20.ValidParentheses.java ├── Add-Two-Numbers.java ├── All_Paths_From_Source_to_Target.java ├── Arithmetic-Subarrays.java ├── Armstrong-Number.java ├── Balanced-Binary-Tree.java ├── BrokenCalculator.java ├── Degree-of-an-Array.java ├── Design-a-Stack-With-Increment-Operation.java ├── FizzBuzz.java ├── Happy-Number.java ├── June-LeetCoding-Challenge │ ├── Day22StrSubsequenceCount.java │ └── StringOperationsCount.java ├── LRU-Cache.java ├── May-LeetCoding-Challenge │ ├── Day-1-First-Bad-Version.java │ ├── Day-2-Jewels-and-Stones.java │ ├── Day-3-Ransom-Note.java │ ├── Day-5-First-Unique-Character.java │ └── README.md ├── Number-of-Good-Pairs.java ├── NumberOfIslands.java ├── PascalsTriangle118.java ├── Perm_Recus.java ├── Power-of-Three.java ├── Range-Sum-Query-Mutable.java ├── Redundant-Connection │ ├── README.md │ ├── images │ │ └── image-1.png │ └── redundant-connection.java ├── Same-Tree.java ├── Search-a-2d-matrix.java ├── SignOf.java ├── Sum_of_two_integers.java ├── Ugly-Number.java ├── WaterBottles.java ├── binary-tree-inorder-traversal.java ├── binary-tree-postorder-traversal.java ├── binary-tree-preorder-traversal.java ├── buddy-strings.java ├── can-make-arithmetic-progression-from-sequence.java ├── climbing-stairs.java ├── complete-binary-tree-inserter.java ├── convert-sorted-list-to-binary-search-tree.java ├── crawler-log-folder-leetcode-1598.java ├── design-circular-deque.java ├── detect-capital-use.java ├── evaluate_reverse_polish_notation.java ├── first-unique-character-in-a-string.java ├── generate-a-string-with-characters-that-have-odd-counts.java ├── graph_connectivity_with_threshold.java ├── integer-to-roman.java ├── intersection-of-two-linked-lists.java ├── linked-list-cycle-ii.java ├── linked-list-cycle.java ├── matrix-diagonal-sum.java ├── max-nesting-depth-parentheses.java ├── median-of-two-sorted-arrays.java ├── middle-of-the-linked-list.java ├── missing-number.java ├── number-complement.java ├── palindrome-number.java ├── path-sum.java ├── path-with-minimum-effort.java ├── ransom-note.java ├── remove-nth-node-from-end-of-list.java ├── reverse-integer.java ├── reverse-words-in-a-string.java ├── roman-to-integer.java ├── running-sum-of-1d-array.java ├── set-matrix-zeroes.java ├── shuffle-the-array.java ├── single-number.java ├── string-to-integer-atoi.java ├── sum-root-to-leaf-numbers.java ├── symmetric-tree.java ├── two-sum.java ├── valid-anagram.java ├── valid-sudoku.java ├── word-ladder.java └── xor-op-in-array.java ├── JavaScript ├── 111-minimum-depth-of-binary-tree.js ├── 146.LRU-Cache.js ├── 152.Maximum-Product-Subarray.js ├── 5.Longest-Palindromic-Substring.js ├── 50.Powxn.js ├── 98.Validate-Binary-Search-Tree.js ├── Binary-Tree-ZigZag-Traversal.js ├── Duplicate-Zeroes.js ├── First-Bad-Version.js ├── Subdomain-Visit-Count.js ├── findPeakElement.js └── single-number.js ├── LICENSE ├── PULL_REQUEST_PROCESS.md ├── PULL_REQUEST_TEMPLATE ├── Python ├── 100.SameTree.py ├── 101.SymmetricTree.py ├── 1042_FlowerPlantingwithNoAdjacent.py ├── 150.EvaluateReversePolishNotation.py ├── 1_TwoSum.py ├── 20_ValidParentheses.py ├── 35.SearchInsertPosition.py ├── 496_nextgreaterelement.py ├── 50.Powxn.py ├── 56_MergeIntervals.py ├── 5_LongestPalindromicSubstring.py ├── 621-Task-Scheduler.py ├── 622-Design-Circular-Queue.py ├── 994_Rotting_Oranges.py ├── Iterative-Inorder-tree-traversal.py ├── LRUCache.py ├── Longest_Substring_Without_Repeating_Characters.py ├── SmallestDifference.py ├── ThreeNumbersSum.py ├── baseK.py ├── best-time-to-buy-and-sell-stock-ii.py ├── binary-tree-inorder-traversal.py ├── container_with_most_water.py ├── contains-duplicate.py ├── count-good-triplets.py ├── decode-ways.py ├── detect-capital.py ├── divisor-game.py ├── edit-distance.py ├── find-minimum-in-rotated-sorted-array.py ├── group_anagram.py ├── jumpGame.py ├── longest-valid-parentheses.py ├── maximum-depth-of-binary-tree.py ├── pascals-triangle-ii.py ├── reorganize-string.py ├── rotate-array.py ├── search-in-rotated-sorted-array.py ├── single-number-ii.py ├── single-number-iii.py ├── single-number.py ├── split-a-string-in-balanced-strings.py ├── trapping_rain.py ├── wildcard-matching.py └── word-break-1.py ├── README.md └── _config.yml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [codedecks-in] 4 | custom: ["https://paypal.me/codedecks"] 5 | -------------------------------------------------------------------------------- /.github/config.yml: -------------------------------------------------------------------------------- 1 | # Configuration for behaviorbot - https://github.com/behaviorbot/ 2 | 3 | # Comment to be posted to on first time issues 4 | newIssueWelcomeComment: > 5 | # Thanks for helping us improve and opening your first issue here! Don't forget to give us a 🌟 to support us. 6 | 7 | While you're waiting, I just wanted to make sure you've had a chance to look at our 8 | [Readme](https://github.com/codedecks-in/LeetCode-Solutions/blob/master/README.md) and [Pull Request Guidelines](https://github.com/codedecks-in/LeetCode-Solutions/blob/master/PULL_REQUEST_PROCESS.md). 9 | 10 | # Comment to be posted to on PRs from first time contributors in your repository 11 | newPRWelcomeComment: > 12 | I can tell this is your first pull request! Thank you I'm so honored. :tada::tada::tada: 13 | I'll take a look at it ASAP! 14 | 15 | # Comment to be posted to on pull requests merged by a first time user 16 | firstPRMergeComment: > 17 | Your code looks great! Congrats, I've gone ahead and merged your first pull request! Keep it up! 18 | ![alt text](https://media.giphy.com/media/d31w24psGYeekCZy/giphy.gif "WOOHOO") 19 | -------------------------------------------------------------------------------- /C++/100_Same_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 isSameTree(TreeNode* p, TreeNode* q) { 15 | if(p == nullptr && q == nullptr) 16 | return true; 17 | if(p == nullptr || q == nullptr) 18 | return false; 19 | if(p->val != q->val) return false; 20 | 21 | return (isSameTree(p->right,q->right) && isSameTree(p->left, q->left)); 22 | } 23 | }; 24 | 25 | // Complexity Analysis: 26 | // Time complexity : O(N), where N is a number of nodes in the tree, since one visits each node exactly once. 27 | // Space complexity :O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree. -------------------------------------------------------------------------------- /C++/143.Reorder_List.cpp: -------------------------------------------------------------------------------- 1 | /* medium difficulty */ 2 | 3 | class Solution { 4 | public: 5 | void reorderList(ListNode* head) { 6 | 7 | //edge cases 8 | if ((!head) || (!head->next) || (!head->next->next)) return; 9 | 10 | int l=0; //to calculate the length 11 | ListNode* curr=head; 12 | while(curr){ 13 | l++; 14 | curr=curr->next; 15 | } 16 | 17 | //stack to store the second half of the elements of the ll 18 | stack s; 19 | curr=head; 20 | 21 | //iterating till the end of the first half 22 | int m=(l+1)/2; 23 | while(m>=1){ 24 | curr=curr->next; 25 | m--; 26 | } 27 | 28 | //pushing the second half of the elements in the stack 29 | while(curr){ 30 | s.push(curr); 31 | curr=curr->next; 32 | } 33 | 34 | //attaching the elements from the top of the stack to the first half of the elements 35 | curr=head; 36 | while(curr&&!s.empty()){ 37 | ListNode* temp=s.top(); 38 | s.pop(); 39 | temp->next=curr->next; 40 | curr->next=temp; 41 | curr=curr->next->next; 42 | } 43 | curr->next=NULL; 44 | } 45 | }; -------------------------------------------------------------------------------- /C++/189.Rotate-array.cpp: -------------------------------------------------------------------------------- 1 | difficulty level: Medium 2 | class Solution { 3 | public: 4 | void rotate(vector& nums, int k) { 5 | int n = nums.size(); 6 | k = k % n; 7 | // we first reverse all the elements,[7 6 5 4 3 2 1] 8 | for (int i = 0, j = n - 1; i < j; i++, j--) { 9 | swap(nums[i], nums[j]); 10 | } 11 | // then we reverse the set of elements sized k for example [7 6 5 4 3 2 1] = [ 5 6 7 4 3 2 1] 12 | for (int i = 0, j = k - 1; i < j; i++, j--) { 13 | swap(nums[i], nums[j]); 14 | } 15 | //finally we reverse the ending elements too = 5 6 7 1 2 3 4 16 | for (int i = k, j = n - 1; i < j; i++, j--) { 17 | swap(nums[i], nums[j]); 18 | } 19 | } 20 | }; 21 | 22 | Time complexity:O(n) 23 | Space Complexity:O(1) 24 | /* 25 | Input: nums = [1,2,3,4,5,6,7], k = 3 26 | Output: [5,6,7,1,2,3,4] 27 | 28 | Example 2: 29 | 30 | Input: nums = [-1,-100,3,99], k = 2 31 | Output: [3,99,-1,-100] 32 | */ 33 | -------------------------------------------------------------------------------- /C++/238.Product_of_array_except_self: -------------------------------------------------------------------------------- 1 | /* 2 | This code uses prefix and postfix product to evaluate answer. 3 | We just need to traverse the array twice, once to the left and once to the right. 4 | Then answer of ith place can be calculated using constant time. 5 | 6 | Time Complexity : O(n) 7 | Space Complexity : O(n) 8 | */ 9 | 10 | 11 | 12 | class Solution { 13 | public: 14 | vector productExceptSelf(vector& nums) { 15 | int n = nums.size(); //Variable for size of the array 16 | //pre[] stores product of all numbers to the left of ith element 17 | //post[] stores product of all numbers to the right of ith element 18 | int pre[n],post[n]; 19 | 20 | //loop to assign values to pre[] 21 | int mul=1; 22 | for(int i=0; i=0; i--){ 30 | mul*=nums[i]; 31 | post[i]=mul; 32 | } 33 | 34 | //declare a vector to return 35 | vector out; 36 | 37 | //first element of out is just going to be product of all elements except first one 38 | out.push_back(post[1]); 39 | 40 | //value of out[i] = product of all elements except ith element 41 | //which is nothing but pre[i-1]*[post[i+1]] 42 | for(int i=1; i> threeSum(vector& nums) { 4 | vector > res; 5 | 6 | std::sort(nums.begin(), nums.end()); 7 | 8 | for (int i = 0; i < nums.size(); i++) { 9 | 10 | int target = -nums[i]; 11 | int front = i + 1; 12 | int back = nums.size() - 1; 13 | 14 | while (front < back) { 15 | 16 | int sum = nums[front] + nums[back]; 17 | 18 | // Finding answer which start from number nums[i] 19 | if (sum < target) 20 | front++; 21 | 22 | else if (sum > target) 23 | back--; 24 | 25 | else { 26 | vector triplet(3, 0); 27 | triplet[0] = nums[i]; 28 | triplet[1] = nums[front]; 29 | triplet[2] = nums[back]; 30 | res.push_back(triplet); 31 | 32 | // Processing duplicates of Number 2 33 | // Rolling the front pointer to the next different number forwards 34 | while (front < back && nums[front] == triplet[1]) front++; 35 | 36 | // Processing duplicates of Number 3 37 | // Rolling the back pointer to the next different number backwards 38 | while (front < back && nums[back] == triplet[2]) back--; 39 | } 40 | 41 | } 42 | 43 | // Processing duplicates of Number i 44 | while (i + 1 < nums.size() && nums[i + 1] == nums[i]) 45 | i++; 46 | 47 | } 48 | 49 | return res; 50 | } 51 | }; -------------------------------------------------------------------------------- /C++/Baseball-Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calPoints(vector& ops) { 4 | stack s; 5 | auto it=ops.begin(); 6 | while(it!=ops.end()){ 7 | if(*it=="+"){ //if char is + then new record is sum of last two records 8 | int val1=s.top(); 9 | s.pop(); 10 | int val2=s.top(); 11 | s.push(val1); 12 | s.push(val1+val2); 13 | } 14 | else if(*it=="D"){ //if char is D then new record is twice the last record 15 | s.push(2*s.top()); 16 | } 17 | else if(*it=="C"){ //if char is C then the last record is invalidated , hence popped 18 | s.pop(); 19 | } 20 | else{ // if none of these conditions occur then just push the new record to stack 21 | s.push(stoi(*it)); 22 | } 23 | it++; 24 | } 25 | int count=0; 26 | while(!s.empty()) //iteratively pop the top value of the stack and add it to the total 27 | { 28 | count+=s.top(); 29 | s.pop(); 30 | } 31 | return count; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/Best-Time-to-Buy-and-Sell-Stock-II.cpp: -------------------------------------------------------------------------------- 1 | /*Runtime: 8 ms, faster than 96.30% of C++ online submissions for Best Time to Buy and Sell Stock II. 2 | Memory Usage: 13.4 MB, less than 5.04% of C++ online submissions for Best Time to Buy and Sell Stock II. 3 | */ 4 | 5 | class Solution 6 | { 7 | public: 8 | int maxProfit(vector &prices) 9 | { 10 | int sum = 0; 11 | //If the number of element in the array are zero or one just return zero. 12 | if (prices.size() == 1 or prices.size() == 0) 13 | { 14 | return 0; 15 | } 16 | 17 | //Traverse the array and compare the consecutive two elements . 18 | for (int i = 0; i < prices.size() - 1; i++) 19 | { 20 | // If first consecuitve element is less than second subtract both and add in the sum varibale. 21 | if (prices[i] < prices[i + 1]) 22 | { 23 | sum += prices[i + 1] - prices[i]; 24 | 25 | } 26 | } 27 | 28 | //Finally return the sum. 29 | return sum; 30 | 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/Binary-Tree-Cameras.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int ans=0; 15 | unordered_set covered; 16 | void dfs(TreeNode* root,TreeNode* parent){ 17 | if(root==NULL) 18 | return; 19 | dfs(root->left,root); 20 | dfs(root->right,root); 21 | if((parent==NULL && covered.find(root)==covered.end()) || covered.find(root->left)==covered.end() || covered.find(root->right)==covered.end()){ 22 | ans++; 23 | covered.insert(root); 24 | covered.insert(parent); 25 | covered.insert(root->left); 26 | covered.insert(root->right); 27 | } 28 | } 29 | int minCameraCover(TreeNode* root) { 30 | covered.insert(NULL); 31 | dfs(root,NULL); 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/Binary-Tree-Level-Order-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: 3 | Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). 4 | 5 | Example 1: 6 | Input: root = [3,9,20,null,null,15,7] 7 | Output: [[3],[9,20],[15,7]] 8 | 9 | Example 2: 10 | Input: root = [1] 11 | Output: [[1]] 12 | 13 | Example 3: 14 | Input: root = [] 15 | Output: [] 16 | 17 | Constraints: 18 | The number of nodes in the tree is in the range [0, 2000]. 19 | -1000 <= Node.val <= 1000 20 | */ 21 | 22 | 23 | /* 24 | Space Complexity : O(N) 25 | Time Complexity : O(N) 26 | Difficulty level : Medium 27 | */ 28 | 29 | class Solution { 30 | public: 31 | void fun( map>&mp, TreeNode* root, int level) 32 | { 33 | if(!root) 34 | return; 35 | 36 | mp[level].push_back(root->val); 37 | 38 | fun(mp,root->left,level+1); 39 | fun(mp,root->right,level+1); 40 | 41 | } 42 | 43 | vector> levelOrder(TreeNode* root) { 44 | vector>v; 45 | if(!root) 46 | return v; 47 | 48 | map>mp; 49 | int level=0; 50 | fun(mp,root,level); 51 | auto it=mp.begin(); 52 | while(it!=mp.end()) 53 | { 54 | v.push_back(it->second); 55 | it++; 56 | } 57 | 58 | return v; 59 | 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /C++/Binary-Tree-Maximum-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 | * Runtime : 40ms 13 | * Memory : 28.5 MB 14 | * 15 | * 16 | */ 17 | class Solution { 18 | public: 19 | 20 | int solve(TreeNode* root, int &ans) 21 | { 22 | if(root == NULL) 23 | return 0; 24 | 25 | # to traverse left and right childs 26 | int l = solve(root->left, ans); 27 | int r = solve(root->right, ans); 28 | 29 | /* to find max sum including root_val and left and child subtree 30 | max sum or just including root val if result from subtree is - negative 31 | */ 32 | int temp = max(max(l,r)+root->val, root->val); 33 | 34 | /* in case max sum does not include main root and 35 | forms maximum sum path through sub tree 36 | */ 37 | int res = max(temp, root->val+l+r); 38 | ans = max(res,ans); 39 | return temp; 40 | } 41 | int maxPathSum(TreeNode* root) { 42 | int ans = INT_MIN; 43 | solve(root,ans); 44 | return ans; 45 | 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /C++/Binary-Tree-Zigzag-Level-Order-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector> zigzagLevelOrder(TreeNode* root) { 13 | vector> finalvec; 14 | int flag = 1; 15 | TreeNode *t; 16 | stacks1; 17 | stacks2; 18 | if(root==NULL) 19 | return finalvec; 20 | s1.push(root); 21 | // vectortemp; 22 | // temp.push_back(root->val); 23 | // finalvec.push_back(temp); 24 | while(!s1.empty() || !s2.empty()) 25 | { 26 | if(flag == 1) 27 | { 28 | vectortemp; 29 | while(!s1.empty()) 30 | { 31 | t = s1.top(); 32 | s1.pop(); 33 | temp.push_back(t->val); 34 | if(t->left) 35 | s2.push(t->left); 36 | if(t->right) 37 | s2.push(t->right); 38 | 39 | } 40 | finalvec.push_back(temp); 41 | flag = 0; 42 | } 43 | else 44 | { 45 | vectortemp; 46 | while(!s2.empty()) 47 | { 48 | t = s2.top(); 49 | s2.pop(); 50 | temp.push_back(t->val); 51 | if(t->right) 52 | s1.push(t->right); 53 | if(t->left) 54 | s1.push(t->left); 55 | 56 | } 57 | finalvec.push_back(temp); 58 | flag = 1; 59 | } 60 | } 61 | 62 | return finalvec; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /C++/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement: Binary Search 2 | 3 | // Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 4 | 5 | 6 | //Solution: 7 | class Solution { 8 | public: 9 | int search(vector& nums, int target) { 10 | 11 | int si=0, ei=nums.size()-1; 12 | 13 | while(si <= ei) { 14 | // index of the middle element 15 | int mid = si + (ei-si)/2; 16 | 17 | // found target element 18 | if(nums[mid] == target) { 19 | return mid; 20 | } else if(nums[mid] < target) { // target on right side of middle element 21 | si += 1; 22 | } else { // target on left side of middle element 23 | ei -= 1; 24 | } 25 | } 26 | 27 | // target element not present in given array 28 | return -1; 29 | } 30 | }; 31 | 32 | // Time Complexity: O(log(n)) 33 | 34 | -------------------------------------------------------------------------------- /C++/Cherry-Pickup-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | // Let's run a simple dfs. If we come to the same cell with two robots, let's subtract that value. 4 | int dfs(int n, int m, int r, int c1, int c2, unordered_map>, int> &dp, vector> &grid) { 5 | if (c1 < 0 || c1 >= m || c2 < 0 || c2 >= m) { 6 | return 0; 7 | } else if (r == n) { 8 | return 0; 9 | } else if (dp.count({r, {c1, c2}}) > 0) { 10 | return dp[{r, {c1, c2}}]; 11 | } else { 12 | int current_ceil = grid[r][c1] + grid[r][c2]; 13 | 14 | // Here is that subtraction 15 | if (c1 == c2) { 16 | current_ceil -= grid[r][c2]; 17 | } 18 | 19 | // Running dfs from all possible cells 20 | int mx = 0; 21 | for (int i = -1; i <= 1; ++i) { 22 | for (int j = -1; j <= 1; ++j) { 23 | mx = max(mx, dfs(n, m, r + 1, c1 + i, c2 + j, dp, grid)); 24 | } 25 | } 26 | 27 | return dp[{r, {c1, c2}}] = current_ceil + mx; 28 | } 29 | } 30 | public: 31 | int cherryPickup(vector>& grid) { 32 | unordered_map>, int> dp; 33 | 34 | int n = grid.size(); 35 | int m = grid[0].size(); 36 | 37 | return dfs(n, m, 0, 0, m - 1, dp, grid); 38 | } 39 | }; -------------------------------------------------------------------------------- /C++/Count-Primes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int countPrimes(int n) { 5 | 6 | vector arr(n+1,0); 7 | arr[0]=true; 8 | arr[1]=true; 9 | for(int i=2;i*i<=n;i++){ 10 | if(arr[i]==false){ 11 | for(int j = i*i;j<=n;j+=i){ 12 | arr[j]=true; 13 | } 14 | } 15 | } 16 | 17 | int count = 0; 18 | for(int i=2;i findOrder(int numCourses, vector>& prerequisites) { 7 | int n=numCourses; 8 | int m=prerequisites.size(); 9 | vectorans; 10 | vectorv(n,0); 11 | vector>g(n); 12 | 13 | 14 | for(int i=0;iq; 19 | for(int i=0;i>& adjlist, vector& visited, int i) { 18 | 19 | // base condition 20 | if(visited[i]==1) return false; 21 | visited[i]=1; // mark as being visited 22 | 23 | for(int a:adjlist[i]) { 24 | if(!dfs(adjlist, visited, a)) // dfs(adjlist, visited, a) == false 25 | return false; 26 | } 27 | 28 | visited[i] = 2; // mark as visited 29 | return true; 30 | } 31 | 32 | 33 | bool canFinish(int numc, vector>& prereq) { 34 | 35 | // numc: numCourses 36 | // prereq: prerequisites 37 | 38 | // create adjacency list 39 | vector> adjlist(numc, vector()); 40 | for(vector& p:prereq) 41 | adjlist[p[0]].push_back(p[1]); 42 | 43 | vector visited(numc, 0); 44 | // unvisited: 0 45 | // being visited: 1 46 | // completely visited: 2 47 | for(int i=0; i& logs) { 4 | stack s; //stack s is initialized and stack is empty when you are on main folder 5 | for(int i=0;i dailyTemperatures(vector& temperatures) { 33 | vector ans(temperatures.size()); 34 | stack s; 35 | 36 | for(int i=0; i temperatures[s.top()]){ 38 | const int k = s.top(); 39 | s.pop(); 40 | ans[k] = i - k; 41 | } 42 | s.push(i); 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /C++/Defanging an IP Address.cpp: -------------------------------------------------------------------------------- 1 | /*Given a valid (IPv4) IP address, return a defanged version of that IP address. 2 | A defanged IP address replaces every period "." with "[.]".*/ 3 | 4 | /* Input: address = "1.1.1.1" 5 | Output: "1[.]1[.]1[.]1"*/ 6 | 7 | #include 8 | class Solution { 9 | public: 10 | string defangIPaddr(string address) { 11 | string op; 12 | //A for loop which will execute till the address[i] which means the string runs till the last character of the string is Null 13 | for(int i=0;address[i]!='\0';i++) 14 | { 15 | //if address[i]== '.' which means that if the in a string contains a period we'll replace it with [.] 16 | if(address[i]=='.') 17 | { 18 | //This line adds the square brackets if there's a period in a string 19 | op=op+'['+ address[i]+']'; 20 | i++; 21 | 22 | } 23 | op=op+address[i]; 24 | 25 | } 26 | return op; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/Degree-of-an-Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 4 | * Runtime : 38 ms 5 | * Memory : 53.3 MB 6 | * 7 | * 8 | */ 9 | 10 | class Solution { 11 | public int findShortestSubArray(int[] nums) { 12 | Map left = new HashMap(), right = new HashMap(), count = new HashMap(); 13 | 14 | //find the leftmost and rightmost index of each characters 15 | for(int i= 0;i 1 9 | // B -> 2 10 | // C -> 3 11 | // ... 12 | // Z -> 26 13 | // AA -> 27 14 | // AB -> 28 15 | // ... 16 | 17 | //Solution: 18 | class Solution { 19 | public: 20 | int titleToNumber(string s) { 21 | 22 | int power=0, colnum=0; 23 | 24 | while(!s.empty()) { 25 | 26 | colnum += (s[s.size()-1] - 'A' + 1)*pow(26, power); 27 | power++; 28 | s=s.substr(0, s.size()-1); 29 | 30 | } 31 | 32 | return colnum; 33 | } 34 | }; 35 | 36 | //Complexity: O(n) 37 | -------------------------------------------------------------------------------- /C++/Excel-Sheet-Column-Title.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Runtime - 0ms 3 | * Memory - 5.8 4 | * LOGIC - simple maths 5 | * 6 | */ 7 | 8 | class Solution { 9 | public: 10 | string convertToTitle(int n) { 11 | string s=""; 12 | while(n>26){ 13 | int rem = n%26; 14 | n=n/26; 15 | if(rem==0){ 16 | rem = 26; 17 | n--; 18 | } 19 | s.push_back('A'+(rem-1)); 20 | } 21 | s.push_back('A'+n-1); 22 | reverse(s.begin(),s.end()); 23 | return s; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /C++/Find-The-Difference.cpp: -------------------------------------------------------------------------------- 1 | //time complexity O(n+m) where n and m are the number of input characters in each input string respectively 2 | //space compexity is O(1) since there is a limit on number of possible unique characters 3 | //loop through the first string and add a count of characters to hashmap 4 | //loop through second string and for each letter lookup in hashmap. If found, decrement the count in the hasmap. If the count <0 for any letter then we have found our extra character 5 | //else if the letter cannot be found in our hashmap, then this must be the extra character 6 | //Otherwise if no differences can be found between the two input strings we just return null character 7 | 8 | 9 | 10 | class Solution { 11 | public: 12 | char findTheDifference(string s, string t) { 13 | 14 | char returnChar= '\0'; 15 | std::unordered_map ourMap; 16 | 17 | //count the letters in the input string and add it to map 18 | for (const char& letter:s) { 19 | 20 | if(ourMap.find(letter)==ourMap.end()){ ourMap[letter]=1;} 21 | else{ourMap[letter]++;} 22 | } 23 | 24 | 25 | //compare with letters in other string 26 | for (const char& letter:t){ 27 | 28 | //if you can find the letter then decrement it 29 | if(ourMap.find(letter)!=ourMap.end()) { 30 | 31 | ourMap[letter]--; 32 | if(ourMap[letter]<0) { return letter; } 33 | 34 | } 35 | 36 | else{return letter;} 37 | } 38 | 39 | return returnChar; 40 | 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/Integer-Break.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 4 | * Runtime : 4 ms 5 | * Memory : 6 MB 6 | * 7 | * 8 | */ 9 | class Solution { 10 | public: 11 | 12 | int integerBreak(int n) { 13 | 14 | // when n = 0,1 no possible cuts hence store 0 15 | int val[n + 1]; 16 | val[0] = val[1] = 0; 17 | 18 | // calculate for all possible cuts possible from 1 to n 19 | for (int i = 1; i <= n; i++) { 20 | int max_value = INT_MIN; 21 | 22 | /*for n = 6 calculate for all possible cuts like maximum of 23 | {(1,5),(5,1)}, {(4,2),(2,4)},{ (3,3) } 24 | */ 25 | for (int j = 1; j <= i / 2; j++) { 26 | max_value = max(max_value, max((i - j) * j, j * val[i - j])); 27 | } 28 | 29 | val[i] = max_value; 30 | } 31 | 32 | return val[n]; 33 | 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/Is-Graph-Bipartite.cpp: -------------------------------------------------------------------------------- 1 | //CPP BFS solution 2 | //Time complexity O(V+E) 3 | //Space Complexity O(V) 4 | class Solution { 5 | public: 6 | bool isBipartite(vector>& graph) { 7 | int n=graph.size(); 8 | vectorv(n,false); 9 | vectorc(n,-1); 10 | queueq; 11 | 12 | for(int i=0;i& h) { 8 | int n = h.size(); 9 | 10 | stack s; 11 | int curr = 0; 12 | int ans = 0; 13 | int tp; 14 | int i = 0; 15 | while (i < n) { 16 | if (s.empty() || h[s.top()] <= h[i]) s.push(i++); 17 | else { 18 | tp = s.top(); s.pop(); 19 | if (s.empty()) curr = h[tp] * i; 20 | else curr = h[tp] * (i - s.top() - 1); 21 | ans = max(ans, curr); 22 | } 23 | } 24 | while (!s.empty()) { 25 | tp = s.top(); s.pop(); 26 | if (s.empty()) curr = h[tp] * i; 27 | else curr = h[tp] * (i - s.top() - 1); 28 | ans = max(ans, curr); 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/Linked-List-Cycle-II.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | ListNode* detectCycle(ListNode *head) 6 | { 7 | //If head is null or head->next is null dont do anything just return. 8 | if (!head) return NULL; 9 | if (head->next == NULL) return NULL; 10 | //Take two pointers slow and fast both initially pointing to head . 11 | ListNode *fast = head; 12 | ListNode *slow = head; 13 | while (fast and fast->next) 14 | { 15 | // Move fast pointer two step and slow pointer one step forward. 16 | fast = fast->next->next; 17 | slow = slow->next; 18 | //At some time if fast and slow are equal it means there is a cycle . 19 | if (fast == slow) break; 20 | } 21 | 22 | if (fast == NULL or fast->next == NULL) return NULL; 23 | //Now we point one pointer to head and increment both the pointers one step untill slow and fast pointer do not become equal. 24 | slow = head; 25 | while (slow != fast) 26 | { 27 | slow = slow->next; 28 | fast = fast->next; 29 | } 30 | 31 | return slow; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/Longest-Mountain-in-Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Difficulty: medium 3 | runtime: 36ms 4 | */ 5 | /* 6 | Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:B.length >= 3 7 | There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] 8 | (Note that B could be any subarray of A, including the entire array A.) 9 | Given an array A of integers, return the length of the longest mountain. Return 0 if there is no mountain. 10 | 11 | Note: 12 | 0 <= A.length <= 10000 13 | 0 <= A[i] <= 10000 14 | 15 | Example 1: 16 | Input: [2,1,4,7,3,2,5] 17 | Output: 5 18 | Explanation: The largest mountain is [1,4,7,3,2] which has length 5. 19 | 20 | Example 2: 21 | Input: [2,2,2] 22 | Output: 0 23 | Explanation: There is no mountain. 24 | 25 | Followup: 26 | Can you solve it using only one pass? YES 27 | Can you solve it in O(1) space? YES 28 | ___________________________________________________________________________________________________________________________ 29 | CodeExplain: 30 | while treversing the array..we have to just count increasing and decreasing numbers. 31 | and maximize the addition of increasing and decreasing numbers. 32 | 33 | */ 34 | 35 | class Solution { 36 | public: 37 | int longestMountain(vector& A) { 38 | int n=A.size(); 39 | if(n<3) 40 | return 0; 41 | int ans = 0, left = 0, right = 0;// left = increasing, right = decreasing 42 | for(int i=1;iA[i-1]){ //increasing count 45 | if(right){ 46 | left=0; 47 | right=0; 48 | } 49 | left += (1 + (left==0)); 50 | } 51 | else if(A[i] val <= l2 -> val) 28 | { 29 | l1 -> next = mergeTwoLists(l1 -> next, l2); 30 | return l1; 31 | } 32 | 33 | else 34 | { 35 | l2 -> next = mergeTwoLists(l1, l2 -> next); 36 | return l2; 37 | } 38 | } 39 | }; 40 | 41 | 42 | -------------------------------------------------------------------------------- /C++/Most-Stones-Removed-with-Same-Row-or-Column.cpp: -------------------------------------------------------------------------------- 1 | // C++ Union Find Solution 2 | // Time Complexity: O(V) 3 | // Space Complexity: O(V) 4 | 5 | class Solution { 6 | public: 7 | vector parent; 8 | void initParent(int n) { 9 | for (int i = 0; i <= n; ++i) 10 | { 11 | parent.push_back(i); 12 | } 13 | } 14 | 15 | int find_parent(int& x) { 16 | if (parent[x] == x) return x; 17 | parent[x] = find_parent(parent[x]); 18 | return parent[x]; 19 | } 20 | 21 | bool unionEdge(int& x, int& y) { 22 | int parent_x = find_parent(x); 23 | int parent_y = find_parent(y); 24 | 25 | if (parent_x == parent_y) return false; 26 | 27 | if (parent_x > parent_y) parent[parent_x] = parent_y; 28 | else parent[parent_y] = parent_x; 29 | 30 | return true; 31 | } 32 | 33 | // map to store the index of first occurence of parent of the current index 34 | unordered_map rows, cols; 35 | 36 | int removeStones(vector>& stones) { 37 | initParent(stones.size()); 38 | 39 | for (int k = 0; k < stones.size(); k++) { 40 | int i = stones[k][0], j = stones[k][1]; 41 | int par_i = INT_MAX, par_j = INT_MAX; 42 | 43 | if (rows.find(i) == rows.end()) rows[i] = k; 44 | else par_i = rows[i]; 45 | 46 | if (cols.find(j) == cols.end()) cols[j] = k; 47 | else par_j = cols[j]; 48 | 49 | if (par_i != INT_MAX) 50 | unionEdge(par_i, k); 51 | 52 | if (par_j != INT_MAX) 53 | unionEdge(par_j, k); 54 | } 55 | 56 | // ans represent number of disjoint sets 57 | int ans = 0; 58 | rows.clear(); cols.clear(); 59 | unordered_set uniq_parents; 60 | 61 | for (int k = 0; k < stones.size(); k++) { 62 | int par_i = find_parent(k); 63 | 64 | if (uniq_parents.find(par_i) == uniq_parents.end()) { 65 | ans++; 66 | uniq_parents.insert(par_i); 67 | } 68 | } 69 | 70 | return stones.size() - ans; 71 | } 72 | }; -------------------------------------------------------------------------------- /C++/Move-Zeroes.cpp: -------------------------------------------------------------------------------- 1 | 2 | //Problem Statement: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | //Solution: 5 | class Solution { 6 | public: 7 | void moveZeroes(vector& nums) { 8 | int i = 0; 9 | for (int j = 0; j < nums.size(); j++) { 10 | // Bring all non zero numbers to the start of the array 11 | if (nums[j] != 0) { 12 | nums[i++] = nums[j]; 13 | } 14 | } 15 | 16 | while(i>& times, int N, int K) { 6 | vector d(N + 1, INT_MAX); 7 | d[K] = 0; 8 | for (int i = 0; i < N; ++i) { 9 | for (int j = 0; j < times.size(); ++j) { 10 | if (d[times[j][1]] > d[times[j][0]] + times[j][2]) { 11 | d[times[j][1]] = d[times[j][0]] + times[j][2]; 12 | } 13 | } 14 | } 15 | 16 | int a = *max_element(d.begin() + 1, d.end()); 17 | return a >= INT_MAX ? -1 : a; 18 | } 19 | }; -------------------------------------------------------------------------------- /C++/Number-Complement.cpp: -------------------------------------------------------------------------------- 1 | // Problem URL: https://leetcode.com/problems/single-number-iii/ 2 | /* 3 | * Runtime - 0ms 4 | * Memory - 5.8mb 5 | */ 6 | 7 | class Solution { 8 | public: 9 | int findComplement(int num) { 10 | int inv = 0, iter = 0; 11 | int reminder; 12 | while(num) { 13 | inv = inv | ((1 - (num % 2))< 2 | class RecentCounter { 3 | deque req; 4 | public: 5 | RecentCounter() { 6 | req={}; 7 | } 8 | 9 | int ping(int t) { 10 | req.push_back(t); 11 | while(req.front() < t-3000) req.pop_front(); 12 | return req.size(); 13 | } 14 | }; 15 | 16 | /** 17 | * Your RecentCounter object will be instantiated and called as such: 18 | * RecentCounter* obj = new RecentCounter(); 19 | * int param_1 = obj->ping(t); 20 | */ 21 | -------------------------------------------------------------------------------- /C++/Partition-Equal-Subset-Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 4 | * Runtime : 80ms 5 | * Memory : 9.6 MB 6 | * Logic : 0/1 knapsack concept used to calculate subsetSum 7 | */ 8 | class Solution { 9 | public: 10 | 11 | // using 0/1 knapsack top down approach 12 | bool subsetSum(vector& nums, int sum) 13 | { 14 | // size = nums+1, sum+1 15 | bool t[nums.size()+1][sum+1]; 16 | 17 | for(int i= 0;i<=nums.size();i++) 18 | { 19 | t[i][0] = true; 20 | } 21 | 22 | for(int i= 0;i<=sum;i++) 23 | { 24 | t[0][i] = false; 25 | } 26 | 27 | t[0][0] = true; 28 | 29 | for(int i= 1;i& nums) { 47 | 48 | int n = nums.size(); 49 | 50 | int sum = 0; 51 | for(int i = 0;i>&v, vectork,TreeNode*r,int s){ 7 | if(r==NULL){ 8 | return; 9 | } 10 | if(s==r->val&&r->left==NULL&&r->right==NULL){ 11 | k.push_back(r->val); 12 | v.push_back(k); 13 | //k.clear(); 14 | return; 15 | 16 | } 17 | else if(s!=r->val&&r->left==NULL&&r->right==NULL){ 18 | return; 19 | } 20 | 21 | k.push_back(r->val); 22 | s-=r->val; 23 | dfs(v,k,r->left,s); 24 | dfs(v,k,r->right,s); 25 | 26 | 27 | 28 | return; 29 | 30 | } 31 | vector> pathSum(TreeNode* root, int sum) { 32 | vector>v; 33 | vectork; 34 | dfs(v,k,root,sum); 35 | return v; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/Recover-a-Tree-From-Preorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* recoverFromPreorder(string s) { 15 | int i = 0; 16 | int n = s.size(); 17 | 18 | vector> vp; 19 | while (i < n) { 20 | int cnt = 0; 21 | while (i < n && s[i] == '-') { 22 | ++cnt; 23 | ++i; 24 | } 25 | 26 | string num; 27 | while (i < n && '0' <= s[i] && s[i] <= '9') { 28 | num += s[i]; 29 | ++i; 30 | } 31 | 32 | int m = stoi(num); 33 | 34 | vp.push_back({cnt, m}); 35 | } 36 | 37 | map> last; 38 | 39 | TreeNode * result = new TreeNode(vp[0].second); 40 | 41 | last[vp[0].first] = {0, result}; 42 | 43 | for (int i = 1; i < vp.size(); ++i) { 44 | if (last[vp[i].first - 1].first == 0) { 45 | last[vp[i].first - 1].second->left = new TreeNode(vp[i].second); 46 | last[vp[i].first - 1].first = 1; 47 | last[vp[i].first] = {0, last[vp[i].first - 1].second->left}; 48 | } else { 49 | last[vp[i].first - 1].second->right = new TreeNode(vp[i].second); 50 | last[vp[i].first - 1].first = 2; 51 | last[vp[i].first] = {0, last[vp[i].first - 1].second->right}; 52 | } 53 | } 54 | 55 | return result; 56 | } 57 | }; -------------------------------------------------------------------------------- /C++/RedundantConnection.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ProblemLink : https://leetcode.com/problems/redundant-connection/ 3 | 4 | In this problem, a tree is an undirected graph that is connected and has no cycles. 5 | 6 | You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. 7 | The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. 8 | The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph. 9 | 10 | Return an edge that can be removed so that the resulting graph is a tree of n nodes. 11 | If there are multiple answers, return the answer that occurs last in the input. 12 | */ 13 | 14 | class Solution { 15 | public: 16 | int find(int v,vector& parent){ 17 | if(parent[v]==-1){ 18 | return v; 19 | } 20 | return find(parent[v],parent); 21 | } 22 | void Union(int x,int y,vector& parent){ 23 | parent[x]=y; 24 | } 25 | 26 | vector findRedundantConnection(vector>& edges) { 27 | int V = edges.size(); 28 | vector parent(V+1,-1); 29 | int v1,v2; 30 | for(auto x:edges){ 31 | int fromP = find(x[0],parent); 32 | int toP = find(x[1],parent); 33 | if(fromP==toP){ 34 | v1=x[0]; 35 | v2=x[1]; 36 | } 37 | else{ 38 | Union(fromP,toP,parent); 39 | } 40 | } 41 | vector ans; 42 | ans.push_back(v1); 43 | ans.push_back(v2); 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /C++/Remove-Covered-Intervals.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement: Remove Covered Intervals 2 | 3 | // Given a list of intervals, remove all intervals that are covered by another interval in the list. 4 | 5 | // Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. 6 | 7 | // After doing so, return the number of remaining intervals. 8 | 9 | //Solution: 10 | class Solution { 11 | public: 12 | int removeCoveredIntervals(vector>& intervals) { 13 | 14 | int ans=0; 15 | for(int i=0; i= intervals[j][0] && intervals[i][1] <= intervals[j][1]) { 19 | // cout << i << endl; 20 | ans++; break; 21 | } 22 | } 23 | } 24 | 25 | return intervals.size()-ans; 26 | } 27 | }; 28 | 29 | //Complexity: O(n*n) 30 | 31 | 32 | 33 | SIMPLIFIED SOLUTION in O(nlogn) time 34 | 35 | // 36 | class Solution { 37 | public: 38 | int removeCoveredIntervals(vector>& intervals) { 39 | sort(intervals.begin(),intervals.end(),[](vector& v1,vector& v2){ 40 | if(v1[0]==v2[0]) 41 | return v1[1]>v2[1]; 42 | return v1[0]end) 49 | { 50 | end = intervals[i][1]; 51 | sz++; 52 | } 53 | } 54 | return sz; 55 | } 56 | }; 57 | 58 | // 59 | -------------------------------------------------------------------------------- /C++/Reshape-the-Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixReshape(vector>& mat, int r, int c) { 4 | if(mat.size()*mat[0].size() != r*c) return mat; 5 | vector v; 6 | for(int i=0;i> vnew; 13 | vector input; 14 | for(int i=0;i INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; 10 | if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; 11 | rev = rev * 10 + pop; 12 | } 13 | return rev; 14 | } 15 | }; 16 | 17 | -------------------------------------------------------------------------------- /C++/Roman_to_Integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /*** 13. Roman to Intege (Easy)***/ 4 | 5 | /* 6 | Symbol Value 7 | I 1 8 | V 5 9 | X 10 10 | L 50 11 | C 100 12 | D 500 13 | M 1000 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int romanToInt(string s) { 19 | int current = 0, last =0; 20 | int sum=0; 21 | for(int i=0;ilast) 54 | sum-=2*last; 55 | last = current; 56 | 57 | } 58 | return sum; 59 | } 60 | }; -------------------------------------------------------------------------------- /C++/Single-Number-II.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode URL: https://leetcode.com/problems/single-number-ii 2 | /* 3 | * Runtime - 4ms 4 | * Memory - 9.5 5 | */ 6 | 7 | class Solution { 8 | public: 9 | int singleNumber(vector& nums) { 10 | int a=0, b=0; 11 | for(int num: nums) { 12 | a = b & (a^num); 13 | b = a | (b^num); 14 | } 15 | return b; 16 | } 17 | }; -------------------------------------------------------------------------------- /C++/Single-Number-III.cpp: -------------------------------------------------------------------------------- 1 | // Problem URL: https://leetcode.com/problems/single-number-iii/ 2 | /* 3 | * Runtime - 8ms 4 | * Memory - 10mb 5 | */ 6 | 7 | class Solution { 8 | public: 9 | vector singleNumber(vector& nums) { 10 | int xor_all = 0; 11 | // Get the XOR value of all the numbers in the vector 12 | for(int num: nums) xor_all ^= num; 13 | // xor_all will contain a^b, where a and b are repeated only once. 14 | // if value of a bit in xor is 1, then it means either a or b has 15 | // 1 in that position, but not both. We can use this to find the answer. 16 | int setbit = 1; 17 | // Find the first position in xor_all where the value is 1 18 | while((setbit & xor_all) == 0) 19 | setbit <<= 1; 20 | 21 | vector result(2); 22 | 23 | // We basically split the numbers into two sets. 24 | // All numbers in first set will have a bit in the setbit position. 25 | // Second set of numbers, will have 0 in the setbit position. 26 | for(int num: nums) { 27 | if(num & setbit) { 28 | result[0] ^= num; 29 | } else { 30 | result[1] ^= num; 31 | } 32 | } 33 | 34 | return result; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/Single-Number.cpp: -------------------------------------------------------------------------------- 1 | /*This solition is the most optiized solution 2 | 3 | Time Complexity: O(N) 4 | Space Complexity: O(1) 5 | 6 | */ 7 | 8 | class Solution 9 | { 10 | public: 11 | int singleNumber(vector &nums) 12 | { 13 | //initialised the xor of numbers in xorr variable 14 | int xorr = 0; 15 | //Linearly traversing the array 16 | for (auto x = 0; x < nums.size(); x++) 17 | { 18 | //Calculating Xor of two numbers . 19 | xorr = xorr ^ nums[x]; 20 | 21 | } 22 | 23 | // Atlast return the final xor . 24 | 25 | return xorr; 26 | } 27 | }; -------------------------------------------------------------------------------- /C++/Spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | //Problem Number : 54 2 | //Problem Name : Spiral Matrix 3 | //Problem Statement : Given an m x n matrix, return all elements of the matrix in spiral order. 4 | 5 | class Solution { 6 | public: 7 | vector spiralOrder(vector>& matrix) { 8 | vectorres; 9 | int left = 0, top = 0, down = matrix.size()-1, right = matrix[0].size()-1; 10 | 11 | while(left <= right && top <= down){ 12 | //From left to right on top side 13 | for(int i = left; i <= right; i++) 14 | res.push_back(matrix[top][i]); 15 | top++; 16 | //From top to down on right side 17 | for(int i = top; i <= down; i++) 18 | res.push_back(matrix[i][right]); 19 | right--; 20 | if(top <= down){ 21 | //From right to left on down side 22 | for(int i = right; i >= left; i--) 23 | res.push_back(matrix[down][i]); 24 | down--; 25 | } 26 | if(left <= right){ 27 | //From down to top on left side 28 | for(int i = down; i >= top; i--) 29 | res.push_back(matrix[i][left]); 30 | left++; 31 | } 32 | } 33 | return res; 34 | } 35 | }; 36 | 37 | //This code is contributed by Nikhil-1503 38 | -------------------------------------------------------------------------------- /C++/Swap-nodes-in-pairs.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* swapPairs(ListNode* head) { 14 | if(head==NULL || head->next==NULL) 15 | return head; 16 | ListNode* p=head->next; 17 | head->next=swapPairs(head->next->next); 18 | p->next=head; 19 | return p; 20 | } 21 | }; 22 | 23 | // Time Complexity: O(N) 24 | // Space Complexity: O(1) 25 | -------------------------------------------------------------------------------- /C++/Time-Needed-To-Inform-All-Employees.cpp: -------------------------------------------------------------------------------- 1 | //CPP DFS SOLUTION 2 | 3 | // Problem statement: Return the no of mins required to inform all employees about the urgent news 4 | 5 | class Solution { 6 | public: 7 | vector adjList[100005]; 8 | 9 | int dfs(int headID, vector& informTime) 10 | { 11 | int maxTime=0; 12 | for(auto employee : adjList[headID]) 13 | { 14 | maxTime=max(maxTime, dfs(employee, informTime)); 15 | } 16 | return informTime[headID] + maxTime; 17 | } 18 | int numOfMinutes(int n, int headID, vector& manager, vector& informTime) { 19 | for(int i=0;i 2 | #include 3 | /* 4 | Example 1: 5 | Input: s = "()" 6 | Output: true 7 | 8 | Example 2: 9 | Input: s = "()[]{}" 10 | Output: true 11 | 12 | Example 3: 13 | Input: s = "(]" 14 | Output: false 15 | 16 | Example 4: 17 | Input: s = "([)]" 18 | Output: false 19 | 20 | Example 5: 21 | Input: s = "{[]}" 22 | Output: true 23 | */ 24 | 25 | class Solution { 26 | public: 27 | bool isValid(string s) { 28 | list open; 29 | if(s.length()%2!=0) 30 | return false; 31 | for(int i=0; i asteroidCollision(vector& asteroids) { 4 | stack s; 5 | 6 | for(int i=0;i0) 9 | { 10 | s.push(asteroids[i]); 11 | } 12 | else 13 | { 14 | while(true) 15 | { 16 | int top = s.top(); 17 | 18 | if(top<0) 19 | { 20 | s.push(asteroids[i]); 21 | break; 22 | } 23 | else if(top==-asteroids[i]) 24 | { 25 | s.pop(); 26 | break; 27 | } 28 | else if(top>(-asteroids[i])) 29 | { 30 | break; 31 | } 32 | else 33 | { 34 | s.pop(); 35 | if(s.empty()) 36 | { 37 | s.push(asteroids[i]); 38 | break; 39 | } 40 | } 41 | } 42 | } 43 | } 44 | 45 | vector output(s.size(),0); 46 | 47 | for(int i=s.size()-1;i>=0;i--) 48 | { 49 | output[i]=s.top(); 50 | s.pop(); 51 | } 52 | 53 | return output; 54 | 55 | 56 | } 57 | }; -------------------------------------------------------------------------------- /C++/brick-wall.cpp: -------------------------------------------------------------------------------- 1 | //done using hash table 2 | class Solution { 3 | public: 4 | int leastBricks(vector>& wall) { 5 | int n=wall.size(),i,j,pos,maxcount=0; 6 | 7 | unordered_map m; 8 | unordered_map:: iterator it; 9 | 10 | for(i=0;isecond); 25 | } 26 | return (n-maxcount); 27 | } 28 | }; 29 | 30 | Reduced Code for the given problem that reduces one for loop and also has less auxiliary space! 31 | 32 | // Time: O(n), n is the total number of the bricks 33 | // Space: O(m), m is the total number different widths 34 | 35 | class Solution { 36 | public: 37 | int leastBricks(vector>& wall) { 38 | unordered_map widths; 39 | auto result = wall.size(); 40 | for (const auto& row : wall) { 41 | for (auto i = 0, width = 0; i < row.size() - 1; ++i) { 42 | result = min(result, wall.size() - (++widths[width += row[i]])); 43 | } 44 | } 45 | return result; 46 | } 47 | }; -------------------------------------------------------------------------------- /C++/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | // Solved using backtracking 2 | class Solution { 3 | public: 4 | void recur(vector>& ans, vector& v, vector& candidates, int target, int curr){ 5 | if(target==0){ 6 | ans.push_back(v); 7 | } 8 | if(target<0){ 9 | return; 10 | } 11 | for(int i = curr; i< candidates.size(); i++){ 12 | if(candidates[i]<=target){ 13 | v.push_back(candidates[i]); 14 | recur(ans,v,candidates,target-candidates[i],i); 15 | v.pop_back(); 16 | } 17 | } 18 | } 19 | 20 | vector> combinationSum(vector& candidates, int target) { 21 | vector>ans; 22 | vector v; 23 | 24 | sort(candidates.begin(), candidates.end()); 25 | 26 | recur(ans,v,candidates,target,0); 27 | 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /C++/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water 2 | // code for the question : "container-with-most-water" 3 | // language : cpp 4 | 5 | 6 | class Solution { 7 | public: 8 | int maxArea(vector& height) { 9 | int n = height.size(); 10 | int max_area = 0; // Variable to store the maximum water that can be contained 11 | int i = 0; // Left pointer 12 | int j = n - 1; // Right pointer 13 | 14 | // Use two-pointer approach to find the maximum area 15 | while (i < j) { 16 | // Calculate the area between the two current pointers 17 | int current_area = (j - i) * min(height[i], height[j]); 18 | 19 | // Update the maximum area found so far 20 | max_area = max(max_area, current_area); 21 | 22 | // Move the pointer with the smaller height 23 | if (height[i] < height[j]) { 24 | i++; // Move left pointer to the right 25 | } else { 26 | j--; // Move right pointer to the left 27 | } 28 | } 29 | return max_area; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/decode-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeString(string s) { 4 | stack chars; 5 | stack nums; 6 | string res; 7 | int num = 0; 8 | for(char c : s) { 9 | if(isdigit(c)) { 10 | num = num*10 + (c-'0'); 11 | } 12 | else if(isalpha(c)) { 13 | res.push_back(c); 14 | } 15 | else if(c == '[') { 16 | chars.push(res); 17 | nums.push(num); 18 | res = ""; 19 | num = 0; 20 | } 21 | else if(c == ']') { 22 | string tmp = res; 23 | for(int i = 0; i < nums.top()-1; ++i) { 24 | res += tmp; 25 | } 26 | res = chars.top() + res; 27 | chars.pop(); nums.pop(); 28 | } 29 | } 30 | return res; 31 | } 32 | }; -------------------------------------------------------------------------------- /C++/k-closest-points-to-origin.cpp: -------------------------------------------------------------------------------- 1 | /*We have a list of points on the plane. Find the K closest points to the origin (0, 0). 2 | 3 | (Here, the distance between two points on a plane is the Euclidean distance.) 4 | 5 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) */ 6 | 7 | 8 | 9 | class Solution { 10 | public: 11 | vector> kClosest(vector>& points, int K) { 12 | vector> vec; 13 | for(int i=0;i> f;//final points vector 19 | for(int i=0;i& nums, int k) { 6 | 7 | map m; 8 | set> sp; 9 | 10 | // create a map storing all the frequencies 11 | for(int i:nums) m[i]++; 12 | 13 | int ans=0; 14 | for(auto i:m){ 15 | 16 | // if k = 0, add one entry to the set if freq > 1 17 | if(k==0 && m[i.first]>1){ 18 | sp.insert({i.first,i.first}); 19 | } 20 | else if(k!=0 && m.find(i.first+k)!=m.end()){ 21 | sp.insert({i.first,i.second}); 22 | } 23 | } 24 | 25 | // answer is the number of elements in the set 26 | return sp.size(); 27 | } 28 | }; -------------------------------------------------------------------------------- /C++/letter-combinations-of-a-phone-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map intToCharsMap; 4 | 5 | void backtracking(string::iterator lf,string::iterator rt,string &path,vector &result) 6 | { 7 | if(lf == rt) 8 | { 9 | result.push_back(path); 10 | return; 11 | } 12 | for(auto c : intToCharsMap[*lf]) 13 | { 14 | path.push_back(c); 15 | backtracking(next(lf,1),rt,path,result); 16 | path.pop_back(); // if a character doesnot matches then we pop that character from the string and again backtrack. 17 | } 18 | } 19 | vector letterCombinations(string digits) 20 | { 21 | int n = digits.size(); 22 | if(digits == "") 23 | return {}; 24 | string path; 25 | // result array stores every string that represents that digit. 26 | vector result; 27 | intToCharsMap = { 28 | {'2', "abc"}, 29 | {'3', "def"}, 30 | {'4', "ghi"}, 31 | {'5', "jkl"}, 32 | {'6', "mno"}, 33 | {'7', "pqrs"}, 34 | {'8', "tuv"}, 35 | {'9', "wxyz"}, 36 | }; 37 | backtracking(digits.begin(),digits.end(),path,result); 38 | return result; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* The Optimized Solution 2 | Time Complexity: O(N) 3 | Space Complexity: O(1) 4 | 5 | */ 6 | 7 | class Solution { 8 | public: 9 | int maxSubArray(vector& nums) { 10 | 11 | int cs=0; 12 | int ms=INT_MIN; 13 | // if size of array is 1 return that elemnt . 14 | if(nums.size()==1){ 15 | return nums[0]; 16 | } 17 | //Linearly traverse the array and add to the current sum variable and take maximum . 18 | for (int i = 0; i < nums.size(); i++) { 19 | cs=cs+nums[i]; 20 | 21 | 22 | ms=max(cs,ms); 23 | if(cs<0){ 24 | cs=0; 25 | } 26 | } 27 | 28 | return ms; 29 | } 30 | 31 | 32 | 33 | 34 | }; -------------------------------------------------------------------------------- /C++/merge-k-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | //Fucntion to append node at the end of lisked list 14 | struct ListNode *begg(struct ListNode *head, int x){ 15 | struct ListNode *temp = new ListNode(x); 16 | //If there is no node 17 | if(head==NULL){ 18 | head=temp; 19 | return head; 20 | } 21 | //If nodes already present 22 | struct ListNode *ptr=head; 23 | while(ptr->next){ 24 | ptr=ptr->next; 25 | } 26 | ptr->next=temp; 27 | return head; 28 | } 29 | ListNode* mergeKLists(vector& lists) { 30 | //Using multiset s it will allow duplicate values and will store them in sorted order. 31 | multiset s; 32 | //Adding values to multiset. 33 | for(int i=0;ival); 37 | p1=p1->next; 38 | } 39 | } 40 | //Initializing the head of linked list. 41 | struct ListNode *head2=NULL; 42 | //Appending nodes in the linked list from multiset. 43 | for(auto it=s.begin();it!=s.end();++it){ 44 | head2=begg(head2,*it); 45 | cout<<*it<<" "; 46 | } 47 | return head2; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /C++/minimum-add-to-make-parentheses-valid.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ 2 | 3 | class Solution { 4 | public: 5 | int minAddToMakeValid(string S) { 6 | int result = 0; 7 | 8 | stack s; //stack to save '(' 9 | 10 | for (int i = 0; i < S.size(); i++) 11 | { 12 | if (S[i] == '(') { 13 | s.push('('); 14 | } 15 | else { 16 | if (s.empty()) { 17 | result++; 18 | } 19 | else { 20 | s.pop(); 21 | } 22 | } 23 | } 24 | 25 | result = result + s.size(); 26 | 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/minimum-remove-to-make-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minRemoveToMakeValid(string s) { 4 | stack stack_for_index; //stack to save index of '(' 5 | string result_string = ""; 6 | 7 | // count wrong parentheses with stack & make string 8 | for (int i = 0; i < s.size(); i++) 9 | { 10 | if (s[i] == '(') { 11 | stack_for_index.push(result_string.size()); 12 | result_string.push_back(s[i]); 13 | } 14 | else if (s[i] == ')') { 15 | if (!stack_for_index.empty()) { 16 | stack_for_index.pop(); 17 | result_string.push_back(s[i]); 18 | } 19 | } 20 | else { 21 | result_string.push_back(s[i]); 22 | } 23 | } 24 | // now "stack_for_characters.size()" is the number of wrong "left" parentheses 25 | 26 | // remove wrong left parentheses 27 | while (!stack_for_index.empty()) 28 | { 29 | result_string.erase(stack_for_index.top(), 1); 30 | stack_for_index.pop(); 31 | } 32 | 33 | return result_string; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/number-of-islands.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool visited[300][300]; 4 | int r[4] = {-1,0,0,1}; 5 | int c[4] = {0,-1,1,0}; 6 | 7 | //Checks if the given row and col value are valid and if the cell is visited and if the cell contains '1' or not. 8 | bool val(int row,int col,vector>& grid,int M,int N) 9 | { 10 | return (row=0 && col>=0 && !visited[row][col] && grid[row][col]=='1'); 11 | } 12 | 13 | //Dfs function for exploring the surrounding cells 14 | void dfs(int i,int j,vector>& grid, int M, int N) 15 | { 16 | visited[i][j] = true; 17 | for(int a=0;a<4;a++) 18 | { 19 | int row = i + r[a]; 20 | int col = j + c[a]; 21 | if(val(row,col,grid,M,N)) 22 | { 23 | dfs(row,col,grid,M,N); 24 | } 25 | } 26 | } 27 | 28 | int numIslands(vector>& grid) { 29 | int m = grid.size(); 30 | int n = grid[0].size(); 31 | memset(visited,0,sizeof(visited)); 32 | int island_count = 0; 33 | for(int i=0;i s; 5 | string answer=""; 6 | for(int i=0;i& nums, int val) { 9 | int slow=0; 10 | int fast = 0; 11 | 12 | 13 | while (fast < nums.size()){ 14 | 15 | if (nums[fast]!=val){nums[slow++]=nums[fast];} 16 | fast++; 17 | 18 | } 19 | 20 | return slow; 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /C++/teemo-attacking.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/teemo-attacking/ 2 | //Difficulty Level: Medium 3 | //Tags: Arrays 4 | //Time complexity: O(n) 5 | //Space complexity: O(1) 6 | //similar to overlapping subintervals problems 7 | 8 | class Solution { 9 | public: 10 | int findPoisonedDuration(vector& timeSeries, int duration) { 11 | 12 | int n = timeSeries.size(); 13 | if(n==0) 14 | return 0; 15 | 16 | int ans = duration; 17 | 18 | for(int i=0; i twoSum(vector& nums, int target) { 5 | vector v(2); 6 | for(int i = 0; i twoSum(vector &numbers, int target) 26 | { 27 | //Key is the number and value is its index in the vector. 28 | unordered_map hash; 29 | // make a vector final result 30 | vector finalresult; 31 | for (int i = 0; i < numbers.size(); i++) { 32 | int n = target - numbers[i]; 33 | 34 | //if n is found in map, return them 35 | if (hash.find(n) != hash.end()) { 36 | result.push_back(hash[n] + 1); 37 | result.push_back(i + 1); 38 | return finalresult; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /C++/xor-operation-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | // difficulty easy 2 | class Solution { 3 | public: 4 | int xorOperation(int n, int start) { 5 | // brute force method 6 | int ans = 0; 7 | for(int i=0;i stack = new Stack(); 5 | for (char c : s.toCharArray()) { 6 | if (c == '(') 7 | stack.push(')'); 8 | else if (c == '{') 9 | stack.push('}'); 10 | else if (c == '[') 11 | stack.push(']'); 12 | else if (stack.isEmpty() || stack.pop() != c) 13 | return false; 14 | } 15 | return stack.isEmpty(); 16 | } 17 | -------------------------------------------------------------------------------- /Java/Add-Two-Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | * 9 | * Runtime: 67 ms 10 | * Memory Usage: 53.9 MB 11 | * 12 | */ 13 | import java.math.BigInteger; 14 | 15 | class Solution { 16 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 17 | ListNode currHead1 = l1; 18 | BigInteger list1 = new BigInteger("0"); 19 | BigInteger x = new BigInteger("1"); 20 | String s; 21 | 22 | while(currHead1 != null){ 23 | s = "" + (x.multiply(BigInteger.valueOf(currHead1.val))); 24 | list1 = list1.add(new BigInteger(s)); 25 | currHead1 = currHead1.next; 26 | x=x.multiply(BigInteger.valueOf(10)); 27 | } 28 | //System.out.println(list1); 29 | 30 | x = new BigInteger("1"); 31 | ListNode currHead2 = l2; 32 | BigInteger list2 = new BigInteger("0"); 33 | 34 | while(currHead2 != null){ 35 | s = "" + (x.multiply(BigInteger.valueOf(currHead2.val))); 36 | list2 = list2.add(new BigInteger(s)); 37 | currHead2 = currHead2.next; 38 | x=x.multiply(BigInteger.valueOf(10)); 39 | } 40 | //System.out.println(list2); 41 | list2 = list2.add(list1); 42 | 43 | //System.out.println(list2); 44 | StringBuffer sb = new StringBuffer(""+list2+""); 45 | sb.reverse(); 46 | //System.out.println(sb.toString()); 47 | String str = sb.toString(); 48 | 49 | ListNode result = new ListNode(Integer.parseInt(str.charAt(0)+"")); 50 | ListNode head = result; 51 | 52 | for(int i=1;i path,List> ans){ 3 | //If fromNode has reached the last Node of graph , add this node to path and return 4 | if(fromNode==graph.length-1) 5 | { 6 | path.add(fromNode); 7 | ans.add(new ArrayList(path)); 8 | path.remove(path.indexOf(fromNode)); 9 | return; 10 | } 11 | //Traverse for all nodes in list of fromNode 12 | for(int i=0;i(); 15 | //Add the node and call for its list of reachable nodes 16 | path.add(fromNode); 17 | findPaths(graph,graph[fromNode][i],path,ans); 18 | path.remove(path.size()-1); 19 | } 20 | return; 21 | } 22 | 23 | public List> allPathsSourceTarget(int[][] graph) { 24 | List> ans=new ArrayList>(); 25 | //Start from 0 node 26 | findPaths(graph,0,new ArrayList(),ans); 27 | return ans; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/Armstrong-Number.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * 5 | * 1134. Armstrong Number 6 | * The k-digit number N is an Armstrong number if and only if the kth power of each digit sums to N. 7 | * Given a positive integer N, return true if and only if it is an Armstrong number. 8 | * 9 | */ 10 | class ArmstrongNum { 11 | 12 | /* driver function commented 13 | public static void main(String[] args) { 14 | 15 | Scanner kb = new Scanner(System.in); 16 | int N = kb.nextInt(); 17 | 18 | int k = length(N); 19 | 20 | System.out.println(isArmstrongNumber(N, k)); 21 | 22 | kb.close(); 23 | } 24 | */ 25 | 26 | public static int length(int N) { 27 | int length = 0; 28 | 29 | while (N != 0) { 30 | N = N / 10; 31 | length++; 32 | } 33 | 34 | return length; 35 | } 36 | 37 | public static boolean isArmstrongNumber(int N, int k) { 38 | long powerSum = 0; 39 | int n = N; 40 | 41 | while (n != 0) { 42 | int rem = n % 10; 43 | 44 | powerSum += (int) Math.pow(rem, k); 45 | 46 | n /= 10; 47 | } 48 | System.out.println(powerSum); 49 | return (powerSum==N); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Java/Balanced-Binary-Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public boolean isBalanced(TreeNode root) { 18 | 19 | if(root==null){ 20 | return true; 21 | } 22 | else{ 23 | int left = height(root.left); 24 | int right = height(root.right); 25 | int diff = left - right; 26 | diff = diff > 0 ? diff : -diff; // absolute 27 | if(diff > 1){ 28 | return false; 29 | } 30 | return isBalanced(root.left) && isBalanced(root.right); 31 | } 32 | } 33 | 34 | private int height(TreeNode root){ 35 | // calculate the height of a tree 36 | if(root == null){ 37 | return 0; 38 | } 39 | else{ 40 | int left = height(root.left); 41 | int right = height(root.right); 42 | int height = left > right ? left : right; 43 | return height + 1; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Java/BrokenCalculator.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/broken-calculator/ 2 | 3 | public int brokenCalc(int startValue, int target) { 4 | 5 | 6 | if(startValue >= target){ 7 | return startValue - target; 8 | } 9 | 10 | if(target % 2 == 0){ 11 | return 1+brokenCalc(startValue,target/2); 12 | } 13 | 14 | return 1+brokenCalc(startValue,target+1); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Java/Degree-of-an-Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 4 | * 5 | */ 6 | 7 | class Solution { 8 | public int findShortestSubArray(int[] nums) { 9 | Map left = new HashMap(), right = new HashMap(), count = new HashMap(); 10 | 11 | //find the leftmost and rightmost index of each characters 12 | for(int i= 0;itop+1?top+1:k);i++) { 24 | stack[i]+=val; 25 | } 26 | } 27 | } 28 | 29 | /** 30 | * Your CustomStack object will be instantiated and called as such: 31 | * CustomStack obj = new CustomStack(maxSize); 32 | * obj.push(x); 33 | * int param_2 = obj.pop(); 34 | * obj.increment(k,val); 35 | */ -------------------------------------------------------------------------------- /Java/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | // https://leetcode.com/problems/fizz-buzz/ 6 | 7 | 8 | public List fizzBuzz(int n) { 9 | List s = new ArrayList<>(); 10 | 11 | for (int i = 1; i <= n ; i++) { 12 | if( i % 15 == 0){ 13 | s.add("FizzBuzz"); 14 | }else if( i % 3 == 0){ 15 | s.add("Fizz"); 16 | }else if(i % 5 == 0){ 17 | s.add("Buzz"); 18 | }else{ 19 | s.add(Integer.toString(i)); 20 | } 21 | } 22 | return s; 23 | } 24 | -------------------------------------------------------------------------------- /Java/Happy-Number.java: -------------------------------------------------------------------------------- 1 | class HappyNumber { 2 | public boolean isHappy(int n) { 3 | int num1, num2; 4 | 5 | num1 = num2 = n; 6 | do 7 | { 8 | num1 = SquareSum(num1); 9 | 10 | 11 | num2 = SquareSum(SquareSum(num2)); 12 | 13 | } 14 | while (num1 != num2); 15 | 16 | return (num1 == 1); 17 | } 18 | 19 | 20 | static int SquareSum(int n) 21 | { 22 | int square = 0; 23 | while (n!= 0) 24 | { 25 | square += (n % 10) * (n % 10); 26 | n /= 10; 27 | } 28 | return square; 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /Java/June-LeetCoding-Challenge/Day22StrSubsequenceCount.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Day22StrSubsequenceCount { 4 | public static void main(String[] args){ 5 | String str = "abacde"; 6 | String[] words = {"a", "bb", "acd", "ace"}; 7 | int count = numMatchingSequence(str,words); 8 | System.out.println(count); 9 | } 10 | 11 | public static int numMatchingSequence(String str, String[] words){ 12 | int result = 0; 13 | Map> map = new HashMap<>(); 14 | 15 | for(int i=0; i()); 17 | map.get(str.charAt(i)).add(i); // It will add size of that character in map (occurence) 18 | } 19 | 20 | for (String word : words) { 21 | if (match(str, word, map, 0)) { 22 | result++; 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | 29 | private static boolean match(String S, String word, Map> map, int startIndex) { 30 | if (word.length() == 0) return true; 31 | if (!map.containsKey(word.charAt(0))) return false; 32 | for (int start : map.get(word.charAt(0))) { 33 | if (start < startIndex) continue; 34 | String newWord = word.substring(1, word.length()); 35 | return match(S, newWord, map, start + 1); 36 | } 37 | 38 | return false; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Java/May-LeetCoding-Challenge/Day-1-First-Bad-Version.java: -------------------------------------------------------------------------------- 1 | /** 2 | * First Bad Version 3 | * 4 | * You are a product manager and currently leading a team to develop a new 5 | * product. Unfortunately, the latest version of your product fails the quality 6 | * check. Since each version is developed based on the previous version, all the 7 | * versions after a bad version are also bad. 8 | * 9 | * Suppose you have n versions [1, 2, ..., n] and you want to find out the first 10 | * bad one, which causes all the following ones to be bad. 11 | * 12 | * You are given an API bool isBadVersion(version) which will return whether 13 | * version is bad. Implement a function to find the first bad version. You 14 | * should minimize the number of calls to the API. 15 | * 16 | */ 17 | 18 | /** 19 | * The isBadVersion API is defined in the parent class VersionControl. boolean 20 | * isBadVersion(int version); 21 | * 22 | * @author gouravrusiya 23 | * 24 | */ 25 | public class Solution extends VersionControl { 26 | public int firstBadVersion(int n) { 27 | int low = 1; 28 | int high = n; 29 | 30 | int mid = (low + high) / 2; 31 | 32 | while (low < high) { 33 | mid = (int) (((long) low + high) / 2); 34 | 35 | if (!isBadVersion(mid)) { 36 | if (isBadVersion(mid + 1)) 37 | return mid + 1; 38 | else 39 | low = mid + 1; 40 | } else { 41 | if (!isBadVersion(mid - 1)) 42 | return mid; 43 | else 44 | high = mid - 1; 45 | } 46 | } 47 | return low; 48 | } 49 | } -------------------------------------------------------------------------------- /Java/May-LeetCoding-Challenge/Day-2-Jewels-and-Stones.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Jewels and Stones 3 | * 4 | * You're given strings J representing the types of stones that are jewels, and 5 | * S representing the stones you have. Each character in S is a type of stone 6 | * you have. You want to know how many of the stones you have are also jewels. 7 | * 8 | * The letters in J are guaranteed distinct, and all characters in J and S are 9 | * letters. Letters are case sensitive, so "a" is considered a different type of 10 | * stone from "A". 11 | * 12 | * @author gouravrusiya 13 | * 14 | */ 15 | public class Solution { 16 | public int numJewelsInStones(String J, String S) { 17 | 18 | int[] asciiCount = new int[128]; 19 | int ch; 20 | 21 | for (int i = 0; i < S.length(); i++) { 22 | // get ASCII of character 23 | ch = S.charAt(i); 24 | asciiCount[ch]++; 25 | } 26 | 27 | int jewelsCount = 0; 28 | 29 | // iterate through Jewels for stones type 30 | for (int i = 0; i < J.length(); i++) { 31 | ch = J.charAt(i); 32 | jewelsCount += asciiCount[ch]; 33 | } 34 | 35 | return jewelsCount; 36 | } 37 | } -------------------------------------------------------------------------------- /Java/May-LeetCoding-Challenge/Day-3-Ransom-Note.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Ransom Note 3 | * 4 | * Given an arbitrary ransom note string and another string containing letters 5 | * from all the magazines, write a function that will return true if the ransom 6 | * note can be constructed from the magazines ; otherwise, it will return false. 7 | * 8 | * Each letter in the magazine string can only be used once in your ransom note. 9 | * 10 | * @author gouravrusiya 11 | * 12 | */ 13 | public class Solution { 14 | public boolean canConstruct(String ransomNote, String magazine) { 15 | 16 | if (ransomNote.length() > magazine.length()) 17 | return false; 18 | 19 | /* 20 | * Logic : character count in ransomNote should be equal to OR less than 21 | * magazine character count 22 | */ 23 | 24 | int[] ransomNoteChCount = new int[26]; // lower case characters are only 26 25 | 26 | for (int i = 0; i < ransomNote.length(); i++) { 27 | ransomNoteChCount[ransomNote.charAt(i) - 'a']++; 28 | } 29 | 30 | for (int i = 0; i < magazine.length(); i++) { 31 | ransomNoteChCount[magazine.charAt(i) - 'a']--; 32 | } 33 | 34 | for (int i = 0; i < 26; i++) { 35 | if (ransomNoteChCount[i] > 0) { 36 | return false; 37 | } 38 | } 39 | 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/May-LeetCoding-Challenge/Day-5-First-Unique-Character.java: -------------------------------------------------------------------------------- 1 | /** 2 | Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. 3 | 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode" 10 | return 2 11 | **/ 12 | class Solution { 13 | public int firstUniqChar(String s) { 14 | 15 | HashMap map = new LinkedHashMap<>(); 16 | 17 | for(int i=0;i entry : map.entrySet()){ 32 | if(entry.getValue() == 1){ 33 | firstNonRepeatChar = entry.getKey(); 34 | break; 35 | } 36 | } 37 | 38 | for(int i=0;i= r || n < 0 || n >= c || visited[m][n] || grid[m][n] == '0') { 65 | 66 | return; 67 | } 68 | 69 | visited[m][n] = true; 70 | 71 | _numIslands(grid, m + 1, n); 72 | _numIslands(grid, m, n + 1); 73 | _numIslands(grid, m - 1, n); 74 | _numIslands(grid, m, n - 1); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Java/PascalsTriangle118.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | public List> generate(int numRows) { 6 | 7 | List> triangle = new ArrayList<>(); 8 | 9 | if(numRows ==0) return triangle; 10 | 11 | List first_row = new ArrayList<>(); 12 | first_row.add(1); 13 | triangle.add(first_row); 14 | 15 | for(int i=1; i prev_row = triangle.get(i-1); 17 | List row = new ArrayList<>(); 18 | row.add(1); 19 | 20 | for(int j=1; j> permute(int[] nums) { 2 | List> result = new ArrayList<>(); 3 | helper(0, nums, result); 4 | return result; 5 | } 6 | 7 | private void helper(int start, int[] nums, List> result) 8 | { 9 | if(start==nums.length-1){ 10 | ArrayList list = new ArrayList<>(); //if starting value(say n) is the last value , this will make a new list with the values and the new starting value is n 11 | for(int num: nums) 12 | { 13 | list.add(num); 14 | } 15 | result.add(list); 16 | return; 17 | } 18 | 19 | for(int i=start; i **Problem Link** : [Redundant Connection (LeetCode)](https://leetcode.com/problems/redundant-connection/)
4 | > **Concepts Involved** : *Tree, Disjoint Union Set* 5 | 6 | ## Problem Statement 7 | We have been provided with a list of edges. These edges form a Tree. The list has one extra edge as well. We have to find that extra edge which if removed from the list makes the resulting list of edges a Tree of N nodes. 8 | 9 | ## Solution 10 |

11 | We have been given with a list of edges. Now we need to remove one edge from the List so that the resultant list forms a Tree. Basically a Tree can be termed as a special Graph where every nodes are connected to one another directly or indirectly and there no loops present. As there is only one extra edge, then it must join two nodes which are already connected. And we neeed to find that particular edge. 12 |

13 |

14 | The basic idea is to use a Disjoint Union Sets here. We will iterate over the list of edges and for every edge (u,v) we will put u and v in a single set. If during the iteration we find an edge such that both the nodes u and v is in the same set, then we can say that it is an extra edge which can be removed. We can store that as our result and return it after the iteration. 15 |

16 | 17 | ![Editorial Image](./images/image-1.png) 18 | 19 |

20 | The basic source code for the problem looks like : 21 | 22 | ``` 23 | for each (edge in edge_list) : 24 | if(same_set(edge.u, edge.v)){ 25 | extra_node_u = edge.u 26 | extra_node_v = edge.v 27 | } 28 | else{ 29 | put_in_same_set(edge.u, edge.v) 30 | } 31 | } 32 | ``` 33 |

34 | 35 | ## Complexity 36 | * The solution Time Complexity is : ***O(N)*** 37 | * The solution Space Complexity is : ***O(N)*** 38 | 39 | > **Author's Note** : I would highly encourage readers to learn the Disjoint Set Union data structure before attempting the question from [here](https://www.geeksforgeeks.org/union-find/). 40 | -------------------------------------------------------------------------------- /Java/Redundant-Connection/images/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codedecks-in/LeetCode-Solutions/214fdad3962a4d895deb93a06c1bd425c22d682b/Java/Redundant-Connection/images/image-1.png -------------------------------------------------------------------------------- /Java/Redundant-Connection/redundant-connection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem Name : Redundant Connection 3 | * Concept Involved : Trees, Union Find 4 | * 5 | * Execution Time : 1 ms 6 | * Memory Consumed : 39 mb 7 | **/ 8 | 9 | class DUS{ 10 | public int[] parent; 11 | public int n; 12 | 13 | DUS(int n){ 14 | this.n = n; 15 | parent = new int[n]; 16 | for(int i=0; i target){ 16 | return false; 17 | } 18 | else if(matrix[i][j] == target){ 19 | return true; 20 | } 21 | else{ 22 | continue; 23 | } 24 | } 25 | } 26 | 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/SignOf.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | // https://leetcode.com/problems/sign-of-the-product-of-an-array/ 4 | 5 | public int arraySign(int[] nums) { 6 | int count = 0; 7 | for(int i : nums){ 8 | if(i == 0){ 9 | return 0; 10 | }else if(i < 0){ 11 | count++; 12 | } 13 | } 14 | if(count % 2 == 0){ 15 | return 1; 16 | } 17 | return -1; 18 | } 19 | -------------------------------------------------------------------------------- /Java/Sum_of_two_integers.java: -------------------------------------------------------------------------------- 1 | // Time-Complexity:- -> O(1) constant as 32 is the number of bits at most we will have to bit shift until carry is zero. 2 | // Space-Complexity:- O(1) 3 | 4 | 5 | class Solution { 6 | public int getSum(int a, int b) { 7 | 8 | int xor=a ^ b; 9 | int carry= a & b; 10 | if(carry == 0) 11 | return xor; 12 | else 13 | return getSum(xor,carry<<1); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/Ugly-Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isUgly(int num) { 3 | if(num == 0) return false; 4 | if(num == 1) return true; 5 | 6 | if(num % 2 == 0){ 7 | num = num / 2; 8 | return isUgly(num); 9 | } 10 | 11 | if(num % 3 == 0){ 12 | num=num / 3; 13 | return isUgly(num); 14 | } 15 | 16 | if(num % 5 == 0){ 17 | num = num / 5; 18 | return isUgly(num); 19 | } 20 | 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/WaterBottles.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | // https://leetcode.com/problems/water-bottles/ 4 | 5 | 6 | public int numWaterBottles(int numBottles, int numExchange) { 7 | 8 | int total = numBottles; 9 | while(numBottles>=numExchange) 10 | { 11 | int exchange=numBottles/numExchange; 12 | int rem=numBottles%numExchange; 13 | total+=exchange; 14 | numBottles=exchange+rem; 15 | } 16 | return total; 17 | } 18 | -------------------------------------------------------------------------------- /Java/binary-tree-inorder-traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | * 10 | * Runtime: 0 ms 11 | * Memory Usage: 37.8 MB 12 | * 13 | */ 14 | 15 | class Solution { 16 | public List inorderTraversal(TreeNode root) { 17 | List list = new ArrayList(); 18 | inorder(root, list); 19 | return list; 20 | } 21 | 22 | public void inorder(TreeNode root, List list){ 23 | /* Inorder traversal is visiting : left subtree then root then right subtree */ 24 | 25 | /* if node is null, then return back to the caller function */ 26 | if(root==null) 27 | return; 28 | /* Recurse for left subtree */ 29 | inorder(root.left, list); 30 | 31 | /* Add the current node's value to the list */ 32 | list.add(root.val); 33 | 34 | /* Recurse for right subtree */ 35 | inorder(root.right, list); 36 | } 37 | } -------------------------------------------------------------------------------- /Java/binary-tree-postorder-traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | * 10 | * Runtime: 0 ms 11 | * Memory Usage: 37.9 MB 12 | * 13 | */ 14 | class Solution { 15 | List list = new ArrayList(); 16 | public List postorderTraversal(TreeNode root) { 17 | postorder(root); 18 | return list; 19 | } 20 | 21 | public void postorder(TreeNode root){ 22 | /* Postorder traversal is visiting : left subtree then right subtree then root */ 23 | 24 | /* if node is null, then return back to the caller function */ 25 | if(root==null) 26 | return; 27 | 28 | /* Recurse for left subtree */ 29 | postorderTraversal(root.left); 30 | 31 | /* Recurse for right subtree */ 32 | postorderTraversal(root.right); 33 | 34 | /* Add the current node's value to the list */ 35 | list.add(root.val); 36 | } 37 | } -------------------------------------------------------------------------------- /Java/binary-tree-preorder-traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | * 10 | * Runtime: 0 ms 11 | * Memory Usage: 37.9 MB 12 | * 13 | */ 14 | 15 | class Solution { 16 | public List preorderTraversal(TreeNode root) { 17 | List ls = new ArrayList(); 18 | preorder(root, ls); 19 | return ls; 20 | } 21 | public void preorder(TreeNode root, List ls){ 22 | /* Preorder traversal is visiting : root then left subtree then right subtree */ 23 | 24 | /* if node is null, then return back to the caller function */ 25 | if(root==null) 26 | return; 27 | 28 | /* Add the current node's value to the list */ 29 | ls.add(root.val); 30 | 31 | /* Recurse for left subtree */ 32 | preorder(root.left, ls); 33 | 34 | /* Recurse for right subtree */ 35 | preorder(root.right, ls); 36 | } 37 | } -------------------------------------------------------------------------------- /Java/buddy-strings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem Name : Buddy Strings 3 | * Concept Involved : String Manipulation, Frequency Computation, Observation 4 | * 5 | * Execution Time : 2 ms 6 | * Memory Consumed : 39.1 mb 7 | * 8 | */ 9 | class Solution { 10 | public boolean isDuplicate(String str){ 11 | int[] fre = new int[26]; 12 | for(int i=0; i 1){ 16 | return true; 17 | } 18 | } 19 | return false; 20 | } 21 | public boolean buddyStrings(String A, String B) { 22 | if(A.length() != B.length()){ 23 | return false; 24 | } 25 | 26 | int count = 0; 27 | char ca = 'A'; 28 | char cb = 'A'; 29 | 30 | for(int i=0; i also they are first & last element 36 | sumOfMaxAndMin = max + min; 37 | 38 | // multiply above value with n 39 | sumOfMaxAndMin *= n; 40 | 41 | // divide above value with 2 42 | sumOfMaxAndMin /= 2; 43 | 44 | if (sum == sumOfMaxAndMin){ 45 | return true; 46 | } 47 | 48 | return false; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Java/climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int climbStairs(int n) { 3 | int prev1=1, prev2=2, cur=0; 4 | if(n<=2) return n; 5 | for(int i=3;i<=n;++i) { 6 | cur=prev1+prev2; 7 | prev1=prev2; 8 | prev2=cur; 9 | } 10 | return cur; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/complete-binary-tree-inserter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class CBTInserter { 11 | TreeNode root; 12 | Queue q = new LinkedList(); 13 | // This queue is a helper to reduce load on insert function.. 14 | public CBTInserter(TreeNode root) { 15 | this.root = root; 16 | Queue temp = new LinkedList(q); 17 | temp.add(root); 18 | q.add(root); 19 | // Prepare a queue for the for our insert function... 20 | while(!temp.isEmpty()){ 21 | TreeNode t = temp.poll(); 22 | if(t.left!=null){ 23 | temp.add(t.left); 24 | q.add(t.left); 25 | } 26 | if(t.right!=null){ 27 | temp.add(t.right); 28 | q.add(t.right); 29 | } 30 | } 31 | } 32 | 33 | 34 | public int insert(int v) { 35 | TreeNode n = new TreeNode(v); 36 | n.left = n.right = null; 37 | TreeNode parent = null; 38 | // Add new node to the queue... 39 | q.add(n); 40 | while(true){ 41 | parent = q.peek(); 42 | // If the node's left is null then, insert there. 43 | if(parent.left==null){ 44 | parent.left = n; 45 | break; 46 | } 47 | // If the node's right is null then, insert there.... 48 | // Now this node can never become parent of new node, so remove it from the queue 49 | if(parent.right==null){ 50 | parent.right = n; 51 | q.poll(); 52 | break; 53 | } 54 | // else it means the node has left and right children which are not null... so remove it from queue. 55 | q.poll(); 56 | } 57 | // Return the parent's value to the caller function... 58 | return parent.val; 59 | } 60 | 61 | public TreeNode get_root() { 62 | return root; 63 | } 64 | } -------------------------------------------------------------------------------- /Java/convert-sorted-list-to-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public TreeNode sortedArrayToBST(int[] nums) { 18 | // use merge sort strategy to convert sorted list to BST 19 | return buildTree(0, nums.length-1, nums); 20 | } 21 | 22 | public TreeNode buildTree(int l, int r, int nums[]){ 23 | // base case 24 | if(l>r) return null; 25 | // get mid of the whole index of the current list 26 | int mid = (l+r)/2; 27 | // create a node for mid of current subarray 28 | TreeNode node = new TreeNode(nums[mid]); 29 | // recurse for getting the left subtree 30 | node.left = buildTree(l, mid-1, nums); 31 | // recurse for getting the right subtree 32 | node.right = buildTree(mid+1, r, nums); 33 | // return the node 34 | return node; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Java/crawler-log-folder-leetcode-1598.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(String[] logs) { 3 | int minOp = 0; 4 | 5 | for(int i=0; i0 && logs[i].equals("../")){ 7 | minOp--; 8 | } 9 | else if(logs[i].contains("/") && !logs[i].contains("./")){ 10 | minOp++; 11 | } 12 | } 13 | return minOp; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/detect-capital-use.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean detectCapitalUse(String word) { 3 | 4 | int upperCaseCount = 0; 5 | int lowerCaseCount = 0; 6 | 7 | int wordLen = word.length(); 8 | 9 | int i = 0; 10 | int firstCharFlag = 0; 11 | 12 | for(i=0 ; i= 'a' && ch <= 'z'){ 16 | lowerCaseCount++; 17 | } 18 | else if(ch >= 'A' && ch <= 'Z'){ 19 | upperCaseCount++; 20 | 21 | if(i == 0){ 22 | firstCharFlag++; 23 | } 24 | } 25 | } 26 | 27 | 28 | if(i == wordLen){ 29 | if(lowerCaseCount == wordLen){ 30 | return true; 31 | } 32 | else if(upperCaseCount == wordLen){ 33 | return true; 34 | } 35 | else if(firstCharFlag == 1 && upperCaseCount == 1 && lowerCaseCount == (wordLen-1)){ 36 | return true; 37 | } 38 | else{ 39 | return false; 40 | } 41 | } 42 | 43 | return false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Java/evaluate_reverse_polish_notation.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public int evalRPN(String[] tokens) { 5 | Stack st = new Stack<>(); 6 | int a,b; 7 | for(String s: tokens){ 8 | if(s.equals("+")){ 9 | st.add(st.pop()+st.pop()); 10 | } 11 | else if(s.equals("*")){ 12 | st.add(st.pop() * st.pop()); 13 | } 14 | else if(s.equals("/")){ 15 | b=st.pop(); 16 | a = st.pop(); 17 | st.add(a/b); 18 | } 19 | else if(s.equals("-")){ 20 | b = st.pop(); 21 | a = st.pop(); 22 | st.add(a-b); 23 | } 24 | else{ 25 | st.add(Integer.parseInt(s)); 26 | } 27 | } 28 | return st.pop(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/first-unique-character-in-a-string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * First Unique Character in a String 3 | * 4 | * Time complexity - O(n) 5 | * Space complexity - O(1) 6 | */ 7 | class Solution { 8 | public int firstUniqChar(String s) { 9 | int len = s.length(); 10 | 11 | // check if string is null or empty 12 | if(s == null || s.isEmpty()){ 13 | return -1; 14 | } 15 | 16 | // Note: You may assume the string contains only lowercase English letters. 17 | int []ch = new int[26]; 18 | 19 | // count chars and store it in ch array 20 | for(int i=0; i areConnected(int n, int threshold, int[][] queries) { 39 | ArrayList res = new ArrayList<>(); 40 | Dus dus = new Dus(n+1); 41 | 42 | for(int i=1; i<=n; i++){ 43 | for(int j=2*i; j<=n; j+=i){ 44 | if(i > threshold){ 45 | dus.union(i,j); 46 | } 47 | } 48 | } 49 | 50 | for(int i=0; i lenB){ 22 | int diff = lenA - lenB; 23 | head1 = moveList(diff, head1); 24 | } 25 | else{ 26 | int diff = lenB - lenA; 27 | head2 = moveList(diff, head2); 28 | } 29 | 30 | while(head1 != null){ 31 | if(head1 == head2){ 32 | return head1; 33 | } 34 | else if(head1.next == head2.next){ 35 | return head1.next; 36 | } 37 | head1 = head1.next; 38 | head2 = head2.next; 39 | } 40 | 41 | return null; 42 | } 43 | 44 | public int getLinkedListLength(ListNode head){ 45 | ListNode currentHead = head; 46 | int len = 0; 47 | 48 | while(currentHead != null){ 49 | currentHead = currentHead.next; 50 | len++; 51 | } 52 | 53 | return len; 54 | } 55 | 56 | public ListNode moveList(int difference, ListNode head){ 57 | while(difference != 0){ 58 | head = head.next; 59 | difference--; 60 | } 61 | return head; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Java/linked-list-cycle-ii.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | 14 | public ListNode detectCycle(ListNode head) { 15 | 16 | if(head == null){ 17 | return null; 18 | } 19 | 20 | ListNode slowPtr = isCycleExists(head); 21 | ListNode fastPtr = head; 22 | 23 | if(slowPtr != null){ 24 | while(fastPtr != slowPtr){ 25 | fastPtr = fastPtr.next; 26 | slowPtr = slowPtr.next; 27 | } 28 | return slowPtr; 29 | } 30 | 31 | return null; 32 | } 33 | 34 | public ListNode isCycleExists(ListNode head){ 35 | ListNode currentHead = head; 36 | 37 | ListNode slowPtr = head; 38 | ListNode fastPtr = head; 39 | 40 | while (fastPtr != null && fastPtr.next != null) { 41 | slowPtr = slowPtr.next; 42 | fastPtr = fastPtr.next.next; 43 | 44 | if (slowPtr == fastPtr) 45 | return slowPtr; 46 | } 47 | 48 | return null; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Java/linked-list-cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | 15 | if (head == null){ 16 | return false; 17 | } 18 | 19 | ListNode slowPtr = head; 20 | ListNode fastPtr = head; 21 | 22 | /** Approach 23 | 24 | // 1. if no cycle exists AND 25 | // a. if there are even number of nodes then fast pointer will be pointing to null. 26 | // b. else there are odd number of nodes then fast pointer will be pointing to last node. 27 | 28 | // 2. if slow pointer meet fast pointer that interprets there exists a loop 29 | */ 30 | 31 | while (fastPtr != null && fastPtr.next != null) { 32 | 33 | // move slow pointer one node at a time 34 | slowPtr = slowPtr.next; 35 | 36 | // move fast pointer two nodes at a time 37 | fastPtr = fastPtr.next.next; 38 | 39 | if (slowPtr == fastPtr) 40 | return true; 41 | } 42 | 43 | return false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Java/matrix-diagonal-sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a square matrix mat, return the sum of the matrix diagonals. 3 | * 4 | * Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. 5 | * 6 | * Time Complexity - O(n) 7 | * Space Complexity - O(1) 8 | */ 9 | class Solution { 10 | public int diagonalSum(int[][] mat) { 11 | 12 | int diagonalSum = 0; 13 | int len = mat.length - 1; 14 | 15 | for(int i=0; i maxDepth) ? depth : maxDepth; 16 | } 17 | 18 | return maxDepth; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/median-of-two-sorted-arrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 | 4 | //Easy for Binary search on smaller length array 5 | //Checking the length and calling the main Function with smaller len array as forst array 6 | if(nums1.length > nums2.length){ 7 | return findMedianSortedArrays(nums2,nums1); 8 | } 9 | 10 | int len1 = nums1.length; 11 | int len2 = nums2.length; 12 | //System.out.println(len1 + " " + len2); 13 | 14 | //Doing Binary search on smaller array 15 | int start = 0; 16 | int end = len1; 17 | while(start<=end){ 18 | int partion1 = (start+end)/2; 19 | int partion2 = ((len1+len2+1)/2 - partion1); 20 | 21 | //finding the max and min lenemt is num1 array 22 | int max1 = (partion1 == 0 ) ? Integer.MIN_VALUE : nums1[partion1-1]; 23 | int min1 = (partion1 == len1) ? Integer.MAX_VALUE : nums1[partion1]; 24 | 25 | //finding the max and min elemnt of nums2 array 26 | int max2 = (partion2 == 0 ) ? Integer.MIN_VALUE : nums2[partion2-1]; 27 | //System.out.println(Integer.MIN_VALUE + " " + Integer.MAX_VALUE); 28 | int min2 = (partion2 == len2) ? Integer.MAX_VALUE : nums2[partion2]; 29 | 30 | if(max1 <= min2 && max2 <= min1){ 31 | if((len1 + len2 ) %2 == 0){ 32 | return (double)(Math.max(max1, max2) + Math.min(min1, min2))/2; 33 | }else{ 34 | return (double)Math.max(max1,max2); 35 | } 36 | }else if( max1 > min2){ 37 | end = partion1 - 1; 38 | }else{ 39 | start = partion1 + 1; 40 | } 41 | } 42 | return 0; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java/middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode middleNode(ListNode head) { 13 | ListNode currentNode = head; 14 | 15 | ListNode slowPtr = head; 16 | ListNode fastPtr = head; 17 | 18 | while(fastPtr != null && fastPtr.next != null){ 19 | slowPtr = slowPtr.next; // slow pointer will move 1 node at a time 20 | fastPtr = fastPtr.next.next; // fast pointer will move 2 nodes at a time 21 | } 22 | 23 | // at end slow pointer will be pointing to middle node 24 | return slowPtr; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/missing-number.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Time Complexity - O(n) 3 | * Space Complexity - O(1) 4 | * 5 | * Please comment one of the method if you are submitting solution directly 6 | */ 7 | class Solution { 8 | 9 | // Using sum of first n natural numbers formula. 10 | public int missingNumber(int[] nums) { 11 | int numsLen = nums.length; 12 | 13 | // sum of n natural number is 14 | // Sn = n * (n+1)/2 15 | int expectedSum = numsLen*(numsLen+1)/2; 16 | 17 | // calculate actual sum 18 | int actualSum = 0; 19 | for (int i=0; i> 1; 17 | countOfBits++; 18 | } 19 | 20 | return countOfBits; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/palindrome-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | String _x = x+""; // integer convert string 4 | String rev = ""; // store reverse 5 | int i = 0; 6 | for(i = _x.length()-1; i>=0; i--){ 7 | rev += _x.charAt(i); 8 | } 9 | 10 | if(_x.compareTo(rev) == 0){ 11 | // correct 12 | return true; 13 | } 14 | else{ 15 | return false; 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/path-sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public boolean hasPathSum(TreeNode root, int sum) { 18 | if(root == null){ 19 | // exception 20 | return false; 21 | } 22 | if(root.left == null && root.right == null){ 23 | if(sum == root.val){ 24 | return true; 25 | } 26 | return false; 27 | } 28 | else{ 29 | boolean left = false; 30 | boolean right = false; 31 | if(root.left != null){ 32 | left = hasPathSum(root.left, sum-root.val); 33 | } 34 | if(root.right != null){ 35 | right = hasPathSum(root.right, sum-root.val); 36 | } 37 | return left||right; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Java/ransom-note.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Ransom Note 3 | * 4 | * Logic : character count in ransomNote should be equal to OR less than magazine character count. 5 | * Runtime: 7 ms 6 | * Memory Usage: 42.5 MB 7 | */ 8 | class Solution { 9 | public boolean canConstruct(String ransomNote, String magazine) { 10 | 11 | if (ransomNote.length() > magazine.length()) 12 | return false; 13 | 14 | /* Logic : character count in ransomNote should be equal to OR less than magazine character count */ 15 | 16 | int [] ransomNoteChCount = new int[26]; // lower case characters are only 26 17 | 18 | for (int i=0;i 0){ 28 | return false; 29 | } 30 | } 31 | 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Java/remove-nth-node-from-end-of-list.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode removeNthFromEnd(ListNode head, int n) { 13 | ListNode slow = head, fast = head, prev = null; 14 | // move one ptr such that it points to nth node from start of Linked List 15 | while(n-->1) 16 | fast = fast.next; 17 | 18 | // now move the second ptr as long as first ptr doesn't point to last node 19 | while(fast.next!=null){ 20 | prev = slow; 21 | slow = slow.next; 22 | fast = fast.next; 23 | } 24 | 25 | // if the nth node from end is the start node of list 26 | if(prev==null) 27 | head = head.next; 28 | else 29 | prev.next = slow.next; 30 | 31 | return head; 32 | } 33 | } -------------------------------------------------------------------------------- /Java/reverse-integer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Not a very good approach. 3 | * StringBuilder reverse function used. 4 | * 5 | * Time Complexity: O(n) 6 | * Space Complexity: O(n) 7 | */ 8 | class Solution { 9 | public int reverse(int x) { 10 | StringBuilder sb = new StringBuilder(""+x); 11 | sb.reverse(); 12 | String str = sb.toString(); 13 | 14 | if(str.charAt(str.length()-1) == '-') { 15 | str = "-" + str.substring(0, str.length()-1); 16 | } 17 | int ans = 0; 18 | 19 | try{ 20 | ans = Integer.parseInt(str); 21 | } catch(Exception ex){ 22 | return 0; 23 | } 24 | 25 | return ans; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/reverse-words-in-a-string.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse Words in a String 3 | * Medium 4 | * 5 | * Given an input string, reverse the string word by word 6 | 7 | Example 1: 8 | 9 | Input: "the sky is blue" 10 | Output: "blue is sky the" 11 | 12 | Example 2: 13 | 14 | Input: " hello world! " 15 | Output: "world! hello" 16 | Explanation: Your reversed string should not contain leading or trailing spaces. 17 | * 18 | * Runtime: 7 ms 19 | * Memory Usage: 41.8 MB 20 | * 21 | */ 22 | class Solution { 23 | public String reverseWords(String s) { 24 | s = s.trim(); 25 | 26 | String [] strArr = s.split(" "); 27 | 28 | String ans = ""; 29 | 30 | for (int i=strArr.length-1; i>=0; i--) { 31 | if (strArr[i].isEmpty()){ 32 | continue; 33 | } 34 | ans += strArr[i].trim() + " "; 35 | } 36 | 37 | return ans.trim(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Java/running-sum-of-1d-array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Running Sum of 1d Array 3 | * 4 | * Time Complexity - O(n) 5 | * Space Complexity - O(n) 6 | * 7 | * Runtime: 0 ms, faster than 100.00% of Java online submissions 8 | */ 9 | class Solution { 10 | public int[] runningSum(int[] nums) { 11 | 12 | int len = nums.length; 13 | int[] runningSumAr = new int[len]; 14 | 15 | int sumSoFar = 0; 16 | 17 | for(int i=0; i 0) 59 | lvar = BigInteger.valueOf(Integer.MAX_VALUE); 60 | else if(lvar.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) 61 | lvar = BigInteger.valueOf(Integer.MIN_VALUE); 62 | 63 | return lvar.intValue(); 64 | } 65 | } -------------------------------------------------------------------------------- /Java/sum-root-to-leaf-numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | * 16 | * Runtime: 0 ms 17 | Memory Usage: 39.2 MB 18 | */ 19 | 20 | class Solution { 21 | int sum = 0; 22 | 23 | public int sumNumbers(TreeNode root) { 24 | traverse(root, 0); 25 | return sum; 26 | } 27 | 28 | public void traverse(TreeNode root, int n) { 29 | // if the node is null, return from the function (specially to handle if root of 30 | // tree is null) 31 | if (root == null) 32 | return; 33 | // shift the previous units place digit to ten's place by multiplying it by 10 34 | // and add the current value of node 35 | n = n * 10 + root.val; 36 | // if the node does not have a left or right children is null, 37 | // the current node is leaf node, so add the value to sum and return 38 | if (root.left == null && root.right == null) { 39 | sum += n; 40 | return; 41 | } 42 | // recurse for left subtree 43 | traverse(root.left, n); 44 | // recurse for right subtree 45 | traverse(root.right, n); 46 | } 47 | } -------------------------------------------------------------------------------- /Java/symmetric-tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | * Runtime: 0 ms 10 | * Memory Usage: 37.9 MB 11 | */ 12 | class Solution { 13 | public boolean isSymmetric(TreeNode root) { 14 | /* if root node of tree itself is null, then it's symmetric */ 15 | if(root==null) 16 | return true; 17 | return checkMirror(root.left, root.right); 18 | } 19 | public boolean checkMirror(TreeNode lt, TreeNode rt){ 20 | /* if root's left and root's right both are null, is then that subtree is symmetric */ 21 | if(lt==null && rt==null) 22 | return true; 23 | 24 | /* if root's left is null and root's right is not null and vice-versa, is then that subtree is not symmetric */ 25 | if((lt!=null && rt==null) || (lt==null && rt!=null)) 26 | return false; 27 | 28 | /* check if left node's value matches with right node's value, and recursively check for their left and right subtrees */ 29 | if(lt.val==rt.val && checkMirror(lt.left,rt.right) && checkMirror(lt.right,rt.left)) 30 | return true; 31 | 32 | return false; 33 | } 34 | } -------------------------------------------------------------------------------- /Java/two-sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * One-pass Hash Table 3 | * we iterate and inserting elements into the table, 4 | * we also look back to check if current element's complement already exists in the table. 5 | * If it exists, we have found a solution and return immediately. 6 | * 7 | * Time complexity : O(n) 8 | * Space complexity : O(n) 9 | */ 10 | class Solution { 11 | public int[] twoSum(int[] nums, int target) { 12 | 13 | Map sumMap = new HashMap<>(); 14 | int [] result = new int[2]; 15 | 16 | for (int i=0; i wordList) { 20 | HashSet hs=new HashSet<>(wordList); 21 | if(!hs.contains(endWord)) 22 | { 23 | return 0; 24 | } 25 | int steps=1; 26 | Queue q=new LinkedList<>(); 27 | q.add(beginWord); 28 | while(!q.isEmpty()) 29 | { 30 | int count=q.size(); 31 | for(int i=0;i { 34 | let current = root; 35 | let right; 36 | let left; 37 | if(!current) { 38 | return null; 39 | // this checks if the current node is a leaf node 40 | } if (!current.right && !current.left) { 41 | return depth; 42 | } 43 | right = traversal(current.right, depth+1) 44 | left = traversal(current.left, depth+1) 45 | if(!right) { 46 | return left; 47 | } else if(!left) { 48 | return right; 49 | } else { 50 | if(right < left) { 51 | return right 52 | } else { 53 | return left 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /JavaScript/152.Maximum-Product-Subarray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | Example 1: 5 | 6 | Input: [2,3,-2,4] 7 | Output: 6 8 | Explanation: [2,3] has the largest product 6. 9 | Example 2: 10 | 11 | Input: [-2,0,-1] 12 | Output: 0 13 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 14 | */ 15 | 16 | /** 17 | * @param {number[]} nums 18 | * @return {number} 19 | */ 20 | var maxProduct = function (nums) { 21 | if (!nums.length) return 0; 22 | let maxEnding = nums[0]; 23 | let minEnding = nums[0]; 24 | let res = nums[0]; 25 | for (let i = 1; i < nums.length; i++) { 26 | if (nums[i] < 0) { 27 | let temp = minEnding; 28 | minEnding = maxEnding; 29 | maxEnding = temp; 30 | } 31 | 32 | maxEnding = Math.max(maxEnding * nums[i], nums[i]); 33 | minEnding = Math.min(minEnding * nums[i], nums[i]); 34 | res = Math.max(res, maxEnding); 35 | } 36 | return res; 37 | }; 38 | -------------------------------------------------------------------------------- /JavaScript/5.Longest-Palindromic-Substring.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a string s, return the longest palindromic substring in s. 3 | * 4 | * Example 1: 5 | 6 | Input: s = "babad" 7 | Output: "bab" 8 | Note: "aba" is also a valid answer. 9 | Example 2: 10 | 11 | Input: s = "cbbd" 12 | Output: "bb" 13 | Example 3: 14 | 15 | Input: s = "a" 16 | Output: "a" 17 | Example 4: 18 | 19 | Input: s = "ac" 20 | Output: "a" 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= s.length <= 1000 26 | s consist of only digits and English letters (lower-case and/or upper-case), 27 | */ 28 | 29 | /** 30 | * @param {string} s 31 | * @return {string} 32 | */ 33 | var longestPalindrome = function (s) { 34 | var max = 0; 35 | var head = 0; 36 | var n = s.length; 37 | var i = 0; 38 | while (i < n - max / 2) { 39 | var lo = i; 40 | while (i < n && s[i] === s[lo]) { 41 | i++; 42 | } 43 | var hi = i - 1; 44 | while (lo >= 0 && hi < n && s[lo] === s[hi]) { 45 | lo--; 46 | hi++; 47 | } 48 | if (hi - lo - 1 > max) { 49 | max = hi - lo - 1; 50 | head = lo + 1; 51 | } 52 | } 53 | return s.slice(head, head + max); 54 | }; 55 | -------------------------------------------------------------------------------- /JavaScript/50.Powxn.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Pow(x, n) 3 | * Medium 4 | 5 | Implement pow(x, n), which calculates x raised to the power n (i.e. xn). 6 | 7 | 8 | Example 1: 9 | 10 | Input: x = 2.00000, n = 10 11 | Output: 1024.00000 12 | 13 | Example 2: 14 | 15 | Input: x = 2.10000, n = 3 16 | Output: 9.26100 17 | 18 | Example 3: 19 | 20 | Input: x = 2.00000, n = -2 21 | Output: 0.25000 22 | Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 23 | 24 | Constraints: 25 | 26 | -100.0 < x < 100.0 27 | -2^31 <= n <= 2^31-1 28 | -10^4 <= x^n <= 10^4 29 | 30 | * Runtime: 84 ms, faster than 43.91% of JavaScript online submissions for Pow(x, n). 31 | * Memory Usage: 39.1 MB, less than 5.12% of JavaScript online submissions for Pow(x, n). 32 | * 33 | */ 34 | 35 | /** 36 | * @param {number} x 37 | * @param {number} n 38 | * @return {number} 39 | */ 40 | var myPow = function(x, n) { 41 | if (n < 0) { 42 | x = 1 / x; 43 | n = -n; 44 | } 45 | return pow(x, n); 46 | 47 | function pow(x, n) { 48 | if (n == 0) { 49 | return 1.0; 50 | } 51 | const half = pow(x, parseInt(n / 2)); 52 | if (n % 2 === 0) { 53 | return half * half; 54 | } else { 55 | return half * half * x; 56 | } 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /JavaScript/98.Validate-Binary-Search-Tree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Given a binary tree, determine if it is a valid binary search tree (BST). 4 | * 5 | * Assume a BST is defined as follows: 6 | * 7 | * The left subtree of a node contains only nodes with keys less than the node's key. 8 | * The right subtree of a node contains only nodes with keys greater than the node's key. 9 | * Both the left and right subtrees must also be binary search trees. 10 | * 11 | * Example 1: 12 | 13 | 2 14 | / \ 15 | 1 3 16 | 17 | Input: [2,1,3] 18 | Output: true 19 | Example 2: 20 | 21 | 5 22 | / \ 23 | 1 4 24 | / \ 25 | 3 6 26 | 27 | Input: [5,1,4,null,null,3,6] 28 | Output: false 29 | Explanation: The root node's value is 5 but its right child's value is 4. 30 | */ 31 | 32 | var isValidBST = function ( 33 | root, 34 | lower = Number.MIN_SAFE_INTEGER, 35 | upper = Number.MAX_SAFE_INTEGER 36 | ) { 37 | if (!root) return true; 38 | 39 | let value = root.val; 40 | if (value <= lower || value >= upper) { 41 | return false; 42 | } 43 | 44 | if (!isValidBST(root.right, value, upper)) { 45 | return false; 46 | } 47 | 48 | if (!isValidBST(root.left, lower, value)) { 49 | return false; 50 | } 51 | return true; 52 | }; 53 | -------------------------------------------------------------------------------- /JavaScript/Binary-Tree-ZigZag-Traversal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Binary Tree ZigZag level Order Traversal 3 | * Medium 4 | * 5 | 6 | Example 1: 7 | 8 | Given a binary tree, return the zigzag level order traversal of its nodes' values. 9 | (ie, from left to right, then right to left for the next level and alternate between). 10 | 11 | For example: 12 | Given binary tree [3,9,20,null,null,15,7], 13 | 14 | 3 15 | / \ 16 | 9 20 17 | / \ 18 | 15 7 19 | 20 | return its zigzag level order traversal as: 21 | 22 | [ 23 | [3], 24 | [20,9], 25 | [15,7] 26 | ] 27 | 28 | * Logic : Using Breadth First Search to Solve This Problem. 29 | Using a boolean to push in front of array and in end of the array and toogle it after every level traversed 30 | * Runtime: 80 ms 31 | * Memory Usage: 37.6 MB 32 | * 33 | */ 34 | 35 | var zigzagLevelOrder = function (root) { 36 | let queue = [], 37 | result = [], 38 | zigzag = true; 39 | if (root == null) return []; 40 | queue.push(root); 41 | while (queue.length) { 42 | let size = queue.length; 43 | let temp = []; 44 | while (size--) { 45 | let pop = queue.shift(); 46 | if (pop && pop.left) queue.push(pop.left); 47 | if (pop && pop.right) queue.push(pop.right); 48 | if (zigzag) { 49 | if (pop) temp.push(pop.val); 50 | } else { 51 | if (pop) temp.unshift(pop.val); 52 | } 53 | } 54 | zigzag = !zigzag; 55 | result.push(temp); 56 | } 57 | 58 | return result; 59 | }; 60 | -------------------------------------------------------------------------------- /JavaScript/Duplicate-Zeroes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Duplicate Zeros 3 | * Easy 4 | * @return {void} Do not return anything, modify arr in-place instead. 5 | * Duplicate Zeros 6 | 7 | Example 1: 8 | 9 | Given arr = [1,0,2,3,0,4,5,0], and modified array = [1,0,0,2,3,0,0,4] is the first bad version. 10 | 11 | call duplicateZeros([1,0,2,3,0,4,5,0]) -> [1,0,0,2,3,0,0,4] 12 | 13 | Given arr = [1,2,3], and modified array = null is the first bad version. 14 | 15 | call duplicateZeros([1,2,3]) -> null 16 | 17 | * Logic : Use built in methods splice() to add an 0 if there's 0 18 | when loops end remove the extra element than original array length 19 | * Runtime: 76 ms faster than 91.89% 20 | * Memory Usage: 38.2 MB less than 18.50% 21 | * 22 | */ 23 | 24 | var duplicateZeros = function (arr) { 25 | let len = arr.length; 26 | for (let i = 0; i < len; i++) { 27 | if (arr[i] == 0) { 28 | arr.splice(i + 1, 0, 0); 29 | i++; 30 | } 31 | } 32 | arr.splice(len); 33 | }; 34 | -------------------------------------------------------------------------------- /JavaScript/First-Bad-Version.js: -------------------------------------------------------------------------------- 1 | /** 2 | * First Bad Version 3 | * Easy 4 | * 5 | * Find The First Bad Version 6 | 7 | Example 1: 8 | 9 | Given n = 5, and version = 4 is the first bad version. 10 | 11 | call isBadVersion(3) -> false 12 | call isBadVersion(5) -> true 13 | call isBadVersion(4) -> true 14 | 15 | Then 4 is the first bad version. 16 | 17 | * Logic : Using binary search to find the first bad version. 18 | if mid - 1 is not a bad version then mid is first bad version 19 | if mid - 1 is a bad version then set end = mid - 1 20 | if mid is not a bad version then set start = mid + 1 21 | * Runtime: 68 ms 22 | * Memory Usage: 36.3 MB 23 | * 24 | */ 25 | 26 | var solution = function (isBadVersion) { 27 | /** 28 | * @param {integer} n Total versions 29 | * @return {integer} The first bad version 30 | */ 31 | return function (n) { 32 | let start = 0, 33 | end = n; 34 | while (start <= end) { 35 | let mid = Math.floor((end + start) / 2); 36 | if (isBadVersion(mid)) { 37 | if (!isBadVersion(mid - 1)) { 38 | return mid; 39 | } else { 40 | end = mid - 1; 41 | } 42 | } else { 43 | start = mid + 1; 44 | } 45 | } 46 | return -1; 47 | }; 48 | }; 49 | -------------------------------------------------------------------------------- /JavaScript/Subdomain-Visit-Count.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Subdomain Visit Count 3 | * Easy 4 | * @param {string[]} cpdomains 5 | * @return {string[]} 6 | 7 | Example 1: 8 | 9 | Given arr = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]. 10 | 11 | call subdomainVisits(arr) -> ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"] 12 | 13 | Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times. 14 | 15 | * Logic : Use built in methods split() and substring() to split domains 16 | and remove the counted subdomain every iteration with substring() 17 | * Runtime: 92 ms faster than 84.31% 18 | * Memory Usage: 41.2 MB less than 70.87% 19 | * 20 | */ 21 | 22 | var subdomainVisits = function (cpdomains) { 23 | if (!cpdomains || cpdomains.length <= 0) return []; 24 | let map = new Map(); 25 | for (let dom of cpdomains) { 26 | let [num, name] = dom.split(" "); 27 | while (name.indexOf(".") >= 0) { 28 | map.set(name, map.get(name) + Number(num) || Number(num)); 29 | name = name.substring(name.indexOf(".") + 1); 30 | } 31 | map.set(name, map.get(name) + Number(num) || Number(num)); 32 | } 33 | let res = []; 34 | for (let [key, value] of map.entries()) { 35 | res.push(`${value} ${key}`); 36 | } 37 | return res; 38 | }; 39 | -------------------------------------------------------------------------------- /JavaScript/findPeakElement.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. 3 | 4 | Example 1: 5 | Input: nums = [1,2,3,1] 6 | Output: 2 7 | Explanation: 3 is a peak element and your function should return the index number 2. 8 | 9 | Example 2: 10 | Input: nums = [1,2,1,3,5,6,4] 11 | Output: 5 12 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. 13 | 14 | */ 15 | 16 | /** 17 | * @param {number[]} nums 18 | * @return {number} 19 | */ 20 | var findPeakElement = function (nums) { 21 | let left = 0, 22 | right = nums.length - 1, 23 | mid; 24 | 25 | while (left < right) { 26 | mid = Math.floor((right + left) / 2); 27 | if (nums[mid] > nums[mid + 1]) right = mid; 28 | else left = mid + 1; 29 | } 30 | return left; 31 | }; 32 | -------------------------------------------------------------------------------- /JavaScript/single-number.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a non-empty array of integers, every element appears twice except for 3 | * one. Find that single one. 4 | * 5 | * Note: 6 | * 7 | * Your algorithm should have a linear runtime complexity. Could you implement 8 | * it without using extra memory? 9 | * 10 | * Example 1: 11 | * 12 | * Input: [2,2,1] Output: 1 13 | * 14 | * Example 2: 15 | * 16 | * Input: [4,1,2,1,2] Output: 4 17 | * 18 | */ 19 | 20 | /** 21 | * @param {number[]} nums 22 | * @return {number} 23 | */ 24 | var singleNumber = function(nums) { 25 | result= [] 26 | nums.sort() 27 | 28 | nums.forEach(element => { 29 | if (result.indexOf(element) == -1){ 30 | result.push(element) 31 | }else{ 32 | result.splice(result.indexOf(element),1) 33 | } 34 | }); 35 | 36 | return result[0] 37 | }; 38 | 39 | 40 | 41 | //------- Test cases ----------------- 42 | // Input: nums = [2,2,1] 43 | // Output: 1 44 | console.log(`Example 01 = ${singleNumber([2,2,1])} expected Output 1.`) 45 | 46 | // Input: nums = [4,1,2,1,2] 47 | // Output: 4 48 | console.log(`Example 02 = ${singleNumber([4,1,2,1,2])} expected Output 4.`) 49 | 50 | // Input: nums = [1] 51 | // Output: 1 52 | console.log(`Example 03 = ${singleNumber([1])} expected Output 1.`) 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 codedecks-in 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 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | # Pull Request Template 2 | 3 | ## Description 4 | 5 | Please include a summary of the problem and about the approach to solve the solution. Please also include relevant motivation and context. 6 | List any dependencies that are required for this change. 7 | 8 | ## Put check marks: 9 | ## Have you made changes in [README](https://github.com/codedecks-in/LeetCode-Solutions/blob/master/README.md) file ? 10 | - [ ] Added problem & solution under correct topic. 11 | - [ ] Specified Space & Time complexity. 12 | - [ ] Specified difficulty level, tag & Note(if any). 13 | 14 | ## How Has This Been Tested? 15 | 16 | Please describe the tests that you ran to verify your changes. Please also note any relevant details for your test configuration. 17 | 18 | - [ ] Test A 19 | - [ ] Test B 20 | 21 | ## Make sure all below guidelines are followed else PR will get Reject: 22 | 23 | - [ ] My code follows the style guidelines of this project 24 | - [ ] I have performed a self-review of my own code 25 | - [ ] I have commented my code so that it is easy to understand 26 | - [ ] I have made corresponding changes to the documentation 27 | - [ ] My changes generate no new warnings 28 | - [ ] Any dependent changes have been merged and published in downstream modules 29 | -------------------------------------------------------------------------------- /Python/100.SameTree.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(n) 2 | #Space Complexity: O(n) 3 | #Speed: 98.83% 4 | #Memory: 13.23% 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode: 8 | # def __init__(self, val=0, left=None, right=None): 9 | # self.val = val 10 | # self.left = left 11 | # self.right = right 12 | 13 | class Solution: 14 | 15 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 16 | result = [] 17 | self.preorder(p, q, result) 18 | return min(result) 19 | 20 | def preorder(self, p, q, result): 21 | if not p and not q: 22 | result.append(True) 23 | return 24 | if not p or not q: 25 | result.append(False) 26 | return 27 | if p.val != q.val: 28 | result.append(False) 29 | if p.val == q.val: 30 | result.append(True) 31 | self.preorder(p.left, q.left, result) 32 | self.preorder(p.right, q.right, result) -------------------------------------------------------------------------------- /Python/101.SymmetricTree.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(n) 2 | #Space Complexity: O(n) 3 | #Speed: 95.44% 4 | #Memory: 23.72% 5 | 6 | class Solution: 7 | def isSymmetric(self, root: TreeNode) -> bool: 8 | queue = [root] 9 | while queue: 10 | length = len(queue) 11 | level = [] 12 | while length: 13 | node = queue.pop(0) 14 | level.append(node.val if node else None) 15 | length -= 1 16 | if node: 17 | queue.append(node.left) 18 | queue.append(node.right) 19 | i = 0 20 | j = len(level) - 1 21 | while i <= j: 22 | if level[i] != level[j]: 23 | return False 24 | i += 1 25 | j -= 1 26 | return True -------------------------------------------------------------------------------- /Python/1042_FlowerPlantingwithNoAdjacent.py: -------------------------------------------------------------------------------- 1 | #Difficulty = Medium 2 | #Submission Speed = 85.81% 3 | ''' 4 | #The Algorithm is similar to Graph coloring algorithm. 5 | After making the graph from edge lists, 6 | We will traverse every node one by one. For every node, create a fresh new list of choices of flowers 7 | While Traversing a particular node (say NODE A), we will check its neighbours and if any of the neighbour has been assigned 8 | flower (say flower 'X') we will remove that flower ('X') from the list of choices of the corresponding Node (NODE A) 9 | ''' 10 | ''' 11 | If E = Number of Edges 12 | V = Number of Vertices/Nodes 13 | Time Complexity = O(V+E) 14 | Space Complexity = O(2V+E) 15 | ''' 16 | from collections import defaultdict 17 | class Solution: 18 | def gardenNoAdj(self, N, paths): 19 | 20 | #Create Graph 21 | graph = defaultdict(list) 22 | for i in paths: 23 | graph[i[0]].append(i[1]) #Since Graph is Bidirectional, we need to add edge both sides 24 | graph[i[1]].append(i[0]) 25 | flowers = [] 26 | for i in range(1, N + 1): #We will traverse every node one by one 27 | choice = [1, 2, 3, 4] #create a fresh new list of choices of flowers 28 | for k in graph[i]: #check its neighbours 29 | try: 30 | choice.remove(flowers[k-1]) #if any of the neighbour has been assigned flower (say flower 'X') we will remove that flower ('X') 31 | except: 32 | pass 33 | flowers.append(choice[0]) #Select the first flower from the remaining choices 34 | return flowers -------------------------------------------------------------------------------- /Python/150.EvaluateReversePolishNotation.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(n) 2 | #Space Complexity: O(1) 3 | #Speed: 84.65% 4 | #Memory: 84.34% 5 | 6 | class Solution: 7 | def evalRPN(self, tokens: List[str]) -> int: 8 | stack = [] 9 | for token in tokens: 10 | if token.isdigit() or token[1:].isdigit(): 11 | stack.append(int(token)) 12 | else: 13 | y = stack.pop() 14 | x = stack.pop() 15 | if token == '+': stack.append(x + y) 16 | if token == '-': stack.append(x - y) 17 | if token == '*': stack.append(x * y) 18 | if token == '/': stack.append(int(x / y)) 19 | return stack[0] -------------------------------------------------------------------------------- /Python/20_ValidParentheses.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #Difficulty: Easy 3 | #Runtime: 82.23% 4 | #Memory Usage: 64.83% 5 | 6 | """ 7 | Algorithm: 8 | 1. Check a bracket (b) in the string (s), if it contains in parentheses 9 | dictionary then we add to stack it's opposite bracket. 10 | 2. If bracket not in parentheses we check does it mach with last bracket in 11 | the stack, also we check if stack exists while iterating through the string. 12 | If one of this conditions is not True - return False immediately. 13 | 3. After we checked whole string we need to check is stack empty or not and 14 | return result. 15 | 4. Result will be true if stack is empty it means all parentheses are valid 16 | and closed in the correct order. 17 | 18 | Time Complexity = O(n) 19 | Space Complexity = O(n) 20 | """ 21 | 22 | class Solution: 23 | def isValid(self, s: str) -> bool: 24 | parentheses = {'(':')', '{':'}', '[':']'} 25 | stack = [] 26 | for b in s: # take bracket 'b' from string 's' 27 | if b in parentheses: # if bracket in parentheses 28 | stack.append(parentheses[b]) # append it's opposite to stack 29 | elif not stack or stack.pop() != b: # if not stack or bracket not 30 | return False # equal last bracket in stack 31 | return not stack # if stack still exists -> False else True -------------------------------------------------------------------------------- /Python/35.SearchInsertPosition.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(log(n)) 2 | #Space Complexity: O(1) 3 | #Speed: 91.93% 4 | #Memory: 5.97% 5 | 6 | class Solution: 7 | def searchInsert(self, nums: List[int], target: int) -> int: 8 | l = 0 9 | r = len(nums)-1 10 | while l <= r: 11 | m = (l+r)//2 12 | if m == r and target > nums[m]: 13 | return m + 1 14 | if target > nums[m]: 15 | l = m + 1 16 | else: 17 | r = m - 1 18 | return m -------------------------------------------------------------------------------- /Python/496_nextgreaterelement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def check(self, number, nums1, nums2): 3 | index = nums2.index(number) 4 | for _ in range(index, len(nums2)): 5 | if(nums2[_]>number): 6 | return nums2[_] 7 | return -1 8 | 9 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 10 | return [self.check(x, nums1, nums2) for x in nums1] 11 | -------------------------------------------------------------------------------- /Python/50.Powxn.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(n) 2 | #Space Complexity: O(1) 3 | #Speed: 92.57% 4 | #Memory: 15.17% 5 | 6 | class Solution: 7 | def myPow(self, x: float, n: int) -> float: 8 | if not n: return 1 9 | power = self.myPow(x, int(n/2)) 10 | if n % 2 == 0: 11 | return power * power 12 | else: 13 | return power * power / x if n < 0 else power * power * x -------------------------------------------------------------------------------- /Python/56_MergeIntervals.py: -------------------------------------------------------------------------------- 1 | #Difficluty - Medium 2 | #Speed = 33.94% 3 | ''' 4 | First we will sort the intervals (with start time of the interval as the key), so that the (overlapping) intervals that could be merged comes adjacent. For Ex: 5 | Original Array -> [[0,2], [5,9], [1,3], [11,12]] 6 | Sorted Array -> [[0,2], [1,3], [5,9], [11,12]] 7 | Note => Time Complexity of Sorting is O(nlogn) 8 | Overlapping Condition: Two intervals (X and Y) are overlapping if end Time of first interval (X) is greater than start time of second interval (Y) 9 | that is, 10 | X.end > Y.start 11 | In case of [0,2] and [1,3], since 2 > 1, these intervals are overlapping. 12 | In case of [5,9] and [11,12], since 9 < 11, these intervals are *NOT* overlapping. 13 | So we will start with pushing the first interval in merged array. 14 | Then traverse the array, checking the overlapping condition of every interval with the last interval in merged array, 15 | 1) If overlapping condition satisfy, We will update the end time of last interval in merged array as maximum of end time of both intervals. 16 | 2) If overlapping condition doesnt satisy, We will push the interval in merged array 17 | ''' 18 | #Time Complexity: O(nlogn) 19 | #Space Complexity: O(n) 20 | class Solution: 21 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 22 | intervals.sort(key=lambda x: x[0]) #sort the intervals with starting time as the key 23 | merged = [] 24 | for interval in intervals: 25 | if not merged or merged[-1][1] < interval[0]: #If merged list is empty (we need to push the first interval) or Overlapping condn doesnt satisfy 26 | merged.append(interval) #push the interval in merged array 27 | else: #else 28 | merged[-1][1] = max(merged[-1][1], interval[1]) #update the end time of last interval in merged array as maximum of end time of both intervals 29 | return merged 30 | -------------------------------------------------------------------------------- /Python/5_LongestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | #Difficulty = Medium 2 | #Submission Speed = 48.40% 3 | ''' 4 | Before Jumping onto Solution, know that: 5 | =>Palindromes are of two types: Odd Palindromes (length is odd) and Even Palindrome (length is even) 6 | =>We traverse the array, and for every element, we suppose that current element is the middle element and check for the largest palindromic 7 | substring that can be made which has middle element as the current element. 8 | Note that, In case of even palindrome, there are two middle elements. 9 | => We check for both Odd and even Palindromes 10 | => How to check for largest palindromic substring with given middle element? 11 | we maintain two pointers left and right. 12 | Initialize them with current index (middle element index) and In every loop we check s[left]==s[right] (and check for 13 | boundary errors too, left and right dont go out of the size of array or 0). In the body of the loop we decrease the left 14 | and increase the right pointer. 15 | ''' 16 | ''' 17 | Time Complexity = O(N^2) 18 | Space Complexity = O(N) 19 | ''' 20 | 21 | 22 | class Solution: 23 | def longestPalindrome(self, s: str) -> str: 24 | longest = "" 25 | size = len(s) 26 | for i in range(size): 27 | #Odd Palindrome 28 | left,right = i,i 29 | ls = "" 30 | while 0<=leftlen(rs) else rs 45 | longest = temp if len(temp)>len(longest) else longest 46 | return longest -------------------------------------------------------------------------------- /Python/621-Task-Scheduler.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. 3 | Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, 4 | the CPU could complete either one task or just be idle. 5 | 6 | However, there is a non-negative integer n that represents the cooldown period between 7 | two same tasks (the same letter in the array), 8 | is that there must be at least n units of time between any two same tasks. 9 | 10 | 11 | Memory ->14.4MB 12 | runtime ->412ms 13 | 14 | 15 | 16 | 17 | """ 18 | 19 | 20 | class Solution: 21 | def leastInterval(self, tasks: List[str], n: int) -> int: 22 | counter=Counter(tasks) 23 | freq=sorted(list(counter.values())) 24 | 25 | max_idle=freq.pop() 26 | total=(max_idle-1)*n 27 | 28 | while freq and total>0: 29 | total=total-min(max_idle-1,freq.pop()) 30 | 31 | total=max(0,total) 32 | return len(tasks) + total 33 | -------------------------------------------------------------------------------- /Python/994_Rotting_Oranges.py: -------------------------------------------------------------------------------- 1 | # Time Complexity = O(rows*columns) 2 | # Space Complexity = O(rows*columns) 3 | 4 | class Solution: 5 | def orangesRotting(self, grid: List[List[int]]) -> int: 6 | n = len(grid) 7 | m = len(grid[0]) 8 | 9 | count = 0 10 | rotten = [] 11 | for i in range(n): 12 | for j in range(m): 13 | if grid[i][j]==2: 14 | rotten.append((i,j)) 15 | count+=1 16 | elif grid[i][j] == 1: 17 | count+=1 18 | 19 | 20 | if count == 0: 21 | return 0 22 | 23 | cycles = 0 24 | 25 | while rotten: 26 | count-=len(rotten) 27 | newRotten = [] 28 | for i,j in rotten: 29 | self.destroy(grid,i+1,j,n,m,newRotten) 30 | self.destroy(grid,i-1,j,n,m,newRotten) 31 | self.destroy(grid,i,j+1,n,m,newRotten) 32 | self.destroy(grid,i,j-1,n,m,newRotten) 33 | rotten = newRotten 34 | cycles+=1 35 | 36 | if count>0: 37 | return -1 38 | else: 39 | return cycles-1 40 | 41 | def destroy(self, grid, i, j, n, m, rotten): 42 | if 0<=i List[int]: 9 | if not root: 10 | return [] 11 | result = [] 12 | stack = [] 13 | node = root 14 | while stack or node: 15 | while node: 16 | stack.append(node) 17 | node = node.left 18 | node = stack.pop() 19 | result.append(node.val) 20 | node = node.right 21 | return result 22 | 23 | 24 | -------------------------------------------------------------------------------- /Python/LRUCache.py: -------------------------------------------------------------------------------- 1 | class ListNode(object): 2 | def __init__(self,key,val): 3 | self.key = key 4 | self.value = val 5 | self.next = None 6 | self.prev = None 7 | 8 | class LRUCache: 9 | 10 | def __init__(self, capacity: int): 11 | self.cap = capacity 12 | self.dic = {} 13 | self.head = ListNode(-1,-1) 14 | self.tail = ListNode(-1,-1) 15 | self.head.next = self.tail 16 | self.tail.prev = self.head 17 | 18 | 19 | def get(self, key: int) -> int: 20 | if key in self.dic: 21 | node = self.dic[key] 22 | self.remove(node) 23 | self.add(node) 24 | return node.value 25 | return -1 26 | 27 | def put(self, key: int, value: int) -> None: 28 | 29 | if key in self.dic: 30 | node = self.dic[key] 31 | self.remove(node) 32 | del self.dic[node.key] 33 | if len(self.dic)>=self.cap: 34 | node = self.head.next 35 | self.remove(node) 36 | del self.dic[node.key] 37 | 38 | node = ListNode(key,value) 39 | self.dic[key] = node 40 | self.add(node) 41 | # self.show(self.head) 42 | 43 | 44 | 45 | def remove(self,node): 46 | prevNode = node.prev 47 | prevNode.next = node.next 48 | node.next.prev = prevNode 49 | 50 | def add(self,node): 51 | tailprev = self.tail.prev 52 | tailprev.next = node 53 | node.prev = tailprev 54 | node.next = self.tail 55 | self.tail.prev = node 56 | # self.show(self.head) 57 | 58 | def show(self,head): 59 | while head: 60 | print(head.value,end=" ") 61 | head = head.next 62 | print() 63 | 64 | 65 | 66 | # Your LRUCache object will be instantiated and called as such: 67 | # obj = LRUCache(capacity) 68 | # param_1 = obj.get(key) 69 | # obj.put(key,value) 70 | -------------------------------------------------------------------------------- /Python/SmallestDifference.py: -------------------------------------------------------------------------------- 1 | """1200. Minimum Absolute Difference 2 | Easy 3 | 4 | 382 5 | 6 | 25 7 | 8 | Add to List 9 | 10 | Share 11 | Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 12 | 13 | Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows 14 | 15 | a, b are from arr 16 | a < b 17 | b - a equals to the minimum absolute difference of any two elements in arr 18 | 19 | 20 | Example 1: 21 | 22 | Input: arr = [4,2,1,3] 23 | Output: [[1,2],[2,3],[3,4]] 24 | Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. 25 | Example 2: 26 | 27 | Input: arr = [1,3,6,10,15] 28 | Output: [[1,3]] 29 | Example 3: 30 | 31 | Input: arr = [3,8,-10,23,19,-4,-14,27] 32 | Output: [[-14,-10],[19,23],[23,27]] 33 | 34 | 35 | Constraints: 36 | 37 | 2 <= arr.length <= 10^5 38 | -10^6 <= arr[i] <= 10^6 39 | """ 40 | 41 | def smallestDifference(arr1 : list, arr2 : list) : 42 | arr1.sort();arr2.sort() 43 | i = 0;j = 0 44 | 45 | smallest = float("inf");current=float("inf") 46 | smallestPair = list() 47 | 48 | while i < len(arr1) and j < len(arr2) : 49 | fnum = arr1[i];snum = arr2[j] 50 | 51 | if fnum < snum : 52 | current = snum - fnum 53 | i += 1 54 | elif snum < fnum : 55 | current = snum - fnum 56 | j += 1 57 | else : 58 | return [fnum, snum] 59 | 60 | if current < smallest : 61 | smallest = current 62 | smallestPair.append((fnum, snum)) 63 | 64 | 65 | 66 | if __name__ == '__main__' : 67 | print(smallestDifference([12,3,45,6], [2,4,3,5])) -------------------------------------------------------------------------------- /Python/ThreeNumbersSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | 15. 3Sum 3 | Medium 4 | 5 | 8121 6 | 7 | 881 8 | 9 | Add to List 10 | 11 | Share 12 | Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 13 | 14 | Notice that the solution set must not contain duplicate triplets. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: nums = [-1,0,1,2,-1,-4] 21 | Output: [[-1,-1,2],[-1,0,1]] 22 | Example 2: 23 | 24 | Input: nums = [] 25 | Output: [] 26 | Example 3: 27 | 28 | Input: nums = [0] 29 | Output: [] 30 | """ 31 | 32 | def sum_of_three(arr, target=0) : 33 | result = list() 34 | arr.sort() 35 | 36 | for i in range(len(arr)-2) : 37 | left = i+1;right=len(arr)-1 38 | 39 | while left < right : 40 | current_sum = arr[i] + arr[left] + arr[right] 41 | if current_sum == target : 42 | result.append((arr[i], arr[left], arr[right])) 43 | left+=1 44 | right-=1 45 | elif current_sum < target : 46 | left += 1 47 | elif current_sum > target : 48 | right -= 1 49 | else : 50 | print("Dont with the loop") 51 | return result 52 | 53 | if __name__ == '__main__' : 54 | print(sum_of_three([3,5,-4,8,11,1,-1,6])) 55 | -------------------------------------------------------------------------------- /Python/baseK.py: -------------------------------------------------------------------------------- 1 | def sumBase(n: int, k: int) : 2 | """ 3 | Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. 4 | After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. 5 | TC : O(N) 6 | SC : O(1) 7 | n : int (integer base 10) 8 | k : int (base to be converted to) 9 | return value : int 10 | """ 11 | summation=0 12 | while n >= k : 13 | 14 | summation = summation + n%k 15 | n=n//k 16 | print(n) 17 | return (summation + n) -------------------------------------------------------------------------------- /Python/best-time-to-buy-and-sell-stock-ii.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 99.14% 3 | Memory: 4 | Time Complexity: O(n) 5 | ''' 6 | class Solution: 7 | def solve(self, prices): 8 | # Write your code here 9 | if len(prices)<2:return 0 10 | buy = prices[0] 11 | profit = 0 12 | for i in range(1,len(prices)): 13 | if prices[i] List[int]: 14 | if root is None: 15 | return [] 16 | else: 17 | return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right) 18 | -------------------------------------------------------------------------------- /Python/container_with_most_water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxArea(self, height): 3 | """ 4 | :type height: List[int] 5 | :rtype: int 6 | """ 7 | 8 | #print(height) 9 | start=0 10 | end=len(height)-1 11 | max_area=0 12 | curr_area=0 13 | while(start!=end): 14 | if(height[start]max_area): 21 | max_area=curr_area 22 | print(curr_area) 23 | return max_area 24 | -------------------------------------------------------------------------------- /Python/contains-duplicate.py: -------------------------------------------------------------------------------- 1 | # Autor: Anuj Sharma (@optider) 2 | # Github Profile: https://github.com/Optider/ 3 | # Problem Link: https://leetcode.com/problems/contains-duplicate/ 4 | 5 | 6 | class Solution: 7 | def containsDuplicate(self, nums: List[int]) -> bool: 8 | count = {} 9 | for n in nums : 10 | if count.get(n) != None : 11 | return True 12 | count[n] = 1 13 | return False 14 | -------------------------------------------------------------------------------- /Python/count-good-triplets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | The Brute Force Solution 4 | 5 | Time Complexity: O(N^3) 6 | Space Complexity: O(1) 7 | """ 8 | 9 | def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: 10 | 11 | triplet_count = 0 12 | 13 | # for each i, for each j, check if the first condition is satisfied 14 | for i in range(len(arr) - 2): 15 | for j in range(i + 1, len(arr) - 1): 16 | if abs(arr[i] - arr[j]) <= a: 17 | 18 | # for each k, check if the last two conditions are satisfied 19 | for k in range(j + 1, len(arr)): 20 | if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: 21 | 22 | # the triplet is Good, increment the count! 23 | triplet_count += 1 24 | return triplet_count 25 | -------------------------------------------------------------------------------- /Python/decode-ways.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 93.43% 3 | Memory: 38.43% 4 | Time Complexity: O(n) 5 | ''' 6 | class Solution: 7 | def numDecodings(self, s: str) -> int: 8 | if not s or s[0]=='0': 9 | return 0 10 | dp = [0]*(len(s)+1) 11 | dp[0],dp[1] = 1,1 12 | for j in range(2,len(s)+1): 13 | i = j-1 14 | a = int(s[i]) 15 | b = int(s[i-1:i+1]) 16 | if 0 int: 30 | if not s or s[0]=='0': 31 | return 0 32 | p,q = 1,1 33 | for i in range(1,len(s)): 34 | a = int(s[i]) 35 | y = 0 36 | if 0 111 7 | Is => 10 8 | country => 0000000 9 | step 2) Word will be valid if: 10 | a) When word starts with Capital and remaining all are small => Then the number for such word will be 10.....0 11 | To make 10...0 we will do: 1<<(size-1) 12 | b) When all are lower => Then the number will be 00...0 13 | To make 00...0 we will do: 0<<(size-1) 14 | c) When all are capital => Then the number will be 1....1 15 | To make 1...1 we will do: (1< bool: 24 | num = 0 25 | size = len(word) 26 | 27 | #Generating the number 28 | for i in range(size): 29 | num = num*10 30 | if word[i].isupper(): 31 | num+=1 32 | num = int(str(num),2) 33 | 34 | #Checking if it matches any of the valid number 35 | if num==(1<<(size-1)) or num==(0<<(size-1)) or num==((1< bool: 8 | dp = [False]*(N+1) 9 | for i in range(N+1): 10 | for j in range(1,i): 11 | if i%j==0 and dp[i-j]==False: 12 | dp[i] = True 13 | return dp[N] -------------------------------------------------------------------------------- /Python/edit-distance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 99.48% 3 | Memory: 81.78% 4 | Time Complexity: O(N*M) where N = len(s1) and M = len(s2) 5 | ''' 6 | class Solution: 7 | def minDistance(self, s1: str, s2: str) -> int: 8 | @lru_cache(None) 9 | def editdistance(i,j,s1=s1,s2=s2): 10 | if not i: 11 | return j 12 | if not j: 13 | return i 14 | if s1[i-1]==s2[j-1]: 15 | return editdistance(i-1,j-1) 16 | else: 17 | return 1 + min(editdistance(i-1,j),editdistance(i,j-1),editdistance(i-1,j-1)) 18 | # Insert,Delete,replace 19 | return editdistance(len(s1),len(s2),s1,s2) -------------------------------------------------------------------------------- /Python/find-minimum-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 37.59% 3 | Memory: 20.90% 4 | Time Complexity: O(logn) 5 | ''' 6 | class Solution: 7 | def findMin(self, nums: List[int]) -> int: 8 | if nums[0]<=nums[-1]: 9 | return nums[0] 10 | l,h = 0,len(nums)-1 11 | while l<=h: 12 | mid = h - (h-l)//2 13 | if mid>0 and nums[mid]nums[0]: 16 | l = mid+1 17 | else: 18 | h = mid-1 -------------------------------------------------------------------------------- /Python/group_anagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 3 | 4 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 5 | 6 | Example: 7 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 8 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 9 | ''' 10 | 11 | class Solution(object): 12 | def groupAnagrams(self, strs): 13 | """ 14 | :type strs: List[str] 15 | :rtype: List[List[str]] 16 | """ 17 | from collections import defaultdict 18 | 19 | anagrams = defaultdict(list) 20 | for s in strs: 21 | anagrams[str(sorted(s))].append(s) 22 | 23 | return list(anagrams.values()) 24 | 25 | n=["eat", "tea", "tan", "ate", "nat", "bat"] 26 | ans=Solution() 27 | res=ans.groupAnagrams(n) 28 | print(res) 29 | -------------------------------------------------------------------------------- /Python/jumpGame.py: -------------------------------------------------------------------------------- 1 | # You are given an integer array nums. You are initially positioned at the array's first index, 2 | # and each element in the array represents your maximum jump length at that position. 3 | # Return true if you can reach the last index, or false otherwise. 4 | 5 | # Input: nums = [2,3,1,1,4] 6 | # Output: true 7 | # Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 8 | 9 | # Input: nums = [3,2,1,0,4] 10 | # Output: false 11 | # Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 12 | 13 | ''' 14 | Time Complexity: O(n), 15 | Space Complexity: O(n) 16 | ''' 17 | 18 | def canJump(nums): 19 | ptr1 = len(nums) - 1 20 | ptr2 = ptr1 - 1 21 | 22 | while ptr2 >= 0: 23 | if nums[ptr2] >= ptr1 - ptr2: 24 | ptr1 = ptr2 25 | ptr2 -= 1 26 | else : 27 | ptr2 -= 1 28 | 29 | if ptr1 == 0: 30 | return True 31 | else: 32 | return False 33 | 34 | print(canJump[3,2,1,0,4]) -------------------------------------------------------------------------------- /Python/longest-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 95.97% 3 | Memory: 24.96% 4 | Time complexity: O(n) 5 | Space complexity: O(n) 6 | ''' 7 | class Solution(object): 8 | def longestValidParentheses(self, s): 9 | ans=0 10 | stack=[-1] 11 | for i in range(len(s)): 12 | if(s[i]=='('): 13 | stack.append(i) 14 | else: 15 | stack.pop() 16 | if(len(stack)==0): 17 | stack.append(i) 18 | else: 19 | ans=max(ans,i-stack[-1]) 20 | return ans -------------------------------------------------------------------------------- /Python/maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | #Time Complexity: O(n) 2 | #Space Complexity: O(n) 3 | #Speed: 98.14% 4 | #Memory: 50.93% 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode: 8 | # def __init__(self, val=0, left=None, right=None): 9 | # self.val = val 10 | # self.left = left 11 | # self.right = right 12 | class Solution: 13 | def maxDepth(self, root: TreeNode) -> int: 14 | if root is None: 15 | return 0 16 | else: 17 | return max(self.maxDepth(root.left)+1, self.maxDepth(root.right)+1) -------------------------------------------------------------------------------- /Python/pascals-triangle-ii.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Speed: 77.11% 3 | Memory: 82.57% 4 | Time Complexity: O(n) 5 | ''' 6 | class Solution: 7 | def getRow(self, k: int) -> List[int]: 8 | res = [1]*(k+1) 9 | #res[0]=1 10 | for i in range(1,k): 11 | for j in range(i,0,-1): 12 | res[j]+=res[j-1] 13 | return res -------------------------------------------------------------------------------- /Python/reorganize-string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | speed: 89.11% 3 | memory: 21:02% 4 | N = len(S), A = 1~26(size of diff alpabet) 5 | ex) aab, N=3, A=2 6 | time complexity: O(A * (N + logA)) 7 | space complexity: O(N) 8 | ''' 9 | class Solution: 10 | def reorganizeString(self, S: str) -> str: 11 | n = len(S) 12 | a= [] 13 | 14 | for c,x in sorted((S.count(x), x) for x in set(S)): 15 | if c > (n+1)/2: # not possible 16 | return '' 17 | a.extend(c*x) 18 | 19 | # empty list 20 | ans = [None] * n 21 | 22 | # placing letters to make possible result 23 | ans[::2], ans[1::2] = a[n//2:], a[:n//2] 24 | return "".join(ans) 25 | 26 | -------------------------------------------------------------------------------- /Python/rotate-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | lenz = len(nums) 7 | k = k % lenz 8 | if k == 0: 9 | return nums 10 | nums += nums[:-k] 11 | del nums[:lenz-k] 12 | -------------------------------------------------------------------------------- /Python/search-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Time Complexity: O(logn) 3 | Space Complexity: O(1) 4 | 5 | Point to observe: Each time either the left half will be sorted or the right half. 6 | Hence Binary Search is a good option. 7 | """ 8 | 9 | class Solution: 10 | def search(self, nums: List[int], target: int) -> int: 11 | n = len(nums) 12 | low = 0 13 | high = n-1 14 | while low<=high: 15 | mid = (low+high)//2 16 | if nums[mid]==target: 17 | return mid 18 | 19 | # if left half is sorted 20 | if nums[low]<=nums[mid]: 21 | if nums[low]<=target int: 3 | dict1 = {} # Create hashtable 4 | # Add counts into the hashtable 5 | for x in nums: 6 | if x not in dict1: 7 | dict1[x] = 1 8 | else: 9 | dict1[x] += 1 10 | # Select the single element 11 | for ans, y in dict1.items(): 12 | if y == 1: 13 | return ans 14 | 15 | # Or bitwise way 16 | class Solution: 17 | def singleNumber(self, nums: List[int]) -> int: 18 | a, b = 0, 0 19 | # Just bitwise operation, (notx and a and notb) or (x and nota and b) ... 20 | for x in nums: 21 | a, b = (~x&a&~b)|(x&~a&b), ~a&(x^b) 22 | return b -------------------------------------------------------------------------------- /Python/single-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | d = dict() 4 | for i in range(len(nums)) : 5 | if nums[i] not in d : 6 | d[nums[i]] = 1 7 | else: 8 | d[nums[i]] += 1 9 | for key, value in d.items() : 10 | if value == 1 : 11 | return key -------------------------------------------------------------------------------- /Python/split-a-string-in-balanced-strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time Complexity: O(N) 4 | Space Complexity: O(1) 5 | """ 6 | 7 | def balanced_string_split(self, s: str) -> int: 8 | # initialize variables 9 | L_count, R_count = 0, 0 10 | balanced_substring_count = 0 11 | 12 | # parse the string 13 | for char in s: 14 | 15 | # update the number of Ls and the number of Rs so far 16 | if char == 'L': 17 | L_count += 1 18 | elif char == 'R': 19 | R_count += 1 20 | 21 | # if the string is balanced, increment the balanced substrings count and reset the counters 22 | if L_count == R_count: 23 | balanced_substring_count += 1 24 | L_count, R_count = 0, 0 25 | return balanced_substring_count 26 | -------------------------------------------------------------------------------- /Python/trapping_rain.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | water=0 4 | left=-1 5 | right=len(height) 6 | current=0 7 | arr1=[] 8 | arr2=[] 9 | left_max=0 10 | right_max=0 11 | for current in range(len(height)): 12 | while(left!=current): 13 | left+=1 14 | if(left_max<=height[left]): 15 | left_max=height[left] 16 | arr1.append(left_max) 17 | while(right!=current): 18 | right-=1 19 | 20 | if(right_max<=height[right]): 21 | right_max=height[right] 22 | arr2.append(right_max) 23 | right_max=0 24 | 25 | right=len(height) 26 | left=-1 27 | 28 | 29 | for i in range(len(arr1)): 30 | s=min(arr1[i],arr2[i])-height[i]; 31 | if(s>0): 32 | water+=s 33 | 34 | return water 35 | -------------------------------------------------------------------------------- /Python/word-break-1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Time Complexity: O(n^3) 3 | Space complexity: O(n) 4 | ''' 5 | 6 | # Method 1 : memoization 7 | 8 | class Solution: 9 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 10 | dict=set(wordDict) 11 | dp = {} 12 | def helper(s,dict,dp): 13 | if s in dp: 14 | return dp[s] 15 | l=len(s) 16 | if l==0: 17 | return True 18 | for i in range(l): 19 | if s[:i+1] in dict and helper(s[i+1:],dict,dp): 20 | dp[s[:i+1]] = True 21 | return True 22 | dp[s] = False 23 | return False 24 | return helper(s,dict,dp) 25 | 26 | 27 | # Method 2 : Tabulation 28 | ''' 29 | create an array of n+1 elements 30 | dp[0] represent empty string and it will be True as we can find it. 31 | Here dp[i] represent if s[:i+1] can be found in wordDict or not. 32 | if dp[i] is found then check for remaining characters in s that is s[i:] 33 | our result will be on last index of the dp array. 34 | ''' 35 | 36 | class Solution: 37 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 38 | n = len(s) 39 | word = set(wordDict) 40 | dp = [False]*(n+1) 41 | dp[0] = True 42 | for i in range(len(s)+1): 43 | if dp[i] == True: 44 | for j in range(i+1,len(s)+1): 45 | if s[i:j] in word: 46 | dp[j] = True 47 | return dp[n] 48 | 49 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker 2 | --------------------------------------------------------------------------------