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
brute force
average-waiting-time
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 averageWaitingTime(self, customers: List[List[int]]) -> float:\n start=customers[0][0]\n total=0\n for i in customers:\n if i[0]>start:\n total=total+i[1]\n start=i[0]+i[1]\n else:\n \n total=total+start+i[1]-i[0]\n start=start+i[1]\n return total/len(customers)\n\n\n\n\n\n\n\n \n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Simple Solution, similar to Merge Interval
average-waiting-time
0
1
\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n \n total = (customers[0][0]+ customers[0][1]) - customers[0][0]\n\n res=[[customers[0][0], customers[0][0]+ customers[0][1]]]\n\n for i in customers[1:]:\n out = res[-1]\n start= max(out[0], out[-1], i[0])\n end= start+ i[1]\n res.append([i[0],end])\n total += end- i[0]\n \n return total/len(customers)\n \n\n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Simple Solution, similar to Merge Interval
average-waiting-time
0
1
\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n \n total = (customers[0][0]+ customers[0][1]) - customers[0][0]\n\n res=[[customers[0][0], customers[0][0]+ customers[0][1]]]\n\n for i in customers[1:]:\n out = res[-1]\n start= max(out[0], out[-1], i[0])\n end= start+ i[1]\n res.append([i[0],end])\n total += end- i[0]\n \n return total/len(customers)\n \n\n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Easy to understand Python3 solution
average-waiting-time
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 averageWaitingTime(self, customers: List[List[int]]) -> float:\n count = 0\n start = 0\n time = 0\n for a,b in customers:\n if a > start:\n start = a\n start += b\n time += start-a\n \n return time / len(customers)\n \n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Easy to understand Python3 solution
average-waiting-time
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 averageWaitingTime(self, customers: List[List[int]]) -> float:\n count = 0\n start = 0\n time = 0\n for a,b in customers:\n if a > start:\n start = a\n start += b\n time += start-a\n \n return time / len(customers)\n \n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Python Simple Interval Based Logic
average-waiting-time
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 averageWaitingTime(self, customers: List[List[int]]) -> float:\n if not customers: return 0\n\n oldEndTime = customers[0][0]+customers[0][1]\n totWaitingTime = customers[0][1]\n newEndTime = 0\n for customer in customers[1:]:\n if customer[0]<oldEndTime:\n newEndTime = oldEndTime+customer[1]\n totWaitingTime += newEndTime-customer[0]\n else:\n totWaitingTime += customer[1]\n newEndTime = customer[0]+customer[1]\n oldEndTime = newEndTime\n return totWaitingTime / len(customers)\n\n\n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Python Simple Interval Based Logic
average-waiting-time
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 averageWaitingTime(self, customers: List[List[int]]) -> float:\n if not customers: return 0\n\n oldEndTime = customers[0][0]+customers[0][1]\n totWaitingTime = customers[0][1]\n newEndTime = 0\n for customer in customers[1:]:\n if customer[0]<oldEndTime:\n newEndTime = oldEndTime+customer[1]\n totWaitingTime += newEndTime-customer[0]\n else:\n totWaitingTime += customer[1]\n newEndTime = customer[0]+customer[1]\n oldEndTime = newEndTime\n return totWaitingTime / len(customers)\n\n\n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Simple and clear python3 solution | 1 pass
average-waiting-time
0
1
# 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``` python3 []\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n n = len(customers)\n result = 0\n\n current_time = 0\n for arrival, time in customers:\n if current_time <= arrival:\n result += time\n current_time = arrival + time\n else:\n result += (current_time - arrival) + time\n current_time += time\n \n return result / n\n\n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Simple and clear python3 solution | 1 pass
average-waiting-time
0
1
# 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``` python3 []\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n n = len(customers)\n result = 0\n\n current_time = 0\n for arrival, time in customers:\n if current_time <= arrival:\n result += time\n current_time = arrival + time\n else:\n result += (current_time - arrival) + time\n current_time += time\n \n return result / n\n\n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Python very easy and intiutive
average-waiting-time
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)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n last=-1\n n=len(customers)\n\n total=0\n for customer in customers:\n\n cur=customer[0]+customer[1]\n cur+=max(last-customer[0], 0)\n total+=cur-customer[0]\n last=cur\n \n return (total/n)\n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Python very easy and intiutive
average-waiting-time
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)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n last=-1\n n=len(customers)\n\n total=0\n for customer in customers:\n\n cur=customer[0]+customer[1]\n cur+=max(last-customer[0], 0)\n total+=cur-customer[0]\n last=cur\n \n return (total/n)\n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
Python - 5 lines, simple O(n) greedy
average-waiting-time
0
1
# Intuition\nSince they are already sorted, for every customer it is enough to find maximum of last time reached and arrival plus time for processing, wait time is diference between those.\nThis si kind of greedy simulation.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers): \n wait = curr_time = 0\n for a, t in customers:\n curr_time = max(curr_time, a) + t\n wait += curr_time - a \n return wait / len(customers)\n```
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Python - 5 lines, simple O(n) greedy
average-waiting-time
0
1
# Intuition\nSince they are already sorted, for every customer it is enough to find maximum of last time reached and arrival plus time for processing, wait time is diference between those.\nThis si kind of greedy simulation.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers): \n wait = curr_time = 0\n for a, t in customers:\n curr_time = max(curr_time, a) + t\n wait += curr_time - a \n return wait / len(customers)\n```
0
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explanation:** All nice pairs (i, j) are as follows: - (0, 1): nums\[0\] XOR nums\[1\] = 5 - (0, 2): nums\[0\] XOR nums\[2\] = 3 - (0, 3): nums\[0\] XOR nums\[3\] = 6 - (1, 2): nums\[1\] XOR nums\[2\] = 6 - (1, 3): nums\[1\] XOR nums\[3\] = 3 - (2, 3): nums\[2\] XOR nums\[3\] = 5 **Example 2:** **Input:** nums = \[9,8,4,2,1\], low = 5, high = 14 **Output:** 8 **Explanation:** All nice pairs (i, j) are as follows: ​​​​​ - (0, 2): nums\[0\] XOR nums\[2\] = 13 - (0, 3): nums\[0\] XOR nums\[3\] = 11 - (0, 4): nums\[0\] XOR nums\[4\] = 8 - (1, 2): nums\[1\] XOR nums\[2\] = 12 - (1, 3): nums\[1\] XOR nums\[3\] = 10 - (1, 4): nums\[1\] XOR nums\[4\] = 9 - (2, 3): nums\[2\] XOR nums\[3\] = 6 - (2, 4): nums\[2\] XOR nums\[4\] = 5 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 2 * 104` * `1 <= low <= high <= 2 * 104`
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + preparation time.
python 3 || clean || easy approach
maximum-binary-string-after-change
0
1
The trick here is that the answer string will contain only **one 0** and that zero will be at the **cth position** (where **c** is the **no of zeroes** in the initial string).The **rest** of the string will be filled with **1s.**\n```\nlass Solution:\n def maximumBinaryString(self, s: str) -> str:\n #count of 0\n c=0\n #final ans string will contain only one zero.therefore shift the first 0 to c places.Initialize ans string with all 1s\n lst=["1"]*len(s)\n for i in range (0,len(s)):\n if s[i]=="0":\n c+=1\n for i in range (0,len(s)):\n\t\t#finding the ist 0\n if s[i]=="0":\n lst[i+c-1]="0"\n return "".join(lst)\n return s\n \n```\nif you like my solution **please upvote** me
6
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
Final Recursive Form | Commented and Explained
maximum-binary-string-after-change
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn the intuition, I\'m stepping through the start of the problem and the outline of the example as a recursive backtrack. Backtracking is not used here, but serves to inform the thinking process and outline some things worth finding in pursuing the solution. \n\nFirst, note that with operations, we can make the final string at most contain 1 zero (could have a string of all 1\'s, in which case we can do nothing, or have a single zero then all 1\'s, same situation). \n\nThis leads to the second realization, which is that if we do not have at least 2 zeroes, we are in fact already maximized (either it\'s one zero and all ones, or a 1 followed by some number of 1s, a zero, and then some number of 1s, in which case any switch is in fact worse) \n\nLooking at the first example (in comments), note that we can in fact group all of the zeroes on the left -> 0000111 (did not show in walk through, but it is in fact possible) \n\nThis means we can isolate the zeros before the switch process takes place \nHow many should we do then? \n\nBased on our answer above to switching zeros, one less than the total number of zeroes! This means we will \n\n- Find unconverted portion as the binary string up to the first zero (leave leading 1\'s alone) \n- Find the number of converted zeroes (one less than total number of zeroes) \n- Find the number of remaining zeroes -> there\'s only 1 \n- Find the number of non-leading-ones -> length of string less first zero (how much unconverted actually is) less the number of zeroes (how many already accounted for) \n- Build string as unconverted portion + number of converted zeroes + a single 0 + number of non leading ones -> this is your answer \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet length of string \nGet number of zeros \nif less than two zeroes -> return binary \notherwise, build as outlined in intuition and return converted string \n\n# Complexity\n- Time complexity : O(n) \n - O(n) to get number of zeros and first zero index \xA0\n\n- Space complexity : O(n) stores final binary string \n\n# Code\n```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n # binary string is binary \n # if number contains 00 -> can replace with 10 \n # if number contains 10 -> can replace with 01 \n # return maximum binary string you can obtain after any number of operations \n # 000110 \n # 100110 # do any 00 first \n # 110110 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 110101 # no 00 but 10 at back. Try doing 10 at back and search for improvement. \n # 110011 # do any 00 first. \n # 111011 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 110111 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 101111 # no 00, but 10 at back. Try doing 10 at back and search for improvement. \n # 011111 # no 00, no 10, stop, recurse backwards. Report best found along the way. \n # hint 1 -> note with operations, can make the string only contain at most 1 zero \n # hint 2 -> less than 2 zeros in input string, return it \n # python -> string.count(char, start, end) \n bL = len(binary)\n num_zeroes = binary.count(\'0\', 0, bL)\n if num_zeroes < 2 : \n return binary \n else : \n # hint 3 -> through operations all 0\'s can be grouped while pushing 1\'s down \n # -> means you can always convert all but 1 zero into a 1 \n # hint 4 -> how far to the left should we push the zeros? leftmost 0 should never be \n # -> pushed further to the left as that would just knock out 1\'s already higher up \n # hint 5 -> considering length of string can be large, time efficient way to construct output? \n # -> \n # taken together, can group all 0\'s, then get length of zeros \n # with length of zeros take one less. At this index less one should be a zero \n # All others should be ones \n # get the leftmost index of zero as we read left to right \n zero_index = binary.index(\'0\') \n # unconverted portion then is based on this index \n unconverted_portion = binary[:zero_index]\n # we can convert num_zeroes less 1 to 1\'s \n converted_zeroes = \'1\' * (num_zeroes - 1) \n # we will have at most 1 remaining zeroes \n remaining_zeroes = \'0\' \n # we will have some non leading ones -> length of string less first index of zero less number of zeros -> cannot be negative \n number_of_non_leading_ones = bL - zero_index - num_zeroes\n if number_of_non_leading_ones < 0 : \n number_of_non_leading_ones = 0 \n unconverted_ones = \'1\' * number_of_non_leading_ones \n # build converted string in order of operations final form \n converted_string = unconverted_portion + converted_zeroes + remaining_zeroes + unconverted_ones \n # return converted string \n return converted_string\n\n```
0
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
beautiful greedy
maximum-binary-string-after-change
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 maximumBinaryString(self, binary: str) -> str:\n zero_count = binary.count("0") - 1\n leftmost_zero = binary.find("0")\n if leftmost_zero == -1:\n return binary\n adjust = min(len(binary) - 1, leftmost_zero + zero_count)\n\n return "1" * adjust + "0" + "1" * ((len(binary) - 1) - adjust)\n\n```
0
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
Magic solution
maximum-binary-string-after-change
0
1
I don\'t remember how I figured out this pattern\n\n# Code\n```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n idx = binary.find(\'01\')\n if idx == -1:\n return \'1\' * (len(binary) - 1) + binary[-1]\n n = idx + binary[idx:].count(\'0\')\n return \'1\' * (n - 1) + \'0\' + \'1\' * (len(binary) - n)\n```
0
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
Simple Python Greedy Solution
maximum-binary-string-after-change
0
1
```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n arr = []\n stack = []\n\n for i in binary:\n stack.append(i)\n \n if stack[0] == \'1\':\n arr.append(\'1\')\n stack.pop()\n elif stack[0] == \'0\' and stack[-1] == \'0\' and len(stack) > 1:\n arr.append(\'1\')\n stack.pop()\n\n return \'\'.join(arr+stack)\n```
0
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
Python | Clean Code
maximum-binary-string-after-change
0
1
# Code\n```\nclass Solution:\n def maximumBinaryString(self, binary: str) -> str:\n i = binary.find(\'0\')\n binary = list(binary)\n if i == 0:\n binary.sort()\n else:\n binary[i:] = sorted(binary[i:])\n while i + 1 < len(binary) and binary[i+1] == \'0\':\n binary[i] = \'1\'\n i += 1\n return "".join(binary)\n \n\n```
0
You are given a binary string `binary` consisting of only `0`'s or `1`'s. You can apply each of the following operations any number of times: * Operation 1: If the number contains the substring `"00 "`, you can replace it with `"10 "`. * For example, `"00010 " -> "10010` " * Operation 2: If the number contains the substring `"10 "`, you can replace it with `"01 "`. * For example, `"00010 " -> "00001 "` _Return the **maximum binary string** you can obtain after any number of operations. Binary string `x` is greater than binary string `y` if `x`'s decimal representation is greater than `y`'s decimal representation._ **Example 1:** **Input:** binary = "000110 " **Output:** "111011 " **Explanation:** A valid transformation sequence can be: "000110 " -> "000101 " "000101 " -> "100101 " "100101 " -> "110101 " "110101 " -> "110011 " "110011 " -> "111011 " **Example 2:** **Input:** binary = "01 " **Output:** "01 " **Explanation:** "01 " cannot be transformed any further. **Constraints:** * `1 <= binary.length <= 105` * `binary` consist of `'0'` and `'1'`.
null
69th solution lol , beats 99% in runtime
minimum-adjacent-swaps-for-k-consecutive-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 minMoves(self, nums: List[int], k: int) -> int:\n if k == 1 or len(nums) == k:\n return 0\n\n indices = [idx for idx, num in enumerate(nums) if num == 1]\n mid = k // 2\n odd = k % 2\n extra_steps = (mid + odd) * mid\n min_swaps = mid_steps = sum(indices[mid+odd:k])-sum(indices[:mid])\n if mid_steps == extra_steps:\n return 0\n\n end = k\n start = 0\n for idx in range(mid, len(indices) - k + mid):\n # 2 rolling sums\n mid_steps += indices[start] - indices[idx] + indices[end] - indices[idx+odd]\n start += 1\n end += 1\n if mid_steps == extra_steps:\n return 0\n elif min_swaps > mid_steps:\n min_swaps = mid_steps\n\n return min_swaps - extra_steps\n```
0
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. **Example 1:** **Input:** nums = \[1,0,0,1,0,1\], k = 2 **Output:** 1 **Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's. **Example 2:** **Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3 **Output:** 5 **Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,0,1\], k = 2 **Output:** 0 **Explanation:** nums already has 2 consecutive 1's. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is `0` or `1`. * `1 <= k <= sum(nums)`
Sort the boxes in ascending order, try to process the box with the smallest height first.
69th solution lol , beats 99% in runtime
minimum-adjacent-swaps-for-k-consecutive-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 minMoves(self, nums: List[int], k: int) -> int:\n if k == 1 or len(nums) == k:\n return 0\n\n indices = [idx for idx, num in enumerate(nums) if num == 1]\n mid = k // 2\n odd = k % 2\n extra_steps = (mid + odd) * mid\n min_swaps = mid_steps = sum(indices[mid+odd:k])-sum(indices[:mid])\n if mid_steps == extra_steps:\n return 0\n\n end = k\n start = 0\n for idx in range(mid, len(indices) - k + mid):\n # 2 rolling sums\n mid_steps += indices[start] - indices[idx] + indices[end] - indices[idx+odd]\n start += 1\n end += 1\n if mid_steps == extra_steps:\n return 0\n elif min_swaps > mid_steps:\n min_swaps = mid_steps\n\n return min_swaps - extra_steps\n```
0
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some integers that are separated by at least one space: `"123 "`, `"34 "`, `"8 "`, and `"34 "`. Return _the number of **different** integers after performing the replacement operations on_ `word`. Two integers are considered different if their decimal representations **without any leading zeros** are different. **Example 1:** **Input:** word = "a123bc34d8ef34 " **Output:** 3 **Explanation:** The three different integers are "123 ", "34 ", and "8 ". Notice that "34 " is only counted once. **Example 2:** **Input:** word = "leet1234code234 " **Output:** 2 **Example 3:** **Input:** word = "a1b01c001 " **Output:** 1 **Explanation:** The three integers "1 ", "01 ", and "001 " all represent the same integer because the leading zeros are ignored when comparing their decimal values. **Constraints:** * `1 <= word.length <= 1000` * `word` consists of digits and lowercase English letters.
Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.
python 3 | O(n) time | O(1) space
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k == 1:\n return 0\n ones = 0\n half = (k + 1) >> 1\n leftSum = rightSum = 0\n for i, num in enumerate(nums):\n if not num:\n continue\n ones += 1\n if ones < half:\n leftSum += i\n if ones == 1:\n left = i\n elif ones == half:\n mid = i\n else:\n rightSum += i\n if ones == k:\n right = i\n break\n if k == 2:\n left = mid\n if k & 1:\n leftHalf = rightHalf = half - 1\n else:\n leftHalf, rightHalf = half - 1, half\n leftOffset = (leftHalf*leftHalf - leftHalf) >> 1\n rightOffset = (rightHalf*rightHalf - rightHalf) >> 1\n cur = res = (\n leftHalf * (mid - 1) - leftSum - leftOffset +\n rightSum - rightHalf * (mid + 1) - rightOffset\n )\n n = len(nums)\n while True:\n right += 1\n while right < n and not nums[right]:\n right += 1\n if right == n:\n break\n rightSum += right\n leftSum -= left\n left += 1\n while not nums[left]:\n left += 1\n leftSum += mid\n mid += 1\n while not nums[mid]:\n mid += 1\n rightSum -= mid\n cur = (\n leftHalf * (mid - 1) - leftSum - leftOffset +\n rightSum - rightHalf * (mid + 1) - rightOffset\n )\n res = min(res, cur)\n return res\n \n \n \n \n\n \n\n```
0
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. **Example 1:** **Input:** nums = \[1,0,0,1,0,1\], k = 2 **Output:** 1 **Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's. **Example 2:** **Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3 **Output:** 5 **Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,0,1\], k = 2 **Output:** 0 **Explanation:** nums already has 2 consecutive 1's. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is `0` or `1`. * `1 <= k <= sum(nums)`
Sort the boxes in ascending order, try to process the box with the smallest height first.
python 3 | O(n) time | O(1) space
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k == 1:\n return 0\n ones = 0\n half = (k + 1) >> 1\n leftSum = rightSum = 0\n for i, num in enumerate(nums):\n if not num:\n continue\n ones += 1\n if ones < half:\n leftSum += i\n if ones == 1:\n left = i\n elif ones == half:\n mid = i\n else:\n rightSum += i\n if ones == k:\n right = i\n break\n if k == 2:\n left = mid\n if k & 1:\n leftHalf = rightHalf = half - 1\n else:\n leftHalf, rightHalf = half - 1, half\n leftOffset = (leftHalf*leftHalf - leftHalf) >> 1\n rightOffset = (rightHalf*rightHalf - rightHalf) >> 1\n cur = res = (\n leftHalf * (mid - 1) - leftSum - leftOffset +\n rightSum - rightHalf * (mid + 1) - rightOffset\n )\n n = len(nums)\n while True:\n right += 1\n while right < n and not nums[right]:\n right += 1\n if right == n:\n break\n rightSum += right\n leftSum -= left\n left += 1\n while not nums[left]:\n left += 1\n leftSum += mid\n mid += 1\n while not nums[mid]:\n mid += 1\n rightSum -= mid\n cur = (\n leftHalf * (mid - 1) - leftSum - leftOffset +\n rightSum - rightHalf * (mid + 1) - rightOffset\n )\n res = min(res, cur)\n return res\n \n \n \n \n\n \n\n```
0
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some integers that are separated by at least one space: `"123 "`, `"34 "`, `"8 "`, and `"34 "`. Return _the number of **different** integers after performing the replacement operations on_ `word`. Two integers are considered different if their decimal representations **without any leading zeros** are different. **Example 1:** **Input:** word = "a123bc34d8ef34 " **Output:** 3 **Explanation:** The three different integers are "123 ", "34 ", and "8 ". Notice that "34 " is only counted once. **Example 2:** **Input:** word = "leet1234code234 " **Output:** 2 **Example 3:** **Input:** word = "a1b01c001 " **Output:** 1 **Explanation:** The three integers "1 ", "01 ", and "001 " all represent the same integer because the leading zeros are ignored when comparing their decimal values. **Constraints:** * `1 <= word.length <= 1000` * `word` consists of digits and lowercase English letters.
Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.
ez sol
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k==1:\n return 0\n n=len(nums)\n ind=[i for i in range(len(nums)) if nums[i]==1]\n pref=[0]*n\n for i in range(n):\n pref[i]+=pref[i-1]+(nums[i]==0)\n win=ind[:k]\n l,hi=0,k-1\n sl,sr=0,0\n ans=float("inf")\n lh=k//2\n rh=k-k//2\n sl=sum([pref[i] for i in win[:k//2]])\n sr=sum([pref[i] for i in win[k//2:]])\n li=deque(win[:k//2])\n ri=deque(win[k//2:])\n win=deque(win)\n while hi<len(ind):\n ans=min(ans,(pref[win[k//2]]*lh)-sl+(sr-(pref[win[k//2]]*rh)))\n l+=1\n hi+=1\n if hi<len(ind):\n x=win.popleft()\n xl=li.popleft()\n xr=ri.popleft()\n sl-=pref[xl]\n sl+=pref[xr]\n li.append(xr)\n ri.append(ind[hi])\n sr-=pref[xr]\n sr+=pref[ind[hi]]\n win.append(ind[hi])\n\n return ans\n```
0
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. **Example 1:** **Input:** nums = \[1,0,0,1,0,1\], k = 2 **Output:** 1 **Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's. **Example 2:** **Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3 **Output:** 5 **Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,0,1\], k = 2 **Output:** 0 **Explanation:** nums already has 2 consecutive 1's. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is `0` or `1`. * `1 <= k <= sum(nums)`
Sort the boxes in ascending order, try to process the box with the smallest height first.
ez sol
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k==1:\n return 0\n n=len(nums)\n ind=[i for i in range(len(nums)) if nums[i]==1]\n pref=[0]*n\n for i in range(n):\n pref[i]+=pref[i-1]+(nums[i]==0)\n win=ind[:k]\n l,hi=0,k-1\n sl,sr=0,0\n ans=float("inf")\n lh=k//2\n rh=k-k//2\n sl=sum([pref[i] for i in win[:k//2]])\n sr=sum([pref[i] for i in win[k//2:]])\n li=deque(win[:k//2])\n ri=deque(win[k//2:])\n win=deque(win)\n while hi<len(ind):\n ans=min(ans,(pref[win[k//2]]*lh)-sl+(sr-(pref[win[k//2]]*rh)))\n l+=1\n hi+=1\n if hi<len(ind):\n x=win.popleft()\n xl=li.popleft()\n xr=ri.popleft()\n sl-=pref[xl]\n sl+=pref[xr]\n li.append(xr)\n ri.append(ind[hi])\n sr-=pref[xr]\n sr+=pref[ind[hi]]\n win.append(ind[hi])\n\n return ans\n```
0
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some integers that are separated by at least one space: `"123 "`, `"34 "`, `"8 "`, and `"34 "`. Return _the number of **different** integers after performing the replacement operations on_ `word`. Two integers are considered different if their decimal representations **without any leading zeros** are different. **Example 1:** **Input:** word = "a123bc34d8ef34 " **Output:** 3 **Explanation:** The three different integers are "123 ", "34 ", and "8 ". Notice that "34 " is only counted once. **Example 2:** **Input:** word = "leet1234code234 " **Output:** 2 **Example 3:** **Input:** word = "a1b01c001 " **Output:** 1 **Explanation:** The three integers "1 ", "01 ", and "001 " all represent the same integer because the leading zeros are ignored when comparing their decimal values. **Constraints:** * `1 <= word.length <= 1000` * `word` consists of digits and lowercase English letters.
Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.
[Python3] 1-pass O(N)
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
**Algo**\nThis implementation is similar to the popular threads in Discuss. But here we built the locations of 1s on-the-fly. \n\n**Implementation** - simulation \n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n ii = val = 0 \n ans = inf\n loc = [] # location of 1s\n for i, x in enumerate(nums): \n if x: \n loc.append(i)\n m = (ii + len(loc) - 1)//2 # median \n val += loc[-1] - loc[m] - (len(loc)-ii)//2 # adding right \n if len(loc) - ii > k: \n m = (ii + len(loc))//2 # updated median \n val -= loc[m] - loc[ii] - (len(loc)-ii)//2 # removing left \n ii += 1\n if len(loc)-ii == k: ans = min(ans, val) # len(ones) - ii effective length\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nA shorter solution given by @lee215 is in this [post](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/987347/JavaC%2B%2BPython-Solution).\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n loc = [i for i, x in enumerate(nums) if x]\n prefix = [0]\n for x in loc: prefix.append(prefix[-1] + x)\n \n ans = inf\n for i in range(len(loc)-k+1): \n ans = min(ans, (prefix[i+k] - prefix[i+(k+1)//2]) - (prefix[i+k//2] - prefix[i]))\n return ans - (k//2)*((k+1)//2)\n```
3
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. **Example 1:** **Input:** nums = \[1,0,0,1,0,1\], k = 2 **Output:** 1 **Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's. **Example 2:** **Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3 **Output:** 5 **Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,0,1\], k = 2 **Output:** 0 **Explanation:** nums already has 2 consecutive 1's. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is `0` or `1`. * `1 <= k <= sum(nums)`
Sort the boxes in ascending order, try to process the box with the smallest height first.
[Python3] 1-pass O(N)
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
**Algo**\nThis implementation is similar to the popular threads in Discuss. But here we built the locations of 1s on-the-fly. \n\n**Implementation** - simulation \n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n ii = val = 0 \n ans = inf\n loc = [] # location of 1s\n for i, x in enumerate(nums): \n if x: \n loc.append(i)\n m = (ii + len(loc) - 1)//2 # median \n val += loc[-1] - loc[m] - (len(loc)-ii)//2 # adding right \n if len(loc) - ii > k: \n m = (ii + len(loc))//2 # updated median \n val -= loc[m] - loc[ii] - (len(loc)-ii)//2 # removing left \n ii += 1\n if len(loc)-ii == k: ans = min(ans, val) # len(ones) - ii effective length\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nA shorter solution given by @lee215 is in this [post](https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/987347/JavaC%2B%2BPython-Solution).\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n loc = [i for i, x in enumerate(nums) if x]\n prefix = [0]\n for x in loc: prefix.append(prefix[-1] + x)\n \n ans = inf\n for i in range(len(loc)-k+1): \n ans = min(ans, (prefix[i+k] - prefix[i+(k+1)//2]) - (prefix[i+k//2] - prefix[i]))\n return ans - (k//2)*((k+1)//2)\n```
3
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some integers that are separated by at least one space: `"123 "`, `"34 "`, `"8 "`, and `"34 "`. Return _the number of **different** integers after performing the replacement operations on_ `word`. Two integers are considered different if their decimal representations **without any leading zeros** are different. **Example 1:** **Input:** word = "a123bc34d8ef34 " **Output:** 3 **Explanation:** The three different integers are "123 ", "34 ", and "8 ". Notice that "34 " is only counted once. **Example 2:** **Input:** word = "leet1234code234 " **Output:** 2 **Example 3:** **Input:** word = "a1b01c001 " **Output:** 1 **Explanation:** The three integers "1 ", "01 ", and "001 " all represent the same integer because the leading zeros are ignored when comparing their decimal values. **Constraints:** * `1 <= word.length <= 1000` * `word` consists of digits and lowercase English letters.
Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.
Simple O(n) python solution
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Find all the ones and keep their indices as a list.\n- The total swaps for the first k indices can be considered as the number of swaps (mid_steps) to move all indices to its mid point (mid=k//2) and then move back to consecutive indices (extra_steps).\n-- mid_steps = sum(indices[mid+k%2:k])-sum(indices[:mid])\n-- extra_tseps = (mid + k%2) * mid\n- Iterate over the rest of k indices to calculate each mid_steps as difference of 2 rolling sums.\n- return the minimum mid_steps - extra_steps\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k == 1 or len(nums) == k:\n return 0\n\n indices = [idx for idx, num in enumerate(nums) if num == 1]\n mid = k // 2\n # Move all k indices to indices[mid], and then back to consecutive positions.\n # ex: [1,4,6,8,9] => [6,6,6,6,6] => [4,5,6,7,8]\n # (8+9)-(1+4)=12 2+1+0+1+2=(2+1)*2=6\n # ex: [1,4,6,8] => [6,6,6,6] => [4,5,6,7]\n # (8)-(1+4)+6=9 2+1+0+1=(2+1)*2-2=2*2=4\n odd = k % 2\n extra_steps = (mid + odd) * mid\n min_swaps = mid_steps = sum(indices[mid+odd:k])-sum(indices[:mid])\n if mid_steps == extra_steps:\n return 0\n\n end = k\n start = 0\n for idx in range(mid, len(indices) - k + mid):\n # 2 rolling sums\n mid_steps += indices[start] - indices[idx] + indices[end] - indices[idx+odd]\n start += 1\n end += 1\n if mid_steps == extra_steps:\n return 0\n elif min_swaps > mid_steps:\n min_swaps = mid_steps\n\n return min_swaps - extra_steps\n\n```
0
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values. Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_. **Example 1:** **Input:** nums = \[1,0,0,1,0,1\], k = 2 **Output:** 1 **Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's. **Example 2:** **Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3 **Output:** 5 **Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,0,1\], k = 2 **Output:** 0 **Explanation:** nums already has 2 consecutive 1's. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is `0` or `1`. * `1 <= k <= sum(nums)`
Sort the boxes in ascending order, try to process the box with the smallest height first.
Simple O(n) python solution
minimum-adjacent-swaps-for-k-consecutive-ones
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Find all the ones and keep their indices as a list.\n- The total swaps for the first k indices can be considered as the number of swaps (mid_steps) to move all indices to its mid point (mid=k//2) and then move back to consecutive indices (extra_steps).\n-- mid_steps = sum(indices[mid+k%2:k])-sum(indices[:mid])\n-- extra_tseps = (mid + k%2) * mid\n- Iterate over the rest of k indices to calculate each mid_steps as difference of 2 rolling sums.\n- return the minimum mid_steps - extra_steps\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n if k == 1 or len(nums) == k:\n return 0\n\n indices = [idx for idx, num in enumerate(nums) if num == 1]\n mid = k // 2\n # Move all k indices to indices[mid], and then back to consecutive positions.\n # ex: [1,4,6,8,9] => [6,6,6,6,6] => [4,5,6,7,8]\n # (8+9)-(1+4)=12 2+1+0+1+2=(2+1)*2=6\n # ex: [1,4,6,8] => [6,6,6,6] => [4,5,6,7]\n # (8)-(1+4)+6=9 2+1+0+1=(2+1)*2-2=2*2=4\n odd = k % 2\n extra_steps = (mid + odd) * mid\n min_swaps = mid_steps = sum(indices[mid+odd:k])-sum(indices[:mid])\n if mid_steps == extra_steps:\n return 0\n\n end = k\n start = 0\n for idx in range(mid, len(indices) - k + mid):\n # 2 rolling sums\n mid_steps += indices[start] - indices[idx] + indices[end] - indices[idx+odd]\n start += 1\n end += 1\n if mid_steps == extra_steps:\n return 0\n elif min_swaps > mid_steps:\n min_swaps = mid_steps\n\n return min_swaps - extra_steps\n\n```
0
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34 "` will become `" 123 34 8 34 "`. Notice that you are left with some integers that are separated by at least one space: `"123 "`, `"34 "`, `"8 "`, and `"34 "`. Return _the number of **different** integers after performing the replacement operations on_ `word`. Two integers are considered different if their decimal representations **without any leading zeros** are different. **Example 1:** **Input:** word = "a123bc34d8ef34 " **Output:** 3 **Explanation:** The three different integers are "123 ", "34 ", and "8 ". Notice that "34 " is only counted once. **Example 2:** **Input:** word = "leet1234code234 " **Output:** 2 **Example 3:** **Input:** word = "a1b01c001 " **Output:** 1 **Explanation:** The three integers "1 ", "01 ", and "001 " all represent the same integer because the leading zeros are ignored when comparing their decimal values. **Constraints:** * `1 <= word.length <= 1000` * `word` consists of digits and lowercase English letters.
Choose k 1s and determine how many steps are required to move them into 1 group. Maintain a sliding window of k 1s, and maintain the steps required to group them. When you slide the window across, should you move the group to the right? Once you move the group to the right, it will never need to slide to the left again.
βœ… [PYTHON] Easy solution: zip() [Beats 96.52%]
determine-if-string-halves-are-alike
0
1
# Code\n```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n vowels = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n s_len = int(len(s) / 2)\n counter_a = counter_b = 0\n # parallel iteration by first and second part of "s":\n for char_a, char_b in zip(s[:s_len], s[s_len:]): \n if char_a in vowels:\n counter_a += 1\n if char_b in vowels:\n counter_b += 1\n return counter_a == counter_b\n```
1
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
βœ… [PYTHON] Easy solution: zip() [Beats 96.52%]
determine-if-string-halves-are-alike
0
1
# Code\n```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n vowels = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n s_len = int(len(s) / 2)\n counter_a = counter_b = 0\n # parallel iteration by first and second part of "s":\n for char_a, char_b in zip(s[:s_len], s[s_len:]): \n if char_a in vowels:\n counter_a += 1\n if char_b in vowels:\n counter_b += 1\n return counter_a == counter_b\n```
1
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
Beats 91.73% || Determine if string halves are alike
determine-if-string-halves-are-alike
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 halvesAreAlike(self, s: str) -> bool:\n vowels=[\'a\',\'e\',\'i\',\'o\',\'u\']\n length=len(s)\n str1=s[:length//2]\n str2=s[length//2:]\n count=0\n for i in str1.lower():\n if i in vowels:\n count+=1\n for i in str2.lower():\n if i in vowels:\n count-=1\n if count==0:\n return True\n else:\n return False\n```
1
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Beats 91.73% || Determine if string halves are alike
determine-if-string-halves-are-alike
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 halvesAreAlike(self, s: str) -> bool:\n vowels=[\'a\',\'e\',\'i\',\'o\',\'u\']\n length=len(s)\n str1=s[:length//2]\n str2=s[length//2:]\n count=0\n for i in str1.lower():\n if i in vowels:\n count+=1\n for i in str2.lower():\n if i in vowels:\n count-=1\n if count==0:\n return True\n else:\n return False\n```
1
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
MOST EASY SOLUTION you can think of
determine-if-string-halves-are-alike
0
1
```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n n = len(s)\n a = s[:n//2]\n b = s[n//2:]\n a_vowels=[]\n b_vowels=[]\n for i in a:\n if i in (\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'):\n a_vowels.append(i)\n for j in b:\n if j in (\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'):\n b_vowels.append(j)\n return(len(a_vowels) == len(b_vowels))\n ```
1
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
MOST EASY SOLUTION you can think of
determine-if-string-halves-are-alike
0
1
```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n n = len(s)\n a = s[:n//2]\n b = s[n//2:]\n a_vowels=[]\n b_vowels=[]\n for i in a:\n if i in (\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'):\n a_vowels.append(i)\n for j in b:\n if j in (\'a\',\'e\',\'i\',\'o\',\'u\',\'A\',\'E\',\'I\',\'O\',\'U\'):\n b_vowels.append(j)\n return(len(a_vowels) == len(b_vowels))\n ```
1
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
Python3 Solution | Easy to Understand
determine-if-string-halves-are-alike
0
1
Approach:\n1. Devided the string s int strings a and b\n2. count the number of vowels in a and b\n3. if the count of vowels in a is equel to the count vowels in b return True otherwise False\n# Smash that UPVOTE button! \uD83D\uDE0B\n\n```\ndef halvesAreAlike(self, s: str) -> bool:\n\tn = len(s)\n\ta = s[:n//2]\n\tb = s[n//2:]\n\tvowels_in_a = 0\n\tvowels_in_b = 0\n\tfor c in a:\n\t\tif c in "aeiouAEIOU":\n\t\t\tvowels_in_a +=1\n\tfor ch in b:\n\t\tif ch in "aeiouAEIOU":\n\t\t\tvowels_in_b +=1 \n\treturn vowels_in_a == vowels_in_b\n
1
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Python3 Solution | Easy to Understand
determine-if-string-halves-are-alike
0
1
Approach:\n1. Devided the string s int strings a and b\n2. count the number of vowels in a and b\n3. if the count of vowels in a is equel to the count vowels in b return True otherwise False\n# Smash that UPVOTE button! \uD83D\uDE0B\n\n```\ndef halvesAreAlike(self, s: str) -> bool:\n\tn = len(s)\n\ta = s[:n//2]\n\tb = s[n//2:]\n\tvowels_in_a = 0\n\tvowels_in_b = 0\n\tfor c in a:\n\t\tif c in "aeiouAEIOU":\n\t\t\tvowels_in_a +=1\n\tfor ch in b:\n\t\tif ch in "aeiouAEIOU":\n\t\t\tvowels_in_b +=1 \n\treturn vowels_in_a == vowels_in_b\n
1
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
βœ”οΈ Python Fastest Solution using Two Pointers | 99% Faster πŸ”₯
determine-if-string-halves-are-alike
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n \n vowels = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n \n right = len(s)-1\n left = 0\n \n a_vowel = 0\n b_vowel = 0\n \n while left<right:\n if s[left] in vowels:\n a_vowel+=1\n if s[right] in vowels:\n b_vowel+=1\n left+=1\n right-=1\n \n return a_vowel == b_vowel\n \n```\n**For Detail Explaination Refer this Blog:\nhttps://www.python-techs.com\n(Please open this link in new tab)**\n\nThank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.
1
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
βœ”οΈ Python Fastest Solution using Two Pointers | 99% Faster πŸ”₯
determine-if-string-halves-are-alike
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nclass Solution:\n def halvesAreAlike(self, s: str) -> bool:\n \n vowels = [\'a\', \'e\', \'i\', \'o\', \'u\', \'A\', \'E\', \'I\', \'O\', \'U\']\n \n right = len(s)-1\n left = 0\n \n a_vowel = 0\n b_vowel = 0\n \n while left<right:\n if s[left] in vowels:\n a_vowel+=1\n if s[right] in vowels:\n b_vowel+=1\n left+=1\n right-=1\n \n return a_vowel == b_vowel\n \n```\n**For Detail Explaination Refer this Blog:\nhttps://www.python-techs.com\n(Please open this link in new tab)**\n\nThank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.
1
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend. The rules of the game are as follows: 1. **Start** at the `1st` friend. 2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once. 3. The last friend you counted leaves the circle and loses the game. 4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat. 5. Else, the last friend in the circle wins the game. Given the number of friends, `n`, and an integer `k`, return _the winner of the game_. **Example 1:** **Input:** n = 5, k = 2 **Output:** 3 **Explanation:** Here are the steps of the game: 1) Start at friend 1. 2) Count 2 friends clockwise, which are friends 1 and 2. 3) Friend 2 leaves the circle. Next start is friend 3. 4) Count 2 friends clockwise, which are friends 3 and 4. 5) Friend 4 leaves the circle. Next start is friend 5. 6) Count 2 friends clockwise, which are friends 5 and 1. 7) Friend 1 leaves the circle. Next start is friend 3. 8) Count 2 friends clockwise, which are friends 3 and 5. 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner. **Example 2:** **Input:** n = 6, k = 5 **Output:** 1 **Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1. **Constraints:** * `1 <= k <= n <= 500` **Follow up:** Could you solve this problem in linear time with constant space?
Create a function that checks if a character is a vowel, either uppercase or lowercase.
Python ACCEPTED solution with detailed explanation.
maximum-number-of-eaten-apples
0
1
Explanation:\nYou should keep track of the available apples on daily basis and consume ones which will rot earlier. We can use a heap ```h``` which will store lists. Each list in the heap will contain the data related to the batch of apples of a day. The first element in the list will tell us till how many days the apple in that batch will stay fresh. The second element will tell how many apples are left in the same batch which can be consumed.\n\nComplexity:\nTime ```O(NlogN)``` Each batch will be inserted and popped from the heap once.\nSpace ```O(N)``` Maximum size of the heap.\n\nCode:\n```\nfrom heapq import heappush, heappop\nclass Solution:\n def eatenApples(self, A: List[int], D: List[int]) -> int:\n ans, i, N = 0, 0, len(A)\n h = []\n while i < N or h:\n # only push to heap when you have a valid i, and the apple has atleast one day to stay fresh.\n if i<N and A[i] > 0:\n heappush(h, [i+D[i], A[i]])\n # remove the rotten apples batches and the batches with no apples left (which might have got consumed).\n while h and (h[0][0] <= i or h[0][1] <= 0):\n heappop(h)\n # only if there is batch in heap after removing all the rotten ones, you can eat. else wait for the subsequent days for new apple batch by incrementing i.\n if h:\n h[0][1]-=1\n ans+=1\n i+=1\n return ans \n```\n\n\n\n
15
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Python ACCEPTED solution with detailed explanation.
maximum-number-of-eaten-apples
0
1
Explanation:\nYou should keep track of the available apples on daily basis and consume ones which will rot earlier. We can use a heap ```h``` which will store lists. Each list in the heap will contain the data related to the batch of apples of a day. The first element in the list will tell us till how many days the apple in that batch will stay fresh. The second element will tell how many apples are left in the same batch which can be consumed.\n\nComplexity:\nTime ```O(NlogN)``` Each batch will be inserted and popped from the heap once.\nSpace ```O(N)``` Maximum size of the heap.\n\nCode:\n```\nfrom heapq import heappush, heappop\nclass Solution:\n def eatenApples(self, A: List[int], D: List[int]) -> int:\n ans, i, N = 0, 0, len(A)\n h = []\n while i < N or h:\n # only push to heap when you have a valid i, and the apple has atleast one day to stay fresh.\n if i<N and A[i] > 0:\n heappush(h, [i+D[i], A[i]])\n # remove the rotten apples batches and the batches with no apples left (which might have got consumed).\n while h and (h[0][0] <= i or h[0][1] <= 0):\n heappop(h)\n # only if there is batch in heap after removing all the rotten ones, you can eat. else wait for the subsequent days for new apple batch by incrementing i.\n if h:\n h[0][1]-=1\n ans+=1\n i+=1\n return ans \n```\n\n\n\n
15
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
[Java/Python] Greedy Solution
maximum-number-of-eaten-apples
1
1
Honestly, when I worked on this one, I spent a lot of time to determine some minor details and jumped between the code and description frequently to make sure I am on the right track.. \n\n**To reach the max result, we need to choose the earliest rotten apples to eat.** So We will use a Priority Queue to simulate this selection. \n\nJava:\n\n```\n public int eatenApples(int[] apples, int[] days) {\n int res = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);\n int length = apples.length;\n for(int day = 0; day < 40001; day++){\n if (day < length){\n pq.add(new int[]{day + days[day]-1, apples[day]});\n }\n while (!pq.isEmpty()){\n int[] cur = pq.peek();\n if(cur[0] < day){\n pq.poll();\n }else{\n break;\n }\n }\n if (!pq.isEmpty()) {\n int[] cur = pq.poll();\n cur[1]--;\n res += 1;\n if(cur[1] > 0){\n pq.add(cur);\n }\n }\n }\n return res;\n }\n```\n\nPython3:\n\n```\n def eatenApples(self, apples: List[int], expire: List[int]) -> int:\n q=[]\n idx=ans=0\n while q or idx<len(apples):\n if idx<len(apples):\n heapq.heappush(q,[expire[idx]+idx,apples[idx]])\n while q and (q[0][0]<=idx or q[0][1]==0):\n heappop(q)\n if q:\n ans+=1\n q[0][1]-=1\n idx+=1\n return ans\n```
9
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
[Java/Python] Greedy Solution
maximum-number-of-eaten-apples
1
1
Honestly, when I worked on this one, I spent a lot of time to determine some minor details and jumped between the code and description frequently to make sure I am on the right track.. \n\n**To reach the max result, we need to choose the earliest rotten apples to eat.** So We will use a Priority Queue to simulate this selection. \n\nJava:\n\n```\n public int eatenApples(int[] apples, int[] days) {\n int res = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);\n int length = apples.length;\n for(int day = 0; day < 40001; day++){\n if (day < length){\n pq.add(new int[]{day + days[day]-1, apples[day]});\n }\n while (!pq.isEmpty()){\n int[] cur = pq.peek();\n if(cur[0] < day){\n pq.poll();\n }else{\n break;\n }\n }\n if (!pq.isEmpty()) {\n int[] cur = pq.poll();\n cur[1]--;\n res += 1;\n if(cur[1] > 0){\n pq.add(cur);\n }\n }\n }\n return res;\n }\n```\n\nPython3:\n\n```\n def eatenApples(self, apples: List[int], expire: List[int]) -> int:\n q=[]\n idx=ans=0\n while q or idx<len(apples):\n if idx<len(apples):\n heapq.heappush(q,[expire[idx]+idx,apples[idx]])\n while q and (q[0][0]<=idx or q[0][1]==0):\n heappop(q)\n if q:\n ans+=1\n q[0][1]-=1\n idx+=1\n return ans\n```
9
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Python Heap Solution Beats 100% with Detailed Explanation
maximum-number-of-eaten-apples
0
1
If this is given to you personally, what would you do?\nI would eat the apples that are going to rot first.\n\nSo let\'s do that. We need to know how many apples have rotten today so that we throw them away and if we have some apples left, eat one from the lot which is going to rot the earliest. \n\nThis means we need to store all this data in a data structure using which we can know which apples have the shortest life span on this day. This means that if 5 apples were produced on day 1 which will rot in 5 days, then on day 3, their validity is 2 days.\n\nA min-heap seems to be the best data structure to store this. We will always have the fastest rotting apple-lot on the top of the heap that we can consume first.\n\n```python\nfrom heapq import heappush as push\nfrom heapq import heappop as pop\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n heap = []\n res = 0\n i=0\n N = len(apples)\n while i<N or heap:\n if i<N and apples[i]>0:\n push(heap, [days[i]+i, apples[i]])\n while heap and (heap[0][0]<=i or heap[0][1]<=0):\n pop(heap)\n if heap:\n heap[0][1]-=1\n res+=1\n i+=1\n return res\n```
6
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Python Heap Solution Beats 100% with Detailed Explanation
maximum-number-of-eaten-apples
0
1
If this is given to you personally, what would you do?\nI would eat the apples that are going to rot first.\n\nSo let\'s do that. We need to know how many apples have rotten today so that we throw them away and if we have some apples left, eat one from the lot which is going to rot the earliest. \n\nThis means we need to store all this data in a data structure using which we can know which apples have the shortest life span on this day. This means that if 5 apples were produced on day 1 which will rot in 5 days, then on day 3, their validity is 2 days.\n\nA min-heap seems to be the best data structure to store this. We will always have the fastest rotting apple-lot on the top of the heap that we can consume first.\n\n```python\nfrom heapq import heappush as push\nfrom heapq import heappop as pop\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n heap = []\n res = 0\n i=0\n N = len(apples)\n while i<N or heap:\n if i<N and apples[i]>0:\n push(heap, [days[i]+i, apples[i]])\n while heap and (heap[0][0]<=i or heap[0][1]<=0):\n pop(heap)\n if heap:\n heap[0][1]-=1\n res+=1\n i+=1\n return res\n```
6
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Easy python solution using heap (priority queue)
maximum-number-of-eaten-apples
0
1
# Intuition\ni have defined `popFromHeap` that will pop from the heap based on the limit and return the `day`, `num` and new `heap` after poping element. \n\nin the `eatenApples` for each day use `popFromHeap` to find if there is any fresh apples left to eat or not. if its there then increment the counter. finally once the `apples` are done check for how long you can eat the remaining apples using the same function. \n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```py\nclass Solution:\n def popFromHeap(self, heap, limit) :\n heap = heap.copy()\n while heap :\n day, num = heappop(heap)\n if day <= limit or num == 0 : \n continue \n return day, num, heap\n return []\n\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n heap, counter = [], 0\n for i in range(len(apples)) :\n heappush(heap, (days[i]+i, apples[i])) \n if self.popFromHeap(heap, i) : \n day, num, heap = self.popFromHeap(heap, i)\n if num > 0 : \n counter += 1\n if num - 1 > 0 :\n heappush(heap, (day, num-1))\n \n pointer = len(apples)\n while heap :\n if self.popFromHeap(heap, pointer) : \n day, num, heap = self.popFromHeap(heap, pointer)\n if num > 0 : \n counter += 1\n if num - 1 > 0 :\n heappush(heap, (day, num-1))\n else : \n break \n pointer += 1\n return counter \n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Easy python solution using heap (priority queue)
maximum-number-of-eaten-apples
0
1
# Intuition\ni have defined `popFromHeap` that will pop from the heap based on the limit and return the `day`, `num` and new `heap` after poping element. \n\nin the `eatenApples` for each day use `popFromHeap` to find if there is any fresh apples left to eat or not. if its there then increment the counter. finally once the `apples` are done check for how long you can eat the remaining apples using the same function. \n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(N)\n\n# Code\n```py\nclass Solution:\n def popFromHeap(self, heap, limit) :\n heap = heap.copy()\n while heap :\n day, num = heappop(heap)\n if day <= limit or num == 0 : \n continue \n return day, num, heap\n return []\n\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n heap, counter = [], 0\n for i in range(len(apples)) :\n heappush(heap, (days[i]+i, apples[i])) \n if self.popFromHeap(heap, i) : \n day, num, heap = self.popFromHeap(heap, i)\n if num > 0 : \n counter += 1\n if num - 1 > 0 :\n heappush(heap, (day, num-1))\n \n pointer = len(apples)\n while heap :\n if self.popFromHeap(heap, pointer) : \n day, num, heap = self.popFromHeap(heap, pointer)\n if num > 0 : \n counter += 1\n if num - 1 > 0 :\n heappush(heap, (day, num-1))\n else : \n break \n pointer += 1\n return counter \n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Python heap
maximum-number-of-eaten-apples
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 heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n expire_days = days\n exp = []\n res = 0\n d = 0\n while d < len(apples) or exp:\n # throw expired\n while exp and exp[0][0] < d:\n heapq.heappop(exp)\n # eat one\n if exp:\n d1, c = heapq.heappop(exp)\n if c > 1:\n heapq.heappush(exp, (d1, c-1))\n res += 1\n # load new ones\n if d < len(apples):\n expire_at, count = d+expire_days[d], apples[d]\n if count > 0:\n heapq.heappush(exp, (expire_at, count))\n d+=1\n return res\n\n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Python heap
maximum-number-of-eaten-apples
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 heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n expire_days = days\n exp = []\n res = 0\n d = 0\n while d < len(apples) or exp:\n # throw expired\n while exp and exp[0][0] < d:\n heapq.heappop(exp)\n # eat one\n if exp:\n d1, c = heapq.heappop(exp)\n if c > 1:\n heapq.heappush(exp, (d1, c-1))\n res += 1\n # load new ones\n if d < len(apples):\n expire_at, count = d+expire_days[d], apples[d]\n if count > 0:\n heapq.heappush(exp, (expire_at, count))\n d+=1\n return res\n\n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Easy to understand Python heap solution
maximum-number-of-eaten-apples
0
1
# Code\n```\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n total = 0\n plan = []\n i = 0\n while i < len(apples) or plan:\n if i < len(apples):\n apple = apples[i]\n heapq.heappush(plan, (i + days[i], apple))\n\n while plan and plan[0][0] <= i:\n heapq.heappop(plan)\n\n if plan:\n expire, a = heapq.heappop(plan)\n total += 1\n if a > 1:\n heapq.heappush(plan, (expire, a-1))\n\n i += 1\n\n return total\n\n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Easy to understand Python heap solution
maximum-number-of-eaten-apples
0
1
# Code\n```\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n total = 0\n plan = []\n i = 0\n while i < len(apples) or plan:\n if i < len(apples):\n apple = apples[i]\n heapq.heappush(plan, (i + days[i], apple))\n\n while plan and plan[0][0] <= i:\n heapq.heappop(plan)\n\n if plan:\n expire, a = heapq.heappop(plan)\n total += 1\n if a > 1:\n heapq.heappush(plan, (expire, a-1))\n\n i += 1\n\n return total\n\n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Python heap solution beats 91.67%
maximum-number-of-eaten-apples
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 eatenApples(self, apples: List[int], days: List[int]) -> int:\n day=0\n res=0\n store=[]\n for a,d in zip(apples,days):\n while store and store[0][0]<day:\n heapq.heappop(store)\n if a>0:\n heapq.heappush(store,[day+d-1,a])\n if store:\n store[0][1]-=1\n res+=1\n if store[0][1]==0:\n heapq.heappop(store)\n day+=1\n while store:\n while store and store[0][0]<day:\n heapq.heappop(store)\n if store:\n store[0][1]-=1\n res+=1\n if store[0][1]==0:\n heapq.heappop(store)\n day+=1\n return res\n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Python heap solution beats 91.67%
maximum-number-of-eaten-apples
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 eatenApples(self, apples: List[int], days: List[int]) -> int:\n day=0\n res=0\n store=[]\n for a,d in zip(apples,days):\n while store and store[0][0]<day:\n heapq.heappop(store)\n if a>0:\n heapq.heappush(store,[day+d-1,a])\n if store:\n store[0][1]-=1\n res+=1\n if store[0][1]==0:\n heapq.heappop(store)\n day+=1\n while store:\n while store and store[0][0]<day:\n heapq.heappop(store)\n if store:\n store[0][1]-=1\n res+=1\n if store[0][1]==0:\n heapq.heappop(store)\n day+=1\n return res\n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Python 3, using heapq
maximum-number-of-eaten-apples
0
1
# Intuition\nAlways eat the oldest apple in stock, provided that they have not expired.\n\n# Approach\nWe use a min heap, sorted by expiry date. When stocking new apples, push to the heap. When eating apples, pop from the heap.\n\n# Complexity\n- Time complexity:\n$$O(n\\log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nimport heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n n = len(apples)\n # within n days: stocking and eating.\n stock = []\n heapq.heapify(stock)\n eaten = 0\n for i in range(n):\n napples, ndays = apples[i], days[i]\n # stock new apples\n if napples or ndays:\n last_day_to_eat = i + ndays - 1\n heapq.heappush(stock, (last_day_to_eat, napples))\n # eat from the oldest apples\n while stock:\n date, na = heapq.heappop(stock)\n if date < i: # expired\n continue\n eaten += 1\n if na != 1:\n heapq.heappush(stock, (date, na - 1))\n break\n\n # beyond n days: comsuming the stock.\n i = n\n while stock:\n date, na = heapq.heappop(stock)\n if date < i: # expired\n continue\n can_have = min(na, date - i + 1)\n eaten += can_have\n i += can_have\n\n return eaten\n\n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
Python 3, using heapq
maximum-number-of-eaten-apples
0
1
# Intuition\nAlways eat the oldest apple in stock, provided that they have not expired.\n\n# Approach\nWe use a min heap, sorted by expiry date. When stocking new apples, push to the heap. When eating apples, pop from the heap.\n\n# Complexity\n- Time complexity:\n$$O(n\\log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nimport heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n n = len(apples)\n # within n days: stocking and eating.\n stock = []\n heapq.heapify(stock)\n eaten = 0\n for i in range(n):\n napples, ndays = apples[i], days[i]\n # stock new apples\n if napples or ndays:\n last_day_to_eat = i + ndays - 1\n heapq.heappush(stock, (last_day_to_eat, napples))\n # eat from the oldest apples\n while stock:\n date, na = heapq.heappop(stock)\n if date < i: # expired\n continue\n eaten += 1\n if na != 1:\n heapq.heappush(stock, (date, na - 1))\n break\n\n # beyond n days: comsuming the stock.\n i = n\n while stock:\n date, na = heapq.heappop(stock)\n if date < i: # expired\n continue\n can_have = min(na, date - i + 1)\n eaten += can_have\n i += can_have\n\n return eaten\n\n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
1705. Maximum Number of Eaten Apples_[Python 3] Easy-to-understand solution
maximum-number-of-eaten-apples
0
1
# Code\n```\nimport heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n res, i = 0, 0 # res is for count eatten apple, i is used to indicate the current day\n heap = []\n while i < len(days) or heap: # \u201Cor heap\u201D represents the remaining apples after n days\n if i < len(days) and apples[i] > 0 : # if apples grow on the i-th day, add the duration of validity and the number of apples to the list\n heapq.heappush(heap, [i + days[i], apples[i]])\n while heap and (heap [0][0] <= i or heap[0][1] <= 0): # remove the expired apples and the elements that do not produce any apples\n heapq.heappop(heap)\n if heap:\n heap[0][1] -= 1\n res += 1\n i += 1 \n \n return res\n```
0
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix β€œrank” where rank[i][j] holds how highly friend β€˜i' views β€˜j’. This allows for O(1) comparisons between people
1705. Maximum Number of Eaten Apples_[Python 3] Easy-to-understand solution
maximum-number-of-eaten-apples
0
1
# Code\n```\nimport heapq\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n res, i = 0, 0 # res is for count eatten apple, i is used to indicate the current day\n heap = []\n while i < len(days) or heap: # \u201Cor heap\u201D represents the remaining apples after n days\n if i < len(days) and apples[i] > 0 : # if apples grow on the i-th day, add the duration of validity and the number of apples to the list\n heapq.heappush(heap, [i + days[i], apples[i]])\n while heap and (heap [0][0] <= i or heap[0][1] <= 0): # remove the expired apples and the elements that do not produce any apples\n heapq.heappop(heap)\n if heap:\n heap[0][1] -= 1\n res += 1\n i += 1 \n \n return res\n```
0
There is a **3 lane road** of length `n` that consists of `n + 1` **points** labeled from `0` to `n`. A frog **starts** at point `0` in the **second** lane and wants to jump to point `n`. However, there could be obstacles along the way. You are given an array `obstacles` of length `n + 1` where each `obstacles[i]` (**ranging from 0 to 3**) describes an obstacle on the lane `obstacles[i]` at point `i`. If `obstacles[i] == 0`, there are no obstacles at point `i`. There will be **at most one** obstacle in the 3 lanes at each point. * For example, if `obstacles[2] == 1`, then there is an obstacle on lane 1 at point 2. The frog can only travel from point `i` to point `i + 1` on the same lane if there is not an obstacle on the lane at point `i + 1`. To avoid obstacles, the frog can also perform a **side jump** to jump to **another** lane (even if they are not adjacent) at the **same** point if there is no obstacle on the new lane. * For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3. Return _the **minimum number of side jumps** the frog needs to reach **any lane** at point n starting from lane `2` at point 0._ **Note:** There will be no obstacles on points `0` and `n`. **Example 1:** **Input:** obstacles = \[0,1,2,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows). Note that the frog can jump over obstacles only when making side jumps (as shown at point 2). **Example 2:** **Input:** obstacles = \[0,1,1,3,3,0\] **Output:** 0 **Explanation:** There are no obstacles on lane 2. No side jumps are required. **Example 3:** **Input:** obstacles = \[0,2,1,0,3,0\] **Output:** 2 **Explanation:** The optimal solution is shown by the arrows above. There are 2 side jumps. **Constraints:** * `obstacles.length == n + 1` * `1 <= n <= 5 * 105` * `0 <= obstacles[i] <= 3` * `obstacles[0] == obstacles[n] == 0`
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
Simple matrix solution with Python3
where-will-the-ball-fall
0
1
# Intuition\nHere we have matrix `grid`.\nOur goal is to put **at each column** a ball and check, if it\'s **feasible** to let a ball to reach **the final row** (that\'s falling over the board).\n\n# Approach\nAt this point we only need to check for pattern `1 => 1` or `-1 <= -1`, this leads the ball to fall over the board. Otherwise, it\'ll be **stuck**.\n\n1. let the ball fall from **each** column\n2. check if one of the patterns is **feasible**\n3. if it\'s, a ball continue to fall, and if it **reached the end**, store `col` to `ans`\n4. otherwise it **stuck in board** \n\n# Complexity\n- Time complexity: **O(N^2)** for matrix iteration.\n\n- Space complexity: **O(K)**, where `K` denotes to the number of columns.\n\n# Code\n```python\nclass Solution:\n def findBall(self, grid: list[list[int]]) -> list[int]:\n n, m = len(grid), len(grid[0])\n ans = [-1] * m\n\n def isValid(col):\n return 0 <= col < m\n\n for i in range(m):\n row = 0\n col = i\n\n while True:\n if row == n:\n ans[i] = col\n break\n\n if grid[row][col] == 1:\n # pattern 1 => 1\n if isValid(col + 1) and grid[row][col + 1] == 1:\n col += 1\n else:\n break \n else:\n # pattern -1 <= -1\n if isValid(col - 1) and grid[row][col - 1] == -1:\n col -= 1\n else:\n break\n \n # a ball continue to fall\n row += 1\n\n return ans\n```
1
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Simple matrix solution with Python3
where-will-the-ball-fall
0
1
# Intuition\nHere we have matrix `grid`.\nOur goal is to put **at each column** a ball and check, if it\'s **feasible** to let a ball to reach **the final row** (that\'s falling over the board).\n\n# Approach\nAt this point we only need to check for pattern `1 => 1` or `-1 <= -1`, this leads the ball to fall over the board. Otherwise, it\'ll be **stuck**.\n\n1. let the ball fall from **each** column\n2. check if one of the patterns is **feasible**\n3. if it\'s, a ball continue to fall, and if it **reached the end**, store `col` to `ans`\n4. otherwise it **stuck in board** \n\n# Complexity\n- Time complexity: **O(N^2)** for matrix iteration.\n\n- Space complexity: **O(K)**, where `K` denotes to the number of columns.\n\n# Code\n```python\nclass Solution:\n def findBall(self, grid: list[list[int]]) -> list[int]:\n n, m = len(grid), len(grid[0])\n ans = [-1] * m\n\n def isValid(col):\n return 0 <= col < m\n\n for i in range(m):\n row = 0\n col = i\n\n while True:\n if row == n:\n ans[i] = col\n break\n\n if grid[row][col] == 1:\n # pattern 1 => 1\n if isValid(col + 1) and grid[row][col + 1] == 1:\n col += 1\n else:\n break \n else:\n # pattern -1 <= -1\n if isValid(col - 1) and grid[row][col - 1] == -1:\n col -= 1\n else:\n break\n \n # a ball continue to fall\n row += 1\n\n return ans\n```
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Example 1:** **Input:** s = "HOW ARE YOU " **Output:** \[ "HAY ", "ORO ", "WEU "\] **Explanation:** Each word is printed vertically. "HAY " "ORO " "WEU " **Example 2:** **Input:** s = "TO BE OR NOT TO BE " **Output:** \[ "TBONTB ", "OEROOE ", " T "\] **Explanation:** Trailing spaces is not allowed. "TBONTB " "OEROOE " " T " **Example 3:** **Input:** s = "CONTEST IS COMING " **Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\] **Constraints:** * `1 <= s.length <= 200` * `s` contains only upper case English letters. * It's guaranteed that there is only one space between 2 words.
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
[Python3] Easy approach! Simulate each ball's trajectory
where-will-the-ball-fall
0
1
My approach to solving this problem is by simulating the trajectory of each ball.\nAnd if the path is not valid, then the inner loop break, otherwise we update the answer with `res[j] = pos` in the else clause after `for` syntax.\n\n``` \nclass Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n m, n = len(grid), len(grid[0])\n \n res = [-1] * n\n for j in range(n):\n pos = j\n i = 0\n for i in range(m):\n # while i < m:\n sep = grid[i][pos] # means seperator\n if sep == 1 and (pos == n - 1 or grid[i][pos + 1] == -1) \\\n or sep == -1 and (pos == 0 or grid[i][pos - 1] == 1): # NOT VALID\n break\n else: # VALID\n if sep == 1:\n pos += 1\n else:\n pos -= 1\n i += 1\n else:\n # The for loop finished without break!\n res[j] = pos\n return res\n```
1
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
[Python3] Easy approach! Simulate each ball's trajectory
where-will-the-ball-fall
0
1
My approach to solving this problem is by simulating the trajectory of each ball.\nAnd if the path is not valid, then the inner loop break, otherwise we update the answer with `res[j] = pos` in the else clause after `for` syntax.\n\n``` \nclass Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n m, n = len(grid), len(grid[0])\n \n res = [-1] * n\n for j in range(n):\n pos = j\n i = 0\n for i in range(m):\n # while i < m:\n sep = grid[i][pos] # means seperator\n if sep == 1 and (pos == n - 1 or grid[i][pos + 1] == -1) \\\n or sep == -1 and (pos == 0 or grid[i][pos - 1] == 1): # NOT VALID\n break\n else: # VALID\n if sep == 1:\n pos += 1\n else:\n pos -= 1\n i += 1\n else:\n # The for loop finished without break!\n res[j] = pos\n return res\n```
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Example 1:** **Input:** s = "HOW ARE YOU " **Output:** \[ "HAY ", "ORO ", "WEU "\] **Explanation:** Each word is printed vertically. "HAY " "ORO " "WEU " **Example 2:** **Input:** s = "TO BE OR NOT TO BE " **Output:** \[ "TBONTB ", "OEROOE ", " T "\] **Explanation:** Trailing spaces is not allowed. "TBONTB " "OEROOE " " T " **Example 3:** **Input:** s = "CONTEST IS COMING " **Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\] **Constraints:** * `1 <= s.length <= 200` * `s` contains only upper case English letters. * It's guaranteed that there is only one space between 2 words.
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
βœ”οΈ Python Solution with Explanation and Diagram | 97% Faster πŸ”₯
where-will-the-ball-fall
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nclass Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n r_len = len(grid)\n c_len = len(grid[0])\n output = list(range(c_len))\n \n for r in range(r_len):\n for i in range(c_len):\n c = output[i]\n if c == -1: continue\n c_nxt = c + grid[r][c]\n if c_nxt < 0 or c_nxt >= c_len or grid[r][c_nxt] == -grid[r][c]:\n output[i] = -1\n continue\n output[i] += grid[r][c]\n \n return output\n```\n\n**For Detail Explanation with Daigram Refer this Blog: https://www.python-techs.com/2022/10/where-will-ball-fall.html**\n\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
1
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
βœ”οΈ Python Solution with Explanation and Diagram | 97% Faster πŸ”₯
where-will-the-ball-fall
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nclass Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n r_len = len(grid)\n c_len = len(grid[0])\n output = list(range(c_len))\n \n for r in range(r_len):\n for i in range(c_len):\n c = output[i]\n if c == -1: continue\n c_nxt = c + grid[r][c]\n if c_nxt < 0 or c_nxt >= c_len or grid[r][c_nxt] == -grid[r][c]:\n output[i] = -1\n continue\n output[i] += grid[r][c]\n \n return output\n```\n\n**For Detail Explanation with Daigram Refer this Blog: https://www.python-techs.com/2022/10/where-will-ball-fall.html**\n\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Example 1:** **Input:** s = "HOW ARE YOU " **Output:** \[ "HAY ", "ORO ", "WEU "\] **Explanation:** Each word is printed vertically. "HAY " "ORO " "WEU " **Example 2:** **Input:** s = "TO BE OR NOT TO BE " **Output:** \[ "TBONTB ", "OEROOE ", " T "\] **Explanation:** Trailing spaces is not allowed. "TBONTB " "OEROOE " " T " **Example 3:** **Input:** s = "CONTEST IS COMING " **Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\] **Constraints:** * `1 <= s.length <= 200` * `s` contains only upper case English letters. * It's guaranteed that there is only one space between 2 words.
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
SIMPLE SOLUTION USING DFS
where-will-the-ball-fall
0
1
```\nclass Solution:\n def dfs(self,x,y,m,n,grid,visited):\n if visited[x][y]!=None:\n return visited[x][y]\n if y+grid[x][y]<0 or y+grid[x][y]>=n or (grid[x][y]+grid[x][y+grid[x][y]]==0):\n visited[x][y]=-1\n return -1\n visited[x][y]=y+grid[x][y]\n if x+1<m:\n return self.dfs(x+1,y+grid[x][y],m,n,grid,visited)\n else:\n return visited[x][y]\n \n def findBall(self, grid: List[List[int]]) -> List[int]:\n m=len(grid)\n n=len(grid[0])\n visited=[[None]*n for _ in range(m)]\n result=[]\n for i in range(n):\n x=self.dfs(0,i,m,n,grid,visited)\n result.append(x)\n return result\n```
1
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
SIMPLE SOLUTION USING DFS
where-will-the-ball-fall
0
1
```\nclass Solution:\n def dfs(self,x,y,m,n,grid,visited):\n if visited[x][y]!=None:\n return visited[x][y]\n if y+grid[x][y]<0 or y+grid[x][y]>=n or (grid[x][y]+grid[x][y+grid[x][y]]==0):\n visited[x][y]=-1\n return -1\n visited[x][y]=y+grid[x][y]\n if x+1<m:\n return self.dfs(x+1,y+grid[x][y],m,n,grid,visited)\n else:\n return visited[x][y]\n \n def findBall(self, grid: List[List[int]]) -> List[int]:\n m=len(grid)\n n=len(grid[0])\n visited=[[None]*n for _ in range(m)]\n result=[]\n for i in range(n):\n x=self.dfs(0,i,m,n,grid,visited)\n result.append(x)\n return result\n```
1
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Example 1:** **Input:** s = "HOW ARE YOU " **Output:** \[ "HAY ", "ORO ", "WEU "\] **Explanation:** Each word is printed vertically. "HAY " "ORO " "WEU " **Example 2:** **Input:** s = "TO BE OR NOT TO BE " **Output:** \[ "TBONTB ", "OEROOE ", " T "\] **Explanation:** Trailing spaces is not allowed. "TBONTB " "OEROOE " " T " **Example 3:** **Input:** s = "CONTEST IS COMING " **Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\] **Constraints:** * `1 <= s.length <= 200` * `s` contains only upper case English letters. * It's guaranteed that there is only one space between 2 words.
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Python || 99.52% Faster || Trie || Easy
maximum-xor-with-an-element-from-array
0
1
```\nclass Trie:\n def __init__(self):\n self.root={}\n self.m=0\n \n def insert(self,word):\n node=self.root\n for ch in word:\n if ch not in node:\n node[ch]={}\n node=node[ch]\n\n def compare(self,word,x):\n node=self.root\n t=""\n a,b=\'0\',\'1\'\n for ch in word:\n if ch==a and b in node:\n t+=b\n node=node[b]\n elif ch==b and a in node:\n t+=a\n node=node[a]\n else:\n t+=ch\n node=node[ch]\n ans=int(t,2)^x\n return ans\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n trie=Trie()\n n,l=len(queries),len(nums)\n for i in range(n):\n queries[i].append(i)\n queries.sort(key=lambda x:x[1])\n nums.sort()\n res=[0]*n\n j=0\n m=nums[0]\n for i in range(n):\n x,y,z=queries[i][0],queries[i][1],queries[i][2]\n if m>y:\n res[z]=-1\n continue\n while j<l and nums[j]<=y:\n word="{:032b}".format(nums[j])\n trie.insert(word)\n j+=1\n word="{:032b}".format(x)\n ans=trie.compare(word,x)\n res[z]=ans\n t=y\n return res\n```\n**An upvote will be encouraging**
2
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`. Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._ **Example 1:** **Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\] **Output:** \[3,3,7\] **Explanation:** 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. **Example 2:** **Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\] **Output:** \[15,-1,5\] **Constraints:** * `1 <= nums.length, queries.length <= 105` * `queries[i].length == 2` * `0 <= nums[j], xi, mi <= 109`
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
Python || 99.52% Faster || Trie || Easy
maximum-xor-with-an-element-from-array
0
1
```\nclass Trie:\n def __init__(self):\n self.root={}\n self.m=0\n \n def insert(self,word):\n node=self.root\n for ch in word:\n if ch not in node:\n node[ch]={}\n node=node[ch]\n\n def compare(self,word,x):\n node=self.root\n t=""\n a,b=\'0\',\'1\'\n for ch in word:\n if ch==a and b in node:\n t+=b\n node=node[b]\n elif ch==b and a in node:\n t+=a\n node=node[a]\n else:\n t+=ch\n node=node[ch]\n ans=int(t,2)^x\n return ans\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n trie=Trie()\n n,l=len(queries),len(nums)\n for i in range(n):\n queries[i].append(i)\n queries.sort(key=lambda x:x[1])\n nums.sort()\n res=[0]*n\n j=0\n m=nums[0]\n for i in range(n):\n x,y,z=queries[i][0],queries[i][1],queries[i][2]\n if m>y:\n res[z]=-1\n continue\n while j<l and nums[j]<=y:\n word="{:032b}".format(nums[j])\n trie.insert(word)\n j+=1\n word="{:032b}".format(x)\n ans=trie.compare(word,x)\n res[z]=ans\n t=y\n return res\n```\n**An upvote will be encouraging**
2
An experiment is being conducted in a lab. To ensure accuracy, there are **two** sensors collecting data simultaneously. You are given two arrays `sensor1` and `sensor2`, where `sensor1[i]` and `sensor2[i]` are the `ith` data points collected by the two sensors. However, this type of sensor has a chance of being defective, which causes **exactly one** data point to be dropped. After the data is dropped, all the data points to the **right** of the dropped data are **shifted** one place to the left, and the last data point is replaced with some **random value**. It is guaranteed that this random value will **not** be equal to the dropped value. * For example, if the correct data is `[1,2,**3**,4,5]` and `3` is dropped, the sensor could return `[1,2,4,5,**7**]` (the last position can be **any** value, not just `7`). We know that there is a defect in **at most one** of the sensors. Return _the sensor number (_`1` _or_ `2`_) with the defect. If there is **no defect** in either sensor or if it is **impossible** to determine the defective sensor, return_ `-1`_._ **Example 1:** **Input:** sensor1 = \[2,3,4,5\], sensor2 = \[2,1,3,4\] **Output:** 1 **Explanation:** Sensor 2 has the correct values. The second data point from sensor 2 is dropped, and the last value of sensor 1 is replaced by a 5. **Example 2:** **Input:** sensor1 = \[2,2,2,2,2\], sensor2 = \[2,2,2,2,5\] **Output:** -1 **Explanation:** It is impossible to determine which sensor has a defect. Dropping the last value for either sensor could produce the output for the other sensor. **Example 3:** **Input:** sensor1 = \[2,3,2,2,3,2\], sensor2 = \[2,3,2,3,2,7\] **Output:** 2 **Explanation:** Sensor 1 has the correct values. The fourth data point from sensor 1 is dropped, and the last value of sensor 1 is replaced by a 7. **Constraints:** * `sensor1.length == sensor2.length` * `1 <= sensor1.length <= 100` * `1 <= sensor1[i], sensor2[i] <= 100`
In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.
[Python3] trie
maximum-xor-with-an-element-from-array
0
1
**Algo**\nThis problem is similar to [421. Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) which can be solved efficiently via a trie. \n\n**Implementation** (100%)\n```\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n ans = [-1]*len(queries)\n \n trie = {}\n k = 0\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n node = trie\n val = bin(nums[k])[2:].zfill(32)\n for c in val: node = node.setdefault(int(c), {})\n node["#"] = nums[k]\n k += 1\n if trie: \n node = trie\n val = bin(x)[2:].zfill(32)\n for c in val: node = node.get(1-int(c)) or node.get(int(c))\n ans[i] = x ^ node["#"]\n return ans \n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nEdited on 12/27/2020\nAdding a refactored version below for clarity \n```\nclass Trie: \n def __init__(self):\n self.root = {}\n \n def __bool__(self):\n return bool(self.root)\n \n def insert(self, num):\n node = self.root \n for x in bin(num)[2:].zfill(32): \n node = node.setdefault(int(x), {})\n node["#"] = num\n \n def query(self, num): \n node = self.root\n for x in bin(num)[2:].zfill(32):\n node = node.get(1 - int(x)) or node.get(int(x))\n return num ^ node["#"]\n\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n \n ans = [-1]*len(queries)\n k = 0\n trie = Trie()\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n trie.insert(nums[k])\n k += 1\n if trie: ans[i] = trie.query(x)\n return ans \n```
19
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`. Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._ **Example 1:** **Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\] **Output:** \[3,3,7\] **Explanation:** 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. **Example 2:** **Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\] **Output:** \[15,-1,5\] **Constraints:** * `1 <= nums.length, queries.length <= 105` * `queries[i].length == 2` * `0 <= nums[j], xi, mi <= 109`
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
[Python3] trie
maximum-xor-with-an-element-from-array
0
1
**Algo**\nThis problem is similar to [421. Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) which can be solved efficiently via a trie. \n\n**Implementation** (100%)\n```\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n ans = [-1]*len(queries)\n \n trie = {}\n k = 0\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n node = trie\n val = bin(nums[k])[2:].zfill(32)\n for c in val: node = node.setdefault(int(c), {})\n node["#"] = nums[k]\n k += 1\n if trie: \n node = trie\n val = bin(x)[2:].zfill(32)\n for c in val: node = node.get(1-int(c)) or node.get(int(c))\n ans[i] = x ^ node["#"]\n return ans \n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nEdited on 12/27/2020\nAdding a refactored version below for clarity \n```\nclass Trie: \n def __init__(self):\n self.root = {}\n \n def __bool__(self):\n return bool(self.root)\n \n def insert(self, num):\n node = self.root \n for x in bin(num)[2:].zfill(32): \n node = node.setdefault(int(x), {})\n node["#"] = num\n \n def query(self, num): \n node = self.root\n for x in bin(num)[2:].zfill(32):\n node = node.get(1 - int(x)) or node.get(int(x))\n return num ^ node["#"]\n\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n \n ans = [-1]*len(queries)\n k = 0\n trie = Trie()\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n trie.insert(nums[k])\n k += 1\n if trie: ans[i] = trie.query(x)\n return ans \n```
19
An experiment is being conducted in a lab. To ensure accuracy, there are **two** sensors collecting data simultaneously. You are given two arrays `sensor1` and `sensor2`, where `sensor1[i]` and `sensor2[i]` are the `ith` data points collected by the two sensors. However, this type of sensor has a chance of being defective, which causes **exactly one** data point to be dropped. After the data is dropped, all the data points to the **right** of the dropped data are **shifted** one place to the left, and the last data point is replaced with some **random value**. It is guaranteed that this random value will **not** be equal to the dropped value. * For example, if the correct data is `[1,2,**3**,4,5]` and `3` is dropped, the sensor could return `[1,2,4,5,**7**]` (the last position can be **any** value, not just `7`). We know that there is a defect in **at most one** of the sensors. Return _the sensor number (_`1` _or_ `2`_) with the defect. If there is **no defect** in either sensor or if it is **impossible** to determine the defective sensor, return_ `-1`_._ **Example 1:** **Input:** sensor1 = \[2,3,4,5\], sensor2 = \[2,1,3,4\] **Output:** 1 **Explanation:** Sensor 2 has the correct values. The second data point from sensor 2 is dropped, and the last value of sensor 1 is replaced by a 5. **Example 2:** **Input:** sensor1 = \[2,2,2,2,2\], sensor2 = \[2,2,2,2,5\] **Output:** -1 **Explanation:** It is impossible to determine which sensor has a defect. Dropping the last value for either sensor could produce the output for the other sensor. **Example 3:** **Input:** sensor1 = \[2,3,2,2,3,2\], sensor2 = \[2,3,2,3,2,7\] **Output:** 2 **Explanation:** Sensor 1 has the correct values. The fourth data point from sensor 1 is dropped, and the last value of sensor 1 is replaced by a 7. **Constraints:** * `sensor1.length == sensor2.length` * `1 <= sensor1.length <= 100` * `1 <= sensor1[i], sensor2[i] <= 100`
In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.
Python | Trie | Offline Queries
maximum-xor-with-an-element-from-array
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 collections import defaultdict\nfrom sortedcontainers import SortedList\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n\n\n #sorting nums\n l=len(nums)\n nums.sort()\n ptr=0\n\n #Initialinsing Trie\n Trie=defaultdict(defaultdict)\n\n # answer\n nq=len(queries)\n ans=[0 for i in range(nq)]\n qury=SortedList()\n\n #sorting of queries\n for i in range(nq):\n qury.add((queries[i][1],queries[i][0],i))\n \n for i in range(nq):\n ref=qury[0]\n qury.discard(ref)\n while ptr<l and nums[ptr]<=ref[0]:\n tt=nums[ptr]\n local_trie=Trie\n\n for i in range(31,-1,-1):\n point=0\n if tt & 1<<i:\n point=1\n if not local_trie[point]:\n local_trie[point]=defaultdict(defaultdict) \n local_trie=local_trie[point]\n local_trie[\'end\']=True\n ptr+=1\n local_trie=Trie\n nm=0\n flag=True\n for i in range(31,-1,-1):\n point=0\n if ref[1] & 1<<i:\n point=1\n if local_trie[point^1]:\n nm+=2**i\n local_trie=local_trie[point ^ 1]\n elif local_trie[point]:\n local_trie=local_trie[point]\n else:\n flag=False\n break\n if not flag:\n ans[ref[2]]=-1\n else:\n ans[ref[2]]=nm \n return ans\n\n \n\n\n\n\n\n \n\n\n \n\n\n\n```
0
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`. Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._ **Example 1:** **Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\] **Output:** \[3,3,7\] **Explanation:** 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7. **Example 2:** **Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\] **Output:** \[15,-1,5\] **Constraints:** * `1 <= nums.length, queries.length <= 105` * `queries[i].length == 2` * `0 <= nums[j], xi, mi <= 109`
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
Python | Trie | Offline Queries
maximum-xor-with-an-element-from-array
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 collections import defaultdict\nfrom sortedcontainers import SortedList\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n\n\n #sorting nums\n l=len(nums)\n nums.sort()\n ptr=0\n\n #Initialinsing Trie\n Trie=defaultdict(defaultdict)\n\n # answer\n nq=len(queries)\n ans=[0 for i in range(nq)]\n qury=SortedList()\n\n #sorting of queries\n for i in range(nq):\n qury.add((queries[i][1],queries[i][0],i))\n \n for i in range(nq):\n ref=qury[0]\n qury.discard(ref)\n while ptr<l and nums[ptr]<=ref[0]:\n tt=nums[ptr]\n local_trie=Trie\n\n for i in range(31,-1,-1):\n point=0\n if tt & 1<<i:\n point=1\n if not local_trie[point]:\n local_trie[point]=defaultdict(defaultdict) \n local_trie=local_trie[point]\n local_trie[\'end\']=True\n ptr+=1\n local_trie=Trie\n nm=0\n flag=True\n for i in range(31,-1,-1):\n point=0\n if ref[1] & 1<<i:\n point=1\n if local_trie[point^1]:\n nm+=2**i\n local_trie=local_trie[point ^ 1]\n elif local_trie[point]:\n local_trie=local_trie[point]\n else:\n flag=False\n break\n if not flag:\n ans[ref[2]]=-1\n else:\n ans[ref[2]]=nm \n return ans\n\n \n\n\n\n\n\n \n\n\n \n\n\n\n```
0
An experiment is being conducted in a lab. To ensure accuracy, there are **two** sensors collecting data simultaneously. You are given two arrays `sensor1` and `sensor2`, where `sensor1[i]` and `sensor2[i]` are the `ith` data points collected by the two sensors. However, this type of sensor has a chance of being defective, which causes **exactly one** data point to be dropped. After the data is dropped, all the data points to the **right** of the dropped data are **shifted** one place to the left, and the last data point is replaced with some **random value**. It is guaranteed that this random value will **not** be equal to the dropped value. * For example, if the correct data is `[1,2,**3**,4,5]` and `3` is dropped, the sensor could return `[1,2,4,5,**7**]` (the last position can be **any** value, not just `7`). We know that there is a defect in **at most one** of the sensors. Return _the sensor number (_`1` _or_ `2`_) with the defect. If there is **no defect** in either sensor or if it is **impossible** to determine the defective sensor, return_ `-1`_._ **Example 1:** **Input:** sensor1 = \[2,3,4,5\], sensor2 = \[2,1,3,4\] **Output:** 1 **Explanation:** Sensor 2 has the correct values. The second data point from sensor 2 is dropped, and the last value of sensor 1 is replaced by a 5. **Example 2:** **Input:** sensor1 = \[2,2,2,2,2\], sensor2 = \[2,2,2,2,5\] **Output:** -1 **Explanation:** It is impossible to determine which sensor has a defect. Dropping the last value for either sensor could produce the output for the other sensor. **Example 3:** **Input:** sensor1 = \[2,3,2,2,3,2\], sensor2 = \[2,3,2,3,2,7\] **Output:** 2 **Explanation:** Sensor 1 has the correct values. The fourth data point from sensor 1 is dropped, and the last value of sensor 1 is replaced by a 7. **Constraints:** * `sensor1.length == sensor2.length` * `1 <= sensor1.length <= 100` * `1 <= sensor1[i], sensor2[i] <= 100`
In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.
simpler solution beat 80% of python users
maximum-units-on-a-truck
0
1
\n\n# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse = True)\n\n p=0\n for i, j in boxTypes:\n if i<truckSize:\n p+=i*j\n truckSize-=i\n else:\n p+=truckSize*j\n break\n return p \n \n \n```
1
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
simpler solution beat 80% of python users
maximum-units-on-a-truck
0
1
\n\n# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse = True)\n\n p=0\n for i, j in boxTypes:\n if i<truckSize:\n p+=i*j\n truckSize-=i\n else:\n p+=truckSize*j\n break\n return p \n \n \n```
1
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Greedy Approach | Sorted boxTypes | Beginner friendly
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n ans = 0\n boxTypes = sorted(boxTypes, key=lambda x: x[1], reverse=True)\n for boxes, units in boxTypes:\n while boxes and truckSize > 0:\n ans += units\n boxes -= 1\n truckSize -= 1\n return ans\n \n```
0
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Greedy Approach | Sorted boxTypes | Beginner friendly
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n ans = 0\n boxTypes = sorted(boxTypes, key=lambda x: x[1], reverse=True)\n for boxes, units in boxTypes:\n while boxes and truckSize > 0:\n ans += units\n boxes -= 1\n truckSize -= 1\n return ans\n \n```
0
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Python βœ…βœ…βœ… || Faster than 81.43% || Memory Beats 84.9%
maximum-units-on-a-truck
0
1
# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(reverse=True, key=lambda x:x[1])\n units = 0\n boxesUsed = 0\n for box in boxTypes:\n if boxesUsed == truckSize: return units\n if boxesUsed + box[0] <= truckSize:\n units += box[1] * box[0]\n boxesUsed += box[0]\n elif boxesUsed + box[0] > truckSize:\n units += box[1] * (truckSize - boxesUsed)\n boxesUsed += truckSize - boxesUsed\n return units\n```\n\n![image.png](https://assets.leetcode.com/users/images/99b8fe17-63a4-4b3f-97ca-73d17f86056a_1669769957.803379.png)\n![image.png](https://assets.leetcode.com/users/images/ddf2151e-735e-4768-a95a-859b496d02a4_1669770109.2075849.png)\n
1
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Python βœ…βœ…βœ… || Faster than 81.43% || Memory Beats 84.9%
maximum-units-on-a-truck
0
1
# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(reverse=True, key=lambda x:x[1])\n units = 0\n boxesUsed = 0\n for box in boxTypes:\n if boxesUsed == truckSize: return units\n if boxesUsed + box[0] <= truckSize:\n units += box[1] * box[0]\n boxesUsed += box[0]\n elif boxesUsed + box[0] > truckSize:\n units += box[1] * (truckSize - boxesUsed)\n boxesUsed += truckSize - boxesUsed\n return units\n```\n\n![image.png](https://assets.leetcode.com/users/images/99b8fe17-63a4-4b3f-97ca-73d17f86056a_1669769957.803379.png)\n![image.png](https://assets.leetcode.com/users/images/ddf2151e-735e-4768-a95a-859b496d02a4_1669770109.2075849.png)\n
1
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
trash solution hoping for coaching
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes = sorted(boxTypes, key = lambda x:x[1],reverse = True)\n sum = 0\n i = 0\n \n while truckSize: \n if i >= len(boxTypes):\n break \n sum = sum + boxTypes[i][1]\n \n boxTypes[i][0] = boxTypes[i][0]-1\n if boxTypes[i][0] == 0:\n i = i+1\n truckSize = truckSize - 1\n\n \n return sum \n\n\n\n\n\n \n```
1
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
trash solution hoping for coaching
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes = sorted(boxTypes, key = lambda x:x[1],reverse = True)\n sum = 0\n i = 0\n \n while truckSize: \n if i >= len(boxTypes):\n break \n sum = sum + boxTypes[i][1]\n \n boxTypes[i][0] = boxTypes[i][0]-1\n if boxTypes[i][0] == 0:\n i = i+1\n truckSize = truckSize - 1\n\n \n return sum \n\n\n\n\n\n \n```
1
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
easy Python3 code
maximum-units-on-a-truck
0
1
# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n box=0 \n boxTypes.sort(key=lambda x:-x[1])\n for i in range(len(boxTypes)):\n if truckSize>=boxTypes[i][0]:\n truckSize -= boxTypes[i][0]\n box += boxTypes[i][0]*boxTypes[i][1]\n else:\n box += boxTypes[i][1]*truckSize\n break\n return box\n\n```
1
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
easy Python3 code
maximum-units-on-a-truck
0
1
# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n box=0 \n boxTypes.sort(key=lambda x:-x[1])\n for i in range(len(boxTypes)):\n if truckSize>=boxTypes[i][0]:\n truckSize -= boxTypes[i][0]\n box += boxTypes[i][0]*boxTypes[i][1]\n else:\n box += boxTypes[i][1]*truckSize\n break\n return box\n\n```
1
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Simple Solution in Python | Beats 84.28%
maximum-units-on-a-truck
0
1
\n# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key = lambda boxTypes: boxTypes[1], reverse=True)\n res = cur_size = 0\n for box, pack in boxTypes:\n if cur_size == truckSize:\n break\n if box > truckSize-cur_size:\n return res + (truckSize-cur_size)*pack\n else:\n res += box*pack\n cur_size += box\n return res\n\n```
1
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Simple Solution in Python | Beats 84.28%
maximum-units-on-a-truck
0
1
\n# Code\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key = lambda boxTypes: boxTypes[1], reverse=True)\n res = cur_size = 0\n for box, pack in boxTypes:\n if cur_size == truckSize:\n break\n if box > truckSize-cur_size:\n return res + (truckSize-cur_size)*pack\n else:\n res += box*pack\n cur_size += box\n return res\n\n```
1
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Easiest solution in python3
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x: -x[1])\n totalnumber=0\n for numberboxes,units in boxTypes:\n if truckSize<=numberboxes:\n totalnumber+=(truckSize*units)\n break\n totalnumber+=(numberboxes*units)\n truckSize-=numberboxes\n return totalnumber\n #plz do upvote it will be greatful if u did it\n \n```
3
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Easiest solution in python3
maximum-units-on-a-truck
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 maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x: -x[1])\n totalnumber=0\n for numberboxes,units in boxTypes:\n if truckSize<=numberboxes:\n totalnumber+=(truckSize*units)\n break\n totalnumber+=(numberboxes*units)\n truckSize-=numberboxes\n return totalnumber\n #plz do upvote it will be greatful if u did it\n \n```
3
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Python 3, Faster than 90%, easy to understand
maximum-units-on-a-truck
0
1
**Explanation:**\n\nI sorted boxTypes in a way that I would go from maximum units per box to minimum.\nThan i simply just add (units * box) to sum_ while truckSize > 0.\n\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n sum_ = 0\n\t\t#sorting boxTypes by the second element\n boxTypes.sort(key=lambda x:x[1])\n\t\t#reverse because going from max units per box to min units per box\n boxTypes.reverse()\n for box, units in boxTypes:\n if truckSize > box:\n truckSize -= box\n sum_ += box * units\n else:\n sum_ += truckSize * units\n break\n return sum_\n```
3
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Python 3, Faster than 90%, easy to understand
maximum-units-on-a-truck
0
1
**Explanation:**\n\nI sorted boxTypes in a way that I would go from maximum units per box to minimum.\nThan i simply just add (units * box) to sum_ while truckSize > 0.\n\n```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n sum_ = 0\n\t\t#sorting boxTypes by the second element\n boxTypes.sort(key=lambda x:x[1])\n\t\t#reverse because going from max units per box to min units per box\n boxTypes.reverse()\n for box, units in boxTypes:\n if truckSize > box:\n truckSize -= box\n sum_ += box * units\n else:\n sum_ += truckSize * units\n break\n return sum_\n```
3
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
[Python] Simple solution
maximum-units-on-a-truck
0
1
```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse=1)\n s=0\n for i,j in boxTypes:\n i=min(i,truckSize)\n s+=i*j\n truckSize-=i\n if truckSize==0:\n break\n return s\n```
31
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
[Python] Simple solution
maximum-units-on-a-truck
0
1
```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse=1)\n s=0\n for i,j in boxTypes:\n i=min(i,truckSize)\n s+=i*j\n truckSize-=i\n if truckSize==0:\n break\n return s\n```
31
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
Python(Simple Solution) | Faster : 96.89 | Time : O(nlogn)
maximum-units-on-a-truck
0
1
\tclass Solution:\n\t\tdef maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n\t\t\tboxTypes = sorted(boxTypes, key = lambda x : x[1], reverse = True)\n\t\t\toutput = 0\n\t\t\tfor no, units in boxTypes:\n\t\t\t\tif truckSize > no:\n\t\t\t\t\ttruckSize -= no\n\t\t\t\t\toutput += (no * units)\n\t\t\t\telse:\n\t\t\t\t\toutput += (truckSize * units)\n\t\t\t\t\tbreak\n\t\t\treturn output\n\n**If You Like The Solution Upvote.**
9
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Python(Simple Solution) | Faster : 96.89 | Time : O(nlogn)
maximum-units-on-a-truck
0
1
\tclass Solution:\n\t\tdef maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n\t\t\tboxTypes = sorted(boxTypes, key = lambda x : x[1], reverse = True)\n\t\t\toutput = 0\n\t\t\tfor no, units in boxTypes:\n\t\t\t\tif truckSize > no:\n\t\t\t\t\ttruckSize -= no\n\t\t\t\t\toutput += (no * units)\n\t\t\t\telse:\n\t\t\t\t\toutput += (truckSize * units)\n\t\t\t\t\tbreak\n\t\t\treturn output\n\n**If You Like The Solution Upvote.**
9
You are given a **sorted** array `nums` of `n` non-negative integers and an integer `maximumBit`. You want to perform the following query `n` **times**: 1. Find a non-negative integer `k < 2maximumBit` such that `nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k` is **maximized**. `k` is the answer to the `ith` query. 2. Remove the **last** element from the current array `nums`. Return _an array_ `answer`_, where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[0,1,1,3\], maximumBit = 2 **Output:** \[0,3,2,3\] **Explanation**: The queries are answered as follows: 1st query: nums = \[0,1,1,3\], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = \[0,1,1\], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = \[0,1\], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = \[0\], k = 3 since 0 XOR 3 = 3. **Example 2:** **Input:** nums = \[2,3,4,7\], maximumBit = 3 **Output:** \[5,2,6,5\] **Explanation**: The queries are answered as follows: 1st query: nums = \[2,3,4,7\], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7. 2nd query: nums = \[2,3,4\], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7. 3rd query: nums = \[2,3\], k = 6 since 2 XOR 3 XOR 6 = 7. 4th query: nums = \[2\], k = 5 since 2 XOR 5 = 7. **Example 3:** **Input:** nums = \[0,1,2,2,5,7\], maximumBit = 3 **Output:** \[4,3,6,4,6,7\] **Constraints:** * `nums.length == n` * `1 <= n <= 105` * `1 <= maximumBit <= 20` * `0 <= nums[i] < 2maximumBit` * `nums`​​​ is sorted in **ascending** order.
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
[Python3] Math + Hash Table - Simple
count-good-meals
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 * 22)$$\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 countPairs(self, deliciousness: List[int]) -> int:\n mod = 10 ** 9 + 7\n cnt = collections.Counter(deliciousness)\n res = 0\n for k, v in cnt.items():\n for i in range(22):\n p = (1 << i) - k\n if p >= 0 and p in cnt:\n if p == k: res += v * (v - 1)\n else: res += v * cnt[p]\n \n return (res // 2) % mod\n```
4
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
[Python3] Math + Hash Table - Simple
count-good-meals
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 * 22)$$\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 countPairs(self, deliciousness: List[int]) -> int:\n mod = 10 ** 9 + 7\n cnt = collections.Counter(deliciousness)\n res = 0\n for k, v in cnt.items():\n for i in range(22):\n p = (1 << i) - k\n if p >= 0 and p in cnt:\n if p == k: res += v * (v - 1)\n else: res += v * cnt[p]\n \n return (res // 2) % mod\n```
4
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
[Python3] frequency table
count-good-meals
0
1
**Algo**\nCompute frequency table of `deliciousness` from which you can check for complement of each `2**k` given a number (since there are only < 30 such power of 2 to consider).\n\n**Implementation**\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0\n freq = defaultdict(int)\n for x in deliciousness: \n for k in range(22): ans += freq[2**k - x]\n freq[x] += 1\n return ans % 1_000_000_007\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nEdited on 1/3/2021\nAdding a 2-pass version\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n freq = defaultdict(int)\n for x in deliciousness: freq[x] += 1\n \n ans = 0\n for x in freq: \n for k in range(22): \n if 2**k - x <= x and 2**k - x in freq: \n ans += freq[x]*(freq[x]-1)//2 if 2**k - x == x else freq[x]*freq[2**k-x]\n return ans % 1_000_000_007\n```
44
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
[Python3] frequency table
count-good-meals
0
1
**Algo**\nCompute frequency table of `deliciousness` from which you can check for complement of each `2**k` given a number (since there are only < 30 such power of 2 to consider).\n\n**Implementation**\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0\n freq = defaultdict(int)\n for x in deliciousness: \n for k in range(22): ans += freq[2**k - x]\n freq[x] += 1\n return ans % 1_000_000_007\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nEdited on 1/3/2021\nAdding a 2-pass version\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n freq = defaultdict(int)\n for x in deliciousness: freq[x] += 1\n \n ans = 0\n for x in freq: \n for k in range(22): \n if 2**k - x <= x and 2**k - x in freq: \n ans += freq[x]*(freq[x]-1)//2 if 2**k - x == x else freq[x]*freq[2**k-x]\n return ans % 1_000_000_007\n```
44
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
O(N) Python Solution
count-good-meals
0
1
# Intuition\nWe know we can solve this in O(n^2). But can we make it efficient? It turns out, yes we can. \n\n# Approach\nWe know that power functions grow very fast.\n- If we look at the constraints, we can see that the largest possible number is 2^20. what this tells us is that, there is exactly 20 numbers in the range 0 - 2^20 that are powers of two. these are 2^0, 2^1, 2^2, 2^3,...,2^20.\n\n- now, the problem is reduced to "two sum" problem but in this case we are not searching for a single sum, but the powers of 2, which we found to be a maximum of 20.\n\n- by doing this, we broke down the problem from O(n^2) to O(20*n), which is O(n).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n powers = [2 ** i for i in range(22)]\n MOD = 10e8 + 7\n count = Counter(deliciousness)\n good_meals = set()\n for n in count:\n for p in powers:\n if p - n in count and (n != p - n or count[p - n] > 1) and (p - n, n) not in good_meals:\n good_meals.add((n, p - n))\n \n ans = 0\n for m in good_meals:\n if m[0] == m[1]:\n ans += ((count[m[0]] - 1) * (count[m[0]]) // 2)\n else:\n ans += (count[m[0]] * count[m[1]])\n return int(ans % MOD)\n\n```
1
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
O(N) Python Solution
count-good-meals
0
1
# Intuition\nWe know we can solve this in O(n^2). But can we make it efficient? It turns out, yes we can. \n\n# Approach\nWe know that power functions grow very fast.\n- If we look at the constraints, we can see that the largest possible number is 2^20. what this tells us is that, there is exactly 20 numbers in the range 0 - 2^20 that are powers of two. these are 2^0, 2^1, 2^2, 2^3,...,2^20.\n\n- now, the problem is reduced to "two sum" problem but in this case we are not searching for a single sum, but the powers of 2, which we found to be a maximum of 20.\n\n- by doing this, we broke down the problem from O(n^2) to O(20*n), which is O(n).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n powers = [2 ** i for i in range(22)]\n MOD = 10e8 + 7\n count = Counter(deliciousness)\n good_meals = set()\n for n in count:\n for p in powers:\n if p - n in count and (n != p - n or count[p - n] > 1) and (p - n, n) not in good_meals:\n good_meals.add((n, p - n))\n \n ans = 0\n for m in good_meals:\n if m[0] == m[1]:\n ans += ((count[m[0]] - 1) * (count[m[0]]) // 2)\n else:\n ans += (count[m[0]] * count[m[1]])\n return int(ans % MOD)\n\n```
1
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
[python3] O(N) | 100% | 100% | easy to understand
count-good-meals
0
1
```\nclass Solution:\n """\n dp -> key: i value: amount of deliciousness == i\n for d in 2**0, 2**1, ..., 2**21\n why 2**21: max of deliciousness is 2*20, sum of 2 max is 2**21\n O(22*N)\n """\n def countPairs(self, ds: List[int]) -> int:\n from collections import defaultdict\n dp = defaultdict(int)\n # ds.sort() # no need to sort\n res = 0\n \n for d in ds:\n for i in range(22):\n # if 2**i - d in dp:\n res += dp[2**i - d]\n dp[d] += 1\n return res % (10**9 + 7)\n \n \n \n \n```
5
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
[python3] O(N) | 100% | 100% | easy to understand
count-good-meals
0
1
```\nclass Solution:\n """\n dp -> key: i value: amount of deliciousness == i\n for d in 2**0, 2**1, ..., 2**21\n why 2**21: max of deliciousness is 2*20, sum of 2 max is 2**21\n O(22*N)\n """\n def countPairs(self, ds: List[int]) -> int:\n from collections import defaultdict\n dp = defaultdict(int)\n # ds.sort() # no need to sort\n res = 0\n \n for d in ds:\n for i in range(22):\n # if 2**i - d in dp:\n res += dp[2**i - d]\n dp[d] += 1\n return res % (10**9 + 7)\n \n \n \n \n```
5
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Clean Code || O(N)
count-good-meals
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(22N)\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 countPairs(self, deliciousness: List[int]) -> int:\n count = {}\n res = 0\n MOD = pow(10, 9) + 7\n\n for rate in deliciousness:\n for i in range(22):\n sqr = pow(2, i)\n target = sqr - rate\n if target in count:\n res += count[target]\n if rate in count:\n count[rate] += 1\n else:\n count[rate] = 1\n \n return res % MOD\n```
2
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.