├── _config.yml ├── Week 4 ├── BitwiseANDofNumbersRange.cpp ├── FirstUniqueNumber_queue.cpp ├── JumpGame.cpp ├── LongestCommonSubsequenceBottomUp.cpp ├── MaximalSquare.cpp ├── LongestCommonSubsequenceTopDown.cpp ├── SubarraySumEqualsK.cpp ├── FirstUniqueNumber_DoublyLinkedList.cpp └── LRUCache.cpp ├── Week 1 ├── MoveZeroes.cpp ├── SingleNumber.cpp ├── MaximumSubarray.cpp ├── GroupAnagrams.cpp ├── HappyNumber.cpp ├── BestTimeToBuyAndSellStockII.cpp └── CountingElements.cpp ├── Week 2 ├── ContiguousArray.cpp ├── DiameterOfBinaryTree.cpp ├── LastStoneWeight.cpp ├── MinStack_2StackApproach.cpp ├── MiddleOfTheLinkedList.cpp ├── MinStack_1VectorApproach.cpp ├── BackspaceStringCompare.cpp └── PerformStringShifts.cpp ├── Week 5 ├── BinaryTreeMaximumPathSum.cpp └── CheckIfAStringIsAValidSequenceFromRootToLeavesPathInABinaryTree.cpp ├── Week 3 ├── MinimumPathSum.cpp ├── SearchInRotatedSortedArray.cpp ├── NumberOfIslands.cpp ├── ProductOfArrayExceptSelf.cpp ├── ValidParenthesisString.cpp ├── ConstructBinarySearchTreefromPreorderTraversal.cpp └── LeftmostColumnWithAtLeastAOne.cpp └── README.md /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-merlot -------------------------------------------------------------------------------- /Week 4/BitwiseANDofNumbersRange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 3 | 4 | Example 1: 5 | Input: [5,7] 6 | Output: 4 7 | */ 8 | 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | class Solution { 14 | public: 15 | int rangeBitwiseAnd(int m, int n) { 16 | if(!(m && n) || (int)log2(n)>(int)log2(m)) return 0; 17 | for(int i=m;i count; 4 | queue q; 5 | FirstUnique(vector& nums) { 6 | for(auto value : nums) 7 | add(value); 8 | } 9 | 10 | int showFirstUnique() { 11 | while(!q.empty() && count[q.front()]!=1) 12 | q.pop(); 13 | return q.size()==0?-1:q.front(); 14 | } 15 | 16 | void add(int value) { 17 | q.push(value); 18 | count[value]++; 19 | } 20 | }; 21 | 22 | /** 23 | * Your FirstUnique object will be instantiated and called as such: 24 | * FirstUnique* obj = new FirstUnique(nums); 25 | * int param_1 = obj->showFirstUnique(); 26 | * obj->add(value); 27 | */ -------------------------------------------------------------------------------- /Week 1/MoveZeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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 | Example: 5 | Input: [0,1,0,3,12] 6 | Output: [1,3,12,0,0] 7 | 8 | Note: 9 | 1. You must do this in-place without making a copy of the array. 10 | 2 .Minimize the total number of operations. 11 | */ 12 | 13 | /* 14 | Approach: 15 | 1. Maintain a varible k. 16 | 2. For each non zero element swap with element at index k and increment k. 17 | */ 18 | 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | void moveZeroes(vector& nums) { 26 | int k = 0; 27 | for(int i = 0;i vec = {0,1,0,3,12}; 37 | obj.moveZeroes(vec); 38 | for(auto i : vec) 39 | cout< 26 | #include 27 | using namespace std; 28 | 29 | class Solution { 30 | public: 31 | int singleNumber(vector& nums) { 32 | int sum=0; 33 | for(int i = 0;i vec = {4,1,2,1,2}; 43 | cout< 14 | #include 15 | using namespace std; 16 | 17 | class Solution { 18 | public: 19 | bool canJump(vector& nums) { 20 | //let's call an index 'goodIndex' if the last index is reachable from there. 21 | int goodIndex = nums.size()-1; 22 | for(int i=nums.size()-2;i>=0;i--) 23 | if(nums[i]>=goodIndex - i) //For every index, check if the last goodIndex reachable from there. 24 | goodIndex = i; //If yes, make the current index as the goodIndex 25 | 26 | return (goodIndex>0)?false:true; 27 | } 28 | }; 29 | int main() 30 | { 31 | vector nums = {3,2,1,0,4}; 32 | cout< 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | class Solution{ 23 | public: 24 | int findMaxLength(vector &nums){ 25 | unordered_map sumSoFar; 26 | sumSoFar[0] = -1; 27 | 28 | int Max = 0; 29 | int sum = 0; 30 | for (int i = 0; i < nums.size(); i++){ 31 | sum += nums[i] ? 1 : -1; 32 | if (sumSoFar.count(sum)>0) 33 | Max = max(Max,i - sumSoFar[sum]); 34 | else 35 | sumSoFar[sum] = i; 36 | } 37 | return Max; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | vector value= {0,1,1,0,1,1,1,0,0,0,0}; 44 | cout< 22 | #include 23 | using namespace std; 24 | 25 | class Solution { 26 | public: 27 | 28 | int maxSubArray(vector& nums) { 29 | int Max = -2147483648; 30 | int curr = 0; 31 | for(int i = 0;i vec = {-2,1,-3,4,-1,2,1,-5,4}; 45 | cout< 13 | #include 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | int longestCommonSubsequence(string text1, string text2) { 19 | 20 | int s1 = text1.size(); 21 | int s2 = text2.size(); 22 | 23 | vector> dp(s1 + 1, vector(s2 + 1)); 24 | 25 | for(int i = 1 ;i<=s1;i++){ 26 | for(int j = 1; j<=s2;j++){ 27 | if(text1[i-1]==text2[j-1]) 28 | dp[i][j] = 1+dp[i-1][j-1]; 29 | else 30 | dp[i][j]= max(dp[i-1][j],dp[i][j-1]); 31 | } 32 | } 33 | 34 | return dp[s1][s2]; 35 | } 36 | }; 37 | 38 | 39 | int main() 40 | { 41 | string text1 = "abcde"; 42 | string text2 = "ace"; 43 | cout< 13 | #include 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | 19 | int maximalSquare(vector>& mat) { 20 | 21 | if(mat.empty()) 22 | return 0; 23 | int rows = mat.size(); 24 | int cols = mat[0].size(); 25 | 26 | vector> dp(rows + 1, vector(cols + 1)); 27 | int maxSqSize = 0; 28 | for(int i =1;i<=rows;i++){ 29 | for(int j=1;j<=cols;j++){ 30 | if(mat[i-1][j-1]=='1'){ 31 | dp[i][j]= 1 + min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1])); 32 | maxSqSize = max(maxSqSize,dp[i][j]); 33 | } 34 | } 35 | } 36 | return maxSqSize*maxSqSize; 37 | } 38 | }; 39 | 40 | int main() 41 | { vector> mat = {{'1','0','1','0','0'},{'1','0','1','1','1'},{'1','1','1','1','1'},{'1','0','0','1','0'}}; 42 | cout<left); 39 | int right=mps(root->right); 40 | 41 | int currMaxSum = max(root->val, root->val+max(left,right)); 42 | totalMaxSum = max(totalMaxSum,max(root->val + left + right, currMaxSum)); 43 | return currMaxSum; 44 | } 45 | 46 | int maxPathSum(TreeNode* root) { 47 | mps(root); 48 | return totalMaxSum; 49 | 50 | } 51 | }; -------------------------------------------------------------------------------- /Week 4/LongestCommonSubsequenceTopDown.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings text1 and text2, return the length of their longest common subsequence. 3 | If there is no common subsequence, return 0. 4 | 5 | Example 1: 6 | Input: text1 = "abcde", text2 = "ace" 7 | Output: 3 8 | Explanation: The longest common subsequence is "ace" and its length is 3. 9 | 10 | */ 11 | 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | int lcs(string &text1,string &text2,int idx1,int idx2,vector> &dp){ 19 | 20 | if(idx1==text1.size() || idx2==text2.size()) 21 | return 0; 22 | 23 | if(dp[idx1][idx2]!= 0 ) 24 | return dp[idx1][idx2]; 25 | 26 | if(text1[idx1] == text2[idx2]) 27 | return dp[idx1][idx2] = 1+lcs(text1,text2,idx1+1,idx2+1,dp); 28 | else 29 | return dp[idx1][idx2] = max(lcs(text1,text2,idx1+1,idx2,dp),lcs(text1,text2,idx1,idx2+1,dp)); 30 | 31 | } 32 | int longestCommonSubsequence(string text1, string text2) { 33 | vector> dp(text1.size() + 1, vector(text2.size() + 1)); 34 | return lcs(text1,text2,0,0,dp); 35 | 36 | } 37 | }; 38 | 39 | int main() 40 | { 41 | string text1 = "abcde"; 42 | string text2 = "ace"; 43 | cout< 21 | #include 22 | #include 23 | using namespace std; 24 | 25 | class Solution { 26 | public: 27 | 28 | int subarraySum(vector& nums, int k) { 29 | unordered_map m{{0,1}}; 30 | int count = 0,sum=0; 31 | for(int i = 0;i0) 34 | count+=m[sum-k]; 35 | m[sum]++; 36 | } 37 | return count; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | vector vec = {1,2,4,5,4,1,4,-3,8}; 44 | cout< 19 | #include 20 | #include 21 | #include 22 | using namespace std; 23 | 24 | class Solution { 25 | public: 26 | vector> groupAnagrams(vector& strs) { 27 | unordered_map aMap; 28 | vector> result; 29 | int count = -1; 30 | for (auto str : strs) { 31 | 32 | string temp = str; 33 | sort(temp.begin(), temp.end()); 34 | 35 | if (aMap.count(temp)) 36 | result[aMap[temp]].push_back(str); 37 | 38 | else { 39 | result.push_back({str}); 40 | aMap[temp] = ++count; 41 | } 42 | } 43 | 44 | return result; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Solution obj; 51 | vector vec = {"ate","eat","tea","nat","tan","bat"}; 52 | vector> res; 53 | res = obj.groupAnagrams(vec); 54 | for(auto i : res){ 55 | for(auto j : i) 56 | cout< 24 | #include 25 | #include 26 | #include 27 | using namespace std; 28 | 29 | class Solution { 30 | public: 31 | bool isHappy(int n) { 32 | unordered_map checkRepeat; 33 | int sum = 0; 34 | while(1){ 35 | while(n>0){ 36 | sum+= pow(n%10,2); 37 | n=n/10; 38 | } 39 | if(sum==1) 40 | return true; 41 | if(checkRepeat.count(sum)>0) 42 | return false; 43 | checkRepeat[sum] = 1; 44 | n = sum; 45 | sum = 0; 46 | 47 | } 48 | } 49 | }; 50 | 51 | int main() 52 | { 53 | Solution obj; 54 | cout<left) 49 | leftDepth = 1 + depthOfTree (node->left); 50 | if (node->right) 51 | rightDepth = 1 + depthOfTree (node->right); 52 | if (leftDepth + rightDepth > Diameter) 53 | Diameter = leftDepth + rightDepth; 54 | return max (leftDepth, rightDepth); 55 | 56 | } 57 | int diameterOfBinaryTree (TreeNode * node) 58 | { 59 | Diameter = 0; 60 | return max (Diameter, depthOfTree (node)); 61 | 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Week 5/CheckIfAStringIsAValidSequenceFromRootToLeavesPathInABinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree 3 | https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/532/week-5/3315/ 4 | 5 | Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 6 | We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. 7 | */ 8 | 9 | /** 10 | * Definition for a binary tree node. 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 17 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | 23 | void ivs(TreeNode* root, vector& arr, int idx, bool &res){ 24 | if(idx==arr.size()-1 && arr[idx] == root->val){ 25 | if(!root->left && !root->right) 26 | res=true; 27 | } 28 | 29 | else{ 30 | if(root->val == arr[idx]){ 31 | if(root->left) 32 | ivs(root->left,arr,idx+1,res); 33 | if(root->right) 34 | ivs(root->right,arr,idx+1,res); 35 | } 36 | } 37 | } 38 | bool isValidSequence(TreeNode* root, vector& arr) { 39 | bool res = false; 40 | ivs(root,arr,0,res); 41 | return res; 42 | } 43 | }; -------------------------------------------------------------------------------- /Week 1/BestTimeToBuyAndSellStockII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array prices for which the ith element is the price of a given stock on day i. 3 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 4 | Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 5 | 6 | Example 1: 7 | Input: [7,1,5,3,6,4] 8 | Output: 7 9 | Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 10 | Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 11 | 12 | Example 2: 13 | Input: [1,2,3,4,5] 14 | Output: 4 15 | Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 16 | Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 17 | engaging multiple transactions at the same time. You must sell before buying again. 18 | 19 | Example 3: 20 | Input: [7,6,4,3,1] 21 | Output: 0 22 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 23 | 24 | Constraints: 25 | -> 1 <= prices.length <= 3 * 10 ^ 4 26 | -> 0 <= prices[i] <= 10 ^ 4 27 | */ 28 | 29 | #include 30 | #include 31 | using namespace std; 32 | 33 | class Solution { 34 | public: 35 | int maxProfit(vector& prices) { 36 | int maxProfit = 0; 37 | for(int i = 1;iprices[i-1]) 39 | maxProfit+=prices[i]-prices[i-1]; 40 | return maxProfit; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | Solution obj; 47 | vector vec = {7,1,5,3,6,4}; 48 | cout< 42 | #include 43 | #include 44 | #include 45 | using namespace std; 46 | 47 | class Solution { 48 | public: 49 | int countElements(vector& arr) { 50 | unordered_map m; 51 | for(auto i : arr) 52 | m[i]++; 53 | int count =0; 54 | for(auto i : arr) 55 | if(m.count(i+1) > 0) 56 | count++; 57 | 58 | return count; 59 | } 60 | }; 61 | 62 | int main() 63 | { 64 | Solution obj; 65 | vector vec = {1,1,3,3,5,5,7,7}; 66 | cout< 33 | #include 34 | 35 | using namespace std; 36 | 37 | class Solution { 38 | public: 39 | int minPathSum(vector>& grid) { 40 | int rows = grid.size(); 41 | int columns = grid[0].size(); 42 | for(int i = 0;i> vec = {{1,3,1},{1,5,1},{4,2,1}}; 64 | cout< 36 | #include 37 | #include 38 | using namespace std; 39 | 40 | class Solution { 41 | public: 42 | int lastStoneWeight(vector& stones) { 43 | priority_queue> pq; 44 | for(auto i : stones){ 45 | pq.push(i); 46 | } 47 | while(pq.size()!=1){ 48 | int x = pq.top(); 49 | pq.pop(); 50 | int y = pq.top(); 51 | pq.pop(); 52 | if(x!=y) 53 | pq.push(abs(x-y)); 54 | else 55 | pq.push(0); 56 | } 57 | 58 | return pq.top(); 59 | } 60 | }; 61 | 62 | int main() 63 | { 64 | vector value= {2,7,4,1,8,1}; 65 | cout< 25 | #include 26 | using namespace std; 27 | 28 | class Solution { 29 | public: 30 | int search(vector& nums, int target) { 31 | if(nums.size() == 0) 32 | return -1; 33 | int start = 0; 34 | int end = nums.size()-1; 35 | while(start=nums[start] && target < nums[mid]) 41 | end = mid-1; 42 | else 43 | start = mid+1; 44 | else 45 | if(target>nums[mid] && target<=nums[end]) 46 | start=mid+1; 47 | else 48 | end = mid-1; 49 | } 50 | if(nums[start]==target) 51 | return start; 52 | else 53 | return -1; 54 | } 55 | }; 56 | 57 | int main () 58 | { 59 | 60 | vector vec = {4,5,6,7,0,1,2}; 61 | cout< 26 | #include 27 | using namespace std; 28 | 29 | class Solution { 30 | public: 31 | 32 | void dfs(int i,int j, int m, int n, vector>& grid){ 33 | 34 | grid[i][j] = '*'; 35 | if(i+1=0 && grid[i-1][j]=='1') 38 | dfs(i-1,j,m,n,grid); 39 | if(j+1=0 && grid[i][j-1]=='1') 42 | dfs(i,j-1,m,n,grid); 43 | 44 | 45 | } 46 | 47 | int numIslands(vector>& grid) { 48 | 49 | int rows = grid.size(); 50 | if(rows==0) 51 | return 0; 52 | int cols = grid[0].size(); 53 | if(cols==0) 54 | return 0; 55 | int count = 0; 56 | for(int i=0;i> vec= {{'1','1','1','1','0'},{'1','1','0','1','0'},{'1','1','0','0','0'},{'0','0','0','0','0'}}; 73 | cout< 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | Input: [1,2,3,4] 6 | Output: [24,12,8,6] 7 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 8 | 9 | Note: Please solve it without division and in O(n). 10 | 11 | Follow up: 12 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 13 | 14 | */ 15 | 16 | /* 17 | 18 | Approach: 19 | 1. The idea is to find the product of all the elements on the left of an element i and multiply it with the product of all the elements on the right of that element. 20 | 2. Take an array (same as the size of the original array but initialized with 1) (finalSol here). Take two variables (start and end) to maintain left product and right product for each element i. 21 | 3. Loop the array and start populating array to get left product and right product simulataneously. 22 | 4. For an element i, left product -> (finalSol[i] = finalSol[i] * start) and right product -> (finalSol[i] = finalSol[i] * end). 23 | 5. Keep updating start and end by multiplying them with the current element. 24 | 6. return the finalSol array. 25 | 26 | */ 27 | 28 | #include 29 | #include 30 | using namespace std; 31 | 32 | class Solution { 33 | public: 34 | vector productExceptSelf(vector& nums) { 35 | 36 | int size = nums.size(); 37 | vector finalSol(size,1); 38 | int end =1; 39 | int start =1; 40 | 41 | for(int i=0; i nums = {1,2,3,4}; 56 | vector res; 57 | res=Solution().productExceptSelf(nums); 58 | for(auto i : res) 59 | cout< Returns -3. 15 | minStack.pop(); 16 | minStack.top(); --> Returns 0. 17 | minStack.getMin(); --> Returns -2. 18 | 19 | */ 20 | 21 | /* 22 | Approach: 23 | 1. Maintain 2 stacks. 24 | 2. Push every incoming element on stack 1. Push current minimum elemnt on stack 2 25 | 3. Pop/return elements accordingly. For every pop, check if you are popping the minimum element from stack 1. If yes, pop from stack 2 as wel.. 26 | */ 27 | 28 | 29 | #include 30 | #include 31 | #include 32 | using namespace std; 33 | 34 | class MinStack { 35 | public: 36 | 37 | stack minStack; 38 | stack s; 39 | MinStack() {} 40 | 41 | void push(int x) { 42 | if (minStack.empty() || x <= minStack.top()) 43 | minStack.push(x); 44 | s.push(x); 45 | } 46 | 47 | void pop() { 48 | if (s.top() == minStack.top()) 49 | minStack.pop(); 50 | s.pop(); 51 | } 52 | 53 | int top() { 54 | return s.top(); 55 | } 56 | 57 | int getMin() { 58 | return minStack.top(); 59 | } 60 | }; 61 | 62 | int main() 63 | { 64 | MinStack* obj = new MinStack(); 65 | vector command = {"push","push","push","getMin","top","pop","getMin"}; 66 | vector > value= {{-2},{0},{-1},{},{},{},{}}; 67 | vector res; 68 | 69 | for(int i = 0;ipush(value[i][0]); 72 | else if(command[i] == "pop") 73 | obj->pop(); 74 | else if(command[i] == "getMin") 75 | res.push_back(obj->getMin()); 76 | else 77 | res.push_back(obj->top()); 78 | } 79 | 80 | 81 | for(auto i : res) 82 | cout< 30 | #include 31 | using namespace std; 32 | 33 | 34 | //Definition for singly-linked list. 35 | struct ListNode { 36 | int val; 37 | ListNode *next; 38 | ListNode(int x) : val(x), next(NULL) {} 39 | }; 40 | 41 | class Solution { 42 | public: 43 | ListNode* middleNode(ListNode* head) { 44 | if(!head || !head->next) 45 | return head; 46 | ListNode * fast = head; 47 | ListNode * slow = head; 48 | 49 | while(fast && fast->next){ 50 | fast=fast->next->next; 51 | slow=slow->next; 52 | } 53 | 54 | return slow; 55 | } 56 | }; 57 | 58 | ListNode* vectorToLinkedList(vector vec) //copying array elements and create linked list 59 | { 60 | ListNode *temp = new ListNode(vec[0]); 61 | ListNode *head = temp; 62 | for(int i=1;inext= temp2; 66 | temp=temp2; 67 | } 68 | return head; 69 | } 70 | 71 | int main() 72 | { 73 | Solution obj; 74 | vector vec = {1,2,3,4,5,6}; 75 | ListNode* head = vectorToLinkedList(vec); 76 | cout<val; 77 | return 0; 78 | } -------------------------------------------------------------------------------- /Week 3/ValidParenthesisString.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 4 | 5 | Any left parenthesis '(' must have a corresponding right parenthesis ')'. 6 | Any right parenthesis ')' must have a corresponding left parenthesis '('. 7 | Left parenthesis '(' must go before the corresponding right parenthesis ')'. 8 | '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 9 | An empty string is also valid. 10 | 11 | Example 1: 12 | Input: "()" 13 | Output: True 14 | 15 | Example 2: 16 | Input: "(*)" 17 | Output: True 18 | 19 | Example 3: 20 | Input: "(*))" 21 | Output: True 22 | 23 | */ 24 | 25 | /* 26 | Approach: 27 | 28 | 1. Let maxOpenB be the maximum number of open brackets 29 | 2. Let minOpenB be the minimum number of open brackets 30 | 3. When we encounter: 31 | - '(' : increment minOpenB and maxOpenB 32 | - ')' : decrement minOpenB and maxOpenB 33 | - '*' : increment maxOpenB and decrement minOpenB ('*' can be a open bracket or close bracket) 34 | 4. Keep checking if maxOpenB is less than 0. If yes, return 0 (This means count of close bracket are more than open bracket and '*' in the current sequence) 35 | 5. Also, minOpenB should froced to 0 as the number of open bracket cannot be less than 0 36 | 6. return true if minOpenB is 0 or else return false. 37 | 38 | */ 39 | 40 | 41 | #include 42 | using namespace std; 43 | 44 | class Solution { 45 | public: 46 | bool checkValidString(string s) { 47 | 48 | int maxOpenB = 0; 49 | int minOpenB = 0; 50 | for(auto c : s){ 51 | if(c == '('){ 52 | maxOpenB++; 53 | minOpenB++; 54 | } 55 | else if(c == ')'){ 56 | maxOpenB--; 57 | minOpenB--; 58 | } 59 | else{ 60 | maxOpenB++; 61 | minOpenB--; 62 | } 63 | if(maxOpenB<0) 64 | return false; 65 | minOpenB = max(0,minOpenB); 66 | 67 | } 68 | 69 | if(minOpenB == 0) 70 | return true; 71 | return false; 72 | } 73 | }; 74 | 75 | 76 | int main() 77 | { 78 | cout< nodeVal; 13 | unordered_map nodeAdd; 14 | 15 | 16 | FirstUnique(vector& nums) { 17 | for(auto i:nums) 18 | add(i); 19 | } 20 | 21 | int showFirstUnique() { 22 | 23 | if(head) 24 | return head->val; 25 | return -1; 26 | } 27 | 28 | void add(int value) { 29 | if(nodeVal[value]==0){ 30 | 31 | ListNode * temp = new ListNode(value); 32 | nodeAdd[value] = temp; 33 | if(!head && !tail){ 34 | 35 | head = temp; 36 | tail = temp; 37 | } 38 | else{ 39 | tail->next = temp; 40 | temp->prev = tail; 41 | tail = temp; 42 | } 43 | 44 | } 45 | 46 | else if(nodeAdd[value]){ 47 | if(nodeAdd[value]==tail){ 48 | if(!tail->prev){ 49 | head=NULL; 50 | tail=NULL; 51 | } 52 | else{ 53 | tail=tail->prev; 54 | tail->next=NULL; 55 | } 56 | } 57 | else if(nodeAdd[value]==head){ 58 | if(!head->next){ 59 | head=NULL; 60 | tail=NULL; 61 | } 62 | else{ 63 | head=head->next; 64 | head->prev=NULL; 65 | } 66 | } 67 | else{ 68 | ListNode * temp = nodeAdd[value]; 69 | temp->prev->next=temp->next; 70 | temp->next->prev=temp->prev; 71 | temp=temp->next; 72 | } 73 | 74 | nodeAdd[value]=NULL; 75 | } 76 | nodeVal[value]++; 77 | } 78 | }; 79 | 80 | /** 81 | * Your FirstUnique object will be instantiated and called as such: 82 | * FirstUnique* obj = new FirstUnique(nums); 83 | * int param_1 = obj->showFirstUnique(); 84 | * obj->add(value); 85 | */ -------------------------------------------------------------------------------- /Week 2/MinStack_1VectorApproach.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | 4 | push(x) -- Push element x onto stack. 5 | pop() -- Removes the element on top of the stack. 6 | top() -- Get the top element. 7 | getMin() -- Retrieve the minimum element in the stack. 8 | 9 | Example: 10 | MinStack minStack = new MinStack(); 11 | minStack.push(-2); 12 | minStack.push(0); 13 | minStack.push(-3); 14 | minStack.getMin(); --> Returns -3. 15 | minStack.pop(); 16 | minStack.top(); --> Returns 0. 17 | minStack.getMin(); --> Returns -2. 18 | 19 | */ 20 | 21 | /* 22 | 23 | Approach: 24 | 1. Maintain 1 vector. 25 | 2. Push every incoming element on even indexes. Push current minimum elemnt on odd indexes 26 | 3. Pop/return elements accordingly 27 | */ 28 | 29 | 30 | #include 31 | #include 32 | #include 33 | using namespace std; 34 | 35 | class MinStack { 36 | public: 37 | /** initialize your data structure here. */ 38 | 39 | vector Stack; 40 | int sizeOfStack; 41 | 42 | MinStack() { 43 | sizeOfStack=0; 44 | } 45 | 46 | void push(int x) { 47 | if(sizeOfStack==0){ 48 | Stack.push_back(x); 49 | Stack.push_back(x); 50 | } 51 | else{ 52 | Stack.push_back(x); 53 | Stack.push_back(min(x,Stack[sizeOfStack-1])); 54 | } 55 | sizeOfStack+=2; 56 | } 57 | 58 | void pop() { 59 | Stack.pop_back(); 60 | Stack.pop_back(); 61 | sizeOfStack-=2; 62 | } 63 | 64 | int top() { 65 | return Stack[sizeOfStack-2]; 66 | } 67 | 68 | int getMin() { 69 | return Stack[sizeOfStack-1]; 70 | } 71 | }; 72 | 73 | int main() 74 | { 75 | MinStack* obj = new MinStack(); 76 | vector command = {"push","push","push","getMin","top","pop","getMin"}; 77 | vector > value= {{-2},{0},{-1},{},{},{},{}}; 78 | vector res; 79 | 80 | for(int i = 0;ipush(value[i][0]); 83 | else if(command[i] == "pop") 84 | obj->pop(); 85 | else if(command[i] == "getMin") 86 | res.push_back(obj->getMin()); 87 | else 88 | res.push_back(obj->top()); 89 | } 90 | 91 | 92 | for(auto i : res) 93 | cout< node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 5 | 6 | Example 1: 7 | 8 | Input: [8,5,1,7,10,12] 9 | Output: [8,5,10,1,7,null,12] 10 | 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | using namespace std; 17 | 18 | 19 | struct TreeNode { 20 | int val; 21 | TreeNode *left; 22 | TreeNode *right; 23 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 24 | }; 25 | 26 | class Solution { 27 | public: 28 | int index = 0; 29 | TreeNode *const_bst(vector& preorder,int parent_value){ 30 | 31 | int curr_val = preorder[index]; 32 | TreeNode* temp = new TreeNode(curr_val); 33 | 34 | if( index+1 < preorder.size() && preorder[index+1]left = const_bst(preorder,curr_val); 37 | } 38 | 39 | if( index+1 < preorder.size() && preorder[index+1]right = const_bst(preorder,parent_value); 42 | } 43 | 44 | return temp; 45 | } 46 | 47 | TreeNode* bstFromPreorder(vector& preorder) { 48 | 49 | return const_bst(preorder,2147483647); //passing INT_MAX 50 | 51 | } 52 | }; 53 | 54 | //utility function to print tree in level order traversal 55 | string treeNodeToString(TreeNode* root) { 56 | if (root == nullptr) { 57 | return "[]"; 58 | } 59 | 60 | string output = ""; 61 | queue q; 62 | q.push(root); 63 | while(!q.empty()) { 64 | TreeNode* node = q.front(); 65 | q.pop(); 66 | 67 | if (node == nullptr) { 68 | output += "null, "; 69 | continue; 70 | } 71 | 72 | output += to_string(node->val) + ", "; 73 | q.push(node->left); 74 | q.push(node->right); 75 | } 76 | return "[" + output.substr(0, output.length() - 2) + "]"; 77 | } 78 | 79 | int main() 80 | { 81 | vector vec = {8,5,1,7,10,12}; 82 | TreeNode * root = Solution().bstFromPreorder(vec); 83 | cout< 0. If yes, skip that character and decrement skip, else add it to the final vector. 36 | 3. Loop strin T in reverse, follow step 2 but for every character that doesn't get skipped, instead of pushing it into a vector, simply compare it to its corresponding character in the final vector for String S. If the condition satisfies, continue else, return false 37 | 4. Return true at the end if all the comparison in step 3 pass 38 | 39 | 40 | */ 41 | 42 | #include 43 | #include 44 | using namespace std; 45 | 46 | class Solution { 47 | public: 48 | bool backspaceCompare(string S, string T) { 49 | vector res; 50 | int skip = 0; 51 | int resSize = 0; 52 | int k = 0; 53 | for(int i=S.size()-1;i>-1;i--){ 54 | if(S[i]=='#') 55 | skip++; 56 | else if(skip>0) 57 | skip--; 58 | else{ 59 | resSize++; 60 | res.push_back(S[i]); 61 | } 62 | } 63 | 64 | skip = 0; 65 | for(int i=T.size()-1;i>-1;i--){ 66 | if(T[i]=='#') 67 | skip++; 68 | else if(skip>0) 69 | skip--; 70 | else{ 71 | if(k dimensions(); 52 | * }; 53 | */ 54 | 55 | class Solution { 56 | public: 57 | int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { 58 | vector dim = binaryMatrix.dimensions(); 59 | int min_col = INT_MAX; 60 | for(int i=0;i=0 && binaryMatrix.get(i, mid-1)==0){ 67 | min_col = min(min_col,mid); 68 | break; 69 | } 70 | else 71 | end = mid-1; 72 | else 73 | start=mid+1; 74 | } 75 | 76 | if(binaryMatrix.get(i, start)==1) min_col = min(min_col,start); 77 | if(min_col == 0) return min_col; 78 | } 79 | 80 | return (min_col==INT_MAX)?-1:min_col; 81 | 82 | } 83 | }; -------------------------------------------------------------------------------- /Week 4/LRUCache.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. 3 | 4 | get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 5 | put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. 6 | The cache is initialized with a positive capacity. 7 | Follow up: 8 | Could you do both operations in O(1) time complexity? 9 | 10 | 11 | */ 12 | 13 | /* 14 | 1. Store the value of each key in a map. 15 | 2. Take a linked list to maintain an order of keys. 16 | 3. Maintain two pointers to add and delete from either side of linkedlist 17 | 4. Take another map to store the address of each node in the linked for deleting any middle node. 18 | 19 | */ 20 | 21 | class LRUCache { 22 | public: 23 | class ll{ 24 | public: 25 | int key; 26 | ll* next; 27 | ll(int data){key = data; next=NULL;} 28 | }; 29 | 30 | int cap; 31 | unordered_map cache; 32 | unordered_map ll_add; 33 | ll* head=NULL; 34 | ll* tail=NULL; 35 | int sizeSoFar=0; 36 | 37 | void push_back_ll(int key){ 38 | ll* temp = new ll(key); 39 | if(tail && tail->key == key){ 40 | ll_add[key]=tail; 41 | sizeSoFar++; 42 | return; 43 | } 44 | else if(head==NULL && tail ==NULL){ 45 | head=temp; 46 | tail=temp; 47 | } 48 | else if(!head) 49 | head=tail; 50 | else{ 51 | tail->next = temp; 52 | tail=temp; 53 | } 54 | ll_add[key]=temp; 55 | sizeSoFar++; 56 | } 57 | void pop_front_ll(){ 58 | 59 | head=head->next; 60 | sizeSoFar--; 61 | } 62 | 63 | void remove_ll(int key){ 64 | 65 | ll * temp = ll_add[key]; 66 | if(temp->next == tail) 67 | tail=temp; 68 | if(temp->next!=NULL){ 69 | temp->key = temp->next->key; 70 | ll_add[temp->next->key] = temp; 71 | temp->next = temp->next->next; 72 | } 73 | 74 | ll_add[key]=NULL; 75 | sizeSoFar--; 76 | } 77 | 78 | LRUCache(int capacity) { 79 | 80 | cap=capacity; 81 | } 82 | 83 | int get(int key) { 84 | 85 | if(cache[key]==0) 86 | return -1; 87 | remove_ll(key); 88 | push_back_ll(key); 89 | return cache[key]; 90 | } 91 | 92 | void put(int key, int value) { 93 | 94 | if(cache[key]==0){ 95 | if(sizeSoFar==cap){ 96 | int temp = head->key; 97 | pop_front_ll(); 98 | cache[temp]=0; 99 | } 100 | } 101 | else 102 | remove_ll(key); 103 | 104 | push_back_ll(key); 105 | cache[key]=value; 106 | } 107 | }; 108 | 109 | /** 110 | * Your LRUCache object will be instantiated and called as such: 111 | * LRUCache* obj = new LRUCache(capacity); 112 | * int param_1 = obj->get(key); 113 | * obj->put(key,value); 114 | */ -------------------------------------------------------------------------------- /Week 2/PerformStringShifts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | ***LEETCODE URL: https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3299/**** 4 | 5 | 6 | You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: 7 | 8 | direction can be 0 (for left shift) or 1 (for right shift). 9 | amount is the amount by which string s is to be shifted. 10 | A left shift by 1 means remove the first character of s and append it to the end. 11 | Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. 12 | Return the final string after all operations. 13 | 14 | Example 1: 15 | Input: s = "abc", shift = [[0,1],[1,2]] 16 | Output: "cab" 17 | Explanation: 18 | [0,1] means shift to left by 1. "abc" -> "bca" 19 | [1,2] means shift to right by 2. "bca" -> "cab" 20 | 21 | Example 2: 22 | Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] 23 | Output: "efgabcd" 24 | Explanation: 25 | [1,1] means shift to right by 1. "abcdefg" -> "gabcdef" 26 | [1,1] means shift to right by 1. "gabcdef" -> "fgabcde" 27 | [0,2] means shift to left by 2. "fgabcde" -> "abcdefg" 28 | [1,3] means shift to right by 3. "abcdefg" -> "efgabcd" 29 | 30 | Constraints: 31 | 1 <= s.length <= 100 32 | s only contains lower case English letters. 33 | 1 <= shift.length <= 100 34 | shift[i].length == 2 35 | 0 <= shift[i][0] <= 1 36 | 0 <= shift[i][1] <= 100 37 | 38 | */ 39 | 40 | /* 41 | Approach: 42 | 1. Loop through the shift vector. 43 | 2. Take a variable to maintain total shifts (here 'totalShift'). 44 | 3. For each left shift, decrement totalShift by the the number of left shifts. For each right shift, increment the variable similarly. 45 | 4. Also, don't forget to mod totalShift by the size of the string (totalShift % SizeOfString). It helps in avoiding redundant shifts. 46 | 5. If totalShift is less than 0, then left shift the entire string by abs(totalShift) times. Else, right shift the string by abs(totalShift) times. 47 | 6. Instead of actually looping through the string and shifting the characters, find the final index for each index after shifting and simply place the character at that index in a temporary string (here 'finalS'). 48 | 7. return finalS. 49 | 50 | */ 51 | 52 | 53 | #include 54 | #include 55 | using namespace std; 56 | 57 | class Solution { 58 | public: 59 | 60 | string leftShift(string s, int n){ 61 | 62 | string finalS = s; 63 | int size = s.size(); 64 | n=n%size; 65 | for(int i =0;i= n) 68 | k = i-n; 69 | else 70 | k = size-(n-i); 71 | finalS[k] = s[i]; 72 | } 73 | 74 | return finalS; 75 | 76 | 77 | } 78 | string rightShift(string s,int n){ 79 | 80 | string finalS = s; 81 | int size = s.size(); 82 | n=n%size; 83 | for(int i =0;isize-1) 86 | k = (i+n)-(size) ; 87 | else 88 | k=i+n; 89 | finalS[k] = s[i]; 90 | } 91 | 92 | return finalS; 93 | 94 | 95 | } 96 | string stringShift(string s, vector>& shift) { 97 | 98 | int totalShift = 0; 99 | for(auto i : shift) 100 | if(i[0]==0) 101 | totalShift-=i[1]; 102 | else 103 | totalShift+=i[1]; 104 | 105 | if(totalShift<0) 106 | return leftShift(s,abs(totalShift)); 107 | return rightShift(s,abs(totalShift)); 108 | 109 | } 110 | }; 111 | 112 | 113 | int main() 114 | { 115 | vector> vec = {{1,1},{1,1},{0,2},{1,3}}; 116 | string s = "abcdefg"; 117 | cout<