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
[Java/Python 3] 3 One liners + one w/o lib w/ analysis.
defanging-an-ip-address
1
1
```java\n public String defangIPaddr(String address) {\n return address.replace(".", "[.]");\n }\n public String defangIPaddr(String address) {\n return String.join("[.]", address.split("\\\\."));\n }\n public String defangIPaddr(String address) {\n return address.replaceAll("\\\\.", "[.]");\n }\n public String defangIPaddr(String address) {\n StringBuilder sb = new StringBuilder();\n for (char c : address.toCharArray()) {\n sb.append(c == \'.\' ? "[.]" : c);\n }\n return sb.toString();\n }\n```\n\n```python\n def defangIPaddr(self, address: str) -> str:\n return address.replace(\'.\', \'[.]\')\n def defangIPaddr(self, address: str) -> str:\n return \'[.]\'.join(address.split(\'.\'))\n def defangIPaddr(self, address: str) -> str:\n return re.sub(\'\\.\', \'[.]\', address)\n def defangIPaddr(self, address: str) -> str:\n return \'\'.join(\'[.]\' if c == \'.\' else c for c in address)\n```\n\n**Analysis:**\n\nAll characters are visited at most twice, therefore, \n\nTime & space: `O(n)`, where `n = address.length()`.
196
Given a valid (IPv4) IP `address`, return a defanged version of that IP address. A _defanged IP address_ replaces every period `". "` with `"[.] "`. **Example 1:** **Input:** address = "1.1.1.1" **Output:** "1\[.\]1\[.\]1\[.\]1" **Example 2:** **Input:** address = "255.100.50.0" **Output:** "255\[.\]100\[.\]50\[.\]0" **Constraints:** * The given `address` is a valid IPv4 address.
Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited.
Simple Python Code with if else statement
defanging-an-ip-address
0
1
# Approach\nsimple approch\n\n# Code\n```\nclass Solution:\n def defangIPaddr(self, address: str) -> str:\n s = \'\'\n for i in address:\n if i == \'.\': s+=\'[.]\'\n else: s+=i\n return s\n```
2
Given a valid (IPv4) IP `address`, return a defanged version of that IP address. A _defanged IP address_ replaces every period `". "` with `"[.] "`. **Example 1:** **Input:** address = "1.1.1.1" **Output:** "1\[.\]1\[.\]1\[.\]1" **Example 2:** **Input:** address = "255.100.50.0" **Output:** "255\[.\]100\[.\]50\[.\]0" **Constraints:** * The given `address` is a valid IPv4 address.
Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited.
using .replace
defanging-an-ip-address
0
1
\n# Code\n```\nclass Solution:\n def defangIPaddr(self, address: str) -> str:\n return address.replace(".","[.]")\n```
2
Given a valid (IPv4) IP `address`, return a defanged version of that IP address. A _defanged IP address_ replaces every period `". "` with `"[.] "`. **Example 1:** **Input:** address = "1.1.1.1" **Output:** "1\[.\]1\[.\]1\[.\]1" **Example 2:** **Input:** address = "255.100.50.0" **Output:** "255\[.\]100\[.\]50\[.\]0" **Constraints:** * The given `address` is a valid IPv4 address.
Let's find for every user separately the websites he visited. Consider all possible 3-sequences, find the number of distinct users who visited each of them. How to check if some user visited some 3-sequence ? Store for every user all the 3-sequence he visited.
Python 3 || 5 lines, prefix sum || T/M: 100% / 24%
corporate-flight-bookings
0
1
```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n arr = [0]*(n+1)\n for lv, ar, seats in bookings:\n arr[lv-1]+= seats\n arr[ar]-= seats\n\n return list(accumulate(arr[:-1]))\n```\n[https://leetcode.com/problems/corporate-flight-bookings/submissions/863934491/](http://)\n\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*).
6
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Python 3 || 5 lines, prefix sum || T/M: 100% / 24%
corporate-flight-bookings
0
1
```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n arr = [0]*(n+1)\n for lv, ar, seats in bookings:\n arr[lv-1]+= seats\n arr[ar]-= seats\n\n return list(accumulate(arr[:-1]))\n```\n[https://leetcode.com/problems/corporate-flight-bookings/submissions/863934491/](http://)\n\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*).
6
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
[Python 3] - Different Arrays data structure
corporate-flight-bookings
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 corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n diff = [0] * (n + 1)\n for f, l, s in bookings:\n diff[f - 1] += s\n diff[l] -= s\n for i in range(1, n):\n diff[i] += diff[i - 1]\n return diff[:-1]\n```
5
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
[Python 3] - Different Arrays data structure
corporate-flight-bookings
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 corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n diff = [0] * (n + 1)\n for f, l, s in bookings:\n diff[f - 1] += s\n diff[l] -= s\n for i in range(1, n):\n diff[i] += diff[i - 1]\n return diff[:-1]\n```
5
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Solution using Range Addition
corporate-flight-bookings
0
1
# Intuition\nThis is the same problem as range addition. For any booking, we essentially add a number of seats to the specified range. \n\n# Approach\nThere are `n` days in total. So we can create an array with length `n`, representing the difference array (ith entry represents the difference of ith and the (i-1)th entry of the original array). Then, for each booking, we add the `seat` to `arr[start]` and minus `seat` to `arr[end+1]`, so we are adding the number of seat to the days from `start` to `end`. \n\n# Complexity\n- Time complexity:\nFor each entry, we modify the array two times. So it\'s $$O(N)$$.\n\n- Space complexity:\nThe `arr` takes $$O(N)$$.\n\n# Code\n```\nclass Solution:\n def increment(self, arr, start, end, val):\n arr[start] += val\n if end + 1 < len(arr):\n arr[end+1] -= val\n \n\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n arr = [0 for _ in range(n)]\n for book in bookings:\n start, end ,seat = book\n self.increment(arr, start-1, end-1, seat)\n # print(arr)\n res = [0 for _ in range(n)]\n res[0] = arr[0]\n for i in range(1, n):\n res[i] = res[i-1] + arr[i]\n # print(res)\n return res\n\n\n```
2
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Solution using Range Addition
corporate-flight-bookings
0
1
# Intuition\nThis is the same problem as range addition. For any booking, we essentially add a number of seats to the specified range. \n\n# Approach\nThere are `n` days in total. So we can create an array with length `n`, representing the difference array (ith entry represents the difference of ith and the (i-1)th entry of the original array). Then, for each booking, we add the `seat` to `arr[start]` and minus `seat` to `arr[end+1]`, so we are adding the number of seat to the days from `start` to `end`. \n\n# Complexity\n- Time complexity:\nFor each entry, we modify the array two times. So it\'s $$O(N)$$.\n\n- Space complexity:\nThe `arr` takes $$O(N)$$.\n\n# Code\n```\nclass Solution:\n def increment(self, arr, start, end, val):\n arr[start] += val\n if end + 1 < len(arr):\n arr[end+1] -= val\n \n\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n arr = [0 for _ in range(n)]\n for book in bookings:\n start, end ,seat = book\n self.increment(arr, start-1, end-1, seat)\n # print(arr)\n res = [0 for _ in range(n)]\n res[0] = arr[0]\n for i in range(1, n):\n res[i] = res[i-1] + arr[i]\n # print(res)\n return res\n\n\n```
2
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Easy Python O(n) using accumulate
corporate-flight-bookings
0
1
```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n res = [0]*n\n for first, last, seat in bookings:\n res[first - 1] += seat\n if last < n:\n res[last] -= seat\n return accumulate(res)\n```
4
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Easy Python O(n) using accumulate
corporate-flight-bookings
0
1
```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n res = [0]*n\n for first, last, seat in bookings:\n res[first - 1] += seat\n if last < n:\n res[last] -= seat\n return accumulate(res)\n```
4
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Python O(n) solution | Top 98% Speed | 9 Lines of Code
corporate-flight-bookings
0
1
**Python O(n) solution | Top 98% Speed | 9 Lines of Code**\n\n"Cummulative Sum" Algorithm Optmized for Maximum speed.\n\n```\nclass Solution:\n def corpFlightBookings(self, bookings, n: int):\n ans = [0]*(n+1)\n for i,j,k in bookings:\n ans[i-1] += k\n ans[j] -= k\n ans.pop()\n prev = ans[0]\n for i in range(1,n):\n prev = ans[i] = prev + ans[i]\n return ans\n```\n\n**PS.** This standard variation seems to be 8% slower:\n```\nclass Solution:\n def corpFlightBookings(self, bookings, n: int):\n ans = [0]*(n+1)\n for i,j,k in bookings:\n ans[i-1] += k\n ans[j] -= k\n ans.pop()\n for i in range(1,n):\n ans[i] += ans[i-1]\n return ans\n```\n\n**Benchmarking Methods**\n```\nfrom time import time\nfrom random import randint\ndef genAn():\n lenA = int(2e6)\n n = int(2e6)\n kmax = int(2e6)\n A = []\n for x in range(lenA):\n i = randint(1,n)\n j = randint(i,n)\n k = randint(1,kmax)\n A.append([i,j,k])\n return A,n\nA,n = genAn()\ndef benchmark(f):\n t1 = time()\n f(A,n)\n return time() - t1\n#\nprint(\'A: \',benchmark(solutionA))\nprint(\'B: \',benchmark(solutionB))\n```
8
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Python O(n) solution | Top 98% Speed | 9 Lines of Code
corporate-flight-bookings
0
1
**Python O(n) solution | Top 98% Speed | 9 Lines of Code**\n\n"Cummulative Sum" Algorithm Optmized for Maximum speed.\n\n```\nclass Solution:\n def corpFlightBookings(self, bookings, n: int):\n ans = [0]*(n+1)\n for i,j,k in bookings:\n ans[i-1] += k\n ans[j] -= k\n ans.pop()\n prev = ans[0]\n for i in range(1,n):\n prev = ans[i] = prev + ans[i]\n return ans\n```\n\n**PS.** This standard variation seems to be 8% slower:\n```\nclass Solution:\n def corpFlightBookings(self, bookings, n: int):\n ans = [0]*(n+1)\n for i,j,k in bookings:\n ans[i-1] += k\n ans[j] -= k\n ans.pop()\n for i in range(1,n):\n ans[i] += ans[i-1]\n return ans\n```\n\n**Benchmarking Methods**\n```\nfrom time import time\nfrom random import randint\ndef genAn():\n lenA = int(2e6)\n n = int(2e6)\n kmax = int(2e6)\n A = []\n for x in range(lenA):\n i = randint(1,n)\n j = randint(i,n)\n k = randint(1,kmax)\n A.append([i,j,k])\n return A,n\nA,n = genAn()\ndef benchmark(f):\n t1 = time()\n f(A,n)\n return time() - t1\n#\nprint(\'A: \',benchmark(solutionA))\nprint(\'B: \',benchmark(solutionB))\n```
8
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
PYTHON SOL | O( M + N ) | EXPLAINED WELL | FAST | ARRAYS |
corporate-flight-bookings
0
1
# Runtime: 896 ms, faster than 94.45% of Python3 online submissions for Corporate Flight Bookings .Memory Usage: 28.6 MB, less than 13.12% of Python3 online submissions for Corporate Flight Bookings.\n\n\n\n\n# EXPLANATION\n\n```\nRemember whenever we want the total for each place and we need to fill via the\nintervals ( start,end) we must use the following technique\n\nFor every start we add the arr[start] by value\nFor every end we substract the arr[end+1] by value\n\nNext we will do prefix sum\n\nWith this let\'s say we have start,end= 2,5 and value = 10\nSo at arr[2] we add 10 and at arr[6] we substract 10\narr = [ 0 , 0 , 10 , 0 , 0 , 0 , -10]\nprefix_sum = [ 0 , 0 , 10 , 10 , 10 , 10, 0]\n\nHence the work is done and we don\'t need to run the loop for the whole interval\n```\n\n\n\n# CODE\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n ans = [0]*n\n m = len(bookings)\n for start,end,seats in bookings:\n ans[start-1]+=seats\n if end < n : ans[end] -= seats\n for i in range(1,n):\n ans[i] += ans[i-1]\n return ans\n```
1
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
PYTHON SOL | O( M + N ) | EXPLAINED WELL | FAST | ARRAYS |
corporate-flight-bookings
0
1
# Runtime: 896 ms, faster than 94.45% of Python3 online submissions for Corporate Flight Bookings .Memory Usage: 28.6 MB, less than 13.12% of Python3 online submissions for Corporate Flight Bookings.\n\n\n\n\n# EXPLANATION\n\n```\nRemember whenever we want the total for each place and we need to fill via the\nintervals ( start,end) we must use the following technique\n\nFor every start we add the arr[start] by value\nFor every end we substract the arr[end+1] by value\n\nNext we will do prefix sum\n\nWith this let\'s say we have start,end= 2,5 and value = 10\nSo at arr[2] we add 10 and at arr[6] we substract 10\narr = [ 0 , 0 , 10 , 0 , 0 , 0 , -10]\nprefix_sum = [ 0 , 0 , 10 , 10 , 10 , 10, 0]\n\nHence the work is done and we don\'t need to run the loop for the whole interval\n```\n\n\n\n# CODE\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n ans = [0]*n\n m = len(bookings)\n for start,end,seats in bookings:\n ans[start-1]+=seats\n if end < n : ans[end] -= seats\n for i in range(1,n):\n ans[i] += ans[i-1]\n return ans\n```
1
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
[Python3] Good enough
corporate-flight-bookings
0
1
``` Python3 []\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n total = [0]*n\n\n for x in bookings:\n total[x[0]-1] += x[2]\n if x[1]<n:\n total[x[1]] -= x[2]\n \n for i in range(1,n):\n total[i] += total[i-1]\n \n return total\n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
[Python3] Good enough
corporate-flight-bookings
0
1
``` Python3 []\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n total = [0]*n\n\n for x in bookings:\n total[x[0]-1] += x[2]\n if x[1]<n:\n total[x[1]] -= x[2]\n \n for i in range(1,n):\n total[i] += total[i-1]\n \n return total\n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
1109, difference
corporate-flight-bookings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the difference between adjacent elements.\n\n# Complexity\n- Time complexity: n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n # bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\n # [0, 0, 0, 0, 0]\n # [10, 0, -10, 0, 0]\n # [10, 20, -10, -20, 0]\n # [10, 45, -10, -20, 0]\n # [10, 55, 45, 25, 25]\n\n # initiate empty list diff of length n\n diff = [0] * n\n for booking in bookings:\n first_i, last_i, seats_i = booking\n diff[first_i - 1] += seats_i\n if last_i < n:\n diff[last_i] -= seats_i\n\n # res = [0] * n\n # for i in range(n):\n # if i == 0:\n # res[i] = diff[i]\n # else:\n # res[i] = res[i-1] + diff[i]\n # return res\n \n # no if\n res = [0] * (n+1)\n for i in range(n):\n res[i+1] = res[i] + diff[i]\n\n return res[1:]\n \n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
1109, difference
corporate-flight-bookings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the difference between adjacent elements.\n\n# Complexity\n- Time complexity: n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n # bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\n # [0, 0, 0, 0, 0]\n # [10, 0, -10, 0, 0]\n # [10, 20, -10, -20, 0]\n # [10, 45, -10, -20, 0]\n # [10, 55, 45, 25, 25]\n\n # initiate empty list diff of length n\n diff = [0] * n\n for booking in bookings:\n first_i, last_i, seats_i = booking\n diff[first_i - 1] += seats_i\n if last_i < n:\n diff[last_i] -= seats_i\n\n # res = [0] * n\n # for i in range(n):\n # if i == 0:\n # res[i] = diff[i]\n # else:\n # res[i] = res[i-1] + diff[i]\n # return res\n \n # no if\n res = [0] * (n+1)\n for i in range(n):\n res[i+1] = res[i] + diff[i]\n\n return res[1:]\n \n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Fast🚀 & Easy🍼 to understand
corporate-flight-bookings
0
1
### My solutions are usually POV answers, what that means is reading it as if you wrote it will make more sense and familiarity.\n###### Do upvote, If you liked it \u2B06\uFE0F\n# Intuition\nOkay, so I thought of many ways and could not understand how to solve the problem, so thought of reading the solutions and then tried to understand the solution but failed to.\n\nAfter a lot of brainstorming, this is how I understand the solution to the problem, and now that I see this solution it feels easy.\n\n# Approach\nFirst and foremost notice one thing, the question asks us to find the number of seats booked in every flight in order given all the bookings. Hmm, can I rephrase the question as follows.\n\nOLD: `Find the number of seats occupied on every flight after all the bookings are done`.\n\nNEW: `Find the number of seats to be installed in every flight assuming there are no seats in any flight initially while considering all the bookings`.\n\nNote that now we no longer keeping track of how many seats are occupied in a given flight but rather finding how many seats are needed for that flight to carry that many bookings.\n\nConfused\uD83D\uDE35 isn\'t it? Lemme rephrase the question once more in a different way, then it might make sense.\n\nOLD: `Find the number of seats occupied on every flight after all the bookings are done`.\n\nNEW: `Find the number of seats occupied in THE flight for EACH DAY considering all the bookings`.\n\nLet\'s understand what the above question means.\n\nFirstly, there is no difference between any of the `n` flights, like speed, or capacity etc., What that means is I can imagine there is only 1 flight for which there are `n` trips, where each trip(day) I am taking bookings.\n\nLet\'s combine the two rephrases, and now the question becomes `Find the number of seats that I need to install on THE flight every day so that I can serve all the bookings`\n\nHmm, what do I need to precompute to find the solution for our new question, the number of seats I need to `ADD` or `REMOVE` from the flight after every day so that for the next day I have just enough seats for the bookings.\n\nWe will maintain an array of size `n + 1`; the reason for the size is mentioned later, where every array element represents the number of seats we need to add or remove from the flight on a given day.\n\nFor every booking, I need to add `seats` number of seats to the flight a day before the flight `start - 1`, and remove `seats` number of seats from the flight on the last day when I used those seats, i.e, `last`\n\nFinally, we will have an array where every `arr[i]` represents the number of seats to be added/removed from the flight to make the flight ready for tomorrow.\n\nTo avoid ArrayIndexOutOfBounds for the flight booking that ends on day `n` we need to maintain an extra index in our array.\n\nExample: Let\'s say `n == 3`, so we might have a booking `[1,3,10]` so we say on `Day 0` we need to add 10 seats for tomorrow i.e, `Day 1`. and on `Day 3` we have finished all our flights and need to remove 10 seats, But `arr[3]` will be invalid as the index goes from `0, 1, 2`. This is why we maintain an extra index.\n\nFinally, we keep track of the number of seats IN our flight as of today for every day we have a flight (`n days`) and return that as our answer.\n\nHow do we do that?, ah if I had added 3 seats yesterday, today I\'d have 3 seats more, if I had removed 4 seats yesterday today I\'d have 4 seats less. Looks like prefixSum isn\'t it?\n\n# Complexity\n- Time complexity: `O(n + m); m === bookings.length`\n\n- Space complexity: `O(n)`\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n howManySeatsToAdd = [0] * (n + 1)\n\n for start, last, seats in bookings:\n # Adding seats to yesterday for today\n howManySeatsToAdd[start - 1] += seats\n\n # Removing seats from today for tomorrow\n howManySeatsToAdd[last] -= seats\n \n # Pythonic way of calculating prefix sum of an array\n howManySeatsToAdd = list(accumulate(howManySeatsToAdd))\n\n # Return the array except for the last day (extra index)\n # where the number of seats will be 0\n # as we have no flight for tomorrow\n return howManySeatsToAdd[:-1]\n\n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Fast🚀 & Easy🍼 to understand
corporate-flight-bookings
0
1
### My solutions are usually POV answers, what that means is reading it as if you wrote it will make more sense and familiarity.\n###### Do upvote, If you liked it \u2B06\uFE0F\n# Intuition\nOkay, so I thought of many ways and could not understand how to solve the problem, so thought of reading the solutions and then tried to understand the solution but failed to.\n\nAfter a lot of brainstorming, this is how I understand the solution to the problem, and now that I see this solution it feels easy.\n\n# Approach\nFirst and foremost notice one thing, the question asks us to find the number of seats booked in every flight in order given all the bookings. Hmm, can I rephrase the question as follows.\n\nOLD: `Find the number of seats occupied on every flight after all the bookings are done`.\n\nNEW: `Find the number of seats to be installed in every flight assuming there are no seats in any flight initially while considering all the bookings`.\n\nNote that now we no longer keeping track of how many seats are occupied in a given flight but rather finding how many seats are needed for that flight to carry that many bookings.\n\nConfused\uD83D\uDE35 isn\'t it? Lemme rephrase the question once more in a different way, then it might make sense.\n\nOLD: `Find the number of seats occupied on every flight after all the bookings are done`.\n\nNEW: `Find the number of seats occupied in THE flight for EACH DAY considering all the bookings`.\n\nLet\'s understand what the above question means.\n\nFirstly, there is no difference between any of the `n` flights, like speed, or capacity etc., What that means is I can imagine there is only 1 flight for which there are `n` trips, where each trip(day) I am taking bookings.\n\nLet\'s combine the two rephrases, and now the question becomes `Find the number of seats that I need to install on THE flight every day so that I can serve all the bookings`\n\nHmm, what do I need to precompute to find the solution for our new question, the number of seats I need to `ADD` or `REMOVE` from the flight after every day so that for the next day I have just enough seats for the bookings.\n\nWe will maintain an array of size `n + 1`; the reason for the size is mentioned later, where every array element represents the number of seats we need to add or remove from the flight on a given day.\n\nFor every booking, I need to add `seats` number of seats to the flight a day before the flight `start - 1`, and remove `seats` number of seats from the flight on the last day when I used those seats, i.e, `last`\n\nFinally, we will have an array where every `arr[i]` represents the number of seats to be added/removed from the flight to make the flight ready for tomorrow.\n\nTo avoid ArrayIndexOutOfBounds for the flight booking that ends on day `n` we need to maintain an extra index in our array.\n\nExample: Let\'s say `n == 3`, so we might have a booking `[1,3,10]` so we say on `Day 0` we need to add 10 seats for tomorrow i.e, `Day 1`. and on `Day 3` we have finished all our flights and need to remove 10 seats, But `arr[3]` will be invalid as the index goes from `0, 1, 2`. This is why we maintain an extra index.\n\nFinally, we keep track of the number of seats IN our flight as of today for every day we have a flight (`n days`) and return that as our answer.\n\nHow do we do that?, ah if I had added 3 seats yesterday, today I\'d have 3 seats more, if I had removed 4 seats yesterday today I\'d have 4 seats less. Looks like prefixSum isn\'t it?\n\n# Complexity\n- Time complexity: `O(n + m); m === bookings.length`\n\n- Space complexity: `O(n)`\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n howManySeatsToAdd = [0] * (n + 1)\n\n for start, last, seats in bookings:\n # Adding seats to yesterday for today\n howManySeatsToAdd[start - 1] += seats\n\n # Removing seats from today for tomorrow\n howManySeatsToAdd[last] -= seats\n \n # Pythonic way of calculating prefix sum of an array\n howManySeatsToAdd = list(accumulate(howManySeatsToAdd))\n\n # Return the array except for the last day (extra index)\n # where the number of seats will be 0\n # as we have no flight for tomorrow\n return howManySeatsToAdd[:-1]\n\n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Easy Python O(N)
corporate-flight-bookings
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 corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n res = [0] * (n+1) \n for first, last, seats in bookings:\n res[first-1] += seats\n res[last] -= seats\n for i in range(1,n+1):\n res[i] = res[i] + res[i-1]\n return res[:-1]\n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Easy Python O(N)
corporate-flight-bookings
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 corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n res = [0] * (n+1) \n for first, last, seats in bookings:\n res[first-1] += seats\n res[last] -= seats\n for i in range(1,n+1):\n res[i] = res[i] + res[i-1]\n return res[:-1]\n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Python Corporate Flight Bookings - beats 96%
corporate-flight-bookings
0
1
\n# Intuition\n- The code processes a list of flight booking records, each containing the starting flight, ending flight, and the number of bookings.\n- It aims to calculate the total number of bookings for each flight within the range of flights from 1 to `n`.\n\n# Approach\n- The code initializes a list `result` of size `n+1` to store the number of bookings for each flight.\n- It iterates through the list of flight booking records (`bookings`).\n- For each booking record, it adds the number of bookings to the starting flight (indexed by `booking[0]-1`) and subtracts the same number of bookings from the flight after the ending flight (indexed by `booking[1]`).\n - This operation is done to mark the range with the deltas of bookings, indicating the increase and decrease in bookings.\n- After processing all booking records, the code performs a cumulative sum processing:\n - It initializes a variable `tmp` to 0.\n - It iterates through the range of flights from 0 to `n-1` (inclusive).\n - For each flight, it adds the delta (stored in the `result` list) to `tmp`, effectively accumulating the bookings.\n - It updates the `result` list with the accumulated bookings for each flight.\n- Finally, the code returns the first `n` elements of the `result` list, which represent the total number of bookings for each flight in the range.\n\n# Complexity\n- Time Complexity: The code processes the list of bookings once and iterates through the range of flights once, resulting in a linear time complexity of O(m + n), where m is the number of booking records and n is the total number of flights.\n- Space Complexity: The code uses a list of size `n+1` to store the results, resulting in a space complexity of O(n).\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n result = [0] * (n+1)\n #mark the range with the deltas (head and tail)\n for booking in bookings:\n #start\n result[booking[0]-1] += booking[2]\n #end\n result[booking[1]] -= booking[2]\n #cumulative sum processing\n tmp = 0\n for i in range(n):\n tmp += result[i]\n result[i] = tmp\n return result[:n]\n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Python Corporate Flight Bookings - beats 96%
corporate-flight-bookings
0
1
\n# Intuition\n- The code processes a list of flight booking records, each containing the starting flight, ending flight, and the number of bookings.\n- It aims to calculate the total number of bookings for each flight within the range of flights from 1 to `n`.\n\n# Approach\n- The code initializes a list `result` of size `n+1` to store the number of bookings for each flight.\n- It iterates through the list of flight booking records (`bookings`).\n- For each booking record, it adds the number of bookings to the starting flight (indexed by `booking[0]-1`) and subtracts the same number of bookings from the flight after the ending flight (indexed by `booking[1]`).\n - This operation is done to mark the range with the deltas of bookings, indicating the increase and decrease in bookings.\n- After processing all booking records, the code performs a cumulative sum processing:\n - It initializes a variable `tmp` to 0.\n - It iterates through the range of flights from 0 to `n-1` (inclusive).\n - For each flight, it adds the delta (stored in the `result` list) to `tmp`, effectively accumulating the bookings.\n - It updates the `result` list with the accumulated bookings for each flight.\n- Finally, the code returns the first `n` elements of the `result` list, which represent the total number of bookings for each flight in the range.\n\n# Complexity\n- Time Complexity: The code processes the list of bookings once and iterates through the range of flights once, resulting in a linear time complexity of O(m + n), where m is the number of booking records and n is the total number of flights.\n- Space Complexity: The code uses a list of size `n+1` to store the results, resulting in a space complexity of O(n).\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n result = [0] * (n+1)\n #mark the range with the deltas (head and tail)\n for booking in bookings:\n #start\n result[booking[0]-1] += booking[2]\n #end\n result[booking[1]] -= booking[2]\n #cumulative sum processing\n tmp = 0\n for i in range(n):\n tmp += result[i]\n result[i] = tmp\n return result[:n]\n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Python easy cummulative sum approach O(n)
corporate-flight-bookings
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. -->\n1. Initialize an array answer of length (n + 1) to represent the number of seats reserved for each flight. We add one extra element to the array for convenience.\n\n2. Iterate through the bookings list. For each booking [first, last, seats], we increment answer[first - 1] by seats to indicate the start of seat reservations, and we decrement answer[last] by seats to indicate the end of seat reservations.\n\n3. After processing all bookings, we perform a cumulative sum on the answer array. Starting from index 1, we add the current element to the previous element. This step calculates the total seats reserved for each flight.\n\n4. Finally, we remove the extra element added at the end of the answer array, as it was only added for convenience.\n\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n answer = [0] * (n + 1)\n\n for booking in bookings:\n first, last, seats = booking\n answer[first - 1] += seats\n answer[last] -= seats\n\n for i in range(1, n):\n answer[i] += answer[i-1]\n \n answer.pop()\n\n return answer \n \n \n\n```
0
There are `n` flights that are labeled from `1` to `n`. You are given an array of flight bookings `bookings`, where `bookings[i] = [firsti, lasti, seatsi]` represents a booking for flights `firsti` through `lasti` (**inclusive**) with `seatsi` seats reserved for **each flight** in the range. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the total number of seats reserved for flight_ `i`. **Example 1:** **Input:** bookings = \[\[1,2,10\],\[2,3,20\],\[2,5,25\]\], n = 5 **Output:** \[10,55,45,25,25\] **Explanation:** Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = \[10,55,45,25,25\] **Example 2:** **Input:** bookings = \[\[1,2,10\],\[2,2,15\]\], n = 2 **Output:** \[10,25\] **Explanation:** Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = \[10,25\] **Constraints:** * `1 <= n <= 2 * 104` * `1 <= bookings.length <= 2 * 104` * `bookings[i].length == 3` * `1 <= firsti <= lasti <= n` * `1 <= seatsi <= 104`
null
Python easy cummulative sum approach O(n)
corporate-flight-bookings
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. -->\n1. Initialize an array answer of length (n + 1) to represent the number of seats reserved for each flight. We add one extra element to the array for convenience.\n\n2. Iterate through the bookings list. For each booking [first, last, seats], we increment answer[first - 1] by seats to indicate the start of seat reservations, and we decrement answer[last] by seats to indicate the end of seat reservations.\n\n3. After processing all bookings, we perform a cumulative sum on the answer array. Starting from index 1, we add the current element to the previous element. This step calculates the total seats reserved for each flight.\n\n4. Finally, we remove the extra element added at the end of the answer array, as it was only added for convenience.\n\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n answer = [0] * (n + 1)\n\n for booking in bookings:\n first, last, seats = booking\n answer[first - 1] += seats\n answer[last] -= seats\n\n for i in range(1, n):\n answer[i] += answer[i-1]\n \n answer.pop()\n\n return answer \n \n \n\n```
0
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Commented Python solution DFS (recursive)
delete-nodes-and-return-forest
0
1
# Code\n```\n\nclass Solution:\n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n # really good explanation: https://leetcode.com/problems/delete-nodes-and-return-forest/solutions/656106/python-recursive-clean-explained-in-details-with-tips-10-lines-fast/\n res = []\n\n # two types of nodes to be deleted: if root or if leaf\n def dfs(root):\n if root is None:\n return None\n \n # don\'t iterate through to_delete, iterate through tree and see if that node\n # is in to_delete and remove it. Since every node is unique this can be done.\n root.left = dfs(root.left)\n root.right = dfs(root.right)\n\n # post order: if the check below is after root.left = ... and root.right = ... calls, we make sure that the leaf\n # nodes are processed first\n\n if root.val in to_delete: # lookup is now O(1) cuz set\n # if leaf node\n if root.left is None and root.right is None:\n return None # assign root.left of calling node as None\n else:\n # non-leaf (root) node, collect subtrees that were attached to this root node\n if root.left:\n res.append(root.left)\n if root.right:\n res.append(root.right)\n return None\n \n # else the node is not be deleted, just return the node as it is to whoever called it\n return root\n \n\n to_delete = set(to_delete)\n # get the remanining tree and append it to res\n node = dfs(root)\n if node:\n res.append(node)\n return res\n
3
Given the `root` of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in `to_delete`, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\], to\_delete = \[3,5\] **Output:** \[\[1,2,null,4\],\[6\],\[7\]\] **Example 2:** **Input:** root = \[1,2,4,null,3\], to\_delete = \[3\] **Output:** \[\[1,2,4\]\] **Constraints:** * The number of nodes in the given tree is at most `1000`. * Each node has a distinct value between `1` and `1000`. * `to_delete.length <= 1000` * `to_delete` contains distinct values between `1` and `1000`.
null
Commented Python solution DFS (recursive)
delete-nodes-and-return-forest
0
1
# Code\n```\n\nclass Solution:\n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n # really good explanation: https://leetcode.com/problems/delete-nodes-and-return-forest/solutions/656106/python-recursive-clean-explained-in-details-with-tips-10-lines-fast/\n res = []\n\n # two types of nodes to be deleted: if root or if leaf\n def dfs(root):\n if root is None:\n return None\n \n # don\'t iterate through to_delete, iterate through tree and see if that node\n # is in to_delete and remove it. Since every node is unique this can be done.\n root.left = dfs(root.left)\n root.right = dfs(root.right)\n\n # post order: if the check below is after root.left = ... and root.right = ... calls, we make sure that the leaf\n # nodes are processed first\n\n if root.val in to_delete: # lookup is now O(1) cuz set\n # if leaf node\n if root.left is None and root.right is None:\n return None # assign root.left of calling node as None\n else:\n # non-leaf (root) node, collect subtrees that were attached to this root node\n if root.left:\n res.append(root.left)\n if root.right:\n res.append(root.right)\n return None\n \n # else the node is not be deleted, just return the node as it is to whoever called it\n return root\n \n\n to_delete = set(to_delete)\n # get the remanining tree and append it to res\n node = dfs(root)\n if node:\n res.append(node)\n return res\n
3
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
[Python] BFS Solution
delete-nodes-and-return-forest
0
1
```class Solution:\n def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n queue = collections.deque([(root, False)])\n res = []\n deleteSet = set(to_delete)\n \n while queue:\n node, hasParent = queue.popleft()\n # new Root found\n if not hasParent and node.val not in to_delete:\n res.append(node)\n \n hasParent = not node.val in to_delete\n\n if node.left: \n queue.append((node.left, hasParent))\n if node.left.val in to_delete:\n node.left = None\n if node.right:\n queue.append((node.right, hasParent))\n if node.right.val in to_delete:\n node.right = None\n \n return res
61
Given the `root` of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in `to_delete`, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\], to\_delete = \[3,5\] **Output:** \[\[1,2,null,4\],\[6\],\[7\]\] **Example 2:** **Input:** root = \[1,2,4,null,3\], to\_delete = \[3\] **Output:** \[\[1,2,4\]\] **Constraints:** * The number of nodes in the given tree is at most `1000`. * Each node has a distinct value between `1` and `1000`. * `to_delete.length <= 1000` * `to_delete` contains distinct values between `1` and `1000`.
null
[Python] BFS Solution
delete-nodes-and-return-forest
0
1
```class Solution:\n def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n queue = collections.deque([(root, False)])\n res = []\n deleteSet = set(to_delete)\n \n while queue:\n node, hasParent = queue.popleft()\n # new Root found\n if not hasParent and node.val not in to_delete:\n res.append(node)\n \n hasParent = not node.val in to_delete\n\n if node.left: \n queue.append((node.left, hasParent))\n if node.left.val in to_delete:\n node.left = None\n if node.right:\n queue.append((node.right, hasParent))\n if node.right.val in to_delete:\n node.right = None\n \n return res
61
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
Simple logic || Two cases, check every node || 99%
delete-nodes-and-return-forest
1
1
# Intuition\n\nSuppose the current node, say $$node$$, you\'re checking is not present in the $$to$$_$$delete$$ array. You leave $$node$$ untouched and check it\'s $$left$$ and $$right$$ children.\n\nIf $$node$$ is present in $$to$$_$$delete$$ array, we need to tell it\'s parent to not point to this node. We also need to check $$node\'s$$ $$left$$ and $$right$$ children and add the ones not present in the delete array to our $$answer$$ list.\n\n# Approach\nFor the case when $$node$$ is not present in $$to$$_$$delete$$ array:\n- return ```false```, signalling $$node\'s$$ parent to keep pointing to it\n- Check whether $$left$$ and $$right$$ children of $$node$$ are to be deleted or not\n\nFor the case when $$node$$ is present in $$to$$_$$delete$$ array:\n- return ```true```, signalling the parent to delete $$node$$.\n- Add $$node\'s$$ left and right children to the list, if they themselves don\'t have to be deleted.\n\nApply the above logic to the root node. If root is present in the $$to$$_$$delete$$ array, you do not include it in the $$answer$$ list, otherwise you add it. \nSame logic is repeated for every node. \n\n# Complexity\n- Time complexity:\n $$O(n)$$\nwhere $$n$$ is the number of nodes in the tree. \n\n- Space complexity:\n$$O(h + n)$$\nwhere $$h$$ is the height of the tree,$$n$$ is the number of nodes in the tree. \n\n# Code\n```Java []\nclass Solution {\n public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {\n HashSet<Integer> set = new HashSet<>(); \n for (int val : to_delete) {\n set.add(val);\n }\n List<TreeNode> ans = new ArrayList<>();\n if (delete(root, ans, set)) {\n // root was deleted\n } else {\n ans.add(root);\n }\n return ans; \n }\n \n // Returns true if the node was deleted\n public boolean delete(TreeNode node, List<TreeNode> list, HashSet<Integer> set) {\n if (node == null) {\n return true;\n }\n if (set.contains(node.val)) {\n // Node to be deleted\n if (!delete(node.left, list, set)) {\n list.add(node.left);\n }\n if (!delete(node.right, list, set)) {\n list.add(node.right);\n }\n return true;\n } else {\n if (delete(node.left, list, set)) {\n node.left = null;\n }\n if (delete(node.right, list, set)) {\n node.right = null;\n }\n return false;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n unordered_set<int> delete_set(to_delete.begin(), to_delete.end());\n vector<TreeNode*> ans;\n deleteNodes(root, true, delete_set, ans);\n return ans;\n }\n \nprivate:\n void deleteNodes(TreeNode* node, bool is_root, unordered_set<int>& delete_set, vector<TreeNode*>& ans) {\n if (!node) {\n return;\n }\n \n bool is_deleted = delete_set.find(node->val) != delete_set.end();\n if (is_root && !is_deleted) {\n ans.push_back(node);\n }\n \n deleteNodes(node->left, is_deleted, delete_set, ans);\n deleteNodes(node->right, is_deleted, delete_set, ans);\n \n if (is_deleted) {\n if (node->left) {\n ans.push_back(node->left);\n }\n if (node->right) {\n ans.push_back(node->right);\n }\n } else {\n node->left = (node->left && delete_set.find(node->left->val) != delete_set.end()) ? NULL : node->left;\n node->right = (node->right && delete_set.find(node->right->val) != delete_set.end()) ? NULL : node->right;\n }\n }\n};\n\n```\n```python3 []\nclass Solution:\n def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n def delete(node):\n if not node:\n return False\n left_deleted = delete(node.left)\n right_deleted = delete(node.right)\n if node.val in to_delete:\n if not left_deleted and node.left:\n ans.append(node.left)\n if not right_deleted and node.right:\n ans.append(node.right)\n return True\n if left_deleted:\n node.left = None\n if right_deleted:\n node.right = None\n return False\n \n to_delete = set(to_delete)\n ans = []\n if not delete(root):\n ans.append(root)\n return ans\n\n```\n
3
Given the `root` of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in `to_delete`, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\], to\_delete = \[3,5\] **Output:** \[\[1,2,null,4\],\[6\],\[7\]\] **Example 2:** **Input:** root = \[1,2,4,null,3\], to\_delete = \[3\] **Output:** \[\[1,2,4\]\] **Constraints:** * The number of nodes in the given tree is at most `1000`. * Each node has a distinct value between `1` and `1000`. * `to_delete.length <= 1000` * `to_delete` contains distinct values between `1` and `1000`.
null
Simple logic || Two cases, check every node || 99%
delete-nodes-and-return-forest
1
1
# Intuition\n\nSuppose the current node, say $$node$$, you\'re checking is not present in the $$to$$_$$delete$$ array. You leave $$node$$ untouched and check it\'s $$left$$ and $$right$$ children.\n\nIf $$node$$ is present in $$to$$_$$delete$$ array, we need to tell it\'s parent to not point to this node. We also need to check $$node\'s$$ $$left$$ and $$right$$ children and add the ones not present in the delete array to our $$answer$$ list.\n\n# Approach\nFor the case when $$node$$ is not present in $$to$$_$$delete$$ array:\n- return ```false```, signalling $$node\'s$$ parent to keep pointing to it\n- Check whether $$left$$ and $$right$$ children of $$node$$ are to be deleted or not\n\nFor the case when $$node$$ is present in $$to$$_$$delete$$ array:\n- return ```true```, signalling the parent to delete $$node$$.\n- Add $$node\'s$$ left and right children to the list, if they themselves don\'t have to be deleted.\n\nApply the above logic to the root node. If root is present in the $$to$$_$$delete$$ array, you do not include it in the $$answer$$ list, otherwise you add it. \nSame logic is repeated for every node. \n\n# Complexity\n- Time complexity:\n $$O(n)$$\nwhere $$n$$ is the number of nodes in the tree. \n\n- Space complexity:\n$$O(h + n)$$\nwhere $$h$$ is the height of the tree,$$n$$ is the number of nodes in the tree. \n\n# Code\n```Java []\nclass Solution {\n public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {\n HashSet<Integer> set = new HashSet<>(); \n for (int val : to_delete) {\n set.add(val);\n }\n List<TreeNode> ans = new ArrayList<>();\n if (delete(root, ans, set)) {\n // root was deleted\n } else {\n ans.add(root);\n }\n return ans; \n }\n \n // Returns true if the node was deleted\n public boolean delete(TreeNode node, List<TreeNode> list, HashSet<Integer> set) {\n if (node == null) {\n return true;\n }\n if (set.contains(node.val)) {\n // Node to be deleted\n if (!delete(node.left, list, set)) {\n list.add(node.left);\n }\n if (!delete(node.right, list, set)) {\n list.add(node.right);\n }\n return true;\n } else {\n if (delete(node.left, list, set)) {\n node.left = null;\n }\n if (delete(node.right, list, set)) {\n node.right = null;\n }\n return false;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n unordered_set<int> delete_set(to_delete.begin(), to_delete.end());\n vector<TreeNode*> ans;\n deleteNodes(root, true, delete_set, ans);\n return ans;\n }\n \nprivate:\n void deleteNodes(TreeNode* node, bool is_root, unordered_set<int>& delete_set, vector<TreeNode*>& ans) {\n if (!node) {\n return;\n }\n \n bool is_deleted = delete_set.find(node->val) != delete_set.end();\n if (is_root && !is_deleted) {\n ans.push_back(node);\n }\n \n deleteNodes(node->left, is_deleted, delete_set, ans);\n deleteNodes(node->right, is_deleted, delete_set, ans);\n \n if (is_deleted) {\n if (node->left) {\n ans.push_back(node->left);\n }\n if (node->right) {\n ans.push_back(node->right);\n }\n } else {\n node->left = (node->left && delete_set.find(node->left->val) != delete_set.end()) ? NULL : node->left;\n node->right = (node->right && delete_set.find(node->right->val) != delete_set.end()) ? NULL : node->right;\n }\n }\n};\n\n```\n```python3 []\nclass Solution:\n def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n def delete(node):\n if not node:\n return False\n left_deleted = delete(node.left)\n right_deleted = delete(node.right)\n if node.val in to_delete:\n if not left_deleted and node.left:\n ans.append(node.left)\n if not right_deleted and node.right:\n ans.append(node.right)\n return True\n if left_deleted:\n node.left = None\n if right_deleted:\n node.right = None\n return False\n \n to_delete = set(to_delete)\n ans = []\n if not delete(root):\n ans.append(root)\n return ans\n\n```\n
3
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
Python || 98.06% Faster || Greedy Approach || O(N) Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans=[]\n prev=1\n for i in seq:\n if i==\'(\':\n if prev==0:\n ans.append(1)\n else:\n ans.append(0)\n else:\n ans.append(prev)\n if prev==0:\n prev=1\n else:\n prev=0\n return ans\n```\n\n**Upvote if you like the solution or ask if there is any query**
2
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python || 98.06% Faster || Greedy Approach || O(N) Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans=[]\n prev=1\n for i in seq:\n if i==\'(\':\n if prev==0:\n ans.append(1)\n else:\n ans.append(0)\n else:\n ans.append(prev)\n if prev==0:\n prev=1\n else:\n prev=0\n return ans\n```\n\n**Upvote if you like the solution or ask if there is any query**
2
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python || Easy || Explained || O(n) Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n m,c,n=0,0,len(seq)\n for i in range(n):\n if seq[i]==\'(\':\n c+=1\n m=max(c,m) # Here m is the maximium depth of the VPS\n elif seq[i]==\')\': \n c-=1\n a=[]\n m//=2 # Minimum depth possible by breaking string in two parts A and B\n for i in range(n):\n if seq[i]==\'(\':\n c+=1\n if c<=m:\n a.append(0) #For A\n else:\n a.append(1) #For B\n else:\n if c<=m:\n a.append(0)\n else:\n a.append(1)\n c-=1\n return a\n```\n\n**Upvote if you like the soluiton or ask if there is any query**
1
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python || Easy || Explained || O(n) Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n m,c,n=0,0,len(seq)\n for i in range(n):\n if seq[i]==\'(\':\n c+=1\n m=max(c,m) # Here m is the maximium depth of the VPS\n elif seq[i]==\')\': \n c-=1\n a=[]\n m//=2 # Minimum depth possible by breaking string in two parts A and B\n for i in range(n):\n if seq[i]==\'(\':\n c+=1\n if c<=m:\n a.append(0) #For A\n else:\n a.append(1) #For B\n else:\n if c<=m:\n a.append(0)\n else:\n a.append(1)\n c-=1\n return a\n```\n\n**Upvote if you like the soluiton or ask if there is any query**
1
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python | 90% Faster | Clear Explanation
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
![image.png](https://assets.leetcode.com/users/images/e118239d-09dd-49b8-b343-918fd195d191_1689183834.8018787.png)\n\n\nI was very confused by this problem, but after looking at some of the testcases, what we have to return is if the depth is odd, we have to return 0, and if it is even, we have to return 1, or I think we can do vice versa. Below is clear and simple code for checking the depth and returning the result respectively.\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n stack=[]\n oc=0\n res=[]\n for i in seq:\n if i=="(":\n if oc%2!=0:\n res.append(0)\n else:\n res.append(1)\n oc+=1\n else:\n oc-=1\n if oc%2!=0:\n res.append(0)\n else:\n res.append(1)\n return res\n```
1
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python | 90% Faster | Clear Explanation
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
![image.png](https://assets.leetcode.com/users/images/e118239d-09dd-49b8-b343-918fd195d191_1689183834.8018787.png)\n\n\nI was very confused by this problem, but after looking at some of the testcases, what we have to return is if the depth is odd, we have to return 0, and if it is even, we have to return 1, or I think we can do vice versa. Below is clear and simple code for checking the depth and returning the result respectively.\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n stack=[]\n oc=0\n res=[]\n for i in seq:\n if i=="(":\n if oc%2!=0:\n res.append(0)\n else:\n res.append(1)\n oc+=1\n else:\n oc-=1\n if oc%2!=0:\n res.append(0)\n else:\n res.append(1)\n return res\n```
1
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python - O(n)
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAssign ( alternatively to A and B. Assign ) to whatever the last ( was assigned to.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n res = []\n prev = 1\n\n for c in seq:\n if c == "(":\n res.append(1-prev)\n else:\n res.append(prev)\n prev = 1-prev\n\n return res\n \n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python - O(n)
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAssign ( alternatively to A and B. Assign ) to whatever the last ( was assigned to.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n res = []\n prev = 1\n\n for c in seq:\n if c == "(":\n res.append(1-prev)\n else:\n res.append(prev)\n prev = 1-prev\n\n return res\n \n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Beat 100% Python Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo minimize the max of two split parenthesis, we need to make two parts\' depth as same as possible (ideally even split). Thus, we could first calculate the depth of each parenthesis. \n\nExample: depths of \'(())()\' will be [1, 2, 2, 1, 1, 1].\n\nWe want to make a "horizontal cut" such that the upper and lower parts\' depths are as similar as possible. In this case, we will cut between 1 and 2, making the lower part [1, 1, 1, 1, 1, 1], and the upper part be [0, 1, 1, 0, 0, 0]. Now, the max of both parts is 1, which is the solution. \n\nThe depth of the cut should be max(depth) // 2. \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n left = 0\n n = len(seq)\n depth = [0] * n\n\n for i, c in enumerate(seq):\n if c == \'(\':\n left += 1\n depth[i] = left\n if c == \')\':\n left -= 1\n \n div = max(depth) // 2\n return [0 if depth[i] <= div else 1 for i in range(n)]\n \n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Beat 100% Python Solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo minimize the max of two split parenthesis, we need to make two parts\' depth as same as possible (ideally even split). Thus, we could first calculate the depth of each parenthesis. \n\nExample: depths of \'(())()\' will be [1, 2, 2, 1, 1, 1].\n\nWe want to make a "horizontal cut" such that the upper and lower parts\' depths are as similar as possible. In this case, we will cut between 1 and 2, making the lower part [1, 1, 1, 1, 1, 1], and the upper part be [0, 1, 1, 0, 0, 0]. Now, the max of both parts is 1, which is the solution. \n\nThe depth of the cut should be max(depth) // 2. \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n left = 0\n n = len(seq)\n depth = [0] * n\n\n for i, c in enumerate(seq):\n if c == \'(\':\n left += 1\n depth[i] = left\n if c == \')\':\n left -= 1\n \n div = max(depth) // 2\n return [0 if depth[i] <= div else 1 for i in range(n)]\n \n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python Solution - Maximum Nesting Depth of Two Valid Parentheses Strings
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
\n\n# Intuition\n- The code aims to split the given valid parentheses sequence into two disjoint subsequences while maximizing the depth of each subsequence.\n- It assigns parentheses to either of the two subsequences in such a way that the depth of both subsequences is as balanced as possible.\n\n# Approach\n- The code initializes an empty list `ans` to store the result.\n- It also initializes a variable `prev` to 1, which represents the "current" group. In this context, 1 represents Group A, and 0 represents Group B.\n- The code then iterates through each character `i` in the input `seq`.\n- If the character is an opening parenthesis `\'(\'`, it checks the value of `prev`:\n - If `prev` is 0 (indicating that the previous character was also `\'(\'`), it appends 1 to the `ans` list, indicating that the current `\'(\'` should be assigned to Group A.\n - Otherwise, it appends 0 to the `ans` list, indicating that the current `\'(\'` should be assigned to Group B.\n- If the character is a closing parenthesis `\')\'`, it appends the value of `prev` to the `ans` list, indicating that the current `\')\'` should belong to the same group as the previous character.\n- After processing each character, the code updates the value of `prev` by toggling it. If `prev` was 0, it becomes 1, and vice versa.\n- Finally, the code returns the `ans` list, which represents the maximum depth after splitting the input sequence into two disjoint subsequences.\n\n# Complexity\n- Time Complexity: The code processes each character in the input string once, resulting in a linear time complexity of O(n), where n is the length of the input `seq`.\n- Space Complexity: The code uses additional space to store the `ans` list, which has the same length as the input string, resulting in a space complexity of O(n).\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans=[]\n prev=1\n for i in seq:\n if i==\'(\':\n if prev==0:\n ans.append(1)\n else:\n ans.append(0)\n else:\n ans.append(prev)\n if prev==0:\n prev=1\n else:\n prev=0\n return ans\n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python Solution - Maximum Nesting Depth of Two Valid Parentheses Strings
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
\n\n# Intuition\n- The code aims to split the given valid parentheses sequence into two disjoint subsequences while maximizing the depth of each subsequence.\n- It assigns parentheses to either of the two subsequences in such a way that the depth of both subsequences is as balanced as possible.\n\n# Approach\n- The code initializes an empty list `ans` to store the result.\n- It also initializes a variable `prev` to 1, which represents the "current" group. In this context, 1 represents Group A, and 0 represents Group B.\n- The code then iterates through each character `i` in the input `seq`.\n- If the character is an opening parenthesis `\'(\'`, it checks the value of `prev`:\n - If `prev` is 0 (indicating that the previous character was also `\'(\'`), it appends 1 to the `ans` list, indicating that the current `\'(\'` should be assigned to Group A.\n - Otherwise, it appends 0 to the `ans` list, indicating that the current `\'(\'` should be assigned to Group B.\n- If the character is a closing parenthesis `\')\'`, it appends the value of `prev` to the `ans` list, indicating that the current `\')\'` should belong to the same group as the previous character.\n- After processing each character, the code updates the value of `prev` by toggling it. If `prev` was 0, it becomes 1, and vice versa.\n- Finally, the code returns the `ans` list, which represents the maximum depth after splitting the input sequence into two disjoint subsequences.\n\n# Complexity\n- Time Complexity: The code processes each character in the input string once, resulting in a linear time complexity of O(n), where n is the length of the input `seq`.\n- Space Complexity: The code uses additional space to store the `ans` list, which has the same length as the input string, resulting in a space complexity of O(n).\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans=[]\n prev=1\n for i in seq:\n if i==\'(\':\n if prev==0:\n ans.append(1)\n else:\n ans.append(0)\n else:\n ans.append(prev)\n if prev==0:\n prev=1\n else:\n prev=0\n return ans\n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Simple Alternating class solution Python3
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n We assign each VPS to either A or B via a class parameter. The intuition is nuanced but to find the disjoint subsequence of VPS with minimum depth for max(depth(A), depth(B)), then essentially all we need to do is find minimum depth for split for the sequence. We need split the nested VPS\'s with max depth. The trick is to see the following: 1) if we have ((())) and we need to split it so as to have minimum depth as outlined in problem, then we can assing the outer bracket (first nested bracket) to class 0, the second nested bracket to class 1 and the third bracket (that is not nested) again to class 0. The maximum depth would be 2 and this would be the minimal depth given the problem constraint. To this end, a simple solution is as follows:\n1) Whenever we encounter a nested bracket we alternate our class, if previosely 0, then for next layer of the nested bracket it is turned to zero.\n2) for "summed" VPS\'s we do not change the class, that is if we have the following situation: ()(), as the depth does not change. \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 maxDepthAfterSplit(self, seq: str) -> List[int]:\n\n\n stack_ = []\n N_stack = 0 \n arr_ = []\n class_ = 0\n\n for seq_ in seq:\n if seq_==")":\n class_ = 1 - class_\n stack_ =stack_[1:]\n N_stack-=1\n arr_ +=[class_]\n else:\n arr_+=[class_]\n stack_ +=["("]\n class_ = 1 - class_\n N_stack +=1\n \n\n return(arr_) \n \n \n\n \n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Simple Alternating class solution Python3
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n We assign each VPS to either A or B via a class parameter. The intuition is nuanced but to find the disjoint subsequence of VPS with minimum depth for max(depth(A), depth(B)), then essentially all we need to do is find minimum depth for split for the sequence. We need split the nested VPS\'s with max depth. The trick is to see the following: 1) if we have ((())) and we need to split it so as to have minimum depth as outlined in problem, then we can assing the outer bracket (first nested bracket) to class 0, the second nested bracket to class 1 and the third bracket (that is not nested) again to class 0. The maximum depth would be 2 and this would be the minimal depth given the problem constraint. To this end, a simple solution is as follows:\n1) Whenever we encounter a nested bracket we alternate our class, if previosely 0, then for next layer of the nested bracket it is turned to zero.\n2) for "summed" VPS\'s we do not change the class, that is if we have the following situation: ()(), as the depth does not change. \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 maxDepthAfterSplit(self, seq: str) -> List[int]:\n\n\n stack_ = []\n N_stack = 0 \n arr_ = []\n class_ = 0\n\n for seq_ in seq:\n if seq_==")":\n class_ = 1 - class_\n stack_ =stack_[1:]\n N_stack-=1\n arr_ +=[class_]\n else:\n arr_+=[class_]\n stack_ +=["("]\n class_ = 1 - class_\n N_stack +=1\n \n\n return(arr_) \n \n \n\n \n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Run time O(n).
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nfrom collections import deque\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n st = deque()\n out = []\n\n for i in range(len(seq)):\n if not len(st) and seq[i] == "(" :\n depth = 1\n st.append((seq[i],depth))\n out.append(0)\n elif len(st) and seq[i] == "(" :\n depth = 1+st[-1][1]\n st.append((seq[i],depth))\n if depth%2 == 0 :\n out.append(1)\n else : \n out.append(0)\n elif len(st) and seq[i] == ")" :\n depth = st[-1][1]\n if depth%2 == 0 :\n out.append(1)\n else : \n out.append(0)\n st.pop()\n return out \n \n \n\n \n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Run time O(n).
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nfrom collections import deque\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n st = deque()\n out = []\n\n for i in range(len(seq)):\n if not len(st) and seq[i] == "(" :\n depth = 1\n st.append((seq[i],depth))\n out.append(0)\n elif len(st) and seq[i] == "(" :\n depth = 1+st[-1][1]\n st.append((seq[i],depth))\n if depth%2 == 0 :\n out.append(1)\n else : \n out.append(0)\n elif len(st) and seq[i] == ")" :\n depth = st[-1][1]\n if depth%2 == 0 :\n out.append(1)\n else : \n out.append(0)\n st.pop()\n return out \n \n \n\n \n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python greedy solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\nFirst we store the current depth of `A` and `B` in `level_A` and `level_B` respectively.\n\nThe current depth is defined to be the number of unclosed brackets in the string. For example\n```\nA = ()()() ; depth = 0\nA = ( ; depth = 1\nA = (( ; depth = 2\nA = (() ; depth = 1\n```\n- When encounters a `(`, we greedily choose to append it to `A` or `B` based on the lower depth.\n- When encounters a `)`, we greedily choose to append it to `A` or `B` based on the highest depth.\n\n# Example\nRun through the example on the string`()(())()`:\n\n1. Initialize `A = "", B = ""`, encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "("`\n2. Encounters `)`: \n insert into either A or B since `level_A = level_B`, we choose `A = "()"`\n3. Encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()("`\n4. Encounters `(`:\n insert into `B = "("` since `level_B` is smaller.\n5. Encounters `)`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()()"`\n6. Encounters `)`:\n insert into `B = "()"` since `level_B` is greater.\n7. Encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()()("` \n8. Encounters `)`:\n insert into `A = "()()()"` since `level_A` is greater.\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n result = []\n level_A = 0\n level_B = 0\n for i, c in enumerate(seq):\n if c == \'(\':\n if level_A < level_B:\n result.append(0)\n level_A += 1\n else:\n result.append(1)\n level_B += 1\n else:\n if level_A > level_B:\n result.append(0)\n level_A -= 1\n else:\n result.append(1)\n level_B -= 1\n\n return result\n```
0
A string is a _valid parentheses string_ (denoted VPS) if and only if it consists of `"( "` and `") "` characters only, and: * It is the empty string, or * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are VPS's, or * It can be written as `(A)`, where `A` is a VPS. We can similarly define the _nesting depth_ `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are VPS's * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a VPS. For example, `" "`, `"()() "`, and `"()(()()) "` are VPS's (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not VPS's. Given a VPS seq, split it into two disjoint subsequences `A` and `B`, such that `A` and `B` are VPS's (and `A.length + B.length = seq.length`). Now choose **any** such `A` and `B` such that `max(depth(A), depth(B))` is the minimum possible value. Return an `answer` array (of length `seq.length`) that encodes such a choice of `A` and `B`: `answer[i] = 0` if `seq[i]` is part of `A`, else `answer[i] = 1`. Note that even though multiple answers may exist, you may return any of them. **Example 1:** **Input:** seq = "(()()) " **Output:** \[0,1,1,1,1,0\] **Example 2:** **Input:** seq = "()(())() " **Output:** \[0,0,0,1,1,0,1,1\] **Constraints:** * `1 <= seq.size <= 10000`
Without loss of generality, there is a triangle that uses adjacent vertices A[0] and A[N-1] (where N = A.length). Depending on your choice K of it, this breaks down the triangulation into two subproblems A[1:K] and A[K+1:N-1].
Python greedy solution
maximum-nesting-depth-of-two-valid-parentheses-strings
0
1
# Intuition\nFirst we store the current depth of `A` and `B` in `level_A` and `level_B` respectively.\n\nThe current depth is defined to be the number of unclosed brackets in the string. For example\n```\nA = ()()() ; depth = 0\nA = ( ; depth = 1\nA = (( ; depth = 2\nA = (() ; depth = 1\n```\n- When encounters a `(`, we greedily choose to append it to `A` or `B` based on the lower depth.\n- When encounters a `)`, we greedily choose to append it to `A` or `B` based on the highest depth.\n\n# Example\nRun through the example on the string`()(())()`:\n\n1. Initialize `A = "", B = ""`, encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "("`\n2. Encounters `)`: \n insert into either A or B since `level_A = level_B`, we choose `A = "()"`\n3. Encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()("`\n4. Encounters `(`:\n insert into `B = "("` since `level_B` is smaller.\n5. Encounters `)`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()()"`\n6. Encounters `)`:\n insert into `B = "()"` since `level_B` is greater.\n7. Encounters `(`:\n insert into either A or B since `level_A = level_B`, we choose `A = "()()("` \n8. Encounters `)`:\n insert into `A = "()()()"` since `level_A` is greater.\n\n# Code\n```\nclass Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n result = []\n level_A = 0\n level_B = 0\n for i, c in enumerate(seq):\n if c == \'(\':\n if level_A < level_B:\n result.append(0)\n level_A += 1\n else:\n result.append(1)\n level_B += 1\n else:\n if level_A > level_B:\n result.append(0)\n level_A -= 1\n else:\n result.append(1)\n level_B -= 1\n\n return result\n```
0
You are given two strings `s` and `t` of the same length and an integer `maxCost`. You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters). Return _the maximum length of a substring of_ `s` _that can be changed to be the same as the corresponding substring of_ `t` _with a cost less than or equal to_ `maxCost`. If there is no substring from `s` that can be changed to its corresponding substring from `t`, return `0`. **Example 1:** **Input:** s = "abcd ", t = "bcdf ", maxCost = 3 **Output:** 3 **Explanation:** "abc " of s can change to "bcd ". That costs 3, so the maximum length is 3. **Example 2:** **Input:** s = "abcd ", t = "cdef ", maxCost = 3 **Output:** 1 **Explanation:** Each character in s costs 2 to change to character in t, so the maximum length is 1. **Example 3:** **Input:** s = "abcd ", t = "acde ", maxCost = 0 **Output:** 1 **Explanation:** You cannot make any change, so the maximum length is 1. **Constraints:** * `1 <= s.length <= 105` * `t.length == s.length` * `0 <= maxCost <= 106` * `s` and `t` consist of only lowercase English letters.
null
Python3 Solution using 5 primitives (lock, semaphore, condition, event, barrier)
print-in-order
0
1
# Approach \\#1. Lock\n- `RLock` is not suitable in this case. \n\n<iframe src="https://leetcode.com/playground/mgRcT2DB/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#2. Semaphore\n- `Semaphore(1)` is equivalent to `Lock()`\n<iframe src="https://leetcode.com/playground/c4bkiTBr/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#3. Condition\n<iframe src="https://leetcode.com/playground/Z2up2An3/shared" frameBorder="0" width="600" height="500"></iframe>\n\n# Approach \\#4. Event \n<iframe src="https://leetcode.com/playground/hTnE2h6z/shared" frameBorder="0" width="600" height="400"></iframe>\n\n# Approach \\#5. Barrier\n<iframe src="https://leetcode.com/playground/RxQpksKT/shared" frameBorder="0" width="600" height="400"></iframe>\n
12
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: * The items that belong to the same group are next to each other in the sorted list. * There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item). Return any solution if there is more than one solution and return an **empty list** if there is no solution. **Example 1:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\] **Output:** \[6,3,4,1,5,2,0,7\] **Example 2:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\] **Output:** \[\] **Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list. **Constraints:** * `1 <= m <= n <= 3 * 104` * `group.length == beforeItems.length == n` * `-1 <= group[i] <= m - 1` * `0 <= beforeItems[i].length <= n - 1` * `0 <= beforeItems[i][j] <= n - 1` * `i != beforeItems[i][j]` * `beforeItems[i]` does not contain duplicates elements.
null
Python 3 | 56ms | Lock vs Event
print-in-order
0
1
The fastest solution for the problem is to use Lock mechanism. See the following code with comments:\n```python3\nimport threading\n\nclass Foo:\n def __init__(self):\n\t\t# create lock to control sequence between first and second functions\n self.lock1 = threading.Lock()\n\t\tself.lock1.acquire()\n\t\t\n\t\t# create another lock to control sequence between second and third functions\n self.lock2 = threading.Lock()\n self.lock2.acquire()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n\t\t\n\t\t# since second function is waiting for the lock1, let\'s release it\n self.lock1.release()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n\t\t# wait for first funtion to finish\n self.lock1.acquire()\n \n\t\tprintSecond()\n\t\t\n\t\t# let\'s release lock2, so third function can run\n self.lock2.release()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n\t\t# wait for second funtion to finish\n self.lock2.acquire()\n\t\t\n printThird()\n```\nNow, when I was solving the problem the result was showing only 76 ms, which is far from the fastest. If you encounter similar issue take into account that you are working with threading and the timing is very unpredictable when CPU decides to switch threads. This can cause different timing results.\n\nAs an alternative you can use other synchronization mechanisms, such as Semaphore or Event. If you peek into CPython code you will see both Event and Semaphore are using Lock inside. That means that technically Lock solution is the fastest.\n\nBut for the reference here is solution with Event synchronization. In my opinion it looks little better:\n\n```python3\nimport threading\n\nclass Foo:\n def __init__(self):\n self.event1 = threading.Event()\n self.event2 = threading.Event()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n self.event1.set()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.event1.wait()\n printSecond()\n self.event2.set()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.event2.wait()\n printThird()\n```
34
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: * The items that belong to the same group are next to each other in the sorted list. * There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item). Return any solution if there is more than one solution and return an **empty list** if there is no solution. **Example 1:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\] **Output:** \[6,3,4,1,5,2,0,7\] **Example 2:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\] **Output:** \[\] **Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list. **Constraints:** * `1 <= m <= n <= 3 * 104` * `group.length == beforeItems.length == n` * `-1 <= group[i] <= m - 1` * `0 <= beforeItems[i].length <= n - 1` * `0 <= beforeItems[i][j] <= n - 1` * `i != beforeItems[i][j]` * `beforeItems[i]` does not contain duplicates elements.
null
2-Lines Python Solution || 75% Faster || Memory less than 95%
print-in-order
0
1
```\nclass Foo:\n is_first_executed=False\n is_second_executed=False\n def __init__(self):\n pass\n\n def first(self, printFirst):\n printFirst()\n self.is_first_executed=True\n\n def second(self, printSecond):\n while not self.is_first_executed: continue \n printSecond()\n self.is_second_executed=True\n \n def third(self, printThird):\n while not self.is_second_executed: continue\n printThird()\n```\n\n-----------------\n### ***Another Solution***\n```\nfrom threading import Event\nclass Foo:\n def __init__(self):\n self.event1=Event()\n self.event2=Event()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n self.event1.set()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.event1.wait()\n printSecond()\n self.event2.set()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.event2.wait()\n printThird()\n```\n-------------------\n***----- Taha Choura -----***\n*[email protected]*
3
There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: * The items that belong to the same group are next to each other in the sorted list. * There are some relations between these items where `beforeItems[i]` is a list containing all the items that should come before the `i`\-th item in the sorted array (to the left of the `i`\-th item). Return any solution if there is more than one solution and return an **empty list** if there is no solution. **Example 1:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3,6\],\[\],\[\],\[\]\] **Output:** \[6,3,4,1,5,2,0,7\] **Example 2:** **Input:** n = 8, m = 2, group = \[-1,-1,1,0,0,1,0,-1\], beforeItems = \[\[\],\[6\],\[5\],\[6\],\[3\],\[\],\[4\],\[\]\] **Output:** \[\] **Explanation:** This is the same as example 1 except that 4 needs to be before 6 in the sorted list. **Constraints:** * `1 <= m <= n <= 3 * 104` * `group.length == beforeItems.length == n` * `-1 <= group[i] <= m - 1` * `0 <= beforeItems[i].length <= n - 1` * `0 <= beforeItems[i][j] <= n - 1` * `i != beforeItems[i][j]` * `beforeItems[i]` does not contain duplicates elements.
null
Python with one Barrier
print-foobar-alternately
0
1
# Intuition\nOne Barrier should be enough to synch each iteration\n\n# Approach\nUse single barrier to sync AFTER foo and BEFORE the bar in each iteration on both threads.\n\nIf you like it, plese up-vote. Thank you!\n\n\n# Code\n```\nfrom threading import Event, Barrier\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.canBar = Barrier(2) # two parties involved\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.canBar.wait() # we both sync here\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canBar.wait() # we both sync here\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.canBar.reset() # replay the sync game\n\n```
2
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Python 3 | 6 Approaches | Explanation
print-foobar-alternately
0
1
## Before you proceed\n- **Intuition**: Make sure the executing order using `Lock` or similar mechanism.\n- Technically 8 approaches since the first two can be rewrote using `Semaphore`. \n\n## Approach \\#1. Lock/Semaphore only\n```python\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.l1 = Lock() # Semaphore(1)\n self.l2 = Lock() # Semaphore(1)\n self.l2.acquire()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.l1.acquire()\n printFoo()\n self.l2.release()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.l2.acquire()\n printBar()\n self.l1.release()\n```\n\n## Approach \\#2. Lock/Semaphore + Barrier\n```python\nfrom threading import Barrier, Lock #, Semaphore\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.b = Barrier(2)\n self.l = Lock() # Semaphore(1)\n self.l.acquire()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.l.release()\n self.b.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.l:\n printBar()\n self.b.wait()\n self.l.acquire()\n```\n## Approach \\#3. Condition only\n```python\nfrom threading import Condition\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.c1 = Condition()\n self.f = True\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c1:\n self.c1.wait_for(lambda: self.f)\n printFoo()\n self.f = False\n self.c1.notify(1)\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c1:\n self.c1.wait_for(lambda: not self.f)\n printBar()\n self.f = True\n self.c1.notify(1)\n```\n\n## Approach \\#4. Condition + Barrier\n```python\nfrom threading import Condition, Barrier\nclass FooBar: \n def __init__(self, n):\n self.n = n\n self.br = Barrier(2)\n self.c = Condition()\n self.f = False\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c:\n printFoo()\n self.f = True\n self.c.notify_all()\n self.br.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.c:\n self.c.wait_for(lambda: self.f)\n printBar() \n self.f = False\n self.br.wait()\n```\n\n\n## Approach \\#5. Event only\n```python\nfrom threading import Event\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.e = Event()\n self.e1 = Event()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.e.set() \n self.e1.wait()\n self.e1.clear()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.e.wait()\n printBar()\n self.e1.set()\n self.e.clear() \n```\n\n\n## Approach \\#6. Event + Barrier\n```python\nfrom threading import Event, Barrier\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.br = Barrier(2)\n self.e = Event()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n printFoo()\n self.e.set()\n self.br.wait()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.e.wait()\n printBar()\n self.e.clear()\n self.br.wait()\n```
6
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
🔥 All Language in Leetcode Solution with Mutex
print-foobar-alternately
1
1
***C++***\n```\n#include<semaphore.h>\n\nclass FooBar {\nprivate:\n int n;\n sem_t F, B;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&F, 0, 0);\n sem_init(&B, 0, 1);\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n sem_wait(&B);\n \tprintFoo();\n sem_post(&F);\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n sem_wait(&F);\n printBar();\n sem_post(&B);\n }\n }\n};\n```\n\n***Java***\n```\nclass FooBar {\n private int n;\n\n private Semaphore F = new Semaphore(1);\n private Semaphore B = new Semaphore(0);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n F.acquire();\n \tprintFoo.run();\n B.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n B.acquire();\n \tprintBar.run();\n F.release();\n }\n }\n}\n```\n\n***Python***\n```\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.F = threading.Semaphore(1)\n self.B = threading.Semaphore(0)\n\n def foo(self, printFoo):\n for i in xrange(self.n):\n self.F.acquire()\n printFoo()\n self.B.release()\n\n def bar(self, printBar):\n for i in xrange(self.n):\n self.B.acquire()\n printBar()\n self.F.release()\n```\n\n***python3***\n```\nimport threading \nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.F = threading.Semaphore(1)\n self.B = threading.Semaphore(0)\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.F.acquire()\n printFoo()\n self.B.release()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.B.acquire()\n printBar()\n self.F.release()\n```\n\n***C***\n```\ntypedef struct {\n int n;\n sem_t F;\n sem_t B;\n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n sem_init(&(obj->F), 0, 0);\n sem_init(&(obj->B), 0, 1);\n return obj;\n}\n\nvoid foo(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&(obj->B));\n printFoo();\n sem_post(&(obj->F));\n }\n}\n\nvoid bar(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&(obj->F));\n printBar();\n sem_post(&(obj->B));\n }\n}\n\nvoid fooBarFree(FooBar* obj) {\n sem_destroy(&(obj->B));\n sem_destroy(&(obj->F));\n free(obj);\n}\n```\n\n***C#***\n```\nusing System.Threading;\npublic class FooBar {\n private int n;\n private SemaphoreSlim F = new SemaphoreSlim(1);\n private SemaphoreSlim B = new SemaphoreSlim(0);\n\n public FooBar(int n)\n {\n this.n = n;\n }\n\n public void Foo(Action printFoo)\n {\n for (int i = 0; i < n; i++)\n {\n F.Wait();\n printFoo();\n B.Release();\n }\n }\n\n public void Bar(Action printBar)\n {\n for (int i = 0; i < n; i++)\n {\n B.Wait();\n printBar();\n F.Release();\n }\n }\n}\n```
2
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
python3: 40ms 86.64% Faster 100% Less memory, using threading.Lock
print-foobar-alternately
0
1
```\nfrom threading import Lock\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n self.bar_lock.acquire()\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.foo_lock.acquire()\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.bar_lock.release()\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.bar_lock.acquire()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.foo_lock.release()\n```
14
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Python with two Events
print-foobar-alternately
0
1
# Intuition\nTwo events: "ready for foo" and "ready for bar". \n\n# Approach\nCreate two events. Just set and clear each in proper moment.\nSee the comments in the code.\n\nIf you like it, plese up-vote. Thank you!\n\n\n# Code\n```\nfrom threading import Event, Barrier\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.canBar = Event()\n self.canBar.clear() # not yet ready for bar\n self.canFoo = Event()\n self.canFoo.set() # ready for foor\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canFoo.wait() # wait until ready for foo\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.canFoo.clear() # that foo is printed\n self.canBar.set() # now, ready for bar\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canBar.wait() # wait until ready for bar \n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.canBar.clear() # that bar is printed\n self.canFoo.set() # now, ready for foo\n```
2
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Print FooBar Alternately, Python Solution
print-foobar-alternately
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 FooBar:\n def __init__(self, n):\n self.n = n\n self.barrier = threading.Barrier(2)\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.barrier.wait()\n self.barrier.wait()\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n self.barrier.wait()\n for i in range(self.n):\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.barrier.wait()\n```
0
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Solution based on threading.Condition()
print-foobar-alternately
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are many solutions using two locks, which works fine for this solution. But two locks usually are risky, and can be a typical root cause for deadlock situation (though in this question, with proper variable initialization deadlock won\'t happen).\n\nHere is a different solution leveraging threading.Condition(), which allows threads to coordinate. It is arguably more scalable, if we want to add more threads to coordinate based on different conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nEssentially, we use a global variable as the switch to decide whether we should proceed with foo or bar method. After printing, then we modify the variable to the opposite value. Then in the next iteration, since the variable is still in the opposite value, the thread will enter condition.wait(), until the other thread notifies it. Alternating this process.\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 FooBar:\n def __init__(self, n):\n self.n = n\n self.nextPrintFoo = True\n self.condition = threading.Condition()\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.condition:\n while not self.nextPrintFoo:\n self.condition.wait()\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.nextPrintFoo = False\n self.condition.notify()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n with self.condition:\n while self.nextPrintFoo:\n self.condition.wait()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.nextPrintFoo = True\n self.condition.notify()\n```
0
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Python3: Canonical Single Lock Solution
print-foobar-alternately
0
1
# Intuition\n\nMost solutions have two `Lock` or `Event` objects or similar.\n\nFortunately there\'s an easier way.\n\nWe know that\n* foo has to be printed before bar\n* for each foo, we print a bar\n\nSo if\n* foo and bar have been printed the same number of times, it\'s time to print foo\n* if foo has been printed 1 more time than bar, it\'s time to print bar\n\nSo we\'ll do this:\n* foo: wait for the different in foos vs bars printed to be 0. then print foo and increment the difference\n* bar: wait for the difference in foos vs bars to be 1. Then print bar and decrement the difference\n\nThis fits nicely into the canonical\n```Python\nwith lock:\n while !condition():\n # wait for condition to be satisfied\n lock.wait()\n\n doThing() # we left the loop; condition is True\n \n # now we\'re done: notify another thread waiting on this\n lock.notify()\n```\n# Approach\n\nIn the scheme above:\n* `condition()` is `diff == 0` for foo, `diff == 1` for bar\n* `doThing()`: print, then update `diff`\n\n## Reentrant or Non-Reentrant Locking?\n\nReentrant is more general because a thread that already holds a lock and reacquire the lock. Hence "reentrant." This feature requires the lock to track the current thread holding the lock, if any, and the number of times it has been acquired. So it\'s a bit more expensive than the non-reentrant `Lock` type.\n\n## Why Not Event?\n\nThere are other solutions with `Event` already.\n\nAnd a weakness of `Event` that I wanted to avoid is that if `Event.is_set()`, then `Event.wait()` doesn\'t block. So that risks the loop from printing many foo and bar in a row if you\'re not careful.\n\nI think this is why all the `Event` solutions need *two* `Event`s, so that one can signal the other - so the two together work like a toggle or latch instead of an `Event` It works, but I was concerned with edge cases about one event signalling the other too soon or something. And it\'s unfortunate to use two `Event`s to basically just not be an `Event`.\n\nSo a single "we have one global state of fooCount - barCount, and thus one lock, and one thread should be making changes at a time" seemed a lot simpler.\n\n# Complexity\n- Time complexity: O(n) for n prints\n\n- Space complexity: O(1)\n\n# Code\n```\nfrom threading import Condition, Lock\n\nclass FooBar:\n def __init__(self, n):\n\n # strategy: foo needs to wait until fooCount == barCount. Then print foo, increment difference\n # bar needs to wait until fooCount == barCount + 1. Then print bar and decrement difference\n # both will do this n times\n # We don\'t literally need fooCount and barCount though - we just need the difference, 0 or 1\n\n self.cv = Condition(Lock())\n self.diff = 0\n self.n = n\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for _ in range(self.n):\n with self.cv:\n while self.diff != 0:\n self.cv.wait()\n\n printFoo()\n self.diff += 1\n self.cv.notify()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for _ in range(self.n):\n with self.cv:\n while self.diff != 1:\n self.cv.wait()\n\n printBar()\n self.diff -= 1\n self.cv.notify()\n```
0
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing. In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`. If there is no way to make `arr1` strictly increasing, return `-1`. **Example 1:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\] **Output:** 1 **Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`. **Example 2:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\] **Output:** 2 **Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`. **Example 3:** **Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\] **Output:** -1 **Explanation:** You can't make `arr1` strictly increasing. **Constraints:** * `1 <= arr1.length, arr2.length <= 2000` * `0 <= arr1[i], arr2[i] <= 10^9`
null
Python solution and explanation (with semaphores and barrier)
building-h2o
0
1
This solution uses `Semaphore` and `Barrier`. It is simple to understand, and performs well.\n\n## Semantics\n* a `Semaphore` -- trying to acquire it, is possible if there are `tokens` left. Otherwise the thread that tried is asked to wait until a different thread returns the tokens it was using.\n* a `Barrier` -- if a thread reaches it, it can cross it, only if a predefined number of other threads have also arrived.\n\n## Logic\nThe solution creates 1 `Semaphore` for Hydrogen, and allows 2 threads to aquire it concurrently. Likewise, we create one for Oxygen, but this one only allows 1 thread.\n\nTo ensure the molecule is generated at once, we use a barrier, which can only be crossed when 3 atoms have gathered.\n\nAfter each function completes, we release the token on the `Semaphore`.\n\n## Tip\nAs others have explained, we can use [_Python_ context managers](https://docs.python.org/3.8/library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement), which makes the code easier to follow.\n```\n## WITH context (with)\nsem = Semaphore(3)\n\nwith sem:\n # code...\n```\nis equivalent to\n```\n## WITHOUT context\nsem = Semaphore(3)\n\nsem.acquire()\ntry:\n # code...\nfinally:\n sem.release()\n```\n\n## Solution\n\n```\nfrom threading import Semaphore\nfrom threading import Barrier\n\nclass H2O:\n def __init__(self):\n self.sem_h = Semaphore(2)\n self.sem_o = Semaphore(1)\n self.bar_assembling = Barrier(3)\n\n\n def hydrogen(self, releaseHydrogen: \'Callable[[], None]\') -> None:\n\n with self.sem_h:\n self.bar_assembling.wait()\n\n releaseHydrogen()\n\n\n\n def oxygen(self, releaseOxygen: \'Callable[[], None]\') -> None:\n\n with self.sem_o:\n self.bar_assembling.wait()\n\n releaseOxygen()\n```
25
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
Simple Python3 Solution Using Two Locks
building-h2o
0
1
# Description\nThe description of this function can be very confusing - but essentially what it says is that there\'s one thread that calls `hydrogen()` 2n times and there\'s another thread that calls `oxygen()` n times. We need to implement the two functions such that the output is n times "HHO". \n\n# Approach\nSince we have two types of tasks, the intuitive way is to use two locks - one for each task. We keep a counter to count how many "H" has been printed out. In `hydrogen()`, we acquire the hydrogen lock. If the counter is odd, we release the hydrogen lock such that we can print another "H" before "O". If the counter is even, we release the oxygen lock such that we finish the "HHO".\n\n# Code\n```\nimport threading\nclass H2O:\n def __init__(self):\n self.h_count = 0\n self.h_lock = threading.Lock()\n self.o_lock = threading.Lock()\n self.o_lock.acquire()\n\n def hydrogen(self, releaseHydrogen: \'Callable[[], None]\') -> None:\n self.h_lock.acquire()\n # releaseHydrogen() outputs "H". Do not change or remove this line.\n releaseHydrogen()\n self.h_count += 1\n if self.h_count % 2 == 0:\n self.o_lock.release()\n else:\n self.h_lock.release()\n\n def oxygen(self, releaseOxygen: \'Callable[[], None]\') -> None:\n self.o_lock.acquire()\n # releaseOxygen() outputs "O". Do not change or remove this line.\n releaseOxygen()\n self.h_lock.release()\n```
0
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
Python3: Two Solutions, Including Explicit Matching
building-h2o
0
1
# Intuition\n\n## First Solution: Explicit Matching\n\nI misunderstood the problem and took a long time to solve it - I thought that the first two threads that called `hydrogen()` had to be matched with the first thread that called `oxygen()`, etc.\n\nSo my thought process was:\n* to release a molecule, the prior molecule must be released (wait on an `Event` that signals the prior molecule\'s emission)\n* then the three atoms have to be ready to be emitted (wait on a `barrier`)\n* then print the characters and signal that the molecule is done\n\n## Second Solution\n\nOn a more careful read, the last half of the problem set basically says "the only thing that matters is that each group of 3 emitted atoms is OOH in some order.\n\nYou do **not** have to match the first O with the first two H\'s, the next O with the next two H\'s, etc.\n\nYou only need to match them up in group of threes, so that each group of three is printed before the next group of three. The order of the input threads does NOT matter.\n\n# Approach\n\n## Explicit Matching\n\nFollowing my intuition, I made a `MEvent`, a twist on `threading.Event` that waits on\n* the prior event, if any, to finish\n* and all three atoms in the current group of 3 to finish\n\nI made two `deque`s of `MEvents` that need atoms, one for hydrogens and another for oxygens. The events are in order so that the first O and first two H\'s are paired, etc.\n\nExample: let\'s say we call `hydrogen()`. If there\'s a next event that needs another hydrogen (i.e. the hydrogen queue has an element), use the next event. If there\'s another hydrogen needed, push it back to the queue and record that we need 1 fewer hydrogen. Otherwise leave it off the queue. If there\'s no event that needs a hydrogen, we create a new one that\n* will wait on the prior molecule to be emitted\n* and has its own barrier for three threads\n* and push it to the hydrogen and oxygen queues\n\nThis way we match the oxygens and hydrogens in the order the methods are called.\n\n## Order Independent Matching\n\nThis one is a LOT easier; it\'s what most other solutions do.\n\nThe idea is that we need the threads to print in groups of 3, with exactly 2 oxygens and 1 hydrogen. So we pretty clearly need to wait on a `Barrier(3)`. And we need one oxygen and two hydrogens, so we should only allow 2 hydrogens and 1 oxygen to wait on the barrier.\n\nThus we have the following three variables\n```Python\nhs = Semaphore(2)\nos = Semaphore(1) # could be a Lock\nb = Barrier(3)\n```\n\nThe `hydrogen()` code becomes this:\n```Python\nwith self.hs:\n b.wait()\n releaseHydrogen()\n```\n\nAnd the `oxygen()` code is this:\n```Python\nwith self.os:\n b.wait()\n releaseOxygen()\n```\n\nSo what will happen is this:\n* we allow at most 2 Hs to await the current barrier with a semaphore. So 2 H threads will await the next barrier, and later ones will have to wait for the current H threads to release\n* we allow at most 1 O to await the current barrier with another semaphore or lock. Other O threads have to wait on the O semaphore to be released\n* the barrier requires requires exactly three threads. This is the maximum, so the ONLY combination that will work is 2 H threads and 1 O thread.\n * the semaphores limit us to <= 2 hydrogens and <= 1 oxygen\n * the barrier requires exactly three threads to participate\n * so the only combination is 2H + 1O\n* **when the barrier is passed, it resets itself**: it will require another 3 `wait`s to pass again\n* then each of the three threads prints (2 H\'s, 1 O in some order)\n* and then the three threads release 1 semaphore count to allow another thread of the same kind to await the next barrier/molecule\n\nSo every barrier is waited on by at most 2 H threads and 1 O thread. The barrier is only passed when exactly 3 threads are waiting on it. Therefore we will print out characters in groups of three, 2 H\'s and 1 O.\n\nAnother H or O can\'t be printed until the next barrier passes. And that barrier requires 3 threads waiting on it, so\n* a next H thread can\'t proceed until another H thread acquires, and another O thread requires\n* a next O thread can\'t proceed until two more H threads acquire\n\n### Note about Python Barriers\n\nA poorly-documented side effect of `threading.Barrier.wait()` is that the `Barrier` resets itself when the `n` threads pass through the barrier.\n\nSo you can reuse the same barrier as many times as you\'d like, each time will involve `n` threads waiting until they all pass.\n\nThis is why the order-independent solution only needs one barrier.\n\n# Complexity\n- Time complexity: O(n) to print out 3n characters\n\n- Space complexity: O(n) because O(n) threads have `hydrogen()` and `oxygen()` stack frames awaiting semaphores and barriers, Memory use will decline over time as more groups of H2O are printed and the corresponding threads exit and release their stack space.\n\n# Code\n\n```\nfrom threading import Condition, Lock, Barrier, Event\n\nclass MEvent:\n def __init__(self, prior: Optional[\'MEvent\']):\n self.priorDone = prior.done if prior else None\n self.barrier = Barrier(3)\n self.done = Event()\n\n def wait(self) -> None:\n if self.priorDone: self.priorDone.wait()\n self.barrier.wait()\n\nclass H2O:\n def __init__(self):\n # for an H:\n # need the prior molecule to be emitted first: priorEvent.wait()?\n # need other H and an O to be ready: Barrier(3).wait()?\n\n # for an O:\n # need the prior mol to be emitted\n # need two Hs to be ready\n\n # so we can have an "MEvent" with\n # > a prior event to wait on\n # > a barrier for all three to wait on\n # > an event to set to signal that this event is done\n\n self.latestEvent = None\n\n # if an event still needs an O, have the next O thread join that MEvent\n # otherwise create a new one. Same with Hs.\n self.oEvents = deque()\n self.hEvents = deque()\n self.cv = Condition(Lock()) # ensure atomic updates to oEvents and hEvents\n self.__addEvent()\n\n def __addEvent(self) -> None:\n """PRE: only call if the lock on self.cv is held."""\n\n mevent = MEvent(prior=self.latestEvent)\n self.latestEvent = mevent\n self.oEvents.append(mevent)\n self.hEvents.append((2, mevent))\n\n def hydrogen(self, releaseHydrogen: \'Callable[[], None]\') -> None:\n with self.cv:\n if not self.hEvents:\n self.__addEvent()\n\n r, mevent = self.hEvents.popleft()\n\n if r > 1:\n r -= 1\n self.hEvents.appendleft((r, mevent))\n\n mevent.wait()\n releaseHydrogen()\n mevent.done.set()\n\n def oxygen(self, releaseOxygen: \'Callable[[], None]\') -> None:\n with self.cv:\n if not self.oEvents:\n self.__addEvent()\n\n mevent = self.oEvents.popleft()\n\n mevent.wait()\n releaseOxygen()\n mevent.done.set()\n\n```
0
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
99.47% Python Solution (Custom lambda)
relative-sort-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```\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n presentElements = {}\n lengthOfArr1 = len(arr1)\n\n for i in range(len(arr2)):\n presentElements[arr2[i]] = i\n\n def relativeSort(x):\n if x in presentElements:\n return presentElements[x]\n return x + lengthOfArr1\n\n arr1.sort(key = relativeSort)\n return arr1\n\n```
0
Given two arrays `arr1` and `arr2`, the elements of `arr2` are distinct, and all elements in `arr2` are also in `arr1`. Sort the elements of `arr1` such that the relative ordering of items in `arr1` are the same as in `arr2`. Elements that do not appear in `arr2` should be placed at the end of `arr1` in **ascending** order. **Example 1:** **Input:** arr1 = \[2,3,1,3,2,4,6,7,9,2,19\], arr2 = \[2,1,4,3,9,6\] **Output:** \[2,2,2,1,4,3,3,9,6,7,19\] **Example 2:** **Input:** arr1 = \[28,6,22,8,44,17\], arr2 = \[22,28,8,6\] **Output:** \[22,28,8,6,17,44\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `0 <= arr1[i], arr2[i] <= 1000` * All the elements of `arr2` are **distinct**. * Each `arr2[i]` is in `arr1`.
Binary search for the length of the answer. (If there's an answer of length 10, then there are answers of length 9, 8, 7, ...) To check whether an answer of length K exists, we can use Rabin-Karp 's algorithm.
99.47% Python Solution (Custom lambda)
relative-sort-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```\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n presentElements = {}\n lengthOfArr1 = len(arr1)\n\n for i in range(len(arr2)):\n presentElements[arr2[i]] = i\n\n def relativeSort(x):\n if x in presentElements:\n return presentElements[x]\n return x + lengthOfArr1\n\n arr1.sort(key = relativeSort)\n return arr1\n\n```
0
We have `n` chips, where the position of the `ith` chip is `position[i]`. We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to: * `position[i] + 2` or `position[i] - 2` with `cost = 0`. * `position[i] + 1` or `position[i] - 1` with `cost = 1`. Return _the minimum cost_ needed to move all the chips to the same position. **Example 1:** **Input:** position = \[1,2,3\] **Output:** 1 **Explanation:** First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. **Example 2:** **Input:** position = \[2,2,2,3,3\] **Output:** 2 **Explanation:** We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2. **Example 3:** **Input:** position = \[1,1000000000\] **Output:** 1 **Constraints:** * `1 <= position.length <= 100` * `1 <= position[i] <= 10^9`
Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.
Python HashMap Fast Solution - Step by Step Explanation
relative-sort-array
0
1
```\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n #Start with creating an array/list to store answer\n ans = []\n \n #Create a hashmap and store all the elements as key and their frequency as value\n mapD = {}\n \n for i in arr1:\n #map.get(i, 0) to avoid key error in hashmap/dictionary\n mapD[i] = 1 + mapD.get(i, 0)\n \n #update the answer with elements as their frequncy in arr1 but in the sequence of arr2\n for i in arr2:\n ans[:] += [i] * mapD[i]\n \n #create another hashmap and a temporary list to find and store all elements that are not in arr2\n h = {}\n li = []\n \n for i in arr1:\n h[i] = 1 + h.get(i, 0)\n \n #Update the temporary list with elements and their frequency which are distinct in arr1\n for i in h:\n if i not in arr2:\n li[:] += [i] * h[i]\n \n li.sort()\n \n #merge the both arrays and here is the final ans\n ans[:] += li[:]\n \n return ans\n```
1
Given two arrays `arr1` and `arr2`, the elements of `arr2` are distinct, and all elements in `arr2` are also in `arr1`. Sort the elements of `arr1` such that the relative ordering of items in `arr1` are the same as in `arr2`. Elements that do not appear in `arr2` should be placed at the end of `arr1` in **ascending** order. **Example 1:** **Input:** arr1 = \[2,3,1,3,2,4,6,7,9,2,19\], arr2 = \[2,1,4,3,9,6\] **Output:** \[2,2,2,1,4,3,3,9,6,7,19\] **Example 2:** **Input:** arr1 = \[28,6,22,8,44,17\], arr2 = \[22,28,8,6\] **Output:** \[22,28,8,6,17,44\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `0 <= arr1[i], arr2[i] <= 1000` * All the elements of `arr2` are **distinct**. * Each `arr2[i]` is in `arr1`.
Binary search for the length of the answer. (If there's an answer of length 10, then there are answers of length 9, 8, 7, ...) To check whether an answer of length K exists, we can use Rabin-Karp 's algorithm.
Python HashMap Fast Solution - Step by Step Explanation
relative-sort-array
0
1
```\nclass Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n #Start with creating an array/list to store answer\n ans = []\n \n #Create a hashmap and store all the elements as key and their frequency as value\n mapD = {}\n \n for i in arr1:\n #map.get(i, 0) to avoid key error in hashmap/dictionary\n mapD[i] = 1 + mapD.get(i, 0)\n \n #update the answer with elements as their frequncy in arr1 but in the sequence of arr2\n for i in arr2:\n ans[:] += [i] * mapD[i]\n \n #create another hashmap and a temporary list to find and store all elements that are not in arr2\n h = {}\n li = []\n \n for i in arr1:\n h[i] = 1 + h.get(i, 0)\n \n #Update the temporary list with elements and their frequency which are distinct in arr1\n for i in h:\n if i not in arr2:\n li[:] += [i] * h[i]\n \n li.sort()\n \n #merge the both arrays and here is the final ans\n ans[:] += li[:]\n \n return ans\n```
1
We have `n` chips, where the position of the `ith` chip is `position[i]`. We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to: * `position[i] + 2` or `position[i] - 2` with `cost = 0`. * `position[i] + 1` or `position[i] - 1` with `cost = 1`. Return _the minimum cost_ needed to move all the chips to the same position. **Example 1:** **Input:** position = \[1,2,3\] **Output:** 1 **Explanation:** First step: Move the chip at position 3 to position 1 with cost = 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total cost is 1. **Example 2:** **Input:** position = \[2,2,2,3,3\] **Output:** 2 **Explanation:** We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2. **Example 3:** **Input:** position = \[1,1000000000\] **Output:** 1 **Constraints:** * `1 <= position.length <= 100` * `1 <= position[i] <= 10^9`
Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.
Python3 solution with explanation. Fast
lowest-common-ancestor-of-deepest-leaves
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that comes to mind for this problem is to use a depth-first search (DFS) approach. The idea is to traverse the tree and find the deepest leaves and the lowest common ancestor (LCA) of those leaves.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create a helper function dfs() that takes in a node as its parameter.\n- In the dfs() function, if the node is None, return 0 and None.\n- Otherwise, recursively call dfs() on the left and right children of the node and store the results in variables l and r.\n- Compare the depths of the left and right subtrees (l[0] and r[0]). If the left subtree has a greater depth, return l[0] + 1 and l[1]. If the right subtree has a greater depth, return r[0] + 1 and r[1].\n- If the depths are equal, return l[0] + 1 and the current node as the LCA of the deepest leaves.\n- Finally, in the main function, call the dfs() function on the root node and return the LCA from the result.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node):\n if not node:\n return 0, None\n l, r = dfs(node.left), dfs(node.right)\n if l[0] > r[0]:\n return l[0] + 1, l[1]\n if l[0] < r[0]:\n return r[0] + 1, r[1]\n return l[0] + 1, node\n return dfs(root)[1]\n```
2
Given the `root` of a binary tree, return _the lowest common ancestor of its deepest leaves_. Recall that: * The node of a binary tree is a leaf if and only if it has no children * The depth of the root of the tree is `0`. if the depth of a node is `d`, the depth of each of its children is `d + 1`. * The lowest common ancestor of a set `S` of nodes, is the node `A` with the largest depth such that every node in `S` is in the subtree with root `A`. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\] **Output:** \[2,7,4\] **Explanation:** We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. **Example 2:** **Input:** root = \[1\] **Output:** \[1\] **Explanation:** The root is the deepest node in the tree, and it's the lca of itself. **Example 3:** **Input:** root = \[0,1,3,null,2\] **Output:** \[2\] **Explanation:** The deepest leaf node in the tree is 2, the lca of one node is itself. **Constraints:** * The number of nodes in the tree will be in the range `[1, 1000]`. * `0 <= Node.val <= 1000` * The values of the nodes in the tree are **unique**. **Note:** This question is the same as 865: [https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
Can be the problem divided in parts, so solving each part and sum their solutions it should return the answer? Yes, you only need to divide the problem in finger jumps. In each finger jump you need to move your finger from one character to another, you need to know its index. Map each character to it's index. Use a hash table to do that.
Python3 solution with explanation. Fast
lowest-common-ancestor-of-deepest-leaves
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that comes to mind for this problem is to use a depth-first search (DFS) approach. The idea is to traverse the tree and find the deepest leaves and the lowest common ancestor (LCA) of those leaves.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create a helper function dfs() that takes in a node as its parameter.\n- In the dfs() function, if the node is None, return 0 and None.\n- Otherwise, recursively call dfs() on the left and right children of the node and store the results in variables l and r.\n- Compare the depths of the left and right subtrees (l[0] and r[0]). If the left subtree has a greater depth, return l[0] + 1 and l[1]. If the right subtree has a greater depth, return r[0] + 1 and r[1].\n- If the depths are equal, return l[0] + 1 and the current node as the LCA of the deepest leaves.\n- Finally, in the main function, call the dfs() function on the root node and return the LCA from the result.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node):\n if not node:\n return 0, None\n l, r = dfs(node.left), dfs(node.right)\n if l[0] > r[0]:\n return l[0] + 1, l[1]\n if l[0] < r[0]:\n return r[0] + 1, r[1]\n return l[0] + 1, node\n return dfs(root)[1]\n```
2
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[1,2,3,4\], difference = 1 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[1,2,3,4\]. **Example 2:** **Input:** arr = \[1,3,5,7\], difference = 1 **Output:** 1 **Explanation:** The longest arithmetic subsequence is any single element. **Example 3:** **Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[7,5,3,1\]. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i], difference <= 104` The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Python Straightforward 2-Pass Solution
lowest-common-ancestor-of-deepest-leaves
0
1
# Intuition\nFind the deepest leaves, push them up one level at a time until they meet. The first node where they meet is the LCA. This is based on the fact that the deepest leaves are on the same level (depth).\n\n# Approach\nBFS to find deepest leaves, and keep a dict to record each node\'s parent in order to push nodes up. At last use a while loop to push deepest leaves up until they meet, return the node where they first meet.\n\n\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n # step 1: find deepest leaves: use level traversal\n\n queue = collections.deque([(root, TreeNode(-1), 0)]) \n # let root\'s parent.val be -1, root\'s level be 0\n parents = dict() # parents[node i] = node i\'s parent\n levels = collections.defaultdict(list) # levels[i] = list of nodes on level i\n\n while queue:\n cur, parent, level = queue.pop()\n parents[cur] = parent\n levels[level].append(cur)\n if cur.left:\n queue.appendleft((cur.left, cur, level + 1))\n if cur.right:\n queue.appendleft((cur.right, cur, level + 1))\n\n deepest = levels[len(levels) - 1] # nodes at the last level\n # corner case: when only have one deepest leaf, return itself\n if len(deepest) == 1:\n return deepest[0]\n\n # step 2: find common ancestor by pushing back all leaves to their parent at a time, if all parents are the same, return this parent\n while True:\n deepest = [parents[node] for node in deepest] \n if len(set(deepest)) == 1: \n return deepest[0] \n \n\n\n```
1
Given the `root` of a binary tree, return _the lowest common ancestor of its deepest leaves_. Recall that: * The node of a binary tree is a leaf if and only if it has no children * The depth of the root of the tree is `0`. if the depth of a node is `d`, the depth of each of its children is `d + 1`. * The lowest common ancestor of a set `S` of nodes, is the node `A` with the largest depth such that every node in `S` is in the subtree with root `A`. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\] **Output:** \[2,7,4\] **Explanation:** We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. **Example 2:** **Input:** root = \[1\] **Output:** \[1\] **Explanation:** The root is the deepest node in the tree, and it's the lca of itself. **Example 3:** **Input:** root = \[0,1,3,null,2\] **Output:** \[2\] **Explanation:** The deepest leaf node in the tree is 2, the lca of one node is itself. **Constraints:** * The number of nodes in the tree will be in the range `[1, 1000]`. * `0 <= Node.val <= 1000` * The values of the nodes in the tree are **unique**. **Note:** This question is the same as 865: [https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
Can be the problem divided in parts, so solving each part and sum their solutions it should return the answer? Yes, you only need to divide the problem in finger jumps. In each finger jump you need to move your finger from one character to another, you need to know its index. Map each character to it's index. Use a hash table to do that.
Python Straightforward 2-Pass Solution
lowest-common-ancestor-of-deepest-leaves
0
1
# Intuition\nFind the deepest leaves, push them up one level at a time until they meet. The first node where they meet is the LCA. This is based on the fact that the deepest leaves are on the same level (depth).\n\n# Approach\nBFS to find deepest leaves, and keep a dict to record each node\'s parent in order to push nodes up. At last use a while loop to push deepest leaves up until they meet, return the node where they first meet.\n\n\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n # step 1: find deepest leaves: use level traversal\n\n queue = collections.deque([(root, TreeNode(-1), 0)]) \n # let root\'s parent.val be -1, root\'s level be 0\n parents = dict() # parents[node i] = node i\'s parent\n levels = collections.defaultdict(list) # levels[i] = list of nodes on level i\n\n while queue:\n cur, parent, level = queue.pop()\n parents[cur] = parent\n levels[level].append(cur)\n if cur.left:\n queue.appendleft((cur.left, cur, level + 1))\n if cur.right:\n queue.appendleft((cur.right, cur, level + 1))\n\n deepest = levels[len(levels) - 1] # nodes at the last level\n # corner case: when only have one deepest leaf, return itself\n if len(deepest) == 1:\n return deepest[0]\n\n # step 2: find common ancestor by pushing back all leaves to their parent at a time, if all parents are the same, return this parent\n while True:\n deepest = [parents[node] for node in deepest] \n if len(set(deepest)) == 1: \n return deepest[0] \n \n\n\n```
1
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[1,2,3,4\], difference = 1 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[1,2,3,4\]. **Example 2:** **Input:** arr = \[1,3,5,7\], difference = 1 **Output:** 1 **Explanation:** The longest arithmetic subsequence is any single element. **Example 3:** **Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[7,5,3,1\]. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i], difference <= 104` The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Python easy to understand and read | DFS
lowest-common-ancestor-of-deepest-leaves
0
1
My main intention is to find the height at every node and check if left subtree height is greater than right and vice versa. If height of left subtree is greater then i go furthur into the left subtree and same logic for right subtree as well. There will be a point where height of left subtree == height of right subtree and that will be LCA of deepest node. Here is the code :\n```\nclass Solution:\n def ht(self, node):\n if not node:\n return 0\n return max(self.ht(node.left), self.ht(node.right)) + 1\n \n def dfs(self, node):\n if not node:\n return None\n left, right = self.ht(node.left), self.ht(node.right)\n if left == right:\n return node\n if left > right:\n return self.dfs(node.left)\n if left < right:\n return self.dfs(node.right)\n\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n return self.dfs(root)
6
Given the `root` of a binary tree, return _the lowest common ancestor of its deepest leaves_. Recall that: * The node of a binary tree is a leaf if and only if it has no children * The depth of the root of the tree is `0`. if the depth of a node is `d`, the depth of each of its children is `d + 1`. * The lowest common ancestor of a set `S` of nodes, is the node `A` with the largest depth such that every node in `S` is in the subtree with root `A`. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\] **Output:** \[2,7,4\] **Explanation:** We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. **Example 2:** **Input:** root = \[1\] **Output:** \[1\] **Explanation:** The root is the deepest node in the tree, and it's the lca of itself. **Example 3:** **Input:** root = \[0,1,3,null,2\] **Output:** \[2\] **Explanation:** The deepest leaf node in the tree is 2, the lca of one node is itself. **Constraints:** * The number of nodes in the tree will be in the range `[1, 1000]`. * `0 <= Node.val <= 1000` * The values of the nodes in the tree are **unique**. **Note:** This question is the same as 865: [https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
Can be the problem divided in parts, so solving each part and sum their solutions it should return the answer? Yes, you only need to divide the problem in finger jumps. In each finger jump you need to move your finger from one character to another, you need to know its index. Map each character to it's index. Use a hash table to do that.
Python easy to understand and read | DFS
lowest-common-ancestor-of-deepest-leaves
0
1
My main intention is to find the height at every node and check if left subtree height is greater than right and vice versa. If height of left subtree is greater then i go furthur into the left subtree and same logic for right subtree as well. There will be a point where height of left subtree == height of right subtree and that will be LCA of deepest node. Here is the code :\n```\nclass Solution:\n def ht(self, node):\n if not node:\n return 0\n return max(self.ht(node.left), self.ht(node.right)) + 1\n \n def dfs(self, node):\n if not node:\n return None\n left, right = self.ht(node.left), self.ht(node.right)\n if left == right:\n return node\n if left > right:\n return self.dfs(node.left)\n if left < right:\n return self.dfs(node.right)\n\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n return self.dfs(root)
6
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[1,2,3,4\], difference = 1 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[1,2,3,4\]. **Example 2:** **Input:** arr = \[1,3,5,7\], difference = 1 **Output:** 1 **Explanation:** The longest arithmetic subsequence is any single element. **Example 3:** **Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[7,5,3,1\]. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i], difference <= 104` The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
python post order solution
lowest-common-ancestor-of-deepest-leaves
0
1
```\nclass Solution:\n def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:\n def post_order(root):\n if not root:\n return 0, None\n d1, n1 = post_order(root.left)\n d2, n2 = post_order(root.right)\n if d1 == d2:\n return d1+1, root\n elif d1 > d2:\n return d1+1, n1\n else:\n return d2+1, n2\n \n d, n = post_order(root)\n return n\n```
12
Given the `root` of a binary tree, return _the lowest common ancestor of its deepest leaves_. Recall that: * The node of a binary tree is a leaf if and only if it has no children * The depth of the root of the tree is `0`. if the depth of a node is `d`, the depth of each of its children is `d + 1`. * The lowest common ancestor of a set `S` of nodes, is the node `A` with the largest depth such that every node in `S` is in the subtree with root `A`. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\] **Output:** \[2,7,4\] **Explanation:** We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. **Example 2:** **Input:** root = \[1\] **Output:** \[1\] **Explanation:** The root is the deepest node in the tree, and it's the lca of itself. **Example 3:** **Input:** root = \[0,1,3,null,2\] **Output:** \[2\] **Explanation:** The deepest leaf node in the tree is 2, the lca of one node is itself. **Constraints:** * The number of nodes in the tree will be in the range `[1, 1000]`. * `0 <= Node.val <= 1000` * The values of the nodes in the tree are **unique**. **Note:** This question is the same as 865: [https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
Can be the problem divided in parts, so solving each part and sum their solutions it should return the answer? Yes, you only need to divide the problem in finger jumps. In each finger jump you need to move your finger from one character to another, you need to know its index. Map each character to it's index. Use a hash table to do that.
python post order solution
lowest-common-ancestor-of-deepest-leaves
0
1
```\nclass Solution:\n def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:\n def post_order(root):\n if not root:\n return 0, None\n d1, n1 = post_order(root.left)\n d2, n2 = post_order(root.right)\n if d1 == d2:\n return d1+1, root\n elif d1 > d2:\n return d1+1, n1\n else:\n return d2+1, n2\n \n d, n = post_order(root)\n return n\n```
12
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[1,2,3,4\], difference = 1 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[1,2,3,4\]. **Example 2:** **Input:** arr = \[1,3,5,7\], difference = 1 **Output:** 1 **Explanation:** The longest arithmetic subsequence is any single element. **Example 3:** **Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2 **Output:** 4 **Explanation:** The longest arithmetic subsequence is \[7,5,3,1\]. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i], difference <= 104` The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
✔ Python3 Solution | O(n)
longest-well-performing-interval
0
1
`Time Complexity` : `O(n)`\n`Space Complexity` : `O(n)`\n```\nclass Solution:\n def longestWPI(self, A):\n curr, ans, D = 0, 0, {}\n for e, i in enumerate(map(lambda x: (-1, 1)[x > 8], A)):\n curr += i\n D[curr] = D.get(curr, e)\n ans = e + 1 if curr > 0 else max(ans, e - D.get(curr - 1, e))\n return ans\n```
1
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
✔ Python3 Solution | O(n)
longest-well-performing-interval
0
1
`Time Complexity` : `O(n)`\n`Space Complexity` : `O(n)`\n```\nclass Solution:\n def longestWPI(self, A):\n curr, ans, D = 0, 0, {}\n for e, i in enumerate(map(lambda x: (-1, 1)[x > 8], A)):\n curr += i\n D[curr] = D.get(curr, e)\n ans = e + 1 if curr > 0 else max(ans, e - D.get(curr - 1, e))\n return ans\n```
1
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Simple Python Solution
longest-well-performing-interval
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 longestWPI(self, hours: List[int]) -> int:\n\n left, right = 0,0\n for i in range(len(hours)):\n if hours[i] > 8:\n hours[i] = 1\n else:\n hours[i] = -1\n longest, tot = 0, 0\n seen = {}\n for i in range(len(hours)):\n tot += hours[i]\n if tot > 0:\n longest = i + 1\n seen.setdefault(tot, i)\n\n if tot - 1 in seen:\n longest = max(longest, i - seen[tot-1])\n return longest \n\n\n```
1
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Simple Python Solution
longest-well-performing-interval
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 longestWPI(self, hours: List[int]) -> int:\n\n left, right = 0,0\n for i in range(len(hours)):\n if hours[i] > 8:\n hours[i] = 1\n else:\n hours[i] = -1\n longest, tot = 0, 0\n seen = {}\n for i in range(len(hours)):\n tot += hours[i]\n if tot > 0:\n longest = i + 1\n seen.setdefault(tot, i)\n\n if tot - 1 in seen:\n longest = max(longest, i - seen[tot-1])\n return longest \n\n\n```
1
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
PYTHON | AS INTERVIEWER WANTS |EXPLAINED WITH PICTURE | FAST | HASHMAP + PREFIX_SUM |
longest-well-performing-interval
0
1
# EXPLANATION\n\n**The idea is shown in the picture:**\n![image](https://assets.leetcode.com/users/images/c89ef794-4d50-484a-bda4-053e7fe31624_1655909773.853173.png)\n\n```\nSearching the j for every i can cost us O(n*n) which will cause TLE \nSo we need to use hashmap here \n\nNow let us say sum is -1 \nSo if we get a j having sum - 3 it will still be increment positively same for sum = -2 \nBut if you observe carefully we can reach -3 only from -2 as we can have (+1 / -1 ) \nSo the number prefix_sum[i] - 1 will always be farther than sum < prefix_sum[-1] \nThis is why we always use prefix_sum[i] - 1\n\nNOTE if sum < prefix_sum[i] - 1 exists : prefix_sum[i] - 1 will always exist as we can reach \nsum having sum < prefix_sum[i] - 1 by prefix_sum[i] - 1\n\nNow all we need to do is to keep a dictionary of all indexes of first occurence of an element\nTIME COMPLEXITY BECOMES O(n)\n```\n\n\n\n\n\n# CODE\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n n = len(hours)\n ans = 0\n prefix_sum = [0]*n\n d = {}\n for i in range(n):\n prefix_sum[i] = 1 if hours[i] > 8 else -1\n prefix_sum[i] += prefix_sum[i-1]\n if prefix_sum[i] > 0 : \n ans = i + 1\n else:\n if prefix_sum[i] - 1 in d:\n j = d[prefix_sum[i] - 1]\n if i - j > ans: ans = i - j\n if prefix_sum[i] not in d: d[prefix_sum[i]] = i\n return ans\n```
5
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
PYTHON | AS INTERVIEWER WANTS |EXPLAINED WITH PICTURE | FAST | HASHMAP + PREFIX_SUM |
longest-well-performing-interval
0
1
# EXPLANATION\n\n**The idea is shown in the picture:**\n![image](https://assets.leetcode.com/users/images/c89ef794-4d50-484a-bda4-053e7fe31624_1655909773.853173.png)\n\n```\nSearching the j for every i can cost us O(n*n) which will cause TLE \nSo we need to use hashmap here \n\nNow let us say sum is -1 \nSo if we get a j having sum - 3 it will still be increment positively same for sum = -2 \nBut if you observe carefully we can reach -3 only from -2 as we can have (+1 / -1 ) \nSo the number prefix_sum[i] - 1 will always be farther than sum < prefix_sum[-1] \nThis is why we always use prefix_sum[i] - 1\n\nNOTE if sum < prefix_sum[i] - 1 exists : prefix_sum[i] - 1 will always exist as we can reach \nsum having sum < prefix_sum[i] - 1 by prefix_sum[i] - 1\n\nNow all we need to do is to keep a dictionary of all indexes of first occurence of an element\nTIME COMPLEXITY BECOMES O(n)\n```\n\n\n\n\n\n# CODE\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n n = len(hours)\n ans = 0\n prefix_sum = [0]*n\n d = {}\n for i in range(n):\n prefix_sum[i] = 1 if hours[i] > 8 else -1\n prefix_sum[i] += prefix_sum[i-1]\n if prefix_sum[i] > 0 : \n ans = i + 1\n else:\n if prefix_sum[i] - 1 in d:\n j = d[prefix_sum[i] - 1]\n if i - j > ans: ans = i - j\n if prefix_sum[i] not in d: d[prefix_sum[i]] = i\n return ans\n```
5
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
📌📌 For-Beginners || Well-Explained || 97% faster || Easy-to-understand 🐍
longest-well-performing-interval
0
1
## IDEA:\n* Firstly create a prefix array (here \'dummy\') which represents number of tired day till specific index.\n* When it is tired day increased by one and similarly decrease 1 for normal day.\n\n**After creating prefix array:**\n* Now go through once and if you are finding positive number then directly update res with the index +1 because positive means from starting till now is the longest interval.\n* But when you get negative or zero then first check less then one value is there in store (dictionary- stores the index of first non-negative values), if it is present comapre res with that interval. It means it is the interval in which trial worling days are more then non-trial days.\n* if it is negative and it is its first occurance then store it in dictionary.\n\n\'\'\'\n\n\tclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n \n dic = defaultdict(int)\n dummy = [1 if hours[0]>8 else -1]\n for h in hours[1:]:\n c = 1 if h>8 else -1\n dummy.append(dummy[-1]+c)\n \n res = 0\n for i in range(len(dummy)):\n if dummy[i]>0:\n res = max(res,i+1)\n else:\n if dummy[i]-1 in dic:\n res = max(res,i-dic[dummy[i]-1])\n if dummy[i] not in dic:\n dic[dummy[i]] = i\n \n return res\n\n**Explaination of last two points:**\n\n*score = dummy[i]*\n\n* If the score is a new lowest score, we record the day by dic[curr] = i.\n* dic[score] means the first time we see the score is dic[score]th day.\n* We want a positive score, so we want to know the first occurrence of score - 1.\n* score - x also works, but it comes later than score - 1.\n* So the maximum interval is i - dic[score - 1]\n\n### Thanks and ***Upvote*** if like the Idea !!\uD83E\uDD1E
4
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
📌📌 For-Beginners || Well-Explained || 97% faster || Easy-to-understand 🐍
longest-well-performing-interval
0
1
## IDEA:\n* Firstly create a prefix array (here \'dummy\') which represents number of tired day till specific index.\n* When it is tired day increased by one and similarly decrease 1 for normal day.\n\n**After creating prefix array:**\n* Now go through once and if you are finding positive number then directly update res with the index +1 because positive means from starting till now is the longest interval.\n* But when you get negative or zero then first check less then one value is there in store (dictionary- stores the index of first non-negative values), if it is present comapre res with that interval. It means it is the interval in which trial worling days are more then non-trial days.\n* if it is negative and it is its first occurance then store it in dictionary.\n\n\'\'\'\n\n\tclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n \n dic = defaultdict(int)\n dummy = [1 if hours[0]>8 else -1]\n for h in hours[1:]:\n c = 1 if h>8 else -1\n dummy.append(dummy[-1]+c)\n \n res = 0\n for i in range(len(dummy)):\n if dummy[i]>0:\n res = max(res,i+1)\n else:\n if dummy[i]-1 in dic:\n res = max(res,i-dic[dummy[i]-1])\n if dummy[i] not in dic:\n dic[dummy[i]] = i\n \n return res\n\n**Explaination of last two points:**\n\n*score = dummy[i]*\n\n* If the score is a new lowest score, we record the day by dic[curr] = i.\n* dic[score] means the first time we see the score is dic[score]th day.\n* We want a positive score, so we want to know the first occurrence of score - 1.\n* score - x also works, but it comes later than score - 1.\n* So the maximum interval is i - dic[score - 1]\n\n### Thanks and ***Upvote*** if like the Idea !!\uD83E\uDD1E
4
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
10 lines, commented.
longest-well-performing-interval
0
1
# Intuition\nuse prefix sum with their indices for quick compute of subarray ends at current iterating index. \n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n hours = [1 if h > 8 else -1 for h in hours]\n summ = 0 \n # keeps negative prefix sum\'s earliest index\n # say our current prefix sum is -2, current index is 5\n # and we know from this dict, the earliest prefix sum== -1 is at index 1\n # then we know the subarry (1, 5] sum is 1, b/c (-1 - -2) = 1 \n d= {}\n res = 0 \n\n for i, h in enumerate(hours): \n summ += h \n if summ > 0: \n # prefix sum is postive.\n res = i + 1 \n else: \n if summ not in d: \n # this check b/c we want the earliest summ-1 index \n d[summ] = i\n if summ-1 in d: \n res = max(res, i - d[summ-1])\n return res\n \n \n \n \n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
10 lines, commented.
longest-well-performing-interval
0
1
# Intuition\nuse prefix sum with their indices for quick compute of subarray ends at current iterating index. \n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n hours = [1 if h > 8 else -1 for h in hours]\n summ = 0 \n # keeps negative prefix sum\'s earliest index\n # say our current prefix sum is -2, current index is 5\n # and we know from this dict, the earliest prefix sum== -1 is at index 1\n # then we know the subarry (1, 5] sum is 1, b/c (-1 - -2) = 1 \n d= {}\n res = 0 \n\n for i, h in enumerate(hours): \n summ += h \n if summ > 0: \n # prefix sum is postive.\n res = i + 1 \n else: \n if summ not in d: \n # this check b/c we want the earliest summ-1 index \n d[summ] = i\n if summ-1 in d: \n res = max(res, i - d[summ-1])\n return res\n \n \n \n \n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Python3: Yet Another Explanation of the O(N) Solution
longest-well-performing-interval
0
1
# Intuition\n\nWe want intervals where there are more >8 hour days than <= 8 hour days.\n\nThey call this a "well performing interval." But by that definition, my entire time working in finance was well performing... and yet I got laid off. So, uh, yeah. Checkmate, atheists?\n\n(yes, I\'m salty!)\n\nANYWAY. That means longDays > shortDays, or longDays - shortDays > 0.\n\nThis is kind of a leap of faith. But any time you see a problem that involves a contiguous window, and you can rewrite it as finding a longest subarray with positive sum or similar, then 99% of the time that\'s the right call.\n\nNow suppose we\'re looking at index `i`.\n* if indices 0..i form a WP interval, this is the longest interval thus far. So `i+1` elements is the new best thus far.\n* if not, suppose the cumulative difference is `cdiff`. If we can find an earlier index `e` with `cdiff\' < cdiff`, then the interval `i-e` has cumulative difference `cdiff-cdiff\' > 0`.\n * example: suppose `cdiff == 0`. Then an earlier index `e` where `cdiff\' == -1` means\n * `0..e` has `cdiff\' < cdiff`\n * `0..i` has `cdiff`\n * so `i+1..e` has `cdiff-cdiff\' > 0`\n\nNow what\'s the longest interval? It involves the *smallest* `e` among any `cdiff\' < cdiff`.\n\nThis *looks* hard. But it turns out to be easy! The earliest index of any `cdiff\' < cdiff` is *always* the index of `cdiff-1`. So just subtract one!\n\nThe reason is this:\n* suppose we have the earliest index of `cdiff = -3`\n* the value of `cdiff` changes by +/- 1 every iteration\n* so to have seen `cdiff = -3`, we had to see `cdiff = -2` for the first time before that.\n* and before *that* we had to see `cdiff = -1`\n* and before *that* we had to see `cdiff = 0`\n* so the more negative `cdiff` gets, the *later* the index gets.\n\nTherefore we want the least negative `cdiff\' < cdiff`. That\'s always `cdiff\' == cdiff-1`.\n\nHere\'s some ASCII art that shows `cdiff` values as we scan across the array\n```\n ^\nc | e \nd | e x x\ni | e x x x x\nf | e x x x x x\nf | e x x x x\n | e x\n V e\n```\ne labels the first index we\'ve seen something with that `cdiff` value.\n\nx labels later times we\'ve seen it.\n\nYou can clearly see that the indices of `cdiff == -1, -2, -3, ..` get later and later. So the least negative `cdiff` value is earliest.\n\n# Approach\n\nSo with this we need a couple of things\n* we need to track `cdiff` as we iterate\n* we also need a map of `cdiff -> earliestIndex`\n * or we can realize that `cdiff` must be in `[-N, N]`, and we don\'t care about knowing the earliest `cdiff >= 0`, so we can just make an array of `[0]*N` where `arr[-cdiff]` is the first index of `cdiff`\n * this is the same worst-case, and has worse best-case complexity. But directly indexing an array is usually faster than a dictionary of counts\n * personally I think the map is more clear, and it\'s more obvious... with only 20 minutes or so to do each problem, I wouldn\'t optimize like this in an interview. Too risky to burn time to not get an asymptotic improvement in the algorithm\n* while we iterate, if `cdiff > 0`, the whole array `0..i` is good, so the new best is i+1\n* if `cdiff <= 0`, then we look for the earliest index of any `cdiff\' < cdiff`: the index of `cdiff-1`\n* finally, if this is the first time we\'ve seen `cdiff`, we put `cdiff -> i` into the map\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N) for N elements. A scan across the array, and some hashmap operations.\n\n- Space complexity: O(N) for N elements. A bunch of elements in the hashmap.\n - if the hours are pseudorandom with probability p=0.5 of being a long or short day, then the most negative cdiff is O(sqrt(N)). So you\'d have O(sqrt(N)) elements in the map.\n - if they\'re all increasing, you don\'t have to store any entries. So O(1)\n - if they\'re all decreasing, then you have to store O(N) entries\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n # tiring: hours > 8\n # well performing: numTiring > numNonTiring\n\n # do all subintervals have to be WP too? NO\n\n # suppose we had k1 tiring, then k2 not tiring, then k3 tiring, and so on\n # we could coalesce intervals of tiring days to others that are not tiring to get larger intervals\n # with more tiring days. Divide and conquer, probably about O(N*log(n))\n\n # or we can brute-force ask "is there an interval of length m that is WP?" -> can answer that in log(n). Then we can do binary search\n # in log(n) because the longest is n\n\n # is there an O(N) solution?\n # suppose we had the cumulative difference of tiring vs not tiring at each index\n # then if the cumulative count is X at index j,\n # and there is an earliest index Y at i where X>Y, then i+1..j has cumulative difference X-Y > 0\n\n # get cumulative difference in tiring-notTiring\n N = len(hours)\n cdiff = 0\n # TODO: replace earliest dictionary with array, same O(N) memory use but better prefactor\n earliest = {} # latest[cdiff] == i where i is first time we saw that cumulative difference\n best = 0\n for i in range(N):\n cdiff += (1 if hours[i] > 8 else -1)\n if cdiff > 0:\n best = i+1 # whole array thus far is good\n elif cdiff-1 in earliest:\n # cdiff-1 is first diff and index where (cdiff-(cdiff-1))==1 > 0\n best = max(best, i-earliest[cdiff-1])\n\n if cdiff not in earliest:\n earliest[cdiff] = i\n\n return best\n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Python3: Yet Another Explanation of the O(N) Solution
longest-well-performing-interval
0
1
# Intuition\n\nWe want intervals where there are more >8 hour days than <= 8 hour days.\n\nThey call this a "well performing interval." But by that definition, my entire time working in finance was well performing... and yet I got laid off. So, uh, yeah. Checkmate, atheists?\n\n(yes, I\'m salty!)\n\nANYWAY. That means longDays > shortDays, or longDays - shortDays > 0.\n\nThis is kind of a leap of faith. But any time you see a problem that involves a contiguous window, and you can rewrite it as finding a longest subarray with positive sum or similar, then 99% of the time that\'s the right call.\n\nNow suppose we\'re looking at index `i`.\n* if indices 0..i form a WP interval, this is the longest interval thus far. So `i+1` elements is the new best thus far.\n* if not, suppose the cumulative difference is `cdiff`. If we can find an earlier index `e` with `cdiff\' < cdiff`, then the interval `i-e` has cumulative difference `cdiff-cdiff\' > 0`.\n * example: suppose `cdiff == 0`. Then an earlier index `e` where `cdiff\' == -1` means\n * `0..e` has `cdiff\' < cdiff`\n * `0..i` has `cdiff`\n * so `i+1..e` has `cdiff-cdiff\' > 0`\n\nNow what\'s the longest interval? It involves the *smallest* `e` among any `cdiff\' < cdiff`.\n\nThis *looks* hard. But it turns out to be easy! The earliest index of any `cdiff\' < cdiff` is *always* the index of `cdiff-1`. So just subtract one!\n\nThe reason is this:\n* suppose we have the earliest index of `cdiff = -3`\n* the value of `cdiff` changes by +/- 1 every iteration\n* so to have seen `cdiff = -3`, we had to see `cdiff = -2` for the first time before that.\n* and before *that* we had to see `cdiff = -1`\n* and before *that* we had to see `cdiff = 0`\n* so the more negative `cdiff` gets, the *later* the index gets.\n\nTherefore we want the least negative `cdiff\' < cdiff`. That\'s always `cdiff\' == cdiff-1`.\n\nHere\'s some ASCII art that shows `cdiff` values as we scan across the array\n```\n ^\nc | e \nd | e x x\ni | e x x x x\nf | e x x x x x\nf | e x x x x\n | e x\n V e\n```\ne labels the first index we\'ve seen something with that `cdiff` value.\n\nx labels later times we\'ve seen it.\n\nYou can clearly see that the indices of `cdiff == -1, -2, -3, ..` get later and later. So the least negative `cdiff` value is earliest.\n\n# Approach\n\nSo with this we need a couple of things\n* we need to track `cdiff` as we iterate\n* we also need a map of `cdiff -> earliestIndex`\n * or we can realize that `cdiff` must be in `[-N, N]`, and we don\'t care about knowing the earliest `cdiff >= 0`, so we can just make an array of `[0]*N` where `arr[-cdiff]` is the first index of `cdiff`\n * this is the same worst-case, and has worse best-case complexity. But directly indexing an array is usually faster than a dictionary of counts\n * personally I think the map is more clear, and it\'s more obvious... with only 20 minutes or so to do each problem, I wouldn\'t optimize like this in an interview. Too risky to burn time to not get an asymptotic improvement in the algorithm\n* while we iterate, if `cdiff > 0`, the whole array `0..i` is good, so the new best is i+1\n* if `cdiff <= 0`, then we look for the earliest index of any `cdiff\' < cdiff`: the index of `cdiff-1`\n* finally, if this is the first time we\'ve seen `cdiff`, we put `cdiff -> i` into the map\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N) for N elements. A scan across the array, and some hashmap operations.\n\n- Space complexity: O(N) for N elements. A bunch of elements in the hashmap.\n - if the hours are pseudorandom with probability p=0.5 of being a long or short day, then the most negative cdiff is O(sqrt(N)). So you\'d have O(sqrt(N)) elements in the map.\n - if they\'re all increasing, you don\'t have to store any entries. So O(1)\n - if they\'re all decreasing, then you have to store O(N) entries\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n # tiring: hours > 8\n # well performing: numTiring > numNonTiring\n\n # do all subintervals have to be WP too? NO\n\n # suppose we had k1 tiring, then k2 not tiring, then k3 tiring, and so on\n # we could coalesce intervals of tiring days to others that are not tiring to get larger intervals\n # with more tiring days. Divide and conquer, probably about O(N*log(n))\n\n # or we can brute-force ask "is there an interval of length m that is WP?" -> can answer that in log(n). Then we can do binary search\n # in log(n) because the longest is n\n\n # is there an O(N) solution?\n # suppose we had the cumulative difference of tiring vs not tiring at each index\n # then if the cumulative count is X at index j,\n # and there is an earliest index Y at i where X>Y, then i+1..j has cumulative difference X-Y > 0\n\n # get cumulative difference in tiring-notTiring\n N = len(hours)\n cdiff = 0\n # TODO: replace earliest dictionary with array, same O(N) memory use but better prefactor\n earliest = {} # latest[cdiff] == i where i is first time we saw that cumulative difference\n best = 0\n for i in range(N):\n cdiff += (1 if hours[i] > 8 else -1)\n if cdiff > 0:\n best = i+1 # whole array thus far is good\n elif cdiff-1 in earliest:\n # cdiff-1 is first diff and index where (cdiff-(cdiff-1))==1 > 0\n best = max(best, i-earliest[cdiff-1])\n\n if cdiff not in earliest:\n earliest[cdiff] = i\n\n return best\n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Two approaches
longest-well-performing-interval
0
1
This problem can be solved with either a prefix sum array, or a monotonic stack.\n\n### Prefix sum approach\n\n``` python\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n score = res = 0\n table = {}\n\n for i, h in enumerate(hours):\n score = score + 1 if h > 8 else score - 1\n if score > 0:\n res = i + 1\n else:\n if (score - 1) in table:\n res = max(res, i - table[score - 1])\n table.setdefault(score, i)\n\n return res\n```\n\n### Monotonic stack approach\n\nSee [editorial](https://leetcode.com/problems/longest-well-performing-interval/solutions/335163/o-n-without-hashmap-generalized-problem-solution-find-longest-subarray-with-sum-k/) which also lists similar problems\n\n``` python\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n stack = [(0, -1)]\n scores = []\n res = score = 0\n\n for i in range(len(hours)):\n score = score + 1 if hours[i] > 8 else score - 1\n scores.append(score)\n if stack[-1][0] > score:\n stack.append((score, i))\n\n for i in range(len(hours) - 1, -1, -1):\n while stack and stack[-1][0] < scores[i]:\n _, idx = stack.pop()\n res = max(res, i - idx)\n \n return res\n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Two approaches
longest-well-performing-interval
0
1
This problem can be solved with either a prefix sum array, or a monotonic stack.\n\n### Prefix sum approach\n\n``` python\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n score = res = 0\n table = {}\n\n for i, h in enumerate(hours):\n score = score + 1 if h > 8 else score - 1\n if score > 0:\n res = i + 1\n else:\n if (score - 1) in table:\n res = max(res, i - table[score - 1])\n table.setdefault(score, i)\n\n return res\n```\n\n### Monotonic stack approach\n\nSee [editorial](https://leetcode.com/problems/longest-well-performing-interval/solutions/335163/o-n-without-hashmap-generalized-problem-solution-find-longest-subarray-with-sum-k/) which also lists similar problems\n\n``` python\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n stack = [(0, -1)]\n scores = []\n res = score = 0\n\n for i in range(len(hours)):\n score = score + 1 if hours[i] > 8 else score - 1\n scores.append(score)\n if stack[-1][0] > score:\n stack.append((score, i))\n\n for i in range(len(hours) - 1, -1, -1):\n while stack and stack[-1][0] < scores[i]:\n _, idx = stack.pop()\n res = max(res, i - idx)\n \n return res\n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Longest well-performing interval
longest-well-performing-interval
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe should look at cumulative good days: cumulative += (1 if hour > 8 else -1) \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculate cumulative good days from t0. If current cumulative > 0 then longest period = current day. If cumulative < 0 the longest period should be current day less the first day when we saw cumulative = current cumulative - 1. So we store different cumulatives when they first appear in dict to access them in constant time. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n)\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: list[int]) -> int:\n dct = {0:0}\n cur = 0\n best = 0\n for day, hour in enumerate(hours):\n delta = 1 if hour > 8 else -1\n cur += delta\n \n if cur not in dct:\n dct[cur] = day + 1\n \n if cur > 0:\n best = day + 1\n else:\n if cur - 1 in dct:\n if day + 1 - dct[cur-1] > best:\n best = day + 1 - dct[cur-1]\n \n return best\n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Longest well-performing interval
longest-well-performing-interval
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe should look at cumulative good days: cumulative += (1 if hour > 8 else -1) \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculate cumulative good days from t0. If current cumulative > 0 then longest period = current day. If cumulative < 0 the longest period should be current day less the first day when we saw cumulative = current cumulative - 1. So we store different cumulatives when they first appear in dict to access them in constant time. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n)\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: list[int]) -> int:\n dct = {0:0}\n cur = 0\n best = 0\n for day, hour in enumerate(hours):\n delta = 1 if hour > 8 else -1\n cur += delta\n \n if cur not in dct:\n dct[cur] = day + 1\n \n if cur > 0:\n best = day + 1\n else:\n if cur - 1 in dct:\n if day + 1 - dct[cur-1] > best:\n best = day + 1 - dct[cur-1]\n \n return best\n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Python O(N) | Debunked all ill-explained solutions | One Post that beats all | True explanation
longest-well-performing-interval
0
1
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Use prefix sum approach first to calculate running net sum of number of tiring and non-tiring days. Use +1 for tiring days and -1 for non-tiring days. \n example - [6,6,9,1,11,8] : [-1, -2, -1, -2, -1, 0]\n\n2. From the prefix sum of any index i, we can easily tell, just by looking at the number that how many negative or positive tiring days it holds. ex- -2 tells that up to this index i, we have (tiring - non_tiring) = -2 days.\n\n\n3. Now to make -2 to postive 1(net tiring days overwhelm non-tiring days by one) i.e. tiring - non_tiring = 1, we need to take away(substract) a value (somePrefixSum) from it so that the result is 1\n -2 - somePrefixSum = 1 \n\nWhy Take Away From it ? \nbecause some value is added to this net -1 in past that is contributing to its negativity. once we identify that contributing value, we remove it from this total sum (-1) and get min positive 1 score.\n\n\n4. From above relation, we have to find this somePrefixSum, such that \n -2 = 1 + somePrefixSum\n so, this somePrefixSum is nothing but = -2 - 1 i.e. -3\n\n\n5. Boiling down, we can say that at any index i of prefix array, if the value is negative, then we need to find (value - 1) prefix sum holding-index viz j and substract j from i. The resulting difference is a candidate for maximum possible window. \n\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n \n \n n = len(hours)\n prefix = [0] * (n+1)\n seen = {}\n max_itvl = 0\n\n for i in range(n):\n prefix[i+1] = prefix[i] + (1 if hours[i] > 8 else -1)\n\n\n for i in range(1, n+1): \n\n if prefix[i] > 0:\n max_itvl = max(max_itvl, i)\n \n else:\n \n somePrefixSum = prefix[i] - 1\n\n if somePrefixSum in seen:\n max_itvl = max(max_itvl, i - seen[somePrefixSum])\n \n if prefix[i] not in seen:\n seen[prefix[i]] = i\n\n return max_itvl \n\n \n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Python O(N) | Debunked all ill-explained solutions | One Post that beats all | True explanation
longest-well-performing-interval
0
1
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Use prefix sum approach first to calculate running net sum of number of tiring and non-tiring days. Use +1 for tiring days and -1 for non-tiring days. \n example - [6,6,9,1,11,8] : [-1, -2, -1, -2, -1, 0]\n\n2. From the prefix sum of any index i, we can easily tell, just by looking at the number that how many negative or positive tiring days it holds. ex- -2 tells that up to this index i, we have (tiring - non_tiring) = -2 days.\n\n\n3. Now to make -2 to postive 1(net tiring days overwhelm non-tiring days by one) i.e. tiring - non_tiring = 1, we need to take away(substract) a value (somePrefixSum) from it so that the result is 1\n -2 - somePrefixSum = 1 \n\nWhy Take Away From it ? \nbecause some value is added to this net -1 in past that is contributing to its negativity. once we identify that contributing value, we remove it from this total sum (-1) and get min positive 1 score.\n\n\n4. From above relation, we have to find this somePrefixSum, such that \n -2 = 1 + somePrefixSum\n so, this somePrefixSum is nothing but = -2 - 1 i.e. -3\n\n\n5. Boiling down, we can say that at any index i of prefix array, if the value is negative, then we need to find (value - 1) prefix sum holding-index viz j and substract j from i. The resulting difference is a candidate for maximum possible window. \n\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n \n \n n = len(hours)\n prefix = [0] * (n+1)\n seen = {}\n max_itvl = 0\n\n for i in range(n):\n prefix[i+1] = prefix[i] + (1 if hours[i] > 8 else -1)\n\n\n for i in range(1, n+1): \n\n if prefix[i] > 0:\n max_itvl = max(max_itvl, i)\n \n else:\n \n somePrefixSum = prefix[i] - 1\n\n if somePrefixSum in seen:\n max_itvl = max(max_itvl, i - seen[somePrefixSum])\n \n if prefix[i] not in seen:\n seen[prefix[i]] = i\n\n return max_itvl \n\n \n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Detailed explanations for beginners like me
longest-well-performing-interval
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbefore this problem you can first solve leetcode 560.\nthan we can change the number that strictly greater than 8 into 1 else into -1. what we need to slove is **finding the longest subarray that the sum strictly greater than 0**.\n\n- why strictly greater than 0?\nbecause once cursum is 0 , this situation means the number of well-performing days(strictly greater than 8) is equal to the number of non-well-performing days(equal or less than 8).Thus, we must find the longest subarray greater than 0.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere are two situations:\n\n1. the first priority is find the longest equal to 1,why 1? because if cursum=2, it means it can include one more -1 and the subarray is still valid, the length will be longer. \n2. however, there are curcumstances than the array contains so many 1, so there will be cursum=2,cursum=3, so it is not strictly the sum of the longest subarray must equals to 1, it can be greater or euqal to 1.\n\nwhen we solve **find the longest subarray that equals k**, for example,\n``` index= [0, 1, 2,3, 4, 5,6]```\n ```array =[5,-3,-2,7, 6,-9,5], k=7``` \n```cursum=[5, 2, 0,7,13, 4,9]``` and we will have a hashtable to store frequencies.\nevery time we can check if **cursum-k** is in the cursum, if it is **the current index i minus the cursum-k\'s index** will be the longestlength for current position. for example, at index 6 the cursum=9, cursum-k=2 , cursum-k\'s index is 1, so the maxlength is 6-1=5, ths subarray is ```[-2,7,6,-9,5]```.\n\nsame as this problem, we store the first occurrence of each unique cursum. because we just want the k for this problem strictly grater than 1, so what we looking for is the first occurrence of **cursum-1**\'s index.\n\n# Complexity\n- Time complexity:O(n)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nwe iterate through the hours array. during the iteration, all other operations(updating cumulative sum, checking dictionary, updating ans ) are constant time.\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nthe main factor contribute to the space is the **firstindex** dictionary. In the worst cases, when all the elements are 1s or -1s, so each cumulative sum will be distinct. the dictionry will have at most n entries, n is the length of the input array.\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n for i in range(len(hours)):\n hours[i]=1 if hours[i]>8 else -1\n\n cursum=0\n firstindex={}\n maxlength=0\n\n for i in range(len(hours)):\n cursum+=hours[i]\n \n if cursum>0:\n maxlength=i+1\n \n if cursum not in firstindex:\n firstindex[cursum]=i\n \n if cursum-1 in firstindex:\n maxlength=max(maxlength,i-firstindex[cursum-1])\n return maxlength\n```
0
We are given `hours`, a list of the number of hours worked per day for a given employee. A day is considered to be a _tiring day_ if and only if the number of hours worked is (strictly) greater than `8`. A _well-performing interval_ is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. **Example 1:** **Input:** hours = \[9,9,6,0,6,6,9\] **Output:** 3 **Explanation:** The longest well-performing interval is \[9,9,6\]. **Example 2:** **Input:** hours = \[6,6,6\] **Output:** 0 **Constraints:** * `1 <= hours.length <= 104` * `0 <= hours[i] <= 16`
Model the problem as a graph problem. Add an edge from one character to another if you need to convert between them. What if one character needs to be converted into more than one character? There would be no solution. Thus, every node can have at most one outgoing edge. How to process a linked list? How to process a cycle? What if there is a character with no outgoing edge? You can use it to break all cycles!
Detailed explanations for beginners like me
longest-well-performing-interval
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbefore this problem you can first solve leetcode 560.\nthan we can change the number that strictly greater than 8 into 1 else into -1. what we need to slove is **finding the longest subarray that the sum strictly greater than 0**.\n\n- why strictly greater than 0?\nbecause once cursum is 0 , this situation means the number of well-performing days(strictly greater than 8) is equal to the number of non-well-performing days(equal or less than 8).Thus, we must find the longest subarray greater than 0.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere are two situations:\n\n1. the first priority is find the longest equal to 1,why 1? because if cursum=2, it means it can include one more -1 and the subarray is still valid, the length will be longer. \n2. however, there are curcumstances than the array contains so many 1, so there will be cursum=2,cursum=3, so it is not strictly the sum of the longest subarray must equals to 1, it can be greater or euqal to 1.\n\nwhen we solve **find the longest subarray that equals k**, for example,\n``` index= [0, 1, 2,3, 4, 5,6]```\n ```array =[5,-3,-2,7, 6,-9,5], k=7``` \n```cursum=[5, 2, 0,7,13, 4,9]``` and we will have a hashtable to store frequencies.\nevery time we can check if **cursum-k** is in the cursum, if it is **the current index i minus the cursum-k\'s index** will be the longestlength for current position. for example, at index 6 the cursum=9, cursum-k=2 , cursum-k\'s index is 1, so the maxlength is 6-1=5, ths subarray is ```[-2,7,6,-9,5]```.\n\nsame as this problem, we store the first occurrence of each unique cursum. because we just want the k for this problem strictly grater than 1, so what we looking for is the first occurrence of **cursum-1**\'s index.\n\n# Complexity\n- Time complexity:O(n)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nwe iterate through the hours array. during the iteration, all other operations(updating cumulative sum, checking dictionary, updating ans ) are constant time.\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nthe main factor contribute to the space is the **firstindex** dictionary. In the worst cases, when all the elements are 1s or -1s, so each cumulative sum will be distinct. the dictionry will have at most n entries, n is the length of the input array.\n# Code\n```\nclass Solution:\n def longestWPI(self, hours: List[int]) -> int:\n for i in range(len(hours)):\n hours[i]=1 if hours[i]>8 else -1\n\n cursum=0\n firstindex={}\n maxlength=0\n\n for i in range(len(hours)):\n cursum+=hours[i]\n \n if cursum>0:\n maxlength=i+1\n \n if cursum not in firstindex:\n firstindex[cursum]=i\n \n if cursum-1 in firstindex:\n maxlength=max(maxlength,i-firstindex[cursum-1])\n return maxlength\n```
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your position, you can walk one step to the left, right, up, or down. * You can't visit the same cell more than once. * Never visit a cell with `0` gold. * You can start and stop collecting gold from **any** position in the grid that has some gold. **Example 1:** **Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\] **Output:** 24 **Explanation:** \[\[0,6,0\], \[5,8,7\], \[0,9,0\]\] Path to get the maximum gold, 9 -> 8 -> 7. **Example 2:** **Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\] **Output:** 28 **Explanation:** \[\[1,0,7\], \[2,0,6\], \[3,4,5\], \[0,3,0\], \[9,0,20\]\] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `0 <= grid[i][j] <= 100` * There are at most **25** cells containing gold.
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Python Hard
smallest-sufficient-team
0
1
```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n\n d = defaultdict(int)\n N = len(req_skills)\n P = len(people)\n\n for i, skill in enumerate(req_skills):\n d[skill] = 1 << i\n\n people_skills = []\n\n for p_list in people:\n \n skills = 0\n\n for s in p_list:\n skills |= d[s]\n\n people_skills.append(skills)\n\n cache = {}\n\n def calc(index, mask):\n\n if (index, mask) in cache:\n return cache[(index, mask)]\n\n if mask == 0:\n return []\n\n if index == P:\n return [0] * 100\n\n best = min(calc(index + 1, mask), [index] + calc(index + 1, mask & ~people_skills[index]), key=len)\n\n cache[(index, mask)] = best\n\n return best\n\n\n return calc(0, (1 << N) - 1)\n\n\n\n\n\n \n\n\n \n```
1
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. * For example, `team = [0, 1, 3]` represents the people with skills `people[0]`, `people[1]`, and `people[3]`. Return _any sufficient team of the smallest possible size, represented by the index of each person_. You may return the answer in **any order**. It is **guaranteed** an answer exists. **Example 1:** **Input:** req\_skills = \["java","nodejs","reactjs"\], people = \[\["java"\],\["nodejs"\],\["nodejs","reactjs"\]\] **Output:** \[0,2\] **Example 2:** **Input:** req\_skills = \["algorithms","math","java","reactjs","csharp","aws"\], people = \[\["algorithms","math","java"\],\["algorithms","math","reactjs"\],\["java","csharp","aws"\],\["reactjs","csharp"\],\["csharp","math"\],\["aws","java"\]\] **Output:** \[1,2\] **Constraints:** * `1 <= req_skills.length <= 16` * `1 <= req_skills[i].length <= 16` * `req_skills[i]` consists of lowercase English letters. * All the strings of `req_skills` are **unique**. * `1 <= people.length <= 60` * `0 <= people[i].length <= 16` * `1 <= people[i][j].length <= 16` * `people[i][j]` consists of lowercase English letters. * All the strings of `people[i]` are **unique**. * Every skill in `people[i]` is a skill in `req_skills`. * It is guaranteed a sufficient team exists.
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.
Python Hard
smallest-sufficient-team
0
1
```\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n\n d = defaultdict(int)\n N = len(req_skills)\n P = len(people)\n\n for i, skill in enumerate(req_skills):\n d[skill] = 1 << i\n\n people_skills = []\n\n for p_list in people:\n \n skills = 0\n\n for s in p_list:\n skills |= d[s]\n\n people_skills.append(skills)\n\n cache = {}\n\n def calc(index, mask):\n\n if (index, mask) in cache:\n return cache[(index, mask)]\n\n if mask == 0:\n return []\n\n if index == P:\n return [0] * 100\n\n best = min(calc(index + 1, mask), [index] + calc(index + 1, mask & ~people_skills[index]), key=len)\n\n cache[(index, mask)] = best\n\n return best\n\n\n return calc(0, (1 << N) - 1)\n\n\n\n\n\n \n\n\n \n```
1
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * Each vowel `'i'` **may not** be followed by another `'i'`. * Each vowel `'o'` may only be followed by an `'i'` or a `'u'`. * Each vowel `'u'` may only be followed by an `'a'.` Since the answer may be too large, return it modulo `10^9 + 7.` **Example 1:** **Input:** n = 1 **Output:** 5 **Explanation:** All possible strings are: "a ", "e ", "i " , "o " and "u ". **Example 2:** **Input:** n = 2 **Output:** 10 **Explanation:** All possible strings are: "ae ", "ea ", "ei ", "ia ", "ie ", "io ", "iu ", "oi ", "ou " and "ua ". **Example 3:** **Input:** n = 5 **Output:** 68 **Constraints:** * `1 <= n <= 2 * 10^4`
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Python short and clean. DP. Bitmask. Functional programming.
smallest-sufficient-team
0
1
# Approach\nTL;DR, Similar to [Editorial solution Approach 2](https://leetcode.com/problems/smallest-sufficient-team/editorial/) but written functionally.\n\n# Complexity\n- Time complexity: $$O(2^k \\cdot n \\cdot log(n))$$\n (Note: $$log(n)$$ is for `int.bit_count()`)\n\n- Space complexity: $$O(2^k)$$\n\nwhere,\n`n is number of people`,\n`k is number of req_skills`.\n\n# Code\n```python\nclass Solution:\n def smallestSufficientTeam(self, req_skills: list[str], people: list[list[str]]) -> list[int]:\n n, k = len(people), len(req_skills)\n\n masks = lambda: accumulate(repeat(1), lshift)\n skill_to_mask = dict(zip(req_skills, masks()))\n person_skills_m = [reduce(or_, map(skill_to_mask.get, skills), 0) for skills in people]\n \n @cache\n def smallest_team_m(req_skills_m: int) -> int:\n rem_skills_m = map(lambda m: req_skills_m & ~m, person_skills_m)\n filtered = (x for x in zip(masks(), rem_skills_m) if x[1] != req_skills_m)\n teams = (p_m | smallest_team_m(rem_m) for p_m, rem_m in filtered)\n return min(teams, key=int.bit_count) if req_skills_m else 0\n \n team_m = smallest_team_m((1 << k) - 1)\n selector = map(int, bin(team_m)[:1:-1])\n return list(compress(range(n), selector))\n\n\n```
1
In a project, you have a list of required skills `req_skills`, and a list of people. The `ith` person `people[i]` contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in `req_skills`, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. * For example, `team = [0, 1, 3]` represents the people with skills `people[0]`, `people[1]`, and `people[3]`. Return _any sufficient team of the smallest possible size, represented by the index of each person_. You may return the answer in **any order**. It is **guaranteed** an answer exists. **Example 1:** **Input:** req\_skills = \["java","nodejs","reactjs"\], people = \[\["java"\],\["nodejs"\],\["nodejs","reactjs"\]\] **Output:** \[0,2\] **Example 2:** **Input:** req\_skills = \["algorithms","math","java","reactjs","csharp","aws"\], people = \[\["algorithms","math","java"\],\["algorithms","math","reactjs"\],\["java","csharp","aws"\],\["reactjs","csharp"\],\["csharp","math"\],\["aws","java"\]\] **Output:** \[1,2\] **Constraints:** * `1 <= req_skills.length <= 16` * `1 <= req_skills[i].length <= 16` * `req_skills[i]` consists of lowercase English letters. * All the strings of `req_skills` are **unique**. * `1 <= people.length <= 60` * `0 <= people[i].length <= 16` * `1 <= people[i][j].length <= 16` * `people[i][j]` consists of lowercase English letters. * All the strings of `people[i]` are **unique**. * Every skill in `people[i]` is a skill in `req_skills`. * It is guaranteed a sufficient team exists.
What if you think of a tree hierarchy for the files?. A path is a node in the tree. Use a hash table to store the valid paths along with their values.