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 Short Clean | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the difference in sum between the two lists. Then put them in the same heap. Pull the biggest difference maker each time from the heap until you compensate for the difference or run the heap out of items.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nmax heap is used so everything needs to be negative in python. When calculating how big of a difference a number can make in your calculation need to see how close it is to either 6 or 1. Also need to determine which direction it should go to get you closer to zeroing out the difference.\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) where n is the total length of list1 + list2\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n diff, cnt = sum(nums2) - sum(nums1), 0\n \n if diff == 0:\n return 0\n if diff < 0:\n combo = [num - 6 for num in nums2] + [1 - num for num in nums1]\n diff = -diff\n else:\n combo = [num - 6 for num in nums1] + [1 - num for num in nums2]\n heapq.heapify(combo)\n while diff > 0 and combo:\n diff += heapq.heappop(combo)\n cnt += 1\n\n return cnt if cnt and diff <= 0 else -1\n``` | 1 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python Solution | Minimize the differenc | reverse sort the Max sum Arr and forward sort min sum Arr | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n\nFind the difference between sums of both array, then minimize the difference \n\n# Approach\n\n1) How to minimize the difference ?\n Decrease the value from the max sum arr and increase the value from min sum array\n\n2) how to choose values optimaly from both arrays ?\nopt max value from the max sum array and decrese the value, similary opt min value from min sum array and increase the value\n\n3) How to increase and decrese the value optimaly ?\ncheck wheather increasing the value is giving the more minimized differnce or by decreasing the value, do the appropirate opeartion which gives more minimized difference\n\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n if 6*len(nums1) < len(nums2) or 6*(len(nums2)) < len(nums1):\n return -1\n\n sm1,sm2 = sum(nums1), sum(nums2)\n if sm1 == sm2:\n return 0\n\n if sm1 < sm2:\n sm1,sm2 = sm2,sm1\n nums1,nums2 = nums2,nums1 \n\n nums1.sort(reverse = True)\n nums2.sort()\n\n diff = sm1-sm2\n mop = 0\n i,j = 0,0\n \n while j < len(nums2) or i < len(nums1):\n x = nums1[i]-1 if i < len(nums1) else -10\n y = 6-nums2[j] if j < len(nums2) else -10\n\n diff -= max(x,y)\n\n if x > y : i += 1\n else: j += 1\n\n if diff <= 0:\n return mop\n\n return -1\n\n\n\n\n \n \n\n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python Solution | Minimize the differenc | reverse sort the Max sum Arr and forward sort min sum Arr | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n\nFind the difference between sums of both array, then minimize the difference \n\n# Approach\n\n1) How to minimize the difference ?\n Decrease the value from the max sum arr and increase the value from min sum array\n\n2) how to choose values optimaly from both arrays ?\nopt max value from the max sum array and decrese the value, similary opt min value from min sum array and increase the value\n\n3) How to increase and decrese the value optimaly ?\ncheck wheather increasing the value is giving the more minimized differnce or by decreasing the value, do the appropirate opeartion which gives more minimized difference\n\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n if 6*len(nums1) < len(nums2) or 6*(len(nums2)) < len(nums1):\n return -1\n\n sm1,sm2 = sum(nums1), sum(nums2)\n if sm1 == sm2:\n return 0\n\n if sm1 < sm2:\n sm1,sm2 = sm2,sm1\n nums1,nums2 = nums2,nums1 \n\n nums1.sort(reverse = True)\n nums2.sort()\n\n diff = sm1-sm2\n mop = 0\n i,j = 0,0\n \n while j < len(nums2) or i < len(nums1):\n x = nums1[i]-1 if i < len(nums1) else -10\n y = 6-nums2[j] if j < len(nums2) else -10\n\n diff -= max(x,y)\n\n if x > y : i += 1\n else: j += 1\n\n if diff <= 0:\n return mop\n\n return -1\n\n\n\n\n \n \n\n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
💋⚡Keep It Simple Stupid. Beats 100% Simplicity, 97% Runtime+Memory. O(N) time, O(1) space. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\nSince we are dealing with a small discrete number of values (1-6), we create a count dictionary of each set $\\{die: count\\}$. For the smaller set, we can change a die to a six, increasing the sum by $value=6-die$. For the larger set, we can change a die to a one, decreasing the sum by $value=die-1$. Convert both sets to values and then merge them $\\{value: count\\}$. Take values, starting from the largest, until the sum difference between the sets is removed. Note that if the value of an operation is larger than the sum difference needed, it can always be changed to a smaller number. E.g. if $value(4\\to6)=2 > distance=1$, we will overshoot, but we can always change our 4 to a 5 instead, making the sum_diff equal zero.\n\n# Approach\nSee intuition.\n1. Create counts of each seq and calculate sum difference (distance).\n2. Convert counts to values $value(x\\to6)=6-x$ for the smaller set, and $value(x\\to1)=x-1$ for the larger set. Merge the two counts.\n3. Take the largest available value until the sum difference <=0.\n\n# Complexity\n- Time complexity:\n$$O(n_1+n_2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n # Count occurances and find sums.\n counts1 = Counter(nums1)\n counts2 = Counter(nums2)\n sum1 = sum(k*v for k,v in counts1.items())\n sum2 = sum(k*v for k,v in counts2.items())\n \n # Reorder so sum(counts1) <= sum(counts2).\n counts1, counts2 = (counts1, counts2) if sum1<sum2 else (counts2, counts1)\n sumdiff = abs(sum2-sum1)\n if sumdiff == 0:\n return 0\n\n # Find value of changing the die. value_up(d->6)=6-d, value_down(d->1)=d-1.\n change2six = lambda dots : 6-dots\n change2one = lambda dots : dots-1\n\n vals = Counter({change2six(dots):count for dots,count in counts1.items()}) \\\n + Counter({change2one(dots):count for dots,count in counts2.items()})\n\n # Find how many operations we need.\n n_ops = 0\n for op_val in reversed(range(1,6)): # Start with best change value of 5.\n count = vals[op_val]\n # Max count operations available, we might need less.\n curr_ops = min(count, int(math.ceil(sumdiff / op_val)))\n sumdiff -= curr_ops*op_val\n n_ops += curr_ops\n if sumdiff <= 0:\n return n_ops\n \n return -1\n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
💋⚡Keep It Simple Stupid. Beats 100% Simplicity, 97% Runtime+Memory. O(N) time, O(1) space. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\nSince we are dealing with a small discrete number of values (1-6), we create a count dictionary of each set $\\{die: count\\}$. For the smaller set, we can change a die to a six, increasing the sum by $value=6-die$. For the larger set, we can change a die to a one, decreasing the sum by $value=die-1$. Convert both sets to values and then merge them $\\{value: count\\}$. Take values, starting from the largest, until the sum difference between the sets is removed. Note that if the value of an operation is larger than the sum difference needed, it can always be changed to a smaller number. E.g. if $value(4\\to6)=2 > distance=1$, we will overshoot, but we can always change our 4 to a 5 instead, making the sum_diff equal zero.\n\n# Approach\nSee intuition.\n1. Create counts of each seq and calculate sum difference (distance).\n2. Convert counts to values $value(x\\to6)=6-x$ for the smaller set, and $value(x\\to1)=x-1$ for the larger set. Merge the two counts.\n3. Take the largest available value until the sum difference <=0.\n\n# Complexity\n- Time complexity:\n$$O(n_1+n_2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n # Count occurances and find sums.\n counts1 = Counter(nums1)\n counts2 = Counter(nums2)\n sum1 = sum(k*v for k,v in counts1.items())\n sum2 = sum(k*v for k,v in counts2.items())\n \n # Reorder so sum(counts1) <= sum(counts2).\n counts1, counts2 = (counts1, counts2) if sum1<sum2 else (counts2, counts1)\n sumdiff = abs(sum2-sum1)\n if sumdiff == 0:\n return 0\n\n # Find value of changing the die. value_up(d->6)=6-d, value_down(d->1)=d-1.\n change2six = lambda dots : 6-dots\n change2one = lambda dots : dots-1\n\n vals = Counter({change2six(dots):count for dots,count in counts1.items()}) \\\n + Counter({change2one(dots):count for dots,count in counts2.items()})\n\n # Find how many operations we need.\n n_ops = 0\n for op_val in reversed(range(1,6)): # Start with best change value of 5.\n count = vals[op_val]\n # Max count operations available, we might need less.\n curr_ops = min(count, int(math.ceil(sumdiff / op_val)))\n sumdiff -= curr_ops*op_val\n n_ops += curr_ops\n if sumdiff <= 0:\n return n_ops\n \n return -1\n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python O(nlogn) Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | We have two arrays, by calculating the sum, we can know which is larger and which is the smaller.\nTo reach a same sum value (reduce the difference on sum to 0):\n\n- For larger array, at each operation, we want to decrease the number as much as possible.\nSince the min value we can decrease to is 1, at position i, the max contribution (to reduce the difference) we can "gain" is larger_array[i] - 1\n- Similarly, for smaller array, we want to increase the number as much as possible.\nSince the max value we can increase to is 6, the "gain" at position i is 6-smaller_array[i]\n\nThus, following this idea, we can:\n\n1. calculate the "gain" at each position in the larger and smaller array\n1. sort them together in an ascending order.\n1. by accumulating the "gain" from large to small, we can know the least steps to reduce the difference to 0.\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max "gain" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the "gain" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1\n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python O(nlogn) Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | We have two arrays, by calculating the sum, we can know which is larger and which is the smaller.\nTo reach a same sum value (reduce the difference on sum to 0):\n\n- For larger array, at each operation, we want to decrease the number as much as possible.\nSince the min value we can decrease to is 1, at position i, the max contribution (to reduce the difference) we can "gain" is larger_array[i] - 1\n- Similarly, for smaller array, we want to increase the number as much as possible.\nSince the max value we can increase to is 6, the "gain" at position i is 6-smaller_array[i]\n\nThus, following this idea, we can:\n\n1. calculate the "gain" at each position in the larger and smaller array\n1. sort them together in an ascending order.\n1. by accumulating the "gain" from large to small, we can know the least steps to reduce the difference to 0.\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max "gain" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the "gain" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1\n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
In place sort. Find maximum step size. O(n logn) time complexity. O(1) space complexity. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n\\log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n\n sum1=sum(nums1)\n sum2=sum(nums2)\n\n if sum2> sum1: \n nums1, nums2 = nums2, nums1\n sum1, sum2 = sum2, sum1\n \n nums1.sort()\n nums2.sort(reverse = True)\n m=len(nums1)\n n=len(nums2)\n\n if max(m,n) *1 > min(m,n) *6: return -1\n\n ans=0\n\n while sum1 > sum2: \n\n if nums1:\n maxdecrease = nums1[-1]-1\n else: maxdecrease=0\n\n if nums2:\n maxincrease = 6 - nums2[-1]\n else: maxincrease=0\n\n if maxdecrease > maxincrease: \n\n sum1 -= maxdecrease\n nums1.pop()\n else: \n sum2 += maxincrease\n nums2.pop()\n\n # print(nums1, nums2)\n ans+=1\n\n return ans\n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
In place sort. Find maximum step size. O(n logn) time complexity. O(1) space complexity. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n\\log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n\n sum1=sum(nums1)\n sum2=sum(nums2)\n\n if sum2> sum1: \n nums1, nums2 = nums2, nums1\n sum1, sum2 = sum2, sum1\n \n nums1.sort()\n nums2.sort(reverse = True)\n m=len(nums1)\n n=len(nums2)\n\n if max(m,n) *1 > min(m,n) *6: return -1\n\n ans=0\n\n while sum1 > sum2: \n\n if nums1:\n maxdecrease = nums1[-1]-1\n else: maxdecrease=0\n\n if nums2:\n maxincrease = 6 - nums2[-1]\n else: maxincrease=0\n\n if maxdecrease > maxincrease: \n\n sum1 -= maxdecrease\n nums1.pop()\n else: \n sum2 += maxincrease\n nums2.pop()\n\n # print(nums1, nums2)\n ans+=1\n\n return ans\n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Optimized Greedy Approach to Minimize Operations for Equal Array Sums | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Minimum Operations to Make Sum of Two Arrays Equal\n\n## Problem Description\n\nYou are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer\'s value in any of the arrays to any value between 1 and 6, inclusive.\n\nReturn the minimum number of operations required to make the sum of values in `nums1` equal to the sum of values in `nums2`. Return -1 if it is not possible to make the sum of the two arrays equal.\n\n## Intuition\n\nThe problem can be solved by trying to bridge the gap between the sum of the two arrays. We can achieve this by either increasing the sum of the smaller array or decreasing the sum of the larger array, or both.\n\n## Approach\n\n1. Sort both arrays.\n2. Calculate the sums of both arrays.\n3. Depending on which array has a greater sum, use a helper function to determine the minimum number of operations needed.\n\n## Algorithm\n\n1. Sort `nums1` and `nums2`.\n2. Calculate `sumNums1` and `sumNums2`.\n3. If `sumNums1` is greater, call the helper function with `nums1` and `nums2`.\n4. Else, call the helper function with `nums2` and `nums1`.\n\n### Helper Function\n\n#### Purpose\n\nThe `helper` function is designed to find the minimum number of operations needed to make the sums of two arrays, `numsGreater` and `numsLessThan`, equal. Here `numsGreater` is the array with the larger sum, and `numsLessThan` has the smaller sum. The variables `s1` and `s2` store these sums, respectively.\n\n#### Steps\n\n1. **Calculate the Extremes**: The function starts by calculating the lowest possible sum for `numsGreater` (if all elements are 1) and the highest possible sum for `numsLessThan` (if all elements are 6).\n\n2. **Check Feasibility**: If it\'s not possible to make the sums equal by changing the elements, the function returns -1. This is checked by comparing `lowestPossibleNumsGreater` and `highestPossibleNumsLessThan`.\n\n3. **Initialize Pointers and Counters**: Two pointers `i` and `j` are initialized to traverse `numsGreater` and `numsLessThan`, respectively. The variable `ops` counts the number of operations.\n\n4. **Iterate and Update**: The function enters a loop that iterates as long as one of the pointers is within the array bounds. In each iteration:\n - It checks if the sums are already equal; if so, it breaks out of the loop.\n - It calculates the maximum possible change for both arrays (`change1` for `numsGreater` and `change2` for `numsLessThan`).\n - Depending on which change is larger, it updates the corresponding sum and moves the pointer.\n - Increments the operations counter `ops`.\n\n#### Return Value\n\nThe function returns the minimum number of operations `ops` needed to make the sums equal.\n\n## Complexity Analysis\n\n- **Time Complexity:** \\( O(n \\log n) \\) where \\( n \\) is the length of the longest array. This is because we sort both arrays.\n- **Space Complexity:** \\( O(1) \\) for constant space.\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n nums1.sort()\n nums2.sort()\n\n sumNums1 = sum(nums1)\n sumNums2 = sum(nums2)\n\n if sumNums1 == sumNums2:\n return 0\n \n if sumNums1>sumNums2:\n return self.helper(nums1, nums2, sumNums1, sumNums2)\n \n return self.helper(nums2, nums1, sumNums2, sumNums1)\n \n def helper(self, numsGreater: List[int], numsLessThan: List[int], s1:int, s2:int) -> int:\n lowestPossibleNumsGreater = len(numsGreater) # when all are 1\n highestPossibleNumsLessThan = len(numsLessThan) * 6 # when all are 6\n\n if highestPossibleNumsLessThan < lowestPossibleNumsGreater:\n return -1\n \n i = len(numsGreater) -1\n j = 0\n ops = 0\n\n while i>=0 or j<len(numsLessThan):\n if s1<=s2:\n break\n change1 = -1 #represents the value which can be decreased in arr1\n change2 = -1 #represents by how much we can increase the sum of arr2\n # initialized them as -1 as it might be that one of the arr is completely used so we should not do any ops \n if i>=0:\n change1 = numsGreater[i] -1\n if j<len(numsLessThan):\n change2 = 6 - numsLessThan[j]\n \n if change1 >= change2:\n s1 = s1 - numsGreater[i] + 1\n i-=1\n else:\n s2 = s2 + 6 - numsLessThan[j]\n j+=1\n \n ops+=1\n\n \n return ops\n \n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Optimized Greedy Approach to Minimize Operations for Equal Array Sums | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Minimum Operations to Make Sum of Two Arrays Equal\n\n## Problem Description\n\nYou are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer\'s value in any of the arrays to any value between 1 and 6, inclusive.\n\nReturn the minimum number of operations required to make the sum of values in `nums1` equal to the sum of values in `nums2`. Return -1 if it is not possible to make the sum of the two arrays equal.\n\n## Intuition\n\nThe problem can be solved by trying to bridge the gap between the sum of the two arrays. We can achieve this by either increasing the sum of the smaller array or decreasing the sum of the larger array, or both.\n\n## Approach\n\n1. Sort both arrays.\n2. Calculate the sums of both arrays.\n3. Depending on which array has a greater sum, use a helper function to determine the minimum number of operations needed.\n\n## Algorithm\n\n1. Sort `nums1` and `nums2`.\n2. Calculate `sumNums1` and `sumNums2`.\n3. If `sumNums1` is greater, call the helper function with `nums1` and `nums2`.\n4. Else, call the helper function with `nums2` and `nums1`.\n\n### Helper Function\n\n#### Purpose\n\nThe `helper` function is designed to find the minimum number of operations needed to make the sums of two arrays, `numsGreater` and `numsLessThan`, equal. Here `numsGreater` is the array with the larger sum, and `numsLessThan` has the smaller sum. The variables `s1` and `s2` store these sums, respectively.\n\n#### Steps\n\n1. **Calculate the Extremes**: The function starts by calculating the lowest possible sum for `numsGreater` (if all elements are 1) and the highest possible sum for `numsLessThan` (if all elements are 6).\n\n2. **Check Feasibility**: If it\'s not possible to make the sums equal by changing the elements, the function returns -1. This is checked by comparing `lowestPossibleNumsGreater` and `highestPossibleNumsLessThan`.\n\n3. **Initialize Pointers and Counters**: Two pointers `i` and `j` are initialized to traverse `numsGreater` and `numsLessThan`, respectively. The variable `ops` counts the number of operations.\n\n4. **Iterate and Update**: The function enters a loop that iterates as long as one of the pointers is within the array bounds. In each iteration:\n - It checks if the sums are already equal; if so, it breaks out of the loop.\n - It calculates the maximum possible change for both arrays (`change1` for `numsGreater` and `change2` for `numsLessThan`).\n - Depending on which change is larger, it updates the corresponding sum and moves the pointer.\n - Increments the operations counter `ops`.\n\n#### Return Value\n\nThe function returns the minimum number of operations `ops` needed to make the sums equal.\n\n## Complexity Analysis\n\n- **Time Complexity:** \\( O(n \\log n) \\) where \\( n \\) is the length of the longest array. This is because we sort both arrays.\n- **Space Complexity:** \\( O(1) \\) for constant space.\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n nums1.sort()\n nums2.sort()\n\n sumNums1 = sum(nums1)\n sumNums2 = sum(nums2)\n\n if sumNums1 == sumNums2:\n return 0\n \n if sumNums1>sumNums2:\n return self.helper(nums1, nums2, sumNums1, sumNums2)\n \n return self.helper(nums2, nums1, sumNums2, sumNums1)\n \n def helper(self, numsGreater: List[int], numsLessThan: List[int], s1:int, s2:int) -> int:\n lowestPossibleNumsGreater = len(numsGreater) # when all are 1\n highestPossibleNumsLessThan = len(numsLessThan) * 6 # when all are 6\n\n if highestPossibleNumsLessThan < lowestPossibleNumsGreater:\n return -1\n \n i = len(numsGreater) -1\n j = 0\n ops = 0\n\n while i>=0 or j<len(numsLessThan):\n if s1<=s2:\n break\n change1 = -1 #represents the value which can be decreased in arr1\n change2 = -1 #represents by how much we can increase the sum of arr2\n # initialized them as -1 as it might be that one of the arr is completely used so we should not do any ops \n if i>=0:\n change1 = numsGreater[i] -1\n if j<len(numsLessThan):\n change2 = 6 - numsLessThan[j]\n \n if change1 >= change2:\n s1 = s1 - numsGreater[i] + 1\n i-=1\n else:\n s2 = s2 + 6 - numsLessThan[j]\n j+=1\n \n ops+=1\n\n \n return ops\n \n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python3 Beats 98.98%, Greedy Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nShould be a greedy problem, because we need to find the most profitable element to turn it either into 1 / 6 to make the sum of both arr the same\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the argument is possible to solve by the array length. \nSort array with bigger sum (desc)\nSort array with smaller sum (asc)\nTurn element in array with the bigger sum into 1\nTurn element in array with the smaller sum into 6\nRepeat until the difference is =< 0\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn = length nums1\nm = length nums2\n$$O(nlogn) + O(mlogm) + O(n+m)$$ = $$O((m+n)log (m+n))$$\n\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n+m)$$\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n high_sum = sum(nums1)\n low_sum = sum(nums2)\n if high_sum > low_sum:\n high_arr = nums1\n low_arr = nums2\n else:\n high_arr = nums2\n low_arr = nums1\n high_sum, low_sum = low_sum, high_sum\n\n difference = high_sum - low_sum\n\n # check if possible\n a = len(nums1)\n b = len(nums2)\n\n min_length = min(a,b)\n max_length = max(a,b)\n\n if min_length * 6 < max_length:\n return -1\n\n # start the process\n high_arr.sort(reverse=True)\n low_arr.sort()\n\n count = 0\n i = 0\n j = 0 \n while difference > 0 and i < len(high_arr) and j < len(low_arr):\n high_potential = high_arr[i] - 1\n low_potential = 6 - low_arr[j]\n\n\n if high_potential > low_potential:\n difference -= high_potential\n i += 1\n else:\n difference -= low_potential\n j += 1\n count += 1\n\n while difference > 0 and i < len(high_arr):\n difference -= (high_arr[i] - 1)\n i += 1\n count += 1\n\n while difference > 0 and j < len(low_arr):\n difference -= (6 - low_arr[j])\n j += 1\n count += 1\n \n return count\n``` | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations required to make the sum of values in_ `nums1` _equal to the sum of values in_ `nums2`_._ Return `-1` if it is not possible to make the sum of the two arrays equal.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5,6\], nums2 = \[1,1,2,2,2,2\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2\[0\] to 6. nums1 = \[1,2,3,4,5,6\], nums2 = \[**6**,1,2,2,2,2\].
- Change nums1\[5\] to 1. nums1 = \[1,2,3,4,5,**1**\], nums2 = \[6,1,2,2,2,2\].
- Change nums1\[2\] to 2. nums1 = \[1,2,**2**,4,5,1\], nums2 = \[6,1,2,2,2,2\].
**Example 2:**
**Input:** nums1 = \[1,1,1,1,1,1,1\], nums2 = \[6\]
**Output:** -1
**Explanation:** There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
**Example 3:**
**Input:** nums1 = \[6,6\], nums2 = \[1\]
**Output:** 3
**Explanation:** You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1\[0\] to 2. nums1 = \[**2**,6\], nums2 = \[1\].
- Change nums1\[1\] to 2. nums1 = \[2,**2**\], nums2 = \[1\].
- Change nums2\[0\] to 4. nums1 = \[2,2\], nums2 = \[**4**\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `1 <= nums1[i], nums2[i] <= 6` | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python3 Beats 98.98%, Greedy Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nShould be a greedy problem, because we need to find the most profitable element to turn it either into 1 / 6 to make the sum of both arr the same\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the argument is possible to solve by the array length. \nSort array with bigger sum (desc)\nSort array with smaller sum (asc)\nTurn element in array with the bigger sum into 1\nTurn element in array with the smaller sum into 6\nRepeat until the difference is =< 0\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn = length nums1\nm = length nums2\n$$O(nlogn) + O(mlogm) + O(n+m)$$ = $$O((m+n)log (m+n))$$\n\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n+m)$$\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n high_sum = sum(nums1)\n low_sum = sum(nums2)\n if high_sum > low_sum:\n high_arr = nums1\n low_arr = nums2\n else:\n high_arr = nums2\n low_arr = nums1\n high_sum, low_sum = low_sum, high_sum\n\n difference = high_sum - low_sum\n\n # check if possible\n a = len(nums1)\n b = len(nums2)\n\n min_length = min(a,b)\n max_length = max(a,b)\n\n if min_length * 6 < max_length:\n return -1\n\n # start the process\n high_arr.sort(reverse=True)\n low_arr.sort()\n\n count = 0\n i = 0\n j = 0 \n while difference > 0 and i < len(high_arr) and j < len(low_arr):\n high_potential = high_arr[i] - 1\n low_potential = 6 - low_arr[j]\n\n\n if high_potential > low_potential:\n difference -= high_potential\n i += 1\n else:\n difference -= low_potential\n j += 1\n count += 1\n\n while difference > 0 and i < len(high_arr):\n difference -= (high_arr[i] - 1)\n i += 1\n count += 1\n\n while difference > 0 and j < len(low_arr):\n difference -= (6 - low_arr[j])\n j += 1\n count += 1\n \n return count\n``` | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal. | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python, Heap and Stack solutions | car-fleet-ii | 0 | 1 | The problem can be solved with a heap or a stack. Heap solution is probably easier to arrive at, given that it only requires us to make two observations about the input, but involves writing more code. Stack solution is elegant and fast, but is harder to come up with, since we have to make more observations about the input.\n\n# Heap solution\nThe intuition behind this solution is that earlier collisions have the potential to affect later collisions and not vice versa. Therefore we\'d like to process collisions in the order they are happening. For this, we put each car that has a potential to collide with the next one in a heap and order it based on the expected collision time based on cars\' positions and speed. A car that has collided is no longer interesting to us, since the previous car can now only collide with the car that follows it. To emulate this behavior we place cars in a linked list so we can easily remove the car after collision.\n## Complexity\nTime: O(NlogN)\nSpace: O(N)\n```\nclass Car:\n def __init__(self, pos, speed, idx, prev=None, next=None):\n self.pos = pos\n self.speed = speed\n self.idx = idx\n self.prev = prev\n self.next = next\n\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times\n```\n# Stack solution\nObservations:\n* For every car we only care about the cars ahead, because those are the ones that we can collide with.\n* Among those ahead of us, some are faster and we will never catch up with those, so we can ignore them.\n* Some of the cars ahead that are slower than us will be in a collision before us, those we can also ignore because after they collide they are not any different to us that the car they collided with.\n* Anything we ignore can also be safely ignored by the cars that follow us, because they can only go as fast as us after colliding with us.\n\nBased on aforementioned observations we produce a stack solution below. We iterate over the cars starting from the last one and process the cars in front of us, getting rid of them if they are no longer interesting.\nTip: for index `i`, `~i` will give us the index with the same offset from the end of the array, e.g. for ` == 0`, `~i == -1`, etc.\n## Complexity\nTime: O(N)\nSpace: O(N)\n```\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars_in_front_stack = []\n for i, (position, speed) in enumerate(reversed(cars)):\n while cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n if front_car_speed >= speed or \\\n (our_collision_with_front := (front_car_pos - position) / (speed - front_car_speed)) >= front_car_collision: \n cars_in_front_stack.pop()\n else: break\n \n if cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n colis_times[~i] = (front_car_pos - position) / (speed - front_car_speed)\n cars_in_front_stack.append((position, speed, colis_times[~i] if colis_times[~i] != -1 else inf))\n \n return colis_times\n``` | 12 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.
* `speedi` is the initial speed of the `ith` car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet.
Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.
**Example 1:**
**Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\]
**Output:** \[1.00000,-1.00000,3.00000,-1.00000\]
**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
**Example 2:**
**Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\]
**Output:** \[2.00000,1.00000,1.50000,-1.00000\]
**Constraints:**
* `1 <= cars.length <= 105`
* `1 <= positioni, speedi <= 106`
* `positioni < positioni+1` | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
Python, Heap and Stack solutions | car-fleet-ii | 0 | 1 | The problem can be solved with a heap or a stack. Heap solution is probably easier to arrive at, given that it only requires us to make two observations about the input, but involves writing more code. Stack solution is elegant and fast, but is harder to come up with, since we have to make more observations about the input.\n\n# Heap solution\nThe intuition behind this solution is that earlier collisions have the potential to affect later collisions and not vice versa. Therefore we\'d like to process collisions in the order they are happening. For this, we put each car that has a potential to collide with the next one in a heap and order it based on the expected collision time based on cars\' positions and speed. A car that has collided is no longer interesting to us, since the previous car can now only collide with the car that follows it. To emulate this behavior we place cars in a linked list so we can easily remove the car after collision.\n## Complexity\nTime: O(NlogN)\nSpace: O(N)\n```\nclass Car:\n def __init__(self, pos, speed, idx, prev=None, next=None):\n self.pos = pos\n self.speed = speed\n self.idx = idx\n self.prev = prev\n self.next = next\n\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times\n```\n# Stack solution\nObservations:\n* For every car we only care about the cars ahead, because those are the ones that we can collide with.\n* Among those ahead of us, some are faster and we will never catch up with those, so we can ignore them.\n* Some of the cars ahead that are slower than us will be in a collision before us, those we can also ignore because after they collide they are not any different to us that the car they collided with.\n* Anything we ignore can also be safely ignored by the cars that follow us, because they can only go as fast as us after colliding with us.\n\nBased on aforementioned observations we produce a stack solution below. We iterate over the cars starting from the last one and process the cars in front of us, getting rid of them if they are no longer interesting.\nTip: for index `i`, `~i` will give us the index with the same offset from the end of the array, e.g. for ` == 0`, `~i == -1`, etc.\n## Complexity\nTime: O(N)\nSpace: O(N)\n```\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars_in_front_stack = []\n for i, (position, speed) in enumerate(reversed(cars)):\n while cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n if front_car_speed >= speed or \\\n (our_collision_with_front := (front_car_pos - position) / (speed - front_car_speed)) >= front_car_collision: \n cars_in_front_stack.pop()\n else: break\n \n if cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n colis_times[~i] = (front_car_pos - position) / (speed - front_car_speed)\n cars_in_front_stack.append((position, speed, colis_times[~i] if colis_times[~i] != -1 else inf))\n \n return colis_times\n``` | 12 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
* `order[0]` will be the **root** of the binary search tree.
* All subsequent elements are inserted as the **child** of **any** existing node such that the binary search tree properties hold.
Return _the **depth** of the binary search tree_.
A binary tree's **depth** is the number of **nodes** along the **longest path** from the root node down to the farthest leaf node.
**Example 1:**
**Input:** order = \[2,1,4,3\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 2:**
**Input:** order = \[2,1,3,4\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 3:**
**Input:** order = \[1,2,3,4\]
**Output:** 4
**Explanation:** The binary search tree has a depth of 4 with path 1->2->3->4.
**Constraints:**
* `n == order.length`
* `1 <= n <= 105`
* `order` is a permutation of integers between `1` and `n`. | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection. |
[Python3] | Stack Approach | car-fleet-ii | 0 | 1 | ```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n n=len(cars)\n ans=[-1]*n\n stack=[]\n for i in range(n-1,-1,-1):\n while stack and cars[i][1]<=cars[stack[-1]][1]:\n stack.pop()\n while stack:\n collisionTime=(cars[stack[-1]][0]-cars[i][0])/(cars[i][1]-cars[stack[-1]][1])\n if collisionTime<=ans[stack[-1]] or ans[stack[-1]]==-1:\n ans[i]=collisionTime\n break\n stack.pop()\n stack.append(i)\n return ans \n``` | 1 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.
* `speedi` is the initial speed of the `ith` car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet.
Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.
**Example 1:**
**Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\]
**Output:** \[1.00000,-1.00000,3.00000,-1.00000\]
**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
**Example 2:**
**Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\]
**Output:** \[2.00000,1.00000,1.50000,-1.00000\]
**Constraints:**
* `1 <= cars.length <= 105`
* `1 <= positioni, speedi <= 106`
* `positioni < positioni+1` | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
[Python3] | Stack Approach | car-fleet-ii | 0 | 1 | ```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n n=len(cars)\n ans=[-1]*n\n stack=[]\n for i in range(n-1,-1,-1):\n while stack and cars[i][1]<=cars[stack[-1]][1]:\n stack.pop()\n while stack:\n collisionTime=(cars[stack[-1]][0]-cars[i][0])/(cars[i][1]-cars[stack[-1]][1])\n if collisionTime<=ans[stack[-1]] or ans[stack[-1]]==-1:\n ans[i]=collisionTime\n break\n stack.pop()\n stack.append(i)\n return ans \n``` | 1 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
* `order[0]` will be the **root** of the binary search tree.
* All subsequent elements are inserted as the **child** of **any** existing node such that the binary search tree properties hold.
Return _the **depth** of the binary search tree_.
A binary tree's **depth** is the number of **nodes** along the **longest path** from the root node down to the farthest leaf node.
**Example 1:**
**Input:** order = \[2,1,4,3\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 2:**
**Input:** order = \[2,1,3,4\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 3:**
**Input:** order = \[1,2,3,4\]
**Output:** 4
**Explanation:** The binary search tree has a depth of 4 with path 1->2->3->4.
**Constraints:**
* `n == order.length`
* `1 <= n <= 105`
* `order` is a permutation of integers between `1` and `n`. | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection. |
[Python3] Stack - Time: O(n) & Space: O(n) | car-fleet-ii | 0 | 1 | Time Complexity: O(n)\nSpace Complexity: O(n)\n\nUse stack to store indices and iterate from the back of car array\n\n```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n # Stack: go from back and use stack to get ans\n # Time: O(n)\n # Space: O(n)\n \n stack = [] # index\n ans = [-1] * len(cars)\n for i in range(len(cars)-1,-1,-1):\n # remove cars that are faster than current car since it will never collide\n while stack and cars[i][1] <= cars[stack[-1]][1]: \n stack.pop()\n\n while stack: # if car left, we can compute collide time with current car. \n collision_t = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])\n # if current car\'s collide time is greater than previous car\'s collide time \n # (previous collided before current), then we have to find previous car\'s previous car\n # to compute collide time with that car, so we pop from stack and re-process\n # Otherwise, we add that collide time to answer and break\n if ans[stack[-1]] == -1 or collision_t <= ans[stack[-1]]:\n ans[i] = collision_t\n break\n stack.pop()\n stack.append(i)\n return ans\n```\n\n | 4 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.
* `speedi` is the initial speed of the `ith` car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet.
Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.
**Example 1:**
**Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\]
**Output:** \[1.00000,-1.00000,3.00000,-1.00000\]
**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
**Example 2:**
**Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\]
**Output:** \[2.00000,1.00000,1.50000,-1.00000\]
**Constraints:**
* `1 <= cars.length <= 105`
* `1 <= positioni, speedi <= 106`
* `positioni < positioni+1` | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
[Python3] Stack - Time: O(n) & Space: O(n) | car-fleet-ii | 0 | 1 | Time Complexity: O(n)\nSpace Complexity: O(n)\n\nUse stack to store indices and iterate from the back of car array\n\n```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n # Stack: go from back and use stack to get ans\n # Time: O(n)\n # Space: O(n)\n \n stack = [] # index\n ans = [-1] * len(cars)\n for i in range(len(cars)-1,-1,-1):\n # remove cars that are faster than current car since it will never collide\n while stack and cars[i][1] <= cars[stack[-1]][1]: \n stack.pop()\n\n while stack: # if car left, we can compute collide time with current car. \n collision_t = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])\n # if current car\'s collide time is greater than previous car\'s collide time \n # (previous collided before current), then we have to find previous car\'s previous car\n # to compute collide time with that car, so we pop from stack and re-process\n # Otherwise, we add that collide time to answer and break\n if ans[stack[-1]] == -1 or collision_t <= ans[stack[-1]]:\n ans[i] = collision_t\n break\n stack.pop()\n stack.append(i)\n return ans\n```\n\n | 4 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
* `order[0]` will be the **root** of the binary search tree.
* All subsequent elements are inserted as the **child** of **any** existing node such that the binary search tree properties hold.
Return _the **depth** of the binary search tree_.
A binary tree's **depth** is the number of **nodes** along the **longest path** from the root node down to the farthest leaf node.
**Example 1:**
**Input:** order = \[2,1,4,3\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 2:**
**Input:** order = \[2,1,3,4\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 3:**
**Input:** order = \[1,2,3,4\]
**Output:** 4
**Explanation:** The binary search tree has a depth of 4 with path 1->2->3->4.
**Constraints:**
* `n == order.length`
* `1 <= n <= 105`
* `order` is a permutation of integers between `1` and `n`. | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection. |
monotonic stack + hashmaop Python 3 | car-fleet-ii | 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 getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n stack = [cars[-1]]\n res = {stack[-1][0]:-1}\n for i in reversed(range(len(cars)-1)):\n while stack:\n if stack[-1][1]>=cars[i][1]:\n stack.pop()\n else:\n time_to_hit = (stack[-1][0]-cars[i][0])/(cars[i][1]-stack[-1][1])\n if time_to_hit <= res[stack[-1][0]] or res[stack[-1][0]] ==-1:\n res[cars[i][0]]=time_to_hit\n stack.append(cars[i])\n break\n else:\n stack.pop()\n\n if len(stack)==0:\n stack = [cars[i]]\n res[cars[i][0]]=-1\n \n final_res = []\n for val in cars:\n final_res.append(res[val[0]])\n return final_res\n\n``` | 0 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`.
* `speedi` is the initial speed of the `ith` car in meters per second.
For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet.
Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted.
**Example 1:**
**Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\]
**Output:** \[1.00000,-1.00000,3.00000,-1.00000\]
**Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.
**Example 2:**
**Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\]
**Output:** \[2.00000,1.00000,1.50000,-1.00000\]
**Constraints:**
* `1 <= cars.length <= 105`
* `1 <= positioni, speedi <= 106`
* `positioni < positioni+1` | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
monotonic stack + hashmaop Python 3 | car-fleet-ii | 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 getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n stack = [cars[-1]]\n res = {stack[-1][0]:-1}\n for i in reversed(range(len(cars)-1)):\n while stack:\n if stack[-1][1]>=cars[i][1]:\n stack.pop()\n else:\n time_to_hit = (stack[-1][0]-cars[i][0])/(cars[i][1]-stack[-1][1])\n if time_to_hit <= res[stack[-1][0]] or res[stack[-1][0]] ==-1:\n res[cars[i][0]]=time_to_hit\n stack.append(cars[i])\n break\n else:\n stack.pop()\n\n if len(stack)==0:\n stack = [cars[i]]\n res[cars[i][0]]=-1\n \n final_res = []\n for val in cars:\n final_res.append(res[val[0]])\n return final_res\n\n``` | 0 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
The binary search tree is constructed as follows:
* `order[0]` will be the **root** of the binary search tree.
* All subsequent elements are inserted as the **child** of **any** existing node such that the binary search tree properties hold.
Return _the **depth** of the binary search tree_.
A binary tree's **depth** is the number of **nodes** along the **longest path** from the root node down to the farthest leaf node.
**Example 1:**
**Input:** order = \[2,1,4,3\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 2:**
**Input:** order = \[2,1,3,4\]
**Output:** 3
**Explanation:** The binary search tree has a depth of 3 with path 2->3->4.
**Example 3:**
**Input:** order = \[1,2,3,4\]
**Output:** 4
**Explanation:** The binary search tree has a depth of 4 with path 1->2->3->4.
**Constraints:**
* `n == order.length`
* `1 <= n <= 105`
* `order` is a permutation of integers between `1` and `n`. | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection. |
Python3 Easiest and Most understandable solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | The solution has three parts, \n1. Checking the validity of the given points.\n2. Finding the smallest Manhattan distance \n3. returning the index of the smallest Manhattan distance \n\nWe check if there are no valid points and return -1\n\n# Code\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n valid=[]\n for i in points:\n if i[0]==x or i[1]==y:\n valid.append(i)\n dist=[]\n if len(valid) == 0:\n return -1\n else :\n for i in valid:\n dist.append(abs(x - i[0]) + abs(y - i[1]))\n if valid[dist.index(min(dist))] in valid:\n return points.index(valid[dist.index(min(dist))])\n\n\n\n\n \n\n``` | 3 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104` | null |
Python3 Easiest and Most understandable solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | The solution has three parts, \n1. Checking the validity of the given points.\n2. Finding the smallest Manhattan distance \n3. returning the index of the smallest Manhattan distance \n\nWe check if there are no valid points and return -1\n\n# Code\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n valid=[]\n for i in points:\n if i[0]==x or i[1]==y:\n valid.append(i)\n dist=[]\n if len(valid) == 0:\n return -1\n else :\n for i in valid:\n dist.append(abs(x - i[0]) + abs(y - i[1]))\n if valid[dist.index(min(dist))] in valid:\n return points.index(valid[dist.index(min(dist))])\n\n\n\n\n \n\n``` | 3 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`. | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
[Python] Easy solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist<minDist:\n ans = i\n minDist = manDist\n return ans\n \n``` | 29 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104` | null |
[Python] Easy solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist<minDist:\n ans = i\n minDist = manDist\n return ans\n \n``` | 29 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`. | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Python - Clean and Simple! | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | **Solution**:\n```\nclass Solution:\n def nearestValidPoint(self, x1, y1, points):\n minIdx, minDist = -1, inf\n for i,point in enumerate(points):\n x2, y2 = point\n if x1 == x2 or y1 == y2:\n dist = abs(x1-x2) + abs(y1-y2)\n if dist < minDist:\n minIdx = i\n minDist = min(dist,minDist)\n return minIdx\n``` | 5 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104` | null |
Python - Clean and Simple! | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | **Solution**:\n```\nclass Solution:\n def nearestValidPoint(self, x1, y1, points):\n minIdx, minDist = -1, inf\n for i,point in enumerate(points):\n x2, y2 = point\n if x1 == x2 or y1 == y2:\n dist = abs(x1-x2) + abs(y1-y2)\n if dist < minDist:\n minIdx = i\n minDist = min(dist,minDist)\n return minIdx\n``` | 5 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`. | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Python for beginners 2 solutions | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: \n #Runtime:1167ms\n dic={}\n iterate=0\n for i in points:\n if(i[0]==x or i[1]==y):\n dic[iterate]=dic.get(iterate,0)+(abs(i[0]-x)+abs(i[1]-y))\n iterate+=1 \n #print(dic)\n if(len(dic)==0):\n return -1\n for k,v in sorted(dic.items(), key=lambda x:x[1]):\n return k\n```\n\nOptimizing above code:.....!\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n\t #Runtime:764ms\n mindist=math.inf\n ans=-1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n mandist=abs(points[i][0]-x)+abs(points[i][1]-y)\n if(mandist<mindist):\n ans=i\n mindist=mandist\n return ans \n\t\n``` | 1 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104` | null |
Python for beginners 2 solutions | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: \n #Runtime:1167ms\n dic={}\n iterate=0\n for i in points:\n if(i[0]==x or i[1]==y):\n dic[iterate]=dic.get(iterate,0)+(abs(i[0]-x)+abs(i[1]-y))\n iterate+=1 \n #print(dic)\n if(len(dic)==0):\n return -1\n for k,v in sorted(dic.items(), key=lambda x:x[1]):\n return k\n```\n\nOptimizing above code:.....!\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n\t #Runtime:764ms\n mindist=math.inf\n ans=-1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n mandist=abs(points[i][0]-x)+abs(points[i][1]-y)\n if(mandist<mindist):\n ans=i\n mindist=mandist\n return ans \n\t\n``` | 1 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`. | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Easy Python solution | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n sm=0\n val=16\n while val>=0:\n tmp=3**val\n if sm+tmp<n:\n sm+=tmp\n elif sm+tmp==n:return True\n val-=1\n return False\n``` | 3 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Example 2:**
**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34
**Example 3:**
**Input:** n = 21
**Output:** false
**Constraints:**
* `1 <= n <= 107` | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Easy Python solution | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n sm=0\n val=16\n while val>=0:\n tmp=3**val\n if sm+tmp<n:\n sm+=tmp\n elif sm+tmp==n:return True\n val-=1\n return False\n``` | 3 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces.
You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes.
* For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`.
Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\]
**Output:** 6
**Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
**Example 2:**
**Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** -1
**Explanation:** There is no box that the package of size 5 can fit in.
**Example 3:**
**Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\]
**Output:** 9
**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
**Constraints:**
* `n == packages.length`
* `m == boxes.length`
* `1 <= n <= 105`
* `1 <= m <= 105`
* `1 <= packages[i] <= 105`
* `1 <= boxes[j].length <= 105`
* `1 <= boxes[j][k] <= 105`
* `sum(boxes[j].length) <= 105`
* The elements in `boxes[j]` are **distinct**. | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python recursive solution with explanation | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Intuition\nThe problem requires us to check if the given integer n can be represented as a sum of distinct powers of 3. One way to approach this problem is to keep dividing the given number by 3 and check if the remainder is either 0 or 1. If we encounter a remainder of 2, we can directly return False as it cannot be represented as a sum of distinct powers of 3.\n\n# Approach\nThe approach we can take is to repeatedly divide the given number n by 3 until it becomes 0. During each division, we can check if the remainder is 2. If it is, we can return False as the number cannot be represented as a sum of distinct powers of 3. If the number becomes 0, we can return True as we have successfully represented the given number as a sum of distinct powers of 3.\n\n# Complexity\n- Time complexity: O(log n) - The time complexity of the solution is proportional to the number of times we need to divide the given number by 3 until it becomes 0. This is equivalent to the number of digi\n\n- Space complexity: O(1) - We are not using any additional data structures to solve this problem, so the space complexity is constant.\n\n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n if n%3==2:\n return False\n if n==1:\n return True\n return self.checkPowersOfThree(n//3)\n``` | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Example 2:**
**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34
**Example 3:**
**Input:** n = 21
**Output:** false
**Constraints:**
* `1 <= n <= 107` | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python recursive solution with explanation | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Intuition\nThe problem requires us to check if the given integer n can be represented as a sum of distinct powers of 3. One way to approach this problem is to keep dividing the given number by 3 and check if the remainder is either 0 or 1. If we encounter a remainder of 2, we can directly return False as it cannot be represented as a sum of distinct powers of 3.\n\n# Approach\nThe approach we can take is to repeatedly divide the given number n by 3 until it becomes 0. During each division, we can check if the remainder is 2. If it is, we can return False as the number cannot be represented as a sum of distinct powers of 3. If the number becomes 0, we can return True as we have successfully represented the given number as a sum of distinct powers of 3.\n\n# Complexity\n- Time complexity: O(log n) - The time complexity of the solution is proportional to the number of times we need to divide the given number by 3 until it becomes 0. This is equivalent to the number of digi\n\n- Space complexity: O(1) - We are not using any additional data structures to solve this problem, so the space complexity is constant.\n\n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n if n%3==2:\n return False\n if n==1:\n return True\n return self.checkPowersOfThree(n//3)\n``` | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces.
You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes.
* For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`.
Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\]
**Output:** 6
**Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
**Example 2:**
**Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** -1
**Explanation:** There is no box that the package of size 5 can fit in.
**Example 3:**
**Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\]
**Output:** 9
**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
**Constraints:**
* `n == packages.length`
* `m == boxes.length`
* `1 <= n <= 105`
* `1 <= m <= 105`
* `1 <= packages[i] <= 105`
* `1 <= boxes[j].length <= 105`
* `1 <= boxes[j][k] <= 105`
* `sum(boxes[j].length) <= 105`
* The elements in `boxes[j]` are **distinct**. | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python | Simple | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n def checkPowersOfThree(self, n: int) -> bool:\n while n > 0:\n if n%3 == 2:\n return False\n n //= 3\n return True | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Example 2:**
**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34
**Example 3:**
**Input:** n = 21
**Output:** false
**Constraints:**
* `1 <= n <= 107` | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python | Simple | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n def checkPowersOfThree(self, n: int) -> bool:\n while n > 0:\n if n%3 == 2:\n return False\n n //= 3\n return True | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces.
You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes.
* For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`.
Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\]
**Output:** 6
**Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
**Example 2:**
**Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** -1
**Explanation:** There is no box that the package of size 5 can fit in.
**Example 3:**
**Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\]
**Output:** 9
**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
**Constraints:**
* `n == packages.length`
* `m == boxes.length`
* `1 <= n <= 105`
* `1 <= m <= 105`
* `1 <= packages[i] <= 105`
* `1 <= boxes[j].length <= 105`
* `1 <= boxes[j][k] <= 105`
* `sum(boxes[j].length) <= 105`
* The elements in `boxes[j]` are **distinct**. | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python very easy Solution in O(log(n,3)) and O(1) 4 Line of Code | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while(n!=0):\n if(n%3>1):return False\n n//=3\n return True\n``` | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Example 2:**
**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34
**Example 3:**
**Input:** n = 21
**Output:** false
**Constraints:**
* `1 <= n <= 107` | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python very easy Solution in O(log(n,3)) and O(1) 4 Line of Code | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while(n!=0):\n if(n%3>1):return False\n n//=3\n return True\n``` | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are given as an integer array `packages`, where `packages[i]` is the **size** of the `ith` package. The suppliers are given as a 2D integer array `boxes`, where `boxes[j]` is an array of **box sizes** that the `jth` supplier produces.
You want to choose a **single supplier** and use boxes from them such that the **total wasted space** is **minimized**. For each package in a box, we define the space **wasted** to be `size of the box - size of the package`. The **total wasted space** is the sum of the space wasted in **all** the boxes.
* For example, if you have to fit packages with sizes `[2,3,5]` and the supplier offers boxes of sizes `[4,8]`, you can fit the packages of size-`2` and size-`3` into two boxes of size-`4` and the package with size-`5` into a box of size-`8`. This would result in a waste of `(4-2) + (4-3) + (8-5) = 6`.
Return _the **minimum total wasted space** by choosing the box supplier **optimally**, or_ `-1` _if it is **impossible** to fit all the packages inside boxes._ Since the answer may be **large**, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** packages = \[2,3,5\], boxes = \[\[4,8\],\[2,8\]\]
**Output:** 6
**Explanation**: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
The total waste is (4-2) + (4-3) + (8-5) = 6.
**Example 2:**
**Input:** packages = \[2,3,5\], boxes = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** -1
**Explanation:** There is no box that the package of size 5 can fit in.
**Example 3:**
**Input:** packages = \[3,5,8,10,11,12\], boxes = \[\[12\],\[11,9\],\[10,5,14\]\]
**Output:** 9
**Explanation:** It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.
The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.
**Constraints:**
* `n == packages.length`
* `m == boxes.length`
* `1 <= n <= 105`
* `1 <= m <= 105`
* `1 <= packages[i] <= 105`
* `1 <= boxes[j].length <= 105`
* `1 <= boxes[j][k] <= 105`
* `sum(boxes[j].length) <= 105`
* The elements in `boxes[j]` are **distinct**. | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Beats 100% - O(N^2) | Python | only using dictionary | sum-of-beauty-of-all-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a frequency groups and frequency dictionary to keep track of min and max frequency in string as we check all poosible \n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach time we traverse from i+1 to n we keep track of max/min frquency \nusing char_fre- dictionary used to track freq of each char. Also we have freq_group[f] which stores number of unique elements with frequency f.\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)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def beautySum(self, s: str) -> int:\n ans=0\n for i in range(len(s)):\n #initialise variables\n freq_groups=collections.defaultdict(int)\n char_freq={}\n max_freq,min_freq=1,1\n char_freq[s[i]]=1\n freq_groups[char_freq[s[i]]]=1\n\n for j in range(i+1,len(s)):\n if s[j] not in char_freq:\n char_freq[s[j]]=1\n min_freq=min(min_freq,1)\n freq_groups[char_freq[s[j]]]+=1\n ans+=max_freq-min_freq\n \n else:\n freq_groups[char_freq[s[j]]]-=1\n if freq_groups[char_freq[s[j]]]==0 and min_freq==char_freq[s[j]]:\n min_freq+=1\n char_freq[s[j]]+=1\n freq_groups[char_freq[s[j]]]+=1\n max_freq=max(char_freq[s[j]],max_freq)\n ans+=max_freq-min_freq\n return ans \n \n \n\n``` | 3 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explanation:** The substrings with non-zero beauty are \[ "aab ", "aabc ", "aabcb ", "abcb ", "bcb "\], each with beauty equal to 1.
**Example 2:**
**Input:** s = "aabcbaa "
**Output:** 17
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters. | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
[Python3] freq table | sum-of-beauty-of-all-substrings | 0 | 1 | \n```\nclass Solution:\n def beautySum(self, s: str) -> int:\n ans = 0 \n for i in range(len(s)):\n freq = [0]*26\n for j in range(i, len(s)):\n freq[ord(s[j])-97] += 1\n ans += max(freq) - min(x for x in freq if x)\n return ans \n``` | 55 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explanation:** The substrings with non-zero beauty are \[ "aab ", "aabc ", "aabcb ", "abcb ", "bcb "\], each with beauty equal to 1.
**Example 2:**
**Input:** s = "aabcbaa "
**Output:** 17
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters. | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
Python Easy Explanation(Beats 95%) | sum-of-beauty-of-all-substrings | 0 | 1 | # Intuition\nIn substring problems we try to generate all substrings and calculate what is asked of them. Most of the time we need to optimize the inner loop to reduce the time complexity for required solution.\n\n# Approach\n1. The problem wants us to find the sum of beauty(diff b/w most frequent and least frequent chars) of all substrings. The inner loop should calculate the maxFrequency(maxF) and minFrequency(minF) in that substring.\n2. Here we calculate the substrings and then maintain a dictionary of frequecies. \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def beautySum(self, s: str) -> int:\n # use dictionary to store the frequencies of characters at each index and calulcate the diff b/w most frequent nd least frequent chars\n ans = 0\n n = len(s)\n for i in range(n):\n freq = {}\n maxF = 0\n for j in range(i,n):\n\n if s[j] in freq:\n freq[s[j]] +=1\n \n else:\n freq[s[j]] = 1\n\n maxF = max(maxF, freq[s[j]])\n\n minF = min(freq.values())\n\n ans += (maxF-minF)\n\n return ans\n\n \n \n``` | 0 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explanation:** The substrings with non-zero beauty are \[ "aab ", "aabc ", "aabcb ", "abcb ", "bcb "\], each with beauty equal to 1.
**Example 2:**
**Input:** s = "aabcbaa "
**Output:** 17
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters. | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
Python 3 || Counters || T/M: 100%/88% | count-pairs-of-nodes | 0 | 1 | ```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n \n nodes = Counter(chain(*edges))\n nodes = {i:nodes[i] if i in nodes else 0 for i in range(1, n+1)}\n edges = Counter(map(lambda x:(min(x), max(x)), edges))\n \n n = 2 + 2*max(nodes.values())\n ans, ctr = [0] * n, Counter(nodes.values())\n\n for c1, c2 in list(product(ctr, ctr)):\n if c1 > c2: continue\n ans[c1+c2] += ctr[c1]*ctr[c2] if c1!=c2 else ctr[c1]*(ctr[c2]-1)//2\n\n for i, j in edges:\n sm = nodes[i] + nodes[j]\n ans[sm] -= 1\n ans[sm - edges[(i,j)]]+= 1\n\n ans = list(accumulate(ans[::-1]))[::-1]\n\n return [ans[min(q+1, n-1)] for q in queries] \n```\n\nI could be wrong, but I think that time complexity is *O*(*N*^2) and space complexity is *O*(*N*). | 4 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.
The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:
* `a < b`
* `incident(a, b) > queries[j]`
Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.
Note that there can be **multiple edges** between the same two nodes.
**Example 1:**
**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
**Example 2:**
**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]
**Constraints:**
* `2 <= n <= 2 * 104`
* `1 <= edges.length <= 105`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= queries.length <= 20`
* `0 <= queries[j] < edges.length` | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
[Python3] 2-pointer | count-pairs-of-nodes | 0 | 1 | \n```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n degree = [0]*n\n freq = defaultdict(int)\n for u, v in edges: \n degree[u-1] += 1\n degree[v-1] += 1\n freq[min(u-1, v-1), max(u-1, v-1)] += 1\n \n vals = sorted(degree)\n \n ans = []\n for query in queries: \n cnt = 0 \n lo, hi = 0, n-1\n while lo < hi: \n if query < vals[lo] + vals[hi]: \n cnt += hi - lo # (lo, hi), (lo+1, hi), ..., (hi-1, hi) all valid\n hi -= 1\n else: lo += 1\n for u, v in freq: \n if degree[u] + degree[v] - freq[u, v] <= query < degree[u] + degree[v]: cnt -= 1\n ans.append(cnt)\n return ans\n``` | 19 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.
The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:
* `a < b`
* `incident(a, b) > queries[j]`
Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.
Note that there can be **multiple edges** between the same two nodes.
**Example 1:**
**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
**Example 2:**
**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]
**Constraints:**
* `2 <= n <= 2 * 104`
* `1 <= edges.length <= 105`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= queries.length <= 20`
* `0 <= queries[j] < edges.length` | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
Python Easy Approach | Faster than 99% | O(20*N) | count-pairs-of-nodes | 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 countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n h = defaultdict(list)\n freq = defaultdict(int)\n for i in range(n):\n freq[i+1] = 0\n for i,j in edges:\n freq[i] += 1\n freq[j] += 1\n freq[(min(i, j), max(i,j))] += 1\n ans = []\n temp = [i for key,i in freq.items() if type(key) is int]\n rem = [key for key in freq if type(key) is not int]\n temp.sort()\n for val in queries:\n cnt = 0\n hi = len(temp)-1\n low = 0\n while low < hi:\n if temp[low] + temp[hi] > val:\n cnt += hi-low\n hi -= 1\n else:\n low += 1\n ans.append(cnt)\n print(temp)\n print(ans)\n for i,j in rem:\n val = freq[i] + freq[j] - freq[(i,j)]\n for x in range(len(queries)):\n if val <= queries[x] and freq[i] + freq[j] > queries[x]:\n # print(val, i, j, queries[x], freq[(i,j)])\n ans[x] -= 1\n return ans\n``` | 0 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.
The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:
* `a < b`
* `incident(a, b) > queries[j]`
Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.
Note that there can be **multiple edges** between the same two nodes.
**Example 1:**
**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
**Example 2:**
**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]
**Constraints:**
* `2 <= n <= 2 * 104`
* `1 <= edges.length <= 105`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= queries.length <= 20`
* `0 <= queries[j] < edges.length` | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
prefix sum of valid pairs based on number of incidents mapping to number of pairs per query | count-pairs-of-nodes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI claim no intuition for this one. It stumped me and I needed to go and break apart the current best answer to get an answer that would work and build up from there. Hopefully someday I\'m at the point to build this from scratch, but at the moment it\'s a great learning tool at least. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step was to get the frequency of each node in all of the edges \nWith this, we can then map the frequency of each node in our range of nodes \nThen, we can determine the frequency of the node pairs in the edges where each undirected edge is also mapped forward to back and back to forward. \nThe greatest frequency of nodes we have doubled and with 2 more is the maximum number of incidents we can have at any one time. This lets us then build our mapping eventually from the number of incidents to the number of pairs, and in doing so is a frequency based transform similar to a lagrangian. \n\nWe then map the frequency of the node frequencies to produce a map that says how many times each frequency signal was produced \n\nThen, we take the cartesian product of the number of times each frequency was produced and do the following for node frequency 1 and node frequency 2 \n- if node freq 1 gt node freq 2 -> continue \n- otherwise\n - get node freq sum as the sum of node freq 1 and node freq 2 \n - if they are not equal \n - our number of valid pairs for node freq sum is the product of number of times each of these frequencies occur \n - otherwise\n - our number of valid pairs for node freq sum is the number of pairs in the closed set of this frequency \n\nOnce that is done, we need to account for some overcounting in the cartesian product \n\nWe first need to address the fact that number of valid pairs at the sum of the node id\'s will be off by 1. This means we can reduce number of valid pairs at the sum of the node pairs for the frequency of node pairs by 1. We also need to account for the idea that the frequency of nodes a and b summed minus the frequency of the node pair for two given nodes forms an address relating the skipped and thus uncounted bidirectional pairing. We need to increment there by 1 in that case. \n\nFinally, we can get the prefix sum of our number of valid pairs. However, based on the stipulations, we need to get the prefix sum in reverse, and then need to reverse it back! This was due to a > b and incidents(a, b) < queries that was required. The mismatch causes the need to reverse once and then reverse again. \n\nFinally, we do not need the entire list, merely the parts at the rate locations. But how do we determine the proper mapping? Based on our query indexed values being 0 mapped and incidents being 1 mapped, we will need to adjust our ranges appropriately. \n\nFor this, we need to consider that \nFor q_i in queries \n- we want the number of valid pairs such that we use \n - the min of q_i + 1 and max incidents - 1 \n - the result of which is now stored in answer \n\nIf a list form of this is returned, it is accepted. \n\n# Complexity\n- Time complexity : O(N + E + max_incidents + F*F + Q)\n - O(E) to build frequency of nodes from edges \n - O(N) to build frequency of nodes using range function\n - O(E) to build frequency of node pairs \n - O(max incidents) to build number of valid pairs \n - O(N) to build frequency of node frequencies \n - O(F * F) to get cartesian product evaluation \n - O(E) to get frequency of node pairs \n - O(max incidents) to build answer \n - O(Q) to get final result \n\n- Space complexity : O(N + E + max_incidents + Q)\n - Complexity follows time for storage due to implementation procedures with exception of cartesian product \n\n# Code\n```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int] :\n # get the frequency of each node id in edges \n frequency_of_nodes = collections.Counter(chain(*edges))\n # get the frequency of each node id in order via an ordering process -> forces ordered dict like pattern via range \n frequency_of_nodes = {node : frequency_of_nodes[node] if node in frequency_of_nodes else 0 for node in range(1, n+1)}\n # get the frequency of each node pair in order related to the edges (puts them back to front properly)\n frequency_of_node_pairs = collections.Counter(map(lambda node_pair : (min(node_pair), max(node_pair)), edges))\n # we can at most have 2 + 2 * max frequency of node frequency incidents \n max_incidents = 2 + 2 * max(frequency_of_nodes.values())\n # from this we build our numbeer of valid pairs of size max incidents -> how many valid pairs occur for how many current incidents \n number_of_valid_pairs = [0] * max_incidents\n # and from the individual node frequencies we build a counter of the frequency of the frequencies \n frequency_of_node_frequencies = collections.Counter(frequency_of_nodes.values())\n\n # get cartesian product of the frequency of node frequencies \n for node_freq_1, node_freq_2 in product(frequency_of_node_frequencies, frequency_of_node_frequencies) : \n # if out of order, continue \n if node_freq_1 > node_freq_2 : \n continue \n else : \n # get node frequency sum as the key to utilize here \n node_freq_sum = node_freq_1 + node_freq_2\n # if non-equal \n if node_freq_1 != node_freq_2 :\n # pairing update is based on the frequency of each node frequencies node frequency \n number_of_valid_pairs[node_freq_sum] += frequency_of_node_frequencies[node_freq_1] * frequency_of_node_frequencies[node_freq_2]\n else : \n # otherwise it is simply the number of pairs you can form from the closed set on this frequency \n number_of_valid_pairs[node_freq_sum] += frequency_of_node_frequencies[node_freq_1] * (frequency_of_node_frequencies[node_freq_2] - 1)//2\n \n # update cartesian product results by first reducing by 1 each instance of frequency key sum to avoid over counting \n for node_a, node_b in frequency_of_node_pairs : \n frequency_key_sum = frequency_of_nodes[node_a] + frequency_of_nodes[node_b]\n # one additional at frequency key sum will be presented by this product \n number_of_valid_pairs[frequency_key_sum] -= 1 \n # then incrementing by 1 the associated offset for the frequency key sum difference with the frequency of this node pairing to account for this pair \n number_of_valid_pairs[frequency_key_sum - frequency_of_node_pairs[(node_a, node_b)]] += 1 \n \n # build answer as the prefix sum of our valid pairs in reverse, then reverse it back \n answer = list(accumulate(number_of_valid_pairs[::-1]))[::-1]\n \n # now, for each q_i, answer at min of q_i + 1 and max incidents - 1 -> maximum total incidents reached or q_i + 1 for 1 offset \n # and based on that, the reversed prefix sum of valid pairs reversed at this location is the number of valid pairs at that time \n return [answer[min(q_i + 1, max_incidents - 1)] for q_i in queries]\n``` | 0 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.
The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:
* `a < b`
* `incident(a, b) > queries[j]`
Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.
Note that there can be **multiple edges** between the same two nodes.
**Example 1:**
**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
**Example 2:**
**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]
**Constraints:**
* `2 <= n <= 2 * 104`
* `1 <= edges.length <= 105`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= queries.length <= 20`
* `0 <= queries[j] < edges.length` | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
[Python 3] Simple solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe string is not leading by \'0\', it means it starts by \'1\'. Thus the satisfy string has the form \'1111...0\' or \'1111...111\'. Thus there must not exist \'01\' form in correct string, otherwise it is false\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return not "01" in s\n``` | 4 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
[Python 3] Simple solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe string is not leading by \'0\', it means it starts by \'1\'. Thus the satisfy string has the form \'1111...0\' or \'1111...111\'. Thus there must not exist \'01\' form in correct string, otherwise it is false\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return not "01" in s\n``` | 4 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
[Python 3] - Check for "01" (1 Liner) | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | **Solution 1**: Check for ```"01"```\nSince the input string cannot ```s``` cannot have any leading zeroes and must contain ```at most one contiguous segment of 1s```, we need to check if ```"01"``` is present in ```s``` or not. If it is present, we can return False, else True.\n\nA few testcases to help understand the intuition:\n1. ```1100``` - True\n2. ```11001``` - False (since ```01``` is present).\n3. ```111111000000``` - True\n4. ```1101010100``` - False\n5. ```1``` - True\n6. ```1111110000111``` - False\n\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return "01" not in s\n```\n<br>\n<br>\n\n**Solution 2**: Using ```strip()```\n```strip("0")``` will remove both the leading and trailing zeroes in the string. Thus, if zeroes are present inside the string, the output must be False.\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n s = s.strip("0")\n return ("0" not in s)\n```\n | 38 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
[Python 3] - Check for "01" (1 Liner) | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | **Solution 1**: Check for ```"01"```\nSince the input string cannot ```s``` cannot have any leading zeroes and must contain ```at most one contiguous segment of 1s```, we need to check if ```"01"``` is present in ```s``` or not. If it is present, we can return False, else True.\n\nA few testcases to help understand the intuition:\n1. ```1100``` - True\n2. ```11001``` - False (since ```01``` is present).\n3. ```111111000000``` - True\n4. ```1101010100``` - False\n5. ```1``` - True\n6. ```1111110000111``` - False\n\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return "01" not in s\n```\n<br>\n<br>\n\n**Solution 2**: Using ```strip()```\n```strip("0")``` will remove both the leading and trailing zeroes in the string. Thus, if zeroes are present inside the string, the output must be False.\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n s = s.strip("0")\n return ("0" not in s)\n```\n | 38 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python3 one liner and explanatory solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n #1st Approach\n # for i in range(len(s)):\n # if s[i] == \'0\':\n # if s[i:].count(\'1\') > 0:\n # return False\n # return True\n\n #2nd Approach\n # return \'1\' not in s[s.index(\'0\'):] if \'0\' in s else True\n\n\n #3rd Approach\n return \'01\' not in s\n``` | 2 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Python3 one liner and explanatory solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n #1st Approach\n # for i in range(len(s)):\n # if s[i] == \'0\':\n # if s[i:].count(\'1\') > 0:\n # return False\n # return True\n\n #2nd Approach\n # return \'1\' not in s[s.index(\'0\'):] if \'0\' in s else True\n\n\n #3rd Approach\n return \'01\' not in s\n``` | 2 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python regex easy solution | check-if-binary-string-has-at-most-one-segment-of-ones | 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```\nimport re\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n res = re.search(r\'^1+0*\n```,s)\n return True if res else False\n \n``` | 1 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Python regex easy solution | check-if-binary-string-has-at-most-one-segment-of-ones | 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```\nimport re\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n res = re.search(r\'^1+0*\n```,s)\n return True if res else False\n \n``` | 1 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Check if Binary String Has at Most One Segment of Ones | check-if-binary-string-has-at-most-one-segment-of-ones | 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 checkOnesSegment(self, s: str) -> bool:\n splitList = s.split(\'0\') # \u5C06\u5B57\u7B26\u4E32 s \u6309 0 \u5206\u6BB5\uFF0C\u5E76\u5C06\u5206\u6BB5\u540E\u7684\u5B57\u7B26\u4E32\u5217\u8868\u8D4B\u503C\u7ED9\u53D8\u91CF splitList\n # splitList.pop(splitList.index(max(s.split(\'0\'))))\n # \u5220\u6389 splitList \u4E2D\u7684\u6700\u5927\u503C\n splitList.remove(max(splitList))\n if splitList != [] and max(splitList).isdigit():\n return False\n else:\n return True \n\n``` | 0 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Check if Binary String Has at Most One Segment of Ones | check-if-binary-string-has-at-most-one-segment-of-ones | 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 checkOnesSegment(self, s: str) -> bool:\n splitList = s.split(\'0\') # \u5C06\u5B57\u7B26\u4E32 s \u6309 0 \u5206\u6BB5\uFF0C\u5E76\u5C06\u5206\u6BB5\u540E\u7684\u5B57\u7B26\u4E32\u5217\u8868\u8D4B\u503C\u7ED9\u53D8\u91CF splitList\n # splitList.pop(splitList.index(max(s.split(\'0\'))))\n # \u5220\u6389 splitList \u4E2D\u7684\u6700\u5927\u503C\n splitList.remove(max(splitList))\n if splitList != [] and max(splitList).isdigit():\n return False\n else:\n return True \n\n``` | 0 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
A python solution | check-if-binary-string-has-at-most-one-segment-of-ones | 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 checkOnesSegment(self, s: str) -> bool:\n ju=True\n # \u81EAs\u7B2C\u4E8C\u4E2A\u5B57\u7B26\u8D77\u904D\u5386\u5B57\u7B26\n for i in s[1:]:\n # \u5224\u65AD\u662F\u5426\u51FA\u73B0"0",\u5E76\u8BB0\u5F55\n if i=="0":\n ju=False\n # \u82E5\u51FA\u73B0"0"\u540E\u53C8\u51FA\u73B0"1"\u5219\u8FD4\u56DEFalse\n elif i=="1" and not ju:\n return False\n # \u5FAA\u73AF\u5B8C\u6210\u5219\u8FD4\u56DETrue\n return True\n``` | 0 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
A python solution | check-if-binary-string-has-at-most-one-segment-of-ones | 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 checkOnesSegment(self, s: str) -> bool:\n ju=True\n # \u81EAs\u7B2C\u4E8C\u4E2A\u5B57\u7B26\u8D77\u904D\u5386\u5B57\u7B26\n for i in s[1:]:\n # \u5224\u65AD\u662F\u5426\u51FA\u73B0"0",\u5E76\u8BB0\u5F55\n if i=="0":\n ju=False\n # \u82E5\u51FA\u73B0"0"\u540E\u53C8\u51FA\u73B0"1"\u5219\u8FD4\u56DEFalse\n elif i=="1" and not ju:\n return False\n # \u5FAA\u73AF\u5B8C\u6210\u5219\u8FD4\u56DETrue\n return True\n``` | 0 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python Elegant & Short | 1-Line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nfrom math import ceil\n\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return ceil(abs(sum(nums) - goal) / limit)\n\n``` | 1 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109` | null |
Python Elegant & Short | 1-Line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nfrom math import ceil\n\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return ceil(abs(sum(nums) - goal) / limit)\n\n``` | 1 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit. |
Python 3 | 1-liner | Explanation | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | ### Explanation\n- Find the absolute difference\n- Add new numbers using `limit`, count how many numbers need to be added using `ceil`\n### Implementation\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n``` | 6 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109` | null |
Python 3 | 1-liner | Explanation | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | ### Explanation\n- Find the absolute difference\n- Add new numbers using `limit`, count how many numbers need to be added using `ceil`\n### Implementation\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n``` | 6 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit. |
One line Python answer | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return abs(sum(nums)-goal)//limit if abs(sum(nums)-goal)%limit==0 else abs(sum(nums)-goal)//limit+1\n``` | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109` | null |
One line Python answer | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return abs(sum(nums)-goal)//limit if abs(sum(nums)-goal)%limit==0 else abs(sum(nums)-goal)//limit+1\n``` | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit. |
Half Liner LOL | Beginner Friendly Explanations | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Explanation\nBrute force some examples and it will become clear that the difference ```diff``` (how much should we add to reach ```goal```) can be either +/-. And it does not matter.\n\nReason is because to reach the goal, we must add numbers. Now as this is not a proof, we can say that the sign of the difference depends on the sign of the goal. [convince this to yourself]\n\nNow we need to fill in the difference ```diff``` such that we dont exceed the limit. \n\nGreedily choose the limit and fill until ```diff``` is exhausted. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n diff=abs(goal-sum(nums))\n return (diff//limit) if not diff%limit else (diff//limit)+1\n``` | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109` | null |
Half Liner LOL | Beginner Friendly Explanations | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Explanation\nBrute force some examples and it will become clear that the difference ```diff``` (how much should we add to reach ```goal```) can be either +/-. And it does not matter.\n\nReason is because to reach the goal, we must add numbers. Now as this is not a proof, we can say that the sign of the difference depends on the sign of the goal. [convince this to yourself]\n\nNow we need to fill in the difference ```diff``` such that we dont exceed the limit. \n\nGreedily choose the limit and fill until ```diff``` is exhausted. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n diff=abs(goal-sum(nums))\n return (diff//limit) if not diff%limit else (diff//limit)+1\n``` | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit. |
Python - one line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return 0 if sum(nums) == goal else ceil(abs(goal - sum(nums)) / limit)\n \n``` | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** nums = \[1,-1,1\], limit = 3, goal = -4
**Output:** 2
**Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.
**Example 2:**
**Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= limit <= 106`
* `-limit <= nums[i] <= limit`
* `-109 <= goal <= 109` | null |
Python - one line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return 0 if sum(nums) == goal else ceil(abs(goal - sum(nums)) / limit)\n \n``` | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any subsequence of_ `nums` _(after **reindexing** the elements of the subsequence)_.
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** nums = \[4,2,5,3\]
**Output:** 7
**Explanation:** It is optimal to choose the subsequence \[4,2,5\] with alternating sum (4 + 5) - 2 = 7.
**Example 2:**
**Input:** nums = \[5,6,7,8\]
**Output:** 8
**Explanation:** It is optimal to choose the subsequence \[8\] with alternating sum 8.
**Example 3:**
**Input:** nums = \[6,2,1,2,4,5\]
**Output:** 10
**Explanation:** It is optimal to choose the subsequence \[6,1,5\] with alternating sum (6 + 5) - 1 = 10.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit. |
[Python3] Dijkstra + Cache DFS ~ DP Top-down Memorization - Simple | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(V)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V + E)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n if n == 1: return 0\n g = collections.defaultdict(list)\n sum_w, mod = 0, 10 ** 9 + 7\n for u, v, w in edges:\n g[u].append((w, v))\n g[v].append((w, u))\n sum_w += w\n \n def dijkstra() -> List[int]:\n pq = [(0, n)]\n distance = [sum_w + 1 for _ in range(n + 1)]\n distance[n] = 0\n while pq:\n w, u = heapq.heappop(pq)\n for v_w, v in g[u]:\n if w + v_w < distance[v]:\n distance[v] = w + v_w\n heapq.heappush(pq, (w + v_w, v))\n return distance\n \n @cache\n def dfs(u: int) -> int:\n if u == n: return 1\n cnt = 0\n for _, v in g[u]:\n if distance[u] > distance[v]: cnt = (cnt + dfs(v)) % mod\n \n return cnt\n \n distance = dijkstra()\n return dfs(1)\n\n``` | 3 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes. | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
[Python3] Dijkstra + Cache DFS ~ DP Top-down Memorization - Simple | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(V)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V + E)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n if n == 1: return 0\n g = collections.defaultdict(list)\n sum_w, mod = 0, 10 ** 9 + 7\n for u, v, w in edges:\n g[u].append((w, v))\n g[v].append((w, u))\n sum_w += w\n \n def dijkstra() -> List[int]:\n pq = [(0, n)]\n distance = [sum_w + 1 for _ in range(n + 1)]\n distance[n] = 0\n while pq:\n w, u = heapq.heappop(pq)\n for v_w, v in g[u]:\n if w + v_w < distance[v]:\n distance[v] = w + v_w\n heapq.heappush(pq, (w + v_w, v))\n return distance\n \n @cache\n def dfs(u: int) -> int:\n if u == n: return 1\n cnt = 0\n for _, v in g[u]:\n if distance[u] > distance[v]: cnt = (cnt + dfs(v)) % mod\n \n return cnt\n \n distance = dijkstra()\n return dfs(1)\n\n``` | 3 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi, moviei, pricei]` indicates that there is a copy of movie `moviei` at shop `shopi` with a rental price of `pricei`. Each shop carries **at most one** copy of a movie `moviei`.
The system should support the following functions:
* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopi` should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
* **Rent**: Rents an **unrented copy** of a given movie from a given shop.
* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop.
* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where `res[j] = [shopj, moviej]` describes that the `jth` cheapest rented movie `moviej` was rented from the shop `shopj`. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopj` should appear first, and if there is still tie, the one with the **smaller** `moviej` should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the `MovieRentingSystem` class:
* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`.
* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above.
* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`.
* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`.
* `List> report()` Returns a list of cheapest **rented** movies as described above.
**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie.
**Example 1:**
**Input**
\[ "MovieRentingSystem ", "search ", "rent ", "rent ", "report ", "drop ", "search "\]
\[\[3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]\], \[1\], \[0, 1\], \[1, 2\], \[\], \[1, 2\], \[2\]\]
**Output**
\[null, \[1, 0, 2\], null, null, \[\[0, 1\], \[1, 2\]\], null, \[0, 1\]\]
**Explanation**
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]);
movieRentingSystem.search(1); // return \[1, 0, 2\], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now \[2,3\].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now \[1\].
movieRentingSystem.report(); // return \[\[0, 1\], \[1, 2\]\]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now \[1,2\].
movieRentingSystem.search(2); // return \[0, 1\]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
**Constraints:**
* `1 <= n <= 3 * 105`
* `1 <= entries.length <= 105`
* `0 <= shopi < n`
* `1 <= moviei, pricei <= 104`
* Each shop carries **at most one** copy of a movie `moviei`.
* At most `105` calls **in total** will be made to `search`, `rent`, `drop` and `report`. | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem. |
[Python3] Dijkstra + dp | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n dist = {n: 0}\n while queue: \n newq = []\n for u in queue: \n for v, w in graph[u]:\n if v not in dist or dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n newq.append(v)\n queue = newq\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(1) % 1_000_000_007\n```\n\nEdited on 3/7/2021\nAdding the implemetation via Dijkstra\'s algo\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u-1, []).append((v-1, w))\n graph.setdefault(v-1, []).append((u-1, w))\n \n # dijkstra\'s algo\n pq = [(0, n-1)]\n dist = [inf]*(n-1) + [0]\n while pq: \n d, u = heappop(pq)\n for v, w in graph[u]: \n if dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n heappush(pq, (dist[v], v))\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n-1: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(0) % 1_000_000_007\n``` | 4 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes. | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
[Python3] Dijkstra + dp | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n dist = {n: 0}\n while queue: \n newq = []\n for u in queue: \n for v, w in graph[u]:\n if v not in dist or dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n newq.append(v)\n queue = newq\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(1) % 1_000_000_007\n```\n\nEdited on 3/7/2021\nAdding the implemetation via Dijkstra\'s algo\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u-1, []).append((v-1, w))\n graph.setdefault(v-1, []).append((u-1, w))\n \n # dijkstra\'s algo\n pq = [(0, n-1)]\n dist = [inf]*(n-1) + [0]\n while pq: \n d, u = heappop(pq)\n for v, w in graph[u]: \n if dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n heappush(pq, (dist[v], v))\n \n @cache\n def fn(u): \n """Return number of restricted paths from u to n."""\n if u == n-1: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(0) % 1_000_000_007\n``` | 4 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi, moviei, pricei]` indicates that there is a copy of movie `moviei` at shop `shopi` with a rental price of `pricei`. Each shop carries **at most one** copy of a movie `moviei`.
The system should support the following functions:
* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopi` should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
* **Rent**: Rents an **unrented copy** of a given movie from a given shop.
* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop.
* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where `res[j] = [shopj, moviej]` describes that the `jth` cheapest rented movie `moviej` was rented from the shop `shopj`. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopj` should appear first, and if there is still tie, the one with the **smaller** `moviej` should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the `MovieRentingSystem` class:
* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`.
* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above.
* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`.
* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`.
* `List> report()` Returns a list of cheapest **rented** movies as described above.
**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie.
**Example 1:**
**Input**
\[ "MovieRentingSystem ", "search ", "rent ", "rent ", "report ", "drop ", "search "\]
\[\[3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]\], \[1\], \[0, 1\], \[1, 2\], \[\], \[1, 2\], \[2\]\]
**Output**
\[null, \[1, 0, 2\], null, null, \[\[0, 1\], \[1, 2\]\], null, \[0, 1\]\]
**Explanation**
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]);
movieRentingSystem.search(1); // return \[1, 0, 2\], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now \[2,3\].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now \[1\].
movieRentingSystem.report(); // return \[\[0, 1\], \[1, 2\]\]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now \[1,2\].
movieRentingSystem.search(2); // return \[0, 1\]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
**Constraints:**
* `1 <= n <= 3 * 105`
* `1 <= entries.length <= 105`
* `0 <= shopi < n`
* `1 <= moviei, pricei <= 104`
* Each shop carries **at most one** copy of a movie `moviei`.
* At most `105` calls **in total** will be made to `search`, `rent`, `drop` and `report`. | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem. |
Python 3 | Dijkstra, DFS, DAG pruning | Explanation | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | ### Implementation\n- The solution is basically an implementation based on `hint`, please seee below comments for detail\n### Explanation\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b, w in edges:\n graph[a].append((w, b))\n graph[b].append((w, a))\n heap = graph[n]\n heapq.heapify(heap)\n d = {n: 0}\n while heap: # Dijkstra from node `n` to other nodes, record shortest distance to each node\n cur_w, cur = heapq.heappop(heap)\n if cur in d: continue\n d[cur] = cur_w\n for w, nei in graph[cur]:\n heapq.heappush(heap, (w+cur_w, nei))\n graph = collections.defaultdict(list)\n for a, b, w in edges: # pruning based on `restricted` condition, make undirected graph to directed-acyclic graph\n if d[a] > d[b]:\n graph[a].append(b)\n elif d[a] < d[b]:\n graph[b].append(a)\n ans, mod = 0, int(1e9+7)\n @cache\n def dfs(node): # use DFS to find total number of paths\n if node == n:\n return 1\n cur = 0 \n for nei in graph[node]:\n cur = (cur + dfs(nei)) % mod\n return cur \n return dfs(1)\n``` | 3 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes. | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
Python 3 | Dijkstra, DFS, DAG pruning | Explanation | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | ### Implementation\n- The solution is basically an implementation based on `hint`, please seee below comments for detail\n### Explanation\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b, w in edges:\n graph[a].append((w, b))\n graph[b].append((w, a))\n heap = graph[n]\n heapq.heapify(heap)\n d = {n: 0}\n while heap: # Dijkstra from node `n` to other nodes, record shortest distance to each node\n cur_w, cur = heapq.heappop(heap)\n if cur in d: continue\n d[cur] = cur_w\n for w, nei in graph[cur]:\n heapq.heappush(heap, (w+cur_w, nei))\n graph = collections.defaultdict(list)\n for a, b, w in edges: # pruning based on `restricted` condition, make undirected graph to directed-acyclic graph\n if d[a] > d[b]:\n graph[a].append(b)\n elif d[a] < d[b]:\n graph[b].append(a)\n ans, mod = 0, int(1e9+7)\n @cache\n def dfs(node): # use DFS to find total number of paths\n if node == n:\n return 1\n cur = 0 \n for nei in graph[node]:\n cur = (cur + dfs(nei)) % mod\n return cur \n return dfs(1)\n``` | 3 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi, moviei, pricei]` indicates that there is a copy of movie `moviei` at shop `shopi` with a rental price of `pricei`. Each shop carries **at most one** copy of a movie `moviei`.
The system should support the following functions:
* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopi` should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
* **Rent**: Rents an **unrented copy** of a given movie from a given shop.
* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop.
* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where `res[j] = [shopj, moviej]` describes that the `jth` cheapest rented movie `moviej` was rented from the shop `shopj`. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopj` should appear first, and if there is still tie, the one with the **smaller** `moviej` should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the `MovieRentingSystem` class:
* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`.
* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above.
* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`.
* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`.
* `List> report()` Returns a list of cheapest **rented** movies as described above.
**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie.
**Example 1:**
**Input**
\[ "MovieRentingSystem ", "search ", "rent ", "rent ", "report ", "drop ", "search "\]
\[\[3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]\], \[1\], \[0, 1\], \[1, 2\], \[\], \[1, 2\], \[2\]\]
**Output**
\[null, \[1, 0, 2\], null, null, \[\[0, 1\], \[1, 2\]\], null, \[0, 1\]\]
**Explanation**
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]);
movieRentingSystem.search(1); // return \[1, 0, 2\], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now \[2,3\].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now \[1\].
movieRentingSystem.report(); // return \[\[0, 1\], \[1, 2\]\]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now \[1,2\].
movieRentingSystem.search(2); // return \[0, 1\]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
**Constraints:**
* `1 <= n <= 3 * 105`
* `1 <= entries.length <= 105`
* `0 <= shopi < n`
* `1 <= moviei, pricei <= 104`
* Each shop carries **at most one** copy of a movie `moviei`.
* At most `105` calls **in total** will be made to `search`, `rent`, `drop` and `report`. | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem. |
similar to 1976. Number of Ways to Arrive at Destination | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Find all dist from node i to n\n- use dfs top down + memo to find how many ways\n- restricted path is non-increasing path from node 1 to n, not shortest path\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)$$ -->\nO(ElogV + V), dp is V\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(V + E)\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n g, mod = defaultdict(list), 10 ** 9 + 7\n # dfs + memo\n @lru_cache(None)\n def dfs(cur):\n if cur == n:\n return 1\n res = 0\n for (nei, w) in g[cur]:\n # no need to maintain set, it\'s impossible to go back\n if dist[cur] > dist[nei]: \n res += dfs(nei)\n return res\n # dijkstra\n for u, v, w in edges:\n g[u].append((v, w))\n g[v].append((u, w))\n \n dist = [inf] * (n + 1)\n dist[n] = 0\n visited = set()\n pq = [(0, n)]\n while pq:\n d, cur = heappop(pq)\n visited.add(cur)\n for (nei, w) in g[cur]:\n if nei not in visited:\n new_dist = d + w\n if new_dist < dist[nei]:\n heappush(pq, (new_dist, nei))\n dist[nei] = new_dist\n res = dfs(1)\n return res % mod\n``` | 0 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes. | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
similar to 1976. Number of Ways to Arrive at Destination | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Find all dist from node i to n\n- use dfs top down + memo to find how many ways\n- restricted path is non-increasing path from node 1 to n, not shortest path\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)$$ -->\nO(ElogV + V), dp is V\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(V + E)\n# Code\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n g, mod = defaultdict(list), 10 ** 9 + 7\n # dfs + memo\n @lru_cache(None)\n def dfs(cur):\n if cur == n:\n return 1\n res = 0\n for (nei, w) in g[cur]:\n # no need to maintain set, it\'s impossible to go back\n if dist[cur] > dist[nei]: \n res += dfs(nei)\n return res\n # dijkstra\n for u, v, w in edges:\n g[u].append((v, w))\n g[v].append((u, w))\n \n dist = [inf] * (n + 1)\n dist[n] = 0\n visited = set()\n pq = [(0, n)]\n while pq:\n d, cur = heappop(pq)\n visited.add(cur)\n for (nei, w) in g[cur]:\n if nei not in visited:\n new_dist = d + w\n if new_dist < dist[nei]:\n heappush(pq, (new_dist, nei))\n dist[nei] = new_dist\n res = dfs(1)\n return res % mod\n``` | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi, moviei, pricei]` indicates that there is a copy of movie `moviei` at shop `shopi` with a rental price of `pricei`. Each shop carries **at most one** copy of a movie `moviei`.
The system should support the following functions:
* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopi` should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
* **Rent**: Rents an **unrented copy** of a given movie from a given shop.
* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop.
* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where `res[j] = [shopj, moviej]` describes that the `jth` cheapest rented movie `moviej` was rented from the shop `shopj`. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopj` should appear first, and if there is still tie, the one with the **smaller** `moviej` should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the `MovieRentingSystem` class:
* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`.
* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above.
* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`.
* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`.
* `List> report()` Returns a list of cheapest **rented** movies as described above.
**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie.
**Example 1:**
**Input**
\[ "MovieRentingSystem ", "search ", "rent ", "rent ", "report ", "drop ", "search "\]
\[\[3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]\], \[1\], \[0, 1\], \[1, 2\], \[\], \[1, 2\], \[2\]\]
**Output**
\[null, \[1, 0, 2\], null, null, \[\[0, 1\], \[1, 2\]\], null, \[0, 1\]\]
**Explanation**
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]);
movieRentingSystem.search(1); // return \[1, 0, 2\], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now \[2,3\].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now \[1\].
movieRentingSystem.report(); // return \[\[0, 1\], \[1, 2\]\]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now \[1,2\].
movieRentingSystem.search(2); // return \[0, 1\]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
**Constraints:**
* `1 <= n <= 3 * 105`
* `1 <= entries.length <= 105`
* `0 <= shopi < n`
* `1 <= moviei, pricei <= 104`
* Each shop carries **at most one** copy of a movie `moviei`.
* At most `105` calls **in total** will be made to `search`, `rent`, `drop` and `report`. | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem. |
Python 3 | Very fast | Dijkstra algo + DP (dfs + memoization) | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n def count_path_from(node, mod):\n """ To be used in the directed graph\n Return the number of paths from node to n (modulo mod)\n """\n if n_path_from[node] != -1:\n return n_path_from[node]\n ans = 0\n for neighb in adj[node]:\n ans += count_path_from(neighb, mod)\n n_path_from[node] = ans\n return ans % mod\n \n # We create the adjacency lists of the graph\n adj = [[] for _ in range(n + 1)]\n for u, v, w in edges:\n adj[u].append((v, w))\n adj[v].append((u, w))\n\n # Dijkstra algorithm\n INF = 10 ** 10\n dist = [INF] * (n + 1)\n dist[n] = 0 # The distance from n to n is 0\n visited = [False] * (n + 1) # To mark the visited nodes\n to_process = []\n heappush(to_process, (dist[n], n))\n while to_process:\n dc, curr = heappop(to_process)\n if not visited[curr]:\n visited[curr] = True\n for neighb, dn in adj[curr]:\n if not visited[neighb] and dc + dn < dist[neighb]:\n dist[neighb] = dc + dn\n heappush(to_process, (dist[neighb], neighb))\n\n # New graph will be directed. We keep only edges with a decreasing distance from start to end\n for u, lst in enumerate(adj[1:], 1):\n nlst = []\n for v, _ in lst:\n if dist[u] > dist[v]:\n nlst.append(v)\n adj[u] = nlst\n\n # DP with DFS (funtion count_path_from) and a memoization list \n n_path_from = [-1] * (n + 1)\n n_path_from[n] = 1\n return count_path_from(1, 1_000_000_007)\n\n\n``` | 0 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes. | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
Python 3 | Very fast | Dijkstra algo + DP (dfs + memoization) | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n def count_path_from(node, mod):\n """ To be used in the directed graph\n Return the number of paths from node to n (modulo mod)\n """\n if n_path_from[node] != -1:\n return n_path_from[node]\n ans = 0\n for neighb in adj[node]:\n ans += count_path_from(neighb, mod)\n n_path_from[node] = ans\n return ans % mod\n \n # We create the adjacency lists of the graph\n adj = [[] for _ in range(n + 1)]\n for u, v, w in edges:\n adj[u].append((v, w))\n adj[v].append((u, w))\n\n # Dijkstra algorithm\n INF = 10 ** 10\n dist = [INF] * (n + 1)\n dist[n] = 0 # The distance from n to n is 0\n visited = [False] * (n + 1) # To mark the visited nodes\n to_process = []\n heappush(to_process, (dist[n], n))\n while to_process:\n dc, curr = heappop(to_process)\n if not visited[curr]:\n visited[curr] = True\n for neighb, dn in adj[curr]:\n if not visited[neighb] and dc + dn < dist[neighb]:\n dist[neighb] = dc + dn\n heappush(to_process, (dist[neighb], neighb))\n\n # New graph will be directed. We keep only edges with a decreasing distance from start to end\n for u, lst in enumerate(adj[1:], 1):\n nlst = []\n for v, _ in lst:\n if dist[u] > dist[v]:\n nlst.append(v)\n adj[u] = nlst\n\n # DP with DFS (funtion count_path_from) and a memoization list \n n_path_from = [-1] * (n + 1)\n n_path_from[n] = 1\n return count_path_from(1, 1_000_000_007)\n\n\n``` | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi, moviei, pricei]` indicates that there is a copy of movie `moviei` at shop `shopi` with a rental price of `pricei`. Each shop carries **at most one** copy of a movie `moviei`.
The system should support the following functions:
* **Search**: Finds the **cheapest 5 shops** that have an **unrented copy** of a given movie. The shops should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopi` should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.
* **Rent**: Rents an **unrented copy** of a given movie from a given shop.
* **Drop**: Drops off a **previously rented copy** of a given movie at a given shop.
* **Report**: Returns the **cheapest 5 rented movies** (possibly of the same movie ID) as a 2D list `res` where `res[j] = [shopj, moviej]` describes that the `jth` cheapest rented movie `moviej` was rented from the shop `shopj`. The movies in `res` should be sorted by **price** in ascending order, and in case of a tie, the one with the **smaller** `shopj` should appear first, and if there is still tie, the one with the **smaller** `moviej` should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.
Implement the `MovieRentingSystem` class:
* `MovieRentingSystem(int n, int[][] entries)` Initializes the `MovieRentingSystem` object with `n` shops and the movies in `entries`.
* `List search(int movie)` Returns a list of shops that have an **unrented copy** of the given `movie` as described above.
* `void rent(int shop, int movie)` Rents the given `movie` from the given `shop`.
* `void drop(int shop, int movie)` Drops off a previously rented `movie` at the given `shop`.
* `List> report()` Returns a list of cheapest **rented** movies as described above.
**Note:** The test cases will be generated such that `rent` will only be called if the shop has an **unrented** copy of the movie, and `drop` will only be called if the shop had **previously rented** out the movie.
**Example 1:**
**Input**
\[ "MovieRentingSystem ", "search ", "rent ", "rent ", "report ", "drop ", "search "\]
\[\[3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]\], \[1\], \[0, 1\], \[1, 2\], \[\], \[1, 2\], \[2\]\]
**Output**
\[null, \[1, 0, 2\], null, null, \[\[0, 1\], \[1, 2\]\], null, \[0, 1\]\]
**Explanation**
MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, \[\[0, 1, 5\], \[0, 2, 6\], \[0, 3, 7\], \[1, 1, 4\], \[1, 2, 7\], \[2, 1, 5\]\]);
movieRentingSystem.search(1); // return \[1, 0, 2\], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.
movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now \[2,3\].
movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now \[1\].
movieRentingSystem.report(); // return \[\[0, 1\], \[1, 2\]\]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.
movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now \[1,2\].
movieRentingSystem.search(2); // return \[0, 1\]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.
**Constraints:**
* `1 <= n <= 3 * 105`
* `1 <= entries.length <= 105`
* `0 <= shopi < n`
* `1 <= moviei, pricei <= 104`
* Each shop carries **at most one** copy of a movie `moviei`.
* At most `105` calls **in total** will be made to `search`, `rent`, `drop` and `report`. | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in a DAG, a standard DP problem. |
[Python3] Dynamic Programming and Optimizations | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | The first observation we need to make is that the moving window of size k must cycle. When a new element enter the window from the right, the same element must leave from the left.\n\nNow, we need to decide which element to place in each position of the window. Since the position of every element in `nums[i::k]` should be equal `for i in range(k)`, we first compile the freqency of each value for each position in the window.\n\n```python\nLIMIT = 2**3 # for now\nmrr = [[0 for _ in range(LIMIT)] for _ in range(k)]\nfor i,x in enumerate(nums):\n mrr[i%k][x] += 1\n```\n\nFor test case `nums = [3,4,5,2,1,7,3,4,7], k = 3` , the freqeuncy matrix now looks like this.\n\n```\n0 0 1 2 0 0 0 0\n0 1 0 0 2 0 0 0\n0 0 0 0 0 1 0 2\n```\n\nEach row is represents a position in the window. Each column represents a value (up to 8 for now). \n\nWe want to maximise the number of values that we do not change. The task is to choose one value from each row such that the target is maximised, subject to having the XOR of all selected values to be zero.\n\nYou might consider a greedy approach where you select the most common element in each position. However, there can be many ties to break and this greatly increases computational complexity.\n\nWe take a dymanic programming approach.\n- Each state is the XOR sum from the first position to the current position. There are C=1024 states.\n- Each stage is the position that we have considered. There are up to k=2000 stages.\n- The value of each state is the maximum number of values we could keep if we our XOR sum equal to the value.\n\nAt each position, we consider the previous position\n- If we choose to value for the current position, it maps all the previous XOR sum to a new XOR sum.\n- We update the dp considering\n - how often the value is found in the current position\n - the maximum number of values we have kept\n\n```python\ndp = [-2000 for _ in range(LIMIT)]\ndp[0] = 0\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n\nreturn len(nums) - new_dp[0]\n```\n\nThis is the value for each state after each stage of the dynamic programming.\n\n```\n0 - - - - - - -\n0 0 1 2 0 0 0 0\n2 2 3 2 2 2 3 4\n6 5 5 4 4 5 4 4\n```\n\nWe return the bottom left value - which is the maximum number of values we can leave unchanged such that the XOR of the window is zero.\n\nHowever, the complexity of the above algorithm is O(kC^2) which will run out of time.\n\nWe observe the we do not need to update the state if the count is zero. There are at most 2000 nonzero count because the array size is up to 2000. This reduces the complexity to O(nC).\n\nWe can split the enumerate logic into two cases - where `cnt == 0` and where `cnt > 0`\n\n```python\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt == 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev)\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n```\n\nThe iteration involving `cnt == 0` it is equivalent to applying `max(dp)` to `new_dp`.\n\nIterating `i^j` for all `j` for a given `i` will cover all 1024 possible values, because of how XOR functions works. When `prev = max(dp)`, this maximum score will be applied to all 1024 values. \n\nWe can replace the block with `cnt == 0` with an `O(C)` code that applies `max(dp)` to all of `new_dp`.\n\nThis is the full code.\n\n```python\ndef minChanges(self, nums: List[int], k: int) -> int:\n\n LIMIT = 2**10\n mrr = [[0 for _ in range(LIMIT)] \n for _ in range(k)]\n for i,x in enumerate(nums):\n mrr[i%k][x] += 1\n\n dp = [-2000 for _ in range(LIMIT)]\n dp[0] = 0\n for row in mrr:\n maxprev = max(dp)\n new_dp = [maxprev for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j], prev+cnt)\n dp = new_dp\n\n return len(nums) - new_dp[0]\n``` | 51 | You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero.
**Example 1:**
**Input:** nums = \[1,2,0,3,0\], k = 1
**Output:** 3
**Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\].
**Example 2:**
**Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\].
**Example 3:**
**Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\].
**Constraints:**
* `1 <= k <= nums.length <= 2000`
* `0 <= nums[i] < 210` | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly. |
[Python3] Dynamic Programming and Optimizations | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | The first observation we need to make is that the moving window of size k must cycle. When a new element enter the window from the right, the same element must leave from the left.\n\nNow, we need to decide which element to place in each position of the window. Since the position of every element in `nums[i::k]` should be equal `for i in range(k)`, we first compile the freqency of each value for each position in the window.\n\n```python\nLIMIT = 2**3 # for now\nmrr = [[0 for _ in range(LIMIT)] for _ in range(k)]\nfor i,x in enumerate(nums):\n mrr[i%k][x] += 1\n```\n\nFor test case `nums = [3,4,5,2,1,7,3,4,7], k = 3` , the freqeuncy matrix now looks like this.\n\n```\n0 0 1 2 0 0 0 0\n0 1 0 0 2 0 0 0\n0 0 0 0 0 1 0 2\n```\n\nEach row is represents a position in the window. Each column represents a value (up to 8 for now). \n\nWe want to maximise the number of values that we do not change. The task is to choose one value from each row such that the target is maximised, subject to having the XOR of all selected values to be zero.\n\nYou might consider a greedy approach where you select the most common element in each position. However, there can be many ties to break and this greatly increases computational complexity.\n\nWe take a dymanic programming approach.\n- Each state is the XOR sum from the first position to the current position. There are C=1024 states.\n- Each stage is the position that we have considered. There are up to k=2000 stages.\n- The value of each state is the maximum number of values we could keep if we our XOR sum equal to the value.\n\nAt each position, we consider the previous position\n- If we choose to value for the current position, it maps all the previous XOR sum to a new XOR sum.\n- We update the dp considering\n - how often the value is found in the current position\n - the maximum number of values we have kept\n\n```python\ndp = [-2000 for _ in range(LIMIT)]\ndp[0] = 0\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n\nreturn len(nums) - new_dp[0]\n```\n\nThis is the value for each state after each stage of the dynamic programming.\n\n```\n0 - - - - - - -\n0 0 1 2 0 0 0 0\n2 2 3 2 2 2 3 4\n6 5 5 4 4 5 4 4\n```\n\nWe return the bottom left value - which is the maximum number of values we can leave unchanged such that the XOR of the window is zero.\n\nHowever, the complexity of the above algorithm is O(kC^2) which will run out of time.\n\nWe observe the we do not need to update the state if the count is zero. There are at most 2000 nonzero count because the array size is up to 2000. This reduces the complexity to O(nC).\n\nWe can split the enumerate logic into two cases - where `cnt == 0` and where `cnt > 0`\n\n```python\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt == 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev)\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n```\n\nThe iteration involving `cnt == 0` it is equivalent to applying `max(dp)` to `new_dp`.\n\nIterating `i^j` for all `j` for a given `i` will cover all 1024 possible values, because of how XOR functions works. When `prev = max(dp)`, this maximum score will be applied to all 1024 values. \n\nWe can replace the block with `cnt == 0` with an `O(C)` code that applies `max(dp)` to all of `new_dp`.\n\nThis is the full code.\n\n```python\ndef minChanges(self, nums: List[int], k: int) -> int:\n\n LIMIT = 2**10\n mrr = [[0 for _ in range(LIMIT)] \n for _ in range(k)]\n for i,x in enumerate(nums):\n mrr[i%k][x] += 1\n\n dp = [-2000 for _ in range(LIMIT)]\n dp[0] = 0\n for row in mrr:\n maxprev = max(dp)\n new_dp = [maxprev for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j], prev+cnt)\n dp = new_dp\n\n return len(nums) - new_dp[0]\n``` | 51 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104` | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
DP Solution | make-the-xor-of-all-segments-equal-to-zero | 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```\nfrom typing import List\nfrom collections import defaultdict\n\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n n = len(nums)\n max_val = 2 ** 10 # The maximum possible XOR value\n\n # Initialize a dynamic programming array to store minimum changes for each XOR value\n dp = [float(\'inf\')] * max_val\n dp[0] = 0 # Base case: No changes needed for XOR 0\n\n # Iterate over each position in the subarray of size k\n for i in range(k):\n freq = defaultdict(int) # Dictionary to store frequency of elements in the current subarray\n count = 0 # Count of elements in the current subarray\n # Iterate over the subarray with a step of k\n for j in range(i, n, k):\n freq[nums[j]] += 1\n count += 1\n\n prev_dp = min(dp) # Get the minimum value from the previous dp array\n\n new_dp = [prev_dp + count] * max_val # Initialize a new dp array\n # Combine loops over possible XOR values and elements in the current subarray\n for xor in range(max_val):\n for num, freq_num in freq.items():\n new_xor = xor ^ num # Calculate the new XOR value\n # Update the dp array with the minimum changes needed\n new_dp[new_xor] = min(new_dp[new_xor], dp[xor] - freq_num + count)\n\n dp = new_dp # Update dp array for the next position in the subarray\n\n return dp[0] # Return the minimum changes needed for XOR 0\n\n``` | 0 | You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero.
**Example 1:**
**Input:** nums = \[1,2,0,3,0\], k = 1
**Output:** 3
**Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\].
**Example 2:**
**Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\].
**Example 3:**
**Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\].
**Constraints:**
* `1 <= k <= nums.length <= 2000`
* `0 <= nums[i] < 210` | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly. |
DP Solution | make-the-xor-of-all-segments-equal-to-zero | 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```\nfrom typing import List\nfrom collections import defaultdict\n\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n n = len(nums)\n max_val = 2 ** 10 # The maximum possible XOR value\n\n # Initialize a dynamic programming array to store minimum changes for each XOR value\n dp = [float(\'inf\')] * max_val\n dp[0] = 0 # Base case: No changes needed for XOR 0\n\n # Iterate over each position in the subarray of size k\n for i in range(k):\n freq = defaultdict(int) # Dictionary to store frequency of elements in the current subarray\n count = 0 # Count of elements in the current subarray\n # Iterate over the subarray with a step of k\n for j in range(i, n, k):\n freq[nums[j]] += 1\n count += 1\n\n prev_dp = min(dp) # Get the minimum value from the previous dp array\n\n new_dp = [prev_dp + count] * max_val # Initialize a new dp array\n # Combine loops over possible XOR values and elements in the current subarray\n for xor in range(max_val):\n for num, freq_num in freq.items():\n new_xor = xor ^ num # Calculate the new XOR value\n # Update the dp array with the minimum changes needed\n new_dp[new_xor] = min(new_dp[new_xor], dp[xor] - freq_num + count)\n\n dp = new_dp # Update dp array for the next position in the subarray\n\n return dp[0] # Return the minimum changes needed for XOR 0\n\n``` | 0 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104` | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
[Python3] dp | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | I learned the solution from the posts of others. This damn problem is sooooo hard! \n\n```\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n freq = defaultdict(lambda: defaultdict(int))\n for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row\n \n n = 1 << 10\n dp = [0] + [-inf]*(n-1)\n for i in range(k): \n mx = max(dp)\n tmp = [0]*n\n for x, c in enumerate(dp): \n for xx, cc in freq[i].items(): \n tmp[x^xx] = max(tmp[x^xx], c + cc, mx)\n dp = tmp \n return len(nums) - dp[0]\n``` | 3 | You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_ such that the `XOR` of all segments of size `k` is equal to zero.
**Example 1:**
**Input:** nums = \[1,2,0,3,0\], k = 1
**Output:** 3
**Explanation:** Modify the array from \[**1**,**2**,0,**3**,0\] to from \[**0**,**0**,0,**0**,0\].
**Example 2:**
**Input:** nums = \[3,4,5,2,1,7,3,4,7\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[3,4,**5**,**2**,**1**,7,3,4,7\] to \[3,4,**7**,**3**,**4**,7,3,4,7\].
**Example 3:**
**Input:** nums = \[1,2,4,1,2,5,1,2,6\], k = 3
**Output:** 3
**Explanation:** Modify the array from \[1,2,**4,**1,2,**5**,1,2,**6**\] to \[1,2,**3**,1,2,**3**,1,2,**3**\].
**Constraints:**
* `1 <= k <= nums.length <= 2000`
* `0 <= nums[i] < 210` | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplified to (nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i-1)). One can build prefix and suffix sums to compute this quickly. |
[Python3] dp | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | I learned the solution from the posts of others. This damn problem is sooooo hard! \n\n```\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n freq = defaultdict(lambda: defaultdict(int))\n for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row\n \n n = 1 << 10\n dp = [0] + [-inf]*(n-1)\n for i in range(k): \n mx = max(dp)\n tmp = [0]*n\n for x, c in enumerate(dp): \n for xx, cc in freq[i].items(): \n tmp[x^xx] = max(tmp[x^xx], c + cc, mx)\n dp = tmp \n return len(nums) - dp[0]\n``` | 3 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104` | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
[Python3] check diff | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]\n``` | 80 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.
**Example 1:**
**Input:** s1 = "bank ", s2 = "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make "bank ".
**Example 2:**
**Input:** s1 = "attack ", s2 = "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.
**Example 3:**
**Input:** s1 = "kelb ", s2 = "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1.length == s2.length`
* `s1` and `s2` consist of only lowercase English letters. | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
[Python3] check diff | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]\n``` | 80 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aba "
**Output:** 4
**Explanation:** The four wonderful substrings are underlined below:
- "**a**ba " -> "a "
- "a**b**a " -> "b "
- "ab**a** " -> "a "
- "**aba** " -> "aba "
**Example 2:**
**Input:** word = "aabb "
**Output:** 9
**Explanation:** The nine wonderful substrings are underlined below:
- "**a**abb " -> "a "
- "**aa**bb " -> "aa "
- "**aab**b " -> "aab "
- "**aabb** " -> "aabb "
- "a**a**bb " -> "a "
- "a**abb** " -> "abb "
- "aa**b**b " -> "b "
- "aa**bb** " -> "bb "
- "aab**b** " -> "b "
**Example 3:**
**Input:** word = "he "
**Output:** 2
**Explanation:** The two wonderful substrings are underlined below:
- "**h**e " -> "h "
- "h**e** " -> "e "
**Constraints:**
* `1 <= word.length <= 105`
* `word` consists of lowercase English letters from `'a'` to `'j'`. | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python | Easy Solution✅ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | ```\ndef areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True # if strings are equal then swaping is not required\n if sorted(s1) != sorted(s2):\n return False # if sorted s1 and s2 are not equal then swaping will not make strings equal\n \n count = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count +=1 \n if count != 2: # the count should be 2, then only we can do at most one string swap\n return False\n \n return True\n``` | 39 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.
**Example 1:**
**Input:** s1 = "bank ", s2 = "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make "bank ".
**Example 2:**
**Input:** s1 = "attack ", s2 = "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.
**Example 3:**
**Input:** s1 = "kelb ", s2 = "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1.length == s2.length`
* `s1` and `s2` consist of only lowercase English letters. | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
Python | Easy Solution✅ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | ```\ndef areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True # if strings are equal then swaping is not required\n if sorted(s1) != sorted(s2):\n return False # if sorted s1 and s2 are not equal then swaping will not make strings equal\n \n count = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count +=1 \n if count != 2: # the count should be 2, then only we can do at most one string swap\n return False\n \n return True\n``` | 39 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aba "
**Output:** 4
**Explanation:** The four wonderful substrings are underlined below:
- "**a**ba " -> "a "
- "a**b**a " -> "b "
- "ab**a** " -> "a "
- "**aba** " -> "aba "
**Example 2:**
**Input:** word = "aabb "
**Output:** 9
**Explanation:** The nine wonderful substrings are underlined below:
- "**a**abb " -> "a "
- "**aa**bb " -> "aa "
- "**aab**b " -> "aab "
- "**aabb** " -> "aabb "
- "a**a**bb " -> "a "
- "a**abb** " -> "abb "
- "aa**b**b " -> "b "
- "aa**bb** " -> "bb "
- "aab**b** " -> "b "
**Example 3:**
**Input:** word = "he "
**Output:** 2
**Explanation:** The two wonderful substrings are underlined below:
- "**h**e " -> "h "
- "h**e** " -> "e "
**Constraints:**
* `1 <= word.length <= 105`
* `word` consists of lowercase English letters from `'a'` to `'j'`. | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
[python]--\easiest soln\ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \n if s1==s2: #strings are equal no swapping required\n return True\n if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal\n return False\n countof=0\n for i in range(len(s1)):\n if s1[i]!=s2[i]:#checking diff aplphabets of both the strings\n countof +=1\n if countof!=2:\n return False\n return True\n\n \n\n\n \n``` | 3 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.
**Example 1:**
**Input:** s1 = "bank ", s2 = "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make "bank ".
**Example 2:**
**Input:** s1 = "attack ", s2 = "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.
**Example 3:**
**Input:** s1 = "kelb ", s2 = "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1.length == s2.length`
* `s1` and `s2` consist of only lowercase English letters. | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
[python]--\easiest soln\ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \n if s1==s2: #strings are equal no swapping required\n return True\n if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal\n return False\n countof=0\n for i in range(len(s1)):\n if s1[i]!=s2[i]:#checking diff aplphabets of both the strings\n countof +=1\n if countof!=2:\n return False\n return True\n\n \n\n\n \n``` | 3 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aba "
**Output:** 4
**Explanation:** The four wonderful substrings are underlined below:
- "**a**ba " -> "a "
- "a**b**a " -> "b "
- "ab**a** " -> "a "
- "**aba** " -> "aba "
**Example 2:**
**Input:** word = "aabb "
**Output:** 9
**Explanation:** The nine wonderful substrings are underlined below:
- "**a**abb " -> "a "
- "**aa**bb " -> "aa "
- "**aab**b " -> "aab "
- "**aabb** " -> "aabb "
- "a**a**bb " -> "a "
- "a**abb** " -> "abb "
- "aa**b**b " -> "b "
- "aa**bb** " -> "bb "
- "aab**b** " -> "b "
**Example 3:**
**Input:** word = "he "
**Output:** 2
**Explanation:** The two wonderful substrings are underlined below:
- "**h**e " -> "h "
- "h**e** " -> "e "
**Constraints:**
* `1 <= word.length <= 105`
* `word` consists of lowercase English letters from `'a'` to `'j'`. | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python solution using Dictionary | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | # Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n c=0\n d={}\n dd={}\n for i in range(len(s1)):\n if s1[i] not in d:\n d[s1[i]]=1\n else:\n d[s1[i]]+=1\n if s2[i] not in dd:\n dd[s2[i]]=1\n else:\n dd[s2[i]]+=1\n\n if s1[i]!=s2[i]:\n c+=1\n if (c==2 or c==0) and sorted(d.items())==sorted(dd.items()):\n return True\n else:\n return False\n``` | 3 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`.
**Example 1:**
**Input:** s1 = "bank ", s2 = "kanb "
**Output:** true
**Explanation:** For example, swap the first character with the last character of s2 to make "bank ".
**Example 2:**
**Input:** s1 = "attack ", s2 = "defend "
**Output:** false
**Explanation:** It is impossible to make them equal with one string swap.
**Example 3:**
**Input:** s1 = "kelb ", s2 = "kelb "
**Output:** true
**Explanation:** The two strings are already equal, so no string swap operation is required.
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1.length == s2.length`
* `s1` and `s2` consist of only lowercase English letters. | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
Python solution using Dictionary | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | # Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n c=0\n d={}\n dd={}\n for i in range(len(s1)):\n if s1[i] not in d:\n d[s1[i]]=1\n else:\n d[s1[i]]+=1\n if s2[i] not in dd:\n dd[s2[i]]=1\n else:\n dd[s2[i]]+=1\n\n if s1[i]!=s2[i]:\n c+=1\n if (c==2 or c==0) and sorted(d.items())==sorted(dd.items()):\n return True\n else:\n return False\n``` | 3 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aba "
**Output:** 4
**Explanation:** The four wonderful substrings are underlined below:
- "**a**ba " -> "a "
- "a**b**a " -> "b "
- "ab**a** " -> "a "
- "**aba** " -> "aba "
**Example 2:**
**Input:** word = "aabb "
**Output:** 9
**Explanation:** The nine wonderful substrings are underlined below:
- "**a**abb " -> "a "
- "**aa**bb " -> "aa "
- "**aab**b " -> "aab "
- "**aabb** " -> "aabb "
- "a**a**bb " -> "a "
- "a**abb** " -> "abb "
- "aa**b**b " -> "b "
- "aa**bb** " -> "bb "
- "aab**b** " -> "b "
**Example 3:**
**Input:** word = "he "
**Output:** 2
**Explanation:** The two wonderful substrings are underlined below:
- "**h**e " -> "h "
- "h**e** " -> "e "
**Constraints:**
* `1 <= word.length <= 105`
* `word` consists of lowercase English letters from `'a'` to `'j'`. | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
One Line of Code Awesome Logic | find-center-of-star-graph | 0 | 1 | \n\n# 1. Awesome Logic----->One Line Code\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return list(set(edges[0]) & set(edges[1]))[0]\n\n #please upvote me it would encourage me alot\n\n```\n# 2. Check first value and Second Value\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n first=edges[0][0]\n second=edges[0][1]\n if edges[1][0]==first or edges[1][1]==first:\n return first\n return second\n #please upvote me it would encourage me alot\n\n\n```\n# please upvote me it would encourage me alot\n | 17 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph. | Calculate the wealth of each customer Find the maximum element in array. |
One Line of Code Awesome Logic | find-center-of-star-graph | 0 | 1 | \n\n# 1. Awesome Logic----->One Line Code\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return list(set(edges[0]) & set(edges[1]))[0]\n\n #please upvote me it would encourage me alot\n\n```\n# 2. Check first value and Second Value\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n first=edges[0][0]\n second=edges[0][1]\n if edges[1][0]==first or edges[1][1]==first:\n return first\n return second\n #please upvote me it would encourage me alot\n\n\n```\n# please upvote me it would encourage me alot\n | 17 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **directly**. Room `0` is already built, so `prevRoom[0] = -1`. The expansion plan is given such that once all the rooms are built, every room will be reachable from room `0`.
You can only build **one room** at a time, and you can travel freely between rooms you have **already built** only if they are **connected**. You can choose to build **any room** as long as its **previous room** is already built.
Return _the **number of different orders** you can build all the rooms in_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** prevRoom = \[-1,0,1\]
**Output:** 1
**Explanation:** There is only one way to build the additional rooms: 0 -> 1 -> 2
**Example 2:**
**Input:** prevRoom = \[-1,0,0,1,2\]
**Output:** 6
**Explanation:**
The 6 ways are:
0 -> 1 -> 3 -> 2 -> 4
0 -> 2 -> 4 -> 1 -> 3
0 -> 1 -> 2 -> 3 -> 4
0 -> 1 -> 2 -> 4 -> 3
0 -> 2 -> 1 -> 3 -> 4
0 -> 2 -> 1 -> 4 -> 3
**Constraints:**
* `n == prevRoom.length`
* `2 <= n <= 105`
* `prevRoom[0] == -1`
* `0 <= prevRoom[i] < n` for all `1 <= i < n`
* Every room is reachable from room `0` once all the rooms are built. | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Easiest 1 liner Python O(1) solution ................. | find-center-of-star-graph | 0 | 1 | ```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:\n return edges[0][0]\n return edges[0][1]\n```\nReducing it to one liner......\n```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return edges[0][1] if edges[0][1]==edges[1][0] or edges[0][1]==edges[1][1] else edges[0][0] | 10 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph. | Calculate the wealth of each customer Find the maximum element in array. |
Easiest 1 liner Python O(1) solution ................. | find-center-of-star-graph | 0 | 1 | ```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:\n return edges[0][0]\n return edges[0][1]\n```\nReducing it to one liner......\n```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return edges[0][1] if edges[0][1]==edges[1][0] or edges[0][1]==edges[1][1] else edges[0][0] | 10 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **directly**. Room `0` is already built, so `prevRoom[0] = -1`. The expansion plan is given such that once all the rooms are built, every room will be reachable from room `0`.
You can only build **one room** at a time, and you can travel freely between rooms you have **already built** only if they are **connected**. You can choose to build **any room** as long as its **previous room** is already built.
Return _the **number of different orders** you can build all the rooms in_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** prevRoom = \[-1,0,1\]
**Output:** 1
**Explanation:** There is only one way to build the additional rooms: 0 -> 1 -> 2
**Example 2:**
**Input:** prevRoom = \[-1,0,0,1,2\]
**Output:** 6
**Explanation:**
The 6 ways are:
0 -> 1 -> 3 -> 2 -> 4
0 -> 2 -> 4 -> 1 -> 3
0 -> 1 -> 2 -> 3 -> 4
0 -> 1 -> 2 -> 4 -> 3
0 -> 2 -> 1 -> 3 -> 4
0 -> 2 -> 1 -> 4 -> 3
**Constraints:**
* `n == prevRoom.length`
* `2 <= n <= 105`
* `prevRoom[0] == -1`
* `0 <= prevRoom[i] < n` for all `1 <= i < n`
* Every room is reachable from room `0` once all the rooms are built. | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Python 1 Liner | find-center-of-star-graph | 0 | 1 | ```\nclass Solution(object):\n def findCenter(self, edges):\n return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]\n``` | 3 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph. | Calculate the wealth of each customer Find the maximum element in array. |
Python 1 Liner | find-center-of-star-graph | 0 | 1 | ```\nclass Solution(object):\n def findCenter(self, edges):\n return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]\n``` | 3 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **directly**. Room `0` is already built, so `prevRoom[0] = -1`. The expansion plan is given such that once all the rooms are built, every room will be reachable from room `0`.
You can only build **one room** at a time, and you can travel freely between rooms you have **already built** only if they are **connected**. You can choose to build **any room** as long as its **previous room** is already built.
Return _the **number of different orders** you can build all the rooms in_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** prevRoom = \[-1,0,1\]
**Output:** 1
**Explanation:** There is only one way to build the additional rooms: 0 -> 1 -> 2
**Example 2:**
**Input:** prevRoom = \[-1,0,0,1,2\]
**Output:** 6
**Explanation:**
The 6 ways are:
0 -> 1 -> 3 -> 2 -> 4
0 -> 2 -> 4 -> 1 -> 3
0 -> 1 -> 2 -> 3 -> 4
0 -> 1 -> 2 -> 4 -> 3
0 -> 2 -> 1 -> 3 -> 4
0 -> 2 -> 1 -> 4 -> 3
**Constraints:**
* `n == prevRoom.length`
* `2 <= n <= 105`
* `prevRoom[0] == -1`
* `0 <= prevRoom[i] < n` for all `1 <= i < n`
* Every room is reachable from room `0` once all the rooms are built. | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
3 Python Solutions | find-center-of-star-graph | 0 | 1 | ```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn (set(e[0]) & set(e[1])).pop()\n```\n\t\t\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\tif e[0][0]==e[1][0] or e[0][0]==e[1][1]:\n\t\treturn e[0][0]\n\treturn e[0][1]\n```\n\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn e[0][e[0][1] in e[1]]\n``` | 19 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph. | Calculate the wealth of each customer Find the maximum element in array. |
3 Python Solutions | find-center-of-star-graph | 0 | 1 | ```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn (set(e[0]) & set(e[1])).pop()\n```\n\t\t\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\tif e[0][0]==e[1][0] or e[0][0]==e[1][1]:\n\t\treturn e[0][0]\n\treturn e[0][1]\n```\n\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn e[0][e[0][1] in e[1]]\n``` | 19 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **directly**. Room `0` is already built, so `prevRoom[0] = -1`. The expansion plan is given such that once all the rooms are built, every room will be reachable from room `0`.
You can only build **one room** at a time, and you can travel freely between rooms you have **already built** only if they are **connected**. You can choose to build **any room** as long as its **previous room** is already built.
Return _the **number of different orders** you can build all the rooms in_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** prevRoom = \[-1,0,1\]
**Output:** 1
**Explanation:** There is only one way to build the additional rooms: 0 -> 1 -> 2
**Example 2:**
**Input:** prevRoom = \[-1,0,0,1,2\]
**Output:** 6
**Explanation:**
The 6 ways are:
0 -> 1 -> 3 -> 2 -> 4
0 -> 2 -> 4 -> 1 -> 3
0 -> 1 -> 2 -> 3 -> 4
0 -> 1 -> 2 -> 4 -> 3
0 -> 2 -> 1 -> 3 -> 4
0 -> 2 -> 1 -> 4 -> 3
**Constraints:**
* `n == prevRoom.length`
* `2 <= n <= 105`
* `prevRoom[0] == -1`
* `0 <= prevRoom[i] < n` for all `1 <= i < n`
* Every room is reachable from room `0` once all the rooms are built. | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
[Python3] - Pythonic Heap-Loop | maximum-average-pass-ratio | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe should always put a good students into a class where the passing guarantees the best improvement.\n\nAs this improvement changes with putting a student into a class, we can utilize a priority with the improvement as a main key.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn order to make it pythonic and reasonably fast, we use the heapq library, list comprehensions and a for loop over the student instead of a while loop, as this also has a small speed improvement because the interpreter does not need to check a condition every time.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N + KlogN), where N is the amount of classes and K is the amount of good students we have.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) in the heap\n# Code\n```\nimport heapq\n\nclass Solution:\n def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n\n # we could always take the student with the lowest denominator using a heap\n classes = [(num/denom - (num+1)/(denom+1), num, denom) for num, denom in classes]\n\n # make the heap of classes according to smallest denominator and biggest numerator\n heapq.heapify(classes)\n\n # check the trivial case that increasing helps nothing\n if classes[0][0] == 0:\n return 1\n\n # assign the students\n for _ in range(extraStudents):\n \n # get the class with the smallest denominator and the biggest numerator\n _, num, denom = heappop(classes)\n\n # increase the amount of students and push it back into the heap\n heappush(classes, ((num+1)/(denom+1) - (num+2)/(denom+2), num+1, denom+1))\n return sum(num/denom for _, num, denom in classes)/len(classes)\n\n\n``` | 1 | There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes.
The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes.
Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2
**Output:** 0.78333
**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
**Example 2:**
**Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4
**Output:** 0.53485
**Constraints:**
* `1 <= classes.length <= 105`
* `classes[i].length == 2`
* `1 <= passi <= totali <= 105`
* `1 <= extraStudents <= 105` | In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right? |
[Python] 100% Efficient solution, easy to understand with comments and explanation | maximum-average-pass-ratio | 0 | 1 | **Key Idea:** We need to keep assigning the remaining extra students to the class which can experience the greatest impact. \n\nLet see an example below, if we have following clasess - [[2,4], [3,9], [4,5], [2,10]], then the impact of assignment students to each class can be defined as,\n\n```\n# In simple terms it can be understood as follows,\n\ncurrentRatio = passCount/totalCount\nexpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\nimpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\nOR\n\n# Formula to calculate impact of assigning a student to a class\nimpacts[i] = (classes[i][0]+1) / (classes[i][1]+1) - classes[i][0]/classes[i][1]\ni.e.\nimpacts[0] -> (4+1)/(2+1)-4/2 \nimpacts[1] -> (3+1)/(9+1)-3/9 \n.\n.\netc.\n```\n\nAnd, once we assign a student to a class, then we need the class with "next" greatest impact. We know that heap is perfect candidate for scenarios in which you need to pick the least/greatest of all the collections at any point of time.\n\nHence, we can leverage that to fetch the greatest impacts in all the cases. \n\n**Note:** in below code we have negated (observe `-` sign ), because by default python heaps are min heaps. Hence, it\'s sort of a workaround to make our logic work :)\n\n```\nclass Solution:\n\tdef maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n\n``` | 16 | There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes.
The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes.
Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2
**Output:** 0.78333
**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
**Example 2:**
**Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4
**Output:** 0.53485
**Constraints:**
* `1 <= classes.length <= 105`
* `classes[i].length == 2`
* `1 <= passi <= totali <= 105`
* `1 <= extraStudents <= 105` | In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.