question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
swap-adjacent-in-lr-string | Fully explained | C++ ✅ | Easy to Understand ✅ | fully-explained-c-easy-to-understand-by-be86h | \n# Approach\n1. First, we need to check if both strings, excluding \'X\', are identical in character order.\n This ensures that the transformation is at leas | Taranum_01 | NORMAL | 2024-08-12T11:03:47.959422+00:00 | 2024-08-13T18:08:56.513992+00:00 | 462 | false | \n# Approach\n1. First, we need to check if both strings, excluding \'X\', are identical in character order.\n This ensures that the transformation is at least possible based on character content.\n 2. Next, we iterate through both strings using two pointers. We skip \'X\' characters \n and compare the positions of \'L\' and \'R\' in both strings:\n a. For \'L\', it should never move right (so it can\'t be further to the right in the end string).\n b. For \'R\', it should never move left (so it can\'t be further to the left in the end string).\n3. If we find any inconsistency in these positions, we return false. If we complete the checks\n without finding inconsistencies, we return true.\n\n\n# Complexity\n- Time complexity: O(n)\n We traverse each string only once, comparing and checking positions of characters.\n\n- Space complexity: O(n)\n The extra space used is for the filtered strings without \'X\', which in the worst case could be of length n.\n\n# Code\n```\nclass Solution {\npublic:\n\n bool canTransform(string start, string end) {\n // If lengths are different, transformation is impossible\n if (start.length() != end.length()) {\n return false;\n }\n \n // Create strings without \'X\' to check if character sequences match\n string startChars, endChars;\n for (char c : start) {\n if (c != \'X\') startChars += c;\n }\n for (char c : end) {\n if (c != \'X\') endChars += c;\n }\n \n // If the sequences without \'X\' don\'t match, return false\n if (startChars != endChars) {\n return false;\n }\n \n // Initialize pointers for both strings\n int p1 = 0, p2 = 0;\n int n = start.size();\n \n while (p1 < n && p2 < n) {\n // Skip \'X\' in both strings\n while (p1 < n && start[p1] == \'X\') p1++;\n while (p2 < n && end[p2] == \'X\') p2++;\n \n // If both pointers reach the end, the strings are transformable\n if (p1 == n && p2 == n) {\n return true;\n }\n \n // If only one pointer reaches the end, strings aren\'t transformable\n if (p1 == n || p2 == n) {\n return false;\n }\n \n // If current characters don\'t match, transformation is impossible\n if (start[p1] != end[p2]) {\n return false;\n }\n \n // \'L\' should not move right (should be left or same position)\n if (start[p1] == \'L\' && p1 < p2) {\n return false; \n }\n // \'R\' should not move left (should be right or same position)\n if (start[p1] == \'R\' && p1 > p2) {\n return false; \n }\n \n // Move to the next character in both strings\n p1++;\n p2++;\n }\n \n // If all checks pass, the transformation is possible\n return true;\n }\n};\n``` | 5 | 1 | ['C++'] | 0 |
swap-adjacent-in-lr-string | Python O(n) with comments and reasonings | python-on-with-comments-and-reasonings-b-kkw3 | \n\nclass Solution:\n \'\'\'\n 1. The order of L and Rs in the start and end must be the same as L and R cannot cross one another. The allowed transformat | cutkey | NORMAL | 2022-05-17T09:00:29.884553+00:00 | 2022-05-17T09:04:06.333359+00:00 | 517 | false | ```\n\nclass Solution:\n \'\'\'\n 1. The order of L and Rs in the start and end must be the same as L and R cannot cross one another. The allowed transformations are \n equivalent to an L/R swapping position with an adjacent X (Left X for L and right X for R). In other words L and R can cross an X \n\t (to the left and right respectively) but they can\'t cross one another.\n 2. Since an L can only cross to the left (of an X), in the destination the index of an L must be the same or less than that of the \n corresponding L in start.\n 3. Similarly since an R can only cross to the Right, in the destination the index of an R must be the same or greater than that of the \n corresponding R in start .\n \'\'\'\n\t\n def canTransform(self, start: str, end: str) -> bool:\n \'\'\'\n Check if order is the same (condition 1)\n \'\'\'\n if start.replace("X", "") != end.replace("X", ""):\n return False\n \n \'\'\'\n Check conditions 2 and 3\n \'\'\'\n startLIndexes = [i for i in range(len(start)) if start[i] == "L"]\n startRIndexes = [i for i in range(len(start)) if start[i] == "R"]\n endLIndexes = [i for i in range(len(end)) if end[i] == "L"]\n endRIndexes = [i for i in range(len(end)) if end[i] == "R"]\n \n for i in range(len(startLIndexes)):\n if endLIndexes[i] > startLIndexes[i]:\n return False\n \n for i in range(len(startRIndexes)):\n if endRIndexes[i] < startRIndexes[i]:\n return False\n \n return True\n\n\n``` | 5 | 0 | [] | 1 |
swap-adjacent-in-lr-string | Python One Pass O(N) Time O(1) Space | python-one-pass-on-time-o1-space-by-bz23-4mqz | Observations:\n1. R can only be moved to right\n2. L can only be moved to left\n3. Relative order of R and L cannot be changed\n\nThus, at any given index i, nu | bz2342 | NORMAL | 2022-01-09T03:15:15.400273+00:00 | 2022-01-09T03:15:15.400305+00:00 | 537 | false | Observations:\n1. R can only be moved to right\n2. L can only be moved to left\n3. Relative order of R and L cannot be changed\n\nThus, at any given index `i`, number R in `start[:i+1]` >= in ` end[:i+1]`, number of L in `start[:i+1]` <= in `end[:i+1]`. \n\nSolution: go thru start and end from left to right, maintain two variables and both variables must be non-negative all the time (recall the observations above).\n\n+ `count_R`: count of R in `start[:i+1]` - count of R in `end[:i+1]`\n+ `count_L`: count of L in `end[:i+1]` - count of L in `start[:i+1]`\n\nBesides, when we are waiting for a L in `start` (`count_L` > 0), we must see next L before next R in `start` (observation 3). Similarly, when we are waiting for a R in `end` (`count_R` > 0), we must see next R before next L in `end`.\n\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n count_R = count_L = 0\n\t\t\n for i in range(len(start)):\n if start[i] == \'R\':\n if count_L > 0:\n return False\n count_R += 1\n if end[i] == \'R\':\n count_R -= 1\n if count_R < 0:\n return False\n if end[i] == \'L\':\n if count_R > 0:\n return False\n count_L += 1\n if start[i] == \'L\':\n count_L -= 1\n if count_L < 0: \n return False\n if count_R or count_L:\n return False\n return True\n``` | 5 | 0 | ['Python'] | 0 |
swap-adjacent-in-lr-string | Simplest Python Solution O(n) | simplest-python-solution-on-by-deo_stree-tdt7 | \'\'\'\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n \n so , eo , sind, eind = [],[],[],[]\n for i in range | Deo_Street | NORMAL | 2021-09-30T06:22:37.434183+00:00 | 2021-09-30T06:22:37.434214+00:00 | 1,370 | false | \'\'\'\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n \n so , eo , sind, eind = [],[],[],[]\n for i in range(len(start)):\n if start[i] != \'X\':\n so.append(start[i])\n sind.append(i)\n if end[i] != \'X\':\n eo.append(end[i])\n eind.append(i)\n if so != eo:\n return False\n \n for j in range(len(so)):\n if so[j] == \'L\' and eind[j]>sind[j]:\n return False\n if so[j] == \'R\' and eind[j]<sind[j]:\n return False\n \n return True\n\'\'\'\nThe idea is to initialy check whether the starting and the ending position have the same order of R and L configuration. We can imagine that X is the space that L and R can move along the array. So, we can check whether we can move R to the right or L to the left with the provided space. | 5 | 0 | ['Python', 'Python3'] | 1 |
swap-adjacent-in-lr-string | Easy to follow C++ solution | easy-to-follow-c-solution-by-levins-9k1k | We just need to record each \'L\' and \'R\' positions in both string, and compare them. Since \'L\' can only move left and \'R\' can only move right, \'L\' pos | levins | NORMAL | 2021-04-25T20:10:44.052182+00:00 | 2021-04-25T20:11:34.492197+00:00 | 378 | false | We just need to record each \'L\' and \'R\' positions in both string, and compare them. Since \'L\' can only move left and \'R\' can only move right, \'L\' position in end string should be <= that in start string. Similarly \'R\' position in end string should be >= that in start string.\n\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n std::vector<std::pair<char, int>> pos1, pos2;\n for (int i = 0; i < start.size(); ++i) {\n if (start[i] != \'X\') {\n pos1.push_back(std::make_pair(start[i], i));\n }\n if (end[i] != \'X\') {\n pos2.push_back(std::make_pair(end[i], i));\n }\n }\n \n if (pos1.size() != pos2.size()) {\n return false;\n }\n \n for (int i = 0; i < pos1.size(); ++i) {\n if (pos1[i].first != pos2[i].first) {\n return false;\n }\n \n if (pos1[i].first == \'L\' && pos1[i].second < pos2[i].second) {\n return false;\n }\n \n if (pos1[i].first == \'R\' && pos1[i].second > pos2[i].second) {\n return false;\n }\n }\n \n return true;\n }\n};\n``` | 5 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Straightforward Python solution | straightforward-python-solution-by-otoc-rghn | Based on the rules, we can move \'L\' to left, \'R\' to right without crossing any \'L\' or \'R\'.\n\n def canTransform(self, start: str, end: str) -> bool:\ | otoc | NORMAL | 2019-08-15T22:26:19.925654+00:00 | 2019-08-15T22:39:07.304204+00:00 | 394 | false | Based on the rules, we can move \'L\' to left, \'R\' to right without crossing any \'L\' or \'R\'.\n```\n def canTransform(self, start: str, end: str) -> bool:\n n = len(start)\n groups_start = [[start[i], i] for i in range(n) if start[i] != \'X\']\n groups_end = [[end[i], i] for i in range(n) if end[i] != \'X\']\n if len(groups_start) != len(groups_end):\n return False\n for i in range(len(groups_start)):\n c_s, i_s = groups_start[i]\n c_e, i_e = groups_end[i]\n if c_s != c_e:\n return False\n elif c_s == \'R\':\n if i_s > i_e:\n return False\n else:\n if i_s < i_e:\n return False\n return True\n``` | 5 | 0 | [] | 1 |
swap-adjacent-in-lr-string | 5ms Java with Explanations | 5ms-java-with-explanations-by-gracemeng-hwid | -- What does either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR" mean?\nL and R cannot go across each other, that i | gracemeng | NORMAL | 2018-10-26T23:28:41.250447+00:00 | 2018-10-26T23:28:41.250517+00:00 | 433 | false | -- What does `either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR"` mean?\nL and R cannot go across each other, that is, their relative order in a string doesn\'t change.\nMeanwhile, we should satisfy either one of cases below: \n```\ncase 1 : L = start[i] = end[j] and i >= j\ncase 2 : R = start[i] = end[j] and i <= j\n```\nfor i, j are the index of next non-X character in start and end separately.\n\n```\nFor example,\n-- i = 0, j = 1 satisfies case 2\nRXXL\ni\nXRLX\n j\n-- i = 3, j = 2 satisfies case 1\nRXXL\n i\nXRLX\n j\n```\nIn order to transfer start to end, they should own same number of Ls and Rs as well. That is, when one run out of non-Xs, the other cannot have non-Xs.\n****\n```\n public boolean canTransform(String start, String end) { \n int i = 0, j = 0, len = start.length();\n \n while (i < len && j < len) {\n while (i < len && start.charAt(i) == \'X\')\n i++;\n while (j < len && end.charAt(j) == \'X\')\n j++; \n if (i < len && j < len) {\n char chS = start.charAt(i);\n char chE = end.charAt(j);\n if ((chS != chE) || (chS == \'L\' && i < j) || (chS == \'R\' && i > j))\n return false;\n i++;\n j++;\n }\n }\n \n while (i < len) {\n if (start.charAt(i) != \'X\')\n return false;\n i++;\n }\n \n while (j < len) {\n if (end.charAt(j) != \'X\')\n return false;\n j++;\n }\n \n return true;\n }\n```\n**(\uFF89>\u03C9<)\uFF89 Vote up, please!** | 5 | 0 | [] | 1 |
swap-adjacent-in-lr-string | Easy C++ Solution || Basic Loops || Easy To Understand For Begineers || proper Comment | easy-c-solution-basic-loops-easy-to-unde-rczo | Read the comment for better understanding of the solution\n\n\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n string f,s; | Abhisheksaware | NORMAL | 2022-08-10T14:59:26.626083+00:00 | 2022-08-10T14:59:26.626112+00:00 | 995 | false | ***Read the comment for better understanding of the solution***\n\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n string f,s; // to copy only original pattern from the string \n for(int i=0;i<start.size();i++)\n {\n if(start[i]!=\'X\') f+=start[i]; //take only elements to check their order\n }\n for(int i=0;i<end.size();i++)\n {\n if(end[i]!=\'X\') s+=end[i]; // to check the order of second and first string \n }\n \n if(f!=s) return false; // means both the string dont have the equal no. of elements and there is no swap in LR or RL\n \n //strat moving with this 2 pointer and check for index of left in both start and end string similarly for \n int i=0,j=0;\n while(i<start.size() and j<end.size())\n {\n if(start[i]==\'X\') i++; // move if dummy found;\n else if(end[j]==\'X\') j++; //move if dummy found in end\n else\n {\n if(start[i]==\'L\' and i<j ) return false; //here the move if LX to XL which is invalid\n else if(start[i]==\'R\' and i>j) return false; //here the move if XR to RX which is invalid\n else {\n i++;\n j++;\n }\n \n }\n }\n return true;\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 0 |
swap-adjacent-in-lr-string | a joke misunderstanding to me | a-joke-misunderstanding-to-me-by-haoleet-x92v | Not sure if only me, but I first mis-understood the L, R switch can only happen one time, to either left or right position X.\n\nAnd the solution I wrote passed | haoleetcode | NORMAL | 2022-08-09T00:11:54.104516+00:00 | 2022-08-09T00:11:54.104546+00:00 | 488 | false | Not sure if only me, but I first mis-understood the L, R switch can only happen one time, to either left or right position X.\n\nAnd the solution I wrote passed 59/94 test cases @_@\n | 4 | 0 | [] | 1 |
swap-adjacent-in-lr-string | [C++] Two pointers solution [Detailed Explanation] | c-two-pointers-solution-detailed-explana-2941 | \n/*\n https://leetcode.com/problems/swap-adjacent-in-lr-string/\n \n Things to note:\n 1. Based on the swap patterns, L can be moved to left in pre | cryptx_ | NORMAL | 2022-06-29T15:50:27.881402+00:00 | 2022-06-29T15:50:27.881453+00:00 | 415 | false | ```\n/*\n https://leetcode.com/problems/swap-adjacent-in-lr-string/\n \n Things to note:\n 1. Based on the swap patterns, L can be moved to left in presence of X\n 2. R can be moved right in presence of X\n \n So that means it is only possible to swap and reach end iff each L in start lies atleast\n >= position compared to end and each R in start should be <= position compared to end.\n This is again due to the fact that L can only move left and R can move right.\n \n So we start traversal ignoring the X and focus on the breaking cases, if we don\'t find any breaking cases\n then it is possible.\n TC: O(N)\n SC: O(1)\n*/\nclass Solution {\npublic:\n bool twoPointerSol(string start, string end) {\n // both the strings have be of same size\n if(start.size() != end.size())\n return false;\n \n int n = start.size();\n int i = 0, j = 0;\n \n while(i < n && j < n) {\n // Get past all the X since these help move L or R\n while(i < n && start[i] == \'X\')\n ++i;\n while(j < n && end[j] == \'X\')\n ++j;\n \n // traversal finished, so it must be possible\n if(i == n && j == n)\n return true;\n \n // if the curr char is not same, then there is no way to match \n if(start[i] != end[j])\n return false;\n \n // If both point to R, then start\'s ptr should be <= end\'s ptr since\n // R can move towards right\n if(start[i] == \'R\' && i > j)\n return false;\n \n // If both point to L, then start\'s ptr should be >= end\'s ptr since\n // L can move towards left\n if(start[i] == \'L\' && i < j)\n return false;\n ++i, ++j;\n }\n \n // We might still have some chars left for one of the strings\n // Eg start = XXXXL, end = XLXXX \n // \'i\' will end first. So let the indices get past X and then check if they both finished processing\n while(i < n && start[i] == \'X\')\n ++i;\n while(j < n && end[j] == \'X\')\n ++j;\n\n return i == j;\n }\n \n bool canTransform(string start, string end) {\n return twoPointerSol(start, end);\n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 0 |
swap-adjacent-in-lr-string | Simple Java one Pass O(N). Moving On A Track | simple-java-one-pass-on-moving-on-a-trac-srb7 | Imagine 2 kinds of pawn moving on a track, left pawn and right pawn. You want to push all the left pawns to the left and all the right pawns to the right.\nThe | vipergo | NORMAL | 2022-05-27T13:27:52.498069+00:00 | 2022-05-27T13:27:52.498108+00:00 | 643 | false | Imagine 2 kinds of pawn moving on a track, left pawn and right pawn. You want to push all the left pawns to the left and all the right pawns to the right.\nThe right pawn will block all the left pawns from its right to move left, and the left pawn will block all the right pawns from its left to move right.\n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n int L1 = 0, L2 = 0, R1 = 0, R2 = 0;\n for (int i = 0; i < start.length(); i++) {\n char c1 = start.charAt(i), c2 = end.charAt(i);\n\t\t\t\n if (c1 == \'R\') {\n\t\t\t\t// if we encounter a R in first string, the number of L on its left is fixed, not more L can added to its left.\n if (L1 != L2) return false;\n R1++;\n }else if (c1 == \'L\') {\n\t\t\t\t// if we encounter a L in first string, the number of R on its left is fixed, it can\'t decrease.\n if (R1 != R2) return false;\n L1++;\n }\n if (c2 == \'L\') {\n L2++;\n } else if (c2 == \'R\') {\n R2++;\n }\n \n\t\t\t// L can\'t move right and R can\'t move left\n if (L2 < L1 || R2 > R1) {\n return false;\n }\n }\n \n\t\t// for case like "XXXX" "LXXX"\n return L1 == L2 && R1 == R2;\n }\n}\n``` | 4 | 0 | [] | 5 |
swap-adjacent-in-lr-string | Super Crisp || Spoon Feeding explanation || Time = O(n) | super-crisp-spoon-feeding-explanation-ti-0p42 | \nclass Solution\n{\n public:\n bool canTransform(string start, string end)\n {\n int si = 0;\n int ei = 0;\n \n while (si | meta_fever | NORMAL | 2022-03-16T14:48:11.945464+00:00 | 2022-03-16T15:19:39.592770+00:00 | 207 | false | ```\nclass Solution\n{\n public:\n bool canTransform(string start, string end)\n {\n int si = 0;\n int ei = 0;\n \n while (si < start.size() || ei < end.size())\n {\n\t\t // Skip all \'X\' and find 1st letter after X in \'start\' & \'end\'.\n while (si < start.size() && start[si]==\'X\') si++;\n while (ei < end.size() && end[ei]==\'X\') ei++;\n \n // start = "XXL" --> start[si] = \'L\'\n // end = "RXX" --> end[ei] = \'R\'\n if (start[si] != end[ei])\n return false;\n \n // start = "XXR" --> start[si] = \'R\'\n // end = "RXX" --> end[ei] = \'R\' --> XXR cannot be converted to RXX, i.e., si cannot be greater than ei\n if (start[si]==\'R\' && si>ei)\n return false;\n \n // start = "LXX" --> start[si] = \'L\'\n // end = "XXL" --> end[ei] = \'L\' --> LXX cannot be converted to XXL, i.e., si cannot be less than ei\n if (start[si]==\'L\' && si<ei)\n return false;\n \n si++;\n ei++;\n }\n return true;\n }\n};\n```\n\nPlease upvote if you understood the solution with my examples above. This will keep my spirits high. Thanks. | 4 | 0 | [] | 1 |
swap-adjacent-in-lr-string | JAVA O(N) with Stack | java-on-with-stack-by-tmc204-wtvl | \nclass Solution {\n public boolean canTransform(String start, String end) {\n Stack<Integer> L = new Stack(), R = new Stack();\n for (int i = | tmc204 | NORMAL | 2022-03-13T07:29:15.437070+00:00 | 2022-03-13T07:29:29.333255+00:00 | 274 | false | ```\nclass Solution {\n public boolean canTransform(String start, String end) {\n Stack<Integer> L = new Stack(), R = new Stack();\n for (int i = 0; i < start.length(); i++) {\n if (start.charAt(i) == \'R\')\n R.add(i);\n if (end.charAt(i) == \'L\')\n L.add(i);\n if (start.charAt(i) == \'L\') {\n if (L.isEmpty() || !R.isEmpty() && L.peek() >= R.peek())\n return false;\n else \n L.pop();\n } \n if (end.charAt(i) == \'R\') {\n if (R.isEmpty() || !L.isEmpty() && R.peek() >= L.peek())\n return false;\n else\n R.pop();\n } \n }\n if (!L.isEmpty() || !R.isEmpty())\n return false;\n return true;\n }\n}\n``` | 4 | 0 | [] | 1 |
swap-adjacent-in-lr-string | Java || Explained || Easy to understand | java-explained-easy-to-understand-by-ico-d22v | // Replace all \'X\' in both strings and see if they are SAME then return true\n// Whenever you see \'X\' just update the idx\n\n// TC : O(N) -> N = start.lengt | ICodeToSurvive | NORMAL | 2022-01-30T09:01:19.087309+00:00 | 2022-01-30T09:01:19.087350+00:00 | 288 | false | // Replace all \'X\' in both strings and see if they are SAME then return true\n// Whenever you see \'X\' just update the idx\n\n// TC : O(N) -> N = start.length\n// SC : O(1)\n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n int startIdx = 0;\n int endIdx = 0;\n \n while(startIdx < start.length() || endIdx < end.length()) {\n while(startIdx < start.length() && start.charAt(startIdx) == \'X\') {\n startIdx++;\n }\n \n while(endIdx < end.length() && end.charAt(endIdx) == \'X\') {\n endIdx++;\n }\n \n if(startIdx >= start.length() || endIdx >= end.length()) break; // come out of while loop\n \n if(start.charAt(startIdx) != end.charAt(endIdx)) return false;\n \n // if the character is \'L\', it can only be moved to the LEFT. startIdx should be greater or equal to endIdx. \n if(start.charAt(startIdx) == \'L\' && endIdx > startIdx) {\n return false;\n }\n \n // if the character is \'R\', it can only be moved to the RIGHT. endIdx should be greater or equal to startIdx.\n if(start.charAt(startIdx) == \'R\' && startIdx > endIdx) {\n return false;\n }\n \n startIdx++;\n endIdx++;\n }\n \n return startIdx == endIdx; // if while loop exited because of the string (start or end) reach end but not other, return false\n }\n}\n``` | 4 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Simple C++ solution | simple-c-solution-by-ranjan_1997-i260 | \nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n if(start.length() == 1)\n return start == end;\n int n | ranjan_1997 | NORMAL | 2021-05-30T06:00:49.819651+00:00 | 2021-05-30T06:00:49.819684+00:00 | 317 | false | ```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n if(start.length() == 1)\n return start == end;\n int n = start.length();\n int i = 0;\n int j = 0;\n while(1)\n {\n while(i<n and start[i] == \'X\')\n i++;\n while(j<n and end[j] == \'X\')\n j++;\n if(i==n or j==n)\n return i==j;\n if(start[i] != end[j])\n return false;\n if(start[i] == \'R\' and i>j)\n return false;\n if(start[i] == \'L\' and i<j)\n return false;\n i++;\n j++;\n }\n return true;\n }\n};\n``` | 4 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Simple C++ Solution with explanation | simple-c-solution-with-explanation-by-ro-lmve | Idea is that L moves backwards (XL->LX) and R moves forwards (RX->XR) so L is decremented and R is incremented. Parallely at the same position of end string, L | rootkonda | NORMAL | 2020-05-04T12:01:38.451912+00:00 | 2020-05-04T12:10:44.924225+00:00 | 315 | false | Idea is that L moves backwards (XL->LX) and R moves forwards (RX->XR) so L is decremented and R is incremented. Parallely at the same position of end string, L will be incremented and R will be decremented. At any point, if the count of L or R becomes -ve then return false. \n\nNote that L cannot move beyond R and R cannot move beyond L. Like mentioned in the HINT.\n\nFor example: \n"XXXXXLXXXLXXXX"\n"XXLXXXXXXXXLXX"\n\nWhen start[i] has \'L\' it means, we should have already encountered \'L\' in end string somewhere before this. In this example, for the second L which comes before second L in end string. Hence \'L\' count becomes -ve and answer is false.\n\nSimilarly, when end[i] has \'R\' it means, we should have already encountered \'R\' in start string before this. If thats not the case then again \'R\' count will become -ve and answer will be false.\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) \n {\n int L=0,R=0;\n \n for(int i=0;i<start.size();i++)\n {\n if(start[i]==\'L\')\n L--,R=0; // Reset count of R to zero because previous \'R\' characters cannot move beyond \'L\' so reset it to zero. If end[i] has \'R\' character then R becomes -ve and returns false or if there is L then L is incremented;\n else if(start[i]==\'R\')\n R++,L=0; // Reset count of L to zero because previous \'L\' characters cannot move beyond \'R\' so reset it to zero. If end[i] \'R\' then \'R\' count is decremented and if there is \'L\' then L is incremented;\n \n if(end[i]==\'L\')\n L++;\n else if(end[i]==\'R\')\n R--;\n \n if(L<0 or R<0)\n return false;\n }\n if(L>0 or R>0)\n return false;\n return true; // If both L and R are zero then return true else return false;\n }\n};\n```\n | 4 | 0 | [] | 1 |
swap-adjacent-in-lr-string | C++ Solution with explanation | c-solution-with-explanation-by-mradul-x4va | We can only move "R" backwards and "L" forward as we can convert "XL" to "LX" and "RX" to "XR"\n\n - Maintain count of R\'s found in the "start" string to ma | mradul | NORMAL | 2019-12-10T06:54:06.659271+00:00 | 2019-12-10T06:54:06.659314+00:00 | 342 | false | We can only move "R" backwards and "L" forward as we can convert "XL" to "LX" and "RX" to "XR"\n\n - Maintain count of R\'s found in the "start" string to match with "end"\n - BECAUSE WE CAN ONLY MOVE "R" BACK WE INC THEM WHEN WE FIND THEM IN "start" AND DECREMENT IN "end" (matching step)\n \n - Maintain count of L\'s found in the "end" string to match with "start"\n - BECAUSE WE CAN ONLY MOVE "L" FWD WE INC THEM WHEN WE FIND THEM IN "end" AND DECREMENT IN "start" (matching step)\n\n - If at any point we have unmatched "R" or "L" we can return false\n \n \n```\nbool canTransform(string start, string end) {\n int i = 0;\n int fwdL = 0, bwdR = 0;\n \n while (i < start.size()) {\n \n if (start[i] == \'R\') bwdR++;\n \n if (end[i] == \'L\') fwdL++;\n \n if (end[i] == \'R\') bwdR--;\n \n if (start[i] == \'L\') fwdL--;\n \n\t\t\t /* If we have more R\'s or L\'s that can be matched or if a cross over b/w R & L has occured (indicated by both +ve) we can\'t transform further*/\n if ((bwdR > 0 && fwdL > 0) || (bwdR < 0 || fwdL < 0))\n return false;\n \n i++;\n }\n \n return fwdL == 0 && bwdR == 0;\n }\n``` | 4 | 0 | [] | 1 |
swap-adjacent-in-lr-string | One pass O(n) Python, beat 99%, easy to understand | one-pass-on-python-beat-99-easy-to-under-ydzr | The idea is keep a variable count. For start, R plus 1, L minus 1, opposite for end. And they should meet two rules:\n1.The count could not be less than 0.\nOne | pengp17 | NORMAL | 2019-06-28T06:24:33.737541+00:00 | 2019-06-28T06:24:33.737588+00:00 | 500 | false | The idea is keep a variable ```count```. For ```start```, R plus 1, L minus 1, opposite for ```end```. And they should meet two rules:\n1.The count could not be less than 0.\nOne example is "XR" and "RX". Remember you can only replace strings in start, not end.\n2.The difference could never be 2 or -2.\nOne example is "RL" and "LR". The reason is to move the letter "R", you have to make sure there is always a "X" on the right of it. Same for "L".\n\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n n = len(start)\n value = {"R":1,"X":0,"L":-1}\n count = 0\n for i in range(n):\n diff = value[start[i]]-value[end[i]]\n count+=diff\n if count < 0 or abs(diff) == 2:\n return False\n return count == 0\n``` | 4 | 1 | [] | 1 |
swap-adjacent-in-lr-string | short and easy solution in C++ | short-and-easy-solution-in-c-by-chaitany-5orr | \nclass Solution {\npublic:\n bool canTransform(string s, string e) {\n int i = 0, j = 0, n = s.size(), m = e.size();\n while(i < n || j < m) { | chaitanyya | NORMAL | 2023-03-15T06:56:47.771917+00:00 | 2023-03-15T06:56:47.771949+00:00 | 955 | false | ```\nclass Solution {\npublic:\n bool canTransform(string s, string e) {\n int i = 0, j = 0, n = s.size(), m = e.size();\n while(i < n || j < m) {\n while(s[i] == \'X\') i++;\n while(e[j] == \'X\') j++;\n\n if(s[i] != e[j]) return false;\n if(s[i] == \'R\' && i > j) return false;\n if(s[i] == \'L\' && i < j) return false; \n i++, j++;\n }\n return true;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
swap-adjacent-in-lr-string | c++ | easy | fast | c-easy-fast-by-venomhighs7-7b5s | \n\n# Code\n\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n \n int i=0, j=0;\n while(i<start.size() && j<e | venomhighs7 | NORMAL | 2022-11-18T04:50:26.012805+00:00 | 2022-11-18T04:50:26.012853+00:00 | 600 | false | \n\n# Code\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n \n int i=0, j=0;\n while(i<start.size() && j<end.size()) {\n \n while(start[i]==\'X\') i++;\n while(end[j]==\'X\') j++;\n \n if(start[i]!=end[j]) return false;\n if(start[i]==\'R\' && i>j) return false;\n if(start[i]==\'L\' && i<j) return false;\n i++; j++;\n }\n while(i<start.size() && start[i]==\'X\') i++;\n while(j<end.size() && end[j]==\'X\') j++;\n return i==j;\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
swap-adjacent-in-lr-string | Python with explanation | python-with-explanation-by-lizihao52100-bf8v | \nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n # replace x with empty string to make sure the left R and L are in same or | lizihao52100 | NORMAL | 2022-03-25T03:23:25.742223+00:00 | 2022-03-25T03:23:25.742260+00:00 | 100 | false | ```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n # replace x with empty string to make sure the left R and L are in same order\n if start.replace("X","") != end.replace("X",""):\n return False\n n = len(start)\n i = j = 0\n # check the index of L in start is more than end(Only XL to LX, L index decrease )\n # check the index of R in start is less than end (Only RX to XR, R index increase )\n while True:\n while i < n and start[i] == "X":\n i += 1\n while j < n and end[j] == "X":\n j += 1\n #if approach the end of start, all the L R statisfied the requirement\n if i == n: return True\n if start[i] == "L" and i < j: return False\n if start[i] == "R" and i > j: return False\n i += 1\n j += 1\n return True\n \n``` | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | JavaScript (two pointer with comments) | javascript-two-pointer-with-comments-by-lrmw0 | \n/**\n* @param {string} start\n* @param {string} end\n* @return {boolean}\n*/\nvar canTransform = function (start, end) {\n const sWithoutX = start.replace( | justin_kunz | NORMAL | 2022-03-21T00:53:39.728569+00:00 | 2022-03-21T00:53:39.728594+00:00 | 300 | false | ```\n/**\n* @param {string} start\n* @param {string} end\n* @return {boolean}\n*/\nvar canTransform = function (start, end) {\n const sWithoutX = start.replace(/X/g, \'\');\n const eWithoutX = end.replace(/X/g, \'\');\n\n // start and end text without x\'s should equal\n if (sWithoutX !== eWithoutX) return false;\n\n const sCount = { l: 0, r: 0 };\n const eCount = { l: 0, r: 0 };\n\n // iterate through original start string\n for (let i = 0; i < start.length; i++) {\n \n // track occurances of L\'s and R\'s\n if (start[i] === \'L\') {\n sCount.l++;\n } else if (start[i] === \'R\') {\n sCount.r++;\n }\n\n // also track L/R occurances on end string\n if (end[i] === \'L\') {\n eCount.l++;\n } else if (end[i] === \'R\') {\n eCount.r++;\n }\n\n // if at any point during iteration, start has more l\'s than end\n // or if start has less r\'s than end - path impossible\n if (sCount.l > eCount.l || sCount.r < eCount.r) return false;\n }\n \n return true;\n \n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
swap-adjacent-in-lr-string | Python O(n) solution with explanation | python-on-solution-with-explanation-by-p-ebj5 | idea:\n1. each time we saw a L in end string, it means that we must find a L in start (increase the debtL)\n2. each time we saw a R in end string, it means that | pacificdou | NORMAL | 2022-03-09T09:31:53.359285+00:00 | 2022-03-09T09:31:53.359317+00:00 | 143 | false | idea:\n1. each time we saw a L in end string, it means that we must find a L in start (increase the debtL)\n2. each time we saw a R in end string, it means that we must already found a R in start (decrease the debtR)\n3. in case of RL, L cannot move left of R, so if this L is a matching L, at the time we found this L, the debtR must be zero; similarly, if it\'s a matching R, debtL must be zero\n\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n\n n = len(start)\n debtL = 0\n debtR = 0\n \n for i in range(n):\n if end[i] == \'L\':\n debtL += 1\n elif end[i] == \'R\':\n debtR -= 1\n \n if start[i] == \'L\' and debtR == 0:\n debtL -= 1\n elif start[i] == \'R\' and debtL == 0:\n debtR += 1\n \n if debtL < 0 or debtR < 0:\n return False\n \n return debtL == 0 and debtR == 0 | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | A solution that moves 'X' if you find this easier to understand. | a-solution-that-moves-x-if-you-find-this-5pmt | The move is as follows:\n\n1. X can go through R to move to the left\nRRRX. -> XRRR\n\n2. X can go through L to move to the right\nXLLL -> LLLX\n\nNow go from l | x372p | NORMAL | 2022-01-22T08:48:12.642656+00:00 | 2022-01-22T08:53:24.336218+00:00 | 203 | false | The move is as follows:\n\n1. X can go through R to move to the left\nRRRX. -> XRRR\n\n2. X can go through L to move to the right\nXLLL -> LLLX\n\nNow go from left to right, have counter to save number of \'X\' in end minus number of \'X\' in start\n```\ncount = #\'X\' in end - #\'X\' in start\n```\n\nThere could be two scenarios:\n\n count > 0 means there\'s an X in start need to move left -> it must go through \'R\' in start, not an \'L\'\n i\n start: R R X\n end : X R R\n \n count < 0 means there\'s an X in start need to move right -> it must go through \'L\' in start, not an \'R\'\n i\n start: X L L\n end : L L X\n \n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n int n = start.length();\n \n //check if R and L count match\n String s1 = start.replace("X", "");\n String s2 = end.replace("X", "");\n if (!s1.equals(s2)) {\n return false;\n }\n\t\t\n // count: go from left to right. Number of X in end - Number of X in start\n int count = 0; \n while(i < n) { \n\t\t\t// need to move right through \'L\', but there\'s an \'R\'\n\t\t if (count < 0 && start.charAt(i) == \'R\') {\n return false;\n }\n if (end.charAt(i) == \'X\') {\n count++;\n }\n if (start.charAt(i) == \'X\') {\n count--;\n }\n\t\t\t// need to move left through \'R\', but there\'s an \'L\'\n if (count > 0 && start.charAt(i) == \'L\') {\n return false;\n } \n i++;\n }\n return true;\n }\n}\n``` | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | C++ two pointers O(n) | c-two-pointers-on-by-bcb98801xx-t10u | The key is that we only can make \'L\' backword and \'R\' forward.\n\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n int | bcb98801xx | NORMAL | 2021-09-14T02:18:43.249333+00:00 | 2021-09-14T02:18:43.249377+00:00 | 260 | false | The key is that we only can make \'L\' backword and \'R\' forward.\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n int n = start.size();\n int i = 0, j = 0;\n \n for( ; j < n; j++){\n if (end[j] == \'X\') continue;\n \n while (i < n && start[i] == \'X\') i++;\n \n if (i == n) return false;\n \n if (end[j] == \'L\'){\n if (i < j || start[i] != \'L\') return false; //we only can make \'L\' backword\n }else{\n if (i > j || start[i] != \'R\') return false; //we only can make \'R\' forward\n }\n i++;\n }\n \n while (i < n && start[i] == \'X\') i++;\n \n return i == n;\n }\n};\n``` | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | java simple solution o(n) | java-simple-solution-on-by-516527986-yyjy | rnum: there are rnum of \'R\' need to move to right;\nlnum: there are lnum of \'L\' need to move to left;\n\nclass Solution {\n public boolean canTransform( | 516527986 | NORMAL | 2021-04-21T10:54:52.716987+00:00 | 2021-12-26T12:00:17.246618+00:00 | 585 | false | rnum: there are rnum of \'R\' need to move to right;\nlnum: there are lnum of \'L\' need to move to left;\n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n if (start.length() != end.length()) return false;\n int rnum = 0, lnum = 0;\n for (int i = 0; i < start.length(); i++) {\n if (start.charAt(i) == \'R\') {\n rnum++;\n }\n if (start.charAt(i) == \'L\') {\n lnum--;\n }\n\t\t\t// if there are R need to move to right , but there are some L obstacles \n if (rnum > 0 && lnum != 0) return false;\n if (end.charAt(i) == \'R\') {\n rnum--;\n }\n if (end.charAt(i) == \'L\') {\n lnum++;\n }\n\t\t\t// there are R in right , or L in left\n if (rnum < 0 || lnum < 0) return false;\n\t\t\t// there are obstacles when we move R or L;\n if (rnum > 0 && lnum > 0) return false;\n }\n return rnum == 0 && lnum == 0;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
swap-adjacent-in-lr-string | C++ O(n) time | O(1) space | Explained with examples | c-on-time-o1-space-explained-with-exampl-07e8 | Rules: \nXL -> LX\nRX -> XR\nRL is a deadline.(incase it dosen\'t match with \'end\')\nSo check for dangling \'R\' to the right side of \'RL\' (i.e an R not fol | aparna_g | NORMAL | 2021-01-22T17:51:48.975824+00:00 | 2021-01-22T17:51:48.975854+00:00 | 427 | false | Rules: \nXL -> LX\nRX -> XR\nRL is a deadline.(incase it dosen\'t match with \'end\')\nSo check for dangling \'R\' to the right side of \'RL\' (i.e an R not followed by an \'X\' and not matching with end[i])\n***Something like : "XRLXR" and "RXXLL"***\nFor finding unpaired \'L\' iterate from the end, check for a dangling \'L\' (i.e an \'L\' to the left of \'RX\' where the \'L\' is not preceded by an \'X\' and not matching with end[i])\n***Something like : "LXRLX" and "RRXXL"***\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n if(start.length()!=end.length()) \n return 0;\n int count =0;\n for(int i=0;i<start.length();i++) {\n if(start[i]==\'R\')\n {\n count++;\n }\n if(end[i]==\'R\') {\n if(--count<0) \n return 0;\n }\n else if(end[i]==\'L\' && count!=0)\n return 0;\n }\n if(count!=0) \n return 0;\n for(int i=start.size();i>=0;i--) {\n if(start[i]==\'L\') \n count++;\n if(end[i]==\'L\') {\n if(--count<0)\n return 0;\n }\n else if(end[i]==\'R\' && count!=0)\n return 0;\n }\n return count==0;\n }\n};\n``` | 3 | 2 | ['C', 'C++'] | 1 |
swap-adjacent-in-lr-string | Easy Python | easy-python-by-ztyreg-drre | python\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n # Same number of L and R\n if start.replace(\'X\', \'\') != e | ztyreg | NORMAL | 2020-08-17T18:45:01.844008+00:00 | 2020-08-17T18:49:19.768332+00:00 | 462 | false | ```python\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n # Same number of L and R\n if start.replace(\'X\', \'\') != end.replace(\'X\', \'\'):\n return False\n # L can only move left and R can only move right\n l_start = [i for i, c in enumerate(start) if c == \'L\']\n r_start = [i for i, c in enumerate(start) if c == \'R\']\n l_end = [i for i, c in enumerate(end) if c == \'L\']\n r_end = [i for i, c in enumerate(end) if c == \'R\']\n if any(l_start[i] < l_end[i] for i in range(len(l_start))):\n return False\n if any(r_start[i] > r_end[i] for i in range(len(r_start))):\n return False\n return True\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
swap-adjacent-in-lr-string | simple C++ O(N) Stack Solution beats 90% | simple-c-on-stack-solution-beats-90-by-i-dxyw | \nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n stack<pair<char, int>> st1, st2;\n if (start.length() != end.leng | indrajohn | NORMAL | 2020-06-24T11:10:38.361056+00:00 | 2020-06-24T11:10:38.361089+00:00 | 184 | false | ```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n stack<pair<char, int>> st1, st2;\n if (start.length() != end.length()) return false;\n for (int i = 0; i < start.length(); i++) {\n if (start[i] != \'X\') st1.push(make_pair(start[i], i));\n if (end[i] != \'X\') st2.push(make_pair(end[i], i));\n }\n if (st1.size() != st2.size()) return false;\n while (!st1.empty()) {\n char ch1 = st1.top().first, ch2 = st2.top().first;\n int pos1 = st1.top().second, pos2 = st2.top().second;\n st1.pop();\n st2.pop();\n if (ch1 != ch2) return false;\n if (ch1 == \'R\') {\n if (pos1 > pos2) return false; \n } else {\n if (pos1 < pos2) return false;\n }\n }\n \n return true;\n }\n};\n``` | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Really concise and fast C++ code 8ms | really-concise-and-fast-c-code-8ms-by-za-ey0z | \nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n int n = start.length();\n if(n != end.length()) return false;\n | zacharyzyh | NORMAL | 2019-07-10T15:21:10.472543+00:00 | 2019-07-10T15:21:10.472587+00:00 | 284 | false | ```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n int n = start.length();\n if(n != end.length()) return false;\n int l1 = 0, l2 = 0, r1 = 0, r2 = 0;\n for(int i = 0; i < n; ++i){\n if(start[i] == \'L\') ++l1;\n else if(start[i] == \'R\') ++r1;\n if(end[i] == \'L\') ++l2;\n else if(end[i] == \'R\') ++r2;\n if(l1 > l2 || r1 < r2 || (l1 < l2 && r1 > r2)) return false;\n }\n return l1==l2 && r1==r2;\n }\n};\n``` | 3 | 0 | [] | 0 |
swap-adjacent-in-lr-string | 4ms 99% simple C++ solution | 4ms-99-simple-c-solution-by-lindawang-mymo | The relative position of R and L can\'t be changed. Since R can only move back and L can only move forward, the position of R in the "end" can\'t be less than i | lindawang | NORMAL | 2019-06-01T07:31:46.052280+00:00 | 2019-06-06T08:55:57.956891+00:00 | 317 | false | The relative position of R and L can\'t be changed. Since R can only move back and L can only move forward, the position of R in the "end" can\'t be less than it in the start, the position of L in the "end" can\'t be larger than that of in the "start". "X"s are like "spaces". \n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n if(start.size()!=end.size()) return false;\n int i=0, j=0;\n while(i<start.size() && j<end.size()){\n while(start[i]==\'X\') i++;\n while(end[j]==\'X\') j++;\n if(start[i]!=end[j]) return false;\n if(start[i]==\'R\' && i>j) return false;\n if(start[i]==\'L\' && i<j) return false;\n i++;\n j++;\n }\n return true;\n }\n};\n``` | 3 | 0 | [] | 3 |
swap-adjacent-in-lr-string | JavaScript super clean, O(n) | javascript-super-clean-on-by-mildog8-jy45 | js\n/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n const N = start.length\n let | mildog8 | NORMAL | 2019-02-27T09:00:31.942422+00:00 | 2019-02-27T09:00:31.942487+00:00 | 252 | false | ```js\n/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n const N = start.length\n let i = 0\n let j = 0\n \n while (i < N && j < N) {\n while (start[i] === \'X\') i++\n while (end[j] === \'X\') j++\n \n if (\n (start[i] !== end[j]) || // chars don\'t match\n (start[i] === \'R\' && i > j) || // Rs can\'t move forward!\n (start[i] === \'L\' && i < j) // Ls can\'t move backward!\n ) return false\n \n i++\n j++\n }\n \n return true\n};\n``` | 3 | 3 | [] | 1 |
swap-adjacent-in-lr-string | One pass O(n) Python Solution | one-pass-on-python-solution-by-toby-0njq | We just need to keep track of two counters.\n\nclass Solution:\n def canTransform(self, start: \'str\', end: \'str\') -> \'bool\':\n countR = 0\n | toby | NORMAL | 2019-02-21T03:18:33.694037+00:00 | 2019-02-21T03:18:33.694075+00:00 | 236 | false | We just need to keep track of two counters.\n```\nclass Solution:\n def canTransform(self, start: \'str\', end: \'str\') -> \'bool\':\n countR = 0\n countL = 0\n for idx in range(len(start)):\n if start[idx] == \'R\':\n countR += 1\n if end[idx] == \'L\':\n countL += 1\n \n if countR > 0 and countL > 0:\n return False\n \n if start[idx] == \'L\':\n countL -= 1\n if end[idx] == \'R\':\n countR -= 1\n \n if countR < 0 or countL < 0:\n return False\n \n return countR == 0 and countL == 0\n``` | 3 | 0 | [] | 1 |
swap-adjacent-in-lr-string | C++ 10 Line O(n) Solution | c-10-line-on-solution-by-code_report-7i0j | ````\n bool canTransform(string start, string end) {\n\n string s, t;\n \n FORI (0, start.size ()) if (start[i] != 'X') s += start[i];\n | code_report | NORMAL | 2018-02-04T04:03:24.192000+00:00 | 2018-02-04T04:03:24.192000+00:00 | 596 | false | ````\n bool canTransform(string start, string end) {\n\n string s, t;\n \n FORI (0, start.size ()) if (start[i] != 'X') s += start[i];\n FORI (0, end.size ()) if (end[i] != 'X') t += end[i];\n \n if (s != t) return false;\n else {\n int sR = 0, sL = 0, eR = 0, eL = 0;\n FORI (0, start.size ()) {\n if (start[i] == 'L') sL++;\n if (start[i] == 'R') sR++;\n if (end[i] == 'R') eR++;\n if (end[i] == 'L') eL++;\n\n if (eR > sR) return false;\n if (sL > eL) return false;\n }\n }\n \n return true;\n } | 3 | 1 | [] | 1 |
swap-adjacent-in-lr-string | 777: Beats 95.06%, Solution with step by step explanation | 777-beats-9506-solution-with-step-by-ste-1cq4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\ni, j = 0, 0\nn, m = len(start), len(end)\n\nWe create two pointers, i a | Marlen09 | NORMAL | 2023-10-28T06:14:40.139569+00:00 | 2023-10-28T06:14:40.139597+00:00 | 595 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ni, j = 0, 0\nn, m = len(start), len(end)\n```\nWe create two pointers, i and j, to iterate through start and end, respectively. We also store the lengths of start and end in n and m.\n\nWe continue while neither i nor j has reached the end of their respective strings.\n\n```\nwhile i < n and j < m:\n```\n\n```\nwhile i < n and start[i] == \'X\':\n i += 1\nwhile j < m and end[j] == \'X\':\n j += 1\n```\n\nWe increment the i and j pointers as long as we see the character \'X\' in the respective string. We do this because \'X\' doesn\'t affect our transformation logic.\n\n```\nif (i == n) != (j == m):\n return False\n```\n\nAfter skipping all \'X\' characters, if one of the pointers has reached the end and the other hasn\'t, the strings cannot be made identical.\n\n```\nif i == n and j == m:\n return True\n```\n\nIf both pointers have reached the end of their strings simultaneously, they are identical.\n\n```\nif start[i] != end[j]:\n return False\n```\n\nIf the characters at i and j are different, then the transformation is not possible.\n\n```\nif start[i] == \'R\' and i > j:\n return False\n```\n\nSince \'R\' can only move right, its position in start should always be to the left (or at the same position) compared to end.\n\n\n```\nif start[i] == \'L\' and i < j:\n return False\n```\n\nSince \'L\' can only move left, its position in start should always be to the right (or at the same position) compared to end.\n\n```\ni += 1\nj += 1\n```\n\nOnce we\'ve done the checks, we move the pointers to examine the next characters.\n\n```\nwhile i < n and start[i] == \'X\':\n i += 1\nwhile j < m and end[j] == \'X\':\n j += 1\n```\n\nAfter exiting the main loop, if there are any \'X\' characters left, we skip them.\n\n```\nreturn i == n and j == m\n```\n\nAt this point, if both i and j have reached the ends of their strings, the transformation is possible; otherwise, it\'s not.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n \n i, j = 0, 0\n n, m = len(start), len(end)\n \n while i < n and j < m:\n \n while i < n and start[i] == \'X\':\n i += 1\n while j < m and end[j] == \'X\':\n j += 1\n \n if (i == n) != (j == m):\n return False\n \n if i == n and j == m:\n return True\n \n if start[i] != end[j]:\n return False\n \n if start[i] == \'R\' and i > j:\n return False\n if start[i] == \'L\' and i < j:\n return False\n\n i += 1\n j += 1\n \n while i < n and start[i] == \'X\':\n i += 1\n while j < m and end[j] == \'X\':\n j += 1\n \n return i == n and j == m\n\n``` | 2 | 0 | ['Two Pointers', 'String', 'Python', 'Python3'] | 1 |
swap-adjacent-in-lr-string | Solution | solution-by-deleted_user-0y63 | C++ []\nclass Solution {\npublic:\n bool canTransform(string st, string tar) {\n int n=tar.length();\n int i=0,j=0;\n while(i<=n && j<=n | deleted_user | NORMAL | 2023-04-28T07:56:06.584074+00:00 | 2023-04-28T08:15:25.681804+00:00 | 789 | false | ```C++ []\nclass Solution {\npublic:\n bool canTransform(string st, string tar) {\n int n=tar.length();\n int i=0,j=0;\n while(i<=n && j<=n){\n while(i<n && tar[i]==\'X\') i++;\n while(j<n && st[j]==\'X\') j++;\n if(i==n || j==n)\n return i==n && j==n;\n if(tar[i]!=st[j] || (tar[i]==\'L\' && j<i) || (tar[i]==\'R\' && i<j)) return false;\n i++,j++;\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n countR = countL = 0\n for i in range(len(start)):\n if start[i]==\'R\':\n if countL > 0:\n return False\n countR += 1\n if end[i]==\'R\':\n countR -= 1\n if countR < 0:\n return False\n if end[i]==\'L\':\n if countR > 0:\n return False\n countL+=1\n if start[i]==\'L\':\n countL -= 1\n if countL < 0:\n return False\n if countR or countL:\n return False\n return True \n```\n\n```Java []\nclass Solution {\n public boolean canTransform(String start, String end) {\n int i = 0;\n int j = 0;\n char[] s = start.toCharArray();\n char[] e = end.toCharArray();\n while (i < s.length || j < e.length)\n {\n while (i<s.length && s[i] == \'X\') { \n i++; \n }\n while (j<e.length && e[j] == \'X\') {\n j++; \n }\n if (i == s.length || j == e.length) {\n break; \n }\n if (s[i] != e[j] || (s[i] == \'R\' && i > j) || (s[i] == \'L\' && i < j)) {\n return false; \n }\n i++;\n j++;\n }\n return i == j;\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 0 |
swap-adjacent-in-lr-string | Simple Java solution | Keep ordering of L, R | simple-java-solution-keep-ordering-of-l-mvy20 | The idea is must guarantee:\n- Number of L, R are the same and keep ordering. \n- Number of X on the left of L from end always less than or equal the correspond | thangloi | NORMAL | 2022-10-13T05:13:29.897308+00:00 | 2022-10-13T05:13:29.897351+00:00 | 1,140 | false | The idea is must guarantee:\n- Number of L, R are the same and keep ordering. \n- Number of X on the left of L from `end` always less than or equal the corresponding L from `start`\n- Number of X on the right of R from `end` always more than or equal the corresponding R from `start`\n\nWe can terminate the process early once got the first violation, no need to loop through the end of `start`.\n\n# Complexity\n- Time complexity: `O(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```\nclass Solution {\n public boolean canTransform(String start, String end) {\n Queue<Node> logs = new LinkedList<>();\n\n int count = 0;\n for (char c : start.toCharArray()) {\n if (c == \'X\') count++;\n else {\n logs.add(new Node(c, count));\n }\n }\n\n count = 0;\n for (char c : end.toCharArray()) {\n if (c == \'X\') count++;\n else {\n if (logs.isEmpty()) return false;\n\n Node node = logs.poll();\n if (c != node.c) return false;\n\n if (c == \'L\' && count > node.count) return false;\n if (c == \'R\' && count < node.count) return false; \n }\n }\n\n return logs.isEmpty();\n }\n\n class Node {\n public Character c;\n public int count;\n\n public Node(Character c, int count) {\n this.c = c;\n this.count = count;\n }\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
swap-adjacent-in-lr-string | simple explanation C++ | two pointers | simple-explanation-c-two-pointers-by-the-yowu | \nclass Solution {\npublic:\n \n // * R and L ka order remains unchanged\n // * L can go only left of X\n // * R can go only right of X\n \n / | thesarimahmed | NORMAL | 2022-09-11T18:11:01.918082+00:00 | 2022-09-11T18:11:01.918131+00:00 | 386 | false | ```\nclass Solution {\npublic:\n \n // * R and L ka order remains unchanged\n // * L can go only left of X\n // * R can go only right of X\n \n // logic: use two pointers to find positions of L and R (ptr1 for start and ptr2 for end)\n // the pointers skip all X\'s (consider X\'s as spaces)\n // after skipping space each time, check if start[ptr1]==end[ptr2] (if not, return false)\n // as R can move only right, index of R in start must <= index of R in end (think!!)\n // as L can move only left, index of L in start must be >= index of L in end (think!!)\n bool canTransform(string start, string end) {\n if(start.size()==1){\n if(start[0]==end[0])\n return true;\n return false;\n }\n \n int ptr1=0, ptr2=0;\n while( ptr1<start.size() && ptr2<end.size() ){\n while(start[ptr1] == \'X\')\n ptr1++;\n while(end[ptr2] == \'X\')\n ptr2++;\n char a=start[ptr1];\n char b=end[ptr2];\n if(a!=b)\n return false;\n if(a == \'L\' && ptr1<ptr2)\n return false;\n if(a == \'R\' && ptr1>ptr2)\n return false;\n ptr1=ptr1+1;\n ptr2=ptr2+1;\n }\n // for remaining spaces in the end (X\'s)\n while(ptr1<start.size() && start[ptr1]==\'X\')\n ptr1++;\n while(ptr2<end.size() && end[ptr2]==\'X\')\n ptr2++;\n \n return ptr1==ptr2;\n }\n};\n```\n\nreferred from soln of :[https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/1704920/C++-one-pass-time:O(n)-space:O(1)-(with-explanation)](http://) | 2 | 0 | ['Two Pointers', 'C', 'C++'] | 0 |
swap-adjacent-in-lr-string | C++ | Easiest code | Clean and easy to understand | c-easiest-code-clean-and-easy-to-underst-yglv | Please upvote\n\nclass Solution {\npublic:\n bool canTransform(string s, string e) {\n int n=s.size(); \n int i=0,j=0;\n while(i<n or j<n) | GeekyBits | NORMAL | 2022-07-12T13:41:34.422971+00:00 | 2022-07-12T13:41:34.423005+00:00 | 108 | false | Please upvote\n```\nclass Solution {\npublic:\n bool canTransform(string s, string e) {\n int n=s.size(); \n int i=0,j=0;\n while(i<n or j<n){\n \n while(i<n and s[i]==\'X\'){\n i++;\n }\n while(j<n and e[j]==\'X\'){\n j++;\n }\n if(i==n or j==n){\n return i==n and j==n;\n }\n //no we are at two characters\n //so now compare\n if(s[i]!=e[j]){\n return false;\n }\n if(s[i]==e[j] and s[i]==\'R\'){\n if(j<i){\n return false;\n }\n }\n if(s[i]==e[j] and s[i]==\'L\'){\n if(j>i){\n return false;\n } \n }\n \n i++;\n j++;\n }\n return true;\n }\n};\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Simple Java two-pointers solution (no replace( ), no equals(), no StringBuilder) | simple-java-two-pointers-solution-no-rep-mt1y | \nclass Solution {\n public boolean canTransform(String start, String end) {\n \n int p1=0, p2=0;\n \n while(p1 < start.length() | Jumbook | NORMAL | 2022-06-15T18:12:15.983668+00:00 | 2022-06-15T18:15:13.518400+00:00 | 639 | false | ```\nclass Solution {\n public boolean canTransform(String start, String end) {\n \n int p1=0, p2=0;\n \n while(p1 < start.length() || p2 < end.length()) {\n while(p1 < start.length() && start.charAt(p1) == \'X\')\n p1++;\n while(p2 < end.length() && end.charAt(p2) == \'X\')\n p2++;\n \n if(p1 >= start.length() && p2 >= end.length())\n return true;\n \n if(p1 >= start.length() || p2 >= end.length())\n return false;\n \n if(start.charAt(p1) != end.charAt(p2)) \n return false;\n \n if(start.charAt(p1) == \'R\' && p1 > p2) {\n return false;\n }\n \n if(start.charAt(p1) == \'L\' && p1 < p2) {\n return false;\n }\n \n p1++;\n p2++;\n }\n \n return true;\n }\n}\n``` | 2 | 0 | ['Two Pointers', 'Java'] | 0 |
swap-adjacent-in-lr-string | [Java] Two Pointer One Pass O(n) with Explanation | java-two-pointer-one-pass-on-with-explan-pghd | We have 3 cases to handle:\n1. if Xs are removed, the two strings should be identical.\n2. L cannot go to right.\n3. R cannot go to left.\n\nBased on that we ca | lancewang | NORMAL | 2022-05-03T17:18:03.856292+00:00 | 2022-05-03T17:18:03.856326+00:00 | 271 | false | We have 3 cases to handle:\n1. if Xs are removed, the two strings should be identical.\n2. L cannot go to right.\n3. R cannot go to left.\n\nBased on that we can use two pointers and check Rs and Ls positions.\n\n```\npublic boolean canTransform(String start, String end) {\n char[] s = start.toCharArray();\n char[] e = end.toCharArray();\n\n int i = 0, j = 0;\n while(i < s.length && j < e.length){\n if(s[i] == \'X\'){\n i++;\n }else if(e[j] == \'X\'){\n j++;\n }else{\n if(s[i] != e[j] || s[i] == \'R\' && j < i || s[i] == \'L\' && j > i) return false;\n i++;\n j++;\n }\n }\n\n while(i < s.length){\n if(s[i++] != \'X\') return false;\n }\n\n while(j < e.length){\n if(e[j++] != \'X\') return false;\n }\n\n return true;\n }\n | 2 | 0 | ['Two Pointers'] | 1 |
swap-adjacent-in-lr-string | Java 2 pointers O(n) | java-2-pointers-on-by-agusg-m7p4 | \nclass Solution {\n public boolean canTransform(String start, String end) {\n int f = 0;\n int s = 0;\n while(f < start.length() || s < | agusg | NORMAL | 2022-04-17T14:32:20.864939+00:00 | 2022-04-17T14:32:49.266719+00:00 | 643 | false | ```\nclass Solution {\n public boolean canTransform(String start, String end) {\n int f = 0;\n int s = 0;\n while(f < start.length() || s < end.length()) {\n while(f < start.length() && start.charAt(f) == \'X\') f++;\n while(s < end.length() && end.charAt(s) == \'X\') s++;\n if (f == start.length() || s == end.length()) return s == end.length() && f == start.length();\n char stChar = start.charAt(f);\n char enChar = end.charAt(s);\n if (stChar != enChar) return false;\n if (stChar == \'R\' && f > s) return false;\n if (stChar == \'L\' && f < s) return false;\n f++;\n s++;\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Two Pointers', 'Java'] | 0 |
swap-adjacent-in-lr-string | FAANG Onsite Interview Problem - Solution - C++ - O(N) | faang-onsite-interview-problem-solution-xxjl1 | My friend was asked from one of the FAANG companies.\n\nLogic & Algo\nWe will check all the cases where it should return false, if none matches then we will ret | kshitijSinha | NORMAL | 2022-03-23T09:26:37.559790+00:00 | 2022-03-23T09:34:33.488171+00:00 | 331 | false | My friend was asked from one of the FAANG companies.\n\n**Logic & Algo**\nWe will check all the cases where it should return false, if none matches then we will return true.\nWe will use two pointers, one for start (say, iS), and one for end(say, iE).\nWe will move iS and iE till they are pointing at \'X\'.\nNow, if iS and iE are pointing to different values, then we can never reach to the end from the start, hence, return false.\nIf it matches:\n* \tif they are pointing to \'R\', then iS must be less than or equal to iE, as R can be moved to right only from start.\n* \tif they are pointing to \'L\', then iS must be greater than or equal to iE, as L can be moved to left only from start.\n* \tIf the above fails, then we will return false.\n\nAs we will reach the end, there must not remain any L or R in any of the start or end remaining strings.\n\n**Code**\n```\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n int iS = 0, iE = 0;\n while(iS < start.size() && iE < end.size()){\n if(start[iS] != \'X\' && end[iE] != \'X\'){\n if(start[iS] != end[iE])\n return false;\n else if(start[iS] == \'R\' && iS > iE)\n return false;\n else if(start[iS] == \'L\' && iS < iE)\n return false;\n iS++;\n iE++;\n }\n else{\n if(start[iS] == \'X\')\n iS++;\n else\n iE++;\n }\n }\n while(iS < start.size()){\n if(start[iS] != \'X\')\n return false;\n iS++;\n }\n while(iE < end.size()){\n if(end[iE] != \'X\')\n return false;\n iE++;\n }\n return true;\n }\n};\n```\n\nPlease upvote and share your feedback. | 2 | 0 | ['C'] | 1 |
swap-adjacent-in-lr-string | java solution with comments | java-solution-with-comments-by-aryan999-yds1 | \npublic boolean swapAdjacentInLRString(String s, String e) {\n\tif(s.length() != e.length()) return false;\n\tint i = 0, j = 0;\n\tchar[] st = s.toCharArray(); | aryan999 | NORMAL | 2022-02-19T13:26:00.034143+00:00 | 2022-02-19T13:26:00.034178+00:00 | 165 | false | ```\npublic boolean swapAdjacentInLRString(String s, String e) {\n\tif(s.length() != e.length()) return false;\n\tint i = 0, j = 0;\n\tchar[] st = s.toCharArray();\n\tchar[] ed = e.toCharArray();\n\twhile(i < st.length || j < ed.length) {\n\t\t// only need to work with \'L\' and \'R\' so ignore \'X\'\n\t\twhile(i < st.length && st[i] == \'X\'){\n\t\t\t++i;\n\t\t}\n\t\twhile(j < ed.length && ed[j] == \'X\') {\n\t\t\t++j;\n\t\t}\n\t\t// both at end\n\t\tif(i == st.length && j == ed.length) {\n\t\t\treturn true;\n\t\t}\n\t\t// one of them at the end\n\t\tif(i == st.length || j == ed.length) {\n\t\t\treturn false;\n\t\t}\n\t\t// character not similar\n\t\tif(st[i] != ed[j]) return false;\n\t\t// if char is R we can go right only when i pointer doesn\'t exceed j pointer\n\t\tif(st[i] == \'R\' && i > j) return false;\n\t\t// if char is L we can go left only when i pointer exceed j pointer\n\t\tif(st[i] == \'L\' && i < j) return false;\n\t\ti++;\n\t\tj++;\n\t}\n\treturn true;\n}\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Python 3 with explanation | python-3-with-explanation-by-2mobile-ywkg | \n\nFound idea in discussion, replacing names to make it readable. The first idea is \'RX\' can be replaced only with \'XR\', which means that \'R\' is always m | 2mobile | NORMAL | 2022-02-01T22:39:09.691416+00:00 | 2022-02-01T22:39:09.691456+00:00 | 209 | false | \n\nFound idea in discussion, replacing names to make it readable. The first idea is \'RX\' can be replaced only with \'XR\', which means that \'R\' is always moving to the right position if replacement was done. If many replacements done, \'R\' can move to the right so many times until there is a \'L\' on the road or the end of string, then \'R\' can not move further. \'L\' has an opposite behaviour - it can move only to the left side from previous position and it can move until \'R\' is found or until it reach the beginning of string. \nSo we will check 2 coditions - 1. we remove all X and we check that order of \'R\' and \'L\' in strings stays same (you remembre \'R\' can no move further if \'L\' is met and opposite). 2. We will start checking on which position R was in Start string and where it is in End string. If we found that R somehow moved to the left (R must always move to right) then we can not make End string by replacement. Same with L - if we found that at End string it\'s position is more right than in Start - this means we wan\'t be able to create End string with replacemnt. \n\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n if start.replace(\'X\', \'\') != end.replace(\'X\', \'\'): #check 1st condition\n return False\n \n posInEnd = 0\n for posInStart in range(len(start)):\n currentChar = start[posInStart]\n if currentChar == \'X\':\n continue\n else:\n while end[posInEnd] != currentChar : \n posInEnd += 1 # we skip all chars until we found first occurance of currentChar,\n\t\t\t\t\t# we don\'t check if skipped positions have \'X\' or \'R\' or \'L\' because we already confirmed \n\t\t\t\t\t# that \'R\' and \'L\' are having same order is strings during 1st condition check\n if currentChar == \'R\':\n if posInEnd < posInStart:\n return False\n elif currentChar == \'L\': \n if posInEnd > posInStart:\n return False\n posInEnd += 1 # we move to next char because current was confirmed\n \n return True # all checks are passed, we can create End from Start\n | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | [C++] Strict one pass, O(n) time, O(1) space | c-strict-one-pass-on-time-o1-space-by-ti-apn8 | \n// IDEA:\n// 1. Observed that for a valid result:\n// a. For each \'R\' in start, you will have to shift it to right\n// without meeting any \' | tinfu330 | NORMAL | 2021-12-17T02:31:29.884276+00:00 | 2021-12-17T08:33:02.916811+00:00 | 352 | false | ```\n// IDEA:\n// 1. Observed that for a valid result:\n// a. For each \'R\' in start, you will have to shift it to right\n// without meeting any \'L\' in either start or end\n// b. Similar to a, For each \'L\' in end, you will have to shift it\n// to right without meeting any \'R\' in either start or end\n// c. The reason why they cannot meet is because if \'L\' and \'R\' meet\n// they cannot cross eachother to their desired position.\n// d. a special case is:\n// s: XXLL\n// e: LLXX\n// observed that rule a and b still cannot be broken, so use a count\n// to store the Ls / Rs that needs to be shifted\n//\n// 3. So for our solution, we use a one pass for loop from left to right,\n// whenever we meet a \'R\' in start or \'L\' in end, mark it. Keep traversing\n// until we meet an \'R\' or \'L\' in the opposing string. If a false condition\n// is encoutnered, return false. As last, check if there is a buffered \'L\'\n// or \'R\', if not, the two strings are valid.\n//\n// 4. Complexity analysis:\n// O(n) time due to for loop checking each character in start and end\n// O(1) space, only two variables c and cnt\n\nclass Solution {\npublic:\n bool canTransform(string s, string e) {\n char c = \'X\'; // current buffered \'L\' or \'R\'\n int cnt = 0; // number of buffered \'L\' or \'R\'\n\n // One pass for loop\n for (int i = 0; i < s.size(); i++) {\n \n // Check if \'L\' or \'R\' is buffered\n if (c == \'X\') {\n \n // continue if the two characters are the same\n if (s[i] == e[i]) continue;\n \n // invalid position of \'L\' / \'R\', because\n // e[i] should have a buffered \'L\' before an \'L\' in s[i]\n // s[i] should have a buffered \'R\' before an \'R\' in e[i]\n if (s[i] == \'L\' || e[i] == \'R\') return false;\n \n // valid position of \'L\' / \'R\', buffer them\n if (s[i] == \'R\') {\n if (e[i] == \'L\') return false;\n c = s[i];\n cnt++;\n } else if (e[i] == \'L\') {\n if (s[i] == \'R\') return false;\n c = e[i];\n cnt++;\n }\n } else {\n if (s[i] == \'X\' && e[i] == \'X\') continue;\n switch (c) {\n case \'L\':\n if (s[i] == \'R\' || e[i] == \'R\') return false; // refer to description 1c\n if (e[i] == \'L\') cnt++;\n if (s[i] == \'L\') cnt--;\n break;\n case \'R\':\n if (s[i] == \'L\' || e[i] == \'L\') return false; // refer to description 1c\n if (s[i] == \'R\') cnt++;\n if (e[i] == \'R\') cnt--;\n break;\n default:\n return false; // catch exception\n }\n // clear buffer if the count is 0\n if (cnt == 0) c = \'X\';\n }\n }\n // Check if the buffer is cleared\n return c == \'X\';\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
swap-adjacent-in-lr-string | Simple Java O(n) solution with O(1) space with explanation | simple-java-on-solution-with-o1-space-wi-r41y | The problem states that cars cannot collide while moving from one position to the other. Hence if we remove the empty lanes both the start and end would look li | shaolao | NORMAL | 2021-07-03T06:27:39.057175+00:00 | 2021-07-03T06:40:01.370915+00:00 | 359 | false | The problem states that cars cannot collide while moving from one position to the other. Hence if we remove the empty lanes both the start and end would look like identical. For Example : \nstart -> `RXXL` end -> `XRXL`. Both of the strings are identical if we remove the empty lanes -> `RL`. This is because no two cars exchange their relative position. Thus the final result is to find whether both the lanes after removing the empty lanes looks identical and the index in the end is either left or right with respect to the start positions.\n\nFor Example : \n`XXRXXL` -> `XRXXL` would be invalid because istead of movig right the first car has moved left.\n\nTo achieve this we use two pointers one poiting the car in the source lane and another in the target lane. For every car in the soure lane we check the next car in the target lane and if it is not positioned with the given conditions we return false.\n\nTime Complexity : `O(n)`\nWe do Atmost 2 * n number of operations.\n\nSpace Complexity : `O(1)`\nWe only use constant space for the pointers and static variables for storing the \'L\', \'R\' and \'X\'.\n\n```\nclass Solution {\n private static char EMPTY = \'X\';\n private static char RIGHT = \'R\';\n private static char LEFT = \'L\';\n public boolean canTransform(String start, String end) {\n int len = start.length();\n if (end.length() != len) {\n return false;\n }\n int endPointer = 0;\n for (int index = 0; index < len; index++) {\n char c = start.charAt(index);\n if (c != EMPTY) {\n while (endPointer < len && end.charAt(endPointer) == EMPTY){//pointing to the next car in the target lane\n endPointer++;\n }\n if (endPointer == len) {//insufficient number of cars in the target// we ran out of cars to match the source lane\n return false;\n }\n if (c != end.charAt(endPointer) || c == RIGHT && endPointer < index || c == LEFT && endPointer > index) {\n return false;\n }\n endPointer++;\n }\n }\n while (endPointer < len){\n if (end.charAt(endPointer) != EMPTY) {//excess cars in the target lane\n return false;\n }\n endPointer++;\n }\n return true;\n }\n}\n``` | 2 | 0 | ['Two Pointers'] | 0 |
swap-adjacent-in-lr-string | Simple one pass solution O(n) c++ | simple-one-pass-solution-on-c-by-miaodi1-j5si | \n bool canTransform(string start, string end) {\n int l = 0;\n int r = 0;\n for(int i = 0;i<start.size();i++){\n if(start[i] | miaodi1987 | NORMAL | 2021-01-31T04:56:15.448409+00:00 | 2021-01-31T04:56:15.448438+00:00 | 361 | false | ```\n bool canTransform(string start, string end) {\n int l = 0;\n int r = 0;\n for(int i = 0;i<start.size();i++){\n if(start[i]==\'R\'){\n r++;\n }\n if(end[i]==\'L\'){\n l++;\n }\n if(l&&r) return false;\n if(start[i]==\'L\'){\n l--;\n if(l==-1) return false;\n }\n if(end[i]==\'R\'){\n r--;\n if(r==-1) return false;\n }\n }\n return l==0&&r==0;\n }\n``` | 2 | 0 | ['C'] | 1 |
swap-adjacent-in-lr-string | (Java Stack) Each 'L' and 'R' in 'start' actually corresponds to each other in 'end' | java-stack-each-l-and-r-in-start-actuall-gvto | As the title indicates, each \'L\' and \'R\' in \'start\' should correspond to their counterparts in \'end\'. This is because \'R\' can only move to right blank | getonthecar | NORMAL | 2020-09-17T20:39:21.408431+00:00 | 2020-09-17T20:55:07.393938+00:00 | 352 | false | As the title indicates, each \'L\' and \'R\' in \'start\' should correspond to their counterparts in \'end\'. This is because \'R\' can only move to right blank space \'X\' (if any) and \'L\' can only move to left blank space \'X\' (if any), and they can\'t \'fly over\' each other (e.g. `RL` can\'t be transformed into `LR`).\n\nKeeping this in mind, take start=`RXXLRXRXL` and end=`XRLXXRRLX` as an example:\n\n1. First \'R\' at index 0 in \'start\' should correspond to the first \'R\' at index 1 in \'end. \'R\' should only move towards right so this step is valid. \'R\' can only move to right so make sure `start.R.index <= end.R.index`\n\n2. Similarly first \'L\' at index 3 in \'start\' corresponds exactly to the first \'L\' at index 2 in \'end\'. It\'s also valid. \'L\' can only move to left so make sure `start.L.index >= end.L.index`.\n\n3. So on so forth...\n\nLet\'s use 2 stacks to indicate this simple mapping and I know this can be optimized :)\n\n```\nclass Solution {\n class Pos {\n char c;\n int index;\n public Pos(char c, int index) {\n this.c = c;\n this.index = index;\n }\n }\n \n public boolean canTransform(String start, String end) {\n Deque<Pos> startStack = new ArrayDeque<>();\n Deque<Pos> endStack = new ArrayDeque<>();\n \n for (int i = 0; i < start.length(); i++) {\n char sc = start.charAt(i);\n char ec = end.charAt(i);\n if (sc != \'X\') {\n startStack.addLast(new Pos(sc, i));\n }\n if (ec != \'X\') {\n endStack.addLast(new Pos(ec, i));\n }\n }\n \n if (startStack.size() != endStack.size()) {\n return false;\n }\n \n while (!startStack.isEmpty() && !endStack.isEmpty()) {\n Pos sPos = startStack.removeLast();\n Pos ePos = endStack.removeLast();\n \n char sc = sPos.c;\n int sIndex = sPos.index;\n char ec = ePos.c;\n int eIndex = ePos.index;\n \n if (sc != ec) {\n return false;\n }\n if (sc == \'L\' && sIndex < eIndex || sc == \'R\' && sIndex > eIndex) {\n return false;\n }\n }\n return startStack.isEmpty() && endStack.isEmpty();\n }\n}\n```\n\nWith O(n) time and space. | 2 | 0 | ['Stack', 'Java'] | 0 |
swap-adjacent-in-lr-string | Does anyone understand what the question is asking? | does-anyone-understand-what-the-question-2j76 | I don\'t understand the explanation provided by the example. Where did RXXLRXRXL come from? My understanding is that the transformation would start with X\n\n`` | johnbaek92 | NORMAL | 2020-09-09T17:55:25.288796+00:00 | 2020-09-09T17:55:25.288826+00:00 | 154 | false | I don\'t understand the explanation provided by the example. Where did `RXXLRXRXL` come from? My understanding is that the transformation would start with X\n\n```\nInput: start = "X", end = "L"\nOutput: false\nExplanation:\nWe can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX | 2 | 0 | [] | 2 |
swap-adjacent-in-lr-string | JavaScript Time O(n) | javascript-time-on-by-yuchen_peng-l7gp | \n/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n let R = 0\n let L = 0\n | yuchen_peng | NORMAL | 2020-06-20T23:43:13.171700+00:00 | 2020-06-20T23:43:48.466281+00:00 | 142 | false | ```\n/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n let R = 0\n let L = 0\n if (start.length != end.length) {\n return false\n }\n var i = 0\n while (i < start.length) {\n let char_s = start[i]\n let char_e = end[i] \n if (char_s === \'R\') {\n R += 1\n } else if (char_s === \'L\') {\n L += 1\n } \n if (L < 0 && R > 0) {\n return false\n } \n \n if (char_e === \'R\') {\n R -= 1\n } else if (char_e === \'L\') {\n L -= 1\n }\n if (L > 0 || R < 0) {\n return false\n }\n if (L < 0 && R > 0) {\n return false\n } \n i++\n }\n \n return L === 0 && R === 0\n};\n``` | 2 | 1 | [] | 1 |
swap-adjacent-in-lr-string | [Python] Simple One Pass O(N) Solution | python-simple-one-pass-on-solution-by-to-yf6t | Iterate from left to right, to check if there are enough R.\nIterate from right to left, to check if there are enough L.\n\nclass Solution:\n def canTransfor | tommmyk253 | NORMAL | 2020-06-16T06:53:13.151415+00:00 | 2020-06-16T06:53:13.151447+00:00 | 121 | false | Iterate from left to right, to check if there are enough ```R```.\nIterate from right to left, to check if there are enough ```L```.\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n L = R = 0\n for i in range(len(start)):\n a, b = start[i], end[i]\n R = R + 1 if a == \'R\' else (0 if a == \'L\' else R)\n if b == \'R\' and not R:\n return False\n R -= b == \'R\'\n \n j = len(start) - 1 - i\n c, d = start[j], end[j]\n L = L + 1 if c == \'L\' else (0 if c == \'R\' else L)\n if d == \'L\' and not L:\n return False\n L -= d == \'L\'\n \n return L == R == 0\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Short and clean JAVA code | short-and-clean-java-code-by-chenzuojing-2j7n | \n\tpublic boolean canTransform(String start, String end) {\n\t\tif (!start.replace("X", "").equals(end.replace("X", ""))) return false;\n\n\t\tint i = 0, j = 0 | chenzuojing | NORMAL | 2020-04-20T13:21:36.443034+00:00 | 2020-04-20T13:21:36.443070+00:00 | 196 | false | ```\n\tpublic boolean canTransform(String start, String end) {\n\t\tif (!start.replace("X", "").equals(end.replace("X", ""))) return false;\n\n\t\tint i = 0, j = 0;\n\t\tint len = start.length();\n\n\t\twhile (i < len && j < len) {\n\t\t\twhile (i < len && start.charAt(i) == \'X\') i++;\n\t\t\twhile (j < len && end.charAt(j) == \'X\') j++;\n\t\t\tif (i < len && start.charAt(i) == \'L\' && i < j) return false;\n\t\t\tif (i < len && start.charAt(i) == \'R\' && i > j) return false;\n\t\t\ti++;\n\t\t\tj++;\n\t\t}\n\n\t\treturn true;\n\t}\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Java AC Solution, with explanation | java-ac-solution-with-explanation-by-gup-enxr | \n```\n public boolean canTransform(String start, String end) {\n /\n Core concept - Left should stay in the left and R should stay in the righ | gupibagha | NORMAL | 2020-03-08T06:15:21.301468+00:00 | 2020-03-08T06:15:21.301515+00:00 | 222 | false | \n```\n public boolean canTransform(String start, String end) {\n /**\n Core concept - Left should stay in the left and R should stay in the right\n we traverse both the string ignoring the \'X\'\n If both indices reach the end, we are good, return true.\n If either reaches end means a mismatch, so return false\n Also L can only move left so if the position of L in the END is after START, return false\n Similarly if R moves left, return false\n \n **/\n if(start.length() != end.length()) return false;\n \n int i=0, j =0;\n while(i<start.length() && j<start.length()) {\n \n while(i<start.length() && start.charAt(i) == \'X\') i++;\n while(j<end.length() && end.charAt(j) == \'X\') j++;\n \n \n if(i == start.length() && j == start.length()) return true;\n if(i == start.length() || j == start.length()) return false;\n \n if(start.charAt(i) != end.charAt(j) ) return false;\n \n if(start.charAt(i) ==\'L\' && i<j) return false;\n \n if(start.charAt(i) ==\'R\' && i>j) return false;\n \n i++;\n j++;\n }\n return true;\n } | 2 | 0 | [] | 1 |
swap-adjacent-in-lr-string | Java O(N), two point. | java-on-two-point-by-sakura-hly-9563 | If start can be tansform to end, then\n1. index of i-L in start >= index of i-L in end,\n2. index of i-R in start <= index of i-R in end.\n\nclass Solution {\n | sakura-hly | NORMAL | 2019-06-27T10:09:32.273695+00:00 | 2019-06-27T10:09:32.273737+00:00 | 238 | false | If start can be tansform to end, then\n1. index of i-L in start >= index of i-L in end,\n2. index of i-R in start <= index of i-R in end.\n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n if (start.equals(end)) return true;\n\n int i = 0, j = 0;\n while (i < start.length() && j < end.length()) {\n while (i < start.length() && start.charAt(i) == \'X\') i++;\n while (j < end.length() && end.charAt(j) == \'X\') j++;\n if (i < start.length() && j < end.length()) {\n if (start.charAt(i) != end.charAt(j)) return false;\n if (start.charAt(i) == \'L\' && i < j) return false;\n if (start.charAt(i) == \'R\' && i > j) return false;\n i++;\n j++;\n } else if (i < start.length() || j < end.length()) return false;\n }\n return true;\n }\n}\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Readable Javascript Solution | readable-javascript-solution-by-codingba-p44d | Javscript solution of https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/113789/Simple-Java-one-pass-O(n)-solution-with-explaination\n\nIdea is to | codingbarista | NORMAL | 2018-11-12T01:30:38.610301+00:00 | 2018-11-12T01:30:38.610347+00:00 | 321 | false | Javscript solution of https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/113789/Simple-Java-one-pass-O(n)-solution-with-explaination\n\nIdea is to get non-X chars and compare their positions\n\n```\nfunction canTransform(start, end) {\n start = start.replace(/X/g, \'\');\n end = end.replace(/X/g, \'\');\n\n if (start !== end) return false;\n\n let p1 = 0;\n let p2 = 0;\n\n while (p1 < start.length && p2 < end.length) {\n // find non-X char\n while (p1 < start.length && start[p1] === \'X\') p1++;\n while (p2 < end.length && end[p2] === \'X\') p2++;\n\n // if both reached the end then they are the same\n if (p1 === start.length && p2 === end.length) return true;\n\n // if only one reached the end then they are not transformable\n if (p1 === start.length || p2 === end.length) return false;\n\n if (start[p1] !== end[p2]) return false;\n\n if (start[p1] === \'L\' && p2 > p1) return false;\n\n if (start[p1] === \'R\' && p1 > p2) return false;\n\n p1++;\n p2++;\n }\n\n return true;\n}\n``` | 2 | 2 | [] | 2 |
swap-adjacent-in-lr-string | [c++, 10 lines, O(n)] detailed explaination, easy to understand! | c-10-lines-on-detailed-explaination-easy-pym0 | The basic idea is to count the number of R in start string, and the number of L in end string. \nThe reason is that when we meet a \'R\' in the end string, we h | strangecloud9 | NORMAL | 2018-11-09T19:20:19.342509+00:00 | 2018-11-09T19:20:19.342554+00:00 | 372 | false | The basic idea is to count the number of R in start string, and the number of L in end string. \nThe reason is that when we meet a \'R\' in the end string, we hope there is a \'R\' in the start string before. This is why we need to count the number of R in the start string.\nAnd when we meet a \'L\' in the start string, we hope we have meet a \'L\' in the end string before.\nIf we didn\'t meet what we need before, return false, that is (cnt_r < 0 || cnt_l < 0).\nIf we meet both \'L\' and \'R\', return false, because we cannot let a \'L\' or \'R\' go across each other, and that is (cnt_r > 0 && cnt_l > 0)\n\nIn the end, we hope all R and L have been used, that is return cnt_r == 0 && cnt_l == 0\n```\n bool canTransform(string start, string end) {\n if(start.length() != end.length()) return false;\n int cnt_r = 0, cnt_l = 0;\n for(int i = 0, j = 0; i < start.size(), j < end.size(); i++, j++) {\n cnt_r += start[i] == \'R\' ? 1 : 0;\n cnt_l += end[j] == \'L\' ? 1 : 0;\n if(end[j] == \'R\' && cnt_l == 0) cnt_r --;\n if(start[i] == \'L\' && cnt_r == 0) cnt_l --;\n if(cnt_r < 0 || cnt_l < 0 || (cnt_r > 0 && cnt_l > 0)) return false;\n }\n return cnt_r == 0 && cnt_l == 0;\n }\n``` | 2 | 0 | [] | 1 |
swap-adjacent-in-lr-string | Python3 O(n) one pass 112 ms | python3-on-one-pass-112-ms-by-luckypants-s2py | ``` class Solution: def canTransform(self, start, end): """ :type start: str :type end: str :rtype: bool """ | luckypants | NORMAL | 2018-03-04T12:56:49.439173+00:00 | 2018-03-04T12:56:49.439173+00:00 | 216 | false | ```
class Solution:
def canTransform(self, start, end):
"""
:type start: str
:type end: str
:rtype: bool
"""
swap = {'R':'X', 'X':'L'}
# print("CanTransform: ", start, end)
if len(start)!=len(end):
return False
if start==end:
return True
dic = collections.Counter(start)
for c in end:
dic[c] -= 1
if dic[c]<0:
return False
length = len(start)
r = length-1
idx = r
laste = end[r]
while r>0:
while r>=0 and start[r]==end[r]:
r -= 1
if r<=0:
return True
if end[r]=='L':
return False
if end[r]!=laste:
idx = r
else:
idx = min(r, idx)
laste = end[r]
while start[idx]!=end[r]:
if start[idx]!=swap[end[r]]:
return False
idx -= 1
if idx<0:
return False
if idx==r:
r -= 1
continue
start = start[:idx] + start[idx+1:] + start[idx]
r -= 1
# print(start, end)
return True
| 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | O(n) time O(1) space C++ | on-time-o1-space-c-by-imrusty-kx8m | Let j be the index that is the first that r[j] != r[i]. Moving i from 0 to n, if r[i] == s[i] then do nothing. When r[i] != s[i], it is only feasible to change | imrusty | NORMAL | 2018-02-08T04:35:13.208000+00:00 | 2018-02-08T04:35:13.208000+00:00 | 585 | false | Let j be the index that is the first that r[j] != r[i]. Moving i from 0 to n, if r[i] == s[i] then do nothing. When r[i] != s[i], it is only feasible to change r to match s if r[i] == 'R' or s[i] == 'L', and one of them is 'X'. In that case the right move is to move r[j] all the way back to i-th position in case r[i] = 'X' and r[j] ='L', or to move r[i] all the way to j-th position if r[i] ='R' and r[j] = 'X'. Either case is equivalent to swap(r[i], r[j]).\n```\nclass Solution {\npublic:\n bool can(string r, string s) {\n int n = r.size();\n r += 'T';\n int i = 0, j = 0;\n while (i < n) {\n while (r[j] == r[i]) ++j;\n if (i >= 0 && s[i] != r[i]) {\n if (r[i] != 'X' && s[i] != 'X') return false;\n if (r[i] == 'R' || s[i] == 'L') {\n if (r[j] != s[i]) return false;\n swap(r[j],r[i]);\n }\n else return false;\n }\n ++i;\n }\n return true;\n } \n \n bool canTransform(string r, string s) {\n if (r.size() != s.size()) return false;\n return can(r,s);\n }\n};\n``` | 2 | 0 | [] | 1 |
swap-adjacent-in-lr-string | python O(n) solution | python-on-solution-by-erjoalgo-jeiw | both strings must have equal character counts\n for any substring end[:i], the number of R characters must be <= those in start, since Rs only move to the right | erjoalgo | NORMAL | 2018-02-04T09:13:07.268000+00:00 | 2018-02-04T09:13:07.268000+00:00 | 260 | false | * both strings must have equal character counts\n* for any substring `end[:i]`, the number of `R` characters must be `<=` those in `start`, since `Rs` only move to the right\n* for any substring `end[:i]`, the number of `L` characters must be `>=` those in `start`, since `Ls` only move to the left\n* an `L` and an `R` cannot cross each other, so we must see the same blocks of consecutive `Ls` and `Rs` in both strings. This can be verified by ignoring the `X` characters\n\n```\nclass Solution(object):\n def canTransform(self, start, end):\n """\n :type start: str\n :type end: str\n :rtype: bool\n """\n\n if collections.Counter(start)!=collections.Counter(end):\n return False\n \n \n a,b=0,0\n \n c,d=0,0\n \n for i in xrange(len(end)):\n a+=start[i]=='R'\n b+=end[i]=='R'\n if a<b: return False\n \n c+=start[i]=='L'\n d+=end[i]=='L'\n if c>d: return False\n \n return start.replace("X", "")==end.replace("X", "")\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | JAVA O(n) Two Pointer Solution | java-on-two-pointer-solution-by-cxu-6rhv | Use two pointer to check the following 2 conditions:\n1. Without 'X', 'L' and 'R' has the same relative position in start and end\n2. For any corresponding 'R' | cxu | NORMAL | 2018-02-04T06:12:46.516000+00:00 | 2018-02-04T06:12:46.516000+00:00 | 364 | false | Use two pointer to check the following 2 conditions:\n1. Without 'X', 'L' and 'R' has the same relative position in start and end\n2. For any corresponding 'R' in start and end, say start[i] and end[j], i <= j, and for any corresponding 'L', i >= j.\n```\npublic boolean canTransform(String start, String end) {\n if (start.length() != end.length()) {\n return false;\n }\n int i = 0, j = 0;\n while (i < start.length() && j < end.length()) {\n if (start.charAt(i) == 'X') {\n i++;\n continue;\n }\n else if (end.charAt(j) == 'X') {\n j++;\n continue;\n }\n else if (start.charAt(i) == end.charAt(j)) {\n if ((start.charAt(i) == 'R' && i > j) || (end.charAt(j) == 'L' && i < j)) {\n return false;\n }\n i++;\n j++;\n }\n else {\n return false;\n }\n }\n while (i < start.length()) {\n if (start.charAt(i++) != 'X') {\n return false;\n }\n }\n while (j < end.length()) {\n if (end.charAt(j++) != 'X') {\n return false;\n }\n }\n return true;\n}\n``` | 2 | 0 | [] | 0 |
swap-adjacent-in-lr-string | Python Regex and Recursion/Iterative versions | python-regex-and-recursioniterative-vers-gyl2 | The recursive solution is easy to understand, but the recursive version fails in OJ for huge strings with maximum recursion depth exceeded, hence I converted it | Cubicon | NORMAL | 2018-02-04T04:36:41.844000+00:00 | 2018-02-04T04:36:41.844000+00:00 | 684 | false | The recursive solution is easy to understand, but the recursive version fails in OJ for huge strings with maximum recursion depth exceeded, hence I converted it to iterative version, which gets accepted easily.\n\nLogic:\n\nIf the current character matches, we just increment i.\nIf the current character does not match:\nthen we are trying to find patterns XXXL or RRRX which is basically [X]+L or [R]+X in regex form.\nSay XXXL matches the start string, then we just make sure that end string starts with L, and we convert the start string to XXX + remaining and proceed with the rest of the string\n\nIterative version:\n```\ndef canTransform(self, start, end):\n if start == end: return True\n i = 0\n while i < len(start):\n if start[i] == end[i]:\n i += 1\n else:\n new_se = self.get_transformed(start[i:], end[i:], 'X+L') or self.get_transformed(start[i:], end[i:], 'R+X')\n if not new_se: return False\n start, end, i = new_se[0], new_se[1], 0\n return True\n\n def get_transformed(self, start, end, regex):\n m = re.match(regex, start)\n if m and end[0] == start[m.end() - 1]:\n return (start[0] * (m.end() - 1)) + start[m.end():], end[1:]\n return None\n```\n\nRecursive version:\n\n def canTransform(self, start, end):\n if start == end: return True\n\n if start[0] == end[0]:\n return self.canTransform(start[1:], end[1:])\n\n new_se = self.get_transformed(start, end, 'X+L') or self.get_transformed(start, end, 'R+X')\n if new_se: return self.canTransform(new_se[0], new_se[1])\n\n return False\n \n def get_transformed(self, start, end, regex):\n m = re.match(regex, start)\n if m and end[0] == start[m.end()-1]:\n return (start[0] * (m.end()-1)) + start[m.end():], end[1:]\n return None | 2 | 0 | [] | 1 |
swap-adjacent-in-lr-string | BEST OPTIMAL SOLUTION✅✅ || 100% BEATS✅ | best-optimal-solution-100-beats-by-gaura-0ms2 | IntuitionApproachComplexity
Time complexity: O(N)
Space complexity: O(1)
Code | Gaurav_SK | NORMAL | 2025-04-11T11:40:24.258576+00:00 | 2025-04-11T11:40:24.258576+00:00 | 27 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool canTransform(string st, string res) {
string s, p;
for (char c : st){
if (c != 'X') s += c;
}
for (char c : res){
if (c != 'X') p += c;
}
if (s != p){
return false;
}
int i = 0, j = 0, n = st.length();
while (i < n && j < n){
while (i<n && st[i] == 'X') i++;
while (j<n && res[j] == 'X') j++;
if (i == n && j == n) return true;
if ((i == n) != (j == n)) return false;
if (st[i] != res[j]) return false;
if (st[i] == 'L' && i<j) return false;
if (st[i] == 'R' && i>j) return false;
i++;
j++;
}
return true;
}
};
``` | 1 | 0 | ['Two Pointers', 'String', 'String Matching', 'C++'] | 0 |
swap-adjacent-in-lr-string | 100% ACCEPTANCE | USING QUEUES 🏆🚀😻😻😻 | 100-acceptance-using-queues-by-shyyshawa-1h1j | IntuitionIN THIS PROBLEM WE WILL DONT REALLY HAVE TO SHIFT THE VALUES WE JUST NEED TO MAKE A CHECK ON THEM.
WE WILL BE MAINTAINING 2 QUEUES EACH FOR THE TWO WOR | Shyyshawarma | NORMAL | 2025-01-24T03:51:45.070262+00:00 | 2025-01-24T03:51:45.070262+00:00 | 43 | false | # Intuition
IN THIS PROBLEM WE WILL DONT REALLY HAVE TO SHIFT THE VALUES WE JUST NEED TO MAKE A CHECK ON THEM.
WE WILL BE MAINTAINING 2 QUEUES EACH FOR THE TWO WORDS AND THEN SKIP THE CHARACTER IF IT IS AN 'X' AND KEEP ONLY THE L OR R COUNTER PIECE, AND THEN WE WILL CHECK IF THE NUMBER OF COUNTERPIECES ARE EQUAL OR NOT.
NOW WE WILL CHECK.
IF WE HAVE DISSIMILAR CHARACTERS RETURN FALSE ELSE WE WILL COMPARE IF THE TARGET HAS OCCURANCE OF L BEFORE THE TARGET OR R AFTER THE TARGET THEN RETURN FALSE.
<!-- Describe your first thoughts on how to solve this problem. -->
<!-- # Approach -->
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(2N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(2N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool canTransform(string start, string result) {
queue<pair<char,int>> startq,resultq;
if(start.size()!=result.size()) return false;
for(int i=0;i<start.size();i++){
if(start[i]!='X') startq.push({start[i],i});
if(result[i]!='X') resultq.push({result[i],i});
}
if(startq.size()!=resultq.size()) return false;
while(!startq.empty()){
auto [startval,startindex]=startq.front();
startq.pop();
auto [resultval,resultindex]=resultq.front();
resultq.pop();
if(resultval!=startval) return false;
if(resultval=='L' && startindex<resultindex) return false;
if(resultval=='R' && startindex>resultindex) return false;
}
return true;
}
};
``` | 1 | 0 | ['C++'] | 0 |
swap-adjacent-in-lr-string | Simple N Complexity two Pointer solution | simple-n-complexity-two-pointer-solution-qcu3 | 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 | samiul_bu | NORMAL | 2024-10-04T19:51:11.876759+00:00 | 2024-10-04T19:51:11.876789+00:00 | 315 | false | # 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```cpp []\nclass Solution {\npublic:\n bool canTransform(string start, string end) {\n string withOutXS = "", withOutXE = "";\n for(int i=0;i<start.size();i++) {\n if(start[i] !=\'X\') {\n withOutXS += start[i];\n }\n if(end[i] != \'X\') {\n withOutXE += end[i];\n }\n }\n if(withOutXS != withOutXE) {\n return false;\n }\n\n int startI = 0, endI = 0;\n int upX = 0, lowX = 0;\n while(startI<start.size() && endI<end.size()) {\n \n if(start[startI]==\'X\' && lowX) {\n startI++; lowX--;\n } else if(end[endI]==\'X\' && upX) {\n endI++; upX--;\n } else if(start[startI]==end[endI]) {\n startI++;\n endI++;\n } else if(start[startI]==\'R\' && end[endI]==\'X\') {\n endI++;\n lowX++;\n } else if(start[startI]==\'X\' && end[endI]==\'L\') {\n startI++; upX++;\n } else {\n return false;\n }\n }\n\n while(startI<start.size() && lowX) {\n if(start[startI]!=\'X\') {\n return false;\n }\n lowX--;\n }\n\n while(endI<end.size() && upX) {\n if(end[endI]!=\'X\') {\n return false;\n }\n upX--;\n }\n if(upX>0 || lowX>0) {\n return false;\n }\n\n return true;\n }\n};\n\n/*\n RX - XR\n XL - LX\n\n RLX\n XRL\n\n X can Move left if R there.\n X can Move right if L there.\n*/\n``` | 1 | 0 | ['C++'] | 0 |
swap-adjacent-in-lr-string | Beats 100% | beats-100-by-groundzerocro-hs1g | Code\n\nclass Solution {\n fun canTransform(start: String, end: String): Boolean {\n\n val size = start.length\n\n var i = 0\n var j = 0 | groundzerocro | NORMAL | 2023-12-18T13:11:06.610685+00:00 | 2023-12-18T13:11:06.610722+00:00 | 7 | false | # Code\n```\nclass Solution {\n fun canTransform(start: String, end: String): Boolean {\n\n val size = start.length\n\n var i = 0\n var j = 0\n\n while (i < size || j < size) {\n while (i < size && start[i] == \'X\') {\n i++\n }\n while (j < size && end[j] == \'X\') {\n j++\n }\n if(i == size || j == size) {\n break\n }\n if (\n start[i] != end[j] ||\n (start[i] == \'L\' && i < j) ||\n (start[i] == \'R\' && i > j)\n ) {\n return false\n }\n i++\n j++\n }\n\n return i == size && j == size\n }\n}\n``` | 1 | 0 | ['Kotlin'] | 0 |
swap-adjacent-in-lr-string | 4 Solutions: TLE -> O(n) Space Optimised - Python/Java | 4-solutions-tle-on-space-optimised-pytho-1h1a | Intuition\n\nIn spite of the downvotes I actually thought this was a pretty good question, even though only the O(n) passes. \n\nI\'ve heavily commented the cod | katsuki-bakugo | NORMAL | 2023-10-04T16:04:10.996543+00:00 | 2023-12-16T20:13:37.398922+00:00 | 384 | false | > # Intuition\n\nIn spite of the downvotes I actually thought this was a pretty good question, even though only the O(n) passes. \n\nI\'ve heavily commented the code with explanations, and provided the brute force alternatives that don\'t pass for people like me who find those helpful:\n\n---\n\n\n> # DFS (TLE)\n\n```python []\n#TLE - DFS\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n #after we\'ve altered the string at some index\n #we need to start i from the beginning, so for the dfs\n #a for loop is needed\n def dfs(curr):\n #if the current string we\'re on ever hits the end\n if curr == end:\n #pass true back up the call stack\n return True\n\n #attempt to change each character in the string\n for i in range(len(curr)):\n #if the search isn\'t out of bounds\n if i+1<len(curr):\n curr_string = curr[i]+curr[i+1]\n #then try to make each i "XL" or "XR" if possible\n if curr_string == "XL" and dfs(curr[:i]+"LX"+curr[i+2:]):\n return True\n elif curr_string == "RX" and dfs(curr[:i]+"XR"+curr[i+2:]):\n return True\n return False\n return dfs(start)\n```\n```Java []\n//Java - TLE - DFS\nclass Solution{\n private String end;\n public Solution(){};\n\n public boolean canTransform(String start, String end){\n this.end = end;\n return dfs(start);\n }\n\n private boolean dfs(String curr){\n if (curr.equals(end)){\n return true;\n }\n for (int i = 0; i < curr.length();i++){\n if (i+1<curr.length()){\n String curr_string = (""+curr.charAt(i))+(""+curr.charAt(i+1));\n String lx_string = curr.substring(0, i)+"LX"+curr.substring(i+2, curr.length());\n String rx_string = curr.substring(0, i)+"XR"+curr.substring(i+2, curr.length());\n if (curr_string.equals("XL") && dfs(lx_string)){\n return true;\n }else if(curr_string.equals("RX") && dfs(rx_string)){\n return true;\n }\n }\n }\n return false;\n }\n}\n```\n\n---\n\n> # DFS + Memoisation (TLE)\n\n```python []\n#TLE - DFS + Memo\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n #exact same concept as the DFS solution, except we memoise\n #the strings, although this still gives TLE\n map = {}\n def dfs(curr):\n if curr == end:\n return True\n elif curr in map:\n return map[curr]\n \n map[curr] = False\n for i in range(len(curr)):\n if i+1<len(curr):\n curr_string = curr[i]+curr[i+1]\n if curr_string == "XL" and dfs(curr[:i]+"LX"+curr[i+2:]):\n return True\n elif curr_string == "RX" and dfs(curr[:i]+"XR"+curr[i+2:]):\n return True\n return map[curr]\n return dfs(start)\n```\n```Java []\n//Java - TLE - DFS + Memo\nclass Solution{\n private String end;\n private Map<String,Boolean> map;\n public Solution(){\n this.map = new HashMap<>();\n };\n \n public boolean canTransform(String start, String end){\n this.end = end;\n return dfs(start);\n }\n\n private boolean dfs(String curr){\n if (curr.equals(end)){\n return true;\n }else if (map.containsKey(curr)){\n return map.get(curr);\n }\n map.put(curr, false);\n for (int i = 0; i < curr.length();i++){\n if (i+1<curr.length()){\n String currString = (""+curr.charAt(i))+(""+curr.charAt(i+1));\n String lx_string = curr.substring(0, i)+"LX"+curr.substring(i+2, curr.length());\n String rx_string = curr.substring(0, i)+"XR"+curr.substring(i+2, curr.length());\n if (currString.equals("XL")&& dfs(lx_string)){\n return true;\n }else if (currString.equals("RX")&& dfs(rx_string)){\n return true;\n }\n }\n }\n return map.get(curr);\n }\n}\n```\n\n---\n\n> # BFS\n\n```python []\n#TLE BFS + Memo\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n #Sadly BFS also too slow, we remember the strings using \n #a hashset\n q = [start]\n seen = set()\n while q:\n curr = q.pop()\n if curr == end:\n return True\n elif curr in seen:\n continue\n #for each string, try changing the characters\n #and adding it to the queue if it\'s valid\n for i in range(len(curr)):\n if i+1<len(curr):\n curr_string = curr[i]+curr[i+1]\n if curr_string == "XL":\n q.append(curr[:i]+"LX"+curr[i+2:])\n #add the string to seen so we don\'t re-visit it\n seen.add(curr)\n elif curr_string == "RX":\n q.append(curr[:i]+"XR"+curr[i+2:])\n seen.add(curr)\n return False\n```\n```Java []\n//Java - BFS + Memo\nclass Solution {\n public Solution(){};\n public boolean canTransform(String start, String end) {\n Queue<String> q = new LinkedList<>();\n Set<String> seen = new HashSet<>();\n\n q.add(start);\n seen.add(start);\n\n while (!q.isEmpty()) {\n String curr = q.poll();\n \n if (curr.equals(end)) {\n return true; \n }\n\n for (int i = 0; i < curr.length(); i++) {\n if (i + 1 < curr.length()) {\n String curr_string = curr.substring(i, i + 2);\n if (curr_string.equals("XL")) {\n String next = curr.substring(0, i) + "LX" + curr.substring(i + 2);\n if (!seen.contains(next)) {\n q.add(next);\n seen.add(next);\n }\n } else if (curr_string.equals("RX")) {\n String next = curr.substring(0, i) + "XR" + curr.substring(i + 2);\n if (!seen.contains(next)) {\n q.add(next);\n seen.add(next);\n }\n }\n }\n }\n }\n return false;\n }\n}\n```\n\n---\n\n> # O(n)\n\nCredit `@HigherBro`\n```python []\n#O(n)\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n #to get the O(n) solution for this problem, you have to\n #use the constraints of the question\n\n #often with these true/false type questions, or optimising\n #problems with vague statements, we need to use our environment\n #or things we already know about the expected input/output\n\n #since XL can only be replaced with LX, and RX can only be\n #replaced with XR, we know that if we ever encounter a scenario\n #where L is next to R or R is next to L e.g "LR" or "RL" it\'ll\n #be impossible for us to ever transform one to the other\n #meaning, if we simply strip the start and end strings of all X\'s\n #start should == end\n\n #why? the shuffling of start to end should ONLY be influenced by X delimiters\n #if the string is valid. meaning if when we remove all X\'s, and the strings aren\'t the same\n #we know some other operation involving the crossing of R\'s and L\'s occurred (with no X\'s in between),\n #or the count of characters in start and end aren\'t the same\n #therefore no matter how many times we move XL or RX, getting the end is impossible\n\n #so let\'s remove the X\'s and if they\'re not the same we immediately return False\n if start.replace("X","") != end.replace("X",""):\n return False\n\n #if they are, we know it may be possible to swap some characters\n #and get the end string\n #PROVIDED THAT all indexes of occurances of L in start, are less than L\n #in end, and all indexes of occurances of R in start are greater than R in end\n #if you notice, when we\'re swapping XL to LX, L is essentially moving to the left\n #likewise with R, R is moving to the right. \n #meaning so long as we DON\'T encounter an occurance of L in end that exceeds\n #it\'s corresponding index in start, it\'s possible to swap these characters\n #and ultimately form the string end. Notice we just need to return if it\'s possible, \n #and not the number of times, so this will work\n\n #find the indexes of l\'s and r\'s in both strings\n l_start, l_end, r_start, r_end = [],[],[],[]\n for i in range(len(start)):\n if start[i] == "L":\n l_start.append(i)\n elif start[i] == "R":\n r_start.append(i)\n if end[i] == "L":\n l_end.append(i)\n elif end[i] == "R":\n r_end.append(i)\n\n #go through the l\'s to verify the indexes:\n for i in range(len(l_start)):\n if l_start[i]<l_end[i]:\n return False\n \n #do the same for the ends\n for i in range(len(r_start)):\n if r_start[i]>r_end[i]:\n return False\n \n #if we never disprove the string, return true\n return True\n```\n```Java []\n//Java - O(n)\nclass Solution {\n public Solution() {};\n\n public boolean canTransform(String start, String end) {\n if (!start.replace("X", "").equals(end.replace("X", ""))) {\n return false;\n }\n\n List<Integer> l_start = new ArrayList<Integer>();\n List<Integer> l_end = new ArrayList<Integer>();\n List<Integer> r_start = new ArrayList<Integer>();\n List<Integer> r_end = new ArrayList<Integer>();\n\n for (int i = 0; i < start.length(); i++) {\n if (start.charAt(i) == \'L\') {\n l_start.add(i);\n } else if (start.charAt(i) == \'R\') {\n r_start.add(i);\n }\n if (end.charAt(i) == \'L\') {\n l_end.add(i);\n } else if (end.charAt(i) == \'R\') {\n r_end.add(i);\n }\n }\n\n for (int i = 0; i < l_start.size(); i++) {\n if (l_start.get(i) < l_end.get(i)) {\n return false;\n }\n }\n\n for (int i = 0; i < r_start.size(); i++) {\n if (r_start.get(i) > r_end.get(i)) {\n return false;\n }\n }\n return true;\n }\n}\n\n```\n\n---\n\n> # O(n) Space Optimised\nCredit `@Samuel_Ji`\n```python []\n#O(n) less space\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n #we can optimise the O(n) to use less space by using two pointers\n \n #we still need to ensure the strings possess the same characters \n #this in essence serves two purposes\n # 1. ensure the strings possess the same count of characters for each distinct character\n # 2. ensures if they have the same characters, that they\'re in the same order\n # to avoid situations like "LR" and "RL" \n if start.replace("X","") != end.replace("X",""):\n #we can have cases such as:\n #start = "RXR"\n #end = "XXR"\n #here start actually has more R\'s than end, so it\'s impossible to make it into XXR\n return False\n\n #p1 and p2 begin at the start of both strings\n p1,p2 = 0,0\n\n #we stay in the loop while at least 1 pointer is less\n #than it\'s respective string\n while p1 < len(start) and p2 < len(end):\n #based on the previous O(n) solution, we know the X\'s\n #are largely irrelevant for this problem, so lets just increment the pointers\n #and skip them. We still need their presence in the strings however, in order\n #to track indexes for p1 and p2\n while p1 < len(start) and start[p1] == "X":\n p1+=1 \n while p2 < len(end) and end[p2] == "X":\n p2+=1 \n \n #if both have hit the end of the string at this point\n if p1 == len(start) and p2 == len(end):\n #then it\'s transformable\n return True\n #if one has, and one hasn\'t\n elif p1 == len(start) or p2 == len(end):\n #we know it\'s not transformable\n return False\n else:\n #if we\'ve made it this far the characters are valid\n #so we just now need to ensure the start index exceeds the end in the case of L\n #and the start preceeds end in the case of R\n if (start[p1] == "L" and p1 < p2) or (start[p1] == "R" and p1>p2):\n return False\n #if none of the above are triggered move on to the next character\n p1 +=1\n p2 +=1\n #if we make it out\n return True\n```\n```Java []\n//Java - O(n) less space\nclass Solution {\n public Solution() {}\n public boolean canTransform(String start, String end) {\n if (!start.replace("X", "").equals(end.replace("X", ""))) {\n return false;\n }\n\n int p1 = 0;\n int p2 = 0;\n\n while (p1 < start.length() && p2 < end.length()) {\n while (p1 < start.length() && start.charAt(p1) == \'X\') {\n p1 += 1;\n }\n\n while (p2 < end.length() && end.charAt(p2) == \'X\') {\n p2 += 1;\n }\n\n if (p1 == start.length() && p2 == end.length()) {\n return true;\n } else if (p1 == start.length() || p2 == end.length()) {\n return false;\n } else {\n if ((start.charAt(p1) == \'L\' && p1 < p2) || (start.charAt(p1) == \'R\' && p1 > p2)) {\n return false;\n }\n }\n p1 += 1;\n p2 += 1;\n }\n return true;\n }\n}\n```\n\n\n | 1 | 0 | ['Two Pointers', 'Depth-First Search', 'Breadth-First Search', 'Python', 'Java', 'Python3'] | 0 |
swap-adjacent-in-lr-string | Python3 simple solution: Beats 100% in speed | python3-simple-solution-beats-100-in-spe-alqs | Intuition\n Describe your first thoughts on how to solve this problem. \nWe keep track of possible Ls and Rs to keep track of, so that they can be accounted for | GodwynLai | NORMAL | 2023-09-15T13:27:50.125541+00:00 | 2023-09-15T13:27:50.125569+00:00 | 69 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe keep track of possible Ls and Rs to keep track of, so that they can be accounted for by future characters. This is kept track of in the lCount and rCount variables.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def canTransform(self, start: str, end: str) -> bool:\n lCount = 0\n rCount = 0\n n = len(start)\n for i in range(n):\n s = start[i]; e = end[i]\n if s == \'L\' and rCount > 0:\n return False\n if e == \'R\' and lCount > 0:\n return False\n if e == \'L\':\n lCount += 1\n if s == \'R\':\n rCount += 1\n if s == \'L\':\n if lCount > 0:\n lCount -= 1\n else:\n return False\n if e == \'R\':\n if rCount > 0:\n rCount -= 1\n else:\n return False\n return lCount == 0 and rCount == 0\n \n``` | 1 | 0 | ['Python3'] | 0 |
swap-adjacent-in-lr-string | Clean and concise C++ code based on Two pointers. One pass, O(N) time, O(1) space. | clean-and-concise-c-code-based-on-two-po-4n3n | Intuition\n Describe your first thoughts on how to solve this problem. \n(1)The relative order of \'X\' and \'R\' in both strings must be the same.\n\n(2-1)For | jianweike | NORMAL | 2023-05-17T18:04:20.453803+00:00 | 2023-05-17T18:04:20.453835+00:00 | 29 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n(1)The relative order of \'X\' and \'R\' in both strings must be the same.\n\n(2-1)For any \'L\', its position in "start" must to the right of that in "end", b/c \'L\' can only move to left. \n\n(2-2)For any \'R\', then its position in "start" must to the left of that in "end", b/c \'R\' can only move to right.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointers. One pass. If any of the above conditions are violated, return false. Otherwise, rethen true.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\nclass Solution {\npublic:\n \n bool canTransform(string start, string end) {\n //check if all relative order of R and L are the same\n int n = start.size();\n int i = 0, j = 0;\n while (i < n || j < n) {\n while (i < n && start[i] == \'X\') i++;\n while (j < n && end[j] == \'X\') j++;\n \n //here i, j piont to \'X\' or \'R\'\n //(1-1) If there are more \'X\' or \'R\' in one string than the other return false \n if (i == n && j != n) return false;\n if (i != n && j == n) return false;\n //(1-2) \'X\' and \'R\' in both strings must have the same relative orders\n\n if (start[i] != end[j]) return false;\n //(2-1) If the current char is \'L\', then its position in start must to the right of that in end, b/c \'L\' can only move to left.\n //If this is not the case, return false;\n if (start[i] == \'L\' && j > i) return false;\n //(2-2) If the current char is \'R\', then its position in start must to the left of that in end, b/c \'R\' can only move to right.\n //If this is not the case, return false;\n if (start[i] == \'R\' && j < i) return false;\n\n i++;\n j++;\n }\n\n return true;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
swap-adjacent-in-lr-string | C++ (4 ms) with explanation | c-4-ms-with-explanation-by-nandini2208-3c1t | \nbool canTransform(string start, string end) {\n int n=start.size();\n string s1="",s2="";\n\t\t//we take LR from 1st string and LR from 2nd stri | Nandini2208 | NORMAL | 2023-03-09T06:48:15.304926+00:00 | 2023-03-09T06:48:15.304960+00:00 | 310 | false | ```\nbool canTransform(string start, string end) {\n int n=start.size();\n string s1="",s2="";\n\t\t//we take LR from 1st string and LR from 2nd string if it is not equal it means\n\t\t//count of R & l in both the strings is not equal ex- start="X" end="L"\n\t\t//excluding the below checking we get wrong ans.\n for(int i=0;i<n;i++){\n if (start[i] != \'X\' ){\n s1+=start[i];\n }\n if(end[i] != \'X\'){\n s2+=end[i];\n }\n }\n if(s1 != s2){\n return false;\n }\n\t\t//then we check if both conditions are true then we return true.\n\t\t//1.if pos of \'L\' of first string is >= pos of \'L\' in second string \n\t\t//2.pos of \'R\' in first string is <= pos of \'R in second string \n\t\t\n for(int i=0,j=0;i<n && j<n;){\n if(start[i] == \'X\'){\n i++;\n continue;\n }\n else if(end[j] == \'X\'){\n j++;\n continue;\n }\n else if(start[i] == \'R\' && end[j] == \'R\' && i > j || \n\t\t\tstart[i] == \'L\' && end[j] == \'L\' && i < j ){\n return false;\n }\n i++;\n j++;\n }\n return true;\n }\n``` | 1 | 0 | ['Two Pointers', 'String', 'C++'] | 0 |
swap-adjacent-in-lr-string | Easy to understand JavaScript solution | easy-to-understand-javascript-solution-b-tsy8 | \tvar canTransform = function(start, end) {\n\t\tlet L = R = 0;\n\n\t\tfor (let index = 0; index < start.length; index++) {\n\t\t\tstart[index] === \'R\' && R++ | tzuyi0817 | NORMAL | 2022-09-11T06:59:02.660945+00:00 | 2022-09-11T07:01:33.873738+00:00 | 135 | false | \tvar canTransform = function(start, end) {\n\t\tlet L = R = 0;\n\n\t\tfor (let index = 0; index < start.length; index++) {\n\t\t\tstart[index] === \'R\' && R++;\n\t\t\tend[index] === \'L\' && L++;\n\t\t\tif (R > 0 && L > 0) return false;\n\n\t\t\tstart[index] === \'L\' && L--;\n\t\t\tend[index] === \'R\' && R--;\n\t\t\tif (L < 0 || R < 0) return false;\n\t\t}\n\t\treturn L === 0 && R === 0;\n\t}; | 1 | 0 | ['JavaScript'] | 1 |
swap-adjacent-in-lr-string | C++||Two Pointers||Easy to Understand | ctwo-pointerseasy-to-understand-by-retur-pouu | ```\nclass Solution {\npublic:\n bool canTransform(string start, string end)\n {\n int n=start.size();\n string s1,s2;\n for(int i=0; | return_7 | NORMAL | 2022-09-04T21:18:25.634776+00:00 | 2022-09-04T21:18:25.634814+00:00 | 253 | false | ```\nclass Solution {\npublic:\n bool canTransform(string start, string end)\n {\n int n=start.size();\n string s1,s2;\n for(int i=0;i<n;i++)\n {\n if(start[i]!=\'X\')\n s1+=start[i];\n }\n for(int i=0;i<n;i++)\n {\n if(end[i]!=\'X\')\n s2+=end[i];\n }\n if(s1!=s2)\n return false;\n for(int i=0,j=0;i<n&&j<n;)\n {\n while(i<n&&start[i]==\'X\')\n i++;\n while(j<n&&end[j]==\'X\')\n j++;\n if(start[i]==\'L\'&&i<j||start[i]==\'R\'&&i>j)\n return false;\n i++;\n j++;\n }\n return true;\n \n \n }\n};\n//if you like the solution plz upvote. | 1 | 0 | ['Two Pointers', 'C'] | 0 |
swap-adjacent-in-lr-string | Easy to Understand Java Solution | easy-to-understand-java-solution-by-star-6g0u | \n\n\nclass Solution {\n public boolean canTransform(String start, String end) {\n String startModified = start.replace("X", "");\n String endModified | starman214 | NORMAL | 2022-08-17T08:12:39.579586+00:00 | 2022-08-17T08:12:39.579614+00:00 | 187 | false | \n\n```\nclass Solution {\n public boolean canTransform(String start, String end) {\n String startModified = start.replace("X", "");\n String endModified = end.replace("X", "");\n if (!startModified.equals(endModified)) return false;\n int stR = 0, enR = 0, stL = 0, enL = 0;\n for (int i = 0; i < start.length(); i++) {\n if (start.charAt(i) == \'R\') stR++;\n if (end.charAt(i) == \'R\') enR++;\n if (start.charAt(i) == \'L\') stL++;\n if (end.charAt(i) == \'L\') enL++;\n if (enR > stR || stL > enL) return false;\n }\n return true;\n }\n}\n``` | 1 | 1 | ['Java'] | 1 |
swap-adjacent-in-lr-string | Explain failing test case | explain-failing-test-case-by-maximp4-5esx | Could someone please explain why this test case returns false?\n"LXXL"\n"XLLX"\n\nWe can only transform XL to LX, right?\nSo transform the 2nd XL of start\nand | maximp4 | NORMAL | 2022-08-04T03:24:44.872434+00:00 | 2022-08-04T04:04:07.340506+00:00 | 57 | false | Could someone please explain why this test case returns false?\n"LXXL"\n"XLLX"\n\nWe can only transform XL to LX, right?\nSo transform the 2nd XL of start\nand 1st XL of end.\n\n"LX -XL-" -> LX LX\n"-XL- LX" -> LX LX\n\nI must be trippin here\n\nEDIT: Nvm, I think I understand. We can only modifiy one string. | 1 | 0 | [] | 0 |
minimum-operations-to-make-all-array-elements-equal | [C++, Java, Python3] Prefix Sums + Binary Search | c-java-python3-prefix-sums-binary-search-u3kj | Intuition\n If there are j numbers in nums that are smaller than query[i], you need to find query[i] * j - sum(j numbers smaller than query[i]) to find incremen | tojuna | NORMAL | 2023-03-26T04:04:53.374792+00:00 | 2023-03-26T19:36:52.754367+00:00 | 13,376 | false | # Intuition\n* If there are `j` numbers in `nums` that are smaller than `query[i]`, you need to find `query[i] * j - sum(j numbers smaller than query[i])` to find increments required in `nums`\n* If there are `k` numbers in `nums` that are greater than `query[i]`, you need to find `sum(k numbers larger than query[i]) - query[i] * k` to find decrements required in `nums`\n* Sum of above two values is `ans[i]`\n\n\n\n# Approach\n* To find smaller numbers than `query[i]` we can sort the array and use binary search\n* Binary search over sorted `nums` to find index of `query[i]`\n* Then use prefix sums to find sum of number in smaller and larger segments\n* `prefix[n] - prefix[i]` is sum of numbers greater than or equal to `query[i]`\n* `prefix[i]` is sum of numbers smaller than `query[i]`\n* `query[i] * i - prefix[i]` is increments required\n* `prefix[n] - prefix[i] - query[i] * (n - i)` is decrements required\n* Total = `query[i] * i - prefix[i] + prefix[n] - prefix[i] - query[i] * (n - i)`\n* Can be simplified to `query[i] * (2 * i - n) + prefix[n] - 2 * prefix[i]`\n\n# Complexity\n- Time complexity: `O((n + m) * log(n))`\n\n- Space complexity: `O(n)`\n\n# Code\n**Python3**:\n```\ndef minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n ans, n, prefix = [], len(nums), [0] + list(accumulate(nums))\n for x in queries:\n i = bisect_left(nums, x)\n ans.append(x * (2 * i - n) + prefix[n] - 2 * prefix[i])\n return ans\n```\n```\ndef minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n prefix = [0] + list(accumulate(nums))\n for x in queries:\n i = bisect_left(nums, x)\n yield x * (2 * i - len(nums)) + prefix[-1] - 2 * prefix[i]\n```\n**C++**:\n```\nvector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n vector<long long> ans, prefix(n + 1);\n for (int i = 0; i < n; i++)\n prefix[i + 1] = prefix[i] + (long long) nums[i];\n for (int& x : queries) {\n int i = lower_bound(nums.begin(), nums.end(), x) - nums.begin();\n ans.push_back(1LL * x * (2 * i - n) + prefix[n] - 2 * prefix[i]);\n }\n return ans;\n}\n```\n\n**Java**:\n```\npublic List<Long> minOperations(int[] nums, int[] queries) {\n Arrays.sort(nums);\n List<Long> ans = new ArrayList<>();\n int n = nums.length;\n long[] prefix = new long[n + 1];\n for (int i = 1; i <= n; i++)\n prefix[i] = prefix[i - 1] + nums[i - 1];\n for (int x: queries) {\n int i = bisect_left(nums, x);\n ans.add(1L * x * (2 * i - n) + prefix[n] - 2 * prefix[i]);\n }\n return ans;\n}\nprivate int bisect_left(int[] nums, int x) {\n int lo = 0, hi = nums.length;\n while (lo < hi) {\n int mid = lo + (hi - lo) / 2;\n if (nums[mid] < x) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n```\n\n**Java using Arrays.binarySearch**:\n```\npublic List<Long> minOperations(int[] nums, int[] queries) {\n Arrays.sort(nums);\n List<Long> ans = new ArrayList<>();\n int n = nums.length;\n long[] prefix = new long[n + 1];\n for (int i = 1; i <= n; i++)\n prefix[i] = prefix[i - 1] + nums[i - 1];\n for (int x: queries) {\n int i = Arrays.binarySearch(nums, x);\n if (i < 0) i = -(i + 1); // convert negative index to insertion point\n ans.add(1L * x * (2 * i - n) + prefix[n] - 2 * prefix[i]);\n }\n return ans;\n}\n```\n*Good to know*: In Java, Arrays.binarySearch returns a negative index when the target element is not found in the array. The negative index returned is equal to -(insertion point) - 1, where the insertion point is the index at which the target element would be inserted into the array to maintain the sorted order.\n\nFor example, suppose we have an array arr = {1, 3, 5, 7, 9} and we want to search for the element 4. The Arrays.binarySearch(arr, 4) method would return -3. To convert this to the insertion point, we take the absolute value of the negative index and subtract 1: insertion point = |-(-3)| - 1 = 2.\n\nTherefore, the insertion point for the element 4 in the sorted array arr would be at index 2, which is the position where we would need to insert 4 to maintain the sorted order.\n\n**More binary search problems:**\n[Minimum Time to Repair Cars](https://leetcode.com/problems/minimum-time-to-repair-cars/solutions/3311975/c-java-python3-binary-search-1-liner/)\n[Minimum Time to Complete Trips](https://leetcode.com/problems/minimum-time-to-complete-trips/solutions/1802415/python3-java-c-binary-search-1-liner/)\n[Kth Missing Positive Number](https://leetcode.com/problems/kth-missing-positive-number/solutions/3262163/c-java-python3-1-line-ologn/)\n[Maximum Tastiness of Candy Basket](https://leetcode.com/problems/maximum-tastiness-of-candy-basket/solutions/2947983/c-java-python-binary-search-and-sorting/)\n[Number of Flowers in Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom/solutions/1976804/python3-2-lines-sort-and-binary-search/) | 113 | 1 | ['C++', 'Java', 'Python3'] | 16 |
minimum-operations-to-make-all-array-elements-equal | Image Explanation🏆- [Sorting + Prefix Sums + Binary Search] - Easy & Concise | image-explanation-sorting-prefix-sums-bi-ofy1 | Video Solution (Aryan Mittal)\n\nMinimum Operations to Make All Array Elements Equal by Aryan Mittal\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n# Code\n\n#defi | aryan_0077 | NORMAL | 2023-03-26T04:58:14.135830+00:00 | 2023-03-26T06:11:14.820435+00:00 | 5,278 | false | # Video Solution (`Aryan Mittal`)\n\n`Minimum Operations to Make All Array Elements Equal` by `Aryan Mittal`\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n# Code\n```\n#define ll long long int\n\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n \n int n = nums.size();\n sort(nums.begin(), nums.end());\n vector<ll> prefSum(n+1, 0);\n \n for(int i=0;i<n;i++){\n prefSum[i+1] = prefSum[i] + nums[i];\n }\n \n nums.insert(nums.begin(), 0);\n n++;\n \n vector<ll> ans;\n for(auto q : queries){\n ll lidx = lower_bound(nums.begin(), nums.end(), q) - nums.begin() - 1;\n ll uidx = upper_bound(nums.begin(), nums.end(), q) - nums.begin();\n \n ll val = q*lidx - (prefSum[lidx] - prefSum[0]);\n \n if(uidx!=n){\n val += (prefSum[n-1] - prefSum[uidx-1]) - q*(n-uidx);\n }\n \n ans.push_back(val);\n }\n \n return ans;\n }\n};\n``` | 40 | 1 | ['Binary Search', 'Sorting', 'Prefix Sum', 'C++'] | 3 |
minimum-operations-to-make-all-array-elements-equal | Prefix Sum | prefix-sum-by-votrubac-97lh | To make all elements equal, we need to increase elements smaller than query q, and decrease larger ones.\n \nWe sort our array first, so we can find index i | votrubac | NORMAL | 2023-03-26T04:14:08.326007+00:00 | 2023-03-26T05:08:51.089068+00:00 | 5,628 | false | To make all elements equal, we need to increase elements smaller than query `q`, and decrease larger ones.\n \nWe sort our array first, so we can find index `i` of first element larger than `q`.\n \nThen, we use the prefix sum array to get:\n- sum of smaller elements `ps[i]`.\n- sum of larger elements `ps[-1] - ps[i]`.\n \nThe number of operations is:\n- `q * i - ps[i]` for smaller elements.\n- `ps[-1] - ps[i] - q * (n - i)` for larger elements.\n \n**Python 3**\n```python\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n ps, n = [0] + list(accumulate(nums)), len(nums)\n splits = [(q, bisect_left(nums, q)) for q in queries]\n return [q * i - ps[i] + (ps[-1] - ps[i]) - q * (n - i) for q, i in splits] \n```\n**C++**\n```cpp\nvector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<long long> ps{0}, res;\n sort(begin(nums), end(nums));\n for (int n : nums)\n ps.push_back(ps.back() + n);\n for (long long q : queries) {\n int i = upper_bound(begin(nums), end(nums), q) - begin(nums);\n res.push_back(q * i - ps[i] + (ps.back() - ps[i]) - q * (nums.size() - i));\n }\n return res;\n}\n``` | 27 | 1 | ['C', 'Python3'] | 4 |
minimum-operations-to-make-all-array-elements-equal | Optimal Approach || Prefix Sum || Binary Search || Fully Explained Approach || O(N * log N) || C++ | optimal-approach-prefix-sum-binary-searc-qqjz | Approach\n- We want to make all the numbers equal to x.\n- There can be two types of numbers in the array ->\n 1. that are <= x (Type 1)\n 2. that are > x (Ty | ChaturvediParth | NORMAL | 2023-03-26T05:29:24.483434+00:00 | 2023-03-26T07:52:31.837728+00:00 | 1,090 | false | # Approach\n- We want to make all the numbers equal to $$x$$.\n- There can be two types of numbers in the array ->\n 1. that are $$<= x$$ (Type 1)\n 2. that are $$> x$$ (Type 2)\n- For numbers of **type 1** $$(<=x)$$, we would increase their value to make them equal to $$x$$.\n Suppose there are $$a$$ numbers that are $$<=x$$. The operations required to change all these numbers to $$x$$ will be $$a*x$$ $$-$$ $$(sum$$ $$of$$ $$all$$ $$these$$ $$numbers) $$ \n\n\n\n- For numbers of **type 2** $$(>x)$$, we would decrease their value to make them equal to $$x$$.\n Suppose there are $$b$$ numbers that are $$>x$$. The operations required to change all these numbers to $$x$$ will be $$(sum$$ $$of$$ $$all$$ $$these$$ $$numbers)$$ $$-$$ $$b*x$$ \n\n- **Note-** We can find sum in O(1) by using prefix array.\n\n- The total number of operations would be the sum of operations of both.\n\nFor example, nums = [3,1,6,8], queries = [1,5]\n\n\n\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\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(),nums.end());\n int n = nums.size();\n\n vector<ll> pre(n,0);\n pre[0]=1ll*nums[0];\n for(int i=1 ; i<n ; i++) pre[i]=pre[i-1]+1ll*nums[i];\n \n vector<ll> ans;\n for(int q:queries) {\n auto it = --upper_bound(nums.begin(),nums.end(),q);\n int i = it - nums.begin();\n \n long long x = (i<0) ? 0 : (1ll*(i+1)*q - pre[i]);\n long long y = (i<0) ? (pre[n-1] - 1ll*n*q) : (pre[n-1] - pre[i] - 1ll*(n-i-1)*q);\n \n ans.push_back(x+y);\n }\n return ans;\n }\n};\n```\n\n## Do let me know if you have any doubt in the solution\u2714.\n## Please upvote\uD83D\uDD3C if you liked the solution\n## \uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47\n\n\n\n\n\n\n | 16 | 0 | ['Binary Search', 'Prefix Sum', 'C++'] | 5 |
minimum-operations-to-make-all-array-elements-equal | [Java/Python 3] Sort, compute prefix sum then binary search. | javapython-3-sort-compute-prefix-sum-the-eogi | Within each query, for each number in nums, if it is less than q, we need to deduct it from q and get the number of the increment operations; if it is NO less | rock | NORMAL | 2023-03-26T04:10:11.512001+00:00 | 2023-03-28T14:11:53.946603+00:00 | 2,514 | false | Within each query, for each number in `nums`, if it is less than `q`, we need to deduct it from `q` and get the number of the increment operations; if it is NO less than `q`, we need to deduct `q` from the number to get the number of the decrement operations.\n\nTherfore, we can sort `nums`, then use prefix sum to compute the partial sum of the sorted `nums`. Use binary search to find the index of the `nums`, `idx`, to separate the less than part and NO less than part. With these information we can compute the total operations needed for a specific query `q`.\n\n**Note:**\n`nums[0 ... idx - 1] <= q, nums[idx ... n - 1] > q`\n`prefixSum[idx] = sum(nums[0 ... idx - 1])`\n`prefixSum[n] - prefixSum[idx] = sum(nums[idx ... n - 1])`\n`idx * q - prefixSum[idx]` : # of increment operations needed for `nums[0 ... idx - 1]`\n`prefixSum[n] - prefixSum[idx] - (n - idx) * q`: # of decrement operations needed for `nums[idx ... n - 1]`\n```java\n public List<Long> minOperations(int[] nums, int[] queries) {\n Arrays.sort(nums);\n int n = nums.length;\n long[] prefixSum = new long[n + 1];\n for (int i = 0; i < n; ++i) {\n prefixSum[i + 1] = prefixSum[i] + nums[i];\n }\n List<Long> ans = new ArrayList<>();\n for (int q : queries) {\n int idx = binarySearch(nums, q); // There are idx numbers in nums less than q.\n ans.add(1L * q * idx - prefixSum[idx] + prefixSum[n] - prefixSum[idx] - 1L * (n - idx) * q);\n }\n return ans;\n }\n private int binarySearch(int[] nums, int key) {\n int lo = 0, hi = nums.length;\n while (lo < hi) {\n int mid = lo + (hi - lo) / 2;\n if (key > nums[mid]) {\n lo = mid + 1;\n }else {\n hi = mid;\n }\n }\n return lo;\n }\n```\n```python\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n prefix_sum, n = [0], len(nums)\n for num in nums:\n prefix_sum.append(num + prefix_sum[-1])\n ans = []\n for q in queries:\n idx = bisect.bisect(nums, q) # There are idx numbers in nums less than q.\n ans.append(q * idx - prefix_sum[idx] + prefix_sum[-1] - prefix_sum[idx] - q * (n - idx)) \n return ans\n```\n\n**Analysis:**\n\nLet `n = nums.length, m = queries.length`:\nSort cost time `O(nlogn)`, each query cost time `O(logn)` and all quries cost `O(mlogn)`; `prefixSum` and sorting cost space `O(n)`, therefore\n\nTime: `O((m + n) * logn)`, space: `O(n)` (`O(m + n)` if including return space). | 15 | 0 | ['Java', 'Python3'] | 3 |
minimum-operations-to-make-all-array-elements-equal | Prefix Sum | Easy to Understand | Explained using Example | prefix-sum-easy-to-understand-explained-jzjxy | Intuition\nThe brute force approach would be to iterate through the queries array and for each query, iterate through the nums array to calculate the number of | nidhiii_ | NORMAL | 2023-03-26T07:18:24.257521+00:00 | 2023-03-26T07:27:40.081228+00:00 | 903 | false | # Intuition\nThe brute force approach would be to iterate through the queries array and for each query, iterate through the nums array to calculate the number of operations for each element. However, this solution\'s time complexity is O(n*m), which doesn\'t satisfy the given constraint.\n\nAnother way is to calculate the prefix sum array, and then for each query, calculate the number of operations using the prefix sum. See the example below to understand better.\n\n### Example\nFor nums=[3,1,6,4,8] and queries=[4,2]\n\nWe will first sort the nums array and then find the index where the element becomes greater than current element.\n<!-- Describe your approach to solving the problem. -->\n\n\n\n\n- prefix_sum= [0, 1, 4, 8, 14, 22]\n\n- left operations = (no. of elements smaller or equal to q) * q - sum of smaller or equal elements to q\n\n = idx*q - prefix_sum[idx]\n = 3 * 4 - 8 = 4\n- right operations = sum of elements greater than q - (no. of elements greater than q) * q \n\n = (prefix_sum[n] - prefix_sum[idx]) - (n-idx) * q\n = 14 - 2 * 4 = 6\n\n- total operations = left+right\n \n = 4+6 = 10\n\nNow, it\'s your turn to dry run the above approach for q=2. \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<long long> ans;\n int n=nums.size();\n sort(nums.begin(), nums.end());\n vector<long long> prefixSum(n+1);\n\n prefixSum[0] = 0;\n for (int i=1;i<=n;++i) {\n prefixSum[i] = prefixSum[i-1] + (nums[i-1]) ; // calculating the prefix sum\n }\n for (long long q:queries) {\n auto itr = upper_bound(nums.begin(), nums.end(),q); // find the iterator where nums[idx]>q\n int idx = itr-nums.begin(); \n long long left= idx*q-prefixSum[idx]; // number of operations for smaller elements\n long long right= (prefixSum[n]-prefixSum[idx])-(n-idx)*q; // number of operations for larger elements\n // cout<<left<<" "<<right<<endl;\n ans.push_back(left + right);\n }\n return ans;\n }\n};\n\n``` | 13 | 0 | ['Prefix Sum', 'C++'] | 1 |
minimum-operations-to-make-all-array-elements-equal | EASIEST SOLUTION EVER JUST BINARY SEARCH | easiest-solution-ever-just-binary-search-cmns | Intuition\nTRIPPY\'S CODING TECHNIQUE \nHERE I AM PRESENTING JAVA CODE USE VECTOR IN PLACE OF ARRAY FOR C++\n\n# Approach\nSS APROACH\nJUST SMILE AND SOLVE\n\n# | gurnainwadhwa | NORMAL | 2023-03-26T04:43:57.147659+00:00 | 2023-03-26T04:48:03.658055+00:00 | 4,213 | false | # Intuition\nTRIPPY\'S CODING TECHNIQUE \nHERE I AM PRESENTING JAVA CODE USE VECTOR IN PLACE OF ARRAY FOR C++\n\n# Approach\nSS APROACH\nJUST SMILE AND SOLVE\n\n# Complexity\nNOTHING COMPLEX\n\n# PLEASE UPVOTE\nPLEASE UPVOTE IF I HELPED YOU \nTHANK YOU\nLOVE FOR YOU BY TRIPPY \n\n# Code\n```\nclass Solution {\n public List<Long> minOperations(int[] nums, int[] queries) {\n \n int n = nums.length;\n int m = queries.length;\n \n List<Long> list = new ArrayList<>();\n \n Arrays.sort(nums);\n long[] arr1 = new long[n];\n long[] arr2 = new long[n];\n \n arr1[0] = nums[0];\n for(int i=1; i<n; i++){\n arr1[i] = arr1[i-1]+nums[i];\n }\n \n arr2[n-1] = nums[n-1];\n for(int i=n-2; i>=0; i--){\n arr2[i] = arr2[i+1]+nums[i];\n }\n \n for(int i : queries){\n long sum = 0l;\n int s=0; int e = n-1;\n \n while(s<=e){\n int mid = s + (e-s)/2;\n \n if(nums[mid] <= i){ s = mid+1; }\n else{ e = mid-1; }\n }\n \n sum += s>0 ?((long)i * (long)s) - arr1[s-1] :0;\n \n sum += s<n ?arr2[s] - ((long)(n-s) * (long)i) :0;\n \n list.add(sum);\n }\n \n return list;\n \n }\n}\n``` | 13 | 1 | ['Array', 'Binary Search', 'Prefix Sum', 'C++', 'Java'] | 2 |
minimum-operations-to-make-all-array-elements-equal | EASIEST SOLUTION EVER JUST BINARY SEARCH | easiest-solution-ever-just-binary-search-e8o8 | Intuition\nSIMPLY BINARY SEARCH \n\n# Approach\nSS APROACH\nJUST SMILE AND SOLVE\n\n# Complexity\nNOTHING COMPLEX\n\n# PLEASE UPVOTE\nPLEASE UPVOTE IF I HELPED | gurnainwadhwa | NORMAL | 2023-03-26T06:50:38.012393+00:00 | 2023-03-26T06:50:38.012426+00:00 | 958 | false | # Intuition\nSIMPLY BINARY SEARCH \n\n# Approach\nSS APROACH\nJUST SMILE AND SOLVE\n\n# Complexity\nNOTHING COMPLEX\n\n# PLEASE UPVOTE\nPLEASE UPVOTE IF I HELPED YOU \nTHANK YOU\nLOVE FOR YOU \n\n# Code\n```\nclass Solution {\n public List<Long> minOperations(int[] nums, int[] queries) {\n \n int n = nums.length;\n int m = queries.length;\n \n List<Long> list = new ArrayList<>();\n \n Arrays.sort(nums);\n long[] arr1 = new long[n];\n long[] arr2 = new long[n];\n \n arr1[0] = nums[0];\n for(int i=1; i<n; i++){\n arr1[i] = arr1[i-1]+nums[i];\n }\n \n arr2[n-1] = nums[n-1];\n for(int i=n-2; i>=0; i--){\n arr2[i] = arr2[i+1]+nums[i];\n }\n \n for(int i : queries){\n long sum = 0l;\n int s=0; int e = n-1;\n \n while(s<=e){\n int mid = s + (e-s)/2;\n \n if(nums[mid] <= i){ s = mid+1; }\n else{ e = mid-1; }\n }\n \n sum += s>0 ?((long)i * (long)s) - arr1[s-1] :0;\n \n sum += s<n ?arr2[s] - ((long)(n-s) * (long)i) :0;\n \n list.add(sum);\n }\n \n return list;\n \n }\n}\n``` | 9 | 0 | ['Java'] | 1 |
minimum-operations-to-make-all-array-elements-equal | C++✅| Binary Search | 4 liner |Easy to Understand🫡a | c-binary-search-4-liner-easy-to-understa-0ari | Intuition\n Describe your first thoughts on how to solve this problem. \nUse binary search to find the position of the element (which we want make all elements | Comrade-in-code | NORMAL | 2023-03-26T05:44:18.472342+00:00 | 2023-03-26T05:44:18.472383+00:00 | 2,558 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse binary search to find the position of the element (which we want make all elements to this element) in the sorted array. Then, store then answer using the formula in approach section\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n`ans.push_back(1LL * x * (2 * i - n) + prefix[n] - 2 * prefix[i]);`\n\n\n# Complexity\n- Time complexity: O(nlogn)\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```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n vector<long long> ans, prefix(n + 1);\n for (int i = 0; i < n; i++)\n prefix[i + 1] = prefix[i] + (long long) nums[i];\n for (int x : queries) {\n int i = lower_bound(nums.begin(), nums.end(), x) - nums.begin();\n ans.push_back(1LL * x * (2 * i - n) + prefix[n] - 2 * prefix[i]);\n }\n return ans;\n }\n};\n``` | 9 | 0 | ['Array', 'Binary Search', 'Prefix Sum', 'C++'] | 1 |
minimum-operations-to-make-all-array-elements-equal | Explained - Prefix sum & Lowerbound || Very simple & Easy to Understand Solution | explained-prefix-sum-lowerbound-very-sim-bzfu | Approach\n\n1. Evaluate prefix sum array\n2. find the index of lower bound of the query q\n3. Once we found the index, the lower half evaluation would take \n | kreakEmp | NORMAL | 2023-03-26T06:58:48.907942+00:00 | 2023-03-26T07:05:16.535363+00:00 | 1,826 | false | # Approach\n\n1. Evaluate prefix sum array\n2. find the index of lower bound of the query q\n3. Once we found the index, the lower half evaluation would take \n (ind * q - v[ind-1]) operations.\n4. Upper half array can be evaluated as equal which take \n (v.back() - v[ind-1]) - ( nums.size() - ind )*q;\n..............^ cur sum....................^sum when all equal\n# Code\n```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(), nums.end());\n vector<long long> ans, v;\n v.push_back(nums[0]);\n for(int i = 1; i < nums.size(); ++i) v.push_back(v.back() + (long long)nums[i]);\n for(auto q: queries){\n long long ind = (lower_bound(nums.begin(), nums.end(), q) - nums.begin());\n long long opLow= ind*(long long)q - ((ind > 0)?v[ind-1]:0); \n long long opHigh = (v.back() - ((ind > 0)?v[ind-1]:0 ) ) - ( (long long)nums.size() - ind )*(long long)q; \n ans.push_back(opLow + opHigh);\n }\n return ans;\n }\n};\n``` | 7 | 0 | ['C++'] | 1 |
minimum-operations-to-make-all-array-elements-equal | ✔💯DAY 361 || 100% || 0MS || EXPLAINED || DRY RUN || MEME | day-361-100-0ms-explained-dry-run-meme-b-ohgf | Please Upvote as it really motivates me\n# Intuition\n Describe your first thoughts on how to solve this problem. \n##### \u2022\tThe intuition behind this code | ManojKumarPatnaik | NORMAL | 2023-03-27T13:20:46.887452+00:00 | 2023-04-02T12:04:48.482471+00:00 | 655 | false | # Please Upvote as it really motivates me\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### \u2022\tThe intuition behind this code is to first sort the input array of numbers and the array of queries. Then, for each query, we calculate the prefix sum of all numbers in the input array that are less than the current query. We use this prefix sum to calculate the number of operations required to make all numbers in the input array equal to the query.\n##### \u2022\tTo do this, we first calculate the total sum of all numbers in the input array. Then, we subtract twice the prefix sum from this total sum, since we need to add q to all numbers less than q and subtract q from all numbers greater than q. The factor of 2 is because we need to perform both additions and subtractions. Finally, we add q times the number of elements less than q that we have already processed, since we have already added q to these elements.\n##### \u2022\tThis approach allows us to efficiently calculate the answer for each query in O(n log n) time, where n is the length of the input array.\n\n\n\n# Explain\n<!-- Describe your approach to solving the problem. -->\n\n##### \u2022\tThe code is implementing the following approach:\n\n##### \u2022\tSort the input array of numbers in ascending order using the sort() function from the STL library.\n##### \u2022\tsort(nums.begin(), nums.end());\n##### \u2022\tCreate a vector of pairs called aug to store the queries and their respective indices. For each query in the input array queries, create a pair with the query value and its index and add it to the aug vector.\n##### \u2022\tvector<pair<int, int>> aug;\n##### \u2022\tfor (int i = 0; i < queries.size(); ++i) {\n##### \u2022\taug.emplace_back(queries[i], i);\n##### \u2022\t}\n##### \u2022\tSort the aug vector of pairs in increasing order of query value.\n##### \u2022\tsort(aug.begin(), aug.end());\n##### \u2022\tCreate a new vector called ans to store the answers for each query. The size of ans is the same as the size of queries.\n##### \u2022\tvector<long long> ans(queries.size());\n##### \u2022\tCalculate the total sum of all numbers in the input array nums using the accumulate() function from the STL library.\n##### \u2022\tlong long total = accumulate(nums.begin(), nums.end(), 0ll);\n##### \u2022\tInitialize a variable called prefix to 0. This variable will be used to calculate the prefix sum of all numbers in nums that are less than the current query.\n##### \u2022\tlong long prefix = 0;\n##### \u2022\tInitialize a variable called k to 0. This variable will be used to keep track of the number of elements in nums that are less than the current query.\n##### \u2022\tint k = 0;\n##### \u2022\tLoop through each pair in the aug vector. For each pair, calculate the number of operations required to make all numbers in nums equal to the current query.\n##### \u2022\tfor (auto& [q, i] : aug) {\n##### \u2022\t// Calculate prefix sum of all numbers less than q\n##### \u2022\twhile (k < nums.size() && nums[k] < q)\no\tprefix += nums[k++];\n##### \u2022\t// Calculate answer for current query\n##### \u2022\tans[i] = total - 2*prefix + (long long) q*(2*k - nums.size());\n##### \u2022\t}\n##### \u2022\tReturn the ans vector, which contains the answers for all queries.\n##### \u2022\treturn ans;\n##### \u2022\tOverall, the approach involves sorting the input array and the queries, and then iterating through the queries and calculating the prefix sum of all numbers less than the current query. This prefix sum is then used to calculate the number of operations required to make all numbers in the input array equal to the current query.\n\n\n\n\n# Code\n```c++ []\nvector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(), nums.end());\n vector<pair<int, int>> aug;\n for (int i = 0; i < queries.size(); ++i) {\n aug.emplace_back(queries[i], i);\n }\n sort(aug.begin(), aug.end());\n vector<long long> ans(queries.size());\n long long total = accumulate(nums.begin(), nums.end(), 0ll);\n long long prefix = 0;\n int k = 0;\n for (auto& [q, i] : aug) {\n while (k < nums.size() && nums[k] < q) {\n prefix += nums[k];\n k++;\n }\n ans[i] = total - 2 * prefix + (long long) q * (2 * k - nums.size());\n }\n return ans;\n}\n```\n```python []\ndef minOperations(self,nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n aug = [(q, i) for i, q in enumerate(queries)]\n aug.sort()\n total = sum(nums)\n prefix = 0\n k = 0\n ans = [0] * len(queries)\n for q, i in aug:\n while k < len(nums) and nums[k] < q:\n prefix += nums[k]\n k += 1\n ans[i] = total - 2 * prefix + q * (2 * k - len(nums))\n return ans\n```\n```java []\npublic List<Long> minOperations(int[] nums, int[] queries) {\n int n = nums.length,m = queries.length;\n \n Arrays.sort(nums);\n \n long[] psum = new long[n + 1];\n for(int i = 0;i < n;i++) psum[i + 1] = psum[i] + nums[i];\n \n List<Long> ans = new ArrayList<>();\n \n for(int i = 0;i < m;i++){\n \n int si = 0,ei = n - 1,idx = 0;\n while(si <= ei){\n int mid = si + (ei - si) / 2;\n \n if(nums[mid] <= queries[i]){\n idx = mid + 1;\n si = mid + 1;\n }else{\n idx = mid;\n ei = mid - 1;\n }\n }\n \n long left = (1L * queries[i] * idx) - psum[si]; \n long right = (psum[n] - psum[idx]) - (1L * queries[i] * (n - idx));\n \n ans.add(left + right);\n }\n return ans;\n }\n# explaination\n\n\n##### \u2022\tThe minOperations function takes two integer arrays as input, nums and queries, and returns a list of long integers as output. For each query in the queries array, the function computes the minimum number of operations required to make all the elements in the nums array greater than or equal to the query value.\n\n##### \u2022\tFirst, the function initializes two variables, n and m, to the lengths of the nums and queries arrays respectively. It then sorts the nums array in ascending order using Arrays.sort().\n\n##### \u2022\tNext, the function initializes a new array called psum of length n + 1. It then populates the psum array with prefix sums of the nums array using a for loop. Specifically, it sets psum[0] to 0, and for each index i from 0 to n - 1, it sets psum[i + 1] to psum[i] + nums[i].\n\n##### \u2022\tThe function then initializes an empty list called ans to store the results of each query.\n\n##### \u2022\tFor each query in the queries array, the function performs a binary search on the nums array to find the index of the first element that is greater than the query value. It initializes three variables, si, ei, and idx, to 0, n - 1, and 0 respectively. It then enters a while loop that continues as long as si is less than or equal to ei. In each iteration of the loop, it calculates the midpoint of the current search range using (si + ei) / 2. If the midpoint element is less than or equal to the query value, it updates idx to the midpoint index plus 1, and sets si to the midpoint index plus 1. Otherwise, it updates idx to the midpoint index, and sets ei to the midpoint index minus 1. Once the loop exits, idx will contain the index\n\n\n\n```\nHERE https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/solutions/3347750/100-0ms-explained-dry-run-meme/\n\n# DRY RUN 1\nFirst, we sort the nums vector in ascending order: nums = [1, 3, 6, 8]. Next, we create a new vector called aug, which will store pairs of each query and its index in the queries vector. In this case, aug = [(1, 0), (5, 1)]. We sort the aug vector in ascending order based on the query value: aug = [(1, 0), (5, 1)]. We create a new vector called ans to store the results of each query. We calculate the total sum of the nums vector using the accumulate function: total = 18. We initialize the prefix variable to 0. We set k to 0. We loop through each pair in the aug vector. For the first pair, q = 1 and i = 0. For the second pair, q = 5 and i = 1. For each pair, we loop through the nums vector while k < nums.size() and nums[k] < q. In this case, k starts at 0 and nums[k] = 1, which is less than q = 1, so we do not enter the loop. For the second pair, k is still 0 and nums[k] = 1, which is less than q = 5, so we enter the loop. We add nums[k] = 1 to prefix, increment k to 1, and check if nums[k] < q. Since nums[k] = 3 is less than q = 5, we add nums[k] = 3 to prefix, increment k to 2, and check again. Since nums[k] = 6 is not less than q = 5, we exit the loop. For the first pair, we calculate ans[i] = total - 2prefix + (long long) q(2k - nums.size()) = 18 - 20 + (long long) 1*(20 - 4) = 14. For the second pair, we calculate ans[i] = total - 2prefix + (long long) q*(2k - nums.size()) = 18 - 24 + (long long) 5*(2*2 - 4) = 10. We return the ans vector: [14, 10].\n\n# dry run 2\n\nFirst, we sort the nums vector in ascending order: nums = [2, 3, 6, 9]. Next, we create a new vector called aug, which will store pairs of each query and its index in the queries vector. In this case, aug = [(10, 0)]. We sort the aug vector in ascending order based on the query value: aug = [(10, 0)]. We create a new vector called ans to store the results of each query. We calculate the total sum of the nums vector using the accumulate function: total = 20. We initialize the prefix variable to 0. We set k to 0. We loop through each pair in the aug vector. For the only pair, q = 10 and i = 0. For the pair, we loop through the nums vector while k < nums.size() and nums[k] < q. In this case, k starts at 0 and nums[k] = 2, which is less than q = 10, so we enter the loop. We add nums[k] = 2 to prefix, increment k to 1, and check if nums[k] < q. Since nums[k] = 3 is less than q = 10, we add nums[k] = 3 to prefix, increment k to 2, and check again. Since nums[k] = 6 is less than q = 10, we add nums[k] = 6 to prefix, increment k to 3, and check again. Since nums[k] = 9 is not less than q = 10, we exit the loop. For the pair, we calculate ans[i] = total - 2 * prefix + (long long) q * (2 * k - nums.size()) = 20 - 2 * (2 + 3 + 6) + (long long) 10 * (2 * 4 - 4) = 20. We return the ans vector: [20].\n\n# Complexity\n# Time complexity: \nO(nlogn + qlogq), where n is the length of the nums vector and q is the length of the queries vector. The sort function has a time complexity of O(nlogn) for sorting the nums vector and O(qlogq) for sorting the aug vector. The while loop inside the for loop has a time complexity of O(n) in the worst case, but since k is incremented at each iteration, the total time complexity of the while loop is O(n) for all iterations of the for loop. Therefore, the overall time complexity of the code is dominated by the sort function, which has a time complexity of O(nlogn + qlogq).\n\n# Space complexity: \nO(q), where q is the length of the queries vector. The aug vector has a space complexity of O(q) and the ans vector has a space complexity of O(q), so the total space complexity of the code is O(q).\n\n\n\n | 6 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 2 |
minimum-operations-to-make-all-array-elements-equal | Easy c++ solution using binary search and prefix sum. | easy-c-solution-using-binary-search-and-u19f5 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can solve each query in log n time using binary search (upper_bound) and prefix sum | aniketrajput25 | NORMAL | 2023-03-26T05:48:42.714001+00:00 | 2023-03-26T05:48:42.714042+00:00 | 1,180 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve each query in log n time using binary search (upper_bound) and prefix sum in sorted array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array.\n2. Calculate prefix sum array of size n+1, and calcculate sum of all element along with that.\n3. Find upper bound for each query. check if query is greater then maximum element then push ans as n*query - total sum, if query is smaller then smallest element of array then push ans as total sum- n*query.\n4. If above two condition not satify then we will use upper bound to divide the array into two parts, in first part we will find sum of first part using index of upper bound and prefix sum and subtract first part sum with (ind)*query where ind is index of upper bound. and in second part subtract (n-ind)*query from sum of seccond part. Add both part and push into ans.\n5. return the ans\n\n# Complexity\n- Time complexity: O(N*LOGN)\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```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<long long> ans,pre;\n sort(nums.begin(),nums.end());\n long long sum=0;\n pre.push_back(0);\n for(int i=0;i<nums.size();i++)\n {\n sum+=nums[i];\n pre.push_back(sum);\n }\n int n=nums.size();\n for(int i=0;i<queries.size();i++)\n {\n int c=queries[i];\n auto b=upper_bound(nums.begin(),nums.end(),c);\n if(c>=nums[n-1])\n {\n ans.push_back((long long)n*(long long)c - sum);\n }\n else if(c<=nums[0])\n {\n ans.push_back(sum-(long long)n*(long long)c);\n }\n else\n {\n int ind=b-nums.begin();\n long long res=abs((sum-pre[ind])-(long long)(n-ind)*(long long)c);\n res+=abs((long long)ind*(long long)c -pre[ind]);\n ans.push_back(res);\n }\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | C++ Easy Solution || Beats 100% || Binary Search Approach || 🔥🔥 | c-easy-solution-beats-100-binary-search-f5vdz | 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 | abhi_pandit_18 | NORMAL | 2023-07-16T19:49:15.369594+00:00 | 2023-07-16T19:49:15.369613+00:00 | 54 | false | # 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 {\npublic:\n int f(vector<int> &nums,int temp)\n {\n int n = nums.size();\n int ans=-1;\n int l=0,h=n-1;\n while(l<=h)\n {\n int m = (l+h)/2;\n if(nums[m]>=temp)\n {\n ans=m;\n h=m-1;\n }\n else\n l=m+1;\n }\n return ans;\n }\n\n vector<long long> minOperations(vector<int>& nums, vector<int>& q) {\n int n = nums.size();\n int m = q.size();\n vector<long long> v;\n sort(nums.begin(),nums.end());\n vector<long long> p(n+1, 0);\n for(int i=0;i<n;i++)\n {\n p[i+1] = p[i]+nums[i];\n }\n for(auto it:q)\n {\n if(it<nums[0] || it>nums[n-1])\n {\n v.push_back(abs(p[n]-(it*1LL*n)));\n continue;\n }\n int temp = f(nums,it);\n long long sum = abs(p[temp]-(temp*1LL*it))+abs(p[n]-p[temp]-((n-temp)*1LL*it));\n v.push_back(sum);\n }\n return v;\n }\n};\n``` | 4 | 0 | ['Binary Search', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | C++ || BINARY SEARCH || EASY TO UDERSTAND | c-binary-search-easy-to-uderstand-by-gan-xd91 | Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\n#define ll long long \nclass Solution {\npublic:\n vector<long long> minOp | ganeshkumawat8740 | NORMAL | 2023-05-09T04:41:48.031522+00:00 | 2023-05-09T04:42:50.863240+00:00 | 1,195 | false | # Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n#define ll long long \nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<ll> v;//ans array\n vector<ll> ps;//previous sum array\n sort(nums.begin(),nums.end());\n ll sum = 0,s;\n for(auto &i: nums){sum += i;ps.push_back(sum);}\n int x = 0,n=nums.size();\n for(auto &i: queries){\n x = upper_bound(nums.begin(),nums.end(),i)-nums.begin();//binary search\n if(x==0){\n v.push_back((sum-n*1LL*i));\n } else if(x==n){\n v.push_back((x*1LL*i - ps[x-1]));\n }else{\n v.push_back((x*1LL*i - ps[x-1]) + (sum-ps[x-1]-i*1LL*(n-x)));\n }\n }\n return v;\n }\n};\n``` | 4 | 0 | ['Array', 'Binary Search', 'Sorting', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | Sort + Prefix Sum + Binary Search | sort-prefix-sum-binary-search-by-fllght-n8ww | Java\n\npublic List<Long> minOperations(int[] nums, int[] queries) {\n List<Long> result = new ArrayList<>();\n Arrays.sort(nums);\n\n long[] prefixSum | FLlGHT | NORMAL | 2023-04-07T07:25:20.753800+00:00 | 2023-04-07T07:25:20.753841+00:00 | 170 | false | # Java\n```\npublic List<Long> minOperations(int[] nums, int[] queries) {\n List<Long> result = new ArrayList<>();\n Arrays.sort(nums);\n\n long[] prefixSum = new long[nums.length];\n for (int i = 0; i < nums.length; ++i) {\n prefixSum[i] = (i > 0 ? prefixSum[i - 1] : 0) + nums[i];\n }\n\n for (int query : queries) {\n int index = firstIndexOfMoreOrEqual(nums, query);\n\n long leftSum = index == 0 ? 0 : prefixSum[index - 1], leftCount = index;\n long rightSum = prefixSum[prefixSum.length - 1] - leftSum, rightCount = nums.length - leftCount;\n\n long leftDifference = query * leftCount - leftSum;\n long rightDifference = rightSum - query * rightCount;\n\n result.add(leftDifference + rightDifference);\n }\n\n return result;\n }\n\n private int firstIndexOfMoreOrEqual(int[] nums, int value) {\n int left = 0, right = nums.length;\n\n while (left < right) {\n int middle = left + (right - left) / 2;\n\n if (nums[middle] < value)\n left = middle + 1;\n else\n right = middle;\n }\n\n return left;\n }\n```\n\n# C++\n```\n\npublic:\n vector<long long> minOperations(vector<int> &nums, vector<int> &queries) {\n vector<long long> result;\n sort(nums.begin(), nums.end());\n\n vector<long long> prefixSum(nums.size());\n for (int i = 0; i < nums.size(); ++i) {\n prefixSum[i] = (i > 0 ? prefixSum[i - 1] : 0) + nums[i];\n }\n\n for (int query: queries) {\n int index = firstIndexOfMoreOrEqual(nums, query);\n\n long leftSum = index == 0 ? 0 : prefixSum[index - 1], leftCount = index;\n long rightSum = prefixSum[prefixSum.size() - 1] - leftSum, rightCount = nums.size() - leftCount;\n\n long leftDifference = query * leftCount - leftSum;\n long rightDifference = rightSum - query * rightCount;\n\n result.push_back(leftDifference + rightDifference);\n }\n\n return result;\n }\n\nprivate:\n int firstIndexOfMoreOrEqual(vector<int> &nums, int value) {\n int left = 0, right = nums.size();\n\n while (left < right) {\n int middle = left + (right - left) / 2;\n\n if (nums[middle] < value)\n left = middle + 1;\n else\n right = middle;\n }\n\n return left;\n }\n``` | 4 | 0 | ['C++', 'Java'] | 0 |
minimum-operations-to-make-all-array-elements-equal | JAVA SOLUTION 100% FASTER || BinarySearch | java-solution-100-faster-binarysearch-by-uucj | Search for all the numbers smaller than the query element the sum total should be number of element*query if sum of all smaller elements is less then we need t | akash0228 | NORMAL | 2023-03-26T04:56:21.617246+00:00 | 2023-03-26T05:01:32.300503+00:00 | 906 | false | **Search for all the numbers smaller than the query element the sum total should be number of element*query if sum of all smaller elements is less then we need to add the difference number of time And in the case of larger element we need to subtract the Sum total from sum of larger elements!!!**\n```\nclass Solution {\n public List<Long> minOperations(int[] nums, int[] queries) {\n int n=nums.length;\n Arrays.sort(nums);\n long prefix[]=new long[n];\n ArrayList<Long> list=new ArrayList<>();\n prefix[0]=nums[0];\n for(int i=1;i<nums.length;i++){\n prefix[i]=prefix[i-1]+nums[i];\n }\n for(int i=0;i<queries.length;i++){\n int l=0;\n int r=n-1;\n long max=(long)queries[i]*n;\n while(l<r){\n int mid=(l+r)>>1;\n if(nums[mid]<queries[i]){\n l=mid+1;\n }\n else{\n r=mid;\n }\n }\n\t\t\t//no smaller element\n if(l<=0){\n long diff=(long)Math.abs(prefix[n-1]-max);\n list.add(diff);\n continue;\n }\n\t\t\t//all smaller\n if(l>=n-1){\n long diff=(long)Math.abs(max-prefix[n-1]);\n list.add(diff);\n continue;\n }\n else{\n int lowerHalfEnd=l;\n if(nums[l]!=queries[i]){\n lowerHalfEnd=l-1;\n }\n long smallerMax=(long)queries[i]*(lowerHalfEnd+1);\n long LargerMax=(long)queries[i]*(n-lowerHalfEnd-1);\n long total=(long)(smallerMax-prefix[lowerHalfEnd])+(prefix[n-1]-prefix[lowerHalfEnd]-LargerMax);\n list.add(total);\n }\n }\n return list; \n }\n}\n``` | 4 | 0 | ['Binary Search', 'Sorting', 'Prefix Sum', 'Java'] | 0 |
minimum-operations-to-make-all-array-elements-equal | Beats 98% || Simple C++ Explanation || Binary Search || Prefix Sum | beats-98-simple-c-explanation-binary-sea-5e6m | Intuition\nThe code aims to efficiently find the minimum cost of operations on a sorted array for given queries. The intuition involves traversing the queries v | king0203 | NORMAL | 2023-12-17T18:00:24.465604+00:00 | 2023-12-17T18:00:24.465631+00:00 | 24 | false | # Intuition\nThe code aims to efficiently find the minimum cost of operations on a sorted array for given queries. The intuition involves traversing the queries vector once and recognizing the need for a logarithmic time solution. Hence, the idea of using binary search is considered. \n\n# Approach\n In the approach, the array is sorted, and the prefix sum is calculated. For each query, binary search is utilized to find the position of the target value in the array. The cost is then calculated as follows:\n- Count of elements before the target multiplied by the target\n (target * (count of elements before target) - sum of elements before target)\n- Plus the sum of elements after the target\n (sum of all elements - sum of elements before target - (count of elements after target) * target)\nThis process is repeated for each query, and the results are stored in a vector. \n\n\n\n# Complexity\n- Time complexity:\nThe time complexity is O(m * log(n)), where m is the number of queries and n is the size of the array, due to the logarithmic binary search operation. \n\n- Space complexity:\nThe space complexity is O(n), where n is the size of the array, mainly due to storing the sorted array and the prefix sum vector. \n\n\n# Code\n```\ntypedef long long ll;\nclass Solution {\npublic:\n // find cost using binary search and prefix sum in log(n) time complexity\n ll findCost(vector<int>& nums, vector<ll> &pre, ll target) {\n ll n = nums.size();\n ll cost = 0, sum = pre[n-1];\n\n // edge cases\n if(target < nums[0])\n return sum - target*n;\n if(target > nums[n-1])\n return target*n - sum;\n \n // binary search\n ll left = 0, right = n-1, i = 0;\n while(left <= right) {\n ll mid = (left + right) /2;\n if(nums[mid] <= target) {\n i = mid;\n left = mid + 1;\n }\n else\n right = mid-1;\n }\n\n cost = (target * (i + 1) - pre[i]) + (sum - pre[i]) - (n - i - 1) * target;\n\n return cost;\n }\n\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n sort(nums.begin(), nums.end());\n int n=nums.size();\n int m=queries.size();\n vector<ll> res(m);\n\n vector<ll> pre(n, 0); \n // calculate prefix sum\n pre[0] = nums[0];\n for(int i = 1; i < n; i++) {\n pre[i] = pre[i-1] + nums[i];\n }\n\n for(int i=0 ; i< m ; i++){\n ll temp=queries[i];\n ll ans=0;\n ans+=findCost(nums,pre,temp);\n res[i]=ans;\n }\n return res;\n }\n};\n```\n\n | 3 | 0 | ['Binary Search', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | C++ | c-by-deepak_2311-8jco | 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 | godmode_2311 | NORMAL | 2023-04-17T20:19:04.691665+00:00 | 2023-04-17T20:19:04.691702+00:00 | 134 | false | # 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```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n \n int n = nums.size();\n int q = queries.size();\n\n // SORT THE ARRAY\n sort(nums.begin(),nums.end());\n\n // CALCULATE PREFIX OF NUMS \n vector<long long>prefix(n,0);\n prefix[0] = nums[0];\n for(int i=1;i<n;i++) prefix[i] = prefix[i-1] + nums[i];\n \n // USE LONG LONG FOR AVOID RUNTIME\n vector<long long>ans;\n\n long long increment = 0 , decrement = 0;\n long long value = 0;\n\n // processing each query \n for(auto q : queries){\n \n // binary search\n int lo = 0 , hi = n-1;\n int mid; value = q;\n\n // find position of current query element in sorted nums\n while(lo <= hi){\n\n mid = lo + (hi - lo)/2;\n\n if(nums[mid] <= value) lo = mid + 1;\n else hi = mid - 1;\n \n }\n\n // reset increment & decrement\n increment = 0 , decrement = 0;\n\n // get length of less than current query element which are need to increment\n if(lo > 0) increment = abs((value * lo) - prefix[lo-1]);\n\n // get length of greater than current query element which are need to decrement\n if(lo == 0) decrement = abs((value*n) - prefix[n-1]);\n else decrement = abs((value * (n-lo)) - (prefix[n-1] - prefix[lo-1]));\n\n // store answerr for current query\n ans.push_back(increment + decrement);\n }\n \n // return result\n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | SORTING + UPPERBOUND + PREFIX SUM | sorting-upperbound-prefix-sum-by-_kitish-whyi | Intuition\n Describe your first thoughts on how to solve this problem. \nSuppose we have a query \'a\' then we have to know the number of elements which is grea | _kitish | NORMAL | 2023-04-05T20:45:37.946186+00:00 | 2023-06-01T18:04:04.509984+00:00 | 111 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSuppose we have a query \'a\' then we have to know the number of elements which is greater than \'a\' and less than or equal to \'a\' in nums array and their sum Let\'s if \'b\' number is greater and \'c\' number is less than or equal to in nums array. And their sum is sa and sb. Then, if we change the all elements to \'a\' then their sum would be \'a\' * \'b\' and \'a\' * \'c\'. Then, simply add their difference value and store them.\n\nHow to find how many numbers are greater than particular query \'q\' in nums array ? \n-> Here, Comes sorting. Sort the array and use binary search or STL upperbound and find their index.\n\nHow to find the sum of numbers are greater than particular query \'q\' in nums array ?\n-> Use the concept of prefix sum\n\n# Complexity\n- Time complexity: $$O(m * log(n))$$\n- m = length of queries array\n- n = length of nums array\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n- n = length of nums array\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& Q) {\n int m = size(Q), n = size(nums);\n sort(begin(nums),end(nums));\n vector<long long> ans, pf(n+1);\n \n for(int i=1; i<=n; ++i)\n pf[i] = pf[i-1] + 0ll + nums[i-1];\n\n for(int&q: Q){\n int idx = upper_bound(begin(nums),end(nums),q) - begin(nums);\n long long bigger = pf[n] - pf[idx], smaller = pf[idx];\n long long bgreq = (n-idx)*1ll*q, smreq = idx*1ll*q;\n long long e = bigger-bgreq + smreq-smaller;\n ans.push_back(e);\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'Prefix Sum', 'C++'] | 1 |
minimum-operations-to-make-all-array-elements-equal | C++||Most Easy Solution Using Prefix & Suffix Sum and Binary Search | cmost-easy-solution-using-prefix-suffix-odiiv | \ntypedef long long ll;\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n ll m=nums.size();\n | Arko-816 | NORMAL | 2023-03-26T16:55:22.120352+00:00 | 2023-03-26T17:06:55.641315+00:00 | 1,922 | false | ```\ntypedef long long ll;\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n ll m=nums.size();\n sort(nums.begin(),nums.end());\n vector<ll> suff(m,0);\n vector<ll>pref(m,0);\n vector<ll> ans;\n suff[m-1]=nums[m-1];\n pref[0]=nums[0];\n for(int i=m-2;i>=0;i--)\n {\n suff[i]=nums[i]+suff[i+1];// calculating the suffix sum\n }\n for(int i=1;i<m;i++)\n pref[i]=pref[i-1]+nums[i];// calculating the prefix sum\n for(int i=0;i<queries.size();i++)\n {\n ll ind=lower_bound(nums.begin(),nums.end(),queries[i])-nums.begin();\n ll inl=ind*queries[i]*1LL; // no of elements to left of index is ind\n ll rl=(m-ind)*queries[i]*1LL;//no of elements to right of index is m-ind where m is no of elements present in array\n\t\t\t //multiplying with queries[i] gives the sum required\n ll sum=0;\n // cout<<ind<<endl;\n //cout<<inl<<" "<<rl<<endl;\n if(ind==m)\n {\n ans.push_back(inl-pref[m-1]);\n continue;\n }\n if(ind-1>=0)\n {\n sum+=(inl-pref[ind-1]);\n }\n sum+=(suff[ind]-rl);\n ans.push_back(sum);\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Prefix Sum'] | 1 |
minimum-operations-to-make-all-array-elements-equal | PREFIX & SUFFIX SUM || BINARY SEARCH || C++ | prefix-suffix-sum-binary-search-c-by-yas-9hsw | \nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<long long int> v;\n sort(nums | yash___sharma_ | NORMAL | 2023-03-26T06:14:46.029701+00:00 | 2023-03-26T12:22:19.762383+00:00 | 790 | false | ````\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n vector<long long int> v;\n sort(nums.begin(),nums.end());\n vector<long long int> l(nums.size()),r(nums.size());\n l[0] = nums[0];\n r[nums.size()-1] = nums[nums.size()-1];\n for(int i = 1; i < nums.size(); i++){\n l[i] += nums[i]+l[i-1];\n }\n for(int i = nums.size()-2; i>=0; i--){\n r[i] += nums[i]+r[i+1];\n }\n for(int i = 0; i < queries.size(); i++){\n int a = 0, b = nums.size()-1, mid,k=nums.size();\n while(a<=b){\n mid = (b-a)/2+a;\n if(nums[mid]>=queries[i]){\n k = mid;\n b = mid-1;\n }else{\n a= mid+1;\n }\n }\n long long int aa = 0;\n if(k-1>=0){\n aa += k*1LL*queries[i]-l[k-1];\n }if(k<nums.size()){\n aa += r[k]-(nums.size()-k)*1LL*queries[i];\n }\n v.push_back(aa);\n }\n return v;\n }\n};\n```` | 3 | 0 | ['Binary Search', 'C', 'Sorting', 'Binary Tree', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | No Binary search, just use sweep line and prefix sum | no-binary-search-just-use-sweep-line-and-h20l | Intuition\nFor a given query x, answer will be sum of left answer and right answer.\nleft answer = x * number of smaller values than x - sum of smaller values t | dush1729 | NORMAL | 2023-03-26T06:08:56.168786+00:00 | 2023-03-26T06:10:28.954386+00:00 | 588 | false | # Intuition\nFor a given query `x`, answer will be sum of `left answer` and `right answer`.\n`left answer` = `x` * `number of smaller values than x` - `sum of smaller values than x`\n`right answer` = `sum of bigger values than x` - `x` * `number of bigger values than x`\n\n\n# Approach\nSort both array and queries.\nYou can find number of smaller(`ln`) and larger values(`rn`) using sweep line.\nAnd find sum of smaller(`ls`) and larger values(`rs`) using prefix sum + sweep line.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`O(nlogn + mlogm + n + m)`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(n)` for prefix sum\n\n# Code\n```\nclass Solution {\npublic:\n\tvector<long long> minOperations(vector<int>& a, vector<int>& queries) {\n\t\tsort(a.begin(), a.end());\n\t\tvector dp(1, 0ll);\n\t\tfor(auto &x: a) dp.push_back(dp.back() + x);\n\n\t\tvector <pair <long long, int>> q;\n\t\tfor(int i = 0; i < queries.size(); i++) q.push_back({queries[i], i});\n\t\tsort(q.begin(), q.end());\n\n\t\tvector ans(q.size(), 0ll);\n\t\tlong long i = 0, n = a.size(), ln = 0, rn = n, ls = 0, rs = dp[n];\n\t\tfor(auto &[x, idx]: q) {\n\t\t\tfor( ; i < n && a[i] <= x; i++) {\n\t\t\t\tln = i + 1, rn = n - (i + 1);\n\t\t\t\tls = dp[i + 1], rs = dp[n] - dp[i + 1];\n\t\t\t}\n\t\t\tans[idx] = (x * ln - ls) + (rs - x * rn);\n\t\t}\n\t\treturn ans;\n\t}\n};\n``` | 3 | 0 | ['C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | C++ Sorting + Binary Search + Prefix Sum || Easy To Understand ⭐⭐⭐ | c-sorting-binary-search-prefix-sum-easy-z3050 | Intuition\n Describe your first thoughts on how to solve this problem. \nPartition the array in set of elements greeater than queries[i] and set of elements sma | Shailesh0302 | NORMAL | 2023-03-26T05:38:21.791125+00:00 | 2023-03-26T05:38:21.791161+00:00 | 143 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPartition the array in set of elements greeater than queries[i] and set of elements smaller than queries[i]\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nAfter partitioning \nFor smaller set \nrequired value to be added = (no.of elements * queries[i])- (sum of all elements)\nFor greater set \nrequired value to be added = (sum of all elements)-(no.of elements * queries[i])\nadd both values and push into answer vector\n\nDo above process m query length times \n\n\n# Complexity\n- Time complexity:O(nlogn + mlogn + n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n) Prefix array \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n long long n=nums.size(), m=queries.size();\n\n vector<long long> ans;\n sort(nums.begin(), nums.end());\n\n vector<long long> prefix(n);\n for(int i=0;i<n;i++) prefix[i]=(long long)nums[i];\n for(int i=1;i<n;i++){\n prefix[i]+=prefix[i-1];\n }\n\n for(int i=0;i<queries.size();i++){\n long long value=queries[i];\n int index=-1;\n \n long long low=0, high=n-1;\n while(low<=high){\n long long mid=low+(high-low)/2;\n if(nums[mid]<=value){\n index=mid;\n low=mid+1;\n }\n else high=mid-1; \n }\n if(index==-1){\n ans.push_back(prefix[n-1]-(value*n));\n }\n else{\n long long req1=(index+1)*value-prefix[index];\n long long req2=(prefix[n-1]-prefix[index])-(n-index-1)*value;\n ans.push_back(req1+req2); \n }\n }\n return ans; \n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | Prefix & Suffix + Binary Search | C++ | prefix-suffix-binary-search-c-by-tusharb-3c0v | \nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n long long n = nums.size();\n sort(nu | TusharBhart | NORMAL | 2023-03-26T05:21:36.251542+00:00 | 2023-03-26T05:27:37.370676+00:00 | 1,932 | false | ```\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n long long n = nums.size();\n sort(nums.begin(), nums.end());\n vector<long long> ps(n + 1), ss(n + 1), ans;\n for(int i=1; i<=n; i++) ps[i] = ps[i - 1] + nums[i - 1];\n for(int i=n-1; i>=0; i--) ss[i] = ss[i + 1] + nums[i];\n \n for(int q : queries) {\n long long pos = lower_bound(nums.begin(), nums.end(), q) - nums.begin();\n long long val = pos * q - ps[pos] + ss[pos] - (n - pos) * q;\n ans.push_back(val);\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Binary Search', 'Suffix Array', 'Sorting', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | Detailed Explanation of Code and Approach | detailed-explanation-of-code-and-approac-ewk4 | Intuition\n Describe your first thoughts on how to solve this problem. \nMy intuition is simpler just finding the number of element that are smaller than ith el | Unstoppable_1 | NORMAL | 2023-03-26T04:33:57.970795+00:00 | 2023-03-26T04:33:57.970839+00:00 | 421 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy intuition is simpler just finding the number of element that are smaller than ith element of query and using prefix sum find its sum and similarly for the element that are greater than the ith element of query.Then, calculate the answer by taking difference from prefixsum and the (numberofelement * i*th* elementofquery). \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.Initialize variables:\n\n->m is the size of the q vector (number of queries).\n->n is the size of the nums vector (number of elements in the array).\n->ans is a vector of size m initialized with zeros, used to store the final answer for each query.\n->sum is a vector of size n initialized with zeros, used to store the prefix sum of the sorted nums vector.\n\n2.Sort the nums vector in non-decreasing order.\n\n3.Calculate the prefix sum of the sorted nums vector and store it in the sum vector.\n\n4.Iterate through each query in q:\na. Find the first element that is greater than the queried value q[i] using upper_bound from the C++ Standard Library. This function returns an iterator pointing to the first element that is greater than the given value.\nb. Calculate the index of the found element in the nums vector.\nc. Calculate the sum of the elements lower than the queried value (lower_sum) and the sum of the elements greater than the queried value (upper_sum) using the prefix sum.\nd. Calculate the total cost for both the lower elements (final_lower_sum) and the upper elements (final_upper_sum).\ne. Add both costs and store the result in the ans vector.\n\nReturn the ans vector containing the minimum total cost for each query.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)+O(mlog(n)). \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) for storing prefixsum.\n# Code\n```\n\nclass Solution {\npublic:\n vector<long long> minOperations(vector<int>& nums, vector<int>& q) {\n int m=q.size(),n=nums.size();\n vector<long long> ans(m,0),sum(n,0);\n sort(nums.begin(),nums.end());\n sum[0]=nums[0];\n for(int i=1;i<n;i++)\n {\n sum[i]=nums[i];\n sum[i]+=sum[i-1]; \n }\n \n for(int i=0;i<m;i++)\n {\n vector<int>::iterator upper; \n upper = upper_bound(nums.begin(), nums.end(), q[i]);\n int index=upper-nums.begin(); \n \n long long lower_sum=0,upper_sum=0;\n if(index!=0) \n lower_sum=sum[index-1];\n \n upper_sum=sum[n-1]-lower_sum;\n \n long long final_lower_sum=((1ll*q[i]*index)-lower_sum);\n long long final_upper_sum=(upper_sum-(1ll*q[i]*(n-index))); \n \n ans[i]=(final_lower_sum+final_upper_sum); \n } \n return ans; \n }\n};\n``` | 3 | 0 | ['Binary Search', 'Prefix Sum', 'C++'] | 0 |
minimum-operations-to-make-all-array-elements-equal | 🐍Python Solution: Sort+PrefixSum+BinSearch | python-solution-sortprefixsumbinsearch-b-ipdy | \n\n# Code\n\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n prefix_sum = [nums[0 | otnyukovd | NORMAL | 2023-04-07T07:34:54.855121+00:00 | 2023-04-07T07:35:08.304264+00:00 | 1,369 | false | \n\n# Code\n```\nclass Solution:\n def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:\n nums.sort()\n prefix_sum = [nums[0]]\n ans = []\n for i in range(1, len(nums)):\n prefix_sum.append(prefix_sum[-1] + nums[i])\n \n for target in queries:\n l = 0\n r = len(nums) - 1\n pos = -2 # -2 for not found case\n #left bin search \n while l <= r:\n mid = (l + r) // 2\n if nums[mid] > target:\n r = mid - 1\n elif nums[mid] < target:\n l = mid + 1\n else:\n pos = mid\n r = mid - 1 \n\n if pos == -2:\n pos = min(l, r)\n # pos == -1 leftmost case\n if pos == -1:\n ans.append(prefix_sum[-1] - (len(nums))*target)\n else:\n ans.append((pos+1)*target - prefix_sum[pos] + prefix_sum[-1] - prefix_sum[pos] - (len(nums) -1 - pos)*target)\n \n return ans\n``` | 2 | 0 | ['Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.