├── .github ├── ISSUE_TEMPLATE │ ├── custom.md │ ├── improvements.md │ └── new_challenge_issue.md └── Pull-Request_Template.md ├── Biweekly 81 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Biweekly 82 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Biweekly Contest 80 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Biweekly Contest 83 ├── BestPokerHand.cpp ├── DesignNumberContainerSystem.cpp ├── NumberZero-FilledSubarrays.cpp ├── README.md └── ShortestImpossibleSequenceRolls.cpp ├── Contributing.md ├── README.md ├── Weekly Contest 297 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Weekly Contest 298 ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Weekly Contest 304 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Weekly Contest 305 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp ├── Weekly Contest 308 ├── README.md ├── question1.cpp ├── question2.cpp ├── question3.cpp └── question4.cpp └── Weekly Contest 321 ├── Append Characters to String to Make Subsequence.cpp ├── Count Subarrays With Median K.cpp ├── Pivot Integer.cpp ├── README.md └── Remove Nodes From Linked List.cpp /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "Custom issue template" 3 | about: "Describe the issue template's purpose here" 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/improvements.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Improve a file 3 | about: You can improve an already existing file 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Description of the change 11 | Describe more about the change. 12 | 13 | 14 | #### Are you contributing under any open-source program ? 15 | 16 |
17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/new_challenge_issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Add a New Issue 3 | about: LeetCode-Contests 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Title 11 | (Write issue title over here) 12 | 13 | ### Description 14 | (Describe the issue over here) 15 | 16 | #### Are you contributing under any open-source program ? 17 | 18 |
19 | -------------------------------------------------------------------------------- /.github/Pull-Request_Template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 🛠️ Fixes Issue 4 | 5 | Closes # 6 | 7 | 8 | 9 | ## 👨‍💻 Changes proposed 10 | 11 | 12 | 13 | 14 | ## ✔️ Check List (Check all the applicable boxes) 15 | 16 | 17 | 21 | 22 | - [] My code follows the code style of this project. 23 | - [] The title of my pull request is a short description of the requested changes. 24 | - [] I'm HSOC'22 Contributor 25 | - [] I have Starred this repo. 26 | 27 | 28 | ## 📄 Note to reviewers 29 | 30 | 31 | 32 | 33 | ## 📷 Output Screenshots (Recommended) 34 | -------------------------------------------------------------------------------- /Biweekly 81/README.md: -------------------------------------------------------------------------------- 1 | |PROBLEMS|IMPORTANT| 2 | |--------|---------| 3 | |[Count Asterisks](https://leetcode.com/contest/biweekly-contest-81/problems/count-asterisks/)| 4 | |[Count Unreachable Pairs of Nodes in an Undirected Graph](https://leetcode.com/contest/biweekly-contest-81/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/)|💡| 5 | |[Maximum XOR After Operations](https://leetcode.com/contest/biweekly-contest-81/problems/maximum-xor-after-operations/)|💡| 6 | |[Number of Distinct Roll Sequences](https://leetcode.com/contest/biweekly-contest-81/problems/number-of-distinct-roll-sequences/)|💡| 7 | 8 | -------------------------------------------------------------------------------- /Biweekly 81/question1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth. 3 | 4 | Return the number of '*' in s, excluding the '*' between each pair of '|'. 5 | 6 | Note that each '|' will belong to exactly one pair. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "l|*e*et|c**o|*de|" 13 | Output: 2 14 | Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|". 15 | The characters between the first and second '|' are excluded from the answer. 16 | Also, the characters between the third and fourth '|' are excluded from the answer. 17 | There are 2 asterisks considered. Therefore, we return 2. 18 | Example 2: 19 | 20 | Input: s = "iamprogrammer" 21 | Output: 0 22 | Explanation: In this example, there are no asterisks in s. Therefore, we return 0. 23 | Example 3: 24 | 25 | Input: s = "yo|uar|e**|b|e***au|tifu|l" 26 | Output: 5 27 | Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5. 28 | 29 | 30 | Constraints: 31 | 32 | 1 <= s.length <= 1000 33 | s consists of lowercase English letters, vertical bars '|', and asterisks '*'. 34 | s contains an even number of vertical bars '|' 35 | 36 | **/ 37 | 38 | 39 | 40 | // Time Complexity is O(N) 41 | // Space Complexity is O(N) 42 | 43 | 44 | 45 | 46 | 47 | // Here is the Solution: 48 | 49 | class Solution 50 | { 51 | public: 52 | int countAsterisks(string s) 53 | { 54 | 55 | int countstar=0; int Vbar=0; 56 | 57 | for(int i=0;i rank[py]) and in that case, we will: 36 | reparent py to point to px as his parent; 37 | add rank[py] to rank[px]; 38 | otherwise: 39 | reparent px to point to py as his parent; 40 | add rank[px] to `rank[py]. 41 | The extra helper method findConnectes will take a node and return us the rank of its parent (found recursively through parent(node), as usual). 42 | 43 | In our main function, we will instatiate a new UF object in uf, with capacity n and then populate it with every single edge in edges, calling union on each pair of points connected (edge[0] and edge[1]). 44 | 45 | We have now a fully formed and clustered graph, so we will go through each node i from 0 to n (excluded) and: 46 | 47 | compute how big is its cluster with uf.findConnected(i); 48 | increase res by n - that number (since if we have overall n nodes and we know this cluster is made of uf.findConnected(i), then we can infer that all the others are not connected to i). 49 | Notice that this way we would count each missing edge twice (ie: [0, 5] and [5, 0] will be both counted), so we ultimately have to return half the value of res (ie: res / 2 or, why not, res >> 1). 50 | 51 | **/ 52 | 53 | // Time Complexity: O(N) 54 | // Space Complexity: O(N) 55 | 56 | 57 | 58 | class UF 59 | { 60 | // support variables 61 | int *parent, *rank; 62 | public: 63 | UF(int n) 64 | { 65 | // preparing parent and rank 66 | parent = new int[n]; 67 | iota(parent, parent + n, 0); 68 | rank = new int[n]; 69 | fill(rank, rank + n, 1); 70 | } 71 | int find(int node) 72 | { 73 | if (parent[node] != node) { 74 | parent[node] = find(parent[node]); 75 | } 76 | return parent[node]; 77 | } 78 | void unite(int x, int y) 79 | { 80 | int px = find(x), py = find(y); 81 | // already united 82 | if (px == py) return; 83 | // attaching elements to the biggest cluster 84 | if (rank[px] > rank[py]) { 85 | parent[py] = px; 86 | rank[px] += rank[py]; 87 | } 88 | else 89 | { 90 | parent[px] = py; 91 | rank[py] += rank[px]; 92 | } 93 | } 94 | int findConnected(int node) 95 | { 96 | return rank[find(node)]; 97 | } 98 | }; 99 | 100 | class Solution 101 | { 102 | public: 103 | long long countPairs(int n, vector>& edges) 104 | { 105 | // support variables 106 | UF uf = UF(n); 107 | long long res = 0; 108 | // populating uf 109 | for (auto &edge: edges) 110 | { 111 | uf.unite(edge[0], edge[1]); 112 | } 113 | // computing res 114 | for (int i = 0; i < n; i++) 115 | { 116 | res += n - uf.findConnected(i); 117 | } 118 | return res >> 1; 119 | } 120 | }; 121 | -------------------------------------------------------------------------------- /Biweekly 81/question3.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | 2317. Maximum XOR After Operations 3 | 4 | You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). 5 | 6 | Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. 7 | 8 | Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [3,2,4,6] 15 | Output: 7 16 | Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. 17 | Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. 18 | It can be shown that 7 is the maximum possible bitwise XOR. 19 | Note that other operations may be used to achieve a bitwise XOR of 7. 20 | Example 2: 21 | 22 | Input: nums = [1,2,3,9,2] 23 | Output: 11 24 | Explanation: Apply the operation zero times. 25 | The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. 26 | It can be shown that 11 is the maximum possible bitwise XOR. 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= nums.length <= 105 32 | 0 <= nums[i] <= 108 33 | **/ 34 | 35 | /** 36 | Approach: 37 | * nums[i] AND (nums[i] XOR x) 38 | * with the above operation we can modify any nums[i] right 39 | * as we are taking AND, we can say that none of the bits of nums[i] can be converted from 0 to 1 40 | on the other hand, we can convert a bit from 1 to 0 41 | as we can choose x such that nums[i]^x = 0 at that ith bit then its & with nums[i] will result in 0 42 | 1&0 = 0 43 | * now to maximize the final answer we want as many 1 as possible in the final value 44 | * So, if there exist atleast a single bit at ith position whose value is 1, we can have a combination of other bits to give XOR =1 for that bit 45 | how? 46 | * we can make all the other elements ith bit = 0 then the xor of all the elements at this ith bit will be 47 | * 1^0^0...^0 = 1 48 | * So, in conclusion if the ith bit of any element is 1 then the ith bit of our final answer will be 1 too and if all the elements has their ith bit =0 then the ith bit of our answer will be 0 49 | * you can clearly guess from the above statement that we just want the OR of all the elements 50 | **/ 51 | 52 | // Time Complexity: O(N) 53 | // Space Complexity: O(N) it mainly depends on the size of input and size of vector. 54 | class Solution 55 | { 56 | public: 57 | int maximumXOR(vector &nums) 58 | { 59 | int n = nums.size(); 60 | int ans = 0; 61 | for (int i = 0; i < n; i++) 62 | ans |= nums[i]; 63 | return ans; 64 | } 65 | }; -------------------------------------------------------------------------------- /Biweekly 81/question4.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Number of Distinct Roll Sequences 4 | 5 | You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: 6 | 7 | The greatest common divisor of any adjacent values in the sequence is equal to 1. 8 | There is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2. 9 | Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7. 10 | 11 | Two sequences are considered distinct if at least one element is different. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: n = 4 18 | Output: 184 19 | Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc. 20 | Some invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6). 21 | (1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed). 22 | (1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3. 23 | There are a total of 184 distinct sequences possible, so we return 184. 24 | Example 2: 25 | 26 | Input: n = 2 27 | Output: 22 28 | Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2). 29 | Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1. 30 | There are a total of 22 distinct sequences possible, so we return 22. 31 | 32 | 33 | Constraints: 34 | 35 | 1 <= n <= 10^4 36 | **/ 37 | 38 | /** 39 | Approach: 40 | 41 | Now, what we see ,that we have choices for every indices:- 42 | -->But we follow rules to fillis according to choices. 43 | -->And when we will fill all indices then we will get one choice. 44 | 45 | **⚫ Algorithm and steps:- ** 46 | 47 | -->Initillay We will create a 2d vector size 7. 48 | -->Ignoring 0'th index. 49 | -->All other i'th index vector will hold the list of all the numbers which will have gcd 1 with i. 50 | 51 | -->We have all 6 choices to fix at index 0. 52 | -->We will call a solve function:- 53 | -->Solve function have three dp state variable : 54 | 1.) idx:-Aindex on which we will put some choices from 1 to 6. 55 | 2.) Val:- value we have putted at index idx-1. 56 | 3.) PreVal:- value we have putted at index idx-2; 57 | 58 | -->Base condition of solve:- if idx hit n then return 1. 59 | -->Other wise for index idx we will Put values which are eligible for putting next of Val i.e thier gcd be 1 and it must not eual to PreVal. 60 | 61 | -->Add all choices in ans1 and return it . 62 | 63 | --> **Time Complexity:- ** O(6n); 64 | --> **Sapce Complexity :- ** O(77n); 65 | 66 | **/ 67 | 68 | 69 | // Here is the solution: 70 | #define mod 1000000007 71 | class Solution 72 | { 73 | public: 74 | int dp[10001][7][7]; 75 | int solve(int PreVal,int Val,int idx,int &n,vector>&v) 76 | { 77 | if(idx>=n) //Base Condition 78 | return 1; 79 | 80 | 81 | if(dp[idx][PreVal][Val]!=-1) //Memoization 82 | return dp[idx][PreVal][Val]%mod; 83 | 84 | 85 | int ans1=0; //Answer that will keep count. 86 | for(int i=0;iAnd val will become preval. 93 | -->Add it in ans1.*/ 94 | ans1=(ans1 % mod + solve(Val,v[Val][i],idx+1,n,v) % mod)%mod; 95 | } 96 | 97 | } 98 | 99 | return dp[idx][PreVal][Val] = ans1%mod; //return ans1 100 | } 101 | int distinctSequences(int n) 102 | { 103 | vector>v(7); //2d vector that will store the Gcd 1 values with i'th index. 104 | 105 | v[1]={2,3,4,5,6}; 106 | v[2]={1,3,5}; 107 | v[3]={1,2,4,5}; 108 | v[4]={1,3,5}; 109 | v[5]={1,2,3,4,6}; 110 | v[6]={1,5}; 111 | 112 | memset(dp,-1,sizeof(dp)); 113 | 114 | int ans=0; 115 | for(int i=1;i<=6;i++) //For index 0 we have all choices from 0 to 6. 116 | { 117 | ans=(ans % mod+solve(i,i,1,n,v) % mod)%mod; //Call solve function from index 1. 118 | } 119 | 120 | return ans%mod; // return ans. 121 | } 122 | }; -------------------------------------------------------------------------------- /Biweekly 82/README.md: -------------------------------------------------------------------------------- 1 | |PROBLEMS|IMPORTANT| 2 | |--------|---------| 3 | |[Evaluate Boolean Binary Tree](https://leetcode.com/contest/biweekly-contest-82/problems/evaluate-boolean-binary-tree)| 4 | |[The Latest Time to Catch a Bus](https://leetcode.com/contest/biweekly-contest-82/problems/the-latest-time-to-catch-a-bus)|💡| 5 | |[Minimum Sum of Squared Difference](https://leetcode.com/contest/biweekly-contest-82/problems/minimum-sum-of-squared-difference)|💡| 6 | |[Subarray With Elements Greater Than Varying Threshold](https://leetcode.com/contest/biweekly-contest-82/problems/subarray-with-elements-greater-than-varying-threshold)|💡| 7 | -------------------------------------------------------------------------------- /Biweekly 82/question1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Evaluate Boolean Binary Tree 3 | 4 | You are given the root of a full binary tree with the following properties: 5 | 6 | Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. 7 | Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. 8 | The evaluation of a node is as follows: 9 | 10 | If the node is a leaf node, the evaluation is the value of the node, i.e. True or False. 11 | Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. 12 | Return the boolean result of evaluating the root node. 13 | 14 | A full binary tree is a binary tree where each node has either 0 or 2 children. 15 | 16 | A leaf node is a node that has zero children. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | 23 | Input: root = [2,1,3,null,null,0,1] 24 | Output: true 25 | Explanation: The above diagram illustrates the evaluation process. 26 | The AND node evaluates to False AND True = False. 27 | The OR node evaluates to True OR False = True. 28 | The root node evaluates to True, so we return true. 29 | Example 2: 30 | 31 | Input: root = [0] 32 | Output: false 33 | Explanation: The root node is a leaf node and it evaluates to false, so we return false. 34 | 35 | 36 | Constraints: 37 | 38 | The number of nodes in the tree is in the range [1, 1000]. 39 | 0 <= Node.val <= 3 40 | Every node has either 0 or 2 children. 41 | Leaf nodes have a value of 0 or 1. 42 | Non-leaf nodes have a value of 2 or 3. 43 | 44 | **/ 45 | 46 | // Here is the Solution: 47 | 48 | class Solution 49 | { 50 | public: 51 | 52 | bool evaluateTree(TreeNode* root) 53 | { 54 | // return true or false if there is no further node.(recursion base) 55 | if(not root) 56 | { 57 | return true; 58 | } 59 | 60 | // if the node is valid, evaluate the left and right val(recursion step). 61 | int lval = evaluateTree(root->left); 62 | int rval = evaluateTree(root->right); 63 | 64 | // do the logical || or && based on the root value. 65 | // if it isn't either 2 or 3, return the value itself. 66 | if(root->val == 2) 67 | { 68 | return lval or rval; 69 | } else if(root->val == 3) 70 | { 71 | return lval and rval; 72 | } else return root->val; 73 | } 74 | }; 75 | 76 | 77 | // TIme Complexity: O(N) 78 | // Space Complexity: O(1) 79 | -------------------------------------------------------------------------------- /Biweekly 82/question2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | The Latest Time to Catch a Bus 3 | 4 | You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger. All bus departure times are unique. All passenger arrival times are unique. 5 | 6 | You are given an integer capacity, which represents the maximum number of passengers that can get on each bus. 7 | 8 | When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus is not full. Passengers with the earliest arrival times get on the bus first. 9 | 10 | More formally when a bus arrives, either: 11 | 12 | If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or 13 | The capacity passengers with the earliest arrival times will get on the bus. 14 | Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger. 15 | 16 | Note: The arrays buses and passengers are not necessarily sorted. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: buses = [10,20], passengers = [2,17,18,19], capacity = 2 23 | Output: 16 24 | Explanation: Suppose you arrive at time 16. 25 | At time 10, the first bus departs with the 0th passenger. 26 | At time 20, the second bus departs with you and the 1st passenger. 27 | Note that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus. 28 | Example 2: 29 | 30 | Input: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2 31 | Output: 20 32 | Explanation: Suppose you arrive at time 20. 33 | At time 10, the first bus departs with the 3rd passenger. 34 | At time 20, the second bus departs with the 5th and 1st passengers. 35 | At time 30, the third bus departs with the 0th passenger and you. 36 | Notice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus. 37 | 38 | 39 | Constraints: 40 | 41 | n == buses.length 42 | m == passengers.length 43 | 1 <= n, m, capacity <= 105 44 | 2 <= buses[i], passengers[i] <= 109 45 | Each element in buses is unique. 46 | Each element in passengers is unique. 47 | 48 | **/ 49 | 50 | /** 51 | Time Complexity: O(NlogN) 52 | Space Complexity: O(1) 53 | **/ 54 | 55 | // Here is the Solution: 56 | 57 | class Solution 58 | { 59 | public: 60 | int latestTimeCatchTheBus(vector& buses, vector& passengers, int capacity) 61 | 62 | { 63 | sort(buses.begin(), buses.end()); 64 | sort(passengers.begin(), passengers.end()); 65 | int cur_passenger = 0; 66 | int elig; 67 | for (int b = 0; b < buses.size(); ++b) 68 | { 69 | int cnt = 0; 70 | // filling the bus if "bus is not full" and "there is still passengers" and "current passenger is on time" 71 | while (cnt < capacity && cur_passenger + cnt < passengers.size() && passengers[cur_passenger + cnt] <= buses[b]) 72 | { 73 | // for each onboarded passenger update your arrival time 74 | // if "onboarding first passenger" or "non-first passenger and there is gap between his arrival time and the privious passenger's arrival time" 75 | if (cur_passenger + cnt == 0 || passengers[cur_passenger + cnt] - 1 != passengers[cur_passenger + cnt - 1]) elig = passengers[cur_passenger + cnt] - 1; 76 | cnt ++; 77 | } 78 | // after picking the obarded passengers, make your arrival time as late as bus departure time 79 | // if "bus has space" and ("no passenger onbarded" or "bus departure time not occupied by the last passenger" 80 | if (cnt < capacity && (cur_passenger + cnt == 0 || passengers[cur_passenger + cnt - 1] != buses[b])) elig = buses[b]; 81 | cur_passenger += cnt; 82 | } 83 | return elig; 84 | } 85 | }; -------------------------------------------------------------------------------- /Biweekly 82/question3.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Minimum sum of Squared Difference. 3 | 4 | You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n. 5 | 6 | The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n. 7 | 8 | You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. 9 | 10 | Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times. 11 | 12 | Note: You are allowed to modify the array elements to become negative integers. 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0 19 | Output: 579 20 | Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. 21 | The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579. 22 | Example 2: 23 | 24 | Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1 25 | Output: 43 26 | Explanation: One way to obtain the minimum sum of square difference is: 27 | - Increase nums1[0] once. 28 | - Increase nums2[2] once. 29 | The minimum of the sum of square difference will be: 30 | (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43. 31 | Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43. 32 | 33 | 34 | Constraints: 35 | 36 | n == nums1.length == nums2.length 37 | 1 <= n <= 105 38 | 0 <= nums1[i], nums2[i] <= 105 39 | 0 <= k1, k2 <= 109 40 | 41 | 42 | 43 | 44 | 45 | TC : O(NlogN) 46 | Space Complexity: O(1) 47 | 48 | 49 | 50 | **/ 51 | 52 | 53 | 54 | // Here is the Solution: 55 | 56 | class Solution 57 | { 58 | public: 59 | //why using set over priority_queue ? 60 | 61 | //General idea: 62 | //We are pre-calculating the count of each difference 63 | //Taking out max number from set by *set.rbegin() 64 | //if the count of the number is less than k, we decrease k by that amount 65 | //otherwise we break making the k to be zero 66 | //This way it will not give TLE as it will decrease k for sure as n <= 10^5 and k<= 10^9 67 | 68 | 69 | long long minSumSquareDiff(vector& nums1, vector& nums2, int k1, int k2) 70 | { 71 | set st; 72 | int n= nums1.size(); 73 | int k= k1 + k2; 74 | 75 | //map to store count of differnce at each index 76 | unordered_map mp; 77 | 78 | //traversing to get count 79 | for(int i= 0; i< n; ++i) 80 | { 81 | long long x= (long long)abs(nums1[i] - nums2[i]); 82 | 83 | //storing unique values into set 84 | st.insert(x); 85 | //taking count 86 | mp[x]++; 87 | } 88 | 89 | long long sum= 0; 90 | while(k) 91 | { 92 | //if set is empty, return 93 | if(st.empty()) 94 | break; 95 | //taking out max element form set 96 | long long x= *st.rbegin(); 97 | 98 | //if the max element si itself 0, then all other value would be definitely 0, so return 0 99 | //there is no negative values, we keep absolute difference 100 | if(x == 0) 101 | return 0; 102 | 103 | int cnt= mp[x]; 104 | //if count is less than or equal to current k, count of current number would become 0 105 | //and count of (current number - 1) would increase by cnt; 106 | if(cnt <= k) 107 | { 108 | mp[x] = 0; 109 | mp[x-1]+= cnt; 110 | k-= cnt; 111 | } 112 | 113 | //if count is more than k, the count is current would decrease by k 114 | //and count of (current number - 1) would increase by k 115 | //we break as k = 0 now. 116 | else 117 | { 118 | mp[x]= cnt- k; 119 | mp[x-1]+= k; 120 | break; 121 | } 122 | 123 | //insert (current number - 1) as it is possible that this number is not in set. 124 | st.insert(x-1); 125 | 126 | //erase the element as it's work is done 127 | st.erase(x); 128 | } 129 | 130 | //take the count of count of each number 131 | //multiply the sqaure of number with its count 132 | for(auto& x: mp) 133 | { 134 | sum+= (x.first * x.first * x.second); 135 | } 136 | return sum; 137 | 138 | //so why to use set ? 139 | //because we can erase element from set easily. 140 | } 141 | }; 142 | -------------------------------------------------------------------------------- /Biweekly 82/question4.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Subarray With Elements Greater Than Varying Threshold 3 | 4 | You are given an integer array nums and an integer threshold. 5 | 6 | Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. 7 | 8 | Return the size of any such subarray. If there is no such subarray, return -1. 9 | 10 | A subarray is a contiguous non-empty sequence of elements within an array. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [1,3,4,3,1], threshold = 6 17 | Output: 3 18 | Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2. 19 | Note that this is the only valid subarray. 20 | Example 2: 21 | 22 | Input: nums = [6,5,6,5,8], threshold = 7 23 | Output: 1 24 | Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned. 25 | Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. 26 | Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions. 27 | Therefore, 2, 3, 4, or 5 may also be returned. 28 | 29 | 30 | Constraints: 31 | 32 | 1 <= nums.length <= 105 33 | 1 <= nums[i], threshold <= 109 34 | **/ 35 | 36 | // Here is the Solution: 37 | 38 | class Solution 39 | { 40 | public: 41 | int validSubarraySize(vector& nums, int threshold) 42 | { 43 | 44 | int n = nums.size(); 45 | 46 | // find the index of next smaller for every element on left 47 | 48 | vector left_smaller(n, -1); 49 | 50 | stack st; 51 | 52 | for(int i = 0; i < n; i++) 53 | { 54 | // remove the index of greater element from stack 55 | 56 | while(!st.empty() && nums[st.top()] >= nums[i]) 57 | { 58 | st.pop(); 59 | } 60 | 61 | // if no smaller element on left 62 | 63 | if(st.empty()) 64 | { 65 | left_smaller[i] = -1; 66 | } 67 | 68 | // if smaller element is present on left 69 | 70 | else 71 | { 72 | left_smaller[i] = st.top(); 73 | } 74 | 75 | // push the index of curr element 76 | 77 | st.push(i); 78 | } 79 | 80 | // empty the stack for finding the next smaller on right 81 | 82 | while(!st.empty()) 83 | { 84 | st.pop(); 85 | } 86 | 87 | // find the index of next smaller on right 88 | 89 | vector right_smaller(n, n); 90 | 91 | for(int i = n - 1; i >= 0; i--) 92 | { 93 | // remove the index of greater element from stack 94 | 95 | while(!st.empty() && nums[st.top()] >= nums[i]) 96 | { 97 | st.pop(); 98 | } 99 | 100 | // if no smaller element on right 101 | 102 | if(st.empty()) 103 | { 104 | right_smaller[i] = n; 105 | } 106 | 107 | // if smaller element is present on right 108 | 109 | else 110 | { 111 | right_smaller[i] = st.top(); 112 | } 113 | 114 | // push the index of curr element 115 | 116 | st.push(i); 117 | } 118 | 119 | // now find the size of subarray, which will contains all the elements greater than (threshold / size of subarray) 120 | 121 | for(int i = 0; i < n; i++) 122 | { 123 | // find size of subarray, considering nums[i] as minimum of subarray 124 | 125 | int k = right_smaller[i] - left_smaller[i] - 1; 126 | 127 | // find the minimum value required for subarray, by doing (threshold / k) 128 | 129 | double min_value_required = (double) threshold / k; 130 | 131 | // check that if minimum of subarray(nums[i]) is greater than min_value_required, then size of subarray is found, return size(k) 132 | 133 | // if minimum of subarray(nums[i]) is greater than min_value_required, then every element of subarray will be greater than min_value_required 134 | 135 | if(nums[i] > min_value_required) 136 | { 137 | return k; 138 | } 139 | } 140 | 141 | return -1; 142 | } 143 | }; 144 | 145 | // Time Complexity: O(N) 146 | // Space Complexity: O(N) -------------------------------------------------------------------------------- /Biweekly Contest 80/README.md: -------------------------------------------------------------------------------- 1 | |PROBLEMS|IMPORTANT| 2 | |--------|---------| 3 | |[Strong Password Checker II](https://leetcode.com/contest/biweekly-contest-80/problems/strong-password-checker-ii)|💡| 4 | |[Successful Pairs of Spells and Potions](https://leetcode.com/contest/biweekly-contest-80/problems/successful-pairs-of-spells-and-potions)|💡| 5 | |[Match Substring After Replacement](https://leetcode.com/contest/biweekly-contest-80/problems/match-substring-after-replacement)| 6 | |[Count Subarrays With Score Less Than K](https://leetcode.com/contest/biweekly-contest-80/problems/count-subarrays-with-score-less-than-k)|💡| 7 | -------------------------------------------------------------------------------- /Biweekly Contest 80/question1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Strong Password Checker II 3 | (Easy) 4 | 5 | A password is said to be strong if it satisfies all the following criteria: 6 | It has at least 8 characters. 7 | It contains at least one lowercase letter. 8 | It contains at least one uppercase letter. 9 | It contains at least one digit. 10 | It contains at least one special character. The special characters are the characters in the following string: "!@#$%^&*()-+". 11 | It does not contain 2 of the same character in adjacent positions (i.e., "aab" violates this condition, but "aba" does not). 12 | Given a string password, return true if it is a strong password. Otherwise, return false. 13 | 14 | Approach : 15 | Simply brute force the questions, 16 | while checking each character, 17 | put the if conditions accordingly to check for 18 | 1. lower case, 19 | 2. upper case, 20 | 3. special characters, 21 | 4.adjacent characters, 22 | 5. numbers and 23 | 6. size of string. 24 | 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | bool strongPasswordCheckerII(string password) 31 | { 32 | if(password.size()<8) return false; 33 | //l=lower, u=upper, d=digit, s=special 34 | bool l=false, u=false, d=false, s=false; 35 | for(int i=0; i0 && password[i]==password[i-1]) 39 | return false; 40 | //checking for lowercase letter 41 | if(islower(password[i])) 42 | l=true; 43 | //checking for uppercase letter 44 | else if(isupper(password[i])) 45 | u=true; 46 | //checking for digit 47 | else if(isdigit(password[i])) 48 | d=true; 49 | else 50 | //checking for special characters 51 | s=true; 52 | } 53 | return l && u && d && s; 54 | } 55 | }; 56 | /* 57 | Time complexity: O(n) 58 | Space complexity: O(1) 59 | */ 60 | -------------------------------------------------------------------------------- /Biweekly Contest 80/question2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two positive integer arrays spells and potions, of length n and m respectively, 3 | where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. 4 | You are also given an integer success. 5 | A spell and potion pair is considered successful if the product of their strengths is at least success. 6 | Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell. 7 | 8 | Approach :(Sorting and Binary Search) 9 | 1. Sorting potions so that binary search can be applied on it 10 | 2. For every spell, binary search on the number of potions that can be used such that spells[i] * potions[j] >= success. 11 | 3. If any particular potion satisfies the above condition, then all the potions from potions[mid] to potions[m - 1] should satisfy the condition as well. 12 | 4. Hence, we now store this index in 'c' and proceed to find if any lower index in potions satisfy the condition or not. 13 | 5. If condition is not satisfied, proceed to a higher index. 14 | 6. Now if all potions from potions[c] to potions[m - 1] satisfy the condition, we have 'm - c' pairs for this particular spell. 15 | 16 | */ 17 | 18 | class Solution 19 | { 20 | public: 21 | // Sorting and Binary Search 22 | vector successfulPairs(vector& spells, vector& potions, long long success) 23 | { 24 | int n = spells.size(), m = potions.size(); 25 | //sorting potions 26 | sort(potions.begin(), potions.end()); 27 | vector ans; 28 | for(int i = 0; i < n; i++) 29 | { 30 | int l = 0, r = m - 1, c = m; 31 | while(l <= r) 32 | { 33 | int mid = l + (r - l) / 2; 34 | if((((long long)potions[mid]) * ((long long)spells[i])) >= success) 35 | { 36 | c = mid; 37 | r = mid - 1; 38 | } 39 | else 40 | { 41 | l = mid + 1; 42 | } 43 | } 44 | ans.push_back(m - c); 45 | } 46 | return ans; 47 | } 48 | }; 49 | 50 | /* 51 | Time Complexity= O(m log m)+ O(n log m) 52 | Space Complexity : O(m) 53 | */ 54 | -------------------------------------------------------------------------------- /Biweekly Contest 80/question3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two strings s and sub. You are also given a 2D character array mappings 3 | where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: 4 | Replace a character oldi of sub with newi. 5 | Each character in sub cannot be replaced more than once. 6 | Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. 7 | Otherwise, return false. 8 | A substring is a contiguous non-empty sequence of characters within a string. 9 | 10 | Approach : 11 | 1. Convert a new mapping 'New' where key is the old character which stores a set of new characters. 12 | 2. This will help to find in O(1) if there is any character 'new' that can be replaced for any character 'old' 13 | 3. Let n be the length of s and m be the length of sub. 14 | 4. Simply loop through each substring of length m in string s and check, 15 | 5. Simply continue if the character matches. 16 | 6. In the absence of a match, see whether we can convert to a character using an unordered map. 17 | 7. Continue if we can effect change. 18 | 8. Else, it is not feasible for that substring. 19 | 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool matchReplacement(string s, string sub, vector>& mappings) 26 | { 27 | unordered_map> New; 28 | int n = s.size(), m = sub.size(); 29 | for(int i = 0; i < mappings.size(); i++) 30 | { 31 | New[mappings[i][0]].insert(mappings[i][1]); 32 | } 33 | for(int i = 0; i < n - m + 1; i++) 34 | { 35 | for(int j = i; j < i + m; j++) 36 | { 37 | if(s[j] == sub[j - i] || New[sub[j - i]].find(s[j]) != New[sub[j - i]].end()) 38 | { 39 | if(j == i + m - 1) return true; 40 | } else break; 41 | } 42 | } 43 | return false; 44 | } 45 | }; 46 | 47 | // Time complexity: O(n * m) where size(s) = n & size(sub) = m 48 | -------------------------------------------------------------------------------- /Biweekly Contest 80/question4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two strings s and sub. You are also given a 2D character array mappings 3 | where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: 4 | Replace a character oldi of sub with newi. 5 | Each character in sub cannot be replaced more than once. 6 | Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. 7 | Otherwise, return false. 8 | A substring is a contiguous non-empty sequence of characters within a string. 9 | 10 | Approach : 11 | 1. It can be solved by the sliding window technique. 12 | 2. Assume, we have a window between start and end, and the product of all elements < k. 13 | 3. Now, let's try to add a new element x. There are two possible cases. 14 | Case-1 ( p >= k) 15 | This indicates that we must first change the left border of the window so that the result is once more less than k. 16 | Case-2 ( p < k) 17 | This means we can move the right bound of the window one step further. 18 | i.e. right - left + 1 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | long long countSubarrays(vector& nums, long long k) 25 | { 26 | int n = nums.size(); 27 | int left = 0; long long sum = 0, ans = 0; 28 | for(int right = 0; right < n; right++) 29 | { 30 | sum += nums[right]; 31 | while(sum * (right - left + 1) >= k) 32 | { 33 | sum -= nums[left++]; 34 | } 35 | ans += right - left + 1; 36 | } 37 | return ans; 38 | } 39 | }; 40 | 41 | // Time Complexity: O(N), 42 | // Space Complexity : O(1) 43 | -------------------------------------------------------------------------------- /Biweekly Contest 83/BestPokerHand.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string bestHand(vector& ranks, vector& suits) 4 | { 5 | unordered_mapmr; 6 | unordered_mapms; 7 | string ans="";//it will store the final answer 8 | 9 | //storing the frequency of all the ranks 10 | for(auto val:ranks) 11 | mr[val]++; 12 | 13 | //storing frequency of the elements of suits 14 | for(auto val:suits) 15 | ms[val]++; 16 | 17 | //case 1 18 | if(ms.size() == 1) 19 | { 20 | ans = "Flush"; 21 | return ans; 22 | } 23 | 24 | if(mr.size() == 5) 25 | { 26 | ans = "High Card"; 27 | return ans; 28 | } 29 | 30 | for(auto current : mr) 31 | { 32 | if(current.second >= 3) 33 | { 34 | ans = "Three of a Kind"; 35 | return ans; 36 | } 37 | } 38 | 39 | ans = "Pair"; 40 | return ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /Biweekly Contest 83/DesignNumberContainerSystem.cpp: -------------------------------------------------------------------------------- 1 | class NumberContainers { 2 | public: 3 | 4 | unordered_mapm1;//index : number 5 | unordered_map>m2;// number : [indices] 6 | 7 | NumberContainers() 8 | { 9 | 10 | } 11 | 12 | void change(int index, int number) 13 | { 14 | //if we are already having a number at index position 15 | //then we need to replace it in m1 and remove its index from m2 16 | //after that we'll also have to add the index of current number in m2 17 | if(m1.find(index) != m1.end()) 18 | { 19 | int prev = m1[index];//the previous value at index in m1 20 | m2[prev].erase(index); 21 | } 22 | m1[index] = number; 23 | m2[number].insert(index); 24 | } 25 | 26 | int find(int number) 27 | { 28 | return m2[number].empty() ? -1 : *m2[number].begin(); 29 | } 30 | }; 31 | 32 | /** 33 | * Your NumberContainers object will be instantiated and called as such: 34 | * NumberContainers* obj = new NumberContainers(); 35 | * obj->change(index,number); 36 | * int param_2 = obj->find(number); 37 | */ -------------------------------------------------------------------------------- /Biweekly Contest 83/NumberZero-FilledSubarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long zeroFilledSubarray(vector& nums) 4 | { 5 | long long ans = 0; 6 | int j = 0; 7 | 8 | for (int i = 0; i < nums.size(); i++) 9 | { 10 | if (nums[i] != 0) 11 | j = i + 1; 12 | ans += i - j + 1; 13 | } 14 | return ans; 15 | } 16 | }; -------------------------------------------------------------------------------- /Biweekly Contest 83/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## [Best Poker Hand](https://leetcode.com/problems/best-poker-hand/) 3 | 4 | #### Approach 5 | 6 | - In this question we are having 4 cases :- 7 | 8 | i.If all the characters of suits vector are same the return "Flush" 9 | 10 | ii.If any of the value in the values in the rank vector has frequency greater than or equal to 3 then return "Three of a Kind" 11 | 12 | iii.Else if any of the values in the rank vector has frequency equals to 2 then return "Pair" 13 | 14 | iv.Else if all the values in the rank vector are differnt then return "High Card" 15 | 16 | 1. Store the frequencies of each elements of rank vector in an unordered map(say mr) and similarly, Store the frequencies of each characters of suits vector in another unordered map(say ms). 17 | 18 | 2. Take an empty string ans to store the answer. 19 | 20 | 3. If the size of ms is equal to 1,then it implies that we have all the values same in suits ,so set ans as "Flush" and return ans. 21 | 22 | 4. If the size of mr is 5,then it implies that we have all distinct values in rank , so set ans as "High Card" and return ans. 23 | 24 | 5. Otherwise traverse mr and if any of the key is having frequency greater than or equal to 3 ,then set ans as "Three of a Kind" and return ans. 25 | 26 | 6. If none of the above holds then simply set ans as "Pair" and return it. 27 | 28 | 29 | #### Time Complexity = O(N) 30 | 31 | - Where N = 5,its because the size of rank & suits vector is fixed and is equal to 5. 32 | 33 | #### Space Complexity = O(N) + O(N) 34 | 35 | - because we are using two unordered maps 36 | 37 | 38 | 39 | ## [Shortest Impossible Sequence of Rolls](https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/) 40 | 41 | #### Approach 42 | 43 | - In this question we are supposed to find the minimum length L for which a sequence of possible dice moves of length L is not possible. 44 | 45 | - Take an empty set. 46 | 47 | - Now, iterate untill the size of the set becomes equals k i.e. we'll find all the k sequence. 48 | 49 | - If we haven't got k sequences even after completing the iteration then this implies that this length combinations can not be created, therefore this lenght is the answer. 50 | 51 | - Otherwise if we have found all the k sequences before completing the whole iteration, then this implies that we can create all the combinations of given length, therefore we have to make the set empty and increment length by one. 52 | 53 | #### Time Complexity = O(nlogk) 54 | 55 | #### Space Complexity = O(k) 56 | 57 | 58 | ## [Design a Number Container System](https://leetcode.com/problems/design-a-number-container-system/) 59 | 60 | #### Approach 61 | 62 | - Take two unordered map :- 1) m1 -> for storing elements corresponding to each given index. 63 | 64 | 2) m2 -> for storing all indices at which an element is present. 65 | 66 | - when change() function is called ,then :- 1) if there is an element already present at that index then store that element in a variable(say prev) 67 | and then earse its occurence i.e. index from m2. 68 | 69 | 2) Now update the value of m1[index] to the given number and add index corresponding to m2[number]. 70 | 71 | - when find() function is called the check if m2[number] is empty then return -1 otherwise return the very 1st index. 72 | 73 | 74 | #### Time Complexity = O(N) 75 | 76 | #### Space Complexity = O(2N) 77 | 78 | ## [Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) 79 | 80 | If we are having 1 zero then we'll add 1 to answer (because :- [0]) 81 | 82 | If we are having 2 zeros then we'll add 2 to answer ([0],[0,0]) 83 | 84 | If we are having 3 zeros then we'll add 3 to answer (because :- [0],[0,0],[0,0,0]) 85 | 86 | and will do the same 87 | 88 | #### Time Complexity = O(N) 89 | 90 | #### Space Complexity = O(1) 91 | -------------------------------------------------------------------------------- /Biweekly Contest 83/ShortestImpossibleSequenceRolls.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int shortestSequence(vector& rolls, int k) { 4 | int len = 1; 5 | set sequence; 6 | 7 | for (int i = 0; i < rolls.size(); i++) { 8 | sequence.insert(rolls[i]); 9 | 10 | if (sequence.size() == k) { 11 | len++; 12 | sequence = set(); 13 | } 14 | } 15 | 16 | return len; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Contributing.md: -------------------------------------------------------------------------------- 1 | ## CONTRIBUTING GUIDELINES 2 | We are happy to welcome all the contributions from anyone willing to improve this project.
3 | Thank you for helping out and remember, **no contribution is too small**.
4 |
5 | - Star the repo. 6 | - Add only the problems which have been a part of Contests **by grouping them into a folder**. 7 | - Name the folder in a valid manner. **Ex : Biweekly 50 and add problems in that folder.** 8 | - Code should be written in **C++**. 9 | - Use curly braces from the **next line**. 10 | - Explain the code with proper **approach** along with its **Time and Space complexity**. 11 | - Write the file name properly **Ex : Longest_common_subsequence**. 12 | 13 | ✔ **MAIN README** 14 | - Write the Contest name in the first column. 15 | - Add the link to the folder containing contest problems in the second column. 16 | 17 | ✔ **FOLDER README** 18 | - Inside the folder, edit readme by having links to the problem asked. 19 | - If any problem is Important in perspective of an interview, mark it as 💡. 20 | 21 | 👻 **Now, Follow these steps :-** 22 | ### Step 1 : Create an issue 23 | ### Step 2 : Fork the Project 24 | - ```Fork this Repository. This will create a Local Copy of this Repository on your Github Profile. Keep a reference to the original project in upstream remote.``` 25 | - ```$ git clone https://github.com//LeetCode-Contests``` 26 | - ```$ cd LeetCode-Contests``` 27 | - ```$ git remote add upstream https://github.com/utkarsh006/LeetCode-Contests``` 28 | 29 | ### Step 3 : Branch 30 | - ```Create a new branch. Use its name to identify the issue your addressing.``` 31 | - ```It will create a new branch with name Branch_Name and switch to that branch.``` 32 | - ```$ git checkout -b branch_name``` 33 | 34 | ### Step 4 : Work on the issue assigned 35 | - ```Work on the issue(s) assigned to you.``` 36 | - ```Add all the files/folders needed.``` 37 | - ```After you've made changes or made your contribution to the project add changes to the branch you've just created by:``` 38 | - ```To add all new files to branch Branch_Name``` 39 | - ```$ git add .``` 40 | ### Step 5 : Commit 41 | - ```This message get associated with all files you have changed``` 42 | - ```$ git commit -m "message"``` 43 | ### Step 6 : Work Remotely 44 | - ```To push your work to your remote repository``` 45 | - ```$ git push -u origin Branch_Name``` 46 | 47 | ### Step 7 : Pull Request 48 | - ```Go to your repository in browser and click on compare and pull requests. Then add a title and description to your pull request that explains your contribution.``` 49 | 50 | - Yahoo ! Your Pull Request has been submitted and will be reviewed by the moderators and merged.🥳 51 | 52 |
53 | Heya! Don't Worry 😇 54 | 55 | It always takes time to understand and learn. So, do not worry at all. We know you have got this!💪
56 | 57 | 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 | 6 | Check [CONTRIBUTING GUIDELINES](https://github.com/nishkarsh800/LeetCode-Contests/blob/main/Contributing.md) 7 | 8 |
9 | 10 |

11 | BIWEEKLY CONTESTS 12 |

13 | 14 |
15 | 16 | |CONTESTS|LINK| 17 | |-------|-----| 18 | | [Biweekly 83](https://leetcode.com/contest/biweekly-contest-83/) | [Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Biweekly%20Contest%2083)| 19 | | [Biweekly 80](https://leetcode.com/contest/biweekly-contest-80/) | [Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Biweekly%20Contest%2080) | 20 | | [Biweekly 81](https://leetcode.com/contest/biweekly-contest-81/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Biweekly%2081)| 21 | | [Biweekly 82](https://leetcode.com/contest/biweekly-contest-82/)| [Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Biweekly%2082) 22 |
23 | 24 |

25 | 26 |

27 | WEEKLY CONTESTS 28 |

29 | 30 |
31 | 32 | |CONTESTS|LINK| 33 | |-------|-----| 34 | |[Weekly Contest 298](https://leetcode.com/contest/weekly-contest-298/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20298)| 35 | |[Weeky Contest 297](https://leetcode.com/contest/weekly-contest-297/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20297)| 36 | |[Weekly Contest 304](https://leetcode.com/contest/weekly-contest-304/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20304)| 37 | |[Weekly Contest 305](https://leetcode.com/contest/weekly-contest-305/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20305)| 38 | |[Weekly Contest 308](https://leetcode.com/contest/weekly-contest-308/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20308)| 39 | |[Weekly Contest 321](https://leetcode.com/contest/weekly-contest-321/)|[Solutions](https://github.com/nishkarsh800/LeetCode-Contests/tree/main/Weekly%20Contest%20321)| 40 | |[Weekly Contest 334](https://leetcode.com/contest/weekly-contest-334/)|[Solutions]()| 41 |
42 |
43 |
44 | 45 |

Project Contributors

46 | 47 |
48 | 49 | 50 | 51 |
52 | -------------------------------------------------------------------------------- /Weekly Contest 297/README.md: -------------------------------------------------------------------------------- 1 | **For Question 1:** 2 | 3 | * Time Complexity: O(N) 4 | * Space Complexity: O(1) 5 | 6 | Approach: 7 | 8 | ``` 9 | The first upper0 dollars earned are taxed at a rate of percent0. 10 | The next upper1 - upper0 dollars earned are taxed at a rate of percent1. 11 | The next upper2 - upper1 dollars earned are taxed at a rate of percent2. 12 | ``` 13 | 14 | * The Approach is given in detailed in code approach with comments. 15 | 16 | **For Question 2:** 17 | 18 | * Space Complexity: O(1) 19 | * Time Complexity: 20 | 21 | Approach: 22 | 23 | 24 | * grid[i][j] will store the minimum cost required to go to the last row 25 | * For the m-1 leave it as it is because we are the last row. 26 | * For the m-2 row try every possible comibanation and find the minimum for each grid[i][j]. 27 | * For the m-3 row do the same but we have already calculated minimum for each grid[i][j] for the m-2 row so just use that for calculating minimum for m-3 row and calulating tille 1st row. 28 | 29 | 30 | **For Question 3:** 31 | 32 | * Space Complexity: O(K), Where K is the Size of Array. 33 | * Time Complexity: O(K!) 34 | 35 | Approach: 36 | 37 | * Divide the given array into k subsequences 38 | * Then find a subsequence which has largest sum out of all those subsequences. 39 | * Out of all possible subsequences, find the min largest sum possible. 40 | 41 | **For Question 4:** 42 | 43 | * Space Complexity: O(26*26) 44 | * Time Complexity: O(26*26*N) 45 | 46 | Approach: 47 | 48 | * Approach is for every pair of loweCase englist letter {x, y} (where x and y can be {'a', 'b', 'c', ..... 'z'}), 49 | * we will pre-compute that in how many we can take letter x while giving letter y 50 | 51 | * Now, for each element ideas[i], we know that take any letter execpt first letter of any such that 52 | ideas[k] such that ideas[i].substr(1, ideas[i].size()-1) == ideas[j].substr(1, ideas[j].size()-1). 53 | while ideas[i] an only give its first letter(i.e, ideas[i][j]); 54 | -------------------------------------------------------------------------------- /Weekly Contest 297/question1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate Amount Paid in Taxes. 3 | You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length). 4 | 5 | Tax is calculated as follows: 6 | 7 | The first upper0 dollars earned are taxed at a rate of percent0. 8 | The next upper1 - upper0 dollars earned are taxed at a rate of percent1. 9 | The next upper2 - upper1 dollars earned are taxed at a rate of percent2. 10 | And so on. 11 | You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: brackets = [[3,50],[7,10],[12,25]], income = 10 18 | Output: 2.65000 19 | Explanation: 20 | Based on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket. 21 | The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively. 22 | In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes. 23 | Example 2: 24 | 25 | Input: brackets = [[1,0],[4,25],[5,50]], income = 2 26 | Output: 0.25000 27 | Explanation: 28 | Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket. 29 | The tax rate for the two tax brackets is 0% and 25%, respectively. 30 | In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes. 31 | Example 3: 32 | 33 | Input: brackets = [[2,50]], income = 0 34 | Output: 0.00000 35 | Explanation: 36 | You have no income to tax, so you have to pay a total of $0 in taxes. 37 | 38 | 39 | Constraints: 40 | 41 | 1 <= brackets.length <= 100 42 | 1 <= upperi <= 1000 43 | 0 <= percenti <= 100 44 | 0 <= income <= 1000 45 | upperi is sorted in ascending order. 46 | All the values of upperi are unique. 47 | The upper bound of the last tax bracket is greater than or equal to income. 48 | 49 | */ 50 | 51 | // Here is the Solution: 52 | 53 | class Solution 54 | { 55 | public: 56 | double calculateTax(vector>& brackets, int income) 57 | { 58 | if(!income) //If income is 0 59 | return 0; 60 | 61 | double ans(0.0); 62 | 63 | int i(0), prev(0); 64 | while(income) 65 | { //While income is not 0.. 66 | int cur = brackets[i][0] - prev; 67 | //This gets the difference between current upper bound and previous upper bound 68 | 69 | ans += double(brackets[i][1]) / 100.0 * min(cur, income); 70 | //It's important to convert to double and divide by 100.0 because 71 | //if we stay with int, for example int 50 / int 100 ends up being 0 which is not accurate. 72 | 73 | income -= min(cur, income); 74 | //Using min because if there is still more income left for the next bracket, 75 | //then only minus the cur (which is the max amount that can be taxed for this bracket). 76 | //If income is less than cur, then this is the last bracket, 77 | //so tax and minus the income left. Then income = 0 and while loop ends. 78 | 79 | prev = brackets[i][0]; //Saving current upper bound 80 | i++; //Moving on to next bracket 81 | } 82 | 83 | return ans; 84 | 85 | } 86 | }; 87 | -------------------------------------------------------------------------------- /Weekly Contest 297/question2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Path Cost in a Grid 3 | Difficulty: Medium 4 | You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row. 5 | 6 | Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored. 7 | 8 | The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row. 9 | 10 | 11 | 12 | Constraints: 13 | 14 | m == grid.length 15 | n == grid[i].length 16 | 2 <= m, n <= 50 17 | grid consists of distinct integers from 0 to m * n - 1. 18 | moveCost.length == m * n 19 | moveCost[i].length == n 20 | 1 <= moveCost[i][j] <= 100 21 | 22 | */ 23 | 24 | // Here is the Solution: 25 | 26 | class Solution 27 | { 28 | public: 29 | int minPathCost(vector>& grid, vector>& cost) 30 | { 31 | int m=grid.size(),n=grid[0].size(),sz=cost.size(); 32 | for(int i=m-2;i>=0;i--){ 33 | for(int j=0;j &buckets, vector &cookies){ 49 | // Out of bounds 50 | if(ind >= cookies.size()) 51 | { 52 | // Find the maximum total cookies obtained by one child 53 | int large = *max_element(buckets.begin(), buckets.end()); 54 | unfairness = min(unfairness, large); 55 | return ; 56 | } 57 | 58 | // Adding cookie to the buckets 59 | // As there will be k buckets, we will add current cookie to each bucket 60 | for(int i=0; i& cookies, int k) 70 | { 71 | // No.of students and cookie bags are same 72 | if(k == cookies.size()) 73 | { 74 | return *max_element(cookies.begin(), cookies.end()); 75 | } 76 | // Divide the array into k parts and find the min largest value 77 | vector buckets(k, 0); 78 | helper(0, k, buckets, cookies); 79 | return unfairness; 80 | } 81 | }; 82 | -------------------------------------------------------------------------------- /Weekly Contest 297/question4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Naming a Company. 3 | Difficulty: Hard 4 | You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows: 5 | 6 | Choose 2 distinct names from ideas, call them ideaA and ideaB. 7 | Swap the first letters of ideaA and ideaB with each other. 8 | If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name. 9 | Otherwise, it is not a valid name. 10 | Return the number of distinct valid names for the company. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: ideas = ["coffee","donuts","time","toffee"] 17 | Output: 6 18 | Explanation: The following selections are valid: 19 | - ("coffee", "donuts"): The company name created is "doffee conuts". 20 | - ("donuts", "coffee"): The company name created is "conuts doffee". 21 | - ("donuts", "time"): The company name created is "tonuts dime". 22 | - ("donuts", "toffee"): The company name created is "tonuts doffee". 23 | - ("time", "donuts"): The company name created is "dime tonuts". 24 | - ("toffee", "donuts"): The company name created is "doffee tonuts". 25 | Therefore, there are a total of 6 distinct company names. 26 | 27 | The following are some examples of invalid selections: 28 | - ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array. 29 | - ("time", "toffee"): Both names are still the same after swapping and exist in the original array. 30 | - ("coffee", "toffee"): Both names formed after swapping already exist in the original array. 31 | Example 2: 32 | 33 | Input: ideas = ["lack","back"] 34 | Output: 0 35 | Explanation: There are no valid selections. Therefore, 0 is returned. 36 | 37 | 38 | Constraints: 39 | 40 | 2 <= ideas.length <= 5 * 104 41 | 1 <= ideas[i].length <= 10 42 | ideas[i] consists of lowercase English letters. 43 | All the strings in ideas are unique. 44 | 45 | */ 46 | 47 | // Here is the Solution: 48 | 49 | 50 | using ll = long long; 51 | class Solution 52 | { 53 | public: 54 | long long distinctNames(vector& ideas) 55 | { 56 | int n = ideas.size(); 57 | map> mp; 58 | for(string &s: ideas) 59 | { 60 | s.push_back('#'); 61 | mp[s.substr(1, s.size()-1)].insert(s[0]); //computing all of the letter for which s can not be swaped 62 | } 63 | vector> adjList(26, vector(26));//[canTake, canGive]; 64 | for(int i=0; i &v = mp[s.substr(1, s.size()-1)]; 68 | int canGive = s[0] - 'a'; 69 | for(int i=0; i<26; i++) 70 | { 71 | adjList[i][canGive]++; 72 | } 73 | 74 | for(char c: v) //removing all such elements that can cause prolems 75 | { 76 | int canNotTake = c-'a'; 77 | adjList[canNotTake][canGive]--; 78 | } 79 | } 80 | 81 | ll res = 0; 82 | 83 | for(int i=0; i &v = mp[s.substr(1, s.size()-1)]; 87 | int whoCanTake = s[0] - 'a'; 88 | for(char c ='a'; c<='z'; c++) 89 | { 90 | if(v.find(c) != v.end()) 91 | continue; 92 | 93 | res += adjList[whoCanTake][c-'a']; 94 | } 95 | } 96 | 97 | return res; 98 | } 99 | }; 100 | -------------------------------------------------------------------------------- /Weekly Contest 298/question1.cpp: -------------------------------------------------------------------------------- 1 | // Greatest English Letter in Upper and Lower Case. 2 | 3 | /* 4 | Explanation of the Sum: 5 | 6 | Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string. 7 | 8 | An English letter b is greater than another letter a if b appears after a in the English alphabet. 9 | */ 10 | 11 | /* 12 | 13 | Example 1: 14 | 15 | Input: s = "lEeTcOdE" 16 | Output: "E" 17 | Explanation: 18 | The letter 'E' is the only letter to appear in both lower and upper case. 19 | 20 | Example 2: 21 | 22 | Input: s = "arRAzFif" 23 | Output: "R" 24 | Explanation: 25 | The letter 'R' is the greatest letter to appear in both lower and upper case. 26 | Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'. 27 | 28 | Example 3: 29 | 30 | Input: s = "AbCdEfGhIjK" 31 | Output: "" 32 | Explanation: 33 | There is no letter that appears in both lower and upper case. 34 | 35 | Constrains: 36 | 37 | 1 <= s.length <= 1000 38 | s consists of lowercase and uppercase English letters. 39 | 40 | */ 41 | 42 | // Here is the solution in C++: 43 | 44 | 45 | class Solution { 46 | public: 47 | string greatestLetter(string s) { 48 | 49 | int lower[26] = {0}; 50 | int upper[26] = {0}; 51 | 52 | for(char c : s){ 53 | if(islower(c)) 54 | lower[c-'a']++; 55 | if(isupper(c)) 56 | upper[c-'A']++; 57 | } 58 | 59 | for(int i = 25 ; i >= 0; i--){ 60 | if(upper[i] && lower[i]) 61 | return string(1, 'A' + i); 62 | } 63 | 64 | return ""; 65 | } 66 | }; 67 | 68 | -------------------------------------------------------------------------------- /Weekly Contest 298/question2.cpp: -------------------------------------------------------------------------------- 1 | // Sum of numbers with unit digits K. 2 | 3 | /* 4 | 5 | Given two integers num and k, consider a set of positive integers with the following properties: 6 | 7 | The units digit of each integer is k. 8 | The sum of the integers is num. 9 | Return the minimum possible size of such a set, or -1 if no such set exists. 10 | 11 | Note: 12 | 13 | The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0. 14 | The units digit of a number is the rightmost digit of the number. 15 | 16 | 17 | Example 1: 18 | 19 | Input: num = 58, k = 9 20 | Output: 2 21 | Explanation: 22 | One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9. 23 | Another valid set is [19,39]. 24 | It can be shown that 2 is the minimum possible size of a valid set. 25 | Example 2: 26 | 27 | Input: num = 37, k = 2 28 | Output: -1 29 | Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2. 30 | Example 3: 31 | 32 | Input: num = 0, k = 7 33 | Output: 0 34 | Explanation: The sum of an empty set is considered 0. 35 | 36 | 37 | Constraints: 38 | 39 | 0 <= num <= 3000 40 | 0 <= k <= 9 41 | 42 | */ 43 | 44 | // Here is the solution: 45 | 46 | class Solution { 47 | private: 48 | int recurse(int num, int k) { 49 | // If empty set return 0 50 | if (num == 0) return 0; 51 | // Not possible to obtain sum, return -inf 52 | if (num < 0) return numeric_limits::min(); 53 | // Last digit match, add 1 to the result and terminate 54 | if (num % 10 == k) return 1; 55 | // If k is 0 and sum does not end in 0 it is not 56 | // possible to calculate the result 57 | if (k == 0) return -1; 58 | // Recurse removing k from sum 59 | return 1 + recurse(num - k, k); 60 | } 61 | public: 62 | int minimumNumbers(int num, int k) { 63 | return max(recurse(num, k), -1); 64 | } 65 | }; -------------------------------------------------------------------------------- /Weekly Contest 298/question3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Longest Binary Subsequence Less Than or Equal to K. 4 | 5 | You are given a binary string s and a positive integer k. 6 | 7 | Return the length of the longest subsequence of s that makes up a binary number less than or equal to k. 8 | 9 | Note: 10 | 11 | The subsequence can contain leading zeroes. 12 | The empty string is considered to be equal to 0. 13 | A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. 14 | 15 | 16 | Example 1: 17 | 18 | Input: s = "1001010", k = 5 19 | Output: 5 20 | Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal. 21 | Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively. 22 | The length of this subsequence is 5, so 5 is returned. 23 | Example 2: 24 | 25 | Input: s = "00101001", k = 1 26 | Output: 6 27 | Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal. 28 | The length of this subsequence is 6, so 6 is returned. 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= s.length <= 1000 34 | s[i] is either '0' or '1'. 35 | 1 <= k <= 109 36 | 37 | */ 38 | 39 | // Here is the solution: 40 | 41 | class Solution { 42 | public: 43 | int longestSubsequence(string s, int k) { 44 | int res = 0, cost = 1, n = s.size(); 45 | for (int i = n - 1; i >= 0; --i) { 46 | if (s[i] == '0' || cost <= k) { 47 | k -= cost * (s[i] - '0'); 48 | res++; 49 | } 50 | if (cost <= k) 51 | cost *= 2; 52 | } 53 | return res; 54 | } 55 | }; -------------------------------------------------------------------------------- /Weekly Contest 298/question4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Selling Pieces of Wood. 4 | You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars. 5 | 6 | To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width. 7 | 8 | Return the maximum money you can earn after cutting an m x n piece of wood. 9 | 10 | Note that you can cut the piece of wood as many times as you want. 11 | 12 | 13 | Constraints: 14 | 15 | 1 <= m, n <= 200 16 | 1 <= prices.length <= 2 * 104 17 | prices[i].length == 3 18 | 1 <= hi <= m 19 | 1 <= wi <= n 20 | 1 <= pricei <= 106 21 | All the shapes of wood (hi, wi) are pairwise distinct. 22 | 23 | */ 24 | // Here is the solution: 25 | 26 | class Solution { 27 | public: 28 | long long sellingWood(int m, int n, vector>& prices) { 29 | long long dp[201][201] = {}; 30 | for (auto& p: prices) 31 | dp[p[0]][p[1]] = p[2]; 32 | for (int w = 1; w <= m; ++w) { 33 | for (int h = 1; h <= n; ++h) { 34 | for (int a = 1; a <= w / 2; ++a) 35 | dp[w][h] = max(dp[w][h], dp[a][h] + dp[w - a][h]); 36 | for (int a = 1; a <= h / 2; ++a) 37 | dp[w][h] = max(dp[w][h], dp[w][a] + dp[w][h - a]); 38 | } 39 | } 40 | return dp[m][n]; 41 | } 42 | }; -------------------------------------------------------------------------------- /Weekly Contest 304/README.md: -------------------------------------------------------------------------------- 1 | # [Weekly Contest 304](https://leetcode.com/contest/weekly-contest-304/) 2 | |PROBLEMS|IMPORTANT| 3 | |--------|---------| 4 | |[Make Array Zero by Subtracting Equal Amounts](https://leetcode.com/contest/weekly-contest-304/problems/make-array-zero-by-subtracting-equal-amounts)|| 5 | |[Maximum Number of Groups Entering a Competition](https://leetcode.com/contest/weekly-contest-304/problems/maximum-number-of-groups-entering-a-competition)|💡| 6 | |[Find Closest Node to Given Two Nodes](https://leetcode.com/contest/weekly-contest-304/problems/find-closest-node-to-given-two-nodes)|💡| 7 | |[Longest Cycle in a Graph](https://leetcode.com/contest/weekly-contest-304/problems/longest-cycle-in-a-graph)|💡| -------------------------------------------------------------------------------- /Weekly Contest 304/question1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a non-negative integer array nums. In one operation, you must: 5 | - Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums. 6 | - Subtract x from every positive element in nums. 7 | Return the minimum number of operations to make every element in nums equal to 0 8 | 9 | Approach: (Greedy Algorithm) 10 | 11 | 1. Create an unordered set and insert elements not present in it. 12 | 2. If the set contains 0 return size of the set 13 | 3. Else return the size of set subracted by 1 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | int minimumOperations(vector& nums) 20 | { 21 | unordered_set s; // Create an unordered set 22 | for (int i=0;i& grades) 26 | { 27 | sort(grades.begin(),grades.end()); // Sorting given vector 28 | int c=0,k=0; 29 | vector a; 30 | vector::iterator it=grades.begin(); 31 | while(it!=grades.end()) 32 | { 33 | int flag=1,sum=accumulate(a.begin(), a.end(), 0); 34 | while (sum<=c || a.size()<=k) 35 | { 36 | if (it!=grades.end()) 37 | { 38 | a.push_back(*it); 39 | sum+=*it; 40 | it++; 41 | } 42 | else 43 | { 44 | flag=0; // Setting flag, inorder to reset vector a and increment k 45 | break; 46 | } 47 | } 48 | if (flag) 49 | { 50 | // resetting variables to inital values 51 | c=accumulate(a.begin(), a.end(), 0); 52 | a.clear(); 53 | k+=1; 54 | continue; 55 | } 56 | } 57 | return k; 58 | } 59 | }; 60 | 61 | /* 62 | Time Complexity: O(n*log(n))) 63 | Space Complexity: O(n) 64 | */ -------------------------------------------------------------------------------- /Weekly Contest 304/question3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. 5 | The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1. 6 | You are also given two integers node1 and node2. 7 | Return the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1. 8 | Note that edges may contain cycles. 9 | 10 | Approach: (DFS) 11 | 12 | 1. Create two unordered sets 'st' and 'tst' 13 | 2. Traverse from each of the node simultaneously, also identify the lower vlaue node and larger value node 14 | 3. Keep on storing the visited node in two different sets 15 | 4. Check for the occurence of first node in next set and second node in the first set 16 | 5. If found report answer, if not found till end then return -1 17 | 6. Also check for cycle, occurence of the node in the same set again. if found set it to -1 to terminate the loop. 18 | 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | int closestMeetingNode(vector& edges, int node1, int node2) 25 | { 26 | unordered_set st, tst; 27 | int ptr = max(node1, node2); 28 | int tptr= min(node1, node2); 29 | while(ptr != -1 || tptr != -1) 30 | { 31 | if(st.find(ptr) != st.end()) ptr = -1; 32 | if(tst.find(tptr) != tst.end()) tptr = -1; 33 | st.insert(ptr); 34 | tst.insert(tptr); 35 | // Important to check ptr first as smaller should be reported first in case of tie 36 | if(tst.find(ptr) != tst.end()) return ptr; 37 | if(st.find(tptr) != st.end() ) return tptr; 38 | if(ptr != -1) ptr = edges[ptr]; 39 | if(tptr != -1) tptr = edges[tptr]; 40 | } 41 | return -1; 42 | } 43 | }; 44 | 45 | /* 46 | Time Complexity: O(n) 47 | Space Complexity: O(n) 48 | */ -------------------------------------------------------------------------------- /Weekly Contest 304/question4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. 5 | The graph is replented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1. 6 | Return the length of the longest cycle in the graph. If no cycle exists, return -1. 7 | A cycle is a path that starts and ends at the same node. 8 | 9 | Approach: (DFS) 10 | 11 | 1. Create a variable 'l' to store the length of longest cycle and initialize to 1 12 | 2. Start from the First directed edge node and traverse using DFS till last edge 13 | 3. Traverse until you find a visited node or an end 14 | 4. While traversing assign each visited nodes to count-1 15 | 5. Check if cycle present in graph, if not found till end return l 16 | 6. If cycle present in graph, asssign 'l' to size of largest cycle. 17 | 7. Return 'l' after all nodes are visited. 18 | */ 19 | 20 | class Solution 21 | { 22 | public: 23 | int longestCycle(vector& edges) 24 | { 25 | int l=-1,count=-2; 26 | for(int i=0; i= 0) 34 | { 35 | prev = cur; 36 | cur = edges[cur]; 37 | edges[prev] = count--; 38 | } 39 | // Check if loop present 40 | if (edges[cur] <= og_count) 41 | { 42 | l=max(l, edges[cur] - edges[prev] + 1); 43 | } 44 | } 45 | return l; 46 | } 47 | }; 48 | 49 | /* 50 | Time Complexity: O(n) 51 | Space Complexity: O(1) 52 | */ -------------------------------------------------------------------------------- /Weekly Contest 305/README.md: -------------------------------------------------------------------------------- 1 | # [Weekly Contest 305](https://leetcode.com/contest/weekly-contest-305/) 2 | |PROBLEMS|IMPORTANT| 3 | |--------|---------| 4 | |[Number of Arithmetic Triplets](https://leetcode.com/contest/weekly-contest-305/problems/number-of-arithmetic-triplets)|| 5 | |[Reachable Nodes With Restrictions](https://leetcode.com/contest/weekly-contest-305/problems/reachable-nodes-with-restrictions)|| 6 | |[Check if There is a Valid Partition For The Array](https://leetcode.com/contest/weekly-contest-305/problems/check-if-there-is-a-valid-partition-for-the-array)|💡| 7 | |[Longest Ideal Subsequence](https://leetcode.com/contest/weekly-contest-305/problems/longest-ideal-subsequence)|💡| -------------------------------------------------------------------------------- /Weekly Contest 305/question1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. 5 | A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: 6 | - i < j < k, 7 | - nums[j]-nums[i]==diff 8 | - nums[k]-nums[j]==diff 9 | 10 | Return the number of unique arithmetic triplets. 11 | 12 | Approach: (Brute Force Approach) 13 | 14 | 1. Traverse through all elements in vector one by one 15 | 2. If the difference between two elements equal to 'diff', go to step 3. 16 | 3. Search for element with difference 'diff' from remaining elements. 17 | 4. If found increment the number of triplets found. 18 | 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | int arithmeticTriplets(vector& nums, int diff) 25 | { 26 | int sum=0,flag,l=nums.size(); 27 | for(int i=0;i>& edges, vector& restricted) 24 | { 25 | vector> adj(n); // Adjacency Matrix to represent graph 26 | // Create an undirected graph 27 | for(auto& edge : edges) 28 | { 29 | adj[edge[0]].push_back(edge[1]); 30 | adj[edge[1]].push_back(edge[0]); 31 | } 32 | // Store all restricted nodes in a set for fast lookup 33 | unordered_set restrictedSet(restricted.begin(), restricted.end()); 34 | // Keep track of Visited nodes 35 | vector visited(n, false); 36 | // Queue to perform BFS 37 | queue que; 38 | int source = 0; 39 | que.push(source); // Add first element source into our queue 40 | int count = 0; // To keep track of all reachable unrestricted nodes 41 | 42 | // Perform BFS 43 | while(que.size()) 44 | { 45 | int node = que.front(); que.pop(); 46 | visited[node] = true; //Mark current node as visited 47 | // If current node is not restricted then only move further 48 | if(restrictedSet.find(node) == restrictedSet.end()) 49 | { 50 | count++; // Increment count of reachable nodes 51 | 52 | // Iterate over all adjacent nodes and add them into queue 53 | // And only insert if it is not visited and unrestricted 54 | for(auto& adjacentNode : adj[node]) 55 | { 56 | if(!visited[adjacentNode] && restrictedSet.find(adjacentNode) == restrictedSet.end()) 57 | { 58 | que.push(adjacentNode); 59 | } 60 | } 61 | } 62 | } 63 | 64 | return count; 65 | } 66 | }; 67 | 68 | /* 69 | Time Complexity: O(n*log(n))) 70 | Space Complexity: O(n) 71 | */ -------------------------------------------------------------------------------- /Weekly Contest 305/question3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. 5 | 6 | We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: 7 | 1. The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good. 8 | 2. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good. 9 | 3. The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elementsis 1. 10 | For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not. 11 | 12 | Return true if the array has at least one valid partition. Otherwise, return false. 13 | 14 | Approach: (Dynamic Programming) 15 | 16 | 1. For the current element, dp[i] indicates if the array can be partitioned up to that element. 17 | 2. For element dp[i + 1], the partition is valid if: 18 | i. dp[i - 1] == true and we have a partition of two elements, or, 19 | ii. dp[i - 2] == true and we have a partition of three elements. 20 | 3. Since we only need to look 3 elements back, we can use a rolling dp array for constant memory complexity. 21 | 22 | */ 23 | class Solution { 24 | 25 | public: 26 | bool validPartition(vector& nums) 27 | { 28 | bool dp[4]={true, false, n[0] == n[1], false}; 29 | for (int i=2; i answerQueries(vector& nums, vector& queries) 30 | { 31 | int n = queries.size(); 32 | // sort the vector, because order will not matter 33 | sort(nums.begin(), nums.end()); 34 | // find the prefix sum 35 | for(int i = 1; i < nums.size(); i++) 36 | { 37 | nums[i] += nums[i - 1]; 38 | } 39 | // res[i] will store the answer of each query 40 | vector res(n); 41 | // solve for each query 42 | for(int i = 0; i < n; i++) 43 | { 44 | // find the upper bound of sum 45 | int idx = upper_bound(nums.begin(), nums.end(), queries[i]) - nums.begin(); 46 | res[i] = idx; 47 | } 48 | return res; 49 | } 50 | }; 51 | 52 | /* 53 | Time Complexity: O(n*log(n)) 54 | Space Complexity: O(1) 55 | */ -------------------------------------------------------------------------------- /Weekly Contest 308/question2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a string s, which contains stars *. 5 | In one operation, you can: 6 | - Choose a star in s. 7 | - Remove the closest non-star character to its left, as well as remove the star itself. 8 | 9 | Return the string after all stars have been removed. 10 | 11 | Example: 12 | 13 | Input: s = "leet**cod*e" 14 | Output: "lecoe" 15 | Explanation: Performing the removals from left to right: 16 | - The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e". 17 | - The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e". 18 | - The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe". 19 | There are no more stars, so we return "lecoe". 20 | 21 | Approach (Stack Simulation) : 22 | 23 | 1. Use a stack to simulate the process of removing stars from a string. 24 | 2. For each character 'c' in string 's', do the following operations, 25 | 3. If c =='*', pop the last element from the stack, to simulate the deletion. 26 | 4. If c != '*', push the element to the stack. 27 | 5. Finally return the string with stars removed. 28 | 29 | */ 30 | 31 | class Solution 32 | { 33 | public: 34 | string removeStars(string s) 35 | { 36 | string res; 37 | for (char c : s) 38 | { 39 | if (c == '*') // Removing element from the stack 40 | { 41 | res.pop_back(); 42 | } 43 | else // Inserting elements into stack 44 | { 45 | res += c; 46 | } 47 | } 48 | return res; 49 | } 50 | }; 51 | 52 | /* 53 | Time Complexity: O(n) 54 | Space Complexity: O(n) 55 | */ -------------------------------------------------------------------------------- /Weekly Contest 308/question3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. 5 | - garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. 6 | - Picking up one unit of any type of garbage takes 1 minute. 7 | - You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1. 8 | - There are three garbage trucks in the city, each responsible for picking up one type of garbage. 9 | - Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house. 10 | - Only one garbage truck may be used at any given moment. 11 | - While one truck is driving or picking up garbage, the other two trucks cannot do anything. 12 | 13 | Return the minimum number of minutes needed to pick up all the garbage. 14 | 15 | Example: 16 | 17 | Input: garbage = ["G","P","GP","GG"], travel = [2,4,3] 18 | Output: 21 19 | Explanation: 20 | The paper garbage truck: 21 | 1. Travels from house 0 to house 1 22 | 2. Collects the paper garbage at house 1 23 | 3. Travels from house 1 to house 2 24 | 4. Collects the paper garbage at house 2 25 | Altogether, it takes 8 minutes to pick up all the paper garbage. 26 | The glass garbage truck: 27 | 1. Collects the glass garbage at house 0 28 | 2. Travels from house 0 to house 1 29 | 3. Travels from house 1 to house 2 30 | 4. Collects the glass garbage at house 2 31 | 5. Travels from house 2 to house 3 32 | 6. Collects the glass garbage at house 3 33 | Altogether, it takes 13 minutes to pick up all the glass garbage. 34 | Since there is no metal garbage, we do not need to consider the metal garbage truck. 35 | Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage. 36 | 37 | Approach (Prefix Sum): 38 | 39 | 1. Firstly sum up the amount of gabages in total. 40 | 2. Second find up the last position for each type. 41 | 3. Calculate the prefix sum array of the travel distance. 42 | 4. Sum up the distance for each type of garbage. 43 | 5. Finally return the minimum time required. 44 | 45 | */ 46 | 47 | class Solution 48 | { 49 | public: 50 | int garbageCollection(vector& garbage, vector& travel) 51 | { 52 | int last[128] = {}, res = 0; 53 | for (int i = 0; i < garbage.size(); ++i) 54 | { 55 | res += garbage[i].size(); 56 | for (char c : garbage[i]) 57 | last[c] = i; 58 | } 59 | for (int j = 1; j < travel.size(); ++j) 60 | { 61 | travel[j] += travel[j - 1]; 62 | } 63 | for (int c : "PGM") 64 | { 65 | if (last[c]) 66 | { 67 | res += travel[last[c] - 1]; 68 | } 69 | return res; 70 | } 71 | } 72 | }; 73 | 74 | /* 75 | Time Complexity: O(n) 76 | Space Complexity: O(1) 77 | */ -------------------------------------------------------------------------------- /Weekly Contest 308/question4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | 4 | You are given a positive integer k. You are also given: 5 | - A 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and 6 | - A 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. 7 | 8 | The two arrays contain integers from 1 to k. 9 | You have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0. 10 | 11 | The matrix should also satisfy the following conditions: 12 | - The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1. 13 | - The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1. 14 | 15 | Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix. 16 | 17 | Example: 18 | 19 | Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]] 20 | Output: [[3,0,0],[0,0,1],[0,2,0]] 21 | Explanation: 22 | The row conditions are the following: 23 | - Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix. 24 | - Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix. 25 | The column conditions are the following: 26 | - Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix. 27 | - Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix. 28 | 29 | 30 | Approach (Topological Sorting and Kahn's Algorithm): 31 | 32 | 1. Create graph for both 'rowConditions' and 'colConditions'. 33 | 2. Check if both graphs are acyclic using Kahn's Algorithm. If either graph is cyclic, then return []. 34 | 3. Kahn's Algorithm will give topological sorting (topo1 and topo2) for both graphs. 35 | 4. 'topo1' will give position of element according to row. 36 | 5. 'topo2' will give position of element according to column. 37 | 6. Return Matrix 'ans' if satisfies given conditions else return []. 38 | 39 | */ 40 | 41 | class graph 42 | { 43 | int n; 44 | vector> adj; 45 | public: 46 | graph(int n) 47 | { 48 | this->n = n; 49 | adj.resize(n); 50 | } 51 | void add_edge(int u, int v) 52 | { 53 | adj[u].push_back(v); 54 | } 55 | void make_adj(vector> arr) 56 | { 57 | for(auto& x:arr) 58 | { 59 | this->add_edge(x[0], x[1]); 60 | } 61 | } 62 | 63 | vector kahn_algo() 64 | { 65 | vector indeg(this->n, 0); 66 | queue q; 67 | vector topo; 68 | 69 | for(auto &x : this->adj) 70 | { 71 | for(int &y: x) 72 | { 73 | indeg[y]++; 74 | } 75 | } 76 | 77 | for(int i=1; in; i++) 78 | { 79 | if(indeg[i] == 0) 80 | { 81 | q.push(i); 82 | } 83 | } 84 | 85 | while(!q.empty()) 86 | { 87 | int cur = q.front(); 88 | q.pop(); 89 | 90 | topo.push_back(cur); 91 | 92 | for(auto& x : this->adj[cur]) 93 | { 94 | indeg[x]--; 95 | if(indeg[x] == 0) 96 | { 97 | q.push(x); 98 | } 99 | } 100 | } 101 | return topo; 102 | } 103 | }; 104 | 105 | class Solution 106 | { 107 | public: 108 | vector> solve(int& n, vector& topo1, vector& topo2) 109 | { 110 | if(topo1.size() != n || topo2.size() != n) 111 | { 112 | return {}; 113 | } 114 | vector> ans(n, vector(n, 0)); 115 | unordered_map mp; 116 | for(int i=0; i> buildMatrix(int n, vector>& rowConditions, vector>& colConditions) 128 | { 129 | graph g1(n+1), g2(n+1); 130 | g1.make_adj(rowConditions); 131 | g2.make_adj(colConditions); 132 | vector topo1 = g1.kahn_algo(), topo2 = g2.kahn_algo(); 133 | return solve(n, topo1, topo2); 134 | } 135 | }; 136 | 137 | /* 138 | Time Complexity: O(n^2) 139 | Space Complexity: O(n^2) 140 | */ -------------------------------------------------------------------------------- /Weekly Contest 321/Append Characters to String to Make Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | /* 5 | Two pointer approach. Compare characters in both the strings one by one and if they matches increment 6 | the counter and return the ans by subtracting it from other string size. 7 | 8 | TIME COMPLEXITY : O(N) 9 | SPACE COMPLEXITY : O(1) 10 | */ 11 | int appendCharacters(string s, string t) 12 | { 13 | int j=0; 14 | 15 | for(int i=0; i& nums, int k) 19 | { 20 | int n = nums.size(); 21 | unordered_mapmp; 22 | mp[0]=1; 23 | 24 | bool includeK = false; 25 | int balance = 0; 26 | 27 | int ans = 0; 28 | for (int i = 0; i < n; i++) 29 | { 30 | if (nums[i] < k) 31 | balance--; 32 | else if (nums[i] > k) 33 | balance++; 34 | else // nums[i] == k 35 | includeK = true; 36 | 37 | if (includeK) 38 | ans += mp[balance] + mp[balance - 1]; 39 | 40 | else 41 | mp[balance]++; 42 | } 43 | return ans; 44 | } 45 | 46 | }; -------------------------------------------------------------------------------- /Weekly Contest 321/Pivot Integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Input: n = 8 3 | Output: 6 4 | Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. 5 | */ 6 | class Solution { 7 | public: 8 | int pivotInteger(int n) 9 | { 10 | //use prefix sum approach 11 | vector left(n+1); 12 | vector right(n+1); 13 | 14 | int total = 0; 15 | 16 | for(int i=1;i<=n;i++) 17 | { 18 | total += i; 19 | } 20 | //total comes out to be 36 21 | 22 | left[0] = 0; 23 | right[0] = 0; 24 | 25 | // during the loop runs, array status of left and right are : 26 | // left : 0 1 3 6 10 15 21 28 36 27 | // right : 0 36 35 33 30 26 21 15 8 28 | // clearly, 21 at idx 6 in both the arrays matches. Hence return 6. 29 | 30 | for(int i=1;i<=n;i++) 31 | { 32 | left[i] = i + left[i-1]; 33 | right[i] = total - left[i-1]; 34 | 35 | if(left[i]==right[i]) return i; 36 | } 37 | 38 | //if no element matches in both the arrays return -1 39 | return -1; 40 | } 41 | }; 42 | 43 | // TIME COMPLEXITY : O(N) 44 | // SPACE COMPLEXITY : O(N) ; using two vectors left and right. -------------------------------------------------------------------------------- /Weekly Contest 321/README.md: -------------------------------------------------------------------------------- 1 | |S.NO.|PROBLEMS| 2 | |---|---| 3 | |1.|[Find the Pivot Integer](https://leetcode.com/contest/weekly-contest-321/problems/find-the-pivot-integer/) 4 | |2.|[Append Characters to String to Make Subsequence](https://leetcode.com/contest/weekly-contest-321/problems/append-characters-to-string-to-make-subsequence/) 5 | |3.|[Remove Nodes From Linked List](https://leetcode.com/contest/weekly-contest-321/problems/remove-nodes-from-linked-list/) 6 | |4.|[Count Subarrays With Median K](https://leetcode.com/contest/weekly-contest-321/problems/count-subarrays-with-median-k/) -------------------------------------------------------------------------------- /Weekly Contest 321/Remove Nodes From Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNodes(ListNode* head) 4 | { 5 | if(head == NULL || head->next == NULL) return head; 6 | 7 | ListNode* myNext= removeNodes(head->next); 8 | if(myNext->val > head->val) return myNext; 9 | 10 | head->next = myNext; 11 | 12 | return head; 13 | } 14 | }; --------------------------------------------------------------------------------