title
stringlengths 3
77
| title_slug
stringlengths 3
77
| question_content
stringlengths 38
1.55k
β | tag
stringclasses 707
values | level
stringclasses 3
values | question_hints
stringlengths 19
3.98k
β | view_count
int64 8
630k
| vote_count
int64 5
10.4k
| content
stringlengths 0
43.9k
| __index_level_0__
int64 0
109k
|
---|---|---|---|---|---|---|---|---|---|
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 1,222 | 11 | Hey LeetCode Admin, kindly check my solution (pasted below). How can this simple O(m * n) \'DP + answer generation\' solution get TLE!!! Why do you not specify the Time Limit for the problems along with the test case limits. In my humble opinion, my O(m * n) solution is well under the general Time Limit we have everywhere, which is ~10^8 operations. \n\n```\nclass Solution {\npublic:\n vector<int> maximumBobPoints(int n, vector<int>& a) {\n int m = 12;\n vector<int> b(m);\n vector<vector<int>> dp(m, vector<int>(n + 1));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j <= n; j++) {\n if (!i) {\n dp[i][j] = 0;\n continue;\n }\n dp[i][j] = dp[i - 1][j];\n if (j > a[i]) {\n dp[i][j] = max(dp[i][j], dp[i - 1][j - a[i] - 1] + i);\n }\n }\n }\n for (int i = m - 1, j = n; i >= 0; i--) {\n if (i == 0) {\n b[0] = j;\n break;\n }\n if (dp[i][j] != dp[i - 1][j]) {\n b[i] = a[i] + 1;\n j -= b[i];\n }\n }\n return b;\n }\n};\n```\n\nI remember this happened to me earlier in some contest as well. In that case, just using 1D DP array, instead of 2D DP table, passed it (basically, I did DP space optimization by reversing the order of inner loop) although theoritically, Time Complexity was still the same. This time it was not possible because I had to generate the answer as well.\n\nAfter that contest, I felt so frustrated that I stopped giving the contests here. Now after so long, I felt healed and I gave one yesterday and thought I would now resume giving these contests regularly for fun, (yes! I do enjoy these contests!), but again the same issue has occured :(\n\nI request you to please look into this. If you think my solution should\'ve passed the tests, then please don\'t affect my ratings, and, I demand 1000 LC coins to compensate for the time waste + frustration caused because of it. If you still don\'t think my solution should\'ve passed, please provide a valid reason for it, and how a participant would know about it beforehand (by mentioning the time limit in ms, or whatever).\n\nIf no action taken, I could NEVER take part in the contests here again (yes, it hurts) :(\n\n**UPDATE**\nSome are commenting/posting that we had to do some optimizations to get AC(using static array, top-down approach). Personally that\'s not my style of doing DP problems (unless it\'s very hard/time-taking for me to implement bottom up). Bottom up feels more elegant to me. Secondly, I can show many of my submissions where I got AC with 2D vector and bottom-up approach on DP problems having similar constraints. The recent one is from yesterday\'s biweekly contest itself: .. Following is my AC submission for the :\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string s, int m, int k) {\n int n = s.size(), inf = n + 1;\n vector<vector<int>> dp(n + 1, vector<int>(m + 1, inf));\n for (int i = 0; i <= n; i++) {\n for (int j = 0; j <= m; j++) {\n if (i == 0) {\n dp[i][j] = 0;\n continue;\n }\n dp[i][j] = min(j? dp[max(0, i - k)][j - 1]: inf, dp[i - 1][j] + (s[i - 1] - \'0\'));\n }\n }\n return dp[n][m];\n }\n};\n``` | 108,566 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 2,189 | 26 | **Intuition:** I observed that since there are 12 rounds, there can be at max 2^12 permutations on either bob wins *ith* round or not. Since 2^12 isnt that big of a number that could give TLE, we can generate all possible sequences. Also we can optimally win a round from Alice by just having 1 extra arrow in the same section as compared to Alice.\nFor each possible sequence, we see if this sequence has a greater score, if yes then we update the answer.\n\n```\nclass Solution {\npublic:\n int maxscore; \n vector<int> ans;\n \n void helper(vector<int> &bob, int i, vector<int>& alice, int remarrows, int score)\n {\n if(i == -1 or remarrows <= 0)\n {\n if(score >= maxscore)\n {\n maxscore = score; \n ans = bob; \n }\n return; \n }\n \n helper(bob, i-1, alice, remarrows, score);\n if(remarrows > alice[i])\n {\n bob[i] = alice[i] + 1;\n remarrows -= (alice[i] + 1);\n score += i; \n helper(bob, i-1, alice, remarrows, score);\n bob[i] = 0;\n } \n }\n \n vector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) {\n vector<int> bob(12, 0);\n maxscore = INT_MIN; \n helper(bob, 11, aliceArrows, numArrows, 0);\n \n int arrows_used = 0; \n for(int a : ans)\n arrows_used += a; \n if(arrows_used < numArrows)\n ans[0] += (numArrows - arrows_used);\n return ans; \n }\n};\n``` | 108,567 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 982 | 16 | We just need to search for the best score. Since we have only 11 sections (we can ignore zero), thare are 2 ^ 11 = 2048 total combinations.\n\n**C++**\nWe use `mask` to indicate when Bob shoots into a section. We update `max_mask` when we achieve a better score.\n\nFor Bob, it only makes sense to shoot `aliceArrows[k] + 1` arrows to section `k`. Therefore, we can restore the score by only looking at the mask.\n\n```cpp\nint max_points = 0, max_mask = 0;\nvoid dfs(int k, int numArrows, vector<int>& aliceArrows, int points, int mask) {\n if (numArrows >= 0 && points > max_points) {\n max_points = points;\n max_mask = mask;\n }\n if (k > 0) {\n dfs(k - 1, numArrows - aliceArrows[k] - 1, aliceArrows, points + k, mask + (1 << k));\n dfs(k - 1, numArrows, aliceArrows, points, mask);\n }\n}\nvector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) {\n vector<int> res(12);\n dfs(11, numArrows, aliceArrows, 0, 0);\n for (int k = 11; k > 0; --k) {\n if (max_mask & (1 << k)) {\n res[k] = aliceArrows[k] + 1;\n numArrows -= aliceArrows[k] + 1;\n }\n }\n res[0] = numArrows;\n return res;\n}\n``` | 108,568 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 1,061 | 8 | **Identify Type of dp**->\nLogic is similar to Knapsack where you are given capacity and Array which can be treated as weight array.\n\n**Goal** -> you need to maximize profit ,where profit will be index if you pick weight at index.\n\n**Approach**->\n* First Compute Dp Array \n```\n\t\tfirst choice is\n \t\t\t\tYou can only pick weight at index, when weight[index]<Your capacity\n\t\t\t\tso, when you pick then your capacity will be capacity-(weight[index]+1).\n\n\t\tother choice is not pick and decrement index\n```\n* Compute Result array from Dp array by traversing from end similar as finding longest increasing subsequence array.\n\n*Advice*\n* Implement first recursive solution\n* Identify Variable changing in recursion\n* Convert it to dp by storing every recursion call in memory of dimension same as No of variables changing in recursion.\n```\nclass Solution {\n public:\n vector<vector<int>> dp;\n vector<int> res;\n int recur(int cap, vector<int>& aliceArrows, int ind) {\n // base case when bob firing capacity is zero or index becomes zero\n if (ind == 0 || cap == 0) return 0;\n int put = 0;\n\n // if element already in DP\n if (dp[ind][cap] != -1) {\n return dp[ind][cap];\n }\n\n if (cap > aliceArrows[ind - 1]) {\n put =\n ind - 1 + recur(cap - aliceArrows[ind - 1] - 1, aliceArrows, ind - 1);\n }\n int nput = recur(cap, aliceArrows, ind - 1);\n\n // if element not in DP then DP[index][capacity] = max(firing At index i,\n // not filing at index i); also if firing then bob will fire\n // aliceArrows[index]+1 to win that location and maximize profit\n return dp[ind][cap] = max(put, nput);\n }\n\n vector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) {\n int bobTotalArrow = numArrows;\n // res to store result, dp will be size 12*bobTotalArrow\n res.clear();\n res.resize(12, 0);\n\n dp.clear();\n dp.resize(13, vector<int>(bobTotalArrow + 1, -1));\n\n recur(bobTotalArrow, aliceArrows, 12);\n\n // computing result array from DP result\n int result = dp[12][bobTotalArrow];\n int total = 0;\n for (int i = 12, j = bobTotalArrow; i > 0 && result > 0; i--) {\n if (result == dp[i - 1][j])\n continue;\n else {\n // This item is included.\n res[i - 1] = aliceArrows[i - 1] + 1;\n result -= (i - 1);\n j -= (aliceArrows[i - 1] + 1);\n total += aliceArrows[i - 1] + 1;\n }\n }\n if (total < bobTotalArrow) {\n res[0] = bobTotalArrow - total;\n }\n return res;\n }\n};\n\n```\n\nTime Complexity \n```\nO(N) because we computing Dp of size 12*bobTotalArrow ,let say bobTotalArrow as N.\n```\nSpace Complexity \n```\nO(N) because we computing Dp of size 12*bobTotalArrow ,let say bobTotalArrow as N. \n``` | 108,569 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 707 | 8 | ```\nclass Solution {\n public int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n maximumBobPoints(numArrows, aliceArrows, 11, 0);\n return result;\n }\n int[] result = new int[12];\n int [] temp = new int[12];\n int max = 0;\n public void maximumBobPoints(int numArrows, int[] aliceArrows, int arrowIndex, int currentScore) {\n if(numArrows<0)\n return;\n\n if(currentScore>=max){\n max = currentScore;\n for(int i=0;i<result.length;i++){\n result[i] = temp[i];\n }\n }\n\n if(numArrows==0)\n return;\n\n temp[arrowIndex] = (arrowIndex==0)?numArrows:(aliceArrows[arrowIndex]+1);\n \n maximumBobPoints(numArrows-temp[arrowIndex], aliceArrows, arrowIndex-1, currentScore + arrowIndex);\n \n temp[arrowIndex] = (arrowIndex==0)?numArrows:0;\n maximumBobPoints(numArrows-temp[arrowIndex], aliceArrows, arrowIndex-1, currentScore);\n temp[arrowIndex] = 0;\n\n }\n} | 108,570 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 416 | 8 | Because there are only 12 targets, we can produce any possible hit or skip combinations (2 ^ 12).\nIf the ith bit in our bitmask is set, Bob will strike the target, and he must hit at least alicearrows[i] + 1 arrows on the ith target to maximise his score.\nSo, using exactly numArrows arrows, we\'ll try to determine the maximum score Bob can achieve for the 2 ^ 12 combinations.\n\nTime complexity: O((2 ^ 12) * 12)\nSpace complexity: O(1)\n```\nclass Solution {\npublic:\n vector<int> maximumBobPoints(int numarrows, vector<int>& alicearrows) {\n \n int n(1<<12), maxscore(0);\n vector<int> res;\n \n for(int mask = 1; mask < n; mask++) {\n \n int arrowsleft(numarrows),score(0);\n vector<int> bob(12,0);\n\t\t\t\n // checking for all the targets\n for(int i = 0; i <= 11; i++) {\n\t\t\t//for checking the bit is set or not at that mask\n if(mask & (1 << i)) { \n\t\t\t\t\n int arrowsneeded = alicearrows[i] + 1;\n\t\t\t\t\t// If the number of arrows required to reach the current target\n\t\t\t\t\t// exceeds the number of arrows available,\n\t\t\t\t\t// then\xA0this combination will not result in a right answer, so we will break.\n if(arrowsneeded > arrowsleft) { \n score = -1;\n break;\n }\n score += i;\n\t\t\t\t\t// bob[i] is arrows Bob must hit to achieve this score\n bob[i] = arrowsneeded;\n arrowsleft -= arrowsneeded; \n }\n }\n \n if(score > maxscore) {\n\t\t\t// in case any arrows are left after hitting targets, we can add it to any target\n if(arrowsleft) bob[0] += arrowsleft;\n maxscore = score;\n res = bob;\n } \n }\n \n return res;\n }\n};\n```\n | 108,578 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 254 | 5 | \n\n# Code\n```\nclass Solution {\n\n int maxScore = 0;\n int[] maxStore = null;\n\n // I m starting from index 0 \n public int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n helper(numArrows , 0 , 0 , aliceArrows , new int[12]);\n return maxStore;\n }\n // These are base conditions \n // If numArrows reduces to 0 that means we have used all the arrows \n // and also when index i reaches to 12 means you have completed all the 12 rounds \n \n // At Base condition \n // check if score > maxScore if yes update maxScore and store this storeArray\n // into maxStore because we want to return this maxStore array.\n\n public void helper(int numArrows , int i , int score , int[] arr , int[] store){\n if (i == 12 || numArrows == 0) {\n if (score > maxScore) {\n maxScore = score; // storing the maxScore\n maxStore = store.clone(); // storing the maxStore array \n maxStore[0] += numArrows;\n }\n return;\n }\n int val = arr[i];\n if(numArrows - (val + 1) >= 0){ \n store[i] = val + 1; \n helper(numArrows - (val + 1) , i + 1 , score + i , arr , store);\n store[i] = 0; \n }\n helper(numArrows , i + 1 , score , arr , store);\n }\n}\n \n \n``` | 108,580 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 306 | 5 | # Code : \n\n```\nclass Solution {\n vector<int> bobArrows;\n int maxScore = 0;\n \n void generate(vector<int>& aliceArrows, vector<int>& arrows, int numArrows, int score, int idx, int n) {\n if(idx == n) {\n if(score > maxScore) {\n bobArrows = arrows;\n bobArrows[0] += numArrows;\n maxScore = score;\n }\n return;\n }\n \n // Alice win this round\n arrows.push_back(0);\n generate(aliceArrows, arrows, numArrows, score, idx+1, n);\n arrows.pop_back();\n \n // Bob win this round\n if(aliceArrows[idx] + 1 <= numArrows) {\n arrows.push_back(aliceArrows[idx] + 1);\n generate(aliceArrows, arrows, numArrows - aliceArrows[idx] - 1, score + idx, idx+1, n);\n arrows.pop_back(); \n }\n }\npublic:\n vector<int> maximumBobPoints(int numArrows, vector<int>& aliceArrows) {\n int n = aliceArrows.size();\n vector<int> arrows;\n generate(aliceArrows, arrows, numArrows, 0, 0, n);\n return bobArrows;\n }\n};\n```\n\n**Complexity :**\n\n* Time : `O(N * 2^N)`, N = 12\n* Space : `O(N)`\n\n***If you find this solution helpful, do give it a like :)*** | 108,585 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 3,649 | 53 | #### Prerequisite: Construction of segment tree\nContruction and updating characters in segment tree is easy ( standard problem ), but keeping the record of longest substring with one repeating is hard. To do this, we will need 5 parameter.\nlet a segement be from index `l` to `h`, then the five parameters are:\n1. longest substring in segment `l` to `h`\n1. leftmost character of segment `l` to `h`\n1. rightmost character of segment `l` to `h`\n1. index of rightend of contiguous characters of segment `l` to `h` from left side \n1. index of leftend of contiguous characters of segment `l` to `h` from right side\n\n### For example,\nfor a string `s` = "**abssefgth**", we have segement from` l = 2` to` h = 8` ( **ssefgth** ). Then the five parameter are:\n1. longest substring in segment is **2**\n1. leftmost character of segment is **s**\n1. rightmost character of segment is **h**\n1. index of rightend of contiguous characters of segment is **3** ( "ss" => 2 to 3)\n1. index of rightend of contiguous characters of segment is **8** ( "h" => 8 to 8)\n\nTo store these values, following arrays are defined:\n* `nums` to store the longest substring in segment\n* `lc` to store leftmost character of segment \n* `rc` to store rightmost character of segment `l` to `h` \n* `left` to store index of rightend of contiguous characters of segment `l` to `h` from **left** side.\n* `right` to store index of contiguous characters of segment `l` to `h` from **right** side\n\n**Idea to find longest substring in segment**:\nAssuming we have done calculation for both *left* and *right* child of a segment, calculation for *parent* is as follows:\nfor example, *parent* = "**smmh**", then the *leftchild* = "**sm**", *rightchild* = "**mh**",\nthe index of segment from `l` to `h` is `in` and left child segment is from `l` to `m` and right child segment is from `m+1` to `h` , where ` m = (l+h)/2`\n* leftmost character of segment is the leftmost character of left child.\n* rightmost character of segment is the rightmost character of right child.\n* Atfirst, ``left[in] = left[left_child]`` and ``right[in] = right[left_child]``, where *leftchild* and *rightchild* are the index of segment of left and right child\n* Now suppose, if rightmost char of left child == leftmost char of right child and also left[left_child] == m (end of segment of left child), then new left[in] = left[right_child]. similarly, if right[right_child] == m+1 (start of the segement of right child), the new value right[in] = right[left_child]\n* Now, longest substring can be, from `l` to `left[in]`, or from `right[in]` to `h`, or from `right[left_child]` to `left[right_child]` if rightmost char of left child == leftmost char of right child. Or it can be max of longest substring of *leftchild* and *rightchild*.\n\nRest of the operations are given in the code below:\n```\nclass sgtree{\npublic:\n vector<int> nums,left,right;\n vector<char> lc,rc; int n;\n sgtree(string &s){\n n = s.size();\n nums = vector<int>(4*n+5,0);\n left = vector<int>(4*n+5,-1);\n right = vector<int>(4*n+5,-1);\n lc = vector<char>(4*n+5,\'*\');\n rc = vector<char>(4*n+5,\'*\');\n build(0,s,0,n-1);\n }\n void build(int in, string &s,int l,int h){\n if(l>h) return;\n if(l==h){\n lc[in] = rc[in] = s[l];\n left[in] = l,right[in] = l; nums[in] = 1;\n return;\n }\n int m = (l+h)/2;\n build(2*in+1,s,l,m); build(2*in+2,s,m+1,h); \n merge(in,l,m,h);\n }\n void merge(int in,int l,int m,int h){\n int lt = in*2+1, rt = in*2+2, max_ = 0;\n lc[in] = lc[lt]; rc[in] = rc[rt];\n left[in] = left[lt];\n right[in] = right[rt]; \n if(rc[lt]==lc[rt]){ \n if(left[lt]==m) left[in] = left[rt];\n }\n if(lc[rt]==rc[lt]){ \n if(right[rt]==m+1) right[in] = right[lt]; \n }\n if(rc[lt]==lc[rt]) max_ = left[rt]-right[lt]+1;\n \n max_ = max(max_,left[in]-l+1);\n max_ = max(max_,h-right[in]+1);\n nums[in] = max(max_,max(nums[lt],nums[rt]));\n }\n int update(int in,int l,int h,int j,char ch){\n if(l>h) return 0;\n if(l==h){\n lc[in] = rc[in] = ch;\n left[in] = l,right[in] = l; nums[in] = 1;\n return 1;\n }\n int m = (l+h)/2;\n if(j>=l && j<=m) update(2*in+1,l,m,j,ch);\n else update(2*in+2,m+1,h,j,ch); \n merge(in,l,m,h);\n return nums[in];\n }\n};\nclass Solution {\npublic:\n vector<int> longestRepeating(string s, string q, vector<int>& in) {\n sgtree node(s);\n vector<int> re(q.size(),0);\n for(int i = 0; i<q.size();++i){\n re[i] = node.update(0,0,s.size()-1,in[i],q[i]);\n }\n return re;\n }\n};\n```\n**Time: O(nlogn)**\n***Upvote*** if it helps | 108,609 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,944 | 20 | Basically, we store the same-character intervals as pairs in an ordered set. (For python you can use SortedList).\n\nOn an update, we split the interval containing that character, and then try to merge the neighboring intervals, keeping track of the length of the frequencies in an ordered map (or multiset, but multiset is much slower). \n\nThe time complexity per query is O(log N).\nThe total time complexity is O(N log N + Q log N).\nSpace complexity is O(N).\n\n```\nclass Solution {\npublic:\n using iv = array<int, 3>;\n // each interval will track [L, R, char]\n\n set<iv> ivals; // intervals\n map<int,int> lens; // length frequencies\n\n void cnt(int l) {\n // cnt(x) adds a length x\n // cnt(-x) removes a length x\n int m = (l<0) ? -1 : 1;\n l = abs(l);\n if ( (lens[l] += m) <= 0 )\n lens.erase(l);\n }\n void add(iv t) { // add new interval\n ivals.insert(t);\n cnt(t[1] - t[0] + 1);\n }\n void del(iv t) { // erase existing interval\n ivals.erase(t);\n cnt( -(t[1]-t[0]+1) );\n }\n\n inline set<iv>::iterator split(int i, iv m, char ch) {\n // split the interval containing index i\n // into (up to 3) new intervals\n // return the iterator to the new interval containing i\n del(m);\n if (m[0] < i)\n add( {m[0], i-1, m[2]} );\n if (m[1] > i)\n add( {i+1, m[1], m[2]} );\n cnt(1);\n auto res = ivals.insert( {i, i, ch} );\n return res.first; // returns the iterator of the inserted interval\n }\n\n template<class IT>\n void merge(IT it) { // merge `it` with neighboring intervals\n iv m = *it;\n iv l = *prev(it);\n iv r = *next(it);\n\n del(m);\n int nl = m[0], nr = m[1]; // bounds of new interval\n\n if (l[2] == m[2]) // merge with left\n del(l),\n nl = l[0];\n\n if (m[2] == r[2]) // merge with right\n del(r),\n nr = r[1];\n\n add( {nl, nr, m[2]} );\n }\n\n void upd(int i, char ch) { // process a query\n auto it = ivals.lower_bound( {i,i,0} );\n iv m = *it;\n if (m[0] > i) m = *(--it); // take previous \n if (ch == m[2]) return;\n\n // here, m is the interval that contains i\n it = split(i, m, ch);\n merge(it);\n }\n\n vector<int> longestRepeating(string S, string qc, vector<int>& qi) {\n int N = S.size();\n int Q = qc.size();\n S = "?" + S + "?"; // add some dummy characters to eliminate edge cases\n\n int st = 1;\n char prev = S[1];\n add( {0, 0, 0} ); // some dummy intervals to eliminate edge cases\n add( {N+1,N+1,0} ); // significantly easier implementation this way\n for (int i = 2; i <= N+1; ++i) {\n if (S[i] == prev) continue;\n add( {st, i-1, prev} );\n prev = S[i];\n st = i;\n }\n\n vector<int> ans(Q);\n for (int i = 0; i < Q; ++i) {\n upd( qi[i]+1, qc[i] );\n ans[i] = lens.rbegin()->first; // take the max length\n }\n return ans;\n }\n};\n```\n | 108,610 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 2,692 | 41 | #### Quick Refresher\nSegment tree is a logarithmic data structure that operates on a fixed-size array. Leaves of the segment tree are elements of the array, and non-leaf nodes hold some value of interest (sum, average, etc.) for the underlying segments.\n\nSince updates and queries affect log(n) nodes, those operations have O(log n) complexity.\n\nSegment tree can be implemented using an array of `2 * n` size. You will need to know the index of the current node (root\'s index is zero), and left and right positions of the current segment. The left child index is `i * 2 + 1`, and the right child - `i * 2 + 2`. We also adjust left and right positions for the children. When left and right are equal - we\'ve reached the leaf node.\n\n> Note that the size of the array `n` needs to be extended to be the power of 2.\n\n#### Implementation\nIt is quite interesting on how to apply a segment tree to this problem. To find out the longest substring, we need to track repeating characters on the left (prefix), suffix, and max length. This is how the segment tree looks like for `abbbbcc ` string:\n![image]()\n\nFor this problem, we do not need to query longest substring for an arbitrary range - only for the entire string. So, we only need the `st_set` operation. \n\nThe `st_set` first reaches the leaf node and sets the new characer, and then goes back and updates non-leaf nodes using the `merge` function.\n\n**C++**\n```cpp\nstruct node {\n char lc = 0, rc = 0;\n int pref = 0, suf = 0, longest = 0, sz = 1;\n void merge(node &l, node &r) {\n longest = max(l.longest, r.longest);\n if (l.rc == r.lc)\n longest = max(longest, l.suf + r.pref);\n sz = l.sz + r.sz;\n lc = l.lc;\n rc = r.rc;\n pref = l.pref + (l.pref == l.sz && l.lc == r.lc ? r.pref : 0);\n suf = r.suf + (r.suf == r.sz && r.rc == l.rc ? l.suf : 0);\n } \n};\nint st_set(vector<node>& st, int pos, char ch, int i, int l, int r) {\n if (l <= pos && pos <= r) {\n if (l != r) {\n auto m = l + (r - l) / 2, li = 2 * i + 1, ri = 2 * i + 2;\n st_set(st, pos, ch, li, l, m);\n st_set(st, pos, ch, ri, m + 1, r);\n st[i].merge(st[li], st[ri]);\n }\n else {\n st[i].lc = st[i].rc = ch;\n st[i].suf = st[i].pref = st[i].longest = 1;\n }\n }\n return st[i].longest;\n} \nvector<int> longestRepeating(string s, string queryCharacters, vector<int>& queryIndices) {\n vector<int> res;\n int powOf2 = 1, sz = s.size();\n while (powOf2 < sz) \n powOf2 <<= 1;\n vector<node> st(powOf2 * 2);\n for (int i = 0; i < s.size(); ++i)\n st_set(st, i, s[i], 0, 0, powOf2 - 1);\n for (int j = 0; j < queryCharacters.size(); ++j)\n res.push_back(st_set(st, queryIndices[j], queryCharacters[j], 0, 0, powOf2 - 1));\n return res;\n}\n``` | 108,611 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,251 | 13 | ```\nclass Node{\n int max;\n int prefSt,prefEnd;\n int suffSt,suffEnd;\n Node(int max,int prefSt,int prefEnd,int suffSt,int suffEnd){\n this.max=max;\n this.prefSt=prefSt;\n this.prefEnd=prefEnd;\n this.suffSt=suffSt;\n this.suffEnd=suffEnd;\n }\n}\n\nclass SegmentTree{\n Node [] tree;\n StringBuilder s;\n SegmentTree(String s){\n this.s=new StringBuilder();\n this.s.append(s);\n tree=new Node[4*s.length()];\n build(0,0,s.length()-1);\n }\n \n Node merge(Node left,Node right,int tl,int tm,int tr){\n int max=Integer.max(left.max,right.max);\n int prefSt=left.prefSt;\n int prefEnd=left.prefEnd;\n int suffSt=right.suffSt;\n int suffEnd=right.suffEnd;\n \n if(s.charAt(tm)==s.charAt(tm+1)){\n max=Integer.max(max,right.prefEnd-left.suffSt+1);\n if(left.prefEnd-left.prefSt+1==tm-tl+1)\n prefEnd=right.prefEnd;\n if(right.suffEnd-right.suffSt+1==tr-tm)\n suffSt=left.suffSt;\n }\n \n return new Node(max,prefSt,prefEnd,suffSt,suffEnd);\n }\n \n void build(int pos,int tl,int tr){\n if(tl==tr){\n tree[pos]=new Node(1,tl,tl,tr,tr);\n }else{\n int tm=tl+(tr-tl)/2;\n build(2*pos+1,tl,tm);\n build(2*pos+2,tm+1,tr);\n \n tree[pos]=merge(tree[2*pos+1],tree[2*pos+2],tl,tm,tr);\n }\n }\n \n void update(int pos,int tl,int tr,int idx,char ch){\n if(tl==tr){\n tree[pos]=new Node(1,tl,tl,tr,tr);\n s.setCharAt(idx,ch);\n // System.out.println(pos);\n }\n else{\n int tm=tl+(tr-tl)/2;\n if(idx<=tm)\n update(2*pos+1,tl,tm,idx,ch);\n else\n update(2*pos+2,tm+1,tr,idx,ch);\n tree[pos]=merge(tree[2*pos+1],tree[2*pos+2],tl,tm,tr);\n }\n }\n}\n\nclass Solution {\n public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) {\n int k=queryIndices.length;\n SegmentTree tree=new SegmentTree(s);\n for(int i=0;i<k;i++){\n tree.update(0,0,s.length()-1,queryIndices[i],queryCharacters.charAt(i));\n queryIndices[i]=tree.tree[0].max;\n }\n return queryIndices;\n }\n}\n``` | 108,612 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 2,323 | 29 | High level idea:\n1. Store the span of each letter in a TreeMap\n2. Also use a second TreeMap to record the frequency of each span length\n2. On each query, update both TreeMaps\n```\n public int[] longestRepeating(String s, String queryCharacters, int[] queryIndices) {\n char[] arr = s.toCharArray();\n int m = arr.length, n = queryIndices.length;\n int[] output = new int[n];\n TreeMap<Integer, Integer> lengths = new TreeMap<>(), spans = new TreeMap<>();\n // Stores spans of each letter in the TreeMap\n for (int i = 0, j = 1; j <= m; j++) if (j == m || arr[i] != arr[j]) {\n lengths.put(j - i, lengths.getOrDefault(j - i, 0) + 1);\n spans.put(i, j - 1);\n i = j;\n }\n // Update spans on each query and find the max length\n for (int i = 0; i < queryIndices.length; i++) {\n int j = queryIndices[i];\n if (arr[j] != queryCharacters.charAt(i)) {\n // Remove the spans that has the character to be updated\n int l = spans.floorKey(j), r = spans.remove(l), length = r - l + 1;\n if (lengths.get(length) == 1) lengths.remove(length);\n else lengths.put(length, lengths.get(length) - 1);\n // if the character is going to be different from its neighbors, break the span\n if (l < j) {\n spans.put(l, j - 1);\n lengths.put(j - l, lengths.getOrDefault(j - l, 0) + 1);\n }\n if (r > j) {\n spans.put(j + 1, r);\n lengths.put(r - j, lengths.getOrDefault(r - j, 0) + 1);\n }\n arr[j] = queryCharacters.charAt(i);\n l = j;\n r = j;\n // if the character is going to be same as its neighbors, merge the spans\n if (j > 0 && arr[j] == arr[j - 1]) {\n l = spans.floorKey(j);\n length = spans.remove(l) - l + 1;\n if (lengths.get(length) == 1) lengths.remove(length);\n else lengths.put(length, lengths.get(length) - 1);\n }\n if (j < m - 1 && arr[j] == arr[j + 1]) {\n int key = spans.ceilingKey(j);\n r = spans.remove(key);\n length = r - key + 1;\n if (lengths.get(length) == 1) lengths.remove(length);\n else lengths.put(length, lengths.get(length) - 1);\n }\n spans.put(l, r);\n lengths.put(r - l + 1, lengths.getOrDefault(r - l + 1, 0) + 1);\n }\n output[i] = lengths.lastKey();\n }\n return output;\n }\n```\nTime complexity: O(nlogn)\nSpace complexity: O(n) | 108,613 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,039 | 9 | If anyone is struggling with getting TLE using `Python` + `Segment Tree`. I think this might help.\n\nThe basic idea is the same. We need to keep tracking the 6 values in each segments.\n\n1. longest repating character (noted as `lc`)\n2. length of the above character (noted as `ll`)\n3. longest repeating prefix character (noted as `pc`)\n4. length of the above character (noted as `pl`)\n5. longest repeating suffix character (noted as `sc`)\n6. length of the above character (noted as `sl`)\n\nBelow is my code. It\'s not very elegant, but can pass the questions without getting TLE.\n\n```\nclass SegmentTree:\n def __init__(self, data):\n self.nodes = [None] * 4 * len(data) #node: (value, left_node_index, right_node_index)\n self.data = data\n self._build_tree(0, 0, len(data)-1)\n\n def _left(self, index):\n return (index + 1) * 2 - 1\n\n def _right(self, index):\n return (index + 1) * 2\n\n def _build_tree(self, node_index, left_data_index, right_data_index):\n value = None\n if left_data_index == right_data_index:\n # (longest c, longest len, prefix c, prefix len, suffix c, suffix len)\n value = (\n self.data[left_data_index],\n 1,\n self.data[left_data_index],\n 1,\n self.data[left_data_index],\n 1)\n else:\n left_node_index = self._left(node_index)\n right_node_index = self._right(node_index)\n\n mid_data_index = (left_data_index + right_data_index) // 2\n (left_lc, left_ll, left_pc, left_pl, left_sc, left_sl) = self._build_tree(left_node_index, left_data_index, mid_data_index)\n (right_lc, right_ll, right_pc, right_pl, right_sc, right_sl) = self._build_tree(right_node_index, mid_data_index + 1, right_data_index)\n \n lc = ll = None\n if left_ll > right_ll:\n lc = left_lc\n ll = left_ll\n else:\n lc = right_lc\n ll = right_ll\n if left_sc == right_pc and left_sl + right_pl > ll:\n ll = left_sl + right_pl\n lc = left_sc\n\n pc = left_pc\n pl = left_pl\n if left_pl == (mid_data_index - left_data_index + 1) and left_pc == right_pc:\n pl = left_pl + right_pl\n\n sc = right_sc\n sl = right_sl\n if right_sl == (right_data_index - mid_data_index) and left_sc == right_sc:\n sl = left_sl + right_sl\n \n value = (lc, ll, pc, pl, sc, sl)\n\n self.nodes[node_index] = value\n return value\n\n def _update(self, node_index, data_index, update_value, left_data_index, right_data_index):\n value = self.nodes[node_index]\n mid_data_index = (left_data_index + right_data_index) // 2\n left_node_index = self._left(node_index)\n right_node_index = self._right(node_index)\n\n new_value = None\n if left_data_index == right_data_index:\n new_value = (\n update_value,\n 1,\n update_value,\n 1,\n update_value,\n 1)\n else:\n left_value = right_value = None\n if data_index <= mid_data_index:\n left_value = self._update(left_node_index, data_index, update_value, left_data_index, mid_data_index)\n right_value = self.nodes[right_node_index]\n else:\n left_value = self.nodes[left_node_index]\n right_value = self._update(right_node_index, data_index, update_value, mid_data_index + 1, right_data_index)\n (left_lc, left_ll, left_pc, left_pl, left_sc, left_sl) = left_value\n (right_lc, right_ll, right_pc, right_pl, right_sc, right_sl) = right_value\n \n lc = ll = None\n if left_ll > right_ll:\n lc = left_lc\n ll = left_ll\n else:\n lc = right_lc\n ll = right_ll\n if left_sc == right_pc and left_sl + right_pl > ll:\n ll = left_sl + right_pl\n lc = left_sc\n\n pc = left_pc\n pl = left_pl\n if left_pl == (mid_data_index - left_data_index + 1) and left_pc == right_pc:\n pl = left_pl + right_pl\n\n sc = right_sc\n sl = right_sl\n if right_sl == (right_data_index - mid_data_index) and left_sc == right_sc:\n sl = left_sl + right_sl\n \n new_value = (lc, ll, pc, pl, sc, sl)\n self.nodes[node_index] = new_value\n return new_value\n\n def update(self, data_index, update_value):\n self.data[data_index] = update_value\n return self._update(0, data_index, update_value, 0, len(self.data)-1)\n\nclass Solution:\n def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n st = SegmentTree(list(s))\n M = len(queryCharacters)\n ans = [0] * M\n for i in range(M):\n c = queryCharacters[i]\n p = queryIndices[i]\n st.update(p, c)\n ans[i] = st.nodes[0][1]\n return ans\n```\n\n\n | 108,614 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,152 | 16 | Using a segment tree seems natural here, though good luck implementing it if you haven\'t practiced that data structure recently.\n\nInstead, we can solve this problem by merging (and breaking) intervals. \n\n> Also check this [segment tree-based solution]().\n\n**C++**\nWe use a hash map to track the start of intervals (with repeating characters), and its length. We also use a multiset to store all lengths in the sorted order (so we know the longest one).\n\nTo simplify coding (and debugging), it\'s good to encapsulate interval operations into `insert`, `erase`, and `replace` functions.\n\nIt is important to first check that the new character is different from the current one. That way, we know that we need to break the interval that covers this character index.\n\n```cpp\nvector<int> longestRepeating(string s, string queryCharacters, vector<int>& queryIndices) {\n map<int, int> m;\n multiset<int> sizes;\n vector<int> res;\n auto insert = [&](int i, int sz) { \n sizes.insert(sz);\n return m.insert({i, sz}).first;\n };\n auto replace = [&](auto p, int new_sz) {\n sizes.erase(sizes.find(p->second));\n sizes.insert(new_sz);\n p->second = new_sz;\n };\n auto erase = [&](auto p) {\n sizes.erase(sizes.find(p->second));\n m.erase(p);\n }; \n auto p = end(m);\n for (int i = 0; i < s.size(); ++i) {\n if (i == 0 || s[i - 1] != s[i])\n p = m.insert({i, 1}).first;\n else\n ++p->second;\n }\n for (auto [i, size] : m)\n sizes.insert(size);\n for (int j = 0; j < queryCharacters.size(); ++j) {\n char ch = queryCharacters[j];\n int i = queryIndices[j];\n if (ch != s[i]) { \n s[i] = ch;\n auto p = m.lower_bound(i);\n if (i > 0 && (p == end(m) || p->first > i)) { // break left\n p = insert(i, prev(p)->second - (i - prev(p)->first));\n replace(prev(p), i - prev(p)->first);\n } \n if (p->second > 1) { // break right\n insert(i + 1, p->second - 1);\n replace(p, 1);\n }\n if (i < s.size() - 1 && ch == s[i + 1]) { // join right\n replace(p, next(p)->second + 1);\n erase(next(p));\n }\n if (i > 0 && s[i - 1] == ch) { // join left\n replace(prev(p), prev(p)->second + p->second);\n erase(p);\n } \n }\n res.push_back(*rbegin(sizes));\n };\n return res;\n}\n``` | 108,615 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 2,170 | 13 | This is my contest solution, which in fact follows official leetcode hints, however it gives TLE.\n\nSo, the idea is to use segment tree, where for each segment we keep the following information:\n(longest repating substring, longest repeating suffix, longest repeating prefix, length of segment, left symbol of segment, right symbol of segment)\n\nThen we can update these `6` values when we merge segments.\n\n\n#### Complexity\nIt is `O(n log n + m log n)`, where `n = len(s)` and `m` is number of queries.\n\n#### Code\n```python\nclass SegmentTree:\n def __init__(self, n, arr):\n self.size = 1\n ZERO = (0, 0, 0, 0, 0, 0)\n while self.size < n:\n self.size *= 2\n self.T = [ZERO] * (2 * self.size - 1)\n self.arr = arr\n self.ZERO = ZERO # neutral element\n\n def combine(self, a, b):\n f1, s1, e1, L1, r1, l1 = a\n f2, s2, e2, L2, r2, l2 = b\n f = max(f1, f2)\n if r1 == l2: f = max(f, e1 + s2)\n e = e2 + e1 if (e2 == L2 and r1 == l2) else e2\n s = s1 + s2 if (e1 == L1 and r1 == l2) else s1\n L = L1 + L2\n r = r2\n l = l1\n return (f, s, e, L, r, l)\n\n def one_element(self, x):\n return 1, 1, 1, 1, x, x\n\n def _build(self, x, lx, rx):\n if rx - lx == 1:\n if lx < len(self.arr):\n self.T[x] = self.one_element(self.arr[lx])\n else:\n mx = (lx + rx) // 2\n self._build(2 * x + 1, lx, mx)\n self._build(2 * x + 2, mx, rx)\n self.T[x] = self.combine(self.T[2 * x + 1], self.T[2 * x + 2])\n\n def build(self):\n self._build(0, 0, self.size)\n\n def _set(self, i, v, x, lx, rx):\n if rx - lx == 1:\n self.T[x] = self.one_element(v)\n return\n mx = (lx + rx) // 2\n if i < mx:\n self._set(i, v, 2 * x + 1, lx, mx)\n else:\n self._set(i, v, 2 * x + 2, mx, rx)\n self.T[x] = self.combine(self.T[2 * x + 1], self.T[2 * x + 2])\n\n def set(self, i, v):\n self._set(i, v, 0, 0, self.size)\n\n def _calc(self, l, r, x, lx, rx):\n if l >= rx or lx >= r:\n return self.ZERO\n if lx >= l and rx <= r:\n return self.T[x]\n mx = (lx + rx) // 2\n s1 = self._calc(l, r, 2 * x + 1, lx, mx)\n s2 = self._calc(l, r, 2 * x + 2, mx, rx)\n return self.combine(s1, s2)\n\n def calc(self, l, r):\n return self._calc(l, r, 0, 0, self.size)\n\nclass Solution:\n def longestRepeating(self, s, Q1, Q2):\n n = len(s)\n m = len(Q1)\n ans = []\n STree = SegmentTree(n, s)\n STree.build()\n for i in range(m):\n STree.set(Q2[i], Q1[i])\n ans += [STree.calc(0, n)[0]]\n return ans\n```\n\n#### Solution 2\nIs it possible to make this problem with segment tree? Yes, but for this you need to optimize it, one of the possible ways is the following:\n1. Use iterative tree instead of recursive. Notice that in this case we need to be careful with the order of operations on segments, it is not commutative!\n2. Make use that we always have queries in range `[0, n)`, it means that we can compute once partition we have and then when we have query, just evaluate merge of these segments.\n\n#### Complexity\nStill the same, but optimized.\n\n#### Code\n```python\nclass SegmentTree:\n def __init__(self, n, F):\n self.N = n\n self.F = F\n self.sums = [(0,0,0,0,0,0) for i in range(2*n)]\n self.dp = list(range(2*n))\n for i in range(n-1, -1, -1): self.dp[i] = self.dp[2*i]\n \n L, R = self.N, 2*self.N - 1\n parts = []\n while L <= R:\n if L & 1:\n parts += [(self.dp[L], L)]\n L += 1\n if R & 1 == 0:\n parts += [(self.dp[R], R)]\n R -= 1\n L//=2; R//=2\n \n parts.sort()\n self.d = [j for i, j in parts]\n \n def update(self, index, val):\n idx = index + self.N\n self.sums[idx] = (1, 1, 1, 1, val, val)\n while idx > 1:\n idx //= 2\n self.sums[idx] = self.F(self.sums[2*idx], self.sums[2*idx+1])\n \n def query(self):\n ans = (0, 0, 0, 0, 0, 0)\n for x in self.d:\n ans = self.F(ans, self.sums[x])\n return ans\n\nclass Solution:\n def longestRepeating(self, s, Q1, Q2):\n def FN(a, b):\n if a == (0, 0, 0, 0, 0, 0): return b\n if b == (0, 0, 0, 0, 0, 0): return a\n f1, s1, e1, L1, r1, l1 = a\n f2, s2, e2, L2, r2, l2 = b\n if r1 == l2:\n return max(f1, f2, e1 + s2), s1+s2*(e1==L1), e2+e1*(e2==L2), L1 + L2, r2, l1\n else:\n return max(f1, f2), s1, e2, L1 + L2, r2, l1\n\n n = len(s)\n m = len(Q1)\n ans = []\n STree = SegmentTree(n, FN)\n for i in range(n):\n STree.update(i, s[i])\n for i in range(m):\n STree.update(Q2[i], Q1[i])\n ans += [STree.query()[0]]\n return ans\n``` | 108,616 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,276 | 6 | Another very typical range-merging problem. One possible solution is to use a segment tree. But I am too lazy to explain everything right now--the Google Kickstart round A starts very soon! XD\n\nSo I am going to paste my solution here, please feel free to use it if you need. Maybe I\'ll get back and explain some details tomorrow.\n``` c++\nclass segmentTree {\n public:\n vector<char> lchar, rchar;\n vector<int> lmax, rmax, _max;\n\n // 0-based\n segmentTree(string& a)\n : lchar(vector<char>((a.size() + 5) << 2)),\n rchar(vector<char>((a.size() + 5) << 2)),\n lmax(vector<int>((a.size() + 5) << 2)),\n rmax(vector<int>((a.size() + 5) << 2)),\n _max(vector<int>((a.size() + 5) << 2)) {\n build(0, a, 0, a.size() - 1);\n }\n\n int lc(int o) { return 2 * o + 1; }\n int rc(int o) { return 2 * o + 2; }\n\n void build(int o, string& a, int l, int r) {\n if (l == r) {\n lchar[o] = rchar[o] = a[l];\n lmax[o] = rmax[o] = _max[o] = 1;\n } else {\n int mid = (l + r) >> 1;\n build(lc(o), a, l, mid);\n build(rc(o), a, mid + 1, r);\n pushUp(o, l, r);\n }\n }\n\n void pushUp(int o, int l, int r) {\n lchar[o] = lchar[lc(o)];\n rchar[o] = rchar[rc(o)];\n lmax[o] = lmax[lc(o)];\n rmax[o] = rmax[rc(o)];\n _max[o] = max(_max[lc(o)], _max[rc(o)]);\n int mid = (l + r) >> 1;\n if (rchar[lc(o)] == lchar[rc(o)]) {\n if (lmax[o] == mid - l + 1) lmax[o] += lmax[rc(o)];\n if (rmax[o] == r - (mid + 1) + 1) rmax[o] += rmax[lc(o)];\n _max[o] = max(_max[o], rmax[lc(o)] + lmax[rc(o)]);\n }\n }\n\n void update(int o, int l, int r, int q, char k) {\n if (r < q || q < l) return;\n if (q <= l && r <= q) {\n lchar[o] = rchar[o] = k;\n lmax[o] = rmax[o] = _max[o] = 1;\n return;\n }\n int mid = (l + r) >> 1;\n update(lc(o), l, mid, q, k);\n update(rc(o), mid + 1, r, q, k);\n pushUp(o, l, r);\n }\n};\n\nclass Solution {\n public:\n vector<int> longestRepeating(string s, string queryCharacters,\n vector<int>& queryIndices) {\n segmentTree st(s);\n int n = s.size();\n int q = queryCharacters.size();\n vector<int> res(q);\n for (int i = 0; i < q; i++) {\n st.update(0, 0, n - 1, queryIndices[i], queryCharacters[i]);\n res[i] = st._max[0];\n }\n return res;\n }\n};\n``` | 108,617 |
Longest Substring of One Repeating Character | longest-substring-of-one-repeating-character | You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed. | Array,String,Segment Tree,Ordered Set | Hard | Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together. | 1,436 | 13 | Keep track of both substrings of one repeating character and their lengths in `SortedList`. We can then find the substring that covers the query index, the one to the left, and the one to the right in O(logn) time. The rest is just tedious bookkeeping of substring split and merge. One pitfall to avoid is that both `add` and `remove` change the index of the elements in `SortedList`, so I defer those calls until I am done with the index.\n\n```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n sl = SortedList()\n length = SortedList()\n curr = 0\n for char, it in itertools.groupby(s):\n c = sum(1 for _ in it)\n length.add(c)\n sl.add((curr, curr + c, char))\n curr += c\n ans = []\n for char, i in zip(queryCharacters, queryIndices):\n t = (i, math.inf, \'a\')\n index = sl.bisect_right(t) - 1\n to_remove = [sl[index]]\n to_add = []\n left, right, original_char = to_remove[0]\n if original_char != char:\n length.remove(right - left)\n if right - left > 1:\n if i == left:\n left += 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n elif i == right - 1:\n right -= 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n else:\n to_add.append((left, i, original_char))\n length.add(i - left)\n to_add.append((i + 1, right, original_char))\n length.add(right - (i + 1))\n \n l, r = i, i + 1\n if index - 1 >= 0 and sl[index - 1][1:3] == (i, char):\n l, old_r, _ = sl[index - 1]\n to_remove.append(sl[index - 1])\n length.remove(old_r - l)\n if index + 1 < len(sl) and sl[index + 1][0] == i + 1 and sl[index + 1][2] == char:\n old_l, r, old_length = sl[index + 1]\n to_remove.append(sl[index + 1])\n length.remove(r - old_l)\n length.add(r - l)\n sl.add((l, r, char))\n for t in to_remove:\n sl.remove(t)\n sl.update(to_add)\n # print(sl)\n # print(length)\n ans.append(length[-1])\n\n return ans\n```\nSadly, I finished this 5 min. after the contest \uD83D\uDE41 | 108,618 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 4,007 | 88 | We can use two pointers to swipe the array once (`i`) and collect all k-distant indices (`j`).\n\n**C++**\n```cpp\nvector<int> findKDistantIndices(vector<int>& nums, int key, int k) {\n vector<int> res;\n for (int i = 0, j = 0; i < nums.size(); ++i)\n if (nums[i] == key)\n for (j = max(j, i - k); j <= i + k && j < nums.size(); ++j)\n res.push_back(j);\n return res;\n}\n``` | 108,661 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 1,329 | 31 | # Breaking down and understanding the problem\nThe problem says to return indexes such that |i - j| <= k and nums[j] = key. What does it mean ?\n\nSee once we find the key at a particular index. We need to print those indexes which satisfy the condtion \n|i - j| <= k. Right ? . Now that we understand it, let\'s look at a visual\n\n\n![image]()\n\nFrom here we see that whenever the key is found. We can only move **AT MOST** k indexes to the left and **AT MOST** k indexes to the right. If we move any further along in any direction the |i - j| <= k condition breaks.\n\n\n**So which basically means that the actual problem is whenever we find the key. we have to move k indexes to the left and k indexes to the right and that gives the answer.**\n\nNow comes a few scenarios to keep in mind.\n\n1. What if we find key on extreme left. We can\'t move to left of index 0, it gives us out of bounds.\n \n ![image]()\n\n In order to avoid this we can move to **max(0, i-k)** positions. So that we never fall below 0.\n\n2. What if we find key on extreme right. We can\'t move beyond array limit.\n\n ![image]()\n\n In order to avoid this we can move to **min(n-1, i+k)** positions. So that we don\'t go beyond limit of array.\n\n3. Avoiding overlapping in intervals\n\n![image]()\n\nHere what we can do is, we check the last entry of index that we stored. We compare it with the start of the new interval. We take the max of last index entry + 1 & current start. In above example last entry for first 3 will be 4 **(See the end of red line)**. Starting index for 3 will be 2 **(See the start of orange line)**. So comparing \nmax(lastEntry of index + 1, startIndex) = max(5, 2) = 5. So we avoid overlapping interval and start from 5.\n\n\n```\n vector<int> findKDistantIndices(vector<int>& nums, int key, int k) \n {\n int n = nums.size();\n vector<int> ans;\n \n for(int i = 0; i<n; i++)\n {\n if(nums[i] == key) // if we find the key\n {\n int start = max(0, i-k); // initialize the start\n int end = min(n-1, i+k); // intialize the end\n \n if(ans.size()!=0) // check if any index is stored earlier\n start = max(ans[ans.size() - 1] + 1, start); // avoid overlapping intervals\n \n for(int j = start; j<=end; j++) // simply push every index from start till end\n ans.push_back(j);\n }\n }\n return ans;\n }\n```\n\n \nAs we are able to avoid overlapping intervals. The time complexity is O(n).\n\nUpvote if it was able to help you. Cheers !!\n | 108,664 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 2,120 | 15 | - Keep on finding the corresponding index **j** w.r.t **i** , having **abs(j-i)<=k** and **nums[j]==target**.\n- In this way index i will automatically be in **sorted order** as we are pushing it on the way.\n- We will use a `break statement` the moment we will get a `j` satisfying all the constraint w.r.t `i`.\n- We don\'t need any `extra data structure `or any `sorting algorithm` because we will automatically get a sorted answer.\n# C++ \n vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {\n vector<int> ans;\n for(int i=0;i<size(nums);i++){\n for(int j=0;j<size(nums);j++){\n //if found atleast one index , break and save\n if(abs(i-j)<=k and nums[j]==key){\n ans.push_back(i);\n break;\n }\n }\n }\n return ans;\n }\n\t\n**Time** - O(N^2)\n**Space** - O(1) -> apart from the space of the answer that is a vector that we must return\n**Pls tell any better approach , if you have**\t | 108,666 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 1,323 | 7 | See my latest update in repo [LeetCode]()\n## Solution 1. Two Pointers\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(N)\nclass Solution {\npublic:\n vector<int> findKDistantIndices(vector<int>& A, int key, int k) {\n int N = A.size();\n vector<int> ans, idx;\n for (int i = 0; i < N; ++i){\n if (A[i] == key) idx.push_back(i); // `idx` is a list of indices whose corresponding value is `key`.\n }\n for (int i = 0, j = 0; i < N && j < idx.size(); ++i) {\n if (i < idx[j] - k) continue; // If `i` is not yet in range of the next `key` element at `idx[j]`, skip.\n while (j < idx.size() && i > idx[j] + k) ++j; // While `i > idx[j] + k`, keep incrementing `j` to bring `idx[j]` in range of `i`.\n if (j < idx.size() && i <= idx[j] + k && i >= idx[j] - k) ans.push_back(i); // add `i` to the answer if `idx[j] - k <= i <= idx[j] + k`.\n }\n return ans;\n }\n};\n```\n\n## Solution 2. Two Pointers\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n vector<int> findKDistantIndices(vector<int>& A, int key, int k) {\n int N = A.size(), j = 0;\n vector<int> ans;\n for (int i = 0, j = 0; i < N; ++i) {\n while (j < N && (A[j] != key || j < i - k)) ++j; // Find the first index `j` that `A[j] == key` and `j >= i - k`.\n if (j == N) break;\n if (i <= j + k && i >= j - k) ans.push_back(i); // add `i` to answer if `j - k <= i <= j + k`.\n }\n return ans;\n }\n};\n``` | 108,668 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 483 | 6 | **Time Complexity:- O(n)\nSpace Complexity:- O(number of keys)**\n\n```\nclass Solution {\npublic:\n vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {\n int n = nums.size();\n \n queue<int> q;\n for(int i=0; i<n; i++) {\n if(nums[i] == key) q.push(i);\n }\n \n vector<int> ans;\n for(int i=0; i<n; i++) {\n if(q.empty()) break;\n int idx = q.front();\n \n if(abs(idx - i) <= k) {\n ans.push_back(i);\n }\n else {\n if(i > idx) {\n\t\t\t\t\t// if not able to cover current index then surely can\'t cover indices after it\n q.pop();\n\t\t\t\t\t\n\t\t\t\t\t// lets again try for current index\n i--;\n }\n }\n }\n \n return ans;\n }\n};\n``` | 108,670 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 1,467 | 6 | The idea here is :\n- Store all the indices of elements in a queue whose value is equal to key\n- for every index in nums, there are 2 options:\n - check with the near index backside whose value = key and difference<=k\n - check with the near index in front whose value = k and difference<=k\n\nCode:\n```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n lis=deque([])\n prev_popped=-1\n for i in range(len(nums)):\n if(nums[i]==key):\n lis.append(i)\n ans=[]\n for i in range(len(nums)):\n if(len(lis)>0 and lis[0]<i):\n prev_popped = lis.popleft()\n if(prev_popped!=-1 and (i-prev_popped) <=k):\n ans.append(i)\n elif(len(lis)>0 and (lis[0]-i)<=k):\n ans.append(i)\n return ans\n``` | 108,671 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 1,199 | 11 | Problem : We have to find all the indices which are at <= k distance from the keys in an array. \n\nIdea : If we find all the indices of the keys in a given array in increasing order, then we can iterate k elements on the right and left sides of that key index to add them to answer in increasing order. For the next key index we can start iterating from the maximum(last key index + k , current key index - k) so that we will not process the already iterated array index. \n\nOnce we process all the indices with keys, we have a answer list in increasing order and we return it without the need of sorting.\n\n```\npublic List<Integer> findKDistantIndices(int[] nums, int key, int k) {\n List<Integer> idx = new ArrayList<>();\n List<Integer> ans = new ArrayList<>();\n for(int i = 0 ; i < nums.length; i++){\n if(nums[i] == key){\n idx.add(i);\n }\n }\n int last = 0;\n for(int ind : idx){\n int i = Math.max(last,ind-k);\n for(; i <= ind+k && i < nums.length; i++){\n ans.add(i);\n }\n last = i;\n }\n return ans;\n }\n``` | 108,673 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 829 | 8 | ```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n ind_j = []\n for ind, elem in enumerate(nums):\n if elem == key:\n ind_j.append(ind)\n res = []\n for i in range(len(nums)):\n for j in ind_j:\n if abs(i - j) <= k:\n res.append(i)\n break\n return sorted(res)\n``` | 108,675 |
Find All K-Distant Indices in an Array | find-all-k-distant-indices-in-an-array | You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order. | Array | Easy | For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices. | 524 | 5 | ```\nPLEASE UPVOTE IF YOU LIKE\n```\n```\n int len = nums.length - 1;\n List<Integer> ans = new ArrayList<>();\n\n int[] arr = new int[len+1];\n int dist1 = 0, dist2 = 0;\n\n for (int i = 0; i <= len; i++) {\n if (nums[i] == key) dist1 = k + 1;\n if (dist1 > 0){\n arr[i]++;\n dist1--;\n }\n\n if (nums[len-i] == key) dist2 = k+1;\n if (dist2 > 0){\n arr[len-i]++;\n dist2--;\n }\n }\n\n for (int i = 0; i < arr.length; i++)\n if (arr[i] > 0)\n ans.add(i);\n\t\t\t\t\n\t\treturn ans; | 108,685 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 4,941 | 146 | The idea is the following: paths from `s1` to `dest` and from `s2` to dest` can have common point `x`. Then we need to reach:\n1. From `s1` to `x`, for this we use Dijkstra\n2. From `s2` to `x`, same.\n3. From `x` to dest, for this we use Dijkstra on the reversed graph.\n4. Finally, we check all possible `x`.\n\n#### Remark\nIn python it was quite challenging to get **AC**, and I need to look for faster implementation of Dijkstra, however complexity is still the same, it depends on implementation details.\n\n#### Complexity\nIt is `O(n*log E)` for time and `O(n)` for space.\n\n#### Code\n```python\nclass Solution:\n def minimumWeight(self, n, edges, s1, s2, dest):\n G1 = defaultdict(list)\n G2 = defaultdict(list)\n for a, b, w in edges:\n G1[a].append((b, w))\n G2[b].append((a, w))\n\n def Dijkstra(graph, K):\n q, t = [(0, K)], {}\n while q:\n time, node = heappop(q)\n if node not in t:\n t[node] = time\n for v, w in graph[node]:\n heappush(q, (time + w, v))\n return [t.get(i, float("inf")) for i in range(n)]\n \n arr1 = Dijkstra(G1, s1)\n arr2 = Dijkstra(G1, s2)\n arr3 = Dijkstra(G2, dest)\n \n ans = float("inf")\n for i in range(n):\n ans = min(ans, arr1[i] + arr2[i] + arr3[i])\n \n return ans if ans != float("inf") else -1\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 108,709 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 4,817 | 96 | \n\nSee my latest update in repo [LeetCode]()\n\n## Solution 1. Dijkstra\n\nDo Dijkstra 3 times.\n\nFirst time: store the shortest distance from node `a` to all other nodes in array `da`.\n\nSecond time: store the shortest distance from node `b` to all other nodes in array `db`.\n\nThird time: store the shortest distance from node `dest` to all other nodes **via Reversed Graph** in array `dd`.\n\nThe answer is the minimum `da[i] + db[i] + dd[i]` (`0 <= i < N`).\n\n![image]()\n\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(ElogE + N)\n// Space: O(E)\nclass Solution {\n typedef pair<long, long> ipair;\npublic:\n long long minimumWeight(int n, vector<vector<int>>& E, int a, int b, int dest) {\n vector<vector<ipair>> G(n), R(n); // `G` is the original graph. `R` is the reversed graph\n for (auto &e : E) {\n long u = e[0], v = e[1], w = e[2];\n G[u].emplace_back(v, w);\n R[v].emplace_back(u, w);\n }\n vector<long> da(n, LONG_MAX), db(n, LONG_MAX), dd(n, LONG_MAX);\n auto solve = [&](vector<vector<ipair>> &G, int a, vector<long> &dist) {\n priority_queue<ipair, vector<ipair>, greater<ipair>> pq;\n dist[a] = 0;\n pq.emplace(0, a);\n while (pq.size()) {\n auto [cost, u] = pq.top();\n pq.pop();\n if (cost > dist[u]) continue;\n for (auto &[v, c] : G[u]) {\n if (dist[v] > dist[u] + c) {\n dist[v] = dist[u] + c;\n pq.emplace(dist[v], v);\n }\n }\n }\n };\n solve(G, a, da);\n solve(G, b, db);\n solve(R, dest, dd);\n long ans = LONG_MAX;\n for (int i = 0; i < n; ++i) {\n if (da[i] == LONG_MAX || db[i] == LONG_MAX || dd[i] == LONG_MAX) continue;\n ans = min(ans, da[i] + db[i] + dd[i]);\n }\n return ans == LONG_MAX ? -1 : ans;\n }\n};\n``` | 108,710 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 3,957 | 60 | **Intuition:** At some point, paths from both sources will reach some common node.\n\nSay, this common node is `i`. The weight of the graph will be the sum of:\n- Minimum distance from first source to `i`.\n- Minimum distance from second source to `i`.\n- Minimum distance from `i` to the destination.\n\nWe run Dijkstra 3 times from both sources and destination. Note that to find smallest distance from all nodes to the destination, we run Dijkstra in reverse from the destination.\n\n**C++**\n```cpp\nvoid bfs(int st, vector<vector<pair<int, int>>> &al, vector<long long>& visited) {\n priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;\n pq.push({0, st});\n while (!pq.empty()) {\n auto [dist, i] = pq.top(); pq.pop();\n if (visited[i] != dist)\n continue;\n for (auto [j, w] : al[i]) {\n if (visited[j] > dist + w) {\n visited[j] = dist + w;\n pq.push({visited[j], j});\n }\n }\n }\n}\nlong long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {\n long long max_val = 10000000000, res = LLONG_MAX;\n vector<vector<pair<int, int>>> al(n), ral(n);\n vector<long long> dd(n, max_val), s1d(n, max_val), s2d(n, max_val);\n dd[dest] = s1d[src1] = s2d[src2] = 0;\n for (auto &e : edges) {\n al[e[0]].push_back({e[1], e[2]});\n ral[e[1]].push_back({e[0], e[2]}); \n }\n bfs(dest, ral, dd);\n bfs(src1, al, s1d);\n bfs(src2, al, s2d);\n if (dd[src1] == max_val || dd[src2] == max_val)\n return -1;\n for (int i = 0; i < n; ++i)\n res = min(res, dd[i] + s1d[i] + s2d[i]);\n return res;\n}\n``` | 108,711 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 1,245 | 55 | **77/78 test cases passes and 1 case TLE is due to not optimized Dijkstra**.\nIn below i had mentioned what to do optimization in Dijkstra and Why ?\n\nwhen we process priority_queue pair by pair in Dijkstra\nthen if we find any pair where `minDistanceFromSrcTo[u] < dist` (where `dist = pq.top().first` & `u = pq.top().second`)\nthen all shortest path passes from this node u is already processed so we have to not need to process this pair.\n\n![image]()\n\n**eg.** during processing let assume that first we found minDistanceFromSrcTo[u] as 5 so we add pair `{5, u}` in priority_queue\nthen after \nfor some path we found minDistanceFromSrcTo[u] as 8 so we add pair `{4, u}` in priority_queue\nso now when we process the queue pair by pair \nfirst we pop `{4, u}` (as we use min pririty queue in Dijkstra) pair and found all shortest path according to that\nand then we get `{5, u}` so now we had no need to process this because this is not lead to any shortest path.\n\n**In Below solution i had done comment in Dijkstra for optimization mentioned above**\n\n**Solution :**\nhere I had done **Dijkstra 3 times**.\n**First time** : store the shortest distance from node `src1` to all other nodes in array `fromSrc1To`.\n**Second time** : store the shortest distance from node `src2` to all other nodes in array `fromSrc2To`.\n**Third time** : store the shortest distance from node `dest` to all other nodes via Reversed Graph in array `fromDestTo`.\n**The answer is the minimum of** `fromSrc1To[i] + fromSrc2To[i] + fromDestTo[i]` (`0 <= i < N`).\n\n```\nclass Solution {\n\tlong MAXX = 1e10;\npublic:\n\t// DIJKSTRA\n\tvoid Dijkstra(long src, vector<pair<long, long>> adj[], vector<long>&minDistanceFromSrcTo)\n\t{\n\t\tpriority_queue<pair<long, long>, vector<pair<long, long>>, greater<pair<long, long>>> pq;\n\t\tpq.push({0, src});\n\t\tminDistanceFromSrcTo[src] = 0;\n\t\tlong u, v, wt, dist;\n\t\twhile (!pq.empty()) {\n\t\t\tu = pq.top().second;\n\t\t\tdist = pq.top().first;\n\t\t\tpq.pop();\n\t\t\t// below line in Dijkstra becomes game changer\n\t\t\t// because if for any pair in priority_queue pq\n\t\t\t// minDistanceFromSrcTo[u] < dist\n\t\t\t// then shortest path passing from this u is already processed\n\t\t\t// so no need to go below for() loop for time consumption\n\t\t\tif (minDistanceFromSrcTo[u] < dist) continue;\n\t\t\tfor (auto it : adj[u]) {\n\t\t\t\tv = it.first;\n\t\t\t\twt = it.second;\n\t\t\t\tif (minDistanceFromSrcTo[u] + wt < minDistanceFromSrcTo[v]) {\n\t\t\t\t\tminDistanceFromSrcTo[v] = wt + minDistanceFromSrcTo[u];\n\t\t\t\t\tpq.push({minDistanceFromSrcTo[v], v});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlong minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {\n\t\tvector<pair<long, long>> adj[n], revadj[n];\n\t\tfor (auto e : edges) {\n\t\t\tadj[e[0]].push_back({e[1], e[2]});\n\t\t\trevadj[e[1]].push_back({e[0], e[2]});\n\t\t}\n\n\t\tvector<long>fromSrc1To(n, MAXX), fromSrc2To(n, MAXX), fromDestTo(n, MAXX);\n\t\tDijkstra(src1, adj, fromSrc1To);\n\t\tDijkstra(src2, adj, fromSrc2To);\n\t\tDijkstra(dest, revadj, fromDestTo);\n\n\t\t// BASE CASE : not fount any path from src1 to dest OR src2 to dest\n\t\tif (fromSrc1To[dest] == MAXX || fromSrc2To[dest] == MAXX) return -1;\n\n\t\tlong ans = MAXX;\n\t\tfor (long i = 0; i < n; i++) {\n\t\t\tans = min(ans, fromSrc1To[i] + fromSrc2To[i] + fromDestTo[i]);\n\t\t}\n\t\treturn ans;\n\t}\n};\n```\n**If find Helpful *Upvote It* \uD83D\uDC4D** | 108,712 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 1,612 | 42 | This problem can actually be solved with just 1 dijkstra. I\'ll try my best to explain it and comment my code. Hope it\'s clear.\n\nFirst, let me mention a fact about dijkstra\'s algorithm that is relevant to understanding this solution.\n\t* We visit nodes in increasing order of total distance from the source.\nIf this is not very clear, please refer to this picture, I\'ve shown it with an example.\n![image]()\n\nFrom this it\'s obvious that the first time we visit a node from the source, we would have visited it with the shortest path possible to that node. (every next node we visit will have a total path length >= current path length)\nSo in a single source dijkstra, we record the path length the first time a node has been visited and discard future occurrences.\n\nIn this problem, we are given 2 sources and a single destination. We have to find the subset of nodes and edges such that the sum of weights of the edges is minumum, and (src1 -> dest) should be connected and (src2 -> dest) should be connected. \nSo in the subgraph we select, we should have 1 path from src1 to dest and 1 path from src2 to dest. (It wouldnt make sense to have 2 or more paths as removal of one would still keep it connected and with a lesser cost, convince yourself of this)\n\nFor a second lets assume src1 = src2. Now its obvious that we just pick any shortest path from the source to the destination. Every edge we have is used by both src1 and src2 and is only counted once.\nIf src2 moves away from src1, some edges will be used only by src1, some edges only by src2 and some edges by both. We would ideally want them to share a lot of edges so we dont count a lot of distinct edges. So the solution to the problem will look something like this.\n![image]()\n\nIn the 3 dijkstra solution, we consider every meeting point and see which one gives us the lowest cost.\nHowever we can exploit the fact that we visit paths in increasing order of total distance and solve it with 1 dijkstra.\n\nLet me define 3 types of nodes, type_1, type_2 and type_3.\na type_1 node is only invloved in the path from src1 to meeting point\na type_2 node is only involved in the path from src_2 to meeting point\na type 3 node is only involved in the path from meeting point to dest.\n\na type_1 node is always trailed by another type_1 node\na type_2 node is always trailed by another type_2 node\na type_3 node is either trailed by another type_3 node or is trailed by a type_1 and type_2 node (when they meet).\n\nNow when we do a dijkstra, we mark every node with either type_1, type_2 or type_3. The dest will always be a type_3 node.\nlet dist_1[i] be the distance from src_1 to i using only type_1 nodes\nlet dist_2[i] be the distance from src_2 to i using only type_2 nodes\nlet dist[i] be the total distance from src1, src2 to i where i is a type 3 node.\nthe answer to the question is dist[dest]\n\nWe start a dijkstra by adding (src1, type_1, 0) and (src2, type_2, 0) to the priorityQueue simultaneously.\nAt some point lets say we visit a node i, which is a type_1 node. if this node has not been previously visited as a type_2 node, we simply just update dist_1[i] and queue its neighbours as type_1. However, if this node has already been visited as a type_2 node, this node now becomes a type_3 node. We update dist[i] = dist_1[i] + dist_2[i] . And from here, we queue its neighbours as type_3.\nAt every point, regardless of the type of node we queue, we will always be visiting nodes in an increasing order of total distance from the source. So the first time we visit dest as a type 3 node, that will be our answer.\nI hope this explanation was clear. Please go through my code too, maybe it will be make it clearer.\n\n```\nprivate static final int only_1 = 1; //type_1\n private static final int only_2 = 2; //type_2\n private static final int both = 3; //type_3\n\n // a weighted edge\n private static class NodeCostPair {\n int to;\n long weight;\n\n public NodeCostPair(int to, long weight) {\n this.to = to;\n this.weight = weight;\n }\n }\n\n // search node for dijkstra\n private static class SeacrhNode implements Comparable<SeacrhNode> {\n int to;\n long cost;\n int type;\n\n public SeacrhNode(int to, long cost, int type) {\n this.to = to;\n this.type = type;\n this.cost = cost;\n }\n\n @Override\n public int compareTo(SeacrhNode o) {\n if(this.cost < o.cost) {\n return -1;\n }\n else if(this.cost > o.cost) {\n return 1;\n }\n else {\n if(this.type == both) {\n return -1;\n }\n }\n return 1;\n }\n }\n\n private static long dijkstra(Map<Integer, List<NodeCostPair>> map, int src_1, int src_2, int dest) {\n int n = map.size();\n long[] dist_1 = new long[n];\n long[] dist_2 = new long[n];\n long[] dist = new long[n];\n //-1 is unvisited\n Arrays.fill(dist_1, -1);\n Arrays.fill(dist_2, -1);\n Arrays.fill(dist, -1);\n\n PriorityQueue<SeacrhNode> pq = new PriorityQueue<>();\n pq.add(new SeacrhNode(src_1, 0, only_1));\n pq.add(new SeacrhNode(src_2, 0, only_2));\n\n while(!pq.isEmpty()) {\n //get the next search node\n SeacrhNode node = pq.poll();\n int cur = node.to;\n long cost = node.cost;\n int type = node.type;\n\n // if this node is type_1\n if(type == only_1) {\n //we have already visited this node as a type_1 node (with a shorter path)\n if(dist_1[cur] != -1) {\n continue;\n }\n //if it\'s the first time we are visiting this node as a type_1 node, update dist_1\n dist_1[cur] = cost;\n //get neighbours\n List<NodeCostPair> neighbours = map.get(cur);\n\n //a type_2 searchNode has already visited this node, it is a potential meeting point\n //from here on out, it is useless to queue type_1 searchNodes from here,\n //as type_3 will be better(subsequent edges will only be counted once)\n if(dist_2[cur] != -1) {\n //queueing type_3 search node\n pq.add(new SeacrhNode(cur, dist_1[cur] + dist_2[cur], both));\n }\n //a type_2 searchNode has not visited this node\n else {\n for(NodeCostPair e : neighbours) {\n //queueing type_1 search nodes\n pq.add(new SeacrhNode(e.to, dist_1[cur] + e.weight, only_1));\n }\n }\n }\n //I\'m not commenting the code for type 2 as it\'s symmetrical to type_1\n else if(type == only_2) {\n if(dist_2[cur] != -1) {\n continue;\n }\n dist_2[cur] = cost;\n List<NodeCostPair> neighbours = map.get(cur);\n if(dist_1[cur] != -1) {\n pq.add(new SeacrhNode(cur, dist_1[cur] + dist_2[cur], both));\n }\n else {\n for(NodeCostPair e : neighbours) {\n pq.add(new SeacrhNode(e.to, dist_2[cur] + e.weight, only_2));\n }\n }\n }\n //type_3 searchNode\n else {\n //we have already visited this node as a type_3 node, (with lower cost)\n if(dist[cur] != -1) {\n continue;\n }\n //the first time we visit dest as a type 3 node, we return the cost to dest\n if(cur == dest) {\n return cost;\n }\n //the first time we visit this node as a type_3 node, update its cost\n dist[cur] = cost;\n //getting neighbours\n List<NodeCostPair> neighbours = map.get(cur);\n for(NodeCostPair e : neighbours) {\n //queueing type_3 searchNodes\n pq.add(new SeacrhNode(e.to, dist[cur] + e.weight, both));\n }\n }\n }\n //we have not encountered dest as a type_3 node in our dijkstra, return -1\n return -1;\n }\n\n\n public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {\n Map<Integer, List<NodeCostPair>> map = new HashMap<>();\n for(int i = 0; i < n; i++) {\n map.put(i, new ArrayList<>());\n }\n for(int[] edge : edges) {\n int from = edge[0];\n int to = edge[1];\n int weight = edge[2];\n map.get(from).add(new NodeCostPair(to, weight));\n }\n\n return dijkstra(map, src1, src2, dest);\n }\n```\n\n | 108,713 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 1,262 | 24 | ## Idea\n- for each node `i` we calculate the following value\n\t```\n\tw[i] := dist(src1, i) + dist(src2, i) + dist(i, dest)\n\t```\n\t- where `dist(a, b)` is defined as the length of the shortest path from node `a` to node `b`.\n\t- then the answer would be the minimum value among all `w[i]`s.\n- to obtain the distance functions, we have to perform **Dijkstra\'s Algorithm** three times:\n\t1. starting from `src1` to get `dist(src1, *)`\n\t2. starting from `src2` to get `dist(src2, *)`\n\t3. starting from `dest` in the **edge-reversed** graph to get `dist(*, dest)`\n## Code\n- C++\n\t```\n\ttypedef long long ll;\n\t\n\tclass Solution {\n\tprivate:\n\t\tconst ll kInf = 1e18;\n\t\tvector<ll> Dijkstra(vector<vector<pair<int, ll>>>& adj, int src) {\n\t\t\tint n = adj.size();\n\t\t\tvector<ll> dist(n, kInf);\n\t\t\tdist[src] = 0;\n\t\t\tpriority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n\t\t\t// pq contains pairs of <the current distance estimate from src to id, id>\n\t\t\tpq.push(make_pair(0, src));\n\t\t\twhile (!pq.empty()) {\n\t\t\t\tauto [d, cur] = pq.top(); pq.pop();\n\t\t\t\tif (d != dist[cur]) continue;\n\t\t\t\tfor (auto [nei, w] : adj[cur]) {\n\t\t\t\t\tif (dist[nei] > d + w) {\n\t\t\t\t\t\tdist[nei] = d + w;\n\t\t\t\t\t\tpq.push(make_pair(dist[nei], nei));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn dist;\n\t\t}\n\tpublic:\n\t\tlong long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {\n\t\t\t// build the graphs\n\t\t\tvector<vector<pair<int, ll>>> adj(n);\n\t\t\tvector<vector<pair<int, ll>>> rev(n); // the graph with reversed edges\n\t\t\tint u, v, w;\n\t\t\tfor (auto& e : edges) {\n\t\t\t\tu = e[0], v = e[1], w = e[2];\n\t\t\t\tadj[u].push_back(make_pair(v, w));\n\t\t\t\trev[v].push_back(make_pair(u, w));\n\t\t\t}\n\t\t\t// Dijkstra\n\t\t\tvector<ll> dist_from_src1 = Dijkstra(adj, src1);\n\t\t\tvector<ll> dist_from_src2 = Dijkstra(adj, src2);\n\t\t\tvector<ll> dist_to_dest = Dijkstra(rev, dest);\n\t\t\t// find the smallest w[i]\n\t\t\tll ans = kInf;\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tans = min(ans, dist_from_src1[i] + dist_from_src2[i] + dist_to_dest[i]);\n\t\t\t}\n\t\t\treturn ans == kInf ? -1 : ans;\n\t\t}\n\t};\n\t```\n- Time Complexity:\n\t- `O(E log E + n)`, where `E` denotes the number of edges in the graph.\n- Space Complexity:\n\t- `O(E + n)` | 108,715 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 1,508 | 27 | Run Dijkstra\'s algorithm 3 times from src1, src2, and dest respectively, to determine the shortest path between each node and src1/src2/dest, then go through each node and min(src1To[i] + src2To[i] + toDest[i]) is the answer.\n\n```\nclass Solution {\n ArrayList<int[]>[] nextGraph, preGraph;\n \n public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {\n buildGraph(n, edges);\n \n long[] src1To = new long[n], src2To = new long[n], toDest = new long[n];\n Arrays.fill(src1To, -1);\n Arrays.fill(src2To, -1);\n Arrays.fill(toDest, -1);\n \n shortestPath(src1, src1To, nextGraph);\n shortestPath(src2, src2To, nextGraph);\n shortestPath(dest, toDest, preGraph);\n \n long res = -1;\n for (int i = 0; i < n; i++) {\n long d1 = src1To[i], d2 = src2To[i], d3 = toDest[i];\n if (d1 >= 0 && d2 >= 0 && d3 >= 0) {\n long d = d1 + d2 + d3;\n if (res == -1 || d < res) {\n res = d;\n }\n }\n }\n \n return res;\n }\n \n private void buildGraph(int n, int[][] edges) {\n nextGraph = new ArrayList[n];\n preGraph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n nextGraph[i] = new ArrayList<int[]>();\n preGraph[i] = new ArrayList<int[]>();\n }\n \n for (int[] edge : edges) {\n int from = edge[0], to = edge[1], weight = edge[2];\n nextGraph[from].add(new int[] {to, weight});\n preGraph[to].add(new int[] {from, weight});\n }\n }\n \n private void shortestPath(int src, long[] srcTo, ArrayList<int[]>[] graph) {\n PriorityQueue<long[]> heap = new PriorityQueue<>((a, b) -> Long.compare(a[1], b[1]));\n heap.offer(new long[] {src, 0});\n \n while (!heap.isEmpty()) {\n long[] node = heap.poll();\n int to = (int) node[0];\n long dist = node[1];\n if (srcTo[to] != -1 && srcTo[to] <= dist) continue;\n srcTo[to] = dist;\n for (int[] next : graph[to]) {\n heap.offer(new long[] {next[0], dist + next[1]});\n }\n }\n }\n}\n``` | 108,716 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 325 | 8 | # Intuition\n- If we were asked to find the answer from `src1` and `src2` independently, then we would have applied dijkstra indivisually.\n- So for this question, there can be a possibility that the path from `src1 to dest` and the path from `src2 to dest` would share some of the edges or they can be completely different.\n- Using this we approach towards the solution of the problem.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUse dijkstra for each of the src1, src2, dest.\n- First dijkstra store the distance of each node from `src1`.\n- Second dijkstra store the distance of each node from `src2`.\n- Third dijkstra use another adjacency list with reversed edge direction to store the distance of each node from `dest`.\n- Finally, the answer is the minimum of these three distances for every node from `0 <= i <= N`.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N * log N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long\n#define pii pair<ll,ll>\n#define inf (1ll << 60)\nclass Solution {\npublic:\n void dijkstra(int src, vector<ll> &dist, vector<vector<pii>> &adj) {\n priority_queue<pii, vector<pii>, greater<pii>> pq;\n dist[src] = 0;\n pq.push({0,src});\n\n while(!pq.empty())\n {\n auto [wt,v] = pq.top();\n pq.pop();\n\n if(wt != dist[v])\n continue;\n\n for(auto [u,d] : adj[v])\n {\n if(dist[u] > wt + d)\n {\n dist[u] = wt + d;\n pq.push({dist[u],u});\n }\n }\n }\n }\n\n long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {\n vector<vector<pii>> adj(n,vector<pii>());\n vector<vector<pii>> radj(n,vector<pii>());\n for(auto it : edges)\n {\n int u = it[0], v = it[1], w = it[2];\n adj[u].push_back({v,w});\n radj[v].push_back({u,w});\n }\n\n vector<ll> dist1(n,inf), dist2(n,inf), dist3(n,inf);\n\n dijkstra(src1,dist1,adj);\n dijkstra(src2,dist2,adj);\n dijkstra(dest,dist3,radj);\n\n if(dist1[dest]==inf || dist2[dest]==inf)\n return -1;\n \n ll ans = inf;\n\n for(int i=0; i<n; i++)\n {\n ll d = dist1[i] + dist2[i] + dist3[i];\n ans = min(ans, d);\n }\n\n return ans;\n }\n};\n```\n\n![6a87bc25-d70b-424f-9e60-7da6f345b82a_1673875931.8933976.jpeg]()\n | 108,717 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 576 | 14 | **Elimination of TLE after 3 times Dijkastra :**\n\n* Generally while running Dijkastra algorithm, we often forget to check that if some node has lower distance than its current cost, we can ignore processing that node.\ni.e. if **dis[u] < cost (where cost = pq.top().first & u = pq.top().second)** then we can stop processing that node.\n\n* And doing that only, we eliminate TLE. \n* This is a good problem, worth solving and checking the actual runtime complexity of Dijkastras.\n\n```\n#define ll long long \n#define maxi 1e18\nclass Solution {\npublic:\n void solve(int src,vector<vector<pair<ll,ll>>>&graph,vector<ll>&dis)\n {\n priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>pq;\n dis[src]=0;\n pq.push({0,src});\n while(!pq.empty())\n {\n int node=pq.top().second;\n int distance=pq.top().first;\n pq.pop();\n \n \n \n /* TLE Elimination */\n if(distance>dis[node])\n continue;\n /* Without above Check u will get TLE */\n \n for(auto itr:graph[node])\n {\n if(dis[itr.first]>itr.second+dis[node])\n {\n dis[itr.first]=itr.second+dis[node];\n pq.push({dis[itr.first],itr.first});\n }\n }\n }\n }\n long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) {\n \n vector<ll>dis1(n,maxi),dis2(n,maxi),dis3(n,maxi);\n \n vector<vector<pair<long long,long long>>>graph(n),reverse(n);\n \n for(auto i:edges)\n {\n int u=i[0];\n int v=i[1];\n int w=i[2];\n \n graph[u].push_back({v,w});\n reverse[v].push_back({u,w});\n\t\t}\n solve(src1,graph,dis1);\n solve(src2,graph,dis2);\n solve(dest,reverse,dis3);\n \n long long ans=maxi;\n // for(auto i:dis1)\n // cout<<i<<" ";\n // cout<<endl;\n // for(auto i:dis2)\n // cout<<i<<" ";\n // cout<<endl;\n \n for(int i=0;i<=n-1;i++)\n {\n if(dis1[i]==maxi or dis2[i]==maxi or dis3[i]==maxi) continue;\n \n ans=min(ans,dis1[i]+dis2[i]+dis3[i]);\n }\n return ans==maxi?-1:ans;\n\t}\n};\n```\n\n**Pls upvote the solution if you found helpful, it means a lot.\nAlso comment down your doubts.\nHappy Coding : )**\n\n | 108,718 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 655 | 5 | The idea is the following: paths from **src1** to **dest** and from **src2** to **dest** can have common point **x**. Then we need to reach:\n1. From **src1** to **x**, for this we use Dijkstra\n2. From **src2** to **x**, for this we use Dijkstra again\n3. From **x** to **dest**, for this we use Dijkstra on the reversed graph.\n\nFinally, we check all possible x to find minimum weight of a subgraph\n\n\tclass Solution \n\t\t{\n\t\t\tclass Edge\n\t\t\t{\n\t\t\t\tint ed;\n\t\t\t\tlong wt;\n\n\t\t\t\tEdge(int ed,long wt)\n\t\t\t\t{\n\t\t\t\t\tthis.ed=ed;\n\t\t\t\t\tthis.wt=wt;\n\t\t\t\t}\n\t\t\t}\n\t\t\tclass Pair\n\t\t\t{\n\t\t\t\tint ed;\n\t\t\t\tlong wsf;\n\n\t\t\t\tPair(int ed,long wsf)\n\t\t\t\t{\n\t\t\t\t\tthis.ed=ed;\n\t\t\t\t\tthis.wsf=wsf;\n\t\t\t\t}\n\t\t\t}\n\t\t\tpublic long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) \n\t\t\t{\n\t\t\t\tArrayList<ArrayList<Edge>> graph=new ArrayList<>();\n\t\t\t\tArrayList<ArrayList<Edge>> rev_graph=new ArrayList<>();\n\n\t\t\t\tfor(int i=0;i<n;i++)\n\t\t\t\t{\n\t\t\t\t\tgraph.add(new ArrayList<>());\n\t\t\t\t\trev_graph.add(new ArrayList<>());\n\t\t\t\t}\n\n\t\t\t\tfor(int i=0;i<edges.length;i++)\n\t\t\t\t{\n\t\t\t\t\tgraph.get(edges[i][0]).add(new Edge(edges[i][1],edges[i][2]));\n\t\t\t\t\trev_graph.get(edges[i][1]).add(new Edge(edges[i][0],edges[i][2])); \n\t\t\t\t}\n\n\t\t\t\tlong[] s1tox=new long[n];\n\t\t\t\tlong[] s2tox=new long[n];\n\t\t\t\tlong[] dtox=new long[n];\n\t\t\t\tArrays.fill(s1tox, -1);\n\t\t\t\tArrays.fill(s2tox, -1);\n\t\t\t\tArrays.fill(dtox, -1);\n\n\t\t\t\tdijkstra(graph,s1tox,src1);\n\t\t\t\tdijkstra(graph,s2tox,src2);\n\t\t\t\tdijkstra(rev_graph,dtox,dest);\n\n\t\t\t\tlong ans=Long.MAX_VALUE;\n\t\t\t\tfor (int i=0;i<n;i++) \n\t\t\t\t{\n\t\t\t\t\tlong l1=s1tox[i];\n\t\t\t\t\tlong l2=s2tox[i];\n\t\t\t\t\tlong l3=dtox[i];\n\n\t\t\t\t\tif (l1!=-1&&l2!=-1&&l3!=-1)\n\t\t\t\t\t{\n\t\t\t\t\t\tlong len=l1+l2+l3;\n\t\t\t\t\t\tans=Math.min(ans,len);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn ans==Long.MAX_VALUE?-1:ans; \n\t\t\t}\n\n\t\t\tpublic void dijkstra(ArrayList<ArrayList<Edge>> graph,long[] res,int src)\n\t\t\t{\n\t\t\t\tPriorityQueue<Pair> q=new PriorityQueue<>((a,b)->(int)(a.wsf-b.wsf));\n\t\t\t\tq.add(new Pair(src,0));\n\t\t\t\tboolean[] visited=new boolean[graph.size()];\n\n\t\t\t\twhile(q.size()>0)\n\t\t\t\t{\n\t\t\t\t\tint size=q.size();\n\n\t\t\t\t\twhile(size-->0)\n\t\t\t\t\t{\n\t\t\t\t\t\tPair p=q.poll();\n\n\t\t\t\t\t\tif(!visited[p.ed])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tArrayList<Edge> al=graph.get(p.ed);\n\t\t\t\t\t\t\tfor(Edge e:al)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(!visited[e.ed])\n\t\t\t\t\t\t\t\t\tq.add(new Pair(e.ed,e.wt+p.wsf));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tres[p.ed]=p.wsf;\n\t\t\t\t\t\t\tvisited[p.ed]=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} | 108,719 |
Minimum Weighted Subgraph With the Required Paths | minimum-weighted-subgraph-with-the-required-paths | You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1. You are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti. Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges. | Graph,Shortest Path | Hard | Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths will coincide. How can algorithms for finding the shortest path between two nodes help us? | 504 | 5 | The problem asks us to find a subgraph with least distance of src1 and src2 to dest.\n\nThere are a couple of key intuitions to get this one right.\n1) If such a subgraph exists, then src1 and src2 can share a common path that leads to dest.\n\t - If such a common path exists, then src1 will move indepndently to the intersecting InterMediate node, lets say IM.\n\t - Similarly src2 will move independently to the intersecting node IM\n\t - From IM both will share the common path\n2) This gives rise to the picture where we have \n\t- src1 -> IM + \n\t- src2 -> IM + \n\t- IM -> dest is minimum\n3) The final intuition is that, IM -> dest can be done by reversing the graph and applying Djikstra on the reversed G.\n\t- src1 -> IM can be done by Djikstra\n\t- src2 -> IM can be done by Djikstra\n\n\t- IM -> dest can be done by Djikstra on the reversed graph\n4) Once we have these distances then finding IM, is just a matter of finding the node that minimizes the total cost\n\n```\ndef minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:\n def djikstra(g, src):\n distances = defaultdict(lambda: inf)\n heap = [(0, src)]\n\n while heap:\n dist, node = heappop(heap)\n if node in distances: continue \n distances[node] = dist\n \n for neigh in g[node].keys():\n if neigh in distances: continue\n newdist = distances[node] + g[node][neigh]\n heappush(heap, [newdist, neigh]) \n return distances\n \n graph = defaultdict(dict)\n rev_graph = defaultdict(dict)\n for u,v,w in edges:\n graph[u][v] = w if v not in graph[u] else min(w, graph[u][v])\n rev_graph[v][u] = w if u not in rev_graph[v] else min(w, rev_graph[v][u])\n \n src1_distances = djikstra(graph, src1)\n src2_distances = djikstra(graph, src2)\n dest_distances = djikstra(rev_graph, dest)\n \n res = inf\n for node in range(n):\n local_res = src1_distances[node] + src2_distances[node] + dest_distances[node]\n res = min(res, local_res) \n return res if res != inf else -1\n``` | 108,720 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 7,992 | 62 | To get minimum bit flips we find XOR of two number : which have set bits only at those places where A differs from B. \nSo, after getting the **xor** `( a ^ b )` , we need to count the number of set bits.\nWe can do that using **__builtin_popcount(i)**: This function is used to count the number of set bits in an integer.\n\n```\nclass Solution {\npublic:\n int minBitFlips(int start, int goal) {\n return __builtin_popcount(start^goal);\n }\n};\n```\nPlease let me know ways to improve my solution. | 108,763 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,232 | 12 | # Intuition\n - Question -> Here given Two numbers. If both no. are represented in Binary then how many minimum bits are required to change in one no. so it convert into second no. \n\n*example* -> \n```\n 10 = 1 0 (1) 0\n 7 = 0 1 (1) 1\n```\nhere, 3 bits are different in both no.s and need to be change in one of them to covert into another.\n\n# Approach \nHere, we have to identify the different bits so , XOR operator can help us -->\n``` \n A | B | A XOR B\n 0 | 0 | 0\n 10 = 1 0 1 0 0 | 1 | 1 \n 7 = 0 1 1 1 1 | 0 | 1 \n____________________________ 1 | 1 | 0\nxor(10,7) = 1 1 0 1\n```\nNow , We have to just count the Set Bits(1) in result of xor.\n no.of Set bits = 3. So, There is minimum 3 flips required.\n# Complexity\n- Time complexity:\n\n Best case - O(1)\n Worst Case - O(n)\n\n- Space complexity:\n \n Constant Space - O(1)\n\n# Code\n\n- C++ Code ->\n```\nclass Solution {\npublic:\n int minBitFlips(int start, int goal) {\n \n int a = (start ^ goal); // this will do xor of given numbers\n //now count set bits\n int count = 0; \n while(a){\n if(a&1){\n count++;\n }\n a = a>>1; // this is right shift operator\n }\n return count;\n }\n};\n```\n- Java Code ->\n```\nclass Solution {\n public int minBitFlips(int start, int goal) {\n int a = (start ^ goal);\n int count = 0;\n \n while(a != 0) {\n if((a & 1) == 1) {\n count++;\n }\n \n a = a >> 1;\n }\n \n return count;\n }\n}\n\n```\n- JavaScript code ->\n```\nvar minBitFlips = function(start, goal) {\n let a = start ^ goal;\n let count = 0;\n \n while (a !== 0) {\n if (a & 1) {\n count++;\n }\n \n a = a >> 1;\n }\n \n return count;\n};\n``` | 108,770 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 4,015 | 29 | Number of different bits is the required bits to flip, to make start and goal same.\nWe can efficiently calculate them using xor operation : \n\n**Java one liner :** \n```\npublic int minBitFlips(int start, int goal) {\n return Integer.bitCount(start^goal);\n}\n```\n\n\n**CPP one liner :**\n```\nint minBitFlips(int start, int goal) {\n return __builtin_popcount(start^goal);\n}\n```\n\n**Python one liner :**\n```\ndef minBitFlips(self, start: int, goal: int) -> int:\n return (start ^ goal).bit_count()\n```\n\n**Javascript one liner :**\n```\nvar minBitFlips = function(start, goal) {\n return (start^goal).toString(2).split("0").join("").length;\n};\n``` | 108,771 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 756 | 12 | **C++**\n```cpp\nint minBitFlips(int start, int goal) {\n return __builtin_popcount(start ^ goal);\n}\n``` | 108,773 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,451 | 17 | # Divmod Remainder Approach:\n#### Time Complexity: O(log(min(s,g))) --> O(log(n)) \n#### Space Complexity: O(1)\n\nWe divide s and q by 2 until either s or g equals zero.\nDuring this process, if the remainder of either of them **do not** equal eachother, we increment the counter.\n\n***This process is similar to converting a decimal number to binary***\n\n**Example:** s=10 g=7\n\n| iterations | s (binary) | g (binary) | counter | explaination\n| - | --- | --- | --- | ---- |\n1| 1010 |0111|+1| The last digit of s and g are ***different***\n2| 0101 |0011|+0| The last digits are the **same** so we do nothing\n3| 0010 |0001|+1| The last digit of s and g are ***different***\n4| 0001 |0000|+1|The last digit of s and g are ***different***\n\n```Python []\nclass Solution:\n def minBitFlips(self, s: int, g: int) -> int:\n count = 0 \n while s or g:\n if s%2 != g%2: count+=1\n s, g = s//2, g//2\n return count\n```\n```Java []\nclass Solution {\n public int minBitFlips(int s, int g) {\n int count = 0;\n while(s > 0 || g > 0){\n if(s%2 != g%2) count++;\n s = s/2;\n g = g/2;\n }\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minBitFlips(int s, int g) {\n int count = 0;\n while(s > 0 || g > 0){\n if(s%2 != g%2) count++;\n s = s/2;\n g = g/2;\n }\n return count;\n }\n};\n```\n```PsudoCode []\nfunction minBitFlips(integer s, integer g){\n\tinitilize counter integer to 0\n\tloop until s or g is equal to zero{\n\t\tif the s mod 2 and g mod 2 have the same remainder, increment counter\n\t\tdivide s and g by 2 every pass\n\t}\n\treturn counter\n}\n```\n\n# PLEASE UPVOTE IF THIS HELPED YOU :)\n | 108,775 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 3,251 | 27 | ## Method-1\n\nWe find last bit of both start and goal by two and check if the bit is same or not. Then divide the numbers by 2.\n\n```\nclass Solution {\npublic:\n int minBitFlips(int start, int goal) {\n int ans=0;\n while(start>0 or goal>0){\n int temp1=start%2;\n int temp2=goal%2;\n if(temp1!=temp2){\n ans++;\n }\n start/=2;\n goal/=2;\n }\n return ans;\n }\n}; \n```\n\n## Method-2\n**XOR** start and goal to find the bits that are different\nUse in-built method **popcount** to count the number of set bits\n```\nclass Solution {\npublic:\n int minBitFlips(int start, int goal) {\n return __builtin_popcount(start^goal);\n }\n};\n``` | 108,776 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,515 | 8 | # Intuition\nWe want to check how many bits need to flipped in the input number to get the output number. So we would need to check the bits which are different in both numbers (No point in counting bits which are same in both) and count them.\n\n# Approach\nE.g. \n10 = 1010\n7 = 0111\nso different bits are, from rightmost bit, 1st, 3rd and 4th. \nWe know XOR operation between two numbers will give us these different bits.\n\n 1010\n ^ 0111\n ____________ \n 1101\nAs we see here, in the output number only bits are set which are different in both numbers. (1 ^ 1) = 0 and (1 ^ 0) = 1\n\nNow, we just have to count these set bits and for that we will use Kernighan\u2019s algorithm to find the number of set bits in a number. The idea behind the algorithm is that when we subtract one from an integer, all the bits following the rightmost set of bits are inverted, turning 1 to 0 and 0 to 1. The rightmost set bit also gets inverted with the bits right to it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minBitFlips(int start, int goal) {\n if(start == goal) return 0;\n int xor = start ^ goal;\n int counter=0;\n while(xor > 0) {\n xor = xor & (xor-1);\n counter++;\n }\n return counter;\n }\n}\n``` | 108,780 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,206 | 6 | We have to count all positions where the i\'th bit of number **A** and **B** is different , so just iterate from bit 32 to 0 and check.\n\n```\nclass Solution\n{\n public:\n int minBitFlips(int start, int goal)\n {\n int cnt = 0;\n for (int i = 32; i >= 0; i--)\n {\n\t\t\t\tint current = (1LL << i) & start;\n int required = (1LL << i) & goal;\n if (required != current)\n cnt++;\n }\n return cnt;\n }\n};\n```\n\nAfter submitting , I realised that we can get different bit when we will do **XOR** of **A** and **B** \nlike A = 101111\nlike B = 110001\nA^B = 011110 , so just count how many ones in A^B , to count 1\'s in a number we have a fucntion called **__builtin_popcount(N)** where N = A^B\n```\nclass Solution {\npublic:\n int minBitFlips(int A, int B) {\n return __builtin_popcount(A^B);\n }\n};\n\n``` | 108,783 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 2,407 | 20 | We need to count the number of corresponding bits of start and goal that are different.\nxor-ing start and goal will result in a new number with binary representation of 0 where the corresponding bits of start and goal are equal and 1 where the corresponding bits are different.\n\nFor example: 10 and 7 \n10 = 1010\n 7 = 0111\n \n10 xor 7 = 1101 (3 ones)\n\nNext we need to count the number of 1s (different bits)\nThe quickest way to count the number of 1s in a number is by eliminating the right most 1 each time and count the number of eliminations, this is done by and-ing the number with (number-1)\nSubtracting a 1 from a number flips all right most bits until the first right most 1 and by and-ing with the number itself we eliminating the all bits until the first tight most 1 (inclusive)\nex. \nnumber =1101\nnumber -1 = 1100\nnumber and (number -1) = 1100 (we eliminated the right most 1)\n\n```\nclass Solution {\n public int minBitFlips(int start, int goal) {\n int xor =start ^ goal;\n int count=0;\n while(xor>0){\n count++;\n xor=xor & (xor-1);\n }\n return count;\n \n }\n}\n``` | 108,784 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,402 | 7 | The given question requires us to count the total number of flips we need to do inorder to make `start -> goal`.\nEx: \n7 - 0111\n10 - 1010\nHere, we only flip the bits which are different in both **start** and **goal**, i.e. `01` or `10`. And, what helps us to find if the bits are different? **XOR**. \nNow, we count these bits (i.e. different bits). And how do we calculate the number of `1\'s` in a number? `n & (n-1)` technique.\n\nSo, the number of flips required is **3**.\n\nTherefore, the solution is divided into two parts - identify the distinct bits in both numbers and then, count these bits.\n\nSolution:\n```python\nclass Solution(object):\n def minBitFlips(self, start, goal):\n res = start ^ goal\n cnt = 0\n while res:\n res &= res - 1\n cnt += 1\n return cnt\n```\n\n | 108,787 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 855 | 7 | **Just xor so we get 1 at places where bits are different and then count those bits.**\n```\nclass Solution:\n def minBitFlips(self, start: int, goal: int) -> int:\n return (bin(start^goal).count("1"))\n``` | 108,789 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 667 | 5 | ```\nclass Solution {\npublic:\n int minBitFlips(int start, int goal) {\n int count=0;\n while(start && goal){\n if(start%2!=goal%2) count++;\n start/=2;\n goal/=2;\n }\n while(start){\n if(start%2)count++;\n start/=2;\n }\n while(goal){\n if(goal%2)count++;\n goal/=2;\n }\n return count;\n }\n};\n``` | 108,798 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 1,244 | 11 | **Please upvote if you find this solution helpful**\n**Code:**\n```\nclass Solution {\npublic:\n //we just check whether binary bit is equal or not \n //if it is we do nothing otherwise we flips the bit and increase the count\n int minBitFlips(int start, int goal) \n { \n int flips=0;\n\t\t\n\t\t//iterate until both numbers get 0\n while(start || goal)\n {\n\t\t\t//check whether bits are equal or not, if not we flip the bit\n if(start%2 != goal%2)\n flips++;\n \n start /= 2;\n goal /= 2;\n }\n return flips;\n \n }\n};\n``` | 108,805 |
Minimum Bit Flips to Convert Number | minimum-bit-flips-to-convert-number | A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal. | Bit Manipulation | Easy | If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip. | 674 | 5 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minBitFlips(self, start: int, goal: int) -> int:\n s=bin(start)[2:].zfill(50)\n g=bin(goal)[2:].zfill(50)\n count=0\n for i in range(50):\n if s[i]!=g[i]:\n count+=1\n return count\n``` | 108,806 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 14,573 | 169 | We can determine the multiplier for each number, how often it goes into the final result.\n\nConsider how often each entry in the triangle gets into the final digit (modulo 10). Let\'s build a triangle of these frequencies. The final digit **is** the result, so it gets into itself once:\n```\n. . . . .\n . . . .\n . . .\n . .\n 1\n```\nThe two digits above it each get into the bottom digit once:\n```\n. . . . .\n . . . .\n . . .\n 1 1\n 1\n```\nThe middle digit gets into both of those 1s, and thereby gets into the final digit *twice*. The border digits still only get into it once:\n```\n. . . . .\n . . . .\n 1 2 1\n 1 1\n 1\n```\nThe digit above `1 2` gets into the `1` and thereby into the final digit once, and it gets into the `2` and thereby into the final digit two more times. Three times overall:\n```\n. . . . .\n . 3 . .\n 1 2 1\n 1 1\n 1\n```\nWith the same argument, the full usage-frequency triangle is:\n```\n1 4 6 4 1\n 1 3 3 1\n 1 2 1\n 1 1\n 1\n```\nIt\'s simply [Pascal\'s triangle]() upside down.\n\nWe can now use the top row frequencies with the input row:\n```\nfrequencies: 1 4 6 4 1\ninput row: 1 2 3 4 5 (the problem\'s first example input)\nfinal digit: (1*1 + 4*2 + 6*3 + 4*4 + 1*5) % 10\n = (1 + 8 + 18 + 16 + 5) % 10\n = (1 + 8 + 8 + 6 + 5) % 10\n = 28 % 10\n = 8\n```\nSo the top row of frequencies is all we really need. It\'s the [binomial coefficients]() `mCk`, where `m = n-1` and `0 \u2264 k \u2264 m`. Which we can compute with the [multiplicative formula]():\n```\n m * (m-1) * ... * (m-k+1) \nmCk = -------------------------\n 1 * 2 * ... * k\n```\nThe next one, mC(k+1), is computed from mCk as mCk * (m-k) / (k+1). So we can compute the whole top row of frequencies from left to right with m multiplications and divisions.\n\nImplementation of that:\n\n def triangularSum(self, nums: List[int]) -> int:\n result = 0\n m = len(nums) - 1\n mCk = 1\n for k, num in enumerate(nums):\n result = (result + mCk * num) % 10\n mCk *= m - k\n mCk //= k + 1\n return result\n\nThe above has the issue that the binomial coefficients grow larger than O(1), so the above solution isn\'t O(n) time O(1) space yet. But the following optimized version is, as it keeps a small representation of the binomial coefficient. Even in Python, it can solve an input of a million digits in less than a second. Also, note that it doesn\'t modify the input, unlike other O(1) space solutions that overwrite it.\n\nIdeally we\'d just compute the binomial coefficient `mCk` modulo 10, as that\'s all we need. But while addition, subtraction and multiplication play well under modulo, division doesn\'t. Instead of dividing by `k+1`, we can *multiply* by its inverse modulo 10, but only if that inverse exists. Which it only does if `k+1` is coprime to 10. So only if `k+1` doesn\'t have factor 2 or 5. Most numbers do have those factors, so I extract those factors out of `mCk` and store the exponents of 2 and 5 separately:\n\nmCk ≡ mck * 2<sup>exp2</sup> * 5<sup>exp5</sup> (modulo 10)\n\nSo instead of `mCk`, I keep track of `mck` (kept modulo 10), `exp2` and `exp5`, and compute `mCk % 10` from them. For example if both `exp2` and `exp5` are positive, that means the full `mCk` is a multiple of both 2 and 5 and thus a multiple of 10. Which means modulo 10 it\'s 0, so the current `num` doesn\'t even play a role for the final result, so I skip it. Otherwise the multiplier is `mck` potentially multiplied by a factor depending on whether `exp2` and `exp5` are positive or 0. Powers of 2 are 2, 4, 8, 16, 32, 64, etc, modulo 10 they\'re 2, 4, 8, 6, 2, 4, etc, cycling through 2, 4, 8, 6. Powers of 5 are 5, 25, 125, 625, etc, modulo 10 that\'s always 5.\n\n def triangularSum(self, nums: List[int]) -> int:\n result = 0\n m = len(nums) - 1\n mck, exp2, exp5 = 1, 0, 0\n inv = (0, 1, 0, 7, 0, 0, 0, 3, 0, 9)\n for k, num in enumerate(nums):\n if not (exp2 and exp5):\n mCk_ = mck * (6, 2, 4, 8)[exp2 % 4] if exp2 else 5 * mck if exp5 else mck\n result = (result + mCk_ * num) % 10\n if k == m:\n return result\n\n # mCk *= m - k\n mul = m - k\n while not mul % 2:\n mul //= 2\n exp2 += 1\n while not mul % 5:\n mul //= 5\n exp5 += 1\n mck = mck * mul % 10\n\n # mCk //= k + 1\n div = k + 1\n while not div % 2:\n div //= 2\n exp2 -= 1\n while not div % 5:\n div //= 5\n exp5 -= 1\n mck = mck * inv[div % 10] % 10\n\t\t\t\nC++ version:\n\n int triangularSum(vector<int>& nums) {\n int result = 0;\n int m = nums.size() - 1;\n int mck = 1, exp2 = 0, exp5 = 0;\n int inv[] = {0, 1, 0, 7, 0, 0, 0, 3, 0, 9};\n int pow2mod10[] = {6, 2, 4, 8}; \n for (int k = 0; true; k++) {\n if (!exp2 || !exp5) {\n int mCk_ = exp2 ? mck * pow2mod10[exp2 % 4] :\n exp5 ? mck * 5 : mck;\n result = (result + mCk_ * nums[k]) % 10;\n }\n if (k == m)\n return result;\n\n // mCk *= m - k\n int mul = m - k;\n while (mul % 2 == 0) {\n mul /= 2;\n exp2++;\n }\n while (mul % 5 == 0) {\n mul /= 5;\n exp5++;\n }\n mck = mck * mul % 10;\n\n // mCk /= k + 1\n int div = k + 1;\n while (div % 2 == 0) {\n div /= 2;\n exp2--;\n }\n while (div % 5 == 0) {\n div /= 5;\n exp5--;\n }\n mck = mck * inv[div % 10] % 10;\n }\n }\n\t\nJava version:\n\n public int triangularSum(int[] nums) {\n int result = 0;\n int m = nums.length - 1;\n int mck = 1, exp2 = 0, exp5 = 0;\n int[] inv = {0, 1, 0, 7, 0, 0, 0, 3, 0, 9};\n int[] pow2mod10 = {6, 2, 4, 8};\n for (int k = 0; true; k++) {\n if (exp2 == 0 || exp5 == 0) {\n int mCk_ = exp2 > 0 ? mck * pow2mod10[exp2 % 4] :\n exp5 > 0 ? mck * 5 : mck;\n result = (result + mCk_ * nums[k]) % 10;\n }\n if (k == m)\n return result;\n\n // mCk *= m - k\n int mul = m - k;\n while (mul % 2 == 0) {\n mul /= 2;\n exp2++;\n }\n while (mul % 5 == 0) {\n mul /= 5;\n exp5++;\n }\n mck = mck * mul % 10;\n\n // mCk /= k + 1\n int div = k + 1;\n while (div % 2 == 0) {\n div /= 2;\n exp2--;\n }\n while (div % 5 == 0) {\n div /= 5;\n exp5--;\n }\n mck = mck * inv[div % 10] % 10;\n }\n }\n | 108,815 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 4,969 | 43 | **Approach-**\nIn 1st loop we iterate n-1 times as size of triangle decreases by 1 at every level.\nIn second loop we iterate the array and store the sum of nums[j] + nums[j+1] and store it in nums[j]\nHere we modify the same array to store the sum so O(1) space is used.\n\n```\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) {\n int n=nums.size();\n for(int i=n-1;i>=1;i--){\n for(int j=0;j<i;j++){\n nums[j]=(nums[j]+nums[j+1])%10; \n }\n }\n return nums[0];\n }\n}; | 108,819 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 6,112 | 35 | We can do a simulation for a O(n * n) solution, but it\'s not interesting. Instead, we will use a bit of math to look at more efficient solutions.\n\nEach number in the array contributes to the final sum a certain number of times. We can visualize how to figure out factors for each number using [Pascal\'s triangle]():\n\n![image]()\n\nFor test case `[1, 2, 3, 4, 5]`, we will get `1 * 1 + 2 * 4 + 3 * 6 + 4 * 4 + 5 * 1` = `1 + 8 + 18 + 16 + 5` = `48`, or `8` after modulo `10`.\n\nThe bottom row of Pascal\'s triangle are [binomial coefficients](), which can be computed as `nCr(n - 1, i)`. \n\n## Approach 1: comb\nUsing the built-in `comb` Python function to compute `nCr`.\n**Python 3**\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n return sum(n * comb(len(nums) - 1, i) for i, n in enumerate(nums)) % 10\n```\n\n## Approach 2: Iterative nCr\nThe `nCr` can be computed iteratively as `nCr(r + 1) = nCr(r) * (n - r) / (r + 1)`.\n**Python 3**\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n res, nCr, n = 0, 1, len(nums) - 1\n for r, num in enumerate(nums):\n res = (res + num * nCr) % 10\n nCr = nCr * (n - r) // (r + 1)\n return res\n```\n## Approach 3: Pascal Triangle\nThe approach 2 above won\'t work for C++ as `nCr` can get quite large. \n\n> We could use modular arithmetic with inverse modulo for the division. However, for modulus `10`, we need to put co-primes `5` and `2` out of brackets before computing the inverse modulo. Check out [this post]((n)-time-O(1)-space-Python-189-ms-C%2B%2B-22-ms-Java-4-ms) by [StefanPochmann]() to see how to do it.\n\nInstead, we can build the entire Pascal Triangle once (for array sizes 1..1000) and store it in a static array. From that point, we can compute the result for any array in O(n). The runtime of the code below is 12 ms.\n\n**C++**\nNote that here we populate the Pascal Triangle lazilly. \n```cpp\nint c[1001][1001] = {}, n = 1;\nclass Solution {\npublic:\nint triangularSum(vector<int>& nums) {\n for (; n <= nums.size(); ++n) // compute once for all test cases.\n for (int r = 0; r < n; ++r) \n c[n][r] = r == 0 ? 1 : (c[n - 1][r - 1] + c[n - 1][r]) % 10;\n return inner_product(begin(nums), end(nums), begin(c[nums.size()]), 0) % 10;\n}\n};\n``` | 108,823 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 349 | 5 | ```\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) { \n int n=nums.size();\n if(n==1) \n return nums[0];\n vector<vector<int>> ans;\n ans.push_back(nums);\n int k=n-1;\n for(int i=1;i<n;i++) \n {\n vector<int> v(k,1); \n int sum=0;\n for(int j=0;j<k;j++) \n {\n v[j]=(ans[i-1][j+1]+ans[i-1][j])%10;\n sum+=v[j];\n }\n k-=1;\n ans.push_back(v);\n if(k==0) \n return sum;\n }\n return 0;\n }\n};\n``` \nTHIS QUESTION IS SIMILIAR TO PASCALS TRIANGLE.\n**TIME COMPLEXITY:-O(N^2)**\n**SPACE COMPLEXITY:-O(N^2)** | 108,826 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 509 | 9 | # Intuition:We will use two pointers method and run through the array with loops and each time we reduce the length of array by decrement the right pointer.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n![photo_2023-04-18_06-15-46.jpg]()\n![photo_2023-04-18_06-15-52.jpg]()\n\n```C++ []\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) {\n int start = 0, end = nums.size() - 1;\n while (start < end) {\n for (int i = start; i < end; i++) {\n nums[i] = (nums[i] + nums[i + 1]) % 10;\n }\n end--;\n }\n return nums[0];\n }\n};\n```\n```C# []\npublic class Solution {\n public int TriangularSum(int[] nums) {\n int start = 0, end = nums.Length - 1;\n while (start < end) {\n for (int i = start; i < end; i++) {\n nums[i] = (nums[i] + nums[i + 1]) % 10;\n }\n end--;\n }\n return nums[0];\n }\n}\n```\n```javascript []\nvar triangularSum = function(nums) {\n let start = 0, end = nums.length - 1;\n while (start < end) {\n for (let i = start; i < end; i++) {\n nums[i] = (nums[i] + nums[i + 1]) % 10;\n }\n end--;\n }\n return nums[0];\n};\n```\n\n![Vote.png]()\n\n | 108,827 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 3,621 | 35 | ```\nclass Solution {\n public int triangularSum(int[] nums) {\n return find(nums,nums.length);\n }\n \n public int find(int[] a, int n){\n if(n == 1)\n return a[0];\n \n for(int i=0;i<n-1;i++){\n a[i] = (a[i] + a[i+1])%10; \n }\n return find(a,n-1);\n }\n}\n```\n![image]() | 108,829 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 1,465 | 20 | ```\n /** Algorithm\n * 1. Traverse the array from i = 0 to length and replace nums[i] with nums[i] + nums[i+1]\n * 2. Deduct 1 from the length with each traversal\n * 3. Return nums[0] when length becomes 1\n */\n public int triangularSum(int[] nums) {\n int length = nums.length;\n while(length > 1) {\n for (int i = 0; i < length -1; i++) {\n nums[i] = (nums[i] + nums[i+1]) % 10;\n }\n length--;\n }\n return nums[0];\n }\n``` | 108,836 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 210 | 7 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n=len(nums)\n while n>0:\n for i in range(n-1):\n nums[i]=(nums[i]+nums[i+1])%10\n n-=1\n return nums[0]\n``` | 108,839 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 2,948 | 22 | ```java\n public int triangularSum(int[] nums) {\n for (int n = nums.length; n > 0; --n) {\n for (int i = 1; i < n; ++i) {\n nums[i - 1] += nums[i];\n nums[i - 1] %= 10;\n }\n }\n return nums[0];\n }\n```\n```python\n def triangularSum(self, nums: List[int]) -> int:\n for j in range(len(nums), 0, -1):\n for i in range(1, j):\n nums[i - 1] += nums[i]\n nums[i - 1] %= 10\n return nums[0]\n```\n**Analysis:**\n\nTime: `O(n ^ 2)`, extra space: `O(1)`, where `n = nums.length`. | 108,844 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 1,513 | 13 | **C++ Solution**\n```\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) {\n \n int n(size(nums));\n while (n > 1) {\n for (int i=0; i<n-1; i++)\n nums[i] = (nums[i] + nums[i+1]) % 10;\n n--;\n }\n return nums[0];\n }\n};\n```\n\n**Java Solution**\n\n```\nclass Solution {\n public int triangularSum(int[] nums) {\n \n int n = nums.length;\n while (n > 1) {\n for (int i=0; i<n-1; i++)\n nums[i] = (nums[i] + nums[i+1]) % 10;\n n--;\n }\n return nums[0];\n }\n}\n``` | 108,845 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 878 | 17 | ## **Approach**\nIf you notice, we are only taking the modulo of the sum of the current element and the next element to form a new the updated current element. We will do this n (size of array) times. \nExample:\n```\nnums = [1,2,3,4,5,6]\n1 2 3 4 5 6\n3 5 7 9 1\n8 2 6 0 \n0 8 6\n8 4\n2\nThus, our answer is 2. \n```\n\n## **Code**\n```\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) {\n int n=nums.size();\n while(n--){\n for(int i=0;i<n;++i){\n nums[i]=(nums[i]+nums[i+1])%10;\n }\n }\n return nums[0];\n }\n};\n```\n**Time complexity:** O(n^2)\n**Space complexity:** O(1) | 108,847 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 1,548 | 8 | # Approach\nGoals: return the single element of triangular sum\n\n![image]()\n\n\nWe can see from the image that we will sum up the first cell and the second cell. Then, since it\'s triangular, the length of the top row is greater (+1) than the next row. \n\n## Brute Force\n\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n = len(nums)\n\n if n == 0: return 0\n if n == 1: return nums[0]\n\n prev = list(nums)\n while n > 1:\n cur = [0]*(n-1)\n for i in range(1, len(prev)):\n cur[i-1] = (prev[i] + prev[i-1]) % 10\n prev = cur\n n -= 1\n return cur[n//2]\n```\n\n## Optimal\n\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n = len(nums)\n while n > 0:\n for i in range(n-1):\n nums[i] = (nums[i] + nums[i+1]) % 10\n n -= 1\n return nums[0]\n``` | 108,849 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 572 | 5 | ## **Solution**\n\n#### **Code** \n```cpp\nclass Solution {\npublic:\n int triangularSum(vector<int>& nums) {\n vector<int> temp;\n \n while (nums.size() != 1){\n temp.clear();\n for (int i = 1; i < nums.size(); i++) {\n temp.push_back((nums[i] + nums[i - 1]) % 10);\n }\n cout << endl;\n nums = temp;\n }\n \n return nums[0];\n }\n};\n```\n\n## **Complexity**\n\n##### __Apporach : 1__ \n##### Time Complexity: **O(size_of_nums * size_of_nums)**, inner ```for``` loop will run for following time ==> (n - 1) + (n - 2) + (n - 3)......2. Now this series give O(n*n) complexity.\n\n##### Space Complexity: **O(size_of_nums)**, beacuse in worst case (first iteration) ```temp``` will be of size ```size_of_nums - 1```, and it will keep decreasing to one.\n\n\n<br>\n\n __Check out all [my]() recent solutions [here]()__\n\n \n __Feel Free to Ask Doubts\nAnd Please Share Some Suggestions\nHAPPY CODING :)__\n\n\n | 108,852 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 1,129 | 5 | See my latest update in repo [LeetCode]()\n## Solution 1.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N^2)\n// Space: O(1) extra space\nclass Solution {\npublic:\n int triangularSum(vector<int>& A) {\n for (int i = A.size(); i >= 1; --i) {\n for (int j = 0; j < i - 1; ++j) {\n A[j] = (A[j] + A[j + 1]) % 10;\n }\n }\n return A[0];\n }\n};\n``` | 108,853 |
Find Triangular Sum of an Array | find-triangular-sum-of-an-array | You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums. | Array,Math,Simulation,Combinatorics | Medium | Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step. | 596 | 5 | ```\nclass Solution:\n def helper(self, nums: List[int]) -> List[int]:\n dp = []\n i = 0\n while i < len(nums) - 1:\n dp.append((nums[i] + nums[i + 1]) % 10)\n i += 1\n return dp\n \n def triangularSum(self, nums: List[int]) -> int:\n while len(nums) > 1:\n nums = self.helper(nums)\n return nums[0]\n``` | 108,856 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 9,282 | 242 | The possible sequences of selected buildings is either "101" or "010".\n\nIf the current building is \'0\', then the number of sequences of pattern "101" will be the product of the number of occurances of building \'1\' before the current building to the number of occurances of building \'1\' after the current building and viceversa.\n\n```\nclass Solution {\npublic:\n long long numberOfWays(string s) {\n long long a=0,b=0,ans=0; // a and b are the number of occurances of \'1\' and \'0\' after the current building respectively.\n for(int i=0;i<s.length();i++){\n if(s[i]==\'1\')\n a++;\n else\n b++;\n }\n long long c=0,d=0; // c and d are the number of occurances of \'1\' and \'0\' before the current building respectively.\n for(int i=0;i<s.length();i++){\n if(s[i]==\'1\'){ // Counting the sequences of "010"\n ans+=(d*b);\n a--;\n c++;\n }\n else{ // Counting the sequences of "101"\n ans+=(a*c);\n b--;\n d++;\n }\n }\n return ans;\n }\n};\n```\n\nComplexity\nTime - O(n)\nSpace - O(1) | 108,861 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 5,872 | 194 | ***Please upvote if you find this helpful :)***\n\nThe only valid combinations possible are 101 and 010.\nSo, lets traverse the string and consider the current character as the centeral character of the combination. \n\nThis means, if the current character is \'0\', then all we need to do it find the number of 1 before this 0 and number of 1 after this 0 and multiply them to add them to the answer.\nWe do the same for the central character as \'1\' and count the number of 0 before and after this one.\n\n\n```\nclass Solution {\n public long numberOfWays(String s) {\n long ans = 0;\n int len = s.length();\n \n long totZeros = 0;\n \n for(int i=0;i<len;i++){\n totZeros += s.charAt(i)==\'0\'?1:0;\n }\n \n long totOnes = len - totZeros;\n \n long currZeros = s.charAt(0)==\'0\'?1:0;\n long currOnes = s.charAt(0)==\'1\'?1:0;\n \n for(int i=1;i<len;i++){\n if(s.charAt(i) == \'0\'){\n ans = ans + (currOnes * (totOnes-currOnes));\n currZeros++;\n }else{\n ans = ans + (currZeros * (totZeros-currZeros));\n currOnes++;\n }\n }\n return ans;\n }\n}\n``` | 108,863 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 5,813 | 149 | **Explanation:**\nWhen you meet a "0", you can possibly form "0", "10", "010" ending with a "0".\nWhen you meet a "1", you can possibly form "1", "01", "101" ending with a "1".\nUpdate the number of possible combinations when you traverse s.\n\n<iframe src="" frameBorder="0" width="1100" height="400"></iframe> | 108,864 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 4,737 | 131 | Traverse the input `s`:\n1. If encontering `0`, count subsequences ending at current `0`: `0`, `10` and `010`\'s; The number of `10` depends on how many `1`s before current `0`, and the number of `010` depends on how many `01` before current `0`;\n\nSimilarly, \n\n2. If encontering `1`, count subsequences ending at current `1`: `1`, `01` and `101`\'s; The number of `01` depends on how many `0`s before current `1`, and the number of `101` depends on how many `10` before current `1`.\n\n```java\n public long numberOfWays(String s) {\n long one = 0, zero = 0, oneZero = 0, zeroOne = 0, ways = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.charAt(i) == \'0\') {\n ++zero;\n oneZero += one; // Count in \'10\'.\n ways += zeroOne; // Count in \'010\'.\n }else {\n ++one;\n zeroOne += zero; // Count in \'01\'.\n ways += oneZero; // Count in \'101\'.\n }\n }\n return ways;\n }\n```\n```python\n def numberOfWays(self, s: str) -> int:\n ways = 0\n one = zero = zero_one = one_zero = 0\n for c in s:\n if c == \'0\':\n zero += 1\n one_zero += one\n ways += zero_one\n else:\n one += 1 \n zero_one += zero \n ways += one_zero\n return ways\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = s.length()`.\n\n----\n\n**Follow-up**\nWhat if the city official would like to select `k`, instead of `3`, buildings?\n\n~~~If **the upvotes can reach `25`**, I will provide time `O(k * n)` space `O(k)` code for the follow-up.~~~\n\nTraverse the input `s`:\n1. If encontering `0`, count subsequences ending at current `0`: `0`, `10` and `010`, `1010`\'s, ...,; The number of `10` depends on how many `1`s before current `0`, the number of `010` depends on how many `01` before current `0`, and the number of `1010` depends on how many `101` before current `0`...;\n\nSimilarly,\n\n2. If encontering `1`, count subsequences ending at current `1`: `1`, `01`, `101`, and `0101`\'s; The number of `01` depends on how many `0`s before current `1`, the number of `101` depends on how many `10` before current `1`, and the number of `0101` depends on how many `010` before current `1`...\n3. We can observe the above patterns and use a 2-D array `ways` to record the corresponding subsequences, e.g., \n \n\t ways[0][0] - number of `0`\'s;\n\t ways[1][0] - number of `10`\'s;\n\t ways[2][0] - number of `010`\'s;\n\t ways[3][0] - number of `1010`\'s;\n\t ...\n\t ways[0][1] - number of `1`\'s;\n\t ways[1][1] - number of `01`\'s;\n\t ways[2][1] - number of `101`\'s;\n\t ways[3][1] - number of `0101`\'s;\n\t ...\n\t \n```java\n public long numberOfWays(String s, int k) {\n // int k = 3;\n long[][] ways = new long[k][2]; \n for (int i = 0; i < s.length(); ++i) {\n int idx = s.charAt(i) - \'0\';\n ++ways[0][idx];\n for (int j = 1; j < k; ++j) {\n ways[j][idx] += ways[j - 1][1 - idx];\n }\n }\n return ways[k - 1][0] + ways[k - 1][1];\n }\n```\n```python\n def numberOfWays(self, s: str, k: int) -> int:\n # k = 3\n ways = [[0, 0] for _ in range(k)]\n for c in s:\n idx = ord(c) - ord(\'0\')\n ways[0][idx] += 1\n for i in range(1, k):\n ways[i][idx] += ways[i - 1][1 - idx]\n return sum(ways[-1])\n```\n**Analysis:**\n\nTime: `O(k * n)`, space: `O(k)`, where `n = s.length()`.\n\n**Do let me know** if you have an algorithm better than `O(k * n)` time or `O(k)` space for the follow-up. | 108,865 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 3,811 | 43 | See my latest update in repo [LeetCode]()\n\n## Solution 1. DP\n\nLet `dp[len][c]` be the count of alternating subsequences of length `len` ending with character `\'0\' + c\'`. The answer is `dp[3][0] + dp[3][1]`.\n\nWe can scan the array from left to right and compute these `dp[len][c]` values.\n\nFor each `dp[len][c]`, its count should increase by `dp[len - 1][1 - c]`, i.e. prepending subsequences of length `len - 1` ending with a different character.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n long long numberOfWays(string s) {\n long dp[4][2] = {};\n dp[0][0] = dp[0][1] = 1;\n for (int i = 0; i < s.size(); ++i) {\n for (int len = 1; len <= 3; ++len) {\n dp[len][s[i] - \'0\'] += dp[len - 1][1 - (s[i] - \'0\')];\n }\n }\n return dp[3][0] + dp[3][1];\n }\n};\n``` | 108,866 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 1,675 | 24 | In overall, they are only looking for \'101\' and \'010\'.\nWe keep track of previous \'0\' and \'1\' using variable \'z\' and \'o\'.\nWhen entering the next building, the previous \'0\' and \'1\' can be upgraded into \'01\' and \'10\' respectively as variable \'oz\' and \'zo\'.\nAgain, from the previous \'01\' and \'10\', we can upgrade them into \'010\' and \'101\' and put them both into variable \'total\', which will be the total valid ways to select 3 buildings.\n```\ndef sumScores(self, s):\n\t# Idea 1: count 0, 1, 01, 10\n z, o, zo, oz, total = 0, 0, 0, 0, 0\n for c in s:\n if c == \'1\':\n total += oz\n zo += z\n o += 1\n elif c == \'0\':\n total += zo\n oz += o\n z += 1\n return total\n | 108,869 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 1,415 | 33 | Step1. Count total number if zeros and ones in string. (count0 and count1)\nStep2. Iterate the string from left and keep count of zeroes and ones in till current index.(cur0 and cur1)\nStep3. There is only two case is possible 101 and 010. \n\tIf you encounter 1 then check for case 010\n\tAdd total no of combinations of 010 formed by taking currrent 1 as centre i.e\n\t\t= (total no of 0s on left) * (total no of 0s on right) = cur0 * (count0-cur0)\n\tIf you encounter 0 then check for case 101\n\tAdd total no of combinations of 101 formed by taking currrent 0 as centre i.e\n\t\t= (total no of 1s on left) * (total no of 1s on right) = cur1 * (count1-cur1)\t\n\t\treturn final ans.\t\n\n\n\n` long long numberOfWays(string s) {`\n \n int count0=0, count1=0;\n for(int i=0;i<s.size();i++)\n\t\t{\n if(s[i]==\'0\')\n count0++;\n else\n count1++;\n }\n long long int ans=0;\n int cur0=0,cur1=0;\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==\'1\')\n {\n cur1++;\n ans+=cur0*(count0-cur0);\n }\n else\n {\n cur0++;\n ans+=cur1*(count1-cur1);\n }\n }\n return ans;\n \n \n \n }\n\'\'\' | 108,870 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 2,202 | 37 | ```\nclass Solution\n{\n public long numberOfWays(String s)\n {\n int zero = 0; // Individual zeroes count\n long zeroOne = 0; // Number of combinations of 01s\n int one = 0; // Individual ones count\n long oneZero = 0; // Number of combinations of 10s\n long tot = 0; // Final answer\n for(char ch : s.toCharArray())\n {\n if(ch == \'0\')\n {\n zero++;\n oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10\n tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010\n }\n else\n {\n one++;\n zeroOne += zero; // Each of the previously found 0s can pair to form 01\n tot += oneZero; // Each of the previously formed 10 can form 101\n }\n }\n return tot;\n }\n}\n``` | 108,871 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 740 | 12 | we have only two types of string 101 or 010\n1. **101** - > 0 is middle , for this 0 find count of 1 in left and 1 in right\n2. **010** - > 1 is middle , for this 1 find count of 0 in left and 0 in right\n \n \n \n ----\n **created left and right array**\n \n **for each index i**\n **if ith index is \'1\' store count of 0 in left in 0 in right**\n **if ith index is \'0\' store count of 1 in left in 1 in right**\n \n for using ith element as middle we have left[i]*right[i] total strng\n > one loop to fill left i=0 to n-1\n > and one loop to fill right i= n-1 to 0\n \n\n\n```\nclass Solution {\n public long numberOfWays(String s) {\n long count0 = 0 , count1 = 0;\n int n = s.length();\n long left[] = new long[n];\n long right[] = new long[n];\n for(int i=0;i<n;i++){\n if(s.charAt(i)==\'1\' ){\n count1++;\n left[i] = count0;\n }\n if(s.charAt(i)==\'0\' ){\n count0++;\n left[i] = count1;\n } \n }\n \n count1 = 0;\n count0 = 0;\n for(int i = n-1 ;i>=0;i--){\n if(s.charAt(i)==\'1\' ){\n count1++;\n right[i] = count0;\n }\n if(s.charAt(i)==\'0\' ){\n count0++;\n right[i] = count1;\n } \n }\n \n long ways = 0;\n for(int i=0;i<n;i++){\n char chi = s.charAt(i);\n ways += left[i]*right[i];\n }\n\n return ways;\n \n }\n}\n``` | 108,875 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 2,233 | 20 | **Intuition :**\n\n* Idea here is similar to that of **Knapsack Problem**.\n* We have two choices for each building. \n\t* Either *pick it*\n\t* Or *skip it*\n* Using this way, we can move across given string and get count. And when length of selected string exceeds 3, simply return from there.\n* Just here we need to track previous element, so that we do not end up picking same type of buildings.\n* Thus, we have total three state and dp will look like :\n\t* `idx` : current index\n\t* `prev` : previous chosen building\n\t* `len` : length/number of buildings picked.\n* Base condition is when we either have picked 3 buildings, or else we have reached end of string.\n\nNote : We are assuming that if no building is picked, then `prev = 2`.\n# Code :\n```\nclass Solution {\nprivate: \n\tlong long dp[100003][3][4];\n\n long long solve(string& s, int idx, int prev, int len, int n) {\n if(len == 3) return 1;\n if(idx == n) {\n return 0;\n }\n if(dp[idx][prev][len] != -1) return dp[idx][prev][len];\n\n long long res = solve(s, idx+1, prev, len, n);\n\n if(prev != (s[idx]-\'0\')) {\n res += solve(s, idx+1, s[idx]-\'0\', len+1, n);\n }\n return dp[idx][prev][len] = res;\n }\n\npublic: \n \n long long numberOfWays(string s) {\n int n = s.size();\n memset(dp, -1, sizeof(dp));\n return solve(s, 0, 2, 0, n);\n }\n};\n```\n\n***If you find this helpful, do give it a like :)*** | 108,878 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 1,122 | 6 | ```\nclass Solution {\n public long numberOfWays(String s) {\n int n = s.length();\n long[][][] dp = new long[n][4][4];\n for(long[][] y : dp)\n for(long[] x : y)\n Arrays.fill(x,-1);\n return solve(0,0,\'2\',s.toCharArray(),dp);\n }\n public long solve(int i ,int c ,char prev ,char[] s,long[][][] dp){\n if(c==3)return 1;\n if(i>=s.length) return 0;\n if(dp[i][c][prev-\'0\']!=-1) return dp[i][c][prev-\'0\'];\n long a=0 ,b=0;\n if(s[i]!=prev){\n a= solve(i+1,c+1,s[i],s,dp); //if current char is not equal to previous then can take it .\n } \n b = solve(i+1,c,prev,s,dp);//if current char is same as previous then cannot take .so just look in the next char.\n \n return dp[i][c][prev-\'0\'] = (a+b);\n \n }\n}\n``` | 108,881 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 812 | 7 | there are only two types of pattern of choosing the three elemets.\nwhich are chosing 1 as middle element and 0 as side building and vice versa.\nso with the help of prefix and suffix sum array find the no. elemets which are left & right of cur element(0 or 1)\nand just add no. of possible ways i.e. (l[i]*r[i])\n```\nclass Solution {\npublic:\n\tlong long numberOfWays(string s) {\n\t\tlong long ans = solve(s, 0); // for 1 as middle element we need to make prefix and surfix array for 0\n\t\tans += solve(s, 1); // same for 0\n\t\treturn ans;\n\t}\n\n\tlong long solve(string s, int c) {\n\t\tlong long ans = 0;\n\t\tlong long n = s.size();\n\t\tvector<long long>l(n, 0), r(n, 0);\n\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tl[i] = cnt;\n\t\t\tif (s[i] == c + \'0\') {\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\tcnt = 0;\n\t\tfor (int i = n - 1; i >= 0; i--) {\n\t\t\tr[i] = cnt;\n\t\t\tif (s[i] == c + \'0\') {\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\tint x = (c == 0) ? 1 : 0;\n\t\tfor (int i = 1; i < n - 1; i++) {\n\t\t\tif (s[i] == x + \'0\') {\n\t\t\t\tans += l[i] * r[i];\n\t\t\t}\n\t\t}\n\n\t\treturn ans;\n\t}\n\n};\n```\n | 108,882 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 555 | 7 | **Solution 1: O(n) space**\n\nOnly 2 patterns are possible:\n`101`\n`010`\n\nCalculate 0s and 1s from left.\nCalculate 0s and 1s from right.\n\nFix the middle element of pattern e.g. `0` in `101`. \nThen total number of combinations will be `cnt(1s on the left) * cnt(1s on the right)`.\n\n\n```\ndef numberOfWays(self, s: str) -> int:\n n = len(s)\n right0, right1 = [0]*n, [0]*n # 0s and 1s to the right of index i\n left0, left1 = [0]*n, [0]*n # 0s and 1s to the left of index i\n\n cnt0, cnt1 = 0, 0\n for i in range(n-1,-1,-1): # right to left\n right0[i], right1[i] = cnt0, cnt1\n if s[i] == \'0\':\n cnt0 += 1\n else:\n cnt1 += 1\n \n \n cnt0, cnt1 = 0, 0\n for i in range(n):\n left0[i], left1[i] = cnt0, cnt1\n if s[i] == \'0\':\n cnt0 += 1\n else:\n cnt1 += 1\n \n\n res = 0\n for i in range(n):\n if s[i] == \'1\':\n res += left0[i] * right0[i] # 010\n else:\n res += left1[i] * right1[i] # 101\n return res\n```\n\n\n\n\n**Solution 2: O(1) space**\n\nBy rock: (1)-code-w-brief-explanation-and-analysis. \n\nCalculate the no. of patterns: `01` and `10`\nNow when you encounter 1, you can use the count of `10`s to the left and append this `1` to the end. This will count for `101`.\nNow when you encounter 0, you can use the count of `01`s to the left. This will count for `010`.\n\n\n```\ndef numberOfWays(self, s: str) -> int:\n ways = 0\n one = zero = zero_one = one_zero = 0\n for c in s:\n if c == \'0\':\n zero += 1\n one_zero += one\n ways += zero_one\n else:\n one += 1 \n zero_one += zero \n ways += one_zero\n return ways\n``` | 108,883 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 265 | 5 | **The Only ways in which you can select 3 buildings where consecutive buildings are not of same type are :\n010\n101**\nSo,when we will be traversing array we will keep track of count of 0\'s, 1\'s, 01\'s ,10\'s ,010\'s and 101\'s till now.\nSo,If current element is 0 then the count of 0\'s,10\'s and 010\'s will change.So:\ncount of 10\'s = count of 1\'s ( Because current 0 will get mapped with all previous 1\'s to make it 10)\ncount of 010\'s = count of 01\'s (Because current 0 will get mapped with previous 01\'s to make it 010]\ncount of 0\'s will increase by 1.\n\nIf current element is 1 then the count of 1\'s, 01\'s and 101\'s will change.So:\ncount of 01\'s = count of 0\'s ( Because current 1 will get mapped with all previous 0\'s to make it 01)\ncount of 101\'s = count of 10\'s ( Because current 1 will get mapped with previous 10\'s to make it 101)\n```\n long long numberOfWays(string s) {\n long int c0 = 0,c1=0,c01=0,c10 = 0,c010=0,c101=0;\n for(int i=0;i<s.size();i++)\n {\n if(s[i] == \'0\')\n {\n c10 += c1;\n c010 += c01;\n c0++;\n }\n else\n {\n c01 += c0;\n c101 += c10;\n c1++;\n }\n }\n return c010 + c101;\n \n }\n``` | 108,885 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 997 | 11 | We need to compute ways to pick `101` and `010` combinations of buildings. We can compute those ways independently.\n\nSay we want to count `010`. It\'s best to look at the specific test case, `"000110010"`:\n\n- `s[5]`: `first == 3`, `second == 2`.\n\t- `s[5]` forms 3 * 2 new combinations. We add it to `comb`.\n\t- `s[5]` adds `comb` (6) combinations to the result (6).\n\t- We reset `second` to zero.\n- `s[6]`: `first == 4`, `second == 0`.\n\t- `s[6]` does not form any new combinations (`second == 0`).\n\t- `s[6]` adds `comb` (6) combinations to the result (12).\n- `s[8]`: `first == 5`, `second == 1`.\n\t- `s[5]` forms 5 * 1 new combinations. We add it to `comb` (11).\n\t- `s[5]` adds `comb` (11) combinations to the result (23).\n\nSimilarly, we count the number of `101` combinations, which is 4. The final result is 27.\n\n**C++**\n```cpp\nlong long numberOfWays(string &s, char firstLast) {\n long long first = 0, second = 0, comb = 0, res = 0;\n for (char ch : s)\n if (ch == firstLast) {\n comb += first * second;\n res += comb;\n second = 0;\n ++first;\n }\n else\n ++second;\n return res;\n}\nlong long numberOfWays(string s) {\n return numberOfWays(s, \'0\') + numberOfWays(s, \'1\');\n}\n``` | 108,886 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 376 | 8 | 1. We\'ll just parse through the array from the last keeping the count of ones and zeros we\'ve passed through. Now when we\'ll arrive at a \'1\', the result will be incremented by the variable oneKeLiye and when we come at a \'0\' result would be incremented by zeroKeLiye.\n\n2. Now how do we maintain oneKeLiye and zeroKeLiye, we can observe that there are only two possible permutation i.e., "010" and "101", now oneKeLiye will store the total possibilities of making "01" after the current index (Therefore added when we arrive at a \'1\'). \n\n3. Similarly, zeroKeLiye will store the possibilites of storing "10" after the current index.\n\n4. Whenever we arrive at a zero we also increase oneKeLiye by the number of ones we\'ve encountered, which is basically the number of "01" when the 0 is at current index.\n\nHere\'s the code:\n\n long long numberOfWays(string s) {\n int n=s.size();\n long long int res=0;\n long long int ones=0,zeros=0;\n long long int oneKeLiye=0,zeroKeLiye=0;\n for(int i=n-1;i>=0;i--)\n {\n if(s[i]==\'1\')\n ones++;\n else\n zeros++;\n \n if(s[i]==\'1\'){\n zeroKeLiye+=zeros;\n res+=oneKeLiye;\n }\n else{\n oneKeLiye+=ones;\n res+=zeroKeLiye;\n }\n }\n return res;\n } | 108,889 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 793 | 13 | There are only 2 Types of Buildings valid for Selection: -> 101 & 010 since these represent an Alternate Subsequence of buildings.\nBut to build up to either of these building Types, we need to Build up on a smaller Subsequence Building.\nFor 101 we need 10, & for 10 we need buildings of type 1.\nLikewise, for 010 we need 01 & for 01 we need buildings of type 0.\n\nIf current char == \'0\', we do the following,\nincrease type 0 building, following which increase 10 type which depends on 1s & then increase 010 which depends on 01 type of buildings previously.\nLikewise we do it for other 3 set of Subsequences.\n\n```\nclass Solution {\n public long numberOfWays(String s) {\n long n0 = 0, n1 = 0, n01 = 0, n10 = 0, n010 = 0, n101 = 0;\n for(char c: s.toCharArray())\n {\n if(c == \'0\')\n {\n n0++;\n n10 += n1;\n n010 += n01;\n }\n else\n {\n n1++;\n n01 += n0;\n n101 += n10;\n }\n }\n \n return n101 + n010;\n }\n}\n``` | 108,890 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 546 | 8 | ```\ndef numberOfWays(self, s: str) -> int:\n ways = one = zero = onesAfterZero = zerosAfterOne = 0\n\t\tfor i in s:\n\t\t\tif i == \'0\':\n\t\t\t\tzero += 1\n\t\t\t\tzerosAfterOne += one\n\t\t\t\tways += onesAfterZero\n\t\t\telse:\n\t\t\t\tone += 1\n\t\t\t\tonesAfterZero += zero\n\t\t\t\tways += zerosAfterOne\n\t\treturn ways\n``` | 108,892 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 168 | 5 | The idea is for every character (\'0\' or \'1\') at index i, the possible solutions that can be formed from it are:\nnumber of the opposite of this character that occured before it (e.i. if it is \'0\', then number of 1\'s before it) * number of 1\'s occured after it and vice versa.\n\n```\nvar numberOfWays = function (s) {\n \n let result = 0,\n zeroes = s.replaceAll(\'1\', \'\').length,\n ones = s.length - zeroes,\n curZeroes = 0,\n curOnes = 0;\n\n for (let i = 0; i < s.length; i++) {\n s[i] === \'0\'\n ? (result += curOnes * (ones - curOnes))\n : (result += curZeroes * (zeroes - curZeroes));\n \n s[i] === \'0\' ? curZeroes++ : curOnes++;\n }\n return result;\n};\n``` | 108,893 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 1,334 | 10 | ```\nclass Solution:\n def numberOfWays(self, s: str) -> int:\n \n temp = []\n c0 = 0\n c1 = 0\n for char in s :\n if char == "0" :\n c0+=1\n else:\n c1+=1\n temp.append([c0,c1])\n \n total0 = c0\n total1 = c1\n \n \n count = 0\n for i in range(1, len(s)-1) :\n \n if s[i] == "0" :\n m1 = temp[i-1][1]\n m2 = total1 - temp[i][1]\n count += m1*m2\n \n else:\n m1 = temp[i-1][0]\n m2 = total0 - temp[i][0]\n count += m1*m2\n return count\n \n \n``` | 108,900 |
Number of Ways to Select Buildings | number-of-ways-to-select-buildings | You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings. | String,Dynamic Programming,Prefix Sum | Medium | There are only 2 valid patterns: β101β and β010β. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β01β or β10β first. Let n01[i] be the number of β01β subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β0βs and β1βs that exists in the prefix of s up to i respectively. Then n01[i] = n01[i β 1] if s[i] == β0β, otherwise n01[i] = n01[i β 1] + n0[i β 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β101β and β010β subsequences. | 320 | 6 | ```\n/*\n\nThere can be only two types of selections: 101 or 010\n\n-> Iterate over the string and in each iteration,\n\tIf current character is \'0\', it can be the middle of "101" slection\n\t\tadd how many selections can be there with this \'0\' as the middle element\n\t\t(this is, numbers of ones on the left * number of ones on the right)\n\tIf current character is \'1\', it can be the middle of "010" selection\n\t\tadd how many selections can be there with this \'1\' as the middle element\n\t\t(this is, numbers of zeros on the left * number of zeros on the right)\n-> return ans\n*/\nclass Solution {\npublic:\n long long numberOfWays(string s) {\n long long left0 = 0, left1 = 0, count0 = 0, count1 = 0, ans = 0;\n for(char ch : s) {\n count0 += (ch == \'0\');\n count1 += (ch == \'1\');\n }\n for(int i=0; i<s.length(); i++) {\n if(s[i] == \'1\') ans += left0 * (count0 - left0);\n if(s[i] == \'0\') ans += left1 * (count1 - left1);\n left0 += (s[i] == \'0\');\n left1 += (s[i] == \'1\');\n }\n return ans;\n }\n};\n\n``` | 108,901 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 4,778 | 52 | Actually, what is asked to find in this problem is famous z-function. For more details please see . If you know this algorithm, this problem is a piece of cake. If you not, it becomes much more difficult.\n\n#### Complexity\nIt is `O(n)` for time and space.\n\n#### Code\n```python\nclass Solution:\n def sumScores(self, s):\n def z_function(s):\n n = len(s)\n z = [0] * n\n l, r = 0, 0\n for i in range(1, n):\n if i <= r:\n z[i] = min(r - i + 1, z[i - l])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if i + z[i] - 1 > r:\n l, r = i, i + z[i] - 1\n return z\n \n return sum(z_function(s)) + len(s)\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 108,910 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 4,455 | 45 | ## Approach 1: LPS (KMP)\nWe build the Longest Prefix Suffix (LPS) array - which is what we would do for the KMP algorithm.\n\nThen, we use the `cnt` array to count the number of times each character appears in a prefix. Summing up `cnt` will give us the length of all prefixes. \n\nLet\'s use `"bababbababb"` as the example . LPS and count arrays are as follows:\n\n- `[0, 0, 1, 2, 3, 1, 2, 3, 4, 5, 6]`\n- `[0, 0, 1, 1, 2, 1, 1, 2, 2, 3, 2]`\n\nIndeed, the letter `b` in position `8` appears in 3 prefixes: `bababb`, `bab` and `b`. Letter `b` in position `9` appears in `bababb` and `b`.\n\n**C++**\n```cpp\nvector<int> lps(string &s) {\n vector<int> lps(s.size());\n for (int i = 1, j = 0; i < s.size(); ++i) {\n while (j && s[i] != s[j])\n j = max(0, lps[j - 1]);\n j += s[i] == s[j];\n lps[i] = j;\n }\n return lps;\n} \nlong long sumScores(string s) {\n vector<int> cnt;\n for (int j : lps(s))\n cnt.push_back(j == 0 ? 0 : cnt[j - 1] + 1); \n return accumulate(begin(cnt), end(cnt), 0LL) + s.size();\n}\n```\n\n## Approach 2: Z-function\nFundamentally, this approach is similar to the one above. The Z-function computes the longest prefix for all suffixes directly, reusing previously computed prefix sizes.\n\nWatching a video on YouTube (search for Z-function) is perhaps the fastest way to learn this algorithm. For the example above (`"bababbababb"`), the `z` array will look like this:\n- `[0, 0, 3, 0, 1, 6, 0, 3, 0, 1, 1]`\n\n**C++**\n```cpp\nvector<int> z(string &s) {\n vector<int> z(s.size());\n int l = 0, r = 1;\n for (int i = 1; i < s.size(); ++i) {\n z[i] = i > r ? 0 : min(r - i, z[i - l]);\n while (i + z[i] < s.size() && s[z[i]] == s[z[i] + i])\n ++z[i];\n if (z[i] + i > r) {\n l = i;\n r = z[i] + i;\n }\n }\n return z;\n}\nlong long sumScores(string s) {\n vector<int> cnt = z(s);\n return accumulate(begin(cnt), end(cnt), 0LL) + s.size();\n}\n``` | 108,911 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 1,838 | 18 | ```\nclass Solution {\n const long long mod = 1000000007LL;\n long long binexp(long long b, int p){\n b %= mod;\n long long result = 1%mod;\n while(p){\n if(p%2){\n result = result * b %mod;\n }\n b = (b * b %mod);\n p/=2;\n }\n return result;\n }\npublic:\n long long sumScores(string s) {\n vector<long long>p(s.size()+1), mi(s.size() + 1), ps(s.size()+1);\n const long long base = 61;\n p[0] = 1;\n for(int i = 1; i <= s.size(); i++){\n p[i] = (p[i-1] * base)%mod; // base to the power i\n mi[i] = binexp(base, mod-1-i); // modular inverse of base to the power i\n //cout << "p[" << i << "]: " << p[i] << endl;\n //cout << "mi[" << i << "]: " << mi[i] << endl;\n }\n \n long long hash = 0;\n for(int i = 0; i < s.size(); i++){\n hash = (hash + p[i+1]*(s[i]-\'a\'+1)%mod)%mod;\n ps[i] = hash;\n }\n \n long long ans = s.size();\n for(int i = 0; i < s.size(); i++){\n int lo = i+1, hi = s.size()-1;\n int len = 0;\n while(lo <= hi){\n int m = (lo + hi)/2;\n hash = ((ps[m]-ps[i]+mod)%mod)*mi[i+1]%mod;//hash of substring i+1 to m\n //cout << m << \' \' << m-i << \' \' << s.substr(i+1, m-i) << \' \' << hash << endl;\n if(hash == ps[m-i-1]){\n lo = m+1;\n len = m-i;\n } else {\n hi = m-1;\n }\n }\n ans += len;\n }\n \n return ans;\n }\n};\n``` | 108,912 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 920 | 8 | Taken directly from [Competitive Programmer\'s Handbook]()\n```\npublic long sumScores(String s) {\n\tchar[] ca= s.toCharArray();\n\tint n= ca.length, x= 0, y= 0;\n\tint[] z= new int[n];\n\tlong ans= n;\n\tfor(int i= 1; i<n; i++) {\n\t\tz[i]= Math.max(0, Math.min(z[i-x], y-i+1));\n\t\twhile(i+z[i] < n && ca[z[i]] == ca[i+z[i]]){\n\t\t\tx= i; y= i+z[i]; z[i]++;\n\t\t}\n\t\tans+= z[i];\n\t}\n\treturn ans;\n} | 108,913 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 1,696 | 21 | **Code**\n```java\n// calculate Z array\npublic int[] calculateZ(char[] input) {\n\tint[] Z = new int[input.length];\n\tint left = 0, right = 0;\n\tfor (int i = 1; i < input.length; i++) {\n\t\tif (i > right) {\n\t\t\tleft = right = i;\n\t\t\twhile (right < input.length && input[right] == input[right - left]) {\n\t\t\t\tright++;\n\t\t\t}\n\t\t\tZ[i] = right - left;\n\t\t\tright--;\n\t\t} else {\n\t\t\tint k = i - left;\n\t\t\tif (Z[k] < right - i + 1) {\n\t\t\t\tZ[i] = Z[k];\n\t\t\t} else {\n\t\t\t\tleft = i;\n\t\t\t\twhile (right < input.length && input[right] == input[right - left]) {\n\t\t\t\t\tright++;\n\t\t\t\t}\n\t\t\t\tZ[i] = right - left;\n\t\t\t\tright--;\n\t\t\t}\n\t\t}\n\t}\n\treturn Z;\n}\n\npublic long sumScores(String s) {\n\tint[] z = calculateZ(s.toCharArray());\n\n\tlong sum = 0;\n\tfor(int el: z)\n\t\tsum += el;\n\tsum += s.length();\n\treturn sum;\n}\n```\n\n**Explanation**\nBasically Z-Algorithm is used for finding pattern occurences in input string, but given problem was very good example where Z-Algorithm can be used.\nLet me explain what is the result of Z[] array for a given string.\nInitial brute force approach of finding this array is:-\n```java\nint[] z = new int[s.length()];\nfor(int i = 1; i < s.length(); i++){\n\tint k = i, j = 0;\n\twhile(k < s.length() && s.charAt(k) == s.charAt(j)){\n\t\tz[i]++;\n\t\tk++; j++;\n\t}\n}\n```\n\nEg. Let string `s = "aabcaadaab"`\nthen output array = `{0, 1, 0, 0, 2, 1, 0, 3, 1, 0}`\nvalue at each index represents length of longest prefix from 0th index for ith index starting substring.\nLet\'s suppose look at index 4th, it\'s value is 2 which indicates that 4th and 5th index ("aa") are a prefix of this string.\nSimilarly at 7th index, 3 indicates length of indices (7, 8, 9) "aab" which is prefix of entire string.\n\nSo according to our question we were required to find sum for all string lengths, which is starting from back till start. So we just need to find sum of entire array.\nAfter finding sum of Z[] array, add length of string `s` to sum because if whole string is compared it will be added every time.\n\nHope it helps\nThanks\nDo upvote\n | 108,914 |
Sum of Scores of Built Strings | sum-of-scores-of-built-strings | You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si. The score of si is the length of the longest common prefix between si and sn (Note that s == sn). Given the final string s, return the sum of the score of every si. | String,Binary Search,Rolling Hash,Suffix Array,String Matching,Hash Function | Hard | Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i? | 1,074 | 7 | \n* This problem is much more easier if you know Z algorithm\n* Basicly Z algorithm builds a array that contains the\nlength of the longest substring of s that begins at position k and is a prefix of s for each index k = 1,..., n \u2212 1 in linear time complexity.\n* This algo is very difficult to understand but it\'s super cool and interesting. Similar idea can be applied to learn Manacher\'s algorithm, that used for Palindrome problems.\n* I don\'t think I can explain better than this guy, so I put [the link **HERE**]() for your reference. \n\n<iframe src="" frameBorder="0" width="800" height="520"></iframe>\n\n**Complexity**\n* Time: `O(N)`\n* Space : `O(N)` | 108,916 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 971 | 5 | \n\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int>odd,even;//To store the even and odd values in descending order separately;\n\n vector<int>seq,nitin; //Seq vector to store the sequence of odd and even occurrences and nitin vector to store the values of priority queue in order;\n\n while(num>0) \n // To split and store the even digits in even priority queue and odd in odd priority queue and all the digits in seq vector;\n { \n int last=num%10;\n if(last%2==0)\n {\n even.emplace(last);\n }\n else\n {\n odd.emplace(last);\n }\n num=num/10;\n seq.emplace_back(last);\n }\n reverse(seq.begin(),seq.end());//reverse the vectore since the digits are stored in reverse order in the vector.\n int ans=0;\n for(int i=0;i<seq.size();i++) //store the digits from even and odd priority queue into nitin vector according to the occurrences.\n\n {\n if(seq[i]%2==0)\n {\n nitin.emplace_back(even.top());\n even.pop();\n }\n else\n {\n nitin.emplace_back(odd.top());\n odd.pop();\n }\n\n }\n for(int i=0;i<nitin.size();i++) //Store the final values in answer.\n {\n ans=ans*10+nitin[i];\n }\n return ans;\n }\n};\n``` | 108,964 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 7,264 | 89 | The simple idea is to store even and odd digits of the number **num** into 2 priority queues (max heap); and then iterate over every digit of **num** to look for places having odd (or even) digits. And then placing the top of the respected queues over those postions.\n\nPlease do upvote if this solution helps.\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n priority_queue<int> p; // priority queue to store odd digits in descending order\n priority_queue<int> q; // priority queue to store even digits in descending order\n string nums=to_string(num); // converting num to a string for easy access of the digits\n int n=nums.size(); // n stores the number of digits in num\n \n for(int i=0;i<n;i++){\n int digit=nums[i]-\'0\'; \n if((digit)%2) // if digit is odd, push it into priority queue p\n p.push(digit);\n else\n q.push(digit); // if digit is even, push it into priority queue q\n }\n \n int answer=0;\n for(int i=0; i<n; i++){\n answer=answer*10;\n if((nums[i]-\'0\')%2) // if the digit is odd, add the largest odd digit of p into the answer\n {answer+=p.top();p.pop();}\n else\n {answer+=q.top();q.pop();} // if the digit is even, add the largest even digit of q into the answer\n }\n return answer;\n }\n};\n```\nSpace: O(n)\nTime: O(nlogn)\n\nAny reccomendations are highly appreciated... | 108,966 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 4,369 | 44 | Look for a digit on the right that is bigger than the current digit and has the same parity, and swap them.\n```(a[j] - a[i]) % 2 == 0``` parity check (true if both a[j] and a[i] are even or both are odd)\n```java\n public int largestInteger(int n){\n char[] a = String.valueOf(n).toCharArray();\n for(int i = 0; i < a.length; i++)\n for(int j = i + 1; j < a.length; j++)\n if(a[j] > a[i] && (a[j] - a[i]) % 2 == 0){\n char t = a[i];\n a[i] = a[j];\n a[j] = t;\n }\n return Integer.parseInt(new String(a));\n } | 108,971 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 1,990 | 28 | ```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s=to_string(num); //first covert the num into a string for easy traversal\n priority_queue<int> odd, even; // then take 2 priority queue odd & even\n for(auto x: s){\n int tmp=x-\'0\'; // covert char to int\n if(tmp%2==0) even.push(tmp); // if tmp is even the push it into even priority queue\n else odd.push(tmp); // else tmp is odd & the push it into odd priority queue\n }\n\t\t// now traverse the string and find whether it is a odd no.\'s position or even no.\'s position\n for(auto& x: s){\n int tmp=x-\'0\'; // converting char to int\n if(tmp%2==0) x= even.top()+\'0\', even.pop(); // if it is even no.\'s position then put there, even priority queue\'s top element & pop that element\n else x= odd.top()+\'0\', odd.pop(); // else it is odd no.\'s position so put there, odd priority queue\'s top element & pop that element\n }\n return stoi(s); // finally convert the string into int and return it!\n }\n};\n\n// P.S: here one more thing why i\'ve written +\'0\' with the top() element?\n// - As in priority queue I\'m using int, so to convert it into a char i\'ve used " +\'0\' " [ascii sum]\n```\n\n**If you like this please upvote!** | 108,972 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 3,268 | 28 | Perhaps not as concise - shooting for efficiency (linear time and no string operations).\n\nWe count how much of each number we have in `cnt`.\n\nThen, we process digits in `num` right to left, determine the parity `par`, and use the smallest number with that parity from the `cnt` array.\n\nWe start from `0` for even, and from `1` for odd. If the count of a number reaches zero, we move up to the next number with the same parity (0 -> 2, 1 -> 3, and so on).\n\n**C++**\n```cpp\nint largestInteger(int num) {\n int cnt[10] = {}, p[2] = {0, 1}, res = 0;\n for (int n = num; n > 0; n /= 10)\n ++cnt[n % 10];\n for (long long n = num, mul = 1; n > 0; n /= 10, mul *= 10) {\n int par = n % 10 % 2 == 1;\n while (cnt[p[par]] == 0)\n p[par] += 2;\n res += mul * p[par];\n --cnt[p[par]];\n }\n return res;\n}\n``` | 108,973 |
Largest Number After Digit Swaps by Parity | largest-number-after-digit-swaps-by-parity | You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps. | Sorting,Heap (Priority Queue) | Easy | The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity. | 2,388 | 16 | ```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int> odd,even,arr;\n while(num)\n {\n int digit =num%10;\n num=num/10;\n if(digit%2==0)\n {\n even.push_back(digit);\n }\n else\n {\n odd.push_back(digit);\n }\n arr.push_back(digit);\n \n }\n sort(even.rbegin(),even.rend());\n sort(odd.rbegin(),odd.rend());\n \n int o=0,e=0;\n int ans=0;\n int n=arr.size();\n for(int i=0;i<arr.size();i++)\n {\n if(arr[n-1-i]%2==0)\n {\n ans=ans*10+even[e++];\n }\n else\n {\n ans=ans*10+odd[o++];\n }\n }\n return ans;\n }\n};\n``` | 108,976 |