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
Solution
shifting-letters
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(false); \n cin.tie(nullptr);\n cout.tie(nullptr);\n }\n string shiftingLetters(string s, vector<int>& shifts) {\n long long ps=0;\n for(int i=s.length()-1;i>=0;i--){\n ps+=shifts[i];\n s[i]=(char)((((s[i]-\'a\')+ps)%26)+\'a\');\n }\n return s;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n s=list(s)\n alphabet="abcdefghijklmnopqrstuvwxyz"\n store={\'a\': 0, \'b\': 1, \'c\': 2, \'d\': 3, \'e\': 4, \'f\': 5, \'g\': 6, \'h\': 7, \'i\': 8, \'j\': 9, \'k\': 10, \'l\': 11, \'m\': 12, \'n\': 13, \'o\': 14, \'p\': 15, \'q\': 16, \'r\': 17, \'s\': 18, \'t\': 19, \'u\': 20, \'v\': 21, \'w\': 22, \'x\': 23, \'y\': 24, \'z\': 25}\n sums=sum(shifts)\n for i in range(len(s)):\n index=store[s[i]]\n index=index+sums\n index=index%26\n s[i]=alphabet[index]\n sums-=shifts[i]\n return "".join(s)\n```\n\n```Java []\nclass Solution {\n public String shiftingLetters(String s, int[] shifts) { \n char arr[]=s.toCharArray();\n int total_shifts=0;\n int i = s.length() -1;\n while(i>=0){\n total_shifts += shifts[i]%26;\n arr[i]=(char)((arr[i] - \'a\' + total_shifts)%26 + \'a\');\n i--;\n }\n return String.valueOf(arr);\n }\n}\n```\n
3
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
Solution
shifting-letters
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(false); \n cin.tie(nullptr);\n cout.tie(nullptr);\n }\n string shiftingLetters(string s, vector<int>& shifts) {\n long long ps=0;\n for(int i=s.length()-1;i>=0;i--){\n ps+=shifts[i];\n s[i]=(char)((((s[i]-\'a\')+ps)%26)+\'a\');\n }\n return s;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n s=list(s)\n alphabet="abcdefghijklmnopqrstuvwxyz"\n store={\'a\': 0, \'b\': 1, \'c\': 2, \'d\': 3, \'e\': 4, \'f\': 5, \'g\': 6, \'h\': 7, \'i\': 8, \'j\': 9, \'k\': 10, \'l\': 11, \'m\': 12, \'n\': 13, \'o\': 14, \'p\': 15, \'q\': 16, \'r\': 17, \'s\': 18, \'t\': 19, \'u\': 20, \'v\': 21, \'w\': 22, \'x\': 23, \'y\': 24, \'z\': 25}\n sums=sum(shifts)\n for i in range(len(s)):\n index=store[s[i]]\n index=index+sums\n index=index%26\n s[i]=alphabet[index]\n sums-=shifts[i]\n return "".join(s)\n```\n\n```Java []\nclass Solution {\n public String shiftingLetters(String s, int[] shifts) { \n char arr[]=s.toCharArray();\n int total_shifts=0;\n int i = s.length() -1;\n while(i>=0){\n total_shifts += shifts[i]%26;\n arr[i]=(char)((arr[i] - \'a\' + total_shifts)%26 + \'a\');\n i--;\n }\n return String.valueOf(arr);\n }\n}\n```\n
3
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
One Line Beats 96% Python
shifting-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust use a reverse previx sum, add the offset, and mod the letter position.\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n return (lambda offsets : "".join([chr(ord(\'a\') + (offsets[i] + ord(s[i]) - ord(\'a\')) % 26) for i in range(len(s))]))(list(accumulate(shifts[::-1]))[::-1])\n```
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
One Line Beats 96% Python
shifting-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust use a reverse previx sum, add the offset, and mod the letter position.\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n return (lambda offsets : "".join([chr(ord(\'a\') + (offsets[i] + ord(s[i]) - ord(\'a\')) % 26) for i in range(len(s))]))(list(accumulate(shifts[::-1]))[::-1])\n```
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
80% Tc and 66% Sc easy python solution
shifting-letters
0
1
```\ndef shiftingLetters(self, s: str, shifts: List[int]) -> str:\n\tcurr = 0\n\tans = [i for i in shifts]\n\tfor i in range(len(s)-1, -1, -1):\n\t\tcurr = (curr + shifts[i]) % 26\n\t\tans[i] = chr(97 + (ord(s[i])-97 + curr)%26)\n\treturn "".join(ans)\n```
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
80% Tc and 66% Sc easy python solution
shifting-letters
0
1
```\ndef shiftingLetters(self, s: str, shifts: List[int]) -> str:\n\tcurr = 0\n\tans = [i for i in shifts]\n\tfor i in range(len(s)-1, -1, -1):\n\t\tcurr = (curr + shifts[i]) % 26\n\t\tans[i] = chr(97 + (ord(s[i])-97 + curr)%26)\n\treturn "".join(ans)\n```
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
Python Simple Logic
shifting-letters
0
1
# Intuition\nThink of no.of letters in English.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf the limit exceeds 25 then take the remainder.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n l = \'abcdefghijklmnopqrstuvwxyz\'\n S = sum(shifts)\n r = \'\'\n for i in range(len(s)):\n if l.index(s[i]) + (S % 26) > 25:\n r += l[(l.index(s[i]) + (S % 26)) % 26]\n else:\n r += l[l.index(s[i]) + (S % 26)]\n S -= shifts[i]\n return r\n```
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
Python Simple Logic
shifting-letters
0
1
# Intuition\nThink of no.of letters in English.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf the limit exceeds 25 then take the remainder.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n l = \'abcdefghijklmnopqrstuvwxyz\'\n S = sum(shifts)\n r = \'\'\n for i in range(len(s)):\n if l.index(s[i]) + (S % 26) > 25:\n r += l[(l.index(s[i]) + (S % 26)) % 26]\n else:\n r += l[l.index(s[i]) + (S % 26)]\n S -= shifts[i]\n return r\n```
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
Beats 99% Python Beginner Friendly
shifting-letters
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 shiftingLetters(self, s: str, shifts: List[int]) -> str:\n s1=list(s)\n res="abcdefghijklmnopqrstuvwxyz"\n p=0\n for i in range(len(shifts)-1,-1,-1):\n p+=shifts[i]\n k=((ord(s1[i])-97)+p)%26\n s1[i]=res[k]\n return "".join(s1)\n```
0
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
Beats 99% Python Beginner Friendly
shifting-letters
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 shiftingLetters(self, s: str, shifts: List[int]) -> str:\n s1=list(s)\n res="abcdefghijklmnopqrstuvwxyz"\n p=0\n for i in range(len(shifts)-1,-1,-1):\n p+=shifts[i]\n k=((ord(s1[i])-97)+p)%26\n s1[i]=res[k]\n return "".join(s1)\n```
0
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = 2, b = 3 **Output:** 6 **Constraints:** * `1 <= n <= 109` * `2 <= a, b <= 4 * 104`
null
python: easy to understand, 3 situations
maximize-distance-to-closest-person
0
1
\n\n# Code\n```\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n #initialization, starting index is 0, result is res\n left,res,index = -1,0,0\n while index != len(seats):\n # only right is 1\n if left == -1 and seats[index] == 1:\n res = max(res,index)\n left = index\n index+=1\n continue\n # only left is 1\n if index == len(seats)-1 and seats[index] == 0:\n res = max(res,index-left)\n index+=1\n continue\n # left and right both 1, sitting in the middle\n if seats[index] == 1:\n res = max(res,(index-left)//2)\n left = index\n index+=1\n return res\n \n```
2
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
python: easy to understand, 3 situations
maximize-distance-to-closest-person
0
1
\n\n# Code\n```\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n #initialization, starting index is 0, result is res\n left,res,index = -1,0,0\n while index != len(seats):\n # only right is 1\n if left == -1 and seats[index] == 1:\n res = max(res,index)\n left = index\n index+=1\n continue\n # only left is 1\n if index == len(seats)-1 and seats[index] == 0:\n res = max(res,index-left)\n index+=1\n continue\n # left and right both 1, sitting in the middle\n if seats[index] == 1:\n res = max(res,(index-left)//2)\n left = index\n index+=1\n return res\n \n```
2
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
[Python 3] - Greedy easy to understand
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- 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 maxDistToClosest(self, seats: List[int]) -> int:\n n = len(seats)\n sit_pos = [i for i in range(n) if seats[i]]\n res = max(0, sit_pos[0] - 0, n - 1 - sit_pos[-1])\n for i in range(1, len(sit_pos)):\n mid_pos = (sit_pos[i] + sit_pos[i - 1]) // 2\n res = max(res, min(mid_pos - sit_pos[i - 1], sit_pos[i] - mid_pos))\n return res\n```
3
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
[Python 3] - Greedy easy to understand
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- 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 maxDistToClosest(self, seats: List[int]) -> int:\n n = len(seats)\n sit_pos = [i for i in range(n) if seats[i]]\n res = max(0, sit_pos[0] - 0, n - 1 - sit_pos[-1])\n for i in range(1, len(sit_pos)):\n mid_pos = (sit_pos[i] + sit_pos[i - 1]) // 2\n res = max(res, min(mid_pos - sit_pos[i - 1], sit_pos[i] - mid_pos))\n return res\n```
3
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
[Python 3] Two pointers + visualisation || beats 99.8% || 112ms 🥷🏼
maximize-distance-to-closest-person
0
1
The main idea it\'s to save last busy seat, and when we meet a next busy seat, then distance will be `(current - previous)//2` => `(4 - 0) // 2` it\'s works either for even or odd distance between seats.\n![Screenshot 2023-08-01 at 01.32.37.png](https://assets.leetcode.com/users/images/2295e8ae-b7c0-4c55-8e2a-cc8258ecd901_1690842997.8815222.png)\nBut also exists 2 edge-cases (otherwise the problem would be simple):\n1 When we can seat on the first free place.\n The distance in this case will be just `i` if we start counting from `0`\n![Screenshot 2023-08-01 at 01.32.50.png](https://assets.leetcode.com/users/images/2d6cf01d-2bf4-454c-b12c-948f70917837_1690843214.7241278.png)\n2 When we can seat on the last free place.\nThe distance will be `i - previous`, or `len(seats) - 1 - previous`\n![Screenshot 2023-08-01 at 01.32.56.png](https://assets.leetcode.com/users/images/dcdb9481-2ffd-458d-ab7d-41e58143a8b0_1690843369.2865133.png)\n\n```python3 []\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n res, prev, L = 0, -1, len(seats)\n for i, n in enumerate(seats):\n if n:\n dist = i if prev == -1 else (i - prev)//2\n res = max(res, dist)\n prev = i\n \n if not seats[i]: #check last seat edge-case\n res = max(res, i - prev)\n\n return res\n```\n![Screenshot 2023-08-01 at 01.26.39.png](https://assets.leetcode.com/users/images/b79fbfd9-b342-4372-a670-8281326d619e_1690842543.9721901.png)\n
7
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
[Python 3] Two pointers + visualisation || beats 99.8% || 112ms 🥷🏼
maximize-distance-to-closest-person
0
1
The main idea it\'s to save last busy seat, and when we meet a next busy seat, then distance will be `(current - previous)//2` => `(4 - 0) // 2` it\'s works either for even or odd distance between seats.\n![Screenshot 2023-08-01 at 01.32.37.png](https://assets.leetcode.com/users/images/2295e8ae-b7c0-4c55-8e2a-cc8258ecd901_1690842997.8815222.png)\nBut also exists 2 edge-cases (otherwise the problem would be simple):\n1 When we can seat on the first free place.\n The distance in this case will be just `i` if we start counting from `0`\n![Screenshot 2023-08-01 at 01.32.50.png](https://assets.leetcode.com/users/images/2d6cf01d-2bf4-454c-b12c-948f70917837_1690843214.7241278.png)\n2 When we can seat on the last free place.\nThe distance will be `i - previous`, or `len(seats) - 1 - previous`\n![Screenshot 2023-08-01 at 01.32.56.png](https://assets.leetcode.com/users/images/dcdb9481-2ffd-458d-ab7d-41e58143a8b0_1690843369.2865133.png)\n\n```python3 []\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n res, prev, L = 0, -1, len(seats)\n for i, n in enumerate(seats):\n if n:\n dist = i if prev == -1 else (i - prev)//2\n res = max(res, dist)\n prev = i\n \n if not seats[i]: #check last seat edge-case\n res = max(res, i - prev)\n\n return res\n```\n![Screenshot 2023-08-01 at 01.26.39.png](https://assets.leetcode.com/users/images/b79fbfd9-b342-4372-a670-8281326d619e_1690842543.9721901.png)\n
7
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
✔️ [Python3] 5 LINES ( ˘ ³˘)ノ°゚º❍。, Explained
maximize-distance-to-closest-person
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThis problem is easy to solve, if notice that the max distance to the closest person can be calculated as numbers of empty spaces devided by two and rounded to ceil: `ceil(dist/2)`. For example: `[1, 0, 0, 0, 1]` => number of zeros between ones is `3` => max distance to the closest person, if sit in between is equal to `ceil(3/2) = 2`. Also, we need to care about edge cases when there are lots of free seats at the start or at the end. In this case the formula is different: `[0, 0, 0, 1]` => number of zeros is 3 => max distance is 3, that is we don\'t need to divide by two.\n\nTime: **O(n)** - for the scan\nSpace: **O(1)** - nothing stored\n\nRuntime: 132 ms, faster than **78.54%** of Python3 online submissions for Maximize Distance to Closest Person.\nMemory Usage: 14.5 MB, less than **92.48%** of Python3 online submissions for Maximize Distance to Closest Person.\n\n```\n def maxDistToClosest(self, seats: List[int]) -> int:\n res, dist = 0, seats.index(1)\n \n for seat in seats:\n if seat: \n res, dist = max(res, math.ceil(dist/2)), 0\n else: \n dist += 1\n \n return max(res, dist)\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
23
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
✔️ [Python3] 5 LINES ( ˘ ³˘)ノ°゚º❍。, Explained
maximize-distance-to-closest-person
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThis problem is easy to solve, if notice that the max distance to the closest person can be calculated as numbers of empty spaces devided by two and rounded to ceil: `ceil(dist/2)`. For example: `[1, 0, 0, 0, 1]` => number of zeros between ones is `3` => max distance to the closest person, if sit in between is equal to `ceil(3/2) = 2`. Also, we need to care about edge cases when there are lots of free seats at the start or at the end. In this case the formula is different: `[0, 0, 0, 1]` => number of zeros is 3 => max distance is 3, that is we don\'t need to divide by two.\n\nTime: **O(n)** - for the scan\nSpace: **O(1)** - nothing stored\n\nRuntime: 132 ms, faster than **78.54%** of Python3 online submissions for Maximize Distance to Closest Person.\nMemory Usage: 14.5 MB, less than **92.48%** of Python3 online submissions for Maximize Distance to Closest Person.\n\n```\n def maxDistToClosest(self, seats: List[int]) -> int:\n res, dist = 0, seats.index(1)\n \n for seat in seats:\n if seat: \n res, dist = max(res, math.ceil(dist/2)), 0\n else: \n dist += 1\n \n return max(res, dist)\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
23
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
maxDistToClosest
maximize-distance-to-closest-person
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 \n def maxDistToClosest(self, seats: List[int]) -> int:\n n = len(seats)\n max_gap = 0\n max_gap_right = 0\n max_gap_left = 0\n max_side = 0\n gap = 0\n for i in range(n):\n if seats[i] == 0:\n gap += 1\n else:\n if gap > 0:\n max_gap = max(max_gap, gap)\n gap = 0\n if gap > 0: # last gap\n max_gap = max(max_gap, gap)\n\n # handle special cases\n\n if seats[0] == 0:\n\n for i in range(n):\n if seats[i] == 0:\n max_gap_left += 1\n max_side = max_gap_left\n else:\n break\n\n if seats[-1] == 0:\n\n for i in range(n-1, -1, -1):\n if seats[i] == 0:\n max_gap_right += 1\n max_side = max(max_gap_left, max_gap_right)\n else:\n break\n \n if max_side > 2:\n if max_side >= max_gap / 2:\n return max_side\n\n\n if max_side == 2 == max_gap:\n return max_side\n\n\n return (max_gap + 1) // 2\n```
1
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
maxDistToClosest
maximize-distance-to-closest-person
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 \n def maxDistToClosest(self, seats: List[int]) -> int:\n n = len(seats)\n max_gap = 0\n max_gap_right = 0\n max_gap_left = 0\n max_side = 0\n gap = 0\n for i in range(n):\n if seats[i] == 0:\n gap += 1\n else:\n if gap > 0:\n max_gap = max(max_gap, gap)\n gap = 0\n if gap > 0: # last gap\n max_gap = max(max_gap, gap)\n\n # handle special cases\n\n if seats[0] == 0:\n\n for i in range(n):\n if seats[i] == 0:\n max_gap_left += 1\n max_side = max_gap_left\n else:\n break\n\n if seats[-1] == 0:\n\n for i in range(n-1, -1, -1):\n if seats[i] == 0:\n max_gap_right += 1\n max_side = max(max_gap_left, max_gap_right)\n else:\n break\n \n if max_side > 2:\n if max_side >= max_gap / 2:\n return max_side\n\n\n if max_side == 2 == max_gap:\n return max_side\n\n\n return (max_gap + 1) // 2\n```
1
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
Solution
rectangle-area-ii
1
1
```C++ []\nclass Solution {\npublic:\n #define ll long long\n ll MOD=1e9+7;\n static bool cmp(vector<int>&v1,vector<int>&v2){\n if(v1[0]==v2[0]){\n return v1[2]<v2[2];\n }\n return v1[0]<v2[0];\n }\n int rectangleArea(vector<vector<int>>& rectangles) {\n ll n=rectangles.size(),answer=0;\n set<ll>ss;\n for(auto &x:rectangles){\n ss.insert(x[1]);ss.insert(x[3]);\n }\n sort(rectangles.begin(),rectangles.end(),cmp);\n ll lower=*ss.begin();\n for(auto &x:ss){\n ll upper=x;\n ll height=upper-lower;\n ll left=rectangles[0][0],right=left;\n for(auto &y:rectangles){\n if(y[1]<=lower && y[3]>=upper){\n if(y[0]>right){\n answer=(answer+height*(right-left))%MOD;\n left=y[0];\n }\n if(y[2]>right){\n right=y[2];\n }\n }\n }\n answer=(answer+height*(right-left))%MOD;\n lower=upper;\n }\n return answer%MOD;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n MOD = (10 ** 9) + 7\n OPEN_EVENT = 0\n CLOSE_EVENT = 1\n\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n events = []\n for start_x, start_y, end_x, end_y in rectangles:\n events.append((start_x, self.OPEN_EVENT, start_y, end_y))\n events.append((end_x, self.CLOSE_EVENT, start_y, end_y))\n \n events.sort(key=lambda event: (event[0], event[1]))\n\n total_area = 0\n previous_sweep_line_halt_point_on_x_axis = float(\'-inf\')\n currently_open_rectangles_y_intervals = []\n for current_x, event_type, rec_start_y, rec_end_y in events:\n total_area += self._calculate_current_area(\n open_rectangles_y_intervals=currently_open_rectangles_y_intervals,\n width=current_x - previous_sweep_line_halt_point_on_x_axis,\n )\n if event_type == self.OPEN_EVENT:\n currently_open_rectangles_y_intervals.append((rec_start_y, rec_end_y))\n \n elif event_type == self.CLOSE_EVENT:\n currently_open_rectangles_y_intervals.remove((rec_start_y, rec_end_y))\n \n previous_sweep_line_halt_point_on_x_axis = current_x\n \n return total_area % self.MOD\n \n def _calculate_current_area(self, open_rectangles_y_intervals, width):\n if len(open_rectangles_y_intervals) == 0:\n return 0\n \n open_rectangles_y_intervals.sort(key=lambda open_rectangle_y_interval: open_rectangle_y_interval[0])\n\n current_area = 0\n\n start = open_rectangles_y_intervals[0][0]\n end = open_rectangles_y_intervals[0][1]\n for i in range(1, len(open_rectangles_y_intervals)):\n current_start_y, current_end_y = open_rectangles_y_intervals[i]\n\n if current_start_y <= end:\n end = max(end, current_end_y)\n else:\n height = end - start\n current_area += (width * height)\n\n start = current_start_y\n end = current_end_y\n \n\n height = end - start\n current_area += (width * height)\n\n return current_area\n```\n\n```Java []\nclass Solution {\n public int rectangleArea(int[][] rectangles) {\n int n = rectangles == null ? 0 : rectangles.length;\n if (n == 0) return 0;\n long xmin = Long.MAX_VALUE;\n long ymin = Long.MAX_VALUE;\n long xmax = Long.MIN_VALUE;\n long ymax = Long.MIN_VALUE;\n for(int[] r: rectangles) {\n if (r[0] < xmin) xmin = r[0];\n if (r[1] < ymin) ymin = r[1];\n if (r[2] > xmax) xmax = r[2];\n if (r[3] > ymax) ymax = r[3];\n }\n Node root = new Node(xmin, ymin, xmax, ymax, false);\n for(int[] r: rectangles) {\n root.add(r[0], r[1], r[2], r[3]);\n }\n return (int)(root.getFilledArea() % 1000000007L);\n }\n static class Node {\n long x1, y1, x2, y2;\n boolean filled;\n Node tl, tr, bl, br;\n Node(long x1, long y1, long x2, long y2, boolean filled) {\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this.filled = filled;\n }\n void add(int x1, int y1, int x2, int y2) {\n if (tl == null && filled) {\n return;\n }\n if (x1 >= this.x2 || x2 <= this.x1 || y1 >= this.y2 || y2 <= this.y1) {\n return;\n }\n if (x1 <= this.x1 && y1 <= this.y1 && x2 >= this.x2 && y2 >= this.y2) {\n filled = true;\n tl = tr = bl = br = null;\n return;\n }\n if (tl == null) {\n long x = this.x1 < x1 ? x1 : Math.min(x2, this.x2);\n long y = this.y1 < y1 ? y1 : Math.min(y2, this.y2);\n bl = new Node(this.x1, this.y1, x, y, false);\n br = new Node(x, this.y1, this.x2, y, false);\n tl = new Node(this.x1, y, x, this.y2, false);\n tr = new Node(x, y, this.x2, this.y2, false);\n }\n bl.add(x1, y1, x2, y2);\n br.add(x1, y1, x2, y2);\n tl.add(x1, y1, x2, y2);\n tr.add(x1, y1, x2, y2);\n }\n long getFilledArea() {\n long area;\n if (tl == null) {\n area = filled ? (x2-x1) * (y2-y1) : 0;\n } else {\n area = tl.getFilledArea() + tr.getFilledArea() + bl.getFilledArea() + br.getFilledArea();\n }\n return area;\n }\n }\n}\n```\n
3
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**. Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\] **Output:** 6 **Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. **Example 2:** **Input:** rectangles = \[\[0,0,1000000000,1000000000\]\] **Output:** 49 **Explanation:** The answer is 1018 modulo (109 + 7), which is 49. **Constraints:** * `1 <= rectangles.length <= 200` * `rectanges[i].length == 4` * `0 <= xi1, yi1, xi2, yi2 <= 109` * `xi1 <= xi2` * `yi1 <= yi2`
null
Solution
rectangle-area-ii
1
1
```C++ []\nclass Solution {\npublic:\n #define ll long long\n ll MOD=1e9+7;\n static bool cmp(vector<int>&v1,vector<int>&v2){\n if(v1[0]==v2[0]){\n return v1[2]<v2[2];\n }\n return v1[0]<v2[0];\n }\n int rectangleArea(vector<vector<int>>& rectangles) {\n ll n=rectangles.size(),answer=0;\n set<ll>ss;\n for(auto &x:rectangles){\n ss.insert(x[1]);ss.insert(x[3]);\n }\n sort(rectangles.begin(),rectangles.end(),cmp);\n ll lower=*ss.begin();\n for(auto &x:ss){\n ll upper=x;\n ll height=upper-lower;\n ll left=rectangles[0][0],right=left;\n for(auto &y:rectangles){\n if(y[1]<=lower && y[3]>=upper){\n if(y[0]>right){\n answer=(answer+height*(right-left))%MOD;\n left=y[0];\n }\n if(y[2]>right){\n right=y[2];\n }\n }\n }\n answer=(answer+height*(right-left))%MOD;\n lower=upper;\n }\n return answer%MOD;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n MOD = (10 ** 9) + 7\n OPEN_EVENT = 0\n CLOSE_EVENT = 1\n\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n events = []\n for start_x, start_y, end_x, end_y in rectangles:\n events.append((start_x, self.OPEN_EVENT, start_y, end_y))\n events.append((end_x, self.CLOSE_EVENT, start_y, end_y))\n \n events.sort(key=lambda event: (event[0], event[1]))\n\n total_area = 0\n previous_sweep_line_halt_point_on_x_axis = float(\'-inf\')\n currently_open_rectangles_y_intervals = []\n for current_x, event_type, rec_start_y, rec_end_y in events:\n total_area += self._calculate_current_area(\n open_rectangles_y_intervals=currently_open_rectangles_y_intervals,\n width=current_x - previous_sweep_line_halt_point_on_x_axis,\n )\n if event_type == self.OPEN_EVENT:\n currently_open_rectangles_y_intervals.append((rec_start_y, rec_end_y))\n \n elif event_type == self.CLOSE_EVENT:\n currently_open_rectangles_y_intervals.remove((rec_start_y, rec_end_y))\n \n previous_sweep_line_halt_point_on_x_axis = current_x\n \n return total_area % self.MOD\n \n def _calculate_current_area(self, open_rectangles_y_intervals, width):\n if len(open_rectangles_y_intervals) == 0:\n return 0\n \n open_rectangles_y_intervals.sort(key=lambda open_rectangle_y_interval: open_rectangle_y_interval[0])\n\n current_area = 0\n\n start = open_rectangles_y_intervals[0][0]\n end = open_rectangles_y_intervals[0][1]\n for i in range(1, len(open_rectangles_y_intervals)):\n current_start_y, current_end_y = open_rectangles_y_intervals[i]\n\n if current_start_y <= end:\n end = max(end, current_end_y)\n else:\n height = end - start\n current_area += (width * height)\n\n start = current_start_y\n end = current_end_y\n \n\n height = end - start\n current_area += (width * height)\n\n return current_area\n```\n\n```Java []\nclass Solution {\n public int rectangleArea(int[][] rectangles) {\n int n = rectangles == null ? 0 : rectangles.length;\n if (n == 0) return 0;\n long xmin = Long.MAX_VALUE;\n long ymin = Long.MAX_VALUE;\n long xmax = Long.MIN_VALUE;\n long ymax = Long.MIN_VALUE;\n for(int[] r: rectangles) {\n if (r[0] < xmin) xmin = r[0];\n if (r[1] < ymin) ymin = r[1];\n if (r[2] > xmax) xmax = r[2];\n if (r[3] > ymax) ymax = r[3];\n }\n Node root = new Node(xmin, ymin, xmax, ymax, false);\n for(int[] r: rectangles) {\n root.add(r[0], r[1], r[2], r[3]);\n }\n return (int)(root.getFilledArea() % 1000000007L);\n }\n static class Node {\n long x1, y1, x2, y2;\n boolean filled;\n Node tl, tr, bl, br;\n Node(long x1, long y1, long x2, long y2, boolean filled) {\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this.filled = filled;\n }\n void add(int x1, int y1, int x2, int y2) {\n if (tl == null && filled) {\n return;\n }\n if (x1 >= this.x2 || x2 <= this.x1 || y1 >= this.y2 || y2 <= this.y1) {\n return;\n }\n if (x1 <= this.x1 && y1 <= this.y1 && x2 >= this.x2 && y2 >= this.y2) {\n filled = true;\n tl = tr = bl = br = null;\n return;\n }\n if (tl == null) {\n long x = this.x1 < x1 ? x1 : Math.min(x2, this.x2);\n long y = this.y1 < y1 ? y1 : Math.min(y2, this.y2);\n bl = new Node(this.x1, this.y1, x, y, false);\n br = new Node(x, this.y1, this.x2, y, false);\n tl = new Node(this.x1, y, x, this.y2, false);\n tr = new Node(x, y, this.x2, this.y2, false);\n }\n bl.add(x1, y1, x2, y2);\n br.add(x1, y1, x2, y2);\n tl.add(x1, y1, x2, y2);\n tr.add(x1, y1, x2, y2);\n }\n long getFilledArea() {\n long area;\n if (tl == null) {\n area = filled ? (x2-x1) * (y2-y1) : 0;\n } else {\n area = tl.getFilledArea() + tr.getFilledArea() + bl.getFilledArea() + br.getFilledArea();\n }\n return area;\n }\n }\n}\n```\n
3
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_. **Example 1:** **Input:** s = "leet2code3 ", k = 10 **Output:** "o " **Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ". The 10th letter in the string is "o ". **Example 2:** **Input:** s = "ha22 ", k = 5 **Output:** "h " **Explanation:** The decoded string is "hahahaha ". The 5th letter is "h ". **Example 3:** **Input:** s = "a2345678999999999999999 ", k = 1 **Output:** "a " **Explanation:** The decoded string is "a " repeated 8301530446056247680 times. The 1st letter is "a ". **Constraints:** * `2 <= s.length <= 100` * `s` consists of lowercase English letters and digits `2` through `9`. * `s` starts with a letter. * `1 <= k <= 109` * It is guaranteed that `k` is less than or equal to the length of the decoded string. * The decoded string is guaranteed to have less than `263` letters.
null
Grid
rectangle-area-ii
0
1
# Intuition\nSeperate x into grids based on distinct values of x1 and x2. For each grid, calculate the vertical area in that grid. Sum up areas from all grids.\n\n# Code\n```\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n area = 0\n rectangles.sort(key=lambda x: x[1])\n x_grid = set()\n for x1, y1, x2, y2 in rectangles:\n if x1 not in x_grid:\n x_grid.add(x1)\n if x2 not in x_grid:\n x_grid.add(x2)\n x_grid = sorted([x for x in x_grid])\n for i in range(len(x_grid) - 1):\n y_min = 0\n dx = x_grid[i+1] - x_grid[i]\n for x1, y1, x2, y2 in rectangles:\n if x1 <= x_grid[i] and x2 >= x_grid[i + 1]:\n if y1 >= y_min:\n area += dx * (y2 - y1) % (10 ** 9 + 7)\n y_min = y2\n elif y2 > y_min:\n area += dx * (y2 - y_min) % (10 ** 9 + 7)\n y_min = y2\n return area % (10 ** 9 + 7)\n```
0
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**. Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\] **Output:** 6 **Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. **Example 2:** **Input:** rectangles = \[\[0,0,1000000000,1000000000\]\] **Output:** 49 **Explanation:** The answer is 1018 modulo (109 + 7), which is 49. **Constraints:** * `1 <= rectangles.length <= 200` * `rectanges[i].length == 4` * `0 <= xi1, yi1, xi2, yi2 <= 109` * `xi1 <= xi2` * `yi1 <= yi2`
null
Grid
rectangle-area-ii
0
1
# Intuition\nSeperate x into grids based on distinct values of x1 and x2. For each grid, calculate the vertical area in that grid. Sum up areas from all grids.\n\n# Code\n```\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n area = 0\n rectangles.sort(key=lambda x: x[1])\n x_grid = set()\n for x1, y1, x2, y2 in rectangles:\n if x1 not in x_grid:\n x_grid.add(x1)\n if x2 not in x_grid:\n x_grid.add(x2)\n x_grid = sorted([x for x in x_grid])\n for i in range(len(x_grid) - 1):\n y_min = 0\n dx = x_grid[i+1] - x_grid[i]\n for x1, y1, x2, y2 in rectangles:\n if x1 <= x_grid[i] and x2 >= x_grid[i + 1]:\n if y1 >= y_min:\n area += dx * (y2 - y1) % (10 ** 9 + 7)\n y_min = y2\n elif y2 > y_min:\n area += dx * (y2 - y_min) % (10 ** 9 + 7)\n y_min = y2\n return area % (10 ** 9 + 7)\n```
0
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_. **Example 1:** **Input:** s = "leet2code3 ", k = 10 **Output:** "o " **Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ". The 10th letter in the string is "o ". **Example 2:** **Input:** s = "ha22 ", k = 5 **Output:** "h " **Explanation:** The decoded string is "hahahaha ". The 5th letter is "h ". **Example 3:** **Input:** s = "a2345678999999999999999 ", k = 1 **Output:** "a " **Explanation:** The decoded string is "a " repeated 8301530446056247680 times. The 1st letter is "a ". **Constraints:** * `2 <= s.length <= 100` * `s` consists of lowercase English letters and digits `2` through `9`. * `s` starts with a letter. * `1 <= k <= 109` * It is guaranteed that `k` is less than or equal to the length of the decoded string. * The decoded string is guaranteed to have less than `263` letters.
null
Python 3 || 8 lines, cached dfs || T/M: 74% / 44%
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n \n n = len(quiet)\n g, f = defaultdict(list), lambda x: list(map(dfs,x)) \n for u, v in richer: g[v].append(u)\n\n @lru_cache(2000)\n def dfs(node):\n return min(((f(g[node]))+[node]), key=lambda x:quiet[x])\n \n return f(range(n))\n```\n[https://leetcode.com/problems/loud-and-rich/submissions/955947460/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*+*R*) and space complexity is *O*(*N*+*R*) in which *N* ~`len(quiet)`and *R* ~`len(richer)`.
3
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Python 3 || 8 lines, cached dfs || T/M: 74% / 44%
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n \n n = len(quiet)\n g, f = defaultdict(list), lambda x: list(map(dfs,x)) \n for u, v in richer: g[v].append(u)\n\n @lru_cache(2000)\n def dfs(node):\n return min(((f(g[node]))+[node]), key=lambda x:quiet[x])\n \n return f(range(n))\n```\n[https://leetcode.com/problems/loud-and-rich/submissions/955947460/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*+*R*) and space complexity is *O*(*N*+*R*) in which *N* ~`len(quiet)`and *R* ~`len(richer)`.
3
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
FASTEST PYTHON SOLUTION
loud-and-rich
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N+LENGTH OF RICHER)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N*LENGTH OF RICHER)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,node,visited,ans,value,lst):\n # print(node)\n visited[node]=1\n for i in lst[node]:\n if visited[i]==0:\n self.dfs(i,visited,ans,value,lst)\n x=value[i]\n # print(node,i,value[node],x)\n if x<value[node]:\n value[node]=x\n ans[node]=ans[i]\n return \n\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n n=len(quiet)\n visited=[0]*n\n lst=[[] for i in range(n)]\n for i,j in richer:\n lst[j].append(i)\n # print(lst)\n ans=[i for i in range(n)]\n value=[quiet[i] for i in range(n)]\n for i in range(n):\n if visited[i]==0:\n self.dfs(i,visited,ans,value,lst)\n return ans \n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
FASTEST PYTHON SOLUTION
loud-and-rich
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N+LENGTH OF RICHER)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N*LENGTH OF RICHER)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,node,visited,ans,value,lst):\n # print(node)\n visited[node]=1\n for i in lst[node]:\n if visited[i]==0:\n self.dfs(i,visited,ans,value,lst)\n x=value[i]\n # print(node,i,value[node],x)\n if x<value[node]:\n value[node]=x\n ans[node]=ans[i]\n return \n\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n n=len(quiet)\n visited=[0]*n\n lst=[[] for i in range(n)]\n for i,j in richer:\n lst[j].append(i)\n # print(lst)\n ans=[i for i in range(n)]\n value=[quiet[i] for i in range(n)]\n for i in range(n):\n if visited[i]==0:\n self.dfs(i,visited,ans,value,lst)\n return ans \n```
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
SIMPLE PYTHON SOLUTION
loud-and-rich
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N+length of richer)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*length of richer)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n n=len(quiet)\n indegree=[0]*n\n lst=[[] for i in range(n)]\n for i,j in richer:\n lst[i].append(j)\n indegree[j]+=1\n ans=[i for i in range(n)]\n value=[quiet[i] for i in range(n)]\n st=[]\n for i in range(n):\n if indegree[i]==0:\n st.append(i)\n while st:\n x=st.pop(0)\n for i in lst[x]:\n indegree[i]-=1\n if value[x]<value[i]:\n ans[i]=ans[x]\n value[i]=value[x]\n if indegree[i]==0:\n st.append(i)\n return ans\n \n\n \n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
SIMPLE PYTHON SOLUTION
loud-and-rich
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N+length of richer)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*length of richer)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n n=len(quiet)\n indegree=[0]*n\n lst=[[] for i in range(n)]\n for i,j in richer:\n lst[i].append(j)\n indegree[j]+=1\n ans=[i for i in range(n)]\n value=[quiet[i] for i in range(n)]\n st=[]\n for i in range(n):\n if indegree[i]==0:\n st.append(i)\n while st:\n x=st.pop(0)\n for i in lst[x]:\n indegree[i]-=1\n if value[x]<value[i]:\n ans[i]=ans[x]\n value[i]=value[x]\n if indegree[i]==0:\n st.append(i)\n return ans\n \n\n \n```
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Beginner-friendly, Readable Python, Black-boxes, Topological Sort
loud-and-rich
0
1
# Intuition\nFind the topological sort order, then iterate through the nodes in the the topological sort order, keeping track of every node\'s minimum value/node compared to its most recent predecessors.\n\nThe topological sort allows us to use a dynamic programming technique of using previously calculated results to find a solution at the current step. Recall there are no cycles in the graph, so this type of problem is solveable via dynamic programming.\n\n# Approach\nThis problem is a lot easier if you think of it in terms of black-boxes:\n\n* The problem is described as a DAG.\n* You are asked to find a solution for each node that depends on some minimum or maximum value propagated from previous nodes; this should clue us in on using `Topological Sort` and `Dynamic Programming`.\n\nThe rest is just fitting the specifics of the problem into the blackboxes of topological sort and value propagation (dynamic programming). \n\nYou can use the topological sort and do bottom-up DP like in my solution; or, like others\' solutions, you can cache the result of DFS and do top-down DP, but then you might have to do traverse the graph in the reverse direction at some point.\n\nIMO, it can be difficult to grasp some of these other solutions if you are a beginner. You will not realize why someone would traverse the graph in one direction versus another, and what and why results are bubbled up and how they are being used. The essence of these solutions are similar to the algorithm described as a black box of techniques, which I do in my solution.\n\n# Code notes\nWhen we build up the solution via DP, we need to know the incoming edges, so we also build up a reverse graph `Gr` to get this information quickly.\n\nAlso, I prefer to just do DFS to find the topological sort order. I know you can get the topological sort via the reverse post order visit. I know Khan\'s algorithm exists, but I\'ve written DFS so many times that I know I can just adapt it to find the topological sort instead of worrying about implementing Khan\'s algorithm every now and then.\n\n# Complexity\n- Time complexity: $$O(m+n)$$\n\n- Space complexity: $$O(m)$$\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n # covnert to adjacency list\n G = defaultdict(list)\n Gr = defaultdict(list) # reverse graph\n for a, b in richer:\n G[a].append(b)\n Gr[b].append(a)\n\n postorder_visit = []\n visited = set()\n for i in range(len(quiet)):\n if i not in visited:\n visited.add(i)\n self.dfs(i, G, postorder_visit, visited)\n\n # topological order is reverse of post order visit\n topological_order = postorder_visit[::-1]\n \n mins = dict()\n for i in topological_order:\n min_node = i\n min_quiet = quiet[i]\n # get incoming edges\n for from_node in Gr[i]:\n other_quiet, other_node = mins[from_node]\n if other_quiet < min_quiet:\n min_quiet = other_quiet\n min_node = other_node\n mins[i] = (min_quiet, min_node)\n \n answer = []\n for i in range(len(quiet)):\n answer.append(mins[i][1])\n return answer\n\n def dfs(self, node, G, postorder_visit, visited):\n for neighbor in G[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n self.dfs(neighbor, G, postorder_visit, visited)\n postorder_visit.append(node)\n\n```
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Beginner-friendly, Readable Python, Black-boxes, Topological Sort
loud-and-rich
0
1
# Intuition\nFind the topological sort order, then iterate through the nodes in the the topological sort order, keeping track of every node\'s minimum value/node compared to its most recent predecessors.\n\nThe topological sort allows us to use a dynamic programming technique of using previously calculated results to find a solution at the current step. Recall there are no cycles in the graph, so this type of problem is solveable via dynamic programming.\n\n# Approach\nThis problem is a lot easier if you think of it in terms of black-boxes:\n\n* The problem is described as a DAG.\n* You are asked to find a solution for each node that depends on some minimum or maximum value propagated from previous nodes; this should clue us in on using `Topological Sort` and `Dynamic Programming`.\n\nThe rest is just fitting the specifics of the problem into the blackboxes of topological sort and value propagation (dynamic programming). \n\nYou can use the topological sort and do bottom-up DP like in my solution; or, like others\' solutions, you can cache the result of DFS and do top-down DP, but then you might have to do traverse the graph in the reverse direction at some point.\n\nIMO, it can be difficult to grasp some of these other solutions if you are a beginner. You will not realize why someone would traverse the graph in one direction versus another, and what and why results are bubbled up and how they are being used. The essence of these solutions are similar to the algorithm described as a black box of techniques, which I do in my solution.\n\n# Code notes\nWhen we build up the solution via DP, we need to know the incoming edges, so we also build up a reverse graph `Gr` to get this information quickly.\n\nAlso, I prefer to just do DFS to find the topological sort order. I know you can get the topological sort via the reverse post order visit. I know Khan\'s algorithm exists, but I\'ve written DFS so many times that I know I can just adapt it to find the topological sort instead of worrying about implementing Khan\'s algorithm every now and then.\n\n# Complexity\n- Time complexity: $$O(m+n)$$\n\n- Space complexity: $$O(m)$$\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n # covnert to adjacency list\n G = defaultdict(list)\n Gr = defaultdict(list) # reverse graph\n for a, b in richer:\n G[a].append(b)\n Gr[b].append(a)\n\n postorder_visit = []\n visited = set()\n for i in range(len(quiet)):\n if i not in visited:\n visited.add(i)\n self.dfs(i, G, postorder_visit, visited)\n\n # topological order is reverse of post order visit\n topological_order = postorder_visit[::-1]\n \n mins = dict()\n for i in topological_order:\n min_node = i\n min_quiet = quiet[i]\n # get incoming edges\n for from_node in Gr[i]:\n other_quiet, other_node = mins[from_node]\n if other_quiet < min_quiet:\n min_quiet = other_quiet\n min_node = other_node\n mins[i] = (min_quiet, min_node)\n \n answer = []\n for i in range(len(quiet)):\n answer.append(mins[i][1])\n return answer\n\n def dfs(self, node, G, postorder_visit, visited):\n for neighbor in G[node]:\n if neighbor not in visited:\n visited.add(neighbor)\n self.dfs(neighbor, G, postorder_visit, visited)\n postorder_visit.append(node)\n\n```
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Solution
loud-and-rich
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n int n = quiet.size();\n vector<int> indg(n,0), ans(n,INT_MAX);\n vector<vector<int>> g(n);\n queue<int> q;\n for(int i=0;i<richer.size();i++){\n g[richer[i][0]].push_back(richer[i][1]);\n indg[richer[i][1]]++;\n }\n for(int i=0;i<n;i++){\n ans[i]=i;\n if(indg[i]==0)\n q.push(i);\n }\n while(!q.empty()){\n int curr = q.front();\n q.pop();\n for(int i : g[curr]){\n if(ans[i] == INT_MAX || quiet[ans[i]] > quiet[ans[curr]])\n ans[i] = ans[curr];\n if(--indg[i]==0)\n q.push(i);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n\n graph = defaultdict(list)\n for a, b in richer:\n graph[b].append(a)\n \n n = len(quiet)\n answer = [i for i in range(n)]\n\n seen = set()\n \n def dfs(x, seen, answer):\n seen.add(x)\n for y in graph[x]:\n if y not in seen:\n dfs(y, seen, answer)\n temp = answer[x]\n if quiet[temp] > quiet[answer[y]]:\n answer[x] = answer[y]\n \n for i in range(n):\n if i not in seen:\n dfs(i, seen, answer)\n\n return answer\n```\n\n```Java []\nclass Solution {\n public int[] loudAndRich(int[][] richer, int[] quiet) {\n int n = quiet.length;\n int[] res = new int[n];\n for(int i=0; i<n; i++){\n res[i] = i;\n }\n boolean changed = true;\n while(changed){\n changed = false;\n for(int[] rich : richer){\n if(quiet[res[rich[0]]] < quiet[res[rich[1]]]){\n res[rich[1]] = res[rich[0]];\n changed = true;\n }\n }\n } \n return res;\n }\n}\n```\n
2
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Solution
loud-and-rich
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n int n = quiet.size();\n vector<int> indg(n,0), ans(n,INT_MAX);\n vector<vector<int>> g(n);\n queue<int> q;\n for(int i=0;i<richer.size();i++){\n g[richer[i][0]].push_back(richer[i][1]);\n indg[richer[i][1]]++;\n }\n for(int i=0;i<n;i++){\n ans[i]=i;\n if(indg[i]==0)\n q.push(i);\n }\n while(!q.empty()){\n int curr = q.front();\n q.pop();\n for(int i : g[curr]){\n if(ans[i] == INT_MAX || quiet[ans[i]] > quiet[ans[curr]])\n ans[i] = ans[curr];\n if(--indg[i]==0)\n q.push(i);\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n\n graph = defaultdict(list)\n for a, b in richer:\n graph[b].append(a)\n \n n = len(quiet)\n answer = [i for i in range(n)]\n\n seen = set()\n \n def dfs(x, seen, answer):\n seen.add(x)\n for y in graph[x]:\n if y not in seen:\n dfs(y, seen, answer)\n temp = answer[x]\n if quiet[temp] > quiet[answer[y]]:\n answer[x] = answer[y]\n \n for i in range(n):\n if i not in seen:\n dfs(i, seen, answer)\n\n return answer\n```\n\n```Java []\nclass Solution {\n public int[] loudAndRich(int[][] richer, int[] quiet) {\n int n = quiet.length;\n int[] res = new int[n];\n for(int i=0; i<n; i++){\n res[i] = i;\n }\n boolean changed = true;\n while(changed){\n changed = false;\n for(int[] rich : richer){\n if(quiet[res[rich[0]]] < quiet[res[rich[1]]]){\n res[rich[1]] = res[rich[0]];\n changed = true;\n }\n }\n } \n return res;\n }\n}\n```\n
2
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
[PYTHON 3] DFS | Recursive Solution
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n @lru_cache(None)\n def dfs(node):\n if node not in graph:\n return node\n minimum = node\n for neighbour in graph[node]:\n candidate = dfs(neighbour)\n if quiet[minimum] > quiet[candidate]:\n minimum = candidate \n return minimum \n n = len(quiet)\n graph = defaultdict(list)\n for u , v in richer:\n graph[v].append(u)\n return list(map(dfs , range(n)))\n```
6
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
[PYTHON 3] DFS | Recursive Solution
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n @lru_cache(None)\n def dfs(node):\n if node not in graph:\n return node\n minimum = node\n for neighbour in graph[node]:\n candidate = dfs(neighbour)\n if quiet[minimum] > quiet[candidate]:\n minimum = candidate \n return minimum \n n = len(quiet)\n graph = defaultdict(list)\n for u , v in richer:\n graph[v].append(u)\n return list(map(dfs , range(n)))\n```
6
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Python3 Solution
loud-and-rich
0
1
# Time Complexity:\n\nO(k * n) where n is the number of nodes and k is the number of nodes with zero in-degree where k will be less than n. \n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n graph = collections.defaultdict(list)\n n = len(quiet)\n\n for x, y in richer:\n graph[y].append(x)\n\n # Find vertices with zero in-degree \n values = set()\n\n for key, val in graph.items():\n values.update(val)\n\n queue = collections.deque()\n\n for i in range(n):\n if i not in values:\n queue.append(i)\n\n # Finding least quiet person for all the nodes\n dp = [-1] * n\n while queue:\n node = queue.popleft()\n self.dfs(node, graph, dp, quiet)\n\n return dp\n\n def dfs(self, node, graph, dp, quiet):\n if dp[node] == -1:\n l = node\n\n for child in graph[node]:\n val = self.dfs(child, graph, dp, quiet)\n\n if quiet[val] < quiet[l]:\n l = val\n\n dp[node] = l\n \n return dp[node]\n \n```
0
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of the `ith` person. All the given data in richer are **logically correct** (i.e., the data will not lead you to a situation where `x` is richer than `y` and `y` is richer than `x` at the same time). Return _an integer array_ `answer` _where_ `answer[x] = y` _if_ `y` _is the least quiet person (that is, the person_ `y` _with the smallest value of_ `quiet[y]`_) among all people who definitely have equal to or more money than the person_ `x`. **Example 1:** **Input:** richer = \[\[1,0\],\[2,1\],\[3,1\],\[3,7\],\[4,3\],\[5,3\],\[6,3\]\], quiet = \[3,2,5,4,6,1,7,0\] **Output:** \[5,5,2,5,4,5,6,7\] **Explanation:** answer\[0\] = 5. Person 5 has more money than 3, which has more money than 1, which has more money than 0. The only person who is quieter (has lower quiet\[x\]) is person 7, but it is not clear if they have more money than person 0. answer\[7\] = 7. Among all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet\[x\]) is person 7. The other answers can be filled out with similar reasoning. **Example 2:** **Input:** richer = \[\], quiet = \[0\] **Output:** \[0\] **Constraints:** * `n == quiet.length` * `1 <= n <= 500` * `0 <= quiet[i] < n` * All the values of `quiet` are **unique**. * `0 <= richer.length <= n * (n - 1) / 2` * `0 <= ai, bi < n` * `ai != bi` * All the pairs of `richer` are **unique**. * The observations in `richer` are all logically consistent.
null
Python3 Solution
loud-and-rich
0
1
# Time Complexity:\n\nO(k * n) where n is the number of nodes and k is the number of nodes with zero in-degree where k will be less than n. \n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n graph = collections.defaultdict(list)\n n = len(quiet)\n\n for x, y in richer:\n graph[y].append(x)\n\n # Find vertices with zero in-degree \n values = set()\n\n for key, val in graph.items():\n values.update(val)\n\n queue = collections.deque()\n\n for i in range(n):\n if i not in values:\n queue.append(i)\n\n # Finding least quiet person for all the nodes\n dp = [-1] * n\n while queue:\n node = queue.popleft()\n self.dfs(node, graph, dp, quiet)\n\n return dp\n\n def dfs(self, node, graph, dp, quiet):\n if dp[node] == -1:\n l = node\n\n for child in graph[node]:\n val = self.dfs(child, graph, dp, quiet)\n\n if quiet[val] < quiet[l]:\n l = val\n\n dp[node] = l\n \n return dp[node]\n \n```
0
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Python Easy Solution || Binary Search || 1 Liner
peak-index-in-a-mountain-array
0
1
***Using In-built Functions:***\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n return arr.index(max(arr))\n```\n\n***By Binary Search:***\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left,right=0,len(arr)-1\n while(left<=right):\n mid=(left+right)//2\n if arr[mid-1]<=arr[mid] and arr[mid+1]<=arr[mid]:\n return mid\n elif arr[mid-1]>arr[mid]:\n right=mid\n else:\n left=mid \n```\n\n# Complexity\n- Time complexity:\nO(logn)\n\n- Space complexity:\nO(1)\n\n
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python Easy Solution || Binary Search || 1 Liner
peak-index-in-a-mountain-array
0
1
***Using In-built Functions:***\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n return arr.index(max(arr))\n```\n\n***By Binary Search:***\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left,right=0,len(arr)-1\n while(left<=right):\n mid=(left+right)//2\n if arr[mid-1]<=arr[mid] and arr[mid+1]<=arr[mid]:\n return mid\n elif arr[mid-1]>arr[mid]:\n right=mid\n else:\n left=mid \n```\n\n# Complexity\n- Time complexity:\nO(logn)\n\n- Space complexity:\nO(1)\n\n
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Easy
peak-index-in-a-mountain-array
0
1
\n\n# Code\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n return max(range(len(arr)), key=arr.__getitem__)\n```
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Easy
peak-index-in-a-mountain-array
0
1
\n\n# Code\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n return max(range(len(arr)), key=arr.__getitem__)\n```
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Python Binary Search beats 92%
peak-index-in-a-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left = 0\n right = len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if mid == 0:\n return mid + 1\n if mid == len(arr) - 1:\n return mid - 1\n if arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1]:\n return mid\n if arr[mid-1] < arr[mid] < arr[mid+1]:\n left = mid + 1\n else:\n right = mid - 1\n \n```
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python Binary Search beats 92%
peak-index-in-a-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left = 0\n right = len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if mid == 0:\n return mid + 1\n if mid == len(arr) - 1:\n return mid - 1\n if arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1]:\n return mid\n if arr[mid-1] < arr[mid] < arr[mid+1]:\n left = mid + 1\n else:\n right = mid - 1\n \n```
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Python short and clean. BinarySearch.
peak-index-in-a-mountain-array
0
1
# Approach\nTL;DR, Similar to [Editorial solution. Approach 2](https://leetcode.com/problems/peak-index-in-a-mountain-array/editorial/) but shorter.\n\n# Complexity\n- Time complexity: $$O(log_2(n))$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of arr`.\n\n# Code\n```python\nclass Solution:\n def peakIndexInMountainArray(self, arr: list[int]) -> int:\n l, r = 0, len(arr) - 1\n while l < r:\n m = (l + r) // 2\n l, r = (m + 1, r) if arr[m] < arr[m + 1] else (l, m)\n return l\n\n\n```
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python short and clean. BinarySearch.
peak-index-in-a-mountain-array
0
1
# Approach\nTL;DR, Similar to [Editorial solution. Approach 2](https://leetcode.com/problems/peak-index-in-a-mountain-array/editorial/) but shorter.\n\n# Complexity\n- Time complexity: $$O(log_2(n))$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of arr`.\n\n# Code\n```python\nclass Solution:\n def peakIndexInMountainArray(self, arr: list[int]) -> int:\n l, r = 0, len(arr) - 1\n while l < r:\n m = (l + r) // 2\n l, r = (m + 1, r) if arr[m] < arr[m + 1] else (l, m)\n return l\n\n\n```
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array
peak-index-in-a-mountain-array
0
1
# Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n i+=1\n else:\n break\n return i\n\n```
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array
peak-index-in-a-mountain-array
0
1
# Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n i+=1\n else:\n break\n return i\n\n```
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Python Simple Binary Search
peak-index-in-a-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search on the "lower boundary of $A[i] > A[i+1]$" instead of $A[i-1] < A[i] > A[i+1]$.\n\n# Complexity\n- Time complexity: $$O(logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Solution:\n def peakIndexInMountainArray(self, A: List[int]) -> int:\n lo, hi = 0, len(A)-1\n while lo < hi:\n mid = (lo+hi)//2\n if A[mid] > A[mid+1]:\n hi = mid\n else:\n lo = mid + 1\n return lo\n```\n\n# Example\n\n[1, 2, 3, 4, 5, 6]\n\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>2</td>\n <td>3</td>\n <td>5</td>\n <td>4</td>\n <td>5</td>\n <td>6</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5</td>\n <td>5</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>\n\n[6, 5, 4, 3, 2, 1]\n\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>4</td>\n <td>3</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>2</td>\n <td>0</td>\n <td>2</td>\n <td>1</td>\n <td>5</td>\n <td>4</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>3</td>\n <td>0</td>\n <td>1</td>\n <td>0</td>\n <td>6</td>\n <td>5</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>4</td>\n <td>0</td>\n <td>0</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>\n\n[1, 6, 5, 4, 3, 2]\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>5</td>\n <td>4</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>2</td>\n <td>0</td>\n <td>2</td>\n <td>1</td>\n <td>6</td>\n <td>5</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>3</td>\n <td>0</td>\n <td>1</td>\n <td>0</td>\n <td>1</td>\n <td>6</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>4</td>\n <td>1</td>\n <td>1</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. You must solve it in `O(log(arr.length))` time complexity. **Example 1:** **Input:** arr = \[0,1,0\] **Output:** 1 **Example 2:** **Input:** arr = \[0,2,1,0\] **Output:** 1 **Example 3:** **Input:** arr = \[0,10,5,2\] **Output:** 1 **Constraints:** * `3 <= arr.length <= 105` * `0 <= arr[i] <= 106` * `arr` is **guaranteed** to be a mountain array.
null
Python Simple Binary Search
peak-index-in-a-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search on the "lower boundary of $A[i] > A[i+1]$" instead of $A[i-1] < A[i] > A[i+1]$.\n\n# Complexity\n- Time complexity: $$O(logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Solution:\n def peakIndexInMountainArray(self, A: List[int]) -> int:\n lo, hi = 0, len(A)-1\n while lo < hi:\n mid = (lo+hi)//2\n if A[mid] > A[mid+1]:\n hi = mid\n else:\n lo = mid + 1\n return lo\n```\n\n# Example\n\n[1, 2, 3, 4, 5, 6]\n\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>2</td>\n <td>3</td>\n <td>5</td>\n <td>4</td>\n <td>5</td>\n <td>6</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5</td>\n <td>5</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>\n\n[6, 5, 4, 3, 2, 1]\n\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>4</td>\n <td>3</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>2</td>\n <td>0</td>\n <td>2</td>\n <td>1</td>\n <td>5</td>\n <td>4</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>3</td>\n <td>0</td>\n <td>1</td>\n <td>0</td>\n <td>6</td>\n <td>5</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>4</td>\n <td>0</td>\n <td>0</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>\n\n[1, 6, 5, 4, 3, 2]\n<table>\n <tr>\n <th>Iteration</th>\n <th>lo</th>\n <th>hi</th>\n <th>mid</th>\n <th>A[mid]</th>\n <th>A[mid+1]</th>\n <th>Branch</th>\n </tr>\n <tr>\n <td>1</td>\n <td>0</td>\n <td>5</td>\n <td>2</td>\n <td>5</td>\n <td>4</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>2</td>\n <td>0</td>\n <td>2</td>\n <td>1</td>\n <td>6</td>\n <td>5</td>\n <td>hi=mid</td>\n </tr>\n <tr>\n <td>3</td>\n <td>0</td>\n <td>1</td>\n <td>0</td>\n <td>1</td>\n <td>6</td>\n <td>lo=mid+1</td>\n </tr>\n <tr>\n <td>4</td>\n <td>1</td>\n <td>1</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n <td>-</td>\n </tr>\n</table>
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge. To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_. **Example 1:** **Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3 **Output:** 13 **Explanation:** The edge subdivisions are shown in the image above. The nodes that are reachable are highlighted in yellow. **Example 2:** **Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4 **Output:** 23 **Example 3:** **Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5 **Output:** 1 **Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable. **Constraints:** * `0 <= edges.length <= min(n * (n - 1) / 2, 104)` * `edges[i].length == 3` * `0 <= ui < vi < n` * There are **no multiple edges** in the graph. * `0 <= cnti <= 104` * `0 <= maxMoves <= 109` * `1 <= n <= 3000`
null
Easy Python solution (detailed explanation) | O(nlogn)
car-fleet
0
1
# Intuition\nThe problem requires finding the number of car fleets that will reach a given target position. Initially, one might consider calculating the time each car takes to reach the target and then group cars into fleets based on their arrival times.\n\n# Approach\nThe approach is to create pairs of positions and speeds for each car. After sorting these pairs based on positions in descending order, iterate through them. For each car, calculate the time it takes to reach the target using the formula (target - position) / speed. Keep track of the arrival times using a stack. Whenever a car\'s arrival time is less than or equal to the time of the previous car in the stack, pop the previous car from the stack, as they will form a fleet together.\n\n# Complexity\n- Time complexity: O(N log N) for sorting the pairs, where N is the number of cars.\n- Space complexity: O(N) for the pairs list and the stack.\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pairs = []\n stack = []\n \n # Create pairs of position and speed for each car\n for x in range(len(speed)):\n pairs.append([position[x], speed[x]])\n \n # Sort the pairs based on position in descending order\n pairs = sorted(pairs)[::-1]\n \n # Iterate through the sorted pairs\n for p, s in pairs:\n # Calculate time to reach the target for the current car\n time = (target - p) / s\n \n # Add the time to the stack\n stack.append(time)\n \n # Check if there are at least two cars in the stack and the current car\n # takes less or equal time than the previous car. If so, pop the previous car.\n if len(stack) >= 2 and stack[-1] <= stack[-2]:\n stack.pop()\n \n # The length of the stack represents the number of car fleets\n return len(stack)\n\n \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/4c76fb4d-0326-4b4c-97fa-1c8481381de0_1697381709.2683005.jpeg)\n
11
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Easy Python solution (detailed explanation) | O(nlogn)
car-fleet
0
1
# Intuition\nThe problem requires finding the number of car fleets that will reach a given target position. Initially, one might consider calculating the time each car takes to reach the target and then group cars into fleets based on their arrival times.\n\n# Approach\nThe approach is to create pairs of positions and speeds for each car. After sorting these pairs based on positions in descending order, iterate through them. For each car, calculate the time it takes to reach the target using the formula (target - position) / speed. Keep track of the arrival times using a stack. Whenever a car\'s arrival time is less than or equal to the time of the previous car in the stack, pop the previous car from the stack, as they will form a fleet together.\n\n# Complexity\n- Time complexity: O(N log N) for sorting the pairs, where N is the number of cars.\n- Space complexity: O(N) for the pairs list and the stack.\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pairs = []\n stack = []\n \n # Create pairs of position and speed for each car\n for x in range(len(speed)):\n pairs.append([position[x], speed[x]])\n \n # Sort the pairs based on position in descending order\n pairs = sorted(pairs)[::-1]\n \n # Iterate through the sorted pairs\n for p, s in pairs:\n # Calculate time to reach the target for the current car\n time = (target - p) / s\n \n # Add the time to the stack\n stack.append(time)\n \n # Check if there are at least two cars in the stack and the current car\n # takes less or equal time than the previous car. If so, pop the previous car.\n if len(stack) >= 2 and stack[-1] <= stack[-2]:\n stack.pop()\n \n # The length of the stack represents the number of car fleets\n return len(stack)\n\n \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/4c76fb4d-0326-4b4c-97fa-1c8481381de0_1697381709.2683005.jpeg)\n
11
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Python3 Simple Solution | 95% | stacks | Easy And Elegant With Explanation
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To form a car fleet, cars must be at the same target position at some point in the future.\n- Sort the cars based on their starting positions in descending order.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a list of pairs, where each pair consists of a car\'s initial position (position) and its speed (speed).\n\n2. Sort the list of pairs in descending order based on the initial positions. This is done to process cars starting from the back of the road first.\n\n3. Initialize an empty stack to keep track of the time it takes for each car to reach the target position.\n\n4. Iterate through the sorted list of pairs. For each car:\n\n- Calculate the time it will take to reach the target position using the formula (target - position) / speed.\n- Push this time onto the stack.\n- Check if there are at least two cars in the stack (since a fleet requires at least two cars).\n- If the time taken by the current car is less than or equal to the time taken by the car ahead of it (top of the stack), it means they will form a fleet.\n- If they will form a fleet, pop the top car from the stack.\n\n5. After processing all the cars, the length of the stack will give you the number of car fleets formed.\n\n6. Return the length of the stack as the result.\n\n---\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log(n))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n---\n\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pair = []\n for p , s in zip(position , speed):\n pair.append([p,s])\n\n stack = []\n for p , s in sorted(pair)[::-1]:\n stack.append((target - p)/s)\n if len(stack) >=2 and stack[-1] <= stack[-2]:\n stack.pop()\n\n return len(stack) \n \n```
3
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Python3 Simple Solution | 95% | stacks | Easy And Elegant With Explanation
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To form a car fleet, cars must be at the same target position at some point in the future.\n- Sort the cars based on their starting positions in descending order.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a list of pairs, where each pair consists of a car\'s initial position (position) and its speed (speed).\n\n2. Sort the list of pairs in descending order based on the initial positions. This is done to process cars starting from the back of the road first.\n\n3. Initialize an empty stack to keep track of the time it takes for each car to reach the target position.\n\n4. Iterate through the sorted list of pairs. For each car:\n\n- Calculate the time it will take to reach the target position using the formula (target - position) / speed.\n- Push this time onto the stack.\n- Check if there are at least two cars in the stack (since a fleet requires at least two cars).\n- If the time taken by the current car is less than or equal to the time taken by the car ahead of it (top of the stack), it means they will form a fleet.\n- If they will form a fleet, pop the top car from the stack.\n\n5. After processing all the cars, the length of the stack will give you the number of car fleets formed.\n\n6. Return the length of the stack as the result.\n\n---\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log(n))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n---\n\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pair = []\n for p , s in zip(position , speed):\n pair.append([p,s])\n\n stack = []\n for p , s in sorted(pair)[::-1]:\n stack.append((target - p)/s)\n if len(stack) >=2 and stack[-1] <= stack[-2]:\n stack.pop()\n\n return len(stack) \n \n```
3
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Stack Solution | O(nlogn) | Python3
car-fleet
0
1
# Intuition\nWhen first approaching the car fleet problem, the key is to recognize that cars form fleets when a faster car catches up to a slower one. Since cars cannot overtake each other, once they form a fleet, they stay together until the destination. The primary challenge lies in determining these fleet formations based on the positions and speeds of the cars. Intuitively, sorting the cars by their starting positions seems crucial, as it allows us to process them in the order they would potentially form fleets.\n\n# Approach\n1. Sort Cars by Position:\n\nFirst, create pairs of positions and speeds, then sort these pairs in descending order of position. This step arranges cars starting from the one closest to the target to the farthest.\n\n2. Calculate Time to Reach Target:\n\nFor each car, calculate the time it takes to reach the destination. This is done using the formula (target - position) / speed.\n\n3. Use a Stack to Form Fleets:\n\nIterate over these times, using a stack to keep track of different fleets. If a car takes less time or equal time to reach the target compared to the car at the top of the stack, it joins the same fleet.\n\nIf a car takes more time, it forms a new fleet, and its time is pushed onto the stack.\n\n4. Counting Fleets:\n\nThe number of elements in the stack at the end of the iteration gives the total number of car fleets.\n\n# Complexity\n- Time complexity: O(nlogn)\n\nThe sorting of cars is the most time-consuming part of the algorithm, with a complexity of O(nlogn), where n is the number of cars. The iteration over the sorted list of cars is O(n). Thus, the overall time complexity is dominated by the sorting step, making it O(nlogn).\n\n- Space complexity: O(n)\n\nThe space complexity is primarily determined by the space used for the stack.In the worst case, every car forms its own fleet, leading to a stack size of n.\n\nTherefore, the space complexity is O(n).\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n cars = sorted(zip(position, speed), reverse=True)\n stack = []\n\n for pos, spd in cars:\n time = (target - pos) / spd\n\n if stack and time <= stack[-1]:\n continue\n\n stack.append(time)\n\n return len(stack)\n```
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Stack Solution | O(nlogn) | Python3
car-fleet
0
1
# Intuition\nWhen first approaching the car fleet problem, the key is to recognize that cars form fleets when a faster car catches up to a slower one. Since cars cannot overtake each other, once they form a fleet, they stay together until the destination. The primary challenge lies in determining these fleet formations based on the positions and speeds of the cars. Intuitively, sorting the cars by their starting positions seems crucial, as it allows us to process them in the order they would potentially form fleets.\n\n# Approach\n1. Sort Cars by Position:\n\nFirst, create pairs of positions and speeds, then sort these pairs in descending order of position. This step arranges cars starting from the one closest to the target to the farthest.\n\n2. Calculate Time to Reach Target:\n\nFor each car, calculate the time it takes to reach the destination. This is done using the formula (target - position) / speed.\n\n3. Use a Stack to Form Fleets:\n\nIterate over these times, using a stack to keep track of different fleets. If a car takes less time or equal time to reach the target compared to the car at the top of the stack, it joins the same fleet.\n\nIf a car takes more time, it forms a new fleet, and its time is pushed onto the stack.\n\n4. Counting Fleets:\n\nThe number of elements in the stack at the end of the iteration gives the total number of car fleets.\n\n# Complexity\n- Time complexity: O(nlogn)\n\nThe sorting of cars is the most time-consuming part of the algorithm, with a complexity of O(nlogn), where n is the number of cars. The iteration over the sorted list of cars is O(n). Thus, the overall time complexity is dominated by the sorting step, making it O(nlogn).\n\n- Space complexity: O(n)\n\nThe space complexity is primarily determined by the space used for the stack.In the worst case, every car forms its own fleet, leading to a stack size of n.\n\nTherefore, the space complexity is O(n).\n\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n cars = sorted(zip(position, speed), reverse=True)\n stack = []\n\n for pos, spd in cars:\n time = (target - pos) / spd\n\n if stack and time <= stack[-1]:\n continue\n\n stack.append(time)\n\n return len(stack)\n```
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Gk's python soln
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith speed, distance can get time to reach target. Time is always a monotonic value -> increasing or decreasing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMonotonic stack\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pos_speed = [(pos, speed) for pos, speed in zip(position, speed)]\n pos_speed.sort(reverse=True, key=lambda x: x[0])\n stack = []\n \n for pos, speed in pos_speed:\n time = (target - pos) / speed\n if stack and stack[-1] >= time:\n time = stack.pop()\n stack.append(time)\n return len(stack)\n```
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Gk's python soln
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith speed, distance can get time to reach target. Time is always a monotonic value -> increasing or decreasing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMonotonic stack\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n pos_speed = [(pos, speed) for pos, speed in zip(position, speed)]\n pos_speed.sort(reverse=True, key=lambda x: x[0])\n stack = []\n \n for pos, speed in pos_speed:\n time = (target - pos) / speed\n if stack and stack[-1] >= time:\n time = stack.pop()\n stack.append(time)\n return len(stack)\n```
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
🔥BEATS 100% | [ Python / Java / C++ / JavaScript / C#/ Go/TypeScript ]
car-fleet
1
1
```Python []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(speed)\n v = [(position[i], speed[i]) for i in range(n)]\n v.sort()\n time = [float(target - v[i][0]) / v[i][1] for i in range(n)]\n\n curr = float(\'-inf\')\n res = 0\n\n for i in range(n - 1, -1, -1):\n if time[i] > curr:\n curr = time[i]\n res += 1\n\n return res\n```\n```Java []\nclass Solution {\n public int carFleet(int target, int[] position, int[] speed) {\n int n = speed.length;\n List<Pair<Integer, Integer>> v = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n v.add(new Pair<>(position[i], speed[i]));\n }\n\n Collections.sort(v, (a, b) -> a.getKey() - b.getKey());\n\n List<Float> time = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n time.add((float) (target - v.get(i).getKey()) / v.get(i).getValue());\n }\n\n float curr = Float.NEGATIVE_INFINITY;\n int res = 0;\n\n for (int i = n - 1; i >= 0; i--) {\n if (time.get(i) > curr) {\n curr = time.get(i);\n res++;\n }\n }\n\n return res;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n int n = speed.size();\n vector<pair<int , int>> v;\n for(int i =0 ; i< n ; i++){\n v.push_back({position[i] , speed[i]});\n }\n sort(v.begin() , v.end());\n vector<float> time;\n for(int i =0 ; i< n ; i++){\n time.push_back((target*1.0 - v[i].first*1.0)/v[i].second*1.0); \n }\n\n float curr = INT_MIN;\n int res = 0;\n\n for(int i = n-1 ; i>=0 ; i--){\n if(time[i] > curr) {\n curr = time[i];\n res++;\n } \n }\n return res;\n }\n};\n```\n```JavaScript []\nvar carFleet = function(target, position, speed) {\n const n = speed.length;\n const v = [];\n for (let i = 0; i < n; i++) {\n v.push([position[i], speed[i]]);\n }\n v.sort((a, b) => a[0] - b[0]);\n const time = [];\n for (let i = 0; i < n; i++) {\n time.push((target - v[i][0]) / v[i][1]);\n }\n\n let curr = Number.NEGATIVE_INFINITY;\n let res = 0;\n\n for (let i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n};\n```\n```C# []\npublic class Solution {\n public int CarFleet(int target, int[] position, int[] speed) {\n int n = speed.Length;\n List<(int, int)> v = new List<(int, int)>();\n\n for (int i = 0; i < n; i++) {\n v.Add((position[i], speed[i]));\n }\n\n v.Sort();\n List<double> time = new List<double>();\n\n for (int i = 0; i < n; i++) {\n time.Add((target * 1.0 - v[i].Item1 * 1.0) / v[i].Item2 * 1.0);\n }\n\n double curr = double.MinValue;\n int res = 0;\n\n for (int i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n }\n}\n```\n```Go []\nimport "sort"\n\nfunc carFleet(target int, position []int, speed []int) int {\n n := len(speed)\n v := make([][2]int, n)\n\n for i := 0; i < n; i++ {\n v[i] = [2]int{position[i], speed[i]}\n }\n\n sort.Slice(v, func(i, j int) bool {\n return v[i][0] < v[j][0]\n })\n\n time := make([]float64, n)\n\n for i := 0; i < n; i++ {\n time[i] = float64(target-v[i][0]) / float64(v[i][1])\n }\n\n curr := -1.0\n res := 0\n\n for i := n - 1; i >= 0; i-- {\n if time[i] > curr {\n curr = time[i]\n res++\n }\n }\n\n return res\n}\n```\n```TypeScript []\nclass Solution {\n carFleet(target: number, position: number[], speed: number[]): number {\n const n: number = speed.length;\n const v: [number, number][] = [];\n\n for (let i = 0; i < n; i++) {\n v.push([position[i], speed[i]]);\n }\n\n v.sort((a, b) => a[0] - b[0]);\n\n const time: number[] = [];\n\n for (let i = 0; i < n; i++) {\n time.push((target - v[i][0]) / v[i][1]);\n }\n\n let curr: number = Number.NEGATIVE_INFINITY;\n let res: number = 0;\n\n for (let i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n }\n}\n```\n\n\n
3
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
🔥BEATS 100% | [ Python / Java / C++ / JavaScript / C#/ Go/TypeScript ]
car-fleet
1
1
```Python []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(speed)\n v = [(position[i], speed[i]) for i in range(n)]\n v.sort()\n time = [float(target - v[i][0]) / v[i][1] for i in range(n)]\n\n curr = float(\'-inf\')\n res = 0\n\n for i in range(n - 1, -1, -1):\n if time[i] > curr:\n curr = time[i]\n res += 1\n\n return res\n```\n```Java []\nclass Solution {\n public int carFleet(int target, int[] position, int[] speed) {\n int n = speed.length;\n List<Pair<Integer, Integer>> v = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n v.add(new Pair<>(position[i], speed[i]));\n }\n\n Collections.sort(v, (a, b) -> a.getKey() - b.getKey());\n\n List<Float> time = new ArrayList<>();\n\n for (int i = 0; i < n; i++) {\n time.add((float) (target - v.get(i).getKey()) / v.get(i).getValue());\n }\n\n float curr = Float.NEGATIVE_INFINITY;\n int res = 0;\n\n for (int i = n - 1; i >= 0; i--) {\n if (time.get(i) > curr) {\n curr = time.get(i);\n res++;\n }\n }\n\n return res;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n int n = speed.size();\n vector<pair<int , int>> v;\n for(int i =0 ; i< n ; i++){\n v.push_back({position[i] , speed[i]});\n }\n sort(v.begin() , v.end());\n vector<float> time;\n for(int i =0 ; i< n ; i++){\n time.push_back((target*1.0 - v[i].first*1.0)/v[i].second*1.0); \n }\n\n float curr = INT_MIN;\n int res = 0;\n\n for(int i = n-1 ; i>=0 ; i--){\n if(time[i] > curr) {\n curr = time[i];\n res++;\n } \n }\n return res;\n }\n};\n```\n```JavaScript []\nvar carFleet = function(target, position, speed) {\n const n = speed.length;\n const v = [];\n for (let i = 0; i < n; i++) {\n v.push([position[i], speed[i]]);\n }\n v.sort((a, b) => a[0] - b[0]);\n const time = [];\n for (let i = 0; i < n; i++) {\n time.push((target - v[i][0]) / v[i][1]);\n }\n\n let curr = Number.NEGATIVE_INFINITY;\n let res = 0;\n\n for (let i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n};\n```\n```C# []\npublic class Solution {\n public int CarFleet(int target, int[] position, int[] speed) {\n int n = speed.Length;\n List<(int, int)> v = new List<(int, int)>();\n\n for (int i = 0; i < n; i++) {\n v.Add((position[i], speed[i]));\n }\n\n v.Sort();\n List<double> time = new List<double>();\n\n for (int i = 0; i < n; i++) {\n time.Add((target * 1.0 - v[i].Item1 * 1.0) / v[i].Item2 * 1.0);\n }\n\n double curr = double.MinValue;\n int res = 0;\n\n for (int i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n }\n}\n```\n```Go []\nimport "sort"\n\nfunc carFleet(target int, position []int, speed []int) int {\n n := len(speed)\n v := make([][2]int, n)\n\n for i := 0; i < n; i++ {\n v[i] = [2]int{position[i], speed[i]}\n }\n\n sort.Slice(v, func(i, j int) bool {\n return v[i][0] < v[j][0]\n })\n\n time := make([]float64, n)\n\n for i := 0; i < n; i++ {\n time[i] = float64(target-v[i][0]) / float64(v[i][1])\n }\n\n curr := -1.0\n res := 0\n\n for i := n - 1; i >= 0; i-- {\n if time[i] > curr {\n curr = time[i]\n res++\n }\n }\n\n return res\n}\n```\n```TypeScript []\nclass Solution {\n carFleet(target: number, position: number[], speed: number[]): number {\n const n: number = speed.length;\n const v: [number, number][] = [];\n\n for (let i = 0; i < n; i++) {\n v.push([position[i], speed[i]]);\n }\n\n v.sort((a, b) => a[0] - b[0]);\n\n const time: number[] = [];\n\n for (let i = 0; i < n; i++) {\n time.push((target - v[i][0]) / v[i][1]);\n }\n\n let curr: number = Number.NEGATIVE_INFINITY;\n let res: number = 0;\n\n for (let i = n - 1; i >= 0; i--) {\n if (time[i] > curr) {\n curr = time[i];\n res++;\n }\n }\n\n return res;\n }\n}\n```\n\n\n
3
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
🚀Beats 97% Time, 98% Space: Python Solution Races to Efficiency! O(nlogn) time
car-fleet
0
1
# Intuition\nmy initial thought was to establish a connection between the cars\' positions, speeds, and the time it takes to reach the destination. This line of thinking led me to consider a sorting-based approach combined with time comparison, which ultimately aligned well with the solution provided in the code.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sorting by Position: The code starts by sorting the cars based on their positions in descending order. This is a crucial step because it allows us to process the cars that are closer to the destination first.\n\n2. Comparing Time to Reach Destination: The code then iterates through the sorted cars. For each car, it calculates the time it will take to reach the destination based on its position and speed. It compares this time with the time it would take for the previous car in the sorted order to reach the destination. If the current car\'s time is greater, it means this car will not catch up with the previous car and will form a new fleet.\n\n3. Updating Fleet Count: When a car forms a new fleet, the fleet count is incremented. The current car becomes the reference car for the next comparison.\n\n4. Returning Fleet Count: Finally, the code returns the total number of fleets that will reach the destination.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(position)\n inds = list(range(n))\n inds.sort(key=lambda i: position[i], reverse=True)\n \n cur = inds[0]\n result = 1\n \n for i in range(1, n):\n idx = inds[i]\n if (target - position[idx]) * speed[cur] > (target - position[cur]) * speed[idx]:\n result += 1\n cur = idx\n \n return result\n```
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
🚀Beats 97% Time, 98% Space: Python Solution Races to Efficiency! O(nlogn) time
car-fleet
0
1
# Intuition\nmy initial thought was to establish a connection between the cars\' positions, speeds, and the time it takes to reach the destination. This line of thinking led me to consider a sorting-based approach combined with time comparison, which ultimately aligned well with the solution provided in the code.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sorting by Position: The code starts by sorting the cars based on their positions in descending order. This is a crucial step because it allows us to process the cars that are closer to the destination first.\n\n2. Comparing Time to Reach Destination: The code then iterates through the sorted cars. For each car, it calculates the time it will take to reach the destination based on its position and speed. It compares this time with the time it would take for the previous car in the sorted order to reach the destination. If the current car\'s time is greater, it means this car will not catch up with the previous car and will form a new fleet.\n\n3. Updating Fleet Count: When a car forms a new fleet, the fleet count is incremented. The current car becomes the reference car for the next comparison.\n\n4. Returning Fleet Count: Finally, the code returns the total number of fleets that will reach the destination.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(position)\n inds = list(range(n))\n inds.sort(key=lambda i: position[i], reverse=True)\n \n cur = inds[0]\n result = 1\n \n for i in range(1, n):\n idx = inds[i]\n if (target - position[idx]) * speed[cur] > (target - position[cur]) * speed[idx]:\n result += 1\n cur = idx\n \n return result\n```
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
[Python3] Increasing stack
car-fleet
0
1
```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n """\n sort the start position.\n the car behind can only catch up no exceed.\n so if the car start late and speed is faster, it will catch up the car ahead of itself and they become a fleet.\n there is a target(or desitination),so use arrive time to measure. \n \n start late but arrive ealier means the car is behind and will catch up before arriving the destination.\n \n position 10 8 5 3 0\n distance 2 4 7 9 12\n speed. 2 4 1 3 1\n time. 1 1 7 3 12\n ^ ^\n | |\n catch catch up the previous car before target, join the fleet\n\t\tstack = [1] , [1],[1,7],[1,7][1,7,12] \t\t\t \n \n """\n stack = []\n for pos, v in sorted(zip(position, speed),reverse = True):\n\n dist = target - pos\n time = dist / v \n \n if not stack:\n stack.append(time)\n elif time > stack[-1]:\n stack.append(time)\n\n return len(stack)\n```
23
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
[Python3] Increasing stack
car-fleet
0
1
```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n """\n sort the start position.\n the car behind can only catch up no exceed.\n so if the car start late and speed is faster, it will catch up the car ahead of itself and they become a fleet.\n there is a target(or desitination),so use arrive time to measure. \n \n start late but arrive ealier means the car is behind and will catch up before arriving the destination.\n \n position 10 8 5 3 0\n distance 2 4 7 9 12\n speed. 2 4 1 3 1\n time. 1 1 7 3 12\n ^ ^\n | |\n catch catch up the previous car before target, join the fleet\n\t\tstack = [1] , [1],[1,7],[1,7][1,7,12] \t\t\t \n \n """\n stack = []\n for pos, v in sorted(zip(position, speed),reverse = True):\n\n dist = target - pos\n time = dist / v \n \n if not stack:\n stack.append(time)\n elif time > stack[-1]:\n stack.append(time)\n\n return len(stack)\n```
23
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Solution
car-fleet
1
1
```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n \n int len = position.size();\n\n vector<pair<int, double>> v(len);\n for(int i = 0; i < len; i++)\n v[i] = {position[i], (double)(target-position[i])/speed[i]};\n \n sort(v.begin(), v.end());\n double time = v.back().second;\n int cnt = 1;\n for(int i = len-2; i>=0; i--){\n if (v[i].second > time){\n time = v[i].second;\n cnt++;\n }\n }\n return cnt;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n car_stack = []\n car_list = list(zip(position, speed))\n sort_car_list = sorted(car_list, reverse = True, key = lambda x:x[0])\n\n ex_max_step = float("-inf")\n for carposi, carspe in sort_car_list:\n current_step = (target - carposi) / carspe\n if current_step > ex_max_step:\n ex_max_step = current_step\n car_stack.append(current_step)\n return len(car_stack)\n```\n\n```Java []\nclass Solution {\n public int carFleet(int target, int[] position, int[] speed) {\n if(position.length==1) return 1;\n float time[]=new float[target+1];\n float max=0;\n for(int i=0;i<position.length;i++){\n time[position[i]] = (float)(target-position[i])/speed[i];\n }\n int count=0;\n for(int i=target;i>=0;i--){\n if(time[i]>max){\n count++;\n max=time[i];\n }\n }\n return count;\n }\n}\n```\n
2
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Solution
car-fleet
1
1
```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n \n int len = position.size();\n\n vector<pair<int, double>> v(len);\n for(int i = 0; i < len; i++)\n v[i] = {position[i], (double)(target-position[i])/speed[i]};\n \n sort(v.begin(), v.end());\n double time = v.back().second;\n int cnt = 1;\n for(int i = len-2; i>=0; i--){\n if (v[i].second > time){\n time = v[i].second;\n cnt++;\n }\n }\n return cnt;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n car_stack = []\n car_list = list(zip(position, speed))\n sort_car_list = sorted(car_list, reverse = True, key = lambda x:x[0])\n\n ex_max_step = float("-inf")\n for carposi, carspe in sort_car_list:\n current_step = (target - carposi) / carspe\n if current_step > ex_max_step:\n ex_max_step = current_step\n car_stack.append(current_step)\n return len(car_stack)\n```\n\n```Java []\nclass Solution {\n public int carFleet(int target, int[] position, int[] speed) {\n if(position.length==1) return 1;\n float time[]=new float[target+1];\n float max=0;\n for(int i=0;i<position.length;i++){\n time[position[i]] = (float)(target-position[i])/speed[i];\n }\n int count=0;\n for(int i=target;i>=0;i--){\n if(time[i]>max){\n count++;\n max=time[i];\n }\n }\n return count;\n }\n}\n```\n
2
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
[Python3] greedy O(NlogN)
car-fleet
0
1
Algo \nSort the position-speed pair in reverse order. Compute the times for the cars to arrive at target. If a car located further away from target arrives at target with less time compared to cars closer to target. They will bump into a group. \n\nImplementation (156ms, 94.92%)\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n ans = prev = 0\n for pp, ss in sorted(zip(position, speed), reverse=True): \n tt = (target - pp)/ss # time to arrive at target \n if prev < tt: \n ans += 1\n prev = tt\n return ans \n```\n\nAnalysis\nTime complexity `O(NlogN)` due to sorting\nSpace complexity `O(N)` due to usage of `sorted()`
28
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
[Python3] greedy O(NlogN)
car-fleet
0
1
Algo \nSort the position-speed pair in reverse order. Compute the times for the cars to arrive at target. If a car located further away from target arrives at target with less time compared to cars closer to target. They will bump into a group. \n\nImplementation (156ms, 94.92%)\n```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n ans = prev = 0\n for pp, ss in sorted(zip(position, speed), reverse=True): \n tt = (target - pp)/ss # time to arrive at target \n if prev < tt: \n ans += 1\n prev = tt\n return ans \n```\n\nAnalysis\nTime complexity `O(NlogN)` due to sorting\nSpace complexity `O(N)` due to usage of `sorted()`
28
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Solution
k-similar-strings
1
1
```C++ []\nclass Solution {\npublic:\n vector<pair<int, int> > edges;\n int n, m;\n map<tuple<int, int, int>, int> memo;\n int dfs(int bitmask, int v, int start) {\n if (v == -1) {\n for (int i = 0; i < m; ++i) {\n if (!(bitmask >> i & 1)) {\n return dfs(bitmask | (1<<i), edges[i].second, edges[i].first) + 1;\n }\n }\n }\n if (bitmask == (1<<m) - 1) {\n return 0;\n }\n assert(v!=-1 && start!=-1);\n\n if (memo.count({bitmask, v, start})) {\n return memo[{bitmask, v, start}];\n }\n int result = m;\n for (int i = 0; i < edges.size(); ++i) {\n if (bitmask>>i&1) continue;\n if (edges[i].first != v) continue;\n if (edges[i].second == start) {\n result = min(result, dfs(bitmask | (1<<i), -1, -1));\n break;\n }\n }\n if (result == m) {\n for (int i = 0; i < edges.size(); ++i) {\n if (bitmask>>i&1) continue;\n if (edges[i].first != v) continue;\n result = min(result, dfs(bitmask | (1<<i), edges[i].second, start) + 1);\n }\n }\n return memo[{bitmask, v, start}] = result;\n }\n int kSimilarity(string s1, string s2) {\n n = s1.size();\n for (int i = 0; i < n; ++i) {\n if (s1[i] != s2[i]) {\n edges.push_back({s1[i] - \'a\', s2[i] - \'a\'});\n }\n }\n m = edges.size();\n\n return dfs(0, -1, -1);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n @lru_cache(None)\n def helper(s1, s2):\n if len(s1) == 0:\n return 0\n if s1 == s2:\n return 0\n if s1[0] == s2[0]:\n return helper(s1[1:], s2[1:])\n for i in range(1, len(s2)):\n if s1[0] == s2[i] and s1[i] == s2[0]:\n return 1 + helper(s1[1:i] + s1[i + 1 :], s2[1:i] + s2[i + 1 :])\n\n ans = 20\n for i in range(1, len(s2)):\n if s1[0] == s2[i]:\n ans = min(ans, 1 + helper(s1[1:], s2[1:i] + s2[0] + s2[i + 1 :]))\n\n return ans\n\n return helper(s1, s2)\n```\n\n```Java []\nclass Solution {\n public int kSimilarity(String a, String b) {\n int ans = 0;\n char[] achars = a.toCharArray();\n char[] bchars = b.toCharArray();\n ans += getAllPerfectMatches(achars, bchars);\n for (int i = 0; i < achars.length; i++) {\n if (achars[i] == bchars[i]) {\n continue;\n }\n return ans + checkAllOptions(achars, bchars, i, b);\n }\n return ans;\n }\n private int checkAllOptions(char[] achars, char[] bchars, int i, String b) {\n int ans = Integer.MAX_VALUE;\n for (int j = i + 1; j < achars.length; j++) {\n if (achars[j] == bchars[i] && achars[j] != bchars[j]) {\n swap(achars, i, j);\n ans = Math.min(ans, 1 + kSimilarity(new String(achars), b));\n swap(achars, i, j);\n }\n }\n return ans;\n }\n private int getAllPerfectMatches(char[] achars, char[] bchars) {\n int ans = 0;\n for (int i = 0; i < achars.length; i++) {\n if (achars[i] == bchars[i]) {\n continue;\n }\n for (int j = i + 1; j < achars.length; j++) {\n if (achars[j] == bchars[i] && bchars[j] == achars[i]) {\n swap(achars, i, j);\n ans++;\n break;\n }\n }\n }\n return ans;\n }\n private void swap(char[] a, int i, int j) {\n char temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n}\n```\n
1
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Solution
k-similar-strings
1
1
```C++ []\nclass Solution {\npublic:\n vector<pair<int, int> > edges;\n int n, m;\n map<tuple<int, int, int>, int> memo;\n int dfs(int bitmask, int v, int start) {\n if (v == -1) {\n for (int i = 0; i < m; ++i) {\n if (!(bitmask >> i & 1)) {\n return dfs(bitmask | (1<<i), edges[i].second, edges[i].first) + 1;\n }\n }\n }\n if (bitmask == (1<<m) - 1) {\n return 0;\n }\n assert(v!=-1 && start!=-1);\n\n if (memo.count({bitmask, v, start})) {\n return memo[{bitmask, v, start}];\n }\n int result = m;\n for (int i = 0; i < edges.size(); ++i) {\n if (bitmask>>i&1) continue;\n if (edges[i].first != v) continue;\n if (edges[i].second == start) {\n result = min(result, dfs(bitmask | (1<<i), -1, -1));\n break;\n }\n }\n if (result == m) {\n for (int i = 0; i < edges.size(); ++i) {\n if (bitmask>>i&1) continue;\n if (edges[i].first != v) continue;\n result = min(result, dfs(bitmask | (1<<i), edges[i].second, start) + 1);\n }\n }\n return memo[{bitmask, v, start}] = result;\n }\n int kSimilarity(string s1, string s2) {\n n = s1.size();\n for (int i = 0; i < n; ++i) {\n if (s1[i] != s2[i]) {\n edges.push_back({s1[i] - \'a\', s2[i] - \'a\'});\n }\n }\n m = edges.size();\n\n return dfs(0, -1, -1);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n @lru_cache(None)\n def helper(s1, s2):\n if len(s1) == 0:\n return 0\n if s1 == s2:\n return 0\n if s1[0] == s2[0]:\n return helper(s1[1:], s2[1:])\n for i in range(1, len(s2)):\n if s1[0] == s2[i] and s1[i] == s2[0]:\n return 1 + helper(s1[1:i] + s1[i + 1 :], s2[1:i] + s2[i + 1 :])\n\n ans = 20\n for i in range(1, len(s2)):\n if s1[0] == s2[i]:\n ans = min(ans, 1 + helper(s1[1:], s2[1:i] + s2[0] + s2[i + 1 :]))\n\n return ans\n\n return helper(s1, s2)\n```\n\n```Java []\nclass Solution {\n public int kSimilarity(String a, String b) {\n int ans = 0;\n char[] achars = a.toCharArray();\n char[] bchars = b.toCharArray();\n ans += getAllPerfectMatches(achars, bchars);\n for (int i = 0; i < achars.length; i++) {\n if (achars[i] == bchars[i]) {\n continue;\n }\n return ans + checkAllOptions(achars, bchars, i, b);\n }\n return ans;\n }\n private int checkAllOptions(char[] achars, char[] bchars, int i, String b) {\n int ans = Integer.MAX_VALUE;\n for (int j = i + 1; j < achars.length; j++) {\n if (achars[j] == bchars[i] && achars[j] != bchars[j]) {\n swap(achars, i, j);\n ans = Math.min(ans, 1 + kSimilarity(new String(achars), b));\n swap(achars, i, j);\n }\n }\n return ans;\n }\n private int getAllPerfectMatches(char[] achars, char[] bchars) {\n int ans = 0;\n for (int i = 0; i < achars.length; i++) {\n if (achars[i] == bchars[i]) {\n continue;\n }\n for (int j = i + 1; j < achars.length; j++) {\n if (achars[j] == bchars[i] && bchars[j] == achars[i]) {\n swap(achars, i, j);\n ans++;\n break;\n }\n }\n }\n return ans;\n }\n private void swap(char[] a, int i, int j) {\n char temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n}\n```\n
1
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
Python BFS Solution (fully explained & commented)
k-similar-strings
0
1
# **Intuition**\n\nFirst, let\'s understand how the BFS works with some examples.\n\n\ts1: "aaabcbea"\n\ts2: "aaaebcba"\n\nA **swap** is when we switch two letters, s1[i] and s1[j]. Not all **swaps** are useful to us. In the above example, we don\'t want to swap s1[0] with any s1[j].\n\n**Swaps** are only useful if they satisfy these conditions:\n1. s1[i] != s2[i] *(the letter isn\'t already in the correct position)*\n2. s1[i] = s2[j] *(we are moving s1[i] to a location where it matches)*\n3. s1[j]! = s2[j] *(the SECOND letter isn\'t already in the correct position*)\n\n**Our approach is to find the first non-matching letter in s1. Then, we try all possible "useful" swaps.**\n\nSo, in the above example, the first non-matching letter is s1[3], or "b". Performing a **swap** with s1[4] and s1[6] are both "useful", because the "b" is moved to the right position.\n\nWe do both of these swaps. This gives us two strings:\n\n\toriginal s1: "aaabcbea"\n\ts2: "aaaebcba"\n\t\n\tnew string 1: "aaacbbea"\n\tnew string 2: "aaaecbba"\n\t\nWe keep track that we made **1** change so far. Then, we repeat the same process on BOTH "new string 1" and "new string 2".\n\nFor new string 1, there is only one possible swap.\n\n\tnew string 1: "aaacbbea"\n\ts2: "aaaebcba"\n\t\n\tnew new string 1: "aaaebbca"\n\t\nFor new string 2, there is also only one possible swap.\n\n\tnew string 2: "aaaecbba"\n\ts2: "aaaebcba"\n\t\n\tnew new string 2: "aaaebcba"\n\t\nAt this point, new new string 2 matches s2, so we are done. We return the number of swaps made so far, which is 2.\n\n\n# **Code**\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n #the deque keeps track of the set of strings that we want to perform swaps on\n #at the start, the deque contains only s1\n deque = collections.deque([s1])\n \n #this set wasn\'t mentioned in the "intuition" part. it helps us avoid doing repeated work by adding the same strings to our deque\n seen = set() \n \n answ=0 #counter for the number of "swaps" done so far\n \n \n while deque:\n for _ in range(len(deque)): #loops through each string in the deque\n \n string = deque.popleft() #gets the first string in the deque\n if string ==s2: return answ\n \n #finds the first non-matching letter in s1\n #this satisfies condition 1 of a "useful" swap\n #ex: this would be s1[3] in the above example\n i=0\n while string[i]==s2[i]:\n i+=1\n \n #checks all the other letters for potential swaps\n for j in range(i+1, len(string)):\n if string[i]==s2[j]!=s1[j]: #checks conditions 2 and 3 of a useful swap\n \n #swaps the letters at positions i and j\n new = string[:i] + string[j] + string[i+1:j] + string[i] + string[j+1:]\n \n #adds the "new string" if it was not previously added\n if new not in seen:\n seen.add(new)\n deque.append(new)\n \n #record that one more swap was done for each string in the deque\n answ+=1\n\n```\n\n**Still Confused?**\nIf you thoroughly read through this explanation and don\'t get it, I\'d recommend checking out this explanation on 2x speed:\nhttps://www.youtube.com/watch?v=GacKZ1-p3-0&t=1292s&ab_channel=HappyCoding
27
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Python BFS Solution (fully explained & commented)
k-similar-strings
0
1
# **Intuition**\n\nFirst, let\'s understand how the BFS works with some examples.\n\n\ts1: "aaabcbea"\n\ts2: "aaaebcba"\n\nA **swap** is when we switch two letters, s1[i] and s1[j]. Not all **swaps** are useful to us. In the above example, we don\'t want to swap s1[0] with any s1[j].\n\n**Swaps** are only useful if they satisfy these conditions:\n1. s1[i] != s2[i] *(the letter isn\'t already in the correct position)*\n2. s1[i] = s2[j] *(we are moving s1[i] to a location where it matches)*\n3. s1[j]! = s2[j] *(the SECOND letter isn\'t already in the correct position*)\n\n**Our approach is to find the first non-matching letter in s1. Then, we try all possible "useful" swaps.**\n\nSo, in the above example, the first non-matching letter is s1[3], or "b". Performing a **swap** with s1[4] and s1[6] are both "useful", because the "b" is moved to the right position.\n\nWe do both of these swaps. This gives us two strings:\n\n\toriginal s1: "aaabcbea"\n\ts2: "aaaebcba"\n\t\n\tnew string 1: "aaacbbea"\n\tnew string 2: "aaaecbba"\n\t\nWe keep track that we made **1** change so far. Then, we repeat the same process on BOTH "new string 1" and "new string 2".\n\nFor new string 1, there is only one possible swap.\n\n\tnew string 1: "aaacbbea"\n\ts2: "aaaebcba"\n\t\n\tnew new string 1: "aaaebbca"\n\t\nFor new string 2, there is also only one possible swap.\n\n\tnew string 2: "aaaecbba"\n\ts2: "aaaebcba"\n\t\n\tnew new string 2: "aaaebcba"\n\t\nAt this point, new new string 2 matches s2, so we are done. We return the number of swaps made so far, which is 2.\n\n\n# **Code**\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n #the deque keeps track of the set of strings that we want to perform swaps on\n #at the start, the deque contains only s1\n deque = collections.deque([s1])\n \n #this set wasn\'t mentioned in the "intuition" part. it helps us avoid doing repeated work by adding the same strings to our deque\n seen = set() \n \n answ=0 #counter for the number of "swaps" done so far\n \n \n while deque:\n for _ in range(len(deque)): #loops through each string in the deque\n \n string = deque.popleft() #gets the first string in the deque\n if string ==s2: return answ\n \n #finds the first non-matching letter in s1\n #this satisfies condition 1 of a "useful" swap\n #ex: this would be s1[3] in the above example\n i=0\n while string[i]==s2[i]:\n i+=1\n \n #checks all the other letters for potential swaps\n for j in range(i+1, len(string)):\n if string[i]==s2[j]!=s1[j]: #checks conditions 2 and 3 of a useful swap\n \n #swaps the letters at positions i and j\n new = string[:i] + string[j] + string[i+1:j] + string[i] + string[j+1:]\n \n #adds the "new string" if it was not previously added\n if new not in seen:\n seen.add(new)\n deque.append(new)\n \n #record that one more swap was done for each string in the deque\n answ+=1\n\n```\n\n**Still Confused?**\nIf you thoroughly read through this explanation and don\'t get it, I\'d recommend checking out this explanation on 2x speed:\nhttps://www.youtube.com/watch?v=GacKZ1-p3-0&t=1292s&ab_channel=HappyCoding
27
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
three solutions of this problem, good for understanding DFS, DFS with memo and BFS
k-similar-strings
0
1
In this problem, we use string `A` as a target, all we need to do is modify string `B` from left to right to make it the same as `A`.\nHow to modify? If `A[i] != B[i]`, we try to swap `B[i]` with all `B[j]` where `i < j <= len(B) && B[j]==A[i] && B[j] != A[j]` \nNaturally, it can be solved with DFS(backtracking) or BFS. Here are three ways(DFS, DFS with memorization, BFS) to approach this problem.\n```python\nclass Solution:\n # DFS\n def kSimilarity(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float(\'inf\')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n return minCnt\n \n return dfs(list(A), list(B), 0)\n\n # DFS with memorization\n def kSimilarity1(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n sB = \'\'.join(B)\n if sB in map:\n return map[sB]\n \n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float(\'inf\')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n map[sB] = minCnt\n return minCnt\n \n map = collections.defaultdict()\n return dfs(list(A), list(B), 0)\n \n # BFS\n def kSimilarity2(self, A: str, B: str) -> int:\n N = len(B)\n q = collections.deque([B])\n visited = set(B)\n \n cnt = 0\n pos = 0\n while q:\n qSize = len(q)\n \n for _ in range(qSize):\n cur = q.popleft()\n if cur == A:\n return cnt\n \n pos = 0\n while cur[pos] == A[pos]:\n pos += 1\n \n lCur = list(cur)\n for i in range(pos + 1, N):\n if lCur[i] == A[pos] and lCur[i] != A[i]:\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n \n sCur = \'\'.join(lCur)\n if sCur not in visited:\n q.append(sCur)\n \n visited.add(sCur)\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n cnt += 1\n \n return cnt\n```
23
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
three solutions of this problem, good for understanding DFS, DFS with memo and BFS
k-similar-strings
0
1
In this problem, we use string `A` as a target, all we need to do is modify string `B` from left to right to make it the same as `A`.\nHow to modify? If `A[i] != B[i]`, we try to swap `B[i]` with all `B[j]` where `i < j <= len(B) && B[j]==A[i] && B[j] != A[j]` \nNaturally, it can be solved with DFS(backtracking) or BFS. Here are three ways(DFS, DFS with memorization, BFS) to approach this problem.\n```python\nclass Solution:\n # DFS\n def kSimilarity(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float(\'inf\')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n return minCnt\n \n return dfs(list(A), list(B), 0)\n\n # DFS with memorization\n def kSimilarity1(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n sB = \'\'.join(B)\n if sB in map:\n return map[sB]\n \n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float(\'inf\')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n map[sB] = minCnt\n return minCnt\n \n map = collections.defaultdict()\n return dfs(list(A), list(B), 0)\n \n # BFS\n def kSimilarity2(self, A: str, B: str) -> int:\n N = len(B)\n q = collections.deque([B])\n visited = set(B)\n \n cnt = 0\n pos = 0\n while q:\n qSize = len(q)\n \n for _ in range(qSize):\n cur = q.popleft()\n if cur == A:\n return cnt\n \n pos = 0\n while cur[pos] == A[pos]:\n pos += 1\n \n lCur = list(cur)\n for i in range(pos + 1, N):\n if lCur[i] == A[pos] and lCur[i] != A[i]:\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n \n sCur = \'\'.join(lCur)\n if sCur not in visited:\n q.append(sCur)\n \n visited.add(sCur)\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n cnt += 1\n \n return cnt\n```
23
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
[Python3] bfs
k-similar-strings
0
1
\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ans = 0\n seen = {s1}\n queue = deque([s1])\n while queue: \n for _ in range(len(queue)): \n s = queue.popleft()\n if s == s2: return ans \n for i in range(len(s)): \n if s[i] != s2[i]: \n for j in range(i+1, len(s)): \n if s[j] != s2[j] and s[j] == s2[i]: \n ss = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]\n if ss not in seen: \n seen.add(ss)\n queue.append(ss)\n break\n ans += 1\n```
3
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
[Python3] bfs
k-similar-strings
0
1
\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ans = 0\n seen = {s1}\n queue = deque([s1])\n while queue: \n for _ in range(len(queue)): \n s = queue.popleft()\n if s == s2: return ans \n for i in range(len(s)): \n if s[i] != s2[i]: \n for j in range(i+1, len(s)): \n if s[j] != s2[j] and s[j] == s2[i]: \n ss = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]\n if ss not in seen: \n seen.add(ss)\n queue.append(ss)\n break\n ans += 1\n```
3
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
Simple python recursion
k-similar-strings
0
1
# Intuition\nWe want to get the minimum by trying every swap combination. There\'s lot of BFS solutions out there, but it flew past my head. \n\n# Approach\nUse recursion and get the min from all the combinations. Use a cache of solved combinations because python so slow. Not the fastest or memory efficient, but it passes and easier to recreate at the coding interview \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nLots\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n self.memo = {} \n return self.get_swaps(list(s1), list(s2), 0)\n\n def get_swaps(self, a1, a2, i):\n # we have a match, no more steps needed\n if str(a1) == str(a2):\n return 0\n\n # increment until we get a mismatch\n while a1[i] == a2[i]:\n i += 1\n\n # get all swap candidates\n candidates = [j for j in range(i, len(a1)) if a2[j] == a1[i]]\n\n min_swaps = None\n for c in candidates:\n # do the swap and recursive call the next\n arr = a2.copy()\n arr[c], arr[i] = arr[i], arr[c]\n\n arr_str = "".join(arr)\n if mem := self.memo.get(arr_str):\n swaps = mem\n else:\n swaps = self.get_swaps(a1, arr, i+1) + 1\n self.memo[arr_str] = swaps\n\n min_swaps = swaps if min_swaps is None else min(min_swaps, swaps)\n \n return min_swaps\n```
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Simple python recursion
k-similar-strings
0
1
# Intuition\nWe want to get the minimum by trying every swap combination. There\'s lot of BFS solutions out there, but it flew past my head. \n\n# Approach\nUse recursion and get the min from all the combinations. Use a cache of solved combinations because python so slow. Not the fastest or memory efficient, but it passes and easier to recreate at the coding interview \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nLots\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n self.memo = {} \n return self.get_swaps(list(s1), list(s2), 0)\n\n def get_swaps(self, a1, a2, i):\n # we have a match, no more steps needed\n if str(a1) == str(a2):\n return 0\n\n # increment until we get a mismatch\n while a1[i] == a2[i]:\n i += 1\n\n # get all swap candidates\n candidates = [j for j in range(i, len(a1)) if a2[j] == a1[i]]\n\n min_swaps = None\n for c in candidates:\n # do the swap and recursive call the next\n arr = a2.copy()\n arr[c], arr[i] = arr[i], arr[c]\n\n arr_str = "".join(arr)\n if mem := self.memo.get(arr_str):\n swaps = mem\n else:\n swaps = self.get_swaps(a1, arr, i+1) + 1\n self.memo[arr_str] = swaps\n\n min_swaps = swaps if min_swaps is None else min(min_swaps, swaps)\n \n return min_swaps\n```
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
Python Greedy Solution: Beats 99%
k-similar-strings
0
1
# Intuition\n\nThis is the solution I came up with. It works by finding the fewest swaps needed to get all elements involved in the swaps into place.\n\nFor example, if you had the strings "ababcd" and "badabc", it would take these steps:\n\n1. Swap the first 2 elements to get "ababcd" and "abdabc" with 1 swap.\n2. No more elements can be directly swapped. There are also no 2 swaps that will get elements into the correct place.\n3. With 3 swaps, however, you can get the last 4 elements into the position, giving 4 total swaps to make the strings equal.\n\nThis idea can be optimized by recognizing that when swapping more than 2 elements, you are essentially cycling them. This mean we can think of the string as a graph, where the nodes are every element of s2 thats out of place and the edges represent what elements are supposed to be in that position. We can use BFS to find the shortest cycle in the graph, and then remove those edges from the graph (as the nodes they connect are in place after the swap cycle)\n\nWhile this strategy passes all the test cases, there are select edge cases where it fails. Moving elements in smaller cycles first is always optimal. However, sometimes making one cycles will prevent multiple others of the same length. We can mostly remedy this by testing multiple orderings of the string. There is a tradeoff between speed and accuracy.\n\n\n\n# Code\n```\nfrom collections import defaultdict, deque\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n return min([self.ks(s1[x:] + s1[:x], s2[x:] + s2[:x]) for x in range(0, len(s1), 3)])\n def ks(self, s1: str, s2: str) -> int:\n n = len(s1)\n edges = defaultdict(lambda: [])\n for x in range(n):\n if s1[x] != s2[x]:\n edges[s1[x]].append(s2[x])\n moves = 0\n \n while len(edges):\n queue = deque() # node, path\n for start in edges.keys():\n queue.append((start, tuple([start])))\n while len(queue):\n node, path = queue.popleft()\n for connection in edges[node]:\n path2 = path + tuple([connection])\n if path2[0] == path2[-1]:\n # found a cycle\n for x in range(len(path2) - 1):\n edges[path2[x]].remove(path2[x + 1])\n if edges[path2[x]] == []:\n del edges[path2[x]]\n moves += len(path2) - 2\n queue = []\n break\n queue.append((connection, path2))\n return moves\n```
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Python Greedy Solution: Beats 99%
k-similar-strings
0
1
# Intuition\n\nThis is the solution I came up with. It works by finding the fewest swaps needed to get all elements involved in the swaps into place.\n\nFor example, if you had the strings "ababcd" and "badabc", it would take these steps:\n\n1. Swap the first 2 elements to get "ababcd" and "abdabc" with 1 swap.\n2. No more elements can be directly swapped. There are also no 2 swaps that will get elements into the correct place.\n3. With 3 swaps, however, you can get the last 4 elements into the position, giving 4 total swaps to make the strings equal.\n\nThis idea can be optimized by recognizing that when swapping more than 2 elements, you are essentially cycling them. This mean we can think of the string as a graph, where the nodes are every element of s2 thats out of place and the edges represent what elements are supposed to be in that position. We can use BFS to find the shortest cycle in the graph, and then remove those edges from the graph (as the nodes they connect are in place after the swap cycle)\n\nWhile this strategy passes all the test cases, there are select edge cases where it fails. Moving elements in smaller cycles first is always optimal. However, sometimes making one cycles will prevent multiple others of the same length. We can mostly remedy this by testing multiple orderings of the string. There is a tradeoff between speed and accuracy.\n\n\n\n# Code\n```\nfrom collections import defaultdict, deque\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n return min([self.ks(s1[x:] + s1[:x], s2[x:] + s2[:x]) for x in range(0, len(s1), 3)])\n def ks(self, s1: str, s2: str) -> int:\n n = len(s1)\n edges = defaultdict(lambda: [])\n for x in range(n):\n if s1[x] != s2[x]:\n edges[s1[x]].append(s2[x])\n moves = 0\n \n while len(edges):\n queue = deque() # node, path\n for start in edges.keys():\n queue.append((start, tuple([start])))\n while len(queue):\n node, path = queue.popleft()\n for connection in edges[node]:\n path2 = path + tuple([connection])\n if path2[0] == path2[-1]:\n # found a cycle\n for x in range(len(path2) - 1):\n edges[path2[x]].remove(path2[x + 1])\n if edges[path2[x]] == []:\n del edges[path2[x]]\n moves += len(path2) - 2\n queue = []\n break\n queue.append((connection, path2))\n return moves\n```
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
BFS Approach (Python)
k-similar-strings
0
1
# Intuition\nWhen you have two strings s1 and s2, and if at position i, s1[i] != s2[i], then you ideally want to find some position j (where j > i) such that s2[j] == s1[i]. Swapping these positions could help both positions (or at least one) to match the respective characters in s1. \n\n# Approach\nBFS\n\n# Complexity\n$O(n^2)$\n\n# Space complexity:\n$O(n^2)$\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n if s1 == s2:\n return 0\n\n def neighbors(s):\n for i, c in enumerate(s):\n if s1[i] != c:\n break\n t = list(s)\n for j in range(i + 1, len(s)):\n if s[j] == s1[i]:\n t[j], t[i] = t[i], t[j]\n yield "".join(t)\n t[j], t[i] = t[i], t[j]\n \n queue = [s2]\n seen = {s2}\n k = 0\n while queue:\n length = len(queue)\n k += 1\n for _ in range(length):\n current = queue.pop(0)\n for nei in neighbors(current):\n if nei in seen:\n continue\n if nei == s1:\n return k\n queue.append(nei)\n seen.add(nei)\n\n```
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
BFS Approach (Python)
k-similar-strings
0
1
# Intuition\nWhen you have two strings s1 and s2, and if at position i, s1[i] != s2[i], then you ideally want to find some position j (where j > i) such that s2[j] == s1[i]. Swapping these positions could help both positions (or at least one) to match the respective characters in s1. \n\n# Approach\nBFS\n\n# Complexity\n$O(n^2)$\n\n# Space complexity:\n$O(n^2)$\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n if s1 == s2:\n return 0\n\n def neighbors(s):\n for i, c in enumerate(s):\n if s1[i] != c:\n break\n t = list(s)\n for j in range(i + 1, len(s)):\n if s[j] == s1[i]:\n t[j], t[i] = t[i], t[j]\n yield "".join(t)\n t[j], t[i] = t[i], t[j]\n \n queue = [s2]\n seen = {s2}\n k = 0\n while queue:\n length = len(queue)\n k += 1\n for _ in range(length):\n current = queue.pop(0)\n for nei in neighbors(current):\n if nei in seen:\n continue\n if nei == s1:\n return k\n queue.append(nei)\n seen.add(nei)\n\n```
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
[Python] BFS with pruning
k-similar-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo find the smallest k, we can model the problem as finding the shortest path in a graph where nodes `u` and `v` have an undirected edge if `v` can be constructed by swapping two characters in `u`. Naively, each node `u` could have up to `n^2` neighbors. Since strings are immutable, constructing the new string to add to the queue would take `O(n)`. Each iteration of BFS would take `O(n^3)` to check and construct all valid neighbors.\n\nPruning optimizations:\nTip 1: if `u[i] == s2[i]`, which means that the ith position is already satisfied, then we shouldn\'t swap `i` at all.\nTip 2: we only care about swapping if we can move `u[i]` to a correct position, where `u[i] == s2[j]`. We can precompute the char_to_index map from `s2`. To avoid redundant swaps, only consider when `i < j`.\n\n\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n n = len(s1)\n\n # precompute char to index map for the target str\n tgt_c_to_idx = collections.defaultdict(list)\n for i, c in enumerate(s2):\n tgt_c_to_idx[c].append(i)\n\n q = collections.deque([(0, s1)]) # steps (int), node (str)\n seen = set()\n seen.add(s1)\n while q:\n k, u = q.popleft()\n if u == s2:\n return k\n for i in range(n - 1):\n if u[i] == s2[i]: continue\n for j in tgt_c_to_idx[u[i]]:\n if j <= i: continue\n # swap i and j, construct neighbor v\n v = list(u)\n v[i], v[j] = v[j], v[i]\n v = \'\'.join(v)\n if v not in seen:\n seen.add(v)\n q.append((k + 1, v))\n break\n```
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
[Python] BFS with pruning
k-similar-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo find the smallest k, we can model the problem as finding the shortest path in a graph where nodes `u` and `v` have an undirected edge if `v` can be constructed by swapping two characters in `u`. Naively, each node `u` could have up to `n^2` neighbors. Since strings are immutable, constructing the new string to add to the queue would take `O(n)`. Each iteration of BFS would take `O(n^3)` to check and construct all valid neighbors.\n\nPruning optimizations:\nTip 1: if `u[i] == s2[i]`, which means that the ith position is already satisfied, then we shouldn\'t swap `i` at all.\nTip 2: we only care about swapping if we can move `u[i]` to a correct position, where `u[i] == s2[j]`. We can precompute the char_to_index map from `s2`. To avoid redundant swaps, only consider when `i < j`.\n\n\n\n# Code\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n n = len(s1)\n\n # precompute char to index map for the target str\n tgt_c_to_idx = collections.defaultdict(list)\n for i, c in enumerate(s2):\n tgt_c_to_idx[c].append(i)\n\n q = collections.deque([(0, s1)]) # steps (int), node (str)\n seen = set()\n seen.add(s1)\n while q:\n k, u = q.popleft()\n if u == s2:\n return k\n for i in range(n - 1):\n if u[i] == s2[i]: continue\n for j in tgt_c_to_idx[u[i]]:\n if j <= i: continue\n # swap i and j, construct neighbor v\n v = list(u)\n v[i], v[j] = v[j], v[i]\n v = \'\'.join(v)\n if v not in seen:\n seen.add(v)\n q.append((k + 1, v))\n break\n```
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**. **Example 1:** **Input:** s1 = "this apple is sweet", s2 = "this apple is sour" **Output:** \["sweet","sour"\] **Example 2:** **Input:** s1 = "apple apple", s2 = "banana" **Output:** \["banana"\] **Constraints:** * `1 <= s1.length, s2.length <= 200` * `s1` and `s2` consist of lowercase English letters and spaces. * `s1` and `s2` do not have leading or trailing spaces. * All the words in `s1` and `s2` are separated by a single space.
null
Python 3 || w/ comments || T/M 40% / 89%
exam-room
0
1
```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n, self.room = n, []\n\n\n def seat(self) -> int:\n if not self.room: ans = 0 # sit at 0 if empty room \n\n else:\n dist, prev, ans = self.room[0], self.room[0], 0 # set best between door and first student \n\n for curr in self.room[1:]: # check between all pairs of students \n d = (curr - prev)//2 # to improve on current best\n\n if dist < d: dist, ans = d, (curr + prev)//2\n prev = curr\n\n if dist < self.n - prev-1: ans = self.n - 1 # finally, check whether last seat is best\n\n insort(self.room, ans) # sit down in best seat\n\n return ans\n```\n[https://leetcode.com/problems/exam-room/submissions/886484133/]()
3
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Python 3 || w/ comments || T/M 40% / 89%
exam-room
0
1
```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n, self.room = n, []\n\n\n def seat(self) -> int:\n if not self.room: ans = 0 # sit at 0 if empty room \n\n else:\n dist, prev, ans = self.room[0], self.room[0], 0 # set best between door and first student \n\n for curr in self.room[1:]: # check between all pairs of students \n d = (curr - prev)//2 # to improve on current best\n\n if dist < d: dist, ans = d, (curr + prev)//2\n prev = curr\n\n if dist < self.n - prev-1: ans = self.n - 1 # finally, check whether last seat is best\n\n insort(self.room, ans) # sit down in best seat\n\n return ans\n```\n[https://leetcode.com/problems/exam-room/submissions/886484133/]()
3
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Solution
exam-room
1
1
```C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn n - 1;\n\t\t\t} return start + size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\tint max_seat_dist(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn size - 1;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn size - 1;\n\t\t\t} return size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\ttuple<gap_t, gap_t> split(int n) const {\n\t\t\tint seat = get_best_seat(n);\n\t\t\treturn {{start, seat - start}, {seat + 1, start + size - seat - 1}};\n\t\t}\n\t\tbool empty() const {\n\t\t\treturn size <= 0;\n\t\t}\n bool operator == (const gap_t& another) const {\n return start == another.start && size == another.size;\n }\n bool operator != (const gap_t& another) const {\n return !(*this == another);\n }\n\t\tint start{};\n\t\tint size{};\n\t};\n\tstruct gap_order_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\treturn g1.start < g2.start;\n\t\t}\n\t};\n\tstruct gap_size_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\tint d1 = g1.max_seat_dist(n);\n int d2 = g2.max_seat_dist(n);\n if (d1 != d2) {\n return d1 < d2;\n } return g1.start > g2.start;\n\t\t}\n\t\tint n{};\n\t};\n ExamRoom(int _n) : n{_n} {\n\t\tgaps.push_back({0, n});\n\t\tseats.insert(-1);\n\t\tseats.insert(n);\n\t}\n\tgap_t get_gap(int gap) {\n\t\tauto it = seats.lower_bound(gap);\n\t\tint start = *it + 1;\n\t\t--it;\n\t\tint size = *it - start;\n\t\treturn {start, size};\n\t}\n\tvoid pop_gap() {\n\t\tpop_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t\tgaps.pop_back();\n }\n\tvoid push_gap(const gap_t& gap) {\n\t\tgaps.push_back(gap);\n\t\tpush_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t}\n int seat() {\n\t\twhile (!gaps.empty()) {\n\t\t\tauto gap = gaps.front();\n\t\t\tauto true_gap = get_gap(gap.start);\n\t\t\tpop_gap();\n\t\t\tif (gap != true_gap) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint new_seat = gap.get_best_seat(n);\n\t\t\tseats.insert(new_seat);\n\n\t\t\tauto [g1, g2] = gap.split(n);\n\t\t\tif (!g1.empty()) {\n\t\t\t\tpush_gap(g1);\n\t\t\t} if (!g2.empty()) {\n\t\t\t\tpush_gap(g2);\n\t\t\t}\n\t\t\treturn new_seat;\n\t\t} return -1;\n }\n void leave(int p) {\n\t\tseats.erase(p);\n\t\tpush_gap(get_gap(p));\n }\n int n{};\n\tset<int, greater<int>> seats;\n\tvector<gap_t> gaps;\n};\n```\n\n```Python3 []\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.heap = []\n\n self.heap.append((-self.dist(0, n - 1), 0, n - 1))\n\n def seat(self) -> int:\n res = 0\n\n curr_dist, l, r = heappop(self.heap)\n curr_dist = -curr_dist\n\n if l == 0:\n res = 0\n elif r == self.n - 1:\n res = self.n - 1\n else:\n res = l + curr_dist\n \n if res > l:\n heappush(self.heap, (-self.dist(l, res - 1), l, res - 1))\n \n if res < r:\n heappush(self.heap, (-self.dist(res + 1, r), res + 1, r))\n\n return res\n\n def leave(self, p: int) -> None:\n prev_interval, next_interval = None, None\n\n for item in self.heap:\n if item[1] - 1 == p:\n next_interval = item\n if item[2] + 1 == p:\n prev_interval = item\n \n start = p\n end = p\n if prev_interval:\n start = prev_interval[1]\n self.heap.remove(prev_interval)\n if next_interval:\n end = next_interval[2]\n self.heap.remove(next_interval)\n\n heappush(self.heap, (-self.dist(start, end), start, end))\n \n def dist(self, l, r):\n if l == 0 or r == self.n - 1:\n return r - l\n else:\n return (r - l) // 2\n```\n\n```Java []\nclass ExamRoom {\n\tprivate int n;\n\tprivate Queue<Interval> queue;\n\tpublic ExamRoom(int n) {\n\t\tthis.queue = new PriorityQueue<>((a, b) -> a.length != b.length ? b.length - a.length : a.start - b.start);\n\t\tthis.n = n;\n\t\tthis.queue.offer(new Interval(n, 0, this.n - 1));\n\t}\n\tpublic int seat() {\n\t\tInterval interval = this.queue.poll();\n\t\tint result;\n\t\tif (interval.start == 0) {\n\t\t\tresult = 0;\n\t\t} else if (interval.end == this.n - 1) {\n\t\t\tresult = this.n - 1;\n\t\t} else {\n\t\t\tresult = interval.start + interval.length;\n\t\t}\n\t\tif (result > interval.start) {\n\t\t\tthis.queue.offer(new Interval(n, interval.start, result - 1));\n\t\t}\n\t\tif (result < interval.end) {\n\t\t\tthis.queue.offer(new Interval(n, result + 1, interval.end));\n\t\t}\n\t\treturn result;\n\t}\n\tpublic void leave(int p) {\n\t\tList<Interval> list = new ArrayList<>(this.queue);\n\t\tInterval prev = null;\n\t\tInterval next = null;\n\t\tfor (Interval interval : list) {\n\t\t\tif (interval.end + 1 == p) {\n\t\t\t\tprev = interval;\n\t\t\t}\n\t\t\tif (interval.start - 1 == p) {\n\t\t\t\tnext = interval;\n\t\t\t}\n\t\t}\n\t\tthis.queue.remove(prev);\n\t\tthis.queue.remove(next);\n\t\tthis.queue.offer(new Interval(n, prev == null ? p : prev.start, next == null ? p : next.end));\n\t}\n}\nclass Interval {\n\tint start;\n\tint end;\n\tint length;\n\tpublic Interval(int n, int start, int end) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tif (start == 0 || end == n - 1) {\n\t\t\tthis.length = end - start;\n\t\t} else {\n\t\t\tthis.length = (end - start) / 2;\n\t\t}\n\t}\n}\n```\n
1
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Solution
exam-room
1
1
```C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn n - 1;\n\t\t\t} return start + size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\tint max_seat_dist(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn size - 1;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn size - 1;\n\t\t\t} return size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\ttuple<gap_t, gap_t> split(int n) const {\n\t\t\tint seat = get_best_seat(n);\n\t\t\treturn {{start, seat - start}, {seat + 1, start + size - seat - 1}};\n\t\t}\n\t\tbool empty() const {\n\t\t\treturn size <= 0;\n\t\t}\n bool operator == (const gap_t& another) const {\n return start == another.start && size == another.size;\n }\n bool operator != (const gap_t& another) const {\n return !(*this == another);\n }\n\t\tint start{};\n\t\tint size{};\n\t};\n\tstruct gap_order_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\treturn g1.start < g2.start;\n\t\t}\n\t};\n\tstruct gap_size_compare_t {\n\t\tbool operator() (const gap_t& g1, const gap_t& g2) const {\n\t\t\tint d1 = g1.max_seat_dist(n);\n int d2 = g2.max_seat_dist(n);\n if (d1 != d2) {\n return d1 < d2;\n } return g1.start > g2.start;\n\t\t}\n\t\tint n{};\n\t};\n ExamRoom(int _n) : n{_n} {\n\t\tgaps.push_back({0, n});\n\t\tseats.insert(-1);\n\t\tseats.insert(n);\n\t}\n\tgap_t get_gap(int gap) {\n\t\tauto it = seats.lower_bound(gap);\n\t\tint start = *it + 1;\n\t\t--it;\n\t\tint size = *it - start;\n\t\treturn {start, size};\n\t}\n\tvoid pop_gap() {\n\t\tpop_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t\tgaps.pop_back();\n }\n\tvoid push_gap(const gap_t& gap) {\n\t\tgaps.push_back(gap);\n\t\tpush_heap(gaps.begin(), gaps.end(), gap_size_compare_t{n});\n\t}\n int seat() {\n\t\twhile (!gaps.empty()) {\n\t\t\tauto gap = gaps.front();\n\t\t\tauto true_gap = get_gap(gap.start);\n\t\t\tpop_gap();\n\t\t\tif (gap != true_gap) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint new_seat = gap.get_best_seat(n);\n\t\t\tseats.insert(new_seat);\n\n\t\t\tauto [g1, g2] = gap.split(n);\n\t\t\tif (!g1.empty()) {\n\t\t\t\tpush_gap(g1);\n\t\t\t} if (!g2.empty()) {\n\t\t\t\tpush_gap(g2);\n\t\t\t}\n\t\t\treturn new_seat;\n\t\t} return -1;\n }\n void leave(int p) {\n\t\tseats.erase(p);\n\t\tpush_gap(get_gap(p));\n }\n int n{};\n\tset<int, greater<int>> seats;\n\tvector<gap_t> gaps;\n};\n```\n\n```Python3 []\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.heap = []\n\n self.heap.append((-self.dist(0, n - 1), 0, n - 1))\n\n def seat(self) -> int:\n res = 0\n\n curr_dist, l, r = heappop(self.heap)\n curr_dist = -curr_dist\n\n if l == 0:\n res = 0\n elif r == self.n - 1:\n res = self.n - 1\n else:\n res = l + curr_dist\n \n if res > l:\n heappush(self.heap, (-self.dist(l, res - 1), l, res - 1))\n \n if res < r:\n heappush(self.heap, (-self.dist(res + 1, r), res + 1, r))\n\n return res\n\n def leave(self, p: int) -> None:\n prev_interval, next_interval = None, None\n\n for item in self.heap:\n if item[1] - 1 == p:\n next_interval = item\n if item[2] + 1 == p:\n prev_interval = item\n \n start = p\n end = p\n if prev_interval:\n start = prev_interval[1]\n self.heap.remove(prev_interval)\n if next_interval:\n end = next_interval[2]\n self.heap.remove(next_interval)\n\n heappush(self.heap, (-self.dist(start, end), start, end))\n \n def dist(self, l, r):\n if l == 0 or r == self.n - 1:\n return r - l\n else:\n return (r - l) // 2\n```\n\n```Java []\nclass ExamRoom {\n\tprivate int n;\n\tprivate Queue<Interval> queue;\n\tpublic ExamRoom(int n) {\n\t\tthis.queue = new PriorityQueue<>((a, b) -> a.length != b.length ? b.length - a.length : a.start - b.start);\n\t\tthis.n = n;\n\t\tthis.queue.offer(new Interval(n, 0, this.n - 1));\n\t}\n\tpublic int seat() {\n\t\tInterval interval = this.queue.poll();\n\t\tint result;\n\t\tif (interval.start == 0) {\n\t\t\tresult = 0;\n\t\t} else if (interval.end == this.n - 1) {\n\t\t\tresult = this.n - 1;\n\t\t} else {\n\t\t\tresult = interval.start + interval.length;\n\t\t}\n\t\tif (result > interval.start) {\n\t\t\tthis.queue.offer(new Interval(n, interval.start, result - 1));\n\t\t}\n\t\tif (result < interval.end) {\n\t\t\tthis.queue.offer(new Interval(n, result + 1, interval.end));\n\t\t}\n\t\treturn result;\n\t}\n\tpublic void leave(int p) {\n\t\tList<Interval> list = new ArrayList<>(this.queue);\n\t\tInterval prev = null;\n\t\tInterval next = null;\n\t\tfor (Interval interval : list) {\n\t\t\tif (interval.end + 1 == p) {\n\t\t\t\tprev = interval;\n\t\t\t}\n\t\t\tif (interval.start - 1 == p) {\n\t\t\t\tnext = interval;\n\t\t\t}\n\t\t}\n\t\tthis.queue.remove(prev);\n\t\tthis.queue.remove(next);\n\t\tthis.queue.offer(new Interval(n, prev == null ? p : prev.start, next == null ? p : next.end));\n\t}\n}\nclass Interval {\n\tint start;\n\tint end;\n\tint length;\n\tpublic Interval(int n, int start, int end) {\n\t\tthis.start = start;\n\t\tthis.end = end;\n\t\tif (start == 0 || end == n - 1) {\n\t\t\tthis.length = end - start;\n\t\t} else {\n\t\t\tthis.length = (end - start) / 2;\n\t\t}\n\t}\n}\n```\n
1
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Magic SortedList 🪄
exam-room
0
1
# Complexity\n- Time complexity: $$O(log(n))$$ for one call.\n\n- Space complexity: $$O(1)$$ for one call.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n def __init__(self, n: int):\n self.n = n\n self.intervals = SortedList(key=lambda x: ((x[1]-x[0])//2, -x[0]))\n self.points = SortedList()\n\n\n def seat(self) -> int:\n if len(self.points) == 0:\n point = 0\n else:\n start, end = self.intervals[-1] if self.intervals else (0, 0)\n firstL, midL, lastL = self.points[0], end - start - 1, self.n-1 - self.points[-1]\n maxx = max(firstL, midL, lastL)\n if maxx == firstL:\n point = 0\n self.intervals.add((point, self.points[0]))\n elif maxx == midL:\n point = start + (end - start)//2\n self.intervals.add((start, point))\n self.intervals.add((point, end))\n self.intervals.remove((start, end))\n elif maxx == lastL:\n point = self.n-1\n self.intervals.add((self.points[-1], point))\n\n self.points.add(point)\n\n return point\n \n\n def leave(self, point: int) -> None:\n if point == self.points[0]:\n if self.intervals:\n self.intervals.remove((self.points[0], self.points[1]))\n elif point == self.points[-1]:\n self.intervals.remove((self.points[-2], self.points[-1]))\n else:\n i = self.points.index(point)\n start, end = self.points[i-1], self.points[i+1]\n self.intervals.remove((start, point))\n self.intervals.remove((point, end))\n self.intervals.add((start, end))\n\n self.points.remove(point)\n```
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Magic SortedList 🪄
exam-room
0
1
# Complexity\n- Time complexity: $$O(log(n))$$ for one call.\n\n- Space complexity: $$O(1)$$ for one call.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n def __init__(self, n: int):\n self.n = n\n self.intervals = SortedList(key=lambda x: ((x[1]-x[0])//2, -x[0]))\n self.points = SortedList()\n\n\n def seat(self) -> int:\n if len(self.points) == 0:\n point = 0\n else:\n start, end = self.intervals[-1] if self.intervals else (0, 0)\n firstL, midL, lastL = self.points[0], end - start - 1, self.n-1 - self.points[-1]\n maxx = max(firstL, midL, lastL)\n if maxx == firstL:\n point = 0\n self.intervals.add((point, self.points[0]))\n elif maxx == midL:\n point = start + (end - start)//2\n self.intervals.add((start, point))\n self.intervals.add((point, end))\n self.intervals.remove((start, end))\n elif maxx == lastL:\n point = self.n-1\n self.intervals.add((self.points[-1], point))\n\n self.points.add(point)\n\n return point\n \n\n def leave(self, point: int) -> None:\n if point == self.points[0]:\n if self.intervals:\n self.intervals.remove((self.points[0], self.points[1]))\n elif point == self.points[-1]:\n self.intervals.remove((self.points[-2], self.points[-1]))\n else:\n i = self.points.index(point)\n start, end = self.points[i-1], self.points[i+1]\n self.intervals.remove((start, point))\n self.intervals.remove((point, end))\n self.intervals.add((start, end))\n\n self.points.remove(point)\n```
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Easiest Solution
exam-room
1
1
\n\n# Code\n```java []\nclass ExamRoom {\n int n;\n ArrayList<Integer> list = new ArrayList<>();\n public ExamRoom(int n) {\n this.n = n;\n }\n \n public int seat() {\n if (list.size() == 0){\n list.add(0);\n return 0;\n }\n int dist = Math.max(list.get(0), n - 1 - list.get(list.size() - 1));\n for (int i = 0; i < list.size() - 1; i++){\n dist = Math.max(dist, (list.get(i + 1) - list.get(i)) / 2);\n }\n if (dist == list.get(0)){\n list.add(0, 0);\n return 0;\n }\n for (int i = 0; i < list.size() - 1; i++){\n if (dist == (list.get(i + 1) - list.get(i)) / 2){\n list.add(i + 1, (list.get(i + 1) - list.get(i)) / 2+ list.get(i));\n return list.get(i + 1);\n }\n }\n list.add(n - 1);\n return n - 1;\n }\n \n public void leave(int p) {\n for (int i = 0; i < list.size(); i++){\n if (list.get(i) == p){\n list.remove(i);\n }\n }\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```\n```c++ []\nclass ExamRoom {\npublic:\n set<int> fill;\n int n;\n ExamRoom(int m) {\n n = m;\n }\n \n int seat() {\n if(fill.size()==0)\n {\n fill.insert(0);\n return 0;\n }\n int maxDis = INT_MIN;\n int seat;\n int dis1 = *fill.begin();\n if(dis1>maxDis)\n {\n maxDis = dis1;\n seat = 0;\n }\n int dis = 0;\n for(auto it = fill.begin();it!=fill.end();it++)\n {\n auto it1 = it;\n it1++;\n if(it1==fill.end())\n {\n dis = max(dis,(n-1-*it));\n }\n else\n {\n dis = max(dis,(*it1-*it)/2);\n }\n if(dis>maxDis)\n {\n maxDis = dis;\n seat = *it+dis;\n }\n }\n fill.insert(seat);\n return seat;\n }\n \n void leave(int p) {\n fill.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```\n```python3 []\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.lst = []\n\n def seat(self) -> int:\n if self.lst == []:\n self.lst.append(0)\n return 0\n else:\n index = 0 \n diff = self.lst[0]\n for i in range(1,len(self.lst)+1):\n if i == len(self.lst):\n tmp = self.n - 1 - self.lst[i-1]\n else:\n tmp = (self.lst[i] - self.lst[i-1])//2\n if tmp > diff:\n diff = tmp\n index = i\n #print(self.lst,diff,index)\n if index ==0: \n self.lst.insert(0,0)\n return 0\n elif index == len(self.lst):\n self.lst.append(self.n-1)\n return self.n-1\n else:\n self.lst.insert(index,self.lst[index-1]+diff)\n return diff+self.lst[index-1]\n def leave(self, p: int) -> None:\n self.lst.remove(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Easiest Solution
exam-room
1
1
\n\n# Code\n```java []\nclass ExamRoom {\n int n;\n ArrayList<Integer> list = new ArrayList<>();\n public ExamRoom(int n) {\n this.n = n;\n }\n \n public int seat() {\n if (list.size() == 0){\n list.add(0);\n return 0;\n }\n int dist = Math.max(list.get(0), n - 1 - list.get(list.size() - 1));\n for (int i = 0; i < list.size() - 1; i++){\n dist = Math.max(dist, (list.get(i + 1) - list.get(i)) / 2);\n }\n if (dist == list.get(0)){\n list.add(0, 0);\n return 0;\n }\n for (int i = 0; i < list.size() - 1; i++){\n if (dist == (list.get(i + 1) - list.get(i)) / 2){\n list.add(i + 1, (list.get(i + 1) - list.get(i)) / 2+ list.get(i));\n return list.get(i + 1);\n }\n }\n list.add(n - 1);\n return n - 1;\n }\n \n public void leave(int p) {\n for (int i = 0; i < list.size(); i++){\n if (list.get(i) == p){\n list.remove(i);\n }\n }\n }\n}\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(n);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n```\n```c++ []\nclass ExamRoom {\npublic:\n set<int> fill;\n int n;\n ExamRoom(int m) {\n n = m;\n }\n \n int seat() {\n if(fill.size()==0)\n {\n fill.insert(0);\n return 0;\n }\n int maxDis = INT_MIN;\n int seat;\n int dis1 = *fill.begin();\n if(dis1>maxDis)\n {\n maxDis = dis1;\n seat = 0;\n }\n int dis = 0;\n for(auto it = fill.begin();it!=fill.end();it++)\n {\n auto it1 = it;\n it1++;\n if(it1==fill.end())\n {\n dis = max(dis,(n-1-*it));\n }\n else\n {\n dis = max(dis,(*it1-*it)/2);\n }\n if(dis>maxDis)\n {\n maxDis = dis;\n seat = *it+dis;\n }\n }\n fill.insert(seat);\n return seat;\n }\n \n void leave(int p) {\n fill.erase(p);\n }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom* obj = new ExamRoom(n);\n * int param_1 = obj->seat();\n * obj->leave(p);\n */\n```\n```python3 []\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n = n\n self.lst = []\n\n def seat(self) -> int:\n if self.lst == []:\n self.lst.append(0)\n return 0\n else:\n index = 0 \n diff = self.lst[0]\n for i in range(1,len(self.lst)+1):\n if i == len(self.lst):\n tmp = self.n - 1 - self.lst[i-1]\n else:\n tmp = (self.lst[i] - self.lst[i-1])//2\n if tmp > diff:\n diff = tmp\n index = i\n #print(self.lst,diff,index)\n if index ==0: \n self.lst.insert(0,0)\n return 0\n elif index == len(self.lst):\n self.lst.append(self.n-1)\n return self.n-1\n else:\n self.lst.insert(index,self.lst[index-1]+diff)\n return diff+self.lst[index-1]\n def leave(self, p: int) -> None:\n self.lst.remove(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Possibly Easier to Understand: SortedSet, FT 50%, O(N*log(N)) total time and O(N) total space
exam-room
0
1
# Intuition\n\nThe intuition is reasonably straightforward because the problem statement gives it to us\n* we want to seat the next student as far away from others as possible\n* ase a tie-breaker, seat the student as close as possible\n\nThe intuition about how to approach the problem is HARD though - if we don\'t come up with a simple approach, there will be too many tricky edge cases to solve for a 45 minute interview. This is something that I think can be coded in that time, or at least close.\n\nNOTE: Let $N$ be the number of calls made to `seat` and `leave`. $n$ (lower case) is the number of seats.\n\nImmediately we see that $n \\sim 10^9$ is huge so we can\'t have an $O(n)$ solution.\n\nTo approach the problem I thought about having sections, or "intervals," of students. When we seat a student, we\'ll take the interval that gives us the best distance, seat the student in the middle, thus creating two new intervals.\n\nWhen student `p` leaves, we have intervals `l..p` and `p..r`. So we\'ll\n* delete intervals `l..p` and `p..r`\n* create interval `l..r`\n\nSo we see that we need a couple of things for better than $O(n^2)$ runtime:\n* `seat`: we need `O(log(n))` or faster access to the interval we\'ll split. This implies a priority queue, sorted set, or other sorted collection\n* `leave`: when `p` leaves, we need `O(log(n))` or faster access to the point on the left and right. We can get `O(1)` with a hashmap\n* `leave`: we need to delete the intervals `l..p` and `p..r`. So the collection of intervals should have a `delete` or `remove` function. So this means NOT using `heapq`, and instead using `SortedSet` or similar.\n * this isn\'t STRICTLY necessary - we can use a "tombstone" set and lazy deletion from a priority queue... but it\'s also a lot harder to keep track of\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nWe maintain three collections\n* a `SortedSet` of `Interval`s. An interval has a left and right endpoint that represent students seated at `l` and `r`, respectively\n * `Interval`, and thus the `SortedSet`, are ordered by distance to a new student descending, then by seat ascending. The point is so `next(iter(ivs))` gives us the interval to seat the next student at\n* `l2i` maps the left endpoint of an interval `l` to its interval\n* `r2i` maps the right endpoint of an interval `r` to its interval\n\nI use -1 to signal "no student on left" and n to signal "no student on right" so that EVERY student has two intervals. This really cuts down on the complexity so we have fewer edge cases to handle.\n\nTo `seat` a student:\n* we pop the interval (students to seat the next student between) off the front of the sorted tree, `l..r`\n* then we seat the new student. this breaks `l..r` into two intervals by seating the new student at seat `s`\n * `l..r` is deleted\n * `l..s` and `s..r` are created\n\nWhen a student `leave`s seat `p`, we do the opposite of `seat`:\n* we get the intervals to the left and right of `p`, called `L` and `R`\n* `L` and `R` are deleted because the student is gone\n* the new interval we make is `L.l .. R.r`\n\n# Complexity\n- Time complexity: $O(N \\log(N))$ where $N$ is the number of calls to `seat` and `leave`. The complexity doesn\'t depend on `n` as long as Python3 treats `n` as fixed-sized integer, so `n < 10^{18}` or so. For each call we do $O(\\log(N))$ work involving the SortedSet.\n\n- Space complexity: $O(N)$. After $N$ calls to seat there will be $O(N)$ intervals in the SortedSet and endpoints in the maps.\n\n# Code\n```\nfrom sortedcontainers import SortedSet\n\nclass ExamRoom:\n\n @functools.total_ordering\n class Interval:\n def __init__(self, l, r, n):\n self.l = l\n self.r = r\n self.n = n\n\n def dist(self):\n """Returns max distance from l and r to a student seated in (l, r)"""\n l = self.l\n r = self.r\n n = self.n\n\n if l == -1:\n return r\n elif r == n:\n return n-1-l\n else:\n return (r-l)//2\n\n def __hash__(self):\n return self.l * self.n + self.r\n\n def __lt__(self, other):\n sd = self.dist()\n od = other.dist()\n \n if sd > od: # order by distance decreasing\n return True\n elif sd == od: # then by seat increasing\n return self.l < other.l\n else:\n return False\n\n def __eq__(self, other):\n return self.l == other.l and self.r == other.r\n \n def __init__(self, n: int):\n # we have a set of intervals l..r, and to seat people we want an interval \n # to avoid "nobody on left/right" as special cases, we use -1 for nobody on left, and n for nobody on the right\n\n # we use a sorted set so we can get the minimum in log(n) time, and make it a lot easier to delete items\n # as an alternative we could use a priority queue, but python3\'s heapq doesn\'t allow O(log(n)) removal of \n # arbitrary elements. so we\'d have to maintain tombstones, which just gets a lot more complicated\n\n # the intervals we currently have, ordered such that the min element is the one we\'ll set the next student in\n self.n = n\n self.ivs = SortedSet()\n iv = self.Interval(-1, n, n)\n \n self.ivs.add(iv)\n\n # for O(1) access when we delete a student: when we delete p, we need to know the adjacent l and r | the intervals are l..p..r\n self.l2i = {-1: iv}\n self.r2i = {n: iv}\n\n def seat(self) -> int:\n iv = next(iter(self.ivs))\n n = self.n\n # get bisection point, i.e. the seat\n if iv.l == -1:\n s = 0\n elif iv.r == n:\n s = n-1\n else:\n s = iv.l + iv.dist()\n\n # bisect the old interval l..r to form l..s..r\n self.ivs.remove(iv)\n L = self.Interval(iv.l, s, n)\n R = self.Interval(s, iv.r, n)\n self.ivs.add(L)\n self.ivs.add(R)\n self.l2i[iv.l] = L\n self.r2i[s] = L\n self.l2i[s] = R\n self.r2i[iv.r] = R\n\n return s\n\n def leave(self, p: int) -> None:\n # we have intervals l..p..r right now, we need to delete L=l..p and R=p..r and replace with l..r\n L = self.r2i[p]\n R = self.l2i[p]\n\n # delete old intervals\n del self.r2i[p]\n del self.l2i[p]\n self.ivs.remove(L)\n self.ivs.remove(R)\n\n # create unified interval l..r\n iv = self.Interval(L.l, R.r, self.n)\n self.ivs.add(iv)\n self.l2i[L.l] = iv\n self.r2i[R.r] = iv\n \n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
Possibly Easier to Understand: SortedSet, FT 50%, O(N*log(N)) total time and O(N) total space
exam-room
0
1
# Intuition\n\nThe intuition is reasonably straightforward because the problem statement gives it to us\n* we want to seat the next student as far away from others as possible\n* ase a tie-breaker, seat the student as close as possible\n\nThe intuition about how to approach the problem is HARD though - if we don\'t come up with a simple approach, there will be too many tricky edge cases to solve for a 45 minute interview. This is something that I think can be coded in that time, or at least close.\n\nNOTE: Let $N$ be the number of calls made to `seat` and `leave`. $n$ (lower case) is the number of seats.\n\nImmediately we see that $n \\sim 10^9$ is huge so we can\'t have an $O(n)$ solution.\n\nTo approach the problem I thought about having sections, or "intervals," of students. When we seat a student, we\'ll take the interval that gives us the best distance, seat the student in the middle, thus creating two new intervals.\n\nWhen student `p` leaves, we have intervals `l..p` and `p..r`. So we\'ll\n* delete intervals `l..p` and `p..r`\n* create interval `l..r`\n\nSo we see that we need a couple of things for better than $O(n^2)$ runtime:\n* `seat`: we need `O(log(n))` or faster access to the interval we\'ll split. This implies a priority queue, sorted set, or other sorted collection\n* `leave`: when `p` leaves, we need `O(log(n))` or faster access to the point on the left and right. We can get `O(1)` with a hashmap\n* `leave`: we need to delete the intervals `l..p` and `p..r`. So the collection of intervals should have a `delete` or `remove` function. So this means NOT using `heapq`, and instead using `SortedSet` or similar.\n * this isn\'t STRICTLY necessary - we can use a "tombstone" set and lazy deletion from a priority queue... but it\'s also a lot harder to keep track of\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nWe maintain three collections\n* a `SortedSet` of `Interval`s. An interval has a left and right endpoint that represent students seated at `l` and `r`, respectively\n * `Interval`, and thus the `SortedSet`, are ordered by distance to a new student descending, then by seat ascending. The point is so `next(iter(ivs))` gives us the interval to seat the next student at\n* `l2i` maps the left endpoint of an interval `l` to its interval\n* `r2i` maps the right endpoint of an interval `r` to its interval\n\nI use -1 to signal "no student on left" and n to signal "no student on right" so that EVERY student has two intervals. This really cuts down on the complexity so we have fewer edge cases to handle.\n\nTo `seat` a student:\n* we pop the interval (students to seat the next student between) off the front of the sorted tree, `l..r`\n* then we seat the new student. this breaks `l..r` into two intervals by seating the new student at seat `s`\n * `l..r` is deleted\n * `l..s` and `s..r` are created\n\nWhen a student `leave`s seat `p`, we do the opposite of `seat`:\n* we get the intervals to the left and right of `p`, called `L` and `R`\n* `L` and `R` are deleted because the student is gone\n* the new interval we make is `L.l .. R.r`\n\n# Complexity\n- Time complexity: $O(N \\log(N))$ where $N$ is the number of calls to `seat` and `leave`. The complexity doesn\'t depend on `n` as long as Python3 treats `n` as fixed-sized integer, so `n < 10^{18}` or so. For each call we do $O(\\log(N))$ work involving the SortedSet.\n\n- Space complexity: $O(N)$. After $N$ calls to seat there will be $O(N)$ intervals in the SortedSet and endpoints in the maps.\n\n# Code\n```\nfrom sortedcontainers import SortedSet\n\nclass ExamRoom:\n\n @functools.total_ordering\n class Interval:\n def __init__(self, l, r, n):\n self.l = l\n self.r = r\n self.n = n\n\n def dist(self):\n """Returns max distance from l and r to a student seated in (l, r)"""\n l = self.l\n r = self.r\n n = self.n\n\n if l == -1:\n return r\n elif r == n:\n return n-1-l\n else:\n return (r-l)//2\n\n def __hash__(self):\n return self.l * self.n + self.r\n\n def __lt__(self, other):\n sd = self.dist()\n od = other.dist()\n \n if sd > od: # order by distance decreasing\n return True\n elif sd == od: # then by seat increasing\n return self.l < other.l\n else:\n return False\n\n def __eq__(self, other):\n return self.l == other.l and self.r == other.r\n \n def __init__(self, n: int):\n # we have a set of intervals l..r, and to seat people we want an interval \n # to avoid "nobody on left/right" as special cases, we use -1 for nobody on left, and n for nobody on the right\n\n # we use a sorted set so we can get the minimum in log(n) time, and make it a lot easier to delete items\n # as an alternative we could use a priority queue, but python3\'s heapq doesn\'t allow O(log(n)) removal of \n # arbitrary elements. so we\'d have to maintain tombstones, which just gets a lot more complicated\n\n # the intervals we currently have, ordered such that the min element is the one we\'ll set the next student in\n self.n = n\n self.ivs = SortedSet()\n iv = self.Interval(-1, n, n)\n \n self.ivs.add(iv)\n\n # for O(1) access when we delete a student: when we delete p, we need to know the adjacent l and r | the intervals are l..p..r\n self.l2i = {-1: iv}\n self.r2i = {n: iv}\n\n def seat(self) -> int:\n iv = next(iter(self.ivs))\n n = self.n\n # get bisection point, i.e. the seat\n if iv.l == -1:\n s = 0\n elif iv.r == n:\n s = n-1\n else:\n s = iv.l + iv.dist()\n\n # bisect the old interval l..r to form l..s..r\n self.ivs.remove(iv)\n L = self.Interval(iv.l, s, n)\n R = self.Interval(s, iv.r, n)\n self.ivs.add(L)\n self.ivs.add(R)\n self.l2i[iv.l] = L\n self.r2i[s] = L\n self.l2i[s] = R\n self.r2i[iv.r] = R\n\n return s\n\n def leave(self, p: int) -> None:\n # we have intervals l..p..r right now, we need to delete L=l..p and R=p..r and replace with l..r\n L = self.r2i[p]\n R = self.l2i[p]\n\n # delete old intervals\n del self.r2i[p]\n del self.l2i[p]\n self.ivs.remove(L)\n self.ivs.remove(R)\n\n # create unified interval l..r\n iv = self.Interval(L.l, R.r, self.n)\n self.ivs.add(iv)\n self.l2i[L.l] = iv\n self.r2i[R.r] = iv\n \n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
python3
exam-room
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWhen a student enters the examination room, there are three situations:\n\n1. If there is no one in the room, then the student can only sit in the seat 0\n\n2. There are more than two students in the examination room, and it is better to choose the seat where these students are located than to sit directly on the left or right seat of the room;\n\n3. if There are fewer than two students, it is better to sit directly on the left or right seat of the room than to choose seat among these students.\n\n\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.sl = SortedList() \n self.n = n\n\n def seat(self) -> int:\n if not self.sl:\n self.sl.add(0)\n return 0\n\n \n diff, idx = self.sl[0], 0\n\n \n for x, y in pairwise(self.sl):\n if (y - x) // 2 > diff:\n diff = (y - x) // 2\n idx = x + (y - x) // 2\n\n if self.n - 1 - self.sl[-1] > diff:\n diff = self.n - 1 - self.sl[-1]\n idx = self.n - 1\n\n self.sl.add(idx)\n return idx\n\n def leave(self, p: int) -> None:\n self.sl.remove(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number `0`. Design a class that simulates the mentioned exam room. Implement the `ExamRoom` class: * `ExamRoom(int n)` Initializes the object of the exam room with the number of the seats `n`. * `int seat()` Returns the label of the seat at which the next student will set. * `void leave(int p)` Indicates that the student sitting at seat `p` will leave the room. It is guaranteed that there will be a student sitting at seat `p`. **Example 1:** **Input** \[ "ExamRoom ", "seat ", "seat ", "seat ", "seat ", "leave ", "seat "\] \[\[10\], \[\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, 0, 9, 4, 2, null, 5\] **Explanation** ExamRoom examRoom = new ExamRoom(10); examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0. examRoom.seat(); // return 9, the student sits at the last seat number 9. examRoom.seat(); // return 4, the student sits at the last seat number 4. examRoom.seat(); // return 2, the student sits at the last seat number 2. examRoom.leave(4); examRoom.seat(); // return 5, the student sits at the last seat number 5. **Constraints:** * `1 <= n <= 109` * It is guaranteed that there is a student sitting at seat `p`. * At most `104` calls will be made to `seat` and `leave`.
null
python3
exam-room
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWhen a student enters the examination room, there are three situations:\n\n1. If there is no one in the room, then the student can only sit in the seat 0\n\n2. There are more than two students in the examination room, and it is better to choose the seat where these students are located than to sit directly on the left or right seat of the room;\n\n3. if There are fewer than two students, it is better to sit directly on the left or right seat of the room than to choose seat among these students.\n\n\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.sl = SortedList() \n self.n = n\n\n def seat(self) -> int:\n if not self.sl:\n self.sl.add(0)\n return 0\n\n \n diff, idx = self.sl[0], 0\n\n \n for x, y in pairwise(self.sl):\n if (y - x) // 2 > diff:\n diff = (y - x) // 2\n idx = x + (y - x) // 2\n\n if self.n - 1 - self.sl[-1] > diff:\n diff = self.n - 1 - self.sl[-1]\n idx = self.n - 1\n\n self.sl.add(idx)\n return idx\n\n def leave(self, p: int) -> None:\n self.sl.remove(p)\n\n\n# Your ExamRoom object will be instantiated and called as such:\n# obj = ExamRoom(n)\n# param_1 = obj.seat()\n# obj.leave(p)\n```
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Solution
score-of-parentheses
1
1
```C++ []\nclass Solution {\npublic:\n int scoreOfParentheses(string s) {\n int ans=0;\n stack<int> st;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\'){\n st.push(-1);\n }\n else if(st.top()==-1){\n st.pop();\n st.push(1);\n }\n else{\n int temp=0;\n while(st.top()!=-1){\n temp+=st.top();\n st.pop();\n }\n st.pop();\n st.push(2*temp);\n }\n }\n while(!st.empty()){\n ans=ans+st.top();\n st.pop();\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stack = [0]\n for c in s:\n if c == \'(\':\n stack.append(0)\n else:\n v = stack.pop()\n stack[-1] += max(2 * v, 1)\n return stack.pop() \n```\n\n```Java []\nclass Solution {\n public int scoreOfParentheses(String s) {\n Stack<Integer> stack = new Stack<>();\n int cur = 0;\n for (char c : s.toCharArray()) {\n if (c == \'(\') {\n stack.push(cur);\n cur = 0;\n } else {\n cur = stack.pop() + Math.max(cur * 2, 1);\n }\n }\n return cur;\n }\n}\n```\n
2
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Solution
score-of-parentheses
1
1
```C++ []\nclass Solution {\npublic:\n int scoreOfParentheses(string s) {\n int ans=0;\n stack<int> st;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\'){\n st.push(-1);\n }\n else if(st.top()==-1){\n st.pop();\n st.push(1);\n }\n else{\n int temp=0;\n while(st.top()!=-1){\n temp+=st.top();\n st.pop();\n }\n st.pop();\n st.push(2*temp);\n }\n }\n while(!st.empty()){\n ans=ans+st.top();\n st.pop();\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stack = [0]\n for c in s:\n if c == \'(\':\n stack.append(0)\n else:\n v = stack.pop()\n stack[-1] += max(2 * v, 1)\n return stack.pop() \n```\n\n```Java []\nclass Solution {\n public int scoreOfParentheses(String s) {\n Stack<Integer> stack = new Stack<>();\n int cur = 0;\n for (char c : s.toCharArray()) {\n if (c == \'(\') {\n stack.push(cur);\n cur = 0;\n } else {\n cur = stack.pop() + Math.max(cur * 2, 1);\n }\n }\n return cur;\n }\n}\n```\n
2
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
Easy + Efficient Stack Solution - Beats 100 %
score-of-parentheses
0
1
# Intuition\n\nThe question involves calculating the score of a string consisting of balanced parentheses. The scoring rule is as follows: \n\n- `()` has a score of 1.\n- `AB` has a score of \\(A + B\\), where \\(A\\) and \\(B\\) are balanced parentheses strings.\n- `(A)` has a score of 2 * \\(A\\), where \\(A\\) is a balanced parentheses string.\n\nUsing a stack can be a very effective approach here. The stack helps in keeping track of the scores of different levels of nested parentheses. We can iterate through each character in the string, and use the stack to manage the calculation of the scores based on the rules given.\n\n# Approach\n\n1. **Initialization:** \n - Start with initializing a stack with a zero. This zero acts as a temporary value to assist in calculation.\n \n2. **Iteration over the string:**\n - For each character in the string:\n - If the character is \'(\', it marks the start of a new level of parentheses. Append a zero to the stack.\n - If the character is \')\', it marks the end of a current level. Pop the value at the top of the stack, calculate its value, and add it to the value at the new top of the stack.\n\n3. **Calculating the value:**\n - For a closing parenthesis, pop the top of the stack.\n - If the popped value is zero, it means we had an empty pair of parentheses, and we add 1 to the new top of the stack.\n - If the popped value is non-zero, it means we had a nested expression. We multiply the popped value by 2 and add it to the new top of the stack.\n\n4. **Final Result:**\n - After the iteration is over, the stack should contain the total score.\n\n# Complexity\n\n- **Time complexity:** \\(O(n)\\)\n - We are iterating over the string once. Each operation inside the iteration (pushing to and popping from the stack) is constant time. So the time complexity is linear.\n \n- **Space complexity:** \\(O(n)\\)\n - In the worst case, we might end up storing every character of the string in the stack (when there are no nested parentheses, and the string consists of individual pairs of parentheses). So the space complexity is linear.\n \n\n# Code\n```\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n\n stack = [0]\n total = 0\n\n for ch in s:\n if ch == "(":\n stack.append(0)\n\n else:\n top = stack.pop()\n val = max(1,2*top)\n\n stack[-1] += val\n\n return stack.pop()\n\n\n\n```
1
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Easy + Efficient Stack Solution - Beats 100 %
score-of-parentheses
0
1
# Intuition\n\nThe question involves calculating the score of a string consisting of balanced parentheses. The scoring rule is as follows: \n\n- `()` has a score of 1.\n- `AB` has a score of \\(A + B\\), where \\(A\\) and \\(B\\) are balanced parentheses strings.\n- `(A)` has a score of 2 * \\(A\\), where \\(A\\) is a balanced parentheses string.\n\nUsing a stack can be a very effective approach here. The stack helps in keeping track of the scores of different levels of nested parentheses. We can iterate through each character in the string, and use the stack to manage the calculation of the scores based on the rules given.\n\n# Approach\n\n1. **Initialization:** \n - Start with initializing a stack with a zero. This zero acts as a temporary value to assist in calculation.\n \n2. **Iteration over the string:**\n - For each character in the string:\n - If the character is \'(\', it marks the start of a new level of parentheses. Append a zero to the stack.\n - If the character is \')\', it marks the end of a current level. Pop the value at the top of the stack, calculate its value, and add it to the value at the new top of the stack.\n\n3. **Calculating the value:**\n - For a closing parenthesis, pop the top of the stack.\n - If the popped value is zero, it means we had an empty pair of parentheses, and we add 1 to the new top of the stack.\n - If the popped value is non-zero, it means we had a nested expression. We multiply the popped value by 2 and add it to the new top of the stack.\n\n4. **Final Result:**\n - After the iteration is over, the stack should contain the total score.\n\n# Complexity\n\n- **Time complexity:** \\(O(n)\\)\n - We are iterating over the string once. Each operation inside the iteration (pushing to and popping from the stack) is constant time. So the time complexity is linear.\n \n- **Space complexity:** \\(O(n)\\)\n - In the worst case, we might end up storing every character of the string in the stack (when there are no nested parentheses, and the string consists of individual pairs of parentheses). So the space complexity is linear.\n \n\n# Code\n```\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n\n stack = [0]\n total = 0\n\n for ch in s:\n if ch == "(":\n stack.append(0)\n\n else:\n top = stack.pop()\n val = max(1,2*top)\n\n stack[-1] += val\n\n return stack.pop()\n\n\n\n```
1
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null