title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python3 🐍 concise solution beats 99%
set-intersection-size-at-least-two
0
1
# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)\n```
0
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order. (Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length. **Example 1:** **Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\] **Output:** \[\[3,4\]\] **Explanation:** There are a total of three employees, and all common free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\]. We discard any intervals that contain inf as they aren't finite. **Example 2:** **Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\] **Output:** \[\[5,6\],\[7,9\]\] **Constraints:** * `1 <= schedule.length , schedule[i].length <= 50` * `0 <= schedule[i].start < schedule[i].end <= 10^8`
null
Python | Greedy Fast Short Documented
set-intersection-size-at-least-two
0
1
# Intuition\r\n- If A contains B, A is fulfilled as long as B is fulfilled, ignore A\r\n- now we have only partially overlapped (or not) intervals, sorted\r\n- what needs to be done should be done, just greedily choose number to added to `nums` from each intervals\r\n- according to `nums` we can know how much shortage we need\r\n- we can choose any numbers in current interval, but the right most one may have change to reduce shortage of next interval, so.\r\n\r\n# Approach\r\n- make a equivalent simpliest intervals, sorted\r\n- from sorted intervals, we do:\r\n - check previous two num in `nums`\r\n - find out how much shortage we need (compare to current interval)\r\n - add right most numbers (#shortage) to `nums`\r\n\r\n# Complexity\r\n- Time complexity:\r\n$$O(nlogn)$$ COZ sorted\r\n- Space complexity:\r\n$$O(n)$$\r\n\r\n```Vote if you think it\'s usefull``` \r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def intersectionSizeTwo(self, intervals):\r\n # make a equivalent simpliest intervals\r\n itvls = []\r\n for itvl in sorted(intervals, key=lambda e: (e[0], -e[1])):\r\n while itvls and itvls[-1][1] >= itvl[1]:\r\n itvls.pop()\r\n itvls.append(itvl)\r\n\r\n # greedily choose right most number from each interval to form nums\r\n # according to two most possible number to fulfill current interval in nums\r\n # we can determine how much shortage current interval needs\r\n nums = []\r\n for l, r in itvls:\r\n lack = 2\r\n if nums: lack -= (l <= nums[-2] <= r) + (l <= nums[-1] <= r)\r\n\r\n for i in range(lack): nums.append(r - i)\r\n\r\n return len(nums)\r\n```
0
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively. A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`. * For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**. Return _the minimum possible size of a containing set_. **Example 1:** **Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\] **Output:** 5 **Explanation:** let nums = \[2, 3, 4, 8, 9\]. It can be shown that there cannot be any containing array of size 4. **Example 2:** **Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\] **Output:** 3 **Explanation:** let nums = \[2, 3, 4\]. It can be shown that there cannot be any containing array of size 2. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\] **Output:** 5 **Explanation:** let nums = \[1, 2, 3, 4, 5\]. It can be shown that there cannot be any containing array of size 4. **Constraints:** * `1 <= intervals.length <= 3000` * `intervals[i].length == 2` * `0 <= starti < endi <= 108`
null
Python | Greedy Fast Short Documented
set-intersection-size-at-least-two
0
1
# Intuition\r\n- If A contains B, A is fulfilled as long as B is fulfilled, ignore A\r\n- now we have only partially overlapped (or not) intervals, sorted\r\n- what needs to be done should be done, just greedily choose number to added to `nums` from each intervals\r\n- according to `nums` we can know how much shortage we need\r\n- we can choose any numbers in current interval, but the right most one may have change to reduce shortage of next interval, so.\r\n\r\n# Approach\r\n- make a equivalent simpliest intervals, sorted\r\n- from sorted intervals, we do:\r\n - check previous two num in `nums`\r\n - find out how much shortage we need (compare to current interval)\r\n - add right most numbers (#shortage) to `nums`\r\n\r\n# Complexity\r\n- Time complexity:\r\n$$O(nlogn)$$ COZ sorted\r\n- Space complexity:\r\n$$O(n)$$\r\n\r\n```Vote if you think it\'s usefull``` \r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def intersectionSizeTwo(self, intervals):\r\n # make a equivalent simpliest intervals\r\n itvls = []\r\n for itvl in sorted(intervals, key=lambda e: (e[0], -e[1])):\r\n while itvls and itvls[-1][1] >= itvl[1]:\r\n itvls.pop()\r\n itvls.append(itvl)\r\n\r\n # greedily choose right most number from each interval to form nums\r\n # according to two most possible number to fulfill current interval in nums\r\n # we can determine how much shortage current interval needs\r\n nums = []\r\n for l, r in itvls:\r\n lack = 2\r\n if nums: lack -= (l <= nums[-2] <= r) + (l <= nums[-1] <= r)\r\n\r\n for i in range(lack): nums.append(r - i)\r\n\r\n return len(nums)\r\n```
0
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order. (Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length. **Example 1:** **Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\] **Output:** \[\[3,4\]\] **Explanation:** There are a total of three employees, and all common free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\]. We discard any intervals that contain inf as they aren't finite. **Example 2:** **Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\] **Output:** \[\[5,6\],\[7,9\]\] **Constraints:** * `1 <= schedule.length , schedule[i].length <= 50` * `0 <= schedule[i].start < schedule[i].end <= 10^8`
null
[Python3] greedy
set-intersection-size-at-least-two
0
1
\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)\n```
1
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively. A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`. * For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**. Return _the minimum possible size of a containing set_. **Example 1:** **Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\] **Output:** 5 **Explanation:** let nums = \[2, 3, 4, 8, 9\]. It can be shown that there cannot be any containing array of size 4. **Example 2:** **Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\] **Output:** 3 **Explanation:** let nums = \[2, 3, 4\]. It can be shown that there cannot be any containing array of size 2. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\] **Output:** 5 **Explanation:** let nums = \[1, 2, 3, 4, 5\]. It can be shown that there cannot be any containing array of size 4. **Constraints:** * `1 <= intervals.length <= 3000` * `intervals[i].length == 2` * `0 <= starti < endi <= 108`
null
[Python3] greedy
set-intersection-size-at-least-two
0
1
\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)\n```
1
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order. (Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length. **Example 1:** **Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\] **Output:** \[\[3,4\]\] **Explanation:** There are a total of three employees, and all common free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\]. We discard any intervals that contain inf as they aren't finite. **Example 2:** **Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\] **Output:** \[\[5,6\],\[7,9\]\] **Constraints:** * `1 <= schedule.length , schedule[i].length <= 50` * `0 <= schedule[i].start < schedule[i].end <= 10^8`
null
Solution
special-binary-string
1
1
```C++ []\nclass Solution {\n public:\n string makeLargestSpecial(string S) {\n vector<string> specials;\n int count = 0;\n\n for (int i = 0, j = 0; j < S.length(); ++j) {\n count += S[j] == \'1\' ? 1 : -1;\n if (count == 0) {\n const string& inner = S.substr(i + 1, j - i - 1);\n specials.push_back(\'1\' + makeLargestSpecial(inner) + \'0\');\n i = j + 1;\n }\n }\n sort(begin(specials), end(specials), greater<>());\n return join(specials);\n }\n private:\n string join(const vector<string>& specials) {\n string joined;\n for (const string& special : specials)\n joined += special;\n return joined;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n def decompose(s):\n i, count = 0, 0\n res = []\n for j in range(len(s)):\n count += 1 if s[j] == \'1\' else -1\n if count == 0:\n res.append(\'1\' + decompose(s[i+1:j]) + \'0\')\n i = j + 1\n res.sort(reverse=True)\n return \'\'.join(res)\n \n return decompose(s)\n```\n\n```Java []\nclass Solution {\n char[] bits;\n int[] ptable;\n\n class Node implements Comparable<Node> {\n long x = 0L;\n int n = 0;\n\n public Node(long x, int n) {\n this.x = x;\n this.n = n;\n }\n public void merge(Node other) {\n this.x <<= other.n;\n this.x |= other.x;\n this.n += other.n;\n }\n public Node expend() {\n x = (x << 1) | (1L << (n + 1));\n n += 2;\n return this;\n }\n public int compareTo(Node other) {\n int mlen = Math.max(this.n, other.n);\n long cx = this.x << (mlen - this.n);\n long co = other.x << (mlen - other.n);\n\n if (cx > co) return -1;\n if (cx < co) return 1;\n return (this.n - other.n);\n }\n public String toString() {\n StringBuilder sb = new StringBuilder();\n long b = 1L << (this.n - 1);\n while (b > 0) {\n char c = ((b & x) > 0) ? \'1\' : \'0\';\n sb.append(c);\n b >>= 1;\n }\n return sb.toString();\n }\n }\n private int helper_processing(int k) {\n if (k == bits.length) {\n return -1;\n }\n if (bits[k] == \'1\') {\n int r = helper_processing(k + 1);\n ptable[k] = r;\n ptable[r] = k;\n return helper_processing(r + 1);\n }\n return k;\n }\n public String makeLargestSpecial(String s) {\n bits = s.toCharArray();\n ptable = new int[bits.length];\n helper_processing(0);\n return helper_enlarge(-1).toString();\n }\n private Node helper_enlarge(int k) {\n int close = (k < 0) ? ptable.length : ptable[k];\n if (k + 1 == close) {\n return new Node(0L, 0);\n }\n PriorityQueue<Node> q = new PriorityQueue<>();\n int e = k;\n while (e + 1 < close) {\n k = e + 1;\n e = ptable[k];\n q.add(helper_enlarge(k));\n }\n Node curr = new Node(0L, 0);\n while (!q.isEmpty()) {\n Node h = q.poll();\n curr.merge(h.expend());\n }\n return curr;\n }\n}\n```\n
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Solution
special-binary-string
1
1
```C++ []\nclass Solution {\n public:\n string makeLargestSpecial(string S) {\n vector<string> specials;\n int count = 0;\n\n for (int i = 0, j = 0; j < S.length(); ++j) {\n count += S[j] == \'1\' ? 1 : -1;\n if (count == 0) {\n const string& inner = S.substr(i + 1, j - i - 1);\n specials.push_back(\'1\' + makeLargestSpecial(inner) + \'0\');\n i = j + 1;\n }\n }\n sort(begin(specials), end(specials), greater<>());\n return join(specials);\n }\n private:\n string join(const vector<string>& specials) {\n string joined;\n for (const string& special : specials)\n joined += special;\n return joined;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n def decompose(s):\n i, count = 0, 0\n res = []\n for j in range(len(s)):\n count += 1 if s[j] == \'1\' else -1\n if count == 0:\n res.append(\'1\' + decompose(s[i+1:j]) + \'0\')\n i = j + 1\n res.sort(reverse=True)\n return \'\'.join(res)\n \n return decompose(s)\n```\n\n```Java []\nclass Solution {\n char[] bits;\n int[] ptable;\n\n class Node implements Comparable<Node> {\n long x = 0L;\n int n = 0;\n\n public Node(long x, int n) {\n this.x = x;\n this.n = n;\n }\n public void merge(Node other) {\n this.x <<= other.n;\n this.x |= other.x;\n this.n += other.n;\n }\n public Node expend() {\n x = (x << 1) | (1L << (n + 1));\n n += 2;\n return this;\n }\n public int compareTo(Node other) {\n int mlen = Math.max(this.n, other.n);\n long cx = this.x << (mlen - this.n);\n long co = other.x << (mlen - other.n);\n\n if (cx > co) return -1;\n if (cx < co) return 1;\n return (this.n - other.n);\n }\n public String toString() {\n StringBuilder sb = new StringBuilder();\n long b = 1L << (this.n - 1);\n while (b > 0) {\n char c = ((b & x) > 0) ? \'1\' : \'0\';\n sb.append(c);\n b >>= 1;\n }\n return sb.toString();\n }\n }\n private int helper_processing(int k) {\n if (k == bits.length) {\n return -1;\n }\n if (bits[k] == \'1\') {\n int r = helper_processing(k + 1);\n ptable[k] = r;\n ptable[r] = k;\n return helper_processing(r + 1);\n }\n return k;\n }\n public String makeLargestSpecial(String s) {\n bits = s.toCharArray();\n ptable = new int[bits.length];\n helper_processing(0);\n return helper_enlarge(-1).toString();\n }\n private Node helper_enlarge(int k) {\n int close = (k < 0) ? ptable.length : ptable[k];\n if (k + 1 == close) {\n return new Node(0L, 0);\n }\n PriorityQueue<Node> q = new PriorityQueue<>();\n int e = k;\n while (e + 1 < close) {\n k = e + 1;\n e = ptable[k];\n q.add(helper_enlarge(k));\n }\n Node curr = new Node(0L, 0);\n while (!q.isEmpty()) {\n Node h = q.poll();\n curr.merge(h.expend());\n }\n return curr;\n }\n}\n```\n
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
761: Solution with step by step explanation
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ncount = i = 0\nres = []\n```\n\nHere, we initialize:\n\ncount to track the balance of the 1s and 0s.\ni to remember the starting point of a chunk.\nres to store all the special chunks we find.\n```\nfor j, c in enumerate(s):\n```\nWe iterate through the string s with both the index (j) and the character (c).\n\n```\ncount += 1 if c == \'1\' else -1\n```\nWe increase the count by 1 for every 1 we see, and decrease by 1 for every 0.\n\n```\nif count == 0:\n```\n\nWhenever the count becomes zero, it means we\'ve found a chunk with an equal number of 1s and 0s.\n\n```\nres.append(\'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n```\n\nFor every valid chunk found, we split it into inner chunks by making a recursive call to the function. The resulting smaller chunks are then wrapped with 1 and 0.\n\n```\ni = j + 1\n```\nAfter processing a chunk, we move the starting pointer (i) to the next character.\n\n```\nreturn \'\'.join(sorted(res)[::-1])\n```\n\nAfter processing the entire string, we sort the chunks in descending order and join them to form the resulting special binary string.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n count = i = 0\n res = []\n for j, c in enumerate(s):\n count += 1 if c == \'1\' else -1\n if count == 0:\n res.append(\'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n i = j + 1\n return \'\'.join(sorted(res)[::-1])\n\n```
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
761: Solution with step by step explanation
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ncount = i = 0\nres = []\n```\n\nHere, we initialize:\n\ncount to track the balance of the 1s and 0s.\ni to remember the starting point of a chunk.\nres to store all the special chunks we find.\n```\nfor j, c in enumerate(s):\n```\nWe iterate through the string s with both the index (j) and the character (c).\n\n```\ncount += 1 if c == \'1\' else -1\n```\nWe increase the count by 1 for every 1 we see, and decrease by 1 for every 0.\n\n```\nif count == 0:\n```\n\nWhenever the count becomes zero, it means we\'ve found a chunk with an equal number of 1s and 0s.\n\n```\nres.append(\'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n```\n\nFor every valid chunk found, we split it into inner chunks by making a recursive call to the function. The resulting smaller chunks are then wrapped with 1 and 0.\n\n```\ni = j + 1\n```\nAfter processing a chunk, we move the starting pointer (i) to the next character.\n\n```\nreturn \'\'.join(sorted(res)[::-1])\n```\n\nAfter processing the entire string, we sort the chunks in descending order and join them to form the resulting special binary string.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n count = i = 0\n res = []\n for j, c in enumerate(s):\n count += 1 if c == \'1\' else -1\n if count == 0:\n res.append(\'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n i = j + 1\n return \'\'.join(sorted(res)[::-1])\n\n```
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
📌📌 Easy-Approach || Well-Explained || Substring 🐍
special-binary-string
0
1
## IDEA:\n* If we regard 1, 0 in the definition of the special string as \'(\' and \')\' separately,\n\n* The problem is actually to get the string which is so-called valid parenthesis and meanwhile is the lexicographically largest.\n\n* It is intuitive that we prefer deeper valid parenthesis to sit in front (deeper means the string surrounded with more pairs of parenthesis, e.g., \'(())\' is deeper than \'()\' ).\n* We can achieve that by sorting them reversely.\n\n\n\'\'\'\n\n\tclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")\n l = r+1\n \n sublist.sort(reverse=True)\n return \'\'.join(sublist)\n\n### If you like the idea, please Upvote!!\uD83E\uDD1E
6
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
📌📌 Easy-Approach || Well-Explained || Substring 🐍
special-binary-string
0
1
## IDEA:\n* If we regard 1, 0 in the definition of the special string as \'(\' and \')\' separately,\n\n* The problem is actually to get the string which is so-called valid parenthesis and meanwhile is the lexicographically largest.\n\n* It is intuitive that we prefer deeper valid parenthesis to sit in front (deeper means the string surrounded with more pairs of parenthesis, e.g., \'(())\' is deeper than \'()\' ).\n* We can achieve that by sorting them reversely.\n\n\n\'\'\'\n\n\tclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")\n l = r+1\n \n sublist.sort(reverse=True)\n return \'\'.join(sublist)\n\n### If you like the idea, please Upvote!!\uD83E\uDD1E
6
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
100% memory beats
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n specials = []\n count = 0\n\n i = 0\n for j, c in enumerate(s):\n count += 1 if c == \'1\' else -1\n if count == 0:\n specials.append(\n \'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n i = j + 1\n\n return \'\'.join(sorted(specials)[::-1])\n\n```
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
100% memory beats
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n specials = []\n count = 0\n\n i = 0\n for j, c in enumerate(s):\n count += 1 if c == \'1\' else -1\n if count == 0:\n specials.append(\n \'1\' + self.makeLargestSpecial(s[i + 1:j]) + \'0\')\n i = j + 1\n\n return \'\'.join(sorted(specials)[::-1])\n\n```
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
Simple Explained Solution
special-binary-string
1
1
\n```\nclass Solution {\n public String makeLargestSpecial(String S) {\n int count = 0, i = 0;\n List<String> res = new ArrayList<String>();\n for (int j = 0; j < S.length(); ++j) {\n if (S.charAt(j) == \'1\') count++;\n else count--;\n if (count == 0) {\n res.add(\'1\' + makeLargestSpecial(S.substring(i + 1, j)) + \'0\');\n i = j + 1;\n }\n }\n Collections.sort(res, Collections.reverseOrder());\n return String.join("", res);\n }\n}\n```
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Simple Explained Solution
special-binary-string
1
1
\n```\nclass Solution {\n public String makeLargestSpecial(String S) {\n int count = 0, i = 0;\n List<String> res = new ArrayList<String>();\n for (int j = 0; j < S.length(); ++j) {\n if (S.charAt(j) == \'1\') count++;\n else count--;\n if (count == 0) {\n res.add(\'1\' + makeLargestSpecial(S.substring(i + 1, j)) + \'0\');\n i = j + 1;\n }\n }\n Collections.sort(res, Collections.reverseOrder());\n return String.join("", res);\n }\n}\n```
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
Fast python sol
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that this problem can be solved using a recursive approach. We can divide the string into smaller substrings that are surrounded by \'1\' and \'0\' characters, and then recursively solve the problem for each substring.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to use a recursive function that takes in a string as input. The function starts by initializing a count variable, a start variable, and a result list. It then iterates through the string, and for each \'1\' character, it increments the count variable, and for each \'0\' character, it decrements the count variable. When the count variable reaches zero, it means that a substring has been found that is surrounded by \'1\' and \'0\' characters. The function then adds this substring to the result list, and recursively calls itself on the substring without the surrounding \'1\' and \'0\' characters. After all substrings have been found, the function sorts the result list in descending order and returns the concatenated string.\n\n# Complexity\n- Time complexity: $$O(2^n \\times n \\log n)$$\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(2^n * n * log(n)) because for every substring of size n, we sort the substrings in descending order which takes O(n * log(n)) and we have 2^n substrings.\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) because we are using a recursive function and each recursive call uses O(n) space on the call stack.\n\n\n\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n count = 0\n start = 0\n result = []\n for i in range(len(s)):\n if s[i] == \'1\':\n count += 1\n else:\n count -= 1\n if count == 0:\n result.append(\'1\' + self.makeLargestSpecial(s[start+1:i]) + \'0\')\n start = i + 1\n return \'\'.join(sorted(result, reverse=True))\n```
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Fast python sol
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that this problem can be solved using a recursive approach. We can divide the string into smaller substrings that are surrounded by \'1\' and \'0\' characters, and then recursively solve the problem for each substring.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to use a recursive function that takes in a string as input. The function starts by initializing a count variable, a start variable, and a result list. It then iterates through the string, and for each \'1\' character, it increments the count variable, and for each \'0\' character, it decrements the count variable. When the count variable reaches zero, it means that a substring has been found that is surrounded by \'1\' and \'0\' characters. The function then adds this substring to the result list, and recursively calls itself on the substring without the surrounding \'1\' and \'0\' characters. After all substrings have been found, the function sorts the result list in descending order and returns the concatenated string.\n\n# Complexity\n- Time complexity: $$O(2^n \\times n \\log n)$$\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(2^n * n * log(n)) because for every substring of size n, we sort the substrings in descending order which takes O(n * log(n)) and we have 2^n substrings.\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) because we are using a recursive function and each recursive call uses O(n) space on the call stack.\n\n\n\n\n# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n count = 0\n start = 0\n result = []\n for i in range(len(s)):\n if s[i] == \'1\':\n count += 1\n else:\n count -= 1\n if count == 0:\n result.append(\'1\' + self.makeLargestSpecial(s[start+1:i]) + \'0\')\n start = i + 1\n return \'\'.join(sorted(result, reverse=True))\n```
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
Python3 🐍 concise solution beats 99%
special-binary-string
0
1
# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")\n l = r+1\n \n sublist.sort(reverse=True)\n return \'\'.join(sublist)\n```
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Python3 🐍 concise solution beats 99%
special-binary-string
0
1
# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")\n l = r+1\n \n sublist.sort(reverse=True)\n return \'\'.join(sublist)\n```
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
[Python3] partition via recursion
special-binary-string
0
1
\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n def fn(lo, hi): \n if lo == hi: return ""\n vals = []\n ii, prefix = lo, 0\n for i in range(lo, hi):\n prefix += 1 if s[i] == "1" else -1 \n if prefix == 0: \n vals.append("1" + fn(ii+1, i) + "0")\n ii = i+1\n return "".join(sorted(vals, reverse=True))\n \n return fn(0, len(s))\n```
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, special substrings of `s`, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string. Return _the lexicographically largest resulting string possible after applying the mentioned operations on the string_. **Example 1:** **Input:** s = "11011000 " **Output:** "11100100 " **Explanation:** The strings "10 " \[occuring at s\[1\]\] and "1100 " \[at s\[3\]\] are swapped. This is the lexicographically largest string possible after some number of swaps. **Example 2:** **Input:** s = "10 " **Output:** "10 " **Constraints:** * `1 <= s.length <= 50` * `s[i]` is either `'0'` or `'1'`. * `s` is a special binary string.
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
[Python3] partition via recursion
special-binary-string
0
1
\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n def fn(lo, hi): \n if lo == hi: return ""\n vals = []\n ii, prefix = lo, 0\n for i in range(lo, hi):\n prefix += 1 if s[i] == "1" else -1 \n if prefix == 0: \n vals.append("1" + fn(ii+1, i) + "0")\n ii = i+1\n return "".join(sorted(vals, reverse=True))\n \n return fn(0, len(s))\n```
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
762: Beats 91.74%, Solution with step by step explanation
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n```\n\nWe create a set of prime numbers which are less than 20. Since the maximum number of bits we are concerned with is 20 (for the given problem constraints), we only need primes below 20.\n\n```\n count = 0\n```\n\nInitialize a count to zero. This variable will keep track of how many numbers have a prime number of set bits.\n\n```\n for num in range(left, right+1):\n```\n\nWe loop through each number in the inclusive range of left to right.\n\n```\n set_bits = num.bit_count()\n```\n\nFor each number, we calculate the number of set bits (i.e., number of 1s in its binary representation). Python provides a built-in method bit_count() for integers to count the number of set bits.\n\n```\n if set_bits in primes:\n count += 1\n```\n\nIf the number of set bits is one of the prime numbers in our set, we increment our count.\n\n```\n return count\n```\nFinally, after iterating through all the numbers, we return the count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n count = 0\n\n for num in range(left, right+1):\n\n set_bits = num.bit_count()\n\n if set_bits in primes:\n count += 1\n\n return count\n\n```
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
762: Beats 91.74%, Solution with step by step explanation
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n```\n\nWe create a set of prime numbers which are less than 20. Since the maximum number of bits we are concerned with is 20 (for the given problem constraints), we only need primes below 20.\n\n```\n count = 0\n```\n\nInitialize a count to zero. This variable will keep track of how many numbers have a prime number of set bits.\n\n```\n for num in range(left, right+1):\n```\n\nWe loop through each number in the inclusive range of left to right.\n\n```\n set_bits = num.bit_count()\n```\n\nFor each number, we calculate the number of set bits (i.e., number of 1s in its binary representation). Python provides a built-in method bit_count() for integers to count the number of set bits.\n\n```\n if set_bits in primes:\n count += 1\n```\n\nIf the number of set bits is one of the prime numbers in our set, we increment our count.\n\n```\n return count\n```\nFinally, after iterating through all the numbers, we return the count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n count = 0\n\n for num in range(left, right+1):\n\n set_bits = num.bit_count()\n\n if set_bits in primes:\n count += 1\n\n return count\n\n```
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python one-liner
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less equivalent to bin(x).count("1") but obviously much faster.\n\n\n# Complexity\n- Time complexity: O(n) - iterating over the left..right range.\n\n- Space complexity: O(1) - sum is computed via generator\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n return (primes := (2,3,5,7,11,13,17,19)) and sum((x.bit_count() in primes) for x in range(left, right+1))\n \n```
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Python one-liner
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less equivalent to bin(x).count("1") but obviously much faster.\n\n\n# Complexity\n- Time complexity: O(n) - iterating over the left..right range.\n\n- Space complexity: O(1) - sum is computed via generator\n\n# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n return (primes := (2,3,5,7,11,13,17,19)) and sum((x.bit_count() in primes) for x in range(left, right+1))\n \n```
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Solution
prime-number-of-set-bits-in-binary-representation
1
1
```C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n ++left;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n c = 0\n\n for i in range(left, right + 1):\n if i.bit_count() in primes:\n c += 1\n \n return c\n```\n\n```Java []\nclass Solution {\n private final int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19};\n private int cnk(int n, int k) {\n if (n <= 0 || k <= 0) {\n return 0;\n }\n long f1 = 1;\n for (int i = k + 1; i <= n; i++) {\n f1 *= i;\n }\n long f2 = 1;\n for (int i = 2; i <= n - k; i++) {\n f2 *= i;\n }\n return (int) (f1 / f2);\n }\n private int primeBitNumbersCount(int length, int minus) {\n int result = 0;\n for (int i = 0; i < primes.length && primes[i] - minus <= length; i++) {\n result += cnk(length, primes[i] - minus);\n }\n return result;\n }\n private int primesTo(int number) {\n for (int i = primes.length - 1; i >= 0; i--) {\n if (number >= primes[i]) {\n return i + 1;\n }\n }\n return 0;\n }\n private int primeBitNumbersCount(int number) {\n int pointer = 0x40000000;\n int position = 31;\n int bitsSet = 0;\n int primeBitNumbersCount = 0; \n\n while (pointer != 0) {\n if ((number & pointer) > 0) {\n primeBitNumbersCount += primeBitNumbersCount(position - 1, bitsSet);\n bitsSet++;\n }\n pointer >>>= 1;\n position--;\n }\n primeBitNumbersCount += primesTo(bitsSet);\n return primeBitNumbersCount;\n }\n public int countPrimeSetBits(int left, int right) {\n return primeBitNumbersCount(right) - primeBitNumbersCount(left - 1);\n }\n}\n```\n
2
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Solution
prime-number-of-set-bits-in-binary-representation
1
1
```C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n ++left;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n c = 0\n\n for i in range(left, right + 1):\n if i.bit_count() in primes:\n c += 1\n \n return c\n```\n\n```Java []\nclass Solution {\n private final int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19};\n private int cnk(int n, int k) {\n if (n <= 0 || k <= 0) {\n return 0;\n }\n long f1 = 1;\n for (int i = k + 1; i <= n; i++) {\n f1 *= i;\n }\n long f2 = 1;\n for (int i = 2; i <= n - k; i++) {\n f2 *= i;\n }\n return (int) (f1 / f2);\n }\n private int primeBitNumbersCount(int length, int minus) {\n int result = 0;\n for (int i = 0; i < primes.length && primes[i] - minus <= length; i++) {\n result += cnk(length, primes[i] - minus);\n }\n return result;\n }\n private int primesTo(int number) {\n for (int i = primes.length - 1; i >= 0; i--) {\n if (number >= primes[i]) {\n return i + 1;\n }\n }\n return 0;\n }\n private int primeBitNumbersCount(int number) {\n int pointer = 0x40000000;\n int position = 31;\n int bitsSet = 0;\n int primeBitNumbersCount = 0; \n\n while (pointer != 0) {\n if ((number & pointer) > 0) {\n primeBitNumbersCount += primeBitNumbersCount(position - 1, bitsSet);\n bitsSet++;\n }\n pointer >>>= 1;\n position--;\n }\n primeBitNumbersCount += primesTo(bitsSet);\n return primeBitNumbersCount;\n }\n public int countPrimeSetBits(int left, int right) {\n return primeBitNumbersCount(right) - primeBitNumbersCount(left - 1);\n }\n}\n```\n
2
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-representation
0
1
# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n a = bin(i)[2:]\n t = a.count("1")\n l = []\n if t==1:\n pass\n else:\n for i in range(2,t):\n if t%i==0:\n break\n else:\n count+=1\n return count\n \n \n\n\n\n\n \n```
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-representation
0
1
# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n a = bin(i)[2:]\n t = a.count("1")\n l = []\n if t==1:\n pass\n else:\n for i in range(2,t):\n if t%i==0:\n break\n else:\n count+=1\n return count\n \n \n\n\n\n\n \n```
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Easy Python solution
prime-number-of-set-bits-in-binary-representation
0
1
```\ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).count("1")\n for j in range(1,n+1):\n if n%j==0:\n c+=1\n if c==2:\n count+=1\n return count\n```
4
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Easy Python solution
prime-number-of-set-bits-in-binary-representation
0
1
```\ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).count("1")\n for j in range(1,n+1):\n if n%j==0:\n c+=1\n if c==2:\n count+=1\n return count\n```
4
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained
partition-labels
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nSince each letter can appear only in one part, we cannot form a part shorter than the index of the last appearance of a letter subtracted by an index of the first appearance. For example here (**a**bsf**a**b) the lengths of the first part are limited by the positions of the letter `a`. So it\'s important to know at what index each letter appears in the string last time. We can create a hash map and fill it with the last indexes for letters.\n\nAlso, we have to validate a candidate part. For the same example (**a***b*sfa**b**) we see that letter `a` cannot form a border for the first part because of a nasty letter `b` inside. So we need to expand the range of the initial part.\n\nTime: **O(n)** - 2 sweeps\nSpace: **O(1)** - hashmap consist of max 26 keys\n\nRuntime: 36 ms, faster than **96.88%** of Python3 online submissions for Partition Labels.\nMemory Usage: 13.8 MB, less than **98.78%** of Python3 online submissions for Partition Labels.\n\n```\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n L = len(s)\n last = {s[i]: i for i in range(L)} # last appearance of the letter\n i, ans = 0, []\n while i < L:\n end, j = last[s[i]], i + 1\n while j < end: # validation of the part [i, end]\n if last[s[j]] > end:\n end = last[s[j]] # extend the part\n j += 1\n \n ans.append(end - i + 1)\n i = end + 1\n \n return ans\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
90
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained
partition-labels
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nSince each letter can appear only in one part, we cannot form a part shorter than the index of the last appearance of a letter subtracted by an index of the first appearance. For example here (**a**bsf**a**b) the lengths of the first part are limited by the positions of the letter `a`. So it\'s important to know at what index each letter appears in the string last time. We can create a hash map and fill it with the last indexes for letters.\n\nAlso, we have to validate a candidate part. For the same example (**a***b*sfa**b**) we see that letter `a` cannot form a border for the first part because of a nasty letter `b` inside. So we need to expand the range of the initial part.\n\nTime: **O(n)** - 2 sweeps\nSpace: **O(1)** - hashmap consist of max 26 keys\n\nRuntime: 36 ms, faster than **96.88%** of Python3 online submissions for Partition Labels.\nMemory Usage: 13.8 MB, less than **98.78%** of Python3 online submissions for Partition Labels.\n\n```\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n L = len(s)\n last = {s[i]: i for i in range(L)} # last appearance of the letter\n i, ans = 0, []\n while i < L:\n end, j = last[s[i]], i + 1\n while j < end: # validation of the part [i, end]\n if last[s[j]] > end:\n end = last[s[j]] # extend the part\n j += 1\n \n ans.append(end - i + 1)\n i = end + 1\n \n return ans\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
90
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Python 91% O(n) intuitive implementation; simple counter solution
partition-labels
0
1
# Intuition\n\nPartitions are defined such that all characters in a partition are only found in this specific partition; any character in one partition must not be in any other partition. \n\nThe \'greedy\' idea is always adding the first character to the partition, and keeping track of how many of this character we have yet to find. Along the way, if we encounter any other characters, we will add them to the partition.\n\nWe initialize a counter `cur` for the current partition we\'re building. This will keep track of the remaining chars we need to see until this partition is done; that is, we initially copy from the total count (`count`) and our termination condition is when `cur` is empty (or has all zero counts).\n\n\nAs we iterate over the string and encounter a character: if it\'s in the partition already, decrease it\'s count by 1; if it\'s new (not in `cur`), then we copy the characters\' overall frequency from `count` and take off one (since we\'ve seen the first occurence of it). Note that `cur[ch] = cur.get(ch, count[ch]) - 1` is equivilent to... \n```py\nif ch in cur:\n cur[ch] = cur[ch] - 1 # first arg\nelse:\n cur[ch] = count[ch]) - 1 # second arg\n\n```\n\n\n# Code\nI have three different sections, all functionally equivilent, ordered fastest to slowest\n\n```py\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n out=[]\n count=Counter(s)\n \n while s:\n cur = Counter()\n\n # === do-While (~43ms) ===\n i=0\n while True:\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n if cur[ch] == 0:\n del cur[ch]\n del count[ch] # not necissary \n i+=1\n if not cur:\n break\n\n # === while (~50ms) ===\n i=0\n ch=s[0]\n cur[ch]=count[ch]\n while cur:\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n if cur[ch] == 0:\n del cur[ch]\n del count[ch]\n i+=1\n\n # === without deletion (~66ms) ===\n i=0\n ch=s[0]\n cur[ch]=count[ch]\n while any(v != 0 for v in cur.values()):\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n i+=1\n\n # =========\n\n\n s = s[i:] # chop the first i characters\n out.append(i)\n\n return out \n```
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
Python 91% O(n) intuitive implementation; simple counter solution
partition-labels
0
1
# Intuition\n\nPartitions are defined such that all characters in a partition are only found in this specific partition; any character in one partition must not be in any other partition. \n\nThe \'greedy\' idea is always adding the first character to the partition, and keeping track of how many of this character we have yet to find. Along the way, if we encounter any other characters, we will add them to the partition.\n\nWe initialize a counter `cur` for the current partition we\'re building. This will keep track of the remaining chars we need to see until this partition is done; that is, we initially copy from the total count (`count`) and our termination condition is when `cur` is empty (or has all zero counts).\n\n\nAs we iterate over the string and encounter a character: if it\'s in the partition already, decrease it\'s count by 1; if it\'s new (not in `cur`), then we copy the characters\' overall frequency from `count` and take off one (since we\'ve seen the first occurence of it). Note that `cur[ch] = cur.get(ch, count[ch]) - 1` is equivilent to... \n```py\nif ch in cur:\n cur[ch] = cur[ch] - 1 # first arg\nelse:\n cur[ch] = count[ch]) - 1 # second arg\n\n```\n\n\n# Code\nI have three different sections, all functionally equivilent, ordered fastest to slowest\n\n```py\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n out=[]\n count=Counter(s)\n \n while s:\n cur = Counter()\n\n # === do-While (~43ms) ===\n i=0\n while True:\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n if cur[ch] == 0:\n del cur[ch]\n del count[ch] # not necissary \n i+=1\n if not cur:\n break\n\n # === while (~50ms) ===\n i=0\n ch=s[0]\n cur[ch]=count[ch]\n while cur:\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n if cur[ch] == 0:\n del cur[ch]\n del count[ch]\n i+=1\n\n # === without deletion (~66ms) ===\n i=0\n ch=s[0]\n cur[ch]=count[ch]\n while any(v != 0 for v in cur.values()):\n ch=s[i]\n cur[ch] = cur.get(ch, count[ch]) - 1\n i+=1\n\n # =========\n\n\n s = s[i:] # chop the first i characters\n out.append(i)\n\n return out \n```
1
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
763: Solution with step by step explanation
partition-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n last_occurrence = {char: index for index, char in enumerate(s)}\n```\n\nUsing a dictionary comprehension, we create a dictionary called last_occurrence. The keys are the characters in the string s, and the values are the indices of their last occurrences. This helps us determine the furthest we have to go in the string to make a partition for each character.\n\n```\n partitions = []\n start, end = 0, 0\n```\n\nWe create an empty list called partitions to store the lengths of the partitions we determine. start and end are two pointers used to denote the start and end of the current partition.\n\n```\n for i, char in enumerate(s):\n```\n\nUsing a loop, we iterate through each character in the string s.\n\n```\n last_index = last_occurrence[char]\n```\n\nFor each character, we check its last occurrence in the string. This gives us an idea of the furthest boundary to which the current partition can extend.\n\n```\n end = max(end, last_index)\n```\n\nThe end of the current partition is determined by the furthest last occurrence of any character in the current partition.\n\n```\n if i == end:\n partitions.append(i - start + 1)\n start = i + 1\n```\n\nIf the current index i matches the end pointer, it indicates we have reached the end of a partition. We calculate the length of this partition and append it to the partitions list. The start pointer is then moved to the next index to begin a new partition.\n\n```\n return partitions\n```\n\nAfter iterating through the entire string, we return the list of partition lengths.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n last_occurrence = {char: index for index, char in enumerate(s)}\n \n partitions = []\n start, end = 0, 0\n\n for i, char in enumerate(s):\n last_index = last_occurrence[char] \n end = max(end, last_index) \n \n if i == end: \n partitions.append(i - start + 1)\n start = i + 1 \n\n return partitions\n```
4
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
763: Solution with step by step explanation
partition-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n last_occurrence = {char: index for index, char in enumerate(s)}\n```\n\nUsing a dictionary comprehension, we create a dictionary called last_occurrence. The keys are the characters in the string s, and the values are the indices of their last occurrences. This helps us determine the furthest we have to go in the string to make a partition for each character.\n\n```\n partitions = []\n start, end = 0, 0\n```\n\nWe create an empty list called partitions to store the lengths of the partitions we determine. start and end are two pointers used to denote the start and end of the current partition.\n\n```\n for i, char in enumerate(s):\n```\n\nUsing a loop, we iterate through each character in the string s.\n\n```\n last_index = last_occurrence[char]\n```\n\nFor each character, we check its last occurrence in the string. This gives us an idea of the furthest boundary to which the current partition can extend.\n\n```\n end = max(end, last_index)\n```\n\nThe end of the current partition is determined by the furthest last occurrence of any character in the current partition.\n\n```\n if i == end:\n partitions.append(i - start + 1)\n start = i + 1\n```\n\nIf the current index i matches the end pointer, it indicates we have reached the end of a partition. We calculate the length of this partition and append it to the partitions list. The start pointer is then moved to the next index to begin a new partition.\n\n```\n return partitions\n```\n\nAfter iterating through the entire string, we return the list of partition lengths.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def partitionLabels(self, s: str) -> List[int]:\n last_occurrence = {char: index for index, char in enumerate(s)}\n \n partitions = []\n start, end = 0, 0\n\n for i, char in enumerate(s):\n last_index = last_occurrence[char] \n end = max(end, last_index) \n \n if i == end: \n partitions.append(i - start + 1)\n start = i + 1 \n\n return partitions\n```
4
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Simple O(n) Python Solution || With Explanation
partition-labels
0
1
# Intuition\n###### This algorithm iterates through the string, tracking the last occurrence index of each character. It creates partitions by extending them from the start character to the last occurrence of any character within the current partition. When the end of a partition is reached, its length is added to the result list, and the process continues until the entire string is processed.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n###### 1. Create a dictionary `d` to store the last occurrence index of each character in the input string.\n\n###### 2. Initialize `mx` (last occurrence index encountered so far), `size` (length of current partition), and `res` (list to store partition lengths).\n\n###### 3. Loop through each character and its index in the string:\n - Increment the `size` counter for the current partition.\n - Update `mx` to the maximum of the current character\'s last occurrence index and the current `mx`.\n\n###### 4. If the current index equals `mx`, it means the current partition is complete:\n - Append the `size` to the `res` list.\n - Reset `size` to 0 for the next partition.\n\n###### 5. Return the `res` list, containing the lengths of the non-overlapping partitions.\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 def partitionLabels(self, s: str) -> List[int]:\n # storing last occurence of every char in s\n d = {char:idx for idx, char in enumerate(s)}\n\n # mx variable to keep track of last occurence of current character\n # size variable to keep track of length of a part\n mx, size, res = 0, 0, []\n \n for idx, char in enumerate(s):\n size += 1\n # a part for the 1st char cannot be lesser than the last occurence\n # so we update mx to the last occurence\n # similarly for the rest of the characters\n mx = max(d[char],mx)\n\n # reset size to 0 if the current char is its last occurence in string s.\n if idx == mx:\n res.append(size)\n size = 0\n return(res)\n```
2
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
Simple O(n) Python Solution || With Explanation
partition-labels
0
1
# Intuition\n###### This algorithm iterates through the string, tracking the last occurrence index of each character. It creates partitions by extending them from the start character to the last occurrence of any character within the current partition. When the end of a partition is reached, its length is added to the result list, and the process continues until the entire string is processed.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n###### 1. Create a dictionary `d` to store the last occurrence index of each character in the input string.\n\n###### 2. Initialize `mx` (last occurrence index encountered so far), `size` (length of current partition), and `res` (list to store partition lengths).\n\n###### 3. Loop through each character and its index in the string:\n - Increment the `size` counter for the current partition.\n - Update `mx` to the maximum of the current character\'s last occurrence index and the current `mx`.\n\n###### 4. If the current index equals `mx`, it means the current partition is complete:\n - Append the `size` to the `res` list.\n - Reset `size` to 0 for the next partition.\n\n###### 5. Return the `res` list, containing the lengths of the non-overlapping partitions.\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 def partitionLabels(self, s: str) -> List[int]:\n # storing last occurence of every char in s\n d = {char:idx for idx, char in enumerate(s)}\n\n # mx variable to keep track of last occurence of current character\n # size variable to keep track of length of a part\n mx, size, res = 0, 0, []\n \n for idx, char in enumerate(s):\n size += 1\n # a part for the 1st char cannot be lesser than the last occurence\n # so we update mx to the last occurence\n # similarly for the rest of the characters\n mx = max(d[char],mx)\n\n # reset size to 0 if the current char is its last occurence in string s.\n if idx == mx:\n res.append(size)\n size = 0\n return(res)\n```
2
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Solution
largest-plus-sign
1
1
```C++ []\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n int ans=0,s,i,j,k;\n int dp[N+2][N+2][4],v[N][N];\n for(i=0;i<N;i++)for(j=0;j<N;j++)v[i][j]=1;\n for(i=0;i<mines.size();i++)v[mines[i][0]][mines[i][1]]=0;\n memset(dp,0,sizeof dp);\n \n for(i=0;i<N;i++){\n for(j=0;j<N;j++){\n if(v[i][j]==1){\n dp[i+1][j+1][0]=dp[i][j+1][0]+1;\n dp[i+1][j+1][1]=dp[i+1][j][1]+1;\n }\n }\n }\n for(i=N-1;i>=0;i--){\n for(j=N-1;j>=0;j--){\n if(v[i][j]==1){\n dp[i+1][j+1][2]=dp[i+2][j+1][2]+1;\n dp[i+1][j+1][3]=dp[i+1][j+2][3]+1;\n }\n }\n }\n for(i=1;i<=N;i++){\n for(j=1;j<=N;j++){\n s=min(dp[i][j][0],min(dp[i][j][1],min(dp[i][j][2],dp[i][j][3])));\n ans=max(ans,s);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:\n rows = [[-1, N] for _ in range(N)]\n cols = [[-1, N] for _ in range(N)]\n for r, c in mines:\n rows[r].append(c)\n cols[c].append(r)\n for i in range(N):\n rows[i].sort()\n cols[i].sort()\n mxp = 0\n for r in range(N):\n for i in range(len(rows[r]) - 1):\n left_b = rows[r][i]\n right_b = rows[r][i+1]\n for c in range(left_b + mxp + 1, right_b - mxp):\n idx = bisect_right(cols[c], r) - 1\n up_b = cols[c][idx]\n down_b = cols[c][idx + 1]\n mxp = max(mxp, min(c - left_b, right_b - c, r - up_b, down_b - r))\n return mxp\n```\n\n```Java []\nclass Solution {\n public int orderOfLargestPlusSign(int n, int[][] mines) {\n int[][] dp = new int[n][n];\n for(int[] mine : mines) {\n int row = mine[0], col = mine[1];\n dp[row][col] = -1;\n }\n for(int row = 0; row < n; row++) {\n int count = 0;\n for(int col = 0; col < n; col++) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = count;\n }\n }\n count = 0;\n for(int col = n - 1; col >= 0; col--) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n }\n }\n int max = 0;\n for(int col = 0; col < n; col++) {\n int count = 0;\n for(int row = 0; row < n; row++) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n }\n count = 0;\n for(int row = n - 1; row >= 0; row--) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n max = Math.max(max, dp[row][col]);\n }\n }\n return max;\n }\n}\n```\n
1
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
Solution
largest-plus-sign
1
1
```C++ []\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n int ans=0,s,i,j,k;\n int dp[N+2][N+2][4],v[N][N];\n for(i=0;i<N;i++)for(j=0;j<N;j++)v[i][j]=1;\n for(i=0;i<mines.size();i++)v[mines[i][0]][mines[i][1]]=0;\n memset(dp,0,sizeof dp);\n \n for(i=0;i<N;i++){\n for(j=0;j<N;j++){\n if(v[i][j]==1){\n dp[i+1][j+1][0]=dp[i][j+1][0]+1;\n dp[i+1][j+1][1]=dp[i+1][j][1]+1;\n }\n }\n }\n for(i=N-1;i>=0;i--){\n for(j=N-1;j>=0;j--){\n if(v[i][j]==1){\n dp[i+1][j+1][2]=dp[i+2][j+1][2]+1;\n dp[i+1][j+1][3]=dp[i+1][j+2][3]+1;\n }\n }\n }\n for(i=1;i<=N;i++){\n for(j=1;j<=N;j++){\n s=min(dp[i][j][0],min(dp[i][j][1],min(dp[i][j][2],dp[i][j][3])));\n ans=max(ans,s);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:\n rows = [[-1, N] for _ in range(N)]\n cols = [[-1, N] for _ in range(N)]\n for r, c in mines:\n rows[r].append(c)\n cols[c].append(r)\n for i in range(N):\n rows[i].sort()\n cols[i].sort()\n mxp = 0\n for r in range(N):\n for i in range(len(rows[r]) - 1):\n left_b = rows[r][i]\n right_b = rows[r][i+1]\n for c in range(left_b + mxp + 1, right_b - mxp):\n idx = bisect_right(cols[c], r) - 1\n up_b = cols[c][idx]\n down_b = cols[c][idx + 1]\n mxp = max(mxp, min(c - left_b, right_b - c, r - up_b, down_b - r))\n return mxp\n```\n\n```Java []\nclass Solution {\n public int orderOfLargestPlusSign(int n, int[][] mines) {\n int[][] dp = new int[n][n];\n for(int[] mine : mines) {\n int row = mine[0], col = mine[1];\n dp[row][col] = -1;\n }\n for(int row = 0; row < n; row++) {\n int count = 0;\n for(int col = 0; col < n; col++) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = count;\n }\n }\n count = 0;\n for(int col = n - 1; col >= 0; col--) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n }\n }\n int max = 0;\n for(int col = 0; col < n; col++) {\n int count = 0;\n for(int row = 0; row < n; row++) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n }\n count = 0;\n for(int row = n - 1; row >= 0; row--) {\n if(dp[row][col] == -1) {\n count = 0;\n } else {\n count += 1;\n dp[row][col] = Math.min(dp[row][col], count);\n }\n max = Math.max(max, dp[row][col]);\n }\n }\n return max;\n }\n}\n```\n
1
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
764: Memory Beats 91.40%, Solution with step by step explanation
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ngrid = [[n] * n for _ in range(n)]\n```\nWe initialize a grid with all values set to n. Why? Because in the best case, if a cell isn\'t blocked (by a mine), its maximum potential reach in any direction is n (from one edge to another).\n\n```\nfor x, y in mines:\n grid[x][y] = 0\n```\n\nWe then loop through the mines and set those cells to 0 in the grid, as they can\'t be a part of any plus sign.\n\nWe need to determine how far each cell can reach in every direction. This will let us determine the size of the plus sign for which the cell can be a center.\n\n```\nfor i in range(n):\n l, r, u, d = 0, 0, 0, 0 \n```\n\nWe begin by iterating through each row and column of the matrix using i. For each row and column, we initialize counters for all four directions (left, right, up, down).\n\n```\n for j in range(n):\n l = l + 1 if grid[i][j] != 0 else 0\n r = r + 1 if grid[i][n-j-1] != 0 else 0\n u = u + 1 if grid[j][i] != 0 else 0\n d = d + 1 if grid[n-j-1][i] != 0 else 0\n \n grid[i][j] = min(grid[i][j], l)\n grid[i][n-j-1] = min(grid[i][n-j-1], r)\n grid[j][i] = min(grid[j][i], u)\n grid[n-j-1][i] = min(grid[n-j-1][i], d)\n```\nWe use another loop with j to traverse through each cell in the row or column. For each cell:\n\nIf the cell isn\'t blocked (i.e., it\'s not a mine), we increment the corresponding counter.\nIf the cell is blocked (i.e., it\'s a mine), we reset the counter to 0 because we can\'t pass through mines.\nWe then update the cell\'s value in the grid to be the minimum of its current value and the counter. This is because the cell\'s value represents the maximum size of the plus sign for which it can be a center, so we\'re continuously refining this estimate.\n\n```\nreturn max(map(max, grid))\n```\n\nFinally, after populating the entire grid with each cell\'s potential as a center of a plus sign, we determine the largest possible plus sign in the grid. This is done by finding the maximum value in the grid.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n grid = [[n] * n for _ in range(n)]\n \n for x, y in mines:\n grid[x][y] = 0\n\n for i in range(n):\n l, r, u, d = 0, 0, 0, 0\n for j in range(n):\n l = l + 1 if grid[i][j] != 0 else 0\n r = r + 1 if grid[i][n-j-1] != 0 else 0\n u = u + 1 if grid[j][i] != 0 else 0\n d = d + 1 if grid[n-j-1][i] != 0 else 0\n \n grid[i][j] = min(grid[i][j], l)\n grid[i][n-j-1] = min(grid[i][n-j-1], r)\n grid[j][i] = min(grid[j][i], u)\n grid[n-j-1][i] = min(grid[n-j-1][i], d)\n \n return max(map(max, grid))\n\n```
3
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
764: Memory Beats 91.40%, Solution with step by step explanation
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ngrid = [[n] * n for _ in range(n)]\n```\nWe initialize a grid with all values set to n. Why? Because in the best case, if a cell isn\'t blocked (by a mine), its maximum potential reach in any direction is n (from one edge to another).\n\n```\nfor x, y in mines:\n grid[x][y] = 0\n```\n\nWe then loop through the mines and set those cells to 0 in the grid, as they can\'t be a part of any plus sign.\n\nWe need to determine how far each cell can reach in every direction. This will let us determine the size of the plus sign for which the cell can be a center.\n\n```\nfor i in range(n):\n l, r, u, d = 0, 0, 0, 0 \n```\n\nWe begin by iterating through each row and column of the matrix using i. For each row and column, we initialize counters for all four directions (left, right, up, down).\n\n```\n for j in range(n):\n l = l + 1 if grid[i][j] != 0 else 0\n r = r + 1 if grid[i][n-j-1] != 0 else 0\n u = u + 1 if grid[j][i] != 0 else 0\n d = d + 1 if grid[n-j-1][i] != 0 else 0\n \n grid[i][j] = min(grid[i][j], l)\n grid[i][n-j-1] = min(grid[i][n-j-1], r)\n grid[j][i] = min(grid[j][i], u)\n grid[n-j-1][i] = min(grid[n-j-1][i], d)\n```\nWe use another loop with j to traverse through each cell in the row or column. For each cell:\n\nIf the cell isn\'t blocked (i.e., it\'s not a mine), we increment the corresponding counter.\nIf the cell is blocked (i.e., it\'s a mine), we reset the counter to 0 because we can\'t pass through mines.\nWe then update the cell\'s value in the grid to be the minimum of its current value and the counter. This is because the cell\'s value represents the maximum size of the plus sign for which it can be a center, so we\'re continuously refining this estimate.\n\n```\nreturn max(map(max, grid))\n```\n\nFinally, after populating the entire grid with each cell\'s potential as a center of a plus sign, we determine the largest possible plus sign in the grid. This is done by finding the maximum value in the grid.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n grid = [[n] * n for _ in range(n)]\n \n for x, y in mines:\n grid[x][y] = 0\n\n for i in range(n):\n l, r, u, d = 0, 0, 0, 0\n for j in range(n):\n l = l + 1 if grid[i][j] != 0 else 0\n r = r + 1 if grid[i][n-j-1] != 0 else 0\n u = u + 1 if grid[j][i] != 0 else 0\n d = d + 1 if grid[n-j-1][i] != 0 else 0\n \n grid[i][j] = min(grid[i][j], l)\n grid[i][n-j-1] = min(grid[i][n-j-1], r)\n grid[j][i] = min(grid[j][i], u)\n grid[n-j-1][i] = min(grid[n-j-1][i], d)\n \n return max(map(max, grid))\n\n```
3
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Python (Simple DP)
largest-plus-sign
0
1
# 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: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n, mines):\n dp, ans = [[0]*n for _ in range(n)], 0\n banned = {tuple(mine) for mine in mines}\n\n for i in range(n):\n count = 0\n for j in range(n):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = count\n\n count = 0\n for j in range(n-1,-1,-1):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n\n\n for j in range(n):\n count = 0\n for i in range(n):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n\n count = 0\n for i in range(n-1,-1,-1):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n ans = max(ans,dp[i][j])\n\n return ans\n\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n \n```
1
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
Python (Simple DP)
largest-plus-sign
0
1
# 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: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n, mines):\n dp, ans = [[0]*n for _ in range(n)], 0\n banned = {tuple(mine) for mine in mines}\n\n for i in range(n):\n count = 0\n for j in range(n):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = count\n\n count = 0\n for j in range(n-1,-1,-1):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n\n\n for j in range(n):\n count = 0\n for i in range(n):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n\n count = 0\n for i in range(n-1,-1,-1):\n count = count + 1 if (i,j) not in banned else 0\n dp[i][j] = min(dp[i][j],count)\n ans = max(ans,dp[i][j])\n\n return ans\n\n\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n \n```
1
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
[Python] Two concise loops. TC: O(n^2), SC: O(n^2)
largest-plus-sign
0
1
\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n mine_set = set([(x, y) for x, y in mines])\n row = lambda: [defaultdict(int) for _ in range(n)]\n dp = [row() for _ in range(n)]\n t, b, l, rt = \'t\', \'b\', \'l\', \'r\'\n res = 0\n\n for r in range(n):\n for c in range(n):\n if (r, c) in mine_set:\n continue\n\n dp[r][c][t] = 1 if r == 0 else 1 + dp[r - 1][c][t]\n dp[r][c][l] = 1 if c == 0 else 1 + dp[r][c - 1][l]\n\n for r in range(n - 1, -1, -1):\n for c in range(n - 1, -1, -1):\n if (r, c) in mine_set:\n continue\n\n dp[r][c][b] = 1 if r == n - 1 else 1 + dp[r + 1][c][b]\n dp[r][c][rt] = 1 if c == n - 1 else 1 + dp[r][c + 1][rt]\n\n res = max(res, min(dp[r][c][t], dp[r][c][b], dp[r][c][l], dp[r][c][rt]))\n\n return res\n```
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
[Python] Two concise loops. TC: O(n^2), SC: O(n^2)
largest-plus-sign
0
1
\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n mine_set = set([(x, y) for x, y in mines])\n row = lambda: [defaultdict(int) for _ in range(n)]\n dp = [row() for _ in range(n)]\n t, b, l, rt = \'t\', \'b\', \'l\', \'r\'\n res = 0\n\n for r in range(n):\n for c in range(n):\n if (r, c) in mine_set:\n continue\n\n dp[r][c][t] = 1 if r == 0 else 1 + dp[r - 1][c][t]\n dp[r][c][l] = 1 if c == 0 else 1 + dp[r][c - 1][l]\n\n for r in range(n - 1, -1, -1):\n for c in range(n - 1, -1, -1):\n if (r, c) in mine_set:\n continue\n\n dp[r][c][b] = 1 if r == n - 1 else 1 + dp[r + 1][c][b]\n dp[r][c][rt] = 1 if c == n - 1 else 1 + dp[r][c + 1][rt]\n\n res = max(res, min(dp[r][c][t], dp[r][c][b], dp[r][c][l], dp[r][c][rt]))\n\n return res\n```
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Minimum Distance DP Explained! [Python3]
largest-plus-sign
0
1
# Intuition\n\nIf we know the minimum distance to either an edge or mine in the x direction for each cell and also the minimum distance to either an edge or mine in the y direction for each cell, we can solve the problem!\n\nWe can find these values using DP!\n\nSee the commented code below.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```python\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n # dp_x is minimum distance to mine or edge in x direction\n # dp_y is minimum distance to mine or edge in y direction\n # find the x,y with max of min of both \n dp_x = [[sys.maxsize] * (n + 2) for _ in range(n + 2)] # use -1 and n (assume mine exists at edge cells), so use n + 2\n dp_y = [row[:] for row in dp_x] # copy of dp_x\n for row in range(n): # set mines at edges of rows\n for col in [n, n+1]:\n dp_x[row][col] = 0\n dp_y[row][col] = 0\n for row in [n, n+1]: # set mines at edges of cols\n dp_x[row] = [0] * (n + 2)\n dp_y[row] = [0] * (n + 2)\n for row, col in mines: # init mines\n dp_x[row][col] = 0\n dp_y[row][col] = 0 \n for row in dp_x: # dp going right\n for col in range(n):\n row[col] = min(row[col], row[col - 1] + 1)\n for row in dp_x: # dp going left\n for col in range(n - 1, -1, -1):\n row[col] = min(row[col], row[col + 1] + 1)\n for col in range(n): # dp going down\n for row in range(n):\n dp_y[row][col] = min(dp_y[row][col], dp_y[row - 1][col] + 1)\n for col in range(n): # dp going up\n for row in range(n - 1, -1, -1):\n dp_y[row][col] = min(dp_y[row][col], dp_y[row + 1][col] + 1)\n max_plus = 0\n for row in range(n):\n for col in range(n):\n max_plus = max(max_plus, min(dp_x[row][col], dp_y[row][col]))\n return max_plus\n```
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
Minimum Distance DP Explained! [Python3]
largest-plus-sign
0
1
# Intuition\n\nIf we know the minimum distance to either an edge or mine in the x direction for each cell and also the minimum distance to either an edge or mine in the y direction for each cell, we can solve the problem!\n\nWe can find these values using DP!\n\nSee the commented code below.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```python\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n # dp_x is minimum distance to mine or edge in x direction\n # dp_y is minimum distance to mine or edge in y direction\n # find the x,y with max of min of both \n dp_x = [[sys.maxsize] * (n + 2) for _ in range(n + 2)] # use -1 and n (assume mine exists at edge cells), so use n + 2\n dp_y = [row[:] for row in dp_x] # copy of dp_x\n for row in range(n): # set mines at edges of rows\n for col in [n, n+1]:\n dp_x[row][col] = 0\n dp_y[row][col] = 0\n for row in [n, n+1]: # set mines at edges of cols\n dp_x[row] = [0] * (n + 2)\n dp_y[row] = [0] * (n + 2)\n for row, col in mines: # init mines\n dp_x[row][col] = 0\n dp_y[row][col] = 0 \n for row in dp_x: # dp going right\n for col in range(n):\n row[col] = min(row[col], row[col - 1] + 1)\n for row in dp_x: # dp going left\n for col in range(n - 1, -1, -1):\n row[col] = min(row[col], row[col + 1] + 1)\n for col in range(n): # dp going down\n for row in range(n):\n dp_y[row][col] = min(dp_y[row][col], dp_y[row - 1][col] + 1)\n for col in range(n): # dp going up\n for row in range(n - 1, -1, -1):\n dp_y[row][col] = min(dp_y[row][col], dp_y[row + 1][col] + 1)\n max_plus = 0\n for row in range(n):\n for col in range(n):\n max_plus = max(max_plus, min(dp_x[row][col], dp_y[row][col]))\n return max_plus\n```
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
DP with space optim. in single pass using nested loops with in-place matrix updates. (Explained)
largest-plus-sign
0
1
# 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: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n\n # we initialize the matrix with MAX possible size of the plus sign\n matrix = [[n] * n for _ in range(n)]\n for row, col in mines:\n matrix[row][col] = 0\n\n for row in range(n):\n right_length = 0\n down_length = 0\n left_length = 0\n up_length = 0\n\n for col in range(n):\n\n # we use col / ~col to calculate the number of \'1\'s in each horizontal direction\n matrix[row][col] = min(matrix[row][col], right_length := right_length + 1 if matrix[row][col] else 0)\n matrix[row][~col] = min(matrix[row][~col], left_length := left_length + 1 if matrix[row][~col] else 0)\n\n # we "swap" col and row to avoid an extra loop as this is an \'n x n\' matrix ==> no problem\n matrix[col][row] = min(matrix[col][row], down_length := down_length + 1 if matrix[col][row] else 0)\n matrix[~col][row] = min(matrix[~col][row], up_length := up_length + 1 if matrix[~col][row] else 0)\n\n # we us MAP to feed each row of the matrix into the MAX function and then calculate the MAX of those results\n return max(map(max, matrix))\n```
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ 1_'s contained in_ `grid`. If there is none, return `0`. An **axis-aligned plus sign** of `1`'s of order `k` has some center `grid[r][c] == 1` along with four arms of length `k - 1` going up, down, left, and right, and made of `1`'s. Note that there could be `0`'s or `1`'s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for `1`'s. **Example 1:** **Input:** n = 5, mines = \[\[4,2\]\] **Output:** 2 **Explanation:** In the above grid, the largest plus sign can only be of order 2. One of them is shown. **Example 2:** **Input:** n = 1, mines = \[\[0,0\]\] **Output:** 0 **Explanation:** There is no plus sign, so return 0. **Constraints:** * `1 <= n <= 500` * `1 <= mines.length <= 5000` * `0 <= xi, yi < n` * All the pairs `(xi, yi)` are **unique**.
null
DP with space optim. in single pass using nested loops with in-place matrix updates. (Explained)
largest-plus-sign
0
1
# 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: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n\n # we initialize the matrix with MAX possible size of the plus sign\n matrix = [[n] * n for _ in range(n)]\n for row, col in mines:\n matrix[row][col] = 0\n\n for row in range(n):\n right_length = 0\n down_length = 0\n left_length = 0\n up_length = 0\n\n for col in range(n):\n\n # we use col / ~col to calculate the number of \'1\'s in each horizontal direction\n matrix[row][col] = min(matrix[row][col], right_length := right_length + 1 if matrix[row][col] else 0)\n matrix[row][~col] = min(matrix[row][~col], left_length := left_length + 1 if matrix[row][~col] else 0)\n\n # we "swap" col and row to avoid an extra loop as this is an \'n x n\' matrix ==> no problem\n matrix[col][row] = min(matrix[col][row], down_length := down_length + 1 if matrix[col][row] else 0)\n matrix[~col][row] = min(matrix[~col][row], up_length := up_length + 1 if matrix[~col][row] else 0)\n\n # we us MAP to feed each row of the matrix into the MAX function and then calculate the MAX of those results\n return max(map(max, matrix))\n```
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Solution
couples-holding-hands
1
1
```C++ []\nclass UnionFind {\n public:\n UnionFind(int n) : count(n), id(n) {\n iota(begin(id), end(id), 0);\n }\n void union_(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n id[i] = j;\n --count;\n }\n int getCount() const {\n return count;\n }\n private:\n int count;\n vector<int> id;\n\n int find(int u) {\n return id[u] == u ? u : id[u] = find(id[u]);\n }\n};\nclass Solution {\n public:\n int minSwapsCouples(vector<int>& row) {\n const int n = row.size() / 2;\n UnionFind uf(n);\n\n for (int i = 0; i < n; ++i) {\n const int a = row[2 * i];\n const int b = row[2 * i + 1];\n uf.union_(a / 2, b / 2);\n }\n return n - uf.getCount();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n couple2seat = [0]* len(row)\n for i in range(len(row)):\n couple2seat[row[i]] = i\n parent = [0]* len(row)\n vis = [False]* len(row)\n ret = 0\n for i in range(len(row)):\n ptr = i\n n_people_on_cycle = 0\n while not vis[ptr]:\n if ptr % 2 == 0:\n parent[ptr] = self.get_couple(row[ptr+1])\n vis[ptr+1] = True\n else: # ptr % 2 == 1\n parent[ptr] = self.get_couple(row[ptr-1])\n vis[ptr-1] = True\n vis[ptr] = True\n ptr = couple2seat[parent[ptr]]\n n_people_on_cycle += 1\n ret += max(n_people_on_cycle - 1, 0)\n return ret\n \n def get_couple(self, a):\n if a % 2 == 0:\n return a + 1\n else:\n return a - 1\n```\n\n```Java []\nclass Solution {\n public int minSwapsCouples(int[] row) {\n int n = row.length;\n int[] pos = new int[n];\n \n for(int i=0; i<n; i++)\n pos[row[i]] = i;\n \n int ans = 0;\n \n for(int i=0; i<n; i += 2) {\n int actualPair = row[i] + (row[i] % 2 == 0 ? 1 : -1);\n int curPair = row[i+1];\n \n if( curPair != actualPair ) {\n swap(row, i+1, pos[actualPair]);\n\t\t\t\t\n swap(pos, curPair, actualPair);\n\t\t\t\t\n ans++;\n }\n }\n return ans;\n }\n private void swap(int[] arr, int i, int j) {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n```\n
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
765: Solution with step by step explanation
couples-holding-hands
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution uses the union-find data structure. Union-find helps in understanding the component or group to which an element belongs.\n\n```\ndef minSwapsCouples(self, row: List[int]) -> int:\n ...\n n = len(row) // 2\n parent = [i for i in range(n)]\n ...\n```\n\nHere, n denotes the total number of couples. We initialize the parent list such that each person is its own parent (or representative). This represents that initially, everyone is in their individual group.\n\n```\ndef find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])\n return parent[x]\n```\n\nThe find function returns the representative (or the leader) of the group to which x belongs. If x is not its own parent, we recursively find the parent of x.\n\n```\ndef union(x, y):\n rootX = find(x)\n rootY = find(y)\n if rootX != rootY:\n parent[rootX] = rootY\n```\n\nThe union function is responsible for merging two groups. We first find the leaders of the groups to which x and y belong. If they are different, we merge them by making rootX a child of rootY.\n\n```\nfor i in range(0, len(row), 2):\n union(row[i] // 2, row[i+1] // 2)\n```\n\nHere, we iterate through the row in pairs. For every pair of persons, we union their groups. The operation row[i] // 2 maps a person to its couple number. For example, person 0 and 1 will map to couple 0, person 2 and 3 will map to couple 1, and so on.\n\n```\ncount = sum([1 for i, x in enumerate(parent) if i == find(x)])\nreturn n - count\n```\n\nAfter performing all the unions, we count how many persons are still their own representative. This indicates the number of couples correctly seated. Since there are n couples in total, the number of swaps required will be n - count.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n \n def find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])\n return parent[x]\n \n def union(x, y):\n rootX = find(x)\n rootY = find(y)\n if rootX != rootY:\n parent[rootX] = rootY\n\n n = len(row) // 2\n parent = [i for i in range(n)]\n \n for i in range(0, len(row), 2):\n union(row[i] // 2, row[i+1] // 2)\n \n count = sum([1 for i, x in enumerate(parent) if i == find(x)])\n return n - count\n\n```
2
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
Simple Solution with proper comments | TC - O(n) | Without using Union, cyclic swapping
couples-holding-hands
0
1
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity -->\n<!-- - Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minSwapsCouples(self, nums: List[int]) -> int:\n # Creating the hashmap for the each element with values of its index in the nums list, \n # so that we can find the index of any element in O(1)\n idxmap = {x : i for i, x in enumerate(nums)}\n n = len(nums)\n count = 0\n \n for i in range(0, n, 2):\n # Partner element can be found out by taking the 1 xor of the current element\n # Pair are in the order (even, odd)\n # if current element is odd (assume 5) -> then its partner will be (current XOR 1) (which will be 4)\n # if current element is even (assume 8) -> then its partner will be (current XOR 1) (which will be 9)\n a = nums[i]\n b = a ^ 1\n \n # If next element is partner element then move forward\n if nums[i + 1] == b:\n continue\n \n # Otherwise swap the next element with the partner element using the index map\n # Finding the index of b\n idx_b = idxmap[b]\n \n # Updating the index of next element and b\n idxmap[nums[i + 1]] = idx_b\n idxmap[b] = i + 1\n \n # Swaping the next element and b\n nums[idx_b], nums[i + 1] = nums[i + 1], nums[idx_b]\n\n # Incrementing the count\n count += 1\n \n return count\n```
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
Number of connected components
couples-holding-hands
0
1
\n\n# Code\n```\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n n = len(row) \n """\n 1 node = 1 couple\n edge between two nodes mean that 1 swap should take place to make one of the node correct - that node will have correct pair .\n so the degree of a node will always be wither 0 or 2 \n if we take 2 nodes then , there will be either 2 edges between them , which means 1 swap will make both of them correct . \n if there is only one edge between two nodes then there must be other node also and this will always create a cycle and other case will not be the part of this graph .\n So the can be multiple components \n\n """\n nodes = n//2\n g = []\n indx = {}\n grp = 0\n for i in range(0 ,n , 2) :\n indx[row[i]] = grp\n indx[row[i+1]] = grp\n grp +=1\n\n \n for i in range(0 , n , 2) :\n x,y = row[i] , row[i+1]\n # z = min(x,y) \n # if(z != x): x,y = y,x\n\n if(x%2 == 0 and y != x+1 ) :\n g.append([indx[x] , indx[x+1]])\n if(y%2 == 0 and x != y+1 ) :\n g.append([indx[y] , indx[y+1]])\n print(g)\n parent = [i for i in range(nodes)]\n def findParent(x) :\n if parent[x] == x :\n return x \n return findParent(parent[x])\n \n for x,y in g :\n a = findParent(x)\n b = findParent(y) \n\n if(a != b) :\n parent[b] = a\n \n count = {} \n print(parent)\n for i in parent : \n x =findParent(i)\n if x in count :\n count[x] +=1 \n else:\n count[x] = 1\n ans = 0 \n for key in count :\n ans += (count[key] -1)\n return ans \n\n \n \n```
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
🐍 python, approach using cycle sort; O(N) time complexity
couples-holding-hands
0
1
# Approach\nlet\'s look at the following example:\n[[1,0],[2,5],[4,6],[3,7]]\nwhich after 2 swaps we have\n[[1,0],[2,3],[4,5],[6,7]]\nWe can easily notice that if the first element on the sublist is odd, the partner should be one value less and if it is even the partner should be one value more.\n\nNow, let\'s go back to the unsolved problem. \n[[1,0],[2,5],[4,6],[3,7]]\nWe start from the beginning, once we see 1, we know the partner should be 0 and in reality it is zero so we are good to move on.\n[[1,0],[2,5],[4,6],[3,7]]\nThen we see 2, which the partner should be 3 but in reality is 5. So we look for 3 to swap 3 with 5\n[[1,0],[2,3],[4,6],[5,7]]\nThe same step for the partner of 4 which is 5. So we swap 6 and 5.\n\nLast but not least, to make the loop up faster, we create a hashmap. \n\n\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n# Code\n```\nclass Solution:\n def minSwapsCouples(self, nums: List[int]) -> int:\n dic = dict()\n for i in range(len(nums)):\n dic[nums[i]] = i\n\n count = 0\n for i in range(0,len(nums),2):\n if nums[i]%2==0:\n partener = nums[i]+1\n else:\n partener = nums[i]-1\n\n stranger = nums[i+1]\n if stranger!=partener:\n nums[i+1], nums[dic[partener]] = partener, stranger\n dic[partener], dic[stranger] = i+1, dic[partener]\n count+=1\n return count\n```
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
766: Beats 91.88%, Solution with step by step explanation
toeplitz-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nfor i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n```\nWe use two nested loops to iterate over the matrix. We start from 1 because the topmost row and leftmost column don\'t have a top-left neighbor to compare with.\n\n```\nif matrix[i][j] != matrix[i-1][j-1]:\n return False\n```\n\nFor each cell (i, j), we compare its value with the cell (i-1, j-1). If they are not equal, then the matrix cannot be a Toeplitz matrix, so we return False.\n\n```\nreturn True\n```\n\nIf the function hasn\'t returned False during the matrix traversal, it means all diagonals from top-left to bottom-right have the same elements. Thus, we can conclude that the matrix is a Toeplitz matrix, so we return True.\n\n# Complexity\n- Time complexity:\nO(m * n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n if matrix[i][j] != matrix[i-1][j-1]:\n return False\n return True\n\n```
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Python Solution || Simple Approach
toeplitz-matrix
0
1
class Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n \n for i in range(0, len(matrix)-1):\n \n for j in range(0, len(matrix[i])-1):\n \n if matrix[i][j] != matrix[i+1][j+1]:\n return False\n \n \n return True
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Simplest Python Solution || O(n^2)
toeplitz-matrix
0
1
# 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:\nO(n^2)\n\n- Space complexity:\n(1)\n\n# Code\n```\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n row = len(matrix)\n col = len(matrix[0])\n for i in range(col):\n first = matrix[0][i]\n j = i \n r = 0\n while j<col and r<row:\n if first != matrix[r][j]:\n return False\n j += 1\n r += 1\n \n for i in range(1,row):\n first = matrix[i][0]\n j = 0 \n r = i\n while j<col and r<row:\n if first != matrix[r][j]:\n return False\n j += 1\n r += 1\n return True\n\n```
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
SIMPLE SOLUTION
toeplitz-matrix
0
1
```\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n m=len(matrix)\n n=len(matrix[0])\n for i in range(m-2,-1,-1):\n curr=matrix[i][0]\n row=i\n col=0\n while row<m and col<n:\n if curr!=matrix[row][col]:\n return False\n row+=1\n col+=1\n for i in range(1,n):\n curr=matrix[0][i]\n row=0\n col=i\n while row<m and col<n:\n if curr!=matrix[row][col]:\n return False\n row+=1\n col+=1\n return True\n```
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above grid, the diagonals are: "\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ". In each diagonal all elements are the same, so the answer is True. **Example 2:** **Input:** matrix = \[\[1,2\],\[2,2\]\] **Output:** false **Explanation:** The diagonal "\[1, 2\] " has different elements. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 20` * `0 <= matrix[i][j] <= 99` **Follow up:** * What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? * What if the `matrix` is so large that you can only load up a partial row into the memory at once?
null
Python 3 || Runtime 26ms
reorganize-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n\n # Create a hashmap to store frequency of words\n hashm={}\n res=""\n for i in s:\n if i in hashm:\n hashm[i]+=1\n else:\n hashm[i]=1\n\n # Maxheap\n h=[]\n for i in hashm:\n heapq.heappush(h,[-hashm[i],i])\n\n # Basically following a greedy approach where we keep on adding higher frequcny chars to result string.\n \n # Intilaaly add most repeated charecter to result\n temp=heapq.heappop(h)\n res+=temp[1]\n if temp[0]+1:\n heapq.heappush(h,[temp[0]+1,temp[1]])\n\n while h:\n\n # Check if last charecter of result matches firstchar in heap i.e; highest count one\n\n # If it doesnt match add to result\n if res[-1]!=h[0][1]:\n temp=heapq.heappop(h)\n res+=temp[1]\n if temp[0]+1:\n heapq.heappush(h,[temp[0]+1,temp[1]])\n else:\n\n # This means there is only one char in heap and this matches with last char in result i.e; we get two same chars even after appending to result. So return empty string\n if len(h)==1:\n return ""\n\n # Else, add second elemnt in heap to result \n else:\n temp1=heapq.heappop(h)\n temp2=heapq.heappop(h)\n res+=temp2[1]\n if temp2[0]+1:\n heapq.heappush(h,[temp2[0]+1,temp2[1]])\n heapq.heappush(h,[temp1[0],temp1[1]])\n \n return res\n\n\n \n\n\n \n\n \n```
2
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python 3 || Runtime 26ms
reorganize-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n\n # Create a hashmap to store frequency of words\n hashm={}\n res=""\n for i in s:\n if i in hashm:\n hashm[i]+=1\n else:\n hashm[i]=1\n\n # Maxheap\n h=[]\n for i in hashm:\n heapq.heappush(h,[-hashm[i],i])\n\n # Basically following a greedy approach where we keep on adding higher frequcny chars to result string.\n \n # Intilaaly add most repeated charecter to result\n temp=heapq.heappop(h)\n res+=temp[1]\n if temp[0]+1:\n heapq.heappush(h,[temp[0]+1,temp[1]])\n\n while h:\n\n # Check if last charecter of result matches firstchar in heap i.e; highest count one\n\n # If it doesnt match add to result\n if res[-1]!=h[0][1]:\n temp=heapq.heappop(h)\n res+=temp[1]\n if temp[0]+1:\n heapq.heappush(h,[temp[0]+1,temp[1]])\n else:\n\n # This means there is only one char in heap and this matches with last char in result i.e; we get two same chars even after appending to result. So return empty string\n if len(h)==1:\n return ""\n\n # Else, add second elemnt in heap to result \n else:\n temp1=heapq.heappop(h)\n temp2=heapq.heappop(h)\n res+=temp2[1]\n if temp2[0]+1:\n heapq.heappush(h,[temp2[0]+1,temp2[1]])\n heapq.heappush(h,[temp1[0],temp1[1]])\n \n return res\n\n\n \n\n\n \n\n \n```
2
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
easy solution
reorganize-string
0
1
\n \n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt,char] for char,cnt in count.items()]\n heapq.heapify(maxHeap)\n\n\n prev,res = None,""\n res = ""\n while prev or maxHeap:\n if prev and not maxHeap:\n return ""\n\n # most frequent char\n cnt,char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap,prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt,char]\n\n return res\n\n# O(nlogn)\n```
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
easy solution
reorganize-string
0
1
\n \n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt,char] for char,cnt in count.items()]\n heapq.heapify(maxHeap)\n\n\n prev,res = None,""\n res = ""\n while prev or maxHeap:\n if prev and not maxHeap:\n return ""\n\n # most frequent char\n cnt,char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap,prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt,char]\n\n return res\n\n# O(nlogn)\n```
1
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
Python Solution Best Approach Reorganize String
reorganize-string
0
1
```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n dic = {}\n for i in s:\n dic[i] = dic.get(i,0)+1 \n max_key = None\n max_value = None\n\n for key, value in dic.items():\n if max_value is None or value > max_value:\n max_value = value\n max_key = key\n if max_value > ((len(s)+1)//2):\n return ""\n\n res = (len(s)) * [\'\']\n idx = 0\n while(max_value):\n res[idx] = max_key\n idx+=2\n max_value-=1\n\n for key, value in dic.items():\n if key not in res:\n val = value\n while(value):\n if idx >= len(s):\n idx=1\n res[idx] = key\n idx+=2\n value-=1\n return "".join(res)\n \n \n```
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python Solution Best Approach Reorganize String
reorganize-string
0
1
```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n dic = {}\n for i in s:\n dic[i] = dic.get(i,0)+1 \n max_key = None\n max_value = None\n\n for key, value in dic.items():\n if max_value is None or value > max_value:\n max_value = value\n max_key = key\n if max_value > ((len(s)+1)//2):\n return ""\n\n res = (len(s)) * [\'\']\n idx = 0\n while(max_value):\n res[idx] = max_key\n idx+=2\n max_value-=1\n\n for key, value in dic.items():\n if key not in res:\n val = value\n while(value):\n if idx >= len(s):\n idx=1\n res[idx] = key\n idx+=2\n value-=1\n return "".join(res)\n \n \n```
1
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
✅ 100% 2-Approaches Priority Queue & Sort
reorganize-string
1
1
# Problem Understanding\n\nIn the "767. Reorganize String" problem, we are given a string `s` consisting of lowercase English letters. The task is to rearrange the string such that no two adjacent characters are the same. If it\'s not possible to do so, we return an empty string.\n\nFor instance, given the input "aab," the output could be "aba"\n\n---\n\n# Live Coding & Explenation\n## Priority Queue\nhttps://youtu.be/69ViY9Trto8\n\n\n- [Priority Queue in Python \uD83D\uDC0D](https://youtu.be/69ViY9Trto8)\n- [Array Sort in Python \uD83D\uDC0D](https://youtu.be/eCBOPJNE4to)\n\n\n---\n\n## Approach 1: Priority Queue Approach\n\n### Objective\nTo solve the "767. Reorganize String" problem, the priority queue approach leverages a max heap to maintain the frequency of each character. By doing so, we can alternate the most frequent characters with the remaining ones to ensure no adjacent characters are the same.\n\n### Key Data Structures\n- **Max Heap**: Used for storing characters sorted by their frequency in descending order.\n\n### Enhanced Breakdown\n\n1. **Initialization**:\n - Count the frequency of each character in the string.\n - Populate the max heap with these frequencies.\n \n2. **Processing Each Character**:\n - Pop the top two characters from the max heap (i.e., the ones with the highest frequency).\n - Append these two characters to the result string.\n - Decrement their frequencies and re-insert them back into the max heap.\n - If only one character remains in the heap, make sure it doesn\'t exceed half of the string length, otherwise, return an empty string.\n\n3. **Wrap-up**:\n - If there\'s a single remaining character with a frequency of 1, append it to the result.\n - Join all the characters to return the final reorganized string.\n\n## Example:\n\nGiven the input "aab":\n\n- Max heap after initialization: `[(-2, \'a\'), (-1, \'b\')]`\n- Result after first iteration: "ab"\n- Wrap-up: Result is "aba"\n\n---\n\n## Approach 2: Array Sort Approach\n\n### Objective\nIn this approach, we sort the array of characters by their frequency and then place them at alternate positions in the result string. This ensures that no two adjacent characters are the same.\n\n### Key Data Structures\n- **Array**: Used for storing characters sorted by frequency for easy access.\n\n### Enhanced Breakdown\n\n1. **Initialization**:\n - Count the frequency of each character in the string.\n - Sort the array of characters based on their frequency in descending order.\n \n2. **Processing Each Character**:\n - Start placing the most frequent characters first. Place them at even indices (0, 2, 4, ...).\n - Next, place the remaining characters at the odd indices (1, 3, 5, ...).\n - During this process, if the most frequent character appears more than $$(\\text{length of string} + 1) / 2$$ times, return an empty string as reorganization is not possible.\n\n3. **Wrap-up**:\n - Combine all the individual characters to form the final reorganized string.\n\n## Example:\n\nGiven the input "aab":\n\n- Sorted array after initialization: `[\'a\', \'a\', \'b\']`\n- Result after processing: "aba"\n\n---\n\n# Complexity:\n\n## Time Complexity:\n\n1. **Priority Queue Approach: $$ O(n \\log k) $$**\n\n - $$ O(n) $$ for counting the frequency of each character in the string. Here, $$ n $$ is the length of the string.\n - $$ O(k \\log k) $$ for building the max heap, where $$ k $$ is the number of unique characters in the string.\n - The heap operations (insertion and deletion) would require $$ \\log k $$ time each. In the worst-case scenario, you would be doing these operations $$ n $$ times (once for each character in the string).\n \n\n2. **Array Sort Approach: $$ O(n + k \\log k) $$**\n\n - $$ O(n) $$ for counting the frequency of each character in the string.\n - $$ O(k \\log k) $$ for sorting the unique characters by their frequency.\n - $$ O(n) $$ for placing the characters into the new string. Here, you iterate through each character, inserting them into their respective places in the result string.\n\n---\n\n## Space Complexity:\n\n1. **Both approaches: $$ O(n) $$**\n\n - For both approaches, you would need an additional data structure (either a max heap or an array) to store the characters and their frequencies. \n - In the Priority Queue Approach, the heap would contain at most $$ k $$ elements (unique characters), and the result string would contain $$ n $$ characters.\n - In the Array Sort Approach, the sorted array and result string would also contain $$ n $$ characters.\n\n---\n\n# Performance:\n\n## Priority Queue\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-----------|--------------|------------------|-------------|-----------------|\n| Go | 0 | 100% | 2.2 | 60.78% |\n| Rust | 1 | 83.33% | 2 | 100% |\n| C++ | 4 | 38.45% | 6.3 | 46.7% |\n| Java | 6 | 35.10% | 40.6 | 67.8% |\n| Python3 | 31 | 98.6% | 16.3 | 46.15% |\n| JavaScript| 57 | 91.34% | 44.7 | 63.78% |\n| C# | 79 | 62.86% | 37.1 | 85.71% |\n\n![p1.png](https://assets.leetcode.com/users/images/62920fbe-6643-4954-9ec5-05f9cf487dca_1692751904.5525727.png)\n\n\n## Array Sort\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-----------|--------------|------------------|-------------|-----------------|\n| C++ | 0 | 100% | 6.4 | 21.22% |\n| Go | 1 | 72.55% | 2 | 70.59% |\n| Rust | 1 | 83.33% | 2.1 | 16.67% |\n| Java | 3 | 68.33% | 40.5 | 87.22% |\n| Python3 | 39 | 85.26% | 16.3 | 46.15% |\n| JavaScript| 49 | 99.21% | 44 | 79.53% |\n| C# | 81 | 60% | 37.2 | 82.86% |\n\n![p2.png](https://assets.leetcode.com/users/images/ea330341-4766-4659-a1b8-4c1e84c1b357_1692751910.8446956.png)\n\n\n# Code Priority Queue\n``` Python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n freq_map = {}\n for char in s:\n freq_map[char] = freq_map.get(char, 0) + 1\n \n max_heap = [(-freq, char) for char, freq in freq_map.items()]\n heapq.heapify(max_heap)\n \n res = []\n \n while len(max_heap) >= 2:\n freq1, char1 = heapq.heappop(max_heap)\n freq2, char2 = heapq.heappop(max_heap)\n \n res.extend([char1, char2])\n \n if freq1 + 1 < 0:\n heapq.heappush(max_heap, (freq1 + 1, char1))\n if freq2 + 1 < 0:\n heapq.heappush(max_heap, (freq2 + 1, char2))\n \n if max_heap:\n freq, char = heapq.heappop(max_heap)\n if -freq > 1:\n return ""\n res.append(char)\n \n return "".join(res)\n\n```\n``` Rust []\nuse std::collections::BinaryHeap;\nuse std::collections::HashMap;\nuse std::cmp::Reverse;\n\nimpl Solution {\n pub fn reorganize_string(s: String) -> String {\n let mut freq_map = HashMap::new();\n for c in s.chars() {\n *freq_map.entry(c).or_insert(0) += 1;\n }\n \n let mut max_heap: BinaryHeap<(i32, char)> = BinaryHeap::new();\n for (&ch, &freq) in freq_map.iter() {\n max_heap.push((freq, ch));\n }\n \n let mut res = Vec::new();\n while max_heap.len() >= 2 {\n let (freq1, char1) = max_heap.pop().unwrap();\n let (freq2, char2) = max_heap.pop().unwrap();\n \n res.push(char1);\n res.push(char2);\n \n if freq1 > 1 { max_heap.push((freq1 - 1, char1)); }\n if freq2 > 1 { max_heap.push((freq2 - 1, char2)); }\n }\n \n if let Some((freq, ch)) = max_heap.pop() {\n if freq > 1 {\n return "".to_string();\n }\n res.push(ch);\n }\n \n let result: String = res.into_iter().collect();\n result\n}\n}\n```\n``` Go []\nimport (\n\t"container/heap"\n\t"strings"\n)\n\ntype CharFreq struct {\n\tchar rune\n\tcount int\n}\n\ntype MaxHeap []CharFreq\n\nfunc (h MaxHeap) Len() int { return len(h) }\nfunc (h MaxHeap) Less(i, j int) bool { return h[i].count > h[j].count }\nfunc (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\t*h = append(*h, x.(CharFreq))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\nfunc reorganizeString(s string) string {\n\tfreqMap := make(map[rune]int)\n\tfor _, c := range s {\n\t\tfreqMap[c]++\n\t}\n\n\tmaxHeap := &MaxHeap{}\n\theap.Init(maxHeap)\n\tfor c, freq := range freqMap {\n\t\theap.Push(maxHeap, CharFreq{c, freq})\n\t}\n\n\tvar res strings.Builder\n\tfor maxHeap.Len() >= 2 {\n\t\tcharFreq1 := heap.Pop(maxHeap).(CharFreq)\n\t\tcharFreq2 := heap.Pop(maxHeap).(CharFreq)\n\n\t\tres.WriteRune(charFreq1.char)\n\t\tres.WriteRune(charFreq2.char)\n\n\t\tif charFreq1.count > 1 {\n\t\t\theap.Push(maxHeap, CharFreq{charFreq1.char, charFreq1.count - 1})\n\t\t}\n\t\tif charFreq2.count > 1 {\n\t\t\theap.Push(maxHeap, CharFreq{charFreq2.char, charFreq2.count - 1})\n\t\t}\n\t}\n\n\tif maxHeap.Len() > 0 {\n\t\tlastFreq := heap.Pop(maxHeap).(CharFreq)\n\t\tif lastFreq.count > 1 {\n\t\t\treturn ""\n\t\t}\n\t\tres.WriteRune(lastFreq.char)\n\t}\n\n\treturn res.String()\n}\n```\n``` C++ []\nclass Solution {\npublic:\n string reorganizeString(string s) {\n unordered_map<char, int> freq_map;\n for (char c : s) {\n freq_map[c]++;\n }\n\n priority_queue<pair<int, char>> max_heap;\n for (auto &[ch, freq] : freq_map) {\n max_heap.push({freq, ch});\n }\n\n string res;\n while (max_heap.size() >= 2) {\n auto [freq1, char1] = max_heap.top(); max_heap.pop();\n auto [freq2, char2] = max_heap.top(); max_heap.pop();\n\n res += char1;\n res += char2;\n\n if (--freq1 > 0) max_heap.push({freq1, char1});\n if (--freq2 > 0) max_heap.push({freq2, char2});\n }\n\n if (!max_heap.empty()) {\n auto [freq, ch] = max_heap.top();\n if (freq > 1) return "";\n res += ch;\n }\n\n return res;\n }\n};\n```\n``` Java []\npublic class Solution {\n public String reorganizeString(String s) {\n HashMap<Character, Integer> freqMap = new HashMap<>();\n for (char c : s.toCharArray()) {\n freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);\n }\n\n PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> freqMap.get(b) - freqMap.get(a));\n maxHeap.addAll(freqMap.keySet());\n\n StringBuilder res = new StringBuilder();\n while (maxHeap.size() >= 2) {\n char char1 = maxHeap.poll();\n char char2 = maxHeap.poll();\n\n res.append(char1);\n res.append(char2);\n\n freqMap.put(char1, freqMap.get(char1) - 1);\n freqMap.put(char2, freqMap.get(char2) - 1);\n\n if (freqMap.get(char1) > 0) maxHeap.add(char1);\n if (freqMap.get(char2) > 0) maxHeap.add(char2);\n }\n\n if (!maxHeap.isEmpty()) {\n char ch = maxHeap.poll();\n if (freqMap.get(ch) > 1) return "";\n res.append(ch);\n }\n\n return res.toString();\n }\n}\n```\n``` C# []\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> freqMap = new Dictionary<char, int>();\n foreach (char c in s) {\n if (!freqMap.ContainsKey(c)) freqMap[c] = 0;\n freqMap[c]++;\n }\n\n var maxHeap = new SortedSet<(int, char)>();\n foreach (var kvp in freqMap) {\n maxHeap.Add((kvp.Value, kvp.Key));\n }\n\n List<char> res = new List<char>();\n while (maxHeap.Count >= 2) {\n var elem1 = maxHeap.Max; maxHeap.Remove(elem1);\n var elem2 = maxHeap.Max; maxHeap.Remove(elem2);\n\n res.Add(elem1.Item2);\n res.Add(elem2.Item2);\n\n if (--elem1.Item1 > 0) maxHeap.Add(elem1);\n if (--elem2.Item1 > 0) maxHeap.Add(elem2);\n }\n\n if (maxHeap.Count > 0) {\n var elem = maxHeap.Max;\n if (elem.Item1 > 1) return "";\n res.Add(elem.Item2);\n }\n\n return new string(res.ToArray());\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar reorganizeString = function(s) {\n const freqMap = {};\n for (const c of s) {\n freqMap[c] = (freqMap[c] || 0) + 1;\n }\n\n const maxHeap = [...Object.keys(freqMap)].sort((a, b) => freqMap[b] - freqMap[a]);\n\n let res = "";\n while (maxHeap.length >= 2) {\n const char1 = maxHeap.shift();\n const char2 = maxHeap.shift();\n\n res += char1;\n res += char2;\n\n if (--freqMap[char1] > 0) maxHeap.push(char1);\n if (--freqMap[char2] > 0) maxHeap.push(char2);\n\n maxHeap.sort((a, b) => freqMap[b] - freqMap[a]);\n }\n\n if (maxHeap.length) {\n const char = maxHeap[0];\n if (freqMap[char] > 1) return "";\n res += char;\n }\n\n return res;\n}\n```\n\n# Code Array Sort\n``` Python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n freq_map = {}\n for char in s:\n freq_map[char] = freq_map.get(char, 0) + 1\n \n sorted_chars = sorted(freq_map.keys(), key=lambda x: freq_map[x], reverse=True)\n \n if freq_map[sorted_chars[0]] > (len(s) + 1) // 2:\n return ""\n \n res = [None] * len(s)\n \n i = 0\n for char in sorted_chars:\n for _ in range(freq_map[char]):\n if i >= len(s):\n i = 1\n res[i] = char\n i += 2\n \n return "".join(res)\n```\n``` Rust []\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn reorganize_string(s: String) -> String {\n let mut freq_map: HashMap<char, usize> = HashMap::new();\n for c in s.chars() {\n *freq_map.entry(c).or_insert(0) += 1;\n }\n\n let mut sorted_chars: Vec<char> = freq_map.keys().cloned().collect();\n sorted_chars.sort_by_key(|&c| std::cmp::Reverse(freq_map[&c]));\n\n if freq_map[&sorted_chars[0]] > (s.len() + 1) / 2 {\n return "".to_string();\n }\n\n let mut res = vec![\' \'; s.len()];\n let mut i = 0;\n for &c in sorted_chars.iter() {\n for _ in 0..freq_map[&c] {\n if i >= s.len() {\n i = 1;\n }\n res[i] = c;\n i += 2;\n }\n }\n\n res.iter().collect()\n }\n}\n```\n``` Go []\nimport "strings"\n\nfunc reorganizeString(s string) string {\n freqMap := make(map[rune]int)\n for _, c := range s {\n freqMap[c]++\n }\n\n var sortedChars []rune\n for ch := range freqMap {\n sortedChars = append(sortedChars, ch)\n }\n\n sort.Slice(sortedChars, func(i, j int) bool {\n return freqMap[sortedChars[i]] > freqMap[sortedChars[j]]\n })\n\n if freqMap[sortedChars[0]] > (len(s)+1)/2 {\n return ""\n }\n\n res := make([]rune, len(s))\n i := 0\n for _, ch := range sortedChars {\n for j := 0; j < freqMap[ch]; j++ {\n if i >= len(s) {\n i = 1\n }\n res[i] = ch\n i += 2\n }\n }\n\n return string(res)\n}\n```\n``` C++ []\nclass Solution {\npublic:\n string reorganizeString(std::string s) {\n std::unordered_map<char, int> freq_map;\n for (char c : s) {\n freq_map[c]++;\n }\n\n std::vector<char> sorted_chars;\n for (auto& pair : freq_map) {\n sorted_chars.push_back(pair.first);\n }\n\n std::sort(sorted_chars.begin(), sorted_chars.end(), [&](char a, char b) {\n return freq_map[a] > freq_map[b];\n });\n\n if (freq_map[sorted_chars[0]] > (s.length() + 1) / 2) {\n return "";\n }\n\n std::string res(s.length(), \' \');\n int i = 0;\n for (char c : sorted_chars) {\n for (int j = 0; j < freq_map[c]; ++j) {\n if (i >= s.length()) {\n i = 1;\n }\n res[i] = c;\n i += 2;\n }\n }\n\n return res;\n}\n};\n```\n``` Java []\npublic class Solution {\n public String reorganizeString(String s) {\n HashMap<Character, Integer> freqMap = new HashMap<>();\n for (char c : s.toCharArray()) {\n freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);\n }\n\n PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> freqMap.get(b) - freqMap.get(a));\n maxHeap.addAll(freqMap.keySet());\n\n if (freqMap.get(maxHeap.peek()) > (s.length() + 1) / 2) {\n return "";\n }\n\n StringBuilder res = new StringBuilder();\n char[] result = new char[s.length()];\n int i = 0;\n while (!maxHeap.isEmpty()) {\n char c = maxHeap.poll();\n for (int j = 0; j < freqMap.get(c); j++) {\n if (i >= s.length()) i = 1;\n result[i] = c;\n i += 2;\n }\n }\n\n return new String(result);\n }\n}\n```\n``` C# []\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> freqMap = new Dictionary<char, int>();\n foreach (char c in s) {\n if (!freqMap.ContainsKey(c)) freqMap[c] = 0;\n freqMap[c]++;\n }\n\n List<char> sortedChars = new List<char>(freqMap.Keys);\n sortedChars.Sort((a, b) => freqMap[b].CompareTo(freqMap[a]));\n\n if (freqMap[sortedChars[0]] > (s.Length + 1) / 2) return "";\n\n char[] res = new char[s.Length];\n int i = 0;\n foreach (char c in sortedChars) {\n for (int j = 0; j < freqMap[c]; j++) {\n if (i >= s.Length) i = 1;\n res[i] = c;\n i += 2;\n }\n }\n\n return new string(res);\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar reorganizeString = function(s) {\n const freqMap = {};\n for (const c of s) {\n freqMap[c] = (freqMap[c] || 0) + 1;\n }\n\n const sortedChars = Object.keys(freqMap).sort((a, b) => freqMap[b] - freqMap[a]);\n\n if (freqMap[sortedChars[0]] > Math.floor((s.length + 1) / 2)) {\n return "";\n }\n\n const res = Array(s.length).fill(null);\n let i = 0;\n for (const c of sortedChars) {\n for (let j = 0; j < freqMap[c]; j++) {\n if (i >= s.length) i = 1;\n res[i] = c;\n i += 2;\n }\n }\n\n return res.join(\'\');\n}\n```\n\n# Live Coding & Explenation\n## Array Sort\n\nhttps://youtu.be/eCBOPJNE4to\n\nWhether you\'re prepping for interviews or just love solving algorithmic challenges, understanding different approaches to problem-solving will sharpen your coding skills. \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB\n
106
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✅ 100% 2-Approaches Priority Queue & Sort
reorganize-string
1
1
# Problem Understanding\n\nIn the "767. Reorganize String" problem, we are given a string `s` consisting of lowercase English letters. The task is to rearrange the string such that no two adjacent characters are the same. If it\'s not possible to do so, we return an empty string.\n\nFor instance, given the input "aab," the output could be "aba"\n\n---\n\n# Live Coding & Explenation\n## Priority Queue\nhttps://youtu.be/69ViY9Trto8\n\n\n- [Priority Queue in Python \uD83D\uDC0D](https://youtu.be/69ViY9Trto8)\n- [Array Sort in Python \uD83D\uDC0D](https://youtu.be/eCBOPJNE4to)\n\n\n---\n\n## Approach 1: Priority Queue Approach\n\n### Objective\nTo solve the "767. Reorganize String" problem, the priority queue approach leverages a max heap to maintain the frequency of each character. By doing so, we can alternate the most frequent characters with the remaining ones to ensure no adjacent characters are the same.\n\n### Key Data Structures\n- **Max Heap**: Used for storing characters sorted by their frequency in descending order.\n\n### Enhanced Breakdown\n\n1. **Initialization**:\n - Count the frequency of each character in the string.\n - Populate the max heap with these frequencies.\n \n2. **Processing Each Character**:\n - Pop the top two characters from the max heap (i.e., the ones with the highest frequency).\n - Append these two characters to the result string.\n - Decrement their frequencies and re-insert them back into the max heap.\n - If only one character remains in the heap, make sure it doesn\'t exceed half of the string length, otherwise, return an empty string.\n\n3. **Wrap-up**:\n - If there\'s a single remaining character with a frequency of 1, append it to the result.\n - Join all the characters to return the final reorganized string.\n\n## Example:\n\nGiven the input "aab":\n\n- Max heap after initialization: `[(-2, \'a\'), (-1, \'b\')]`\n- Result after first iteration: "ab"\n- Wrap-up: Result is "aba"\n\n---\n\n## Approach 2: Array Sort Approach\n\n### Objective\nIn this approach, we sort the array of characters by their frequency and then place them at alternate positions in the result string. This ensures that no two adjacent characters are the same.\n\n### Key Data Structures\n- **Array**: Used for storing characters sorted by frequency for easy access.\n\n### Enhanced Breakdown\n\n1. **Initialization**:\n - Count the frequency of each character in the string.\n - Sort the array of characters based on their frequency in descending order.\n \n2. **Processing Each Character**:\n - Start placing the most frequent characters first. Place them at even indices (0, 2, 4, ...).\n - Next, place the remaining characters at the odd indices (1, 3, 5, ...).\n - During this process, if the most frequent character appears more than $$(\\text{length of string} + 1) / 2$$ times, return an empty string as reorganization is not possible.\n\n3. **Wrap-up**:\n - Combine all the individual characters to form the final reorganized string.\n\n## Example:\n\nGiven the input "aab":\n\n- Sorted array after initialization: `[\'a\', \'a\', \'b\']`\n- Result after processing: "aba"\n\n---\n\n# Complexity:\n\n## Time Complexity:\n\n1. **Priority Queue Approach: $$ O(n \\log k) $$**\n\n - $$ O(n) $$ for counting the frequency of each character in the string. Here, $$ n $$ is the length of the string.\n - $$ O(k \\log k) $$ for building the max heap, where $$ k $$ is the number of unique characters in the string.\n - The heap operations (insertion and deletion) would require $$ \\log k $$ time each. In the worst-case scenario, you would be doing these operations $$ n $$ times (once for each character in the string).\n \n\n2. **Array Sort Approach: $$ O(n + k \\log k) $$**\n\n - $$ O(n) $$ for counting the frequency of each character in the string.\n - $$ O(k \\log k) $$ for sorting the unique characters by their frequency.\n - $$ O(n) $$ for placing the characters into the new string. Here, you iterate through each character, inserting them into their respective places in the result string.\n\n---\n\n## Space Complexity:\n\n1. **Both approaches: $$ O(n) $$**\n\n - For both approaches, you would need an additional data structure (either a max heap or an array) to store the characters and their frequencies. \n - In the Priority Queue Approach, the heap would contain at most $$ k $$ elements (unique characters), and the result string would contain $$ n $$ characters.\n - In the Array Sort Approach, the sorted array and result string would also contain $$ n $$ characters.\n\n---\n\n# Performance:\n\n## Priority Queue\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-----------|--------------|------------------|-------------|-----------------|\n| Go | 0 | 100% | 2.2 | 60.78% |\n| Rust | 1 | 83.33% | 2 | 100% |\n| C++ | 4 | 38.45% | 6.3 | 46.7% |\n| Java | 6 | 35.10% | 40.6 | 67.8% |\n| Python3 | 31 | 98.6% | 16.3 | 46.15% |\n| JavaScript| 57 | 91.34% | 44.7 | 63.78% |\n| C# | 79 | 62.86% | 37.1 | 85.71% |\n\n![p1.png](https://assets.leetcode.com/users/images/62920fbe-6643-4954-9ec5-05f9cf487dca_1692751904.5525727.png)\n\n\n## Array Sort\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-----------|--------------|------------------|-------------|-----------------|\n| C++ | 0 | 100% | 6.4 | 21.22% |\n| Go | 1 | 72.55% | 2 | 70.59% |\n| Rust | 1 | 83.33% | 2.1 | 16.67% |\n| Java | 3 | 68.33% | 40.5 | 87.22% |\n| Python3 | 39 | 85.26% | 16.3 | 46.15% |\n| JavaScript| 49 | 99.21% | 44 | 79.53% |\n| C# | 81 | 60% | 37.2 | 82.86% |\n\n![p2.png](https://assets.leetcode.com/users/images/ea330341-4766-4659-a1b8-4c1e84c1b357_1692751910.8446956.png)\n\n\n# Code Priority Queue\n``` Python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n freq_map = {}\n for char in s:\n freq_map[char] = freq_map.get(char, 0) + 1\n \n max_heap = [(-freq, char) for char, freq in freq_map.items()]\n heapq.heapify(max_heap)\n \n res = []\n \n while len(max_heap) >= 2:\n freq1, char1 = heapq.heappop(max_heap)\n freq2, char2 = heapq.heappop(max_heap)\n \n res.extend([char1, char2])\n \n if freq1 + 1 < 0:\n heapq.heappush(max_heap, (freq1 + 1, char1))\n if freq2 + 1 < 0:\n heapq.heappush(max_heap, (freq2 + 1, char2))\n \n if max_heap:\n freq, char = heapq.heappop(max_heap)\n if -freq > 1:\n return ""\n res.append(char)\n \n return "".join(res)\n\n```\n``` Rust []\nuse std::collections::BinaryHeap;\nuse std::collections::HashMap;\nuse std::cmp::Reverse;\n\nimpl Solution {\n pub fn reorganize_string(s: String) -> String {\n let mut freq_map = HashMap::new();\n for c in s.chars() {\n *freq_map.entry(c).or_insert(0) += 1;\n }\n \n let mut max_heap: BinaryHeap<(i32, char)> = BinaryHeap::new();\n for (&ch, &freq) in freq_map.iter() {\n max_heap.push((freq, ch));\n }\n \n let mut res = Vec::new();\n while max_heap.len() >= 2 {\n let (freq1, char1) = max_heap.pop().unwrap();\n let (freq2, char2) = max_heap.pop().unwrap();\n \n res.push(char1);\n res.push(char2);\n \n if freq1 > 1 { max_heap.push((freq1 - 1, char1)); }\n if freq2 > 1 { max_heap.push((freq2 - 1, char2)); }\n }\n \n if let Some((freq, ch)) = max_heap.pop() {\n if freq > 1 {\n return "".to_string();\n }\n res.push(ch);\n }\n \n let result: String = res.into_iter().collect();\n result\n}\n}\n```\n``` Go []\nimport (\n\t"container/heap"\n\t"strings"\n)\n\ntype CharFreq struct {\n\tchar rune\n\tcount int\n}\n\ntype MaxHeap []CharFreq\n\nfunc (h MaxHeap) Len() int { return len(h) }\nfunc (h MaxHeap) Less(i, j int) bool { return h[i].count > h[j].count }\nfunc (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *MaxHeap) Push(x interface{}) {\n\t*h = append(*h, x.(CharFreq))\n}\n\nfunc (h *MaxHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\nfunc reorganizeString(s string) string {\n\tfreqMap := make(map[rune]int)\n\tfor _, c := range s {\n\t\tfreqMap[c]++\n\t}\n\n\tmaxHeap := &MaxHeap{}\n\theap.Init(maxHeap)\n\tfor c, freq := range freqMap {\n\t\theap.Push(maxHeap, CharFreq{c, freq})\n\t}\n\n\tvar res strings.Builder\n\tfor maxHeap.Len() >= 2 {\n\t\tcharFreq1 := heap.Pop(maxHeap).(CharFreq)\n\t\tcharFreq2 := heap.Pop(maxHeap).(CharFreq)\n\n\t\tres.WriteRune(charFreq1.char)\n\t\tres.WriteRune(charFreq2.char)\n\n\t\tif charFreq1.count > 1 {\n\t\t\theap.Push(maxHeap, CharFreq{charFreq1.char, charFreq1.count - 1})\n\t\t}\n\t\tif charFreq2.count > 1 {\n\t\t\theap.Push(maxHeap, CharFreq{charFreq2.char, charFreq2.count - 1})\n\t\t}\n\t}\n\n\tif maxHeap.Len() > 0 {\n\t\tlastFreq := heap.Pop(maxHeap).(CharFreq)\n\t\tif lastFreq.count > 1 {\n\t\t\treturn ""\n\t\t}\n\t\tres.WriteRune(lastFreq.char)\n\t}\n\n\treturn res.String()\n}\n```\n``` C++ []\nclass Solution {\npublic:\n string reorganizeString(string s) {\n unordered_map<char, int> freq_map;\n for (char c : s) {\n freq_map[c]++;\n }\n\n priority_queue<pair<int, char>> max_heap;\n for (auto &[ch, freq] : freq_map) {\n max_heap.push({freq, ch});\n }\n\n string res;\n while (max_heap.size() >= 2) {\n auto [freq1, char1] = max_heap.top(); max_heap.pop();\n auto [freq2, char2] = max_heap.top(); max_heap.pop();\n\n res += char1;\n res += char2;\n\n if (--freq1 > 0) max_heap.push({freq1, char1});\n if (--freq2 > 0) max_heap.push({freq2, char2});\n }\n\n if (!max_heap.empty()) {\n auto [freq, ch] = max_heap.top();\n if (freq > 1) return "";\n res += ch;\n }\n\n return res;\n }\n};\n```\n``` Java []\npublic class Solution {\n public String reorganizeString(String s) {\n HashMap<Character, Integer> freqMap = new HashMap<>();\n for (char c : s.toCharArray()) {\n freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);\n }\n\n PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> freqMap.get(b) - freqMap.get(a));\n maxHeap.addAll(freqMap.keySet());\n\n StringBuilder res = new StringBuilder();\n while (maxHeap.size() >= 2) {\n char char1 = maxHeap.poll();\n char char2 = maxHeap.poll();\n\n res.append(char1);\n res.append(char2);\n\n freqMap.put(char1, freqMap.get(char1) - 1);\n freqMap.put(char2, freqMap.get(char2) - 1);\n\n if (freqMap.get(char1) > 0) maxHeap.add(char1);\n if (freqMap.get(char2) > 0) maxHeap.add(char2);\n }\n\n if (!maxHeap.isEmpty()) {\n char ch = maxHeap.poll();\n if (freqMap.get(ch) > 1) return "";\n res.append(ch);\n }\n\n return res.toString();\n }\n}\n```\n``` C# []\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> freqMap = new Dictionary<char, int>();\n foreach (char c in s) {\n if (!freqMap.ContainsKey(c)) freqMap[c] = 0;\n freqMap[c]++;\n }\n\n var maxHeap = new SortedSet<(int, char)>();\n foreach (var kvp in freqMap) {\n maxHeap.Add((kvp.Value, kvp.Key));\n }\n\n List<char> res = new List<char>();\n while (maxHeap.Count >= 2) {\n var elem1 = maxHeap.Max; maxHeap.Remove(elem1);\n var elem2 = maxHeap.Max; maxHeap.Remove(elem2);\n\n res.Add(elem1.Item2);\n res.Add(elem2.Item2);\n\n if (--elem1.Item1 > 0) maxHeap.Add(elem1);\n if (--elem2.Item1 > 0) maxHeap.Add(elem2);\n }\n\n if (maxHeap.Count > 0) {\n var elem = maxHeap.Max;\n if (elem.Item1 > 1) return "";\n res.Add(elem.Item2);\n }\n\n return new string(res.ToArray());\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar reorganizeString = function(s) {\n const freqMap = {};\n for (const c of s) {\n freqMap[c] = (freqMap[c] || 0) + 1;\n }\n\n const maxHeap = [...Object.keys(freqMap)].sort((a, b) => freqMap[b] - freqMap[a]);\n\n let res = "";\n while (maxHeap.length >= 2) {\n const char1 = maxHeap.shift();\n const char2 = maxHeap.shift();\n\n res += char1;\n res += char2;\n\n if (--freqMap[char1] > 0) maxHeap.push(char1);\n if (--freqMap[char2] > 0) maxHeap.push(char2);\n\n maxHeap.sort((a, b) => freqMap[b] - freqMap[a]);\n }\n\n if (maxHeap.length) {\n const char = maxHeap[0];\n if (freqMap[char] > 1) return "";\n res += char;\n }\n\n return res;\n}\n```\n\n# Code Array Sort\n``` Python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n freq_map = {}\n for char in s:\n freq_map[char] = freq_map.get(char, 0) + 1\n \n sorted_chars = sorted(freq_map.keys(), key=lambda x: freq_map[x], reverse=True)\n \n if freq_map[sorted_chars[0]] > (len(s) + 1) // 2:\n return ""\n \n res = [None] * len(s)\n \n i = 0\n for char in sorted_chars:\n for _ in range(freq_map[char]):\n if i >= len(s):\n i = 1\n res[i] = char\n i += 2\n \n return "".join(res)\n```\n``` Rust []\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn reorganize_string(s: String) -> String {\n let mut freq_map: HashMap<char, usize> = HashMap::new();\n for c in s.chars() {\n *freq_map.entry(c).or_insert(0) += 1;\n }\n\n let mut sorted_chars: Vec<char> = freq_map.keys().cloned().collect();\n sorted_chars.sort_by_key(|&c| std::cmp::Reverse(freq_map[&c]));\n\n if freq_map[&sorted_chars[0]] > (s.len() + 1) / 2 {\n return "".to_string();\n }\n\n let mut res = vec![\' \'; s.len()];\n let mut i = 0;\n for &c in sorted_chars.iter() {\n for _ in 0..freq_map[&c] {\n if i >= s.len() {\n i = 1;\n }\n res[i] = c;\n i += 2;\n }\n }\n\n res.iter().collect()\n }\n}\n```\n``` Go []\nimport "strings"\n\nfunc reorganizeString(s string) string {\n freqMap := make(map[rune]int)\n for _, c := range s {\n freqMap[c]++\n }\n\n var sortedChars []rune\n for ch := range freqMap {\n sortedChars = append(sortedChars, ch)\n }\n\n sort.Slice(sortedChars, func(i, j int) bool {\n return freqMap[sortedChars[i]] > freqMap[sortedChars[j]]\n })\n\n if freqMap[sortedChars[0]] > (len(s)+1)/2 {\n return ""\n }\n\n res := make([]rune, len(s))\n i := 0\n for _, ch := range sortedChars {\n for j := 0; j < freqMap[ch]; j++ {\n if i >= len(s) {\n i = 1\n }\n res[i] = ch\n i += 2\n }\n }\n\n return string(res)\n}\n```\n``` C++ []\nclass Solution {\npublic:\n string reorganizeString(std::string s) {\n std::unordered_map<char, int> freq_map;\n for (char c : s) {\n freq_map[c]++;\n }\n\n std::vector<char> sorted_chars;\n for (auto& pair : freq_map) {\n sorted_chars.push_back(pair.first);\n }\n\n std::sort(sorted_chars.begin(), sorted_chars.end(), [&](char a, char b) {\n return freq_map[a] > freq_map[b];\n });\n\n if (freq_map[sorted_chars[0]] > (s.length() + 1) / 2) {\n return "";\n }\n\n std::string res(s.length(), \' \');\n int i = 0;\n for (char c : sorted_chars) {\n for (int j = 0; j < freq_map[c]; ++j) {\n if (i >= s.length()) {\n i = 1;\n }\n res[i] = c;\n i += 2;\n }\n }\n\n return res;\n}\n};\n```\n``` Java []\npublic class Solution {\n public String reorganizeString(String s) {\n HashMap<Character, Integer> freqMap = new HashMap<>();\n for (char c : s.toCharArray()) {\n freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);\n }\n\n PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> freqMap.get(b) - freqMap.get(a));\n maxHeap.addAll(freqMap.keySet());\n\n if (freqMap.get(maxHeap.peek()) > (s.length() + 1) / 2) {\n return "";\n }\n\n StringBuilder res = new StringBuilder();\n char[] result = new char[s.length()];\n int i = 0;\n while (!maxHeap.isEmpty()) {\n char c = maxHeap.poll();\n for (int j = 0; j < freqMap.get(c); j++) {\n if (i >= s.length()) i = 1;\n result[i] = c;\n i += 2;\n }\n }\n\n return new String(result);\n }\n}\n```\n``` C# []\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> freqMap = new Dictionary<char, int>();\n foreach (char c in s) {\n if (!freqMap.ContainsKey(c)) freqMap[c] = 0;\n freqMap[c]++;\n }\n\n List<char> sortedChars = new List<char>(freqMap.Keys);\n sortedChars.Sort((a, b) => freqMap[b].CompareTo(freqMap[a]));\n\n if (freqMap[sortedChars[0]] > (s.Length + 1) / 2) return "";\n\n char[] res = new char[s.Length];\n int i = 0;\n foreach (char c in sortedChars) {\n for (int j = 0; j < freqMap[c]; j++) {\n if (i >= s.Length) i = 1;\n res[i] = c;\n i += 2;\n }\n }\n\n return new string(res);\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar reorganizeString = function(s) {\n const freqMap = {};\n for (const c of s) {\n freqMap[c] = (freqMap[c] || 0) + 1;\n }\n\n const sortedChars = Object.keys(freqMap).sort((a, b) => freqMap[b] - freqMap[a]);\n\n if (freqMap[sortedChars[0]] > Math.floor((s.length + 1) / 2)) {\n return "";\n }\n\n const res = Array(s.length).fill(null);\n let i = 0;\n for (const c of sortedChars) {\n for (let j = 0; j < freqMap[c]; j++) {\n if (i >= s.length) i = 1;\n res[i] = c;\n i += 2;\n }\n }\n\n return res.join(\'\');\n}\n```\n\n# Live Coding & Explenation\n## Array Sort\n\nhttps://youtu.be/eCBOPJNE4to\n\nWhether you\'re prepping for interviews or just love solving algorithmic challenges, understanding different approaches to problem-solving will sharpen your coding skills. \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB\n
106
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
✅Easy Solution🔥Python3/C#/C++/Java/Python🔥With 🗺️Image🗺️
reorganize-string
1
1
\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/62945814-a6d0-4e8c-89c9-6f7a605695a0_1692760772.3556774.png)\n\n```Python3 []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n heapq.heapify(maxHeap)\n\n prev = None\n res = ""\n while maxHeap or prev:\n if prev and not maxHeap:\n return ""\n cnt, char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap, prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt, char]\n\n return res\n```\n```python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n heapq.heapify(maxHeap)\n\n prev = None\n res = ""\n while maxHeap or prev:\n if prev and not maxHeap:\n return ""\n cnt, char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap, prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt, char]\n\n return res\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> count = new Dictionary<char, int>();\n foreach (char c in s) {\n if (count.ContainsKey(c)) {\n count[c]++;\n } else {\n count[c] = 1;\n }\n }\n\n List<int[]> maxHeap = new List<int[]>();\n foreach (var entry in count) {\n maxHeap.Add(new int[] {-entry.Value, entry.Key});\n }\n Heapify(maxHeap);\n\n int[] prev = null;\n string res = "";\n while (maxHeap.Count > 0 || prev != null) {\n if (prev != null && maxHeap.Count == 0) {\n return "";\n }\n \n int[] top = HeapPop(maxHeap);\n res += (char)top[1];\n top[0]++;\n\n if (prev != null) {\n HeapPush(maxHeap, prev);\n prev = null;\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res;\n }\n\n private void Heapify(List<int[]> heap) {\n int n = heap.Count;\n for (int i = n / 2 - 1; i >= 0; i--) {\n HeapifyDown(heap, i);\n }\n }\n\n private void HeapifyDown(List<int[]> heap, int index) {\n int n = heap.Count;\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap[left][0] < heap[largest][0]) {\n largest = left;\n }\n if (right < n && heap[right][0] < heap[largest][0]) {\n largest = right;\n }\n\n if (largest != index) {\n Swap(heap, index, largest);\n HeapifyDown(heap, largest);\n }\n }\n\n private int[] HeapPop(List<int[]> heap) {\n int n = heap.Count;\n int[] top = heap[0];\n heap[0] = heap[n - 1];\n heap.RemoveAt(n - 1);\n HeapifyDown(heap, 0);\n return top;\n }\n\n private void HeapPush(List<int[]> heap, int[] element) {\n heap.Add(element);\n HeapifyUp(heap, heap.Count - 1);\n }\n\n private void HeapifyUp(List<int[]> heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap[index][0] >= heap[parent][0]) {\n break;\n }\n Swap(heap, index, parent);\n index = parent;\n }\n }\n\n private void Swap(List<int[]> heap, int i, int j) {\n int[] temp = heap[i];\n heap[i] = heap[j];\n heap[j] = temp;\n }\n}\n```\n\n```Java []\nclass Solution {\n public String reorganizeString(String s) {\n Map<Character, Integer> count = new HashMap<>();\n for (char c : s.toCharArray()) {\n count.put(c, count.getOrDefault(c, 0) + 1);\n }\n\n List<int[]> maxHeap = new ArrayList<>();\n for (Map.Entry<Character, Integer> entry : count.entrySet()) {\n maxHeap.add(new int[]{-entry.getValue(), entry.getKey()});\n }\n heapify(maxHeap);\n\n int[] prev = null;\n StringBuilder res = new StringBuilder();\n while (!maxHeap.isEmpty() || prev != null) {\n if (prev != null && maxHeap.isEmpty()) {\n return "";\n }\n\n int[] top = heapPop(maxHeap);\n res.append((char) top[1]);\n top[0]++;\n\n if (prev != null) {\n heapPush(maxHeap, prev);\n prev = null;\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res.toString();\n }\n\n private void heapify(List<int[]> heap) {\n int n = heap.size();\n for (int i = n / 2 - 1; i >= 0; i--) {\n heapifyDown(heap, i);\n }\n }\n\n private void heapifyDown(List<int[]> heap, int index) {\n int n = heap.size();\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap.get(left)[0] < heap.get(largest)[0]) {\n largest = left;\n }\n if (right < n && heap.get(right)[0] < heap.get(largest)[0]) {\n largest = right;\n }\n\n if (largest != index) {\n Collections.swap(heap, index, largest);\n heapifyDown(heap, largest);\n }\n }\n\n private int[] heapPop(List<int[]> heap) {\n int n = heap.size();\n int[] top = heap.get(0);\n heap.set(0, heap.get(n - 1));\n heap.remove(n - 1);\n heapifyDown(heap, 0);\n return top;\n }\n\n private void heapPush(List<int[]> heap, int[] element) {\n heap.add(element);\n heapifyUp(heap, heap.size() - 1);\n }\n\n private void heapifyUp(List<int[]> heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap.get(index)[0] >= heap.get(parent)[0]) {\n break;\n }\n Collections.swap(heap, index, parent);\n index = parent;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n std::string reorganizeString(std::string s) {\n std::unordered_map<char, int> count;\n for (char c : s) {\n count[c]++;\n }\n\n std::vector<std::vector<int>> maxHeap;\n for (auto entry : count) {\n maxHeap.push_back({-entry.second, entry.first});\n }\n heapify(maxHeap);\n\n std::vector<int> prev;\n std::string res = "";\n while (!maxHeap.empty() || !prev.empty()) {\n if (!prev.empty() && maxHeap.empty()) {\n return "";\n }\n\n std::vector<int> top = heapPop(maxHeap);\n res += static_cast<char>(top[1]);\n top[0]++;\n\n if (!prev.empty()) {\n heapPush(maxHeap, prev);\n prev.clear();\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res;\n }\n\nprivate:\n void heapify(std::vector<std::vector<int>>& heap) {\n int n = heap.size();\n for (int i = n / 2 - 1; i >= 0; i--) {\n heapifyDown(heap, i);\n }\n }\n\n void heapifyDown(std::vector<std::vector<int>>& heap, int index) {\n int n = heap.size();\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap[left][0] < heap[largest][0]) {\n largest = left;\n }\n if (right < n && heap[right][0] < heap[largest][0]) {\n largest = right;\n }\n\n if (largest != index) {\n std::swap(heap[index], heap[largest]);\n heapifyDown(heap, largest);\n }\n }\n\n std::vector<int> heapPop(std::vector<std::vector<int>>& heap) {\n int n = heap.size();\n std::vector<int> top = heap[0];\n heap[0] = heap[n - 1];\n heap.pop_back();\n heapifyDown(heap, 0);\n return top;\n }\n\n void heapPush(std::vector<std::vector<int>>& heap, std::vector<int>& element) {\n heap.push_back(element);\n heapifyUp(heap, heap.size() - 1);\n }\n\n void heapifyUp(std::vector<std::vector<int>>& heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap[index][0] >= heap[parent][0]) {\n break;\n }\n std::swap(heap[index], heap[parent]);\n index = parent;\n }\n }\n};\n```\n
42
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✅Easy Solution🔥Python3/C#/C++/Java/Python🔥With 🗺️Image🗺️
reorganize-string
1
1
\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/62945814-a6d0-4e8c-89c9-6f7a605695a0_1692760772.3556774.png)\n\n```Python3 []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n heapq.heapify(maxHeap)\n\n prev = None\n res = ""\n while maxHeap or prev:\n if prev and not maxHeap:\n return ""\n cnt, char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap, prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt, char]\n\n return res\n```\n```python []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n heapq.heapify(maxHeap)\n\n prev = None\n res = ""\n while maxHeap or prev:\n if prev and not maxHeap:\n return ""\n cnt, char = heapq.heappop(maxHeap)\n res += char\n cnt += 1\n\n if prev:\n heapq.heappush(maxHeap, prev)\n prev = None\n\n if cnt != 0:\n prev = [cnt, char]\n\n return res\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public string ReorganizeString(string s) {\n Dictionary<char, int> count = new Dictionary<char, int>();\n foreach (char c in s) {\n if (count.ContainsKey(c)) {\n count[c]++;\n } else {\n count[c] = 1;\n }\n }\n\n List<int[]> maxHeap = new List<int[]>();\n foreach (var entry in count) {\n maxHeap.Add(new int[] {-entry.Value, entry.Key});\n }\n Heapify(maxHeap);\n\n int[] prev = null;\n string res = "";\n while (maxHeap.Count > 0 || prev != null) {\n if (prev != null && maxHeap.Count == 0) {\n return "";\n }\n \n int[] top = HeapPop(maxHeap);\n res += (char)top[1];\n top[0]++;\n\n if (prev != null) {\n HeapPush(maxHeap, prev);\n prev = null;\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res;\n }\n\n private void Heapify(List<int[]> heap) {\n int n = heap.Count;\n for (int i = n / 2 - 1; i >= 0; i--) {\n HeapifyDown(heap, i);\n }\n }\n\n private void HeapifyDown(List<int[]> heap, int index) {\n int n = heap.Count;\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap[left][0] < heap[largest][0]) {\n largest = left;\n }\n if (right < n && heap[right][0] < heap[largest][0]) {\n largest = right;\n }\n\n if (largest != index) {\n Swap(heap, index, largest);\n HeapifyDown(heap, largest);\n }\n }\n\n private int[] HeapPop(List<int[]> heap) {\n int n = heap.Count;\n int[] top = heap[0];\n heap[0] = heap[n - 1];\n heap.RemoveAt(n - 1);\n HeapifyDown(heap, 0);\n return top;\n }\n\n private void HeapPush(List<int[]> heap, int[] element) {\n heap.Add(element);\n HeapifyUp(heap, heap.Count - 1);\n }\n\n private void HeapifyUp(List<int[]> heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap[index][0] >= heap[parent][0]) {\n break;\n }\n Swap(heap, index, parent);\n index = parent;\n }\n }\n\n private void Swap(List<int[]> heap, int i, int j) {\n int[] temp = heap[i];\n heap[i] = heap[j];\n heap[j] = temp;\n }\n}\n```\n\n```Java []\nclass Solution {\n public String reorganizeString(String s) {\n Map<Character, Integer> count = new HashMap<>();\n for (char c : s.toCharArray()) {\n count.put(c, count.getOrDefault(c, 0) + 1);\n }\n\n List<int[]> maxHeap = new ArrayList<>();\n for (Map.Entry<Character, Integer> entry : count.entrySet()) {\n maxHeap.add(new int[]{-entry.getValue(), entry.getKey()});\n }\n heapify(maxHeap);\n\n int[] prev = null;\n StringBuilder res = new StringBuilder();\n while (!maxHeap.isEmpty() || prev != null) {\n if (prev != null && maxHeap.isEmpty()) {\n return "";\n }\n\n int[] top = heapPop(maxHeap);\n res.append((char) top[1]);\n top[0]++;\n\n if (prev != null) {\n heapPush(maxHeap, prev);\n prev = null;\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res.toString();\n }\n\n private void heapify(List<int[]> heap) {\n int n = heap.size();\n for (int i = n / 2 - 1; i >= 0; i--) {\n heapifyDown(heap, i);\n }\n }\n\n private void heapifyDown(List<int[]> heap, int index) {\n int n = heap.size();\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap.get(left)[0] < heap.get(largest)[0]) {\n largest = left;\n }\n if (right < n && heap.get(right)[0] < heap.get(largest)[0]) {\n largest = right;\n }\n\n if (largest != index) {\n Collections.swap(heap, index, largest);\n heapifyDown(heap, largest);\n }\n }\n\n private int[] heapPop(List<int[]> heap) {\n int n = heap.size();\n int[] top = heap.get(0);\n heap.set(0, heap.get(n - 1));\n heap.remove(n - 1);\n heapifyDown(heap, 0);\n return top;\n }\n\n private void heapPush(List<int[]> heap, int[] element) {\n heap.add(element);\n heapifyUp(heap, heap.size() - 1);\n }\n\n private void heapifyUp(List<int[]> heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap.get(index)[0] >= heap.get(parent)[0]) {\n break;\n }\n Collections.swap(heap, index, parent);\n index = parent;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n std::string reorganizeString(std::string s) {\n std::unordered_map<char, int> count;\n for (char c : s) {\n count[c]++;\n }\n\n std::vector<std::vector<int>> maxHeap;\n for (auto entry : count) {\n maxHeap.push_back({-entry.second, entry.first});\n }\n heapify(maxHeap);\n\n std::vector<int> prev;\n std::string res = "";\n while (!maxHeap.empty() || !prev.empty()) {\n if (!prev.empty() && maxHeap.empty()) {\n return "";\n }\n\n std::vector<int> top = heapPop(maxHeap);\n res += static_cast<char>(top[1]);\n top[0]++;\n\n if (!prev.empty()) {\n heapPush(maxHeap, prev);\n prev.clear();\n }\n\n if (top[0] != 0) {\n prev = top;\n }\n }\n\n return res;\n }\n\nprivate:\n void heapify(std::vector<std::vector<int>>& heap) {\n int n = heap.size();\n for (int i = n / 2 - 1; i >= 0; i--) {\n heapifyDown(heap, i);\n }\n }\n\n void heapifyDown(std::vector<std::vector<int>>& heap, int index) {\n int n = heap.size();\n int left = 2 * index + 1;\n int right = 2 * index + 2;\n int largest = index;\n\n if (left < n && heap[left][0] < heap[largest][0]) {\n largest = left;\n }\n if (right < n && heap[right][0] < heap[largest][0]) {\n largest = right;\n }\n\n if (largest != index) {\n std::swap(heap[index], heap[largest]);\n heapifyDown(heap, largest);\n }\n }\n\n std::vector<int> heapPop(std::vector<std::vector<int>>& heap) {\n int n = heap.size();\n std::vector<int> top = heap[0];\n heap[0] = heap[n - 1];\n heap.pop_back();\n heapifyDown(heap, 0);\n return top;\n }\n\n void heapPush(std::vector<std::vector<int>>& heap, std::vector<int>& element) {\n heap.push_back(element);\n heapifyUp(heap, heap.size() - 1);\n }\n\n void heapifyUp(std::vector<std::vector<int>>& heap, int index) {\n while (index > 0) {\n int parent = (index - 1) / 2;\n if (heap[index][0] >= heap[parent][0]) {\n break;\n }\n std::swap(heap[index], heap[parent]);\n index = parent;\n }\n }\n};\n```\n
42
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim. Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`. **Example 1:** **Input:** grid = \[\[0,2\],\[1,3\]\] **Output:** 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid. **Example 2:** **Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\] **Output:** 16 **Explanation:** The final route is shown. We need to wait until time 16 so that (0, 0) and (4, 4) are connected. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] < n2` * Each value `grid[i][j]` is **unique**.
Alternate placing the most common letters.
Python || Sorting+Hashmap || O(n logn)
max-chunks-to-make-sorted-ii
0
1
We have 2 arrays. One sorted and one unsorted.Now traverse over both.For one array increment by one for every value and for other decrement.We delete an element from map when its count is reached 0, it means when one element who was in excess in one array has been compensated by the same value in other array.(basically its +1-1=0 or +2-2=0 .....)Finally we will have a chunk when we have common elements in both subarrays i.e. when length of map will be 0.\n```\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n arr2=sorted(arr)\n n=len(arr)\n cnt={}\n ans=0\n for i in range(n):\n if arr[i] not in cnt:\n cnt[arr[i]]=1\n else:\n cnt[arr[i]]+=1\n if cnt[arr[i]]==0:\n del cnt[arr[i]]\n if arr2[i] not in cnt:\n cnt[arr2[i]]=-1\n else:\n cnt[arr2[i]]-=1\n if cnt[arr2[i]]==0:\n del cnt[arr2[i]]\n ans+=(1 if len(cnt)==0 else 0)\n return ans\n \n```
1
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Python || Sorting+Hashmap || O(n logn)
max-chunks-to-make-sorted-ii
0
1
We have 2 arrays. One sorted and one unsorted.Now traverse over both.For one array increment by one for every value and for other decrement.We delete an element from map when its count is reached 0, it means when one element who was in excess in one array has been compensated by the same value in other array.(basically its +1-1=0 or +2-2=0 .....)Finally we will have a chunk when we have common elements in both subarrays i.e. when length of map will be 0.\n```\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n arr2=sorted(arr)\n n=len(arr)\n cnt={}\n ans=0\n for i in range(n):\n if arr[i] not in cnt:\n cnt[arr[i]]=1\n else:\n cnt[arr[i]]+=1\n if cnt[arr[i]]==0:\n del cnt[arr[i]]\n if arr2[i] not in cnt:\n cnt[arr2[i]]=-1\n else:\n cnt[arr2[i]]-=1\n if cnt[arr2[i]]==0:\n del cnt[arr2[i]]\n ans+=(1 if len(cnt)==0 else 0)\n return ans\n \n```
1
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍
max-chunks-to-make-sorted-ii
0
1
## IDEA:\n**Take this [ 2, 1, 7, 6, 3, 5, 4, 9, 8 ] as an example and once try yourself to split it into maximum chunks using stack.**\n\nYou will come to following conclusions : \n* The max number in the left chunk must always be <= the max number in the right chunk. \n\n* We only need to maintain the max number of each chunk in the stack. This is because if num[i] >= stack[-1], then num[i] must be bigger than all other elements in that chunk. \n* Otherwise if num[i] < stack[-1], then it must belong to the previous chunk regardless of whether num[i] is bigger than the other elements or not. Hence, only the max num in each chunk is relevant.\n\n**Implementation:**\n\n* So, we can loop through the array and maintain a stack. Each element in the stack represents a chunk.\n\n* Each time we encounter a num[i] that is bigger than or equal to the previous chunk max, we push it to the stack. If we encounter a smaller number, we must combine this number with the previous chunks. We do this by comparing with the top chunk in the stack and popping them off until we encounter a chunk with max number that is smaller than num[i]. \n* Then, we update the new combined chunk with the new max by pushing it back onto the stack. The number of elements in this stack at the end is the number of chunks.\n\n### CODE:\n\'\'\'\n\n\tclass Solution:\n def maxChunksToSorted(self, nums: List[int]) -> int:\n \n st = []\n for n in nums:\n if len(st)==0 or st[-1]<=n:\n st.append(n)\n else:\n ma = st[-1]\n while st and st[-1]>n:\n ma = max(ma,st.pop())\n st.append(ma)\n \n return len(st)\n\n**Thanks and *Upvote* if you like the idea!!\uD83E\uDD1E**
16
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2,1\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[5, 4\], \[3, 2, 1\] will result in \[4, 5, 1, 2, 3\], which isn't sorted. **Example 2:** **Input:** arr = \[2,1,3,4,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[2, 1\], \[3, 4, 4\]. However, splitting into \[2, 1\], \[3\], \[4\], \[4\] is the highest number of chunks possible. **Constraints:** * `1 <= arr.length <= 2000` * `0 <= arr[i] <= 108`
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍
max-chunks-to-make-sorted-ii
0
1
## IDEA:\n**Take this [ 2, 1, 7, 6, 3, 5, 4, 9, 8 ] as an example and once try yourself to split it into maximum chunks using stack.**\n\nYou will come to following conclusions : \n* The max number in the left chunk must always be <= the max number in the right chunk. \n\n* We only need to maintain the max number of each chunk in the stack. This is because if num[i] >= stack[-1], then num[i] must be bigger than all other elements in that chunk. \n* Otherwise if num[i] < stack[-1], then it must belong to the previous chunk regardless of whether num[i] is bigger than the other elements or not. Hence, only the max num in each chunk is relevant.\n\n**Implementation:**\n\n* So, we can loop through the array and maintain a stack. Each element in the stack represents a chunk.\n\n* Each time we encounter a num[i] that is bigger than or equal to the previous chunk max, we push it to the stack. If we encounter a smaller number, we must combine this number with the previous chunks. We do this by comparing with the top chunk in the stack and popping them off until we encounter a chunk with max number that is smaller than num[i]. \n* Then, we update the new combined chunk with the new max by pushing it back onto the stack. The number of elements in this stack at the end is the number of chunks.\n\n### CODE:\n\'\'\'\n\n\tclass Solution:\n def maxChunksToSorted(self, nums: List[int]) -> int:\n \n st = []\n for n in nums:\n if len(st)==0 or st[-1]<=n:\n st.append(n)\n else:\n ma = st[-1]\n while st and st[-1]>n:\n ma = max(ma,st.pop())\n st.append(ma)\n \n return len(st)\n\n**Thanks and *Upvote* if you like the idea!!\uD83E\uDD1E**
16
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Python Easy Sol(28ms) with Detailed Explanation
max-chunks-to-make-sorted
0
1
\n\n \n So the idea is that we initally set a max_so_far which is initally taken as the first ele of arr\n \n secondly we are checking two things first if max_so_far < arr[i] if so then update max_so_far\n \n and then we are checking that once the max_so_far has reached the index which is equal to it,\n \n means that that if the maximum where it can be in a sorted arr or in other words that it is \n \n the max it can impact. So we will incremnt the count and keep going that way.\n \n THIS TECHNIQUE IS CALLED CHAIN TECHNIQUE \n \n \n max_so_far = arr[0]\n \n count = 0\n \n for i in range(len(arr)):\n if max_so_far<arr[i]:\n max_so_far = arr[i]\n \n if max_so_far == i:\n count+=1\n \n return count\n\t\t\n*Time complexity O(n) and Space complexity is O(1)\n\n\t\t\n**If you like it kindly upvote**
28
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Python Easy Sol(28ms) with Detailed Explanation
max-chunks-to-make-sorted
0
1
\n\n \n So the idea is that we initally set a max_so_far which is initally taken as the first ele of arr\n \n secondly we are checking two things first if max_so_far < arr[i] if so then update max_so_far\n \n and then we are checking that once the max_so_far has reached the index which is equal to it,\n \n means that that if the maximum where it can be in a sorted arr or in other words that it is \n \n the max it can impact. So we will incremnt the count and keep going that way.\n \n THIS TECHNIQUE IS CALLED CHAIN TECHNIQUE \n \n \n max_so_far = arr[0]\n \n count = 0\n \n for i in range(len(arr)):\n if max_so_far<arr[i]:\n max_so_far = arr[i]\n \n if max_so_far == i:\n count+=1\n \n return count\n\t\t\n*Time complexity O(n) and Space complexity is O(1)\n\n\t\t\n**If you like it kindly upvote**
28
Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_. The allowed operation on some point `(x, y)` is to convert it to either `(x, x + y)` or `(x + y, y)`. **Example 1:** **Input:** sx = 1, sy = 1, tx = 3, ty = 5 **Output:** true **Explanation:** One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) **Example 2:** **Input:** sx = 1, sy = 1, tx = 2, ty = 2 **Output:** false **Example 3:** **Input:** sx = 1, sy = 1, tx = 1, ty = 1 **Output:** true **Constraints:** * `1 <= sx, sy, tx, ty <= 109`
The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.
Solution
max-chunks-to-make-sorted
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int ch=0;\n int right = arr[0];\n for(int i=0;i<arr.size();i++){\n right = max(right, arr[i]);\n if(right == i)ch++;\n }\n return ch;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n curMax, res = -1, 0\n for i, v in enumerate(arr):\n curMax = max(curMax, v)\n res += curMax == i\n return res\n```\n\n```Java []\nclass Solution {\n public int maxChunksToSorted(int[] arr) {\n int n = arr.length;\n int count=0;\n int curr=0;\n for(int i=0;i<n;i++){\n curr += arr[i];\n if(curr ==((i)*(i+1))/2){\n count++;\n }\n }\n return count;\n }\n}\n```\n
2
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[4,3,2,1,0\] **Output:** 1 **Explanation:** Splitting into two or more chunks will not return the required result. For example, splitting into \[4, 3\], \[2, 1, 0\] will result in \[3, 4, 0, 1, 2\], which isn't sorted. **Example 2:** **Input:** arr = \[1,0,2,3,4\] **Output:** 4 **Explanation:** We can split into two chunks, such as \[1, 0\], \[2, 3, 4\]. However, splitting into \[1, 0\], \[2\], \[3\], \[4\] is the highest number of chunks possible. **Constraints:** * `n == arr.length` * `1 <= n <= 10` * `0 <= arr[i] < n` * All the elements of `arr` are **unique**.
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Solution
max-chunks-to-make-sorted
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int ch=0;\n int right = arr[0];\n for(int i=0;i<arr.size();i++){\n right = max(right, arr[i]);\n if(right == i)ch++;\n }\n return ch;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n curMax, res = -1, 0\n for i, v in enumerate(arr):\n curMax = max(curMax, v)\n res += curMax == i\n return res\n```\n\n```Java []\nclass Solution {\n public int maxChunksToSorted(int[] arr) {\n int n = arr.length;\n int count=0;\n int curr=0;\n for(int i=0;i<n;i++){\n curr += arr[i];\n if(curr ==((i)*(i+1))/2){\n count++;\n }\n }\n return count;\n }\n}\n```\n
2
Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_. The allowed operation on some point `(x, y)` is to convert it to either `(x, x + y)` or `(x + y, y)`. **Example 1:** **Input:** sx = 1, sy = 1, tx = 3, ty = 5 **Output:** true **Explanation:** One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5) **Example 2:** **Input:** sx = 1, sy = 1, tx = 2, ty = 2 **Output:** false **Example 3:** **Input:** sx = 1, sy = 1, tx = 1, ty = 1 **Output:** true **Constraints:** * `1 <= sx, sy, tx, ty <= 109`
The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.
Solution
basic-calculator-iv
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {\n unordered_map<string, int> mp;\n int n = evalvars.size();\n for (int i = 0; i < n; ++i) mp[evalvars[i]] = evalints[i];\n int pos = 0;\n unordered_map<string, int> output = helper(expression, mp, pos);\n vector<pair<string, int>> ans(output.begin(), output.end());\n sort(ans.begin(), ans.end(), mycompare);\n vector<string> res;\n for (auto& p: ans) {\n if (p.second == 0) continue;\n res.push_back(to_string(p.second));\n if (p.first != "") res.back() += "*"+p.first;\n }\n return res;\n }\nprivate:\n unordered_map<string, int> helper(string& s, unordered_map<string, int>& mp, int& pos) {\n vector<unordered_map<string, int>> operands;\n vector<char> ops;\n ops.push_back(\'+\');\n int n = s.size();\n while (pos < n && s[pos] != \')\') {\n if (s[pos] == \'(\') {\n pos++;\n operands.push_back(helper(s, mp, pos));\n }\n else {\n int k = pos;\n while (pos < n && s[pos] != \' \' && s[pos] != \')\') pos++;\n string t = s.substr(k, pos-k);\n bool isNum = true;\n for (char c: t) {\n if (!isdigit(c)) isNum = false;\n }\n unordered_map<string, int> tmp;\n if (isNum) \n tmp[""] = stoi(t);\n else if (mp.count(t)) \n tmp[""] = mp[t];\n else \n tmp[t] = 1;\n operands.push_back(tmp);\n }\n if (pos < n && s[pos] == \' \') {\n ops.push_back(s[++pos]);\n pos += 2;\n }\n }\n pos++;\n return calculate(operands, ops);\n }\n unordered_map<string, int> calculate(vector<unordered_map<string, int>>& operands, vector<char>& ops) {\n unordered_map<string, int> ans;\n int n = ops.size();\n for (int i = n-1; i >= 0; --i) {\n unordered_map<string, int> tmp = operands[i];\n while (i >= 0 && ops[i] == \'*\')\n tmp = multi(tmp, operands[--i]);\n int sign = ops[i] == \'+\'? 1: -1;\n for (auto& p: tmp) ans[p.first] += sign*p.second;\n }\n return ans;\n }\n unordered_map<string, int> multi(unordered_map<string, int>& lhs, unordered_map<string, int>& rhs) {\n unordered_map<string, int> ans;\n int m = lhs.size(), n = rhs.size();\n for (auto& p: lhs) {\n for (auto& q: rhs) {\n string t = combine(p.first, q.first);\n ans[t] += p.second*q.second;\n }\n }\n return ans;\n }\n string combine(const string& a, const string& b) {\n if (a == "") return b;\n if (b == "") return a;\n vector<string> strs = split(a, \'*\');\n for (auto& s: split(b, \'*\')) strs.push_back(s);\n sort(strs.begin(), strs.end());\n string s;\n for (auto& t: strs) s += t +\'*\';\n s.pop_back();\n return s;\n }\n static vector<string> split(const string& s, char c) {\n vector<string> ans;\n int i = 0, n = s.size();\n while (i < n) {\n int j = i;\n i = s.find(c, i);\n if (i == -1) i = n;\n ans.push_back(s.substr(j, i-j));\n i++;\n }\n return ans;\n }\n static bool mycompare(pair<string, int>& a, pair<string, int>& b) {\n string s1 = a.first, s2 = b.first;\n vector<string> left = split(s1, \'*\'); \n vector<string> right = split(s2, \'*\');\n return left.size() > right.size() || (left.size() == right.size() && left < right);\n } \n};\n```\n\n```Python3 []\nfrom functools import cmp_to_key\n\nclass Expr:\n def __init__(self):\n self.coef = 0\n self.vars = []\n\n def getVal(self):\n if not self.coef:\n return ""\n if not self.vars:\n return str(self.coef)\n return str(self.coef) + "*" + "*".join(self.vars)\n \ndef mul(expr1, expr2):\n ret = Expr()\n ret.coef = expr1.coef * expr2.coef\n if ret.coef == 0:\n return ret\n ret.vars = list(sorted(expr1.vars + expr2.vars))\n return ret\n\ndef mergeExpr(stack, signs, expr):\n sign = signs[-1][-1]\n match sign:\n case "+":\n stack[-1].append([expr])\n case "-":\n expr.coef = - expr.coef\n stack[-1].append([expr])\n case "*":\n last = stack[-1][-1]\n temp = []\n for prev in last:\n temp.append(mul(prev, expr))\n stack[-1][-1] = temp\n signs[-1].pop()\n\ndef mergeGroup(stack, signs, group):\n sign = signs[-1][-1]\n match sign:\n case "+":\n stack[-1].append(group) \n case "-":\n temp = []\n for expr in group:\n expr.coef = -expr.coef\n temp.append(expr) \n stack[-1].append(temp)\n case "*":\n last = stack[-1].pop()\n temp = []\n for expr1 in last:\n for expr2 in group:\n temp.append(mul(expr1, expr2))\n stack[-1].append(temp)\n signs[-1].pop()\n\ndef compare(c, d):\n a, b = c.split("*"), d.split("*")\n if len(a) != len(b):\n return len(b) - len(a)\n return 1 if a > b else -1\n\ndef getSum(curLevel):\n exprs = {"":0}\n for groups in curLevel:\n for expr in groups:\n if not expr.vars:\n exprs[""] += expr.coef\n else:\n key = "*".join(expr.vars)\n if key not in exprs:\n exprs[key] = expr\n else:\n exprs[key].coef += expr.coef\n ret = [exprs[key] for key in sorted(exprs.keys(), key=cmp_to_key(compare)) if key != "" and exprs[key].coef]\n\n if exprs[""] != 0:\n temp = Expr()\n temp.coef = exprs[""]\n ret.append(temp)\n return ret\n\ndef calculate(s, a, b):\n stack, signs = [[]], [["+"]]\n i, n = 0, len(s)\n dic = {x:y for x, y in zip(a, b)}\n while i < n:\n if s[i] == " ":\n i += 1\n continue\n if s[i].isalpha():\n expr = Expr()\n temp = s[i]\n while i+1 < n and s[i+1].isalpha():\n temp += s[i+1]\n i += 1\n if temp in dic:\n expr.coef = dic[temp]\n else:\n expr.coef = 1\n expr.vars = [temp]\n mergeExpr(stack, signs, expr)\n elif s[i].isdigit():\n expr = Expr()\n num = int(s[i])\n while i+1 < n and s[i+1].isdigit():\n num = num * 10 + int(s[i+1])\n i += 1\n expr.coef = num\n mergeExpr(stack, signs, expr)\n elif s[i] in "+-*":\n signs[-1].append(s[i])\n elif s[i] == "(":\n stack.append([])\n signs.append(["+"])\n elif s[i] == ")":\n curLevel = getSum(stack.pop())\n signs.pop()\n mergeGroup(stack, signs, curLevel)\n i += 1\n res = getSum(stack.pop())\n return [expr.getVal() for expr in res]\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n return calculate(expression, evalvars, evalints)\n```\n\n```Java []\nclass Solution {\n int n;\n String s;\n char[] arr;\n int[] braces;\n HashMap<String, Integer> variables = new HashMap<>();\n \n public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {\n s = expression;\n arr = s.toCharArray();\n n = arr.length;\n braces = new int[n];\n Arrays.fill(braces, -1);\n int[] stack = new int[n/2];\n int index = -1;\n for(int i=0; i<n; ++i) {\n if(arr[i] == \'(\') stack[++index] = i;\n else if(arr[i] == \')\') {\n int last = stack[index--];\n braces[last] = i;\n braces[i] = last;\n }\n }\n for(int i=0; i<evalvars.length; ++i) variables.put(evalvars[i], evalints[i]);\n List<Term> terms = dewIt(0, n-1);\n TreeMap<String, Integer> map = new TreeMap<>(new Comparator<>() {\n public int compare(String a, String b) {\n int ca = countStars(a), cb = countStars(b);\n if(ca != cb) return cb - ca;\n else return a.compareTo(b);\n }\n private int countStars(String s) {\n int ans = 0;\n for(char c: s.toCharArray()) if(c == \'*\') ++ans;\n return ans;\n }\n });\n for(Term term: terms) {\n if(term.coeff != 0) {\n String key = term.getKey();\n if(map.containsKey(key)) {\n int oldCoeff = map.get(key);\n if(oldCoeff == -term.coeff) map.remove(key);\n else map.put(key, oldCoeff + term.coeff);\n } else map.put(key, term.coeff);\n }\n }\n List<String> ans = new LinkedList<>();\n for(String k: map.keySet()) ans.add(map.get(k) + "" + k);\n return ans;\n }\n private List<Term> dewIt(int a, int b) {\n if(braces[a] == b) return dewIt(a+1, b-1);\n List<Term> ans = new LinkedList<>(), buffer = new LinkedList<>();\n buffer.add(new Term(1, new LinkedList<>()));\n for(int i=a; i<=b; ) {\n int j = i;\n List<Term> curr = null;\n if(arr[i] == \'(\') {\n j = braces[i] + 1;\n curr = dewIt(i+1, j-2);\n }\n else {\n while(j <= b && arr[j] != \' \') ++j;\n String exp = s.substring(i, j);\n int val = 1;\n List<String> vars = new LinkedList<>();\n if(variables.containsKey(exp)) val = variables.get(exp);\n else if (exp.charAt(0) <= \'9\') val = Integer.valueOf(exp);\n else vars.add(exp);\n curr = new LinkedList<>();\n curr.add(new Term(val, vars));\n }\n buffer = multiply(buffer, curr);\n if(j > b || arr[j+1] == \'+\' || arr[j+1] == \'-\') {\n ans.addAll(buffer);\n buffer = new LinkedList<>();\n }\n if(j < b) {\n ++j;\n if(arr[j] == \'+\') buffer.add(new Term(1, new LinkedList<>()));\n else if(arr[j] == \'-\') buffer.add(new Term(-1, new LinkedList<>()));\n j += 2;\n }\n i = j;\n }\n return ans;\n }\n private List<Term> multiply(List<Term> a, List<Term> b) {\n List<Term> ans = new LinkedList<>();\n for(Term x: a) for(Term y: b) {\n Term prod = x.clone();\n prod.multiply(y);\n ans.add(prod);\n }\n return ans;\n }\n}\nclass Term {\n int coeff;\n List<String> vars;\n\n public Term(int a, List<String> c) {\n this.coeff = a;\n vars = new LinkedList<>();\n vars.addAll(c);\n }\n public String getKey() {\n StringBuilder b = new StringBuilder();\n Collections.sort(vars);\n for(String x: vars) {\n b.append(\'*\');\n b.append(x);\n }\n return b.toString();\n }\n public void multiply(Term that) {\n this.coeff *= that.coeff;\n if(this.coeff == 0) vars.clear();\n else this.vars.addAll(that.vars);\n }\n public Term clone() {\n return new Term(coeff, vars);\n }\n}\n```\n
1
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space separating each chunk and symbol. * A chunk is either an expression in parentheses, a variable, or a non-negative integer. * A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x "` or `"-x "`. Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. * For example, `expression = "1 + 2 * 3 "` has an answer of `[ "7 "]`. The format of the output is as follows: * For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. * For example, we would never write a term like `"b*a*c "`, only `"a*b*c "`. * Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. * For example, `"a*a*b*c "` has degree `4`. * The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. * An example of a well-formatted answer is `[ "-2*a*a*a ", "3*a*a*b ", "3*b*b ", "4*a ", "5*c ", "-6 "]`. * Terms (including constant terms) with coefficient `0` are not included. * For example, an expression of `"0 "` has an output of `[]`. **Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Example 1:** **Input:** expression = "e + 8 - a + 5 ", evalvars = \[ "e "\], evalints = \[1\] **Output:** \[ "-1\*a ", "14 "\] **Example 2:** **Input:** expression = "e - 8 + temperature - pressure ", evalvars = \[ "e ", "temperature "\], evalints = \[1, 12\] **Output:** \[ "-1\*pressure ", "5 "\] **Example 3:** **Input:** expression = "(e + 8) \* (e - 8) ", evalvars = \[\], evalints = \[\] **Output:** \[ "1\*e\*e ", "-64 "\] **Constraints:** * `1 <= expression.length <= 250` * `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`. * `expression` does not contain any leading or trailing spaces. * All the tokens in `expression` are separated by a single space. * `0 <= evalvars.length <= 100` * `1 <= evalvars[i].length <= 20` * `evalvars[i]` consists of lowercase English letters. * `evalints.length == evalvars.length` * `-100 <= evalints[i] <= 100`
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
Solution
basic-calculator-iv
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {\n unordered_map<string, int> mp;\n int n = evalvars.size();\n for (int i = 0; i < n; ++i) mp[evalvars[i]] = evalints[i];\n int pos = 0;\n unordered_map<string, int> output = helper(expression, mp, pos);\n vector<pair<string, int>> ans(output.begin(), output.end());\n sort(ans.begin(), ans.end(), mycompare);\n vector<string> res;\n for (auto& p: ans) {\n if (p.second == 0) continue;\n res.push_back(to_string(p.second));\n if (p.first != "") res.back() += "*"+p.first;\n }\n return res;\n }\nprivate:\n unordered_map<string, int> helper(string& s, unordered_map<string, int>& mp, int& pos) {\n vector<unordered_map<string, int>> operands;\n vector<char> ops;\n ops.push_back(\'+\');\n int n = s.size();\n while (pos < n && s[pos] != \')\') {\n if (s[pos] == \'(\') {\n pos++;\n operands.push_back(helper(s, mp, pos));\n }\n else {\n int k = pos;\n while (pos < n && s[pos] != \' \' && s[pos] != \')\') pos++;\n string t = s.substr(k, pos-k);\n bool isNum = true;\n for (char c: t) {\n if (!isdigit(c)) isNum = false;\n }\n unordered_map<string, int> tmp;\n if (isNum) \n tmp[""] = stoi(t);\n else if (mp.count(t)) \n tmp[""] = mp[t];\n else \n tmp[t] = 1;\n operands.push_back(tmp);\n }\n if (pos < n && s[pos] == \' \') {\n ops.push_back(s[++pos]);\n pos += 2;\n }\n }\n pos++;\n return calculate(operands, ops);\n }\n unordered_map<string, int> calculate(vector<unordered_map<string, int>>& operands, vector<char>& ops) {\n unordered_map<string, int> ans;\n int n = ops.size();\n for (int i = n-1; i >= 0; --i) {\n unordered_map<string, int> tmp = operands[i];\n while (i >= 0 && ops[i] == \'*\')\n tmp = multi(tmp, operands[--i]);\n int sign = ops[i] == \'+\'? 1: -1;\n for (auto& p: tmp) ans[p.first] += sign*p.second;\n }\n return ans;\n }\n unordered_map<string, int> multi(unordered_map<string, int>& lhs, unordered_map<string, int>& rhs) {\n unordered_map<string, int> ans;\n int m = lhs.size(), n = rhs.size();\n for (auto& p: lhs) {\n for (auto& q: rhs) {\n string t = combine(p.first, q.first);\n ans[t] += p.second*q.second;\n }\n }\n return ans;\n }\n string combine(const string& a, const string& b) {\n if (a == "") return b;\n if (b == "") return a;\n vector<string> strs = split(a, \'*\');\n for (auto& s: split(b, \'*\')) strs.push_back(s);\n sort(strs.begin(), strs.end());\n string s;\n for (auto& t: strs) s += t +\'*\';\n s.pop_back();\n return s;\n }\n static vector<string> split(const string& s, char c) {\n vector<string> ans;\n int i = 0, n = s.size();\n while (i < n) {\n int j = i;\n i = s.find(c, i);\n if (i == -1) i = n;\n ans.push_back(s.substr(j, i-j));\n i++;\n }\n return ans;\n }\n static bool mycompare(pair<string, int>& a, pair<string, int>& b) {\n string s1 = a.first, s2 = b.first;\n vector<string> left = split(s1, \'*\'); \n vector<string> right = split(s2, \'*\');\n return left.size() > right.size() || (left.size() == right.size() && left < right);\n } \n};\n```\n\n```Python3 []\nfrom functools import cmp_to_key\n\nclass Expr:\n def __init__(self):\n self.coef = 0\n self.vars = []\n\n def getVal(self):\n if not self.coef:\n return ""\n if not self.vars:\n return str(self.coef)\n return str(self.coef) + "*" + "*".join(self.vars)\n \ndef mul(expr1, expr2):\n ret = Expr()\n ret.coef = expr1.coef * expr2.coef\n if ret.coef == 0:\n return ret\n ret.vars = list(sorted(expr1.vars + expr2.vars))\n return ret\n\ndef mergeExpr(stack, signs, expr):\n sign = signs[-1][-1]\n match sign:\n case "+":\n stack[-1].append([expr])\n case "-":\n expr.coef = - expr.coef\n stack[-1].append([expr])\n case "*":\n last = stack[-1][-1]\n temp = []\n for prev in last:\n temp.append(mul(prev, expr))\n stack[-1][-1] = temp\n signs[-1].pop()\n\ndef mergeGroup(stack, signs, group):\n sign = signs[-1][-1]\n match sign:\n case "+":\n stack[-1].append(group) \n case "-":\n temp = []\n for expr in group:\n expr.coef = -expr.coef\n temp.append(expr) \n stack[-1].append(temp)\n case "*":\n last = stack[-1].pop()\n temp = []\n for expr1 in last:\n for expr2 in group:\n temp.append(mul(expr1, expr2))\n stack[-1].append(temp)\n signs[-1].pop()\n\ndef compare(c, d):\n a, b = c.split("*"), d.split("*")\n if len(a) != len(b):\n return len(b) - len(a)\n return 1 if a > b else -1\n\ndef getSum(curLevel):\n exprs = {"":0}\n for groups in curLevel:\n for expr in groups:\n if not expr.vars:\n exprs[""] += expr.coef\n else:\n key = "*".join(expr.vars)\n if key not in exprs:\n exprs[key] = expr\n else:\n exprs[key].coef += expr.coef\n ret = [exprs[key] for key in sorted(exprs.keys(), key=cmp_to_key(compare)) if key != "" and exprs[key].coef]\n\n if exprs[""] != 0:\n temp = Expr()\n temp.coef = exprs[""]\n ret.append(temp)\n return ret\n\ndef calculate(s, a, b):\n stack, signs = [[]], [["+"]]\n i, n = 0, len(s)\n dic = {x:y for x, y in zip(a, b)}\n while i < n:\n if s[i] == " ":\n i += 1\n continue\n if s[i].isalpha():\n expr = Expr()\n temp = s[i]\n while i+1 < n and s[i+1].isalpha():\n temp += s[i+1]\n i += 1\n if temp in dic:\n expr.coef = dic[temp]\n else:\n expr.coef = 1\n expr.vars = [temp]\n mergeExpr(stack, signs, expr)\n elif s[i].isdigit():\n expr = Expr()\n num = int(s[i])\n while i+1 < n and s[i+1].isdigit():\n num = num * 10 + int(s[i+1])\n i += 1\n expr.coef = num\n mergeExpr(stack, signs, expr)\n elif s[i] in "+-*":\n signs[-1].append(s[i])\n elif s[i] == "(":\n stack.append([])\n signs.append(["+"])\n elif s[i] == ")":\n curLevel = getSum(stack.pop())\n signs.pop()\n mergeGroup(stack, signs, curLevel)\n i += 1\n res = getSum(stack.pop())\n return [expr.getVal() for expr in res]\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n return calculate(expression, evalvars, evalints)\n```\n\n```Java []\nclass Solution {\n int n;\n String s;\n char[] arr;\n int[] braces;\n HashMap<String, Integer> variables = new HashMap<>();\n \n public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {\n s = expression;\n arr = s.toCharArray();\n n = arr.length;\n braces = new int[n];\n Arrays.fill(braces, -1);\n int[] stack = new int[n/2];\n int index = -1;\n for(int i=0; i<n; ++i) {\n if(arr[i] == \'(\') stack[++index] = i;\n else if(arr[i] == \')\') {\n int last = stack[index--];\n braces[last] = i;\n braces[i] = last;\n }\n }\n for(int i=0; i<evalvars.length; ++i) variables.put(evalvars[i], evalints[i]);\n List<Term> terms = dewIt(0, n-1);\n TreeMap<String, Integer> map = new TreeMap<>(new Comparator<>() {\n public int compare(String a, String b) {\n int ca = countStars(a), cb = countStars(b);\n if(ca != cb) return cb - ca;\n else return a.compareTo(b);\n }\n private int countStars(String s) {\n int ans = 0;\n for(char c: s.toCharArray()) if(c == \'*\') ++ans;\n return ans;\n }\n });\n for(Term term: terms) {\n if(term.coeff != 0) {\n String key = term.getKey();\n if(map.containsKey(key)) {\n int oldCoeff = map.get(key);\n if(oldCoeff == -term.coeff) map.remove(key);\n else map.put(key, oldCoeff + term.coeff);\n } else map.put(key, term.coeff);\n }\n }\n List<String> ans = new LinkedList<>();\n for(String k: map.keySet()) ans.add(map.get(k) + "" + k);\n return ans;\n }\n private List<Term> dewIt(int a, int b) {\n if(braces[a] == b) return dewIt(a+1, b-1);\n List<Term> ans = new LinkedList<>(), buffer = new LinkedList<>();\n buffer.add(new Term(1, new LinkedList<>()));\n for(int i=a; i<=b; ) {\n int j = i;\n List<Term> curr = null;\n if(arr[i] == \'(\') {\n j = braces[i] + 1;\n curr = dewIt(i+1, j-2);\n }\n else {\n while(j <= b && arr[j] != \' \') ++j;\n String exp = s.substring(i, j);\n int val = 1;\n List<String> vars = new LinkedList<>();\n if(variables.containsKey(exp)) val = variables.get(exp);\n else if (exp.charAt(0) <= \'9\') val = Integer.valueOf(exp);\n else vars.add(exp);\n curr = new LinkedList<>();\n curr.add(new Term(val, vars));\n }\n buffer = multiply(buffer, curr);\n if(j > b || arr[j+1] == \'+\' || arr[j+1] == \'-\') {\n ans.addAll(buffer);\n buffer = new LinkedList<>();\n }\n if(j < b) {\n ++j;\n if(arr[j] == \'+\') buffer.add(new Term(1, new LinkedList<>()));\n else if(arr[j] == \'-\') buffer.add(new Term(-1, new LinkedList<>()));\n j += 2;\n }\n i = j;\n }\n return ans;\n }\n private List<Term> multiply(List<Term> a, List<Term> b) {\n List<Term> ans = new LinkedList<>();\n for(Term x: a) for(Term y: b) {\n Term prod = x.clone();\n prod.multiply(y);\n ans.add(prod);\n }\n return ans;\n }\n}\nclass Term {\n int coeff;\n List<String> vars;\n\n public Term(int a, List<String> c) {\n this.coeff = a;\n vars = new LinkedList<>();\n vars.addAll(c);\n }\n public String getKey() {\n StringBuilder b = new StringBuilder();\n Collections.sort(vars);\n for(String x: vars) {\n b.append(\'*\');\n b.append(x);\n }\n return b.toString();\n }\n public void multiply(Term that) {\n this.coeff *= that.coeff;\n if(this.coeff == 0) vars.clear();\n else this.vars.addAll(that.vars);\n }\n public Term clone() {\n return new Term(coeff, vars);\n }\n}\n```\n
1
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. **Example 1:** **Input:** answers = \[1,1,2\] **Output:** 5 **Explanation:** The two rabbits that answered "1 " could both be the same color, say red. The rabbit that answered "2 " can't be red or the answers would be inconsistent. Say the rabbit that answered "2 " was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. **Example 2:** **Input:** answers = \[10,10,10\] **Output:** 11 **Constraints:** * `1 <= answers.length <= 1000` * `0 <= answers[i] < 1000`
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`. * `Poly:toList(this)` returns the polynomial in the correct output format. * `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`. * `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`. * `Solution::parse(expr)` parses an expression into a new `Poly`.
Standard Parser
basic-calculator-iv
0
1
```python\nclass Atom:\n def __init__(self, h={}):\n self.h = defaultdict(int)\n for k, v in h.items(): self.h[k] += v\n\n def __add__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] += other.h[k]\n return Atom({k: v for k, v in h.items() if v})\n\n def __sub__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] -= other.h[k]\n return Atom({k: v for k, v in h.items() if v})\n\n def __mul__(self, other):\n def f(k1, k2):\n k1, k2 = k1.split(\'*\'), k2.split(\'*\')\n k = [x for x in k1 if x] + [x for x in k2 if x]\n return \'*\'.join(sorted(k)) if k else \'\'\n h = defaultdict(int)\n for k in self.h:\n for kk in other.h:\n h[f(k, kk)] += self.h[k] * other.h[kk]\n print(\'here\', h, list(self.h.keys()), list(other.h.keys()))\n return Atom({k: v for k, v in h.items() if v})\n\n def __repr__(self):\n return str(self.h)\n\n def fmt(self):\n res = []\n for k, v in sorted(self.h.items(), key=lambda x : (-len(x[0].split(\'*\')), x[0])):\n if k: res.append(f\'{v}*{k}\')\n if self.h[\'\']: res.append(str(self.h[\'\']))\n return res\n\nclass Parser:\n def __init__(self, s, h):\n self.tokens = deque(re.findall(\'[a-z]+|[0-9]+|\\+|\\*|-|\\(|\\)\', s))\n self.h = h\n print(s)\n\n def _test(self, pred=lambda x : True):\n return self.tokens and pred(self.tokens[0])\n\n def _consume(self, pred=None):\n if pred: assert self._test(pred)\n return self.tokens.popleft()\n\n def _atom(self):\n if self._test(lambda x : x.isdigit()):\n return Atom({\'\': int(self._consume())})\n if self._test(lambda x : x.isalpha()):\n x = self._consume()\n if x in self.h:\n return Atom({\'\': self.h[x]})\n return Atom({x: 1})\n if self._test(lambda x : x == \'(\'):\n self._consume()\n res = self._l2()\n self._consume()\n return res\n\n def _l1(self):\n ops = {\n \'*\': lambda x, y : x * y,\n }\n res = self._atom()\n while self._test(lambda x : x in ops):\n op = ops[self._consume()]\n res = op(res, self._atom())\n return res\n \n def _l2(self):\n ops = {\n \'+\': lambda x, y : x + y,\n \'-\': lambda x, y : x - y,\n }\n res = self._l1()\n while self._test(lambda x : x in ops):\n op = ops[self._consume()]\n res = op(res, self._l1())\n return res\n\n def parse(self):\n res = self._l2()\n return res.fmt()\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n return Parser(expression, dict(zip(evalvars, evalints))).parse()\n```
0
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space separating each chunk and symbol. * A chunk is either an expression in parentheses, a variable, or a non-negative integer. * A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x "` or `"-x "`. Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. * For example, `expression = "1 + 2 * 3 "` has an answer of `[ "7 "]`. The format of the output is as follows: * For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. * For example, we would never write a term like `"b*a*c "`, only `"a*b*c "`. * Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. * For example, `"a*a*b*c "` has degree `4`. * The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. * An example of a well-formatted answer is `[ "-2*a*a*a ", "3*a*a*b ", "3*b*b ", "4*a ", "5*c ", "-6 "]`. * Terms (including constant terms) with coefficient `0` are not included. * For example, an expression of `"0 "` has an output of `[]`. **Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Example 1:** **Input:** expression = "e + 8 - a + 5 ", evalvars = \[ "e "\], evalints = \[1\] **Output:** \[ "-1\*a ", "14 "\] **Example 2:** **Input:** expression = "e - 8 + temperature - pressure ", evalvars = \[ "e ", "temperature "\], evalints = \[1, 12\] **Output:** \[ "-1\*pressure ", "5 "\] **Example 3:** **Input:** expression = "(e + 8) \* (e - 8) ", evalvars = \[\], evalints = \[\] **Output:** \[ "1\*e\*e ", "-64 "\] **Constraints:** * `1 <= expression.length <= 250` * `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`. * `expression` does not contain any leading or trailing spaces. * All the tokens in `expression` are separated by a single space. * `0 <= evalvars.length <= 100` * `1 <= evalvars[i].length <= 20` * `evalvars[i]` consists of lowercase English letters. * `evalints.length == evalvars.length` * `-100 <= evalints[i] <= 100`
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
Standard Parser
basic-calculator-iv
0
1
```python\nclass Atom:\n def __init__(self, h={}):\n self.h = defaultdict(int)\n for k, v in h.items(): self.h[k] += v\n\n def __add__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] += other.h[k]\n return Atom({k: v for k, v in h.items() if v})\n\n def __sub__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] -= other.h[k]\n return Atom({k: v for k, v in h.items() if v})\n\n def __mul__(self, other):\n def f(k1, k2):\n k1, k2 = k1.split(\'*\'), k2.split(\'*\')\n k = [x for x in k1 if x] + [x for x in k2 if x]\n return \'*\'.join(sorted(k)) if k else \'\'\n h = defaultdict(int)\n for k in self.h:\n for kk in other.h:\n h[f(k, kk)] += self.h[k] * other.h[kk]\n print(\'here\', h, list(self.h.keys()), list(other.h.keys()))\n return Atom({k: v for k, v in h.items() if v})\n\n def __repr__(self):\n return str(self.h)\n\n def fmt(self):\n res = []\n for k, v in sorted(self.h.items(), key=lambda x : (-len(x[0].split(\'*\')), x[0])):\n if k: res.append(f\'{v}*{k}\')\n if self.h[\'\']: res.append(str(self.h[\'\']))\n return res\n\nclass Parser:\n def __init__(self, s, h):\n self.tokens = deque(re.findall(\'[a-z]+|[0-9]+|\\+|\\*|-|\\(|\\)\', s))\n self.h = h\n print(s)\n\n def _test(self, pred=lambda x : True):\n return self.tokens and pred(self.tokens[0])\n\n def _consume(self, pred=None):\n if pred: assert self._test(pred)\n return self.tokens.popleft()\n\n def _atom(self):\n if self._test(lambda x : x.isdigit()):\n return Atom({\'\': int(self._consume())})\n if self._test(lambda x : x.isalpha()):\n x = self._consume()\n if x in self.h:\n return Atom({\'\': self.h[x]})\n return Atom({x: 1})\n if self._test(lambda x : x == \'(\'):\n self._consume()\n res = self._l2()\n self._consume()\n return res\n\n def _l1(self):\n ops = {\n \'*\': lambda x, y : x * y,\n }\n res = self._atom()\n while self._test(lambda x : x in ops):\n op = ops[self._consume()]\n res = op(res, self._atom())\n return res\n \n def _l2(self):\n ops = {\n \'+\': lambda x, y : x + y,\n \'-\': lambda x, y : x - y,\n }\n res = self._l1()\n while self._test(lambda x : x in ops):\n op = ops[self._consume()]\n res = op(res, self._l1())\n return res\n\n def parse(self):\n res = self._l2()\n return res.fmt()\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n return Parser(expression, dict(zip(evalvars, evalints))).parse()\n```
0
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. **Example 1:** **Input:** answers = \[1,1,2\] **Output:** 5 **Explanation:** The two rabbits that answered "1 " could both be the same color, say red. The rabbit that answered "2 " can't be red or the answers would be inconsistent. Say the rabbit that answered "2 " was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. **Example 2:** **Input:** answers = \[10,10,10\] **Output:** 11 **Constraints:** * `1 <= answers.length <= 1000` * `0 <= answers[i] < 1000`
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`. * `Poly:toList(this)` returns the polynomial in the correct output format. * `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`. * `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`. * `Solution::parse(expr)` parses an expression into a new `Poly`.
770: Solution with step by step explanation
basic-calculator-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__: Initializes the term with given expression or term.\n__add__, __sub__, __mul__: Arithmetic operations to add, subtract, and multiply two terms.\nget: Returns the term as a list of strings.\n_exp: Splits the variables in the term.\n_pm: Helps in addition and subtraction of two terms.\n\n```\n\nclass Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n # Check if \'exp\' is a number (including negative numbers)\n if re.match(r\'^\\-?\\d+$\', exp):\n # If it is a constant number, use empty string as key.\n self.d[\'\'] += int(exp)\n elif exp:\n # If it\'s a variable, set its coefficient to 1\n self.d[exp] += 1\n\n def __add__(self, other: \'Term\') -> \'Term\':\n # Delegate to helper function with \'add\' flag set to True\n return self._pm(other, add=True)\n\n def __mul__(self, other: \'Term\') -> \'Term\':\n # For multiplication, we\'ll iterate over each term of \'self\' and \'other\'\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n # Multiply the terms and add them to result\n res[\'*\'.join(sorted(self._exp(l_var) + self._exp(r_var)))] += l_coef * r_coef\n return Term(term=res)\n\n def __sub__(self, other: \'Term\') -> \'Term\':\n # Delegate to helper function with \'add\' flag set to False\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n # Convert the term to list of strings\n return [str(coef) + \'*\' * bool(var) + var for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n\n def _exp(self, var: str) -> List[str]:\n # Split the term into individual variables\n return list(filter(bool, var.split(\'*\')))\n\n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n # Helper function for addition and subtraction\n res = defaultdict(int, self.d)\n for var, coef in other.d.items():\n res[var] += coef * (-1) ** (1 - add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n # Create a dictionary to map variable names to their respective values\n vals = dict(zip(evalvars, evalints))\n # Evaluate the expression after replacing variables with their values or terms\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'" + str(vals.get(m.group(), m.group())) + "\')", expression)).get()\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 Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r\'^\\-?\\d+\n```, exp):\n self.d[\'\'] += int(exp)\n elif exp:\n self.d[exp] += 1\n \n def __add__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=True)\n \n def __mul__(self, other: \'Term\') -> \'Term\':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res[\'*\'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n \n def __sub__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+\'*\'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n \n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split(\'*\')))\n \n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'"+str(vals.get(m.group(), m.group()))+"\')", expression)).get()\n```
0
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space separating each chunk and symbol. * A chunk is either an expression in parentheses, a variable, or a non-negative integer. * A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x "` or `"-x "`. Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. * For example, `expression = "1 + 2 * 3 "` has an answer of `[ "7 "]`. The format of the output is as follows: * For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. * For example, we would never write a term like `"b*a*c "`, only `"a*b*c "`. * Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. * For example, `"a*a*b*c "` has degree `4`. * The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. * An example of a well-formatted answer is `[ "-2*a*a*a ", "3*a*a*b ", "3*b*b ", "4*a ", "5*c ", "-6 "]`. * Terms (including constant terms) with coefficient `0` are not included. * For example, an expression of `"0 "` has an output of `[]`. **Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Example 1:** **Input:** expression = "e + 8 - a + 5 ", evalvars = \[ "e "\], evalints = \[1\] **Output:** \[ "-1\*a ", "14 "\] **Example 2:** **Input:** expression = "e - 8 + temperature - pressure ", evalvars = \[ "e ", "temperature "\], evalints = \[1, 12\] **Output:** \[ "-1\*pressure ", "5 "\] **Example 3:** **Input:** expression = "(e + 8) \* (e - 8) ", evalvars = \[\], evalints = \[\] **Output:** \[ "1\*e\*e ", "-64 "\] **Constraints:** * `1 <= expression.length <= 250` * `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`. * `expression` does not contain any leading or trailing spaces. * All the tokens in `expression` are separated by a single space. * `0 <= evalvars.length <= 100` * `1 <= evalvars[i].length <= 20` * `evalvars[i]` consists of lowercase English letters. * `evalints.length == evalvars.length` * `-100 <= evalints[i] <= 100`
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
770: Solution with step by step explanation
basic-calculator-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__: Initializes the term with given expression or term.\n__add__, __sub__, __mul__: Arithmetic operations to add, subtract, and multiply two terms.\nget: Returns the term as a list of strings.\n_exp: Splits the variables in the term.\n_pm: Helps in addition and subtraction of two terms.\n\n```\n\nclass Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n # Check if \'exp\' is a number (including negative numbers)\n if re.match(r\'^\\-?\\d+$\', exp):\n # If it is a constant number, use empty string as key.\n self.d[\'\'] += int(exp)\n elif exp:\n # If it\'s a variable, set its coefficient to 1\n self.d[exp] += 1\n\n def __add__(self, other: \'Term\') -> \'Term\':\n # Delegate to helper function with \'add\' flag set to True\n return self._pm(other, add=True)\n\n def __mul__(self, other: \'Term\') -> \'Term\':\n # For multiplication, we\'ll iterate over each term of \'self\' and \'other\'\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n # Multiply the terms and add them to result\n res[\'*\'.join(sorted(self._exp(l_var) + self._exp(r_var)))] += l_coef * r_coef\n return Term(term=res)\n\n def __sub__(self, other: \'Term\') -> \'Term\':\n # Delegate to helper function with \'add\' flag set to False\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n # Convert the term to list of strings\n return [str(coef) + \'*\' * bool(var) + var for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n\n def _exp(self, var: str) -> List[str]:\n # Split the term into individual variables\n return list(filter(bool, var.split(\'*\')))\n\n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n # Helper function for addition and subtraction\n res = defaultdict(int, self.d)\n for var, coef in other.d.items():\n res[var] += coef * (-1) ** (1 - add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n # Create a dictionary to map variable names to their respective values\n vals = dict(zip(evalvars, evalints))\n # Evaluate the expression after replacing variables with their values or terms\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'" + str(vals.get(m.group(), m.group())) + "\')", expression)).get()\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 Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r\'^\\-?\\d+\n```, exp):\n self.d[\'\'] += int(exp)\n elif exp:\n self.d[exp] += 1\n \n def __add__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=True)\n \n def __mul__(self, other: \'Term\') -> \'Term\':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res[\'*\'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n \n def __sub__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+\'*\'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n \n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split(\'*\')))\n \n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'"+str(vals.get(m.group(), m.group()))+"\')", expression)).get()\n```
0
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. **Example 1:** **Input:** answers = \[1,1,2\] **Output:** 5 **Explanation:** The two rabbits that answered "1 " could both be the same color, say red. The rabbit that answered "2 " can't be red or the answers would be inconsistent. Say the rabbit that answered "2 " was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. **Example 2:** **Input:** answers = \[10,10,10\] **Output:** 11 **Constraints:** * `1 <= answers.length <= 1000` * `0 <= answers[i] < 1000`
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`. * `Poly:toList(this)` returns the polynomial in the correct output format. * `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`. * `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`. * `Solution::parse(expr)` parses an expression into a new `Poly`.
[Python] Cheating with eval(), thoughts?
basic-calculator-iv
0
1
### Explanation\n\nI basically built a class that automatically handles the addition, subtraction and multiplication of two expressions (called \'terms\'), overriding the `__add__()`, `__sub__()`, and `__mul__()` dunder methods respectively. All that\'s left to do is to parse each variable as a \'term\', and let Python\'s `eval()` do the logic handling for me.\n\nLazy, and borderline cheating, but I\'ll get around to implementing this properly next time around. It\'s also very OOP-based and quite Pythonic IMO.\n\n---\n\n### Code\n\n```python\nclass Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r\'^\\-?\\d+$\', exp):\n self.d[\'\'] += int(exp)\n elif exp:\n self.d[exp] += 1\n \n def __add__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=True)\n \n def __mul__(self, other: \'Term\') -> \'Term\':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res[\'*\'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n \n def __sub__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+\'*\'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n \n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split(\'*\')))\n \n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'"+str(vals.get(m.group(), m.group()))+"\')", expression)).get()\n```\n\n---\n\nLet me know your thoughts on this approach to the problem. Appreciate any other comments as well :)
1
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space separating each chunk and symbol. * A chunk is either an expression in parentheses, a variable, or a non-negative integer. * A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x "` or `"-x "`. Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. * For example, `expression = "1 + 2 * 3 "` has an answer of `[ "7 "]`. The format of the output is as follows: * For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. * For example, we would never write a term like `"b*a*c "`, only `"a*b*c "`. * Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. * For example, `"a*a*b*c "` has degree `4`. * The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. * An example of a well-formatted answer is `[ "-2*a*a*a ", "3*a*a*b ", "3*b*b ", "4*a ", "5*c ", "-6 "]`. * Terms (including constant terms) with coefficient `0` are not included. * For example, an expression of `"0 "` has an output of `[]`. **Note:** You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Example 1:** **Input:** expression = "e + 8 - a + 5 ", evalvars = \[ "e "\], evalints = \[1\] **Output:** \[ "-1\*a ", "14 "\] **Example 2:** **Input:** expression = "e - 8 + temperature - pressure ", evalvars = \[ "e ", "temperature "\], evalints = \[1, 12\] **Output:** \[ "-1\*pressure ", "5 "\] **Example 3:** **Input:** expression = "(e + 8) \* (e - 8) ", evalvars = \[\], evalints = \[\] **Output:** \[ "1\*e\*e ", "-64 "\] **Constraints:** * `1 <= expression.length <= 250` * `expression` consists of lowercase English letters, digits, `'+'`, `'-'`, `'*'`, `'('`, `')'`, `' '`. * `expression` does not contain any leading or trailing spaces. * All the tokens in `expression` are separated by a single space. * `0 <= evalvars.length <= 100` * `1 <= evalvars[i].length <= 20` * `evalvars[i]` consists of lowercase English letters. * `evalints.length == evalvars.length` * `-100 <= evalints[i] <= 100`
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
[Python] Cheating with eval(), thoughts?
basic-calculator-iv
0
1
### Explanation\n\nI basically built a class that automatically handles the addition, subtraction and multiplication of two expressions (called \'terms\'), overriding the `__add__()`, `__sub__()`, and `__mul__()` dunder methods respectively. All that\'s left to do is to parse each variable as a \'term\', and let Python\'s `eval()` do the logic handling for me.\n\nLazy, and borderline cheating, but I\'ll get around to implementing this properly next time around. It\'s also very OOP-based and quite Pythonic IMO.\n\n---\n\n### Code\n\n```python\nclass Term:\n def __init__(self, exp: Optional[str]=\'\', *, term: Optional[Mapping[str, int]]={}) -> None:\n self.d = defaultdict(int, **term)\n if re.match(r\'^\\-?\\d+$\', exp):\n self.d[\'\'] += int(exp)\n elif exp:\n self.d[exp] += 1\n \n def __add__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=True)\n \n def __mul__(self, other: \'Term\') -> \'Term\':\n res = defaultdict(int)\n for (l_var, l_coef), (r_var, r_coef) in product(self.d.items(), other.d.items()):\n res[\'*\'.join(sorted(self._exp(l_var)+self._exp(r_var)))] += l_coef*r_coef\n return Term(term=res)\n \n def __sub__(self, other: \'Term\') -> \'Term\':\n return self._pm(other, add=False)\n\n def get(self) -> List[str]:\n return [str(coef)+\'*\'*bool(var)+var \\\n for var, coef in sorted(self.d.items(), key=lambda t: (-len(self._exp(t[0])), t[0])) if coef]\n \n def _exp(self, var: str) -> List[str]:\n return list(filter(bool, var.split(\'*\')))\n \n def _pm(self, other: \'Term\', *, add: bool) -> \'Term\':\n res = copy.copy(self.d)\n for var, coef in other.d.items():\n res[var] += coef*(-1)**(1-add)\n return Term(term=res)\n\nclass Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n vals = dict(zip(evalvars, evalints))\n return eval(re.sub(r\'[a-z0-9]+\', lambda m: "Term(\'"+str(vals.get(m.group(), m.group()))+"\')", expression)).get()\n```\n\n---\n\nLet me know your thoughts on this approach to the problem. Appreciate any other comments as well :)
1
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. **Example 1:** **Input:** answers = \[1,1,2\] **Output:** 5 **Explanation:** The two rabbits that answered "1 " could both be the same color, say red. The rabbit that answered "2 " can't be red or the answers would be inconsistent. Say the rabbit that answered "2 " was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. **Example 2:** **Input:** answers = \[10,10,10\] **Output:** 11 **Constraints:** * `1 <= answers.length <= 1000` * `0 <= answers[i] < 1000`
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`. * `Poly:toList(this)` returns the polynomial in the correct output format. * `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`. * `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`. * `Solution::parse(expr)` parses an expression into a new `Poly`.
[C++] [Python] Brute Force Approach || Too Easy || Fully Explained
jewels-and-stones
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose we have the following inputs:\n```\nstring jw = "aA";\nstring st = "aAAbbbb";\n```\n\nNow, let\'s go through the function step by step:\n\n1. Initialize `count` to 0.\n2. Start a loop to iterate through the `jw` string using an index-based loop.\n - First iteration: `i` is 0, `jw[i]` is \'a\'.\n - Start another loop to iterate through the `st` string using an index-based loop.\n - First iteration: `j` is 0, `st[j]` is \'a\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'a\'). They are equal, so increment `count` to 1.\n - Second iteration: `j` is 1, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'A\'). They are not equal, so no change in `count`.\n - Third iteration: `j` is 2, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'A\'). They are not equal, so no change in `count`.\n - Fourth iteration: `j` is 3, `st[j]` is \'b\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'b\'). They are not equal, so no change in `count`.\n - The loop continues for the remaining characters in the `st` string.\n\n - Second iteration: `i` is 1, `jw[i]` is \'A\'.\n - Start another loop to iterate through the `st` string using an index-based loop.\n - First iteration: `j` is 0, `st[j]` is \'a\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'a\'). They are not equal, so no change in `count`.\n - Second iteration: `j` is 1, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'A\'). They are equal, so increment `count` to 2.\n - Third iteration: `j` is 2, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'A\'). They are equal, so increment `count` to 3.\n - Fourth iteration: `j` is 3, `st[j]` is \'b\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'b\'). They are not equal, so no change in `count`.\n - The loop continues for the remaining characters in the `st` string.\n\n3. After both loops, `count` is 3, which represents the number of characters in the `st` string that are also present in the `jw` string.\n# Complexity\n- Time complexity:$$O(n^2)$$\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``` C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jw, string st) {\n int count = 0;\n for(int i = 0; jw[i] != \'\\0\'; i++){\n for(int j = 0; st[j] !=\'\\0\'; j++){\n if(jw[i] == st[j])\n count++;\n }\n }\n return count;\n }\n};\n```\n``` Python []\nclass Solution:\n def numJewelsInStones(self, jw: str, st: str) -> int:\n count = 0\n for i in range(len(jw)):\n for j in range(len(st)):\n if jw[i] is st[j]:\n count += 1\n return count\n```
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
[C++] [Python] Brute Force Approach || Too Easy || Fully Explained
jewels-and-stones
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose we have the following inputs:\n```\nstring jw = "aA";\nstring st = "aAAbbbb";\n```\n\nNow, let\'s go through the function step by step:\n\n1. Initialize `count` to 0.\n2. Start a loop to iterate through the `jw` string using an index-based loop.\n - First iteration: `i` is 0, `jw[i]` is \'a\'.\n - Start another loop to iterate through the `st` string using an index-based loop.\n - First iteration: `j` is 0, `st[j]` is \'a\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'a\'). They are equal, so increment `count` to 1.\n - Second iteration: `j` is 1, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'A\'). They are not equal, so no change in `count`.\n - Third iteration: `j` is 2, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'A\'). They are not equal, so no change in `count`.\n - Fourth iteration: `j` is 3, `st[j]` is \'b\'.\n - Compare `jw[i]` (which is \'a\') with `st[j]` (which is \'b\'). They are not equal, so no change in `count`.\n - The loop continues for the remaining characters in the `st` string.\n\n - Second iteration: `i` is 1, `jw[i]` is \'A\'.\n - Start another loop to iterate through the `st` string using an index-based loop.\n - First iteration: `j` is 0, `st[j]` is \'a\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'a\'). They are not equal, so no change in `count`.\n - Second iteration: `j` is 1, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'A\'). They are equal, so increment `count` to 2.\n - Third iteration: `j` is 2, `st[j]` is \'A\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'A\'). They are equal, so increment `count` to 3.\n - Fourth iteration: `j` is 3, `st[j]` is \'b\'.\n - Compare `jw[i]` (which is \'A\') with `st[j]` (which is \'b\'). They are not equal, so no change in `count`.\n - The loop continues for the remaining characters in the `st` string.\n\n3. After both loops, `count` is 3, which represents the number of characters in the `st` string that are also present in the `jw` string.\n# Complexity\n- Time complexity:$$O(n^2)$$\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``` C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jw, string st) {\n int count = 0;\n for(int i = 0; jw[i] != \'\\0\'; i++){\n for(int j = 0; st[j] !=\'\\0\'; j++){\n if(jw[i] == st[j])\n count++;\n }\n }\n return count;\n }\n};\n```\n``` Python []\nclass Solution:\n def numJewelsInStones(self, jw: str, st: str) -> int:\n count = 0\n for i in range(len(jw)):\n for j in range(len(st)):\n if jw[i] is st[j]:\n count += 1\n return count\n```
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Solution
jewels-and-stones
1
1
```C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jewels, string stones) {\n int res=0;\n for (char c:stones) if (jewels.find(c)<jewels.length()) res++;\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n count = 0\n for stone in stones:\n if stone in jewels:\n count += 1\n return count\n```\n\n```Java []\nclass Solution {\n public static int numJewelsInStones(String jewels, String stones) {\n char[] jewArr = jewels.toCharArray();\n char[] stoneArr = stones.toCharArray();\n int ans = 0;\n\n for (int i = 0; i < jewArr.length; i++) {\n for (int j = 0; j < stoneArr.length; j++) {\n if (jewArr[i] == stoneArr[j]) {\n ans++;\n }\n }\n }\n return ans;\n }\n}\n```\n
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Solution
jewels-and-stones
1
1
```C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jewels, string stones) {\n int res=0;\n for (char c:stones) if (jewels.find(c)<jewels.length()) res++;\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n count = 0\n for stone in stones:\n if stone in jewels:\n count += 1\n return count\n```\n\n```Java []\nclass Solution {\n public static int numJewelsInStones(String jewels, String stones) {\n char[] jewArr = jewels.toCharArray();\n char[] stoneArr = stones.toCharArray();\n int ans = 0;\n\n for (int i = 0; i < jewArr.length; i++) {\n for (int j = 0; j < stoneArr.length; j++) {\n if (jewArr[i] == stoneArr[j]) {\n ans++;\n }\n }\n }\n return ans;\n }\n}\n```\n
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Python3 Hash Map Beats 98.25% Runtime | 65.81% Memory
jewels-and-stones
0
1
# Intuition\nJust count the number of occurrences of each jewel in stones via a hash map.\n\n# Approach\nCreate a hash map with each character in jewels as key and their frequency in stones as value. Initially all jewel counts are set to 0. Iterate over the stones string checking on each iteration whether it is a jewel or not, if so we increment they key-value pair by 1. \n\n# Complexity\n\nLet m & n be lengths of jewels and stones strings respectively.\n\n- Time complexity: $$\\bold O(\\bold n)$$\n\n- Space complexity: $$\\bold O(\\bold m)$$\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n\n jewel_map = {j:0 for j in jewels}\n\n for s in stones:\n if s in jewel_map:\n jewel_map[s] += 1\n \n return sum(jewel_map.values())\n```
3
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Python3 Hash Map Beats 98.25% Runtime | 65.81% Memory
jewels-and-stones
0
1
# Intuition\nJust count the number of occurrences of each jewel in stones via a hash map.\n\n# Approach\nCreate a hash map with each character in jewels as key and their frequency in stones as value. Initially all jewel counts are set to 0. Iterate over the stones string checking on each iteration whether it is a jewel or not, if so we increment they key-value pair by 1. \n\n# Complexity\n\nLet m & n be lengths of jewels and stones strings respectively.\n\n- Time complexity: $$\\bold O(\\bold n)$$\n\n- Space complexity: $$\\bold O(\\bold m)$$\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n\n jewel_map = {j:0 for j in jewels}\n\n for s in stones:\n if s in jewel_map:\n jewel_map[s] += 1\n \n return sum(jewel_map.values())\n```
3
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Solution of jewels and stones problem
jewels-and-stones
0
1
# Approach\n- Step one: create list of all jewels\n- Step two: check if the stone is on the list\n- Step three: return answer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as algorithm takes linear time and\n.count() function takes linear time --> O(n*n) == O(n^2).\n\n- Space complexity:\n$$O(n)$$ - as we use extra space for list\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n jew_list = list(jewels)\n answer = 0\n for jewel in jew_list:\n answer += stones.count(jewel)\n return answer\n \n```
3
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Solution of jewels and stones problem
jewels-and-stones
0
1
# Approach\n- Step one: create list of all jewels\n- Step two: check if the stone is on the list\n- Step three: return answer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as algorithm takes linear time and\n.count() function takes linear time --> O(n*n) == O(n^2).\n\n- Space complexity:\n$$O(n)$$ - as we use extra space for list\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n jew_list = list(jewels)\n answer = 0\n for jewel in jew_list:\n answer += stones.count(jewel)\n return answer\n \n```
3
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Simple 1 liner, with line by line explanation
jewels-and-stones
0
1
\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n return sum(x in jewels for x in stones)\n```\n# Line by Line\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n result = 0\n for x in list(stones):\n if x in jewels:\n result += 1\n return result \n```\nplease upvote :D
4
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Simple 1 liner, with line by line explanation
jewels-and-stones
0
1
\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n return sum(x in jewels for x in stones)\n```\n# Line by Line\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n result = 0\n for x in list(stones):\n if x in jewels:\n result += 1\n return result \n```\nplease upvote :D
4
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Easy to understand Python code
jewels-and-stones
0
1
# Complexity\n- Time complexity\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n m = {}\n for i in stones:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = 0\n for j in jewels:\n if j in m:\n ans += m[j]\n return ans\n```
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Easy to understand Python code
jewels-and-stones
0
1
# Complexity\n- Time complexity\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n m = {}\n for i in stones:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = 0\n for j in jewels:\n if j in m:\n ans += m[j]\n return ans\n```
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent. **Example 1:** **Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\] **Output:** 2 **Explanation:** One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row. **Example 2:** **Input:** board = \[\[0,1\],\[1,0\]\] **Output:** 0 **Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard. **Example 3:** **Input:** board = \[\[1,0\],\[1,0\]\] **Output:** -1 **Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard. **Constraints:** * `n == board.length` * `n == board[i].length` * `2 <= n <= 30` * `board[i][j]` is either `0` or `1`.
For each stone, check if it is a jewel.
Python 3 || 17 lines, BFS || T/M: 99% / 91%
sliding-puzzle
0
1
```\nmoves = ((1,3), (0,2,4), (1,5),\n (0,4), (1,3,5), (2,4))\n\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n\n state = (*board[0], *board[1])\n queue, seen, cnt = deque([state]), set(), 0\n\n while queue:\n\n for _ in range(len(queue)):\n state = list(queue.popleft())\n idx = state.index(0)\n if state == [1,2,3,4,5,0]: return cnt\n\n for i in moves[idx]:\n curr = state[:]\n curr[idx], curr[i] = curr[i], 0\n curr = tuple(curr)\n if curr in seen: continue\n queue.append(curr)\n seen.add(curr)\n\n cnt+= 1\n\n return -1\n```\n[https://leetcode.com/problems/sliding-puzzle/submissions/998764708/](http://)\n\nThe time and space complexities are tough to determine (at least for me). One could say they are each *O*(1)because of the 2 x 3 constraint, but that seems like cheating.\n\nThere are 6! = 720 possible states for `board`, but exactly 360 (those permutations with *odd parity*) quickly resolve to "unsolvable".\n\nThat still leaves 360 states to possibly iterate through before solving a given solvable state, but it can be shown that all states resolve to a solution in at most 21 iterations.
3
On an `2 x 3` board, there are five tiles labeled from `1` to `5`, and an empty square represented by `0`. A **move** consists of choosing `0` and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is `[[1,2,3],[4,5,0]]`. Given the puzzle board `board`, return _the least number of moves required so that the state of the board is solved_. If it is impossible for the state of the board to be solved, return `-1`. **Example 1:** **Input:** board = \[\[1,2,3\],\[4,0,5\]\] **Output:** 1 **Explanation:** Swap the 0 and the 5 in one move. **Example 2:** **Input:** board = \[\[1,2,3\],\[5,4,0\]\] **Output:** -1 **Explanation:** No number of moves will make the board solved. **Example 3:** **Input:** board = \[\[4,1,2\],\[5,0,3\]\] **Output:** 5 **Explanation:** 5 is the smallest number of moves that solves the board. An example path: After move 0: \[\[4,1,2\],\[5,0,3\]\] After move 1: \[\[4,1,2\],\[0,5,3\]\] After move 2: \[\[0,1,2\],\[4,5,3\]\] After move 3: \[\[1,0,2\],\[4,5,3\]\] After move 4: \[\[1,2,0\],\[4,5,3\]\] After move 5: \[\[1,2,3\],\[4,5,0\]\] **Constraints:** * `board.length == 2` * `board[i].length == 3` * `0 <= board[i][j] <= 5` * Each value `board[i][j]` is **unique**.
null
Python 3 || 17 lines, BFS || T/M: 99% / 91%
sliding-puzzle
0
1
```\nmoves = ((1,3), (0,2,4), (1,5),\n (0,4), (1,3,5), (2,4))\n\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n\n state = (*board[0], *board[1])\n queue, seen, cnt = deque([state]), set(), 0\n\n while queue:\n\n for _ in range(len(queue)):\n state = list(queue.popleft())\n idx = state.index(0)\n if state == [1,2,3,4,5,0]: return cnt\n\n for i in moves[idx]:\n curr = state[:]\n curr[idx], curr[i] = curr[i], 0\n curr = tuple(curr)\n if curr in seen: continue\n queue.append(curr)\n seen.add(curr)\n\n cnt+= 1\n\n return -1\n```\n[https://leetcode.com/problems/sliding-puzzle/submissions/998764708/](http://)\n\nThe time and space complexities are tough to determine (at least for me). One could say they are each *O*(1)because of the 2 x 3 constraint, but that seems like cheating.\n\nThere are 6! = 720 possible states for `board`, but exactly 360 (those permutations with *odd parity*) quickly resolve to "unsolvable".\n\nThat still leaves 360 states to possibly iterate through before solving a given solvable state, but it can be shown that all states resolve to a solution in at most 21 iterations.
3
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.