title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
βŒ€
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Reverse Nodes in Even Length Groups
reverse-nodes-in-even-length-groups
You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list.
Linked List
Medium
Consider the list structure ...A β†’ (B β†’ ... β†’ C) β†’ D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B β†’ ... β†’ C reversed (because it was of even length) so that it is now C β†’ ... β†’ B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.
2,253
26
Similiar to [25. Reverse Nodes in k-Group](), reverse a range of linked list when the range has an even length\n```\ndef reverseEvenLengthGroups(head):\n\tprev = head\n\td = 2 # the head doesn\'t need to be reversed anytime so starts with length 2\n\twhile prev.next:\n\t\tnode, n = prev, 0\n\t\tfor _ in range(d):\n\t\t\tif not node.next:\n\t\t\t\tbreak\n\t\t\tn += 1\n\t\t\tnode = node.next\n\t\tif n & 1: # odd length\n\t\t\tprev = node\n\t\telse: # even length\n\t\t\tnode, rev = prev.next, None\n\t\t\tfor _ in range(n):\n\t\t\t\tnode.next, node, rev = rev, node.next, node\n\t\t\tprev.next.next, prev.next, prev = node, rev, prev.next\n\t\td += 1\n\treturn head\n```\n\nCheat during the contest to save time, convert linked list to a list and then just do slice reversion.\nOf course cost extra O(n) space\n```\ndef reverseEvenLengthGroups(self, head):\n\ta = []\n\tnode = head\n\twhile node:\n\t\ta.append(node.val)\n\t\tnode = node.next\n\ti, d, n = 0, 1, len(a)\n\twhile i < n:\n\t\tif min(d, n-i) & 1 == 0:\n\t\t\ta[i:i+d] = a[i:i+d][::-1]\n\t\ti += d\n\t\td += 1\n\tnode = head\n\tfor x in a:\n\t\tnode.val = x\n\t\tnode = node.next\n\treturn head\n```
103,822
Reverse Nodes in Even Length Groups
reverse-nodes-in-even-length-groups
You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list.
Linked List
Medium
Consider the list structure ...A β†’ (B β†’ ... β†’ C) β†’ D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B β†’ ... β†’ C reversed (because it was of even length) so that it is now C β†’ ... β†’ B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.
952
7
```\nclass Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n start_joint = head \n group_size = 1\n while start_joint and start_joint.next: \n group_size += 1\n start = end = start_joint.next \n group_num = 1 \n while end and end.next and group_num < group_size: \n end = end.next \n group_num += 1 \n end_joint = end.next \n if group_num % 2 != 0: \n start_joint = end \n continue \n start_joint.next = self.reverse(start, end, end_joint)\n start_joint = start \n return head\n def reverse(self, start, end, end_joint): \n prev, curr = end_joint, start\n while curr and curr != end_joint: \n next_node = curr.next\n curr.next = prev\n prev, curr = curr, next_node\n return prev\n```\nComments: This questions is a hard, it uses concepts from other hard questions like Reverse K-Nodes in Group, do not attempt if you are a beginner or haven\'t had experience with those type of problems. The helper function reverse neatly reverses between start and end, makes sure the reversed end points to the node after end originally(end_joint), and `start_joint.next = self.reverse()` ties it all up. The remainder of the tricky part is handling the odd/even and not matching group_sizes. For those still confused of why there is start_joint, end_joint, this is because you need to maintain the node before and after the part that is being reversed.\n
103,824
Reverse Nodes in Even Length Groups
reverse-nodes-in-even-length-groups
You are given the head of a linked list. The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words, Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. Reverse the nodes in each group with an even length, and return the head of the modified linked list.
Linked List
Medium
Consider the list structure ...A β†’ (B β†’ ... β†’ C) β†’ D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B β†’ ... β†’ C reversed (because it was of even length) so that it is now C β†’ ... β†’ B. What references do you need to fix so that the transitions between the previous, current, and next groups are correct? A.next should be set to C, and B.next should be set to D. Once the current group is finished being modified, you need to find the new A, B, C, and D nodes for the next group. How can you use the old A, B, C, and D nodes to find the new ones? The new A is either the old B or old C depending on if the group was of even or odd length. The new B is always the old D. The new C and D can be found based on the new B and the next group's length. You can set the initial values of A, B, C, and D to A = null, B = head, C = head, D = head.next. Repeat the steps from the previous hints until D is null.
972
13
Downvoters, leave a comment! \n\nPlease check out this [commit]() for solutions of weekly 267.\n```\nclass Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n n, node = 0, head\n while node: n, node = n+1, node.next\n \n k, node = 0, head \n while n: \n k += 1\n size = min(k, n)\n stack = []\n if not size & 1: \n temp = node \n for _ in range(size): \n stack.append(temp.val)\n temp = temp.next \n for _ in range(size): \n if stack: node.val = stack.pop()\n node = node.next \n n -= size\n return head \n```
103,829
Decode the Slanted Ciphertext
decode-the-slanted-ciphertext
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.
String,Simulation
Medium
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
2,845
64
Knowing `rows`, we can find out `cols`. Knowing `cols`, we can jump to the next letter (`cols + 1`).\n\nExample: `"ch ie pr"`, rows = 3, columns = 12 / 3 = 4.\n0: [0, 5, 10] `"cip"`\n1: [1, 6, 11] `"her"`\n2: [2, 7] `" "` <- we will trim this.\n3: [3, 8] `" "` <- we will trim this.\n\n**Java**\n```java\npublic String decodeCiphertext(String encodedText, int rows) {\n int sz = encodedText.length(), cols = sz / rows;\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < cols; ++i)\n for (int j = i; j < sz; j += cols + 1)\n sb.append(encodedText.charAt(j));\n return sb.toString().stripTrailing();\n}\n```\n**Python 3**\n```python\nclass Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n cols, res = len(encodedText) // rows, ""\n for i in range(cols):\n for j in range(i, len(encodedText), cols + 1):\n res += encodedText[j]\n return res.rstrip()\n```\n**C++**\n```cpp\nstring decodeCiphertext(string encodedText, int rows) {\n int sz = encodedText.size(), cols = sz / rows;\n string res;\n for (int i = 0; i < cols; ++i)\n for (int j = i; j < sz; j += cols + 1)\n res += encodedText[j];\n while (!res.empty() && isspace(res.back()))\n res.pop_back();\n return res;\n}\n\n```
103,863
Decode the Slanted Ciphertext
decode-the-slanted-ciphertext
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.
String,Simulation
Medium
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
592
5
This solution works as the problem states "the rightmost column will not be empty after filling in `originalText`". But then just wonder why it not avoid corner cases as `len(originalText) == 0`. Anyway, testcase like `"a ", 4` is treated as invalid case.\n```\ndef decodeCiphertext(s, r):\n\tk = len(s) // r\n\tmat = [s[i*k+i:i*k+k] for i in range(r)]\n\tmat[-1] += " " # handle trailing characters for rows in mat[:-1]\n\treturn "".join(map("".join, zip(*mat))).rstrip()\n```
103,869
Two Furthest Houses With Different Colors
two-furthest-houses-with-different-colors
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Array,Greedy
Easy
The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
3,949
80
The maximum distance will always include either first or the last house. This can be proven by a contradiction.\n\nTherefore, we need to return the maximum of two cases: `max(j, n - i - 1)`, where\n- `i` is the leftmost position of the color different from the last color.\n- `j` is the rightmost position of the color different from the first one.\n\n![image]()\n\n**C++**\n```cpp\nint maxDistance(vector<int>& cs) {\n int n = cs.size(), i = 0, j = n - 1;\n while (cs[0] == cs[j])\n --j;\n while (cs[n - 1] == cs[i])\n ++i;\n return max(j, n - i - 1);\n}\n```\n**Java**\n```java\npublic int maxDistance(int[] cs) {\n int n = cs.length, i = 0, j = n - 1;\n while (cs[0] == cs[j])\n --j;\n while (cs[n - 1] == cs[i])\n ++i;\n return Math.max(j, n - i - 1); \n}\n```\n\n#### Alternative Solution\nWe only care about two positions: `0` for the first color, and the first position for some other color (`p`).\n\nIt works since we are looking for a maximum distance:\n- If color `i` is different than the first one, the maximum distance is `i`.\n- If color `i` is the same as the first one, the maximum distance is `i - p`.\n\n**Python 3**\n```python\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n p, res = inf, 0\n for i, c in enumerate(colors):\n if (c != colors[0]):\n res = i\n p = min(p, i)\n else:\n res = max(res, i - p)\n return res\n```\n**C++**\n```cpp\nint maxDistance(vector<int>& cs) {\n int p = INT_MAX, res = 1;\n for (int i = 1; i < cs.size(); ++i) {\n if (cs[i] != cs[0])\n p = min(i, p);\n res = max({res, cs[i] == cs[0] ? 0 : i, i - p });\n }\n return res;\n}\n```\n**Java**\n```java\npublic int maxDistance(int[] cs) {\n int p_col2 = Integer.MAX_VALUE, res = 1;\n for (int i = 1; i < cs.length; ++i) {\n if (cs[i] != cs[0]) {\n p_col2 = Math.min(i, p_col2);\n res = i;\n }\n else\n res = Math.max(res, i - p_col2);\n }\n return res; \n}\n```
103,965
Two Furthest Houses With Different Colors
two-furthest-houses-with-different-colors
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Array,Greedy
Easy
The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
1,735
33
Downvoters, lease a comment! \n\nIt is not difficult to find out that at least one of the end points will be used. \n\nPlease check out this [commit]() for the solutions of weekly 268. \n```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n ans = 0 \n for i, x in enumerate(colors): \n if x != colors[0]: ans = max(ans, i)\n if x != colors[-1]: ans = max(ans, len(colors)-1-i)\n return ans \n```
103,969
Two Furthest Houses With Different Colors
two-furthest-houses-with-different-colors
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Array,Greedy
Easy
The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
901
6
Easiest way to do a scan like this is with two pointers. Fix a left pointer, and while they\'re equal, move the right pointer from the end, inward until they arent. Then, take the distance by index. However, that will only solve the example cases. To correctly solve an edge case (where Greedy comes in to play), do the same thing but from the other end. Fix the right pointer at the end and move the left pointer by one every time. Since you\'re making two separate passes, time complexity isn\'t compounding so it is just O(n). No extra space, either O(1). \n![image]()\n\n```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n\t\t#first pass\n l, r = 0, len(colors)-1\n dist = 0\n \n while r > l:\n if colors[r] != colors[l]:\n dist = r-l\n\t\t\t\t#slight performance increase, break out if you find it \n\t\t\t\t#because it can\'t get bigger than this\n break \n r -= 1\n\t\t\t\n #second pass, backwards\n l, r = 0, len(colors)-1\n while r > l:\n if colors[r] != colors[l]:\n dist = max(dist, r-l)\n break\n l += 1\n \n return dist\n\t\n\t
103,988
Two Furthest Houses With Different Colors
two-furthest-houses-with-different-colors
There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.
Array,Greedy
Easy
The constraints are small. Can you try the combination of every two houses? Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
1,024
6
```\ndef maxDistance(self, colors: List[int]) -> int:\n m=0\n for i in range(0,len(colors)):\n for j in range(len(colors)-1,0,-1):\n if colors[i]!=colors[j] and j>i:\n m=max(m,j-i)\n return m\n```
104,000
Stamping the Grid
stamping-the-grid
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements: Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.
Array,Greedy,Matrix,Prefix Sum
Hard
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restrictions and requirements. For each row, find every consecutive row of empty cells, and mark all the cells where the consecutive row is at least stampWidth wide. Do the same for the columns with stampHeight. Then, you can check if every cell is marked twice.
6,334
83
# **Pre-Knowledge**\nCalulate the sub-matrix sum.\n<br>\n\n# **Intitution**\n`M[i][j]` can be coverd by any stamp with right-bottom point\nin the sub-matrix from `(i,j)` to `(i + h - 1, j + w - 1)`.\n\nA stamp with right-bottom point at `(i,j)` can fit,\nif the sub the sub-matrix from `(i - h + 1, j - w + 1)` to `(i,j)` is all empty.\n\nSo we just need to calulate the sub-matrix sum **twice**.\n<br>\n\n# **Explanation**\n`M` is the input matrix.\n\n`A[i][j]` means the total empty points in the rectangle,\nwith top-left at `(0, 0)` and right-bottom at `(i - 1, j - 1)`.\n\n`good[i][j]` means it fits a stamp with stamp right-bottom at `(i, j)`\n\n\n`B[i][j]` means the sub-martix is all empty,\nwith top-left at `(0, 0)` and right-bottom at `(i - 1, j - 1)`\n\n`M[i][j]` can be coverd by any stamp with right-bottom point\nin the sub-matrix from `(i,j)` to `(i + w - 1, j + h - 1)`.\n\n<br>\n\n# **Complexity**\nTime `O(mn)`\nSpace `O(mn)`\n<br>\n\n**Java**\n```java\n public boolean possibleToStamp(int[][] M, int h, int w) {\n int m = M.length, n = M[0].length;\n int[][] A = new int[m + 1][n + 1], B = new int[m + 1][n + 1], good = new int[m][n];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + (1 - M[i][j]);\n if (i + 1 >= h && j + 1 >= w) { \n int x = i + 1 - h, y = j + 1 - w;\n if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == w * h)\n good[i][j]++;\n }\n }\n }\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + good[i][j];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n int x = Math.min(i + h, m), y = Math.min(j + w, n);\n if (M[i][j] == 0 && B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0)\n return false;\n }\n }\n return true; \n }\n```\n\n**C++**\n```cpp\n bool possibleToStamp(vector<vector<int>>& M, int h, int w) {\n int m = M.size(), n = M[0].size();\n vector<vector<int>> A(m + 1, vector<int>(n + 1)), B(m + 1, vector<int>(n + 1)), good(m, vector<int>(n));\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + (1 - M[i][j]);\n if (i + 1 >= h && j + 1 >= w) {\n int x = i + 1 - h, y = j + 1 - w;\n if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == w * h)\n good[i][j]++;\n }\n }\n }\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + good[i][j];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n int x = min(i + h, m), y = min(j + w, n);\n if (M[i][j] == 0 && B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0)\n return false;\n }\n }\n return true;\n }\n```\n\n**Python**\n```py\n def possibleToStamp(self, M, h, w):\n m, n = len(M), len(M[0])\n A = [[0] * (n + 1) for _ in range(m + 1)]\n good = [[0] * n for _ in range(m)]\n for i in xrange(m):\n for j in xrange(n):\n A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + (1 - M[i][j])\n if i + 1 >= h and j + 1 >= w:\n x, y = i + 1 - h, j + 1 -w\n if A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == w * h:\n good[i][j] += 1\n B = [[0] * (n + 1) for _ in range(m + 1)]\n for i in xrange(m):\n for j in xrange(n):\n B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + good[i][j]\n for i in xrange(m):\n for j in xrange(n):\n x, y = min(i + h, m), min(j + w, n)\n if M[i][j] == 0 and B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0:\n return False\n return True\n```\n
104,012
Valid Arrangement of Pairs
valid-arrangement-of-pairs
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.
Depth-First Search,Graph,Eulerian Circuit
Hard
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
2,242
39
Please check out this [commit]() for solutions of weekly 270.\n\n```\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n graph = defaultdict(list)\n degree = defaultdict(int) # net out degree \n for x, y in pairs: \n graph[x].append(y)\n degree[x] += 1\n degree[y] -= 1\n \n for k in degree: \n if degree[k] == 1: \n x = k\n break \n \n ans = []\n\n def fn(x): \n """Return Eulerian path via dfs."""\n while graph[x]: fn(graph[x].pop()) \n ans.append(x)\n \n fn(x)\n ans.reverse()\n return [[ans[i], ans[i+1]] for i in range(len(ans)-1)]\n```\n\nAdding an iterative implementation of Hieholzer\'s algo from @delphih\n```\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n graph = defaultdict(list)\n degree = defaultdict(int) # net out degree \n for x, y in pairs: \n graph[x].append(y)\n degree[x] += 1\n degree[y] -= 1\n \n for k in degree: \n if degree[k] == 1: \n x = k\n break \n \n ans = []\n stack = [x]\n while stack: \n while graph[stack[-1]]: \n stack.append(graph[stack[-1]].pop())\n ans.append(stack.pop())\n ans.reverse()\n return [[ans[i], ans[i+1]] for i in range(len(ans)-1)]\n```
104,062
Valid Arrangement of Pairs
valid-arrangement-of-pairs
You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti. Return any valid arrangement of pairs. Note: The inputs will be generated such that there exists a valid arrangement of pairs.
Depth-First Search,Graph,Eulerian Circuit
Hard
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
4,263
42
Basically finding the [Eulerian path]() in a directed graph. \n\nAlgorithm: [Hierholzer\'s Algorithm](\'s_algorithm)\n\nSee also: [332. Reconstruct Itinerary]()\n\nMy code:\n```py\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n g = defaultdict(list) # graph\n din, dout = Counter(), Counter() #in degree, out degree\n for u, v in pairs:\n g[u].append(v)\n dout[u] += 1\n din[v] += 1\n\n S = pairs[0][0] # Start anywhere if it\'s an Eulerian cycle.\n for p in dout:\n if dout[p] - din[p] == 1: # It\'s an Eulerian trail. Have to start here\n S = p\n break\n \n\t\t# Hierholzer\'s Algorithm:\n route = []\n st = [S]\n while st:\n while g[st[-1]]:\n st.append(g[st[-1]].pop())\n route.append(st.pop())\n route.reverse()\n return [[route[i], route[i+1]] for i in range(len(route)-1)]\n```
104,063
Sum of k-Mirror Numbers
sum-of-k-mirror-numbers
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n, return the sum of the n smallest k-mirror numbers.
Math,Enumeration
Hard
Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to "generate" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated is a "k-Mirror" number.
3,361
48
Please check out this [commit]() for the solutions of weekly 268. \n\n```\nclass Solution:\n def kMirror(self, k: int, n: int) -> int:\n \n def fn(x):\n """Return next k-symmetric number."""\n n = len(x)//2\n for i in range(n, len(x)): \n if int(x[i])+1 < k: \n x[i] = x[~i] = str(int(x[i])+1)\n for ii in range(n, i): x[ii] = x[~ii] = \'0\'\n return x\n return ["1"] + ["0"]*(len(x)-1) + ["1"]\n \n x = ["0"]\n ans = 0\n for _ in range(n): \n while True: \n x = fn(x)\n val = int("".join(x), k)\n if str(val)[::-1] == str(val): break\n ans += val\n return ans \n```
104,110
Sum of k-Mirror Numbers
sum-of-k-mirror-numbers
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. Given the base k and the number n, return the sum of the n smallest k-mirror numbers.
Math,Enumeration
Hard
Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to "generate" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated is a "k-Mirror" number.
795
10
```python\nclass Solution:\n def kMirror(self, k: int, n: int) -> int:\n\n def numberToBase(n, b):\n if n == 0:\n return [0]\n digits = []\n while n:\n digits.append(n % b)\n n //= b\n return digits[::-1]\n \n # not used\n def baseToNumber(arr, b):\n ans = 0\n for x in arr:\n ans = ans * b + int(x)\n return ans\n \n def is_mirror(s):\n l, r = 0, len(s)-1\n while l <= r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\n return True\n \n def gen():\n \'\'\'\n generate for value with different length\n when i == 0: num\uFF1A[1, 10)\n size of num: 1, 2 -> 1 or 11\n when i == 1: [10, 100)\n size of num: 3, 4 -> 10 or 101\n when i == 2: [100, 1000)\n size of num: 5, 6 -> 10001 or 100001\n \n the num will be increasing\n \'\'\'\n for i in range(30):\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1][1:]\n yield int(s)\n for num in range(10**i, 10**(i+1)):\n s = str(num) + str(num)[::-1]\n yield int(s)\n \n ans = 0\n left = n\n for num in gen():\n base = numberToBase(num, k)\n\t\t\t# if is_mirror(base):\n if base == base[::-1]:\n ans += num\n left -= 1\n if left == 0:\n break\n\n return ans\n```
104,119
Find Subsequence of Length K With the Largest Sum
find-subsequence-of-length-k-with-the-largest-sum
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Array,Hash Table,Sorting,Heap (Priority Queue)
Easy
From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?
11,567
59
**Method 1: Sort**\n\n*Sort the whole array*\n1. Combine each index with its corresponding value to create a 2-d array;\n2. Sort the 2-d array reversely by value, then copy the largest k ones;\n3. Sort the largest k ones by index, then return the corresponding values by index order.\n\n```java\n public int[] maxSubsequence(int[] nums, int k) {\n int n = nums.length;\n int[][] indexAndVal = new int[n][2];\n for (int i = 0; i < n; ++i) {\n indexAndVal[i] = new int[]{i, nums[i]};\n }\n // Reversely sort by value.\n Arrays.sort(indexAndVal, Comparator.comparingInt(a -> -a[1]));\n int[][] maxK = Arrays.copyOf(indexAndVal, k);\n // Sort by index.\n Arrays.sort(maxK, Comparator.comparingInt(a -> a[0]));\n int[] seq = new int[k];\n for (int i = 0; i < k; ++i) {\n seq[i] = maxK[i][1];\n }\n return seq;\n }\n```\n```python\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n val_and_index = sorted([(num, i) for i, num in enumerate(nums)])\n return [num for num, i in sorted(val_and_index[-k :], key=lambda x: x[1])]\n```\n\n**Analysis:**\n\nTime: `O(n * logn)`, space: `O(n)`.\n\n----\n\n**Method 2: PriorityQueue/heap**\n\n**Two Passes**\n\n1. Travse input and use PriorityQueue / heap to store `k` largest items, poll out if its size bigger than `k`;\n2. Use Map/dict to store the `k` items in 1.;\n3. Traverse input again, if encounter any item in the afore-mentioned Map/ dict, save it into the output array, then remove the item from the Map/dict.\n```java\n public int[] maxSubsequence(int[] nums, int k) {\n PriorityQueue<Integer> pq = new PriorityQueue<>(k + 1);\n for (int n : nums) {\n pq.offer(n);\n if (pq.size() > k) {\n pq.poll();\n }\n }\n Map<Integer, Integer> freq = new HashMap<>();\n for (int n : pq) {\n freq.merge(n, 1, Integer::sum);\n }\n int[] seq = new int[k]; \n int i = 0;\n for (int n : nums) {\n if (freq.merge(n, -1, Integer::sum) >= 0) {\n seq[i++] = n;\n }\n }\n return seq;\n }\n```\n```python\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n heap = []\n for n in nums:\n heapq.heappush(heap, n)\n if len(heap) > k:\n heapq.heappop(heap)\n cnt = Counter(heap)\n res = []\n for n in nums:\n if cnt[n] > 0:\n cnt[n] -= 1\n res.append(n)\n return res\n```\n\n----\n\n*Simplified the above to **One pass*** - credit to **@climberig**\n\nStore indexes of the input array by PriorityQueue/heap, and get rid of Map/dict.\n\n```java\n public int[] maxSubsequence(int[] nums, int k) {\n PriorityQueue<Integer> pq = new PriorityQueue<>\n (Comparator.comparingInt(i -> nums[i]));\n for (int i = 0; i < nums.length; ++i) {\n pq.offer(i);\n if (pq.size() > k) {\n pq.poll();\n }\n }\n return pq.stream().sorted().mapToInt(i -> nums[i]).toArray();\n }\n```\n```python\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n heap = []\n for i, n in enumerate(nums):\n heapq.heappush(heap, (n, i))\n if len(heap) > k:\n heapq.heappop(heap)\n return [a[0] for a in sorted(heap, key=lambda x: x[1])] \n```\n\nTime: `O(n * logk)`, space: `O(k)`\n\n----\n\n**Method 3: Quick Select**\n\n```java\n public int[] maxSubsequence(int[] nums, int k) {\n int n = nums.length;\n int[] index = new int[n];\n for (int i = 0; i < n; ++i) {\n index[i] = i;\n }\n \n // Use Quick Select to put the indexes of the \n // max k items to the left of index array. \n int lo = 0, hi = n - 1;\n while (lo < hi) {\n int idx = quickSelect(nums, index, lo, hi);\n if (idx < k) {\n lo = idx + 1;\n }else {\n hi = idx;\n }\n }\n \n // Count the occurrencs of the kth largest items\n // within the k largest ones.\n int kthVal = nums[index[k - 1]], freqOfkthVal = 0;\n for (int i : Arrays.copyOf(index, k)) {\n freqOfkthVal += nums[i] == kthVal ? 1 : 0;\n }\n \n // Greedily copy the subsequence into output array seq.\n int[] seq = new int[k];\n int i = 0;\n for (int num : nums) {\n if (num > kthVal || num == kthVal && freqOfkthVal-- > 0) {\n seq[i++] = num;\n }\n }\n return seq;\n }\n \n // Divide index[lo...hi] into two parts: larger and less than \n // the pivot; Then return the position of the pivot;\n private int quickSelect(int[] nums, int[] index, int lo, int hi) {\n int pivot = index[lo];\n while (lo < hi) {\n while (lo < hi && nums[index[hi]] <= nums[pivot]) {\n --hi;\n }\n index[lo] = index[hi];\n while (lo < hi && nums[index[lo]] >= nums[pivot]) {\n ++lo;\n }\n index[hi] = index[lo];\n } \n index[lo] = pivot;\n return lo;\n }\n```\n```python\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n \n # Divide index[lo...hi] into two parts: larger and less than \n # the pivot; Then return the position of the pivot;\n def quickSelect(lo: int, hi: int) -> int:\n pivot = index[lo]\n while lo < hi:\n while lo < hi and nums[index[hi]] <= nums[pivot]:\n hi -= 1\n index[lo] = index[hi]\n while lo < hi and nums[index[lo]] >= nums[pivot]:\n lo += 1\n index[hi] = index[lo]\n index[lo] = pivot\n return lo\n\n n = len(nums)\n index = list(range(n))\n \n # Use Quick Select to put the indexes of the \n # max k items to the left of index array.\n left, right = 0, n - 1\n while left < right:\n idx = quickSelect(left, right)\n if idx < k:\n left = idx + 1\n else:\n right = idx\n \n # Count the occurrencs of the kth largest items\n # within the k largest ones.\n kth_val, freq_of_kth_val = nums[index[k - 1]], 0\n for i in index[ : k]:\n if nums[i] == kth_val:\n freq_of_kth_val += 1\n \n # Greedily copy the subsequence into output array seq.\n seq = []\n for num in nums:\n if num > kth_val or num == kth_val and freq_of_kth_val > 0:\n seq.append(num)\n if num == kth_val:\n freq_of_kth_val -= 1\n return seq\n```\nTime: average `O(n)`, worst `O(n ^ 2)`, space: `O(n)`.\n\n----\n\n***Please feel free to let me know if you can make the codes better.***
104,165
Find Subsequence of Length K With the Largest Sum
find-subsequence-of-length-k-with-the-largest-sum
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Array,Hash Table,Sorting,Heap (Priority Queue)
Easy
From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?
3,950
24
* The subsequence of length k with the largest sum are composed of the largest k numbers in nums.\n* \'sorted(nums, reverse=True)[:k]\' can find the largest k numbers in num, but destroy their original order.\n* We can traverse the list again and reconstruct the original order of max_k in the list.\n\n**Python 100% Faster**\n```\nclass Solution(object):\n def maxSubsequence(self, nums, k):\n ret, max_k = [], sorted(nums, reverse=True)[:k]\n for num in nums:\n if num in max_k:\n ret.append(num)\n max_k.remove(num)\n if len(max_k) == 0:\n return ret\n```\n**An alternative python solution, maybe a little more pythonic!**\n```\nclass Solution(object):\n def maxSubsequence(self, nums, k):\n # Build a two-keyword(index, num) list and sort by num in reverse order and intercept the top k\n nums_with_idx_topk = sorted(enumerate(nums), reverse=True, key=lambda elem: elem[1])[:k]\n nums_with_idx_topk = sorted(nums_with_idx_topk) # Sort by index in order\n return [num for i, num in nums_with_idx_topk]\n```\n**Python, One-liner, 100% Faster, Upvote!**\n```\nclass Solution(object):\n def maxSubsequence(self, nums, k):\n return [n for i, n in sorted(sorted(enumerate(nums), key=lambda e: -e[1])[:k])]\n```\n**Further More O(n), Using Quick Select**\n* The average Time Complexity of Quick Select is O(n), while the worst-case performance is O(n<sup>2</sup>).\n\t* Note that it is very important to choose the split point randomly.\n* Learn more about quick select algorithm: \n\n```\nclass Solution(object):\n def maxSubsequence(self, nums, k):\n def findKthLargest(nums, k):\n pivot = random.choice(nums)\n less = [num for num in nums if num < pivot]\n equal = [num for num in nums if num == pivot]\n greater = [num for num in nums if num > pivot]\n\n if len(greater) >= k:\n return findKthLargest(greater, k)\n elif len(greater) + len(equal) < k:\n return findKthLargest(less, k - len(greater) - len(equal))\n else:\n return pivot, k - len(greater)\n\n kth_largest, kth_largest_equal = findKthLargest(nums, k)\n ans = []\n for num in nums:\n if num > kth_largest:\n ans.append(num)\n elif num == kth_largest and kth_largest_equal:\n ans.append(num)\n kth_largest_equal -= 1\n return ans\n```\n**If you hava any question, feel free to ask. If you like the solution or the explaination, Please UPVOTE!**\n\n**C++ 53% Faster**\n```\nclass Solution {\npublic:\n vector<int> maxSubsequence(vector<int>& nums, int k) {\n vector<int> max_k(nums);\n vector<int> ret;\n sort(max_k.rbegin(), max_k.rend());\n for (int i = 0; i < size(nums); i ++) {\n for (int j = 0; j < k; j ++) {\n if (nums[i] == max_k[j]) {\n ret.push_back(nums[i]);\n nums[i] = -1000000;\n max_k[j] = 1000000;\n if (size(ret) == k) return ret;\n }\n }\n }\n return ret;\n }\n};\n```\n**If you hava any question, feel free to ask. If you like the solution or the explaination, Please UPVOTE!**
104,179
Find Subsequence of Length K With the Largest Sum
find-subsequence-of-length-k-with-the-largest-sum
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Array,Hash Table,Sorting,Heap (Priority Queue)
Easy
From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?
612
8
# 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 maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n while len(nums) > k:\n nums.remove(min(nums))\n return nums\n```
104,188
Find Subsequence of Length K With the Largest Sum
find-subsequence-of-length-k-with-the-largest-sum
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Array,Hash Table,Sorting,Heap (Priority Queue)
Easy
From a greedy perspective, what k elements should you pick? Could you sort the array while maintaining the index?
2,441
14
## Code:\n```\nclass Solution:\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n tuple_heap = [] # Stores (value, index) as min heap\n for i, val in enumerate(nums):\n if len(tuple_heap) == k:\n heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k\n else:\n heappush(tuple_heap, (val, i))\n\t\t# heap now contains only the k largest elements with their indices as well.\n tuple_heap.sort(key=lambda x: x[1]) # To get the original order of values. That is why we sort it by index(x[1]) & not value(x[0])\n ans = []\n for i in tuple_heap:\n ans.append(i[0])\n return ans\n```\nGive an \u2B06\uFE0Fupvote if you found this article helpful.
104,197
Find Good Days to Rob the Bank
find-good-days-to-rob-the-bank
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.
Array,Dynamic Programming,Prefix Sum
Medium
The trivial solution is to check the time days before and after each day. There are a lot of repeated operations using this solution. How could we optimize this solution? We can use precomputation to make the solution faster. Use an array to store the number of days before the ith day that is non-increasing, and another array to store the number of days after the ith day that is non-decreasing.
868
17
Algorithm:-\n1.Place two pointers p1 and p2 at 1 and time steps ahead of p1.\n2.check non-increasing and non-decreasing condition for p1 and p2 respectively. If condition is satisfied increment by 1 else reduce to 0.\n3.check if p1 and p2 both are greater than equal to time. If True then append the index to result.\nnums=[5,4,4,3,3,4,5,7,8] , time=3\n![image]()\n```\nclass Solution:\n def goodDaysToRobBank(self, nums: List[int], time: int) -> List[int]: \n n=len(nums)\n if time==0:return range(n)\n res=[]\n p1,p2=0,0\n for i in range(1,n-time):\n p1+=1 if nums[i-1]>=nums[i] else -p1\n p2+=1 if nums[i+time-1]<=nums[i+time] else -p2\n \n if p1>=time and p2>=time:res.append(i)\n return res\n```\nTime Complexity- O(N)\nSpace Complexity-O(1) (Ignoring the space required for result.\n
104,226
Find Good Days to Rob the Bank
find-good-days-to-rob-the-bank
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.
Array,Dynamic Programming,Prefix Sum
Medium
The trivial solution is to check the time days before and after each day. There are a lot of repeated operations using this solution. How could we optimize this solution? We can use precomputation to make the solution faster. Use an array to store the number of days before the ith day that is non-increasing, and another array to store the number of days after the ith day that is non-decreasing.
584
6
Please check out this [commit]() for solutions of weekly 67. \n\n```\nclass Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n suffix = [0]*len(security)\n for i in range(len(security)-2, 0, -1): \n if security[i] <= security[i+1]: suffix[i] = suffix[i+1] + 1\n \n ans = []\n prefix = 0\n for i in range(len(security)-time): \n if i and security[i-1] >= security[i]: prefix += 1\n else: prefix = 0\n if prefix >= time and suffix[i] >= time: ans.append(i)\n return ans \n```
104,247
Sequentially Ordinal Rank Tracker
sequentially-ordinal-rank-tracker
A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better. You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports: Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system. Implement the SORTracker class:
Design,Heap (Priority Queue),Data Stream,Ordered Set
Hard
If the problem were to find the median of a stream of scenery locations while they are being added, can you solve it? We can use a similar approach as an optimization to avoid repeated sorting. Employ two heaps: left heap and right heap. The left heap is a max-heap, and the right heap is a min-heap. The size of the left heap is k + 1 (best locations), where k is the number of times the get method was invoked. The other locations are maintained in the right heap. Every time when add is being called, we add it to the left heap. If the size of the left heap exceeds k + 1, we move the head element to the right heap. When the get method is invoked again (the k + 1 time it is invoked), we can return the head element of the left heap. But before returning it, if the right heap is not empty, we maintain the left heap to have the best k + 2 items by moving the best location from the right heap to the left heap.
1,201
17
```\nfrom heapq import *\n\nclass MinHeapItem:\n def __init__(self, name, score):\n self.name = name\n self.score = score\n def __lt__(self, other):\n return self.score < other.score or \\\n (self.score == other.score and self.name > other.name)\n\nclass MaxHeapItem:\n def __init__(self, name, score):\n self.name = name\n self.score = score\n def __lt__(self, other):\n return self.score > other.score or \\\n (self.score == other.score and self.name < other.name)\n\nclass SORTracker:\n def __init__(self):\n self.min_heap = []\n self.max_heap = []\n self.i = 1\n\n def add(self, name: str, score: int) -> None:\n current = MinHeapItem(name, score)\n if len(self.min_heap) < self.i:\n heappush(self.min_heap, current)\n elif current > self.min_heap[0]:\n temp = heapreplace(self.min_heap, current)\n heappush(self.max_heap, MaxHeapItem(temp.name, temp.score))\n else:\n heappush(self.max_heap, MaxHeapItem(name, score))\n \n\n def get(self) -> str:\n ans = self.min_heap[0].name\n self.i += 1 \n if self.max_heap:\n temp = heappop(self.max_heap)\n heappush(self.min_heap, MinHeapItem(temp.name, temp.score))\n return ans\n```
104,319
Find Target Indices After Sorting Array
find-target-indices-after-sorting-array
You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Array,Binary Search,Sorting
Easy
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
439
10
# Intuition\nwe dont need actual indices, we dont care about sequence or order so we don\'t need sort.\nbinary search \n# Approach\nJust count number of elements which are less than or equal to given target. say lessThanOrEqualCount\nThen count number of elements which are strictly less than given target onlyLessThanCount\n\nif lessThanOrEqualCount = onlyLessThanCount: return empty\nor else all numbers between them\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity: O(1)\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def targetIndices(self, nums: List[int], target: int) -> List[int]:\n lessThanEqual = 0\n onlyLess = 0\n for i in nums:\n if i <= target:\n lessThanEqual += 1\n if i < target:\n onlyLess += 1\n return list(range(onlyLess, lessThanEqual))\n```\n\nPlease upvote if you like the solution.\n
104,382
Find Target Indices After Sorting Array
find-target-indices-after-sorting-array
You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Array,Binary Search,Sorting
Easy
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
595
5
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q2089. Find Target Indices After Sorting Array***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def targetIndices(self, nums: List[int], target: int) -> List[int]:\n l,h=0,len(nums)\n for n in nums:\n if n>target:\n h-=1\n elif n<target:\n l+=1\n return (range(l,h))\n```\n**Runtime:** 55 ms\t\n**Memory Usage:** 13.6 MB\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public List<Integer> targetIndices(int[] nums, int target) {\n List<Integer> ans=new ArrayList<>();\n Arrays.sort(nums);\n int l=0,h=nums.length-1;\n for(int num:nums)\n {\n if(num<target)\n l++;\n else if(num>target)\n h--;\n }\n while(l<=h)\n ans.add(l++);\n \n return ans;\n }\n}\n```\n**Runtime:** 3 ms\t\t\n**Memory Usage:** 43..8 MB\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n vector<int> targetIndices(vector<int>& nums, int target) {\n vector<int> ans;\n int l=0,h=nums.size()-1;\n sort(nums.begin(),nums.end());\n for(auto num:nums)\n {\n if (num>target)\n h--;\n else if(num<target)\n l++;\n }\n while(l<=h)\n {\n ans.push_back(l++);\n }\n return ans;\n }\n};\n```\n**Runtime:** 7 ms\t\n**Memory Usage:** 11.3 MB\t\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
104,405
Find Target Indices After Sorting Array
find-target-indices-after-sorting-array
You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target. Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
Array,Binary Search,Sorting
Easy
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
2,002
24
**Python :**\nTime complexity: *O(n)*\n```\ndef targetIndices(self, nums: List[int], target: int) -> List[int]:\n\tindex = 0\n\tcount = 0\n\n\tfor num in nums:\n\t\tif num < target:\n\t\t\tindex += 1\n\n\t\tif num == target:\n\t\t\tcount += 1\n\n\treturn list(range(index, index + count))\n```\n\nTime complexity: *O(nlogn)*\n\n```\ndef targetIndices(self, nums: List[int], target: int) -> List[int]:\n\tnums = sorted(nums)\n\treturn [i for i in range(len(nums)) if nums[i]== target]\n```\n\n**Like it ? please upvote !**\n\n
104,408
K Radius Subarray Averages
k-radius-subarray-averages
You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.
Array,Sliding Window
Medium
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array.
1,291
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis function calculates sliding window averages for a given input vector nums and window size k. It first checks if there are enough elements in the input vector to form a valid window. If not, it returns a vector with all elements set to -1. If there are enough elements, it proceeds to calculate the sliding window averages.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPlease turn english subtitles if neccessary\n[]()\nTo calculate the averages, the code initializes a vector avg of the same size as the input vector, with all elements initially set to -1.\n\nIt uses a loop to iterate over the input vector, summing up the first 2 * k + 1 elements. It then calculates the average of these elements and stores it in the avg vector at the index k, representing the center of the window.\n\nNext, the code enters another loop that starts from k + 1 and iterates until n - k - 1, where n is the size of the input vector.\n\nWithin this loop, it updates the sum by subtracting the element that moved out of the window (at index i - k - 1) and adding the element that enters the window (at index k + i). It then calculates the average based on the updated sum and stores it in the avg vector at the current index i.\n\nFinally, the function returns the avg vector, which contains the sliding window averages for each position in the input vector. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code Runtime 229 ms Beats 94.77%\n```\nclass Solution {\npublic:\n vector<int> getAverages(vector<int>& nums, int k) {\n int n=nums.size();\n vector<int> avg(n, -1);\n if (2*k+1>n) return avg;\n unsigned long long sum=0;\n //sum=accumulate(nums.begin(), nums.begin()+(k*2+1), 0L);\n for(int i=0; i<=2*k; i++){\n sum+=nums[i];\n }\n avg[k]=sum/(2*k+1);\n for(int i=k+1; i<n-k; i++){\n sum+=nums[k+i]-nums[i-k-1];\n avg[i]=sum/(2*k+1);\n }\n return avg;\n }\n};\n```\n# Python solution\n```\nclass Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n n=len(nums)\n avg=[-1]*n\n k2_1=2*k+1\n if k2_1>n: return avg\n # wsum=sum(nums[0:k2_1])\n wsum=0\n for x in nums[0:k2_1]:\n wsum+=x\n # Can replace by sum()\n avg[k]=wsum//k2_1\n for i in range(k+1, n-k):\n wsum+=nums[k+i]-nums[i-k-1]\n avg[i]=sum//k2_1\n return avg\n```\n# C solution\n```\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* getAverages(int* nums, int n, int k, int* returnSize){\n int* avg=(int*)malloc(sizeof(int)*n);\n memset(avg, -1, sizeof(int)*n);\n *returnSize=n;\n int k2_1=2*k+1;\n if (k2_1>n) return avg;\n unsigned long long sum=0;\n for(register int i=0; i<k2_1; i++){\n sum+=nums[i];\n }\n avg[k]=sum/k2_1;\n for(register int i=k+1; i<n-k; i++){\n sum+=nums[k+i]-nums[i-k-1];\n avg[i]=sum/k2_1;\n }\n return avg;\n\n}\n```
104,411
K Radius Subarray Averages
k-radius-subarray-averages
You are given a 0-indexed array nums of n integers, and an integer k. The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1. Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i. The average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.
Array,Sliding Window
Medium
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer type for the prefix sum array.
766
5
C++ Code--------------------------------------------------------------------->\n\n```\nclass Solution {\npublic:\n vector<int> getAverages(vector<int>& nums, int k) {\n int n=nums.size();\n// create an array to store the mid vals if present\n vector<int>ans(n,-1);\n// end bounds check \n if(n%2==0&&n/2<=k){\n return ans;\n }else if(n%2!=0&&n/2<k){\n return ans;\n }\n \n int j=0,i=0,sz=2*k+1,m=k;\n long long int s=0;\n// iteration over the array \n while(i<n&&j<n){\n s+=nums[i];\n if(i-j+1==sz){\n ans[m++]=s/sz;\n s-=nums[j++];\n }\n i++;\n }\n return ans;\n \n }\n};\n```\nJava code-------------------------------------------------------------------->\n```\nclass Solution {\n public int[] getAverages(int[] nums, int k) {\n int n = nums.length;\n // Create an array to store the mid vals if present\n int[] ans = new int[n];\n for (int i = 0; i < n; i++) {\n ans[i] = -1;\n }\n // End bounds check\n if (n % 2 == 0 && n / 2 <= k) {\n return ans;\n } else if (n % 2 != 0 && n / 2 < k) {\n return ans;\n }\n\n int j = 0, i = 0, sz = 2 * k + 1, m = k;\n long s = 0;\n // Iteration over the array\n while (i < n && j < n) {\n s += nums[i];\n if (i - j + 1 == sz) {\n ans[m] = (int) (s / sz);\n s -= nums[j];\n j++;\n m++;\n }\n i++;\n }\n return ans;\n }\n};\n```\nPython------------------------------------------------------->\n```\nclass Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n n = len(nums)\n # Create a list to store the mid vals if present\n ans = [-1] * n\n # End bounds check\n if n % 2 == 0 and n // 2 <= k:\n return ans\n elif n % 2 != 0 and n // 2 < k:\n return ans\n\n j, i, sz, m = 0, 0, 2 * k + 1, k\n s = 0\n # Iteration over the list\n while i < n and j < n:\n s += nums[i]\n if i - j + 1 == sz:\n ans[m] = s // sz\n s -= nums[j]\n j += 1\n m += 1\n i += 1\n return ans\n```
104,412
Removing Minimum and Maximum From Array
removing-minimum-and-maximum-from-array
You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.
Array,Greedy
Medium
There can only be three scenarios for deletions such that both minimum and maximum elements are removed: Scenario 1: Both elements are removed by only deleting from the front. Scenario 2: Both elements are removed by only deleting from the back. Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element. Compare which of the three scenarios results in the minimum number of moves.
7,074
44
# **Explanation**\nFind index `i` of the minimum\nFind index `j` of the maximum\n\nTo remove element `A[i]`,\nwe can remove `i + 1` elements from front,\nor we can remove `n - i` elements from back.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int minimumDeletions(int[] A) {\n int i = 0, j = 0, n = A.length;\n for (int k = 0; k < n; ++k) {\n if (A[i] < A[k]) i = k;\n if (A[j] > A[k]) j = k;\n }\n return Math.min(Math.min(Math.max(i + 1, j + 1), Math.max(n - i, n - j)), Math.min(i + 1 + n - j, j + 1 + n - i));\n }\n```\n\n**C++**\n```cpp\n int minimumDeletions(vector<int>& A) {\n int i = 0, j = 0, n = A.size();\n for (int k = 0; k < n; ++k) {\n if (A[i] < A[k]) i = k;\n if (A[j] > A[k]) j = k;\n }\n return min({max(i + 1, j + 1), max(n - i, n - j), i + 1 + n - j, j + 1 + n - i});\n }\n```\n\n**Python**\n```py\n def minimumDeletions(self, A):\n i, j, n = A.index(min(A)), A.index(max(A)), len(A)\n return min(max(i + 1, j + 1), max(n - i, n - j), i + 1 + n - j, j + 1 + n - i)\n```\n
104,482
Removing Minimum and Maximum From Array
removing-minimum-and-maximum-from-array
You are given a 0-indexed array of distinct integers nums. There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array. A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array. Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.
Array,Greedy
Medium
There can only be three scenarios for deletions such that both minimum and maximum elements are removed: Scenario 1: Both elements are removed by only deleting from the front. Scenario 2: Both elements are removed by only deleting from the back. Scenario 3: Delete from the front to remove one of the elements, and delete from the back to remove the other element. Compare which of the three scenarios results in the minimum number of moves.
1,268
20
**Explanation:**\n\nThere are only 4 cases to consider.\n\n* **Case 1:** [**1,10000**,5,6,7,8,9,2] - It\'s optimal to grab both from the front.\n\n* **Case 2:** [2,3,4,5,6,7,**10000,1**] - It\'s optimal to grab both from the back.\n\n* **Case 3:** [2,3,**10000**,5,6,7,4,**1**] - It\'s optimal to grab the max from the front and min from back.\n\n* **Case 4:** [2,3,**1**,5,6,7,4,**10000**] - It\'s optimal to grab the min from the front and max from back.\n\nConsider them all and take the minimum.\n\n---\n\n**Code:**\n\n```\nclass Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n minFromFront = nums.index(min(nums))\n maxFromFront = nums.index(max(nums))\n \n minFromBack = len(nums) - minFromFront - 1\n maxFromBack = len(nums) - maxFromFront - 1 \n \n return min(max(minFromFront, maxFromFront) + 1, # Case 1\n max(minFromBack, maxFromBack) + 1, # Case 2\n minFromBack + maxFromFront + 2, # Case 3 \n minFromFront + maxFromBack + 2) # Case 4\n```\n\n---\n\n**Time Complexity:** O(N)\n**Space Complexity:** O(1)\n
104,496
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
4,004
29
Pleaes check out this [commit]() for solutions of weekly 269.\n\n```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n can = {0, firstPerson}\n for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]): \n queue = set()\n graph = defaultdict(list)\n for x, y, _ in grp: \n graph[x].append(y)\n graph[y].append(x)\n if x in can: queue.add(x)\n if y in can: queue.add(y)\n \n queue = deque(queue)\n while queue: \n x = queue.popleft()\n for y in graph[x]: \n if y not in can: \n can.add(y)\n queue.append(y)\n return can\n```\n\nor \n```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n can = {0, firstPerson}\n for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]): \n stack = set()\n graph = defaultdict(list)\n for x, y, _ in grp: \n graph[x].append(y)\n graph[y].append(x)\n if x in can: stack.add(x)\n if y in can: stack.add(y)\n \n stack = list(stack)\n while stack: \n x = stack.pop()\n for y in graph[x]: \n if y not in can: \n can.add(y)\n stack.append(y)\n return can\n```\n\nAdding union-find implementation inspired by @lzl124631x\'s post.\n```\nclass UnionFind:\n\n\tdef __init__(self, n: int):\n\t\tself.parent = list(range(n))\n\t\tself.rank = [1] * n\n\n\tdef find(self, p: int) -> int:\n\t\t"""Find with path compression"""\n\t\tif p != self.parent[p]:\n\t\t\tself.parent[p] = self.find(self.parent[p])\n\t\treturn self.parent[p]\n\n\tdef union(self, p: int, q: int) -> bool:\n\t\t"""Union with rank"""\n\t\tprt, qrt = self.find(p), self.find(q)\n\t\tif prt == qrt: return False\n\t\tif self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt \n\t\tself.parent[prt] = qrt\n\t\tself.rank[qrt] += self.rank[prt]\n\t\treturn True\n\n\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n uf = UnionFind(n)\n uf.union(0, firstPerson)\n for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]): \n seen = set()\n for x, y, _ in grp: \n seen.add(x)\n seen.add(y)\n uf.union(x, y)\n for x in seen: \n if uf.find(x) != uf.find(0): uf.parent[x] = x # reset \n return [x for x in range(n) if uf.find(x) == uf.find(0)]\n```
104,512
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
975
18
![image]()\n\n**Time Complexity Analysis** - I am scared to talk about time complexity for this problem..\nLet **M** - number of total meetings, **T** - number of distinct time of meetings, **n** - number of people\nFirst of all, the sort of the meeting is O(M * log(M))\nThen iteration over the sorted meetings to build an array is O(M)\nThen iteration over the sorted array is O(T) where T can be M at worst\n\t - inside the iteration, building the graph is about ~O(M / T) assuming total number of meetings divide by number of distinct time is the number of iteration we need to\n \t - then pre-enqueing the people knows secret can be O(n) at worst\n\t - BFS iteration is visiting every edges which is number of meetings for the time which I assume to be ~O(M/T)\nOverall, I would say O(M log(M)) + O(M) + O(T * 2M/T * n) => **O(M * (log(M) + n))** for the time complexity. Please correct me if I am wrong. \n\n**Space complexity** will be O(M + n) overall. M for sorted array, and n for the queue\n\n```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n # person 0, and firstPerson already knows the secret\n knowsSecret = set([0, firstPerson])\n \n # after sort the meeting by time, the same time meeting will be grouped together\n # so we can relie on people that knows secret before that time from "knowsSecret"\n sortedMeetings = []\n meetings.sort(key=lambda x:x[2]) # O(M*log(M))\n \n # tracking every meeting times to decide if current meeting has same time as previous meeting\n seenTime = set()\n \n # building the sortedMeetings as explained above\n for meeting in meetings: # O(M)\n if meeting[2] not in seenTime:\n seenTime.add(meeting[2])\n sortedMeetings.append([])\n sortedMeetings[-1].append((meeting[0], meeting[1]))\n\n # we then now will build graph for each meeting time, and traverse(BFS) the graph from\n # people that already knows the secret to find more people who knows secret\n for meetingGroup in sortedMeetings: #O(T)\n # q needs to be set then push to queue, because of duplicate values we find from meetings\n # otherwise it will reach the TLE\n pplKnowSecret = set()\n graph = defaultdict(list)\n \n # building bidirectional graph, and make sure to build our queue as well if we find\n # a person who knows secret\n for p1, p2 in meetingGroup: # ~O(M/T)\n graph[p1].append(p2)\n graph[p2].append(p1)\n if p1 in knowsSecret:\n pplKnowSecret.add(p1)\n if p2 in knowsSecret:\n pplKnowSecret.add(p2)\n \n # adding people that already knows the secret to start off our graph traversal \n queue = deque((pplKnowSecret)) # O(n)\n \n while queue: # ~O(M/T)\n curr = queue.popleft()\n #any1 we find from our queue knows secret, so record it\n knowsSecret.add(curr)\n for neigh in graph[curr]:\n if neigh not in knowsSecret:\n knowsSecret.add(neigh)\n queue.append(neigh)\n\n return list(knowsSecret)\n```\n**Please correct me if I am wrong !\nPlease UPVOTE if you find this solution helpful !\nHappy algo!**
104,514
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
2,350
27
**Key Observation:**\nAt every timestamp, the connections between people will form several disjoint sets.\n\nFor example,\n```\nmeetings = [[0, 1, 1], [1, 2, 1], [3, 4, 1], [1, 5, 1],\n [1, 5, 2], [2, 6, 2]]\n```\nwill form the groups like below:\n```\ntime = 1, groups = [{0, 1, 2, 5}, {3, 4}]\ntime = 2, groups = [{1, 5}, {2, 6}]\n```\n\nSo we collect the connections and sorted them with its timestamp as key.\n```python\ntime2meets = defaultdict(list)\nfor x, y, t in meetings:\n time2meets[t].append((x, y))\ntime2meets = sorted(time2meets.items())\n```\n\n---\n**Update as time goes on:**\n\nLet ```curr_know``` represents the set of people who have known the secret now.\nThen at every timestamp, all of the members of a certain group may know the secret if there exists a member who is already in ```curr_know```.\n\n```python\ncurr_know = set([0, firstPerson])\n\nfor time, meets in time2meets:\n # construct groups at this timestamp\n uf = UnionFind()\n for x, y in meets:\n uf.union(x, y)\n\n # finding the group members\n groups = defaultdict(set)\n for idx in uf.parents:\n groups[uf.find_parent(idx)].add(idx)\n \n # if a member of group is in curr_know, \n # update curr_know with all the members of this group \n for group in groups.values():\n if group & curr_know:\n curr_know.update(group)\n```\n---\n**Complexity Analysis:**\n\nLet `N` be the number of peoples, `M` be the number of meetings.\n\n* **Time Complexity:**\n * Sorting the timestamp of meetings takes at most `O(M log M)` time (or if you use bucket sort it will take `O(T)` where `T = 10 ** 5` ).\n * Merging all meetings takes `O(M)` times:\n * Suppose there are `K` people attending a meeting at a certain timestamp:\n * The union part takes `O(K)` times if we implement DSU with path compression and union by rank.\n * Finding the group members takes `O(K)` times.\n * Updating the group members takes `O(K)` times.\n * Since `sum(K) = M * 2`, this part takes `O(M)` times.\n * Total time complexity is `O(M log M)`, irrelevant to `N` if we use hash table to maintain `parents` and `ranks` in DSU.\n\n* **Space Complexity: `O(M + N)`**\n\n---\n\n**Complete code:**\n```python\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n \n class UnionFind:\n def __init__(self):\n self.parents = {}\n self.ranks = {}\n \n def insert(self, x):\n if x not in self.parents:\n self.parents[x] = x\n self.ranks[x] = 0\n \n def find_parent(self, x):\n if self.parents[x] != x:\n self.parents[x] = self.find_parent(self.parents[x])\n return self.parents[x]\n \n def union(self, x, y):\n self.insert(x)\n self.insert(y)\n x, y = self.find_parent(x), self.find_parent(y)\n if x == y:\n return \n if self.ranks[x] > self.ranks[y]:\n self.parents[y] = x\n else:\n self.parents[x] = y\n if self.ranks[x] == self.ranks[y]:\n self.ranks[y] += 1\n \n time2meets = defaultdict(list)\n for x, y, t in meetings:\n time2meets[t].append((x, y))\n time2meets = sorted(time2meets.items())\n \n curr_know = set([0, firstPerson])\n\n for time, meets in time2meets:\n uf = UnionFind()\n for x, y in meets:\n uf.union(x, y)\n \n groups = defaultdict(set)\n for idx in uf.parents:\n groups[uf.find_parent(idx)].add(idx)\n \n for group in groups.values():\n if group & curr_know:\n curr_know.update(group)\n\n return list(curr_know)\n```\n \n
104,518
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
1,115
12
## IDEA :\n* Firstly group all the meetings with the key as time on which meeting is happening.\n\n* So one by one go through all the groups (timing by increasing order) and add all the persons to whom secrets got get shared.\n* Here `sh` denotes the persons having secret with them.\n* Going through each group find the persons with whom secrets got shared and add them in `sh` .\n* At last return the `sh` as a list.\n\n**Implementation :**\n\n## BFS :\n\'\'\'\n\n\tclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n \n meetings.sort(key=lambda x:x[2])\n groups = itertools.groupby(meetings,key = lambda x:x[2])\n \n sh = {0,firstPerson}\n for key,grp in groups:\n seen = set()\n graph = defaultdict(list)\n for a,b,t in grp:\n graph[a].append(b)\n graph[b].append(a)\n if a in sh:\n seen.add(a)\n if b in sh:\n seen.add(b)\n \n queue = deque(seen)\n while queue:\n node = queue.popleft()\n for neig in graph[node]:\n if neig not in sh:\n sh.add(neig)\n queue.append(neig)\n \n return list(sh)\n\n## DFS :\n\'\'\'\n\n\tclass Solution:\n\t\tdef findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n\n\t\t\tmeetings.sort(key=lambda x:x[2])\n\t\t\tgroups = itertools.groupby(meetings,key = lambda x:x[2])\n\n\t\t\tsh = {0,firstPerson}\n\t\t\tfor key,grp in groups:\n\t\t\t\tseen = set()\n\t\t\t\tgraph = defaultdict(list)\n\t\t\t\tfor a,b,t in grp:\n\t\t\t\t\tgraph[a].append(b)\n\t\t\t\t\tgraph[b].append(a)\n\t\t\t\t\tif a in sh:\n\t\t\t\t\t\tseen.add(a)\n\t\t\t\t\tif b in sh:\n\t\t\t\t\t\tseen.add(b)\n\n\t\t\t\tst = list(seen)[::]\n\t\t\t\twhile st:\n\t\t\t\t\tnode = st.pop()\n\t\t\t\t\tfor neig in graph[node]:\n\t\t\t\t\t\tif neig not in sh:\n\t\t\t\t\t\t\tsh.add(neig)\n\t\t\t\t\t\t\tst.append(neig)\n\n\t\t\treturn list(sh)\n\n**Thanks & Upvote if you got any help !!\uD83E\uDD1E**
104,519
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
1,457
20
We use Union-Find to group people. For people who know the secret, we group them with the number 0 people. (roots[n] == 0 or find(n) == 0 means the person n knows the secrete)\n\nFlow:\n1. Sort the meetings by time\n\n2. Aggregate the meetings with the same time, union the attending people into groups. If any person in a group knows the secrete, other people will know the secrete too. After union, we need to reset the group that people do not get the secrete.\n\n3. Return the result\n\nTricks:\n1. roots[n] == 0 or find(n) == 0, means person n knows the secrete\n2. When doing union, the first piority is to set the root as 0 (mark as known secrete).\n\n```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n roots = [i for i in range(n)]\n \n # if roots[n] == 0 or find(n) == 0, means person n knows the secrete\n roots[firstPerson] = 0\n \n def find(x):\n if roots[x] == x:\n return x\n roots[x] = find(roots[x])\n return roots[x]\n \n def union(x, y):\n rootX = find(x)\n rootY = find(y)\n if rootX != rootY:\n # x or y knows the secrete, make both as known secrete\n if rootX == 0 or rootY == 0:\n roots[rootY] = roots[rootX] = 0\n # Neither x nor y knows the secrete, just union them into the same group\n else:\n roots[rootY] = rootX\n \n meetings.sort(key=lambda m:m[2])\n N = len(meetings)\n i = 0\n while i < N:\n # aggregate meetings at the same time\n sameTimeMeetings = [meetings[i]]\n while i < N-1 and meetings[i+1][2] == meetings[i][2]:\n i = i+1\n sameTimeMeetings.append(meetings[i])\n continue\n \n # union people in the same time meetings into groups\n for x,y,time in sameTimeMeetings:\n union(x, y)\n \n # reset the union groups that people do not know the secrete from meetings\n for x,y,time in sameTimeMeetings:\n rootX = find(x)\n # Since x and y are unioned into same group, if x does not know the secret, y does not know either\n if rootX != 0:\n roots[x] = x\n roots[y] = y\n \n i+=1\n\n return [i for i in range(n) if find(i) == 0]\n```
104,521
Find All People With Secret
find-all-people-with-secret
You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson. Person 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
Depth-First Search,Breadth-First Search,Union Find,Graph,Sorting
Hard
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
738
7
```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n g = defaultdict(dict)\n for p1, p2, t in meetings:\n g[t][p1] = g[t].get(p1, [])\n g[t][p1].append(p2)\n g[t][p2] = g[t].get(p2, [])\n g[t][p2].append(p1)\n known = {0, firstPerson}\n for t in sorted(g.keys()):\n seen = set()\n for p in g[t]:\n if p in known and p not in seen:\n q = deque([p])\n seen.add(p)\n while q:\n cur = q.popleft()\n for nxt in g[t][cur]:\n if nxt not in seen:\n q.append(nxt)\n seen.add(nxt)\n known.add(nxt)\n return known\n```\nEdited to make it more concise. \n__________________________\nInterestingly, for this part\n```\n g[t][p1] = g[t].get(p1, [])\n g[t][p1].append(p2)\n g[t][p2] = g[t].get(p2, [])\n g[t][p2].append(p1)\n```\nIf we write it as below, we would get TLE\n```\n g[t][p1] = g[t].get(p1, [])+[p2]\n g[t][p2] = g[t].get(p2, [])+[p1]\n```\nThe main reason is that `g[t].get(p1, [])+[p2]` creates a new array whereas `g[t][p1].append(p2)` simply adds `p2` to the original array
104,527
Finding 3-Digit Even Numbers
finding-3-digit-even-numbers
You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.
Array,Hash Table,Sorting,Enumeration
Easy
The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array?
4,891
73
**C++**\n```cpp\nvector<int> findEvenNumbers(vector<int>& digits) {\n vector<int> res;\n int cnt[10] = {};\n for (auto d : digits)\n ++cnt[d];\n for (int i = 1; i < 10; ++i)\n for (int j = 0; cnt[i] > 0 && j < 10; ++j)\n for (int k = 0; cnt[j] > (i == j) && k < 10; k += 2)\n if (cnt[k] > (k == i) + (k == j))\n res.push_back(i * 100 + j * 10 + k);\n return res;\n}\n```\n**Python 3**\nFor brevity, we check for `cnt` at the very end. It is faster to prune earier, but here we only need to check 450 numbers. \n\n```python\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n res, cnt = [], Counter(digits)\n for i in range(1, 10):\n for j in range(0, 10):\n for k in range(0, 10, 2):\n if cnt[i] > 0 and cnt[j] > (i == j) and cnt[k] > (k == i) + (k == j):\n res.append(i * 100 + j * 10 + k)\n return res\n```
104,564
Finding 3-Digit Even Numbers
finding-3-digit-even-numbers
You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.
Array,Hash Table,Sorting,Enumeration
Easy
The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array?
3,544
33
Please check out this [commit]() for solutions of weekly 270.\n\n```\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n ans = set()\n for x, y, z in permutations(digits, 3): \n if x != 0 and z & 1 == 0: \n ans.add(100*x + 10*y + z) \n return sorted(ans)\n```\n\nAlternative `O(N)` approach \n```\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n ans = []\n freq = Counter(digits)\n for x in range(100, 1000, 2): \n if not Counter(int(d) for d in str(x)) - freq: ans.append(x)\n return ans \n```
104,565
Finding 3-Digit Even Numbers
finding-3-digit-even-numbers
You are given an integer array digits, where each element is a digit. The array may contain duplicates. You need to find all the unique integers that follow the given requirements: For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements. Return a sorted array of the unique integers.
Array,Hash Table,Sorting,Enumeration
Easy
The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array?
1,165
8
* We need 3 digit numbers so we travese form 100 to 999\n* For every num in range we check if its digits are in digits array and frequency of its digits is less than or equal to frequency of digits in digits array.\n```\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n hmap, res = defaultdict(int), []\n for num in digits:\n hmap[num] += 1 #counting frequency of digits of digits array\n \n for num in range(100, 999, 2): #step 2 because we need even numbers\n checker = defaultdict(int)\n for digit in str(num):\n checker[int(digit)] += 1 #counting frequency of digits of num\n \n\t\t\t#check if every digit in num is in digits array and its frequency is less than or equal to its frequency in digits array\n if all(map(lambda x: x in hmap and checker[x] <= hmap[x], checker)):\n res.append(num)\n \n return res\n```
104,592
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
42,288
775
1. Build directions for both start and destination from the root.\n\t- Say we get "LLRRL" and "LRR".\n2. Remove common prefix path.\n\t- We remove "L", and now start direction is "LRRL", and destination - "RR"\n3. Replace all steps in the start direction to "U" and add destination direction.\n\t- The result is "UUUU" + "RR".\n\n**C++**\nHere, we build path in the reverse order to avoid creating new strings.\n\n```cpp\nbool find(TreeNode* n, int val, string &path) {\n if (n->val == val)\n return true;\n if (n->left && find(n->left, val, path))\n path.push_back(\'L\');\n else if (n->right && find(n->right, val, path))\n path.push_back(\'R\');\n return !path.empty();\n}\nstring getDirections(TreeNode* root, int startValue, int destValue) {\n string s_p, d_p;\n find(root, startValue, s_p);\n find(root, destValue, d_p);\n while (!s_p.empty() && !d_p.empty() && s_p.back() == d_p.back()) {\n s_p.pop_back();\n d_p.pop_back();\n }\n return string(s_p.size(), \'U\') + string(rbegin(d_p), rend(d_p));\n}\n```\n**Java**\n```java\nprivate boolean find(TreeNode n, int val, StringBuilder sb) {\n if (n.val == val) \n return true;\n if (n.left != null && find(n.left, val, sb))\n sb.append("L");\n else if (n.right != null && find(n.right, val, sb))\n sb.append("R");\n return sb.length() > 0;\n}\npublic String getDirections(TreeNode root, int startValue, int destValue) {\n StringBuilder s = new StringBuilder(), d = new StringBuilder();\n find(root, startValue, s);\n find(root, destValue, d);\n int i = 0, max_i = Math.min(d.length(), s.length());\n while (i < max_i && s.charAt(s.length() - i - 1) == d.charAt(d.length() - i - 1))\n ++i;\n return "U".repeat(s.length() - i) + d.reverse().toString().substring(i);\n}\n```\n**Python 3**\nLists in Python are mutable and passed by a reference.\n\n```python\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n def find(n: TreeNode, val: int, path: List[str]) -> bool:\n if n.val == val:\n return True\n if n.left and find(n.left, val, path):\n path += "L"\n elif n.right and find(n.right, val, path):\n path += "R"\n return path\n s, d = [], []\n find(root, startValue, s)\n find(root, destValue, d)\n while len(s) and len(d) and s[-1] == d[-1]:\n s.pop()\n d.pop()\n return "".join("U" * len(s)) + "".join(reversed(d))\n```
104,660
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
11,225
120
Please check out this [commit]() for solutions of weekly 270.\n\n```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n def lca(node): \n """Return lowest common ancestor of start and dest nodes."""\n if not node or node.val in (startValue , destValue): return node \n left, right = lca(node.left), lca(node.right)\n return node if left and right else left or right\n \n root = lca(root) # only this sub-tree matters\n \n ps = pd = ""\n stack = [(root, "")]\n while stack: \n node, path = stack.pop()\n if node.val == startValue: ps = path \n if node.val == destValue: pd = path\n if node.left: stack.append((node.left, path + "L"))\n if node.right: stack.append((node.right, path + "R"))\n return "U"*len(ps) + pd\n```
104,669
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
490
7
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n def dfs(node, path, val) :\n if node.val == val :\n return True\n if node.left and dfs(node.left, path, val) :\n path.append(\'L\')\n elif node.right and dfs(node.right, path, val) :\n path.append(\'R\')\n return len(path) > 0 # failed to find a path\n \n start, dest = [], []\n dfs(root, start, startValue) # create a start node path\n dfs(root, dest, destValue) # create a dest node path\n \n while start and dest and start[-1] == dest[-1] :\n start.pop()\n dest.pop()\n \n return \'U\'*len(start) + \'\'.join(reversed(dest))\n \n```
104,682
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
2,635
35
```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n # The idea is that we find paths for both start and target nodes.\n # Once we have found them we reduce paths to a lowest common parent node.\n # We change the all items in path of start to \'U\' and keep the path of target same.\n def dfs(node, target, path):\n if not node:\n return False\n\n if node.val == target:\n return True\n\n if node.left:\n if dfs(node.left, target, path):\n path.appendleft(\'L\')\n return True\n\n if node.right:\n if dfs(node.right, target, path):\n path.appendleft(\'R\')\n return True \n \n s_path, t_path = deque(), deque()\n dfs(root, startValue, s_path)\n dfs(root, destValue, t_path)\n \n while s_path and t_path and s_path[0] == t_path[0]:\n s_path.popleft()\n t_path.popleft()\n \n return \'U\' * len(s_path) + \'\'.join(t_path)\n
104,685
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
2,590
16
we record the path from root to start (path1) and dest node(path2). Drawing some examples, we can find that when two paths have same parent path which part we can just ignore, then we turn the left path1 to \'U\' and concate the left path2 path.\n\n```python\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n """\n The number of nodes in the tree is n.\n 2 <= n <= 10^5\n 1 <= Node.val <= n\n All the values in the tree are unique.\n 1 <= startValue, destValue <= n\n startValue != destValue\n :param root:\n :param startValue:\n :param destValue:\n :return:\n """\n if root is None:\n return ""\n\n dq = collections.deque()\n dq.append((root, ""))\n start_found = False\n dest_found = False\n start_path = ""\n dest_path = ""\n while len(dq) > 0 and not (start_found and dest_found):\n node, path = dq.popleft()\n if node.val == startValue:\n start_found = True\n start_path = path\n elif node.val == destValue:\n dest_found = True\n dest_path = path\n if node.left is not None:\n dq.append((node.left, path + "L"))\n if node.right is not None:\n dq.append((node.right, path + "R"))\n i = 0\n while len(start_path) > i and len(dest_path) > i and start_path[i] == dest_path[i]:\n i += 1\n return (len(start_path) - i) * \'U\' + dest_path[i:]\n```
104,690
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
5,836
31
3 Step Process:\n1. Do a recursive DFS and mark each node\'s parent in the ListNode class.\n2. Save the value of `startNode` and `endNode`.\n3. Start a BFS from the `startNode` till you reach `endNode` recording the path on the way. You\'re guarenteed to reach `endNode` by the shortest path.\n\nTime Complexity: `O(n)`\nSpace Complexity: `O(n)`\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n# self.parent = parent\n\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n self.startNode = None\n self.endNode = None \n \n def createParent(root, parent):\n if not root:\n return\n \n root.parent = parent\n createParent(root.left, root)\n createParent(root.right, root)\n \n if root.val == startValue:\n self.startNode = root\n if root.val == destValue:\n self.endNode = root\n \n return\n \n createParent(root, None)\n \n queue = [(self.startNode, "")]\n visited = set()\n visited.add(self.startNode.val)\n \n while queue:\n node, value = queue.pop(0)\n \n if node == self.endNode:\n return value\n \n if node.parent and node.parent.val not in visited:\n queue.append((node.parent, value+"U"))\n visited.add(node.parent.val)\n \n if node.right and node.right.val not in visited:\n queue.append((node.right, value+"R"))\n visited.add(node.right.val)\n \n if node.left and node.left.val not in visited:\n queue.append((node.left, value+"L"))\n visited.add(node.left.val)\n \n return ""\n```
104,692
Step-By-Step Directions From a Binary Tree Node to Another
step-by-step-directions-from-a-binary-tree-node-to-another
You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t. Find the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction: Return the step-by-step directions of the shortest path from node s to node t.
String,Tree,Depth-First Search,Binary Tree
Medium
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root β†’ s, and root β†’ t. Can you use these two strings to prepare the final answer? Remove the longest common prefix of the two path strings to get the path LCA β†’ s, and LCA β†’ t. Each step in the path of LCA β†’ s should be reversed as 'U'.
2,059
19
#### **Solution 1: Graph Based, passed**\n#### Space=O(N) for building graph and queue. Time= O(N) for traversing the tree and for the BFS\nThe idea is build an undirected graph, the directions from Node1--> Node2 is either L or R, and the opposite Node2-->1 is always U\n```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n\t\n graph=defaultdict(list) \n stack=[(root)]\n\t\t\n\t\t#Step1: Build Graph\n while stack:\n node=stack.pop()\n \n if node.left:\n graph[node.val].append((node.left.val,"L"))\n graph[node.left.val].append((node.val,"U"))\n stack.append(node.left)\n if node.right:\n graph[node.val].append((node.right.val,"R"))\n graph[node.right.val].append((node.val,"U"))\n stack.append(node.right)\n #Step 2: Normal BFS\n q=deque([(startValue,"")])\n seen=set()\n seen.add(startValue)\n \n while q:\n node,path=q.popleft()\n if node==destValue:\n return path\n \n for neigh in graph[node]:\n v,d=neigh\n if v not in seen:\n q.append((v,path+d))\n seen.add(v)\n return -1\n```\n\n#### **Solution 2: LCA with getPath recursion: Memory Limit Exceded**\n#### When I tried the LCA solution, I got the path from LCA to start and LCA to end recursively which is correct, but didn\'t pass memory constraint\nThe idea is that the 2 nodes must have a LCA, if you get the LCA, then the answer is startNode to LCA + LCA to dest node, but if you notice the first part start to LCA is always \'U\', but I do care about the length, how many U\'\'s? so I still get the path from start to LCA then I relace the path with U\'s\n```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n def getLCA(root,p,q):\n if not root: return None\n if root.val==p or root.val==q:\n return root\n L=getLCA(root.left,p,q)\n R=getLCA(root.right,p,q)\n if L and R:\n return root\n return L or R\n \n \n def getPath(node1,node2,path): #---> Problem here\n if not node1: return\n if node1.val==node2: return path\n return getPath(node1.left,node2,path+["L"]) or getPath(node1.right,node2,path+["R"])\n \n \n LCA=getLCA(root,startValue,destValue)\n path1=getPath(LCA,startValue,[]) \n path2=getPath(LCA,destValue,[])\n path=["U"]*len(path1) + path2 if path1 else path2 \n return "".join(path)\n \n```\n\n#### **Solution 2 Revisited: LCA then get path iterative*\nExact same idea as above, the only change is getPath,\n```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n #soltion 2 LCA\n def getLCA(root,p,q):\n if not root: return None\n if root.val==p or root.val==q:\n return root\n L=getLCA(root.left,p,q)\n R=getLCA(root.right,p,q)\n if L and R:\n return root\n return L or R\n \n \n \n LCA=getLCA(root,startValue,destValue)\n ps,pd="",""\n stack = [(LCA, "")]\n while stack: \n node, path = stack.pop()\n if node.val == startValue: ps = path \n if node.val == destValue: pd = path\n if node.left: stack.append((node.left, path + "L"))\n if node.right: stack.append((node.right, path + "R"))\n \n return "U"*len(ps) + pd\n```\n\n**A 3rd solution is getting the depth of each node from the root, then removing the common prefix.\n**
104,704
Maximum Number of Words Found in Sentences
maximum-number-of-words-found-in-sentences
A sentence is a list of words that are separated by a single spaceΒ with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence.
Array,String
Easy
Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1.
15,762
101
Count spaces in each sentence, and return `max + 1`. The benefit (comparing to a split method) is that we do not create temporary strings.\n\n**Python 3**\n```python\nclass Solution:\n def mostWordsFound(self, ss: List[str]) -> int:\n return max(s.count(" ") for s in ss) + 1\n```\n\n**C++**\n```cpp\nint mostWordsFound(vector<string>& s) {\n return 1 + accumulate(begin(s), end(s), 0, [](int res, const auto &s) {\n return max(res, (int)count(begin(s), end(s), \' \')); });\n}\n```\n\n**Java**\n```java\npublic int mostWordsFound(String[] sentences) {\n return 1 + Stream.of(sentences).mapToInt(s -> (int)s.chars().filter(ch -> ch == \' \').count()).max().getAsInt();\n}\n```
104,725
Maximum Number of Words Found in Sentences
maximum-number-of-words-found-in-sentences
A sentence is a list of words that are separated by a single spaceΒ with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence.
Array,String
Easy
Process each sentence separately and count the number of words by looking for the number of space characters in the sentence and adding it by 1.
6,049
44
**Python :**\n\n```\ndef mostWordsFound(self, sentences: List[str]) -> int:\n\treturn max(len(word.split()) for word in sentences)\n```\n\n**Like it ? please upvote !**
104,740
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
22,922
110
**Method 1: Bruteforce**\nRepeated BFS till no any more finding\n\n1. Put all supplies into a HashSet, `seen`, for checking the availability in `O(1)` time;\n2. Put into a Queue all indexes of the recipes;\n3. BFS and put into `seen` all recipes that we currently can create; put back into the Queue if a recipe we currently can not create;\n4. After any round of breadth search, if no any more recipe we can create, return the recipes we found so far.\n\n```java\n public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {\n Set<String> seen = new HashSet<>();\n for (String sup : supplies) {\n seen.add(sup);\n }\n Queue<Integer> q = new LinkedList<>();\n for (int i = 0; i < recipes.length; ++i) {\n q.offer(i);\n }\n List<String> ans = new ArrayList<>();\n int prevSize = seen.size() - 1;\n while (seen.size() > prevSize) {\n prevSize = seen.size();\n mid:\n for (int sz = q.size(); sz > 0; --sz) {\n int i = q.poll();\n for (String ing : ingredients.get(i)) {\n if (!seen.contains(ing)) {\n q.offer(i);\n continue mid;\n }\n }\n seen.add(recipes[i]);\n ans.add(recipes[i]);\n }\n }\n return ans;\n }\n```\n```python\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n \n ans = []\n seen = set(supplies)\n dq = deque([(r, ing) for r, ing in zip(recipes, ingredients)])\n \n # dummy value for prev_size, just to make sure \n # the initial value of prev_size < len(seen) \n prev_size = len(seen) - 1 \n \n # Keep searching if we have any new finding(s).\n while len(seen) > prev_size:\n prev_size = len(seen)\n for _ in range(len(dq)):\n r, ing = dq.popleft()\n if all(i in seen for i in ing):\n ans.append(r)\n seen.add(r)\n else:\n dq.append((r, ing))\n return ans\n```\n\n----\n\n**Method 2: Topological sort**\n1. For each recipe, count its non-available ingredients as in degree; Store (non-available ingredient, dependent recipes) as HashMap; \n2. Store all 0-in-degree recipes into a list as the starting points of topological sort;\n3. Use topogical sort to decrease the in degree of recipes, whenever the in-degree reaches `0`, add it to return list.\n\n```java\n public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {\n List<String> ans = new ArrayList<>();\n // Put all supplies into HashSet.\n Set<String> available = Stream.of(supplies).collect(Collectors.toCollection(HashSet::new));\n Map<String, Set<String>> ingredientToRecipes = new HashMap<>();\n Map<String, Integer> inDegree = new HashMap<>();\n for (int i = 0; i < recipes.length; ++i) {\n int nonAvailable = 0;\n for (String ing : ingredients.get(i)) {\n if (!available.contains(ing)) {\n ingredientToRecipes.computeIfAbsent(ing, s -> new HashSet<>()).add(recipes[i]);\n ++nonAvailable;\n }\n }\n if (nonAvailable == 0) {\n ans.add(recipes[i]);\n }else {\n inDegree.put(recipes[i], nonAvailable);\n }\n }\n // Toplogical Sort.\n for (int i = 0; i < ans.size(); ++i) {\n String recipe = ans.get(i);\n if (ingredientToRecipes.containsKey(recipe)) {\n for (String rcp : ingredientToRecipes.remove(recipe)) {\n if (inDegree.merge(rcp, -1, Integer::sum) == 0) {\n ans.add(rcp);\n }\n }\n }\n }\n return ans;\n }\n```\n```python\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n available = set(supplies)\n ans, ingredient_to_recipe, in_degree = [], defaultdict(set), Counter()\n for rcp, ingredient in zip(recipes, ingredients):\n non_available = 0\n for ing in ingredient:\n if ing not in available:\n non_available += 1\n ingredient_to_recipe[ing].add(rcp)\n if non_available == 0:\n ans.append(rcp)\n else:\n in_degree[rcp] = non_available\n for rcp in ans:\n for recipe in ingredient_to_recipe.pop(rcp, set()):\n in_degree[recipe] -= 1\n if in_degree[recipe] == 0:\n ans.append(recipe)\n return ans\n```\n\nSimpler version is as follows:\n\nAssumption: `ingredients do not contain any recipe`.\n1. For each recipe, count its dependent ingredients as in degree; Store (ingredient, recipes that dependent on it) as HashMap; \n2. Use the `supplies` as the starting points of topological sort;\n3. Use topogical sort to decrease the in degree of recipes, whenever the in-degree reaches `0`, add it to return list.\n```java\n public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {\n // Construct directed graph and count in-degrees.\n Map<String, Set<String>> ingredientToRecipes = new HashMap<>();\n Map<String, Integer> inDegree = new HashMap<>();\n for (int i = 0; i < recipes.length; ++i) {\n for (String ing : ingredients.get(i)) {\n ingredientToRecipes.computeIfAbsent(ing, s -> new HashSet<>()).add(recipes[i]);\n }\n inDegree.put(recipes[i], ingredients.get(i).size());\n }\n // Toplogical Sort.\n List<String> ans = new ArrayList<>();\n Queue<String> available = Stream.of(supplies).collect(Collectors.toCollection(LinkedList::new));\n while (!available.isEmpty()) {\n String ing = available.poll();\n if (ingredientToRecipes.containsKey(ing)) {\n for (String rcp : ingredientToRecipes.remove(ing)) {\n if (inDegree.merge(rcp, -1, Integer::sum) == 0) {\n available.offer(rcp);\n ans.add(rcp);\n }\n }\n }\n }\n return ans;\n }\n```\n\n```python\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n # Construct directed graph and count the in-degrees\n ingredient_to_recipe, in_degree = defaultdict(set), Counter()\n for rcp, ingredient in zip(recipes, ingredients):\n for ing in ingredient:\n ingredient_to_recipe[ing].add(rcp)\n in_degree[rcp] = len(ingredient)\n # Topological sort. \n available, ans = deque(supplies), []\n while available:\n ing = available.popleft()\n for rcp in ingredient_to_recipe.pop(ing, set()):\n in_degree[rcp] -= 1\n if in_degree[rcp] == 0:\n available.append(rcp)\n ans.append(rcp)\n return ans\n```\n\nWe can further simplify a bit the above Python 3 code, if you do NOT mind modifying the input `supplies`: get rid of the deque `available` and use `supplies` instead.\n\n```python\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n # Construct directed graph and count the in-degrees\n ingredient_to_recipe, in_degree = defaultdict(set), Counter()\n for rcp, ingredient in zip(recipes, ingredients):\n for ing in ingredient:\n ingredient_to_recipe[ing].add(rcp)\n in_degree[rcp] = len(ingredient)\n # Topological sort. \n ans = []\n for ing in supplies:\n for rcp in ingredient_to_recipe.pop(ing, set()):\n in_degree[rcp] -= 1\n if in_degree[rcp] == 0:\n supplies.append(rcp)\n ans.append(rcp)\n return ans\n```\n\n----\n\n**Q & A**\nQ1: Please explain the below statement(particularly how these set() funtion here).\n\n```python\n for rcp in ingredient_to_recipe.pop(ing, set()):\n```\nA1: `ingredient_to_recipe.pop(ing, set())`: If existing, the dict will remove the entry (key, value) and return the value corresponding to the key; if not, the dict will return the default value, a empty set.\n\nTherefore, if the key `ing` is in the dict, `ingredient_to_recipe`, the statement will one by one traverse the value, the set corresponding to `ing`; if not, it will NOT iterate into a empty set.\n\nQ2: Can you explain the intuition behind mapping ingredients to recipes instead of recipes to ingredients?\nA2: Mapping ingredients to recipes is an iterative way, and from recipes to ingredients is a recursive way. Topological Sort I used is an iterative algorithm to handle the problem.\n\nSince the problem ask us to find all of the possible recipes, and it says that "Ingredients to a recipe may need to be created from other recipes", we build nonavailable ingredient to its dependent recipe mapping to implement the Topological Sort algorithm. You may need to learn the algorithm if you are not familiar with it. \n\n**End of Q & A**\n
104,763
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
10,263
74
This problem is not complex but "hairy".\n\nSince we only care if a recipe can be made or not (regarless of in which order), we do not need a topological sort. \n\nWe can use a simple DFS; we just need to track `can_make` for each recipe (undefined, yes or no), so that we traverse each node only once.\n\nTo simplify the DFS logic, we check `supplies` when generating `graph`, and create a self-loop for recipes without needed `supplies`. This ensures that those `recipes` cannot be made.\n\n**Python 3**\n```python\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n graph, can_make, supplies = {recipe : [] for recipe in recipes}, {}, set(supplies)\n def dfs(recipe : str) -> bool:\n if recipe not in can_make:\n can_make[recipe] = False\n can_make[recipe] = all([dfs(ingr) for ingr in graph[recipe]])\n return can_make[recipe]\n for i, recipe in enumerate(recipes):\n for ingr in ingredients[i]:\n if ingr not in supplies:\n graph[recipe].append(ingr if ingr in graph else recipe)\n return [recipe for recipe in recipes if dfs(recipe)]\n```
104,765
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
5,730
68
Please check out this [commit]() for solutions of biweekly 68. \n\n```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n indeg = defaultdict(int)\n graph = defaultdict(list)\n for r, ing in zip(recipes, ingredients): \n indeg[r] = len(ing)\n for i in ing: graph[i].append(r)\n \n ans = []\n queue = deque(supplies)\n recipes = set(recipes)\n while queue: \n x = queue.popleft()\n if x in recipes: ans.append(x)\n for xx in graph[x]: \n indeg[xx] -= 1\n if indeg[xx] == 0: queue.append(xx)\n return ans \n```
104,766
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
153
5
# Intuition\nSome Recipe depends on some other Recipe that is cooked before -> Sound very similar to course schedule -> Topological sort\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 * M)$$ with N is the number of recipes, M is number of ingredients/recipes requires for each recipes\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M * N + S)$$ with N is the number of recipes, M is number of ingredients/recipes requires for each recipes and S is number of supplies\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n not_supplied_needs = collections.Counter()\n ingredients_needs = collections.defaultdict(list)\n supplies_set = set(supplies)\n\n for i in range(len(recipes)):\n recipe = recipes[i]\n for ingredient in ingredients[i]:\n if ingredient not in supplies:\n not_supplied_needs[recipe] += 1\n ingredients_needs[ingredient].append(recipe)\n \n\n q = collections.deque()\n for recipe in recipes:\n if not_supplied_needs[recipe] == 0: q.append(recipe)\n\n res = []\n while q:\n recipe = q.popleft()\n res.append(recipe)\n for new_recipe in ingredients_needs[recipe]:\n not_supplied_needs[new_recipe] -= 1\n if not_supplied_needs[new_recipe] == 0: q.append(new_recipe)\n \n return res\n```
104,770
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
4,271
47
## IDEA :\n*Yeahh, This question is little tricky. But when we come to question in which one element is dependent on others element to complete then we have to first think of Graph.*\nHere, All the recipes and supplies ingredients should be made node and Edges `a->b` to be defined as for completion of recipe `b` we should have ingredients `a`.\n\nTaking the first Example:\n\'\'\'\n\n\trecipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]\n\t\n\twe can now draw the graph first. (Consider the graph directed from upper nodes to downwards)\n\t\n\t\t\t\t\tyeast flour\n\t\t\t\t\t\t \\ /\n\t\t\t\tmeat Bread\n\t\t\t\t \\ /\n\t\t\t\t SandWhich\n\nSo From here, we can clearly see that we have to do topological sort, Since our graph will be always DAG.\n\n**Topological Sort :-** Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.\n****\n### Implementation :\n\'\'\'\n\n\tclass Solution:\n\t\tdef findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n\n\t\t\tgraph = defaultdict(list)\n\t\t\tin_degree = defaultdict(int)\n\t\t\tfor r,ing in zip(recipes,ingredients):\n\t\t\t\tfor i in ing:\n\t\t\t\t\tgraph[i].append(r)\n\t\t\t\t\tin_degree[r]+=1\n\n\t\t\tqueue = supplies[::]\n\t\t\tres = []\n\t\t\twhile queue:\n\t\t\t\ting = queue.pop(0)\n\t\t\t\tif ing in recipes:\n\t\t\t\t\tres.append(ing)\n\n\t\t\t\tfor child in graph[ing]:\n\t\t\t\t\tin_degree[child]-=1\n\t\t\t\t\tif in_degree[child]==0:\n\t\t\t\t\t\tqueue.append(child)\n\n\t\t\treturn res\n\t\t\n### Feel free to ask if you have any doubts!! \uD83E\uDD17\n### **Thanks & Upvote if you like the Idea !!** \uD83E\uDD1E
104,771
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
1,205
9
```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n adj=defaultdict(list)\n ind=defaultdict(int)\n \n for i in range(len(ingredients)):\n for j in range(len(ingredients[i])):\n adj[ingredients[i][j]].append(recipes[i])\n ind[recipes[i]]+=1\n ans=[]\n q=deque()\n for i in range(len(supplies)):\n q.append(supplies[i])\n while q:\n node=q.popleft()\n for i in adj[node]:\n ind[i]-=1\n if ind[i]==0:\n q.append(i)\n ans.append(i)\n return ans\n\n```
104,794
Find All Possible Recipes from Given Supplies
find-all-possible-recipes-from-given-supplies
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
Array,Hash Table,String,Graph,Topological Sort
Medium
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
1,133
14
below is the graph for example 2 - \n![image]()\n\n```\nclass Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n \n graph = defaultdict(list)\n indegree = defaultdict(int)\n q = deque()\n result = []\n \n # everything in supplies has an indegree of 0\n for s in supplies:\n indegree[s] = 0\n q.append(s)\n \n for i, r in enumerate(recipes):\n for ing in ingredients[i]:\n graph[ing].append(r)\n indegree[r] += 1\n \n while q:\n node = q.pop()\n if node in recipes:\n result.append(node)\n for n in graph[node]:\n indegree[n] -= 1\n if indegree[n] == 0:\n q.append(n)\n \n return result\n```
104,802
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
13,741
207
A useful trick (when doing any parentheses validation) is to greedily check balance left-to-right, and then right-to-left.\n- Left-to-right check ensures that we do not have orphan \')\' parentheses.\n- Right-to-left checks for orphan \'(\' parentheses.\n\nWe go left-to-right:\n- Count `wild` (not locked) characters. \n- Track the balance `bal` for locked parentheses. \n\t- If the balance goes negative, we check if we have enough `wild` characters to compensate.\n- In the end, check that we have enough `wild` characters to cover positive balance (open parentheses). \n\nThis approach alone, however, will fail for `["))((", "0011"]` test case. That is why we also need to do the same going right-to-left.\n\n**Python 3**\n```python\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n def validate(s: str, locked: str, op: str) -> bool:\n bal, wild = 0, 0\n for i in range(len(s)):\n if locked[i] == "1":\n bal += 1 if s[i] == op else -1\n else:\n wild += 1\n if wild + bal < 0:\n return False\n return bal <= wild\n return len(s) % 2 == 0 and validate(s, locked, \'(\') and validate(s[::-1], locked[::-1], \')\')\n```\n\n**Java**\n```java\nboolean validate(String s, String locked, char op) {\n int bal = 0, wild = 0, sz = s.length();\n int start = op == \'(\' ? 0 : sz - 1, dir = op == \'(\' ? 1 : - 1;\n for (int i = start; i >= 0 && i < sz && wild + bal >= 0; i += dir)\n if (locked.charAt(i) == \'1\')\n bal += s.charAt(i) == op ? 1 : -1;\n else\n ++wild;\n return Math.abs(bal) <= wild;\n}\npublic boolean canBeValid(String s, String locked) {\n return s.length() % 2 == 0 && validate(s, locked, \'(\') && validate(s, locked, \')\');\n}\n```\n**C++**\n```cpp\nbool canBeValid(string s, string locked) {\n auto validate = [&](char op) {\n int bal = 0, wild = 0, sz = s.size();\n int start = op == \'(\' ? 0 : sz - 1, dir = op == \'(\' ? 1 : - 1;\n for (int i = start; i >= 0 && i < sz && wild + bal >= 0; i += dir)\n if (locked[i] == \'1\')\n bal += s[i] == op ? 1 : -1;\n else\n ++wild;\n return abs(bal) <= wild;\n };\n return s.size() % 2 == 0 && validate(\'(\') && validate(\')\');\n}\n```
104,809
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
7,254
120
* We iterate over the string s twice. \n* Count of variable brackets is maintained using `tot`\n* Count of fixed open brackets is maintained using `op`\n* Count of fixed closed brackets is maintained using `cl`\n* In forward iteration we are checking if we have too many fixed closed brackets `)`, this is achieved using: `if tot + op - cl < 0: return False `\n* In backward iteration we are checking if we have too many fixed open brackets `(`, this is achieved using: `if tot - op + cl < 0: return False`\n\n**Python3**:\n```\n def canBeValid(self, s: str, l: str) -> bool:\n if len(s) % 2 == 1: return False\n tot = op = cl = 0 # tot -> Total variable brackets, op -> Open, cl -> Closed\n for i in range(len(s) - 1, -1, -1):\n if l[i] == \'0\': tot += 1\n elif s[i] == \'(\': op += 1\n elif s[i] == \')\': cl += 1\n if tot - op + cl < 0: return False\n tot = op = cl = 0\n for i in range(len(s)):\n if l[i] == \'0\': tot += 1\n elif s[i] == \'(\': op += 1\n elif s[i] == \')\': cl += 1\n if tot + op - cl < 0: return False \n return True\n```\n\n<iframe src="" frameBorder="0" width="700" height="490"></iframe>\n\n
104,811
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
1,733
28
**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n```\nclass Solution(object):\n def canBeValid(self, s, locked):\n if len(s) % 2: # Intuitively, odd-length s cannot be valid.\n return False\n\n # traverse each parenthesis forward, treat all unlocked Parentheses as\'(\' and check if there is \')\'\n # that cannot be eliminated by previous \'(\', if it exists, then the input s can\'t be valid.\n balance = 0\n for i in range(len(s)):\n balance += 1 if s[i] == \'(\' or locked[i] == \'0\' else -1\n if balance < 0:\n return False\n\n # traverse each parenthesis backward, treat all unlocked Parentheses as\')\' and check if there is \'(\'\n # that cannot be eliminated by previous \')\', if it exists, then the input s can\'t be valid.\n balance = 0\n for i in range(len(s) - 1, -1, -1):\n balance += 1 if s[i] == \')\' or locked[i] == \'0\' else -1\n if balance < 0:\n return False\n\n return True\n```
104,817
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
1,246
9
Please check out this [commit]() for solutions of biweekly 68. \n\n```\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n if len(s)&1: return False\n bal = 0\n for ch, lock in zip(s, locked):\n if lock == \'0\' or ch == \'(\': bal += 1\n elif ch == \')\': bal -= 1\n if bal < 0: return False \n bal = 0\n for ch, lock in zip(reversed(s), reversed(locked)): \n if lock == \'0\' or ch == \')\': bal += 1\n elif ch == \'(\': bal -= 1\n if bal < 0: return False\n return True\n```\n\nNote: zip object is not reversable but reversed object is zippable.
104,823
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
767
8
We go through in one pass, with 3 variables: \n\t\n\t1. freeL, the number of left parentheses that may be toggled\n\t2. freeR, the number of rights that can be toggled\n\t3. degree, the number of left parentheses so far minus right parentheses so far\n\nFormulated this way, the problem is whether we can swap parentheses so that at no point does degree drop below 0, and, at the end, the degree = freeL.\n\nIterating through s, we adjust the variables in the obvious way. If we come on a right parenthesis, and degree is 0, the case is possible invalid. Now, if there are no free rights, then the case definitely is invalid and we return false. If there is a free right, then we decrement freeR by 1 and increment degree by 2, simulating swapping a prior free right into a left.\n\nAfter this, number of free lefts must be adjusted to be no greater than degree/2. The reason for this is, toggling a left parenthesis decrements degree by 2. If we were to toggle more than degree/2 lefts, degree would drop below 0.\n\nLast, we only need to check if the degree is equal to number of free lefts.\n\n```\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n freeL, freeR, degree = 0, 0, 0\n for c, lock in zip(s, locked):\n if c == \'(\': \n degree += 1\n if lock == \'0\': freeL += 1\n else: \n degree -= 1\n if lock == \'0\': freeR += 1\n if degree < 0:\n if not freeR: return False\n freeR -= 1\n degree += 2\n freeL = min(degree//2, freeL)\n return degree == freeL*2
104,826
Check if a Parentheses String Can Be Valid
check-if-a-parentheses-string-can-be-valid
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, Return true if you can make s a valid parentheses string. Otherwise, return false.
String,Stack,Greedy
Medium
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(' and additional unlocked indices. How can you balance out the locked '(' now? What if you cannot balance any locked '('?
473
5
If s has an odd length, it\'s impossible to get a valid string.\nPass through s and locked, and use low and high to track the range of the possible number of "(" remained.\nIf s[i] is locked, add or minus low and high by 1.\nIf s[i] is unlocked, it can be modified as \')\' with low -= 1, or \'(\' with high += 1.\nIn each step, low should not be lower than 0, so we get low=max(0, low) and if low > high, it\'s impossible to be valid.\nFinally, the string can be valid only if 0 is within the range of [low, high], or low == 0.\n\n```\nclass Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n if len(s) % 2 == 1:\n return False\n low = high = 0\n for i in range(len(s)):\n if locked[i] == \'1\':\n if s[i] == \'(\':\n low += 1\n high += 1\n else:\n low -= 1\n high -= 1\n else:\n low -= 1\n high += 1\n low = max(low, 0)\n if low > high:\n return False\n return low == 0\n```
104,833
Abbreviating the Product of a Range
abbreviating-the-product-of-a-range
You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right]. Since the product may be very large, you will abbreviate it following these steps: Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].
Math
Hard
Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is nothing but the number of times the product is completely divisible by 10. Since 2 and 5 are the only prime factors of 10, C will be equal to the minimum number of times 2 or 5 appear in the prime factorization of the product. Iterate through the integers from left to right. For every integer, keep dividing it by 2 as long as it is divisible by 2 and C occurrences of 2 haven't been removed in total. Repeat this process for 5. Finally, multiply the integer under modulo of 10^5 with the product obtained till now to obtain the last five digits. The product P can be represented as P=10^(x+y) where x is the integral part and y is the fractional part of x+y. Using the property "if S = A * B, then log(S) = log(A) + log(B)", we can write x+y = log_10(P) = sum(log_10(i)) for each integer i in [left, right]. Once we obtain the sum, the first five digits can be represented as floor(10^(y+4)).
811
10
Please check out this [commit]() for solutions of biweekly 68. \n\n```\nclass Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n ans = prefix = suffix = 1\n trailing = 0 \n flag = False \n for x in range(left, right+1): \n if not flag: \n ans *= x\n while ans % 10 == 0: ans //= 10 \n if ans >= 1e10: flag = True \n prefix *= x\n suffix *= x\n while prefix >= 1e12: prefix //= 10 \n while suffix % 10 == 0: \n trailing += 1\n suffix //= 10 \n if suffix >= 1e10: suffix %= 10_000_000_000\n while prefix >= 100000: prefix //= 10 \n suffix %= 100000\n if flag: return f"{prefix}...{suffix:>05}e{trailing}"\n return f"{ans}e{trailing}"\n```
104,864
Rings and Rods
rings-and-rods
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them.
Hash Table,String
Easy
For every rod, look through β€˜rings’ to see if the rod contains all colors. Create 3 booleans, 1 for each color, to store if that color is present for the current rod. If all 3 are true after looking through the string, then the rod contains all the colors.
1,797
24
```\nclass Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if \'R\'+i in r and \'G\'+i in r and \'B\'+i in r:\n ans += 1\n return ans\n```
104,923
Rings and Rods
rings-and-rods
There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them.
Hash Table,String
Easy
For every rod, look through β€˜rings’ to see if the rod contains all colors. Create 3 booleans, 1 for each color, to store if that color is present for the current rod. If all 3 are true after looking through the string, then the rod contains all the colors.
492
8
```class Solution:\n def countPoints(self, rings: str) -> int:\n out =0\n for i in range(0,10):\n if rings.count(\'R\'+str(i)) and rings.count(\'G\'+str(i)) and rings.count(\'B\'+str(i)):\n out +=1\n return out\n\t\t\n\t\t
104,940
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
56,986
379
# **Solution 0, Brute Force**\nTime `O(n^3)`\nSpace `O(1)`\n<br>\n\n# **Solution 1, Two Loops Solution**\nTime `O(n^2)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public long subArrayRanges(int[] A) {\n long res = 0;\n for (int i = 0; i < A.length; i++) {\n int max = A[i], min = A[i];\n for (int j = i; j < A.length; j++) {\n max = Math.max(max, A[j]);\n min = Math.min(min, A[j]);\n res += max - min;\n }\n }\n return res;\n }\n```\n**C++**\n```cpp\n long long subArrayRanges(vector<int>& A) {\n long long res = 0;\n for (int i = 0; i < A.size(); i++) {\n int ma = A[i], mi = A[i];\n for (int j = i; j < A.size(); j++) {\n ma = max(ma, A[j]);\n mi = min(mi, A[j]);\n res += ma - mi;\n }\n }\n return res;\n }\n```\n**Python**\n```py\n def subArrayRanges(self, A):\n res = 0\n n = len(A)\n for i in xrange(n):\n l,r = A[i],A[i]\n for j in xrange(i, n):\n l = min(l, A[j])\n r = max(r, A[j])\n res += r - l\n return res\n```\n\n# **Solution 2, O(n) Stack Solution**\nFollow the explanation in [907. Sum of Subarray Minimums]()\n\n# Intuition\nres = sum(A[i] * f(i))\nwhere f(i) is the number of subarrays,\nin which A[i] is the minimum.\n\nTo get f(i), we need to find out:\nleft[i], the length of strict bigger numbers on the left of A[i],\nright[i], the length of bigger numbers on the right of A[i].\n\nThen,\nleft[i] + 1 equals to\nthe number of subarray ending with A[i],\nand A[i] is single minimum.\n\nright[i] + 1 equals to\nthe number of subarray starting with A[i],\nand A[i] is the first minimum.\n\nFinally f(i) = (left[i] + 1) * (right[i] + 1)\n\nFor [3,1,2,4] as example:\nleft + 1 = [1,2,1,1]\nright + 1 = [1,3,2,1]\nf = [1,6,2,1]\nres = 3 * 1 + 1 * 6 + 2 * 2 + 4 * 1 = 17\n\n\n# Explanation\nTo calculate left[i] and right[i],\nwe use two increasing stacks.\n\nIt will be easy if you can refer to this problem and my post:\n901. Online Stock Span\nI copy some of my codes from this solution.\n\n\n# Complexity\nAll elements will be pushed twice and popped at most twice\nTime `O(n)`\nSpace `O(n)`\n\n**Java**\n```java\n public long subArrayRanges(int[] A) {\n int n = A.length, j, k;\n long res = 0;\n \n Stack<Integer> s = new Stack<>();\n for (int i = 0; i <= n; i++) {\n while (!s.isEmpty() && A[s.peek()] > (i == n ? Integer.MIN_VALUE : A[i])) {\n j = s.pop();\n k = s.isEmpty() ? -1 : s.peek();\n res -= (long)A[j] * (i - j) * (j - k);\n\n }\n s.push(i);\n }\n \n s.clear();\n for (int i = 0; i <= n; i++) {\n while (!s.isEmpty() && A[s.peek()] < (i == n ? Integer.MAX_VALUE : A[i])) {\n j = s.pop();\n k = s.isEmpty() ? -1 : s.peek();\n res += (long)A[j] * (i - j) * (j - k);\n\n }\n s.push(i);\n }\n return res;\n }\n```\n**C++**\n```cpp\n long long subArrayRanges(vector<int>& A) {\n long res = 0, n = A.size(), j, k;\n stack<int> s;\n for (int i = 0; i <= n; ++i) {\n while (!s.empty() && A[s.top()] > (i == n ? -2e9 : A[i])) {\n j = s.top(), s.pop();\n k = s.empty() ? -1 : s.top();\n res -= (long)A[j] * (i - j) * (j - k);\n }\n s.push(i);\n }\n s = stack<int>();\n for (int i = 0; i <= n; ++i) {\n while (!s.empty() && A[s.top()] < (i == n ? 2e9 : A[i])) {\n j = s.top(), s.pop();\n k = s.empty() ? -1 : s.top();\n res += (long)A[j] * (i - j) * (j - k);\n }\n s.push(i);\n }\n return res;\n }\n```\n**Python**\n```py\n def subArrayRanges(self, A0):\n res = 0\n inf = float(\'inf\')\n A = [-inf] + A0 + [-inf]\n s = []\n for i, x in enumerate(A):\n while s and A[s[-1]] > x:\n j = s.pop()\n k = s[-1]\n res -= A[j] * (i - j) * (j - k)\n s.append(i)\n \n A = [inf] + A0 + [inf]\n s = []\n for i, x in enumerate(A):\n while s and A[s[-1]] < x:\n j = s.pop()\n k = s[-1]\n res += A[j] * (i - j) * (j - k)\n s.append(i)\n return res\n```
104,959
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
6,060
45
```python\n\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n n = len(nums)\n \n # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n # so totalsum = maxsum - minsum\n # we calculate minsum and maxsum in two different loops\n minsum = maxsum = 0\n \n # first calculate sum{ Min(subarray) } over all subarrays\n # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1\n # where f(i) is number of subarrays where nums[i] is the minimum value\n # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i]\n # we can claculate these indices in linear time using a monotonically increasing stack.\n stack = []\n for next_smaller in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically increasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]):\n i = stack.pop()\n prev_smaller = stack[-1] if stack else -1\n minsum += nums[i] * (next_smaller - i) * (i - prev_smaller)\n stack.append(next_smaller)\n \n # then calculate sum{ Max(subarray) } over all subarrays\n # sum{ Max(subarray) } = sum(f\'(i) * nums[i]) ; i=0..n-1\n # where f\'(i) is number of subarrays where nums[i] is the maximum value\n # f\'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i]\n # this time we use a monotonically decreasing stack.\n stack = []\n for next_larger in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically decreasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]):\n i = stack.pop()\n prev_larger = stack[-1] if stack else -1\n maxsum += nums[i] * (next_larger - i) * (i - prev_larger)\n stack.append(next_larger)\n \n return maxsum - minsum\n```
104,963
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
4,624
17
Please check out this [commit]() for solutions of weekly 271. \n\n```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n \n def fn(op): \n """Return min sum (if given gt) or max sum (if given lt)."""\n ans = 0 \n stack = []\n for i in range(len(nums) + 1): \n while stack and (i == len(nums) or op(nums[stack[-1]], nums[i])): \n mid = stack.pop()\n ii = stack[-1] if stack else -1 \n ans += nums[mid] * (i - mid) * (mid - ii)\n stack.append(i)\n return ans \n \n return fn(lt) - fn(gt)\n```\n\n**Related problems**\n[907. Sum of Subarray Minimums]((N))
104,972
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
2,329
8
```\n"""\nif you are not sure what is monotonous stack go through the concept given in this post:\n\n\n\n(n)\n"""\n\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n """\n [4,-2,-3,4,1]\n \n """\n n = len(nums)\n \n min_stack = []\n min_sum = 0\n\n for i in range(n + 1):\n while min_stack and nums[min_stack[-1]] > (nums[i] if i < n else -float(\'Inf\')):\n j = min_stack.pop()\n k = min_stack[-1] if min_stack else -1\n min_sum += (j - k) * (i - j) * nums[j]\n min_stack.append(i)\n \n max_stack = []\n max_sum = 0\n for i in range(n + 1):\n while max_stack and nums[max_stack[-1]] < (nums[i] if i < n else float(\'Inf\')):\n j = max_stack.pop()\n k = max_stack[-1] if max_stack else -1\n max_sum += (j - k) * (i - j) * nums[j]\n\n max_stack.append(i)\n \n ans = max_sum - min_sum\n \n return ans\n```
104,975
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
3,095
11
```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n res = 0\n min_stack, max_stack = [], []\n n = len(nums)\n nums.append(0)\n for i, num in enumerate(nums):\n while min_stack and (i == n or num < nums[min_stack[-1]]):\n top = min_stack.pop()\n starts = top - min_stack[-1] if min_stack else top + 1\n ends = i - top\n res -= starts * ends * nums[top] \n min_stack.append(i) \n while max_stack and (i == n or num > nums[max_stack[-1]]):\n top = max_stack.pop()\n starts = top - max_stack[-1] if max_stack else top + 1\n ends = i - top\n res += starts * ends * nums[top] \n max_stack.append(i) \n return res
104,979
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
1,323
5
```\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n mon = monotonicStack()\n \n # for each element, check in how many sub-arrays arrays, it can be max\n # find the prev and next greater element\n\n # for each element, check in how many sub-arrays arrays, it can be min\n # find the prev and next smaller element\n \n nse_l = mon.nextSmaller_left_idx(nums)\n nse_r = mon.nextSmaller_right_idx(nums)\n nge_l = mon.nextGreater_left_idx(nums)\n nge_r = mon.nextGreater_right_idx(nums)\n \n ans = 0\n \n for idx in range(len(nums)):\n smaller_left, smaller_right = nse_l[idx], nse_r[idx]\n greater_left, greater_right = nge_l[idx], nge_r[idx]\n \n if smaller_right == -1:\n smaller_right = len(nums)\n if greater_right == -1:\n greater_right = len(nums)\n \n min_val = (idx - smaller_left) * (smaller_right - idx) * nums[idx]\n max_val = (idx - greater_left) * (greater_right - idx) * nums[idx]\n \n ans += (max_val - min_val)\n return ans\n \nclass monotonicStack:\n def nextGreater_right_idx(self,arr):\n ans = [None] * len(arr)\n stack = []\n for idx in range(len(arr)-1,-1,-1):\n while stack and arr[stack[-1]] < arr[idx]:\n stack.pop()\n if not stack:\n #no greater element\n ans[idx] = -1\n else:\n ans[idx] = stack[-1]\n stack.append(idx)\n return ans\n \n def nextGreater_left_idx(self,arr):\n ans = [None] * len(arr)\n stack = []\n for idx in range(len(arr)):\n while stack and arr[stack[-1]] <= arr[idx]:\n stack.pop()\n if not stack:\n #no greater element\n ans[idx] = -1\n else:\n ans[idx] = stack[-1]\n stack.append(idx)\n return ans \n \n def nextSmaller_right_idx(self,arr):\n ans = [None] * len(arr)\n stack = []\n for idx in range(len(arr)-1,-1,-1):\n while stack and arr[stack[-1]] > arr[idx]:\n stack.pop()\n if not stack:\n #no smaller element\n ans[idx] = -1\n else:\n ans[idx] = stack[-1]\n stack.append(idx)\n return ans \n \n def nextSmaller_left_idx(self,arr):\n ans = [None] * len(arr)\n stack = []\n for idx in range(len(arr)):\n while stack and arr[stack[-1]] >= arr[idx]:\n stack.pop()\n if not stack:\n #no smaller element\n ans[idx] = -1\n else:\n ans[idx] = stack[-1]\n stack.append(idx)\n return ans \n```
104,984
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
906
5
Answer is `sum of max of all subarrays` - `sum of min of all subarrays`\n\nInspired from (n)-slightly-easier-to-grasp-solution-(explained)\n\nI am still using the same approach for `sum of min of all subarrays` and extended it to `sum of max of all subarrays` using decreasing monotonic stack. You need to understand the above solution to understand this. \n\n```python\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n nums = nums\n N = len(nums)\n maxRes = collections.defaultdict(int) # maxRes[-1] = 0 \n decMonoStack = []\n minRes = collections.defaultdict(int) # minRes[-1] = 0 \n incMonoStack = []\n \n for i in range(N):\n while decMonoStack and nums[decMonoStack[-1]] < nums[i]:\n decMonoStack.pop()\n j = decMonoStack[-1] if decMonoStack else -1\n maxRes[i] = maxRes[j] + (i - j) * nums[i]\n decMonoStack.append(i)\n \n for i in range(N):\n while incMonoStack and nums[incMonoStack[-1]] > nums[i]:\n incMonoStack.pop()\n j = incMonoStack[-1] if incMonoStack else -1\n minRes[i] = minRes[j] + (i - j) * nums[i]\n incMonoStack.append(i)\n \n return sum(maxRes.values()) - sum(minRes.values())\n```\nYou can merge them into one loop but I prefer to keep it separate.
104,989
Sum of Subarray Ranges
sum-of-subarray-ranges
You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array.
Array,Stack,Monotonic Stack
Medium
Can you get the max/min of a certain subarray by using the max/min of a smaller subarray within it? Notice that the max of the subarray from index i to j is equal to max of (max of the subarray from index i to j-1) and nums[j].
844
6
\'\'\'\nThere are alot of good answers that explains max_sum and min_sum initiative \nHere I will try to explain how I analyzed and solved this monotonic stack problem\n\nAssuming you are familiar with monotonic stack but don\'t know how to write the "while" part that pops the stack\n\nLet\'s go with an example:\n\nnums = [2,3,4,1,5]\n\n5|----------X\n4|----X\n3| --X \n2| X \n1|-------X \n---------------------------\n\nStep 1: Let\'s see how many ranges do we have and what they are\n\n2: [2] [2,3] [2,4] [2,1] [2,5]\n3: [3] [3,4] [3,1] [3,5]\n4: [4] [4,1] [4,5]\n1: [1] [1,5]\n2: [5]\n\nStep 2: Let\'s maintain a monotonicly increasing stack to keep the minimum of ranges\nas a thump of rule, we always process a number when we pop it\nso if we add 2 and then 3 and then 4 to our stack, we don\'t process anything\n\nSo let\'s write down the structure\n\nStep 3: Let\'s pop!\nwhen we reach to 1 (remember we never process the current item in mono stack problems)\nwe pop 4 and so we can say [4] is found here\nnow let\'s pop 3, at this point we know that there is no element less than 3 after index of 3 cause if it was we didn\'t have 3\nin our stack so i (index of current element in for) minus index of 3 is the range that we can surely say everything in between doesn\'t matter and 3 is the minimum for them\nso we have [3] and [3,4] here\nnow we pop 2 and same as above we have [2] and [2,3] and [2,3,4]\n\nAs you can see, if we just care about the minimum, we might as well just say the sum of min for all of these fetched ranges are:\n\n2: [2] [2,3] [2,4] min in all ranges is 2\n3: [3] [3,4] min in all ranges is 3\n4: [4] min in all ranges is 4\n\nSo the formula would be poped_item * (poped_index - i)\n\nwe push 1 to the stack BTW ATM :D\n\nStep 4:\nNow that we have 1 in stack we can put 5 in the stack but we just need to process these items\nSo like others we can just add a Integer.MIN_VALUE or float("-inf") to or input array to do the trick\n\nNo let\'s pop!\nJust like step 3 we can pop 5 and then 1 and after this round we have checked and know the min for all of the following ranges:\n2: [2] [2,3] [2,4]\n3: [3] [3,4]\n4: [4] \n1: [1] [1,5]\n2: [5]\n\nBut we should have come up with the following list!\n\n2: [2] [2,3] [2,4] [2,1] [2,5]\n3: [3] [3,4] [3,1] [3,5]\n4: [4] [4,1] [4,5]\n1: [1] [1,5]\n2: [5]\n\nTo find the missed ranges we should have looked into our stack and see what\'s on the top (that\'s our minimum for missed ranges) and then multiply them by their distance to i\nand if the stack is empty then we might have some elements in the stack that we already poped. we don\'t care what they were cause the were obviously greater than 1 (in this case)\nSo it\'s safe to say that the INDEX of whatever is on top of the stack or -1 should be multipled by the element that we poped from the stack (min of all of those ranges)\n\nSame goes with sum_max (second pass with min mono stack)\n\n\'\'\'\nclass Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n \n st = []\n sum_min = 0\n for i,n in enumerate(nums+[float("-inf")]):\n while st and nums[st[-1]] > n:\n j = st.pop()\n poped = nums[j]\n k = -1\n if st:\n k = st[-1]\n sum_min += poped * (i - j)*(j - k)\n st.append(i)\n \n st = []\n sum_max = 0\n for i,n in enumerate(nums+[float("inf")]):\n while st and nums[st[-1]] < n:\n j = st.pop()\n poped = nums[j]\n k = -1\n if st:\n k = st[-1]\n sum_max += poped * (i - j)*(j - k)\n st.append(i)\n \n return sum_max - sum_min
104,999
Watering Plants II
watering-plants-ii
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way: Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.
Array,Two Pointers,Simulation
Medium
Try "simulating" the process. Since watering each plant takes the same amount of time, where will Alice and Bob meet if they start watering the plants simultaneously? How can you use this to optimize your solution? What will you do when both Alice and Bob have to water the same plant?
708
8
Please check out this [commit]() for solutions of weekly 271. \n\n```\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n canA, canB = capacityA, capacityB\n while lo < hi: \n if canA < plants[lo]: ans += 1; canA = capacityA\n canA -= plants[lo]\n if canB < plants[hi]: ans += 1; canB = capacityB\n canB -= plants[hi]\n lo, hi = lo+1, hi-1\n if lo == hi and max(canA, canB) < plants[lo]: ans += 1\n return ans \n```
105,021
Maximum Fruits Harvested After at Most K Steps
maximum-fruits-harvested-after-at-most-k-steps
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique. You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position. Return the maximum total number of fruits you can harvest.
Array,Binary Search,Sliding Window,Prefix Sum
Hard
Does an optimal path have very few patterns? For example, could a path that goes left, turns and goes right, then turns again and goes left be any better than a path that simply goes left, turns, and goes right? The optimal path turns at most once. That is, the optimal path is one of these: to go left only; to go right only; to go left, turn and go right; or to go right, turn and go left. Moving x steps left then k-x steps right gives you a range of positions that you can reach. Use prefix sums to get the sum of all fruits for each possible range. Use a similar strategy for all the paths that go right, then turn and go left.
1,173
11
By ignoring those out of range, we can simplify the given fruits into a new array, where the size of window is 2k+1. So the new array looks like: [ arr[0] ..... arr[k] = fruits[startPos] ..... arr[2k+1]]\n\nNote that we can also operate on the given array to save few lines (the pre-treatment above is also a O(N)).\n\nFirst, we begin from the sum of left part and sum of right part.\n\nNext, handle the cases when there\'s a change of direction: we use 2 moves when we go 1 step, turn back, and 1 step back to original spot. **Compared with no change of direction, we\'ve lost 2 positions.**\n\ne.g. \nsay we initially go right, but change direction at arr[k+1] \n=> we can no longer reach arr[0] and arr[1] \n=> simply use leftSum+arr[k+1] - arr[0] - arr[1]\n\nKeep increase the turning point (both at left and right side), so on and so forth. Both python and c++ are provided below. The logic is the same and I believe there\'s some room to make the code more concise. See [this]() for a 10 liner solution.\n\n**Trick**: using ~ in the Python index assignment to avoid counting index with array length.\n\n**Python**\n```\nclass Solution:\n def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n arr = [0 for _ in range(2*k+1)]\n for pos, numOfFruit in fruits:\n if pos < startPos-k or pos > startPos+k:\n continue\n arr[pos-(startPos-k)] += numOfFruit\n \n left, right = sum(arr[:k+1]), sum(arr[k:])\n maxSeen = max(left, right)\n \n turn = 1 # turning point\n for i in range(2, k+1, 2):\n left = left-arr[i-2]-arr[i-1]+arr[k+turn]\n right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn]\n maxSeen = max(maxSeen, left, right)\n turn += 1\n \n return maxSeen\n```\n\n**C++**\n```\nclass Solution {\npublic:\n int maxTotalFruits(vector<vector<int>>& fruits, int startPos, int k) {\n vector<int> arr;\n for (int i=0; i<2*k+1; ++i) {\n arr.push_back(0);\n }\n \n for (int i=0; i<fruits.size(); ++i) {\n if ((fruits[i][0] < startPos-k) || (fruits[i][0] > startPos+k)) continue;\n arr[fruits[i][0]-(startPos-k)] += fruits[i][1];\n }\n \n int left = 0, right = 0;\n for (int i = 0; i <= k; ++i) {\n left += arr[i];\n right += arr[k+i];\n }\n int maxSeen = max(left, right);\n int L = arr.size();\n int turn = 1;\n for (int i = 2; i < k+1; i += 2) {\n left = left+arr[k+turn]-arr[i-1]-arr[i-2];\n right = right+arr[k-turn]-arr[L-1-(i-1)]-arr[L-1-(i-2)];\n if (left > maxSeen) maxSeen = left;\n if (right > maxSeen) maxSeen = right;\n turn++;\n }\n return maxSeen;\n \n \n }\n};\n\n```\n
105,070
Find First Palindromic String in the Array
find-first-palindromic-string-in-the-array
Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "". A string is palindromic if it reads the same forward and backward.
Array,Two Pointers,String
Easy
Iterate through the elements in order. As soon as the current element is a palindrome, return it. To check if an element is a palindrome, can you reverse the string?
2,603
32
**Python :**\n\n```\ndef firstPalindrome(self, words: List[str]) -> str:\n for word in words:\n if word == word[::-1]\n return word\n \n return ""\n```\n\nand an one line version :\n\n```\ndef firstPalindrome(self, words: List[str]) -> str:\n\treturn next((word for word in words if word == word[::-1]), "")\n```\n\n**Like it ? please upvote !**
105,127
Adding Spaces to a String
adding-spaces-to-a-string
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.
Array,String,Simulation
Medium
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).
2,499
15
Reversely traverse input.\n\n```java\n public String addSpaces(String s, int[] spaces) {\n StringBuilder ans = new StringBuilder();\n for (int i = s.length() - 1, j = spaces.length - 1; i >= 0; --i) {\n ans.append(s.charAt(i));\n if (j >= 0 && spaces[j] == i) {\n --j;\n ans.append(\' \');\n }\n }\n return ans.reverse().toString();\n }\n```\n```python\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n ans = []\n i = len(s) - 1\n while i >= 0:\n ans.append(s[i])\n if spaces and i == spaces[-1]:\n ans.append(\' \')\n spaces.pop()\n i -= 1 \n return \'\'.join(ans[:: -1])\n```\n\n----\n\nTraverse input from left to right.\n```java\n public String addSpaces(String s, int[] spaces) {\n StringBuilder ans = new StringBuilder();\n for (int i = 0, j = 0; i < s.length(); ++i) {\n if (j < spaces.length && spaces[j] == i) {\n ans.append(\' \');\n ++j;\n }\n ans.append(s.charAt(i));\n }\n return ans.toString();\n }\n```\n```python\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n ans = []\n j = 0\n for i, c in enumerate(s):\n if j < len(spaces) and i == spaces[j]:\n ans.append(\' \')\n j += 1\n ans.append(c)\n return \'\'.join(ans)\n```
105,172
Adding Spaces to a String
adding-spaces-to-a-string
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.
Array,String,Simulation
Medium
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).
965
8
Just do what the question said i.e \nAdd spaces at that index \n\nIn the first solution i guess due to python\'s way of working with strings we are getting a TLE error\n```\n#TLE SOLUTION\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n\t\tspaces_idx = len(spaces)-1\n\n\t\tdef addString(index,s):\n\t\t\ts = s[:index]+" "+s[index:] \n\t\t\t#This changes the string at every instance hence taking so much time\n\t\t\treturn s\n\t\t\t\n\t\twhile spaces_idx>=0:\n\t\t\ts = addString(spaces[spaces_idx],s)\n\t\t\tspaces_idx-=1\n\t\treturn s\n```\nTo tackle this I **split** the required words and then used the **join** method to combine it with a whitespaces\n\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n \n arr = []\n prev = 0\n for space in spaces:\n arr.append(s[prev:space])\n prev = space\n arr.append(s[space:])\n \n return " ".join(arr)\n```
105,176
Adding Spaces to a String
adding-spaces-to-a-string
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.
Array,String,Simulation
Medium
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).
616
6
```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n arr=[]\n prev=0\n for i in spaces:\n arr.append(s[prev:i])\n prev=i\n arr.append(s[i:])\n return " ".join(arr)\n```
105,177
Adding Spaces to a String
adding-spaces-to-a-string
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.
Array,String,Simulation
Medium
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).
864
8
**Python :**\n\n```\ndef addSpaces(self, s: str, spaces: List[int]) -> str:\n\tres = s[:spaces[0]] + " "\n\n\tfor j in range(1, len(spaces)):\n\t\tres += s[spaces[j- 1]:spaces[j]] + " "\n\n\tres += s[spaces[-1]:] \n\treturn res\n```\n\n**Like it ? please upvote !**
105,181
Adding Spaces to a String
adding-spaces-to-a-string
You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index. Return the modified string after the spaces have been added.
Array,String,Simulation
Medium
Create a new string, initially empty, as the modified string. Iterate through the original string and append each character of the original string to the new string. However, each time you reach a character that requires a space before it, append a space before appending the character. Since the array of indices for the space locations is sorted, use a pointer to keep track of the next index to place a space. Only increment the pointer once a space has been appended. Ensure that your append operation can be done in O(1).
738
5
Please check out this [commit]() for solutions of weekly 272. \n\n**Approach 1 -- forward**\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n ans = []\n j = 0 \n for i, ch in enumerate(s): \n if j < len(spaces) and i == spaces[j]: \n ans.append(\' \')\n j += 1\n ans.append(ch)\n return \'\'.join(ans)\n```\n\n**Approach 2 -- backward**\n```\nclass Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n ans = []\n for i in reversed(range(len(s))): \n ans.append(s[i])\n if spaces and spaces[-1] == i: \n ans.append(\' \')\n spaces.pop()\n return "".join(reversed(ans))\n```
105,184
Number of Smooth Descent Periods of a Stock
number-of-smooth-descent-periods-of-a-stock
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.
Array,Math,Dynamic Programming
Medium
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k.
970
11
For each descent periods ending at `i`, use `cnt` to count the # of the the periods and add to the output variable `ans`.\n```java\n public long getDescentPeriods(int[] prices) {\n long ans = 0;\n int cnt = 0, prev = -1;\n for (int cur : prices) {\n if (prev - cur == 1) {\n ++cnt; \n }else {\n cnt = 1;\n }\n ans += cnt;\n prev = cur;\n }\n return ans;\n }\n```\n```python\n def getDescentPeriods(self, prices: List[int]) -> int:\n ans = cnt = 0\n prev = -math.inf\n for cur in prices:\n if prev - cur == 1:\n cnt += 1\n else:\n cnt = 1\n ans += cnt\n prev = cur\n return ans\n```
105,228
Number of Smooth Descent Periods of a Stock
number-of-smooth-descent-periods-of-a-stock
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.
Array,Math,Dynamic Programming
Medium
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k.
476
5
In order to solve this problem I would prefer you take a pen and paper and make few testcases of your own.\nDuring that youll find some similarities\nLet me illustrate:\n[3,2,1] - [3,2] , [2,1] , [3,2,1] and singular values\n3+3 = 6\nNow when we have 4 numbers\n[4,3,2,1] \nwhen we take two numbers at once\n[4,3] ,[3,2] ,[2,1] 3 cases-.\nwhen we take 3 numbers at once\n[4,3,2] , [3,2,1] - 2 cases\nwhen we take 4 numbers at once\n[4,3,2,1] - 1 cases\n\nTo add we sum it i.e **sum of natural numbers **\n**(N*(N+1))//2**\nHere N is size of the **(contiguous valid array - 1)**\nAlso we will add all singualar values as they also satisfy the condition\nThus **ans+=len(arr)**.\n\n**So all different contiguous arrays which satisfy + size of array** \nIn the code we keep track of contiguous array using the value of k \nAnd calculate the value using the sum of natural numbers.\n\n```\nimport sys\nclass Solution:\n def getDescentPeriods(self, prices: List[int]) -> int: \n def calculate(k,ans):\n if k>1:\n ans+=((k-1)*(k))//2 \n\t\t\t\t#Sum of Natural Numbers\n return ans\n else:\n return ans\n end = 0\n start = 0\n prev= sys.maxsize\n k= 0\n ans = 0\n while end<len(prices): \n if prev- prices[end]==1 or prev == sys.maxsize:\n k+=1\n prev = prices[end]\n end+=1 \n else: \n ans = calculate(k,ans)\n start = end\n if end<len(prices):\n prev = sys.maxsize\n k=0\n if k>1:\n ans = calculate(k,ans)\n\t\t\t\n return ans+len(prices)\n```
105,235
Number of Smooth Descent Periods of a Stock
number-of-smooth-descent-periods-of-a-stock
You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day. A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule. Return the number of smooth descent periods.
Array,Math,Dynamic Programming
Medium
Any array is a series of adjacent longest possible smooth descent periods. For example, [5,3,2,1,7,6] is [5] + [3,2,1] + [7,6]. Think of a 2-pointer approach to traverse the array and find each longest possible period. Suppose you found the longest possible period with a length of k. How many periods are within that period? How can you count them quickly? Think of the formula to calculate the sum of 1, 2, 3, ..., k.
503
8
Please check out this [commit]() for solutions of weekly 272. \n\n```\nclass Solution:\n def getDescentPeriods(self, prices: List[int]) -> int:\n ans = 0 \n for i, x in enumerate(prices): \n if i == 0 or prices[i-1] != x + 1: cnt = 0\n cnt += 1\n ans += cnt \n return ans \n```
105,239
Minimum Operations to Make the Array K-Increasing
minimum-operations-to-make-the-array-k-increasing
You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1. In one operation, you can choose an index i and change arr[i] into any positive integer. Return the minimum number of operations required to make the array K-increasing for the given k.
Array,Binary Search
Hard
Can we divide the array into non-overlapping subsequences and simplify the problem? In the final array, arr[i-k] ≀ arr[i] should hold. We can use this to divide the array into at most k non-overlapping sequences, where arr[i] will belong to the (i%k)th sequence. Now our problem boils down to performing the minimum operations on each sequence such that it becomes non-decreasing. Our answer will be the sum of operations on each sequence. Which indices of a sequence should we not change in order to count the minimum operations? Can finding the longest non-decreasing subsequence of the sequence help?
732
5
* First divide arr into k groups and consider each group individually.\n* In each group, we need to find out the length of the longest increasing sequence, because the longest increasing sequence does not need to be operated, and the remaining positions can be set to the value of the previous or next in the longest increasing sequence.\n* For example, `arr = [2, 3, 4, 2, 3 , 3]`\n\t* the longest increasing sequence is [2, 2, 3, 3], that is [**2**, 3, 4, **2**, **3** , **3**]\n\t* we can modify arr[1] from 3 to 2 and arr[2] from 4 to 2, and then the arr is increasing, that is [2, 2, 2, 2, 3, 3]\n\t* after all we need to make 2 operations to make `arr = [2, 3, 4, 2, 3 , 3]` increasing, that is `len(arr) - len(lis(arr))`\n\n[Prob 300 Longest-Increasing-Subsequence]((nlogn)-time-with-explanation), **@dietpepsi explained very well, I just copied his explanation below.**\n\n`tails` **is an array storing the smallest tail of all increasing subsequences with length** `i+1` in `tails[i]`.\nFor example, say we have `nums = [4,5,6,3]`, then all the available increasing subsequences are:\n\n```\nlen = 1 : [4], [5], [6], [3] => tails[0] = 3\nlen = 2 : [4, 5], [5, 6] => tails[1] = 5\nlen = 3 : [4, 5, 6] => tails[2] = 6\n```\nWe can easily prove that tails is a increasing array. Therefore it is possible to do a binary search in tails array to find the one needs update.\n\n\n\n```\n(1) if x is larger than all tails, append it, increase the size by 1\n(2) if tails[i-1] < x <= tails[i], update tails[i]\n```\n\n\n**If you have any question, feel free to ask. If you like the solution or the explanation, Please UPVOTE!**\n\n**Python 100% Faster**\n```\nclass Solution(object):\n def kIncreasing(self, arr, k):\n ans = len(arr)\n for i in range(k):\n tails = []\n for j in range(i, len(arr), k):\n if tails and tails[-1] > arr[j]:\n tails[bisect.bisect(tails, arr[j])] = arr[j]\n else:\n tails.append(arr[j])\n ans -= len(tails)\n return ans\n```\n\n**C++ 63.64% Faster**\n```\nclass Solution {\npublic:\n int kIncreasing(vector<int>& arr, int k) {\n int ans = arr.size();\n for(int i = 0; i < k; i ++) {\n vector<int> tails;\n for(int j = i; j < arr.size(); j += k) {\n if(tails.size() == 0 or arr[j] >= tails[tails.size() - 1]) {\n tails.push_back(arr[j]);\n } else {\n tails[upper_bound(tails.begin(), tails.end(), arr[j]) - tails.begin()] = arr[j];\n }\n }\n ans -= tails.size();\n }\n return ans;\n }\n};\n```\n**Java 100% Faster**\n* I\'m not very good at Java, and I did not find a function like bisect in Python, so I implement one below, that\'s why the java code is longer than C++ or Python above.\n* I hope friends who are good at java can help me simplify the Java code below.\n```\nclass Solution {\n public int kIncreasing(int[] arr, int k) {\n int ans = arr.length;\n int[] tails = new int[arr.length];\n for (int i = 0; i < k; i ++) {\n int size = 0;\n for (int j = i; j < arr.length; j += k) {\n if (size == 0 || arr[j] >= tails[size - 1]) {\n tails[size ++] = arr[j];\n } else {\n int low = 0, high = size - 1;\n while (low <= high) {\n int mid = (low + high) / 2;\n if (tails[mid] <= arr[j] && tails[mid + 1] > arr[j]) {\n tails[mid + 1] = arr[j];\n break;\n } else if (tails[mid + 1] <= arr[j]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n if (low > high) {\n tails[0] = arr[j];\n }\n }\n }\n ans -= size;\n }\n return ans;\n }\n}\n```\n\n**If you have any question, feel free to ask. If you like the solution or the explanation, Please UPVOTE!**
105,267
Capitalize the Title
capitalize-the-title
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title.
String
Easy
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
1,922
23
**Python :**\n\n```\ndef capitalizeTitle(self, title: str) -> str:\n\treturn " ".join([word.lower() if len(word) < 3 else word.title() for word in title.split()])\n```\n\n**Like it ? please upvote !**
105,329
Capitalize the Title
capitalize-the-title
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title.
String
Easy
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
1,785
11
**Q & A**\nQ1: Where can I find the material about togglling letter cases in Java?\nA1: You can find [here](). - credit to **@Aaditya_Burujwale**\n\n**End of Q & A**\n\n----\n\n```java\n public String capitalizeTitle(String title) {\n List<String> ans = new ArrayList<>();\n for (String w : title.split(" ")) {\n if (w.length() < 3) {\n ans.add(w.toLowerCase());\n }else {\n char[] ca = w.toLowerCase().toCharArray();\n ca[0] ^= 32; // toggle letter case.\n ans.add(String.valueOf(ca));\n }\n }\n return String.join(" ", ans);\n }\n```\n```python\n def capitalizeTitle(self, title: str) -> str:\n ans = []\n for s in title.split():\n if len(s) < 3:\n ans.append(s.lower())\n else:\n ans.append(s.capitalize())\n return \' \'.join(ans) \n```\n**Analysis:**\n\nTime & space: `O(n)`, where `n = title.length()`.
105,338
Capitalize the Title
capitalize-the-title
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title.
String
Easy
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
998
6
```\ndef capitalizeTitle(self, title: str) -> str:\n output = list()\n word_arr = title.split()\n for word in word_arr:\n output.append(word.title()) if len(word) > 2 else output.append(word.lower())\n return " ".join(output)\n```
105,339
Capitalize the Title
capitalize-the-title
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title.
String
Easy
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
675
6
**C++:**\n```\nclass Solution {\npublic:\n string str_to_lower(string word, bool cap) {\n for (auto& letter : word) letter = tolower(letter);\n if (cap) word[0] = toupper(word[0]);\n return word;\n }\n \n string capitalizeTitle(string title) {\n stringstream ss(title);\n string word, res;\n \n while (ss >> word)\n res += str_to_lower(word, word.size() > 2) + " ";\n \n res.pop_back();\n return res;\n }\n};\n```\n****\n**Python One Liner**\n```\nclass Solution:\n def capitalizeTitle(self, title: str) -> str:\n return " ".join([word.capitalize() if len(word) > 2 else word.lower() for word in title.split()])\n```\n**Like it? please upvote!**
105,341
Capitalize the Title
capitalize-the-title
You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that: Return the capitalized title.
String
Easy
Firstly, try to find all the words present in the string. On the basis of each word's lengths, simulate the process explained in Problem.
872
5
```\nclass Solution:\n def capitalizeTitle(self, title: str) -> str:\n title = title.split()\n word = ""\n for i in range(len(title)):\n if len(title[i]) < 3:\n word = word + title[i].lower() + " "\n else:\n word = word + title[i].capitalize() + " "\n return word[:-1]\n```\nOr \n```\nclass Solution:\n def capitalizeTitle(self, title: str) -> str:\n title = title.split()\n word = []\n for i in range(len(title)):\n if len(title[i]) < 3:\n word.append(title[i].lower())\n else:\n word.append(title[i].capitalize())\n return " ".join(word)\n```
105,357
Maximum Twin Sum of a Linked List
maximum-twin-sum-of-a-linked-list
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list.
Linked List,Two Pointers,Stack
Medium
How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums.
17,936
76
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Maximum Twin Sum of a Linked List` by `Aryan Mittal`\n![lc.png]()\n\n\n# Approach & Intution\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n\n\n\n# Code\n```C++ []\nclass Solution {\n public:\n int pairSum(ListNode* head) {\n ListNode* slow = head;\n ListNode* fast = head;\n int maxVal = 0;\n\n while(fast && fast -> next)\n {\n slow = slow -> next;\n fast = fast -> next -> next;\n }\n\n ListNode *nextNode, *prev = NULL;\n while (slow) {\n nextNode = slow->next;\n slow->next = prev;\n prev = slow;\n slow = nextNode;\n }\n\n while(prev)\n {\n maxVal = max(maxVal, head -> val + prev -> val);\n prev = prev -> next;\n head = head -> next;\n }\n\n return maxVal;\n }\n};\n```\n```Java []\nclass Solution {\n public int pairSum(ListNode head) {\n ListNode slow = head;\n ListNode fast = head;\n int maxVal = 0;\n\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n\n ListNode nextNode, prev = null;\n while (slow != null) {\n nextNode = slow.next;\n slow.next = prev;\n prev = slow;\n slow = nextNode;\n }\n\n while (prev != null) {\n maxVal = Math.max(maxVal, head.val + prev.val);\n prev = prev.next;\n head = head.next;\n }\n\n return maxVal;\n }\n}\n```\n```Python []\nclass Solution:\n def pairSum(self, head):\n slow = head\n fast = head\n maxVal = 0\n\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n\n nextNode, prev = None, None\n while slow:\n nextNode = slow.next\n slow.next = prev\n prev = slow\n slow = nextNode\n\n while prev:\n maxVal = max(maxVal, head.val + prev.val)\n prev = prev.next\n head = head.next\n\n return maxVal\n```
105,400
Maximum Twin Sum of a Linked List
maximum-twin-sum-of-a-linked-list
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list.
Linked List,Two Pointers,Stack
Medium
How can "reversing" a part of the linked list help find the answer? We know that the nodes of the first half are twins of nodes in the second half, so try dividing the linked list in half and reverse the second half. How can two pointers be used to find every twin sum optimally? Use two different pointers pointing to the first nodes of the two halves of the linked list. The second pointer will point to the first node of the reversed half, which is the (n-1-i)th node in the original linked list. By moving both pointers forward at the same time, we find all twin sums.
19,666
212
**C++ :**\n\n```\nint pairSum(ListNode* head) {\n\tListNode* slow = head;\n\tListNode* fast = head;\n\tint maxVal = 0;\n\n\t// Get middle of linked list\n\twhile(fast && fast -> next)\n\t{\n\t\tfast = fast -> next -> next;\n\t\tslow = slow -> next;\n\t}\n\n\t// Reverse second part of linked list\n\tListNode *nextNode, *prev = NULL;\n\twhile (slow) {\n\t\tnextNode = slow->next;\n\t\tslow->next = prev;\n\t\tprev = slow;\n\t\tslow = nextNode;\n\t}\n\n\t// Get max sum of pairs\n\twhile(prev)\n\t{\n\t\tmaxVal = max(maxVal, head -> val + prev -> val);\n\t\tprev = prev -> next;\n\t\thead = head -> next;\n\t}\n\n\treturn maxVal;\n}\n```\n\n\n**Python :**\n\n```\ndef pairSum(self, head: Optional[ListNode]) -> int:\n\tslow, fast = head, head\n\tmaxVal = 0\n\n\t# Get middle of linked list\n\twhile fast and fast.next:\n\t\tfast = fast.next.next\n\t\tslow = slow.next\n\n\t# Reverse second part of linked list\n\tcurr, prev = slow, None\n\n\twhile curr: \n\t\tcurr.next, prev, curr = prev, curr, curr.next \n\n\t# Get max sum of pairs\n\twhile prev:\n\t\tmaxVal = max(maxVal, head.val + prev.val)\n\t\tprev = prev.next\n\t\thead = head.next\n\n\treturn maxVal\n```\n\n**Like it ? please upvote !**
105,403
Longest Palindrome by Concatenating Two Letter Words
longest-palindrome-by-concatenating-two-letter-words
You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once. Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0. A palindrome is a string that reads the same forward and backward.
Array,Hash Table,String,Greedy,Counting
Medium
A palindrome must be mirrored over the center. Suppose we have a palindrome. If we prepend the word "ab" on the left, what must we append on the right to keep it a palindrome? We must append "ba" on the right. The number of times we can do this is the minimum of (occurrences of "ab") and (occurrences of "ba"). For words that are already palindromes, e.g. "aa", we can prepend and append these in pairs as described in the previous hint. We can also use exactly one in the middle to form an even longer palindrome.
1,475
5
```\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n dc=defaultdict(lambda:0)\n for a in words:\n dc[a]+=1\n count=0\n palindromswords=0\n inmiddle=0\n wds=set(words)\n for a in wds:\n if(a==a[::-1]):\n if(dc[a]%2==1):\n inmiddle=1\n palindromswords+=(dc[a]//2)*2\n elif(dc[a[::-1]]>0):\n count+=(2*(min(dc[a],dc[a[::-1]])))\n dc[a]=0\n return (palindromswords+count+inmiddle)*2\n ``\n```
105,411
A Number After a Double Reversal
a-number-after-a-double-reversal
Reversing an integer means to reverse all its digits. Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.
Math
Easy
Other than the number 0 itself, any number that ends with 0 would lose some digits permanently when reversed.
2,359
31
**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n\n* All you have to do is check the Trailing zeros\n\t* input num as a valid number should not have leading zeros\n\t* the trailing zeros will become leading zeros after the **First Reversal**\n\t\t* So after **Double Reversal**, they will be removed.\n\n**Python**\n```\nclass Solution(object):\n def isSameAfterReversals(self, num):\n\t\t# All you have to do is check the Trailing zeros\n return num == 0 or num % 10 # num % 10 means num % 10 != 0\n```\n**C++**\n```\nclass Solution {\npublic:\n bool isSameAfterReversals(int num) {\n return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros\n }\n};\n```\n**Java**\n```\nclass Solution {\n public boolean isSameAfterReversals(int num) {\n return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros\n }\n}\n```
105,504
Execution of All Suffix Instructions Staying in a Grid
execution-of-all-suffix-instructions-staying-in-a-grid
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met: Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.
String,Simulation
Medium
The constraints are not very large. Can we simulate the execution by starting from each index of s? Before any of the stopping conditions is met, stop the simulation for that index and set the answer for that index.
4,614
25
\n# **Solution 1: Brute force**\nHelper fucntion `test(i)` to check the the number of instructions the robot can execute,\nif the robot begins executing from the `i`th instruction in s.\n\nTime `O(m^2)`\nSpace `O(1)`\n\n**Python**\n```py\n def executeInstructions(self, n, start, s):\n na = len(s)\n def test(i):\n res = 0\n x,y = start\n for j in xrange(i, na):\n o = s[j]\n if o == \'L\': y -= 1\n if o == \'R\': y += 1\n if o == \'U\': x -= 1\n if o == \'D\': x += 1\n if not (0 <= x < n and 0 <= y < n):\n return j - i\n return na - i\n return map(test, range(na))\n```\n<br>\n\n# **Solution 2: Multiplication**\nShared by @OOTTF:\nFor every start point `i`,\nrecord the position after 2^k steps,\nand extrene position in the 4 directions.\n\nTime `O(mlogm)`\nSpace `O(mlogm)`\n<br>\n\n# **Solution 3: O(m) solution**\nStarting from the first order,\nfind the difference on x-axis and y-axis\n\n`count` reocrd the postion with start index.\nFor example,\n`count[x0, None].add(0)`, means that at index `0`, we are at x-axis `x0`.\n`count[None, y0].add(0)`, means that at index `0`, we are at x-axis `y0`.\n\nThe tricky and the difficult point for this solution is that,\nstarting at `(x0,y0)` and excute from `s[i]`,\nis same as\nstarting at `(x0 - x, y0 - y)` and excute from `s[0]`.\nThis process has a sense of backtracking.\n\nNow at step `s[i]` we have delta `(x, y)`,\nif `x > 0`, we have moved down, and making points starting as x-axis `n-x` off the grid.\nif `y > 0`, we have moved down, and making points starting as x-axis `n-y` off the grid.\nif `x < 0`, we have moved down, and making points starting as x-axis `-x-1` off the grid.\nif `y < 0`, we have moved down, and making points starting as x-axis `-y-1` off the grid.\n\nAt the end of each step, we clean all starting point already off the grid.\nThe ensures the whole solution is `O(m)`, where we add only once and clean only once.\n\nTime `O(m)`\nSpace `O(m)`\n<br>\n\n\n**Python**\n```py\n def executeInstructions(self, n, start, s):\n ns = len(s)\n (x0, y0), (x, y) = start, (0, 0)\n res = range(ns, 0, -1)\n count = collections.defaultdict(set)\n count[x0, None].add(0)\n count[None, y0].add(0)\n for i in xrange(ns):\n if s[i] == \'L\': y -= 1\n if s[i] == \'R\': y += 1\n if s[i] == \'U\': x -= 1\n if s[i] == \'D\': x += 1\n count[x0 - x, None].add(i + 1)\n count[None, y0 - y].add(i + 1)\n for key in [(n-x, None), (None, n-y), (-x-1, None), (None, -y-1)]:\n for j in count[key]:\n if res[j] > i - j:\n res[j] = i - j\n count[key] = set()\n return res\n```\n
105,522
Intervals Between Identical Elements
intervals-between-identical-elements
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.
Array,Hash Table,Prefix Sum
Medium
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums. For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values.
3,672
45
Dictionary/Hashmap is used to store all the occurences of a given number as {num: [indexes of occurences in arr]}\n\n***Explanation for the use of prefix array***:\nPrefix array `pre` is first used to fetch the sum of numbers uptil index i (for a given number arr[i]). We know that the numbers in the list are sorted thus these numbers will be smaller than i.\n\n`v * (i + 1) - pre[i + 1]` finds the `\u2211 (l[i] - (numbers smaller than or equal to l[i] in list))`\nLet\'s say for given list 1, 3, 5, 7, 9:\nFor example, we choose `i` = 3 or the number `l[i]` = 7.\nTo find abs difference for numbers smaller than equal to 7:\n7 - 1 + 7 - 3 + 7 - 5 + 7 - 7\nor\n7 * 4 - (1 + 3 + 5 + 7)\nor\n7 * `(i + 1)` - `pre[i + 1]`\n\nSimilarly\n`((pre[len(l)] - pre[i]) - v * (len(l) - (i)))` calculates abs difference between` l[i]` and numbers greater than `l[i]`\n\n**Python3**:\n```\ndef getDistances(self, arr: List[int]) -> List[int]:\n m, res = {}, [0] * len(arr)\n for i, v in enumerate(arr):\n if v not in m: m[v] = list()\n m[v].append(i)\n \n for x in m:\n l = m[x]\n pre = [0] * (len(l) + 1)\n for i in range(len(l)):\n pre[i + 1] = pre[i] + l[i]\n for i, v in enumerate(l):\n res[v] = (v * (i + 1) - pre[i + 1]) + ((pre[len(l)] - pre[i]) - v * (len(l) - (i)))\n return res\n```\n\n<iframe src="" frameBorder="0" width="800" height="410"></iframe>\n\n
105,565
Intervals Between Identical Elements
intervals-between-identical-elements
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.
Array,Hash Table,Prefix Sum
Medium
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums. For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values.
1,658
10
Please check out this [commit]() for solutions of weely 273. \n\n```\nclass Solution:\n def getDistances(self, arr: List[int]) -> List[int]:\n loc = defaultdict(list)\n for i, x in enumerate(arr): loc[x].append(i)\n \n for k, idx in loc.items(): \n prefix = list(accumulate(idx, initial=0))\n vals = []\n for i, x in enumerate(idx): \n vals.append(prefix[-1] - prefix[i] - prefix[i+1] - (len(idx)-2*i-1)*x)\n loc[k] = deque(vals)\n \n return [loc[x].popleft() for x in arr]\n```\n\n**Explanation on the formula**\nGiven an array, say `nums = [3,2,1,5,4]`. Calculate its prefix sum `[0,3,5,6,11,15]` (note the leading zero). Now let\'s loop through `nums` by index. At `i`, there are \n1) `i` numbers whose indices are below `i` with sum `prefix[i]`;\n2) `len(nums)-i-1` numbers whose indices are above `i` with sum `prefix[-1] - prefix[i+1]`. \n\nSo the desired value in this case is `i*x - prefix[i] + prefix[-1] - prefix[i+1] - (len(nums)-i-1)*x`. Rearranging the terms one would arrive at the formula used in this implementation.
105,574
Intervals Between Identical Elements
intervals-between-identical-elements
You are given a 0-indexed array of n integers arr. The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|. Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i]. Note: |x| is the absolute value of x.
Array,Hash Table,Prefix Sum
Medium
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array. One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array. Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums. For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values.
631
6
**Hint**:\n\nWhen it comes to **accumulation on history data in the same direction**, think of **prefix sum** / **postfix sum** technique,\nlike what we did in [#2100 Find good days to rob]() as well as [#303 Range sum query - immutable]()\n\nWe can define Presum and Postsum as following:\n\n**Presum**( i ) = 0 if we have no identical elements **on the lefthand side** of i.\n**Presum**( i ) = Presum( j ) + ( **i - j** ) * **count of equal elements so far**, where **j < i**, and j is the nearest index to i\n\nSimilarly,\n\n**Postsum**( i ) = 0 if we have no identical elements **on the righthand side** of i.\n**Postsum**( i ) = Postsum( k ) + ( **k - i** ) * **count of equal elements so far**, where **k > i**, and k is the nearest index to i\n\nFinally, we have summation of distance to all identical elements for i \n= summation of distance to all identical elements for i on the **lefthand side** + summation of distance to all identical elements for i on the **righthand side**\n= Presum( i ) + Postsum( i )\n\n\n\n\n---\n\n```\n\n# helper data structure Scout\nclass Scout:\n \n def __init__(self, prev_idx=-1, count_of_equal=0):\n \n # record of index of last identical element\n self.prev_idx = prev_idx\n \n # count of identical elements so far\n self.count_of_equal = count_of_equal\n \n def __iter__(self):\n\t\t# ouput previous index, and count of equal in order\n return iter( (self.prev_idx, self.count_of_equal) )\n \n \n \nclass Solution:\n def getDistances(self, arr: List[int]) -> List[int]:\n \n size = len(arr)\n \n pre_scout = defaultdict( Scout )\n pre_dist_sum = [0 for _ in range(size)]\n \n post_scout = defaultdict( Scout )\n post_dist_sum = [0 for _ in range(size)]\n \n \n ## Step_1:\n # update for pre_dist_sum table, direction is from left to right\n for i, element in enumerate(arr):\n \n prev_equal_idx, prev_count_of_equal = pre_scout[element]\n \n # update pre_dist_sum table if we have identical elements before index i\n if prev_count_of_equal:\n pre_dist_sum[i] += pre_dist_sum[ prev_equal_idx ] + (i - prev_equal_idx) * prev_count_of_equal\n \n # update Scout information for current element\n pre_scout[element] = i, prev_count_of_equal+1\n \n # --------------------------------------------------------------\n \n ## Step_2:\n # update for pos_dist_sum table, direction is from right to left\n for i, element in reversed( [*enumerate(arr)] ):\n \n post_equal_idx, post_count_of_equal = post_scout[element]\n\n # update post_dist_sum table if we have identical elements after index i\n if post_count_of_equal:\n post_dist_sum[i] += post_dist_sum[ post_equal_idx ] + (post_equal_idx - i) * post_count_of_equal\n \n # update Scout information for current element\n post_scout[element] = i, post_count_of_equal+1\n \n \n ## Step_3:\n # Generate final output by definition\n return [ pre_dist_sum[i] + post_dist_sum[i] for i in range(size) ]\n \n \n```\n\n---\n\nRelated leetcode challenge:\n\n [Leetcode #2100 Find good days to rob]() \n \n [Leetcode #303 Range sum query - immutable]()
105,589
Recover the Original Array
recover-the-original-array
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr.
Array,Hash Table,Sorting,Enumeration
Hard
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest value of nums (as lower[i]) against every other value in nums (as the corresponding higher[i]). For every computed k, greedily pair up the values in nums. This can be done sorting nums, then using a map to store previous values and searching that map for a corresponding lower[i] for the current nums[j] (as higher[i]).
645
16
**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n\n`The time complexity is O(N^2)`\n\n```\nclass Solution(object):\n def recoverArray(self, nums):\n nums.sort()\n mid = len(nums) // 2\n # All possible k are (nums[j] - nums[0]) // 2, otherwise there is no num that satisfies nums[0] + k = num - k.\n # For nums is sorted, so that any 2 elements (x, y) in nums[1:j] cannot satisfy x + k = y - k.\n # In other words, for any x in nums[1:j], it needs to find y from nums[j + 1:] to satisfy x + k = y - k, but\n # unfortunately if j > mid, then len(nums[j + 1:]) < mid <= len(nums[1:j]), nums[j + 1:] are not enough.\n # The conclusion is j <= mid.\n\t\t# If you think it\u2019s not easy to understand why mid is enough, len(nums) can also work well\n\t\t# for j in range(1, len(nums)): \n for j in range(1, mid + 1): # O(N)\n if nums[j] - nums[0] > 0 and (nums[j] - nums[0]) % 2 == 0: # Note the problem described k is positive.\n k, counter, ans = (nums[j] - nums[0]) // 2, collections.Counter(nums), []\n # For each number in lower, we try to find the corresponding number from higher list.\n # Because nums is sorted, current n is always the current lowest num which can only come from lower\n # list, so we search the corresponding number of n which equals to n + 2 * k in the left\n # if it can not be found, change another k and continue to try.\n for n in nums: # check if n + 2 * k available as corresponding number in higher list of n\n if counter[n] == 0: # removed by previous num as its corresponding number in higher list\n continue\n if counter[n + 2 * k] == 0: # not found corresponding number in higher list\n break\n ans.append(n + k)\n counter[n] -= 1 # remove n\n counter[n + 2 * k] -= 1 # remove the corresponding number in higher list\n if len(ans) == mid:\n return ans\n```
105,614
Recover the Original Array
recover-the-original-array
Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner: Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array. Given an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array. Note: The test cases are generated such that there exists at least one valid array arr.
Array,Hash Table,Sorting,Enumeration
Hard
If we fix the value of k, how can we check if an original array exists for the fixed k? The smallest value of nums is obtained by subtracting k from the smallest value of the original array. How can we use this to reduce the search space for finding a valid k? You can compute every possible k by using the smallest value of nums (as lower[i]) against every other value in nums (as the corresponding higher[i]). For every computed k, greedily pair up the values in nums. This can be done sorting nums, then using a map to store previous values and searching that map for a corresponding lower[i] for the current nums[j] (as higher[i]).
725
12
Please check out this [commit]() for solutions of weely 273. \n\n```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n cnt = Counter(nums)\n for i in range(1, len(nums)): \n diff = nums[i] - nums[0]\n if diff and diff&1 == 0: \n ans = []\n freq = cnt.copy()\n for k, v in freq.items(): \n if v: \n if freq[k+diff] < v: break \n ans.extend([k+diff//2]*v)\n freq[k+diff] -= v\n else: return ans \n```
105,619
Check if All A's Appears Before All B's
check-if-all-as-appears-before-all-bs
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
String
Easy
You can check the opposite: check if there is a β€˜b’ before an β€˜a’. Then, negate and return that answer. s should not have any occurrences of β€œba” as a substring.
3,733
42
**Method 1**\n\n```java\n public boolean checkString(String s) {\n for (int i = 1; i < s.length(); ++i) {\n if (s.charAt(i - 1) == \'b\' && s.charAt(i) == \'a\') {\n return false;\n }\n }\n return true;\n }\n```\n```python\n def checkString(self, s: str) -> bool:\n for i, c in enumerate(s):\n if i > 0 and s[i - 1] == \'b\' and c == \'a\':\n return False\n return True\n```\n\n----\n\n**Method 2:**\n\n```java\n public boolean checkString(String s) {\n return !s.contains("ba");\n }\n```\n```python\n def checkString(self, s: str) -> bool:\n return \'ba\' not in s\n```\n**Analysis**\n\nTime: `O(n)`, space: `O(1)`, where `n = s.length()`.
105,688
Check if All A's Appears Before All B's
check-if-all-as-appears-before-all-bs
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
String
Easy
You can check the opposite: check if there is a β€˜b’ before an β€˜a’. Then, negate and return that answer. s should not have any occurrences of β€œba” as a substring.
1,234
21
```\ndef checkString(self, s: str) -> bool:\n return (\'\'.join(sorted(list(s))))==s\n```\n\n```\ndef checkString(self, s: str) -> bool:\n return "ba" not in s\n```
105,694
Check if All A's Appears Before All B's
check-if-all-as-appears-before-all-bs
Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
String
Easy
You can check the opposite: check if there is a β€˜b’ before an β€˜a’. Then, negate and return that answer. s should not have any occurrences of β€œba” as a substring.
674
10
**Python :**\n\n```\ndef checkString(self, s: str) -> bool:\n\tisA = True\n\tfor char in s:\n\t\tif char == \'a\' and not isA:\n\t\t\treturn False\n\t\tif char == \'b\':\n\t\t\tisA = False\n\n\treturn True\n```\n\n**One line :**\n\n```\ndef checkString(self, s: str) -> bool:\n\treturn "ba" not in s\n```\n\n**Like it ? please upvote !**
105,706