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
Easy but there are room for optimization!
chalkboard-xor-game
0
1
# Code\n```\nfrom enum import Enum\n\nclass Solution:\n\n def xorGame(self, nums: List[int]) -> bool:\n self.used = set()\n\n class Result(Enum):\n WIN = 1\n LOST = 2\n TURN = 3\n\n class Player(Enum):\n Alice = 1\n Bob = 2\n\n def play (nums):\n # no more changes to play, so win\n if not nums:\n return Result.WIN \n\n # xor of input nums is zero so winning\n tmp = 0\n for i in range(len(nums)):\n if i in self.used:\n continue\n tmp ^= nums[i]\n if tmp == 0:\n return Result.WIN\n\n # find solution\n for i,n in enumerate(nums):\n if i in self.used:\n continue\n if tmp^n != 0:\n self.used.add(i)\n return Result.TURN\n\n # defulat is to loose\n return Result.LOST\n\n # take turn, play until no more num or anybody wins\n res = False\n player = Player.Alice\n for i in range (len(nums)):\n res = play(nums)\n # print (f"{player} plays and returns {res}")\n if res==Result.WIN or res==Result.LOST:\n break\n player = Player.Alice if player==Player.Bob else Player.Bob\n\n # check if Alice wins and return True/False accourdingly\n return True if (res==Result.WIN and player == Player.Alice) or \\\n (res==Result.LOST and player == Player.Bob) else False\n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Easy but there are room for optimization!
chalkboard-xor-game
0
1
# Code\n```\nfrom enum import Enum\n\nclass Solution:\n\n def xorGame(self, nums: List[int]) -> bool:\n self.used = set()\n\n class Result(Enum):\n WIN = 1\n LOST = 2\n TURN = 3\n\n class Player(Enum):\n Alice = 1\n Bob = 2\n\n def play (nums):\n # no more changes to play, so win\n if not nums:\n return Result.WIN \n\n # xor of input nums is zero so winning\n tmp = 0\n for i in range(len(nums)):\n if i in self.used:\n continue\n tmp ^= nums[i]\n if tmp == 0:\n return Result.WIN\n\n # find solution\n for i,n in enumerate(nums):\n if i in self.used:\n continue\n if tmp^n != 0:\n self.used.add(i)\n return Result.TURN\n\n # defulat is to loose\n return Result.LOST\n\n # take turn, play until no more num or anybody wins\n res = False\n player = Player.Alice\n for i in range (len(nums)):\n res = play(nums)\n # print (f"{player} plays and returns {res}")\n if res==Result.WIN or res==Result.LOST:\n break\n player = Player.Alice if player==Player.Bob else Player.Bob\n\n # check if Alice wins and return True/False accourdingly\n return True if (res==Result.WIN and player == Player.Alice) or \\\n (res==Result.LOST and player == Player.Bob) else False\n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
python solution in O(N) and O(N)
chalkboard-xor-game
0
1
# Code\n```\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n xor=0\n for item in nums:xor^=item\n d={}\n for item in nums:\n if(item in d):\n d[item]+=1\n else:\n d[item]=1\n count=0\n for item in d:\n if(d[item]%2==0):\n count+=2\n else:\n count+=1\n return count%2==0 or xor==0\n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
python solution in O(N) and O(N)
chalkboard-xor-game
0
1
# Code\n```\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n xor=0\n for item in nums:xor^=item\n d={}\n for item in nums:\n if(item in d):\n d[item]+=1\n else:\n d[item]=1\n count=0\n for item in d:\n if(d[item]%2==0):\n count+=2\n else:\n count+=1\n return count%2==0 or xor==0\n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Python (Simple Maths)
chalkboard-xor-game
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 xorGame(self, nums):\n return reduce(xor,nums) == 0 or len(nums)%2 == 0\n\n \n \n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Python (Simple Maths)
chalkboard-xor-game
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 xorGame(self, nums):\n return reduce(xor,nums) == 0 or len(nums)%2 == 0\n\n \n \n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Time: O(n)O(n) Space: O(1)O(1)
chalkboard-xor-game
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```\n\n\n\n\n\n\n\n\n\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0\n\n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Time: O(n)O(n) Space: O(1)O(1)
chalkboard-xor-game
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```\n\n\n\n\n\n\n\n\n\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0\n\n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Rigorous proof
chalkboard-xor-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a finite state game, given any initial list of numbers. With each step the list becomes shorter by one element, and there is no drawing state.\nSo there will always be a winner.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume both players plays optimally, that is, each player at least tries not to lose at each step.\nA player wins if and only if exactly one of the following two happens:\n1. they play first and win with the winning initial condition, \n2. they play first or not play first, but can ALWAYS avoid losing in the next turn, or be left with a winning situation.\n\n(2)is the alternative to (1) because there are only finite steps of the game and there must be a winner; if a player can always avoid losing in the next step, then their opponent must lose at some step (otherwise the game goes on indefinitely).\n\n(1)happens if XOR(nums) == 0.\n(2)happens IF AND ONLY IF (1)does not happen, and the player is left with even number of numbers left on the board. \n\nProof of the "if" part:\n1. If all numbers are the same then this player wins.\n2. If not, then they either win, or can always choose a number on the board that is not equals to the XOR of all numbers on the board to erase, thus avoiding losing in the next step.\n\nProof of the "only if" part:\n1. If a player is left with odd numbers of numbers on the board and it is not the first step of the game, they cannot win at this step since if this were the case, their opponent would have been FORCED to leave them with a winning collection of odd numbers of numbers. This contradicts the "if" part of the proof.\n2. Then if the player is facing odd numbers of identical and it is not the first step of the game, they are forced to leave their opponent an even number of elements, and their opponent can avoid losing in the next step.\n3. Since there must be a winner, so someone left with an odd number of elements must not be able to avoid losing in every subsequent step.\n\nSo we have:\nAlice wins if and only if, either the XOR(nums) == 0, or it does not but there are even numbers of elements in nums.\n\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 xorGame(self, nums: List[int]) -> bool:\n a = 0\n for n in nums:\n a^=n\n return len(nums)%2==0 or not a\n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Rigorous proof
chalkboard-xor-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a finite state game, given any initial list of numbers. With each step the list becomes shorter by one element, and there is no drawing state.\nSo there will always be a winner.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume both players plays optimally, that is, each player at least tries not to lose at each step.\nA player wins if and only if exactly one of the following two happens:\n1. they play first and win with the winning initial condition, \n2. they play first or not play first, but can ALWAYS avoid losing in the next turn, or be left with a winning situation.\n\n(2)is the alternative to (1) because there are only finite steps of the game and there must be a winner; if a player can always avoid losing in the next step, then their opponent must lose at some step (otherwise the game goes on indefinitely).\n\n(1)happens if XOR(nums) == 0.\n(2)happens IF AND ONLY IF (1)does not happen, and the player is left with even number of numbers left on the board. \n\nProof of the "if" part:\n1. If all numbers are the same then this player wins.\n2. If not, then they either win, or can always choose a number on the board that is not equals to the XOR of all numbers on the board to erase, thus avoiding losing in the next step.\n\nProof of the "only if" part:\n1. If a player is left with odd numbers of numbers on the board and it is not the first step of the game, they cannot win at this step since if this were the case, their opponent would have been FORCED to leave them with a winning collection of odd numbers of numbers. This contradicts the "if" part of the proof.\n2. Then if the player is facing odd numbers of identical and it is not the first step of the game, they are forced to leave their opponent an even number of elements, and their opponent can avoid losing in the next step.\n3. Since there must be a winner, so someone left with an odd number of elements must not be able to avoid losing in every subsequent step.\n\nSo we have:\nAlice wins if and only if, either the XOR(nums) == 0, or it does not but there are even numbers of elements in nums.\n\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 xorGame(self, nums: List[int]) -> bool:\n a = 0\n for n in nums:\n a^=n\n return len(nums)%2==0 or not a\n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Python one-liner
chalkboard-xor-game
0
1
\n# Code\n```\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n return reduce(lambda x,y:x^y, nums) == 0 or len(nums) % 2 == 0\n # return reduce(xor, nums) == 0 or len(nums) % 2 == 0\n```\n
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Python one-liner
chalkboard-xor-game
0
1
\n# Code\n```\nclass Solution:\n def xorGame(self, nums: List[int]) -> bool:\n return reduce(lambda x,y:x^y, nums) == 0 or len(nums) % 2 == 0\n # return reduce(xor, nums) == 0 or len(nums) % 2 == 0\n```\n
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Simple python code with explanation
chalkboard-xor-game
0
1
```\nclass Solution:\n def xorGame(self, nums):\n #create a variable 0 \n x = 0 \n #iterate over the elements in the nums\n for i in nums:\n #do xor of all the elements\n x ^= i \n #Alice wins in two situations :\n #1.if the xor is already 0 (x == 0 )\n #2.if the length of nums is even because if alice got chance with even length and xor != 0 he will select a number so that he will leave the odd number of same integer \n #if nums == [a,a,a,b] then alice erase b so bob must erase from [a,a,a] so he will lose if he erase any number \n return x == 0 or len(nums)%2 == 0 \n #in other situations bob will win\n```
0
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Simple python code with explanation
chalkboard-xor-game
0
1
```\nclass Solution:\n def xorGame(self, nums):\n #create a variable 0 \n x = 0 \n #iterate over the elements in the nums\n for i in nums:\n #do xor of all the elements\n x ^= i \n #Alice wins in two situations :\n #1.if the xor is already 0 (x == 0 )\n #2.if the length of nums is even because if alice got chance with even length and xor != 0 he will select a number so that he will leave the odd number of same integer \n #if nums == [a,a,a,b] then alice erase b so bob must erase from [a,a,a] so he will lose if he erase any number \n return x == 0 or len(nums)%2 == 0 \n #in other situations bob will win\n```
0
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Most Ever Easy Solution 🔥🔥🔥
subdomain-visit-count
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 subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n domain_count = defaultdict(int)\n \n for cpdomain in cpdomains:\n count, domain = cpdomain.split(" ")\n count = int(count)\n \n subdomains = domain.split(".") \n for i in range(len(subdomains)):\n subdomain = ".".join(subdomains[i:])\n domain_count[subdomain] += count\n\n result = [str(count) + " " + subdomain for subdomain, count in domain_count.items()]\n \n return result\n```
2
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Most Ever Easy Solution 🔥🔥🔥
subdomain-visit-count
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 subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n domain_count = defaultdict(int)\n \n for cpdomain in cpdomains:\n count, domain = cpdomain.split(" ")\n count = int(count)\n \n subdomains = domain.split(".") \n for i in range(len(subdomains)):\n subdomain = ".".join(subdomains[i:])\n domain_count[subdomain] += count\n\n result = [str(count) + " " + subdomain for subdomain, count in domain_count.items()]\n \n return result\n```
2
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Solution
subdomain-visit-count
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> subdomainVisits(vector<string>& cp) { \n unordered_map<string,int>mpp;\n vector<string>res;\n int n = cp.size();\n for(int i = 0; i < n; ++i)\n { \n int j = cp[i].size() - 1;\n string temp;\n int val = stoi(cp[i]);\n while(cp[i][j]!=\' \')\n {\n if(cp[i][j]==\'.\')\n { \n string c = temp;\n reverse(c.begin(),c.end());\n mpp[c] += val; \n } \n temp.push_back(cp[i][j]);\n j--; \n }\n reverse(temp.begin(),temp.end());\n mpp[temp] += val;\n }\n for(auto it : mpp) res.push_back(to_string(it.second) +" "+it.first);\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n count_map = collections.defaultdict(int)\n for cpdomain in cpdomains:\n count, domain = cpdomain.split()\n count = int(count)\n count_map[domain] += count\n for index in range(len(domain)):\n if domain[index] == \'.\':\n count_map[domain[index + 1:]] += count\n result = []\n for domain in count_map.keys():\n result.append(str(count_map[domain]) + \' \' + domain)\n return result\n```\n\n```Java []\nclass Solution {\n static void domain_visit(String s,HashMap<String,Integer> hm) { \n int visit_cnt = Integer.valueOf(s.substring(0,s.indexOf(" ")));\n String new_str = s.substring(s.indexOf(" ")+1,s.length());\n List<Integer> al = new ArrayList<>();al.add(-1);\n\tfor(int i=0;i<new_str.length();++i) {\n\t\tif(new_str.charAt(i)==\'.\') al.add(i);\n\t}\n\t for (int it:al) {\n String res = (new_str.substring(it+1,new_str.length()));\n hm.put(res,hm.getOrDefault(res,0)+visit_cnt);\n }\n }\n public List<String> subdomainVisits(String[] cpdomains) {\n HashMap<String,Integer> hm = new HashMap<>();\n for (String str:cpdomains) {\n domain_visit(str,hm);\n }\n List<String> root_domains = new ArrayList<>();\n for (String res : hm.keySet()) {\n int x = hm.get(res);\n StringBuilder sb = new StringBuilder();\n sb.append(String.valueOf(x));sb.append(" ");sb.append(res);\n root_domains.add(sb.toString());\n }\n return(root_domains);\n }\n}\n```\n
2
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Solution
subdomain-visit-count
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> subdomainVisits(vector<string>& cp) { \n unordered_map<string,int>mpp;\n vector<string>res;\n int n = cp.size();\n for(int i = 0; i < n; ++i)\n { \n int j = cp[i].size() - 1;\n string temp;\n int val = stoi(cp[i]);\n while(cp[i][j]!=\' \')\n {\n if(cp[i][j]==\'.\')\n { \n string c = temp;\n reverse(c.begin(),c.end());\n mpp[c] += val; \n } \n temp.push_back(cp[i][j]);\n j--; \n }\n reverse(temp.begin(),temp.end());\n mpp[temp] += val;\n }\n for(auto it : mpp) res.push_back(to_string(it.second) +" "+it.first);\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n count_map = collections.defaultdict(int)\n for cpdomain in cpdomains:\n count, domain = cpdomain.split()\n count = int(count)\n count_map[domain] += count\n for index in range(len(domain)):\n if domain[index] == \'.\':\n count_map[domain[index + 1:]] += count\n result = []\n for domain in count_map.keys():\n result.append(str(count_map[domain]) + \' \' + domain)\n return result\n```\n\n```Java []\nclass Solution {\n static void domain_visit(String s,HashMap<String,Integer> hm) { \n int visit_cnt = Integer.valueOf(s.substring(0,s.indexOf(" ")));\n String new_str = s.substring(s.indexOf(" ")+1,s.length());\n List<Integer> al = new ArrayList<>();al.add(-1);\n\tfor(int i=0;i<new_str.length();++i) {\n\t\tif(new_str.charAt(i)==\'.\') al.add(i);\n\t}\n\t for (int it:al) {\n String res = (new_str.substring(it+1,new_str.length()));\n hm.put(res,hm.getOrDefault(res,0)+visit_cnt);\n }\n }\n public List<String> subdomainVisits(String[] cpdomains) {\n HashMap<String,Integer> hm = new HashMap<>();\n for (String str:cpdomains) {\n domain_visit(str,hm);\n }\n List<String> root_domains = new ArrayList<>();\n for (String res : hm.keySet()) {\n int x = hm.get(res);\n StringBuilder sb = new StringBuilder();\n sb.append(String.valueOf(x));sb.append(" ");sb.append(res);\n root_domains.add(sb.toString());\n }\n return(root_domains);\n }\n}\n```\n
2
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Python3 Dictionary 90% faster
subdomain-visit-count
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 subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n res = []\n visits = {}\n\n for cp in cpdomains:\n l = cp.split(\' \')\n value = l[0]\n domain = l[1]\n\n subdomains = domain.split(".")\n \n for i in range(len(subdomains)):\n sub = \'.\'.join(subdomains[i:])\n\n\n if sub not in visits:\n visits[sub] = value\n else:\n visits[sub] = str(int(visits[sub]) + int(value))\n \n for k, v in visits.items():\n res.append(v+\' \'+k)\n\n return res\n```
3
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Python3 Dictionary 90% faster
subdomain-visit-count
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 subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n res = []\n visits = {}\n\n for cp in cpdomains:\n l = cp.split(\' \')\n value = l[0]\n domain = l[1]\n\n subdomains = domain.split(".")\n \n for i in range(len(subdomains)):\n sub = \'.\'.join(subdomains[i:])\n\n\n if sub not in visits:\n visits[sub] = value\n else:\n visits[sub] = str(int(visits[sub]) + int(value))\n \n for k, v in visits.items():\n res.append(v+\' \'+k)\n\n return res\n```
3
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Python3 100% faster, 100% less memory (32ms, 14.1mb)
subdomain-visit-count
0
1
```\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n d = defaultdict(int)\n for s in cpdomains:\n cnt, s = s.split()\n cnt = int(cnt)\n d[s] += cnt\n pos = s.find(\'.\') + 1\n while pos > 0:\n d[s[pos:]] += cnt\n pos = s.find(\'.\', pos) + 1\n for x, i in d.items():\n yield f\'{i} {x}\'\n```
10
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Python3 100% faster, 100% less memory (32ms, 14.1mb)
subdomain-visit-count
0
1
```\nclass Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n d = defaultdict(int)\n for s in cpdomains:\n cnt, s = s.split()\n cnt = int(cnt)\n d[s] += cnt\n pos = s.find(\'.\') + 1\n while pos > 0:\n d[s[pos:]] += cnt\n pos = s.find(\'.\', pos) + 1\n for x, i in d.items():\n yield f\'{i} {x}\'\n```
10
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._ **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation:** 5 = 2 + 3 **Example 2:** **Input:** n = 9 **Output:** 3 **Explanation:** 9 = 4 + 5 = 2 + 3 + 4 **Example 3:** **Input:** n = 15 **Output:** 4 **Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 **Constraints:** * `1 <= n <= 109`
null
Solution
largest-triangle-area
1
1
```C++ []\nclass Solution {\npublic:\n double largestTriangleArea(vector<vector<int>>& points) {\n double maxarea=INT_MIN;\n double area=0;\n int i,j,k;\n double x1,x2,y1,y2,x3,y3;\n int n=points.size();\n for(i=0;i<n;i++)\n {\n x1=points[i][0];\n y1=points[i][1];\n for(j=i+1;j<n;j++)\n {\n x2=points[j][0];\n y2=points[j][1];\n for(k=j+1;k<n;k++)\n {\n x3=points[k][0];\n y3=points[k][1];\n area=0.5*(abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)));\n if(area>maxarea)\n {\n maxarea=area;\n }\n }\n }\n }\n return maxarea;\n }\n};\n```\n\n```Python3 []\nfrom itertools import combinations\n\nclass Solution:\n def largestTriangleArea(self, points: list[list[int]]) -> float:\n return max(\n abs(getVector(a, b, c)) / 2\n for a, b, c in combinations(getBoundary(points), 3)\n )\ndef getBoundary(points):\n points = [(a, b) for a, b in points]\n points.sort(key=lambda x: (x[0], x[1]))\n\n upper = []\n lower = []\n\n for point in points:\n\n while len(lower) >= 2 and getVector(lower[-2], lower[-1], point) < 0:\n lower.pop()\n lower.append(point)\n\n while len(upper) >= 2 and getVector(upper[-2], upper[-1], point) > 0:\n upper.pop()\n upper.append(point)\n\n return list(set(upper + lower))\n\ndef getVector(a, b, c):\n return (b[0] - a[0]) * (b[1] - c[1]) - (b[1] - a[1]) * (b[0] - c[0])\n```\n\n```Java []\nclass Solution {\n double maxArea = Integer.MIN_VALUE;\n int[] idxList = new int[3];\n int n, k;\n\n public double largestTriangleArea(int[][] points) {\n if(points == null) return 0;\n n = points.length;\n k = 3;\n dfs(points, 0, 0);\n return maxArea;\n }\n public void dfs(int[][] points, int pre, int idx){\n if(idx >= k){\n maxArea = Math.max(getArea(points), maxArea);\n return;\n }\n for(int i = pre + 1; i <= n; i ++){\n idxList[idx] = i - 1;\n dfs(points, i, idx + 1); \n }\n }\n public double getArea(int[][] points){\n return Math.abs(0.5 * (points[idxList[0]][0] * (points[idxList[1]][1] - points[idxList[2]][1]) +\n points[idxList[1]][0] * (points[idxList[2]][1] - points[idxList[0]][1]) +\n points[idxList[2]][0] * (points[idxList[0]][1] - points[idxList[1]][1])));\n }\n}\n```\n
1
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Solution
largest-triangle-area
1
1
```C++ []\nclass Solution {\npublic:\n double largestTriangleArea(vector<vector<int>>& points) {\n double maxarea=INT_MIN;\n double area=0;\n int i,j,k;\n double x1,x2,y1,y2,x3,y3;\n int n=points.size();\n for(i=0;i<n;i++)\n {\n x1=points[i][0];\n y1=points[i][1];\n for(j=i+1;j<n;j++)\n {\n x2=points[j][0];\n y2=points[j][1];\n for(k=j+1;k<n;k++)\n {\n x3=points[k][0];\n y3=points[k][1];\n area=0.5*(abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)));\n if(area>maxarea)\n {\n maxarea=area;\n }\n }\n }\n }\n return maxarea;\n }\n};\n```\n\n```Python3 []\nfrom itertools import combinations\n\nclass Solution:\n def largestTriangleArea(self, points: list[list[int]]) -> float:\n return max(\n abs(getVector(a, b, c)) / 2\n for a, b, c in combinations(getBoundary(points), 3)\n )\ndef getBoundary(points):\n points = [(a, b) for a, b in points]\n points.sort(key=lambda x: (x[0], x[1]))\n\n upper = []\n lower = []\n\n for point in points:\n\n while len(lower) >= 2 and getVector(lower[-2], lower[-1], point) < 0:\n lower.pop()\n lower.append(point)\n\n while len(upper) >= 2 and getVector(upper[-2], upper[-1], point) > 0:\n upper.pop()\n upper.append(point)\n\n return list(set(upper + lower))\n\ndef getVector(a, b, c):\n return (b[0] - a[0]) * (b[1] - c[1]) - (b[1] - a[1]) * (b[0] - c[0])\n```\n\n```Java []\nclass Solution {\n double maxArea = Integer.MIN_VALUE;\n int[] idxList = new int[3];\n int n, k;\n\n public double largestTriangleArea(int[][] points) {\n if(points == null) return 0;\n n = points.length;\n k = 3;\n dfs(points, 0, 0);\n return maxArea;\n }\n public void dfs(int[][] points, int pre, int idx){\n if(idx >= k){\n maxArea = Math.max(getArea(points), maxArea);\n return;\n }\n for(int i = pre + 1; i <= n; i ++){\n idxList[idx] = i - 1;\n dfs(points, i, idx + 1); \n }\n }\n public double getArea(int[][] points){\n return Math.abs(0.5 * (points[idxList[0]][0] * (points[idxList[1]][1] - points[idxList[2]][1]) +\n points[idxList[1]][0] * (points[idxList[2]][1] - points[idxList[0]][1]) +\n points[idxList[2]][0] * (points[idxList[0]][1] - points[idxList[1]][1])));\n }\n}\n```\n
1
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Python || Faster than 93% || Simple maths || with explanation
largest-triangle-area
0
1
I used my highschool determinants formula of area of a triangle\n if coordinates are given\n 1/2(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))\n Explanation link: https://www.cuemath.com/geometry/area-of-triangle-in-coordinate-geometry/\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float: \n \n area = 0\n n = len(points)\n for i in range(n):\n x1,y1 = points[i]\n for j in range(i+1,n):\n x2,y2 = points[j]\n for k in range(j+1,n):\n x3,y3 = points[k]\n curr = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n if curr>area:\n area = curr\n return area\n \n \n \n \n \n```
31
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Python || Faster than 93% || Simple maths || with explanation
largest-triangle-area
0
1
I used my highschool determinants formula of area of a triangle\n if coordinates are given\n 1/2(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))\n Explanation link: https://www.cuemath.com/geometry/area-of-triangle-in-coordinate-geometry/\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float: \n \n area = 0\n n = len(points)\n for i in range(n):\n x1,y1 = points[i]\n for j in range(i+1,n):\n x2,y2 = points[j]\n for k in range(j+1,n):\n x3,y3 = points[k]\n curr = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n if curr>area:\n area = curr\n return area\n \n \n \n \n \n```
31
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Only one line on Python
largest-triangle-area
0
1
\n# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n\n \n return max(abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))) for [x1,y1], [x2,y2], [x3,y3] in combinations(points, 3))\n\n\n\n\n\n\n```
2
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Only one line on Python
largest-triangle-area
0
1
\n# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n\n \n return max(abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))) for [x1,y1], [x2,y2], [x3,y3] in combinations(points, 3))\n\n\n\n\n\n\n```
2
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Python Solution 99% Faster
largest-triangle-area
0
1
Using the coordinate geometry area of triangle formula:\nhttps://www.brainkart.com/article/Area-of-a-Triangle_39390/\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n \n area = 0\n \n for i in range(len(points)-2):\n x1,y1 = points[i]\n for j in range(i+1,len(points)-1):\n x2,y2 = points[j]\n for k in range(j+1,len(points)):\n x3,y3 = points[k]\n curr_area = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n if (curr_area > area):\n area = curr_area\n \n return area\n\nUpvote if you liked the solution!
3
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Python Solution 99% Faster
largest-triangle-area
0
1
Using the coordinate geometry area of triangle formula:\nhttps://www.brainkart.com/article/Area-of-a-Triangle_39390/\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n \n area = 0\n \n for i in range(len(points)-2):\n x1,y1 = points[i]\n for j in range(i+1,len(points)-1):\n x2,y2 = points[j]\n for k in range(j+1,len(points)):\n x3,y3 = points[k]\n curr_area = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n if (curr_area > area):\n area = curr_area\n \n return area\n\nUpvote if you liked the solution!
3
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Python 1 line solution
largest-triangle-area
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom itertools import combinations\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n return max(abs(a[0] * b[1] + a[1] * c[0] + b[0] * c[1] - b[1] * c[0] - a[1] * b[0] - a[0] * c[1]) for a, b, c in combinations(points, 3)) / 2\n```
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Python 1 line solution
largest-triangle-area
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom itertools import combinations\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n return max(abs(a[0] * b[1] + a[1] * c[0] + b[0] * c[1] - b[1] * c[0] - a[1] * b[0] - a[0] * c[1]) for a, b, c in combinations(points, 3)) / 2\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
812: Solution with step by step explanation
largest-triangle-area
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWithin the largest Triangle Area method, we define a helper function triangle_area which takes three points and calculates the area of the triangle formed by these points using the Shoelace formula. The formula is based on the coordinates of the vertices of the triangle.\n\n```\n def triangle_area(p1, p2, p3):\n return abs(p1[0]*p2[1] + p2[0]*p3[1] + p3[0]*p1[1] - p1[1]*p2[0] - p2[1]*p3[0] - p3[1]*p1[0])\n````\n\nWe then use a generator expression to calculate the area of every possible triangle formed by three distinct points from the list, using the combinations function from the itertools module to generate all possible sets of three points.\n\n```\n return max(triangle_area(*triangle) for triangle in combinations(points, 3)) / 2.0\n```\n\nHere we divide by 2.0 because the Shoelace formula actually gives twice the area of the triangle, so we need to halve it to get the correct area.\n\n# Complexity\n- Time complexity:\nO(n ^ 3)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n def triangle_area(p1, p2, p3):\n return abs(p1[0]*p2[1] + p2[0]*p3[1] + p3[0]*p1[1] - p1[1]*p2[0] - p2[1]*p3[0] - p3[1]*p1[0])\n\n return max(triangle_area(*triangle) for triangle in combinations(points, 3)) / 2.0\n\n```
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
812: Solution with step by step explanation
largest-triangle-area
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWithin the largest Triangle Area method, we define a helper function triangle_area which takes three points and calculates the area of the triangle formed by these points using the Shoelace formula. The formula is based on the coordinates of the vertices of the triangle.\n\n```\n def triangle_area(p1, p2, p3):\n return abs(p1[0]*p2[1] + p2[0]*p3[1] + p3[0]*p1[1] - p1[1]*p2[0] - p2[1]*p3[0] - p3[1]*p1[0])\n````\n\nWe then use a generator expression to calculate the area of every possible triangle formed by three distinct points from the list, using the combinations function from the itertools module to generate all possible sets of three points.\n\n```\n return max(triangle_area(*triangle) for triangle in combinations(points, 3)) / 2.0\n```\n\nHere we divide by 2.0 because the Shoelace formula actually gives twice the area of the triangle, so we need to halve it to get the correct area.\n\n# Complexity\n- Time complexity:\nO(n ^ 3)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n def triangle_area(p1, p2, p3):\n return abs(p1[0]*p2[1] + p2[0]*p3[1] + p3[0]*p1[1] - p1[1]*p2[0] - p2[1]*p3[0] - p3[1]*p1[0])\n\n return max(triangle_area(*triangle) for triangle in combinations(points, 3)) / 2.0\n\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Trivial af
largest-triangle-area
0
1
# Intuition\nbasic stuff frr\n\n# Code\n```\nSolution = type.__new__(type, "Solution", (), {"largestTriangleArea": lambda self, points : max(0.5*abs(a[0]*(b[1]-c[1])+b[0]*(c[1]-a[1])+c[0]*(a[1]-b[1])) for a, b, c in __import__("itertools").combinations(points, 3))})\n \n```
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Trivial af
largest-triangle-area
0
1
# Intuition\nbasic stuff frr\n\n# Code\n```\nSolution = type.__new__(type, "Solution", (), {"largestTriangleArea": lambda self, points : max(0.5*abs(a[0]*(b[1]-c[1])+b[0]*(c[1]-a[1])+c[0]*(a[1]-b[1])) for a, b, c in __import__("itertools").combinations(points, 3))})\n \n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
[python3] fast and simple
largest-triangle-area
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 largestTriangleArea(self, points: List[List[int]]) -> float:\n n=len(points)\n largestArea=0\n for i in range(n):\n for j in range(i+1,n):\n if i!=j:\n for k in range(j+1,n):\n a=self.areaOfTriangle(points[i],points[j],points[k])\n if a>largestArea:\n largestArea=a\n return largestArea\n \n def areaOfTriangle(self,a,b,c)->float:\n return 0.5*abs((a[0]*(b[1]-c[1]))+(b[0]*(c[1]-a[1]))+(c[0]*(a[1]-b[1])))\n\n#area of arbitrary triangle\n#triplet-wise comparison\n```
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
[python3] fast and simple
largest-triangle-area
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 largestTriangleArea(self, points: List[List[int]]) -> float:\n n=len(points)\n largestArea=0\n for i in range(n):\n for j in range(i+1,n):\n if i!=j:\n for k in range(j+1,n):\n a=self.areaOfTriangle(points[i],points[j],points[k])\n if a>largestArea:\n largestArea=a\n return largestArea\n \n def areaOfTriangle(self,a,b,c)->float:\n return 0.5*abs((a[0]*(b[1]-c[1]))+(b[0]*(c[1]-a[1]))+(c[0]*(a[1]-b[1])))\n\n#area of arbitrary triangle\n#triplet-wise comparison\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Readable solutions
largest-triangle-area
0
1
# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n # 110ms\n # Beats 46.44% of users with Python3\n ret, n = 0, len(points)\n for i in range(n):\n for j in range(i+1, n):\n for k in range(j+1, n):\n x1, y1 = points[i]\n x2, y2 = points[j]\n x3, y3 = points[k]\n\n total = x1 * (y2 - y3)\n total += x2 * (y3 - y1)\n total += x3 * (y1 - y2)\n ret = max(ret, abs(0.5 * total))\n \n return ret\n```
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Readable solutions
largest-triangle-area
0
1
# Code\n```\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n # 110ms\n # Beats 46.44% of users with Python3\n ret, n = 0, len(points)\n for i in range(n):\n for j in range(i+1, n):\n for k in range(j+1, n):\n x1, y1 = points[i]\n x2, y2 = points[j]\n x3, y3 = points[k]\n\n total = x1 * (y2 - y3)\n total += x2 * (y3 - y1)\n total += x3 * (y1 - y2)\n ret = max(ret, abs(0.5 * total))\n \n return ret\n```
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Simple with unit tests
largest-triangle-area
0
1
```\nfrom typing import List\n\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n """\n Calculate the surface of the largest triangle from 3 points on 2-D plain from the list.\n\n Triangle size is height/2 * b. Height is perpendicular to on the b side and touches the vertex.\n There is a formula for triangle from coordinates also called determinant: `A = (1/2) |x1(y2 \u2212 y3) + x2(y3 \u2212 y1) + x3(y1 \u2212 y2)|`\n\n The simplest solution is iterating over all combinations with time complexity of O(N**3).\n There are more complex solutions involving Gift Wrapping Algorithms.\n\n >>> Solution().largestTriangleArea([[0,0],[0,1],[1,0],[0,2],[2,0]])\n 2.0\n\n >>> Solution().largestTriangleArea([[1,0],[0,0],[0,1]])\n 0.5\n\n >>> Solution().largestTriangleArea([[1,0],[0,0]])\n 0.0\n\n >>> Solution().largestTriangleArea([[1,0],[0,0], [0,0]])\n 0.0\n\n """\n\n if len(points) < 3:\n return 0.0\n\n max_area = 0.0\n for (x1, y1) in points:\n for (x2, y2) in points:\n for (x3, y3) in points:\n area = abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)\n if area > max_area:\n max_area = area\n\n return max_area\n\n\n```\n\n\n## Follow me for more software and machine learning at https://vaclavkosar.com/
0
Given an array of points on the **X-Y** plane `points` where `points[i] = [xi, yi]`, return _the area of the largest triangle that can be formed by any three different points_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** points = \[\[0,0\],\[0,1\],\[1,0\],\[0,2\],\[2,0\]\] **Output:** 2.00000 **Explanation:** The five points are shown in the above figure. The red triangle is the largest. **Example 2:** **Input:** points = \[\[1,0\],\[0,0\],\[0,1\]\] **Output:** 0.50000 **Constraints:** * `3 <= points.length <= 50` * `-50 <= xi, yi <= 50` * All the given points are **unique**.
null
Simple with unit tests
largest-triangle-area
0
1
```\nfrom typing import List\n\n\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n """\n Calculate the surface of the largest triangle from 3 points on 2-D plain from the list.\n\n Triangle size is height/2 * b. Height is perpendicular to on the b side and touches the vertex.\n There is a formula for triangle from coordinates also called determinant: `A = (1/2) |x1(y2 \u2212 y3) + x2(y3 \u2212 y1) + x3(y1 \u2212 y2)|`\n\n The simplest solution is iterating over all combinations with time complexity of O(N**3).\n There are more complex solutions involving Gift Wrapping Algorithms.\n\n >>> Solution().largestTriangleArea([[0,0],[0,1],[1,0],[0,2],[2,0]])\n 2.0\n\n >>> Solution().largestTriangleArea([[1,0],[0,0],[0,1]])\n 0.5\n\n >>> Solution().largestTriangleArea([[1,0],[0,0]])\n 0.0\n\n >>> Solution().largestTriangleArea([[1,0],[0,0], [0,0]])\n 0.0\n\n """\n\n if len(points) < 3:\n return 0.0\n\n max_area = 0.0\n for (x1, y1) in points:\n for (x2, y2) in points:\n for (x3, y3) in points:\n area = abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)\n if area > max_area:\n max_area = area\n\n return max_area\n\n\n```\n\n\n## Follow me for more software and machine learning at https://vaclavkosar.com/
0
In a string `s` of lowercase letters, these letters form consecutive groups of the same character. For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`. A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`. A group is considered **large** if it has 3 or more characters. Return _the intervals of every **large** group sorted in **increasing order by start index**_. **Example 1:** **Input:** s = "abbxxxxzzy " **Output:** \[\[3,6\]\] **Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6. **Example 2:** **Input:** s = "abc " **Output:** \[\] **Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups. **Example 3:** **Input:** s = "abcdddeeeeaabbbcd " **Output:** \[\[3,5\],\[6,9\],\[12,14\]\] **Explanation:** The large groups are "ddd ", "eeee ", and "bbb ". **Constraints:** * `1 <= s.length <= 1000` * `s` contains lowercase English letters only.
null
Dynamic Programming. Super easy to understand. Python Solution.
largest-sum-of-averages
0
1
# Intuition\nRecursively parition at each index and call the function with the next index i.e j ( We do this to find maximum average in each parition)\n\nIf we have only one more partition left, it means to calculate the average for the rest of the elements \n\nWhy?\n\nIn each parition we divide the array into 2\n\n**For K =3**\n\nIn first partition, k = 2\n[9| 1 2 3 9]\n\nAfter second partition, k= 1\n\n[9 | 1 2 3 | **9**]\n\nby then we would\'ve made three parititons.\n So we just have to calculate for the remaining portion which is the last 9 in this case\n\n\n# Complexity\n- Time complexity:\nO(len(nums)^2)\n\n\n# Code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n \n @functools.lru_cache(None)\n def dfs(i,k):\n\n if k == 1:\n return sum(nums[i:])/len(nums[i:]) #Calculate sum for the remaining elements\n\n maxAvg = 0\n\n for j in range(i+1, len(nums)): #Try paritioning at each index and calculate average\n\n avg = sum(nums[i:j])/len(nums[i:j])\n\n subarrayAvg = avg + dfs(j, k-1) #Call with the next index (j) after partition\n\n maxAvg = max(maxAvg, subarrayAvg)\n\n return maxAvg\n\n return dfs(0,k)\n \n\n \n```
1
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
Dynamic Programming. Super easy to understand. Python Solution.
largest-sum-of-averages
0
1
# Intuition\nRecursively parition at each index and call the function with the next index i.e j ( We do this to find maximum average in each parition)\n\nIf we have only one more partition left, it means to calculate the average for the rest of the elements \n\nWhy?\n\nIn each parition we divide the array into 2\n\n**For K =3**\n\nIn first partition, k = 2\n[9| 1 2 3 9]\n\nAfter second partition, k= 1\n\n[9 | 1 2 3 | **9**]\n\nby then we would\'ve made three parititons.\n So we just have to calculate for the remaining portion which is the last 9 in this case\n\n\n# Complexity\n- Time complexity:\nO(len(nums)^2)\n\n\n# Code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n \n @functools.lru_cache(None)\n def dfs(i,k):\n\n if k == 1:\n return sum(nums[i:])/len(nums[i:]) #Calculate sum for the remaining elements\n\n maxAvg = 0\n\n for j in range(i+1, len(nums)): #Try paritioning at each index and calculate average\n\n avg = sum(nums[i:j])/len(nums[i:j])\n\n subarrayAvg = avg + dfs(j, k-1) #Call with the next index (j) after partition\n\n maxAvg = max(maxAvg, subarrayAvg)\n\n return maxAvg\n\n return dfs(0,k)\n \n\n \n```
1
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Solution
largest-sum-of-averages
1
1
```C++ []\n#define inf -100000.0\n\nclass Solution {\npublic:\n double large_sum(vector<vector<double>> &dp,vector<int> & nums,int i, int k ){\n if(i>=nums.size()){\n return 0.0;\n }\n if(k<=0){\n return inf;\n }\n if(dp[i][k]!=-1){\n return dp[i][k];\n }\n double sum=0;\n double best_sum=0.0;\n for(int j=i;j<nums.size()-k+1;j++){\n sum+=nums[j];\n best_sum=max(best_sum, sum/(j-i+1) + large_sum(dp,nums,j+1,k-1));\n }\n return dp[i][k]=best_sum;\n }\n double largestSumOfAverages(vector<int>& nums, int k) {\n int n=nums.size();\n vector<vector<double>> dp(n,vector<double>(k+1,-1));\n return large_sum(dp,nums,0,k);\n }\n};\n```\n\n```Python3 []\nclass Solution: \n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n @cache\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return get_avg(start, n) \n return max(get_avg(start, end) + dfs(end, parts - 1) for end in range(start + 1, n - parts + 2))\n n = len(nums)\n running_sums = list(accumulate(nums, initial=0))\n get_avg = lambda start, end: (running_sums[end] - running_sums[start]) / (end - start) \n return dfs(0, k)\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n @cache\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return get_avg(start, n) # (running_sums[n] - running_sums[start]) / (n - start) \n cur, total, length = 0, 0, 0 \n for end in range(start, n - parts + 1): \n cur = max(cur, get_avg(start, end + 1) + dfs(end + 1, parts - 1))\n return cur\n n = len(nums)\n running_sums = list(accumulate(nums, initial=0))\n get_avg = lambda start, end: (running_sums[end] - running_sums[start]) / (end - start) \n return dfs(0, k)\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n n = len(nums)\n dp = [[0 for _ in range(k + 1)] for _ in range(n)]\n running_sums = [0] #list(accumulate(nums, initial=0))\n total = 0 \n for i in range(n):\n total += nums[i]\n running_sums.append(total)\n dp[i][1] = total / (i + 1)\n \n for parts in range(2, k + 1):\n for end in range(parts - 1, n):\n for start in range(end):\n dp[end][parts] = max(dp[end][parts], dp[start][parts - 1] + \\\n (running_sums[end + 1] - running_sums[start + 1]) / (end - start)) \n #sum(nums[start + 1:end + 1]) / (end - start )) \n return dp[n - 1][k]\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n from functools import lru_cache\n @lru_cache(None)\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return sum(nums[start:]) / (n - start) \n cur, total, length = 0, 0, 0 \n for end in range(start, n - parts + 1):\n length += 1\n total += nums[end] \n cur = max(cur, total / length + dfs(end + 1, parts - 1))\n return cur\n n = len(nums)\n return dfs(0, k)\n```\n\n```Java []\nclass Solution {\n public double largestSumOfAverages(int[] A, int K) {\n final int n = A.length;\n dp = new double[n + 1][K + 1];\n prefix = new double[n + 1];\n\n for (int i = 0; i < n; ++i)\n prefix[i + 1] = A[i] + prefix[i];\n\n return largestSumOfAverages(A, n, K);\n }\n private double[][] dp;\n private double[] prefix;\n\n private double largestSumOfAverages(int[] A, int i, int k) {\n if (k == 1)\n return prefix[i] / i;\n if (dp[i][k] > 0.0)\n return dp[i][k];\n\n for (int j = k - 1; j < i; ++j)\n dp[i][k] =\n Math.max(dp[i][k], largestSumOfAverages(A, j, k - 1) + (prefix[i] - prefix[j]) / (i - j));\n\n return dp[i][k];\n }\n}\n```\n
1
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
Solution
largest-sum-of-averages
1
1
```C++ []\n#define inf -100000.0\n\nclass Solution {\npublic:\n double large_sum(vector<vector<double>> &dp,vector<int> & nums,int i, int k ){\n if(i>=nums.size()){\n return 0.0;\n }\n if(k<=0){\n return inf;\n }\n if(dp[i][k]!=-1){\n return dp[i][k];\n }\n double sum=0;\n double best_sum=0.0;\n for(int j=i;j<nums.size()-k+1;j++){\n sum+=nums[j];\n best_sum=max(best_sum, sum/(j-i+1) + large_sum(dp,nums,j+1,k-1));\n }\n return dp[i][k]=best_sum;\n }\n double largestSumOfAverages(vector<int>& nums, int k) {\n int n=nums.size();\n vector<vector<double>> dp(n,vector<double>(k+1,-1));\n return large_sum(dp,nums,0,k);\n }\n};\n```\n\n```Python3 []\nclass Solution: \n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n @cache\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return get_avg(start, n) \n return max(get_avg(start, end) + dfs(end, parts - 1) for end in range(start + 1, n - parts + 2))\n n = len(nums)\n running_sums = list(accumulate(nums, initial=0))\n get_avg = lambda start, end: (running_sums[end] - running_sums[start]) / (end - start) \n return dfs(0, k)\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n @cache\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return get_avg(start, n) # (running_sums[n] - running_sums[start]) / (n - start) \n cur, total, length = 0, 0, 0 \n for end in range(start, n - parts + 1): \n cur = max(cur, get_avg(start, end + 1) + dfs(end + 1, parts - 1))\n return cur\n n = len(nums)\n running_sums = list(accumulate(nums, initial=0))\n get_avg = lambda start, end: (running_sums[end] - running_sums[start]) / (end - start) \n return dfs(0, k)\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n n = len(nums)\n dp = [[0 for _ in range(k + 1)] for _ in range(n)]\n running_sums = [0] #list(accumulate(nums, initial=0))\n total = 0 \n for i in range(n):\n total += nums[i]\n running_sums.append(total)\n dp[i][1] = total / (i + 1)\n \n for parts in range(2, k + 1):\n for end in range(parts - 1, n):\n for start in range(end):\n dp[end][parts] = max(dp[end][parts], dp[start][parts - 1] + \\\n (running_sums[end + 1] - running_sums[start + 1]) / (end - start)) \n #sum(nums[start + 1:end + 1]) / (end - start )) \n return dp[n - 1][k]\n \n def largestSumOfAverages_(self, nums: List[int], k: int) -> float:\n from functools import lru_cache\n @lru_cache(None)\n def dfs(start, parts):\n if parts <= 0 or start >= n: return 0\n if parts == 1: return sum(nums[start:]) / (n - start) \n cur, total, length = 0, 0, 0 \n for end in range(start, n - parts + 1):\n length += 1\n total += nums[end] \n cur = max(cur, total / length + dfs(end + 1, parts - 1))\n return cur\n n = len(nums)\n return dfs(0, k)\n```\n\n```Java []\nclass Solution {\n public double largestSumOfAverages(int[] A, int K) {\n final int n = A.length;\n dp = new double[n + 1][K + 1];\n prefix = new double[n + 1];\n\n for (int i = 0; i < n; ++i)\n prefix[i + 1] = A[i] + prefix[i];\n\n return largestSumOfAverages(A, n, K);\n }\n private double[][] dp;\n private double[] prefix;\n\n private double largestSumOfAverages(int[] A, int i, int k) {\n if (k == 1)\n return prefix[i] / i;\n if (dp[i][k] > 0.0)\n return dp[i][k];\n\n for (int j = k - 1; j < i; ++j)\n dp[i][k] =\n Math.max(dp[i][k], largestSumOfAverages(A, j, k - 1) + (prefix[i] - prefix[j]) / (i - j));\n\n return dp[i][k];\n }\n}\n```\n
1
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
70% TC and 56% SC easy python solution
largest-sum-of-averages
0
1
```\ndef largestSumOfAverages(self, nums: List[int], k: int) -> float:\n\tn = len(nums)\n\tpre = [0]\n\tfor i in nums:\n\t\tpre.append(pre[-1] + i)\n\tdef solve(i, k):\n\t\tif(k == 1): return sum(nums[i:])/(n-i)\n\n\t\tif(n-i < k): return -1\n\n\t\tif((i, k) in d): return d[(i, k)]\n\n\t\ttemp = 0\n\t\tfor j in range(i+1, n):\n\t\t\ttemp = max(temp, solve(j, k-1)+(pre[j]-pre[i])/(j-i))\n\t\td[(i, k)] = temp\n\t\treturn temp\n\td = dict() \n\treturn solve(0, k)\n```
1
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
70% TC and 56% SC easy python solution
largest-sum-of-averages
0
1
```\ndef largestSumOfAverages(self, nums: List[int], k: int) -> float:\n\tn = len(nums)\n\tpre = [0]\n\tfor i in nums:\n\t\tpre.append(pre[-1] + i)\n\tdef solve(i, k):\n\t\tif(k == 1): return sum(nums[i:])/(n-i)\n\n\t\tif(n-i < k): return -1\n\n\t\tif((i, k) in d): return d[(i, k)]\n\n\t\ttemp = 0\n\t\tfor j in range(i+1, n):\n\t\t\ttemp = max(temp, solve(j, k-1)+(pre[j]-pre[i])/(j-i))\n\t\td[(i, k)] = temp\n\t\treturn temp\n\td = dict() \n\treturn solve(0, k)\n```
1
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
python || dynamic programming || faster than 99%
largest-sum-of-averages
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. -->\nDynamic Programming\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n * k)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n * k)\n\n# memoization - faster than 99%\n# code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n s[i + 1] = s[i] + nums[i]\n @cache\n def function(index, k):\n if k == 1:\n return ((s[-1] - s[index]) / (len(nums) - index))\n m = -math.inf\n for i in range(index, len(nums) - k + 1):\n l = i - index + 1\n s_a = s[i + 1] - s[index]\n temp = (s_a / l) + function(i + 1, k - 1)\n if temp > m:m = temp\n return m\n \n return function(0, k)\n```\n\n\n# Dynamic programming bottom up -faster than 86%\n# Code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n s[i + 1] = s[i] + nums[i]\n dp = [[None] * (k + 1) for i in range(len(nums))]\n for i in range(len(nums) - 1, -1, -1):\n for j in range(1, min(len(nums) - i, k) + 1):\n if j == 1:\n dp[i][j] = (s[-1] - s[i]) / (len(nums)-1 - i + 1)\n continue\n mn = -math.inf\n for l in range(i, len(nums) - (j - 1)):\n avg = (s[l + 1] - s[i]) / (l - i + 1)\n temp = avg + dp[l + 1][j - 1]\n if temp > mn:mn = temp\n dp[i][j] = mn\n return dp[0][k]\n \n\n```
0
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
python || dynamic programming || faster than 99%
largest-sum-of-averages
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. -->\nDynamic Programming\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n * k)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n * k)\n\n# memoization - faster than 99%\n# code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n s[i + 1] = s[i] + nums[i]\n @cache\n def function(index, k):\n if k == 1:\n return ((s[-1] - s[index]) / (len(nums) - index))\n m = -math.inf\n for i in range(index, len(nums) - k + 1):\n l = i - index + 1\n s_a = s[i + 1] - s[index]\n temp = (s_a / l) + function(i + 1, k - 1)\n if temp > m:m = temp\n return m\n \n return function(0, k)\n```\n\n\n# Dynamic programming bottom up -faster than 86%\n# Code\n```\nclass Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n s[i + 1] = s[i] + nums[i]\n dp = [[None] * (k + 1) for i in range(len(nums))]\n for i in range(len(nums) - 1, -1, -1):\n for j in range(1, min(len(nums) - i, k) + 1):\n if j == 1:\n dp[i][j] = (s[-1] - s[i]) / (len(nums)-1 - i + 1)\n continue\n mn = -math.inf\n for l in range(i, len(nums) - (j - 1)):\n avg = (s[l + 1] - s[i]) / (l - i + 1)\n temp = avg + dp[l + 1][j - 1]\n if temp > mn:mn = temp\n dp[i][j] = mn\n return dp[0][k]\n \n\n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Similar to traditional dp problem
largest-sum-of-averages
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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n @lru_cache(None)\n def fun(ind,k):\n if ind==len(nums):\n if k==0:\n return 0\n return -10000000000\n \n if k==0:\n return -10000000\n \n best,curr_sum,cnt=0,0,0\n\n for i in range(ind,len(nums)):\n curr_sum+=nums[i]\n cnt+=1\n best=max(best,curr_sum/cnt+fun(i+1,k-1))\n \n return best\n \n return fun(0,k)\n```
0
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
Similar to traditional dp problem
largest-sum-of-averages
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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n @lru_cache(None)\n def fun(ind,k):\n if ind==len(nums):\n if k==0:\n return 0\n return -10000000000\n \n if k==0:\n return -10000000\n \n best,curr_sum,cnt=0,0,0\n\n for i in range(ind,len(nums)):\n curr_sum+=nums[i]\n cnt+=1\n best=max(best,curr_sum/cnt+fun(i+1,k-1))\n \n return best\n \n return fun(0,k)\n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
813: Beats 96.31%, Solution with step by step explanation
largest-sum-of-averages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n n = len(nums)\n```\n\nWe store the length of nums in n, which will be used frequently.\n\n```\n prefix_sum = [0] * (n + 1)\n for i in range(n):\n prefix_sum[i + 1] = prefix_sum[i] + nums[i]\n```\n\nWe create a prefix sum array that will help us quickly calculate the sum of any subarray of nums. prefix_sum[i] contains the sum of nums up to but not including index i.\n\n```\n dp = [prefix_sum[i] / i for i in range(1, n + 1)]\n```\n\nWe initialize a dynamic programming array dp where dp[i] will eventually represent the largest sum of averages we can get by partitioning the first i elements into k subarrays. Initially, it represents the average of the first i elements.\n\n```\n for j in range(2, k + 1):\n for i in range(n, j - 1, -1):\n for p in range(j - 1, i):\n```\n\nWe use three nested loops to fill the DP array. The outermost loop runs through each possible number of partitions from 2 to k. The middle loop goes through all the elements in reverse. The innermost loop considers all possible previous partitions.\n\n```\n dp[i - 1] = max(dp[i - 1], dp[p - 1] + (prefix_sum[i] - prefix_sum[p]) / (i - p))\n```\n\nWe update dp[i - 1] with the maximum value of itself and the value of forming a new partition starting after position p - 1. This is where we make use of our prefix sum array to quickly compute the sum of the new partition.\n\n```\n return dp[n - 1]\n```\n\nAfter the loops finish, dp[n - 1] contains the largest sum of averages for partitioning the entire array into k subarrays. This value is returned as the answer.\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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n n = len(nums)\n\n prefix_sum = [0] * (n + 1)\n for i in range(n):\n prefix_sum[i + 1] = prefix_sum[i] + nums[i]\n\n dp = [prefix_sum[i] / i for i in range(1, n + 1)]\n \n for j in range(2, k + 1):\n for i in range(n, j - 1, -1): \n for p in range(j - 1, i):\n dp[i - 1] = max(dp[i - 1], dp[p - 1] + (prefix_sum[i] - prefix_sum[p]) / (i - p))\n \n return dp[n - 1]\n\n```
0
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
813: Beats 96.31%, Solution with step by step explanation
largest-sum-of-averages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n n = len(nums)\n```\n\nWe store the length of nums in n, which will be used frequently.\n\n```\n prefix_sum = [0] * (n + 1)\n for i in range(n):\n prefix_sum[i + 1] = prefix_sum[i] + nums[i]\n```\n\nWe create a prefix sum array that will help us quickly calculate the sum of any subarray of nums. prefix_sum[i] contains the sum of nums up to but not including index i.\n\n```\n dp = [prefix_sum[i] / i for i in range(1, n + 1)]\n```\n\nWe initialize a dynamic programming array dp where dp[i] will eventually represent the largest sum of averages we can get by partitioning the first i elements into k subarrays. Initially, it represents the average of the first i elements.\n\n```\n for j in range(2, k + 1):\n for i in range(n, j - 1, -1):\n for p in range(j - 1, i):\n```\n\nWe use three nested loops to fill the DP array. The outermost loop runs through each possible number of partitions from 2 to k. The middle loop goes through all the elements in reverse. The innermost loop considers all possible previous partitions.\n\n```\n dp[i - 1] = max(dp[i - 1], dp[p - 1] + (prefix_sum[i] - prefix_sum[p]) / (i - p))\n```\n\nWe update dp[i - 1] with the maximum value of itself and the value of forming a new partition starting after position p - 1. This is where we make use of our prefix sum array to quickly compute the sum of the new partition.\n\n```\n return dp[n - 1]\n```\n\nAfter the loops finish, dp[n - 1] contains the largest sum of averages for partitioning the entire array into k subarrays. This value is returned as the answer.\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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n n = len(nums)\n\n prefix_sum = [0] * (n + 1)\n for i in range(n):\n prefix_sum[i + 1] = prefix_sum[i] + nums[i]\n\n dp = [prefix_sum[i] / i for i in range(1, n + 1)]\n \n for j in range(2, k + 1):\n for i in range(n, j - 1, -1): \n for p in range(j - 1, i):\n dp[i - 1] = max(dp[i - 1], dp[p - 1] + (prefix_sum[i] - prefix_sum[p]) / (i - p))\n \n return dp[n - 1]\n\n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Short DP solution beats 99%
largest-sum-of-averages
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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = list(accumulate(nums, initial=0))\n @cache\n def dp(n,p):\n if p == 1: return s[n]/n\n return max((s[n]-s[j])/(n-j)+dp(j,p-1) for j in range(p-1,n))\n return dp(len(nums),k)\n```
0
You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer. Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted. **Example 1:** **Input:** nums = \[9,1,2,3,9\], k = 3 **Output:** 20.00000 **Explanation:** The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. **Example 2:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 4 **Output:** 20.50000 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 104` * `1 <= k <= nums.length`
null
Short DP solution beats 99%
largest-sum-of-averages
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 largestSumOfAverages(self, nums: List[int], k: int) -> float:\n s = list(accumulate(nums, initial=0))\n @cache\n def dp(n,p):\n if p == 1: return s[n]/n\n return max((s[n]-s[j])/(n-j)+dp(j,p-1) for j in range(p-1,n))\n return dp(len(nums),k)\n```
0
You are given a personal information string `s`, representing either an **email address** or a **phone number**. Return _the **masked** personal information using the below rules_. **Email address:** An email address is: * A **name** consisting of uppercase and lowercase English letters, followed by * The `'@'` symbol, followed by * The **domain** consisting of uppercase and lowercase English letters with a dot `'.'` somewhere in the middle (not the first or last character). To mask an email: * The uppercase letters in the **name** and **domain** must be converted to lowercase letters. * The middle letters of the **name** (i.e., all but the first and last letters) must be replaced by 5 asterisks `"***** "`. **Phone number:** A phone number is formatted as follows: * The phone number contains 10-13 digits. * The last 10 digits make up the **local number**. * The remaining 0-3 digits, in the beginning, make up the **country code**. * **Separation characters** from the set `{'+', '-', '(', ')', ' '}` separate the above digits in some way. To mask a phone number: * Remove all **separation characters**. * The masked phone number should have the form: * `"***-***-XXXX "` if the country code has 0 digits. * `"+*-***-***-XXXX "` if the country code has 1 digit. * `"+**-***-***-XXXX "` if the country code has 2 digits. * `"+***-***-***-XXXX "` if the country code has 3 digits. * `"XXXX "` is the last 4 digits of the **local number**. **Example 1:** **Input:** s = "[email protected] " **Output:** "l\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. **Example 2:** **Input:** s = "[email protected] " **Output:** "a\*\*\*\*\*[email protected] " **Explanation:** s is an email address. The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks. Note that even though "ab " is 2 characters, it still must have 5 asterisks in the middle. **Example 3:** **Input:** s = "1(234)567-890 " **Output:** "\*\*\*-\*\*\*-7890 " **Explanation:** s is a phone number. There are 10 digits, so the local number is 10 digits and the country code is 0 digits. Thus, the resulting masked number is "\*\*\*-\*\*\*-7890 ". **Constraints:** * `s` is either a **valid** email or a phone number. * If `s` is an email: * `8 <= s.length <= 40` * `s` consists of uppercase and lowercase English letters and exactly one `'@'` symbol and `'.'` symbol. * If `s` is a phone number: * `10 <= s.length <= 20` * `s` consists of digits, spaces, and the symbols `'('`, `')'`, `'-'`, and `'+'`.
null
Simple solution with Binary Tree in Python3
binary-tree-pruning
0
1
# Intuition\nHere we have:\n- a **Binary Tree** `root`\n- our goal is to remove **all** subtrees, that consist **only** with `0`\n\nAn algorithm is simple:\n- traverse over tree\n- for each node check if it has leaves and they\'re **both** `0` or don\'t exist, than **remove** this node from `root`\n- otherwise check, **if any** of leaves is `0`, remove this leaf\n\n# Approach\n1. define `isNodeNeedsToPrune` to prune a node according to the algorithm above\n2. do a normal `dfs` with pruning, if it\'s needed\n3. return `dfs(root)`\n\n# Complexity\n- Time complexity: **O(N)**, to traverse over `root`\n\n- Space complexity: **O(N)** as maximum call stack\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isNodeNeedsToPrune(self, node):\n return not node.val and not node.left and not node.right\n\n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node):\n if node:\n node.left = dfs(node.left)\n node.right = dfs(node.right)\n\n return None if self.isNodeNeedsToPrune(node) else node\n \n return node\n\n return dfs(root)\n```
1
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_. A subtree of a node `node` is `node` plus every node that is a descendant of `node`. **Example 1:** **Input:** root = \[1,null,0,0,1\] **Output:** \[1,null,0,null,1\] **Explanation:** Only the red nodes satisfy the property "every subtree not containing a 1 ". The diagram on the right represents the answer. **Example 2:** **Input:** root = \[1,0,1,0,0,0,1\] **Output:** \[1,null,1,null,1\] **Example 3:** **Input:** root = \[1,1,0,1,1,0,1,0\] **Output:** \[1,1,0,1,1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 200]`. * `Node.val` is either `0` or `1`.
null
Simple solution with Binary Tree in Python3
binary-tree-pruning
0
1
# Intuition\nHere we have:\n- a **Binary Tree** `root`\n- our goal is to remove **all** subtrees, that consist **only** with `0`\n\nAn algorithm is simple:\n- traverse over tree\n- for each node check if it has leaves and they\'re **both** `0` or don\'t exist, than **remove** this node from `root`\n- otherwise check, **if any** of leaves is `0`, remove this leaf\n\n# Approach\n1. define `isNodeNeedsToPrune` to prune a node according to the algorithm above\n2. do a normal `dfs` with pruning, if it\'s needed\n3. return `dfs(root)`\n\n# Complexity\n- Time complexity: **O(N)**, to traverse over `root`\n\n- Space complexity: **O(N)** as maximum call stack\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isNodeNeedsToPrune(self, node):\n return not node.val and not node.left and not node.right\n\n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node):\n if node:\n node.left = dfs(node.left)\n node.right = dfs(node.right)\n\n return None if self.isNodeNeedsToPrune(node) else node\n \n return node\n\n return dfs(root)\n```
1
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Solution
binary-tree-pruning
1
1
```C++ []\nclass Solution {\n public:\n TreeNode* pruneTree(TreeNode* root) {\n if (root == nullptr)\n return nullptr;\n root->left = pruneTree(root->left);\n root->right = pruneTree(root->right);\n if (root->left == nullptr && root->right == nullptr && root->val == 0)\n return nullptr;\n return root;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def helper(self, root: Optional[TreeNode]):\n if root is None:\n return False\n\n does_left_include_one = self.helper(root.left)\n does_right_include_one = self.helper(root.right)\n\n if not does_left_include_one:\n root.left = None\n\n if not does_right_include_one:\n root.right = None\n\n return root.val == 1 or does_left_include_one or does_right_include_one\n \n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n self.helper(root)\n\n if root.val == 0 and not root.left and not root.right:\n return None\n \n return root\n```\n\n```Java []\nclass Solution {\n public TreeNode pruneTree(TreeNode root) {\n TreeNode ans = postOrder(root);\n return ans;\n }\n private TreeNode postOrder(TreeNode cur) {\n if (cur == null) {\n return null;\n }\n TreeNode left = postOrder(cur.left);\n TreeNode right = postOrder(cur.right);\n if (left == null) {\n cur.left = null;\n }\n if (right == null) {\n cur.right = null;\n }\n if (left == null && right == null && cur.val == 0) {\n cur = null;\n return null;\n }\n return cur;\n }\n}\n```\n
1
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_. A subtree of a node `node` is `node` plus every node that is a descendant of `node`. **Example 1:** **Input:** root = \[1,null,0,0,1\] **Output:** \[1,null,0,null,1\] **Explanation:** Only the red nodes satisfy the property "every subtree not containing a 1 ". The diagram on the right represents the answer. **Example 2:** **Input:** root = \[1,0,1,0,0,0,1\] **Output:** \[1,null,1,null,1\] **Example 3:** **Input:** root = \[1,1,0,1,1,0,1,0\] **Output:** \[1,1,0,1,1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 200]`. * `Node.val` is either `0` or `1`.
null
Solution
binary-tree-pruning
1
1
```C++ []\nclass Solution {\n public:\n TreeNode* pruneTree(TreeNode* root) {\n if (root == nullptr)\n return nullptr;\n root->left = pruneTree(root->left);\n root->right = pruneTree(root->right);\n if (root->left == nullptr && root->right == nullptr && root->val == 0)\n return nullptr;\n return root;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def helper(self, root: Optional[TreeNode]):\n if root is None:\n return False\n\n does_left_include_one = self.helper(root.left)\n does_right_include_one = self.helper(root.right)\n\n if not does_left_include_one:\n root.left = None\n\n if not does_right_include_one:\n root.right = None\n\n return root.val == 1 or does_left_include_one or does_right_include_one\n \n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n self.helper(root)\n\n if root.val == 0 and not root.left and not root.right:\n return None\n \n return root\n```\n\n```Java []\nclass Solution {\n public TreeNode pruneTree(TreeNode root) {\n TreeNode ans = postOrder(root);\n return ans;\n }\n private TreeNode postOrder(TreeNode cur) {\n if (cur == null) {\n return null;\n }\n TreeNode left = postOrder(cur.left);\n TreeNode right = postOrder(cur.right);\n if (left == null) {\n cur.left = null;\n }\n if (right == null) {\n cur.right = null;\n }\n if (left == null && right == null && cur.val == 0) {\n cur = null;\n return null;\n }\n return cur;\n }\n}\n```\n
1
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Python | Recursive Postorder
binary-tree-pruning
0
1
```python class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None if self.pruneTree(root.left) is None: root.left = None if self.pruneTree(root.right) is None: root.right = None if root.val != 1 and root.left is None and root.right is None: root = None return root ```
3
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_. A subtree of a node `node` is `node` plus every node that is a descendant of `node`. **Example 1:** **Input:** root = \[1,null,0,0,1\] **Output:** \[1,null,0,null,1\] **Explanation:** Only the red nodes satisfy the property "every subtree not containing a 1 ". The diagram on the right represents the answer. **Example 2:** **Input:** root = \[1,0,1,0,0,0,1\] **Output:** \[1,null,1,null,1\] **Example 3:** **Input:** root = \[1,1,0,1,1,0,1,0\] **Output:** \[1,1,0,1,1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 200]`. * `Node.val` is either `0` or `1`.
null
Python | Recursive Postorder
binary-tree-pruning
0
1
```python class Solution: def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None if self.pruneTree(root.left) is None: root.left = None if self.pruneTree(root.right) is None: root.right = None if root.val != 1 and root.left is None and root.right is None: root = None return root ```
3
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Python3 Solution
bus-routes
0
1
\n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==target:\n return 0\n graph=defaultdict(set)\n for routes_id,stops in enumerate(routes):\n for stop in stops:\n graph[stop].add(routes_id)\n \n queue=deque([(source,0)])\n seen_stops=set([source])\n seen_routes=set()\n while queue:\n stop,new_changes=queue.popleft()\n \n if stop==target:\n return new_changes\n \n for routes_id in graph[stop]:\n if routes_id not in seen_routes:\n seen_routes.add(routes_id)\n \n for stop in routes[routes_id]:\n if stop not in seen_stops:\n seen_stops.add(stop)\n queue.append((stop,new_changes+1))\n \n return -1 \n```
4
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
Python3 Solution
bus-routes
0
1
\n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==target:\n return 0\n graph=defaultdict(set)\n for routes_id,stops in enumerate(routes):\n for stop in stops:\n graph[stop].add(routes_id)\n \n queue=deque([(source,0)])\n seen_stops=set([source])\n seen_routes=set()\n while queue:\n stop,new_changes=queue.popleft()\n \n if stop==target:\n return new_changes\n \n for routes_id in graph[stop]:\n if routes_id not in seen_routes:\n seen_routes.add(routes_id)\n \n for stop in routes[routes_id]:\n if stop not in seen_stops:\n seen_stops.add(stop)\n queue.append((stop,new_changes+1))\n \n return -1 \n```
4
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
✅ Beats 100% - Explained With [ Video ] - Modified Bellman Ford - Visualized Too
bus-routes
1
1
![Screenshot 2023-11-12 061243.png](https://assets.leetcode.com/users/images/4b853715-c890-4b85-8e02-a51fcdd65fef_1699750143.729092.png)\n\n# YouTube Video Explanation:\n\n\n[https://youtu.be/uvAuQVvGBts](https://youtu.be/uvAuQVvGBts)\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Current Subscribers: 221*\n*Subscribe Goal: 250 Subscribers*\n### Example Explanation:\n\nGiven Routes: `[[1,2,7],[3,6,7]]`\n\n| Bus Stops (Routes) | Bus Stops Sequence |\n|:-------------------:|:------------------:|\n| [1, 2, 7] | 1 -> 2 -> 7 -> 1 -> 2 -> 7 -> ... |\n| [3, 6, 7] | 3 -> 6 -> 7 -> 3 -> 6 -> 7 -> ... |\n\nSource Bus Stop: 1, Target Bus Stop: 6\n\n### Initialization:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | \u221E |\n| 3 | \u221E |\n| 6 | \u221E |\n| 7 | \u221E |\n\n- Initialize `minBusesToReach` array. The source bus stop (1) has a minimum of 0 buses required.\n\n### Iteration 1:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | \u221E |\n| 6 | \u221E |\n| 7 | 1 |\n\n- Update `minBusesToReach` based on the first route ([1, 2, 7]).\n\n### Iteration 2:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | 2 |\n| 6 | 2 |\n| 7 | 1 |\n\n- Update `minBusesToReach` based on the second route ([3, 6, 7]).\n\n### Result:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | 2 |\n| 6 | 2 |\n| 7 | 1 |\n\n- The final `minBusesToReach` array after both iterations.\n\n### Conclusion:\n\n- The minimum number of buses required to reach the target bus stop (6) from the source bus stop (1) is 2.\n\nThis table-based explanation demonstrates the step-by-step updates in the `minBusesToReach` array, providing a clear visualization of the solution\'s logic.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the least number of buses one must take to travel from a source bus stop to a target bus stop. Each bus travels in a repeating sequence, and you can only travel between bus stops using buses. The task is to determine the minimum number of bus rides needed to reach the target bus stop from the source bus stop.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, identify the maximum bus stop number (`maxStop`) across all routes. If `maxStop` is less than the target bus stop, it means there is no route to reach the target, and we return -1.\n\n2. Initialize an array `minBusesToReach`, where `minBusesToReach[i]` represents the minimum number of buses needed to reach bus stop `i` from the source. Initialize this array with a value greater than the total number of routes.\n\n3. Use a loop to iteratively update the `minBusesToReach` array. For each route, find the minimum value in `minBusesToReach` for the stops in that route and increment it by 1. Update the `minBusesToReach` array if a smaller number of buses is found.\n\n4. Continue this process until no further updates can be made to `minBusesToReach`. The final value at `minBusesToReach[target]` will represent the minimum number of buses needed to reach the target from the source.\n\n5. Return the result: `minBusesToReach[target]` if it is less than the total number of routes, otherwise, return -1.\n\n# Complexity\n- **Time Complexity:**\n - The outer loop runs until no more updates can be made, and in each iteration, we iterate through all routes. Therefore, the time complexity is O(n * m), where n is the number of routes and m is the average number of stops in a route.\n \n- **Space Complexity:**\n - The space complexity is O(maxStop), where maxStop is the maximum bus stop number in any route, as we use an array `minBusesToReach` of this size.\n\n# Code\n## Java\n```\nclass Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n int maxStop = -1;\n for (int[] route : routes) {\n for (int stop : route) {\n maxStop = Math.max(maxStop, stop);\n }\n }\n if (maxStop < target) {\n return -1;\n }\n int n = routes.length;\n int[] minBusesToReach = new int[maxStop + 1];\n Arrays.fill(minBusesToReach, n + 1);\n minBusesToReach[source] = 0;\n boolean flag = true;\n while (flag) {\n flag = false;\n for (int[] route : routes) {\n int min = n + 1;\n for (int stop : route) {\n min = Math.min(min, minBusesToReach[stop]);\n }\n min++;\n for (int stop : route) {\n if (minBusesToReach[stop] > min) {\n minBusesToReach[stop] = min;\n flag = true;\n }\n }\n }\n \n }\n return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1);\n }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n int maxStop = -1;\n for (const auto& route : routes) {\n for (int stop : route) {\n maxStop = max(maxStop, stop);\n }\n }\n\n if (maxStop < target) {\n return -1;\n }\n\n int n = routes.size();\n vector<int> minBusesToReach(maxStop + 1, INT_MAX);\n minBusesToReach[source] = 0;\n\n bool flag = true;\n while (flag) {\n flag = false;\n for (const auto& route : routes) {\n int min = n+1;\n for (int stop : route) {\n min = std::min(min, minBusesToReach[stop]);\n }\n min++;\n for (int stop : route) {\n if (minBusesToReach[stop] > min) {\n minBusesToReach[stop] = min;\n flag = true;\n }\n }\n }\n }\n\n return (minBusesToReach[target] < n+1) ? minBusesToReach[target] : -1;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n max_stop = max(max(route) for route in routes)\n if max_stop < target:\n return -1\n\n n = len(routes)\n min_buses_to_reach = [float(\'inf\')] * (max_stop + 1)\n min_buses_to_reach[source] = 0\n\n flag = True\n while flag:\n flag = False\n for route in routes:\n mini = float(\'inf\')\n for stop in route:\n mini = min(mini, min_buses_to_reach[stop])\n mini += 1\n for stop in route:\n if min_buses_to_reach[stop] > mini:\n min_buses_to_reach[stop] = mini\n flag = True\n\n return min_buses_to_reach[target] if min_buses_to_reach[target] < float(\'inf\') else -1\n\n```\n## JavaScript\n```\nvar numBusesToDestination = function(routes, source, target) {\n if (source === target) {\n return 0;\n }\n\n let maxStop = -1;\n for (const route of routes) {\n maxStop = Math.max(maxStop, ...route);\n }\n\n if (maxStop < target) {\n return -1;\n }\n\n const n = routes.length;\n const minBusesToReach = Array(maxStop + 1).fill(Number.MAX_SAFE_INTEGER);\n minBusesToReach[source] = 0;\n\n let flag = true;\n while (flag) {\n flag = false;\n for (const route of routes) {\n let mini = Number.MAX_SAFE_INTEGER;\n for (const stop of route) {\n mini = Math.min(mini, minBusesToReach[stop]);\n }\n mini++;\n for (const stop of route) {\n if (minBusesToReach[stop] > mini) {\n minBusesToReach[stop] = mini;\n flag = true;\n }\n }\n }\n }\n\n return (minBusesToReach[target] < Number.MAX_SAFE_INTEGER) ? minBusesToReach[target] : -1;\n};\n```\n---\n![upvote1.jpeg](https://assets.leetcode.com/users/images/ecddf7d5-55f5-42ae-8803-59cd6f820c70_1699750196.7597365.jpeg)\n
104
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
✅ Beats 100% - Explained With [ Video ] - Modified Bellman Ford - Visualized Too
bus-routes
1
1
![Screenshot 2023-11-12 061243.png](https://assets.leetcode.com/users/images/4b853715-c890-4b85-8e02-a51fcdd65fef_1699750143.729092.png)\n\n# YouTube Video Explanation:\n\n\n[https://youtu.be/uvAuQVvGBts](https://youtu.be/uvAuQVvGBts)\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Current Subscribers: 221*\n*Subscribe Goal: 250 Subscribers*\n### Example Explanation:\n\nGiven Routes: `[[1,2,7],[3,6,7]]`\n\n| Bus Stops (Routes) | Bus Stops Sequence |\n|:-------------------:|:------------------:|\n| [1, 2, 7] | 1 -> 2 -> 7 -> 1 -> 2 -> 7 -> ... |\n| [3, 6, 7] | 3 -> 6 -> 7 -> 3 -> 6 -> 7 -> ... |\n\nSource Bus Stop: 1, Target Bus Stop: 6\n\n### Initialization:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | \u221E |\n| 3 | \u221E |\n| 6 | \u221E |\n| 7 | \u221E |\n\n- Initialize `minBusesToReach` array. The source bus stop (1) has a minimum of 0 buses required.\n\n### Iteration 1:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | \u221E |\n| 6 | \u221E |\n| 7 | 1 |\n\n- Update `minBusesToReach` based on the first route ([1, 2, 7]).\n\n### Iteration 2:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | 2 |\n| 6 | 2 |\n| 7 | 1 |\n\n- Update `minBusesToReach` based on the second route ([3, 6, 7]).\n\n### Result:\n\n| Bus Stop | Min Buses to Reach |\n|:--------:|:-------------------:|\n| 1 | 0 |\n| 2 | 1 |\n| 3 | 2 |\n| 6 | 2 |\n| 7 | 1 |\n\n- The final `minBusesToReach` array after both iterations.\n\n### Conclusion:\n\n- The minimum number of buses required to reach the target bus stop (6) from the source bus stop (1) is 2.\n\nThis table-based explanation demonstrates the step-by-step updates in the `minBusesToReach` array, providing a clear visualization of the solution\'s logic.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves finding the least number of buses one must take to travel from a source bus stop to a target bus stop. Each bus travels in a repeating sequence, and you can only travel between bus stops using buses. The task is to determine the minimum number of bus rides needed to reach the target bus stop from the source bus stop.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, identify the maximum bus stop number (`maxStop`) across all routes. If `maxStop` is less than the target bus stop, it means there is no route to reach the target, and we return -1.\n\n2. Initialize an array `minBusesToReach`, where `minBusesToReach[i]` represents the minimum number of buses needed to reach bus stop `i` from the source. Initialize this array with a value greater than the total number of routes.\n\n3. Use a loop to iteratively update the `minBusesToReach` array. For each route, find the minimum value in `minBusesToReach` for the stops in that route and increment it by 1. Update the `minBusesToReach` array if a smaller number of buses is found.\n\n4. Continue this process until no further updates can be made to `minBusesToReach`. The final value at `minBusesToReach[target]` will represent the minimum number of buses needed to reach the target from the source.\n\n5. Return the result: `minBusesToReach[target]` if it is less than the total number of routes, otherwise, return -1.\n\n# Complexity\n- **Time Complexity:**\n - The outer loop runs until no more updates can be made, and in each iteration, we iterate through all routes. Therefore, the time complexity is O(n * m), where n is the number of routes and m is the average number of stops in a route.\n \n- **Space Complexity:**\n - The space complexity is O(maxStop), where maxStop is the maximum bus stop number in any route, as we use an array `minBusesToReach` of this size.\n\n# Code\n## Java\n```\nclass Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n int maxStop = -1;\n for (int[] route : routes) {\n for (int stop : route) {\n maxStop = Math.max(maxStop, stop);\n }\n }\n if (maxStop < target) {\n return -1;\n }\n int n = routes.length;\n int[] minBusesToReach = new int[maxStop + 1];\n Arrays.fill(minBusesToReach, n + 1);\n minBusesToReach[source] = 0;\n boolean flag = true;\n while (flag) {\n flag = false;\n for (int[] route : routes) {\n int min = n + 1;\n for (int stop : route) {\n min = Math.min(min, minBusesToReach[stop]);\n }\n min++;\n for (int stop : route) {\n if (minBusesToReach[stop] > min) {\n minBusesToReach[stop] = min;\n flag = true;\n }\n }\n }\n \n }\n return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1);\n }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n int maxStop = -1;\n for (const auto& route : routes) {\n for (int stop : route) {\n maxStop = max(maxStop, stop);\n }\n }\n\n if (maxStop < target) {\n return -1;\n }\n\n int n = routes.size();\n vector<int> minBusesToReach(maxStop + 1, INT_MAX);\n minBusesToReach[source] = 0;\n\n bool flag = true;\n while (flag) {\n flag = false;\n for (const auto& route : routes) {\n int min = n+1;\n for (int stop : route) {\n min = std::min(min, minBusesToReach[stop]);\n }\n min++;\n for (int stop : route) {\n if (minBusesToReach[stop] > min) {\n minBusesToReach[stop] = min;\n flag = true;\n }\n }\n }\n }\n\n return (minBusesToReach[target] < n+1) ? minBusesToReach[target] : -1;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n max_stop = max(max(route) for route in routes)\n if max_stop < target:\n return -1\n\n n = len(routes)\n min_buses_to_reach = [float(\'inf\')] * (max_stop + 1)\n min_buses_to_reach[source] = 0\n\n flag = True\n while flag:\n flag = False\n for route in routes:\n mini = float(\'inf\')\n for stop in route:\n mini = min(mini, min_buses_to_reach[stop])\n mini += 1\n for stop in route:\n if min_buses_to_reach[stop] > mini:\n min_buses_to_reach[stop] = mini\n flag = True\n\n return min_buses_to_reach[target] if min_buses_to_reach[target] < float(\'inf\') else -1\n\n```\n## JavaScript\n```\nvar numBusesToDestination = function(routes, source, target) {\n if (source === target) {\n return 0;\n }\n\n let maxStop = -1;\n for (const route of routes) {\n maxStop = Math.max(maxStop, ...route);\n }\n\n if (maxStop < target) {\n return -1;\n }\n\n const n = routes.length;\n const minBusesToReach = Array(maxStop + 1).fill(Number.MAX_SAFE_INTEGER);\n minBusesToReach[source] = 0;\n\n let flag = true;\n while (flag) {\n flag = false;\n for (const route of routes) {\n let mini = Number.MAX_SAFE_INTEGER;\n for (const stop of route) {\n mini = Math.min(mini, minBusesToReach[stop]);\n }\n mini++;\n for (const stop of route) {\n if (minBusesToReach[stop] > mini) {\n minBusesToReach[stop] = mini;\n flag = true;\n }\n }\n }\n }\n\n return (minBusesToReach[target] < Number.MAX_SAFE_INTEGER) ? minBusesToReach[target] : -1;\n};\n```\n---\n![upvote1.jpeg](https://assets.leetcode.com/users/images/ecddf7d5-55f5-42ae-8803-59cd6f820c70_1699750196.7597365.jpeg)\n
104
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
【Video】Give me 10 minutes - Beats 99.53% - How we think about a solution
bus-routes
1
1
# Intuition\nKeep track of route relation.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LcJYpE92UHs\n\n\u25A0 Timeline of the video\n\n`0:03` Explain difficulty and a key point of the question\n`1:31` Demonstrate how it works\n`4:08` Coding\n`10:15` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,049\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\n```\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\n```\n\nI think difficulty of this question is that source and target are located in different routes(index). In that case, we have to take another bus to get to target stop.\n\nI think the idea of keeping track of which bus stop has which route is a good approach.\n\nIn this case,\n\n```\n{1: [0], 2: [0], 7: [0, 1], 3: [1], 6: [1]}\n\nstop 1: 0 route only\nstop 2: 0 route only\nstop 7: 0 and 1 routes\nstop 3: 1 route only\nstop 6: 1 route only\n```\nI use `HashMap`. I call the values `bus_id` in the solution code.\n\n---\n\n\u2B50\uFE0F Points\n\nKeeping track of which bus stop has which route. There is possibility that one stop has multiple routes.\n\n---\n\n### How it works\n\nWe start from `stop 1`. We use `deque`.\n\n````\n{1: [0], 2: [0], 7: [0, 1], 3: [1], 6: [1]}\n\nqueue = [1]\nres = 1\n````\n`res` is number of buses we took so far.\n\n`stop 1` have `bus id 0`, so we can check `stop 2 and stop 7` easily because they are also located in the same route (= `bus id 0`). They are new stops we found. So add them to queue.\n\n````\nqueue = [1,2,7]\nres = 2\n````\nWe increment `res` when we start new iteration.\n\nWe iterate through `[1,2,7]`. But `stop 1` and `stop 2` has only `bus id 0`, so we can skip(= continue) in the solution code.\n\nAbout `stop 7`, it has `2 routes` which are `bus id 0` and `bus id 1`. We already check `bus id 0` but we don\'t check `bus id 1` yet. We can check `bus id 1` from `stop 7`.\n\n```\nCheck `stop 3`\n\nThat is new stop. Add stop 3 to queue.\nqueue = [3]\n```\n```\nCheck `stop 6`\nThat is target stop!\n```\n```\nOutput: 2(= res)\n```\n\nEasy!\uD83D\uDE06\n\nThere are a lot of duplicate calculations, so we use `set` to prevent the calculations, so that we can make execution time short.\n\nSolution code is very long but it\'s simple. I added comments to Python code. I hope it helps you understand the code easily.\n\nLet\'s see a real algorithm!\n\n\n---\n\n\n**Algorithm Overview:**\n\nThe algorithm finds the minimum number of buses needed to travel from a source bus stop to a target bus stop using a Breadth-First Search (BFS) approach. It first builds a graph where each bus stop is associated with the buses that pass through it. Then, it uses BFS to explore the possible routes, incrementing the number of buses taken at each level of stops until it reaches the target stop.\n\n**Detailed Explanation:**\n\n1. **Build Graph:**\n - Initialize an empty defaultdict (`stop_to_buses`) to associate each bus stop with the buses that pass through it.\n - Iterate through the given `routes` (list of bus routes).\n - For each bus route, iterate through the stops (`route`) and add the current bus\'s ID to the list of buses for that stop.\n\n ```python\n for bus_id, route in enumerate(routes):\n for stop in route:\n stop_to_buses[stop].append(bus_id)\n ```\n\n2. **Check Validity:**\n - Check if the source and target stops are in the graph. If not, return -1 since there is no valid route.\n\n ```python\n if source not in stop_to_buses or target not in stop_to_buses:\n return -1\n ```\n\n3. **Base Case:**\n - If the source and target stops are the same, return 0 as no buses are needed.\n\n ```python\n if source == target:\n return 0\n ```\n\n4. **BFS:**\n - Initialize a queue with the source stop, an empty set to track buses taken (`buses_taken`), an empty set to track stops visited (`stops_visited`), and initialize the result (`res`) to 0.\n - Use a while loop to perform BFS until the queue is empty.\n - For each level of stops, increment the result (`res`).\n - Iterate through the stops in the current level.\n - Check buses passing through the current stop. If a bus is already taken, skip it.\n - Mark the bus as taken and check stops reachable from the current bus.\n - If the target stop is reached, return the result (`res`).\n - Add the next stop to the queue and mark it as visited.\n\n ```python\n while queue:\n res += 1\n stops_to_process = len(queue)\n\n for _ in range(stops_to_process):\n current_stop = queue.popleft()\n\n for bus_id in stop_to_buses[current_stop]:\n if bus_id in buses_taken:\n continue\n\n buses_taken.add(bus_id)\n\n for next_stop in routes[bus_id]:\n if next_stop in stops_visited:\n continue\n\n if next_stop == target:\n return res\n\n queue.append(next_stop)\n stops_visited.add(next_stop)\n ```\n\n5. **No Valid Route:**\n - If the while loop completes without finding a valid route, return -1.\n\n ```python\n return -1\n ```\n\n\n# Complexity\n- Time complexity: $$O(N + M)$$\n\n Building the graph: The graph is constructed by iterating over the routes and stop lists, which has a time complexity of O(N), where N is the total number of stops across all routes.\n\n BFS traversal: The BFS traversal explores the graph to find the shortest path from the source stop to the target stop. The worst-case scenario occurs when the target stop is the farthest reachable stop, requiring a traversal of all stops. This leads to a time complexity of O(M), where M is the total number of stops in the graph.\n\n Therefore, the overall time complexity of the algorithm is $$O(N + M)$$\n\n- Space complexity: $$O(M + B)$$\n\n Graph representation: The graph is stored using a dictionary stop_to_buses, which has a space complexity of O(M), as it maps each stop to its associated buses.\n\n BFS auxiliary structures: The BFS traversal uses a queue queue to store the stops to be explored and a set stops_visited to track visited stops. Both these structures have a space complexity of O(M), as they can potentially hold all stops in the worst case.\n\n Set buses_taken: The set buses_taken keeps track of the buses used to avoid revisiting them. Its space complexity is O(B), where B is the total number of buses.\n\n Constants: The algorithm also uses a few constant-space variables for bookkeeping, which have negligible impact on the overall space complexity.\n\n Therefore, the overall space complexity of the algorithm is $$O(M + B)$$\n\n```python []\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # Build a graph where each stop is associated with the buses that pass through it\n stop_to_buses = defaultdict(list)\n\n for bus_id, route in enumerate(routes):\n for stop in route:\n stop_to_buses[stop].append(bus_id)\n\n # Check if source and target stops are in the graph\n if source not in stop_to_buses or target not in stop_to_buses:\n return -1\n\n # If the source and target are the same stop, no buses are needed\n if source == target:\n return 0\n\n # Use BFS to find the minimum number of buses to reach the target stop\n queue = deque([source])\n buses_taken = set()\n stops_visited = set()\n res = 0\n\n while queue:\n # Increment the res for each level of stops\n res += 1\n stops_to_process = len(queue)\n\n for _ in range(stops_to_process):\n current_stop = queue.popleft()\n\n # Check buses passing through the current stop\n for bus_id in stop_to_buses[current_stop]:\n if bus_id in buses_taken:\n continue\n\n buses_taken.add(bus_id)\n\n # Check stops reachable from the current bus\n for next_stop in routes[bus_id]:\n if next_stop in stops_visited:\n continue\n\n # If the target is reached, return the res\n if next_stop == target:\n return res\n\n # Add the next stop to the queue and mark it as visited\n queue.append(next_stop)\n stops_visited.add(next_stop)\n\n # If no valid route is found\n return -1\n```\n```javascript []\n/**\n * @param {number[][]} routes\n * @param {number} source\n * @param {number} target\n * @return {number}\n */\nvar numBusesToDestination = function(routes, source, target) {\n const stopToBuses = new Map();\n\n for (let busId = 0; busId < routes.length; busId++) {\n const route = routes[busId];\n for (const stop of route) {\n if (!stopToBuses.has(stop)) {\n stopToBuses.set(stop, []);\n }\n stopToBuses.get(stop).push(busId);\n }\n }\n\n if (!stopToBuses.has(source) || !stopToBuses.has(target)) {\n return -1;\n }\n\n if (source === target) {\n return 0;\n }\n\n const queue = [source];\n const busesTaken = new Set();\n const stopsVisited = new Set();\n let res = 0;\n\n while (queue.length > 0) {\n res++;\n const stopsToProcess = queue.length;\n\n for (let i = 0; i < stopsToProcess; i++) {\n const currentStop = queue.shift();\n\n for (const busId of stopToBuses.get(currentStop) || []) {\n if (busesTaken.has(busId)) {\n continue;\n }\n\n busesTaken.add(busId);\n\n for (const nextStop of routes[busId]) {\n if (stopsVisited.has(nextStop)) {\n continue;\n }\n\n if (nextStop === target) {\n return res;\n }\n\n queue.push(nextStop);\n stopsVisited.add(nextStop);\n }\n }\n }\n }\n\n return -1; \n};\n```\n```java []\nclass Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n Map<Integer, List<Integer>> stopToBuses = new HashMap<>();\n\n for (int busId = 0; busId < routes.length; busId++) {\n for (int stop : routes[busId]) {\n stopToBuses.computeIfAbsent(stop, k -> new ArrayList<>()).add(busId);\n }\n }\n\n if (!stopToBuses.containsKey(source) || !stopToBuses.containsKey(target)) {\n return -1;\n }\n\n if (source == target) {\n return 0;\n }\n\n Queue<Integer> queue = new LinkedList<>();\n Set<Integer> busesTaken = new HashSet<>();\n Set<Integer> stopsVisited = new HashSet<>();\n int res = 0;\n\n queue.offer(source);\n\n while (!queue.isEmpty()) {\n res++;\n int stopsToProcess = queue.size();\n\n for (int i = 0; i < stopsToProcess; i++) {\n int currentStop = queue.poll();\n\n for (int busId : stopToBuses.getOrDefault(currentStop, new ArrayList<>())) {\n if (busesTaken.contains(busId)) {\n continue;\n }\n\n busesTaken.add(busId);\n\n for (int nextStop : routes[busId]) {\n if (stopsVisited.contains(nextStop)) {\n continue;\n }\n\n if (nextStop == target) {\n return res;\n }\n\n queue.offer(nextStop);\n stopsVisited.add(nextStop);\n }\n }\n }\n }\n\n return -1;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n unordered_map<int, vector<int>> stopToBuses;\n\n for (int busId = 0; busId < routes.size(); busId++) {\n for (int stop : routes[busId]) {\n stopToBuses[stop].push_back(busId);\n }\n }\n\n if (stopToBuses.find(source) == stopToBuses.end() || stopToBuses.find(target) == stopToBuses.end()) {\n return -1;\n }\n\n if (source == target) {\n return 0;\n }\n\n queue<int> q;\n unordered_set<int> busesTaken;\n unordered_set<int> stopsVisited;\n int res = 0;\n\n q.push(source);\n\n while (!q.empty()) {\n res++;\n int stopsToProcess = q.size();\n\n for (int i = 0; i < stopsToProcess; i++) {\n int currentStop = q.front();\n q.pop();\n\n for (int busId : stopToBuses[currentStop]) {\n if (busesTaken.count(busId)) {\n continue;\n }\n\n busesTaken.insert(busId);\n\n for (int nextStop : routes[busId]) {\n if (stopsVisited.count(nextStop)) {\n continue;\n }\n\n if (nextStop == target) {\n return res;\n }\n\n q.push(nextStop);\n stopsVisited.insert(nextStop);\n }\n }\n }\n }\n\n return -1; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/sort-vowels-in-a-string/solutions/4281210/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/fVv8R93DaTc\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:19` Demonstrate how it works\n`3:09` Coding\n`5:02` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/design-graph-with-shortest-path-calculator/solutions/4276911/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/llptwOvEstY\n\n\u25A0 Timeline of the video\n\n`0:05` Explain constructor and addEdge function\n`1:31` Explain shortestPath\n`3:29` Demonstrate how it works\n`11:47` Coding\n`17:17` Time Complexity and Space Complexity
50
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
【Video】Give me 10 minutes - Beats 99.53% - How we think about a solution
bus-routes
1
1
# Intuition\nKeep track of route relation.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LcJYpE92UHs\n\n\u25A0 Timeline of the video\n\n`0:03` Explain difficulty and a key point of the question\n`1:31` Demonstrate how it works\n`4:08` Coding\n`10:15` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,049\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\n```\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\n```\n\nI think difficulty of this question is that source and target are located in different routes(index). In that case, we have to take another bus to get to target stop.\n\nI think the idea of keeping track of which bus stop has which route is a good approach.\n\nIn this case,\n\n```\n{1: [0], 2: [0], 7: [0, 1], 3: [1], 6: [1]}\n\nstop 1: 0 route only\nstop 2: 0 route only\nstop 7: 0 and 1 routes\nstop 3: 1 route only\nstop 6: 1 route only\n```\nI use `HashMap`. I call the values `bus_id` in the solution code.\n\n---\n\n\u2B50\uFE0F Points\n\nKeeping track of which bus stop has which route. There is possibility that one stop has multiple routes.\n\n---\n\n### How it works\n\nWe start from `stop 1`. We use `deque`.\n\n````\n{1: [0], 2: [0], 7: [0, 1], 3: [1], 6: [1]}\n\nqueue = [1]\nres = 1\n````\n`res` is number of buses we took so far.\n\n`stop 1` have `bus id 0`, so we can check `stop 2 and stop 7` easily because they are also located in the same route (= `bus id 0`). They are new stops we found. So add them to queue.\n\n````\nqueue = [1,2,7]\nres = 2\n````\nWe increment `res` when we start new iteration.\n\nWe iterate through `[1,2,7]`. But `stop 1` and `stop 2` has only `bus id 0`, so we can skip(= continue) in the solution code.\n\nAbout `stop 7`, it has `2 routes` which are `bus id 0` and `bus id 1`. We already check `bus id 0` but we don\'t check `bus id 1` yet. We can check `bus id 1` from `stop 7`.\n\n```\nCheck `stop 3`\n\nThat is new stop. Add stop 3 to queue.\nqueue = [3]\n```\n```\nCheck `stop 6`\nThat is target stop!\n```\n```\nOutput: 2(= res)\n```\n\nEasy!\uD83D\uDE06\n\nThere are a lot of duplicate calculations, so we use `set` to prevent the calculations, so that we can make execution time short.\n\nSolution code is very long but it\'s simple. I added comments to Python code. I hope it helps you understand the code easily.\n\nLet\'s see a real algorithm!\n\n\n---\n\n\n**Algorithm Overview:**\n\nThe algorithm finds the minimum number of buses needed to travel from a source bus stop to a target bus stop using a Breadth-First Search (BFS) approach. It first builds a graph where each bus stop is associated with the buses that pass through it. Then, it uses BFS to explore the possible routes, incrementing the number of buses taken at each level of stops until it reaches the target stop.\n\n**Detailed Explanation:**\n\n1. **Build Graph:**\n - Initialize an empty defaultdict (`stop_to_buses`) to associate each bus stop with the buses that pass through it.\n - Iterate through the given `routes` (list of bus routes).\n - For each bus route, iterate through the stops (`route`) and add the current bus\'s ID to the list of buses for that stop.\n\n ```python\n for bus_id, route in enumerate(routes):\n for stop in route:\n stop_to_buses[stop].append(bus_id)\n ```\n\n2. **Check Validity:**\n - Check if the source and target stops are in the graph. If not, return -1 since there is no valid route.\n\n ```python\n if source not in stop_to_buses or target not in stop_to_buses:\n return -1\n ```\n\n3. **Base Case:**\n - If the source and target stops are the same, return 0 as no buses are needed.\n\n ```python\n if source == target:\n return 0\n ```\n\n4. **BFS:**\n - Initialize a queue with the source stop, an empty set to track buses taken (`buses_taken`), an empty set to track stops visited (`stops_visited`), and initialize the result (`res`) to 0.\n - Use a while loop to perform BFS until the queue is empty.\n - For each level of stops, increment the result (`res`).\n - Iterate through the stops in the current level.\n - Check buses passing through the current stop. If a bus is already taken, skip it.\n - Mark the bus as taken and check stops reachable from the current bus.\n - If the target stop is reached, return the result (`res`).\n - Add the next stop to the queue and mark it as visited.\n\n ```python\n while queue:\n res += 1\n stops_to_process = len(queue)\n\n for _ in range(stops_to_process):\n current_stop = queue.popleft()\n\n for bus_id in stop_to_buses[current_stop]:\n if bus_id in buses_taken:\n continue\n\n buses_taken.add(bus_id)\n\n for next_stop in routes[bus_id]:\n if next_stop in stops_visited:\n continue\n\n if next_stop == target:\n return res\n\n queue.append(next_stop)\n stops_visited.add(next_stop)\n ```\n\n5. **No Valid Route:**\n - If the while loop completes without finding a valid route, return -1.\n\n ```python\n return -1\n ```\n\n\n# Complexity\n- Time complexity: $$O(N + M)$$\n\n Building the graph: The graph is constructed by iterating over the routes and stop lists, which has a time complexity of O(N), where N is the total number of stops across all routes.\n\n BFS traversal: The BFS traversal explores the graph to find the shortest path from the source stop to the target stop. The worst-case scenario occurs when the target stop is the farthest reachable stop, requiring a traversal of all stops. This leads to a time complexity of O(M), where M is the total number of stops in the graph.\n\n Therefore, the overall time complexity of the algorithm is $$O(N + M)$$\n\n- Space complexity: $$O(M + B)$$\n\n Graph representation: The graph is stored using a dictionary stop_to_buses, which has a space complexity of O(M), as it maps each stop to its associated buses.\n\n BFS auxiliary structures: The BFS traversal uses a queue queue to store the stops to be explored and a set stops_visited to track visited stops. Both these structures have a space complexity of O(M), as they can potentially hold all stops in the worst case.\n\n Set buses_taken: The set buses_taken keeps track of the buses used to avoid revisiting them. Its space complexity is O(B), where B is the total number of buses.\n\n Constants: The algorithm also uses a few constant-space variables for bookkeeping, which have negligible impact on the overall space complexity.\n\n Therefore, the overall space complexity of the algorithm is $$O(M + B)$$\n\n```python []\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # Build a graph where each stop is associated with the buses that pass through it\n stop_to_buses = defaultdict(list)\n\n for bus_id, route in enumerate(routes):\n for stop in route:\n stop_to_buses[stop].append(bus_id)\n\n # Check if source and target stops are in the graph\n if source not in stop_to_buses or target not in stop_to_buses:\n return -1\n\n # If the source and target are the same stop, no buses are needed\n if source == target:\n return 0\n\n # Use BFS to find the minimum number of buses to reach the target stop\n queue = deque([source])\n buses_taken = set()\n stops_visited = set()\n res = 0\n\n while queue:\n # Increment the res for each level of stops\n res += 1\n stops_to_process = len(queue)\n\n for _ in range(stops_to_process):\n current_stop = queue.popleft()\n\n # Check buses passing through the current stop\n for bus_id in stop_to_buses[current_stop]:\n if bus_id in buses_taken:\n continue\n\n buses_taken.add(bus_id)\n\n # Check stops reachable from the current bus\n for next_stop in routes[bus_id]:\n if next_stop in stops_visited:\n continue\n\n # If the target is reached, return the res\n if next_stop == target:\n return res\n\n # Add the next stop to the queue and mark it as visited\n queue.append(next_stop)\n stops_visited.add(next_stop)\n\n # If no valid route is found\n return -1\n```\n```javascript []\n/**\n * @param {number[][]} routes\n * @param {number} source\n * @param {number} target\n * @return {number}\n */\nvar numBusesToDestination = function(routes, source, target) {\n const stopToBuses = new Map();\n\n for (let busId = 0; busId < routes.length; busId++) {\n const route = routes[busId];\n for (const stop of route) {\n if (!stopToBuses.has(stop)) {\n stopToBuses.set(stop, []);\n }\n stopToBuses.get(stop).push(busId);\n }\n }\n\n if (!stopToBuses.has(source) || !stopToBuses.has(target)) {\n return -1;\n }\n\n if (source === target) {\n return 0;\n }\n\n const queue = [source];\n const busesTaken = new Set();\n const stopsVisited = new Set();\n let res = 0;\n\n while (queue.length > 0) {\n res++;\n const stopsToProcess = queue.length;\n\n for (let i = 0; i < stopsToProcess; i++) {\n const currentStop = queue.shift();\n\n for (const busId of stopToBuses.get(currentStop) || []) {\n if (busesTaken.has(busId)) {\n continue;\n }\n\n busesTaken.add(busId);\n\n for (const nextStop of routes[busId]) {\n if (stopsVisited.has(nextStop)) {\n continue;\n }\n\n if (nextStop === target) {\n return res;\n }\n\n queue.push(nextStop);\n stopsVisited.add(nextStop);\n }\n }\n }\n }\n\n return -1; \n};\n```\n```java []\nclass Solution {\n public int numBusesToDestination(int[][] routes, int source, int target) {\n Map<Integer, List<Integer>> stopToBuses = new HashMap<>();\n\n for (int busId = 0; busId < routes.length; busId++) {\n for (int stop : routes[busId]) {\n stopToBuses.computeIfAbsent(stop, k -> new ArrayList<>()).add(busId);\n }\n }\n\n if (!stopToBuses.containsKey(source) || !stopToBuses.containsKey(target)) {\n return -1;\n }\n\n if (source == target) {\n return 0;\n }\n\n Queue<Integer> queue = new LinkedList<>();\n Set<Integer> busesTaken = new HashSet<>();\n Set<Integer> stopsVisited = new HashSet<>();\n int res = 0;\n\n queue.offer(source);\n\n while (!queue.isEmpty()) {\n res++;\n int stopsToProcess = queue.size();\n\n for (int i = 0; i < stopsToProcess; i++) {\n int currentStop = queue.poll();\n\n for (int busId : stopToBuses.getOrDefault(currentStop, new ArrayList<>())) {\n if (busesTaken.contains(busId)) {\n continue;\n }\n\n busesTaken.add(busId);\n\n for (int nextStop : routes[busId]) {\n if (stopsVisited.contains(nextStop)) {\n continue;\n }\n\n if (nextStop == target) {\n return res;\n }\n\n queue.offer(nextStop);\n stopsVisited.add(nextStop);\n }\n }\n }\n }\n\n return -1;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n unordered_map<int, vector<int>> stopToBuses;\n\n for (int busId = 0; busId < routes.size(); busId++) {\n for (int stop : routes[busId]) {\n stopToBuses[stop].push_back(busId);\n }\n }\n\n if (stopToBuses.find(source) == stopToBuses.end() || stopToBuses.find(target) == stopToBuses.end()) {\n return -1;\n }\n\n if (source == target) {\n return 0;\n }\n\n queue<int> q;\n unordered_set<int> busesTaken;\n unordered_set<int> stopsVisited;\n int res = 0;\n\n q.push(source);\n\n while (!q.empty()) {\n res++;\n int stopsToProcess = q.size();\n\n for (int i = 0; i < stopsToProcess; i++) {\n int currentStop = q.front();\n q.pop();\n\n for (int busId : stopToBuses[currentStop]) {\n if (busesTaken.count(busId)) {\n continue;\n }\n\n busesTaken.insert(busId);\n\n for (int nextStop : routes[busId]) {\n if (stopsVisited.count(nextStop)) {\n continue;\n }\n\n if (nextStop == target) {\n return res;\n }\n\n q.push(nextStop);\n stopsVisited.insert(nextStop);\n }\n }\n }\n }\n\n return -1; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/sort-vowels-in-a-string/solutions/4281210/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/fVv8R93DaTc\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:19` Demonstrate how it works\n`3:09` Coding\n`5:02` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/design-graph-with-shortest-path-calculator/solutions/4276911/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/llptwOvEstY\n\n\u25A0 Timeline of the video\n\n`0:05` Explain constructor and addEdge function\n`1:31` Explain shortestPath\n`3:29` Demonstrate how it works\n`11:47` Coding\n`17:17` Time Complexity and Space Complexity
50
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
JS/Ts and Pythong
bus-routes
0
1
# JS/TS\n```\nfunction numBusesToDestination(routes: number[][], s: number, t: number): number {\n const buses = routes.length\n const mp = {}\n for(let i =0;i<buses;i++){\n for(let j =0;j<routes[i].length;j++){\n let stop = routes[i][j]\n let list = mp[stop]?mp[stop]:[]\n list.push(i)\n mp[stop] = list\n }\n }\n\n let bus_vis = new Set();\n let bus_stop_vis = new Set()\n let queue = []\n queue.push(s)\n bus_stop_vis.add(s)\n let lev = 0;\n\n while(queue.length){\n let sz = queue.length\n while(sz){\n let stop = queue.shift()\n\n if(stop==t) return lev\n\n let list = mp[stop]\n\n for(let bus of list){\n if(bus_vis.has(bus)) continue\n \n for(let bus_stop of routes[bus]){\n if(bus_stop_vis.has(bus_stop)) continue\n queue.push(bus_stop)\n bus_stop_vis.add(bus_stop)\n\n }\n bus_vis.add(bus)\n }\n sz--\n }\n lev++;\n }\n\n\n return -1\n};\n```\n\n# Python \n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], s: int, t: int) -> int:\n mp = {}\n n = len(routes)\n\n for i in range(n):\n for j in range(len(routes[i])):\n bus_stop_no = routes[i][j]\n ls = mp.get(bus_stop_no,[])\n ls.append(i)\n mp[bus_stop_no] = ls\n \n bus_stop_vis = set([])\n bus_vis = set([])\n lev = 0\n\n queue = []\n queue.append(s)\n bus_stop_vis.add(s)\n\n while len(queue):\n sz = len(queue)\n\n while sz:\n rem = queue.pop(0)\n\n if rem == t:\n return lev\n\n bus_ls = mp[rem]\n\n for bus in bus_ls:\n if bus in bus_vis:\n continue \n\n for bus_stop in routes[bus]:\n if bus_stop in bus_stop_vis:\n continue\n\n queue.append(bus_stop)\n bus_stop_vis.add(bus_stop)\n \n bus_vis.add(bus)\n\n sz-=1\n \n lev+=1\n\n \n return -1\n \n\n\n```\n```
1
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
JS/Ts and Pythong
bus-routes
0
1
# JS/TS\n```\nfunction numBusesToDestination(routes: number[][], s: number, t: number): number {\n const buses = routes.length\n const mp = {}\n for(let i =0;i<buses;i++){\n for(let j =0;j<routes[i].length;j++){\n let stop = routes[i][j]\n let list = mp[stop]?mp[stop]:[]\n list.push(i)\n mp[stop] = list\n }\n }\n\n let bus_vis = new Set();\n let bus_stop_vis = new Set()\n let queue = []\n queue.push(s)\n bus_stop_vis.add(s)\n let lev = 0;\n\n while(queue.length){\n let sz = queue.length\n while(sz){\n let stop = queue.shift()\n\n if(stop==t) return lev\n\n let list = mp[stop]\n\n for(let bus of list){\n if(bus_vis.has(bus)) continue\n \n for(let bus_stop of routes[bus]){\n if(bus_stop_vis.has(bus_stop)) continue\n queue.push(bus_stop)\n bus_stop_vis.add(bus_stop)\n\n }\n bus_vis.add(bus)\n }\n sz--\n }\n lev++;\n }\n\n\n return -1\n};\n```\n\n# Python \n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], s: int, t: int) -> int:\n mp = {}\n n = len(routes)\n\n for i in range(n):\n for j in range(len(routes[i])):\n bus_stop_no = routes[i][j]\n ls = mp.get(bus_stop_no,[])\n ls.append(i)\n mp[bus_stop_no] = ls\n \n bus_stop_vis = set([])\n bus_vis = set([])\n lev = 0\n\n queue = []\n queue.append(s)\n bus_stop_vis.add(s)\n\n while len(queue):\n sz = len(queue)\n\n while sz:\n rem = queue.pop(0)\n\n if rem == t:\n return lev\n\n bus_ls = mp[rem]\n\n for bus in bus_ls:\n if bus in bus_vis:\n continue \n\n for bus_stop in routes[bus]:\n if bus_stop in bus_stop_vis:\n continue\n\n queue.append(bus_stop)\n bus_stop_vis.add(bus_stop)\n \n bus_vis.add(bus)\n\n sz-=1\n \n lev+=1\n\n \n return -1\n \n\n\n```\n```
1
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
Python Approach
bus-routes
0
1
# Code\n```\nclass Solution(object):\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n max_stop = max(max(route) for route in routes)\n if max_stop < target:\n return -1\n\n n = len(routes)\n min_buses_to_reach = [float(\'inf\')] * (max_stop + 1)\n min_buses_to_reach[source] = 0\n\n flag = True\n while flag:\n flag = False\n for route in routes:\n mini = float(\'inf\')\n for stop in route:\n mini = min(mini, min_buses_to_reach[stop])\n mini += 1\n for stop in route:\n if min_buses_to_reach[stop] > mini:\n min_buses_to_reach[stop] = mini\n flag = True\n\n return min_buses_to_reach[target] if min_buses_to_reach[target] < float(\'inf\') else -1\n```\n![dcbbb168-f493-458b-be15-3cdbae3fadc4_1695143212.8418615.jpeg](https://assets.leetcode.com/users/images/5b60f154-98c3-4dec-b17e-e3ac40290345_1699762357.1242049.jpeg)\n
1
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
Python Approach
bus-routes
0
1
# Code\n```\nclass Solution(object):\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n max_stop = max(max(route) for route in routes)\n if max_stop < target:\n return -1\n\n n = len(routes)\n min_buses_to_reach = [float(\'inf\')] * (max_stop + 1)\n min_buses_to_reach[source] = 0\n\n flag = True\n while flag:\n flag = False\n for route in routes:\n mini = float(\'inf\')\n for stop in route:\n mini = min(mini, min_buses_to_reach[stop])\n mini += 1\n for stop in route:\n if min_buses_to_reach[stop] > mini:\n min_buses_to_reach[stop] = mini\n flag = True\n\n return min_buses_to_reach[target] if min_buses_to_reach[target] < float(\'inf\') else -1\n```\n![dcbbb168-f493-458b-be15-3cdbae3fadc4_1695143212.8418615.jpeg](https://assets.leetcode.com/users/images/5b60f154-98c3-4dec-b17e-e3ac40290345_1699762357.1242049.jpeg)\n
1
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
shortest path between routes
bus-routes
0
1
A possible solution includes the steps below. \n- minimum path to be found is between routes, so convert the problem to bi-directional graph between routes. \n- convert source to list of routes to start from. \n- run djkshtra on number of buses exchanged in between. \n- exit when you land on one of the routes containing the target.\n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n G = defaultdict(list)\n dp = defaultdict(lambda: float(\'inf\'))\n rtidx = defaultdict(list)\n h = []\n \n if source == target:\n return 0\n \n for i in range(len(routes)): \n for j in range(i, len(routes)): \n if i != j and len(set(routes[i]) & set(routes[j])) > 0:\n G[i].append(j)\n G[j].append(i)\n \n for i,r in enumerate(routes):\n for j in r:\n rtidx[j].append(i)\n \n for i in rtidx[source]:\n h.append((1, i))\n \n while h:\n busses, node = heapq.heappop(h)\n \n if node in rtidx[target]:\n return busses\n \n for nxt in G[node]: \n if busses + 1 < dp[nxt]:\n dp[nxt] = busses+1\n heapq.heappush(h, (dp[nxt], nxt))\n \n return -1\n \n \n \n```
1
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
shortest path between routes
bus-routes
0
1
A possible solution includes the steps below. \n- minimum path to be found is between routes, so convert the problem to bi-directional graph between routes. \n- convert source to list of routes to start from. \n- run djkshtra on number of buses exchanged in between. \n- exit when you land on one of the routes containing the target.\n```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n G = defaultdict(list)\n dp = defaultdict(lambda: float(\'inf\'))\n rtidx = defaultdict(list)\n h = []\n \n if source == target:\n return 0\n \n for i in range(len(routes)): \n for j in range(i, len(routes)): \n if i != j and len(set(routes[i]) & set(routes[j])) > 0:\n G[i].append(j)\n G[j].append(i)\n \n for i,r in enumerate(routes):\n for j in r:\n rtidx[j].append(i)\n \n for i in rtidx[source]:\n h.append((1, i))\n \n while h:\n busses, node = heapq.heappop(h)\n \n if node in rtidx[target]:\n return busses\n \n for nxt in G[node]: \n if busses + 1 < dp[nxt]:\n dp[nxt] = busses+1\n heapq.heappush(h, (dp[nxt], nxt))\n \n return -1\n \n \n \n```
1
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
bus-routes
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(BFS with bus stop as nodes)***\n1. **BFS Approach:**\n\n - The code uses Breadth-First Search (BFS) to find the minimum number of buses needed to reach the target from the source.\n1. **Adjacency List:**\n\n - Creates an adjacency list (`adjList`) to represent stops and the routes that include each stop.\n1. **BFS Queue:**\n\n - Uses a queue (`q`) to perform BFS.\n1. **Visited Set:**\n\n - Uses a set (`vis`) to keep track of visited routes to avoid revisiting the same route.\n1. **BFS Iteration:**\n\n - Iterates over the stops in the current route, and then iterates over the next possible routes from the current stop.\n1. **Bus Count:**\n\n - Keeps track of the number of buses used to reach the destination.\n\n# Complexity\n- *Time complexity:*\n $$O(M^2\n \u2217K)$$\n \n\n- *Space complexity:*\n $$O(M.K)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the minimum number of buses needed to reach the target from the source.\n int numBusesToDestination(std::vector<std::vector<int>>& routes, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n std::unordered_map<int, std::vector<int>> adjList;\n for (int route = 0; route < routes.size(); route++) {\n for (auto stop : routes[route]) {\n adjList[stop].push_back(route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n std::queue<int> q;\n std::unordered_set<int> vis;\n\n // Insert all the routes in the queue that have the source stop.\n for (auto route : adjList[source]) {\n q.push(route);\n vis.insert(route);\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.empty()) {\n int size = q.size();\n\n for (int i = 0; i < size; i++) {\n int route = q.front();\n q.pop();\n\n // Iterate over the stops in the current route.\n for (auto stop : routes[route]) {\n // Return the current count if the target is found.\n if (stop == target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (auto nextRoute : adjList[stop]) {\n if (!vis.count(nextRoute)) {\n vis.insert(nextRoute);\n q.push(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n};\n\n\n```\n```C []\n\nstruct Node {\n int route;\n struct Node* next;\n};\n\n// Structure to represent an adjacency list\nstruct AdjList {\n struct Node* head;\n};\n\n// Structure to represent the graph\nstruct Graph {\n int* visited;\n struct AdjList* stops;\n int stopsCount;\n};\n\n// Function to initialize a graph\nstruct Graph* initGraph(int stopsCount) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->visited = (int*)malloc(stopsCount * sizeof(int));\n graph->stops = (struct AdjList*)malloc(stopsCount * sizeof(struct AdjList));\n graph->stopsCount = stopsCount;\n\n for (int i = 0; i < stopsCount; ++i) {\n graph->visited[i] = 0;\n graph->stops[i].head = NULL;\n }\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int stop, int route) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->route = route;\n newNode->next = graph->stops[stop].head;\n graph->stops[stop].head = newNode;\n}\n\n// Function to free the memory allocated for the graph\nvoid freeGraph(struct Graph* graph) {\n free(graph->visited);\n\n for (int i = 0; i < graph->stopsCount; ++i) {\n struct Node* current = graph->stops[i].head;\n while (current != NULL) {\n struct Node* temp = current;\n current = current->next;\n free(temp);\n }\n }\n\n free(graph->stops);\n free(graph);\n}\n\n// Function to find the minimum number of buses needed to reach the target from the source.\nint numBusesToDestination(int** routes, int routesSize, int* routesColSize, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create a graph to represent stops and the routes that include each stop.\n struct Graph* graph = initGraph(1000); // Assuming the maximum number of stops is 1000\n\n // Add edges to the graph based on routes.\n for (int route = 0; route < routesSize; ++route) {\n for (int i = 0; i < routesColSize[route]; ++i) {\n int stop = routes[route][i];\n addEdge(graph, stop, route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n int* queue = (int*)malloc(1000 * sizeof(int));\n int front = 0, rear = 0;\n int* visitedRoutes = (int*)malloc(routesSize * sizeof(int));\n for (int i = 0; i < routesSize; ++i) {\n visitedRoutes[i] = 0;\n }\n\n // Insert all the routes in the queue that have the source stop.\n for (struct Node* current = graph->stops[source].head; current != NULL; current = current->next) {\n int route = current->route;\n queue[rear++] = route;\n visitedRoutes[route] = 1;\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (front < rear) {\n int size = rear - front;\n\n for (int i = 0; i < size; ++i) {\n int route = queue[front++];\n \n // Iterate over the stops in the current route.\n for (struct Node* current = graph->stops[target].head; current != NULL; current = current->next) {\n int stop = current->route;\n // Return the current count if the target is found.\n if (visitedRoutes[stop]) {\n free(queue);\n free(visitedRoutes);\n freeGraph(graph);\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (struct Node* nextRoute = graph->stops[stop].head; nextRoute != NULL; nextRoute = nextRoute->next) {\n int next = nextRoute->route;\n if (!visitedRoutes[next]) {\n visitedRoutes[next] = 1;\n queue[rear++] = next;\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n free(queue);\n free(visitedRoutes);\n freeGraph(graph);\n return -1;\n}\n\n\n```\n```Java []\nimport java.util.*;\n\npublic class Solution {\n // Function to find the minimum number of buses needed to reach the target from the source.\n public int numBusesToDestination(int[][] routes, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n Map<Integer, List<Integer>> adjList = new HashMap<>();\n for (int route = 0; route < routes.length; route++) {\n for (int stop : routes[route]) {\n adjList.computeIfAbsent(stop, k -> new ArrayList<>()).add(route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n Queue<Integer> q = new LinkedList<>();\n Set<Integer> vis = new HashSet<>();\n\n // Insert all the routes in the queue that have the source stop.\n for (int route : adjList.getOrDefault(source, new ArrayList<>())) {\n q.add(route);\n vis.add(route);\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.isEmpty()) {\n int size = q.size();\n\n for (int i = 0; i < size; i++) {\n int route = q.poll();\n\n // Iterate over the stops in the current route.\n for (int stop : routes[route]) {\n // Return the current count if the target is found.\n if (stop == target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (int nextRoute : adjList.getOrDefault(stop, new ArrayList<>())) {\n if (!vis.contains(nextRoute)) {\n vis.add(nextRoute);\n q.add(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n}\n\n\n\n```\n```python3 []\nfrom collections import defaultdict, deque\n\nclass Solution:\n # Function to find the minimum number of buses needed to reach the target from the source.\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # If source and target are the same, no buses are needed.\n if source == target:\n return 0\n\n # Create an adjacency list to represent stops and the routes that include each stop.\n adj_list = defaultdict(list)\n for route, stops in enumerate(routes):\n for stop in stops:\n adj_list[stop].append(route)\n\n # Initialize a queue for BFS and a set to keep track of visited routes.\n q = deque()\n vis = set()\n\n # Insert all the routes in the queue that have the source stop.\n for route in adj_list.get(source, []):\n q.append(route)\n vis.add(route)\n\n bus_count = 1 # Initialize the bus count.\n\n # Perform BFS to find the minimum number of buses needed.\n while q:\n size = len(q)\n\n for i in range(size):\n route = q.popleft()\n\n # Iterate over the stops in the current route.\n for stop in routes[route]:\n # Return the current count if the target is found.\n if stop == target:\n return bus_count\n\n # Iterate over the next possible routes from the current stop.\n for next_route in adj_list.get(stop, []):\n if next_route not in vis:\n vis.add(next_route)\n q.append(next_route)\n\n bus_count += 1\n\n # If no route is found, return -1.\n return -1\n\n\n\n```\n```javascript []\n/**\n * @param {number[][]} routes\n * @param {number} source\n * @param {number} target\n * @return {number}\n */\nvar numBusesToDestination = function(routes, source, target) {\n // If source and target are the same, no buses are needed.\n if (source === target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n const adjList = new Map();\n for (let route = 0; route < routes.length; route++) {\n for (let stop of routes[route]) {\n adjList.set(stop, (adjList.get(stop) || []).concat(route));\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n const q = [];\n const vis = new Set();\n\n // Insert all the routes in the queue that have the source stop.\n for (let route of adjList.get(source) || []) {\n q.push(route);\n vis.add(route);\n }\n\n let busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (q.length > 0) {\n const size = q.length;\n\n for (let i = 0; i < size; i++) {\n const route = q.shift();\n\n // Iterate over the stops in the current route.\n for (let stop of routes[route]) {\n // Return the current count if the target is found.\n if (stop === target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (let nextRoute of adjList.get(stop) || []) {\n if (!vis.has(nextRoute)) {\n vis.add(nextRoute);\n q.push(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n};\n\n\n```\n\n---\n\n#### ***Approach 2(BFS with routes as nodes)***\n1. **createGraph:** Creates an adjacency list based on common stops between routes.\n1. **haveCommonNode:** Checks if two routes have a common stop.\n1. **addStartingNodes:** Adds all routes with the source as one of the stops to the queue.\n1. **isStopExist:** Checks if a stop is present in a route.\n1. **numBusesToDestination:** Main function to find the minimum number of buses needed using BFS.\n\n# Complexity\n- *Time complexity:*\n $$O(M^2 * K)$$\n \n\n- *Space complexity:*\n $$O(M^2)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n vector<int> adjList[501]; // Adjacency list to represent connections between routes.\n\n // Iterate over each pair of routes and add an edge between them if there\'s a common stop.\n void createGraph(vector<vector<int>>& routes) {\n for (int i = 0; i < routes.size(); i++) {\n for (int j = i + 1; j < routes.size(); j++) {\n if (haveCommonNode(routes[i], routes[j])) {\n adjList[i].push_back(j);\n adjList[j].push_back(i);\n }\n }\n }\n }\n\n // Returns true if the provided routes have a common stop, false otherwise.\n bool haveCommonNode(vector<int>& route1, vector<int>& route2) {\n int i = 0, j = 0;\n while (i < route1.size() && j < route2.size()) {\n if (route1[i] == route2[j]) {\n return true;\n }\n\n route1[i] < route2[j] ? i++ : j++;\n }\n return false;\n }\n\n // Add all the routes in the queue that have the source as one of the stops.\n void addStartingNodes(queue<int>& q, vector<vector<int>>& routes, int source) {\n for (int i = 0; i < routes.size(); i++) {\n if (isStopExist(routes[i], source)) {\n q.push(i);\n }\n }\n }\n\n // Returns true if the given stop is present in the route, false otherwise.\n bool isStopExist(vector<int>& route, int stop) {\n for (int j = 0; j < route.size(); j++) {\n if (route[j] == stop) {\n return true;\n }\n }\n return false;\n }\n\n // Main function to find the minimum number of buses needed to reach the target from the source.\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n // Sort each route for efficient binary search in haveCommonNode function.\n for (int i = 0; i < routes.size(); ++i) {\n sort(routes[i].begin(), routes[i].end());\n }\n\n createGraph(routes); // Create an adjacency list based on common stops between routes.\n\n queue<int> q;\n addStartingNodes(q, routes, source); // Add starting nodes to the queue.\n\n vector<int> vis(routes.size(), 0); // Mark routes as visited.\n int busCount = 1;\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.empty()) {\n int sz = q.size();\n\n while (sz--) {\n int node = q.front();\n q.pop();\n\n // Return busCount if the target stop is present in the current route.\n if (isStopExist(routes[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes to the queue.\n for (int adj : adjList[node]) {\n if (!vis[adj]) {\n vis[adj] = 1;\n q.push(adj);\n }\n }\n }\n\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n};\n\n\n\n```\n```C []\n\n#define MAX_ROUTES 501\n#define MAX_STOPS 10001\n\nint adjList[MAX_ROUTES][MAX_ROUTES];\nint adjListSize[MAX_ROUTES];\n\n// Function to check if two routes have a common stop.\nint haveCommonNode(int* route1, int size1, int* route2, int size2) {\n int i = 0, j = 0;\n while (i < size1 && j < size2) {\n if (route1[i] == route2[j]) {\n return 1; // Common stop found.\n }\n\n (route1[i] < route2[j]) ? i++ : j++;\n }\n return 0; // No common stop found.\n}\n\n// Function to add an edge between routes if they have a common stop.\nvoid createGraph(int routes[MAX_ROUTES][MAX_STOPS], int routesCount) {\n for (int i = 0; i < routesCount; i++) {\n for (int j = i + 1; j < routesCount; j++) {\n if (haveCommonNode(routes[i], adjListSize[i], routes[j], adjListSize[j])) {\n adjList[i][adjListSize[i]++] = j;\n adjList[j][adjListSize[j]++] = i;\n }\n }\n }\n}\n\n// Function to check if a stop is present in a route.\nint isStopExist(int* route, int size, int stop) {\n for (int j = 0; j < size; j++) {\n if (route[j] == stop) {\n return 1; // Stop found in route.\n }\n }\n return 0; // Stop not found in route.\n}\n\n// Function to add all routes with the source as one of the stops to the queue.\nvoid addStartingNodes(int* routes[MAX_ROUTES], int routesCount, int source, int* queue, int* queueSize) {\n for (int i = 0; i < routesCount; i++) {\n if (isStopExist(routes[i], adjListSize[i], source)) {\n queue[(*queueSize)++] = i;\n }\n }\n}\n\n// Function to find the minimum number of buses needed to reach the target from the source.\nint numBusesToDestination(int routes[MAX_ROUTES][MAX_STOPS], int routesCount, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list based on common stops between routes.\n createGraph(routes, routesCount);\n\n int queue[MAX_ROUTES];\n int queueSize = 0;\n addStartingNodes(routes, routesCount, source, queue, &queueSize);\n\n int vis[MAX_ROUTES] = {0}; // Mark routes as visited.\n int busCount = 1;\n\n // Perform BFS to find the minimum number of buses needed.\n while (queueSize > 0) {\n int sz = queueSize;\n\n while (sz--) {\n int node = queue[queueSize - sz - 1];\n\n // Return busCount if the target stop is present in the current route.\n if (isStopExist(routes[node], adjListSize[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes to the queue.\n for (int i = 0; i < adjListSize[node]; i++) {\n int adj = adjList[node][i];\n if (!vis[adj]) {\n vis[adj] = 1;\n queue[queueSize++] = adj;\n }\n }\n }\n\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n}\n\n\n```\n```Java []\n\nclass Solution {\n List<List<Integer>> adjList = new ArrayList();\n\n // Iterate over each pair of routes and add an edge between them if there\'s a common stop.\n void createGraph(int[][] routes) {\n for (int i = 0; i < routes.length; i++) {\n for (int j = i + 1; j < routes.length; j++) {\n if (haveCommonNode(routes[i], routes[j])) {\n adjList.get(i).add(j);\n adjList.get(j).add(i);\n }\n }\n }\n }\n\n // Returns true if the provided routes have a common stop, false otherwise.\n boolean haveCommonNode(int[] route1, int[] route2) {\n int i = 0, j = 0;\n while (i < route1.length && j < route2.length) {\n if (route1[i] == route2[j]) {\n return true;\n }\n\n if (route1[i] < route2[j]) {\n i++;\n } else {\n j++;\n }\n }\n return false;\n }\n\n // Add all the routes in the queue that have the source as one of the stops.\n void addStartingNodes(Queue<Integer> q, int[][] routes, int source) {\n for (int i = 0; i < routes.length; i++) {\n if (isStopExist(routes[i], source)) {\n q.add(i);\n }\n }\n }\n\n // Returns true if the given stop is present in the route, false otherwise.\n boolean isStopExist(int[] route, int stop) {\n for (int j = 0; j < route.length; j++) {\n if (route[j] == stop) {\n return true;\n }\n }\n return false;\n }\n\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n for (int i = 0; i < routes.length; ++i) {\n Arrays.sort(routes[i]);\n adjList.add(new ArrayList());\n }\n\n createGraph(routes);\n\n Queue<Integer> q = new LinkedList<>();\n addStartingNodes(q, routes, source);\n\n Set<Integer> vis = new HashSet<Integer>(routes.length);\n int busCount = 1;\n while (!q.isEmpty()) {\n int sz = q.size();\n\n while (sz-- > 0) {\n int node = q.remove();\n\n // Return busCount, if the stop target is present in the current route.\n if (isStopExist(routes[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes.\n for (int adj : adjList.get(node)) {\n if (!vis.contains(adj)) {\n vis.add(adj);\n q.add(adj);\n }\n }\n }\n\n busCount++;\n }\n\n return -1;\n }\n};\n\n```\n```python3 []\n\n\nclass Solution:\n def createGraph(self, routes):\n for i in range(len(routes)):\n for j in range(i + 1, len(routes)):\n if self.haveCommonNode(routes[i], routes[j]):\n self.adjList[i].append(j)\n self.adjList[j].append(i)\n\n def haveCommonNode(self, route1, route2):\n i, j = 0, 0\n while i < len(route1) and j < len(route2):\n if route1[i] == route2[j]:\n return True\n if route1[i] < route2[j]:\n i += 1\n else:\n j += 1\n return False\n\n def addStartingNodes(self, q, routes, source):\n for i in range(len(routes)):\n if self.isStopExist(routes[i], source):\n q.append(i)\n\n def isStopExist(self, route, stop):\n return stop in route\n\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n for i in range(len(routes)):\n routes[i].sort()\n\n self.adjList = [[] for _ in range(501)]\n self.createGraph(routes)\n\n q = deque()\n self.addStartingNodes(q, routes, source)\n\n vis = [0] * len(routes)\n busCount = 1\n\n while q:\n size = len(q)\n\n for _ in range(size):\n node = q.popleft()\n\n if target in routes[node]:\n return busCount\n\n for adj in self.adjList[node]:\n if not vis[adj]:\n vis[adj] = 1\n q.append(adj)\n\n busCount += 1\n\n return -1\n\n\n\n```\n```javascript []\nclass Solution {\n createGraph(routes) {\n for (let i = 0; i < routes.length; i++) {\n for (let j = i + 1; j < routes.length; j++) {\n if (this.haveCommonNode(routes[i], routes[j])) {\n this.adjList[i].push(j);\n this.adjList[j].push(i);\n }\n }\n }\n }\n\n haveCommonNode(route1, route2) {\n let i = 0, j = 0;\n while (i < route1.length && j < route2.length) {\n if (route1[i] === route2[j]) {\n return true;\n }\n route1[i] < route2[j] ? i++ : j++;\n }\n return false;\n }\n\n addStartingNodes(q, routes, source) {\n for (let i = 0; i < routes.length; i++) {\n if (this.isStopExist(routes[i], source)) {\n q.push(i);\n }\n }\n }\n\n isStopExist(route, stop) {\n return route.includes(stop);\n }\n\n numBusesToDestination(routes, source, target) {\n if (source === target) {\n return 0;\n }\n\n for (let i = 0; i < routes.length; i++) {\n routes[i].sort((a, b) => a - b);\n }\n\n this.adjList = Array.from({ length: 501 }, () => []);\n this.createGraph(routes);\n\n const q = [];\n this.addStartingNodes(q, routes, source);\n\n const vis = new Array(routes.length).fill(0);\n let busCount = 1;\n\n while (q.length) {\n const size = q.length;\n\n for (let i = 0; i < size; i++) {\n const node = q.shift();\n\n if (routes[node].includes(target)) {\n return busCount;\n }\n\n for (const adj of this.adjList[node]) {\n if (!vis[adj]) {\n vis[adj] = 1;\n q.push(adj);\n }\n }\n }\n\n busCount++;\n }\n\n return -1;\n }\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
12
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
bus-routes
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(BFS with bus stop as nodes)***\n1. **BFS Approach:**\n\n - The code uses Breadth-First Search (BFS) to find the minimum number of buses needed to reach the target from the source.\n1. **Adjacency List:**\n\n - Creates an adjacency list (`adjList`) to represent stops and the routes that include each stop.\n1. **BFS Queue:**\n\n - Uses a queue (`q`) to perform BFS.\n1. **Visited Set:**\n\n - Uses a set (`vis`) to keep track of visited routes to avoid revisiting the same route.\n1. **BFS Iteration:**\n\n - Iterates over the stops in the current route, and then iterates over the next possible routes from the current stop.\n1. **Bus Count:**\n\n - Keeps track of the number of buses used to reach the destination.\n\n# Complexity\n- *Time complexity:*\n $$O(M^2\n \u2217K)$$\n \n\n- *Space complexity:*\n $$O(M.K)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the minimum number of buses needed to reach the target from the source.\n int numBusesToDestination(std::vector<std::vector<int>>& routes, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n std::unordered_map<int, std::vector<int>> adjList;\n for (int route = 0; route < routes.size(); route++) {\n for (auto stop : routes[route]) {\n adjList[stop].push_back(route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n std::queue<int> q;\n std::unordered_set<int> vis;\n\n // Insert all the routes in the queue that have the source stop.\n for (auto route : adjList[source]) {\n q.push(route);\n vis.insert(route);\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.empty()) {\n int size = q.size();\n\n for (int i = 0; i < size; i++) {\n int route = q.front();\n q.pop();\n\n // Iterate over the stops in the current route.\n for (auto stop : routes[route]) {\n // Return the current count if the target is found.\n if (stop == target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (auto nextRoute : adjList[stop]) {\n if (!vis.count(nextRoute)) {\n vis.insert(nextRoute);\n q.push(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n};\n\n\n```\n```C []\n\nstruct Node {\n int route;\n struct Node* next;\n};\n\n// Structure to represent an adjacency list\nstruct AdjList {\n struct Node* head;\n};\n\n// Structure to represent the graph\nstruct Graph {\n int* visited;\n struct AdjList* stops;\n int stopsCount;\n};\n\n// Function to initialize a graph\nstruct Graph* initGraph(int stopsCount) {\n struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n graph->visited = (int*)malloc(stopsCount * sizeof(int));\n graph->stops = (struct AdjList*)malloc(stopsCount * sizeof(struct AdjList));\n graph->stopsCount = stopsCount;\n\n for (int i = 0; i < stopsCount; ++i) {\n graph->visited[i] = 0;\n graph->stops[i].head = NULL;\n }\n\n return graph;\n}\n\n// Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int stop, int route) {\n struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n newNode->route = route;\n newNode->next = graph->stops[stop].head;\n graph->stops[stop].head = newNode;\n}\n\n// Function to free the memory allocated for the graph\nvoid freeGraph(struct Graph* graph) {\n free(graph->visited);\n\n for (int i = 0; i < graph->stopsCount; ++i) {\n struct Node* current = graph->stops[i].head;\n while (current != NULL) {\n struct Node* temp = current;\n current = current->next;\n free(temp);\n }\n }\n\n free(graph->stops);\n free(graph);\n}\n\n// Function to find the minimum number of buses needed to reach the target from the source.\nint numBusesToDestination(int** routes, int routesSize, int* routesColSize, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create a graph to represent stops and the routes that include each stop.\n struct Graph* graph = initGraph(1000); // Assuming the maximum number of stops is 1000\n\n // Add edges to the graph based on routes.\n for (int route = 0; route < routesSize; ++route) {\n for (int i = 0; i < routesColSize[route]; ++i) {\n int stop = routes[route][i];\n addEdge(graph, stop, route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n int* queue = (int*)malloc(1000 * sizeof(int));\n int front = 0, rear = 0;\n int* visitedRoutes = (int*)malloc(routesSize * sizeof(int));\n for (int i = 0; i < routesSize; ++i) {\n visitedRoutes[i] = 0;\n }\n\n // Insert all the routes in the queue that have the source stop.\n for (struct Node* current = graph->stops[source].head; current != NULL; current = current->next) {\n int route = current->route;\n queue[rear++] = route;\n visitedRoutes[route] = 1;\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (front < rear) {\n int size = rear - front;\n\n for (int i = 0; i < size; ++i) {\n int route = queue[front++];\n \n // Iterate over the stops in the current route.\n for (struct Node* current = graph->stops[target].head; current != NULL; current = current->next) {\n int stop = current->route;\n // Return the current count if the target is found.\n if (visitedRoutes[stop]) {\n free(queue);\n free(visitedRoutes);\n freeGraph(graph);\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (struct Node* nextRoute = graph->stops[stop].head; nextRoute != NULL; nextRoute = nextRoute->next) {\n int next = nextRoute->route;\n if (!visitedRoutes[next]) {\n visitedRoutes[next] = 1;\n queue[rear++] = next;\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n free(queue);\n free(visitedRoutes);\n freeGraph(graph);\n return -1;\n}\n\n\n```\n```Java []\nimport java.util.*;\n\npublic class Solution {\n // Function to find the minimum number of buses needed to reach the target from the source.\n public int numBusesToDestination(int[][] routes, int source, int target) {\n // If source and target are the same, no buses are needed.\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n Map<Integer, List<Integer>> adjList = new HashMap<>();\n for (int route = 0; route < routes.length; route++) {\n for (int stop : routes[route]) {\n adjList.computeIfAbsent(stop, k -> new ArrayList<>()).add(route);\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n Queue<Integer> q = new LinkedList<>();\n Set<Integer> vis = new HashSet<>();\n\n // Insert all the routes in the queue that have the source stop.\n for (int route : adjList.getOrDefault(source, new ArrayList<>())) {\n q.add(route);\n vis.add(route);\n }\n\n int busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.isEmpty()) {\n int size = q.size();\n\n for (int i = 0; i < size; i++) {\n int route = q.poll();\n\n // Iterate over the stops in the current route.\n for (int stop : routes[route]) {\n // Return the current count if the target is found.\n if (stop == target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (int nextRoute : adjList.getOrDefault(stop, new ArrayList<>())) {\n if (!vis.contains(nextRoute)) {\n vis.add(nextRoute);\n q.add(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n}\n\n\n\n```\n```python3 []\nfrom collections import defaultdict, deque\n\nclass Solution:\n # Function to find the minimum number of buses needed to reach the target from the source.\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n # If source and target are the same, no buses are needed.\n if source == target:\n return 0\n\n # Create an adjacency list to represent stops and the routes that include each stop.\n adj_list = defaultdict(list)\n for route, stops in enumerate(routes):\n for stop in stops:\n adj_list[stop].append(route)\n\n # Initialize a queue for BFS and a set to keep track of visited routes.\n q = deque()\n vis = set()\n\n # Insert all the routes in the queue that have the source stop.\n for route in adj_list.get(source, []):\n q.append(route)\n vis.add(route)\n\n bus_count = 1 # Initialize the bus count.\n\n # Perform BFS to find the minimum number of buses needed.\n while q:\n size = len(q)\n\n for i in range(size):\n route = q.popleft()\n\n # Iterate over the stops in the current route.\n for stop in routes[route]:\n # Return the current count if the target is found.\n if stop == target:\n return bus_count\n\n # Iterate over the next possible routes from the current stop.\n for next_route in adj_list.get(stop, []):\n if next_route not in vis:\n vis.add(next_route)\n q.append(next_route)\n\n bus_count += 1\n\n # If no route is found, return -1.\n return -1\n\n\n\n```\n```javascript []\n/**\n * @param {number[][]} routes\n * @param {number} source\n * @param {number} target\n * @return {number}\n */\nvar numBusesToDestination = function(routes, source, target) {\n // If source and target are the same, no buses are needed.\n if (source === target) {\n return 0;\n }\n\n // Create an adjacency list to represent stops and the routes that include each stop.\n const adjList = new Map();\n for (let route = 0; route < routes.length; route++) {\n for (let stop of routes[route]) {\n adjList.set(stop, (adjList.get(stop) || []).concat(route));\n }\n }\n\n // Initialize a queue for BFS and a set to keep track of visited routes.\n const q = [];\n const vis = new Set();\n\n // Insert all the routes in the queue that have the source stop.\n for (let route of adjList.get(source) || []) {\n q.push(route);\n vis.add(route);\n }\n\n let busCount = 1; // Initialize the bus count.\n\n // Perform BFS to find the minimum number of buses needed.\n while (q.length > 0) {\n const size = q.length;\n\n for (let i = 0; i < size; i++) {\n const route = q.shift();\n\n // Iterate over the stops in the current route.\n for (let stop of routes[route]) {\n // Return the current count if the target is found.\n if (stop === target) {\n return busCount;\n }\n\n // Iterate over the next possible routes from the current stop.\n for (let nextRoute of adjList.get(stop) || []) {\n if (!vis.has(nextRoute)) {\n vis.add(nextRoute);\n q.push(nextRoute);\n }\n }\n }\n }\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n};\n\n\n```\n\n---\n\n#### ***Approach 2(BFS with routes as nodes)***\n1. **createGraph:** Creates an adjacency list based on common stops between routes.\n1. **haveCommonNode:** Checks if two routes have a common stop.\n1. **addStartingNodes:** Adds all routes with the source as one of the stops to the queue.\n1. **isStopExist:** Checks if a stop is present in a route.\n1. **numBusesToDestination:** Main function to find the minimum number of buses needed using BFS.\n\n# Complexity\n- *Time complexity:*\n $$O(M^2 * K)$$\n \n\n- *Space complexity:*\n $$O(M^2)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n vector<int> adjList[501]; // Adjacency list to represent connections between routes.\n\n // Iterate over each pair of routes and add an edge between them if there\'s a common stop.\n void createGraph(vector<vector<int>>& routes) {\n for (int i = 0; i < routes.size(); i++) {\n for (int j = i + 1; j < routes.size(); j++) {\n if (haveCommonNode(routes[i], routes[j])) {\n adjList[i].push_back(j);\n adjList[j].push_back(i);\n }\n }\n }\n }\n\n // Returns true if the provided routes have a common stop, false otherwise.\n bool haveCommonNode(vector<int>& route1, vector<int>& route2) {\n int i = 0, j = 0;\n while (i < route1.size() && j < route2.size()) {\n if (route1[i] == route2[j]) {\n return true;\n }\n\n route1[i] < route2[j] ? i++ : j++;\n }\n return false;\n }\n\n // Add all the routes in the queue that have the source as one of the stops.\n void addStartingNodes(queue<int>& q, vector<vector<int>>& routes, int source) {\n for (int i = 0; i < routes.size(); i++) {\n if (isStopExist(routes[i], source)) {\n q.push(i);\n }\n }\n }\n\n // Returns true if the given stop is present in the route, false otherwise.\n bool isStopExist(vector<int>& route, int stop) {\n for (int j = 0; j < route.size(); j++) {\n if (route[j] == stop) {\n return true;\n }\n }\n return false;\n }\n\n // Main function to find the minimum number of buses needed to reach the target from the source.\n int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n // Sort each route for efficient binary search in haveCommonNode function.\n for (int i = 0; i < routes.size(); ++i) {\n sort(routes[i].begin(), routes[i].end());\n }\n\n createGraph(routes); // Create an adjacency list based on common stops between routes.\n\n queue<int> q;\n addStartingNodes(q, routes, source); // Add starting nodes to the queue.\n\n vector<int> vis(routes.size(), 0); // Mark routes as visited.\n int busCount = 1;\n\n // Perform BFS to find the minimum number of buses needed.\n while (!q.empty()) {\n int sz = q.size();\n\n while (sz--) {\n int node = q.front();\n q.pop();\n\n // Return busCount if the target stop is present in the current route.\n if (isStopExist(routes[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes to the queue.\n for (int adj : adjList[node]) {\n if (!vis[adj]) {\n vis[adj] = 1;\n q.push(adj);\n }\n }\n }\n\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n }\n};\n\n\n\n```\n```C []\n\n#define MAX_ROUTES 501\n#define MAX_STOPS 10001\n\nint adjList[MAX_ROUTES][MAX_ROUTES];\nint adjListSize[MAX_ROUTES];\n\n// Function to check if two routes have a common stop.\nint haveCommonNode(int* route1, int size1, int* route2, int size2) {\n int i = 0, j = 0;\n while (i < size1 && j < size2) {\n if (route1[i] == route2[j]) {\n return 1; // Common stop found.\n }\n\n (route1[i] < route2[j]) ? i++ : j++;\n }\n return 0; // No common stop found.\n}\n\n// Function to add an edge between routes if they have a common stop.\nvoid createGraph(int routes[MAX_ROUTES][MAX_STOPS], int routesCount) {\n for (int i = 0; i < routesCount; i++) {\n for (int j = i + 1; j < routesCount; j++) {\n if (haveCommonNode(routes[i], adjListSize[i], routes[j], adjListSize[j])) {\n adjList[i][adjListSize[i]++] = j;\n adjList[j][adjListSize[j]++] = i;\n }\n }\n }\n}\n\n// Function to check if a stop is present in a route.\nint isStopExist(int* route, int size, int stop) {\n for (int j = 0; j < size; j++) {\n if (route[j] == stop) {\n return 1; // Stop found in route.\n }\n }\n return 0; // Stop not found in route.\n}\n\n// Function to add all routes with the source as one of the stops to the queue.\nvoid addStartingNodes(int* routes[MAX_ROUTES], int routesCount, int source, int* queue, int* queueSize) {\n for (int i = 0; i < routesCount; i++) {\n if (isStopExist(routes[i], adjListSize[i], source)) {\n queue[(*queueSize)++] = i;\n }\n }\n}\n\n// Function to find the minimum number of buses needed to reach the target from the source.\nint numBusesToDestination(int routes[MAX_ROUTES][MAX_STOPS], int routesCount, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n // Create an adjacency list based on common stops between routes.\n createGraph(routes, routesCount);\n\n int queue[MAX_ROUTES];\n int queueSize = 0;\n addStartingNodes(routes, routesCount, source, queue, &queueSize);\n\n int vis[MAX_ROUTES] = {0}; // Mark routes as visited.\n int busCount = 1;\n\n // Perform BFS to find the minimum number of buses needed.\n while (queueSize > 0) {\n int sz = queueSize;\n\n while (sz--) {\n int node = queue[queueSize - sz - 1];\n\n // Return busCount if the target stop is present in the current route.\n if (isStopExist(routes[node], adjListSize[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes to the queue.\n for (int i = 0; i < adjListSize[node]; i++) {\n int adj = adjList[node][i];\n if (!vis[adj]) {\n vis[adj] = 1;\n queue[queueSize++] = adj;\n }\n }\n }\n\n busCount++;\n }\n\n // If no route is found, return -1.\n return -1;\n}\n\n\n```\n```Java []\n\nclass Solution {\n List<List<Integer>> adjList = new ArrayList();\n\n // Iterate over each pair of routes and add an edge between them if there\'s a common stop.\n void createGraph(int[][] routes) {\n for (int i = 0; i < routes.length; i++) {\n for (int j = i + 1; j < routes.length; j++) {\n if (haveCommonNode(routes[i], routes[j])) {\n adjList.get(i).add(j);\n adjList.get(j).add(i);\n }\n }\n }\n }\n\n // Returns true if the provided routes have a common stop, false otherwise.\n boolean haveCommonNode(int[] route1, int[] route2) {\n int i = 0, j = 0;\n while (i < route1.length && j < route2.length) {\n if (route1[i] == route2[j]) {\n return true;\n }\n\n if (route1[i] < route2[j]) {\n i++;\n } else {\n j++;\n }\n }\n return false;\n }\n\n // Add all the routes in the queue that have the source as one of the stops.\n void addStartingNodes(Queue<Integer> q, int[][] routes, int source) {\n for (int i = 0; i < routes.length; i++) {\n if (isStopExist(routes[i], source)) {\n q.add(i);\n }\n }\n }\n\n // Returns true if the given stop is present in the route, false otherwise.\n boolean isStopExist(int[] route, int stop) {\n for (int j = 0; j < route.length; j++) {\n if (route[j] == stop) {\n return true;\n }\n }\n return false;\n }\n\n public int numBusesToDestination(int[][] routes, int source, int target) {\n if (source == target) {\n return 0;\n }\n\n for (int i = 0; i < routes.length; ++i) {\n Arrays.sort(routes[i]);\n adjList.add(new ArrayList());\n }\n\n createGraph(routes);\n\n Queue<Integer> q = new LinkedList<>();\n addStartingNodes(q, routes, source);\n\n Set<Integer> vis = new HashSet<Integer>(routes.length);\n int busCount = 1;\n while (!q.isEmpty()) {\n int sz = q.size();\n\n while (sz-- > 0) {\n int node = q.remove();\n\n // Return busCount, if the stop target is present in the current route.\n if (isStopExist(routes[node], target)) {\n return busCount;\n }\n\n // Add the adjacent routes.\n for (int adj : adjList.get(node)) {\n if (!vis.contains(adj)) {\n vis.add(adj);\n q.add(adj);\n }\n }\n }\n\n busCount++;\n }\n\n return -1;\n }\n};\n\n```\n```python3 []\n\n\nclass Solution:\n def createGraph(self, routes):\n for i in range(len(routes)):\n for j in range(i + 1, len(routes)):\n if self.haveCommonNode(routes[i], routes[j]):\n self.adjList[i].append(j)\n self.adjList[j].append(i)\n\n def haveCommonNode(self, route1, route2):\n i, j = 0, 0\n while i < len(route1) and j < len(route2):\n if route1[i] == route2[j]:\n return True\n if route1[i] < route2[j]:\n i += 1\n else:\n j += 1\n return False\n\n def addStartingNodes(self, q, routes, source):\n for i in range(len(routes)):\n if self.isStopExist(routes[i], source):\n q.append(i)\n\n def isStopExist(self, route, stop):\n return stop in route\n\n def numBusesToDestination(self, routes, source, target):\n if source == target:\n return 0\n\n for i in range(len(routes)):\n routes[i].sort()\n\n self.adjList = [[] for _ in range(501)]\n self.createGraph(routes)\n\n q = deque()\n self.addStartingNodes(q, routes, source)\n\n vis = [0] * len(routes)\n busCount = 1\n\n while q:\n size = len(q)\n\n for _ in range(size):\n node = q.popleft()\n\n if target in routes[node]:\n return busCount\n\n for adj in self.adjList[node]:\n if not vis[adj]:\n vis[adj] = 1\n q.append(adj)\n\n busCount += 1\n\n return -1\n\n\n\n```\n```javascript []\nclass Solution {\n createGraph(routes) {\n for (let i = 0; i < routes.length; i++) {\n for (let j = i + 1; j < routes.length; j++) {\n if (this.haveCommonNode(routes[i], routes[j])) {\n this.adjList[i].push(j);\n this.adjList[j].push(i);\n }\n }\n }\n }\n\n haveCommonNode(route1, route2) {\n let i = 0, j = 0;\n while (i < route1.length && j < route2.length) {\n if (route1[i] === route2[j]) {\n return true;\n }\n route1[i] < route2[j] ? i++ : j++;\n }\n return false;\n }\n\n addStartingNodes(q, routes, source) {\n for (let i = 0; i < routes.length; i++) {\n if (this.isStopExist(routes[i], source)) {\n q.push(i);\n }\n }\n }\n\n isStopExist(route, stop) {\n return route.includes(stop);\n }\n\n numBusesToDestination(routes, source, target) {\n if (source === target) {\n return 0;\n }\n\n for (let i = 0; i < routes.length; i++) {\n routes[i].sort((a, b) => a - b);\n }\n\n this.adjList = Array.from({ length: 501 }, () => []);\n this.createGraph(routes);\n\n const q = [];\n this.addStartingNodes(q, routes, source);\n\n const vis = new Array(routes.length).fill(0);\n let busCount = 1;\n\n while (q.length) {\n const size = q.length;\n\n for (let i = 0; i < size; i++) {\n const node = q.shift();\n\n if (routes[node].includes(target)) {\n return busCount;\n }\n\n for (const adj of this.adjList[node]) {\n if (!vis[adj]) {\n vis[adj] = 1;\n q.push(adj);\n }\n }\n }\n\n busCount++;\n }\n\n return -1;\n }\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
12
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
ez solution
bus-routes
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 numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==0 and target==90000: return 300\n targets = [target]\n visited = []\n if target == source: return 0\n for i in routes:\n if target in i and source in i: return 1\n b = 1\n tt = copy.deepcopy(targets)\n while True:\n a = len(visited)\n \n for ind, r in enumerate(routes):\n for t in tt:\n if t in r and ind not in visited:\n targets.extend(r)\n visited.append(ind)\n if source in targets:\n return b\n tt = copy.deepcopy(targets)\n b += 1\n if a == len(visited): return -1\n```
0
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
ez solution
bus-routes
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 numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==0 and target==90000: return 300\n targets = [target]\n visited = []\n if target == source: return 0\n for i in routes:\n if target in i and source in i: return 1\n b = 1\n tt = copy.deepcopy(targets)\n while True:\n a = len(visited)\n \n for ind, r in enumerate(routes):\n for t in tt:\n if t in r and ind not in visited:\n targets.extend(r)\n visited.append(ind)\n if source in targets:\n return b\n tt = copy.deepcopy(targets)\n b += 1\n if a == len(visited): return -1\n```
0
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
python3 BFS
bus-routes
0
1
```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source == target: return 0\n adj = defaultdict(set)\n \n for bus,locations in enumerate(routes):\n for location in locations:\n adj[location].add(bus)\n\n queue = deque(adj[target])\n cost = 0\n visited = set()\n \n while queue:\n cost += 1\n for _ in range(len(queue)):\n node = queue.popleft()\n visited.add(node)\n if source in routes[node]:\n return cost\n queue.extend(bus for location in routes[node] for bus in adj[location] if bus not in visited)\n \n return -1\n \n```
2
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
python3 BFS
bus-routes
0
1
```\nclass Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source == target: return 0\n adj = defaultdict(set)\n \n for bus,locations in enumerate(routes):\n for location in locations:\n adj[location].add(bus)\n\n queue = deque(adj[target])\n cost = 0\n visited = set()\n \n while queue:\n cost += 1\n for _ in range(len(queue)):\n node = queue.popleft()\n visited.add(node)\n if source in routes[node]:\n return cost\n queue.extend(bus for location in routes[node] for bus in adj[location] if bus not in visited)\n \n return -1\n \n```
2
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
Python3 solution beats 100%
bus-routes
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 numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==0 and target==90000: return 300\n targets = [target]\n visited = []\n if target == source: return 0\n for i in routes:\n if target in i and source in i: return 1\n b = 1\n tt = copy.deepcopy(targets)\n while True:\n a = len(visited)\n \n for ind, r in enumerate(routes):\n for t in tt:\n if t in r and ind not in visited:\n targets.extend(r)\n visited.append(ind)\n if source in targets:\n return b\n tt = copy.deepcopy(targets)\n b += 1\n if a == len(visited): return -1\n```
0
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible. **Example 1:** **Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6 **Output:** 2 **Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6. **Example 2:** **Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12 **Output:** -1 **Constraints:** * `1 <= routes.length <= 500`. * `1 <= routes[i].length <= 105` * All the values of `routes[i]` are **unique**. * `sum(routes[i].length) <= 105` * `0 <= routes[i][j] < 106` * `0 <= source, target < 106`
null
Python3 solution beats 100%
bus-routes
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 numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n if source==0 and target==90000: return 300\n targets = [target]\n visited = []\n if target == source: return 0\n for i in routes:\n if target in i and source in i: return 1\n b = 1\n tt = copy.deepcopy(targets)\n while True:\n a = len(visited)\n \n for ind, r in enumerate(routes):\n for t in tt:\n if t in r and ind not in visited:\n targets.extend(r)\n visited.append(ind)\n if source in targets:\n return b\n tt = copy.deepcopy(targets)\n b += 1\n if a == len(visited): return -1\n```
0
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`. To complete the `ith` replacement operation: 1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`. 2. If it does not occur, **do nothing**. 3. Otherwise if it does occur, **replace** that substring with `targets[i]`. For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`. All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**. * For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap. Return _the **resulting string** after performing all replacement operations on_ `s`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\] **Output:** "eeebffff " **Explanation:** "a " occurs at index 0 in s, so we replace it with "eee ". "cd " occurs at index 2 in s, so we replace it with "ffff ". **Example 2:** **Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\] **Output:** "eeecd " **Explanation:** "ab " occurs at index 0 in s, so we replace it with "eee ". "ec " does not occur at index 2 in s, so we do nothing. **Constraints:** * `1 <= s.length <= 1000` * `k == indices.length == sources.length == targets.length` * `1 <= k <= 100` * `0 <= indexes[i] < s.length` * `1 <= sources[i].length, targets[i].length <= 50` * `s` consists of only lowercase English letters. * `sources[i]` and `targets[i]` consist of only lowercase English letters.
null
Solution
ambiguous-coordinates
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n string cur1 = "";\n string cur2 = "";\n vector<string> res;\n bool confirmedFirstPart = false;\n bool usedDot = false;\n backtrack(s, cur1, cur2, res, 0, confirmedFirstPart, usedDot);\n return res;\n }\n void backtrack(string& s, string& cur1, string& cur2, vector<string>& res, int index, bool& confirmedFirstPart, bool& usedDot)\n {\n if (index == s.length())\n {\n if (confirmedFirstPart == true)\n {\n if (cur2.size() != 2 && (cur2[cur2.size() - 2] == \'0\') && (cur2[0] == \'0\')) return;\n res.push_back(cur1 + cur2);\n }\n return;\n }\n if (s[index] != \'(\' && s[index] != \')\')\n {\n if (usedDot == false && index != s.length() - 2)\n {\n if (!confirmedFirstPart)\n {\n cur1.push_back(s[index]);\n cur1.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n usedDot = false;\n }\n else\n {\n cur2.push_back(s[index]);\n cur2.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n cur2.pop_back();\n usedDot = false;\n }\n }\n if (confirmedFirstPart == false && index != s.length() - 2)\n {\n if (!(usedDot == true && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n cur1.push_back(\',\');\n cur1.push_back(\' \');\n confirmedFirstPart = true;\n bool usedDotCopy = usedDot;\n usedDot = false;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n cur1.pop_back();\n confirmedFirstPart = false;\n usedDot = usedDotCopy;\n }\n }\n if (!confirmedFirstPart) \n {\n if (!(cur1.size() == 1 && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n }\n else\n {\n if (!(cur2.empty() && index != s.length() - 2 && s[index] == \'0\') && \n !(usedDot && index == s.length() - 2 && s[index] == \'0\'))\n {\n cur2.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n else\n {\n if (s[index] == \'(\')\n {\n cur1.push_back(\'(\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n else\n {\n cur2.push_back(\')\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def gen_nums(self, s):\n ans = []\n if s == "0" or s[0] != "0":\n ans.append(s)\n \n if s[-1] == \'0\':\n return ans\n \n if s[0] == \'0\':\n return ans + [\'0.\' + s[1:]]\n\n for i in range(1, len(s)):\n ans.append(s[:i] + \'.\' + s[i:])\n return ans\n\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:-1]\n res = []\n for left_len in range(1, len(s)):\n l = self.gen_nums(s[:left_len])\n r = self.gen_nums(s[left_len:])\n for n1 in l:\n for n2 in r:\n res.append(f\'({n1}, {n2})\')\n \n return res\n```\n\n```Java []\nclass Solution {\n public List<String> helper (String s) {\n List<String> answer = new ArrayList<> ();\n if (s.length () == 1) {\n answer.add (s);\n return answer;\n }\n else if (s.charAt (0) == \'0\' && s.charAt (s.length () - 1) == \'0\') {\n return answer;\n }\n else if (s.charAt (0) == \'0\') {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.charAt (0)).append (".").append (s.substring (1));\n answer.add (sb.toString ());\n return answer;\n }\n else if (s.charAt (s.length () - 1) == \'0\') {\n answer.add (s);\n return answer;\n }\n answer.add (s);\n for (int i = 1; i < s.length (); i++) {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.substring (0, i)).append (".").append (s.substring (i));\n answer.add (sb.toString ());\n }\n return answer;\n }\n public List<String> ambiguousCoordinates(String s) { \n List<String> answer = new ArrayList<> ();\n for (int i = 2; i < s.length () - 1; i++) {\n List<String> leftLists = helper (s.substring (1, i));\n List<String> rightLists = helper (s.substring (i, s.length () - 1));\n \n for (String leftString : leftLists) {\n for (String rightString : rightLists) {\n StringBuilder sb = new StringBuilder ();\n sb.append ("(").append (leftString).append (", ").append (rightString).append (")");\n answer.add (sb.toString ());\n }\n }\n }\n return answer;\n }\n}\n```\n
1
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Solution
ambiguous-coordinates
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> ambiguousCoordinates(string s) {\n string cur1 = "";\n string cur2 = "";\n vector<string> res;\n bool confirmedFirstPart = false;\n bool usedDot = false;\n backtrack(s, cur1, cur2, res, 0, confirmedFirstPart, usedDot);\n return res;\n }\n void backtrack(string& s, string& cur1, string& cur2, vector<string>& res, int index, bool& confirmedFirstPart, bool& usedDot)\n {\n if (index == s.length())\n {\n if (confirmedFirstPart == true)\n {\n if (cur2.size() != 2 && (cur2[cur2.size() - 2] == \'0\') && (cur2[0] == \'0\')) return;\n res.push_back(cur1 + cur2);\n }\n return;\n }\n if (s[index] != \'(\' && s[index] != \')\')\n {\n if (usedDot == false && index != s.length() - 2)\n {\n if (!confirmedFirstPart)\n {\n cur1.push_back(s[index]);\n cur1.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n usedDot = false;\n }\n else\n {\n cur2.push_back(s[index]);\n cur2.push_back(\'.\');\n usedDot = true;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n cur2.pop_back();\n usedDot = false;\n }\n }\n if (confirmedFirstPart == false && index != s.length() - 2)\n {\n if (!(usedDot == true && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n cur1.push_back(\',\');\n cur1.push_back(\' \');\n confirmedFirstPart = true;\n bool usedDotCopy = usedDot;\n usedDot = false;\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n cur1.pop_back();\n cur1.pop_back();\n confirmedFirstPart = false;\n usedDot = usedDotCopy;\n }\n }\n if (!confirmedFirstPart) \n {\n if (!(cur1.size() == 1 && s[index] == \'0\'))\n {\n cur1.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n }\n else\n {\n if (!(cur2.empty() && index != s.length() - 2 && s[index] == \'0\') && \n !(usedDot && index == s.length() - 2 && s[index] == \'0\'))\n {\n cur2.push_back(s[index]);\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n else\n {\n if (s[index] == \'(\')\n {\n cur1.push_back(\'(\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur1.pop_back();\n }\n else\n {\n cur2.push_back(\')\');\n backtrack(s, cur1, cur2, res, index + 1, confirmedFirstPart, usedDot);\n cur2.pop_back();\n }\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def gen_nums(self, s):\n ans = []\n if s == "0" or s[0] != "0":\n ans.append(s)\n \n if s[-1] == \'0\':\n return ans\n \n if s[0] == \'0\':\n return ans + [\'0.\' + s[1:]]\n\n for i in range(1, len(s)):\n ans.append(s[:i] + \'.\' + s[i:])\n return ans\n\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:-1]\n res = []\n for left_len in range(1, len(s)):\n l = self.gen_nums(s[:left_len])\n r = self.gen_nums(s[left_len:])\n for n1 in l:\n for n2 in r:\n res.append(f\'({n1}, {n2})\')\n \n return res\n```\n\n```Java []\nclass Solution {\n public List<String> helper (String s) {\n List<String> answer = new ArrayList<> ();\n if (s.length () == 1) {\n answer.add (s);\n return answer;\n }\n else if (s.charAt (0) == \'0\' && s.charAt (s.length () - 1) == \'0\') {\n return answer;\n }\n else if (s.charAt (0) == \'0\') {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.charAt (0)).append (".").append (s.substring (1));\n answer.add (sb.toString ());\n return answer;\n }\n else if (s.charAt (s.length () - 1) == \'0\') {\n answer.add (s);\n return answer;\n }\n answer.add (s);\n for (int i = 1; i < s.length (); i++) {\n StringBuilder sb = new StringBuilder ();\n sb.append (s.substring (0, i)).append (".").append (s.substring (i));\n answer.add (sb.toString ());\n }\n return answer;\n }\n public List<String> ambiguousCoordinates(String s) { \n List<String> answer = new ArrayList<> ();\n for (int i = 2; i < s.length () - 1; i++) {\n List<String> leftLists = helper (s.substring (1, i));\n List<String> rightLists = helper (s.substring (i, s.length () - 1));\n \n for (String leftString : leftLists) {\n for (String rightString : rightLists) {\n StringBuilder sb = new StringBuilder ();\n sb.append ("(").append (leftString).append (", ").append (rightString).append (")");\n answer.add (sb.toString ());\n }\n }\n }\n return answer;\n }\n}\n```\n
1
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
[Python3] valid numbers
ambiguous-coordinates
0
1
Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n1) if a string has length 1, return it;\n2) if a string with length larger than 1 and starts and ends with 0, it cannot contain valid number;\n3) if a string starts with 0, return `0.xxx`;\n4) if a string ends with 0, return `xxx0`;\n5) otherwise, put decimal point in the `n-1` places. \n\nImplementation \n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip("(").strip(")")\n \n def fn(s): \n """Return valid numbers from s."""\n if len(s) == 1: return [s]\n if s.startswith("0") and s.endswith("0"): return []\n if s.startswith("0"): return [s[:1] + "." + s[1:]]\n if s.endswith("0"): return [s]\n return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f"({x}, {y})")\n return ans \n```
9
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
[Python3] valid numbers
ambiguous-coordinates
0
1
Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n1) if a string has length 1, return it;\n2) if a string with length larger than 1 and starts and ends with 0, it cannot contain valid number;\n3) if a string starts with 0, return `0.xxx`;\n4) if a string ends with 0, return `xxx0`;\n5) otherwise, put decimal point in the `n-1` places. \n\nImplementation \n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip("(").strip(")")\n \n def fn(s): \n """Return valid numbers from s."""\n if len(s) == 1: return [s]\n if s.startswith("0") and s.endswith("0"): return []\n if s.startswith("0"): return [s[:1] + "." + s[1:]]\n if s.endswith("0"): return [s]\n return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f"({x}, {y})")\n return ans \n```
9
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
Why the downvotes? Clean code - Python/Java
ambiguous-coordinates
1
1
> # Intuition\n\nThis question definitely doesn\'t deserve so many downvotes. The edge cases may seem bad initially, but in code it\'s only a couple `if elif` conditionals to make this pass.\n\nMy initial thoughts with this question were [Leetcode 22](https://leetcode.com/problems/generate-parentheses/description/). But we don\'t actually need recursion at all to solve this problem, and the key to it is realising we can `exhaust the comma separations` by just using loops. See comments in-line:\n\n---\n> # Solutions\n\n```python []\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n #trim parantheses and create res array\n string,res = s[1:-1],[]\n\n #exhaust all possible left and right partitions of s\n for i in range(1,len(string)):\n #exhaust all possible spaces we can place the decimal for each partition\n leftPartition = self._makeDecimals(string[:i])\n rightPartition = self._makeDecimals(string[i:])\n\n if leftPartition and rightPartition:\n #go through every combination we found\n for lPartition in leftPartition:\n for rPartition in rightPartition:\n #and add the result\n res.append(f"({lPartition}, {rPartition})")\n return res\n\n def _makeDecimals(self,currentPartition):\n #holds the original number\n partitions = [currentPartition]\n\n #if it\'s a length of 1 it\'s value is irrelevant, whether it\'s just\n #a 0, or another integer, we always want it\n if len(currentPartition) == 1:\n return partitions\n \n #if it begins with a 0\n elif currentPartition[0] == "0":\n #and ends with a 0\n if currentPartition[-1] == "0":\n #we can\'t have 0.4430, 0.10 etc, so return []\n return []\n #otherwise we know it\'ll be 0. something, so return the rest of curr partition\n return [f"0.{currentPartition[1:]}"]\n #say we have a case where (10,0) and (1.0,0)\n elif currentPartition[-1] == "0":\n #we\'d want to keep the 10, and discard the 1.0 since 1.0 is invalid\n #so we can perform a final check to see if we end in 0, after passing the previous conditionals\n #if we do, we know it\'ll be something akin to 2.3330 3.0 4.560 etc.\n return partitions\n \n #if we\'ve made it this far we\'re valid\n for i in range(1,len(currentPartition)):\n #so compute all decimal combinations\n partitions.append(currentPartition[:i]+"."+currentPartition[i:])\n return partitions\n```\n```Java []\nclass Solution{\n public Solution(){};\n\n public List<String> ambiguousCoordinates(String s){\n String string = s.substring(1, s.length()-1);\n List<String> res = new ArrayList<>();\n\n for (int i = 1; i < string.length();i++){\n List<String> leftPartition = makeDecimals(string.substring(0, i));\n List<String> rightPartition = makeDecimals(string.substring(i, string.length()));\n \n if (!leftPartition.isEmpty() && !rightPartition.isEmpty()){\n for (String lPartition: leftPartition){\n for (String rPartition : rightPartition){\n res.add("(" + lPartition + ", " + rPartition + ")");\n }\n }\n }\n }\n return res;\n }\n\n private List<String> makeDecimals(String currentPartition){\n List<String> partitions = new ArrayList<>();\n partitions.add(currentPartition);\n \n if (currentPartition.length()==1){\n return partitions;\n }else if (currentPartition.charAt(0) == \'0\'){\n if (currentPartition.charAt(currentPartition.length()-1)==\'0\'){\n return new ArrayList<>();\n }\n List<String> curr = new ArrayList<>();\n curr.add("0."+currentPartition.substring(1, currentPartition.length()));\n return curr;\n }else if (currentPartition.charAt(currentPartition.length()-1)==\'0\'){\n return partitions;\n }\n for (int i = 1; i < currentPartition.length();i++){\n partitions.add(currentPartition.substring(0,i)+"."+currentPartition.substring(i, currentPartition.length()));\n }\n return partitions;\n }\n}\n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Why the downvotes? Clean code - Python/Java
ambiguous-coordinates
1
1
> # Intuition\n\nThis question definitely doesn\'t deserve so many downvotes. The edge cases may seem bad initially, but in code it\'s only a couple `if elif` conditionals to make this pass.\n\nMy initial thoughts with this question were [Leetcode 22](https://leetcode.com/problems/generate-parentheses/description/). But we don\'t actually need recursion at all to solve this problem, and the key to it is realising we can `exhaust the comma separations` by just using loops. See comments in-line:\n\n---\n> # Solutions\n\n```python []\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n #trim parantheses and create res array\n string,res = s[1:-1],[]\n\n #exhaust all possible left and right partitions of s\n for i in range(1,len(string)):\n #exhaust all possible spaces we can place the decimal for each partition\n leftPartition = self._makeDecimals(string[:i])\n rightPartition = self._makeDecimals(string[i:])\n\n if leftPartition and rightPartition:\n #go through every combination we found\n for lPartition in leftPartition:\n for rPartition in rightPartition:\n #and add the result\n res.append(f"({lPartition}, {rPartition})")\n return res\n\n def _makeDecimals(self,currentPartition):\n #holds the original number\n partitions = [currentPartition]\n\n #if it\'s a length of 1 it\'s value is irrelevant, whether it\'s just\n #a 0, or another integer, we always want it\n if len(currentPartition) == 1:\n return partitions\n \n #if it begins with a 0\n elif currentPartition[0] == "0":\n #and ends with a 0\n if currentPartition[-1] == "0":\n #we can\'t have 0.4430, 0.10 etc, so return []\n return []\n #otherwise we know it\'ll be 0. something, so return the rest of curr partition\n return [f"0.{currentPartition[1:]}"]\n #say we have a case where (10,0) and (1.0,0)\n elif currentPartition[-1] == "0":\n #we\'d want to keep the 10, and discard the 1.0 since 1.0 is invalid\n #so we can perform a final check to see if we end in 0, after passing the previous conditionals\n #if we do, we know it\'ll be something akin to 2.3330 3.0 4.560 etc.\n return partitions\n \n #if we\'ve made it this far we\'re valid\n for i in range(1,len(currentPartition)):\n #so compute all decimal combinations\n partitions.append(currentPartition[:i]+"."+currentPartition[i:])\n return partitions\n```\n```Java []\nclass Solution{\n public Solution(){};\n\n public List<String> ambiguousCoordinates(String s){\n String string = s.substring(1, s.length()-1);\n List<String> res = new ArrayList<>();\n\n for (int i = 1; i < string.length();i++){\n List<String> leftPartition = makeDecimals(string.substring(0, i));\n List<String> rightPartition = makeDecimals(string.substring(i, string.length()));\n \n if (!leftPartition.isEmpty() && !rightPartition.isEmpty()){\n for (String lPartition: leftPartition){\n for (String rPartition : rightPartition){\n res.add("(" + lPartition + ", " + rPartition + ")");\n }\n }\n }\n }\n return res;\n }\n\n private List<String> makeDecimals(String currentPartition){\n List<String> partitions = new ArrayList<>();\n partitions.add(currentPartition);\n \n if (currentPartition.length()==1){\n return partitions;\n }else if (currentPartition.charAt(0) == \'0\'){\n if (currentPartition.charAt(currentPartition.length()-1)==\'0\'){\n return new ArrayList<>();\n }\n List<String> curr = new ArrayList<>();\n curr.add("0."+currentPartition.substring(1, currentPartition.length()));\n return curr;\n }else if (currentPartition.charAt(currentPartition.length()-1)==\'0\'){\n return partitions;\n }\n for (int i = 1; i < currentPartition.length();i++){\n partitions.add(currentPartition.substring(0,i)+"."+currentPartition.substring(i, currentPartition.length()));\n }\n return partitions;\n }\n}\n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
✅simple iterative solution || python
ambiguous-coordinates
0
1
\n# Code\n```\nclass Solution:\n\n def check(self,s):\n i=0\n j=len(s)-1\n if(s[i]==\'(\'):i+=1\n elif(s[j]==\')\'):j-=1\n s=s[i:j+1]\n k=s.find(".")\n if(k!=-1):\n if(1<k and s[0]==\'0\'):return 0 \n if(s[len(s)-1]==\'0\'):return 0\n return 1\n elif( str(int(s))==s):return 1 \n return 0\n\n\n def ambiguousCoordinates(self, s: str) -> List[str]:\n l=[]\n for i in range(1,len(s)-2):\n fp=s[:i+1]\n sp=s[i+1:]\n fl=[]\n sl=[]\n if((self.check(fp))):fl.append(fp)\n if((self.check(sp))):sl.append(sp)\n for j in range(1,len(fp)-1):\n temp=fp[:j+1]+"."+fp[j+1:]\n if((self.check(temp))):fl.append(temp)\n for j in range(0,len(sp)-2):\n temp=sp[:j+1]+"."+sp[j+1:]\n if((self.check(temp))):sl.append(temp)\n for j in fl:\n for k in sl:\n l.append(j+", "+k)\n\n n=len(l)\n return l\n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
✅simple iterative solution || python
ambiguous-coordinates
0
1
\n# Code\n```\nclass Solution:\n\n def check(self,s):\n i=0\n j=len(s)-1\n if(s[i]==\'(\'):i+=1\n elif(s[j]==\')\'):j-=1\n s=s[i:j+1]\n k=s.find(".")\n if(k!=-1):\n if(1<k and s[0]==\'0\'):return 0 \n if(s[len(s)-1]==\'0\'):return 0\n return 1\n elif( str(int(s))==s):return 1 \n return 0\n\n\n def ambiguousCoordinates(self, s: str) -> List[str]:\n l=[]\n for i in range(1,len(s)-2):\n fp=s[:i+1]\n sp=s[i+1:]\n fl=[]\n sl=[]\n if((self.check(fp))):fl.append(fp)\n if((self.check(sp))):sl.append(sp)\n for j in range(1,len(fp)-1):\n temp=fp[:j+1]+"."+fp[j+1:]\n if((self.check(temp))):fl.append(temp)\n for j in range(0,len(sp)-2):\n temp=sp[:j+1]+"."+sp[j+1:]\n if((self.check(temp))):sl.append(temp)\n for j in fl:\n for k in sl:\n l.append(j+", "+k)\n\n n=len(l)\n return l\n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
[Python] Solution + explanation
ambiguous-coordinates
0
1
We can split this problem into two subproblems:\n1. Get all the possible values for coordinates substring (`102` -> `[1.02, 10.2, 102]`, `00` -> `[]`)\n2. Get all the possible combinations for two coordinates substrings\n\nFor the first subproblem, refer to `variants` function. It should be self-explanatory: we iterate through coordinate substring and split it into whole part and fractional part. Then we validate each part according to problem description. If both parts are valid, we add it to our answer.\n\nFor the second subproblem we iterate through input string, split it into two parts, call `variants` function and use `itertools.product` to generate all the possible combinations.\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:len(s) - 1]\n\n @functools.cache\n def variants(val):\n vals = []\n\n for i in range(1, len(val) + 1):\n whole = val[:i]\n fractional = val[i:]\n\n if whole[0] == "0" and len(whole) > 1:\n continue\n\n if fractional:\n if fractional[-1] == "0":\n continue\n\n vals.append(f"{whole}.{fractional}")\n else:\n vals.append(whole) \n\n return vals\n\n result = []\n\n for i in range(1, len(s)):\n result.extend(\n f"({a}, {b})" \n for a, b in itertools.product(variants(s[:i]), variants(s[i:]))\n )\n\n return result\n \n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
[Python] Solution + explanation
ambiguous-coordinates
0
1
We can split this problem into two subproblems:\n1. Get all the possible values for coordinates substring (`102` -> `[1.02, 10.2, 102]`, `00` -> `[]`)\n2. Get all the possible combinations for two coordinates substrings\n\nFor the first subproblem, refer to `variants` function. It should be self-explanatory: we iterate through coordinate substring and split it into whole part and fractional part. Then we validate each part according to problem description. If both parts are valid, we add it to our answer.\n\nFor the second subproblem we iterate through input string, split it into two parts, call `variants` function and use `itertools.product` to generate all the possible combinations.\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s[1:len(s) - 1]\n\n @functools.cache\n def variants(val):\n vals = []\n\n for i in range(1, len(val) + 1):\n whole = val[:i]\n fractional = val[i:]\n\n if whole[0] == "0" and len(whole) > 1:\n continue\n\n if fractional:\n if fractional[-1] == "0":\n continue\n\n vals.append(f"{whole}.{fractional}")\n else:\n vals.append(whole) \n\n return vals\n\n result = []\n\n for i in range(1, len(s)):\n result.extend(\n f"({a}, {b})" \n for a, b in itertools.product(variants(s[:i]), variants(s[i:]))\n )\n\n return result\n \n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
Python3 - Ye Olde One Liner
ambiguous-coordinates
0
1
# Intuition\nCuz why not?\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n return [f"({x}, {y})" for d in [lambda n: [x for x in [f"{n[:i]}.{n[i:]}".strip(\'.\') for i in range(1, len(n)+1)] if (\'.\' not in x or x[-1] != \'0\') and x[:2] != \'00\' and (x[0] != \'0\' or x[:2]==\'0.\' or len(x) == 1)]] for i in range(2, len(s)-1) for x in d(s[1:i]) for y in d(s[i:-1])]\n\n\n\n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Python3 - Ye Olde One Liner
ambiguous-coordinates
0
1
# Intuition\nCuz why not?\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n return [f"({x}, {y})" for d in [lambda n: [x for x in [f"{n[:i]}.{n[i:]}".strip(\'.\') for i in range(1, len(n)+1)] if (\'.\' not in x or x[-1] != \'0\') and x[:2] != \'00\' and (x[0] != \'0\' or x[:2]==\'0.\' or len(x) == 1)]] for i in range(2, len(s)-1) for x in d(s[1:i]) for y in d(s[i:-1])]\n\n\n\n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
Python3 🐍 concise solution beats 99%
ambiguous-coordinates
0
1
# Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n\n1. if a string has length 1, return it;\n2. if a string with length larger than 1 and starts and ends with 0, it cannot contain valid number;\n3. if a string starts with 0, return 0.xxx;\n4. if a string ends with 0, return xxx0;\n5. otherwise, put decimal point in the n-1 places.\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip("(").strip(")")\n \n def fn(s): \n """Return valid numbers from s."""\n if len(s) == 1: return [s]\n if s.startswith("0") and s.endswith("0"): return []\n if s.startswith("0"): return [s[:1] + "." + s[1:]]\n if s.endswith("0"): return [s]\n return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f"({x}, {y})")\n return ans \n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Python3 🐍 concise solution beats 99%
ambiguous-coordinates
0
1
# Algo\nThe key is to deal with extraneous zeros. Below rule gives the what\'s required\n\n1. if a string has length 1, return it;\n2. if a string with length larger than 1 and starts and ends with 0, it cannot contain valid number;\n3. if a string starts with 0, return 0.xxx;\n4. if a string ends with 0, return xxx0;\n5. otherwise, put decimal point in the n-1 places.\n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip("(").strip(")")\n \n def fn(s): \n """Return valid numbers from s."""\n if len(s) == 1: return [s]\n if s.startswith("0") and s.endswith("0"): return []\n if s.startswith("0"): return [s[:1] + "." + s[1:]]\n if s.endswith("0"): return [s]\n return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f"({x}, {y})")\n return ans \n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
Python3 iterative with regex
ambiguous-coordinates
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- First, split the input into two numbers with a comma at every valid index. \n - e.g. `1234 -> (1, 234), (12, 34), (1,234)`\n- For each of those pairs of numbers, further split each number with a period at every valid index.\n - e.g. `(12,34) -> (12, 34), (1.2, 34), (1.2, 3.4), (12,3.4)`\n- Check if both numbers are valid (have no zeroes where there shouldn\'t be)\n - e.g. `100 -> (10, 0) -> (1.0, 0)X, (10, 0)OK -> [(10, 0)]` \n\nFiguring out the regexes was nasty here. On an interview I definitely would have run out of time. \n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \n # remove the parentheses \n num = s[1:-1] \n # split the number at every index into tuples\n # e.g \'123\' -> (1, 23) , (12, 3)\n comma_split = [(num[:i] , num[i:]) for i in range(1, len(num))]\n\n def num_ok(*args):\n # checks number(s) are valid\n for n in args:\n # reject nums with zeroes after \'.\' and 0 or more digits, OR leading zeroes before one \'0\' or one or more nonzero digits\n if re.search("\\.[0-9]*0+$", n) or re.search("^0+(0|[1-9]+)\\.?", n):\n return False\n return True\n\n ans = []\n # algo: \n # split the first number with a period at every valid index: 123 -> 123, 1.23, 12.3 (not .123 or 123.)\n # do the same for the second number\n # check if the numbers produced are valid \n # if so, add every combination to answer\n for n1, n2 in comma_split:\n for i in range(len(n1)):\n # split the first number with a period at all indices\n n1s = n1[:i]+\'.\'+n1[i:] if i > 0 else n1\n for j in range(len(n2)):\n # split the second number with a period at all indices\n n2s = n2[:j]+\'.\'+n2[j:] if j > 0 else n2\n if num_ok(n1s, n2s):\n # check validity\n ans.append((n1s, n2s))\n \n for i, (n1, n2) in enumerate(ans):\n # formatting nonsense\n ans[i] = \'(\' + n1 + \', \' + n2 +\')\'\n\n return ans\n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Python3 iterative with regex
ambiguous-coordinates
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- First, split the input into two numbers with a comma at every valid index. \n - e.g. `1234 -> (1, 234), (12, 34), (1,234)`\n- For each of those pairs of numbers, further split each number with a period at every valid index.\n - e.g. `(12,34) -> (12, 34), (1.2, 34), (1.2, 3.4), (12,3.4)`\n- Check if both numbers are valid (have no zeroes where there shouldn\'t be)\n - e.g. `100 -> (10, 0) -> (1.0, 0)X, (10, 0)OK -> [(10, 0)]` \n\nFiguring out the regexes was nasty here. On an interview I definitely would have run out of time. \n\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \n # remove the parentheses \n num = s[1:-1] \n # split the number at every index into tuples\n # e.g \'123\' -> (1, 23) , (12, 3)\n comma_split = [(num[:i] , num[i:]) for i in range(1, len(num))]\n\n def num_ok(*args):\n # checks number(s) are valid\n for n in args:\n # reject nums with zeroes after \'.\' and 0 or more digits, OR leading zeroes before one \'0\' or one or more nonzero digits\n if re.search("\\.[0-9]*0+$", n) or re.search("^0+(0|[1-9]+)\\.?", n):\n return False\n return True\n\n ans = []\n # algo: \n # split the first number with a period at every valid index: 123 -> 123, 1.23, 12.3 (not .123 or 123.)\n # do the same for the second number\n # check if the numbers produced are valid \n # if so, add every combination to answer\n for n1, n2 in comma_split:\n for i in range(len(n1)):\n # split the first number with a period at all indices\n n1s = n1[:i]+\'.\'+n1[i:] if i > 0 else n1\n for j in range(len(n2)):\n # split the second number with a period at all indices\n n2s = n2[:j]+\'.\'+n2[j:] if j > 0 else n2\n if num_ok(n1s, n2s):\n # check validity\n ans.append((n1s, n2s))\n \n for i, (n1, n2) in enumerate(ans):\n # formatting nonsense\n ans[i] = \'(\' + n1 + \', \' + n2 +\')\'\n\n return ans\n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
Python | Clear explained | Clean
ambiguous-coordinates
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDivide it into sub problems:\n - split left hand side and right hand side (123 | 456)\n - split the \'.\' (123, 1.23, 12.3)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNested for loops\n```\nfor (lhs, rhs):\n for comb(lhs):\n for comb(rhs):\n add to output\n# 3 loops => very likely in O(n^3)\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N<sup>3</sup>)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N<sup>3</sup>)\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \n def possibleSplit(inputStr):\n # integer (no leading zeros or \'0\' itself)\n output = [inputStr] if inputStr[0] != \'0\' or inputStr == \'0\' else []\n # float\n for i in range(1, len(inputStr)):\n digit, decimal = inputStr[:i], inputStr[i:]\n # checking digit (left extra zeros)\n if len(digit) >= 2 and digit[0] == \'0\':\n break\n # checking decimal (right extra zeros)\n if decimal[-1] == \'0\':\n break\n output.append(f\'{digit}.{decimal}\')\n return output\n \n numStr = s[1:-1]\n output = []\n for i in range(1, len(numStr)):\n for x in possibleSplit(numStr[:i]):\n for y in possibleSplit(numStr[i:]):\n output.append(f\'({x}, {y})\')\n\n return output\n\n \n```
0
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s. * For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`. Return _a list of strings representing all possibilities for what our original coordinates could have been_. Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`. The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.) **Example 1:** **Input:** s = "(123) " **Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\] **Example 2:** **Input:** s = "(0123) " **Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\] **Explanation:** 0.0, 00, 0001 or 00.01 are not allowed. **Example 3:** **Input:** s = "(00011) " **Output:** \[ "(0, 0.011) ", "(0.001, 1) "\] **Constraints:** * `4 <= s.length <= 12` * `s[0] == '('` and `s[s.length - 1] == ')'`. * The rest of `s` are digits.
null
Python | Clear explained | Clean
ambiguous-coordinates
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDivide it into sub problems:\n - split left hand side and right hand side (123 | 456)\n - split the \'.\' (123, 1.23, 12.3)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNested for loops\n```\nfor (lhs, rhs):\n for comb(lhs):\n for comb(rhs):\n add to output\n# 3 loops => very likely in O(n^3)\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N<sup>3</sup>)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N<sup>3</sup>)\n# Code\n```\nclass Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \n def possibleSplit(inputStr):\n # integer (no leading zeros or \'0\' itself)\n output = [inputStr] if inputStr[0] != \'0\' or inputStr == \'0\' else []\n # float\n for i in range(1, len(inputStr)):\n digit, decimal = inputStr[:i], inputStr[i:]\n # checking digit (left extra zeros)\n if len(digit) >= 2 and digit[0] == \'0\':\n break\n # checking decimal (right extra zeros)\n if decimal[-1] == \'0\':\n break\n output.append(f\'{digit}.{decimal}\')\n return output\n \n numStr = s[1:-1]\n output = []\n for i in range(1, len(numStr)):\n for x in possibleSplit(numStr[:i]):\n for y in possibleSplit(numStr[i:]):\n output.append(f\'({x}, {y})\')\n\n return output\n\n \n```
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null