title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
[Python 3] - Easy to understand COMMENTED solution.
maximum-number-of-balls-in-a-box
0
1
Approach:\n\nIterate through the ```lowLimit``` and ```highLimit```. While doing so, compute the sum of all the elements of the current number and update it\'s count in the frequency table. \nBasically, ```boxes[sum(element)] += 1```, (boxes is my frequency table). Finally, return ```max(boxes)```.\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n boxes = [0] * 100\n \n for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number "i", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n boxes[sum([int(j) for j in str(i)])] += 1\n \n return max(boxes)\n```
7
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
simple python solution
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d=dict()\n for i in range(lowLimit,highLimit+1):\n s=str(i)\n c=0\n for i in s:\n c+=int(i)\n if(c in d):\n d[c]+=1\n else:\n d[c]=1\n return max(d.values())\n\n\n```
2
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
simple python solution
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d=dict()\n for i in range(lowLimit,highLimit+1):\n s=str(i)\n c=0\n for i in s:\n c+=int(i)\n if(c in d):\n d[c]+=1\n else:\n d[c]=1\n return max(d.values())\n\n\n```
2
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python simple and short solution
maximum-number-of-balls-in-a-box
0
1
**Python :**\n\n```\ndef countBalls(self, lowLimit: int, highLimit: int) -> int:\n\tballBox = collections.defaultdict(int)\n\n\tfor i in range(lowLimit, highLimit + 1):\n\t\tballSum = sum([int(i) for i in str(i)])\n\t\tballBox[ballSum] += 1\n\n\treturn max(ballBox.values())\n```\n\n**Like it ? please upvote !**
6
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Python simple and short solution
maximum-number-of-balls-in-a-box
0
1
**Python :**\n\n```\ndef countBalls(self, lowLimit: int, highLimit: int) -> int:\n\tballBox = collections.defaultdict(int)\n\n\tfor i in range(lowLimit, highLimit + 1):\n\t\tballSum = sum([int(i) for i in str(i)])\n\t\tballBox[ballSum] += 1\n\n\treturn max(ballBox.values())\n```\n\n**Like it ? please upvote !**
6
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python3 frequency hash table
maximum-number-of-balls-in-a-box
0
1
# Intuition\n\nAlthough the problem description was fairly confusing, in essence, you need find the most frequent digit sum. For other problems like this, I\'ve used a hash table to store frequencies.\n\n# Approach\n\nFor each number in the range of the lower limit and the higher limit +1 (to include the higher limit), convert the number to a string, get the sum of the two digits, then add that sum in the frequency hash table. Since we don\'t need to know the identity of the box, just the most frequent digit sum, we can simply return `max(digit_sums.values())`.\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n digit_sums = {}\n\n for num in range(lowLimit, highLimit + 1):\n ball_sum = 0\n for digit in str(num):\n ball_sum += int(digit)\n if ball_sum not in digit_sums:\n digit_sums[ball_sum] = 1\n else:\n digit_sums[ball_sum] += 1\n\n return max(digit_sums.values())\n \n\n```
0
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Python3 frequency hash table
maximum-number-of-balls-in-a-box
0
1
# Intuition\n\nAlthough the problem description was fairly confusing, in essence, you need find the most frequent digit sum. For other problems like this, I\'ve used a hash table to store frequencies.\n\n# Approach\n\nFor each number in the range of the lower limit and the higher limit +1 (to include the higher limit), convert the number to a string, get the sum of the two digits, then add that sum in the frequency hash table. Since we don\'t need to know the identity of the box, just the most frequent digit sum, we can simply return `max(digit_sums.values())`.\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n digit_sums = {}\n\n for num in range(lowLimit, highLimit + 1):\n ball_sum = 0\n for digit in str(num):\n ball_sum += int(digit)\n if ball_sum not in digit_sums:\n digit_sums[ball_sum] = 1\n else:\n digit_sums[ball_sum] += 1\n\n return max(digit_sums.values())\n \n\n```
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python 83ms || Beginner || Dictionary
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d=dict()\n for i in range(lowLimit,highLimit+1):\n k=i\n s=0\n while k>0:\n rem=k%10\n s=s+rem\n k=k//10\n if s not in d:\n d[s]=1\n else:\n d[s]=d[s]+1\n l=sorted(d.items(),key=lambda x:x[1],reverse=True)\n return l[0][1]\n\n```
0
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Python 83ms || Beginner || Dictionary
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d=dict()\n for i in range(lowLimit,highLimit+1):\n k=i\n s=0\n while k>0:\n rem=k%10\n s=s+rem\n k=k//10\n if s not in d:\n d[s]=1\n else:\n d[s]=d[s]+1\n l=sorted(d.items(),key=lambda x:x[1],reverse=True)\n return l[0][1]\n\n```
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
python simple solution, dictionary, for and while loop
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d = {}\n for ballnum in range(lowLimit, highLimit+1) :\n sum = 0\n while ballnum >= 10 : \n r = ballnum % 10 # r --> remainder\n ballnum = ballnum // 10\n sum += r\n sum += ballnum\n if sum in d :\n d[sum] += 1\n else : \n d[sum] = 1\n return max(d.values())\n \n```
0
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
python simple solution, dictionary, for and while loop
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n d = {}\n for ballnum in range(lowLimit, highLimit+1) :\n sum = 0\n while ballnum >= 10 : \n r = ballnum % 10 # r --> remainder\n ballnum = ballnum // 10\n sum += r\n sum += ballnum\n if sum in d :\n d[sum] += 1\n else : \n d[sum] = 1\n return max(d.values())\n \n```
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
【Video】Give me 5 minutes - O(n) time and space - How we think about a solution
restore-the-array-from-adjacent-pairs
1
1
# Intuition\nTry to find numbers that have only one adjacent number.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/P14SbuALeJ8\n\n\u25A0 Timeline of the video\n\n`0:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,021\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers yesterday. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nLook at this.\n```\n[1,2,3,4]\n```\n\nSimply, edge of numbers(= `1`,`4`) have one adjacent number and inside of the array(= `2`,`3`) have two adjacent numbers.\n\nSo, the numbers that have one adjacent number should be start number or end number. But we don\'t have care about start number or end number because the description says "If there are multiple solutions, return any of them". That means we can return `[1,2,3,4]` or `[4,3,2,1]`.\n\n---\n\n\u2B50\uFE0F Points\n\nTry to find numbers that have only one adjacent number. The numbers should be start number or end number. We can start from one of them.\n\n---\n\n- How do you know adjacent number of each number?\n\nThe next question is how you know adjacent number of each number.\n\nMy answer is simply to create adjacent candidate list.\n\n```\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\n```\nFrom the input, we can create this. We use `HashMap`. In solution code `graph`.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n\n2: [1, 3]\n\u2192 1 from [2:1], 3 from [3,2]\n\n1: [2]\n\u2192 2 from [2,1]\n\n3: [4, 2]\n\u2192 4 from [3,4], 2 from [3,2]\n\n4: [3]\n\u2192 3 from [3,4]\n\nvalues are adjacent candidate numbers of the key number\n```\n\nWhat are the numbers that have only one adjacent number? The answer is `1` or `4`. We can take one of them. I start with `1`.\n\n```\nres = [1, 2]\n```\nWe know that `2` is adjacent number of `1`, so add `2` to `res` after `1`.\n\nThen we check candidates of the last number which is `2` in this case.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n```\nThe candidates are `1` or `3`. It\'s obvious that `3` is the next adjacent number right?\n\nIn solution code, we can compare like if candidate number is not `1`, that is the next number because `1` is left adjacent number of `2`. Now we are tyring to find right adjacent number of `2`. That\'s why before we compare the numbers, we take the last two numbers of `res`, so that we can compare them easily.\n\nLet\'s see how it works!\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2]\n\nlast = 2\nprev = 1\n\nCheck last values\ncandidates = [1, 3] (from 2: [1, 3])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 1)\nfalse \u2192 the next number is candidates[1](= 3)\n\nIn this case, it\'s false. so add 3 to res\n\nIn the end, res = [1, 2, 3]\n```\nLet\'s go next. Take the last two numbers from `res`.\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2, 3]\n\nlast = 3\nprev = 2\n\nCheck last values\ncandidates = [4, 2] (from 3: [4, 2])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 4)\nfalse \u2192 the next number is candidates[1](= 2)\n\nIn this case, it\'s true. so add 4 to res\n\nres = [1, 2, 3, 4]\n```\nThen we stop.\n\n```\nOutput: [1, 2, 3, 4]\n```\n\nEasy\uFF01\uD83D\uDE06\nLet\'s see a real algorithm!\n\nI added comments in Python code. I hope it helps you understand solution code.\n\n---\n\n\n\n### Algorithm Overview:\n\nThe algorithm aims to restore an array given a list of adjacent pairs. It uses a graph representation to model the adjacent relationships and then iteratively builds the array.\n\n### Detailed Explanation:\n\n1. **Create a Graph:**\n - Initialize an empty graph using a `defaultdict` to represent adjacent pairs. Iterate through the given pairs, and for each pair `[u, v]`, add `v` to the list of neighbors of `u` and vice versa.\n\n ```python\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n ```\n\n2. **Initialize Result List:**\n - Initialize an empty list `res` to store the elements of the restored array.\n\n ```python\n res = []\n ```\n\n3. **Find Starting Node:**\n - Iterate through the nodes in the graph and find the starting node with only one neighbor. Set `res` to contain this starting node and its neighbor.\n\n ```python\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n ```\n\n4. **Build the Array:**\n - Use a `while` loop to continue building the array until its length matches the number of pairs plus one.\n\n ```python\n while len(res) < len(pairs) + 1:\n last, prev = res[-1], res[-2] # Get the last two elements in the result array\n candidates = graph[last] # Find the candidates for the next element\n next_element = candidates[0] if candidates[0] != prev else candidates[1] # Choose the candidate that is not the previous element\n res.append(next_element) # Append the next element to the result array\n ```\n\n5. **Return Result:**\n - Return the final restored array.\n\n ```python\n return res\n ```\n\nIn summary, the algorithm builds the array by selecting adjacent elements based on the graph representation until the array is fully restored. The starting point is identified by finding a node with only one neighbor. The process continues until the array\'s length matches the number of pairs.\n\n# Complexity\n- Time complexity: $$O(n)$$\n`n` is the number of pairs.\n\n- Space complexity: $$O(n)$$\n`n` is the number of pairs.\n\n```python []\nclass Solution:\n def restoreArray(self, pairs: List[List[int]]) -> List[int]:\n # Create a graph to represent adjacent pairs\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n\n # Initialize the result list\n res = []\n\n # Find the starting node with only one neighbor\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n\n # Continue building the array until its length matches the number of pairs\n while len(res) < len(pairs) + 1:\n # Get the last two elements in the result array\n last, prev = res[-1], res[-2]\n\n # Find the candidates for the next element\n candidates = graph[last]\n\n # Choose the candidate that is not the previous element\n next_element = candidates[0] if candidates[0] != prev else candidates[1]\n\n # Append the next element to the result array\n res.append(next_element)\n\n return res\n```\n```javascript []\n/**\n * @param {number[][]} adjacentPairs\n * @return {number[]}\n */\nvar restoreArray = function(adjacentPairs) {\n const graph = new Map();\n\n for (const [u, v] of adjacentPairs) {\n if (!graph.has(u)) graph.set(u, []);\n if (!graph.has(v)) graph.set(v, []);\n graph.get(u).push(v);\n graph.get(v).push(u);\n }\n\n let result = [];\n\n for (const [node, neighbors] of graph.entries()) {\n if (neighbors.length === 1) {\n result = [node, neighbors[0]];\n break;\n }\n }\n\n while (result.length < adjacentPairs.length + 1) {\n const [last, prev] = [result[result.length - 1], result[result.length - 2]];\n const candidates = graph.get(last);\n const nextElement = candidates[0] !== prev ? candidates[0] : candidates[1];\n result.push(nextElement);\n }\n\n return result; \n};\n```\n```java []\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n\n for (int[] pair : adjacentPairs) {\n graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);\n graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);\n }\n\n List<Integer> result = new ArrayList<>();\n\n for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {\n if (entry.getValue().size() == 1) {\n result.add(entry.getKey());\n result.add(entry.getValue().get(0));\n break;\n }\n }\n\n while (result.size() < adjacentPairs.length + 1) {\n int last = result.get(result.size() - 1);\n int prev = result.get(result.size() - 2);\n List<Integer> candidates = graph.get(last);\n int nextElement = candidates.get(0) != prev ? candidates.get(0) : candidates.get(1);\n result.add(nextElement);\n }\n\n return result.stream().mapToInt(Integer::intValue).toArray(); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n unordered_map<int, vector<int>> graph;\n\n for (const auto& pair : adjacentPairs) {\n graph[pair[0]].push_back(pair[1]);\n graph[pair[1]].push_back(pair[0]);\n }\n\n vector<int> result;\n\n for (const auto& entry : graph) {\n if (entry.second.size() == 1) {\n result = {entry.first, entry.second[0]};\n break;\n }\n }\n\n while (result.size() < adjacentPairs.size() + 1) {\n int last = result[result.size() - 1];\n int prev = result[result.size() - 2];\n const vector<int>& candidates = graph[last];\n int nextElement = (candidates[0] != prev) ? candidates[0] : candidates[1];\n result.push_back(nextElement);\n }\n\n return result; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/design-graph-with-shortest-path-calculator/solutions/4276911/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/llptwOvEstY\n\n\u25A0 Timeline of the video\n\n`0:05` Explain constructor and addEdge function\n`1:31` Explain shortestPath\n`3:29` Demonstrate how it works\n`11:47` Coding\n`17:17` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\n\u2B50\uFE0F **Including all posts from yesterday, my post reached the top spot for the first time!**\n\npost\nhttps://leetcode.com/problems/count-number-of-homogenous-substrings/solutions/4266765/video-give-me-5-minutes-on-time-o1-space-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/VcZrmO045Bo\n\n\u25A0 Timeline of the video\n\n`0:04` Let\'s find a solution pattern\n`1:38` A key point to solve Count Number of Homogenous Substrings\n`2:20` Demonstrate how it works with all the same characters\n`4:55` What if we find different characters\n`7:13` Coding\n`8:21` Time Complexity and Space Complexity
95
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
【Video】Give me 5 minutes - O(n) time and space - How we think about a solution
restore-the-array-from-adjacent-pairs
1
1
# Intuition\nTry to find numbers that have only one adjacent number.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/P14SbuALeJ8\n\n\u25A0 Timeline of the video\n\n`0:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,021\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers yesterday. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nLook at this.\n```\n[1,2,3,4]\n```\n\nSimply, edge of numbers(= `1`,`4`) have one adjacent number and inside of the array(= `2`,`3`) have two adjacent numbers.\n\nSo, the numbers that have one adjacent number should be start number or end number. But we don\'t have care about start number or end number because the description says "If there are multiple solutions, return any of them". That means we can return `[1,2,3,4]` or `[4,3,2,1]`.\n\n---\n\n\u2B50\uFE0F Points\n\nTry to find numbers that have only one adjacent number. The numbers should be start number or end number. We can start from one of them.\n\n---\n\n- How do you know adjacent number of each number?\n\nThe next question is how you know adjacent number of each number.\n\nMy answer is simply to create adjacent candidate list.\n\n```\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\n```\nFrom the input, we can create this. We use `HashMap`. In solution code `graph`.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n\n2: [1, 3]\n\u2192 1 from [2:1], 3 from [3,2]\n\n1: [2]\n\u2192 2 from [2,1]\n\n3: [4, 2]\n\u2192 4 from [3,4], 2 from [3,2]\n\n4: [3]\n\u2192 3 from [3,4]\n\nvalues are adjacent candidate numbers of the key number\n```\n\nWhat are the numbers that have only one adjacent number? The answer is `1` or `4`. We can take one of them. I start with `1`.\n\n```\nres = [1, 2]\n```\nWe know that `2` is adjacent number of `1`, so add `2` to `res` after `1`.\n\nThen we check candidates of the last number which is `2` in this case.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n```\nThe candidates are `1` or `3`. It\'s obvious that `3` is the next adjacent number right?\n\nIn solution code, we can compare like if candidate number is not `1`, that is the next number because `1` is left adjacent number of `2`. Now we are tyring to find right adjacent number of `2`. That\'s why before we compare the numbers, we take the last two numbers of `res`, so that we can compare them easily.\n\nLet\'s see how it works!\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2]\n\nlast = 2\nprev = 1\n\nCheck last values\ncandidates = [1, 3] (from 2: [1, 3])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 1)\nfalse \u2192 the next number is candidates[1](= 3)\n\nIn this case, it\'s false. so add 3 to res\n\nIn the end, res = [1, 2, 3]\n```\nLet\'s go next. Take the last two numbers from `res`.\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2, 3]\n\nlast = 3\nprev = 2\n\nCheck last values\ncandidates = [4, 2] (from 3: [4, 2])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 4)\nfalse \u2192 the next number is candidates[1](= 2)\n\nIn this case, it\'s true. so add 4 to res\n\nres = [1, 2, 3, 4]\n```\nThen we stop.\n\n```\nOutput: [1, 2, 3, 4]\n```\n\nEasy\uFF01\uD83D\uDE06\nLet\'s see a real algorithm!\n\nI added comments in Python code. I hope it helps you understand solution code.\n\n---\n\n\n\n### Algorithm Overview:\n\nThe algorithm aims to restore an array given a list of adjacent pairs. It uses a graph representation to model the adjacent relationships and then iteratively builds the array.\n\n### Detailed Explanation:\n\n1. **Create a Graph:**\n - Initialize an empty graph using a `defaultdict` to represent adjacent pairs. Iterate through the given pairs, and for each pair `[u, v]`, add `v` to the list of neighbors of `u` and vice versa.\n\n ```python\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n ```\n\n2. **Initialize Result List:**\n - Initialize an empty list `res` to store the elements of the restored array.\n\n ```python\n res = []\n ```\n\n3. **Find Starting Node:**\n - Iterate through the nodes in the graph and find the starting node with only one neighbor. Set `res` to contain this starting node and its neighbor.\n\n ```python\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n ```\n\n4. **Build the Array:**\n - Use a `while` loop to continue building the array until its length matches the number of pairs plus one.\n\n ```python\n while len(res) < len(pairs) + 1:\n last, prev = res[-1], res[-2] # Get the last two elements in the result array\n candidates = graph[last] # Find the candidates for the next element\n next_element = candidates[0] if candidates[0] != prev else candidates[1] # Choose the candidate that is not the previous element\n res.append(next_element) # Append the next element to the result array\n ```\n\n5. **Return Result:**\n - Return the final restored array.\n\n ```python\n return res\n ```\n\nIn summary, the algorithm builds the array by selecting adjacent elements based on the graph representation until the array is fully restored. The starting point is identified by finding a node with only one neighbor. The process continues until the array\'s length matches the number of pairs.\n\n# Complexity\n- Time complexity: $$O(n)$$\n`n` is the number of pairs.\n\n- Space complexity: $$O(n)$$\n`n` is the number of pairs.\n\n```python []\nclass Solution:\n def restoreArray(self, pairs: List[List[int]]) -> List[int]:\n # Create a graph to represent adjacent pairs\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n\n # Initialize the result list\n res = []\n\n # Find the starting node with only one neighbor\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n\n # Continue building the array until its length matches the number of pairs\n while len(res) < len(pairs) + 1:\n # Get the last two elements in the result array\n last, prev = res[-1], res[-2]\n\n # Find the candidates for the next element\n candidates = graph[last]\n\n # Choose the candidate that is not the previous element\n next_element = candidates[0] if candidates[0] != prev else candidates[1]\n\n # Append the next element to the result array\n res.append(next_element)\n\n return res\n```\n```javascript []\n/**\n * @param {number[][]} adjacentPairs\n * @return {number[]}\n */\nvar restoreArray = function(adjacentPairs) {\n const graph = new Map();\n\n for (const [u, v] of adjacentPairs) {\n if (!graph.has(u)) graph.set(u, []);\n if (!graph.has(v)) graph.set(v, []);\n graph.get(u).push(v);\n graph.get(v).push(u);\n }\n\n let result = [];\n\n for (const [node, neighbors] of graph.entries()) {\n if (neighbors.length === 1) {\n result = [node, neighbors[0]];\n break;\n }\n }\n\n while (result.length < adjacentPairs.length + 1) {\n const [last, prev] = [result[result.length - 1], result[result.length - 2]];\n const candidates = graph.get(last);\n const nextElement = candidates[0] !== prev ? candidates[0] : candidates[1];\n result.push(nextElement);\n }\n\n return result; \n};\n```\n```java []\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n\n for (int[] pair : adjacentPairs) {\n graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);\n graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);\n }\n\n List<Integer> result = new ArrayList<>();\n\n for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {\n if (entry.getValue().size() == 1) {\n result.add(entry.getKey());\n result.add(entry.getValue().get(0));\n break;\n }\n }\n\n while (result.size() < adjacentPairs.length + 1) {\n int last = result.get(result.size() - 1);\n int prev = result.get(result.size() - 2);\n List<Integer> candidates = graph.get(last);\n int nextElement = candidates.get(0) != prev ? candidates.get(0) : candidates.get(1);\n result.add(nextElement);\n }\n\n return result.stream().mapToInt(Integer::intValue).toArray(); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n unordered_map<int, vector<int>> graph;\n\n for (const auto& pair : adjacentPairs) {\n graph[pair[0]].push_back(pair[1]);\n graph[pair[1]].push_back(pair[0]);\n }\n\n vector<int> result;\n\n for (const auto& entry : graph) {\n if (entry.second.size() == 1) {\n result = {entry.first, entry.second[0]};\n break;\n }\n }\n\n while (result.size() < adjacentPairs.size() + 1) {\n int last = result[result.size() - 1];\n int prev = result[result.size() - 2];\n const vector<int>& candidates = graph[last];\n int nextElement = (candidates[0] != prev) ? candidates[0] : candidates[1];\n result.push_back(nextElement);\n }\n\n return result; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/design-graph-with-shortest-path-calculator/solutions/4276911/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/llptwOvEstY\n\n\u25A0 Timeline of the video\n\n`0:05` Explain constructor and addEdge function\n`1:31` Explain shortestPath\n`3:29` Demonstrate how it works\n`11:47` Coding\n`17:17` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\n\u2B50\uFE0F **Including all posts from yesterday, my post reached the top spot for the first time!**\n\npost\nhttps://leetcode.com/problems/count-number-of-homogenous-substrings/solutions/4266765/video-give-me-5-minutes-on-time-o1-space-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/VcZrmO045Bo\n\n\u25A0 Timeline of the video\n\n`0:04` Let\'s find a solution pattern\n`1:38` A key point to solve Count Number of Homogenous Substrings\n`2:20` Demonstrate how it works with all the same characters\n`4:55` What if we find different characters\n`7:13` Coding\n`8:21` Time Complexity and Space Complexity
95
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Iterative Python solution
restore-the-array-from-adjacent-pairs
0
1
The key observation is that except for the first and the last numbers of the array which has only 1 adjacent vertex, the #adjacent vertices will be 2. (In graph theory language, this is a path.)\nTherefore, we can start from either end, and iteratively traverse along the path.\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n d = defaultdict(set)\n for u, v in adjacentPairs:\n d[u].add(v)\n d[v].add(u)\n for u, nbr_u in d.items():\n if len(nbr_u) == 1:\n break\n ans = [u]\n prev_u = None\n n = len(adjacentPairs) + 1\n while len(ans) < n:\n for v in d[u]:\n # prev_u => u => v, we need to make sure v != prev_u\n if v != prev_u:\n # advance to the next vertex\n ans.append(v)\n prev_u = u\n u = v\n break\n return ans\n```
2
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Iterative Python solution
restore-the-array-from-adjacent-pairs
0
1
The key observation is that except for the first and the last numbers of the array which has only 1 adjacent vertex, the #adjacent vertices will be 2. (In graph theory language, this is a path.)\nTherefore, we can start from either end, and iteratively traverse along the path.\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n d = defaultdict(set)\n for u, v in adjacentPairs:\n d[u].add(v)\n d[v].add(u)\n for u, nbr_u in d.items():\n if len(nbr_u) == 1:\n break\n ans = [u]\n prev_u = None\n n = len(adjacentPairs) + 1\n while len(ans) < n:\n for v in d[u]:\n # prev_u => u => v, we need to make sure v != prev_u\n if v != prev_u:\n # advance to the next vertex\n ans.append(v)\n prev_u = u\n u = v\n break\n return ans\n```
2
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
restore-the-array-from-adjacent-pairs
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(DFS)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - Keys of the map are integers representing nodes, and values are vectors of integers representing neighbors of each node.\n1. **Building the Graph:**\n\n - It iterates through the given `adjacentPairs` vector, which contains pairs of integers representing adjacent nodes in the graph.\n - For each pair, it adds edges to the graph by updating the adjacency lists of both nodes.\n1. **Finding the Root:**\n\n - After building the graph, the code searches for the root of the tree.\n - It does so by iterating through the `graph` map and finding the node with only one neighbor (degree 1).\n1. **DFS Traversal to Restore Array:**\n\n - The code initializes variables for traversal: `root` as the starting point, an empty vector `ans` to store the restored array, and `prev` to store the previous node.\n - It then calls the DFS function starting from the root.\n1. **DFS Traversal Details:**\n\n - The DFS function (`dfs`) is a recursive function that traverses the graph and restores the array.\n - At each step, it adds the current node to the `ans` vector.\n - It then iterates through the neighbors of the current node, avoiding revisiting the node it came from to prevent cycles.\n - For each neighbor, it recursively calls the DFS function.\n1. **Returning the Result:**\n\n - The final restored array is returned as a vector of integers.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Adjacency list representation of the graph\n unordered_map<int, vector<int>> graph;\n\n // Function to restore the array using DFS\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n // Build the graph from the given adjacent pairs\n for (auto& edge : adjacentPairs) {\n graph[edge[0]].push_back(edge[1]);\n graph[edge[1]].push_back(edge[0]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (auto& pair : graph) {\n if (pair.second.size() == 1) {\n root = pair.first;\n break;\n }\n }\n\n // Vector to store the restored array\n vector<int> ans;\n\n // Perform DFS traversal starting from the root\n dfs(root, INT_MAX, ans);\n\n // Return the restored array\n return ans;\n }\n\n // Recursive DFS function to traverse the graph and restore the array\n void dfs(int node, int prev, vector<int>& ans) {\n // Add the current node to the result array\n ans.push_back(node);\n\n // Traverse neighbors of the current node\n for (int neighbor : graph[node]) {\n // Avoid revisiting the node we came from (avoid cycles)\n if (neighbor != prev) {\n // Recursively visit the neighbor\n dfs(neighbor, node, ans);\n }\n }\n }\n};\n\n\n```\n\n```C []\n\n\n\n// Structure to represent a node in the graph\nstruct Node {\n int value;\n struct Node* next;\n};\n\n// Structure to represent the adjacency list\nstruct Graph {\n int numVertices;\n struct Node** adjList;\n};\n\n// Function to create a new node\nstruct Node* createNode(int value) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->value = value;\n newNode->next = NULL;\n return newNode;\n}\n\n// Function to create a graph with a given number of vertices\nstruct Graph* createGraph(int numVertices) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->numVertices = numVertices;\n graph->adjList = (struct Node**)malloc(numVertices * sizeof(struct Node*));\n\n for (int i = 0; i < numVertices; ++i)\n graph->adjList[i] = NULL;\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n struct Node* newNode = createNode(dest);\n newNode->next = graph->adjList[src];\n graph->adjList[src] = newNode;\n\n newNode = createNode(src);\n newNode->next = graph->adjList[dest];\n graph->adjList[dest] = newNode;\n}\n\n// Function to perform DFS traversal\nvoid dfs(struct Graph* graph, int node, int prev, int* ans, int* index) {\n ans[(*index)++] = node;\n\n struct Node* current = graph->adjList[node];\n while (current != NULL) {\n if (current->value != prev) {\n dfs(graph, current->value, node, ans, index);\n }\n current = current->next;\n }\n}\n\n// Function to restore the array using DFS\nint* restoreArray(int** adjacentPairs, int adjacentPairsSize, int* adjacentPairsColSize, int* returnSize) {\n // Create the graph and add edges\n int numVertices = adjacentPairsSize + 1;\n struct Graph* graph = createGraph(numVertices);\n for (int i = 0; i < adjacentPairsSize; ++i) {\n addEdge(graph, adjacentPairs[i][0], adjacentPairs[i][1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (int i = 0; i < numVertices; ++i) {\n if (graph->adjList[i] != NULL && graph->adjList[i]->next == NULL) {\n root = i;\n break;\n }\n }\n\n // Vector to store the restored array\n int* ans = (int*)malloc(numVertices * sizeof(int));\n int index = 0;\n\n // Perform DFS traversal starting from the root\n dfs(graph, root, INT_MAX, ans, &index);\n\n // Set the return size and return the restored array\n *returnSize = numVertices;\n return ans;\n}\n\n\n\n\n```\n\n```Java []\nclass Solution {\n Map<Integer, List<Integer>> graph = new HashMap();\n \n public int[] restoreArray(int[][] adjacentPairs) {\n for (int[] edge : adjacentPairs) {\n int x = edge[0];\n int y = edge[1];\n \n if (!graph.containsKey(x)) {\n graph.put(x, new ArrayList());\n }\n \n if (!graph.containsKey(y)) {\n graph.put(y, new ArrayList());\n }\n \n graph.get(x).add(y);\n graph.get(y).add(x);\n }\n \n int root = 0;\n for (int num : graph.keySet()) {\n if (graph.get(num).size() == 1) {\n root = num;\n break;\n }\n }\n \n int[] ans = new int[graph.size()];\n dfs(root, Integer.MAX_VALUE, ans, 0);\n return ans;\n }\n \n private void dfs(int node, int prev, int[] ans, int i) {\n ans[i] = node;\n for (int neighbor : graph.get(node)) {\n if (neighbor != prev) {\n dfs(neighbor, node, ans, i + 1);\n }\n }\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n \n for x, y in adjacentPairs:\n graph[x].append(y)\n graph[y].append(x)\n \n root = None\n for num in graph:\n if len(graph[num]) == 1:\n root = num\n break\n \n def dfs(node, prev, ans):\n ans.append(node)\n for neighbor in graph[node]:\n if neighbor != prev:\n dfs(neighbor, node, ans)\n\n ans = []\n dfs(root, None, ans)\n return ans\n\n```\n\n```javascript []\n\n/**\n * Class representing a graph node.\n */\nclass Node {\n constructor(value) {\n this.value = value;\n this.next = null;\n }\n}\n\n/**\n * Class representing a graph with adjacency list representation.\n */\nclass Graph {\n constructor(numVertices) {\n this.numVertices = numVertices;\n this.adjList = new Array(numVertices).fill(null).map(() => []);\n }\n\n /**\n * Add an edge to the graph.\n * @param {number} src - The source vertex.\n * @param {number} dest - The destination vertex.\n */\n addEdge(src, dest) {\n this.adjList[src].push(dest);\n this.adjList[dest].push(src);\n }\n}\n\n/**\n * Perform DFS traversal on the graph.\n * @param {Graph} graph - The graph.\n * @param {number} node - The current node.\n * @param {number} prev - The previous node.\n * @param {number[]} ans - The array to store the result.\n * @param {number[]} index - The current index in the result array.\n */\nfunction dfs(graph, node, prev, ans, index) {\n ans[index[0]++] = node;\n\n for (const neighbor of graph.adjList[node]) {\n if (neighbor !== prev) {\n dfs(graph, neighbor, node, ans, index);\n }\n }\n}\n\n/**\n * Restore the array using DFS.\n * @param {number[][]} adjacentPairs - The array of adjacent pairs.\n * @returns {number[]} - The restored array.\n */\nfunction restoreArray(adjacentPairs) {\n // Build the graph from the given adjacent pairs\n const numVertices = adjacentPairs.length + 1;\n const graph = new Graph(numVertices);\n for (const edge of adjacentPairs) {\n graph.addEdge(edge[0], edge[1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n let root = 0;\n for (let i = 0; i < numVertices; ++i) {\n if (graph.adjList[i].length === 1) {\n root = i;\n break;\n }\n }\n\n // Vector to store the restored array\n const ans = new Array(numVertices);\n let index = 0;\n\n // Perform DFS traversal starting from the root\n dfs(graph, root, Number.MAX_SAFE_INTEGER, ans, [index]);\n\n // Return the restored array\n return ans;\n}\n\n\n\n```\n---\n\n#### ***Approach 2(Iterative)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - The keys of the map are integers representing nodes, and the values are vectors of integers representing the neighbors of each node.\n1. **Building the Graph:**\n\n - The code iterates through the given `adjacentPairs` vector, which contains pairs of integers representing adjacent nodes in the graph.\n - For each pair, it adds edges to the graph by updating the adjacency lists of both nodes.\n1. **Finding the Root:**\n\n - After building the graph, the code searches for the root of the tree.\n - It does so by iterating through the `graph` map and finding the node with only one neighbor (degree 1).\n1. **DFS Traversal to Restore Array:**\n\n - The code initializes variables for traversal: `curr` to keep track of the current node, `ans` to store the restored array, and `prev` to store the previous node.\n - It starts with the root and adds it to the `ans` vector.\n - It then enters a while loop until the `ans` vector\'s size is equal to the size of the graph.\n1. **DFS Traversal Details:**\n\n - Within the while loop, the code iterates through the neighbors of the current node (`curr`) in the graph.\n - It selects the neighbor that is not equal to the previous node (`prev`).\n - The selected neighbor is added to the `ans` vector, and the current node and previous node are updated accordingly.\n - The loop continues until the `ans` vector is fully populated.\n1. **Returning the Result:**\n\n - The final restored array is returned as a vector of integers.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n unordered_map<int, vector<int>> graph;\n\n for (auto& edge : adjacentPairs) {\n graph[edge[0]].push_back(edge[1]);\n graph[edge[1]].push_back(edge[0]);\n }\n \n int root = 0;\n for (auto& pair : graph) {\n if (pair.second.size() == 1) {\n root = pair.first;\n break;\n }\n }\n \n int curr = root;\n vector<int> ans = {root};\n int prev = INT_MAX;\n \n while (ans.size() < graph.size()) {\n for (int neighbor : graph[curr]) {\n if (neighbor != prev) {\n ans.push_back(neighbor);\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n return ans;\n }\n};\n\n```\n\n```C []\n\n\n// Structure to represent a node in the graph\nstruct Node {\n int value;\n struct Node* next;\n};\n\n// Structure to represent the adjacency list\nstruct Graph {\n int numVertices;\n struct Node** adjList;\n};\n\n// Function to create a new node\nstruct Node* createNode(int value) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->value = value;\n newNode->next = NULL;\n return newNode;\n}\n\n// Function to create a graph with a given number of vertices\nstruct Graph* createGraph(int numVertices) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->numVertices = numVertices;\n graph->adjList = (struct Node**)malloc(numVertices * sizeof(struct Node*));\n\n for (int i = 0; i < numVertices; ++i)\n graph->adjList[i] = NULL;\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n struct Node* newNode = createNode(dest);\n newNode->next = graph->adjList[src];\n graph->adjList[src] = newNode;\n\n newNode = createNode(src);\n newNode->next = graph->adjList[dest];\n graph->adjList[dest] = newNode;\n}\n\n// Function to restore the array\nint* restoreArray(int** adjacentPairs, int adjacentPairsSize, int* adjacentPairsColSize, int* returnSize) {\n // Create the graph and add edges\n int numVertices = adjacentPairsSize + 1;\n struct Graph* graph = createGraph(numVertices);\n for (int i = 0; i < adjacentPairsSize; ++i) {\n addEdge(graph, adjacentPairs[i][0], adjacentPairs[i][1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (int i = 0; i < numVertices; ++i) {\n if (graph->adjList[i] != NULL && graph->adjList[i]->next == NULL) {\n root = i;\n break;\n }\n }\n\n // Initialize variables for traversal\n int curr = root;\n int* ans = (int*)malloc(numVertices * sizeof(int));\n int index = 0;\n int prev = INT_MAX;\n\n // Traverse the graph to restore the array\n while (index < numVertices) {\n ans[index++] = curr;\n\n struct Node* current = graph->adjList[curr];\n while (current != NULL) {\n if (current->value != prev) {\n prev = curr;\n curr = current->value;\n break;\n }\n current = current->next;\n }\n }\n\n // Set the return size and return the restored array\n *returnSize = numVertices;\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n Map<Integer, List<Integer>> graph = new HashMap();\n \n for (int[] edge : adjacentPairs) {\n int x = edge[0];\n int y = edge[1];\n \n if (!graph.containsKey(x)) {\n graph.put(x, new ArrayList());\n }\n \n if (!graph.containsKey(y)) {\n graph.put(y, new ArrayList());\n }\n \n graph.get(x).add(y);\n graph.get(y).add(x);\n }\n \n int root = 0;\n for (int num : graph.keySet()) {\n if (graph.get(num).size() == 1) {\n root = num;\n break;\n }\n }\n \n int curr = root;\n int[] ans = new int[graph.size()];\n ans[0] = root;\n int i = 1;\n int prev = Integer.MAX_VALUE;\n \n while (i < graph.size()) {\n for (int neighbor : graph.get(curr)) {\n if (neighbor != prev) {\n ans[i] = neighbor;\n i++;\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n \n for x, y in adjacentPairs:\n graph[x].append(y)\n graph[y].append(x)\n \n root = None\n for num in graph:\n if len(graph[num]) == 1:\n root = num\n break\n \n curr = root\n ans = [root]\n prev = None\n\n while len(ans) < len(graph):\n for neighbor in graph[curr]:\n if neighbor != prev:\n ans.append(neighbor)\n prev = curr\n curr = neighbor\n break\n\n return ans\n\n```\n\n```javascript []\n\n/**\n * Class representing a graph node.\n */\nclass Node {\n constructor(value) {\n this.value = value;\n this.next = null;\n }\n}\n\n/**\n * Class representing a graph with adjacency list representation.\n */\nclass Graph {\n constructor(numVertices) {\n this.numVertices = numVertices;\n this.adjList = new Array(numVertices).fill(null).map(() => []);\n }\n\n /**\n * Add an edge to the graph.\n * @param {number} src - The source vertex.\n * @param {number} dest - The destination vertex.\n */\n addEdge(src, dest) {\n this.adjList[src].push(dest);\n this.adjList[dest].push(src);\n }\n}\n\n/**\n * Restore the array using DFS.\n * @param {number[][]} adjacentPairs - The array of adjacent pairs.\n * @returns {number[]} - The restored array.\n */\nfunction restoreArray(adjacentPairs) {\n // Build the graph from the given adjacent pairs\n const numVertices = adjacentPairs.length + 1;\n const graph = new Graph(numVertices);\n for (const edge of adjacentPairs) {\n graph.addEdge(edge[0], edge[1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n let root = 0;\n for (let i = 0; i < numVertices; ++i) {\n if (graph.adjList[i].length === 1) {\n root = i;\n break;\n }\n }\n\n // Initialize variables for traversal\n let curr = root;\n const ans = new Array(numVertices);\n let index = 0;\n let prev = Number.MAX_SAFE_INTEGER;\n\n // Traverse the graph to restore the array\n while (index < numVertices) {\n ans[index++] = curr;\n\n for (const neighbor of graph.adjList[curr]) {\n if (neighbor !== prev) {\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n // Return the restored array\n return ans;\n}\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
2
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
restore-the-array-from-adjacent-pairs
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(DFS)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - Keys of the map are integers representing nodes, and values are vectors of integers representing neighbors of each node.\n1. **Building the Graph:**\n\n - It iterates through the given `adjacentPairs` vector, which contains pairs of integers representing adjacent nodes in the graph.\n - For each pair, it adds edges to the graph by updating the adjacency lists of both nodes.\n1. **Finding the Root:**\n\n - After building the graph, the code searches for the root of the tree.\n - It does so by iterating through the `graph` map and finding the node with only one neighbor (degree 1).\n1. **DFS Traversal to Restore Array:**\n\n - The code initializes variables for traversal: `root` as the starting point, an empty vector `ans` to store the restored array, and `prev` to store the previous node.\n - It then calls the DFS function starting from the root.\n1. **DFS Traversal Details:**\n\n - The DFS function (`dfs`) is a recursive function that traverses the graph and restores the array.\n - At each step, it adds the current node to the `ans` vector.\n - It then iterates through the neighbors of the current node, avoiding revisiting the node it came from to prevent cycles.\n - For each neighbor, it recursively calls the DFS function.\n1. **Returning the Result:**\n\n - The final restored array is returned as a vector of integers.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Adjacency list representation of the graph\n unordered_map<int, vector<int>> graph;\n\n // Function to restore the array using DFS\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n // Build the graph from the given adjacent pairs\n for (auto& edge : adjacentPairs) {\n graph[edge[0]].push_back(edge[1]);\n graph[edge[1]].push_back(edge[0]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (auto& pair : graph) {\n if (pair.second.size() == 1) {\n root = pair.first;\n break;\n }\n }\n\n // Vector to store the restored array\n vector<int> ans;\n\n // Perform DFS traversal starting from the root\n dfs(root, INT_MAX, ans);\n\n // Return the restored array\n return ans;\n }\n\n // Recursive DFS function to traverse the graph and restore the array\n void dfs(int node, int prev, vector<int>& ans) {\n // Add the current node to the result array\n ans.push_back(node);\n\n // Traverse neighbors of the current node\n for (int neighbor : graph[node]) {\n // Avoid revisiting the node we came from (avoid cycles)\n if (neighbor != prev) {\n // Recursively visit the neighbor\n dfs(neighbor, node, ans);\n }\n }\n }\n};\n\n\n```\n\n```C []\n\n\n\n// Structure to represent a node in the graph\nstruct Node {\n int value;\n struct Node* next;\n};\n\n// Structure to represent the adjacency list\nstruct Graph {\n int numVertices;\n struct Node** adjList;\n};\n\n// Function to create a new node\nstruct Node* createNode(int value) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->value = value;\n newNode->next = NULL;\n return newNode;\n}\n\n// Function to create a graph with a given number of vertices\nstruct Graph* createGraph(int numVertices) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->numVertices = numVertices;\n graph->adjList = (struct Node**)malloc(numVertices * sizeof(struct Node*));\n\n for (int i = 0; i < numVertices; ++i)\n graph->adjList[i] = NULL;\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n struct Node* newNode = createNode(dest);\n newNode->next = graph->adjList[src];\n graph->adjList[src] = newNode;\n\n newNode = createNode(src);\n newNode->next = graph->adjList[dest];\n graph->adjList[dest] = newNode;\n}\n\n// Function to perform DFS traversal\nvoid dfs(struct Graph* graph, int node, int prev, int* ans, int* index) {\n ans[(*index)++] = node;\n\n struct Node* current = graph->adjList[node];\n while (current != NULL) {\n if (current->value != prev) {\n dfs(graph, current->value, node, ans, index);\n }\n current = current->next;\n }\n}\n\n// Function to restore the array using DFS\nint* restoreArray(int** adjacentPairs, int adjacentPairsSize, int* adjacentPairsColSize, int* returnSize) {\n // Create the graph and add edges\n int numVertices = adjacentPairsSize + 1;\n struct Graph* graph = createGraph(numVertices);\n for (int i = 0; i < adjacentPairsSize; ++i) {\n addEdge(graph, adjacentPairs[i][0], adjacentPairs[i][1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (int i = 0; i < numVertices; ++i) {\n if (graph->adjList[i] != NULL && graph->adjList[i]->next == NULL) {\n root = i;\n break;\n }\n }\n\n // Vector to store the restored array\n int* ans = (int*)malloc(numVertices * sizeof(int));\n int index = 0;\n\n // Perform DFS traversal starting from the root\n dfs(graph, root, INT_MAX, ans, &index);\n\n // Set the return size and return the restored array\n *returnSize = numVertices;\n return ans;\n}\n\n\n\n\n```\n\n```Java []\nclass Solution {\n Map<Integer, List<Integer>> graph = new HashMap();\n \n public int[] restoreArray(int[][] adjacentPairs) {\n for (int[] edge : adjacentPairs) {\n int x = edge[0];\n int y = edge[1];\n \n if (!graph.containsKey(x)) {\n graph.put(x, new ArrayList());\n }\n \n if (!graph.containsKey(y)) {\n graph.put(y, new ArrayList());\n }\n \n graph.get(x).add(y);\n graph.get(y).add(x);\n }\n \n int root = 0;\n for (int num : graph.keySet()) {\n if (graph.get(num).size() == 1) {\n root = num;\n break;\n }\n }\n \n int[] ans = new int[graph.size()];\n dfs(root, Integer.MAX_VALUE, ans, 0);\n return ans;\n }\n \n private void dfs(int node, int prev, int[] ans, int i) {\n ans[i] = node;\n for (int neighbor : graph.get(node)) {\n if (neighbor != prev) {\n dfs(neighbor, node, ans, i + 1);\n }\n }\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n \n for x, y in adjacentPairs:\n graph[x].append(y)\n graph[y].append(x)\n \n root = None\n for num in graph:\n if len(graph[num]) == 1:\n root = num\n break\n \n def dfs(node, prev, ans):\n ans.append(node)\n for neighbor in graph[node]:\n if neighbor != prev:\n dfs(neighbor, node, ans)\n\n ans = []\n dfs(root, None, ans)\n return ans\n\n```\n\n```javascript []\n\n/**\n * Class representing a graph node.\n */\nclass Node {\n constructor(value) {\n this.value = value;\n this.next = null;\n }\n}\n\n/**\n * Class representing a graph with adjacency list representation.\n */\nclass Graph {\n constructor(numVertices) {\n this.numVertices = numVertices;\n this.adjList = new Array(numVertices).fill(null).map(() => []);\n }\n\n /**\n * Add an edge to the graph.\n * @param {number} src - The source vertex.\n * @param {number} dest - The destination vertex.\n */\n addEdge(src, dest) {\n this.adjList[src].push(dest);\n this.adjList[dest].push(src);\n }\n}\n\n/**\n * Perform DFS traversal on the graph.\n * @param {Graph} graph - The graph.\n * @param {number} node - The current node.\n * @param {number} prev - The previous node.\n * @param {number[]} ans - The array to store the result.\n * @param {number[]} index - The current index in the result array.\n */\nfunction dfs(graph, node, prev, ans, index) {\n ans[index[0]++] = node;\n\n for (const neighbor of graph.adjList[node]) {\n if (neighbor !== prev) {\n dfs(graph, neighbor, node, ans, index);\n }\n }\n}\n\n/**\n * Restore the array using DFS.\n * @param {number[][]} adjacentPairs - The array of adjacent pairs.\n * @returns {number[]} - The restored array.\n */\nfunction restoreArray(adjacentPairs) {\n // Build the graph from the given adjacent pairs\n const numVertices = adjacentPairs.length + 1;\n const graph = new Graph(numVertices);\n for (const edge of adjacentPairs) {\n graph.addEdge(edge[0], edge[1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n let root = 0;\n for (let i = 0; i < numVertices; ++i) {\n if (graph.adjList[i].length === 1) {\n root = i;\n break;\n }\n }\n\n // Vector to store the restored array\n const ans = new Array(numVertices);\n let index = 0;\n\n // Perform DFS traversal starting from the root\n dfs(graph, root, Number.MAX_SAFE_INTEGER, ans, [index]);\n\n // Return the restored array\n return ans;\n}\n\n\n\n```\n---\n\n#### ***Approach 2(Iterative)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - The keys of the map are integers representing nodes, and the values are vectors of integers representing the neighbors of each node.\n1. **Building the Graph:**\n\n - The code iterates through the given `adjacentPairs` vector, which contains pairs of integers representing adjacent nodes in the graph.\n - For each pair, it adds edges to the graph by updating the adjacency lists of both nodes.\n1. **Finding the Root:**\n\n - After building the graph, the code searches for the root of the tree.\n - It does so by iterating through the `graph` map and finding the node with only one neighbor (degree 1).\n1. **DFS Traversal to Restore Array:**\n\n - The code initializes variables for traversal: `curr` to keep track of the current node, `ans` to store the restored array, and `prev` to store the previous node.\n - It starts with the root and adds it to the `ans` vector.\n - It then enters a while loop until the `ans` vector\'s size is equal to the size of the graph.\n1. **DFS Traversal Details:**\n\n - Within the while loop, the code iterates through the neighbors of the current node (`curr`) in the graph.\n - It selects the neighbor that is not equal to the previous node (`prev`).\n - The selected neighbor is added to the `ans` vector, and the current node and previous node are updated accordingly.\n - The loop continues until the `ans` vector is fully populated.\n1. **Returning the Result:**\n\n - The final restored array is returned as a vector of integers.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n unordered_map<int, vector<int>> graph;\n\n for (auto& edge : adjacentPairs) {\n graph[edge[0]].push_back(edge[1]);\n graph[edge[1]].push_back(edge[0]);\n }\n \n int root = 0;\n for (auto& pair : graph) {\n if (pair.second.size() == 1) {\n root = pair.first;\n break;\n }\n }\n \n int curr = root;\n vector<int> ans = {root};\n int prev = INT_MAX;\n \n while (ans.size() < graph.size()) {\n for (int neighbor : graph[curr]) {\n if (neighbor != prev) {\n ans.push_back(neighbor);\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n return ans;\n }\n};\n\n```\n\n```C []\n\n\n// Structure to represent a node in the graph\nstruct Node {\n int value;\n struct Node* next;\n};\n\n// Structure to represent the adjacency list\nstruct Graph {\n int numVertices;\n struct Node** adjList;\n};\n\n// Function to create a new node\nstruct Node* createNode(int value) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->value = value;\n newNode->next = NULL;\n return newNode;\n}\n\n// Function to create a graph with a given number of vertices\nstruct Graph* createGraph(int numVertices) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->numVertices = numVertices;\n graph->adjList = (struct Node**)malloc(numVertices * sizeof(struct Node*));\n\n for (int i = 0; i < numVertices; ++i)\n graph->adjList[i] = NULL;\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n struct Node* newNode = createNode(dest);\n newNode->next = graph->adjList[src];\n graph->adjList[src] = newNode;\n\n newNode = createNode(src);\n newNode->next = graph->adjList[dest];\n graph->adjList[dest] = newNode;\n}\n\n// Function to restore the array\nint* restoreArray(int** adjacentPairs, int adjacentPairsSize, int* adjacentPairsColSize, int* returnSize) {\n // Create the graph and add edges\n int numVertices = adjacentPairsSize + 1;\n struct Graph* graph = createGraph(numVertices);\n for (int i = 0; i < adjacentPairsSize; ++i) {\n addEdge(graph, adjacentPairs[i][0], adjacentPairs[i][1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n int root = 0;\n for (int i = 0; i < numVertices; ++i) {\n if (graph->adjList[i] != NULL && graph->adjList[i]->next == NULL) {\n root = i;\n break;\n }\n }\n\n // Initialize variables for traversal\n int curr = root;\n int* ans = (int*)malloc(numVertices * sizeof(int));\n int index = 0;\n int prev = INT_MAX;\n\n // Traverse the graph to restore the array\n while (index < numVertices) {\n ans[index++] = curr;\n\n struct Node* current = graph->adjList[curr];\n while (current != NULL) {\n if (current->value != prev) {\n prev = curr;\n curr = current->value;\n break;\n }\n current = current->next;\n }\n }\n\n // Set the return size and return the restored array\n *returnSize = numVertices;\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n Map<Integer, List<Integer>> graph = new HashMap();\n \n for (int[] edge : adjacentPairs) {\n int x = edge[0];\n int y = edge[1];\n \n if (!graph.containsKey(x)) {\n graph.put(x, new ArrayList());\n }\n \n if (!graph.containsKey(y)) {\n graph.put(y, new ArrayList());\n }\n \n graph.get(x).add(y);\n graph.get(y).add(x);\n }\n \n int root = 0;\n for (int num : graph.keySet()) {\n if (graph.get(num).size() == 1) {\n root = num;\n break;\n }\n }\n \n int curr = root;\n int[] ans = new int[graph.size()];\n ans[0] = root;\n int i = 1;\n int prev = Integer.MAX_VALUE;\n \n while (i < graph.size()) {\n for (int neighbor : graph.get(curr)) {\n if (neighbor != prev) {\n ans[i] = neighbor;\n i++;\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n \n for x, y in adjacentPairs:\n graph[x].append(y)\n graph[y].append(x)\n \n root = None\n for num in graph:\n if len(graph[num]) == 1:\n root = num\n break\n \n curr = root\n ans = [root]\n prev = None\n\n while len(ans) < len(graph):\n for neighbor in graph[curr]:\n if neighbor != prev:\n ans.append(neighbor)\n prev = curr\n curr = neighbor\n break\n\n return ans\n\n```\n\n```javascript []\n\n/**\n * Class representing a graph node.\n */\nclass Node {\n constructor(value) {\n this.value = value;\n this.next = null;\n }\n}\n\n/**\n * Class representing a graph with adjacency list representation.\n */\nclass Graph {\n constructor(numVertices) {\n this.numVertices = numVertices;\n this.adjList = new Array(numVertices).fill(null).map(() => []);\n }\n\n /**\n * Add an edge to the graph.\n * @param {number} src - The source vertex.\n * @param {number} dest - The destination vertex.\n */\n addEdge(src, dest) {\n this.adjList[src].push(dest);\n this.adjList[dest].push(src);\n }\n}\n\n/**\n * Restore the array using DFS.\n * @param {number[][]} adjacentPairs - The array of adjacent pairs.\n * @returns {number[]} - The restored array.\n */\nfunction restoreArray(adjacentPairs) {\n // Build the graph from the given adjacent pairs\n const numVertices = adjacentPairs.length + 1;\n const graph = new Graph(numVertices);\n for (const edge of adjacentPairs) {\n graph.addEdge(edge[0], edge[1]);\n }\n\n // Find the root of the tree by identifying the node with only one neighbor\n let root = 0;\n for (let i = 0; i < numVertices; ++i) {\n if (graph.adjList[i].length === 1) {\n root = i;\n break;\n }\n }\n\n // Initialize variables for traversal\n let curr = root;\n const ans = new Array(numVertices);\n let index = 0;\n let prev = Number.MAX_SAFE_INTEGER;\n\n // Traverse the graph to restore the array\n while (index < numVertices) {\n ans[index++] = curr;\n\n for (const neighbor of graph.adjList[curr]) {\n if (neighbor !== prev) {\n prev = curr;\n curr = neighbor;\n break;\n }\n }\n }\n\n // Return the restored array\n return ans;\n}\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
2
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python3 Solution
restore-the-array-from-adjacent-pairs
0
1
\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adjs=collections.defaultdict(set)\n for i,j in adjacentPairs:\n adjs[i].add(j)\n adjs[j].add(i)\n\n for node,adj in adjs.items():\n if len(adj)==1:\n break\n ans=[node]\n while adjs[node]:\n new=adjs[node].pop()\n ans.append(new)\n adjs[new].remove(node)\n node=new\n return ans \n```
11
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Python3 Solution
restore-the-array-from-adjacent-pairs
0
1
\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adjs=collections.defaultdict(set)\n for i,j in adjacentPairs:\n adjs[i].add(j)\n adjs[j].add(i)\n\n for node,adj in adjs.items():\n if len(adj)==1:\n break\n ans=[node]\n while adjs[node]:\n new=adjs[node].pop()\n ans.append(new)\n adjs[new].remove(node)\n node=new\n return ans \n```
11
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Solution with Graph/HashTable in TypeScript/Python3
restore-the-array-from-adjacent-pairs
0
1
\n# Intuition\nHere we have:\n- list of integers `adj`, that represent neighbours in `adj`\n- our goal is to **reconstruct** an **original** array of integers\n\nThe logic is straightforward and let\'s imagine, that we\'ve already done a task:\n- here is the list, for example `[1,2,3,4]`\n- according to the task description we should reconstruct an array of integers and we have only **relationships** between neighbours\n- here is the tip: \n```\n# If we break down a list of integers we could see a fact, \n# that each integer EXCEPT the FIRST and the LAST ones\n# HAS TWO neighbours.\n\n# Let\'s build a graph to represent relationship:\n\ngraph = {\n "1": [2],\n "2": [1,2],\n "3": [3,4],\n "4": [3],\n}\n\n# Have you seen a thing?\n# If you haven\'t, then the last tip will be =>\n# Since we have ONLY two integers with one neighbour it DOESN\'T\n# MATTER which one we might use (1 or 4) and then you can do \n# a normal Depth-First Search traversing over graph.\n```\n\n# Approach\n1. declare `graph`, `ans`, `seen` (to store **visited** nodes)\n2. iterate over graph, add relationships between edges and vertices\n3. after that you must have **EXACTLY** two entry points to traverse a graph (starting and ending)\n4. choose any of them\n5. and do standard `dfs`\n6. collect values while traversing a `graph`\n7. ignore **visited** nodes with `seen`\n8. return `ans` that\'ll represent a valid sequence of integers \n\n# Complexity\n- Time complexity: **O(N)**, since we iterate over `graph`, `dfs`, and over `adj`\n\n- Space complexity: **O(N)**, the same for storing\n\n# Code in Python3\n```\nclass Solution:\n def restoreArray(self, adj: list[list[int]]) -> list[int]:\n graph = defaultdict(list)\n ans = []\n seen = set()\n\n for a, b in adj:\n graph[a].append(b)\n graph[b].append(a)\n\n def dfs(node):\n for neig in graph[node]:\n if neig not in seen: \n seen.add(neig)\n ans.append(neig)\n dfs(neig)\n\n for node in graph:\n if len(graph[node]) == 1:\n ans.append(node)\n seen.add(node)\n dfs(node)\n break \n \n return ans\n```\n# Code in TypeScript\n```\nfunction restoreArray(adj: number[][]): number[] {\n const graph = {}\n const ans = []\n const seen = new Set()\n\n for (const [a, b] of adj) {\n if (!(a in graph)) graph[a] = []\n if (!(b in graph)) graph[b] = []\n\n graph[a].push(b)\n graph[b].push(a)\n }\n\n const dfs = (node: number) => {\n for (const neig of graph[node]) {\n if (!seen.has(neig)) {\n seen.add(neig)\n ans.push(neig)\n dfs(neig)\n }\n }\n }\n\n for (const node in graph) {\n if (graph[node].length === 1) {\n ans.push(+node)\n seen.add(+node)\n dfs(+node)\n break\n }\n }\n\n return ans\n};\n```
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Solution with Graph/HashTable in TypeScript/Python3
restore-the-array-from-adjacent-pairs
0
1
\n# Intuition\nHere we have:\n- list of integers `adj`, that represent neighbours in `adj`\n- our goal is to **reconstruct** an **original** array of integers\n\nThe logic is straightforward and let\'s imagine, that we\'ve already done a task:\n- here is the list, for example `[1,2,3,4]`\n- according to the task description we should reconstruct an array of integers and we have only **relationships** between neighbours\n- here is the tip: \n```\n# If we break down a list of integers we could see a fact, \n# that each integer EXCEPT the FIRST and the LAST ones\n# HAS TWO neighbours.\n\n# Let\'s build a graph to represent relationship:\n\ngraph = {\n "1": [2],\n "2": [1,2],\n "3": [3,4],\n "4": [3],\n}\n\n# Have you seen a thing?\n# If you haven\'t, then the last tip will be =>\n# Since we have ONLY two integers with one neighbour it DOESN\'T\n# MATTER which one we might use (1 or 4) and then you can do \n# a normal Depth-First Search traversing over graph.\n```\n\n# Approach\n1. declare `graph`, `ans`, `seen` (to store **visited** nodes)\n2. iterate over graph, add relationships between edges and vertices\n3. after that you must have **EXACTLY** two entry points to traverse a graph (starting and ending)\n4. choose any of them\n5. and do standard `dfs`\n6. collect values while traversing a `graph`\n7. ignore **visited** nodes with `seen`\n8. return `ans` that\'ll represent a valid sequence of integers \n\n# Complexity\n- Time complexity: **O(N)**, since we iterate over `graph`, `dfs`, and over `adj`\n\n- Space complexity: **O(N)**, the same for storing\n\n# Code in Python3\n```\nclass Solution:\n def restoreArray(self, adj: list[list[int]]) -> list[int]:\n graph = defaultdict(list)\n ans = []\n seen = set()\n\n for a, b in adj:\n graph[a].append(b)\n graph[b].append(a)\n\n def dfs(node):\n for neig in graph[node]:\n if neig not in seen: \n seen.add(neig)\n ans.append(neig)\n dfs(neig)\n\n for node in graph:\n if len(graph[node]) == 1:\n ans.append(node)\n seen.add(node)\n dfs(node)\n break \n \n return ans\n```\n# Code in TypeScript\n```\nfunction restoreArray(adj: number[][]): number[] {\n const graph = {}\n const ans = []\n const seen = new Set()\n\n for (const [a, b] of adj) {\n if (!(a in graph)) graph[a] = []\n if (!(b in graph)) graph[b] = []\n\n graph[a].push(b)\n graph[b].push(a)\n }\n\n const dfs = (node: number) => {\n for (const neig of graph[node]) {\n if (!seen.has(neig)) {\n seen.add(neig)\n ans.push(neig)\n dfs(neig)\n }\n }\n }\n\n for (const node in graph) {\n if (graph[node].length === 1) {\n ans.push(+node)\n seen.add(+node)\n dfs(+node)\n break\n }\n }\n\n return ans\n};\n```
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Basic graph DFS approach!😸
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n for u,v in adjacentPairs:\n graph[u].append(v)\n graph[v].append(u)\n r , visited = [] , set()\n for i in adjacentPairs:\n r.extend(i)\n c , start = Counter(r) , 1\n for i in c:\n if c[i] == 1:\n start = i #start/end will be the element which only appears once in the list of list bcuz they have no neighbours.\n break\n res = []\n def dfs(start):\n visited.add(start)\n res.append(start)\n for neigh in graph[start]:\n if neigh not in visited:\n dfs(neigh)\n # print(start)\n dfs(start)\n return res\n```
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Basic graph DFS approach!😸
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n for u,v in adjacentPairs:\n graph[u].append(v)\n graph[v].append(u)\n r , visited = [] , set()\n for i in adjacentPairs:\n r.extend(i)\n c , start = Counter(r) , 1\n for i in c:\n if c[i] == 1:\n start = i #start/end will be the element which only appears once in the list of list bcuz they have no neighbours.\n break\n res = []\n def dfs(start):\n visited.add(start)\n res.append(start)\n for neigh in graph[start]:\n if neigh not in visited:\n dfs(neigh)\n # print(start)\n dfs(start)\n return res\n```
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
DFS Solution O(n) Time O(n) Space
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBecause all the members of our final list are unique, we can use DFS to pick one of the ending elements and utilize an adjacency list to contiously find the next element\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate an adjacency list with the key being a number and the values being its neighbors. Find a key whose number of adjacent members is 1, as this means its one of the ends. Then put it on our stack and dfs from there, making sure to not traverse nums we\'ve seen.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) as we traverse `adjacentPairs` once to make our adjacency list. We go through our adjacency list to find an end, and we DFS by going to the next unseen neighbor, both of which also take O(n) time.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe have to store an adjacency list, a stack, and our result, all of which can take O(n) space. Though the stack will only ever have 0 or 1 elements in it.\n\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adj_list = defaultdict(list)\n for a,b in adjacentPairs:\n adj_list[a].append(b)\n adj_list[b].append(a)\n result = []\n seen = set()\n stack = []\n for key,value in adj_list.items():\n if len(value) == 1:\n stack.append(key)\n break\n while stack:\n curr_num = stack.pop()\n seen.add(curr_num)\n result.append(curr_num)\n for adj_nums in adj_list[curr_num]:\n if adj_nums not in seen:\n stack.append(adj_nums)\n return result\n```
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
DFS Solution O(n) Time O(n) Space
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBecause all the members of our final list are unique, we can use DFS to pick one of the ending elements and utilize an adjacency list to contiously find the next element\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate an adjacency list with the key being a number and the values being its neighbors. Find a key whose number of adjacent members is 1, as this means its one of the ends. Then put it on our stack and dfs from there, making sure to not traverse nums we\'ve seen.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) as we traverse `adjacentPairs` once to make our adjacency list. We go through our adjacency list to find an end, and we DFS by going to the next unseen neighbor, both of which also take O(n) time.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe have to store an adjacency list, a stack, and our result, all of which can take O(n) space. Though the stack will only ever have 0 or 1 elements in it.\n\n# Code\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adj_list = defaultdict(list)\n for a,b in adjacentPairs:\n adj_list[a].append(b)\n adj_list[b].append(a)\n result = []\n seen = set()\n stack = []\n for key,value in adj_list.items():\n if len(value) == 1:\n stack.append(key)\n break\n while stack:\n curr_num = stack.pop()\n seen.add(curr_num)\n result.append(curr_num)\n for adj_nums in adj_list[curr_num]:\n if adj_nums not in seen:\n stack.append(adj_nums)\n return result\n```
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python Unroll elements one by one
restore-the-array-from-adjacent-pairs
0
1
# Intuition\nIf the elements are none repeating then we can unroll them one by one creating a chain.\n\nIf we will look at a chaing `v1 - v2 - v3 - v4` you can see that all the elements have 2 neighbours except of two (first and a second). \n\nSo we need to create a dictionary which has nodes as keys set of childrens as values. Then look at the dicionary to find the first any starting position (`len(neighbors) == 1`). \n\nNow we try to increase our chain. At each step we look at the last value in our chain and operate based on it:\n - get the next value by poping from the dictionary: `data[res[-1]].pop()`\n - then remove the value `data[next_val].remove(res[-1])`\n - and add to the list `res.append(next_val)`\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n```\nclass Solution:\n def restoreArray(self, arr: List[List[int]]) -> List[int]:\n data = defaultdict(set)\n for v1, v2 in arr:\n data[v1].add(v2)\n data[v2].add(v1)\n\n res = []\n for k, v in data.items():\n if len(v) == 1:\n res.append(k)\n break\n \n while len(res) != len(arr):\n next_val = data[res[-1]].pop()\n data[next_val].remove(res[-1])\n res.append(next_val)\n\n res.append(data[res[-1]].pop())\n return res\n```
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Python Unroll elements one by one
restore-the-array-from-adjacent-pairs
0
1
# Intuition\nIf the elements are none repeating then we can unroll them one by one creating a chain.\n\nIf we will look at a chaing `v1 - v2 - v3 - v4` you can see that all the elements have 2 neighbours except of two (first and a second). \n\nSo we need to create a dictionary which has nodes as keys set of childrens as values. Then look at the dicionary to find the first any starting position (`len(neighbors) == 1`). \n\nNow we try to increase our chain. At each step we look at the last value in our chain and operate based on it:\n - get the next value by poping from the dictionary: `data[res[-1]].pop()`\n - then remove the value `data[next_val].remove(res[-1])`\n - and add to the list `res.append(next_val)`\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n```\nclass Solution:\n def restoreArray(self, arr: List[List[int]]) -> List[int]:\n data = defaultdict(set)\n for v1, v2 in arr:\n data[v1].add(v2)\n data[v2].add(v1)\n\n res = []\n for k, v in data.items():\n if len(v) == 1:\n res.append(k)\n break\n \n while len(res) != len(arr):\n next_val = data[res[-1]].pop()\n data[next_val].remove(res[-1])\n res.append(next_val)\n\n res.append(data[res[-1]].pop())\n return res\n```
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
dfs traversal
restore-the-array-from-adjacent-pairs
0
1
A possible solution could do the following three steps. \n- Construct a graph with either sides nodes as array elements (n) and hold traversal visited info (v).\n- Find the starting point of the list.\n- Traverse the graph from the start to find the list.\n\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n G = defaultdict(lambda: {\'n\': [], \'v\': False})\n ans = []\n start = float(\'inf\')\n \n for l,r in adjacentPairs: \n G[l][\'n\'].append(r)\n G[r][\'n\'].append(l)\n \n for i,j in G.items():\n if len(j[\'n\']) == 1:\n start = i\n break\n \n while G[start][\'v\'] == False:\n ans.append(start)\n G[start][\'v\'] = True\n for nxt in G[start][\'n\']:\n if G[nxt][\'v\'] == False:\n start = nxt\n break\n \n return ans\n \n \n \n```
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
dfs traversal
restore-the-array-from-adjacent-pairs
0
1
A possible solution could do the following three steps. \n- Construct a graph with either sides nodes as array elements (n) and hold traversal visited info (v).\n- Find the starting point of the list.\n- Traverse the graph from the start to find the list.\n\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n G = defaultdict(lambda: {\'n\': [], \'v\': False})\n ans = []\n start = float(\'inf\')\n \n for l,r in adjacentPairs: \n G[l][\'n\'].append(r)\n G[r][\'n\'].append(l)\n \n for i,j in G.items():\n if len(j[\'n\']) == 1:\n start = i\n break\n \n while G[start][\'v\'] == False:\n ans.append(start)\n G[start][\'v\'] = True\n for nxt in G[start][\'n\']:\n if G[nxt][\'v\'] == False:\n start = nxt\n break\n \n return ans\n \n \n \n```
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python 3 || 2 lines, prefix || T/M: 97% / 26%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n \n pref = list(accumulate(candiesCount, initial = 0)) \n \n return [pref[candy]//cap <= day < pref[candy + 1]\n for candy, day, cap in queries]\n```\n[https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/submissions/961866113/](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).
3
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python 3 || 2 lines, prefix || T/M: 97% / 26%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n \n pref = list(accumulate(candiesCount, initial = 0)) \n \n return [pref[candy]//cap <= day < pref[candy + 1]\n for candy, day, cap in queries]\n```\n[https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/submissions/961866113/](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).
3
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
[Python3] greedy
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Algo**\nCompute the prefix sum of `candiesCount`. For a given query (`t`, `day` and `cap`), the condition for `True` is \n`prefix[t] < (day + 1) * cap and day < prefix[t+1]`\nwhere the first half reflects the fact that if we eat maximum candies every day we can reach the preferred one and the second half means that if we eat minimum candies (i.e. one candy) every day we won\'t pass the preferred one. \n\n**Implementation**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = [0]\n for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum \n return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`
6
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
[Python3] greedy
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Algo**\nCompute the prefix sum of `candiesCount`. For a given query (`t`, `day` and `cap`), the condition for `True` is \n`prefix[t] < (day + 1) * cap and day < prefix[t+1]`\nwhere the first half reflects the fact that if we eat maximum candies every day we can reach the preferred one and the second half means that if we eat minimum candies (i.e. one candy) every day we won\'t pass the preferred one. \n\n**Implementation**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = [0]\n for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum \n return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`
6
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
Python - clear explanation and simple code
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Explanation:**\n\nLets take the below test case\n```\ncandiesCount = [7, 4, 5, 3, 8]\nqueries = [[0, 2, 2], [4, 2, 4], [2, 13, 1000000000]]\n```\n\nWe need to know the total number of candies available till ```i-1``` for each type ```i``` as we will have to eat all candies before ```i```th type. So we use accumulate.\n\n```accumulate``` will turn ```[7, 4, 5, 3, 8]``` to ```[7, 7 + 4, 7 + 4 + 5, 7 + 4 + 5 + 3, 7 + 4 + 5 + 3 + 8]``` = ```[7, 11, 16, 19, 27]```\n\nWe have two cases - for type 0 and type > 0. It can be generalised if we add a dummy 0 in candiesCount at the beginning.\n\n**Case 1: Type 0**\n* In the first query ```[0, 2, 2]```, you have to be able to eat type 0 candy on day 2 by not eating more than 2 candies on any given day.\n* Since its type 0 candy, there\'s no i-1. \n* So if type is 0, all you need to check is, whether the number of candies of 0th type (here, it\'s 7) is greater than the favourite day.\n* Why? - Because, even if you consider cap as 1, you can eat 1 candy each day and you\'ll have atleast one candy remaining on fav day.\n* Edge case: Number of candies = Number of days\n\t* Since we are starting at day 0, number of candies need to be greater than number of days.\n\t* Say you have 8 candies of type 0 and you fav day is 8. You will eat 1 candy each day from 0, 1,...till 7, so you will run out of candies on day 8.\n\n**Case 2: Type greater than 0**\n* If type is not 0, you need to eat all candies till i-1.\n* In this case, number of candies to eat is accumulated value till i-1 plus 1 candy of type i.\n\n\t```A = list(accumulate(candiesCount)) # equals [7, 11, 16, 19, 27]```\n\n* In the ```[4, 2, 4]``` query, fav type is 4. So you need to eat 19 candies (i-1) plus 1 = 20. This has to be done on day 2.\n* Since you can eat only max of 4 candies per day, 4 (day 0) + 4 (day 1) + 4 (day 2), you can eat only max of 12.\n* Suppose if you were able to eat 8 per day, then 8*3=24 which is greater than 20, so this is possible.\n\n* So, you need to check whether number of candies to be eaten is less than or equal to ```(day + 1) * cap``` --> day + 1 because we start at day 0\n* And you also need to check if number of candies you have is greater than number of days (this is same as case 1)\n* Reason - you may have 48 candies to eat but if day is 48, you won\'t have candy even if its cap is 1.\n\n**Code:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n if type == 0:\n res.append(A[0] > day)\n else:\n to_be_eaten = A[type-1] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type] > day)\n return res\n```\n\n**Generalised version for both cases by adding 0 in beginning:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = [0] + list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n to_be_eaten = A[type] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type + 1] > day)\n return res\n```
7
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python - clear explanation and simple code
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Explanation:**\n\nLets take the below test case\n```\ncandiesCount = [7, 4, 5, 3, 8]\nqueries = [[0, 2, 2], [4, 2, 4], [2, 13, 1000000000]]\n```\n\nWe need to know the total number of candies available till ```i-1``` for each type ```i``` as we will have to eat all candies before ```i```th type. So we use accumulate.\n\n```accumulate``` will turn ```[7, 4, 5, 3, 8]``` to ```[7, 7 + 4, 7 + 4 + 5, 7 + 4 + 5 + 3, 7 + 4 + 5 + 3 + 8]``` = ```[7, 11, 16, 19, 27]```\n\nWe have two cases - for type 0 and type > 0. It can be generalised if we add a dummy 0 in candiesCount at the beginning.\n\n**Case 1: Type 0**\n* In the first query ```[0, 2, 2]```, you have to be able to eat type 0 candy on day 2 by not eating more than 2 candies on any given day.\n* Since its type 0 candy, there\'s no i-1. \n* So if type is 0, all you need to check is, whether the number of candies of 0th type (here, it\'s 7) is greater than the favourite day.\n* Why? - Because, even if you consider cap as 1, you can eat 1 candy each day and you\'ll have atleast one candy remaining on fav day.\n* Edge case: Number of candies = Number of days\n\t* Since we are starting at day 0, number of candies need to be greater than number of days.\n\t* Say you have 8 candies of type 0 and you fav day is 8. You will eat 1 candy each day from 0, 1,...till 7, so you will run out of candies on day 8.\n\n**Case 2: Type greater than 0**\n* If type is not 0, you need to eat all candies till i-1.\n* In this case, number of candies to eat is accumulated value till i-1 plus 1 candy of type i.\n\n\t```A = list(accumulate(candiesCount)) # equals [7, 11, 16, 19, 27]```\n\n* In the ```[4, 2, 4]``` query, fav type is 4. So you need to eat 19 candies (i-1) plus 1 = 20. This has to be done on day 2.\n* Since you can eat only max of 4 candies per day, 4 (day 0) + 4 (day 1) + 4 (day 2), you can eat only max of 12.\n* Suppose if you were able to eat 8 per day, then 8*3=24 which is greater than 20, so this is possible.\n\n* So, you need to check whether number of candies to be eaten is less than or equal to ```(day + 1) * cap``` --> day + 1 because we start at day 0\n* And you also need to check if number of candies you have is greater than number of days (this is same as case 1)\n* Reason - you may have 48 candies to eat but if day is 48, you won\'t have candy even if its cap is 1.\n\n**Code:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n if type == 0:\n res.append(A[0] > day)\n else:\n to_be_eaten = A[type-1] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type] > day)\n return res\n```\n\n**Generalised version for both cases by adding 0 in beginning:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = [0] + list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n to_be_eaten = A[type] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type + 1] > day)\n return res\n```
7
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
✅prefix sum || python
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n for i in range(len(candiesCount)):\n if(i==0):continue\n candiesCount[i]+=candiesCount[i-1]\n ans=[]\n for q in queries:\n last=candiesCount[q[0]]-1\n first=0\n if(q[0]!=0):first=ceil((candiesCount[q[0]-1]+1)/q[2])-1\n if(q[1]>=first and q[1]<=last):ans.append(1)\n else:ans.append(0)\n # print(q,first,last,(candiesCount[q[0]-1])/q[2])\n return ans \n```
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
✅prefix sum || python
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n for i in range(len(candiesCount)):\n if(i==0):continue\n candiesCount[i]+=candiesCount[i-1]\n ans=[]\n for q in queries:\n last=candiesCount[q[0]]-1\n first=0\n if(q[0]!=0):first=ceil((candiesCount[q[0]-1]+1)/q[2])-1\n if(q[1]>=first and q[1]<=last):ans.append(1)\n else:ans.append(0)\n # print(q,first,last,(candiesCount[q[0]-1])/q[2])\n return ans \n```
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
python3 beats 98%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n presum = []\n res = []\n tot = 0\n presum.append(0)\n for e in candiesCount:\n tot+=e\n presum.append(tot)\n for type,day,cap in queries:\n day+=1\n min = day\n max = cap*day\n if min <= presum[type+1] and max > presum[type]:\n res.append(True)\n else:\n res.append(False)\n\n return res\n```
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
python3 beats 98%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n presum = []\n res = []\n tot = 0\n presum.append(0)\n for e in candiesCount:\n tot+=e\n presum.append(tot)\n for type,day,cap in queries:\n day+=1\n min = day\n max = cap*day\n if min <= presum[type+1] and max > presum[type]:\n res.append(True)\n else:\n res.append(False)\n\n return res\n```
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
Python | Prefix Sum | O(n) | 100% Faster
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
# Code\n```\nfrom itertools import accumulate\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = list(accumulate(candiesCount,initial = 0))\n res = []\n for t, d, c in queries:\n if prefix[t]//c <= d < prefix[t+1]:\n res.append(True)\n else:\n res.append(False)\n return res\n```
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python | Prefix Sum | O(n) | 100% Faster
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
# Code\n```\nfrom itertools import accumulate\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = list(accumulate(candiesCount,initial = 0))\n res = []\n for t, d, c in queries:\n if prefix[t]//c <= d < prefix[t+1]:\n res.append(True)\n else:\n res.append(False)\n return res\n```
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
Python O(N) Solution
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
Find the maximum number of candies you can eat before eating on the favorite day, and check if you can eat atleast 1 of your favorite candy on the favorite day.\nThe two hurdles to check are, \n* Overshooting the given targeting by eating the minimum number of candies (1) per day.\n* Undershooting it by not able to eat all the previous candies (UpperCap * FavoriteDay) until favorite day.\n\nSo just find the candies you need to eat before eating current candy and check whether it is within the specified range or not.\n```\ndef canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n c,n=[],0\n res=[]\n for i in candiesCount:\n n+=i\n c.append([n,i])\n for i in queries:\n if (c[i[0]][0]-c[i[0]][1]-i[2])>=i[1]*i[2] or c[i[0]][0]<=i[1]:\n res.append(False)\n else:\n res.append(True)\n return res\n```
1
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start eating candies on day `**0**`. * You **cannot** eat **any** candy of type `i` unless you have eaten **all** candies of type `i - 1`. * You must eat **at least** **one** candy per day until you have eaten all the candies. Construct a boolean array `answer` such that `answer.length == queries.length` and `answer[i]` is `true` if you can eat a candy of type `favoriteTypei` on day `favoriteDayi` without eating **more than** `dailyCapi` candies on **any** day, and `false` otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return _the constructed array_ `answer`. **Example 1:** **Input:** candiesCount = \[7,4,5,3,8\], queries = \[\[0,2,2\],\[4,2,4\],\[2,13,1000000000\]\] **Output:** \[true,false,true\] **Explanation:** 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. **Example 2:** **Input:** candiesCount = \[5,2,6,4,1\], queries = \[\[3,1,2\],\[4,10,3\],\[3,10,100\],\[4,100,30\],\[1,3,1\]\] **Output:** \[false,true,true,false,false\] **Constraints:** * `1 <= candiesCount.length <= 105` * `1 <= candiesCount[i] <= 105` * `1 <= queries.length <= 105` * `queries[i].length == 3` * `0 <= favoriteTypei < candiesCount.length` * `0 <= favoriteDayi <= 109` * `1 <= dailyCapi <= 109`
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python O(N) Solution
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
Find the maximum number of candies you can eat before eating on the favorite day, and check if you can eat atleast 1 of your favorite candy on the favorite day.\nThe two hurdles to check are, \n* Overshooting the given targeting by eating the minimum number of candies (1) per day.\n* Undershooting it by not able to eat all the previous candies (UpperCap * FavoriteDay) until favorite day.\n\nSo just find the candies you need to eat before eating current candy and check whether it is within the specified range or not.\n```\ndef canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n c,n=[],0\n res=[]\n for i in candiesCount:\n n+=i\n c.append([n,i])\n for i in queries:\n if (c[i[0]][0]-c[i[0]][1]-i[2])>=i[1]*i[2] or c[i[0]][0]<=i[1]:\n res.append(False)\n else:\n res.append(True)\n return res\n```
1
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
Beats 95%, Java
palindrome-partitioning-iv
1
1
# Intuition\n![Palindrome Partitioning IV - solution - Intuition 1.png](https://assets.leetcode.com/users/images/f587229c-1490-47ac-b758-f25d5362f365_1699694661.774286.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe are required to split the string into three parts, which means we need to find two breaking points for those. Let\'s call them `i` and `j`.\nEach substring is of `length > 0`. Let\'s call them `s1`, `s2`, and `s3`.\n`s1` can be of substring indexes between `[0, 1)` and `[0, n-2)`, which means `i` can of be `1 to n-2`\n`s2` can be of substring indexes between `[i, i+1)` and `[i, n-1)`, which means `j` can of be `i to n-1`\n`s3` can be of substring indexed from `j to n` (the remaining substring)\nWe can iterate for `i` in one loop -> $$O(n)$$, \nFor `j`, we would need to iterate over another loop -> $$O(n)$$\nWhen we check if all three strings are palindrome using traditional palindrome check algorithm for a string input, it will take O(n), and we have three strings -> $$O(n)$$\nHence overall computation would have resulted in $$O(n^3)$$\n\nBut since we have pre-computed the palindrome check in our method in dp before hand (in $$O(n^2)$$), we can now retrieve if a given substring is palindrome or not in $$O(1)$$.\nSo the overall time complexity of this approach is $$O(n^2 + n^2)$$ ~> $$O(n^2)$$\n\nTo get better understanding of how to build dp matrix, let us have a look at the diagram.\nWe first initialize matrix with `n*n` boolean, set to `false` for each cell. `n` here represents the total number of characters.\nHere intuition is that we want to take any substring `p`, and only when it\'s first and last characters match and (substring with 1 character removed from both sides is palindrome as saved in dp OR length of p is 1), then we set `dp[begin][end]` to `true`, i,e, \n`p[begin] == p[end]` `AND` (`p.substring(begin+1, end-1)` `OR` `len(p) == 1`)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean checkPartitioning(String s) {\n int N = s.length();\n char[] A = s.toCharArray();\n // initialize dp (On^2)\n boolean[][] dp = new boolean[N][N];\n for (int i = N - 1; i >= 0; --i) {\n for (int j = i; j < N; ++j) {\n dp[i][j] = (A[i] == A[j]) && (j - i < 2 || dp[i + 1][j - 1]);\n }\n }\n // find in dp if all three substrings are palindrome, worst case O(N^2)\n for (int i = 1; i < N - 1; ++i) {\n if (dp[0][i - 1]) {\n for (int j = i; j < N - 1; ++j) {\n if (dp[i][j]) {\n if (dp[j + 1][N - 1]) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n}\n```\n```python []\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n N = len(s)\n A = list(s)\n # initialize dp (On^2)\n dp = [[False] * N for _ in range(N)]\n for i in range(N - 1, -1, -1):\n for j in range(i, N):\n dp[i][j] = (A[i] == A[j]) and (j - i < 2 or dp[i + 1][j - 1])\n # find in dp if all three substrings are palindrome, worst case O(N^2)\n for i in range(1, N - 1):\n if dp[0][i - 1]:\n for j in range(i, N - 1):\n if dp[i][j] and dp[j + 1][N - 1]:\n return True\n return False\n```\n```cpp []\nclass Solution {\npublic:\n bool checkPartitioning(string s) {\n int N = s.length();\n std::vector<std::vector<bool>> dp(N, std::vector<bool>(N, false));\n std::vector<char> A(s.begin(), s.end());\n // initialize dp (On^2)\n for (int i = N - 1; i >= 0; --i) {\n for (int j = i; j < N; ++j) {\n dp[i][j] = (A[i] == A[j]) && (j - i < 2 || dp[i + 1][j - 1]);\n }\n }\n // find in dp if all three substrings are palindrome, worst case O(N^2)\n for (int i = 1; i < N - 1; ++i) {\n if (dp[0][i - 1]) {\n for (int j = i; j < N - 1; ++j) {\n if (dp[i][j] && dp[j + 1][N - 1]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n};\n```\n
1
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes. **Example 2:** **Input:** s = "bcbddxy " **Output:** false **Explanation:** s cannot be split into 3 palindromes. **Constraints:** * `3 <= s.length <= 2000` * `s`​​​​​​ consists only of lowercase English letters.
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
Beats 95%, Java
palindrome-partitioning-iv
1
1
# Intuition\n![Palindrome Partitioning IV - solution - Intuition 1.png](https://assets.leetcode.com/users/images/f587229c-1490-47ac-b758-f25d5362f365_1699694661.774286.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe are required to split the string into three parts, which means we need to find two breaking points for those. Let\'s call them `i` and `j`.\nEach substring is of `length > 0`. Let\'s call them `s1`, `s2`, and `s3`.\n`s1` can be of substring indexes between `[0, 1)` and `[0, n-2)`, which means `i` can of be `1 to n-2`\n`s2` can be of substring indexes between `[i, i+1)` and `[i, n-1)`, which means `j` can of be `i to n-1`\n`s3` can be of substring indexed from `j to n` (the remaining substring)\nWe can iterate for `i` in one loop -> $$O(n)$$, \nFor `j`, we would need to iterate over another loop -> $$O(n)$$\nWhen we check if all three strings are palindrome using traditional palindrome check algorithm for a string input, it will take O(n), and we have three strings -> $$O(n)$$\nHence overall computation would have resulted in $$O(n^3)$$\n\nBut since we have pre-computed the palindrome check in our method in dp before hand (in $$O(n^2)$$), we can now retrieve if a given substring is palindrome or not in $$O(1)$$.\nSo the overall time complexity of this approach is $$O(n^2 + n^2)$$ ~> $$O(n^2)$$\n\nTo get better understanding of how to build dp matrix, let us have a look at the diagram.\nWe first initialize matrix with `n*n` boolean, set to `false` for each cell. `n` here represents the total number of characters.\nHere intuition is that we want to take any substring `p`, and only when it\'s first and last characters match and (substring with 1 character removed from both sides is palindrome as saved in dp OR length of p is 1), then we set `dp[begin][end]` to `true`, i,e, \n`p[begin] == p[end]` `AND` (`p.substring(begin+1, end-1)` `OR` `len(p) == 1`)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean checkPartitioning(String s) {\n int N = s.length();\n char[] A = s.toCharArray();\n // initialize dp (On^2)\n boolean[][] dp = new boolean[N][N];\n for (int i = N - 1; i >= 0; --i) {\n for (int j = i; j < N; ++j) {\n dp[i][j] = (A[i] == A[j]) && (j - i < 2 || dp[i + 1][j - 1]);\n }\n }\n // find in dp if all three substrings are palindrome, worst case O(N^2)\n for (int i = 1; i < N - 1; ++i) {\n if (dp[0][i - 1]) {\n for (int j = i; j < N - 1; ++j) {\n if (dp[i][j]) {\n if (dp[j + 1][N - 1]) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n}\n```\n```python []\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n N = len(s)\n A = list(s)\n # initialize dp (On^2)\n dp = [[False] * N for _ in range(N)]\n for i in range(N - 1, -1, -1):\n for j in range(i, N):\n dp[i][j] = (A[i] == A[j]) and (j - i < 2 or dp[i + 1][j - 1])\n # find in dp if all three substrings are palindrome, worst case O(N^2)\n for i in range(1, N - 1):\n if dp[0][i - 1]:\n for j in range(i, N - 1):\n if dp[i][j] and dp[j + 1][N - 1]:\n return True\n return False\n```\n```cpp []\nclass Solution {\npublic:\n bool checkPartitioning(string s) {\n int N = s.length();\n std::vector<std::vector<bool>> dp(N, std::vector<bool>(N, false));\n std::vector<char> A(s.begin(), s.end());\n // initialize dp (On^2)\n for (int i = N - 1; i >= 0; --i) {\n for (int j = i; j < N; ++j) {\n dp[i][j] = (A[i] == A[j]) && (j - i < 2 || dp[i + 1][j - 1]);\n }\n }\n // find in dp if all three substrings are palindrome, worst case O(N^2)\n for (int i = 1; i < N - 1; ++i) {\n if (dp[0][i - 1]) {\n for (int j = i; j < N - 1; ++j) {\n if (dp[i][j] && dp[j + 1][N - 1]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n};\n```\n
1
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Simply Python O(N**2) | It is not hard
palindrome-partitioning-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n \'\'\'\n div into 3 palindrome parts, meaning one starts at begining, one ends at the end, of s\n 1. get the beginning palindrome candidates s[:i+1], save i to indicate its end (i+1 is starting of middle palindrome)\n 2. get the ending palindrome candidates s[j:], save j, save j to indicate the its beginning (j-1 is ending of middle palindrome)\n 3. iretatively check each beginning candidate and ending candidate, if remaining middle is non empty and fits the criteria, return True \n \'\'\'\n firsts_end, thirds_start = [], []\n \n for i in range(len(s)):\n if s[:i+1] == s[:i+1][::-1]:\n firsts_end.append(i)\n \n for i in range(len(s)):\n if s[i:] == s[i:][::-1]:\n thirds_start.append(i)\n \n # check\n for f in firsts_end:\n for t in reversed(thirds_start):\n second = s[f+1:t]\n if second == \'\': break\n if second == second[::-1]:\n return True\n\n # return \n return False \n```
2
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes. **Example 2:** **Input:** s = "bcbddxy " **Output:** false **Explanation:** s cannot be split into 3 palindromes. **Constraints:** * `3 <= s.length <= 2000` * `s`​​​​​​ consists only of lowercase English letters.
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
Simply Python O(N**2) | It is not hard
palindrome-partitioning-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n \'\'\'\n div into 3 palindrome parts, meaning one starts at begining, one ends at the end, of s\n 1. get the beginning palindrome candidates s[:i+1], save i to indicate its end (i+1 is starting of middle palindrome)\n 2. get the ending palindrome candidates s[j:], save j, save j to indicate the its beginning (j-1 is ending of middle palindrome)\n 3. iretatively check each beginning candidate and ending candidate, if remaining middle is non empty and fits the criteria, return True \n \'\'\'\n firsts_end, thirds_start = [], []\n \n for i in range(len(s)):\n if s[:i+1] == s[:i+1][::-1]:\n firsts_end.append(i)\n \n for i in range(len(s)):\n if s[i:] == s[i:][::-1]:\n thirds_start.append(i)\n \n # check\n for f in firsts_end:\n for t in reversed(thirds_start):\n second = s[f+1:t]\n if second == \'\': break\n if second == second[::-1]:\n return True\n\n # return \n return False \n```
2
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Python (Simple Maths)
palindrome-partitioning-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, s):\n if s == s[::-1]:\n return True\n\n def is_pal(t):\n return t == t[::-1]\n\n for i in range(1,len(s)+1):\n if is_pal(s[:i]):\n for j in range(i+1,len(s)):\n if is_pal(s[i:j]) and is_pal(s[j:]):\n return True\n\n return False\n\n```
1
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes. **Example 2:** **Input:** s = "bcbddxy " **Output:** false **Explanation:** s cannot be split into 3 palindromes. **Constraints:** * `3 <= s.length <= 2000` * `s`​​​​​​ consists only of lowercase English letters.
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
Python (Simple Maths)
palindrome-partitioning-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, s):\n if s == s[::-1]:\n return True\n\n def is_pal(t):\n return t == t[::-1]\n\n for i in range(1,len(s)+1):\n if is_pal(s[:i]):\n for j in range(i+1,len(s)):\n if is_pal(s[i:j]) and is_pal(s[j:]):\n return True\n\n return False\n\n```
1
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
✔ Python3 Solution | DP | Bit Manipulation | O(n^2)
palindrome-partitioning-iv
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, S):\n N = len(S)\n dp = [1] + [0] * N\n for i in range(2 * N - 1):\n l = i // 2\n r = l + (i & 1)\n while 0 <= l and r < N and S[l] == S[r]:\n dp[r + 1] |= (dp[l] << 1)\n l -= 1\n r += 1\n return bool(dp[-1] & (1 << 3))\n```
2
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes. **Example 2:** **Input:** s = "bcbddxy " **Output:** false **Explanation:** s cannot be split into 3 palindromes. **Constraints:** * `3 <= s.length <= 2000` * `s`​​​​​​ consists only of lowercase English letters.
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
✔ Python3 Solution | DP | Bit Manipulation | O(n^2)
palindrome-partitioning-iv
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, S):\n N = len(S)\n dp = [1] + [0] * N\n for i in range(2 * N - 1):\n l = i // 2\n r = l + (i & 1)\n while 0 <= l and r < N and S[l] == S[r]:\n dp[r + 1] |= (dp[l] << 1)\n l -= 1\n r += 1\n return bool(dp[-1] & (1 << 3))\n```
2
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
[Python3] dp
palindrome-partitioning-iv
0
1
**Algo**\nDefine `fn(i, k)` to be `True` if `s[i:]` can be split into `k` palindromic substrings. Then, \n\n`fn(i, k) = any(fn(ii+1, k-1) where s[i:ii] == s[i:ii][::-1]`\n\nHere we create a mapping to memoize all palindromic substrings starting from any given `i`. \n\n**Implementation**\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = {}\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp.setdefault(lo, set()).add(hi)\n lo -= 1\n hi += 1\n \n @lru_cache(None)\n def fn(i, k): \n """Return True if s[i:] can be split into k palindromic substrings."""\n if k < 0: return False \n if i == len(s): return k == 0\n return any(fn(ii+1, k-1) for ii in mp[i])\n \n return fn(0, 3)\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)`\n\nEdited on 2/1/2021\nAdding an alternative implementation\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = defaultdict(set)\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp[lo].add(hi)\n lo, hi = lo-1, hi+1\n \n for i in range(len(s)):\n for j in range(i+1, len(s)):\n if i-1 in mp[0] and j-1 in mp[i] and len(s)-1 in mp[j]: return True\n return False \n```
11
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes. **Example 2:** **Input:** s = "bcbddxy " **Output:** false **Explanation:** s cannot be split into 3 palindromes. **Constraints:** * `3 <= s.length <= 2000` * `s`​​​​​​ consists only of lowercase English letters.
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
[Python3] dp
palindrome-partitioning-iv
0
1
**Algo**\nDefine `fn(i, k)` to be `True` if `s[i:]` can be split into `k` palindromic substrings. Then, \n\n`fn(i, k) = any(fn(ii+1, k-1) where s[i:ii] == s[i:ii][::-1]`\n\nHere we create a mapping to memoize all palindromic substrings starting from any given `i`. \n\n**Implementation**\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = {}\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp.setdefault(lo, set()).add(hi)\n lo -= 1\n hi += 1\n \n @lru_cache(None)\n def fn(i, k): \n """Return True if s[i:] can be split into k palindromic substrings."""\n if k < 0: return False \n if i == len(s): return k == 0\n return any(fn(ii+1, k-1) for ii in mp[i])\n \n return fn(0, 3)\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)`\n\nEdited on 2/1/2021\nAdding an alternative implementation\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = defaultdict(set)\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp[lo].add(hi)\n lo, hi = lo-1, hi+1\n \n for i in range(len(s)):\n for j in range(i+1, len(s)):\n if i-1 in mp[0] and j-1 in mp[i] and len(s)-1 in mp[j]: return True\n return False \n```
11
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j] == '0'`. Return `true` _if you can reach index_ `s.length - 1` _in_ `s`_, or_ `false` _otherwise._ **Example 1:** **Input:** s = "011010 ", minJump = 2, maxJump = 3 **Output:** true **Explanation:** In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. **Example 2:** **Input:** s = "01101110 ", minJump = 2, maxJump = 3 **Output:** false **Constraints:** * `2 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`. * `s[0] == '0'` * `1 <= minJump <= maxJump < s.length`
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Very simple approach ᕙ(▀̿ĺ̯▀̿ ̿)ᕗ
sum-of-unique-elements
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a for loop and count.\n# Complexity\n- Time complexity: 35ms (Beats ***90.98%*** of users with Python3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.14 MB (Beats ***78.93%*** of users with Python3)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n sum = 0\n for i in nums:\n # This checks if a number appears once and if so, adds it onto the sum.\n if nums.count(i)==1:\n sum+=i\n return sum\n```
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Very simple approach ᕙ(▀̿ĺ̯▀̿ ̿)ᕗ
sum-of-unique-elements
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a for loop and count.\n# Complexity\n- Time complexity: 35ms (Beats ***90.98%*** of users with Python3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.14 MB (Beats ***78.93%*** of users with Python3)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n sum = 0\n for i in nums:\n # This checks if a number appears once and if so, adds it onto the sum.\n if nums.count(i)==1:\n sum+=i\n return sum\n```
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Easy solution using Hash Map !!
sum-of-unique-elements
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n dic=Counter(nums)\n c=0\n for i,j in dic.items():\n if j==1:\n c+=i\n return c\n```
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Easy solution using Hash Map !!
sum-of-unique-elements
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n dic=Counter(nums)\n c=0\n for i,j in dic.items():\n if j==1:\n c+=i\n return c\n```
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Simple 1 liner Python
sum-of-unique-elements
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n return sum([k for k,v in Counter(nums).items() if nums.count(k) == 1])\n```
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Simple 1 liner Python
sum-of-unique-elements
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n return sum([k for k,v in Counter(nums).items() if nums.count(k) == 1])\n```
2
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Python3 | Easy Solution | No Libraries | No skill | Beats 7.40%
sum-of-unique-elements
0
1
\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n totalSum = 0\n timesSeen = {}\n for num in nums:\n if num not in timesSeen:\n totalSum += num\n timesSeen[num] = 1\n elif num in timesSeen:\n # Turns out this number isn\'t unique, remove it from the sum\n if timesSeen[num] == 1:\n totalSum -= num\n timesSeen[num] += 1\n \n return totalSum\n\n```
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Python3 | Easy Solution | No Libraries | No skill | Beats 7.40%
sum-of-unique-elements
0
1
\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n totalSum = 0\n timesSeen = {}\n for num in nums:\n if num not in timesSeen:\n totalSum += num\n timesSeen[num] = 1\n elif num in timesSeen:\n # Turns out this number isn\'t unique, remove it from the sum\n if timesSeen[num] == 1:\n totalSum -= num\n timesSeen[num] += 1\n \n return totalSum\n\n```
2
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Described easily with example and solution in C++, Java, Python3, JavaScript
maximum-absolute-sum-of-any-subarray
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst approach is to get all the subarray. Then get the sum of all elements and absolute it for each subarray and take the maximum of them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBut problem is that we need pow(2,n) complexity time to get all subarrays and O(n) to get sum for each subarray. So the total time complexity will be O(n*pow(2,n)). So it will not work.\nIf we look carefully we can get result either from maximum sum or from minimum sum if it is negative. So it will be better if we take two variable one for local maximum and another for local minimum and we started traversing linearly from index 0. And every time cur_max will be maximum of cur_max and cur_max+value at ith index. Similarly for cur_minimum. And we need a global_max which will keep the maximum of all cur_max and global_min for all cur_min.\nLet\'s understand with an example..\nnums = [1,-3,2,3,-4]\ninitially g_max = Int_min, g_min = Int_max, cur_max = 0, cur_min = 0\nat index i=0\ncur_max = max(1,0+1) = 1, cur_min = min(1,0+1) = 1\ng_max = max(Int_min,1) = 1, g_min = min(Int_max,1) = 1\nat index i = 1\ncur_max = max(-3,1-3) = -2, cur_min = min(-3,1-3) = -3\ng_max = max(1,-2) = 1, g_min = min(1,-3) = -3\nat index i=2\ncur_max = max(2,-2+2) = 2, cur_min = min(2,-3+2) = -1\ng_max = max(1,2) = 2, g_min = min(-3,-1) = -3\nat index i =3\ncur_max = max(3,2+3) = 5, cur_min = min(3,-1+3) = 2\ng_max = max(2,5) = 5, g_min = min(-3,2) = -3\nat index i = 4\ncur_max = max(-4,5-4) = 1, cur_min = min(-4,2-4) = -4\ng_max = max(5,1) = 5, g_min = min(-3,-4) = -4\n\nSo at the end result = max(5,abs(-4)) = 5\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nHere we are traversing the whole array only one time. So time complexity will be O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nHere we are using only four variables for extra space. So Space Complexity will be constant i,e O(1)\n\n# Code\n- C++\n```\nclass Solution {\npublic:\n int maxAbsoluteSum(vector<int>& nums) {\n int maxi = INT_MIN, mini = INT_MAX;\n int cur_max = 0, cur_min = 0;\n for(int i=0; i<nums.size(); i++){\n cur_max = max(cur_max+nums[i],nums[i]);\n cur_min = min(cur_min+nums[i],nums[i]);\n maxi = max(maxi,cur_max);\n mini = min(mini,cur_min);\n }\n return max(maxi,-mini);\n\n }\n};\n```\n- Java\n```\nclass Solution {\n public int maxAbsoluteSum(int[] nums) {\n int maxi = Integer.MIN_VALUE, mini = Integer.MAX_VALUE;\n int cur_max = 0, cur_min = 0;\n for(int i=0; i<nums.length; i++){\n cur_max = Math.max(nums[i],cur_max+nums[i]);\n cur_min = Math.min(nums[i],cur_min+nums[i]);\n maxi = Math.max(cur_max,maxi);\n mini = Math.min(cur_min,mini);\n }\n return Math.max(maxi,-mini);\n }\n}\n```\n- Python3\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n maxi,mini = -2**31 , 2**31 -1\n cur_max,cur_min = 0,0\n for i in range(0,len(nums)):\n cur_max = max(cur_max+nums[i],nums[i]);\n cur_min = min(cur_min+nums[i],nums[i])\n maxi = max(cur_max,maxi)\n mini = min(cur_min,mini)\n return max(maxi,-mini)\n```\n- JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxAbsoluteSum = function(nums) {\n maxi = Number.MIN_VALUE , mini = Number.MAX_VALUE\n cur_max = 0, cur_min = 0\n for(let i=0; i<nums.length; i++){\n cur_max = Math.max(cur_max+nums[i],nums[i])\n cur_min = Math.min(cur_min+nums[i], nums[i])\n maxi = Math.max(maxi,cur_max)\n mini = Math.min(mini,cur_min)\n }\n return Math.max(maxi,-mini)\n};\n```\n\n\n
2
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Described easily with example and solution in C++, Java, Python3, JavaScript
maximum-absolute-sum-of-any-subarray
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst approach is to get all the subarray. Then get the sum of all elements and absolute it for each subarray and take the maximum of them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBut problem is that we need pow(2,n) complexity time to get all subarrays and O(n) to get sum for each subarray. So the total time complexity will be O(n*pow(2,n)). So it will not work.\nIf we look carefully we can get result either from maximum sum or from minimum sum if it is negative. So it will be better if we take two variable one for local maximum and another for local minimum and we started traversing linearly from index 0. And every time cur_max will be maximum of cur_max and cur_max+value at ith index. Similarly for cur_minimum. And we need a global_max which will keep the maximum of all cur_max and global_min for all cur_min.\nLet\'s understand with an example..\nnums = [1,-3,2,3,-4]\ninitially g_max = Int_min, g_min = Int_max, cur_max = 0, cur_min = 0\nat index i=0\ncur_max = max(1,0+1) = 1, cur_min = min(1,0+1) = 1\ng_max = max(Int_min,1) = 1, g_min = min(Int_max,1) = 1\nat index i = 1\ncur_max = max(-3,1-3) = -2, cur_min = min(-3,1-3) = -3\ng_max = max(1,-2) = 1, g_min = min(1,-3) = -3\nat index i=2\ncur_max = max(2,-2+2) = 2, cur_min = min(2,-3+2) = -1\ng_max = max(1,2) = 2, g_min = min(-3,-1) = -3\nat index i =3\ncur_max = max(3,2+3) = 5, cur_min = min(3,-1+3) = 2\ng_max = max(2,5) = 5, g_min = min(-3,2) = -3\nat index i = 4\ncur_max = max(-4,5-4) = 1, cur_min = min(-4,2-4) = -4\ng_max = max(5,1) = 5, g_min = min(-3,-4) = -4\n\nSo at the end result = max(5,abs(-4)) = 5\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nHere we are traversing the whole array only one time. So time complexity will be O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nHere we are using only four variables for extra space. So Space Complexity will be constant i,e O(1)\n\n# Code\n- C++\n```\nclass Solution {\npublic:\n int maxAbsoluteSum(vector<int>& nums) {\n int maxi = INT_MIN, mini = INT_MAX;\n int cur_max = 0, cur_min = 0;\n for(int i=0; i<nums.size(); i++){\n cur_max = max(cur_max+nums[i],nums[i]);\n cur_min = min(cur_min+nums[i],nums[i]);\n maxi = max(maxi,cur_max);\n mini = min(mini,cur_min);\n }\n return max(maxi,-mini);\n\n }\n};\n```\n- Java\n```\nclass Solution {\n public int maxAbsoluteSum(int[] nums) {\n int maxi = Integer.MIN_VALUE, mini = Integer.MAX_VALUE;\n int cur_max = 0, cur_min = 0;\n for(int i=0; i<nums.length; i++){\n cur_max = Math.max(nums[i],cur_max+nums[i]);\n cur_min = Math.min(nums[i],cur_min+nums[i]);\n maxi = Math.max(cur_max,maxi);\n mini = Math.min(cur_min,mini);\n }\n return Math.max(maxi,-mini);\n }\n}\n```\n- Python3\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n maxi,mini = -2**31 , 2**31 -1\n cur_max,cur_min = 0,0\n for i in range(0,len(nums)):\n cur_max = max(cur_max+nums[i],nums[i]);\n cur_min = min(cur_min+nums[i],nums[i])\n maxi = max(cur_max,maxi)\n mini = min(cur_min,mini)\n return max(maxi,-mini)\n```\n- JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxAbsoluteSum = function(nums) {\n maxi = Number.MIN_VALUE , mini = Number.MAX_VALUE\n cur_max = 0, cur_min = 0\n for(let i=0; i<nums.length; i++){\n cur_max = Math.max(cur_max+nums[i],nums[i])\n cur_min = Math.min(cur_min+nums[i], nums[i])\n maxi = Math.max(maxi,cur_max)\n mini = Math.min(mini,cur_min)\n }\n return Math.max(maxi,-mini)\n};\n```\n\n\n
2
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
[Python3] Kadane's algo
maximum-absolute-sum-of-any-subarray
0
1
**Algo**\nExtend Kadane\'s algo by keeping track of max and min of subarray sum respectively. \n\n**Implementation**\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ans = max(ans, mx, -mn)\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(1)`
14
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
[Python3] Kadane's algo
maximum-absolute-sum-of-any-subarray
0
1
**Algo**\nExtend Kadane\'s algo by keeping track of max and min of subarray sum respectively. \n\n**Implementation**\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ans = max(ans, mx, -mn)\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(1)`
14
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
📌📌 Greedy and Easy Approach 🐍
maximum-absolute-sum-of-any-subarray
0
1
## IDEA :\n*Our target is to find the maximum/minimum subarray sum and choose maximum absolute value between them.*\nThis situation is suited for adopting **Kadane\'s algorithm**.\n\n\'\'\'\n\n\tclass Solution:\n\t\tdef maxAbsoluteSum(self, A):\n\n\t\t\tma,mi,res = 0,0,0\n\t\t\tfor a in A:\n\t\t\t\tma = max(0,ma+a)\n\t\t\t\tmi = min(0,mi+a)\n\t\t\t\tres = max(res,ma,-mi)\n\t\t\treturn res\n\t\t\t\n### TThanks and Upvote if you like the Idea!!\u270C
4
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
📌📌 Greedy and Easy Approach 🐍
maximum-absolute-sum-of-any-subarray
0
1
## IDEA :\n*Our target is to find the maximum/minimum subarray sum and choose maximum absolute value between them.*\nThis situation is suited for adopting **Kadane\'s algorithm**.\n\n\'\'\'\n\n\tclass Solution:\n\t\tdef maxAbsoluteSum(self, A):\n\n\t\t\tma,mi,res = 0,0,0\n\t\t\tfor a in A:\n\t\t\t\tma = max(0,ma+a)\n\t\t\t\tmi = min(0,mi+a)\n\t\t\t\tres = max(res,ma,-mi)\n\t\t\treturn res\n\t\t\t\n### TThanks and Upvote if you like the Idea!!\u270C
4
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
Python3 Double Kadane's
maximum-absolute-sum-of-any-subarray
0
1
Use of one kadane\'s algorithm to compute max absolute sum and anothe kadane\'s to compute min absolute sum, return max comparing both\n\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n min_sum = nums[0]\n curr_min = nums[0]\n \n max_sum = nums[0]\n curr_max = max_sum\n \n for i in range(1, len(nums)):\n curr_max = max(nums[i], curr_max + nums[i])\n max_sum = max(curr_max, max_sum)\n \n for i in range(1, len(nums)):\n curr_min = min(nums[i], curr_min + nums[i])\n min_sum = min(curr_min, min_sum)\n \n return max(abs(max_sum), abs(min_sum))\n```
5
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Python3 Double Kadane's
maximum-absolute-sum-of-any-subarray
0
1
Use of one kadane\'s algorithm to compute max absolute sum and anothe kadane\'s to compute min absolute sum, return max comparing both\n\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n min_sum = nums[0]\n curr_min = nums[0]\n \n max_sum = nums[0]\n curr_max = max_sum\n \n for i in range(1, len(nums)):\n curr_max = max(nums[i], curr_max + nums[i])\n max_sum = max(curr_max, max_sum)\n \n for i in range(1, len(nums)):\n curr_min = min(nums[i], curr_min + nums[i])\n min_sum = min(curr_min, min_sum)\n \n return max(abs(max_sum), abs(min_sum))\n```
5
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
O(N) solution with intution for how to arrive to it from the naive solution using logical steps
maximum-absolute-sum-of-any-subarray
0
1
# Intuition & Approach\nfirst, we see the most obvious algorithm:\n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n m = 0\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n m = max(m, sum(nums[i:j]))\n return m\n```\n\nThis algorithm is $$O(n^3)$$, which is much too slow. However, it does latch us on to the right solution, by letting us observe where we are running duplicated computation.\n\nFirst, we see that we are calling `sum` way too often. A very common way to reduce this is to use a prefix sum. \n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n prefix = []\n p = 0\n for n in nums:\n prefix.append(p)\n p += n\n prefix.append(p)\n m = 0\n for i in range(len(nums) + 1):\n for j in range(i, len(nums) + 1):\n m = max(m, abs(prefix[j] - prefix[i]))\n return m\n```\nNow, we removed that call to `sum` by iteratively adding up all the elements, and storing the intermediate computation one at a time.\n\nso, this now computes `sum[i:j]` in $$O(1)$$ time, after our prefix sum precomputation.\n\nHowever, in this code, we can think about exactly when `prefix[j] - prefix[i]` will be maximal. This will be the case exactly when we have the maximal value in our `prefix` array set to `prefix[j]` and the minimal one set to `prefix[i]`. So, we can skip this $$O(n^2)$$ computation and immediately search for these maximal and minimal elements. This produces the code given in the Code section.\n\n# Complexity\n- Time complexity: $$O(N)$$. Nice and optimal.\n\n- Space complexity: $$O(N)$$. We can improve this to $$O(1)$$ if we store only the max and min values in our prefix sum. This only requires a small change in the code. \n\n# Code\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n prefix = []\n p = 0\n for n in nums:\n prefix.append(p)\n p += n\n prefix.append(p)\n return abs(max(prefix) - min(prefix))\n\n```
0
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
O(N) solution with intution for how to arrive to it from the naive solution using logical steps
maximum-absolute-sum-of-any-subarray
0
1
# Intuition & Approach\nfirst, we see the most obvious algorithm:\n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n m = 0\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n m = max(m, sum(nums[i:j]))\n return m\n```\n\nThis algorithm is $$O(n^3)$$, which is much too slow. However, it does latch us on to the right solution, by letting us observe where we are running duplicated computation.\n\nFirst, we see that we are calling `sum` way too often. A very common way to reduce this is to use a prefix sum. \n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n prefix = []\n p = 0\n for n in nums:\n prefix.append(p)\n p += n\n prefix.append(p)\n m = 0\n for i in range(len(nums) + 1):\n for j in range(i, len(nums) + 1):\n m = max(m, abs(prefix[j] - prefix[i]))\n return m\n```\nNow, we removed that call to `sum` by iteratively adding up all the elements, and storing the intermediate computation one at a time.\n\nso, this now computes `sum[i:j]` in $$O(1)$$ time, after our prefix sum precomputation.\n\nHowever, in this code, we can think about exactly when `prefix[j] - prefix[i]` will be maximal. This will be the case exactly when we have the maximal value in our `prefix` array set to `prefix[j]` and the minimal one set to `prefix[i]`. So, we can skip this $$O(n^2)$$ computation and immediately search for these maximal and minimal elements. This produces the code given in the Code section.\n\n# Complexity\n- Time complexity: $$O(N)$$. Nice and optimal.\n\n- Space complexity: $$O(N)$$. We can improve this to $$O(1)$$ if we store only the max and min values in our prefix sum. This only requires a small change in the code. \n\n# Code\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n prefix = []\n p = 0\n for n in nums:\n prefix.append(p)\n p += n\n prefix.append(p)\n return abs(max(prefix) - min(prefix))\n\n```
0
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid. * Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order. Return `true` _if it is possible to split_ `s`​​​​​​ _as described above__, or_ `false` _otherwise._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "1234 " **Output:** false **Explanation:** There is no valid way to split s. **Example 2:** **Input:** s = "050043 " **Output:** true **Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\]. The values are in descending order with adjacent values differing by 1. **Example 3:** **Input:** s = "9080701 " **Output:** false **Explanation:** There is no valid way to split s. **Constraints:** * `1 <= s.length <= 20` * `s` only consists of digits.
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
Python easy sol. using two pointers
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n f,r=0,len(s)-1\n while f<=r:\n if f==r and s[f]==s[r]:\n return 1\n if s[f]!=s[r]:\n return r-f+1\n e1,e2=f,r\n while e1<r and s[e1]==s[f]:\n e1+=1\n f=e1\n while e2>=0 and s[e2]==s[r]:\n e2-=1\n r=e2\n return 0\n```
1
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python easy sol. using two pointers
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n f,r=0,len(s)-1\n while f<=r:\n if f==r and s[f]==s[r]:\n return 1\n if s[f]!=s[r]:\n return r-f+1\n e1,e2=f,r\n while e1<r and s[e1]==s[f]:\n e1+=1\n f=e1\n while e2>=0 and s[e2]==s[r]:\n e2-=1\n r=e2\n return 0\n```
1
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
C++ / Python simple solution
minimum-length-of-string-after-deleting-similar-ends
0
1
**C++ :**\n\n```\nint minimumLength(string s) {\n\tif(s.length() <= 1)\n\t\treturn s.length();\n\n\tint l = 0, r = s.length() - 1;\n\n\twhile(l < r && s[l] == s[r])\n\t{\n\t\tchar ch = s[l];\n\n\t\twhile(l <= r && s[l] == ch)\n\t\t\t++l;\n\n\t\twhile(l <= r && s[r] == ch)\n\t\t\t--r;\n\n\t}\n\n\treturn r - l + 1;\n}\n```\n\n**Python :**\n\n```\ndef minimumLength(self, s: str) -> int:\n\tif len(s) <= 1:\n\t\treturn len(s)\n\n\twhile len(s) > 1 and s[0] == s[-1]:\n\t\ti = 0\n\t\twhile i + 1 < len(s) and s[i] == s[i + 1]:\n\t\t\ti += 1\n\n\t\tj = len(s) - 1\n\t\twhile j - 1 > 0 and s[j] == s[j - 1] and j != i:\n\t\t\tj -= 1\n\n\t\ts = s[i + 1:j]\n\n\treturn len(s)\n```\n\n**Like it ? please upvote !**
9
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
C++ / Python simple solution
minimum-length-of-string-after-deleting-similar-ends
0
1
**C++ :**\n\n```\nint minimumLength(string s) {\n\tif(s.length() <= 1)\n\t\treturn s.length();\n\n\tint l = 0, r = s.length() - 1;\n\n\twhile(l < r && s[l] == s[r])\n\t{\n\t\tchar ch = s[l];\n\n\t\twhile(l <= r && s[l] == ch)\n\t\t\t++l;\n\n\t\twhile(l <= r && s[r] == ch)\n\t\t\t--r;\n\n\t}\n\n\treturn r - l + 1;\n}\n```\n\n**Python :**\n\n```\ndef minimumLength(self, s: str) -> int:\n\tif len(s) <= 1:\n\t\treturn len(s)\n\n\twhile len(s) > 1 and s[0] == s[-1]:\n\t\ti = 0\n\t\twhile i + 1 < len(s) and s[i] == s[i + 1]:\n\t\t\ti += 1\n\n\t\tj = len(s) - 1\n\t\twhile j - 1 > 0 and s[j] == s[j - 1] and j != i:\n\t\t\tj -= 1\n\n\t\ts = s[i + 1:j]\n\n\treturn len(s)\n```\n\n**Like it ? please upvote !**
9
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python || 96.67% Faster || Two Pointers || O(n) Solution
minimum-length-of-string-after-deleting-similar-ends
0
1
```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n i,j=0,len(s)-1\n while i<j and s[i]==s[j]:\n t=s[i]\n while i<len(s) and s[i]==t:\n i+=1\n while j>=0 and s[j]==t:\n j-=1\n if j<i:\n return 0\n return j-i+1\n```\n\n**An upvote will be encouraging**
5
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python || 96.67% Faster || Two Pointers || O(n) Solution
minimum-length-of-string-after-deleting-similar-ends
0
1
```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n i,j=0,len(s)-1\n while i<j and s[i]==s[j]:\n t=s[i]\n while i<len(s) and s[i]==t:\n i+=1\n while j>=0 and s[j]==t:\n j-=1\n if j<i:\n return 0\n return j-i+1\n```\n\n**An upvote will be encouraging**
5
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Exactly as the hint says | commented and explained
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBuild your algorithm off of the hints and examples \nMake a can run algorithm checker with the edge cases to prevent need to check in the algorithm itself \nMake an algorithm function that given a string to modify and knowing that it can be modified, modifies according to the hints in the problem \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe can run algorithm when given a string to modify checks two things and uses that to determine output \n- if string to modify is 1 char or less, return False \n- else if string to modify does not have matching character start and end return False \n- otherwise return True \n\nThe algorithm works by doing as follows for a string to modify that can be\n- get the length of the string currently \n- get the front index and back index then set as 0 and 1 less then length \n- set move front to true and move back to true \n- set char match as string to modify at 0 \n- while front index + 1 is lte back index - 1 \n - get next char front and next char back as one forward and one back \n - set move front and move back as bools of whether or not the next of each match the char match \n - increment front index by status of move front and decrement back index by status of move back \n - if move front and move back are both False, break \n- if front index is gte back index, return empty string \n- otherwise, return string to modify from front index + 1 to back index \n\nThe solution then is as follows \n- set can run to result of can run algorithm on s \n- while can run \n - s = run algorithm on s \n - can run = can run algorithm on s \n- return len of s \n\n# Complexity\n- Time complexity : O(SL) \n - At worst, you need to traverse string length \n\n- Space complexity : O(1) \n - No aditional storage is used, all is internally referencing \n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n # pick non-empty prefix from string s where all the characters in the prefix are equal \n # pick non-empty suffix from string s where all the characters in the suffix are equal \n # prefix and suffix must not intersect at any index \n # characters must be the same for prefix and suffix \n # remove both the prefix and the suffix \n # checker to see if we can run algorithm any longer according to hint \n def can_run_algorithm(string_to_modify) : \n if len(string_to_modify) <= 1 : \n return False \n elif (string_to_modify[0] != string_to_modify[-1]) : \n return False \n else : \n return True \n\n # running of the algorithm \n def run_algorithm(string_to_modify) : \n # get length \n stml = len(string_to_modify)\n # find front and back \n front_index = 0 \n back_index = stml - 1 \n # decide if you can or cannot move \n move_front = True \n move_back = True \n # decide what you must currently match \n char_match = string_to_modify[0] \n # prevent overlap with one look ahead \n while front_index + 1 <= back_index - 1 : \n # get next char front and back, even if would abut one another \n next_char_front = string_to_modify[front_index + 1] \n next_char_back = string_to_modify[back_index - 1] \n # set move determination appropriately \n move_front = next_char_front == char_match \n move_back = next_char_back == char_match \n # based on that, decide movement \n front_index += move_front\n back_index -= move_back\n # include optional break once matched \n if move_front == move_back == False : \n break\n # if overlapped -> null string return \n if front_index >= back_index : \n return "" \n else : \n # otherwise from front index plus 1 to back index non inclusive is returned \n return string_to_modify[front_index + 1 : back_index]\n\n # determine if you can run algorithm on s currently \n can_run = can_run_algorithm(s) \n # while you can \n while can_run : \n # run it, and see if you can go again \n s = run_algorithm(s)\n can_run = can_run_algorithm(s)\n\n # return length when finished \n return len(s) \n\n```
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Exactly as the hint says | commented and explained
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBuild your algorithm off of the hints and examples \nMake a can run algorithm checker with the edge cases to prevent need to check in the algorithm itself \nMake an algorithm function that given a string to modify and knowing that it can be modified, modifies according to the hints in the problem \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe can run algorithm when given a string to modify checks two things and uses that to determine output \n- if string to modify is 1 char or less, return False \n- else if string to modify does not have matching character start and end return False \n- otherwise return True \n\nThe algorithm works by doing as follows for a string to modify that can be\n- get the length of the string currently \n- get the front index and back index then set as 0 and 1 less then length \n- set move front to true and move back to true \n- set char match as string to modify at 0 \n- while front index + 1 is lte back index - 1 \n - get next char front and next char back as one forward and one back \n - set move front and move back as bools of whether or not the next of each match the char match \n - increment front index by status of move front and decrement back index by status of move back \n - if move front and move back are both False, break \n- if front index is gte back index, return empty string \n- otherwise, return string to modify from front index + 1 to back index \n\nThe solution then is as follows \n- set can run to result of can run algorithm on s \n- while can run \n - s = run algorithm on s \n - can run = can run algorithm on s \n- return len of s \n\n# Complexity\n- Time complexity : O(SL) \n - At worst, you need to traverse string length \n\n- Space complexity : O(1) \n - No aditional storage is used, all is internally referencing \n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n # pick non-empty prefix from string s where all the characters in the prefix are equal \n # pick non-empty suffix from string s where all the characters in the suffix are equal \n # prefix and suffix must not intersect at any index \n # characters must be the same for prefix and suffix \n # remove both the prefix and the suffix \n # checker to see if we can run algorithm any longer according to hint \n def can_run_algorithm(string_to_modify) : \n if len(string_to_modify) <= 1 : \n return False \n elif (string_to_modify[0] != string_to_modify[-1]) : \n return False \n else : \n return True \n\n # running of the algorithm \n def run_algorithm(string_to_modify) : \n # get length \n stml = len(string_to_modify)\n # find front and back \n front_index = 0 \n back_index = stml - 1 \n # decide if you can or cannot move \n move_front = True \n move_back = True \n # decide what you must currently match \n char_match = string_to_modify[0] \n # prevent overlap with one look ahead \n while front_index + 1 <= back_index - 1 : \n # get next char front and back, even if would abut one another \n next_char_front = string_to_modify[front_index + 1] \n next_char_back = string_to_modify[back_index - 1] \n # set move determination appropriately \n move_front = next_char_front == char_match \n move_back = next_char_back == char_match \n # based on that, decide movement \n front_index += move_front\n back_index -= move_back\n # include optional break once matched \n if move_front == move_back == False : \n break\n # if overlapped -> null string return \n if front_index >= back_index : \n return "" \n else : \n # otherwise from front index plus 1 to back index non inclusive is returned \n return string_to_modify[front_index + 1 : back_index]\n\n # determine if you can run algorithm on s currently \n can_run = can_run_algorithm(s) \n # while you can \n while can_run : \n # run it, and see if you can go again \n s = run_algorithm(s)\n can_run = can_run_algorithm(s)\n\n # return length when finished \n return len(s) \n\n```
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python easy two pointer solution with explanation
minimum-length-of-string-after-deleting-similar-ends
0
1
\n# Approach\nUse 2 pointers, `i` and `j`, initialize at 0 and `n-1` respectively\nWe also need to keep track of `currChar` which is the char at which both pointers last matched \n\n`if` chars at i and j are equal:\n- move both pointers\n\n`else:` \n- If either of the pointers is equal to `currChar` move that pointer, this means that we have a sequence of matching chars and we can increase the substring on the matching side. For example: **aaba**, left substring will be ***aa*** and the right ***a***\n- If nothing matches, this means we can\'t move ahead anymore `break`\n\n\nWe keep doing this until the pointers cross or we break\n\nWe return length of the string that\'s left behind based on the final positions of i and j\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n\n i=0\n j=len(s)-1\n n=len(s)\n currChar=""\n\n while(i<=j):\n if(s[i]==s[j] and i!=j):\n currChar=s[i]\n j-=1\n i+=1\n else:\n if(s[i]==currChar):\n i+=1\n continue\n if(s[j]==currChar):\n j-=1\n continue \n break\n\n return j+1-i\n \n\n \n```
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python easy two pointer solution with explanation
minimum-length-of-string-after-deleting-similar-ends
0
1
\n# Approach\nUse 2 pointers, `i` and `j`, initialize at 0 and `n-1` respectively\nWe also need to keep track of `currChar` which is the char at which both pointers last matched \n\n`if` chars at i and j are equal:\n- move both pointers\n\n`else:` \n- If either of the pointers is equal to `currChar` move that pointer, this means that we have a sequence of matching chars and we can increase the substring on the matching side. For example: **aaba**, left substring will be ***aa*** and the right ***a***\n- If nothing matches, this means we can\'t move ahead anymore `break`\n\n\nWe keep doing this until the pointers cross or we break\n\nWe return length of the string that\'s left behind based on the final positions of i and j\n\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n\n i=0\n j=len(s)-1\n n=len(s)\n currChar=""\n\n while(i<=j):\n if(s[i]==s[j] and i!=j):\n currChar=s[i]\n j-=1\n i+=1\n else:\n if(s[i]==currChar):\n i+=1\n continue\n if(s[j]==currChar):\n j-=1\n continue \n break\n\n return j+1-i\n \n\n \n```
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python Efficient Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n l, r = 0, len(s) - 1\n while l < r and s[l] == s[r]:\n p = s[l]\n while l <= r and s[l] == p:\n l += 1\n while l <= r and s[r] == p:\n r -= 1\n return r - l + 1\n```
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python Efficient Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n l, r = 0, len(s) - 1\n while l < r and s[l] == s[r]:\n p = s[l]\n while l <= r and s[l] == p:\n l += 1\n while l <= r and s[r] == p:\n r -= 1\n return r - l + 1\n```
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Beats 99.4 % in python O(N) TC & O(1) SC
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nprefix and suffix need to be same \n# Approach\n<!-- Describe your approach to solving the problem. -->\n2 pointer\n* l and r pointer at extreme ends\n* hold right pointer until left get mismatched and inrease l\n* same for left increement rit\n* anytime you get mismatch just break\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n n=len(s)\n l,r=0,n-1\n temp=\'\'\n while l < r:\n if s[l] != s[r]:\n break\n else:\n temp = s[r]\n while l <= r and s[l] == s[r]:\n l+=1\n while l <= r and s[r] == temp :\n r-=1\n if l > r:\n return 0\n return r-l +1\n \n\n```
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Beats 99.4 % in python O(N) TC & O(1) SC
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nprefix and suffix need to be same \n# Approach\n<!-- Describe your approach to solving the problem. -->\n2 pointer\n* l and r pointer at extreme ends\n* hold right pointer until left get mismatched and inrease l\n* same for left increement rit\n* anytime you get mismatch just break\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n n=len(s)\n l,r=0,n-1\n temp=\'\'\n while l < r:\n if s[l] != s[r]:\n break\n else:\n temp = s[r]\n while l <= r and s[l] == s[r]:\n l+=1\n while l <= r and s[r] == temp :\n r-=1\n if l > r:\n return 0\n return r-l +1\n \n\n```
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python Easy Solution || Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n start=0\n end=len(s)-1\n if len(set(s))==1 and len(s)>1:\n return 0\n while(start<end):\n if s[start]==s[end]:\n while(s[start]==s[start+1]):\n start+=1\n while(s[end]==s[end-1]):\n end-=1\n else:\n break\n start+=1\n end-=1\n if end<start:\n return 0\n return end-start+1\n```
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python Easy Solution || Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n start=0\n end=len(s)-1\n if len(set(s))==1 and len(s)>1:\n return 0\n while(start<end):\n if s[start]==s[end]:\n while(s[start]==s[start+1]):\n start+=1\n while(s[end]==s[end-1]):\n end-=1\n else:\n break\n start+=1\n end-=1\n if end<start:\n return 0\n return end-start+1\n```
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, when `num = "5489355142 "`: * The 1st smallest wonderful integer is `"5489355214 "`. * The 2nd smallest wonderful integer is `"5489355241 "`. * The 3rd smallest wonderful integer is `"5489355412 "`. * The 4th smallest wonderful integer is `"5489355421 "`. Return _the **minimum number of adjacent digit swaps** that needs to be applied to_ `num` _to reach the_ `kth` _**smallest wonderful** integer_. The tests are generated in such a way that `kth` smallest wonderful integer exists. **Example 1:** **Input:** num = "5489355142 ", k = 4 **Output:** 2 **Explanation:** The 4th smallest wonderful number is "5489355421 ". To get this number: - Swap index 7 with index 8: "5489355142 " -> "5489355412 " - Swap index 8 with index 9: "5489355412 " -> "5489355421 " **Example 2:** **Input:** num = "11112 ", k = 4 **Output:** 4 **Explanation:** The 4th smallest wonderful number is "21111 ". To get this number: - Swap index 3 with index 4: "11112 " -> "11121 " - Swap index 2 with index 3: "11121 " -> "11211 " - Swap index 1 with index 2: "11211 " -> "12111 " - Swap index 0 with index 1: "12111 " -> "21111 " **Example 3:** **Input:** num = "00123 ", k = 1 **Output:** 1 **Explanation:** The 1st smallest wonderful number is "00132 ". To get this number: - Swap index 3 with index 4: "00123 " -> "00132 " **Constraints:** * `2 <= num.length <= 1000` * `1 <= k <= 1000` * `num` only consists of digits.
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
EASY PYTHON SOLUTION USING DP || GREEDY || SORTING
maximum-number-of-events-that-can-be-attended-ii
0
1
# Intuition\nThe question is similar to what we do in meeting problems in greedy but the catch here is that now it has some reward attached to it which makes it a dp problem. Now we have to look for time a meeting ends as well as the value it brings on attending it. \n\n# Approach\nSorting and DP\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n^3)\n\n# Code\n```\nclass Solution:\n def dp(self,i,events,k,timeBooked,dct):\n if i<0 or k==0:\n return 0\n x=0\n if (i,k,timeBooked) in dct:\n return dct[(i,k,timeBooked)]\n if events[i][1]<timeBooked:\n x=self.dp(i-1,events,k-1,events[i][0],dct)+events[i][2]\n y=self.dp(i-1,events,k,timeBooked,dct)\n dct[(i,k,timeBooked)]=max(x,y)\n return max(x,y)\n \n def maxValue(self, events: List[List[int]], k: int) -> int:\n n=len(events)\n dct={}\n events.sort(key=lambda x:x[1])\n return self.dp(n-1,events,k,float("infinity"),dct)\n```
3
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
EASY PYTHON SOLUTION USING DP || GREEDY || SORTING
maximum-number-of-events-that-can-be-attended-ii
0
1
# Intuition\nThe question is similar to what we do in meeting problems in greedy but the catch here is that now it has some reward attached to it which makes it a dp problem. Now we have to look for time a meeting ends as well as the value it brings on attending it. \n\n# Approach\nSorting and DP\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(n^3)\n\n# Code\n```\nclass Solution:\n def dp(self,i,events,k,timeBooked,dct):\n if i<0 or k==0:\n return 0\n x=0\n if (i,k,timeBooked) in dct:\n return dct[(i,k,timeBooked)]\n if events[i][1]<timeBooked:\n x=self.dp(i-1,events,k-1,events[i][0],dct)+events[i][2]\n y=self.dp(i-1,events,k,timeBooked,dct)\n dct[(i,k,timeBooked)]=max(x,y)\n return max(x,y)\n \n def maxValue(self, events: List[List[int]], k: int) -> int:\n n=len(events)\n dct={}\n events.sort(key=lambda x:x[1])\n return self.dp(n-1,events,k,float("infinity"),dct)\n```
3
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python3 Solution
maximum-number-of-events-that-can-be-attended-ii
0
1
\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort(key=lambda ans:ans[1])\n dp=[[0,0]]\n dp2=[[0,0]]\n for x in range(k):\n for s,e,v in events:\n i=bisect.bisect(dp,[s])-1\n if dp[i][1]+v>dp2[-1][1]:\n dp2.append([e,dp[i][1]+v])\n\n dp=dp2\n dp2=[[0,0]]\n\n return dp[-1][-1] \n```
2
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Python3 Solution
maximum-number-of-events-that-can-be-attended-ii
0
1
\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort(key=lambda ans:ans[1])\n dp=[[0,0]]\n dp2=[[0,0]]\n for x in range(k):\n for s,e,v in events:\n i=bisect.bisect(dp,[s])-1\n if dp[i][1]+v>dp2[-1][1]:\n dp2.append([e,dp[i][1]+v])\n\n dp=dp2\n dp2=[[0,0]]\n\n return dp[-1][-1] \n```
2
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Leave it or take it DP
maximum-number-of-events-that-can-be-attended-ii
0
1
T: O(nlogn+nk)\ns:O(nk)\n\n# Code\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort()\n n=len(events)\n dp=[[-1]*n for _ in range(k)]\n def choice(index,count,end):\n if count==k or index==n:\n return 0\n if events[index][0]<=end:\n return choice(index+1,count,end)\n if dp[count][index]!=-1:\n return dp[count][index]\n\n dp[count][index]=max(choice(index+1,count+1,events[index][1])+events[index][2],choice(index+1,count,end))\n return dp[count][index]\n\n return choice(0,0,-1)\n \n\n\n \n```
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Leave it or take it DP
maximum-number-of-events-that-can-be-attended-ii
0
1
T: O(nlogn+nk)\ns:O(nk)\n\n# Code\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort()\n n=len(events)\n dp=[[-1]*n for _ in range(k)]\n def choice(index,count,end):\n if count==k or index==n:\n return 0\n if events[index][0]<=end:\n return choice(index+1,count,end)\n if dp[count][index]!=-1:\n return dp[count][index]\n\n dp[count][index]=max(choice(index+1,count+1,events[index][1])+events[index][2],choice(index+1,count,end))\n return dp[count][index]\n\n return choice(0,0,-1)\n \n\n\n \n```
1
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python Hard
maximum-number-of-events-that-can-be-attended-ii
0
1
```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n\n\n events.sort(key = lambda x: x[0])\n N = len(events)\n\n\n @cache\n def calc(index, currentDay, currentK):\n if index == N or currentK == 0:\n return 0\n\n while index < N and events[index][0] <= currentDay:\n index += 1\n \n if index == N:\n return 0\n\n best = 0\n\n for j in range(index, N):\n best = max(best, events[j][2] + calc(j + 1, events[j][1], currentK - 1))\n\n return best\n\n return calc(0, 0, k)\n \n \n\n\n```
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Python Hard
maximum-number-of-events-that-can-be-attended-ii
0
1
```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n\n\n events.sort(key = lambda x: x[0])\n N = len(events)\n\n\n @cache\n def calc(index, currentDay, currentK):\n if index == N or currentK == 0:\n return 0\n\n while index < N and events[index][0] <= currentDay:\n index += 1\n \n if index == N:\n return 0\n\n best = 0\n\n for j in range(index, N):\n best = max(best, events[j][2] + calc(j + 1, events[j][1], currentK - 1))\n\n return best\n\n return calc(0, 0, k)\n \n \n\n\n```
1
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python Easy solution beats 99% users in Runtime and Space
check-if-array-is-sorted-and-rotated
0
1
# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe provided code takes an approach of brute force to solve the problem:\n\n1. It iterates through all possible rotations of the given array.\n\n2. For each rotation, it checks if the array is sorted in non-decreasing order by comparing it with the sorted version of the array. If they are equal, it returns True, indicating that the array was originally sorted and possibly rotated to its current state.\n\n3. If no rotation results in a sorted array, it returns False, indicating that the array cannot be sorted by rotation.\n\n# Complexity\n- Time complexity: O(n^2)\n - The code iterates through all possible rotations (n rotations), and for each rotation, it checks if the array is sorted (O(n * log(n)) time complexity for sorting). This results in a total time complexity of O(n^2).\n\n- Space complexity: O(n)\n - The code creates a new list for each rotation using slicing (`nums[1:] + [nums[0]`]) and also creates a sorted copy of the array. Therefore, the space complexity is O(n).\n\nThe provided code correctly solves the problem using a brute force approach, but it may not be the most efficient solution for large input arrays. There are more efficient algorithms to determine if an array is sorted and possibly rotated with a lower time complexity.\n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n for i in range (len(nums)):\n if nums == sorted(nums):\n return True\n nums= nums[1 : ] + [nums[0]]\n return False\n```
2
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** true **Explanation:** \[1,2,3,4,5\] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\]. **Example 2:** **Input:** nums = \[2,1,3,4\] **Output:** false **Explanation:** There is no sorted array once rotated that can make nums. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Explanation:** \[1,2,3\] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.
Python Easy solution beats 99% users in Runtime and Space
check-if-array-is-sorted-and-rotated
0
1
# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe provided code takes an approach of brute force to solve the problem:\n\n1. It iterates through all possible rotations of the given array.\n\n2. For each rotation, it checks if the array is sorted in non-decreasing order by comparing it with the sorted version of the array. If they are equal, it returns True, indicating that the array was originally sorted and possibly rotated to its current state.\n\n3. If no rotation results in a sorted array, it returns False, indicating that the array cannot be sorted by rotation.\n\n# Complexity\n- Time complexity: O(n^2)\n - The code iterates through all possible rotations (n rotations), and for each rotation, it checks if the array is sorted (O(n * log(n)) time complexity for sorting). This results in a total time complexity of O(n^2).\n\n- Space complexity: O(n)\n - The code creates a new list for each rotation using slicing (`nums[1:] + [nums[0]`]) and also creates a sorted copy of the array. Therefore, the space complexity is O(n).\n\nThe provided code correctly solves the problem using a brute force approach, but it may not be the most efficient solution for large input arrays. There are more efficient algorithms to determine if an array is sorted and possibly rotated with a lower time complexity.\n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n for i in range (len(nums)):\n if nums == sorted(nums):\n return True\n nums= nums[1 : ] + [nums[0]]\n return False\n```
2
You are given an `m x n` integer matrix `grid`​​​. A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each **rhombus sum**: Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return _the biggest three **distinct rhombus sums** in the_ `grid` _in **descending order**__. If there are less than three distinct values, return all of them_. **Example 1:** **Input:** grid = \[\[3,4,5,1,3\],\[3,3,4,2,3\],\[20,30,200,40,10\],\[1,5,5,4,1\],\[4,3,2,2,5\]\] **Output:** \[228,216,211\] **Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. - Blue: 20 + 3 + 200 + 5 = 228 - Red: 200 + 2 + 10 + 4 = 216 - Green: 5 + 200 + 4 + 2 = 211 **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[20,9,8\] **Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. - Blue: 4 + 2 + 6 + 8 = 20 - Red: 9 (area 0 rhombus in the bottom right corner) - Green: 8 (area 0 rhombus in the bottom middle) **Example 3:** **Input:** grid = \[\[7,7,7\]\] **Output:** \[7\] **Explanation:** All three possible rhombus sums are the same, so return \[7\]. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 50` * `1 <= grid[i][j] <= 105`
Brute force and check if it is possible for a sorted array to start from each position.
Efficient Python Solution for Checking if an Array is Sorted and Possibly Rotated
check-if-array-is-sorted-and-rotated
0
1
\n# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe code uses an optimized approach without sorting:\n\n1. It finds the pivot point where the rotation occurs by using binary search.\n\n2. It checks if the array is sorted before and after the pivot point.\n\n3. If the array is sorted in either configuration, it returns True, indicating that the array was originally sorted and possibly rotated to its current state.\n\n4. If the array is not sorted in either configuration, it returns False, indicating that the array cannot be sorted by rotation.\n\n# Complexity\n- Time complexity: O(n)\n - It uses binary search to find the pivot point in O(log(n)) time. Then, it checks if the array is sorted before and after the pivot, which takes O(n) time for sorting the subarrays. Therefore, the overall time complexity is O(n).\n\n- Space complexity: O(n)\n - The space complexity is O(n) because it creates sorted copies of the array.\n\nThis code efficiently checks if the given array is sorted and possibly rotated with a lower runtime compared to the brute-force approach.\n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n n = len(nums)\n left, right = 0, n - 1\n while left < right and nums[left] == nums[right]:\n left += 1\n while left < right:\n mid = (left + right) // 2\n if nums[mid] > nums[right]:\n left = mid + 1\n else:\n right = mid\n pivot = left\n return nums == sorted(nums) or nums[pivot:] + nums[:pivot] == sorted(nums)\n\n```
1
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** true **Explanation:** \[1,2,3,4,5\] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\]. **Example 2:** **Input:** nums = \[2,1,3,4\] **Output:** false **Explanation:** There is no sorted array once rotated that can make nums. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Explanation:** \[1,2,3\] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.
Efficient Python Solution for Checking if an Array is Sorted and Possibly Rotated
check-if-array-is-sorted-and-rotated
0
1
\n# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe code uses an optimized approach without sorting:\n\n1. It finds the pivot point where the rotation occurs by using binary search.\n\n2. It checks if the array is sorted before and after the pivot point.\n\n3. If the array is sorted in either configuration, it returns True, indicating that the array was originally sorted and possibly rotated to its current state.\n\n4. If the array is not sorted in either configuration, it returns False, indicating that the array cannot be sorted by rotation.\n\n# Complexity\n- Time complexity: O(n)\n - It uses binary search to find the pivot point in O(log(n)) time. Then, it checks if the array is sorted before and after the pivot, which takes O(n) time for sorting the subarrays. Therefore, the overall time complexity is O(n).\n\n- Space complexity: O(n)\n - The space complexity is O(n) because it creates sorted copies of the array.\n\nThis code efficiently checks if the given array is sorted and possibly rotated with a lower runtime compared to the brute-force approach.\n# Code\n```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n n = len(nums)\n left, right = 0, n - 1\n while left < right and nums[left] == nums[right]:\n left += 1\n while left < right:\n mid = (left + right) // 2\n if nums[mid] > nums[right]:\n left = mid + 1\n else:\n right = mid\n pivot = left\n return nums == sorted(nums) or nums[pivot:] + nums[:pivot] == sorted(nums)\n\n```
1
You are given an `m x n` integer matrix `grid`​​​. A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each **rhombus sum**: Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return _the biggest three **distinct rhombus sums** in the_ `grid` _in **descending order**__. If there are less than three distinct values, return all of them_. **Example 1:** **Input:** grid = \[\[3,4,5,1,3\],\[3,3,4,2,3\],\[20,30,200,40,10\],\[1,5,5,4,1\],\[4,3,2,2,5\]\] **Output:** \[228,216,211\] **Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. - Blue: 20 + 3 + 200 + 5 = 228 - Red: 200 + 2 + 10 + 4 = 216 - Green: 5 + 200 + 4 + 2 = 211 **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[20,9,8\] **Explanation:** The rhombus shapes for the three biggest distinct rhombus sums are depicted above. - Blue: 4 + 2 + 6 + 8 = 20 - Red: 9 (area 0 rhombus in the bottom right corner) - Green: 8 (area 0 rhombus in the bottom middle) **Example 3:** **Input:** grid = \[\[7,7,7\]\] **Output:** \[7\] **Explanation:** All three possible rhombus sums are the same, so return \[7\]. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 50` * `1 <= grid[i][j] <= 105`
Brute force and check if it is possible for a sorted array to start from each position.
Is Array Sorted and Rotated, Python code made easy
check-if-array-is-sorted-and-rotated
0
1
```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n count = 0\n for i in range(len(nums) - 1):\n if nums[i] > nums[i+1]:\n count += 1\n \n if nums[0] < nums[len(nums)-1]:\n count += 1\n \n return count <= 1\n```
4
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** true **Explanation:** \[1,2,3,4,5\] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\]. **Example 2:** **Input:** nums = \[2,1,3,4\] **Output:** false **Explanation:** There is no sorted array once rotated that can make nums. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Explanation:** \[1,2,3\] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.